pySerialTransfer 2.6.9__tar.gz → 3.0.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 (47) hide show
  1. {pySerialTransfer-2.6.9 → pyserialtransfer-3.0.0}/LICENSE +21 -21
  2. pyserialtransfer-3.0.0/MANIFEST.in +2 -0
  3. pyserialtransfer-3.0.0/PKG-INFO +202 -0
  4. pyserialtransfer-3.0.0/README.md +171 -0
  5. pyserialtransfer-3.0.0/create_live_pypi.bat +3 -0
  6. pyserialtransfer-3.0.0/create_test_pypi.bat +3 -0
  7. pyserialtransfer-3.0.0/examples/data/Arduino/rx_data/rx_data.ino +33 -0
  8. pyserialtransfer-3.0.0/examples/data/Arduino/tx_data/tx_data.ino +39 -0
  9. pyserialtransfer-3.0.0/examples/data/Python/rx_data.py +46 -0
  10. pyserialtransfer-3.0.0/examples/data/Python/tx_data.py +43 -0
  11. pyserialtransfer-3.0.0/examples/datum/Arduino/rx_datum/rx_datum.ino +22 -0
  12. pyserialtransfer-3.0.0/examples/datum/Arduino/tx_datum/tx_datum.ino +22 -0
  13. pyserialtransfer-3.0.0/examples/datum/Python/rx_datum.py +44 -0
  14. pyserialtransfer-3.0.0/examples/datum/Python/tx_datum.py +37 -0
  15. pyserialtransfer-3.0.0/examples/file/Arduino/rx_file/rx_file.ino +84 -0
  16. pyserialtransfer-3.0.0/examples/file/Arduino/tx_file/tx_file.ino +74 -0
  17. pyserialtransfer-3.0.0/examples/file/Python/file_transfer.py +139 -0
  18. pyserialtransfer-3.0.0/examples/file/Python/rx_file.py +65 -0
  19. pyserialtransfer-3.0.0/examples/file/Python/tx_file.py +61 -0
  20. pyserialtransfer-3.0.0/pySerialTransfer/CRC.py +109 -0
  21. pyserialtransfer-3.0.0/pySerialTransfer/__init__.py +5 -0
  22. pyserialtransfer-3.0.0/pySerialTransfer/__main__.py +4 -0
  23. pyserialtransfer-3.0.0/pySerialTransfer/cli.py +291 -0
  24. pyserialtransfer-3.0.0/pySerialTransfer/pySerialTransfer.py +569 -0
  25. pyserialtransfer-3.0.0/pySerialTransfer.egg-info/PKG-INFO +202 -0
  26. pyserialtransfer-3.0.0/pySerialTransfer.egg-info/SOURCES.txt +38 -0
  27. pyserialtransfer-3.0.0/pySerialTransfer.egg-info/entry_points.txt +2 -0
  28. pyserialtransfer-3.0.0/pySerialTransfer.egg-info/requires.txt +11 -0
  29. {pySerialTransfer-2.6.9 → pyserialtransfer-3.0.0}/setup.cfg +1 -1
  30. {pySerialTransfer-2.6.9 → pyserialtransfer-3.0.0}/setup.py +12 -7
  31. pyserialtransfer-3.0.0/tests/test_cli.py +94 -0
  32. pyserialtransfer-3.0.0/tests/test_crc.py +193 -0
  33. pyserialtransfer-3.0.0/tests/test_file_transfer_example.py +78 -0
  34. pyserialtransfer-3.0.0/tests/test_py_serial_transfer.py +544 -0
  35. pyserialtransfer-3.0.0/tests/test_uart_regressions.py +138 -0
  36. pyserialtransfer-3.0.0/tools/release.py +34 -0
  37. pyserialtransfer-3.0.0/update_live_pypi.bat +3 -0
  38. pySerialTransfer-2.6.9/PKG-INFO +0 -195
  39. pySerialTransfer-2.6.9/README.md +0 -183
  40. pySerialTransfer-2.6.9/pySerialTransfer/CRC.py +0 -61
  41. pySerialTransfer-2.6.9/pySerialTransfer/__init__.py +0 -1
  42. pySerialTransfer-2.6.9/pySerialTransfer/pySerialTransfer.py +0 -642
  43. pySerialTransfer-2.6.9/pySerialTransfer.egg-info/PKG-INFO +0 -195
  44. pySerialTransfer-2.6.9/pySerialTransfer.egg-info/SOURCES.txt +0 -12
  45. pySerialTransfer-2.6.9/pySerialTransfer.egg-info/requires.txt +0 -1
  46. {pySerialTransfer-2.6.9 → pyserialtransfer-3.0.0}/pySerialTransfer.egg-info/dependency_links.txt +0 -0
  47. {pySerialTransfer-2.6.9 → pyserialtransfer-3.0.0}/pySerialTransfer.egg-info/top_level.txt +0 -0
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2020 PB2
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.
1
+ MIT License
2
+
3
+ Copyright (c) 2020 PB2
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,2 @@
1
+ recursive-include examples *.py *.ino
2
+ include tools/release.py create_live_pypi.bat create_test_pypi.bat update_live_pypi.bat
@@ -0,0 +1,202 @@
1
+ Metadata-Version: 2.4
2
+ Name: pySerialTransfer
3
+ Version: 3.0.0
4
+ Summary: Python package used to transmit and receive low overhead byte packets - especially useful for PC<-->Arduino USB communication (compatible with https://github.com/PowerBroker2/SerialTransfer)
5
+ Home-page: https://github.com/PowerBroker2/pySerialTransfer
6
+ Author: Power_Broker
7
+ Author-email: gitstuff2@gmail.com
8
+ Keywords: Arduino,serial,usb,protocol,communication
9
+ Requires-Python: >=3.8
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: pyserial>=3.5
13
+ Requires-Dist: typer>=0.15.0
14
+ Provides-Extra: release
15
+ Requires-Dist: build>=1; extra == "release"
16
+ Requires-Dist: twine>=5; extra == "release"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8.1.1; extra == "dev"
19
+ Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
20
+ Requires-Dist: pytest-mock>=3.14.0; extra == "dev"
21
+ Dynamic: author
22
+ Dynamic: author-email
23
+ Dynamic: description-content-type
24
+ Dynamic: home-page
25
+ Dynamic: keywords
26
+ Dynamic: license-file
27
+ Dynamic: provides-extra
28
+ Dynamic: requires-dist
29
+ Dynamic: requires-python
30
+ Dynamic: summary
31
+
32
+ # pySerialTransfer
33
+
34
+ Python package to transfer data in a fast, reliable, and packetized form over serial/UART.
35
+
36
+ If using this package to communicate with Arduinos, see [SerialTransfer](https://github.com/PowerBroker2/SerialTransfer) for the corresponding and compatible library (also available through the Arduino IDE's Libraries Manager).
37
+
38
+ Use Python to send and receive packets with an Arduino over a USB serial connection or a USB-to-UART adapter. Each packet carries up to 255 payload bytes and an application-defined ID. The package includes a Python API for two-way exchanges and the `pySerialTransfer` command for inspecting ports, sending a packet, and watching incoming traffic.
39
+
40
+ ## Quick start: get an echo from your board
41
+
42
+ ### 1. Install the matching libraries
43
+
44
+ This development checkout requires Python 3.8 or later.
45
+
46
+ In a terminal, change to this **pySerialTransfer** checkout and run:
47
+
48
+ ```console
49
+ python -m pip install -e .
50
+ pySerialTransfer --help
51
+ ```
52
+
53
+ This installs the checkout and its CLI into the active Python environment. If the command is missing from your shell's path, use `python -m pySerialTransfer` anywhere this guide uses `pySerialTransfer`.
54
+
55
+ On the board, use the version of [Arduino SerialTransfer](https://github.com/PowerBroker2/SerialTransfer) that documents `START | ID | LENGTH | PAYLOAD | CRC`. The older protocol with byte stuffing and a stop byte is incompatible. If the Arduino checkout is already in your sketchbook's `libraries/SerialTransfer` folder, the IDE can use it there. Otherwise, install its ZIP using **Sketch > Include Library > Add .ZIP Library**. [Arduino library installation guide](https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-installing-a-library/)
56
+
57
+ ### 2. Upload the Arduino sketch
58
+
59
+ Connect the board to the computer with a USB data cable. The sketch below uses the board port exposed to the computer as `Serial`. Select the board and port in the Arduino IDE, paste the sketch into a new sketch window, and upload it. Close the IDE's Serial Monitor before opening the port in Python.
60
+
61
+ ```cpp
62
+ #include <SerialTransfer.h>
63
+
64
+ SerialTransfer transfer;
65
+
66
+ void setup() {
67
+ Serial.begin(115200);
68
+ transfer.begin(Serial, false);
69
+ }
70
+
71
+ void loop() {
72
+ if (transfer.tick()) {
73
+ // Return the original payload and packet ID.
74
+ memcpy(transfer.packet.txBuff, transfer.packet.rxBuff, transfer.bytesRead);
75
+ transfer.sendData(transfer.bytesRead, transfer.currentPacketID());
76
+ }
77
+ }
78
+ ```
79
+
80
+ For a **USB-to-UART adapter**, use a board with an available hardware UART such as `Serial1`. Change both occurrences of `Serial` in `setup()` to that UART. Connect adapter TX to board RX1, adapter RX to board TX1, and GND to GND. Use an adapter with logic levels compatible with the board. Select the adapter's port in Python. On a direct USB connection, the USB cable handles both directions.
81
+
82
+ ### 3. Send and receive on the same port
83
+
84
+ Run `pySerialTransfer ports` and find the port that appears when you plug in the board, for example `COM3` on Windows or `/dev/ttyACM0` on Linux.
85
+
86
+ Save the following as `echo.py`. It sends the word `hello` with packet ID 1, waits for its reply on the same open connection, then closes the port.
87
+
88
+ ```python
89
+ import sys
90
+ import time
91
+ from pySerialTransfer import pySerialTransfer as txfer
92
+
93
+ port = sys.argv[1]
94
+ link = txfer.SerialTransfer(port, baud=115200)
95
+ try:
96
+ if not link.open():
97
+ raise OSError(f"Could not open {port}")
98
+ time.sleep(2) # Some boards restart when the port opens.
99
+ size = link.tx_obj("hello")
100
+ if size is None or not link.send(size, packet_id=1):
101
+ raise OSError("Could not send hello")
102
+
103
+ deadline = time.monotonic() + 3
104
+ while time.monotonic() < deadline:
105
+ link.available()
106
+ if link.status == txfer.Status.NEW_DATA and link.id_byte == 1:
107
+ print(bytes(link.rx_buff[:link.bytes_read]).decode("utf-8"))
108
+ break
109
+ time.sleep(0.001)
110
+ else:
111
+ raise TimeoutError("No echo within three seconds")
112
+ finally:
113
+ link.close()
114
+ ```
115
+
116
+ Run `python echo.py COM3` with the port you found earlier. On Linux or macOS, substitute the full device name. Printing `hello` confirms that the packet reached the board and the reply reached Python.
117
+
118
+ ## Command line
119
+
120
+ Run `pySerialTransfer` or `pySerialTransfer --help` for an overview. Each command accepts `-h` or `--help` and lists its options and defaults.
121
+
122
+ | Command | Use it when |
123
+ | --- | --- |
124
+ | `pySerialTransfer ports` | You need the names of serial devices available to Python. |
125
+ | `pySerialTransfer send --port COM3 --text hello` | You want to send one UTF-8 message. The command prints the packet details and closes the connection. |
126
+ | `pySerialTransfer send --port COM3 --hex "00 7e ff" --packet-id 0x10` | You know the payload bytes and packet ID. Supply exactly one of `--hex` and `--text`. |
127
+ | `pySerialTransfer listen --port COM3 --count 1 --duration 5` | A device transmits on its own. Print the next packet as JSON and stop, or report an error if five seconds pass first. |
128
+
129
+ Substitute your device name for `COM3`. Sender and receiver must agree on `--baud` (115200 by default). Run `pySerialTransfer send --help` for write and startup timing. The separate `send` and `listen` commands each open the port anew. For request/reply exchanges, use the Python example above so the reply stays on the same connection.
130
+
131
+ ### Troubleshooting your first packet
132
+
133
+ | Symptom | What to check |
134
+ | --- | --- |
135
+ | The port is missing or fails to open | Use a USB data cable, close the Serial Monitor and other port users, and check your account's serial-device permissions. |
136
+ | The port opens but the echo times out | Check the selected port, baud rate and sketch. A board that restarts on port open may need a longer startup delay. For adapters, check crossed TX/RX, ground and logic voltage. |
137
+ | CRC errors or unreadable packets | Confirm the protocol versions match and keep diagnostic text off the data stream. Use a separate debug port. |
138
+ | Payload bytes look right but decoded numbers are wrong | Check the byte order and width of each field on both ends. |
139
+
140
+ ## Working with payloads
141
+
142
+ Packet IDs are numbers from 0 through 255. Give each message type an ID and decide its payload layout on both sides. To send opaque bytes, use `link.tx_struct_obj(data)` with at most 255 bytes, then pass its returned length to `link.send(length, packet_id=...)`. A successful send means the local serial connection accepted the frame. If the application needs delivery confirmation, have the receiver reply.
143
+
144
+ `tx_obj(value, start_pos=...)` packs a Python value and returns the next free byte offset. `rx_obj(type, start_pos=...)` reads a value from the current payload. The default byte order is little-endian. A Python `int` uses four signed bytes, a `float` uses four bytes, and a string uses UTF-8. For binary data containing zeros, use the raw bytes in `rx_buff[:bytes_read]`.
145
+
146
+ For example, message ID 7 can carry a two-byte unsigned channel followed by a four-byte signed count. On a little-endian Arduino, pack `uint16_t channel` and `int32_t count` separately with `txObj`. The six bytes for channel 3 and count -42 are `03 00 D6 FF FF FF`. After a completed Python receive:
147
+
148
+ ```python
149
+ import struct
150
+
151
+ if link.status == txfer.Status.NEW_DATA and link.id_byte == 7:
152
+ if link.bytes_read == 6:
153
+ channel, count = struct.unpack_from("<Hi", link.rx_buff)
154
+ print(channel, count)
155
+ ```
156
+
157
+ With the library helpers the same fields are `link.rx_obj("H")` and `link.rx_obj("i", start_pos=2)`. For lists of fixed-width values, specify a byte count and a format, such as `link.rx_obj(list, obj_byte_size=8, list_format="i")` for two signed 32-bit integers. Arduino struct padding and the platform-dependent widths of `int` and `double` can affect the wire layout.
158
+
159
+ The `send` command waits two seconds after opening the port so boards that reset can finish booting. Set `--startup-delay 0` for a link that is already ready.
160
+
161
+ ## Advanced: parsing, timeouts, and callbacks
162
+
163
+ `available()` polls for one completed packet and returns its payload length. Always use `status == Status.NEW_DATA` when an empty payload is meaningful. Both an empty packet and an idle poll return zero. Read or copy `rx_buff[:bytes_read]` before polling again. Extra buffered frames can be consumed on subsequent calls.
164
+
165
+ The OS read timeout (`timeout`) and parser timeout (`inter_byte_timeout`) are separate, both in seconds. The parser default is 0.05 seconds. It discards an incomplete packet when it observes a gap that long. Pass `inter_byte_timeout=None` in Python or `--inter-byte-timeout none` in the CLI to disable that check. Use an application deadline when waiting for a reply. `Status.CRC_ERROR` means the checksum failed, and `Status.STALE_PACKET_ERROR` reports an expired partial frame.
166
+
167
+ For dispatch by ID, use `set_callbacks()` and poll with `tick()`. Position zero in the callback list corresponds to packet ID zero. This snippet assumes `link` is open:
168
+
169
+ ```python
170
+ def on_message():
171
+ print(bytes(link.rx_buff[:link.bytes_read]))
172
+
173
+ link.set_callbacks([on_message])
174
+ while True:
175
+ if not link.tick():
176
+ time.sleep(0.001)
177
+ ```
178
+
179
+ ### Wire format
180
+
181
+ | Field | Bytes | Meaning |
182
+ | --- | ---: | --- |
183
+ | Start | 1 | Always `0x7E`. |
184
+ | ID | 1 | Application-defined message type, 0 to 255. |
185
+ | Length | 1 | Number of payload bytes, 0 to 255. |
186
+ | Payload | Length | Any bytes, including `0x00` and `0x7E`. |
187
+ | CRC | 1 | CRC-8 over ID, length, and payload, in that order. |
188
+
189
+ CRC calculation starts at zero, uses polynomial `0x9B`, processes the most significant bit first, and applies no final XOR. For example, ID 0 with payload `01 02 03 04` produces the eight wire bytes `7E 00 04 01 02 03 04 6A`. Once the parser knows the length, it can consume a literal `0x7E` inside the payload. There is no escaping or trailing delimiter.
190
+
191
+ ### File transfers and paired examples
192
+
193
+ The USB examples pair one program on the computer with the opposite sketch on the board. Run the Python scripts from the repository root. For a float, use the [datum examples](examples/datum/). For a marker, float, and text in a single message, use the [data examples](examples/data/).
194
+
195
+ | Direction | Upload to the Arduino | Run on the computer |
196
+ | --- | --- | --- |
197
+ | Computer sends a file | [rx_file.ino](examples/file/Arduino/rx_file/rx_file.ino) | `python examples/file/Python/tx_file.py --port COM3 sample.bin` |
198
+ | Computer receives a file | [tx_file.ino](examples/file/Arduino/tx_file/tx_file.ino) | `python examples/file/Python/rx_file.py --port COM3 --output-dir received` |
199
+
200
+ These file sketches use USB `Serial` by default. To use a separate adapter on a board with `Serial1`, set `FILE_PORT` to `Serial1` in the selected sketch. The example accepts up to 4096 file bytes. Packet ID 0 carries the size, a 32-bit FNV-1a checksum, and filename. ID 1 carries a two-byte little-endian offset followed by up to 253 data bytes. ID 2 repeats the size and checksum. The receiver checks every offset and verifies the completed file. This one-way protocol detects incomplete transfers. The Arduino library's separate acknowledged file examples use different IDs and support retries.
201
+
202
+ On boards with `LED_BUILTIN`, the Arduino receiver lights it after a valid file arrives. The Python receiver saves verified files into the output directory and skips filenames that already exist.
@@ -0,0 +1,171 @@
1
+ # pySerialTransfer
2
+
3
+ Python package to transfer data in a fast, reliable, and packetized form over serial/UART.
4
+
5
+ If using this package to communicate with Arduinos, see [SerialTransfer](https://github.com/PowerBroker2/SerialTransfer) for the corresponding and compatible library (also available through the Arduino IDE's Libraries Manager).
6
+
7
+ Use Python to send and receive packets with an Arduino over a USB serial connection or a USB-to-UART adapter. Each packet carries up to 255 payload bytes and an application-defined ID. The package includes a Python API for two-way exchanges and the `pySerialTransfer` command for inspecting ports, sending a packet, and watching incoming traffic.
8
+
9
+ ## Quick start: get an echo from your board
10
+
11
+ ### 1. Install the matching libraries
12
+
13
+ This development checkout requires Python 3.8 or later.
14
+
15
+ In a terminal, change to this **pySerialTransfer** checkout and run:
16
+
17
+ ```console
18
+ python -m pip install -e .
19
+ pySerialTransfer --help
20
+ ```
21
+
22
+ This installs the checkout and its CLI into the active Python environment. If the command is missing from your shell's path, use `python -m pySerialTransfer` anywhere this guide uses `pySerialTransfer`.
23
+
24
+ On the board, use the version of [Arduino SerialTransfer](https://github.com/PowerBroker2/SerialTransfer) that documents `START | ID | LENGTH | PAYLOAD | CRC`. The older protocol with byte stuffing and a stop byte is incompatible. If the Arduino checkout is already in your sketchbook's `libraries/SerialTransfer` folder, the IDE can use it there. Otherwise, install its ZIP using **Sketch > Include Library > Add .ZIP Library**. [Arduino library installation guide](https://docs.arduino.cc/software/ide-v2/tutorials/ide-v2-installing-a-library/)
25
+
26
+ ### 2. Upload the Arduino sketch
27
+
28
+ Connect the board to the computer with a USB data cable. The sketch below uses the board port exposed to the computer as `Serial`. Select the board and port in the Arduino IDE, paste the sketch into a new sketch window, and upload it. Close the IDE's Serial Monitor before opening the port in Python.
29
+
30
+ ```cpp
31
+ #include <SerialTransfer.h>
32
+
33
+ SerialTransfer transfer;
34
+
35
+ void setup() {
36
+ Serial.begin(115200);
37
+ transfer.begin(Serial, false);
38
+ }
39
+
40
+ void loop() {
41
+ if (transfer.tick()) {
42
+ // Return the original payload and packet ID.
43
+ memcpy(transfer.packet.txBuff, transfer.packet.rxBuff, transfer.bytesRead);
44
+ transfer.sendData(transfer.bytesRead, transfer.currentPacketID());
45
+ }
46
+ }
47
+ ```
48
+
49
+ For a **USB-to-UART adapter**, use a board with an available hardware UART such as `Serial1`. Change both occurrences of `Serial` in `setup()` to that UART. Connect adapter TX to board RX1, adapter RX to board TX1, and GND to GND. Use an adapter with logic levels compatible with the board. Select the adapter's port in Python. On a direct USB connection, the USB cable handles both directions.
50
+
51
+ ### 3. Send and receive on the same port
52
+
53
+ Run `pySerialTransfer ports` and find the port that appears when you plug in the board, for example `COM3` on Windows or `/dev/ttyACM0` on Linux.
54
+
55
+ Save the following as `echo.py`. It sends the word `hello` with packet ID 1, waits for its reply on the same open connection, then closes the port.
56
+
57
+ ```python
58
+ import sys
59
+ import time
60
+ from pySerialTransfer import pySerialTransfer as txfer
61
+
62
+ port = sys.argv[1]
63
+ link = txfer.SerialTransfer(port, baud=115200)
64
+ try:
65
+ if not link.open():
66
+ raise OSError(f"Could not open {port}")
67
+ time.sleep(2) # Some boards restart when the port opens.
68
+ size = link.tx_obj("hello")
69
+ if size is None or not link.send(size, packet_id=1):
70
+ raise OSError("Could not send hello")
71
+
72
+ deadline = time.monotonic() + 3
73
+ while time.monotonic() < deadline:
74
+ link.available()
75
+ if link.status == txfer.Status.NEW_DATA and link.id_byte == 1:
76
+ print(bytes(link.rx_buff[:link.bytes_read]).decode("utf-8"))
77
+ break
78
+ time.sleep(0.001)
79
+ else:
80
+ raise TimeoutError("No echo within three seconds")
81
+ finally:
82
+ link.close()
83
+ ```
84
+
85
+ Run `python echo.py COM3` with the port you found earlier. On Linux or macOS, substitute the full device name. Printing `hello` confirms that the packet reached the board and the reply reached Python.
86
+
87
+ ## Command line
88
+
89
+ Run `pySerialTransfer` or `pySerialTransfer --help` for an overview. Each command accepts `-h` or `--help` and lists its options and defaults.
90
+
91
+ | Command | Use it when |
92
+ | --- | --- |
93
+ | `pySerialTransfer ports` | You need the names of serial devices available to Python. |
94
+ | `pySerialTransfer send --port COM3 --text hello` | You want to send one UTF-8 message. The command prints the packet details and closes the connection. |
95
+ | `pySerialTransfer send --port COM3 --hex "00 7e ff" --packet-id 0x10` | You know the payload bytes and packet ID. Supply exactly one of `--hex` and `--text`. |
96
+ | `pySerialTransfer listen --port COM3 --count 1 --duration 5` | A device transmits on its own. Print the next packet as JSON and stop, or report an error if five seconds pass first. |
97
+
98
+ Substitute your device name for `COM3`. Sender and receiver must agree on `--baud` (115200 by default). Run `pySerialTransfer send --help` for write and startup timing. The separate `send` and `listen` commands each open the port anew. For request/reply exchanges, use the Python example above so the reply stays on the same connection.
99
+
100
+ ### Troubleshooting your first packet
101
+
102
+ | Symptom | What to check |
103
+ | --- | --- |
104
+ | The port is missing or fails to open | Use a USB data cable, close the Serial Monitor and other port users, and check your account's serial-device permissions. |
105
+ | The port opens but the echo times out | Check the selected port, baud rate and sketch. A board that restarts on port open may need a longer startup delay. For adapters, check crossed TX/RX, ground and logic voltage. |
106
+ | CRC errors or unreadable packets | Confirm the protocol versions match and keep diagnostic text off the data stream. Use a separate debug port. |
107
+ | Payload bytes look right but decoded numbers are wrong | Check the byte order and width of each field on both ends. |
108
+
109
+ ## Working with payloads
110
+
111
+ Packet IDs are numbers from 0 through 255. Give each message type an ID and decide its payload layout on both sides. To send opaque bytes, use `link.tx_struct_obj(data)` with at most 255 bytes, then pass its returned length to `link.send(length, packet_id=...)`. A successful send means the local serial connection accepted the frame. If the application needs delivery confirmation, have the receiver reply.
112
+
113
+ `tx_obj(value, start_pos=...)` packs a Python value and returns the next free byte offset. `rx_obj(type, start_pos=...)` reads a value from the current payload. The default byte order is little-endian. A Python `int` uses four signed bytes, a `float` uses four bytes, and a string uses UTF-8. For binary data containing zeros, use the raw bytes in `rx_buff[:bytes_read]`.
114
+
115
+ For example, message ID 7 can carry a two-byte unsigned channel followed by a four-byte signed count. On a little-endian Arduino, pack `uint16_t channel` and `int32_t count` separately with `txObj`. The six bytes for channel 3 and count -42 are `03 00 D6 FF FF FF`. After a completed Python receive:
116
+
117
+ ```python
118
+ import struct
119
+
120
+ if link.status == txfer.Status.NEW_DATA and link.id_byte == 7:
121
+ if link.bytes_read == 6:
122
+ channel, count = struct.unpack_from("<Hi", link.rx_buff)
123
+ print(channel, count)
124
+ ```
125
+
126
+ With the library helpers the same fields are `link.rx_obj("H")` and `link.rx_obj("i", start_pos=2)`. For lists of fixed-width values, specify a byte count and a format, such as `link.rx_obj(list, obj_byte_size=8, list_format="i")` for two signed 32-bit integers. Arduino struct padding and the platform-dependent widths of `int` and `double` can affect the wire layout.
127
+
128
+ The `send` command waits two seconds after opening the port so boards that reset can finish booting. Set `--startup-delay 0` for a link that is already ready.
129
+
130
+ ## Advanced: parsing, timeouts, and callbacks
131
+
132
+ `available()` polls for one completed packet and returns its payload length. Always use `status == Status.NEW_DATA` when an empty payload is meaningful. Both an empty packet and an idle poll return zero. Read or copy `rx_buff[:bytes_read]` before polling again. Extra buffered frames can be consumed on subsequent calls.
133
+
134
+ The OS read timeout (`timeout`) and parser timeout (`inter_byte_timeout`) are separate, both in seconds. The parser default is 0.05 seconds. It discards an incomplete packet when it observes a gap that long. Pass `inter_byte_timeout=None` in Python or `--inter-byte-timeout none` in the CLI to disable that check. Use an application deadline when waiting for a reply. `Status.CRC_ERROR` means the checksum failed, and `Status.STALE_PACKET_ERROR` reports an expired partial frame.
135
+
136
+ For dispatch by ID, use `set_callbacks()` and poll with `tick()`. Position zero in the callback list corresponds to packet ID zero. This snippet assumes `link` is open:
137
+
138
+ ```python
139
+ def on_message():
140
+ print(bytes(link.rx_buff[:link.bytes_read]))
141
+
142
+ link.set_callbacks([on_message])
143
+ while True:
144
+ if not link.tick():
145
+ time.sleep(0.001)
146
+ ```
147
+
148
+ ### Wire format
149
+
150
+ | Field | Bytes | Meaning |
151
+ | --- | ---: | --- |
152
+ | Start | 1 | Always `0x7E`. |
153
+ | ID | 1 | Application-defined message type, 0 to 255. |
154
+ | Length | 1 | Number of payload bytes, 0 to 255. |
155
+ | Payload | Length | Any bytes, including `0x00` and `0x7E`. |
156
+ | CRC | 1 | CRC-8 over ID, length, and payload, in that order. |
157
+
158
+ CRC calculation starts at zero, uses polynomial `0x9B`, processes the most significant bit first, and applies no final XOR. For example, ID 0 with payload `01 02 03 04` produces the eight wire bytes `7E 00 04 01 02 03 04 6A`. Once the parser knows the length, it can consume a literal `0x7E` inside the payload. There is no escaping or trailing delimiter.
159
+
160
+ ### File transfers and paired examples
161
+
162
+ The USB examples pair one program on the computer with the opposite sketch on the board. Run the Python scripts from the repository root. For a float, use the [datum examples](examples/datum/). For a marker, float, and text in a single message, use the [data examples](examples/data/).
163
+
164
+ | Direction | Upload to the Arduino | Run on the computer |
165
+ | --- | --- | --- |
166
+ | Computer sends a file | [rx_file.ino](examples/file/Arduino/rx_file/rx_file.ino) | `python examples/file/Python/tx_file.py --port COM3 sample.bin` |
167
+ | Computer receives a file | [tx_file.ino](examples/file/Arduino/tx_file/tx_file.ino) | `python examples/file/Python/rx_file.py --port COM3 --output-dir received` |
168
+
169
+ These file sketches use USB `Serial` by default. To use a separate adapter on a board with `Serial1`, set `FILE_PORT` to `Serial1` in the selected sketch. The example accepts up to 4096 file bytes. Packet ID 0 carries the size, a 32-bit FNV-1a checksum, and filename. ID 1 carries a two-byte little-endian offset followed by up to 253 data bytes. ID 2 repeats the size and checksum. The receiver checks every offset and verifies the completed file. This one-way protocol detects incomplete transfers. The Arduino library's separate acknowledged file examples use different IDs and support retries.
170
+
171
+ On boards with `LED_BUILTIN`, the Arduino receiver lights it after a valid file arrives. The Python receiver saves verified files into the output directory and skips filenames that already exist.
@@ -0,0 +1,3 @@
1
+ @echo off
2
+ python "%~dp0tools\release.py" --repository pypi
3
+ exit /b %errorlevel%
@@ -0,0 +1,3 @@
1
+ @echo off
2
+ python "%~dp0tools\release.py" --repository testpypi
3
+ exit /b %errorlevel%
@@ -0,0 +1,33 @@
1
+ #include "SerialTransfer.h"
2
+
3
+
4
+ SerialTransfer myTransfer;
5
+
6
+ struct __attribute__((packed)) STRUCT {
7
+ char z;
8
+ float y;
9
+ } testStruct;
10
+
11
+ char arr[6];
12
+
13
+
14
+ void setup()
15
+ {
16
+ Serial.begin(115200);
17
+ myTransfer.begin(Serial);
18
+ }
19
+
20
+
21
+ void loop()
22
+ {
23
+ if (myTransfer.available() == sizeof(testStruct) + sizeof(arr) - 1 && myTransfer.currentPacketID() == 0)
24
+ {
25
+ // use this variable to keep track of how many
26
+ // bytes we've processed from the receive buffer
27
+ uint16_t recSize = 0;
28
+
29
+ recSize = myTransfer.rxObj(testStruct, recSize);
30
+ myTransfer.rxObj(arr, recSize, sizeof(arr) - 1);
31
+ arr[sizeof(arr) - 1] = '\0';
32
+ }
33
+ }
@@ -0,0 +1,39 @@
1
+ #include "SerialTransfer.h"
2
+
3
+
4
+ SerialTransfer myTransfer;
5
+
6
+ struct __attribute__((packed)) STRUCT {
7
+ char z;
8
+ float y;
9
+ } testStruct;
10
+
11
+ char arr[] = "hello";
12
+
13
+
14
+ void setup()
15
+ {
16
+ Serial.begin(115200);
17
+ myTransfer.begin(Serial);
18
+
19
+ testStruct.z = '$';
20
+ testStruct.y = 4.5;
21
+ }
22
+
23
+
24
+ void loop()
25
+ {
26
+ // use this variable to keep track of how many
27
+ // bytes we're stuffing in the transmit buffer
28
+ uint16_t sendSize = 0;
29
+
30
+ ///////////////////////////////////////// Stuff buffer with struct
31
+ sendSize = myTransfer.txObj(testStruct, sendSize);
32
+
33
+ ///////////////////////////////////////// Stuff buffer with array
34
+ sendSize = myTransfer.txObj(arr, sendSize, strlen(arr));
35
+
36
+ ///////////////////////////////////////// Send buffer
37
+ myTransfer.sendData(sendSize);
38
+ delay(500);
39
+ }
@@ -0,0 +1,46 @@
1
+ """Receive and decode a marker, 32-bit float, and UTF-8 text payload."""
2
+
3
+ import argparse
4
+ import sys
5
+ import time
6
+
7
+ from pySerialTransfer import pySerialTransfer as txfer
8
+ from pySerialTransfer.pySerialTransfer import Status
9
+
10
+
11
+ def main(argv=None):
12
+ parser = argparse.ArgumentParser(description="Receive and decode a packed data packet over UART.")
13
+ parser.add_argument("--port", required=True, help="serial port, such as COM11 or /dev/ttyUSB0")
14
+ parser.add_argument("--baud", type=int, default=115200, help="UART baud rate (default: 115200)")
15
+ args = parser.parse_args(argv)
16
+ link = None
17
+ try:
18
+ link = txfer.SerialTransfer(args.port, baud=args.baud, restrict_ports=False)
19
+ if not link.open():
20
+ raise RuntimeError("could not open serial port {!r}".format(args.port))
21
+ while True:
22
+ link.available()
23
+ if link.status == Status.NEW_DATA:
24
+ marker = link.rx_obj(obj_type="c", start_pos=0)
25
+ value = link.rx_obj(obj_type="f", start_pos=1)
26
+ text = link.rx_obj(obj_type=str, start_pos=5, obj_byte_size=5)
27
+ if link.id_byte != 0 or link.bytes_read != 10 or marker != b"$" or value is None or text is None:
28
+ print("Received packet did not match the expected 10-byte layout.", file=sys.stderr)
29
+ else:
30
+ print("${} | {}".format(value, text))
31
+ elif link.status in (Status.CRC_ERROR, Status.STALE_PACKET_ERROR):
32
+ print("SerialTransfer parser reported {}".format(link.status.name), file=sys.stderr)
33
+ else:
34
+ time.sleep(0.001)
35
+ except KeyboardInterrupt:
36
+ return 0
37
+ except (OSError, RuntimeError, ValueError) as exc:
38
+ print("Error: {}".format(exc), file=sys.stderr)
39
+ return 1
40
+ finally:
41
+ if link is not None:
42
+ link.close()
43
+
44
+
45
+ if __name__ == "__main__":
46
+ raise SystemExit(main())
@@ -0,0 +1,43 @@
1
+ """Send a packed marker, float, and UTF-8 text payload over UART."""
2
+
3
+ import argparse
4
+ import sys
5
+ import time
6
+
7
+ from pySerialTransfer import pySerialTransfer as txfer
8
+
9
+
10
+ def main(argv=None):
11
+ parser = argparse.ArgumentParser(description="Send a marker, float, and text packet repeatedly.")
12
+ parser.add_argument("--port", required=True, help="serial port, such as COM11 or /dev/ttyUSB0")
13
+ parser.add_argument("--baud", type=int, default=115200, help="UART baud rate (default: 115200)")
14
+ args = parser.parse_args(argv)
15
+ link = None
16
+ try:
17
+ link = txfer.SerialTransfer(args.port, baud=args.baud, restrict_ports=False)
18
+ if not link.open():
19
+ raise RuntimeError("could not open serial port {!r}".format(args.port))
20
+ time.sleep(2) # allow boards that reset on serial open to restart
21
+ while True:
22
+ send_size = link.tx_obj("$", val_type_override="c")
23
+ if send_size is None:
24
+ raise RuntimeError("could not pack the marker byte")
25
+ send_size = link.tx_obj(4.5, start_pos=send_size)
26
+ if send_size is None:
27
+ raise RuntimeError("could not pack the float value")
28
+ send_size = link.tx_obj("hello", start_pos=send_size)
29
+ if send_size is None or not link.send(send_size):
30
+ raise RuntimeError("could not send the complete data packet")
31
+ time.sleep(0.5)
32
+ except KeyboardInterrupt:
33
+ return 0
34
+ except (OSError, RuntimeError, ValueError) as exc:
35
+ print("Error: {}".format(exc), file=sys.stderr)
36
+ return 1
37
+ finally:
38
+ if link is not None:
39
+ link.close()
40
+
41
+
42
+ if __name__ == "__main__":
43
+ raise SystemExit(main())
@@ -0,0 +1,22 @@
1
+ #include "SerialTransfer.h"
2
+
3
+
4
+ SerialTransfer myTransfer;
5
+
6
+ float y;
7
+
8
+
9
+ void setup()
10
+ {
11
+ Serial.begin(115200);
12
+ myTransfer.begin(Serial);
13
+ }
14
+
15
+
16
+ void loop()
17
+ {
18
+ if (myTransfer.available() == sizeof(y) && myTransfer.currentPacketID() == 0)
19
+ {
20
+ myTransfer.rxObj(y);
21
+ }
22
+ }
@@ -0,0 +1,22 @@
1
+ #include "SerialTransfer.h"
2
+
3
+
4
+ SerialTransfer myTransfer;
5
+
6
+ float y;
7
+
8
+
9
+ void setup()
10
+ {
11
+ Serial.begin(115200);
12
+ myTransfer.begin(Serial);
13
+
14
+ y = 4.5;
15
+ }
16
+
17
+
18
+ void loop()
19
+ {
20
+ myTransfer.sendDatum(y);
21
+ delay(500);
22
+ }