iosignal 0.1.0__tar.gz

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.
Files changed (49) hide show
  1. iosignal-0.1.0/.gitignore +8 -0
  2. iosignal-0.1.0/LICENSE +21 -0
  3. iosignal-0.1.0/PKG-INFO +180 -0
  4. iosignal-0.1.0/README.ko.md +157 -0
  5. iosignal-0.1.0/README.md +157 -0
  6. iosignal-0.1.0/examples/board_light.py +20 -0
  7. iosignal-0.1.0/examples/board_relay_buttons.py +56 -0
  8. iosignal-0.1.0/examples/virtual_home.py +123 -0
  9. iosignal-0.1.0/examples/virtual_lamp.py +59 -0
  10. iosignal-0.1.0/package.json +46 -0
  11. iosignal-0.1.0/pyproject.toml +39 -0
  12. iosignal-0.1.0/src/iosignal/__init__.py +19 -0
  13. iosignal-0.1.0/src/iosignal/board.py +154 -0
  14. iosignal-0.1.0/src/iosignal/boho.py +340 -0
  15. iosignal-0.1.0/src/iosignal/client.py +850 -0
  16. iosignal-0.1.0/src/iosignal/cong.py +79 -0
  17. iosignal-0.1.0/src/iosignal/devices.py +416 -0
  18. iosignal-0.1.0/src/iosignal/mbp.py +295 -0
  19. iosignal-0.1.0/src/iosignal/mclient.py +361 -0
  20. iosignal-0.1.0/src/iosignal/mdevice.py +200 -0
  21. iosignal-0.1.0/src/iosignal/protocol.py +267 -0
  22. iosignal-0.1.0/src/iosignal/replcli.py +426 -0
  23. iosignal-0.1.0/src/iosignal/replhost.py +319 -0
  24. iosignal-0.1.0/src/iosignal/replpoll.py +736 -0
  25. iosignal-0.1.0/src/iosignal/replproto.py +76 -0
  26. iosignal-0.1.0/src/iosignal/sync.py +241 -0
  27. iosignal-0.1.0/src/iosignal/x25519.py +90 -0
  28. iosignal-0.1.0/tests/_path.py +7 -0
  29. iosignal-0.1.0/tests/fixtures/device-rules.json +370 -0
  30. iosignal-0.1.0/tests/fixtures/js-vectors.json +472 -0
  31. iosignal-0.1.0/tests/fixtures/x25519-vectors.json +50 -0
  32. iosignal-0.1.0/tests/mpy_board_check.py +64 -0
  33. iosignal-0.1.0/tests/mpy_mdevice.py +92 -0
  34. iosignal-0.1.0/tests/mpy_vectors.py +133 -0
  35. iosignal-0.1.0/tests/mpy_x25519.py +46 -0
  36. iosignal-0.1.0/tests/test_boho.py +203 -0
  37. iosignal-0.1.0/tests/test_client.py +443 -0
  38. iosignal-0.1.0/tests/test_devices.py +227 -0
  39. iosignal-0.1.0/tests/test_js_vectors.py +54 -0
  40. iosignal-0.1.0/tests/test_mbp.py +124 -0
  41. iosignal-0.1.0/tests/test_mdevice.py +40 -0
  42. iosignal-0.1.0/tests/test_package.py +24 -0
  43. iosignal-0.1.0/tests/test_protocol.py +97 -0
  44. iosignal-0.1.0/tests/test_sync.py +110 -0
  45. iosignal-0.1.0/tests/test_x25519.py +21 -0
  46. iosignal-0.1.0/tools/build_web_pkg.py +58 -0
  47. iosignal-0.1.0/tools/mpy_board_setup.py +100 -0
  48. iosignal-0.1.0/tools/mpy_repl_key.py +45 -0
  49. iosignal-0.1.0/tools/mpy_wifi_setup.py +63 -0
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .DS_Store
8
+ *.key
iosignal-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Taeo Lee <sixgen@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,180 @@
1
+ Metadata-Version: 2.5
2
+ Name: iosignal
3
+ Version: 0.1.0
4
+ Summary: IOSignal client for Python: signals, device rules, and remote MicroPython boards
5
+ Project-URL: Homepage, https://iosignal.net
6
+ Project-URL: Documentation, https://docs.iosignal.net
7
+ Project-URL: Repository, https://github.com/remocons/iosignal-python
8
+ Author-email: Taeo Lee <sixgen@gmail.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: esp32,iosignal,iot,micropython,pubsub,websocket
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Framework :: AsyncIO
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: Implementation :: MicroPython
18
+ Classifier: Topic :: Home Automation
19
+ Classifier: Topic :: Internet
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: websockets>=13
22
+ Description-Content-Type: text/markdown
23
+
24
+ # iosignal (Python)
25
+
26
+ [English](README.md) | [한국어](README.ko.md)
27
+
28
+ Python client for [IOSignal](https://iosignal.net), a real-time signal broker for web apps, devices and boards.
29
+ The same package runs on CPython 3.10+ (asyncio or blocking) and on MicroPython boards (ESP32, ESP32-C3, ESP32-S3).
30
+
31
+ - Signals, subscriptions, RPC calls and server ping, byte-compatible with the [JS client](https://github.com/remocons/iosignal)
32
+ - Boho login with ENC_488 encryption, end-to-end sealed signals
33
+ - WebSocket (`ws://`, `wss://`) and TCP (`cong://`, the same link Arduino boards use)
34
+ - [Device rules](https://docs.iosignal.net/docs/devices/types): make devices that appear in IOSignal apps, find and command them
35
+ - MicroPython: a board becomes a device, and a sealed remote REPL with file transfer (`iosignal-repl`)
36
+
37
+ ## Install
38
+
39
+ ```sh
40
+ pip install iosignal
41
+ ```
42
+
43
+ The only dependency is `websockets`.
44
+
45
+ ## Blocking (scripts)
46
+
47
+ ```python
48
+ from iosignal.sync import IOSignal
49
+
50
+ with IOSignal("wss://io.iosignal.net/ws") as io:
51
+ io.ready() # returns the CID
52
+ inbox = io.listen("room#t") # without a handler: a queue.Queue
53
+ io.signal("room#t", "hello")
54
+ print(inbox.get(timeout=3).text)
55
+ print(io.ping_server(), "ms")
56
+ ```
57
+
58
+ Handlers run on a background thread. They may send (`signal()` and so on), but not wait (`ready()`, `call()`).
59
+
60
+ ## asyncio
61
+
62
+ ```python
63
+ import asyncio
64
+ from iosignal import IOSignal
65
+
66
+ async def main():
67
+ io = IOSignal("wss://io.iosignal.net/ws")
68
+ io.auth("dev1", "key") # or io.auth("dev1.key"); anonymous without it
69
+ io.listen("room#t", lambda s: print(s.tag, s.args))
70
+ io.on_event("state", print)
71
+ async with io:
72
+ await io.ready()
73
+ io.signal("room#t", "value", b"\x01")
74
+ print(await io.ping_server(), "ms")
75
+ await asyncio.sleep(10)
76
+
77
+ asyncio.run(main())
78
+ ```
79
+
80
+ - Sending (`signal`, `subscribe`, `unsubscribe`, `iam`) is synchronous and returns False without a connection.
81
+ - Handlers are functions or coroutines and receive a `Signal` (`tag`, `type`, `data`, `text`, `args`, `is_direct`).
82
+ - Events: `state`, `ready`, `message`, `direct`, `server_signal`, `iam`, `pong`, `over_size`, `error`.
83
+ - Subscriptions are remembered and sent again after a reconnect. A logged-in `ws://` connection is encrypted with ENC_488.
84
+ - `await io.call(target, topic, *args)` calls a server service (`RpcError` on failure).
85
+ - `await io.ping_server(timeout=3.0)` returns the round trip in milliseconds. It raises `PingError` with `code` `NOT_READY`, `BUSY` (one at a time), `TIMEOUT`, `CONNECTION_CLOSED` or `INVALID_ARGUMENT`.
86
+
87
+ ### Values and payload types (as JS `signal()`)
88
+
89
+ | `signal(tag, ...)` | type | receiver `args` |
90
+ |---|---|---|
91
+ | nothing | EMPTY | `[]` |
92
+ | `"text"`, `42`, `3.5` | TEXT | `["text"]`, `["42"]` |
93
+ | `b"..."` | BINARY | `[b"..."]` |
94
+ | `{...}`, `[...]`, `None` | OBJECT | `[value]` |
95
+ | several values, no bytes | MJSON | `[value, ...]` |
96
+ | several values with bytes | MBA | `[value, ...]` |
97
+
98
+ ## TCP and E2E signals
99
+
100
+ - A `cong://host:port` address connects over TCP. Logged in, it is encrypted with ENC_488, and a TCP switcher redirect is followed: `IOSignal("cong://io.iosignal.net:55488")`.
101
+ - `io.signal_e2e(tag, data, key)` seals data with a key the server never sees (logged-in connections only). A received `Signal` with `e2e` True opens with `io.decrypt_e2e(sig.data, key)` (None for a wrong key or a forgery).
102
+
103
+ ## Devices
104
+
105
+ ```python
106
+ from iosignal.sync import IOSignal
107
+
108
+ with IOSignal("wss://io.iosignal.net/ws") as io:
109
+ lamp = io.device("Python lamp:Living room", type="dimmer.1", state={"on": "0", "level": "60"})
110
+ io.ready()
111
+ io.run(lambda: lamp.set(level=80)) # change device state on the client's thread
112
+
113
+ for d in io.discover(): # devices on the same home channel (same public IP)
114
+ print(d.id, d.name, d.category, d.ui.type, d.fields)
115
+ io.command(d, "toggle")
116
+ ```
117
+
118
+ A `Device` answers `#search`, announces `$panel`, `$view`, `$name`, `$ui`, `$state` and `#notify` in that order, and answers every command with `$state`. `on_command(cmd, device)` returning True means it handled the command; otherwise the standard commands apply (`on`, `off`, `toggle`, `all=`, `key=value`). Examples: [examples/virtual_lamp.py](examples/virtual_lamp.py), [examples/virtual_home.py](examples/virtual_home.py) (five devices, `--minutes` to stop).
119
+
120
+ ## MicroPython boards
121
+
122
+ ### Install on a board
123
+
124
+ With network on the board (MicroPython 1.28+):
125
+
126
+ ```python
127
+ import mip
128
+ mip.install("github:remocons/iosignal-python")
129
+ ```
130
+
131
+ or from a computer: `mpremote mip install github:remocons/iosignal-python`. [tools/mpy_board_setup.py](tools/mpy_board_setup.py) installs precompiled `.mpy` files over USB with the board configuration, and [tools/mpy_wifi_setup.py](tools/mpy_wifi_setup.py) writes the Wi-Fi settings.
132
+
133
+ ### The board as a device
134
+
135
+ ```python
136
+ import iosignal.board
137
+ from machine import Pin
138
+
139
+ iosignal.board.start()
140
+ led = Pin(2, Pin.OUT)
141
+ lamp = iosignal.board.device(type="light.1", state="on=0",
142
+ on_change=lambda d: led.value(d.get("on") == "1"))
143
+ lamp.set(on="1") # changes from your own code show in the apps at once
144
+ ```
145
+
146
+ - One board is one CID and one device. Options: `name`, `type`, `state` (`"on=0;level=50"`, key order kept), `buttons`, `panel`, `view`, `on_command(cmd, device)`, `on_change(device)`.
147
+ - Callbacks run in the link's timer: keep them short. Their errors go to `board.status()` and the link keeps running.
148
+ - Other devices: `board.subscribe("abc-123@$state", fn)` and `board.signal("abc-123@", "r1=1")`. Example: [examples/board_relay_buttons.py](examples/board_relay_buttons.py).
149
+ - Without code: a `"device"` entry in `/iosignal.json`, for example `{"type": "relay4.1", "pins": [16, 17, 18, 19], "invert": true}`, makes a pin device (light.1, dimmer.1 PWM, relay4.1, switch2.1~8.1).
150
+
151
+ ### Remote REPL: `iosignal-repl`
152
+
153
+ A board with a REPL key can be used like `mpremote` from anywhere, through IOSignal. Sessions are sealed with the REPL key and one-time X25519 keys (forward secrecy), so the broker relays only sealed bytes.
154
+
155
+ ```sh
156
+ export REPL_KEY_FILE=~/.iosignal/repl-myboard.key # or -k FILE
157
+ iosignal-repl find # boards on the same network
158
+ iosignal-repl repl # interactive (Ctrl-] leaves, Ctrl-C goes to the board)
159
+ iosignal-repl exec "print(1+1)" # streamed output, exit code 1 on an exception
160
+ iosignal-repl run app.py # run a local file without copying it
161
+ iosignal-repl ls / | cat /main.py | get /log.txt | put main.py | rm /x | mkdir /d | rmdir /d | mv /a /b
162
+ iosignal-repl info | reset
163
+ ```
164
+
165
+ Server: `-s` or `IOSIGNAL_SERVER` (default `wss://io.iosignal.net/ws`). Board: `-b` or `IOSIGNAL_BOARD`; without it, the only board on the network. Make a REPL key with [tools/mpy_repl_key.py](tools/mpy_repl_key.py).
166
+
167
+ ## Not supported
168
+
169
+ JS `echo` and `link`.
170
+
171
+ ## Tests
172
+
173
+ ```sh
174
+ python3 -m unittest discover -s tests # no server needed
175
+ micropython tests/mpy_vectors.py # byte layer on the MicroPython unix port
176
+ ```
177
+
178
+ ## License
179
+
180
+ MIT
@@ -0,0 +1,157 @@
1
+ # iosignal (Python)
2
+
3
+ [English](README.md) | [한국어](README.ko.md)
4
+
5
+ 웹 앱, 장치, 보드를 잇는 실시간 시그널 브로커 [IOSignal](https://iosignal.net)의 Python 클라이언트입니다.
6
+ 같은 패키지가 CPython 3.10 이상(asyncio 또는 동기)과 MicroPython 보드(ESP32, ESP32-C3, ESP32-S3)에서 돕니다.
7
+
8
+ - 시그널, 구독, RPC 호출, 서버 ping. [JS 클라이언트](https://github.com/remocons/iosignal)와 바이트 단위로 같음
9
+ - Boho 로그인과 ENC_488 암호화, 종단 간(E2E) 봉한 시그널
10
+ - WebSocket(`ws://`, `wss://`)과 TCP(`cong://`, 아두이노 보드와 같은 연결)
11
+ - [장치 규칙](https://docs.iosignal.net/docs/devices/types): IOSignal 앱에 나타나는 장치 만들기, 찾기, 명령 보내기
12
+ - MicroPython: 보드를 장치로, 봉한 원격 REPL과 파일 전송(`iosignal-repl`)
13
+
14
+ ## 설치
15
+
16
+ ```sh
17
+ pip install iosignal
18
+ ```
19
+
20
+ 의존성은 `websockets` 하나입니다.
21
+
22
+ ## 동기 (스크립트)
23
+
24
+ ```python
25
+ from iosignal.sync import IOSignal
26
+
27
+ with IOSignal("wss://io.iosignal.net/ws") as io:
28
+ io.ready() # CID를 돌려줌
29
+ inbox = io.listen("room#t") # 핸들러를 안 주면 queue.Queue
30
+ io.signal("room#t", "안녕")
31
+ print(inbox.get(timeout=3).text)
32
+ print(io.ping_server(), "ms")
33
+ ```
34
+
35
+ 핸들러는 백그라운드 스레드에서 돕니다. 핸들러 안에서 `signal()` 등은 부를 수 있지만 `ready()`, `call()`처럼 기다리는 것은 부르지 않습니다.
36
+
37
+ ## asyncio
38
+
39
+ ```python
40
+ import asyncio
41
+ from iosignal import IOSignal
42
+
43
+ async def main():
44
+ io = IOSignal("wss://io.iosignal.net/ws")
45
+ io.auth("dev1", "key") # 또는 io.auth("dev1.key"), 생략하면 익명
46
+ io.listen("room#t", lambda s: print(s.tag, s.args))
47
+ io.on_event("state", print)
48
+ async with io:
49
+ await io.ready()
50
+ io.signal("room#t", "값", b"\x01")
51
+ print(await io.ping_server(), "ms")
52
+ await asyncio.sleep(10)
53
+
54
+ asyncio.run(main())
55
+ ```
56
+
57
+ - 보내기(`signal`, `subscribe`, `unsubscribe`, `iam`)는 동기이며 연결이 없으면 False입니다.
58
+ - 핸들러는 함수나 코루틴이고 `Signal`(`tag`, `type`, `data`, `text`, `args`, `is_direct`)을 받습니다.
59
+ - 이벤트: `state`, `ready`, `message`, `direct`, `server_signal`, `iam`, `pong`, `over_size`, `error`.
60
+ - 구독은 기억했다가 재접속 때 다시 보냅니다. 로그인한 `ws://` 연결은 ENC_488로 암호화합니다.
61
+ - `await io.call(target, topic, *args)`는 서버 서비스를 부릅니다(실패하면 `RpcError`).
62
+ - `await io.ping_server(timeout=3.0)`은 서버 왕복 시간을 밀리초로 돌려줍니다. 실패하면 `PingError`, `code`는 `NOT_READY`, `BUSY`(한 번에 하나), `TIMEOUT`, `CONNECTION_CLOSED`, `INVALID_ARGUMENT`.
63
+
64
+ ### 보내는 값과 페이로드 형식 (JS `signal()`과 같음)
65
+
66
+ | `signal(tag, ...)` | 형식 | 받는 쪽 `args` |
67
+ |---|---|---|
68
+ | 없음 | EMPTY | `[]` |
69
+ | `"글자"`, `42`, `3.5` | TEXT | `["글자"]`, `["42"]` |
70
+ | `b"..."` | BINARY | `[b"..."]` |
71
+ | `{...}`, `[...]`, `None` | OBJECT | `[값]` |
72
+ | 값 여러 개, bytes 없음 | MJSON | `[값, ...]` |
73
+ | 값 여러 개, bytes 있음 | MBA | `[값, ...]` |
74
+
75
+ ## TCP와 E2E 시그널
76
+
77
+ - 주소가 `cong://host:port`면 TCP로 붙습니다. 로그인하면 ENC_488로 암호화하고, TCP 스위처의 redirect도 따라갑니다: `IOSignal("cong://io.iosignal.net:55488")`.
78
+ - `io.signal_e2e(tag, data, key)`는 서버가 모르는 키로 봉해 보냅니다(로그인한 연결에서만). 받은 `Signal.e2e`가 True면 `io.decrypt_e2e(sig.data, key)`로 엽니다(다른 키나 위조면 None).
79
+
80
+ ## 장치
81
+
82
+ ```python
83
+ from iosignal.sync import IOSignal
84
+
85
+ with IOSignal("wss://io.iosignal.net/ws") as io:
86
+ lamp = io.device("파이썬 전등:거실", type="dimmer.1", state={"on": "0", "level": "60"})
87
+ io.ready()
88
+ io.run(lambda: lamp.set(level=80)) # 장치 상태는 클라이언트 스레드에서 바꿈
89
+
90
+ for d in io.discover(): # 같은 홈채널(같은 공인 IP)의 장치
91
+ print(d.id, d.name, d.category, d.ui.type, d.fields)
92
+ io.command(d, "toggle")
93
+ ```
94
+
95
+ `Device`는 `#search`에 답하고 `$panel`·`$view`·`$name`·`$ui`·`$state`·`#notify` 순서로 알리며, 명령마다 `$state`로 답합니다. `on_command(cmd, device)`가 True를 돌려주면 직접 처리한 것이고, 아니면 표준 처리(`on`, `off`, `toggle`, `all=`, `key=value`)를 합니다. 예: [examples/virtual_lamp.py](examples/virtual_lamp.py), [examples/virtual_home.py](examples/virtual_home.py)(장치 다섯 개, `--minutes`로 멈출 시간).
96
+
97
+ ## MicroPython 보드
98
+
99
+ ### 보드에 설치
100
+
101
+ 보드가 네트워크에 붙어 있으면(MicroPython 1.28 이상):
102
+
103
+ ```python
104
+ import mip
105
+ mip.install("github:remocons/iosignal-python")
106
+ ```
107
+
108
+ 컴퓨터에서는 `mpremote mip install github:remocons/iosignal-python`. [tools/mpy_board_setup.py](tools/mpy_board_setup.py)는 USB로 미리 컴파일한 `.mpy`와 보드 설정을 넣고, [tools/mpy_wifi_setup.py](tools/mpy_wifi_setup.py)는 Wi-Fi 설정을 씁니다.
109
+
110
+ ### 보드를 장치로
111
+
112
+ ```python
113
+ import iosignal.board
114
+ from machine import Pin
115
+
116
+ iosignal.board.start()
117
+ led = Pin(2, Pin.OUT)
118
+ lamp = iosignal.board.device(type="light.1", state="on=0",
119
+ on_change=lambda d: led.value(d.get("on") == "1"))
120
+ lamp.set(on="1") # 내 코드에서 바꿔도 앱에 바로 보임
121
+ ```
122
+
123
+ - 보드 하나가 CID 하나, 장치 하나입니다. 옵션: `name`, `type`, `state`(`"on=0;level=50"`, 키 순서 유지), `buttons`, `panel`, `view`, `on_command(cmd, device)`, `on_change(device)`.
124
+ - 콜백은 링크의 타이머 안에서 돌므로 짧게 씁니다. 콜백 오류는 `board.status()`에 남고 링크는 계속 돕니다.
125
+ - 다른 장치: `board.subscribe("abc-123@$state", fn)`, `board.signal("abc-123@", "r1=1")`. 예: [examples/board_relay_buttons.py](examples/board_relay_buttons.py).
126
+ - 코드 없이: `/iosignal.json`에 `"device"` 항목(예: `{"type": "relay4.1", "pins": [16, 17, 18, 19], "invert": true}`)을 두면 핀 장치가 됩니다(light.1, dimmer.1 PWM, relay4.1, switch2.1~8.1).
127
+
128
+ ### 원격 REPL `iosignal-repl`
129
+
130
+ REPL 키가 있는 보드는 어디서나 IOSignal을 거쳐 `mpremote`처럼 다룰 수 있습니다. 세션은 REPL 키와 일회용 X25519 키로 봉하므로(forward secrecy) 브로커는 봉한 바이트만 전달합니다.
131
+
132
+ ```sh
133
+ export REPL_KEY_FILE=~/.iosignal/repl-myboard.key # 또는 -k FILE
134
+ iosignal-repl find # 같은 네트워크의 보드
135
+ iosignal-repl repl # 대화형 (Ctrl-] 나가기, Ctrl-C는 보드로)
136
+ iosignal-repl exec "print(1+1)" # 출력이 오는 대로, 예외면 종료 코드 1
137
+ iosignal-repl run app.py # 로컬 파일을 복사하지 않고 실행
138
+ iosignal-repl ls / | cat /main.py | get /log.txt | put main.py | rm /x | mkdir /d | rmdir /d | mv /a /b
139
+ iosignal-repl info | reset
140
+ ```
141
+
142
+ 서버는 `-s` 또는 `IOSIGNAL_SERVER`(기본 `wss://io.iosignal.net/ws`), 보드는 `-b` 또는 `IOSIGNAL_BOARD`이고, 안 주면 같은 네트워크에 하나뿐인 보드를 씁니다. REPL 키는 [tools/mpy_repl_key.py](tools/mpy_repl_key.py)로 만듭니다.
143
+
144
+ ## 지원하지 않는 것
145
+
146
+ JS의 `echo`, `link`.
147
+
148
+ ## 시험
149
+
150
+ ```sh
151
+ python3 -m unittest discover -s tests # 서버 없이
152
+ micropython tests/mpy_vectors.py # MicroPython unix 포트에서 바이트 계층
153
+ ```
154
+
155
+ ## 라이선스
156
+
157
+ MIT
@@ -0,0 +1,157 @@
1
+ # iosignal (Python)
2
+
3
+ [English](README.md) | [한국어](README.ko.md)
4
+
5
+ Python client for [IOSignal](https://iosignal.net), a real-time signal broker for web apps, devices and boards.
6
+ The same package runs on CPython 3.10+ (asyncio or blocking) and on MicroPython boards (ESP32, ESP32-C3, ESP32-S3).
7
+
8
+ - Signals, subscriptions, RPC calls and server ping, byte-compatible with the [JS client](https://github.com/remocons/iosignal)
9
+ - Boho login with ENC_488 encryption, end-to-end sealed signals
10
+ - WebSocket (`ws://`, `wss://`) and TCP (`cong://`, the same link Arduino boards use)
11
+ - [Device rules](https://docs.iosignal.net/docs/devices/types): make devices that appear in IOSignal apps, find and command them
12
+ - MicroPython: a board becomes a device, and a sealed remote REPL with file transfer (`iosignal-repl`)
13
+
14
+ ## Install
15
+
16
+ ```sh
17
+ pip install iosignal
18
+ ```
19
+
20
+ The only dependency is `websockets`.
21
+
22
+ ## Blocking (scripts)
23
+
24
+ ```python
25
+ from iosignal.sync import IOSignal
26
+
27
+ with IOSignal("wss://io.iosignal.net/ws") as io:
28
+ io.ready() # returns the CID
29
+ inbox = io.listen("room#t") # without a handler: a queue.Queue
30
+ io.signal("room#t", "hello")
31
+ print(inbox.get(timeout=3).text)
32
+ print(io.ping_server(), "ms")
33
+ ```
34
+
35
+ Handlers run on a background thread. They may send (`signal()` and so on), but not wait (`ready()`, `call()`).
36
+
37
+ ## asyncio
38
+
39
+ ```python
40
+ import asyncio
41
+ from iosignal import IOSignal
42
+
43
+ async def main():
44
+ io = IOSignal("wss://io.iosignal.net/ws")
45
+ io.auth("dev1", "key") # or io.auth("dev1.key"); anonymous without it
46
+ io.listen("room#t", lambda s: print(s.tag, s.args))
47
+ io.on_event("state", print)
48
+ async with io:
49
+ await io.ready()
50
+ io.signal("room#t", "value", b"\x01")
51
+ print(await io.ping_server(), "ms")
52
+ await asyncio.sleep(10)
53
+
54
+ asyncio.run(main())
55
+ ```
56
+
57
+ - Sending (`signal`, `subscribe`, `unsubscribe`, `iam`) is synchronous and returns False without a connection.
58
+ - Handlers are functions or coroutines and receive a `Signal` (`tag`, `type`, `data`, `text`, `args`, `is_direct`).
59
+ - Events: `state`, `ready`, `message`, `direct`, `server_signal`, `iam`, `pong`, `over_size`, `error`.
60
+ - Subscriptions are remembered and sent again after a reconnect. A logged-in `ws://` connection is encrypted with ENC_488.
61
+ - `await io.call(target, topic, *args)` calls a server service (`RpcError` on failure).
62
+ - `await io.ping_server(timeout=3.0)` returns the round trip in milliseconds. It raises `PingError` with `code` `NOT_READY`, `BUSY` (one at a time), `TIMEOUT`, `CONNECTION_CLOSED` or `INVALID_ARGUMENT`.
63
+
64
+ ### Values and payload types (as JS `signal()`)
65
+
66
+ | `signal(tag, ...)` | type | receiver `args` |
67
+ |---|---|---|
68
+ | nothing | EMPTY | `[]` |
69
+ | `"text"`, `42`, `3.5` | TEXT | `["text"]`, `["42"]` |
70
+ | `b"..."` | BINARY | `[b"..."]` |
71
+ | `{...}`, `[...]`, `None` | OBJECT | `[value]` |
72
+ | several values, no bytes | MJSON | `[value, ...]` |
73
+ | several values with bytes | MBA | `[value, ...]` |
74
+
75
+ ## TCP and E2E signals
76
+
77
+ - A `cong://host:port` address connects over TCP. Logged in, it is encrypted with ENC_488, and a TCP switcher redirect is followed: `IOSignal("cong://io.iosignal.net:55488")`.
78
+ - `io.signal_e2e(tag, data, key)` seals data with a key the server never sees (logged-in connections only). A received `Signal` with `e2e` True opens with `io.decrypt_e2e(sig.data, key)` (None for a wrong key or a forgery).
79
+
80
+ ## Devices
81
+
82
+ ```python
83
+ from iosignal.sync import IOSignal
84
+
85
+ with IOSignal("wss://io.iosignal.net/ws") as io:
86
+ lamp = io.device("Python lamp:Living room", type="dimmer.1", state={"on": "0", "level": "60"})
87
+ io.ready()
88
+ io.run(lambda: lamp.set(level=80)) # change device state on the client's thread
89
+
90
+ for d in io.discover(): # devices on the same home channel (same public IP)
91
+ print(d.id, d.name, d.category, d.ui.type, d.fields)
92
+ io.command(d, "toggle")
93
+ ```
94
+
95
+ A `Device` answers `#search`, announces `$panel`, `$view`, `$name`, `$ui`, `$state` and `#notify` in that order, and answers every command with `$state`. `on_command(cmd, device)` returning True means it handled the command; otherwise the standard commands apply (`on`, `off`, `toggle`, `all=`, `key=value`). Examples: [examples/virtual_lamp.py](examples/virtual_lamp.py), [examples/virtual_home.py](examples/virtual_home.py) (five devices, `--minutes` to stop).
96
+
97
+ ## MicroPython boards
98
+
99
+ ### Install on a board
100
+
101
+ With network on the board (MicroPython 1.28+):
102
+
103
+ ```python
104
+ import mip
105
+ mip.install("github:remocons/iosignal-python")
106
+ ```
107
+
108
+ or from a computer: `mpremote mip install github:remocons/iosignal-python`. [tools/mpy_board_setup.py](tools/mpy_board_setup.py) installs precompiled `.mpy` files over USB with the board configuration, and [tools/mpy_wifi_setup.py](tools/mpy_wifi_setup.py) writes the Wi-Fi settings.
109
+
110
+ ### The board as a device
111
+
112
+ ```python
113
+ import iosignal.board
114
+ from machine import Pin
115
+
116
+ iosignal.board.start()
117
+ led = Pin(2, Pin.OUT)
118
+ lamp = iosignal.board.device(type="light.1", state="on=0",
119
+ on_change=lambda d: led.value(d.get("on") == "1"))
120
+ lamp.set(on="1") # changes from your own code show in the apps at once
121
+ ```
122
+
123
+ - One board is one CID and one device. Options: `name`, `type`, `state` (`"on=0;level=50"`, key order kept), `buttons`, `panel`, `view`, `on_command(cmd, device)`, `on_change(device)`.
124
+ - Callbacks run in the link's timer: keep them short. Their errors go to `board.status()` and the link keeps running.
125
+ - Other devices: `board.subscribe("abc-123@$state", fn)` and `board.signal("abc-123@", "r1=1")`. Example: [examples/board_relay_buttons.py](examples/board_relay_buttons.py).
126
+ - Without code: a `"device"` entry in `/iosignal.json`, for example `{"type": "relay4.1", "pins": [16, 17, 18, 19], "invert": true}`, makes a pin device (light.1, dimmer.1 PWM, relay4.1, switch2.1~8.1).
127
+
128
+ ### Remote REPL: `iosignal-repl`
129
+
130
+ A board with a REPL key can be used like `mpremote` from anywhere, through IOSignal. Sessions are sealed with the REPL key and one-time X25519 keys (forward secrecy), so the broker relays only sealed bytes.
131
+
132
+ ```sh
133
+ export REPL_KEY_FILE=~/.iosignal/repl-myboard.key # or -k FILE
134
+ iosignal-repl find # boards on the same network
135
+ iosignal-repl repl # interactive (Ctrl-] leaves, Ctrl-C goes to the board)
136
+ iosignal-repl exec "print(1+1)" # streamed output, exit code 1 on an exception
137
+ iosignal-repl run app.py # run a local file without copying it
138
+ iosignal-repl ls / | cat /main.py | get /log.txt | put main.py | rm /x | mkdir /d | rmdir /d | mv /a /b
139
+ iosignal-repl info | reset
140
+ ```
141
+
142
+ Server: `-s` or `IOSIGNAL_SERVER` (default `wss://io.iosignal.net/ws`). Board: `-b` or `IOSIGNAL_BOARD`; without it, the only board on the network. Make a REPL key with [tools/mpy_repl_key.py](tools/mpy_repl_key.py).
143
+
144
+ ## Not supported
145
+
146
+ JS `echo` and `link`.
147
+
148
+ ## Tests
149
+
150
+ ```sh
151
+ python3 -m unittest discover -s tests # no server needed
152
+ micropython tests/mpy_vectors.py # byte layer on the MicroPython unix port
153
+ ```
154
+
155
+ ## License
156
+
157
+ MIT
@@ -0,0 +1,20 @@
1
+ # main.py for a MicroPython board: the board starts its IOSignal link and becomes a light.1 device.
2
+ # Copy it to the board as /main.py (web IDE, iosignal-repl put, or mpremote). The LED is GPIO 2 on most
3
+ # ESP32 DevKit boards. In apps (remocon.kr, IOSignal Desktop) it shows as a light with on/off; the web IDE
4
+ # still finds the board ($ui t=light.1;r=1).
5
+ import iosignal.board
6
+ from machine import Pin
7
+
8
+ iosignal.board.start()
9
+
10
+ led = Pin(2, Pin.OUT)
11
+
12
+
13
+ def changed(d):
14
+ led.value(d.get("on") == "1") # runs in the link's timer: keep it short
15
+
16
+
17
+ lamp = iosignal.board.device(type="light.1", state="on=0", on_change=changed)
18
+
19
+ # Your own code can change the state too; apps see it at once:
20
+ # lamp.set(on="1")
@@ -0,0 +1,56 @@
1
+ # main.py for a board (made on an ESP32-C3): buttons on GPIO 0 and 1 toggle r1 and r2 of a relay4.1
2
+ # device (set TARGET to its CID). Copy it to the board as /main.py (web IDE, or iosignal-repl put).
3
+ #
4
+ # Wiring: each button connects its pin to GND when pressed (the internal pull-up keeps it high otherwise).
5
+ # As the device rules ask of a controller, the board follows the relay's $state and sends no toggle before it
6
+ # knows the state: a press sends "r1=1" or "r1=0" (the opposite of the last state) to <relay>@.
7
+ # The buttons use pin interrupts, so main.py returns at once and the REPL (USB and remote) stays free.
8
+ import time
9
+
10
+ import iosignal.board as board
11
+ from machine import Pin
12
+
13
+ board.start()
14
+
15
+ TARGET = "abc-123" # the relay4.1 device's CID (shown on its card in the apps)
16
+ BUTTONS = {0: "r1", 1: "r2"} # GPIO -> relay channel key
17
+ DEBOUNCE_MS = 200
18
+
19
+ state = {} # the relay's last $state, e.g. {"r1": "0", "r2": "1", "r3": "0", "r4": "0"}; {} while unknown
20
+ last_press = {}
21
+ pins = {}
22
+
23
+
24
+ def on_state(tag, text):
25
+ state.clear()
26
+ if not isinstance(text, str) or text == "close": # "close": the relay went offline
27
+ return
28
+ for part in text.split(";"):
29
+ key, _, value = part.partition("=")
30
+ if key.strip():
31
+ state[key.strip()] = value.strip()
32
+
33
+
34
+ def press(gpio, key):
35
+ now = time.ticks_ms()
36
+ before = last_press.get(gpio)
37
+ if before is not None and time.ticks_diff(now, before) < DEBOUNCE_MS:
38
+ return # contact bounce
39
+ last_press[gpio] = now
40
+ if pins[gpio].value() != 0:
41
+ return # not held down (a bounce on release)
42
+ current = state.get(key)
43
+ if current not in ("0", "1"):
44
+ print("relay %s: state of %s unknown yet, not sent" % (TARGET, key))
45
+ return
46
+ new = "0" if current == "1" else "1"
47
+ if board.signal(TARGET + "@", key + "=" + new):
48
+ state[key] = new # until the relay answers with its $state
49
+ else:
50
+ print("not online, %s not sent" % key)
51
+
52
+
53
+ board.subscribe(TARGET + "@$state", on_state)
54
+ for gpio, key in BUTTONS.items():
55
+ pins[gpio] = Pin(gpio, Pin.IN, Pin.PULL_UP)
56
+ pins[gpio].irq(trigger=Pin.IRQ_FALLING, handler=lambda p, g=gpio, k=key: press(g, k))