inovonics-echostream-processor 1.5.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
1
+ from inovonics_echostream_processor.compat import (
2
+ detect_runtime,
3
+ is_cpython,
4
+ is_micropython,
5
+ )
6
+ from inovonics_echostream_processor.bit_coalescer import (
7
+ BitStateCoalescer,
8
+ BitStateCoalescerConfig,
9
+ BitStateUpdate,
10
+ security_event_to_bit_state_updates,
11
+ security_event_to_supported_bit_state_updates,
12
+ )
13
+ from inovonics_echostream_processor.core import (
14
+ EchoStreamProcessorCore,
15
+ ProcessBatch,
16
+ )
17
+ from inovonics_echostream_processor.device_types import (
18
+ security_status_bit_definition,
19
+ security_status_capabilities,
20
+ decode_icn3000_7,
21
+ device_category_label,
22
+ device_model_label,
23
+ )
24
+ from inovonics_echostream_processor.events import (
25
+ AckEvent,
26
+ AggregateMessageEvent,
27
+ ConfigurationReportEvent,
28
+ CoordinatorNetworkIdEvent,
29
+ CoordinatorSerialNumberEvent,
30
+ CoordinatorStatusEvent,
31
+ NakEvent,
32
+ NetworkStatusEvent,
33
+ ProcessorEvent,
34
+ RepeaterResetEvent,
35
+ SecurityMessageEvent,
36
+ SerialDataEvent,
37
+ UnknownMessageEvent,
38
+ )
39
+ from inovonics_echostream_processor.protocol import EchoStreamProtocol
40
+ from inovonics_echostream_processor.version import __version__
41
+
42
+ __all__ = [
43
+ "__version__",
44
+ "AckEvent",
45
+ "AggregateMessageEvent",
46
+ "ConfigurationReportEvent",
47
+ "BitStateCoalescer",
48
+ "BitStateCoalescerConfig",
49
+ "BitStateUpdate",
50
+ "CoordinatorNetworkIdEvent",
51
+ "CoordinatorSerialNumberEvent",
52
+ "CoordinatorStatusEvent",
53
+ "EchoStreamProcessorCore",
54
+ "EchoStreamProtocol",
55
+ "NakEvent",
56
+ "NetworkStatusEvent",
57
+ "ProcessBatch",
58
+ "ProcessorEvent",
59
+ "RepeaterResetEvent",
60
+ "SecurityMessageEvent",
61
+ "SerialDataEvent",
62
+ "UnknownMessageEvent",
63
+ "decode_icn3000_7",
64
+ "detect_runtime",
65
+ "device_category_label",
66
+ "device_model_label",
67
+ "is_cpython",
68
+ "is_micropython",
69
+ "security_event_to_bit_state_updates",
70
+ "security_event_to_supported_bit_state_updates",
71
+ "security_status_bit_definition",
72
+ "security_status_capabilities",
73
+ ]
74
+
75
+ if is_cpython():
76
+ from inovonics_echostream_processor.transports.cpython_socket import (
77
+ ProcessorMetrics,
78
+ SocketProcessorConfig,
79
+ SocketProcessorService,
80
+ )
81
+ from inovonics_echostream_processor.transports.cpython_uart import (
82
+ CpythonUartProcessorConfig,
83
+ CpythonUartProcessorService,
84
+ )
85
+
86
+ __all__.extend(
87
+ [
88
+ "CpythonUartProcessorConfig",
89
+ "CpythonUartProcessorService",
90
+ "ProcessorMetrics",
91
+ "SocketProcessorConfig",
92
+ "SocketProcessorService",
93
+ ]
94
+ )
95
+
96
+ if is_micropython():
97
+ from inovonics_echostream_processor.transports.micropython_socket import (
98
+ MicroPythonSocketProcessor,
99
+ MicroPythonSocketProcessorConfig,
100
+ )
101
+ from inovonics_echostream_processor.transports.micropython_uart import (
102
+ MicroPythonUartProcessor,
103
+ MicroPythonUartProcessorConfig,
104
+ )
105
+
106
+ __all__.extend(
107
+ [
108
+ "MicroPythonSocketProcessor",
109
+ "MicroPythonSocketProcessorConfig",
110
+ "MicroPythonUartProcessor",
111
+ "MicroPythonUartProcessorConfig",
112
+ ]
113
+ )
@@ -0,0 +1,61 @@
1
+ import argparse
2
+ import json
3
+ import logging
4
+ import time
5
+
6
+ from inovonics_echostream_processor.compat import is_cpython
7
+ from inovonics_echostream_processor.version import __version__
8
+
9
+
10
+ def main():
11
+ if not is_cpython():
12
+ raise SystemExit("The bundled CLI is only available on standard Python.")
13
+
14
+ from inovonics_echostream_processor.transports.cpython_socket import (
15
+ SocketProcessorConfig,
16
+ SocketProcessorService,
17
+ )
18
+
19
+ parser = argparse.ArgumentParser(description="Dump normalized EchoStream events.")
20
+ parser.add_argument("--host", required=True, help="EchoStream TCP host")
21
+ parser.add_argument("--port", type=int, required=True, help="EchoStream TCP port")
22
+ parser.add_argument(
23
+ "--log-level",
24
+ default="INFO",
25
+ help="Python logging level",
26
+ )
27
+ parser.add_argument(
28
+ "--debug",
29
+ action="store_true",
30
+ help="Shortcut for --log-level DEBUG",
31
+ )
32
+ args = parser.parse_args()
33
+
34
+ log_level_name = "DEBUG" if args.debug else args.log_level
35
+ logging.basicConfig(
36
+ level=getattr(logging, log_level_name.upper(), logging.INFO),
37
+ format="%(asctime)s [%(levelname)s] %(message)s",
38
+ )
39
+ print(f"Inovonics EchoStream Processor {__version__}", flush=True)
40
+
41
+ service = SocketProcessorService(
42
+ SocketProcessorConfig(host=args.host, port=args.port),
43
+ )
44
+ service.add_event_handler(
45
+ lambda event: print(json.dumps(event.to_dict(), default=str))
46
+ )
47
+ service.start()
48
+
49
+ try:
50
+ while service.is_running:
51
+ time.sleep(1)
52
+ except KeyboardInterrupt:
53
+ logging.info("Interrupted by user.")
54
+ finally:
55
+ service.stop()
56
+
57
+ return 0
58
+
59
+
60
+ if __name__ == "__main__":
61
+ raise SystemExit(main())
@@ -0,0 +1,324 @@
1
+ import time
2
+
3
+ from inovonics_echostream_processor.device_types import security_status_bit_definition, security_status_capabilities
4
+
5
+
6
+ DEFAULT_QUIET_PERIOD_MS = 500
7
+ DEFAULT_MAX_HOLD_MS = 2000
8
+ DEFAULT_IDLE_TTL_MS = 900000
9
+
10
+
11
+ class BitStateUpdate(object):
12
+ def __init__(
13
+ self,
14
+ device_uid_hex,
15
+ stat_group,
16
+ bit,
17
+ value,
18
+ source_event_type=None,
19
+ toggles_suppressed=0,
20
+ protocol_bit=None,
21
+ status_name=None,
22
+ status_label=None,
23
+ supported=None,
24
+ reserved=False,
25
+ ):
26
+ self.device_uid_hex = device_uid_hex
27
+ self.stat_group = stat_group
28
+ self.bit = bit
29
+ self.value = bool(value)
30
+ self.source_event_type = source_event_type
31
+ self.toggles_suppressed = toggles_suppressed
32
+ # Keep the historical one-based ``bit`` field while exposing the actual
33
+ # zero-based wire bit used by the EchoStream specification.
34
+ self.protocol_bit = int(protocol_bit) if protocol_bit is not None else max(int(bit) - 1, 0)
35
+ self.status_name = status_name
36
+ self.status_label = status_label
37
+ self.supported = supported
38
+ self.reserved = bool(reserved)
39
+
40
+ @property
41
+ def key(self):
42
+ return (self.device_uid_hex, self.stat_group, self.bit)
43
+
44
+
45
+ class BitStateCoalescerConfig(object):
46
+ def __init__(
47
+ self,
48
+ enabled=True,
49
+ quiet_period_ms=DEFAULT_QUIET_PERIOD_MS,
50
+ max_hold_ms=DEFAULT_MAX_HOLD_MS,
51
+ idle_ttl_ms=DEFAULT_IDLE_TTL_MS,
52
+ ):
53
+ self.enabled = bool(enabled)
54
+ self.quiet_period_ms = int(quiet_period_ms)
55
+ self.max_hold_ms = int(max_hold_ms)
56
+ self.idle_ttl_ms = int(idle_ttl_ms)
57
+
58
+ if self.quiet_period_ms < 0:
59
+ raise ValueError("quiet_period_ms must be >= 0")
60
+ if self.max_hold_ms <= 0:
61
+ raise ValueError("max_hold_ms must be > 0")
62
+ if self.idle_ttl_ms < 0:
63
+ raise ValueError("idle_ttl_ms must be >= 0")
64
+
65
+
66
+ class _BitStateEntry(object):
67
+ def __init__(self, update, now_ms):
68
+ self.device_uid_hex = update.device_uid_hex
69
+ self.stat_group = update.stat_group
70
+ self.bit = update.bit
71
+ self.update = update
72
+ self.last_emitted_value = None
73
+ self.has_emitted_value = False
74
+ self.pending_value = update.value
75
+ self.pending_started_ms = now_ms
76
+ self.last_changed_ms = now_ms
77
+ self.last_activity_ms = now_ms
78
+ self.source_event_type = update.source_event_type
79
+ self.toggles_suppressed = 0
80
+ self.force_emit_pending = False
81
+
82
+
83
+ class BitStateCoalescer(object):
84
+ def __init__(self, config=None, now_ms=None, diff_ms=None):
85
+ self.config = config or BitStateCoalescerConfig()
86
+ self._entries = {}
87
+ self._now_ms = now_ms or _default_now_ms
88
+ self._diff_ms = diff_ms or _default_diff_ms
89
+
90
+ @property
91
+ def entry_count(self):
92
+ return len(self._entries)
93
+
94
+ def ingest(self, updates, now_ms=None):
95
+ normalized_updates = _normalize_updates(updates)
96
+ if not normalized_updates:
97
+ return []
98
+
99
+ if not self.config.enabled:
100
+ return normalized_updates
101
+
102
+ now_ms = self._resolve_now_ms(now_ms)
103
+
104
+ for update in normalized_updates:
105
+ self._ingest_update(update, now_ms)
106
+
107
+ return self.flush_due(now_ms=now_ms)
108
+
109
+ def flush_due(self, now_ms=None):
110
+ if not self.config.enabled:
111
+ return []
112
+
113
+ now_ms = self._resolve_now_ms(now_ms)
114
+ ready_updates = []
115
+
116
+ for key, entry in list(self._entries.items()):
117
+ if entry.pending_value is not None and self._is_ready_to_emit(entry, now_ms):
118
+ emitted_update = self._emit_entry(entry)
119
+ if emitted_update is not None:
120
+ ready_updates.append(emitted_update)
121
+
122
+ if self._is_idle(entry, now_ms):
123
+ del self._entries[key]
124
+
125
+ return ready_updates
126
+
127
+ def flush_all(self, now_ms=None):
128
+ if not self.config.enabled:
129
+ return []
130
+
131
+ now_ms = self._resolve_now_ms(now_ms)
132
+ ready_updates = []
133
+
134
+ for key, entry in list(self._entries.items()):
135
+ if entry.pending_value is not None:
136
+ emitted_update = self._emit_entry(entry)
137
+ if emitted_update is not None:
138
+ ready_updates.append(emitted_update)
139
+
140
+ if self._is_idle(entry, now_ms):
141
+ del self._entries[key]
142
+
143
+ return ready_updates
144
+
145
+ def requeue(self, updates, now_ms=None):
146
+ normalized_updates = _normalize_updates(updates)
147
+ if not normalized_updates:
148
+ return
149
+
150
+ if not self.config.enabled:
151
+ return
152
+
153
+ now_ms = self._resolve_now_ms(now_ms)
154
+
155
+ for update in normalized_updates:
156
+ self._requeue_update(update, now_ms)
157
+
158
+ def clear(self):
159
+ self._entries.clear()
160
+
161
+ def _ingest_update(self, update, now_ms):
162
+ entry = self._entries.get(update.key)
163
+ if entry is None:
164
+ self._entries[update.key] = _BitStateEntry(update, now_ms)
165
+ return
166
+
167
+ entry.last_activity_ms = now_ms
168
+ entry.update = update
169
+ entry.source_event_type = update.source_event_type or entry.source_event_type
170
+
171
+ if entry.pending_value is None:
172
+ if entry.has_emitted_value and entry.last_emitted_value == update.value:
173
+ return
174
+
175
+ entry.pending_value = update.value
176
+ entry.pending_started_ms = now_ms
177
+ entry.last_changed_ms = now_ms
178
+ entry.toggles_suppressed = 0
179
+ entry.force_emit_pending = False
180
+ return
181
+
182
+ if entry.pending_value != update.value:
183
+ entry.pending_value = update.value
184
+ entry.last_changed_ms = now_ms
185
+ entry.toggles_suppressed += 1
186
+ entry.force_emit_pending = False
187
+
188
+ def _requeue_update(self, update, now_ms):
189
+ entry = self._entries.get(update.key)
190
+ if entry is None:
191
+ entry = _BitStateEntry(update, now_ms)
192
+ self._entries[update.key] = entry
193
+
194
+ entry.last_activity_ms = now_ms
195
+ entry.source_event_type = update.source_event_type or entry.source_event_type
196
+ entry.pending_value = update.value
197
+ entry.pending_started_ms = now_ms
198
+ entry.last_changed_ms = now_ms
199
+ entry.toggles_suppressed = max(
200
+ int(getattr(update, "toggles_suppressed", 0)),
201
+ entry.toggles_suppressed,
202
+ )
203
+ entry.force_emit_pending = True
204
+
205
+ def _emit_entry(self, entry):
206
+ if (
207
+ not entry.force_emit_pending
208
+ and entry.has_emitted_value
209
+ and entry.last_emitted_value == entry.pending_value
210
+ ):
211
+ entry.pending_value = None
212
+ entry.pending_started_ms = None
213
+ entry.last_changed_ms = None
214
+ entry.toggles_suppressed = 0
215
+ entry.force_emit_pending = False
216
+ return None
217
+
218
+ update = BitStateUpdate(
219
+ device_uid_hex=entry.device_uid_hex,
220
+ stat_group=entry.stat_group,
221
+ bit=entry.bit,
222
+ value=entry.pending_value,
223
+ source_event_type=entry.source_event_type,
224
+ toggles_suppressed=entry.toggles_suppressed,
225
+ protocol_bit=entry.update.protocol_bit,
226
+ status_name=entry.update.status_name,
227
+ status_label=entry.update.status_label,
228
+ supported=entry.update.supported,
229
+ reserved=entry.update.reserved,
230
+ )
231
+ entry.last_emitted_value = entry.pending_value
232
+ entry.has_emitted_value = True
233
+ entry.pending_value = None
234
+ entry.pending_started_ms = None
235
+ entry.last_changed_ms = None
236
+ entry.toggles_suppressed = 0
237
+ entry.force_emit_pending = False
238
+ return update
239
+
240
+ def _is_ready_to_emit(self, entry, now_ms):
241
+ quiet_elapsed_ms = self._diff_ms(now_ms, entry.last_changed_ms)
242
+ hold_elapsed_ms = self._diff_ms(now_ms, entry.pending_started_ms)
243
+ return (
244
+ quiet_elapsed_ms >= self.config.quiet_period_ms
245
+ or hold_elapsed_ms >= self.config.max_hold_ms
246
+ )
247
+
248
+ def _is_idle(self, entry, now_ms):
249
+ if entry.pending_value is not None:
250
+ return False
251
+
252
+ if self.config.idle_ttl_ms == 0:
253
+ return True
254
+
255
+ return self._diff_ms(now_ms, entry.last_activity_ms) >= self.config.idle_ttl_ms
256
+
257
+ def _resolve_now_ms(self, now_ms):
258
+ if now_ms is not None:
259
+ return int(now_ms)
260
+ return int(self._now_ms())
261
+
262
+
263
+ def security_event_to_bit_state_updates(event, supported_only=False):
264
+ """Convert both status bytes, optionally excluding documented reserved bits.
265
+
266
+ Unknown product models intentionally keep all raw bits. Dropping data for a
267
+ model that is missing from the capability table would hide useful evidence.
268
+ """
269
+ updates = []
270
+ source_event_type = getattr(event, "event_type", None)
271
+ device_model = getattr(event, "device_model", None)
272
+ supported_bits = security_status_capabilities(device_model)
273
+
274
+ for stat_group, flags in ((1, getattr(event, "stat1_flags", ())), (0, getattr(event, "stat0_flags", ()))):
275
+ for protocol_bit, value in enumerate(flags):
276
+ supported = None if supported_bits is None else (stat_group, protocol_bit) in supported_bits
277
+ if supported_only and supported is False:
278
+ continue
279
+ definition = security_status_bit_definition(stat_group, protocol_bit, device_model)
280
+ updates.append(
281
+ BitStateUpdate(
282
+ device_uid_hex=event.device_uid_hex,
283
+ stat_group=stat_group,
284
+ bit=protocol_bit + 1,
285
+ value=value,
286
+ source_event_type=source_event_type,
287
+ protocol_bit=protocol_bit,
288
+ status_name=definition["name"] if definition else None,
289
+ status_label=definition["label"] if definition else None,
290
+ supported=supported,
291
+ reserved=definition is None,
292
+ )
293
+ )
294
+
295
+ return updates
296
+
297
+
298
+ def security_event_to_supported_bit_state_updates(event):
299
+ """Return only supported status bits for a known product model."""
300
+ return security_event_to_bit_state_updates(event, supported_only=True)
301
+
302
+
303
+ def _normalize_updates(updates):
304
+ if updates is None:
305
+ return []
306
+
307
+ if isinstance(updates, BitStateUpdate):
308
+ return [updates]
309
+
310
+ return list(updates)
311
+
312
+
313
+ def _default_now_ms():
314
+ ticks_ms = getattr(time, "ticks_ms", None)
315
+ if ticks_ms is not None:
316
+ return int(ticks_ms())
317
+ return int(time.monotonic() * 1000)
318
+
319
+
320
+ def _default_diff_ms(later_ms, earlier_ms):
321
+ ticks_diff = getattr(time, "ticks_diff", None)
322
+ if ticks_diff is not None:
323
+ return int(ticks_diff(later_ms, earlier_ms))
324
+ return int(later_ms - earlier_ms)
@@ -0,0 +1,11 @@
1
+ from inovonics_echostream_processor.transports.cpython_socket import (
2
+ ProcessorMetrics,
3
+ SocketProcessorConfig as EchoStreamProcessorConfig,
4
+ SocketProcessorService as EchoStreamProcessor,
5
+ )
6
+
7
+ __all__ = [
8
+ "EchoStreamProcessor",
9
+ "EchoStreamProcessorConfig",
10
+ "ProcessorMetrics",
11
+ ]
@@ -0,0 +1,16 @@
1
+ import sys
2
+
3
+
4
+ def detect_runtime():
5
+ implementation = getattr(sys, "implementation", None)
6
+ if implementation is None:
7
+ return "unknown"
8
+ return getattr(implementation, "name", "unknown")
9
+
10
+
11
+ def is_cpython():
12
+ return detect_runtime() == "cpython"
13
+
14
+
15
+ def is_micropython():
16
+ return detect_runtime() == "micropython"
@@ -0,0 +1,125 @@
1
+ import logging
2
+
3
+ from inovonics_echostream_processor.events import (
4
+ AggregateMessageEvent,
5
+ CoordinatorNetworkIdEvent,
6
+ CoordinatorSerialNumberEvent,
7
+ CoordinatorStatusEvent,
8
+ )
9
+ from inovonics_echostream_processor.protocol import EchoStreamProtocol
10
+
11
+
12
+ class ProcessBatch(object):
13
+ def __init__(self, frames=None, events=None, outbound_commands=None):
14
+ self.frames = frames or []
15
+ self.events = events or []
16
+ self.outbound_commands = outbound_commands or []
17
+
18
+
19
+ class EchoStreamProcessorCore(object):
20
+ def __init__(self, auto_request_coordinator_metadata=True, logger=None):
21
+ self.auto_request_coordinator_metadata = auto_request_coordinator_metadata
22
+ self._logger = logger or logging.getLogger(self.__class__.__name__)
23
+ self._buffer = b""
24
+ self._handlers = []
25
+ self.coordinator_serial_number = None
26
+ self.coordinator_network_id = None
27
+
28
+ def add_event_handler(self, handler):
29
+ self._handlers.append(handler)
30
+
31
+ def feed(self, data):
32
+ if not data:
33
+ self._logger.debug("Ignoring empty EchoStream data chunk.")
34
+ return ProcessBatch()
35
+
36
+ self._logger.debug(
37
+ "Received %d bytes of EchoStream data; buffer before append=%d.",
38
+ len(data),
39
+ len(self._buffer),
40
+ )
41
+ self._buffer += data
42
+ frames, self._buffer = EchoStreamProtocol.extract_frames(self._buffer)
43
+ self._logger.debug(
44
+ "Extracted %d frame(s); %d buffered byte(s) remain.",
45
+ len(frames),
46
+ len(self._buffer),
47
+ )
48
+
49
+ events = []
50
+ outbound_commands = []
51
+ for frame in frames:
52
+ self._logger.debug("Processing frame: %s", frame.hex().upper())
53
+ event, commands = self.process_frame(frame)
54
+ events.append(event)
55
+ if isinstance(event, AggregateMessageEvent):
56
+ events.extend(event.children)
57
+ outbound_commands.extend(commands)
58
+
59
+ self._logger.debug(
60
+ "Feed completed with %d event(s) and %d outbound command(s).",
61
+ len(events),
62
+ len(outbound_commands),
63
+ )
64
+ return ProcessBatch(
65
+ frames=frames,
66
+ events=events,
67
+ outbound_commands=outbound_commands,
68
+ )
69
+
70
+ def process_frame(self, frame):
71
+ event = EchoStreamProtocol.parse_message(frame)
72
+ commands = self._update_state(event)
73
+ self._emit(event)
74
+ if isinstance(event, AggregateMessageEvent):
75
+ for child in event.children:
76
+ self._emit(child)
77
+ self._logger.debug(
78
+ "Parsed frame into %s; queued %d outbound command(s).",
79
+ event.event_type,
80
+ len(commands),
81
+ )
82
+ return event, commands
83
+
84
+ def _update_state(self, event):
85
+ if isinstance(event, CoordinatorSerialNumberEvent):
86
+ self.coordinator_serial_number = event.serial_number
87
+ self._logger.debug(
88
+ "Updated coordinator serial number to %s.",
89
+ event.serial_number,
90
+ )
91
+ return []
92
+
93
+ if isinstance(event, CoordinatorNetworkIdEvent):
94
+ self.coordinator_network_id = event.network_id
95
+ self._logger.debug(
96
+ "Updated coordinator network id to %s.",
97
+ event.network_id,
98
+ )
99
+ return []
100
+
101
+ if (
102
+ isinstance(event, CoordinatorStatusEvent)
103
+ and self.auto_request_coordinator_metadata
104
+ ):
105
+ if self.coordinator_serial_number is None:
106
+ self._logger.debug(
107
+ "Coordinator status received without serial number; requesting metadata."
108
+ )
109
+ return [EchoStreamProtocol.REQUEST_COORDINATOR_SERIAL_NUMBER]
110
+ if self.coordinator_network_id is None:
111
+ self._logger.debug(
112
+ "Coordinator status received without network id; requesting metadata."
113
+ )
114
+ return [EchoStreamProtocol.REQUEST_COORDINATOR_NETWORK_ID]
115
+
116
+ return []
117
+
118
+ def _emit(self, event):
119
+ self._logger.debug(
120
+ "Emitting %s to %d handler(s).",
121
+ event.event_type,
122
+ len(self._handlers),
123
+ )
124
+ for handler in list(self._handlers):
125
+ handler(event)