simpleiot 0.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.
simpleiot/__init__.py ADDED
@@ -0,0 +1,47 @@
1
+ """A Python client for Simple IoT.
2
+
3
+ Connect with the shared token, read and write nodes and points, and watch
4
+ for changes::
5
+
6
+ import asyncio
7
+ import simpleiot
8
+
9
+ async def main():
10
+ async with await simpleiot.connect() as c:
11
+ root = await c.get_root()
12
+ print(root.description)
13
+
14
+ asyncio.run(main())
15
+ """
16
+
17
+ from .client import Client, PointsMessage, Subscription, connect
18
+ from .codec import (
19
+ DataType,
20
+ Node,
21
+ NotFoundError,
22
+ Point,
23
+ SiotError,
24
+ decode_nodes,
25
+ decode_points,
26
+ encode_points,
27
+ )
28
+ from .ids import new_id, valid_id
29
+
30
+ __version__ = "0.1.0"
31
+
32
+ __all__ = [
33
+ "Client",
34
+ "DataType",
35
+ "Node",
36
+ "NotFoundError",
37
+ "Point",
38
+ "PointsMessage",
39
+ "SiotError",
40
+ "Subscription",
41
+ "connect",
42
+ "decode_nodes",
43
+ "decode_points",
44
+ "encode_points",
45
+ "new_id",
46
+ "valid_id",
47
+ ]
simpleiot/client.py ADDED
@@ -0,0 +1,449 @@
1
+ """A Simple IoT client over NATS.
2
+
3
+ The client connects with the shared token (``SIOT_AUTH_TOKEN``), which gives
4
+ it the full subject space described in the API reference:
5
+ https://docs.simpleiot.org/docs/ref/api.html
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import hashlib
12
+ import logging
13
+ import os
14
+ import time
15
+ from collections.abc import AsyncIterator, Iterable
16
+ from dataclasses import dataclass
17
+
18
+ import nats
19
+ from nats.aio.client import Client as NATS
20
+ from nats.aio.subscription import Subscription as NatsSubscription
21
+
22
+ from .codec import (
23
+ Node,
24
+ NotFoundError,
25
+ Point,
26
+ SiotError,
27
+ decode_nodes,
28
+ decode_points,
29
+ encode_points,
30
+ )
31
+ from .ids import new_id, valid_id
32
+
33
+ __all__ = ["Client", "PointsMessage", "Subscription", "connect"]
34
+
35
+ log = logging.getLogger("simpleiot")
36
+
37
+ DEFAULT_SERVER = "nats://localhost:4222"
38
+
39
+ # The store answers in milliseconds once it is running, but can take
40
+ # seconds while it recovers streams at start-up. This matches the Go client.
41
+ DEFAULT_TIMEOUT = 20.0
42
+
43
+ _INVALID_TOKEN_CHARS = set(".*> \t\r\n")
44
+
45
+
46
+ async def connect(
47
+ server: str | None = None,
48
+ token: str | None = None,
49
+ **options,
50
+ ) -> Client:
51
+ """Connects to a Simple IoT instance.
52
+
53
+ ``server`` defaults to ``SIOT_NATS_SERVER``, then ``nats://localhost:4222``.
54
+ ``token`` defaults to ``SIOT_AUTH_TOKEN``; an instance with no token set
55
+ accepts a connection without one. Other options are passed to
56
+ ``nats.connect``.
57
+
58
+ The first connection attempt raises if the server cannot be reached or
59
+ refuses the token. Once connected, the client reconnects without limit
60
+ by default. Connection errors are logged to the ``simpleiot`` logger.
61
+ """
62
+ server = server or os.environ.get("SIOT_NATS_SERVER") or DEFAULT_SERVER
63
+ if token is None:
64
+ token = os.environ.get("SIOT_AUTH_TOKEN") or None
65
+ allow_reconnect = options.pop("allow_reconnect", True)
66
+ max_reconnect = options.pop("max_reconnect_attempts", -1)
67
+ wait = options.pop("reconnect_time_wait", 2)
68
+ options.setdefault("error_cb", _log_error)
69
+ # nats-py retries the first connection under the reconnect settings, so
70
+ # with no limit a server that is down would hang here. Try twice, then
71
+ # apply the caller's settings once connected.
72
+ nc = await nats.connect(
73
+ servers=[server],
74
+ token=token,
75
+ allow_reconnect=False,
76
+ max_reconnect_attempts=1,
77
+ reconnect_time_wait=0.2,
78
+ **options,
79
+ )
80
+ nc.options["allow_reconnect"] = allow_reconnect
81
+ nc.options["max_reconnect_attempts"] = max_reconnect
82
+ nc.options["reconnect_time_wait"] = wait
83
+ return Client(nc)
84
+
85
+
86
+ async def _log_error(e: Exception) -> None:
87
+ log.warning("nats: %s", e)
88
+
89
+
90
+ @dataclass
91
+ class PointsMessage:
92
+ """Points received on a subscription.
93
+
94
+ ``parent_id`` is set for edge points and empty for node points. For an
95
+ ``up`` subject, ``upstream_id`` is the ancestor the points were fanned
96
+ out to.
97
+ """
98
+
99
+ subject: str
100
+ node_id: str
101
+ parent_id: str
102
+ type: str
103
+ key: str
104
+ points: list[Point]
105
+ upstream_id: str = ""
106
+
107
+ @property
108
+ def is_edge(self) -> bool:
109
+ return self.parent_id != ""
110
+
111
+
112
+ def parse_subject(subject: str) -> dict[str, str]:
113
+ """Splits a point subject into its parts.
114
+
115
+ ::
116
+
117
+ p.<node>.<type>.<key>
118
+ ep.<node>.<parent>.<type>.<key>
119
+ up.<upstream>.<node>.<type>.<key>
120
+ up.<upstream>.<node>.<parent>.<type>.<key>
121
+ """
122
+ t = subject.split(".")
123
+ ret = {"upstream_id": "", "node_id": "", "parent_id": "", "type": "", "key": ""}
124
+ if t[0] == "up" and len(t) == 6:
125
+ ret.update(upstream_id=t[1], node_id=t[2], parent_id=t[3], type=t[4], key=t[5])
126
+ elif t[0] == "up" and len(t) == 5:
127
+ ret.update(upstream_id=t[1], node_id=t[2], type=t[3], key=t[4])
128
+ elif t[0] == "ep" and len(t) >= 3:
129
+ ret.update(node_id=t[1], parent_id=t[2])
130
+ if len(t) == 5:
131
+ ret.update(type=t[3], key=t[4])
132
+ elif t[0] == "p" and len(t) == 4:
133
+ ret.update(node_id=t[1], type=t[2], key=t[3])
134
+ return ret
135
+
136
+
137
+ class Subscription:
138
+ """Decoded point messages from a NATS subscription.
139
+
140
+ Iterate with ``async for msg in sub`` and stop with ``await
141
+ sub.unsubscribe()``, or use it as an async context manager.
142
+ """
143
+
144
+ def __init__(self, sub: NatsSubscription) -> None:
145
+ self._sub = sub
146
+
147
+ @property
148
+ def subject(self) -> str:
149
+ return self._sub.subject
150
+
151
+ async def __aiter__(self) -> AsyncIterator[PointsMessage]:
152
+ async for m in self._sub.messages:
153
+ try:
154
+ points = decode_points(m.data)
155
+ except ValueError:
156
+ continue
157
+ yield PointsMessage(subject=m.subject, points=points, **parse_subject(m.subject))
158
+
159
+ async def unsubscribe(self) -> None:
160
+ await self._sub.unsubscribe()
161
+
162
+ async def __aenter__(self) -> Subscription:
163
+ return self
164
+
165
+ async def __aexit__(self, *exc) -> None:
166
+ await self.unsubscribe()
167
+
168
+
169
+ def _check_token(what: str, s: str) -> None:
170
+ if not s or any(c in _INVALID_TOKEN_CHARS for c in s):
171
+ raise ValueError(f"{what} {s!r} may not be empty or contain '.', '*', '>', or whitespace")
172
+
173
+
174
+ def _check_reply(data: bytes) -> None:
175
+ if data:
176
+ raise SiotError(data.decode(errors="replace"))
177
+
178
+
179
+ class Client:
180
+ """A connection to a Simple IoT instance. Create one with :func:`connect`."""
181
+
182
+ def __init__(self, nc: NATS, timeout: float = DEFAULT_TIMEOUT) -> None:
183
+ self.nc = nc
184
+ self.timeout = timeout
185
+
186
+ async def close(self) -> None:
187
+ """Flushes pending messages and closes the connection."""
188
+ await self.nc.drain()
189
+
190
+ async def __aenter__(self) -> Client:
191
+ return self
192
+
193
+ async def __aexit__(self, *exc) -> None:
194
+ await self.close()
195
+
196
+ # --- reading nodes ---
197
+
198
+ async def get_nodes(
199
+ self,
200
+ parent: str,
201
+ id: str = "all",
202
+ *,
203
+ type: str = "",
204
+ include_deleted: bool = False,
205
+ depth: int = 0,
206
+ ) -> list[Node]:
207
+ """Fetches nodes, as the ``nodes.<parent>.<id>`` request.
208
+
209
+ - ``parent="all"`` returns every instance of node ``id``, one per edge.
210
+ - ``id="all"`` returns the children of ``parent``.
211
+ - ``parent="root", id="all"`` returns the root node.
212
+
213
+ ``type`` keeps only nodes of that type, ``include_deleted`` includes
214
+ deleted ones, and ``depth`` also returns descendants that many levels
215
+ down, in one flat list placed by each node's ``parent``.
216
+ """
217
+ params: list[Point] = []
218
+ if include_deleted:
219
+ params.append(Point("tombstone", 1))
220
+ if type:
221
+ params.append(Point("nodeType", type))
222
+ if depth > 0:
223
+ params.append(Point("depth", depth))
224
+ m = await self.nc.request(
225
+ f"nodes.{parent or 'all'}.{id or 'all'}", encode_points(params), timeout=self.timeout
226
+ )
227
+ try:
228
+ return decode_nodes(m.data)
229
+ except NotFoundError:
230
+ return []
231
+
232
+ async def get_node(self, id: str, parent: str = "all") -> Node:
233
+ """Returns one node. Raises :class:`NotFoundError` when it does not exist.
234
+
235
+ A node that sits in several places in the tree is returned under the
236
+ first of its parents unless ``parent`` names one.
237
+ """
238
+ nodes = await self.get_nodes(parent, id)
239
+ if not nodes:
240
+ raise NotFoundError(f"node {id} not found")
241
+ return nodes[0]
242
+
243
+ async def get_children(
244
+ self, parent: str, *, type: str = "", include_deleted: bool = False
245
+ ) -> list[Node]:
246
+ """Returns the children of a node."""
247
+ return await self.get_nodes(parent, "all", type=type, include_deleted=include_deleted)
248
+
249
+ async def get_root(self) -> Node:
250
+ """Returns the root node of the instance."""
251
+ nodes = await self.get_nodes("root", "all")
252
+ if not nodes:
253
+ raise NotFoundError("root node not found")
254
+ return nodes[0]
255
+
256
+ async def search(self, below: str, query: str, *, limit: int = 0, type: str = "") -> list[Node]:
257
+ """Finds nodes below ``below`` whose description, ID, or type matches.
258
+
259
+ The reply carries each match and its ancestors below ``below``.
260
+ ``limit`` caps the matches (20 by default, 100 at most).
261
+ """
262
+ params = [Point("search", query)]
263
+ if limit > 0:
264
+ params.append(Point("limit", limit))
265
+ if type:
266
+ params.append(Point("nodeType", type))
267
+ m = await self.nc.request(f"nodes.{below}.all", encode_points(params), timeout=self.timeout)
268
+ return decode_nodes(m.data)
269
+
270
+ # --- writing points ---
271
+
272
+ async def send_points(self, node_id: str, points: Iterable[Point], *, ack: bool = True) -> None:
273
+ """Writes points to a node.
274
+
275
+ Each point is its own message on ``p.<node>.<type>.<key>``. With
276
+ ``ack`` the call waits for the store to accept each point and raises
277
+ :class:`SiotError` if it refuses one.
278
+ """
279
+ _check_token("node ID", node_id)
280
+ for p in points:
281
+ _check_token("point type", p.type)
282
+ _check_token("point key", p.key or "0")
283
+ subject = f"p.{node_id}.{p.type}.{p.key or '0'}"
284
+ await self._send(subject, [p], ack)
285
+
286
+ async def send_point(self, node_id: str, type: str, value, key: str = "0", **kw) -> None:
287
+ """Writes a single point to a node. Extra arguments go to :class:`Point`."""
288
+ await self.send_points(node_id, [Point(type, value, key=key, **kw)])
289
+
290
+ async def send_edge_points(
291
+ self, node_id: str, parent: str, points: Iterable[Point], *, ack: bool = True
292
+ ) -> None:
293
+ """Writes points to the edge between a node and its parent, in one message."""
294
+ _check_token("node ID", node_id)
295
+ _check_token("parent ID", parent)
296
+ await self._send(f"ep.{node_id}.{parent}", list(points), ack)
297
+
298
+ async def _send(self, subject: str, points: list[Point], ack: bool) -> None:
299
+ data = encode_points(points)
300
+ if ack:
301
+ m = await self.nc.request(subject, data, timeout=self.timeout)
302
+ _check_reply(m.data)
303
+ else:
304
+ await self.nc.publish(subject, data)
305
+
306
+ # --- creating and removing nodes ---
307
+
308
+ async def create_node(
309
+ self,
310
+ parent: str,
311
+ type: str,
312
+ points: Iterable[Point] = (),
313
+ *,
314
+ id: str | None = None,
315
+ description: str | None = None,
316
+ primary: bool = False,
317
+ ) -> str:
318
+ """Creates a node under ``parent`` and returns its ID.
319
+
320
+ ``id`` defaults to a new random ID. ``description`` is a shortcut for
321
+ a description point. Set ``primary`` for a node type that owns
322
+ hardware or a connection (Modbus, serial, sync, and the like), so its
323
+ client runs on this edge only; see "Primary and mirror edges" in the
324
+ data reference.
325
+
326
+ Sending to an existing ID and parent updates that node.
327
+ """
328
+ id = id or new_id()
329
+ if not valid_id(id):
330
+ raise ValueError(f"invalid node ID {id!r}")
331
+ pts = list(points)
332
+ if description is not None:
333
+ pts.append(Point("description", description))
334
+ await self.send_points(id, pts)
335
+ edge = [Point("tombstone", 0), Point("nodeType", type)]
336
+ if primary:
337
+ edge.append(Point("primary", 1))
338
+ await self.send_edge_points(id, parent, edge)
339
+ return id
340
+
341
+ async def delete_node(self, id: str, parent: str) -> None:
342
+ """Removes a node from ``parent``.
343
+
344
+ Deleting a node's primary edge also deletes its mirrors, as the web
345
+ UI does. The node can be restored by setting the edge tombstone back
346
+ to 0.
347
+ """
348
+ nodes = await self.get_nodes("all", id)
349
+ tomb = [Point("tombstone", 1)]
350
+ here = next((n for n in nodes if n.parent == parent), None)
351
+ if here is not None and _role_set(here, "primary"):
352
+ for n in nodes:
353
+ if n.parent != parent and _role_set(n, "mirror"):
354
+ await self.send_edge_points(id, n.parent, tomb)
355
+ await self.send_edge_points(id, parent, tomb)
356
+
357
+ async def move_node(self, id: str, old_parent: str, new_parent: str) -> None:
358
+ """Moves a node from one parent to another, keeping its edge role."""
359
+ nodes = await self.get_nodes(old_parent, id)
360
+ if not nodes:
361
+ raise NotFoundError(f"node {id} not found under {old_parent}")
362
+ n = nodes[0]
363
+ edge = [Point("tombstone", 0), Point("nodeType", n.type)]
364
+ for role in ("primary", "mirror"):
365
+ if _role_set(n, role):
366
+ edge.append(Point(role, 1))
367
+ await self.send_edge_points(id, new_parent, edge)
368
+ await self.send_edge_points(id, old_parent, [Point("tombstone", 1)])
369
+
370
+ # --- provisioning ---
371
+
372
+ async def provision(self, name: str, contents: str, *, timeout: float = 30.0) -> str:
373
+ """Uploads a YAML node file for the server to apply, and waits until it has.
374
+
375
+ The file is a ``file`` node called ``name`` under the instance's
376
+ ``provisioning`` node, which is created if there is none. The server
377
+ applies it the way ``siot import`` does: nodes are matched by
378
+ description, missing ones are created, and changed points are
379
+ updated. It applies the file again only when its contents change.
380
+
381
+ Returns the file node's ID. Raises :class:`SiotError` with the
382
+ server's message if the file fails to apply, and ``TimeoutError`` if
383
+ it is not applied within ``timeout`` seconds. See "Configuration
384
+ provisioning" in the configuration guide.
385
+ """
386
+ want = hashlib.sha256(contents.encode()).hexdigest()
387
+ root = await self.get_root()
388
+ provs = await self.get_children(root.id, type="provisioning")
389
+ if provs:
390
+ prov = provs[0].id
391
+ else:
392
+ prov = await self.create_node(
393
+ root.id, "provisioning", description="Provisioning", primary=True
394
+ )
395
+
396
+ file = next(
397
+ (
398
+ f
399
+ for f in await self.get_children(prov, type="file")
400
+ if name in (f.value("name"), f.description)
401
+ ),
402
+ None,
403
+ )
404
+ if file is None:
405
+ id = await self.create_node(
406
+ prov,
407
+ "file",
408
+ [Point("name", name), Point("created", int(time.time())), Point("data", contents)],
409
+ description=name,
410
+ )
411
+ else:
412
+ id = file.id
413
+ if file.value("data") != contents:
414
+ await self.send_point(id, "data", contents)
415
+
416
+ # the server records the hash of what it tried, with the error, after
417
+ # each attempt
418
+ deadline = time.monotonic() + timeout
419
+ while True:
420
+ n = await self.get_node(id, prov)
421
+ if n.value("provisionHash") == want:
422
+ err = n.value("error", default="")
423
+ if err:
424
+ raise SiotError(f"provisioning {name}: {err}")
425
+ return id
426
+ if time.monotonic() > deadline:
427
+ raise TimeoutError(f"provisioning {name} was not applied within {timeout} s")
428
+ await asyncio.sleep(0.2)
429
+
430
+ # --- subscriptions ---
431
+
432
+ async def subscribe(self, subject: str) -> Subscription:
433
+ """Subscribes to any point subject and returns decoded messages."""
434
+ return Subscription(await self.nc.subscribe(subject))
435
+
436
+ async def subscribe_node(self, id: str) -> Subscription:
437
+ """Subscribes to the node points of one node, after the store accepts them."""
438
+ _check_token("node ID", id)
439
+ return await self.subscribe(f"up.{id}.{id}.*.*")
440
+
441
+ async def subscribe_tree(self, id: str) -> Subscription:
442
+ """Subscribes to every node and edge point at or below a node."""
443
+ _check_token("node ID", id)
444
+ return await self.subscribe(f"up.{id}.>")
445
+
446
+
447
+ def _role_set(n: Node, role: str) -> bool:
448
+ p = n.edge_point(role)
449
+ return p is not None and p.bool
simpleiot/codec.py ADDED
@@ -0,0 +1,372 @@
1
+ """Points, nodes, and their binary wire encoding.
2
+
3
+ This mirrors ``data/point.go`` and ``data/node.go`` in the Go code. Integers
4
+ are little endian, strings and byte fields carry a two-byte length, time is
5
+ int64 nanoseconds since the epoch, and a node reply starts with a version
6
+ byte and an error string.
7
+
8
+ The tests check this module against the fixtures ``data/point_fixture_test.go``
9
+ writes, so the Python and Go encoders cannot drift without a test failing.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import struct
16
+ from dataclasses import dataclass, field
17
+ from datetime import datetime, timedelta, timezone
18
+ from enum import IntEnum
19
+ from typing import Any
20
+
21
+ __all__ = [
22
+ "DataType",
23
+ "Node",
24
+ "Point",
25
+ "SiotError",
26
+ "NotFoundError",
27
+ "decode_nodes",
28
+ "decode_points",
29
+ "encode_points",
30
+ ]
31
+
32
+ NODE_FRAME_VERSION = 1
33
+ MAX_POINTS_PER_MESSAGE = 10000
34
+ MAX_NODES_PER_FRAME = 10000
35
+
36
+ # the error string the server sends when a node does not exist
37
+ # (data.ErrDocumentNotFound)
38
+ _NOT_FOUND = "document not found"
39
+
40
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
41
+
42
+
43
+ class SiotError(Exception):
44
+ """An error reported by the Simple IoT server."""
45
+
46
+
47
+ class NotFoundError(SiotError):
48
+ """The requested node does not exist."""
49
+
50
+
51
+ class DataType(IntEnum):
52
+ """How a point's value is encoded, as ``data.PointDataType``."""
53
+
54
+ UNKNOWN = 0
55
+ FLOAT = 1
56
+ INT = 2
57
+ STRING = 3
58
+ JSON = 4
59
+
60
+
61
+ Value = float | int | str | bool | dict | list | bytes | None
62
+
63
+
64
+ @dataclass
65
+ class Point:
66
+ """A single value on a node or an edge.
67
+
68
+ ``value`` sets both the data and its type when sending: a ``str`` is a
69
+ string point, a ``dict`` or ``list`` is a JSON point, and a number or
70
+ ``bool`` is a float point. Pass ``data_type=DataType.INT`` to send an
71
+ integer as an int point, or ``DataType.JSON`` to send a string that
72
+ already holds JSON. ``None`` sends a point with no value.
73
+
74
+ A missing ``time`` is filled in with the current time when the point is
75
+ sent. ``key`` separates points of the same type, such as the channels of
76
+ an input; most points use ``"0"``.
77
+ """
78
+
79
+ type: str
80
+ value: Value = None
81
+ key: str = "0"
82
+ time: datetime | None = None
83
+ tombstone: int = 0
84
+ origin: str = ""
85
+ data_type: DataType | None = None
86
+
87
+ @property
88
+ def number(self) -> float:
89
+ """The numeric value, or 0 for a point that is not a number.
90
+
91
+ This matches ``Point.Val()`` in Go. A ``bool`` value reads as 1 or 0.
92
+ """
93
+ v = self.value
94
+ if isinstance(v, bool):
95
+ return 1.0 if v else 0.0
96
+ if isinstance(v, (int, float)):
97
+ return float(v)
98
+ return 0.0
99
+
100
+ @property
101
+ def text(self) -> str:
102
+ """The string value, or ``""`` for a point that is not a string.
103
+
104
+ This matches ``Point.Txt()`` in Go. A JSON point returns its JSON text.
105
+ """
106
+ dt, data = _point_data(self)
107
+ if dt in (DataType.STRING, DataType.JSON):
108
+ return data.decode()
109
+ return ""
110
+
111
+ @property
112
+ def bool(self) -> bool:
113
+ """True when the numeric value is 1, as ``Point.Bool()`` in Go."""
114
+ return self.number == 1
115
+
116
+ @property
117
+ def deleted(self) -> bool:
118
+ """True when the point has been deleted (its tombstone is set)."""
119
+ return self.tombstone != 0
120
+
121
+
122
+ @dataclass
123
+ class Node:
124
+ """A node and the edge points that place it under ``parent``."""
125
+
126
+ id: str
127
+ type: str
128
+ parent: str = ""
129
+ points: list[Point] = field(default_factory=list)
130
+ edge_points: list[Point] = field(default_factory=list)
131
+
132
+ def point(self, type: str, key: str = "0") -> Point | None:
133
+ """Returns the node point with this type and key, or None."""
134
+ return _find(self.points, type, key)
135
+
136
+ def edge_point(self, type: str, key: str = "0") -> Point | None:
137
+ """Returns the edge point with this type and key, or None."""
138
+ return _find(self.edge_points, type, key)
139
+
140
+ def value(self, type: str, key: str = "0", default: Any = None) -> Any:
141
+ """Returns the value of a node point, or ``default`` when it is missing."""
142
+ p = self.point(type, key)
143
+ if p is None or p.deleted:
144
+ return default
145
+ return p.value
146
+
147
+ @property
148
+ def description(self) -> str:
149
+ """The node's description, or ``""``."""
150
+ p = self.point("description")
151
+ return p.text if p else ""
152
+
153
+ @property
154
+ def deleted(self) -> bool:
155
+ """True when the edge to ``parent`` has been deleted."""
156
+ p = self.edge_point("tombstone")
157
+ return p is not None and p.bool
158
+
159
+
160
+ def _norm_key(key: str) -> str:
161
+ # the store keeps an empty key as "0"
162
+ return key or "0"
163
+
164
+
165
+ def _find(points: list[Point], type: str, key: str) -> Point | None:
166
+ key = _norm_key(key)
167
+ for p in points:
168
+ if p.type == type and _norm_key(p.key) == key:
169
+ return p
170
+ return None
171
+
172
+
173
+ def _int_bytes(v: int) -> bytes:
174
+ # the smallest width that holds the value, as data.Point.PutInt
175
+ if -(1 << 7) <= v < (1 << 7):
176
+ return struct.pack("<b", v)
177
+ if -(1 << 15) <= v < (1 << 15):
178
+ return struct.pack("<h", v)
179
+ if -(1 << 31) <= v < (1 << 31):
180
+ return struct.pack("<i", v)
181
+ return struct.pack("<q", v)
182
+
183
+
184
+ def _point_data(p: Point) -> tuple[DataType, bytes]:
185
+ v = p.value
186
+ dt = p.data_type
187
+ if v is None:
188
+ return DataType.UNKNOWN, b""
189
+ if isinstance(v, bytes):
190
+ return (dt if dt is not None else DataType.UNKNOWN), v
191
+ if isinstance(v, str):
192
+ return (DataType.JSON if dt == DataType.JSON else DataType.STRING), v.encode()
193
+ if isinstance(v, (dict, list)):
194
+ return DataType.JSON, json.dumps(v, separators=(",", ":")).encode()
195
+ if isinstance(v, bool):
196
+ v = 1 if v else 0
197
+ if isinstance(v, (int, float)):
198
+ if dt == DataType.INT:
199
+ if isinstance(v, float) and not v.is_integer():
200
+ raise ValueError(f"point {p.type}: {v} is not an integer")
201
+ return DataType.INT, _int_bytes(int(v))
202
+ return DataType.FLOAT, struct.pack("<d", float(v))
203
+ raise TypeError(f"point {p.type}: unsupported value type {type(v).__name__}")
204
+
205
+
206
+ def _to_nanos(t: datetime | None) -> int:
207
+ if t is None:
208
+ t = datetime.now(timezone.utc)
209
+ elif t.tzinfo is None:
210
+ t = t.astimezone()
211
+ d = t - _EPOCH
212
+ return (d.days * 86400 + d.seconds) * 1_000_000_000 + d.microseconds * 1000
213
+
214
+
215
+ def _from_nanos(ns: int) -> datetime:
216
+ return _EPOCH + timedelta(microseconds=ns // 1000)
217
+
218
+
219
+ def _decode_value(dt: int, data: bytes) -> Value:
220
+ if dt == DataType.FLOAT:
221
+ if len(data) == 8:
222
+ return struct.unpack("<d", data)[0]
223
+ if len(data) == 4:
224
+ return struct.unpack("<f", data)[0]
225
+ return 0.0
226
+ if dt == DataType.INT:
227
+ fmt = {1: "<b", 2: "<h", 4: "<i", 8: "<q"}.get(len(data))
228
+ return struct.unpack(fmt, data)[0] if fmt else 0
229
+ if dt in (DataType.STRING, DataType.JSON):
230
+ return data.decode()
231
+ if not data:
232
+ return None
233
+ return data
234
+
235
+
236
+ class _Writer:
237
+ def __init__(self) -> None:
238
+ self.buf = bytearray()
239
+
240
+ def u8(self, v: int) -> None:
241
+ self.buf.append(v & 0xFF)
242
+
243
+ def u32(self, v: int) -> None:
244
+ self.buf += struct.pack("<I", v & 0xFFFFFFFF)
245
+
246
+ def i64(self, v: int) -> None:
247
+ self.buf += struct.pack("<q", v)
248
+
249
+ def bytes(self, b: bytes) -> None:
250
+ if len(b) > 0xFFFF:
251
+ raise ValueError(f"field of {len(b)} bytes is too long to encode")
252
+ self.buf += struct.pack("<H", len(b))
253
+ self.buf += b
254
+
255
+ def string(self, s: str) -> None:
256
+ self.bytes(s.encode())
257
+
258
+
259
+ class _Reader:
260
+ def __init__(self, data: bytes) -> None:
261
+ self.data = memoryview(data)
262
+ self.off = 0
263
+
264
+ def _take(self, n: int, what: str) -> memoryview:
265
+ if self.off + n > len(self.data):
266
+ raise ValueError(f"decode: not enough data for {what} at offset {self.off}")
267
+ b = self.data[self.off : self.off + n]
268
+ self.off += n
269
+ return b
270
+
271
+ def u8(self) -> int:
272
+ return self._take(1, "byte")[0]
273
+
274
+ def u32(self) -> int:
275
+ return struct.unpack("<I", self._take(4, "count"))[0]
276
+
277
+ def i32(self) -> int:
278
+ return struct.unpack("<i", self._take(4, "int32"))[0]
279
+
280
+ def i64(self) -> int:
281
+ return struct.unpack("<q", self._take(8, "time"))[0]
282
+
283
+ def bytes(self) -> bytes:
284
+ n = struct.unpack("<H", self._take(2, "length"))[0]
285
+ return bytes(self._take(n, "bytes"))
286
+
287
+ def string(self) -> str:
288
+ return self.bytes().decode()
289
+
290
+
291
+ def _encode_points_to(w: _Writer, points: list[Point]) -> None:
292
+ w.u32(len(points))
293
+ for p in points:
294
+ dt, data = _point_data(p)
295
+ w.string(p.type)
296
+ w.string(p.key)
297
+ w.i64(_to_nanos(p.time))
298
+ w.u8(dt)
299
+ w.bytes(data)
300
+ w.u32(p.tombstone)
301
+ w.string(p.origin)
302
+
303
+
304
+ def _decode_points_from(r: _Reader) -> list[Point]:
305
+ count = r.u32()
306
+ if count > MAX_POINTS_PER_MESSAGE:
307
+ raise ValueError(f"decode: point count {count} exceeds maximum")
308
+ points = []
309
+ for _ in range(count):
310
+ typ = r.string()
311
+ key = r.string() or "0"
312
+ t = _from_nanos(r.i64())
313
+ dt = r.u8()
314
+ data = r.bytes()
315
+ tombstone = r.i32()
316
+ origin = r.string()
317
+ points.append(
318
+ Point(
319
+ type=typ,
320
+ key=key,
321
+ time=t,
322
+ value=_decode_value(dt, data),
323
+ data_type=DataType(dt) if dt in DataType._value2member_map_ else None,
324
+ tombstone=tombstone,
325
+ origin=origin,
326
+ )
327
+ )
328
+ return points
329
+
330
+
331
+ def encode_points(points: list[Point]) -> bytes:
332
+ """Returns the wire encoding of a list of points."""
333
+ w = _Writer()
334
+ _encode_points_to(w, points)
335
+ return bytes(w.buf)
336
+
337
+
338
+ def decode_points(data: bytes) -> list[Point]:
339
+ """Returns the points in a wire payload."""
340
+ return _decode_points_from(_Reader(data))
341
+
342
+
343
+ def decode_nodes(data: bytes) -> list[Node]:
344
+ """Returns the nodes in a node reply.
345
+
346
+ An error the server put in the reply is raised as :class:`SiotError`, or
347
+ :class:`NotFoundError` when the node does not exist. An empty payload is
348
+ no nodes.
349
+ """
350
+ if not data:
351
+ return []
352
+ r = _Reader(data)
353
+ version = r.u8()
354
+ if version != NODE_FRAME_VERSION:
355
+ raise ValueError(f"decode: unsupported node frame version {version}")
356
+ err = r.string()
357
+ if err == _NOT_FOUND:
358
+ raise NotFoundError(err)
359
+ if err:
360
+ raise SiotError(err)
361
+ count = r.u32()
362
+ if count > MAX_NODES_PER_FRAME:
363
+ raise ValueError(f"decode: node count {count} exceeds maximum")
364
+ nodes = []
365
+ for _ in range(count):
366
+ nid = r.string()
367
+ typ = r.string()
368
+ parent = r.string()
369
+ points = _decode_points_from(r)
370
+ edge_points = _decode_points_from(r)
371
+ nodes.append(Node(nid, typ, parent, points, edge_points))
372
+ return nodes
simpleiot/ids.py ADDED
@@ -0,0 +1,31 @@
1
+ """Node IDs, as ``data/id.go``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import os
7
+ import re
8
+
9
+ __all__ = ["new_id", "valid_id"]
10
+
11
+ # lowercase Crockford base32, the alphabet data.NewID uses
12
+ _STD = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
13
+ _CROCKFORD = "0123456789abcdefghjkmnpqrstvwxyz"
14
+ _TO_CROCKFORD = str.maketrans(_STD, _CROCKFORD)
15
+
16
+ _VALID = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{0,63}")
17
+
18
+
19
+ def new_id() -> str:
20
+ """Returns a new random node ID: 128 random bits as 26 characters."""
21
+ b = base64.b32encode(os.urandom(16)).decode().rstrip("=")
22
+ return b.translate(_TO_CROCKFORD)
23
+
24
+
25
+ def valid_id(id: str) -> bool:
26
+ """Reports whether an ID chosen by hand is safe to use.
27
+
28
+ An ID is 1 to 64 ASCII letters, digits, and ``-``, not starting with
29
+ ``-``. Other characters would split or corrupt a NATS subject.
30
+ """
31
+ return _VALID.fullmatch(id) is not None
simpleiot/py.typed ADDED
File without changes
@@ -0,0 +1,160 @@
1
+ Metadata-Version: 2.5
2
+ Name: simpleiot
3
+ Version: 0.1.0
4
+ Summary: Python client for Simple IoT, over NATS
5
+ Project-URL: Homepage, https://simpleiot.org
6
+ Project-URL: Documentation, https://docs.simpleiot.org/python/
7
+ Project-URL: Repository, https://github.com/simpleiot/simpleiot
8
+ Project-URL: Changelog, https://github.com/simpleiot/simpleiot/blob/master/python/CHANGELOG.md
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: iot,nats,simpleiot
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: System :: Networking
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: nats-py>=2.6
19
+ Description-Content-Type: text/markdown
20
+
21
+ # simpleiot
22
+
23
+ A Python client for [Simple IoT](https://simpleiot.org). Read and write nodes
24
+ and points, and watch for changes, over the NATS API.
25
+
26
+ The client connects with the instance's shared token (`SIOT_AUTH_TOKEN`), which
27
+ reaches the whole tree. It suits scripts and services running alongside an
28
+ instance you operate.
29
+
30
+ ![a Python process on an edge device talks to the local SIOT over NATS; the local SIOT syncs with the cloud, and people use the web UI on either instance](https://docs.simpleiot.org/python/images/deployment.svg)
31
+
32
+ A typical setup runs the Python process next to SIOT on an edge device. What it
33
+ writes reaches the cloud through sync, and a person sees it in the web UI on
34
+ site or remotely.
35
+
36
+ ## Install
37
+
38
+ ```
39
+ pip install simpleiot
40
+ ```
41
+
42
+ Requires Python 3.10 or newer. The client is built on
43
+ [nats-py](https://github.com/nats-io/nats.py) and uses `asyncio`.
44
+
45
+ ## Usage
46
+
47
+ ```python
48
+ import asyncio
49
+ import simpleiot
50
+ from simpleiot import Point
51
+
52
+
53
+ async def main():
54
+ async with await simpleiot.connect() as c:
55
+ root = await c.get_root()
56
+ print("root:", root.description)
57
+
58
+ id = await c.create_node(root.id, "variable", description="tank level")
59
+ await c.send_point(id, "value", 42.5)
60
+
61
+ async with await c.subscribe_node(id) as sub:
62
+ async for m in sub:
63
+ for p in m.points:
64
+ print(p.type, p.value)
65
+
66
+
67
+ asyncio.run(main())
68
+ ```
69
+
70
+ `connect()` reads `SIOT_NATS_SERVER` (default `nats://localhost:4222`) and
71
+ `SIOT_AUTH_TOKEN` from the environment, or takes them as arguments:
72
+
73
+ ```python
74
+ c = await simpleiot.connect("nats://10.0.0.5:4222", token="...")
75
+ ```
76
+
77
+ ## Nodes and points
78
+
79
+ Data in Simple IoT is a tree of **nodes**, each holding **points**. A point has
80
+ a `type`, a `key` (`"0"` unless a node holds several of a type), a `value`, and
81
+ a `time`. The edge from a node to its parent carries its own points, such as
82
+ `tombstone` for a deleted node. See the
83
+ [data reference](https://docs.simpleiot.org/docs/ref/data.html).
84
+
85
+ `Point.value` sets the encoding when sending:
86
+
87
+ | Value | Sent as |
88
+ | ---------------------- | --------------------- |
89
+ | `float`, `int`, `bool` | a float point |
90
+ | `str` | a string point |
91
+ | `dict`, `list` | a JSON point |
92
+ | `None` | a point with no value |
93
+
94
+ Pass `data_type=DataType.INT` to send an integer as an int point. A received
95
+ point's `value` is a `float`, `int`, or `str` by its data type; `number` and
96
+ `text` read it as a number or string either way.
97
+
98
+ ## API
99
+
100
+ All methods are coroutines on `Client`.
101
+
102
+ - `get_root()`, `get_node(id, parent="all")`, `get_children(parent, type=...)`
103
+ - `get_nodes(parent, id="all", type=..., include_deleted=..., depth=...)`, the
104
+ `nodes.<parent>.<id>` request
105
+ - `search(below, query, limit=..., type=...)`
106
+ - `send_points(id, points)`, `send_point(id, type, value, key="0")`
107
+ - `send_edge_points(id, parent, points)`
108
+ - `create_node(parent, type, points, id=..., description=..., primary=...)`
109
+ - `delete_node(id, parent)`, `move_node(id, old_parent, new_parent)`
110
+ - `provision(name, yaml)` uploads a node file for the server to apply, as
111
+ `siot import` would, and waits until it has
112
+ - `subscribe_node(id)`, `subscribe_tree(id)`, `subscribe(subject)`: async
113
+ iterators of `PointsMessage`
114
+ - `close()`
115
+
116
+ A server error raises `SiotError`; a missing node raises `NotFoundError`.
117
+
118
+ ## Examples
119
+
120
+ Each example is a short script in its own directory with a README:
121
+
122
+ - [tree](https://github.com/simpleiot/simpleiot/tree/master/python/examples/tree)
123
+ prints the node tree
124
+ - [send_points](https://github.com/simpleiot/simpleiot/tree/master/python/examples/send_points)
125
+ creates a node and writes a value to it once a second
126
+ - [watch](https://github.com/simpleiot/simpleiot/tree/master/python/examples/watch)
127
+ prints every point change below a node
128
+ - [mirror_temperature](https://github.com/simpleiot/simpleiot/tree/master/python/examples/mirror_temperature)
129
+ reacts to one point by writing another
130
+ - [rover](https://github.com/simpleiot/simpleiot/tree/master/python/examples/rover)
131
+ drives a simulated autonomous rover from a dashboard, with a live map, status,
132
+ and commands
133
+
134
+ Run them against a local instance:
135
+
136
+ ```
137
+ SIOT_AUTH_TOKEN=... python examples/tree/tree.py
138
+ ```
139
+
140
+ ## Development
141
+
142
+ The client lives in the
143
+ [Simple IoT repository](https://github.com/simpleiot/simpleiot) under `python/`,
144
+ so it changes together with the server.
145
+
146
+ ```
147
+ cd python
148
+ uv sync
149
+ uv run pytest
150
+ ```
151
+
152
+ The tests need [uv](https://docs.astral.sh/uv/). The codec tests check the
153
+ encoder against the fixtures `data/point_fixture_test.go` writes, the same ones
154
+ the JavaScript client is checked against. The integration tests start a scratch
155
+ `siot` when `SIOT_BIN` names one; `siot_test_python` in `envsetup.sh` builds it
156
+ and runs them.
157
+
158
+ To publish a release, set the version in `python/src/simpleiot/__init__.py`, add
159
+ a `python/CHANGELOG.md` entry, and push a `py-v<version>` tag. The
160
+ `Python release` workflow builds the package and publishes it to PyPI.
@@ -0,0 +1,9 @@
1
+ simpleiot/__init__.py,sha256=9Z0epZ2L_yi58ulfLyK2zavq7XWpkov2GLfCKMdrx0c,869
2
+ simpleiot/client.py,sha256=uUt7AbIecd03V9EZ73m8s_vx-qN-g3H7EdV4lLb08Dg,16097
3
+ simpleiot/codec.py,sha256=0LHLHA5jzO-BuiA9Hq1YnkxSBFSWLJlTlvZpLrSxKyo,10986
4
+ simpleiot/ids.py,sha256=tmxhTaB6NIksO_b7SyOXTAilDcDUCUN-zOCm6uHSSiM,876
5
+ simpleiot/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ simpleiot-0.1.0.dist-info/METADATA,sha256=HjHKSr9RNhLhywh0yDSThkphY7Eh8b0K9NpdowAPryc,5813
7
+ simpleiot-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
8
+ simpleiot-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ simpleiot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.