cobs-proto 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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: cobs-proto
3
+ Version: 0.1.0
4
+ Summary: Shared COBS+CRC framed protobuf transport for asyncio serial protocols
5
+ Author-email: Richard Lin <richardlin@enphaseenergy.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/enphase/cobs-proto
8
+ Project-URL: Issues, https://github.com/enphase/cobs-proto/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: protobuf~=7.0
15
+ Requires-Dist: cobs
16
+ Requires-Dist: mypy
17
+ Provides-Extra: dev
18
+ Requires-Dist: black~=26.0; extra == "dev"
19
+ Requires-Dist: pytest~=9.0; extra == "dev"
20
+ Requires-Dist: pytest-asyncio~=1.0; extra == "dev"
21
+ Requires-Dist: types-protobuf~=7.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # cobs-proto
25
+
26
+ Host-side COBS + CRC framed protobuf transport for asyncio serial protocols.
27
+
28
+ Provides an `asyncio.Protocol` implementation with request-response structure and optional
29
+ (unrequested) streaming readings.
30
+
31
+ See the [Rust README](https://github.com/enphase/cobs-proto/blob/main/rust/README.md) for details on the matching device-side implementation.
32
+ See the [top-level README](https://github.com/enphase/cobs-proto) for details on the wire format.
33
+
34
+ This is a pre-v1 release and API stability is not guaranteed.
35
+
36
+
37
+ ## Usage
38
+
39
+ ```console
40
+ pip install cobs-proto
41
+ ```
42
+
43
+ ```python
44
+ import asyncio
45
+ from cobs_proto import CobsProtoProtocol
46
+ from your_proto import packet_pb2
47
+
48
+ # Subclass to specify the decoded packet type
49
+ # Request-response only, see CobsProtoStreamingProtocol which adds device streaming data
50
+ class MyProtocol(CobsProtoProtocol[packet_pb2.HostPacket, packet_pb2.DevicePacket]):
51
+ @staticmethod
52
+ def _device_packet_type():
53
+ return packet_pb2.DevicePacket
54
+
55
+ # Connect (via pyserial-asyncio or similar)
56
+ transport, protocol = await serial_asyncio.create_serial_connection(
57
+ asyncio.get_running_loop(), lambda: MyProtocol(), port, baudrate=115200,
58
+ )
59
+
60
+ # Send a request and await the response
61
+ response = await protocol.send_request(packet_pb2.HostPacket(ping=packet_pb2.Ping()))
62
+ ```
@@ -0,0 +1,39 @@
1
+ # cobs-proto
2
+
3
+ Host-side COBS + CRC framed protobuf transport for asyncio serial protocols.
4
+
5
+ Provides an `asyncio.Protocol` implementation with request-response structure and optional
6
+ (unrequested) streaming readings.
7
+
8
+ See the [Rust README](https://github.com/enphase/cobs-proto/blob/main/rust/README.md) for details on the matching device-side implementation.
9
+ See the [top-level README](https://github.com/enphase/cobs-proto) for details on the wire format.
10
+
11
+ This is a pre-v1 release and API stability is not guaranteed.
12
+
13
+
14
+ ## Usage
15
+
16
+ ```console
17
+ pip install cobs-proto
18
+ ```
19
+
20
+ ```python
21
+ import asyncio
22
+ from cobs_proto import CobsProtoProtocol
23
+ from your_proto import packet_pb2
24
+
25
+ # Subclass to specify the decoded packet type
26
+ # Request-response only, see CobsProtoStreamingProtocol which adds device streaming data
27
+ class MyProtocol(CobsProtoProtocol[packet_pb2.HostPacket, packet_pb2.DevicePacket]):
28
+ @staticmethod
29
+ def _device_packet_type():
30
+ return packet_pb2.DevicePacket
31
+
32
+ # Connect (via pyserial-asyncio or similar)
33
+ transport, protocol = await serial_asyncio.create_serial_connection(
34
+ asyncio.get_running_loop(), lambda: MyProtocol(), port, baudrate=115200,
35
+ )
36
+
37
+ # Send a request and await the response
38
+ response = await protocol.send_request(packet_pb2.HostPacket(ping=packet_pb2.Ping()))
39
+ ```
@@ -0,0 +1,24 @@
1
+ # Copyright 2026 Enphase Energy, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from .transport import CobsProtoProtocol, CobsProtoStreamingProtocol
16
+ from .testing import encode_device_frame, make_connected_protocol, respond
17
+
18
+ __all__ = [
19
+ "CobsProtoProtocol",
20
+ "CobsProtoStreamingProtocol",
21
+ "encode_device_frame",
22
+ "make_connected_protocol",
23
+ "respond",
24
+ ]
File without changes
@@ -0,0 +1,55 @@
1
+ # Copyright 2026 Enphase Energy, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Test helpers for COBS+CRC framed asyncio protocols."""
16
+
17
+ import asyncio
18
+ import binascii
19
+ import struct
20
+ from typing import cast, TypeVar
21
+ from unittest.mock import MagicMock
22
+
23
+ import cobs.cobs
24
+ from google.protobuf import message as pb_message
25
+
26
+ TProtocol = TypeVar("TProtocol", bound=asyncio.Protocol)
27
+
28
+
29
+ def make_connected_protocol(protocol: TProtocol) -> tuple[TProtocol, MagicMock]:
30
+ """Wire a mock serial transport to an asyncio Protocol and call connection_made.
31
+
32
+ Returns ``(protocol, transport)`` so the caller can inspect writes if needed.
33
+ """
34
+ transport = MagicMock(spec=asyncio.Transport)
35
+ transport.serial = MagicMock()
36
+ transport.serial.reset_input_buffer = MagicMock()
37
+ protocol.connection_made(transport)
38
+ return protocol, transport
39
+
40
+
41
+ def encode_device_frame(packet: pb_message.Message) -> bytes:
42
+ """Encode a protobuf message into a COBS+CRC framed wire packet."""
43
+ message_bytes = packet.SerializeToString()
44
+ crc = binascii.crc_hqx(message_bytes, 0)
45
+ message_with_crc = message_bytes + struct.pack(">H", crc)
46
+ return cast(bytes, b"\x00" + cobs.cobs.encode(message_with_crc) + b"\x00")
47
+
48
+
49
+ async def respond(
50
+ protocol: asyncio.Protocol,
51
+ wire_packet: pb_message.Message,
52
+ ) -> None:
53
+ """Wait one event loop turn then feed wire_packet into the protocol."""
54
+ await asyncio.sleep(0)
55
+ protocol.data_received(encode_device_frame(wire_packet))
@@ -0,0 +1,206 @@
1
+ # Copyright 2026 Enphase Energy, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """COBS+CRC framed protobuf transport over asyncio serial.
16
+
17
+ Provides a base class for request/response protocols that use:
18
+ - Protobuf serialization
19
+ - CRC-16/XMODEM integrity
20
+ - COBS byte stuffing with 0x00 frame delimiter
21
+
22
+ Subclasses specify the concrete protobuf message types and (for streaming
23
+ devices) implement packet classification to route between the response
24
+ future and the streaming queue.
25
+ """
26
+
27
+ import abc
28
+ import asyncio
29
+ import binascii
30
+ import logging
31
+ import struct
32
+ from typing import (
33
+ AsyncIterator,
34
+ Generic,
35
+ Optional,
36
+ Type,
37
+ TypeVar,
38
+ )
39
+
40
+ import cobs.cobs
41
+ from google.protobuf import message as pb_message
42
+
43
+ TWireHostPacket = TypeVar("TWireHostPacket", bound=pb_message.Message)
44
+ TWireDevicePacket = TypeVar("TWireDevicePacket", bound=pb_message.Message)
45
+
46
+
47
+ class CobsProtoProtocol(
48
+ asyncio.Protocol,
49
+ abc.ABC,
50
+ Generic[TWireHostPacket, TWireDevicePacket],
51
+ ):
52
+ """Base asyncio.Protocol for COBS+CRC framed protobuf serial communication.
53
+
54
+ Only one request may be in flight at a time.
55
+
56
+ Type parameters:
57
+ TWireHostPacket: The protobuf message serialized on the wire to the device.
58
+ TWireDevicePacket: The protobuf message deserialized from the wire.
59
+ """
60
+
61
+ REQUEST_TIMEOUT = 1.0 # seconds before a pending request is discarded
62
+
63
+ # --- Subclass must set these ---
64
+
65
+ @staticmethod
66
+ @abc.abstractmethod
67
+ def _device_packet_type() -> Type[TWireDevicePacket]:
68
+ """Return the protobuf class used to deserialize incoming device packets."""
69
+ ...
70
+
71
+ def __init__(self) -> None:
72
+ super().__init__()
73
+ self._buffer = bytearray()
74
+ self._transport: Optional[asyncio.Transport] = None
75
+ self._pending_response: Optional[asyncio.Future[TWireDevicePacket]] = None
76
+ self._connected = asyncio.Event()
77
+
78
+ def connection_made(self, transport: asyncio.BaseTransport) -> None:
79
+ assert isinstance(transport, asyncio.Transport)
80
+ serial = transport.serial # type: ignore[attr-defined]
81
+ serial.reset_input_buffer() # clear any stale pending data in the buffer
82
+ self._transport = transport
83
+ self._connected.set()
84
+
85
+ def connection_lost(self, exc: Optional[Exception]) -> None:
86
+ logging.error(f"connection lost: {exc}")
87
+ self._transport = None
88
+
89
+ async def wait_connected(self) -> None:
90
+ """Block until the serial connection is established."""
91
+ await self._connected.wait()
92
+
93
+ # --- Send side ---
94
+
95
+ def _write_message(self, message: pb_message.Message) -> None:
96
+ if self._transport is None:
97
+ raise ConnectionError("no connection")
98
+ message_bytes = message.SerializeToString()
99
+ crc = binascii.crc_hqx(message_bytes, 0)
100
+ message_with_crc = message_bytes + struct.pack(">H", crc)
101
+ cobs_bytes = cobs.cobs.encode(message_with_crc)
102
+ self._transport.write(b"\x00" + cobs_bytes + b"\x00")
103
+
104
+ async def send_request(self, packet: TWireHostPacket) -> TWireDevicePacket:
105
+ """Send a command and await the response.
106
+
107
+ Raises ``asyncio.TimeoutError`` if no response arrives in time.
108
+ """
109
+ assert self._pending_response is None, "only one request may be in flight"
110
+
111
+ fut: asyncio.Future[TWireDevicePacket] = (
112
+ asyncio.get_running_loop().create_future()
113
+ )
114
+ self._pending_response = fut
115
+ self._write_message(packet)
116
+ try:
117
+ return await asyncio.wait_for(asyncio.shield(fut), self.REQUEST_TIMEOUT)
118
+ except asyncio.TimeoutError:
119
+ self._pending_response = None
120
+ raise
121
+
122
+ # --- Receive side ---
123
+
124
+ def _dispatch_device_packet(self, packet: TWireDevicePacket) -> None:
125
+ """Route a decoded device packet to the pending response future.
126
+
127
+ Subclasses (e.g. streaming) may override to intercept other
128
+ messages before delegating to super.
129
+ """
130
+ if self._pending_response is not None:
131
+ fut = self._pending_response
132
+ self._pending_response = None
133
+ fut.set_result(packet)
134
+ else:
135
+ logging.warning(
136
+ f"discarding received packet with no pending request: {packet}"
137
+ )
138
+
139
+ def data_received(self, data: bytes) -> None:
140
+ self._buffer += data
141
+ split = self._buffer.split(b"\x00")
142
+ self._buffer = bytearray(split[-1])
143
+ for serial_bytes in split[:-1]:
144
+ if not serial_bytes:
145
+ continue # skip empty frames
146
+ try:
147
+ decoded_bytes = cobs.cobs.decode(serial_bytes)
148
+ if len(decoded_bytes) < 2:
149
+ raise ValueError("Frame too short for CRC")
150
+ message_bytes = decoded_bytes[:-2]
151
+ received_crc = struct.unpack(">H", decoded_bytes[-2:])[0]
152
+ computed_crc = binascii.crc_hqx(message_bytes, 0)
153
+ if received_crc != computed_crc:
154
+ raise ValueError(
155
+ f"CRC mismatch: received {received_crc:04x}, computed {computed_crc:04x}"
156
+ )
157
+ packet = self._device_packet_type().FromString(message_bytes)
158
+ except Exception as e:
159
+ logging.warning(
160
+ f"discarding bad packet: {len(serial_bytes)} bytes, {serial_bytes!r} - {e}"
161
+ )
162
+ continue
163
+ logging.debug(f"received message {packet}")
164
+
165
+ self._dispatch_device_packet(packet)
166
+
167
+
168
+ class CobsProtoStreamingProtocol(
169
+ CobsProtoProtocol[TWireHostPacket, TWireDevicePacket],
170
+ Generic[TWireHostPacket, TWireDevicePacket],
171
+ ):
172
+ """Extension of ``CobsProtoProtocol`` for devices that also send
173
+ unsolicited streaming packets alongside request/response traffic.
174
+
175
+ Subclasses implement ``_is_streaming_packet`` to determine routing:
176
+ return ``True`` for streaming packets (enqueued for ``iter_readings``),
177
+ ``False`` for request-response packets (resolved against the pending future).
178
+
179
+ The streaming queue holds the full ``TWireDevicePacket``; unpacking
180
+ is the caller's responsibility.
181
+ """
182
+
183
+ @abc.abstractmethod
184
+ def _is_streaming_packet(self, packet: TWireDevicePacket) -> bool:
185
+ """Return ``True`` if the packet is an unsolicited streaming packet,
186
+ ``False`` if it is a response to a request."""
187
+ ...
188
+
189
+ def __init__(self) -> None:
190
+ super().__init__()
191
+ self._reading_queue: asyncio.Queue[TWireDevicePacket] = asyncio.Queue()
192
+
193
+ def _dispatch_device_packet(self, packet: TWireDevicePacket) -> None:
194
+ if self._is_streaming_packet(packet):
195
+ self._reading_queue.put_nowait(packet)
196
+ else:
197
+ super()._dispatch_device_packet(packet)
198
+
199
+ async def next_reading(self) -> TWireDevicePacket:
200
+ """Return the next streaming packet, blocking if none is available."""
201
+ return await self._reading_queue.get()
202
+
203
+ async def iter_readings(self) -> AsyncIterator[TWireDevicePacket]:
204
+ """Yield streaming packets as they arrive."""
205
+ while True:
206
+ yield await self._reading_queue.get()
@@ -0,0 +1,62 @@
1
+ Metadata-Version: 2.4
2
+ Name: cobs-proto
3
+ Version: 0.1.0
4
+ Summary: Shared COBS+CRC framed protobuf transport for asyncio serial protocols
5
+ Author-email: Richard Lin <richardlin@enphaseenergy.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/enphase/cobs-proto
8
+ Project-URL: Issues, https://github.com/enphase/cobs-proto/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.10
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: protobuf~=7.0
15
+ Requires-Dist: cobs
16
+ Requires-Dist: mypy
17
+ Provides-Extra: dev
18
+ Requires-Dist: black~=26.0; extra == "dev"
19
+ Requires-Dist: pytest~=9.0; extra == "dev"
20
+ Requires-Dist: pytest-asyncio~=1.0; extra == "dev"
21
+ Requires-Dist: types-protobuf~=7.0; extra == "dev"
22
+ Dynamic: license-file
23
+
24
+ # cobs-proto
25
+
26
+ Host-side COBS + CRC framed protobuf transport for asyncio serial protocols.
27
+
28
+ Provides an `asyncio.Protocol` implementation with request-response structure and optional
29
+ (unrequested) streaming readings.
30
+
31
+ See the [Rust README](https://github.com/enphase/cobs-proto/blob/main/rust/README.md) for details on the matching device-side implementation.
32
+ See the [top-level README](https://github.com/enphase/cobs-proto) for details on the wire format.
33
+
34
+ This is a pre-v1 release and API stability is not guaranteed.
35
+
36
+
37
+ ## Usage
38
+
39
+ ```console
40
+ pip install cobs-proto
41
+ ```
42
+
43
+ ```python
44
+ import asyncio
45
+ from cobs_proto import CobsProtoProtocol
46
+ from your_proto import packet_pb2
47
+
48
+ # Subclass to specify the decoded packet type
49
+ # Request-response only, see CobsProtoStreamingProtocol which adds device streaming data
50
+ class MyProtocol(CobsProtoProtocol[packet_pb2.HostPacket, packet_pb2.DevicePacket]):
51
+ @staticmethod
52
+ def _device_packet_type():
53
+ return packet_pb2.DevicePacket
54
+
55
+ # Connect (via pyserial-asyncio or similar)
56
+ transport, protocol = await serial_asyncio.create_serial_connection(
57
+ asyncio.get_running_loop(), lambda: MyProtocol(), port, baudrate=115200,
58
+ )
59
+
60
+ # Send a request and await the response
61
+ response = await protocol.send_request(packet_pb2.HostPacket(ping=packet_pb2.Ping()))
62
+ ```
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ cobs_proto/__init__.py
5
+ cobs_proto/py.typed
6
+ cobs_proto/testing.py
7
+ cobs_proto/transport.py
8
+ cobs_proto.egg-info/PKG-INFO
9
+ cobs_proto.egg-info/SOURCES.txt
10
+ cobs_proto.egg-info/dependency_links.txt
11
+ cobs_proto.egg-info/requires.txt
12
+ cobs_proto.egg-info/top_level.txt
13
+ tests/test_transport.py
@@ -0,0 +1,9 @@
1
+ protobuf~=7.0
2
+ cobs
3
+ mypy
4
+
5
+ [dev]
6
+ black~=26.0
7
+ pytest~=9.0
8
+ pytest-asyncio~=1.0
9
+ types-protobuf~=7.0
@@ -0,0 +1 @@
1
+ cobs_proto
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cobs-proto"
7
+ description = "Shared COBS+CRC framed protobuf transport for asyncio serial protocols"
8
+ version = "0.1.0"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [
13
+ { name = "Richard Lin", email = "richardlin@enphaseenergy.com" }
14
+ ]
15
+ requires-python = ">=3.10"
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ ]
20
+ dependencies = [
21
+ "protobuf~=7.0",
22
+ "cobs",
23
+ "mypy",
24
+ ]
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/enphase/cobs-proto"
28
+ Issues = "https://github.com/enphase/cobs-proto/issues"
29
+
30
+
31
+ [project.optional-dependencies]
32
+ dev = [
33
+ "black~=26.0",
34
+ "pytest~=9.0",
35
+ "pytest-asyncio~=1.0",
36
+ "types-protobuf~=7.0",
37
+ ]
38
+
39
+ [tool.mypy]
40
+ check_untyped_defs = true
41
+ disallow_incomplete_defs = true
42
+ disallow_untyped_defs = true
43
+ strict = true
44
+
45
+ [[tool.mypy.overrides]]
46
+ module = ["cobs.*"]
47
+ ignore_missing_imports = true
48
+
49
+ [[tool.mypy.overrides]]
50
+ module = ["tests.proto.*"]
51
+ ignore_errors = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,204 @@
1
+ # Copyright 2026 Enphase Energy, Inc.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Tests for cobs_proto transport using the shared test_packet proto."""
16
+
17
+ import asyncio
18
+ from pathlib import Path
19
+ from typing import cast
20
+ from unittest.mock import MagicMock
21
+
22
+ import pytest
23
+
24
+ from cobs_proto import CobsProtoProtocol, CobsProtoStreamingProtocol
25
+ from cobs_proto import encode_device_frame, make_connected_protocol, respond
26
+ from .proto import test_packet_pb2 as pb
27
+
28
+ # --- Concrete test protocol subclasses ---
29
+
30
+
31
+ class _ExampleProtocol(
32
+ CobsProtoProtocol[pb.HostPacket, pb.DevicePacket],
33
+ ):
34
+ @staticmethod
35
+ def _device_packet_type() -> type[pb.DevicePacket]:
36
+ return pb.DevicePacket
37
+
38
+
39
+ class _ExampleStreamingProtocol(
40
+ CobsProtoStreamingProtocol[pb.HostPacket, pb.DevicePacket],
41
+ ):
42
+ @staticmethod
43
+ def _device_packet_type() -> type[pb.DevicePacket]:
44
+ return pb.DevicePacket
45
+
46
+ def _is_streaming_packet(self, packet: pb.DevicePacket) -> bool:
47
+ return packet.HasField("reading")
48
+
49
+
50
+ # --- Cross-language golden vectors ---
51
+ # The .bin files are raw golden wire frames shared with the Rust tests.
52
+
53
+ _VECTORS_DIR = Path(__file__).resolve().parents[2] / "test_proto"
54
+
55
+ GOLDEN_DEVICE_PACKET = pb.DevicePacket(value_status=pb.ValueStatus(current_value=42))
56
+ GOLDEN_DEVICE_FRAME = (_VECTORS_DIR / "device_value_status_42.bin").read_bytes()
57
+
58
+ # HostPacket { ping: Ping {} }
59
+ GOLDEN_HOST_FRAME = (_VECTORS_DIR / "host_ping.bin").read_bytes()
60
+
61
+
62
+ # --- Wire encoding tests ---
63
+
64
+
65
+ class TestWireEncoding:
66
+ def test_encode_device_frame_matches_golden(self) -> None:
67
+ """encode_device_frame produces bytes matching the Rust encoder."""
68
+ assert encode_device_frame(GOLDEN_DEVICE_PACKET) == GOLDEN_DEVICE_FRAME
69
+
70
+ def test_encode_host_frame_matches_golden(self) -> None:
71
+ """_write_message produces bytes matching the Rust encoder."""
72
+ protocol, transport = make_connected_protocol(_ExampleProtocol())
73
+ protocol._write_message(pb.HostPacket(ping=pb.Ping()))
74
+ written = transport.write.call_args[0][0]
75
+ assert written == GOLDEN_HOST_FRAME
76
+
77
+
78
+ # --- Wire decoding tests ---
79
+
80
+
81
+ class TestWireDecoding:
82
+ def test_decode_golden_frame(self) -> None:
83
+ """data_received correctly decodes the golden device frame."""
84
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
85
+ fut = asyncio.get_event_loop().create_future()
86
+ protocol._pending_response = fut
87
+ protocol.data_received(GOLDEN_DEVICE_FRAME)
88
+ assert fut.done()
89
+ assert fut.result() == GOLDEN_DEVICE_PACKET
90
+
91
+ def test_crc_mismatch_discards_packet(self) -> None:
92
+ """A corrupted frame is silently discarded."""
93
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
94
+ fut = asyncio.get_event_loop().create_future()
95
+ protocol._pending_response = fut
96
+ corrupted = bytearray(GOLDEN_DEVICE_FRAME)
97
+ corrupted[3] ^= 0xFF
98
+ protocol.data_received(bytes(corrupted))
99
+ assert not fut.done()
100
+
101
+ def test_partial_frame_delivery(self) -> None:
102
+ """A frame split across two data_received calls still decodes."""
103
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
104
+ fut = asyncio.get_event_loop().create_future()
105
+ protocol._pending_response = fut
106
+ mid = len(GOLDEN_DEVICE_FRAME) // 2
107
+ protocol.data_received(GOLDEN_DEVICE_FRAME[:mid])
108
+ assert not fut.done()
109
+ protocol.data_received(GOLDEN_DEVICE_FRAME[mid:])
110
+ assert fut.done()
111
+ assert fut.result() == GOLDEN_DEVICE_PACKET
112
+
113
+
114
+ # --- Request-response lifecycle ---
115
+
116
+
117
+ class TestRequestResponse:
118
+ @pytest.mark.asyncio
119
+ async def test_send_request_and_respond(self) -> None:
120
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
121
+
122
+ result, _ = await asyncio.gather(
123
+ protocol.send_request(pb.HostPacket(ping=pb.Ping())),
124
+ respond(protocol, GOLDEN_DEVICE_PACKET),
125
+ )
126
+ assert result == GOLDEN_DEVICE_PACKET
127
+
128
+ @pytest.mark.asyncio
129
+ async def test_timeout_on_no_response(self) -> None:
130
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
131
+ protocol.REQUEST_TIMEOUT = 0.01
132
+ with pytest.raises(asyncio.TimeoutError):
133
+ await protocol.send_request(pb.HostPacket(ping=pb.Ping()))
134
+ assert protocol._pending_response is None
135
+
136
+ @pytest.mark.asyncio
137
+ async def test_one_in_flight_enforcement(self) -> None:
138
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
139
+ asyncio.ensure_future(protocol.send_request(pb.HostPacket(ping=pb.Ping())))
140
+ await asyncio.sleep(0)
141
+ with pytest.raises(AssertionError, match="only one request"):
142
+ await protocol.send_request(pb.HostPacket(ping=pb.Ping()))
143
+
144
+ @pytest.mark.asyncio
145
+ async def test_unrequested_packet_discarded(self) -> None:
146
+ """A packet with no pending request is discarded (not raised)."""
147
+ protocol, _ = make_connected_protocol(_ExampleProtocol())
148
+ protocol.data_received(encode_device_frame(GOLDEN_DEVICE_PACKET))
149
+
150
+
151
+ # --- Streaming protocol tests ---
152
+
153
+
154
+ class TestStreaming:
155
+ @pytest.mark.asyncio
156
+ async def test_streaming_packet_goes_to_queue(self) -> None:
157
+ protocol, _ = make_connected_protocol(_ExampleStreamingProtocol())
158
+ reading = pb.DeviceReading(value=42)
159
+ protocol.data_received(encode_device_frame(pb.DevicePacket(reading=reading)))
160
+
161
+ pkt = await asyncio.wait_for(protocol.next_reading(), timeout=0.1)
162
+ assert pkt.reading == reading
163
+
164
+ @pytest.mark.asyncio
165
+ async def test_response_packet_resolves_future(self) -> None:
166
+ protocol, _ = make_connected_protocol(_ExampleStreamingProtocol())
167
+
168
+ result, _ = await asyncio.gather(
169
+ protocol.send_request(pb.HostPacket(ping=pb.Ping())),
170
+ respond(protocol, GOLDEN_DEVICE_PACKET),
171
+ )
172
+ assert result == GOLDEN_DEVICE_PACKET
173
+
174
+ @pytest.mark.asyncio
175
+ async def test_interleaved_streaming_and_response(self) -> None:
176
+ protocol, _ = make_connected_protocol(_ExampleStreamingProtocol())
177
+ reading = pb.DeviceReading(value=7)
178
+
179
+ async def simulate() -> None:
180
+ await respond(protocol, pb.DevicePacket(reading=reading))
181
+ await respond(protocol, GOLDEN_DEVICE_PACKET)
182
+
183
+ result, _ = await asyncio.gather(
184
+ protocol.send_request(pb.HostPacket(ping=pb.Ping())),
185
+ simulate(),
186
+ )
187
+ assert result == GOLDEN_DEVICE_PACKET
188
+
189
+ pkt = await asyncio.wait_for(protocol.next_reading(), timeout=0.1)
190
+ assert pkt.reading == reading
191
+
192
+ @pytest.mark.asyncio
193
+ async def test_iter_readings(self) -> None:
194
+ protocol, _ = make_connected_protocol(_ExampleStreamingProtocol())
195
+ readings = [pb.DeviceReading(value=i) for i in range(3)]
196
+ for r in readings:
197
+ protocol.data_received(encode_device_frame(pb.DevicePacket(reading=r)))
198
+
199
+ collected = []
200
+ async for pkt in protocol.iter_readings():
201
+ collected.append(pkt.reading)
202
+ if len(collected) == 3:
203
+ break
204
+ assert collected == readings