iotflows-device 1.1.0__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,6 @@
|
|
|
1
|
+
"""IoTFlows device/gateway client: publish machine execution state, production counts and metrics to IoTFlows over MQTT."""
|
|
2
|
+
|
|
3
|
+
from .device import Asset, Execution, IoTFlowsDevice, IoTFlowsError
|
|
4
|
+
|
|
5
|
+
__all__ = ["IoTFlowsDevice", "Asset", "Execution", "IoTFlowsError"]
|
|
6
|
+
__version__ = "1.1.0"
|
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import json
|
|
5
|
+
import math
|
|
6
|
+
import re
|
|
7
|
+
import secrets
|
|
8
|
+
import ssl
|
|
9
|
+
import threading
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
from collections import deque
|
|
14
|
+
from datetime import datetime, timezone
|
|
15
|
+
from enum import Enum
|
|
16
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
|
17
|
+
|
|
18
|
+
import paho.mqtt.client as mqtt
|
|
19
|
+
from paho.mqtt.enums import CallbackAPIVersion, MQTTErrorCode
|
|
20
|
+
|
|
21
|
+
DEFAULT_API_URL = "https://api.iotflows.com"
|
|
22
|
+
DEFAULT_MQTT_URL = "mqtts://mqtts.connections.iotflows.com:443"
|
|
23
|
+
DEFAULT_CONNECT_TIMEOUT = 30.0
|
|
24
|
+
RECONNECT_DELAY = 5
|
|
25
|
+
# IoTFlows sets every asset to STOPPED when the device connects, so each asset's last state is re-sent after this delay
|
|
26
|
+
RESTORE_DELAY = 2.0
|
|
27
|
+
# Messages published while offline are kept (oldest dropped first) and sent once reconnected
|
|
28
|
+
MAX_OFFLINE_MESSAGES = 1000
|
|
29
|
+
|
|
30
|
+
EVENTS = ("connect", "offline", "close", "error")
|
|
31
|
+
|
|
32
|
+
Timestamp = Union[datetime, str, int, float]
|
|
33
|
+
MetricValue = Union[int, float, str, bool]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Execution(str, Enum):
|
|
37
|
+
"""Asset execution states."""
|
|
38
|
+
|
|
39
|
+
RUNNING = "RUNNING"
|
|
40
|
+
STOPPED = "STOPPED"
|
|
41
|
+
UNKNOWN = "UNKNOWN"
|
|
42
|
+
"""Offline, disconnected or unknown."""
|
|
43
|
+
|
|
44
|
+
def __str__(self) -> str:
|
|
45
|
+
return self.value
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class IoTFlowsError(Exception):
|
|
49
|
+
"""Connecting to IoTFlows failed, or the device is used while not connected."""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _fetch_device(api_url: str, username: str, password: str, timeout: float) -> dict:
|
|
53
|
+
auth = base64.b64encode(f"{username}:{password}".encode()).decode()
|
|
54
|
+
request = urllib.request.Request(
|
|
55
|
+
f"{api_url}/v1/devices/{urllib.parse.quote(username, safe='')}",
|
|
56
|
+
headers={"Authorization": f"Basic {auth}", "Accept": "application/json"},
|
|
57
|
+
)
|
|
58
|
+
try:
|
|
59
|
+
with urllib.request.urlopen(request, timeout=timeout) as response:
|
|
60
|
+
return json.load(response)["data"]
|
|
61
|
+
except urllib.error.HTTPError as err:
|
|
62
|
+
if err.code == 401:
|
|
63
|
+
raise IoTFlowsError("Wrong device username or password") from None
|
|
64
|
+
body = err.read().decode(errors="replace")
|
|
65
|
+
raise IoTFlowsError(f"Failed to fetch device info (HTTP {err.code}): {body}") from None
|
|
66
|
+
except urllib.error.URLError as err:
|
|
67
|
+
raise IoTFlowsError(f"Failed to fetch device info: {err.reason}") from None
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class IoTFlowsDevice:
|
|
71
|
+
"""A device or gateway connected to IoTFlows.
|
|
72
|
+
|
|
73
|
+
Usage::
|
|
74
|
+
|
|
75
|
+
device = IoTFlowsDevice(username="dev_xxxxxxxx", password="xxxxxxxx")
|
|
76
|
+
device.connect()
|
|
77
|
+
device.asset("Line 10").execution(Execution.RUNNING)
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
def __init__(
|
|
81
|
+
self,
|
|
82
|
+
username: str,
|
|
83
|
+
password: str,
|
|
84
|
+
*,
|
|
85
|
+
api_url: str = DEFAULT_API_URL,
|
|
86
|
+
mqtt_url: str = DEFAULT_MQTT_URL,
|
|
87
|
+
connect_timeout: float = DEFAULT_CONNECT_TIMEOUT,
|
|
88
|
+
) -> None:
|
|
89
|
+
if not username or not password:
|
|
90
|
+
raise ValueError("IoTFlowsDevice requires a username and password")
|
|
91
|
+
|
|
92
|
+
self.uuid: str = username
|
|
93
|
+
self.organization_uuid: Optional[str] = None
|
|
94
|
+
self.base_topic: Optional[str] = None
|
|
95
|
+
self.assets: List[Asset] = []
|
|
96
|
+
self._password = password
|
|
97
|
+
self._api_url = api_url.rstrip("/")
|
|
98
|
+
self._mqtt_url = mqtt_url
|
|
99
|
+
self._connect_timeout = connect_timeout
|
|
100
|
+
self._client: Optional[mqtt.Client] = None
|
|
101
|
+
self._connected = False
|
|
102
|
+
self._lock = threading.Lock()
|
|
103
|
+
self._offline: deque = deque(maxlen=MAX_OFFLINE_MESSAGES)
|
|
104
|
+
self._restore_timer: Optional[threading.Timer] = None
|
|
105
|
+
self._listeners: Dict[str, List[Callable[..., Any]]] = {event: [] for event in EVENTS}
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def connected(self) -> bool:
|
|
109
|
+
return self._connected
|
|
110
|
+
|
|
111
|
+
def on(self, event: str, listener: Optional[Callable[..., Any]] = None):
|
|
112
|
+
"""Listen for 'connect', 'offline', 'close' or 'error' (called with the exception).
|
|
113
|
+
|
|
114
|
+
Listeners run on the MQTT network thread, so keep them short. Also works as a decorator::
|
|
115
|
+
|
|
116
|
+
@device.on("offline")
|
|
117
|
+
def offline():
|
|
118
|
+
print("offline")
|
|
119
|
+
"""
|
|
120
|
+
if event not in self._listeners:
|
|
121
|
+
raise ValueError(f'Unknown event "{event}". Use one of: {", ".join(EVENTS)}')
|
|
122
|
+
if listener is None:
|
|
123
|
+
return lambda fn: self.on(event, fn)
|
|
124
|
+
self._listeners[event].append(listener)
|
|
125
|
+
return listener
|
|
126
|
+
|
|
127
|
+
def connect(self) -> None:
|
|
128
|
+
"""Fetch the device's info (organization, topic, assets) and open the MQTT connection.
|
|
129
|
+
|
|
130
|
+
Returns once connected. After that the client reconnects on its own if the connection drops.
|
|
131
|
+
"""
|
|
132
|
+
if self._client:
|
|
133
|
+
raise IoTFlowsError("Already connected. Call disconnect() first.")
|
|
134
|
+
self._set_info(_fetch_device(self._api_url, self.uuid, self._password, self._connect_timeout))
|
|
135
|
+
self._connect()
|
|
136
|
+
|
|
137
|
+
def asset(self, key: str) -> Asset:
|
|
138
|
+
"""Find an asset by asset_uuid, custom identifier or custom name.
|
|
139
|
+
|
|
140
|
+
Exact matches win; otherwise matching ignores case and extra whitespace.
|
|
141
|
+
"""
|
|
142
|
+
if not self.base_topic:
|
|
143
|
+
raise IoTFlowsError("Call connect() before looking up assets")
|
|
144
|
+
for a in self.assets:
|
|
145
|
+
if key in (a.uuid, a.custom_identifier, a.custom_name):
|
|
146
|
+
return a
|
|
147
|
+
|
|
148
|
+
k = _normalize_name(key)
|
|
149
|
+
loose = [
|
|
150
|
+
a for a in self.assets
|
|
151
|
+
if _normalize_name(a.custom_identifier) == k or _normalize_name(a.custom_name) == k
|
|
152
|
+
]
|
|
153
|
+
if len(loose) == 1:
|
|
154
|
+
return loose[0]
|
|
155
|
+
|
|
156
|
+
names = ", ".join(f'"{a.custom_name}" ({a.uuid})' for a in self.assets)
|
|
157
|
+
if loose:
|
|
158
|
+
raise LookupError(f'Asset "{key}" matches more than one asset: {names}. Use its asset_uuid.')
|
|
159
|
+
raise LookupError(f'Asset "{key}" not found on this device. Available: {names or "none"}')
|
|
160
|
+
|
|
161
|
+
def disconnect(self) -> None:
|
|
162
|
+
"""Close the MQTT connection. IoTFlows then sets the device's assets to UNKNOWN."""
|
|
163
|
+
self._cancel_restore()
|
|
164
|
+
client, self._client = self._client, None
|
|
165
|
+
self._connected = False
|
|
166
|
+
self._offline.clear()
|
|
167
|
+
if client is None:
|
|
168
|
+
return
|
|
169
|
+
client.disconnect()
|
|
170
|
+
client.loop_stop()
|
|
171
|
+
|
|
172
|
+
def __enter__(self) -> IoTFlowsDevice:
|
|
173
|
+
self.connect()
|
|
174
|
+
return self
|
|
175
|
+
|
|
176
|
+
def __exit__(self, *exc: Any) -> None:
|
|
177
|
+
self.disconnect()
|
|
178
|
+
|
|
179
|
+
def _set_info(self, info: dict) -> None:
|
|
180
|
+
self.organization_uuid = info.get("organization_uuid")
|
|
181
|
+
self.base_topic = info.get("base_publishing_topic")
|
|
182
|
+
self.assets = [Asset(self, a) for a in info.get("assets") or []]
|
|
183
|
+
|
|
184
|
+
def _connect(self) -> None:
|
|
185
|
+
url = urllib.parse.urlparse(self._mqtt_url)
|
|
186
|
+
if url.scheme not in ("mqtt", "mqtts"):
|
|
187
|
+
raise ValueError(f"mqtt_url must start with mqtt:// or mqtts://, got {self._mqtt_url}")
|
|
188
|
+
tls = url.scheme == "mqtts"
|
|
189
|
+
|
|
190
|
+
client = mqtt.Client(
|
|
191
|
+
CallbackAPIVersion.VERSION2,
|
|
192
|
+
client_id=f"{self.uuid}_{secrets.token_hex(6)}",
|
|
193
|
+
protocol=mqtt.MQTTv5,
|
|
194
|
+
)
|
|
195
|
+
client.username_pw_set(self.uuid, self._password)
|
|
196
|
+
if tls:
|
|
197
|
+
client.tls_set_context(ssl.create_default_context())
|
|
198
|
+
client.reconnect_delay_set(RECONNECT_DELAY, RECONNECT_DELAY)
|
|
199
|
+
|
|
200
|
+
first = threading.Event()
|
|
201
|
+
failure: List[str] = []
|
|
202
|
+
|
|
203
|
+
def on_connect(client, userdata, flags, reason_code, properties):
|
|
204
|
+
if reason_code.is_failure:
|
|
205
|
+
if not first.is_set():
|
|
206
|
+
failure.append(f"IoTFlows refused the connection: {reason_code}")
|
|
207
|
+
first.set()
|
|
208
|
+
else:
|
|
209
|
+
self._emit("error", IoTFlowsError(f"IoTFlows refused the connection: {reason_code}"))
|
|
210
|
+
return
|
|
211
|
+
first.set()
|
|
212
|
+
with self._lock:
|
|
213
|
+
self._connected = True
|
|
214
|
+
while self._offline:
|
|
215
|
+
topic, payload = self._offline.popleft()
|
|
216
|
+
client.publish(topic, payload, qos=0, retain=False)
|
|
217
|
+
self._schedule_restore()
|
|
218
|
+
self._emit("connect")
|
|
219
|
+
|
|
220
|
+
def on_disconnect(client, userdata, flags, reason_code, properties):
|
|
221
|
+
if self._client is not client: # disconnect() was called
|
|
222
|
+
self._emit("close")
|
|
223
|
+
return
|
|
224
|
+
was_connected = self._connected
|
|
225
|
+
self._connected = False
|
|
226
|
+
self._cancel_restore()
|
|
227
|
+
if was_connected:
|
|
228
|
+
self._emit("offline")
|
|
229
|
+
self._emit("close")
|
|
230
|
+
|
|
231
|
+
client.on_connect = on_connect
|
|
232
|
+
client.on_disconnect = on_disconnect
|
|
233
|
+
self._client = client
|
|
234
|
+
client.connect_async(url.hostname, url.port or (8883 if tls else 1883), keepalive=60, clean_start=True)
|
|
235
|
+
client.loop_start()
|
|
236
|
+
|
|
237
|
+
if not first.wait(self._connect_timeout) or failure:
|
|
238
|
+
self._client = None
|
|
239
|
+
client.disconnect()
|
|
240
|
+
client.loop_stop()
|
|
241
|
+
if failure:
|
|
242
|
+
raise IoTFlowsError(failure[0])
|
|
243
|
+
raise IoTFlowsError(f"Timed out connecting to {self._mqtt_url} after {self._connect_timeout:g} s")
|
|
244
|
+
|
|
245
|
+
def _schedule_restore(self) -> None:
|
|
246
|
+
"""After every (re)connect, re-send each asset's last execution state, which IoTFlows has just reset to STOPPED."""
|
|
247
|
+
self._cancel_restore()
|
|
248
|
+
timer = threading.Timer(RESTORE_DELAY, self._restore)
|
|
249
|
+
timer.daemon = True
|
|
250
|
+
self._restore_timer = timer
|
|
251
|
+
timer.start()
|
|
252
|
+
|
|
253
|
+
def _cancel_restore(self) -> None:
|
|
254
|
+
if self._restore_timer:
|
|
255
|
+
self._restore_timer.cancel()
|
|
256
|
+
self._restore_timer = None
|
|
257
|
+
|
|
258
|
+
def _restore(self) -> None:
|
|
259
|
+
for asset in self.assets:
|
|
260
|
+
if asset._execution is None:
|
|
261
|
+
continue
|
|
262
|
+
try:
|
|
263
|
+
self._publish(asset, "execution", {"execution": asset._execution.value})
|
|
264
|
+
except Exception as err: # noqa: BLE001 - reported to 'error' listeners
|
|
265
|
+
self._emit("error", err)
|
|
266
|
+
|
|
267
|
+
def _publish(self, asset: Asset, action: str, payload: dict) -> None:
|
|
268
|
+
if not self._client:
|
|
269
|
+
raise IoTFlowsError("Not connected. Call connect() first.")
|
|
270
|
+
topic = f"{self.base_topic}/assets/{asset.uuid}/{action}"
|
|
271
|
+
message = json.dumps(payload, separators=(",", ":"))
|
|
272
|
+
with self._lock:
|
|
273
|
+
if self._connected:
|
|
274
|
+
info = self._client.publish(topic, message, qos=0, retain=False)
|
|
275
|
+
if info.rc == MQTTErrorCode.MQTT_ERR_SUCCESS:
|
|
276
|
+
return
|
|
277
|
+
if info.rc != MQTTErrorCode.MQTT_ERR_NO_CONN:
|
|
278
|
+
raise IoTFlowsError(f"Publish failed: {mqtt.error_string(info.rc)}")
|
|
279
|
+
self._offline.append((topic, message))
|
|
280
|
+
|
|
281
|
+
def _emit(self, event: str, *args: Any) -> None:
|
|
282
|
+
for listener in list(self._listeners[event]):
|
|
283
|
+
try:
|
|
284
|
+
listener(*args)
|
|
285
|
+
except Exception as err: # noqa: BLE001 - a listener error must not kill the network thread
|
|
286
|
+
if event != "error":
|
|
287
|
+
self._emit("error", err)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
class Asset:
|
|
291
|
+
"""An asset (machine) the device can publish to. Get one with ``device.asset(key)``."""
|
|
292
|
+
|
|
293
|
+
def __init__(self, device: IoTFlowsDevice, info: dict) -> None:
|
|
294
|
+
self._device = device
|
|
295
|
+
self.uuid: str = info.get("asset_uuid")
|
|
296
|
+
self.custom_identifier: Optional[str] = info.get("asset_custom_identifier")
|
|
297
|
+
self.custom_name: Optional[str] = info.get("asset_custom_name")
|
|
298
|
+
self.machine_name: Optional[str] = info.get("machine_name")
|
|
299
|
+
self.machine_identifier: Optional[str] = info.get("machine_identifier")
|
|
300
|
+
self._execution: Optional[Execution] = None # the last state set, re-sent after a reconnect
|
|
301
|
+
|
|
302
|
+
def __repr__(self) -> str:
|
|
303
|
+
return f"Asset(uuid={self.uuid!r}, custom_name={self.custom_name!r})"
|
|
304
|
+
|
|
305
|
+
def execution(self, state: Union[Execution, str], *, timestamp: Optional[Timestamp] = None) -> None:
|
|
306
|
+
"""Publish the execution state: Execution.RUNNING, Execution.STOPPED or Execution.UNKNOWN."""
|
|
307
|
+
value = _execution(state)
|
|
308
|
+
payload = _with_timestamp({"execution": value.value}, timestamp)
|
|
309
|
+
self._execution = value
|
|
310
|
+
self._device._publish(self, "execution", payload)
|
|
311
|
+
|
|
312
|
+
def count(
|
|
313
|
+
self,
|
|
314
|
+
count: int,
|
|
315
|
+
*,
|
|
316
|
+
operation_uuid: Optional[str] = None,
|
|
317
|
+
part_name: Optional[str] = None,
|
|
318
|
+
operation_name: Optional[str] = None,
|
|
319
|
+
timestamp: Optional[Timestamp] = None,
|
|
320
|
+
) -> None:
|
|
321
|
+
"""Add to the production count (incremental, not a total)."""
|
|
322
|
+
if not isinstance(count, int) or isinstance(count, bool):
|
|
323
|
+
raise ValueError(f"count must be an integer, got {count!r}")
|
|
324
|
+
|
|
325
|
+
payload: Dict[str, Any] = {"count": count}
|
|
326
|
+
for key, value in (("operation_uuid", operation_uuid), ("part_name", part_name), ("operation_name", operation_name)):
|
|
327
|
+
if value is None:
|
|
328
|
+
continue
|
|
329
|
+
if not isinstance(value, str) or not value.strip():
|
|
330
|
+
raise ValueError(f'count() option "{key}" must be a non-empty string')
|
|
331
|
+
payload[key] = value
|
|
332
|
+
self._device._publish(self, "count", _with_timestamp(payload, timestamp))
|
|
333
|
+
|
|
334
|
+
def metric(self, data: Dict[str, MetricValue], *, timestamp: Optional[Timestamp] = None) -> None:
|
|
335
|
+
"""Publish metrics, e.g. {"temperature": 72.5, "pressure": 101}.
|
|
336
|
+
|
|
337
|
+
Values must be finite numbers, strings or booleans.
|
|
338
|
+
"""
|
|
339
|
+
if not isinstance(data, dict) or not data:
|
|
340
|
+
raise ValueError('metric data must be a non-empty dict, e.g. {"temperature": 72.5}')
|
|
341
|
+
for key, value in data.items():
|
|
342
|
+
if not isinstance(key, str):
|
|
343
|
+
raise ValueError(f"metric names must be strings, got {key!r}")
|
|
344
|
+
ok = isinstance(value, (str, bool)) or (
|
|
345
|
+
isinstance(value, (int, float)) and math.isfinite(value)
|
|
346
|
+
)
|
|
347
|
+
if not ok:
|
|
348
|
+
raise ValueError(f'metric "{key}" must be a finite number, string or boolean, got {value!r}')
|
|
349
|
+
self._device._publish(self, "metric", _with_timestamp({"data": dict(data)}, timestamp))
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _execution(state: Any) -> Execution:
|
|
353
|
+
if isinstance(state, Execution):
|
|
354
|
+
return state
|
|
355
|
+
if isinstance(state, str):
|
|
356
|
+
try:
|
|
357
|
+
return Execution(state.strip().upper())
|
|
358
|
+
except ValueError:
|
|
359
|
+
pass
|
|
360
|
+
raise ValueError(
|
|
361
|
+
f"Invalid execution state {state!r}. Use Execution.RUNNING, Execution.STOPPED or Execution.UNKNOWN"
|
|
362
|
+
)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _with_timestamp(payload: dict, timestamp: Any) -> dict:
|
|
366
|
+
"""Accept a datetime, ISO 8601 string or epoch seconds, and send it as an ISO 8601 UTC string."""
|
|
367
|
+
if timestamp is None:
|
|
368
|
+
return payload
|
|
369
|
+
try:
|
|
370
|
+
if isinstance(timestamp, datetime):
|
|
371
|
+
date = timestamp
|
|
372
|
+
elif isinstance(timestamp, str):
|
|
373
|
+
# Python < 3.11 doesn't accept a trailing "Z"
|
|
374
|
+
date = datetime.fromisoformat(re.sub(r"[zZ]$", "+00:00", timestamp.strip()))
|
|
375
|
+
elif isinstance(timestamp, (int, float)) and not isinstance(timestamp, bool):
|
|
376
|
+
date = datetime.fromtimestamp(timestamp, timezone.utc)
|
|
377
|
+
else:
|
|
378
|
+
raise TypeError
|
|
379
|
+
# A naive datetime is taken as local time
|
|
380
|
+
date = date.astimezone(timezone.utc)
|
|
381
|
+
except (TypeError, ValueError, OverflowError, OSError):
|
|
382
|
+
raise ValueError(
|
|
383
|
+
f"Invalid timestamp {timestamp!r}. Use a datetime, ISO 8601 string or epoch seconds (time.time())"
|
|
384
|
+
) from None
|
|
385
|
+
payload["timestamp"] = date.isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
386
|
+
return payload
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
def _normalize_name(name: Any) -> str:
|
|
390
|
+
return " ".join(str(name if name is not None else "").split()).lower()
|
iotflows_device/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: iotflows-device
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: IoTFlows device/gateway client: publish machine execution state, production counts and metrics to IoTFlows over MQTT.
|
|
5
|
+
Project-URL: Homepage, https://iotflows.com
|
|
6
|
+
Project-URL: Source, https://github.com/iotflows/iotflows-device-python
|
|
7
|
+
Author-email: IoTFlows <support@iotflows.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: industrial,iot,iotflows,machine-monitoring,mqtt,oee
|
|
11
|
+
Classifier: Intended Audience :: Manufacturing
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: System :: Monitoring
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.9
|
|
17
|
+
Requires-Dist: paho-mqtt<3,>=2.0
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: pytest; extra == 'test'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# iotflows-device
|
|
23
|
+
|
|
24
|
+
Connect a device or gateway to [IoTFlows](https://iotflows.com) and publish machine data: execution state, production counts and metrics.
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
pip install iotflows-device
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Requires Python 3.9+. Includes type hints.
|
|
31
|
+
|
|
32
|
+
## Quick start
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
from iotflows_device import IoTFlowsDevice, Execution
|
|
36
|
+
|
|
37
|
+
device = IoTFlowsDevice(
|
|
38
|
+
username="dev_xxxxxxxx", # your device username
|
|
39
|
+
password="xxxxxxxx", # your device password
|
|
40
|
+
)
|
|
41
|
+
device.connect()
|
|
42
|
+
|
|
43
|
+
line = device.asset("Line 10") # by name, custom identifier or asset_uuid
|
|
44
|
+
|
|
45
|
+
line.execution(Execution.RUNNING)
|
|
46
|
+
line.count(1) # add 1 to the production count
|
|
47
|
+
line.metric({"temperature": 72.5, "rpm": 1200})
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Or as a context manager, which connects and disconnects for you:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
with IoTFlowsDevice(username="dev_xxxxxxxx", password="xxxxxxxx") as device:
|
|
54
|
+
device.asset("Line 10").count(1)
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Assets
|
|
58
|
+
|
|
59
|
+
After `connect()`, `device.assets` lists every asset (machine) this device can publish to:
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
for asset in device.assets:
|
|
63
|
+
print(asset.uuid, asset.custom_name, asset.custom_identifier, asset.machine_name)
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
`device.asset(key)` finds one by `asset_uuid`, custom identifier or custom name. Name matching ignores case and extra spaces, so `"line 10"` finds `Line 10`. It raises a `LookupError` listing the available assets if there's no match.
|
|
67
|
+
|
|
68
|
+
## Publishing
|
|
69
|
+
|
|
70
|
+
Every method accepts an optional `timestamp`: a `datetime`, an ISO 8601 string, or epoch seconds (`time.time()`). A `datetime` without a time zone is taken as local time. If you leave it out, IoTFlows uses the time the message arrives.
|
|
71
|
+
|
|
72
|
+
Invalid input raises a `ValueError` and nothing is sent. A misspelled option name such as `partName` instead of `part_name` raises a `TypeError`.
|
|
73
|
+
|
|
74
|
+
### Execution state
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
from iotflows_device import Execution
|
|
78
|
+
|
|
79
|
+
asset.execution(Execution.RUNNING)
|
|
80
|
+
asset.execution(Execution.STOPPED, timestamp=datetime.now(timezone.utc))
|
|
81
|
+
asset.execution(Execution.UNKNOWN) # offline / disconnected / unknown
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Use the `Execution` enum. Plain strings also work and are case-insensitive (`"running"`), but anything that isn't a valid state is rejected.
|
|
85
|
+
|
|
86
|
+
When the device connects, IoTFlows sets all of its assets to `STOPPED`. When it disconnects, they're set to `UNKNOWN`. You don't need to publish either one yourself.
|
|
87
|
+
|
|
88
|
+
After every connect and reconnect, the client re-sends each asset's last execution state (2 seconds later, once IoTFlows has reset it to `STOPPED`). So a machine that was running shows `RUNNING` again after a network drop, and a state set while offline is sent once the connection is back.
|
|
89
|
+
|
|
90
|
+
### Production count
|
|
91
|
+
|
|
92
|
+
`count` is **incremental**: it adds to the asset's count. It doesn't set a total.
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
asset.count(1)
|
|
96
|
+
asset.count(5, part_name="Bracket A", operation_name="Stamping")
|
|
97
|
+
asset.count(1, operation_uuid="op_xxxxxxxx")
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
IoTFlows picks the operation in this order:
|
|
101
|
+
1. `operation_uuid`, if given.
|
|
102
|
+
2. Otherwise `part_name` and/or `operation_name`, if given. An operation with those names is looked up, or created.
|
|
103
|
+
3. Otherwise the operation currently selected for the asset.
|
|
104
|
+
4. Otherwise a new unnamed part operation is created.
|
|
105
|
+
|
|
106
|
+
### Metrics
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
asset.metric({"temperature": 72.5, "pressure": 101.3, "status": "ok", "door_open": False})
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Values must be finite numbers, strings or booleans.
|
|
113
|
+
|
|
114
|
+
## Connection
|
|
115
|
+
|
|
116
|
+
The client runs its network connection on a background thread and reconnects on its own if the connection drops. Messages published while offline are queued (up to 1000) and sent once it reconnects. Publishing is thread-safe.
|
|
117
|
+
|
|
118
|
+
Add listeners before calling `connect()` so you don't miss the first event. They run on the network thread, so keep them short:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
device.on("connect", lambda: print("connected"))
|
|
122
|
+
device.on("offline", lambda: print("offline"))
|
|
123
|
+
|
|
124
|
+
@device.on("error")
|
|
125
|
+
def on_error(err):
|
|
126
|
+
print(err)
|
|
127
|
+
|
|
128
|
+
device.connect()
|
|
129
|
+
device.connected # bool
|
|
130
|
+
device.disconnect() # IoTFlows sets the assets to UNKNOWN; you can connect() again later
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`connect()` raises `IoTFlowsError` if the credentials are wrong or the broker can't be reached within `connect_timeout` (default 30 seconds).
|
|
134
|
+
|
|
135
|
+
## See also
|
|
136
|
+
|
|
137
|
+
- [`iotflows-mtconnect`](https://pypi.org/project/iotflows-mtconnect/): read execution state and part counts from an MTConnect agent, with a ready-to-run gateway to IoTFlows.
|
|
138
|
+
- [`@iotflows/device`](https://www.npmjs.com/package/@iotflows/device): the same client for Node.js.
|
|
139
|
+
|
|
140
|
+
## Development
|
|
141
|
+
|
|
142
|
+
```bash
|
|
143
|
+
pip install -e ".[test]"
|
|
144
|
+
pytest # offline unit tests
|
|
145
|
+
IOTFLOWS_USERNAME=dev_... IOTFLOWS_PASSWORD=... python tests/live.py # publishes real data
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
To build a client in another language, see [PROTOCOL.md](./PROTOCOL.md).
|
|
149
|
+
|
|
150
|
+
## License
|
|
151
|
+
|
|
152
|
+
Apache-2.0
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
iotflows_device/__init__.py,sha256=f8zztthyO66Fj6iNPs7KdCJKYbjklO-ssFpoIlzWfTY,284
|
|
2
|
+
iotflows_device/device.py,sha256=06jVXE8EFLUB1zfXYoAU2FXOVzKd4mb4NcrWfsp98Wk,15631
|
|
3
|
+
iotflows_device/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
iotflows_device-1.1.0.dist-info/METADATA,sha256=qf2g0cEAP4knhTJWcjiZfLhUWZzKx_LtG7XxQWNtvh0,5636
|
|
5
|
+
iotflows_device-1.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
iotflows_device-1.1.0.dist-info/licenses/LICENSE,sha256=UOZ1F5fFDe3XXvG4oNnkL1-Ecun7zpHzRxjp-XsMeAo,11324
|
|
7
|
+
iotflows_device-1.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|