Integrate scoped offline HMI control and durable bidirectional settings sync
Reuse platform API, MQTT invalidation and native configuration loading. Persist local settings/outbox, merge acknowledged clocks without stale rollback, refresh native fallback documents and wake synchronization after changes. Keep observed output freshness and immediate-only Push authorization separate from legacy projections; add transport and storage regressions.
This commit is contained in:
parent
8430b8ddda
commit
4e58671b32
|
|
@ -6,6 +6,8 @@ import re
|
|||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
|
@ -63,6 +65,11 @@ class BridgeState:
|
|||
self.last_message_at = ""
|
||||
self.mqtt_connected = False
|
||||
self.mqtt_last_error = ""
|
||||
self.hmi_received = None
|
||||
self.hmi_emitted = None
|
||||
self.hmi_registers = {}
|
||||
self.hmi_components = {}
|
||||
self.hmi_capabilities = {}
|
||||
|
||||
def set_mqtt_connected(self, value):
|
||||
with self.lock:
|
||||
|
|
@ -89,6 +96,36 @@ class BridgeState:
|
|||
self.raw_payload = payload
|
||||
self.last_message_at = utc_timestamp()
|
||||
|
||||
def observe_hmi(self, payload, registers=False):
|
||||
now = time.monotonic()
|
||||
if registers:
|
||||
emitted = payload.get('observed_at_ms')
|
||||
if type(emitted) not in (int, float) or not math.isfinite(emitted) or abs(time.time()*1000-emitted)>5000: return False
|
||||
for item in (payload.get('payload') or payload).get('values', []):
|
||||
if not isinstance(item, dict) or not isinstance(item.get('id'), int): continue
|
||||
with self.lock:
|
||||
previous=self.hmi_registers.get(str(item['id']))
|
||||
if previous and previous[1]['observed_at_ms'] >= emitted: continue
|
||||
self.hmi_registers[str(item['id'])] = (now, dict(item,observed_at_ms=emitted))
|
||||
else:
|
||||
emitted = payload.get('emitted_at')
|
||||
if type(emitted) not in (int, float) or not math.isfinite(emitted) or abs(time.time()*1000-emitted)>5000: return False
|
||||
with self.lock:
|
||||
if self.hmi_emitted is not None and emitted <= self.hmi_emitted: return False
|
||||
self.hmi_emitted, self.hmi_received = emitted, now
|
||||
self.hmi_components = payload.get("components") or {}
|
||||
self.hmi_capabilities = payload.get("capabilities") or {}
|
||||
return True
|
||||
|
||||
def hmi_observation(self, component_id):
|
||||
with self.lock:
|
||||
now = time.monotonic()
|
||||
fresh = self.mqtt_connected and self.hmi_received is not None and 0 <= now-self.hmi_received <= 5
|
||||
return {'fresh': bool(fresh), 'component': dict(self.hmi_components.get(str(component_id), {})) if fresh else {},
|
||||
'observed_at_ms': self.hmi_emitted if fresh else None,
|
||||
'capabilities': dict(self.hmi_capabilities) if fresh else {},
|
||||
'registers': {key:value for key,(received,value) in self.hmi_registers.items() if 0 <= now-received <= 5} if fresh else {}}
|
||||
|
||||
def get_component(self, component_id):
|
||||
with self.lock:
|
||||
component = self.components.get(str(component_id))
|
||||
|
|
@ -111,6 +148,7 @@ class MqttBridge:
|
|||
self.host, self.port = parse_mqtt_url(mqtt_url)
|
||||
self.topic_prefix = prefix
|
||||
self.state_topic = f"{prefix}/client/pub/component/plays/{device_id}"
|
||||
self.register_topic = f"{prefix}/client/pub/interface/values/{device_id}"
|
||||
self._publish_lock = threading.Lock()
|
||||
self._ready = threading.Event()
|
||||
self._client = None
|
||||
|
|
@ -153,7 +191,7 @@ class MqttBridge:
|
|||
def is_connected(self):
|
||||
return self._ready.is_set()
|
||||
|
||||
def publish_event(self, component_id, value, title):
|
||||
def publish_event(self, component_id, value, title, expires_in_ms=None):
|
||||
if self._client is None:
|
||||
raise RuntimeError("MQTT client is unavailable")
|
||||
topic = f"{self.topic_prefix}/client/sub/event/push/{component_id}"
|
||||
|
|
@ -164,7 +202,11 @@ class MqttBridge:
|
|||
"time": utc_timestamp(),
|
||||
"user": "root",
|
||||
"title": str(title),
|
||||
"command_id": uuid.uuid4().hex,
|
||||
}
|
||||
if expires_in_ms is not None:
|
||||
payload['issued_at_ms'] = round(time.time()*1000)
|
||||
payload['expires_at_ms'] = payload['issued_at_ms'] + int(expires_in_ms)
|
||||
serialized = json.dumps(payload, ensure_ascii=True, separators=(",", ":"))
|
||||
with self._publish_lock:
|
||||
if not self.is_connected():
|
||||
|
|
@ -184,7 +226,7 @@ class MqttBridge:
|
|||
self.state.set_mqtt_error(f"connect failed ({rc})")
|
||||
log(f"mqtt connect failed rc={rc}")
|
||||
return
|
||||
result, _ = client.subscribe(self.state_topic, qos=0)
|
||||
result, _ = client.subscribe([(self.state_topic, 0), (self.register_topic, 0)])
|
||||
if result != mqtt_err_success():
|
||||
self._ready.clear()
|
||||
self.state.set_mqtt_error("subscribe failed")
|
||||
|
|
@ -216,6 +258,10 @@ class MqttBridge:
|
|||
log(f"ignored invalid mqtt json topic={msg.topic} error={exc}")
|
||||
return
|
||||
try:
|
||||
if msg.topic == self.register_topic:
|
||||
if not getattr(msg, "retain", False): self.state.observe_hmi(payload, registers=True)
|
||||
return
|
||||
if not getattr(msg, 'retain', False): self.state.observe_hmi(payload)
|
||||
self.state.update_components(payload)
|
||||
except Exception as exc:
|
||||
log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}")
|
||||
|
|
@ -235,7 +281,6 @@ class Handler(BaseHTTPRequestHandler):
|
|||
|
||||
def end_headers(self):
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
||||
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
|
|
@ -244,6 +289,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
def send_json(self, payload, code=200):
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
|
@ -307,6 +353,9 @@ class Handler(BaseHTTPRequestHandler):
|
|||
def do_POST(self):
|
||||
if self.app.offline_edit and self.app.offline_edit.handle(self): return
|
||||
parsed = urlparse(self.path)
|
||||
if self.app.offline_edit and parsed.path == '/api/event':
|
||||
self.send_json({'error':'Use the scoped HMI control endpoint'},code=403)
|
||||
return
|
||||
if parsed.path != "/api/event":
|
||||
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
||||
return
|
||||
|
|
@ -383,7 +432,8 @@ class App:
|
|||
deadline=time.monotonic()+2.0
|
||||
while not result.is_published() and time.monotonic()<deadline: time.sleep(0.02)
|
||||
if not result.is_published(): raise RuntimeError('Local broker acknowledgement timed out')
|
||||
self.offline_edit = Runtime(offline_config, invalidate)
|
||||
from offline_edit.control import Control
|
||||
self.offline_edit = Runtime(offline_config, invalidate, control=Control(self.state, self.mqtt_bridge))
|
||||
self.httpd = ThreadingHTTPServer((self.bind, self.port), Handler)
|
||||
self.httpd.app = self
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
"""Delegated immediate control adapter. No scheduler, persistence or replay queue."""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Control:
|
||||
def __init__(self, state, bridge, monotonic=time.monotonic):
|
||||
self.state, self.bridge, self.monotonic = state, bridge, monotonic
|
||||
self.lock = threading.Lock()
|
||||
self.last_command = {}
|
||||
|
||||
def observation(self, component):
|
||||
observed = self.state.hmi_observation(int(component['id']))
|
||||
outputs = component.get('hardware_outputs') or []
|
||||
reason = 'unbound_output' if not outputs else None
|
||||
if not reason and not observed['fresh']: reason = 'observation_unavailable'
|
||||
if not reason and observed['capabilities'].get('push_expiry_v1') is not True: reason = 'client_update_required'
|
||||
registers = []
|
||||
for register in outputs:
|
||||
item = dict(register)
|
||||
status = observed['registers'].get(str(register['id']))
|
||||
item['status'] = status
|
||||
registers.append(item)
|
||||
if not reason and (not status or status.get('available') is not True
|
||||
or status.get('error_code', 0) != 0 or status.get('emulated') is True):
|
||||
reason = 'output_unavailable'
|
||||
observed.update(registers=registers, reason=reason,
|
||||
can_start=not reason and component['groups']['active']['value']['active'] == 1,
|
||||
can_stop=not reason)
|
||||
observed.pop('capabilities', None)
|
||||
return observed
|
||||
|
||||
def issue(self, component, action):
|
||||
if action not in ('start', 'stop'): raise ValueError('Only immediate Start/Stop is allowed')
|
||||
with self.lock:
|
||||
# Re-read observations immediately before dispatch; UI readiness is not authority.
|
||||
state = self.observation(component)
|
||||
if not state['can_' + action]: raise PermissionError(state['reason'] or 'component_inactive')
|
||||
key = int(component['id'])
|
||||
now = self.monotonic()
|
||||
if now - self.last_command.get(key, -math.inf) < 1:
|
||||
raise PermissionError('command_pending')
|
||||
self.last_command = {k:stamp for k,stamp in self.last_command.items() if now-stamp < 60}
|
||||
self.last_command[key] = now
|
||||
try:
|
||||
topic, payload = self.bridge.publish_event(key, action, component['title'], expires_in_ms=5000)
|
||||
except RuntimeError as error:
|
||||
raise OSError('Immediate command unavailable; it was not queued') from error
|
||||
return {'status': 'accepted', 'execution_confirmed': False,
|
||||
'command_id': payload['command_id'], 'expires_at_ms': payload['expires_at_ms']}
|
||||
|
|
@ -17,7 +17,8 @@ NATIVE_PATHS = {'/v2/device': 'native_config', '/v2/device/layout': 'native_fram
|
|||
|
||||
|
||||
class Runtime:
|
||||
def __init__(self, config_path, publish_invalidation):
|
||||
def __init__(self, config_path, publish_invalidation, control=None):
|
||||
self.control = control
|
||||
self.config = json.loads(Path(config_path).read_text())
|
||||
credentials = json.loads(Path(self.config['native_config_path']).read_text())
|
||||
self.authorization = 'Basic ' + base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
|
||||
|
|
@ -29,6 +30,7 @@ class Runtime:
|
|||
Path(self.config['database']).chmod(0o600)
|
||||
self.session = secrets.token_urlsafe(32)
|
||||
self.stop_event = threading.Event()
|
||||
self.sync_event = threading.Event()
|
||||
self.online, self.last_error = False, 'not_connected'
|
||||
self.last_invalidated = None
|
||||
self.cloud_api = self._origin(self.config['cloud_api_url'])
|
||||
|
|
@ -49,9 +51,9 @@ class Runtime:
|
|||
if parsed.hostname not in LOCAL_HOSTS: raise ValueError('Public upstream requires TLS')
|
||||
return value.rstrip('/')
|
||||
|
||||
def _request(self, base, path, body=None):
|
||||
def _request(self, base, path, body=None, headers=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
request = urllib.request.Request(base + path, data=data, headers={'Authorization': self.authorization, 'Content-Type': 'application/json', 'Accept': 'application/json'})
|
||||
request = urllib.request.Request(base + path, data=data, headers={'Authorization': self.authorization, 'Content-Type': 'application/json', 'Accept': 'application/json', **(headers or {})})
|
||||
with urllib.request.urlopen(request, timeout=8) as response:
|
||||
if response.status != 200: raise OSError('Unexpected API response')
|
||||
reader=gzip.GzipFile(fileobj=response) if response.headers.get('Content-Encoding','').lower()=='gzip' else response
|
||||
|
|
@ -84,17 +86,22 @@ class Runtime:
|
|||
except (OSError,RuntimeError):
|
||||
return False # Durable settings remain visible; a later tick retries invalidation only.
|
||||
|
||||
def request_sync(self):
|
||||
self.sync_event.set()
|
||||
|
||||
def start(self):
|
||||
def loop():
|
||||
while not self.stop_event.is_set():
|
||||
self.sync_event.clear()
|
||||
self.synchronize()
|
||||
self.notify_desired()
|
||||
self.stop_event.wait(10 if self.online else 15)
|
||||
self.sync_event.wait(10 if self.online else 15)
|
||||
self.thread = threading.Thread(target=loop, name='offline-edit-sync', daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.stop_event.set()
|
||||
self.sync_event.set()
|
||||
if hasattr(self, 'thread'): self.thread.join(timeout=9)
|
||||
|
||||
def _cache(self, key, value=None):
|
||||
|
|
@ -106,12 +113,24 @@ class Runtime:
|
|||
if row is None: raise OSError('No cached native configuration')
|
||||
return json.loads(row[0])
|
||||
|
||||
def native(self, path, query):
|
||||
def native(self, path, query, headers=None):
|
||||
if path not in NATIVE_PATHS: raise PermissionError('Native route is outside the configuration scope')
|
||||
name = NATIVE_PATHS[path]
|
||||
# The platform's geometry wire contract is version-dependent. Preserve
|
||||
# native capability headers; never reuse a cache from a different one.
|
||||
forwarded={key:str(value)[:512] for key,value in (headers or {}).items() if key in ('User-Agent','X-Edge-Client-Version') and value}
|
||||
if forwarded:
|
||||
try: previous=self._cache('native_contract')
|
||||
except OSError: previous=None
|
||||
if previous!=forwarded:
|
||||
with self.store.transaction() as db: db.execute("DELETE FROM metadata WHERE key IN ('native_config','native_frames')")
|
||||
self._cache('native_contract',forwarded)
|
||||
try:
|
||||
payload = self._request(self.native_base, path + ('?' + query if query else ''))
|
||||
payload = self._request(self.native_base, path + ('?' + query if query else ''), headers=forwarded)
|
||||
self._cache(name, payload)
|
||||
# Native already receives the platform MQTT update channel. Its
|
||||
# configuration fetch also refreshes HMI clocks without another subscriber.
|
||||
self.request_sync()
|
||||
except (OSError, ValueError):
|
||||
payload = self._cache(name)
|
||||
return self.store.overlay(payload) if name == 'native_frames' else payload
|
||||
|
|
@ -140,12 +159,25 @@ class Runtime:
|
|||
if parsed.path.startswith('/native/'):
|
||||
if handler.command != 'GET' or not hmac.compare_digest(handler.headers.get('Authorization', ''), self.authorization):
|
||||
handler.send_response(401); handler.send_header('WWW-Authenticate', 'Basic realm="IOMATEX native configuration"'); handler.end_headers(); return True
|
||||
handler.send_json(self.native(parsed.path[len('/native'):], parsed.query)); return True
|
||||
handler.send_json(self.native(parsed.path[len('/native'):], parsed.query, {key:handler.headers.get(key) for key in ('User-Agent','X-Edge-Client-Version')})); return True
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
if handler.command == 'GET' and parsed.path == '/hmi/api/session':
|
||||
handler.send_json({'session': self.session, 'online': self.online, 'error': self.last_error}); return True
|
||||
if handler.command == 'GET' and parsed.path == '/hmi/api/component':
|
||||
handler.send_json(self.store.view(int(query['id'][0]))); return True
|
||||
if handler.command == 'GET' and parsed.path == '/hmi/api/runtime':
|
||||
component = self.store.view(int(query['id'][0]))
|
||||
value = self.control.observation(component) if self.control else {'fresh':False,'component':{},'registers':[],'can_start':False,'can_stop':False,'reason':'control_unavailable'}
|
||||
handler.send_json(value); return True
|
||||
if handler.command == 'POST' and parsed.path == '/hmi/api/event':
|
||||
self._write_allowed(handler)
|
||||
size=int(handler.headers.get('Content-Length','0'))
|
||||
if not 0 < size <= 2048: raise ValueError('Invalid command size')
|
||||
value=json.loads(handler.rfile.read(size))
|
||||
if set(value)!={'component_id','action'} or type(value['component_id']) is not int: raise ValueError('Invalid immediate command')
|
||||
component=self.store.view(value['component_id'])
|
||||
if not self.control: raise PermissionError('Control is not installed')
|
||||
handler.send_json(self.control.issue(component,value['action'])); return True
|
||||
if handler.command == 'POST' and parsed.path == '/hmi/api/settings':
|
||||
self._write_allowed(handler)
|
||||
size = int(handler.headers.get('Content-Length', '0'))
|
||||
|
|
@ -154,6 +186,7 @@ class Runtime:
|
|||
operation = self.store.edit(int(value['component_id']), str(value['group']), value['value'])
|
||||
# Existing local MQTT subscriber + native configuration application own execution.
|
||||
applied=self.notify_desired()
|
||||
self.request_sync()
|
||||
handler.send_json({'operation': operation, 'status': 'saved_locally', 'application_status':'notification_sent' if applied else 'pending'}); return True
|
||||
if handler.command == 'GET' and parsed.path in ('/hmi', '/hmi/'):
|
||||
body = (self.assets / 'index.html').read_bytes()
|
||||
|
|
|
|||
|
|
@ -12,7 +12,31 @@ GROUPS = {
|
|||
'duration': ('duration',), 'active': ('active',),
|
||||
'schedule': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week'),
|
||||
'conditions': ('triggers', 'start_condition_operator', 'per_hour'),
|
||||
'availability': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week', 'activity'),
|
||||
}
|
||||
ACTIVITY_KEYS = {'activity_schedules', 'activity_time_ranges', 'activity_date_ranges', 'activity_date_operator'}
|
||||
|
||||
|
||||
def attributes(value):
|
||||
result = copy.deepcopy(value)
|
||||
if 'activity' in result:
|
||||
result.pop('activity')
|
||||
return result
|
||||
|
||||
|
||||
def apply_value(element, value):
|
||||
if 'triggers' in value:
|
||||
current = element.get('triggers') or {}
|
||||
if isinstance(current, str): current = json.loads(current)
|
||||
value = copy.deepcopy(value)
|
||||
value['triggers'] = {**{k:v for k,v in current.items() if k in ACTIVITY_KEYS},
|
||||
**{k:v for k,v in value['triggers'].items() if k not in ACTIVITY_KEYS}}
|
||||
element.update(attributes(value))
|
||||
if 'activity' in value:
|
||||
triggers = element.get('triggers') or {}
|
||||
if isinstance(triggers, str): triggers = json.loads(triggers)
|
||||
element['triggers'] = {k:v for k,v in triggers.items() if k not in ACTIVITY_KEYS}
|
||||
element['triggers'].update(copy.deepcopy(value['activity']))
|
||||
|
||||
|
||||
def boot_id():
|
||||
|
|
@ -33,6 +57,10 @@ def validate(group, value, generator='sync'):
|
|||
raise ValueError('Activity must be 0 or 1')
|
||||
if group == 'schedule' and any(v is not None and not isinstance(v, str) for v in value.values()):
|
||||
raise ValueError('Invalid schedule value')
|
||||
if group == 'availability':
|
||||
if (not isinstance(value['activity'], dict) or set(value['activity']) - ACTIVITY_KEYS
|
||||
or any(v is not None and not isinstance(v, str) for k,v in value.items() if k != 'activity')):
|
||||
raise ValueError('Invalid availability group')
|
||||
if group == 'conditions' and (not isinstance(value['triggers'], dict) or value['start_condition_operator'] not in ('AND', 'OR') or type(value['per_hour']) is not int or value['per_hour'] < 0):
|
||||
raise ValueError('Invalid conditions')
|
||||
return copy.deepcopy(value)
|
||||
|
|
@ -77,17 +105,51 @@ class Store:
|
|||
raise ValueError('Device identity changed; use a separate database')
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('device_id',?)", (str(device_id),))
|
||||
ids = []
|
||||
changed = False
|
||||
for component in snapshot['components']:
|
||||
component_id = int(component['id'])
|
||||
ids.append(component_id)
|
||||
component=copy.deepcopy(component)
|
||||
previous=db.execute('SELECT payload FROM components WHERE id=?',(component_id,)).fetchone()
|
||||
previous=json.loads(previous[0]) if previous else None
|
||||
if previous:
|
||||
# An in-flight older snapshot must not undo an acknowledged edit.
|
||||
for group,canonical in previous['groups'].items():
|
||||
incoming=component['groups'].get(group)
|
||||
if incoming and int(incoming['clock']['revision']) < int(canonical['clock']['revision']):
|
||||
component['groups'][group]=canonical
|
||||
before={k:v['value'] for k,v in (previous or {}).get('groups',{}).items()}
|
||||
after={k:v['value'] for k,v in component['groups'].items()}
|
||||
if before!=after:
|
||||
changed=True
|
||||
self._update_native_cache(db,component_id,{k:v for value in after.values() for k,v in value.items()})
|
||||
db.execute('INSERT OR REPLACE INTO components VALUES(?,?,?,?,?)', (component_id, json.dumps(component), self.monotonic(), self.wall(), self.boot()))
|
||||
# A complete server grant snapshot is authoritative for deletions and revocations.
|
||||
allowed = set(ids)
|
||||
for row in db.execute('SELECT id FROM components').fetchall():
|
||||
if row['id'] not in allowed:
|
||||
changed=True
|
||||
db.execute('DELETE FROM components WHERE id=?', (row['id'],))
|
||||
db.execute("UPDATE outbox SET status='scope_removed' WHERE component_id=? AND status='pending'", (row['id'],))
|
||||
|
||||
if changed:
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)",(json.dumps('server-'+uuid.uuid4().hex),))
|
||||
|
||||
@staticmethod
|
||||
def _update_native_cache(db,component_id,value):
|
||||
cached=db.execute("SELECT value FROM metadata WHERE key='native_frames'").fetchone()
|
||||
if not cached:return
|
||||
document=json.loads(cached[0])
|
||||
for layout in document.get('layouts',[]):
|
||||
for frame in layout.get('frames',[]):
|
||||
for model in frame.get('playlists',[]):
|
||||
for key in ('elements','diagnostic_elements'):
|
||||
for element in model.get(key,[]):
|
||||
if int(element['id'])!=component_id:continue
|
||||
apply_value(element,value)
|
||||
if element.get('execution_eligibility',{}).get('eligible') is False:element['active']=0
|
||||
db.execute("UPDATE metadata SET value=? WHERE key='native_frames'",(json.dumps(document),))
|
||||
|
||||
def _component(self, db, component_id):
|
||||
row = db.execute('SELECT * FROM components WHERE id=?', (component_id,)).fetchone()
|
||||
if not row:
|
||||
|
|
@ -164,19 +226,7 @@ class Store:
|
|||
db.execute('UPDATE components SET payload=? WHERE id=?', (json.dumps(data), row['component_id']))
|
||||
# ACK, canonical settings and the native fallback document are one
|
||||
# durable commit. A power loss must not restore a pre-ACK duration.
|
||||
cached = db.execute("SELECT value FROM metadata WHERE key='native_frames'").fetchone()
|
||||
if cached:
|
||||
document = json.loads(cached[0])
|
||||
for layout in document.get('layouts', []):
|
||||
for frame in layout.get('frames', []):
|
||||
for model in frame.get('playlists', []):
|
||||
for key in ('elements', 'diagnostic_elements'):
|
||||
for element in model.get(key, []):
|
||||
if int(element['id']) == row['component_id']:
|
||||
element.update(canonical['value'])
|
||||
if element.get('execution_eligibility', {}).get('eligible') is False:
|
||||
element['active'] = 0
|
||||
db.execute("UPDATE metadata SET value=? WHERE key='native_frames'", (json.dumps(document),))
|
||||
self._update_native_cache(db,row['component_id'],canonical['value'])
|
||||
db.execute('UPDATE outbox SET status=?,result=? WHERE id=?', (status, json.dumps(result), row['id']))
|
||||
if status in ('accepted','superseded'):
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-ack-'+row['id']),))
|
||||
|
|
@ -200,7 +250,7 @@ class Store:
|
|||
for key in ('elements', 'diagnostic_elements'):
|
||||
for element in model.get(key, []):
|
||||
if int(element['id']) in values:
|
||||
element.update(values[int(element['id'])])
|
||||
apply_value(element, values[int(element['id'])])
|
||||
if element.get('execution_eligibility', {}).get('eligible') is False:
|
||||
element['active'] = 0 # Never bypass the platform's unbound-output guard.
|
||||
return payload
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
"""Exercise the real HTTP handler, not a browser route interception."""
|
||||
import sys,threading,unittest,urllib.request
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from http.server import ThreadingHTTPServer
|
||||
sys.path.insert(0,str(Path(__file__).parents[1]/'dashboard_bridge_core/backend'))
|
||||
from bridge import Handler
|
||||
|
||||
class HttpTest(unittest.TestCase):
|
||||
def test_hmi_html_has_one_html_mime_and_json_stays_json(self):
|
||||
class Offline:
|
||||
def handle(self,handler):
|
||||
if handler.path!='/hmi/':return False
|
||||
body=b'<!doctype html><title>HMI</title>'
|
||||
handler.send_response(200);handler.send_header('Content-Type','text/html; charset=utf-8');handler.send_header('Content-Length',str(len(body)));handler.end_headers();handler.wfile.write(body);return True
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||
server.app=SimpleNamespace(offline_edit=Offline())
|
||||
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
||||
try:
|
||||
with urllib.request.urlopen('http://127.0.0.1:%s/hmi/'%server.server_port) as response:
|
||||
self.assertEqual(response.headers.get_all('Content-Type'),['text/html; charset=utf-8'])
|
||||
self.assertTrue(response.read().startswith(b'<!doctype html>'))
|
||||
with self.assertRaises(urllib.error.HTTPError) as context:urllib.request.urlopen('http://127.0.0.1:%s/unknown'%server.server_port)
|
||||
self.assertEqual(context.exception.headers.get_all('Content-Type'),['application/json; charset=utf-8'])
|
||||
finally:server.shutdown();server.server_close();thread.join()
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import copy
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
sys.path.insert(0,str(Path(__file__).parents[1]/'dashboard_bridge_core/backend'))
|
||||
from offline_edit.control import Control
|
||||
from offline_edit.store import apply_value
|
||||
|
||||
class ControlTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.state=Mock();self.bridge=Mock();self.now=10
|
||||
self.observed={'fresh':True,'capabilities':{'push_expiry_v1':True},'registers':{'8':{'available':True,'error_code':0,'value':0}},'component':{}}
|
||||
self.state.hmi_observation.side_effect=lambda _:copy.deepcopy(self.observed)
|
||||
self.component={'id':22,'title':'Fixture','hardware_outputs':[{'id':8}], 'groups':{'active':{'value':{'active':1}}}}
|
||||
self.control=Control(self.state,self.bridge,lambda:self.now)
|
||||
self.bridge.publish_event.return_value=('fixture',{'command_id':'test-command-0001','expires_at_ms':5000})
|
||||
def test_fail_closed_for_unbound_stale_legacy_and_bad_output(self):
|
||||
for patch,reason in [({'fresh':False},'observation_unavailable'),({'capabilities':{}},'client_update_required'),({'registers':{}},'output_unavailable'),({'registers':{'8':{'available':True,'emulated':True}}},'output_unavailable')]:
|
||||
baseline=copy.deepcopy(self.observed);self.observed.update(patch)
|
||||
self.assertEqual(self.control.observation(self.component)['reason'],reason)
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
|
||||
self.observed=baseline
|
||||
self.component['hardware_outputs']=[]
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'stop')
|
||||
self.bridge.publish_event.assert_not_called()
|
||||
def test_dispatch_once_with_deadline_and_no_optimistic_confirmation(self):
|
||||
result=self.control.issue(self.component,'start')
|
||||
self.assertFalse(result['execution_confirmed'])
|
||||
self.bridge.publish_event.assert_called_once_with(22,'start','Fixture',expires_in_ms=5000)
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
|
||||
self.now+=2;self.component['groups']['active']['value']['active']=0
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
|
||||
self.control.issue(self.component,'stop')
|
||||
def test_schedule_and_conditions_preserve_each_other(self):
|
||||
element={'triggers':{'start':{'type':'push'},'activity_schedules':[{'days_week':[1]}]}}
|
||||
apply_value(element,{'activity':{'activity_schedules':[{'days_week':[2]}]}})
|
||||
self.assertEqual(element['triggers']['start'],{'type':'push'})
|
||||
apply_value(element,{'triggers':{'stop':{'type':'push'}}})
|
||||
self.assertEqual(element['triggers']['activity_schedules'],[{'days_week':[2]}])
|
||||
self.assertEqual(element['triggers']['stop'],{'type':'push'})
|
||||
|
||||
class ObservationTest(unittest.TestCase):
|
||||
def test_old_observations_cannot_replace_fresh_hmi_state(self):
|
||||
import time
|
||||
from bridge import BridgeState
|
||||
state=BridgeState();state.set_mqtt_connected(True)
|
||||
now=int(time.time()*1000)
|
||||
payload={'emitted_at':now,'components':{'22':{'rest_duration':10}},'capabilities':{'push_expiry_v1':True}}
|
||||
self.assertTrue(state.observe_hmi(payload))
|
||||
self.assertFalse(state.observe_hmi(dict(payload,emitted_at=now-1)))
|
||||
# Compatibility updates are deliberately separate from HMI authority.
|
||||
state.update_components({'components':{'22':{'rest_duration':999}}})
|
||||
self.assertEqual(state.hmi_observation(22)['component']['rest_duration'],10)
|
||||
self.assertFalse(state.observe_hmi(dict(payload,emitted_at=float('nan'))))
|
||||
self.assertTrue(state.observe_hmi({'observed_at_ms':now,'payload':{'values':[{'id':8,'available':True}]}},registers=True))
|
||||
state.observe_hmi({'observed_at_ms':now-1,'payload':{'values':[{'id':8,'available':False}]}},registers=True)
|
||||
self.assertTrue(state.hmi_observation(22)['registers']['8']['available'])
|
||||
state.set_mqtt_connected(False)
|
||||
self.assertFalse(state.hmi_observation(22)['fresh'])
|
||||
self.assertEqual(state.hmi_observation(22)['registers'],{})
|
||||
|
||||
def test_retained_packet_does_not_authorize_control(self):
|
||||
import json,time
|
||||
from types import SimpleNamespace
|
||||
from bridge import BridgeState,MqttBridge
|
||||
state=BridgeState();state.set_mqtt_connected(True)
|
||||
bridge=MqttBridge.__new__(MqttBridge);bridge.state=state;bridge.register_topic='fixture/registers'
|
||||
packet={'components':{'22':{'rest_duration':15}},'emitted_at':int(time.time()*1000),'capabilities':{'push_expiry_v1':True}}
|
||||
bridge._on_message(None,None,SimpleNamespace(topic='fixture/plays',retain=True,payload=json.dumps(packet).encode()))
|
||||
self.assertFalse(state.hmi_observation(22)['fresh'])
|
||||
self.assertEqual(state.get_component(22)['rest_duration'],15)
|
||||
|
|
@ -30,7 +30,7 @@ class RuntimeTest(unittest.TestCase):
|
|||
config = {'native_config_path':str(native),'database':str(root/'edits.sqlite3'),
|
||||
'cloud_api_url':'http://127.0.0.1:8000/api','native_base_url':'http://127.0.0.1:8000','assets':str(root)}
|
||||
self.config_path = root/'config.json'; self.config_path.write_text(json.dumps(config))
|
||||
self.notifications=[]; self.runtime=Runtime(self.config_path,lambda *args:self.notifications.append(args))
|
||||
self.notifications=[]; self.runtime=Runtime(self.config_path,lambda *args,**kwargs:self.notifications.append(args))
|
||||
now=int(time.time()*1000)
|
||||
self.runtime.store.ingest({'schema_version':1,'device_id':109,'components':[{'id':22,'title':'Fixture','grant_id':'grant','grant_expires_at':now//1000+3600,'generator_type':'sync',
|
||||
'anchor':{'id':'anchor','server_time_ms':now},'groups':{'duration':{'value':{'duration':15},'clock':{'revision':1}},'active':{'value':{'active':1},'clock':{'revision':1}}}}]})
|
||||
|
|
@ -43,6 +43,30 @@ class RuntimeTest(unittest.TestCase):
|
|||
self.runtime.handle(h); self.assertEqual(h.code,403)
|
||||
self.assertEqual(self.runtime.store.pending(),[])
|
||||
|
||||
def test_native_proxy_preserves_geometry_capability_and_separates_cache(self):
|
||||
from unittest.mock import Mock
|
||||
self.runtime._request=Mock(return_value={'layouts':[]})
|
||||
headers={'User-Agent':'it-screen/5.1.60','X-Edge-Client-Version':'5.1.60','Authorization':'must-not-forward'}
|
||||
self.runtime.native('/v2/device/layout','',headers)
|
||||
self.assertEqual(self.runtime._request.call_args.kwargs['headers'],{'User-Agent':'it-screen/5.1.60','X-Edge-Client-Version':'5.1.60'})
|
||||
self.runtime._request.side_effect=OSError('offline')
|
||||
self.assertEqual(self.runtime.native('/v2/device/layout','',headers),{'layouts':[]})
|
||||
with self.assertRaises(OSError):self.runtime.native('/v2/device/layout','',dict(headers,**{'X-Edge-Client-Version':'5.1.61'}))
|
||||
|
||||
def test_immediate_route_checks_grant_session_and_never_queues(self):
|
||||
from unittest.mock import Mock
|
||||
self.runtime.control=Mock()
|
||||
self.runtime.control.issue.return_value={'status':'accepted','execution_confirmed':False}
|
||||
for component_id,headers in [(22,{}),(999,{'X-HMI-Session':self.runtime.session})]:
|
||||
handler=Handler('/hmi/api/event','POST',{'component_id':component_id,'action':'start'},headers)
|
||||
self.runtime.handle(handler)
|
||||
self.assertEqual(handler.code,403)
|
||||
self.runtime.control.issue.assert_not_called()
|
||||
handler=Handler('/hmi/api/event','POST',{'component_id':22,'action':'start'},{'X-HMI-Session':self.runtime.session})
|
||||
self.runtime.handle(handler);self.assertEqual(handler.code,200)
|
||||
self.assertFalse(handler.result['execution_confirmed'])
|
||||
self.assertEqual(self.runtime.store.pending(),[])
|
||||
|
||||
def test_hardware_actions_are_not_settings_or_retryable(self):
|
||||
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'start','value':{'active':1}}, {'X-HMI-Session':self.runtime.session})
|
||||
self.runtime.handle(h);self.assertEqual(h.code,422);self.assertEqual(self.notifications,[])
|
||||
|
|
@ -57,10 +81,10 @@ class RuntimeTest(unittest.TestCase):
|
|||
with self.assertRaises(PermissionError):self.runtime.native('/v2/device/reboot','')
|
||||
|
||||
def test_durable_save_survives_broker_outage_and_notifies_on_restart(self):
|
||||
self.runtime.publish_invalidation=lambda *args: (_ for _ in ()).throw(RuntimeError('broker offline'))
|
||||
self.runtime.publish_invalidation=lambda *args,**kwargs: (_ for _ in ()).throw(RuntimeError('broker offline'))
|
||||
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':120}}, {'X-HMI-Session':self.runtime.session})
|
||||
self.runtime.handle(h);self.assertEqual(h.code,200);self.assertEqual(h.result['application_status'],'pending')
|
||||
restarted=Runtime(self.config_path,lambda *args:self.notifications.append(args))
|
||||
self.runtime.handle(h);self.assertEqual(h.code,200);self.assertEqual(h.result['application_status'],'pending');self.assertTrue(self.runtime.sync_event.is_set())
|
||||
restarted=Runtime(self.config_path,lambda *args,**kwargs:self.notifications.append(args))
|
||||
self.assertEqual(len(restarted.store.pending()),1)
|
||||
self.assertTrue(restarted.notify_desired())
|
||||
self.assertEqual(self.notifications[0][0],'tenant/fixture/client/sub/action/fixture-edge')
|
||||
|
|
@ -73,13 +97,32 @@ class RuntimeTest(unittest.TestCase):
|
|||
operation=self.runtime.store.edit(22,'duration',{'duration':120})
|
||||
self.runtime.store.acknowledge({'operation_id':operation['operation_id'],'component_id':22,'group':'duration','status':'accepted',
|
||||
'canonical':{'value':{'duration':120},'clock':{'revision':2}}})
|
||||
restarted=Runtime(self.config_path,lambda *args:None)
|
||||
restarted._request=lambda *args: (_ for _ in ()).throw(OSError('offline'))
|
||||
restarted=Runtime(self.config_path,lambda *args,**kwargs:None)
|
||||
restarted._request=lambda *args,**kwargs: (_ for _ in ()).throw(OSError('offline'))
|
||||
value=restarted.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
|
||||
self.assertEqual(restarted.store.pending(),[])
|
||||
self.assertEqual(value['duration'],120)
|
||||
self.assertEqual(value['active'],0)
|
||||
|
||||
def test_remote_duration_refreshes_native_cache_and_notifies_once(self):
|
||||
import copy
|
||||
document={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0,'execution_eligibility':{'eligible':False}}]}]}]}]}
|
||||
self.runtime._cache('native_frames',document)
|
||||
self.runtime.notify_desired();self.notifications.clear()
|
||||
component=copy.deepcopy(self.runtime.store.view(22));component.pop('pending')
|
||||
component['groups']['duration']={'value':{'duration':77},'clock':{'revision':2}}
|
||||
snapshot={'schema_version':1,'device_id':109,'components':[component]}
|
||||
self.runtime._request=lambda *args,**kwargs:snapshot
|
||||
self.runtime.synchronize();self.assertTrue(self.runtime.notify_desired())
|
||||
self.assertEqual(len(self.notifications),1)
|
||||
self.runtime.synchronize();self.runtime.notify_desired();self.assertEqual(len(self.notifications),1)
|
||||
self.runtime._request=lambda *args,**kwargs:(_ for _ in ()).throw(OSError('offline'))
|
||||
element=self.runtime.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
|
||||
self.assertEqual(element['duration'],77);self.assertEqual(element['active'],0)
|
||||
older=copy.deepcopy(snapshot);older['components'][0]['groups']['duration']={'value':{'duration':15},'clock':{'revision':1}}
|
||||
self.runtime.store.ingest(older)
|
||||
self.assertEqual(self.runtime.store.view(22)['groups']['duration']['value']['duration'],77)
|
||||
|
||||
def test_plaintext_public_upstream_is_rejected(self):
|
||||
for url in ['http://public.example','http://8.8.8.8','https://user:secret@example.test','file:///etc/passwd']:
|
||||
with self.assertRaises(ValueError):Runtime._origin(url)
|
||||
|
|
|
|||
Loading…
Reference in New Issue