pepper-c1 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pepper_c1/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """pepper_c1 — Python driver for the Eccel Peeper C1 RFID reader."""
2
+
3
+ from .client import PepperC1
4
+ from .commands import Command, KEY_TYPE_AES128, KEY_TYPE_AES192, KEY_TYPE_AES256
5
+ from .commands import KEY_TYPE_DES, KEY_TYPE_2K3DES, KEY_TYPE_3K3DES, KEY_TYPE_MIFARE
6
+ from .exceptions import CommandError, ProtocolError, TransportError
7
+ from .transport import TCPTransport, UARTTransport
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = [
11
+ "PepperC1",
12
+ "UARTTransport",
13
+ "TCPTransport",
14
+ "Command",
15
+ "CommandError",
16
+ "ProtocolError",
17
+ "TransportError",
18
+ "KEY_TYPE_AES128",
19
+ "KEY_TYPE_AES192",
20
+ "KEY_TYPE_AES256",
21
+ "KEY_TYPE_DES",
22
+ "KEY_TYPE_2K3DES",
23
+ "KEY_TYPE_3K3DES",
24
+ "KEY_TYPE_MIFARE",
25
+ ]
pepper_c1/client.py ADDED
@@ -0,0 +1,306 @@
1
+ """High-level client for the Eccel Peeper C1 RFID reader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import List
6
+
7
+ from .commands import Command
8
+ from .exceptions import CommandError, ProtocolError
9
+ from .protocol import build_frame
10
+ from .transport import Transport
11
+
12
+
13
+ class PepperC1:
14
+ """Driver for the Eccel Peeper C1 RFID reader.
15
+
16
+ Usage::
17
+
18
+ from pepper_c1 import PepperC1, UARTTransport
19
+ with PepperC1(UARTTransport('/dev/ttyUSB0')) as reader:
20
+ print(reader.get_version())
21
+ print(reader.get_uid().hex())
22
+ """
23
+
24
+ def __init__(self, transport: Transport, response_timeout: float = 2.0) -> None:
25
+ self._transport = transport
26
+ self._timeout = response_timeout
27
+ self.async_events: List[bytes] = []
28
+
29
+ # ------------------------------------------------------------------
30
+ # Low-level interface
31
+ # ------------------------------------------------------------------
32
+
33
+ def send_command(self, cmd: Command, data: bytes = b"") -> bytes:
34
+ """Send a command frame and return the response payload (without CMD_ACK byte).
35
+
36
+ Raises CommandError if the device responds with CMD_ERROR.
37
+ Async events received while waiting are stored in self.async_events.
38
+ """
39
+ payload = bytes([cmd]) + data
40
+ self._transport.write(build_frame(payload))
41
+ return self._wait_response(cmd)
42
+
43
+ def _wait_response(self, sent_cmd: Command) -> bytes:
44
+ from .protocol import FrameParser
45
+ parser = FrameParser()
46
+ import time
47
+ deadline = time.monotonic() + self._timeout
48
+ buf = b""
49
+
50
+ while time.monotonic() < deadline:
51
+ chunk = self._transport._read_chunk(256)
52
+ if not chunk:
53
+ continue
54
+ completed = parser.feed(chunk)
55
+ for payload in completed:
56
+ if not payload:
57
+ continue
58
+ resp_byte = payload[0]
59
+ if resp_byte == Command.ASYNC:
60
+ self.async_events.append(payload[1:])
61
+ elif resp_byte == Command.ERROR:
62
+ failed_cmd = payload[1] if len(payload) > 1 else 0xFF
63
+ error_code = 0
64
+ if len(payload) >= 4:
65
+ error_code = payload[2] | (payload[3] << 8)
66
+ raise CommandError(failed_cmd, error_code)
67
+ elif resp_byte == Command.ACK:
68
+ return payload[2:] # skip ACK byte and echoed command byte
69
+ raise TimeoutError(f"No response to command 0x{sent_cmd:02X} within {self._timeout}s")
70
+
71
+ # ------------------------------------------------------------------
72
+ # General commands
73
+ # ------------------------------------------------------------------
74
+
75
+ def get_version(self) -> str:
76
+ """Return firmware version string."""
77
+ data = self.send_command(Command.GET_VERSION)
78
+ return data.decode("ascii", errors="replace").rstrip("\x00")
79
+
80
+ def get_tag_count(self) -> int:
81
+ """Return number of tags in the RF field."""
82
+ data = self.send_command(Command.GET_TAG_COUNT)
83
+ return data[0] if data else 0
84
+
85
+ def get_uid(self, tag_index: int = 0) -> bytes:
86
+ """Return UID info for tag at tag_index (0-based).
87
+
88
+ Response payload: [type, param, uid_bytes...]
89
+ """
90
+ return self.send_command(Command.GET_UID, bytes([tag_index]))
91
+
92
+ def activate_tag(self, tag_index: int = 0) -> bytes:
93
+ """Activate the tag at tag_index; returns response payload."""
94
+ return self.send_command(Command.ACTIVATE_TAG, bytes([tag_index]))
95
+
96
+ def halt(self) -> None:
97
+ """Halt the active tag."""
98
+ self.send_command(Command.HALT)
99
+
100
+ def set_polling(self, enable: bool, interval_ms: int = 500) -> None:
101
+ """Enable or disable automatic tag polling.
102
+
103
+ Args:
104
+ enable: True to start polling, False to stop.
105
+ interval_ms: Polling interval in milliseconds (0–65535).
106
+ """
107
+ data = bytes([1 if enable else 0, interval_ms & 0xFF, (interval_ms >> 8) & 0xFF])
108
+ self.send_command(Command.SET_POLLING, data)
109
+
110
+ def reboot(self) -> None:
111
+ """Reboot the reader module."""
112
+ self.send_command(Command.REBOOT)
113
+
114
+ # ------------------------------------------------------------------
115
+ # Key management
116
+ # ------------------------------------------------------------------
117
+
118
+ def set_key(self, key_slot: int, key_type: int, key_data: bytes) -> None:
119
+ """Store a key in the reader's key slot.
120
+
121
+ Args:
122
+ key_slot: Key slot index.
123
+ key_type: One of the KEY_TYPE_* constants from pepper_c1.commands.
124
+ key_data: Raw key bytes.
125
+ """
126
+ data = bytes([key_slot, key_type]) + key_data
127
+ self.send_command(Command.SET_KEY, data)
128
+
129
+ def save_keys(self) -> None:
130
+ """Persist stored keys to non-volatile memory."""
131
+ self.send_command(Command.SAVE_KEYS)
132
+
133
+ # ------------------------------------------------------------------
134
+ # MIFARE Classic
135
+ # ------------------------------------------------------------------
136
+
137
+ def mf_read_block(self, block: int, count: int = 1,
138
+ auth_param: int = 0x0A, key_no: int = 0) -> bytes:
139
+ """Read one or more 16-byte MIFARE Classic blocks.
140
+
141
+ Args:
142
+ block: First block number.
143
+ count: Number of consecutive blocks to read.
144
+ auth_param: Firmware authentication parameter (empirically 0x0A).
145
+ key_no: Key slot index stored via set_key().
146
+ """
147
+ payload = bytes([block, count, auth_param, key_no])
148
+ data = self.send_command(Command.MF_READ_BLOCK, payload)
149
+ expected = 16 * count
150
+ if len(data) != expected:
151
+ raise ProtocolError(f"Expected {expected} bytes for MF block(s), got {len(data)}")
152
+ return data
153
+
154
+ def mf_write_block(self, block: int, data: bytes,
155
+ count: int = 1, auth_param: int = 0x0A, key_no: int = 0) -> None:
156
+ """Write one or more 16-byte MIFARE Classic blocks.
157
+
158
+ Args:
159
+ block: First block number.
160
+ data: Raw bytes; must be exactly count*16 bytes.
161
+ count: Number of consecutive blocks to write.
162
+ auth_param: Firmware authentication parameter (empirically 0x0A).
163
+ key_no: Key slot index stored via set_key().
164
+ """
165
+ if len(data) != 16 * count:
166
+ raise ValueError(f"MIFARE Classic write expects {16 * count} bytes, got {len(data)}")
167
+ payload = bytes([block, count, auth_param, key_no]) + data
168
+ self.send_command(Command.MF_WRITE_BLOCK, payload)
169
+
170
+ def mf_read_value(self, block: int, auth_param: int = 0x0A, key_no: int = 0) -> int:
171
+ """Read a MIFARE Classic value block; returns a signed 32-bit integer."""
172
+ data = self.send_command(Command.MF_READ_VALUE, bytes([block, auth_param, key_no]))
173
+ return int.from_bytes(data[:4], "little", signed=True)
174
+
175
+ def mf_write_value(self, block: int, value: int,
176
+ auth_param: int = 0x0A, key_no: int = 0) -> None:
177
+ """Write a MIFARE Classic value block."""
178
+ payload = bytes([block, auth_param, key_no]) + value.to_bytes(4, "little", signed=True)
179
+ self.send_command(Command.MF_WRITE_VALUE, payload)
180
+
181
+ def mf_increment(self, block: int, delta: int,
182
+ auth_param: int = 0x0A, key_no: int = 0) -> None:
183
+ """Increment a MIFARE Classic value block."""
184
+ data = bytes([block, auth_param, key_no]) + delta.to_bytes(4, "little", signed=False)
185
+ self.send_command(Command.MF_INCREMENT, data)
186
+
187
+ # ------------------------------------------------------------------
188
+ # MIFARE Ultralight
189
+ # ------------------------------------------------------------------
190
+
191
+ def mfu_read_page(self, page: int, count: int = 1) -> bytes:
192
+ """Read one or more 4-byte MIFARE Ultralight pages."""
193
+ data = self.send_command(Command.MFU_READ_PAGE, bytes([page, count]))
194
+ return data[:4 * count]
195
+
196
+ def mfu_write_page(self, page: int, data: bytes, count: int = 1) -> None:
197
+ """Write one or more 4-byte MIFARE Ultralight pages."""
198
+ if len(data) != 4 * count:
199
+ raise ValueError(f"Ultralight write expects {4 * count} bytes, got {len(data)}")
200
+ self.send_command(Command.MFU_WRITE_PAGE, bytes([page, count]) + data)
201
+
202
+ def mfu_read_counter(self, counter: int) -> int:
203
+ """Read a 3-byte NFC counter value."""
204
+ data = self.send_command(Command.MFU_READ_COUNTER, bytes([counter]))
205
+ return int.from_bytes(data[:3], "little")
206
+
207
+ def mfu_increment_counter(self, counter: int, delta: int) -> None:
208
+ """Increment an NFC counter."""
209
+ data = bytes([counter]) + delta.to_bytes(3, "little")
210
+ self.send_command(Command.MFU_INCREMENT_COUNTER, data)
211
+
212
+ def mfu_passwd_auth(self, password: bytes, pack: bytes = b"\x00\x00") -> bytes:
213
+ """Authenticate with a 4-byte password; returns 2-byte PACK."""
214
+ if len(password) != 4:
215
+ raise ValueError("Password must be 4 bytes")
216
+ return self.send_command(Command.MFU_PASSWD_AUTH, password + pack)
217
+
218
+ # ------------------------------------------------------------------
219
+ # MIFARE DESFire
220
+ # ------------------------------------------------------------------
221
+
222
+ def mfdf_select_app(self, aid: bytes) -> None:
223
+ """Select a DESFire application by its 3-byte AID."""
224
+ if len(aid) != 3:
225
+ raise ValueError("AID must be 3 bytes")
226
+ self.send_command(Command.MFDF_SELECT_APP, aid)
227
+
228
+ def mfdf_get_app_ids(self) -> list[bytes]:
229
+ """Return list of 3-byte AIDs present on the card."""
230
+ data = self.send_command(Command.MFDF_APP_IDS)
231
+ return [data[i:i + 3] for i in range(0, len(data), 3)]
232
+
233
+ def mfdf_auth(self, key_no: int, key_slot: int = 0) -> None:
234
+ """Authenticate with a DESFire key (3DES/DES) stored in reader key slot."""
235
+ self.send_command(Command.MFDF_AUTH, bytes([key_no, key_slot, 0]))
236
+
237
+ def mfdf_auth_aes(self, key_no: int, key_slot: int = 0) -> None:
238
+ """Authenticate with a DESFire AES key stored in reader key slot."""
239
+ self.send_command(Command.MFDF_AUTH_AES, bytes([key_no, key_slot, 0]))
240
+
241
+ def mfdf_read_data(self, file_no: int, offset: int, length: int) -> bytes:
242
+ """Read data from a DESFire standard/backup data file."""
243
+ data = (
244
+ bytes([file_no])
245
+ + offset.to_bytes(3, "little")
246
+ + length.to_bytes(3, "little")
247
+ )
248
+ return self.send_command(Command.MFDF_READ_DATA, data)
249
+
250
+ def mfdf_write_data(self, file_no: int, offset: int, data: bytes) -> None:
251
+ """Write data to a DESFire standard/backup data file."""
252
+ header = (
253
+ bytes([file_no])
254
+ + offset.to_bytes(3, "little")
255
+ + len(data).to_bytes(3, "little")
256
+ )
257
+ self.send_command(Command.MFDF_WRITE_DATA, header + data)
258
+
259
+ def mfdf_get_value(self, file_no: int) -> int:
260
+ """Read a DESFire value file; returns a signed 32-bit integer."""
261
+ data = self.send_command(Command.MFDF_GET_VALUE, bytes([file_no]))
262
+ return int.from_bytes(data[:4], "little", signed=True)
263
+
264
+ def mfdf_commit_transaction(self) -> None:
265
+ """Commit the current DESFire transaction."""
266
+ self.send_command(Command.MFDF_COMMIT_TRANSACTION)
267
+
268
+ def mfdf_abort_transaction(self) -> None:
269
+ """Abort the current DESFire transaction."""
270
+ self.send_command(Command.MFDF_ABORT_TRANSACTION)
271
+
272
+ # ------------------------------------------------------------------
273
+ # ICODE
274
+ # ------------------------------------------------------------------
275
+
276
+ def icode_inventory_start(self) -> bytes:
277
+ """Start ICODE inventory; returns UID of first tag found."""
278
+ return self.send_command(Command.ICODE_INVENTORY_START)
279
+
280
+ def icode_read_block(self, block: int, count: int = 1) -> bytes:
281
+ """Read one or more ICODE blocks (4 bytes each)."""
282
+ return self.send_command(Command.ICODE_READ_BLOCK, bytes([block, count]))
283
+
284
+ def icode_write_block(self, block: int, data: bytes, count: int = 1) -> None:
285
+ """Write one or more 4-byte ICODE blocks."""
286
+ if len(data) != 4 * count:
287
+ raise ValueError(f"ICODE write expects {4 * count} bytes, got {len(data)}")
288
+ self.send_command(Command.ICODE_WRITE_BLOCK, bytes([block, count]) + data)
289
+
290
+ def icode_get_system_information(self) -> bytes:
291
+ """Return ICODE system information."""
292
+ return self.send_command(Command.ICODE_GET_SYSTEM_INFORMATION)
293
+
294
+ # ------------------------------------------------------------------
295
+ # Context manager
296
+ # ------------------------------------------------------------------
297
+
298
+ def __enter__(self) -> "PepperC1":
299
+ return self
300
+
301
+ def __exit__(self, *_: object) -> None:
302
+ self._transport.close()
303
+
304
+ def close(self) -> None:
305
+ """Close the underlying transport."""
306
+ self._transport.close()
pepper_c1/commands.py ADDED
@@ -0,0 +1,124 @@
1
+ from enum import IntEnum
2
+
3
+
4
+ class Command(IntEnum):
5
+ # General
6
+ ACK = 0x00
7
+ DUMMY = 0x01
8
+ GET_TAG_COUNT = 0x02
9
+ GET_UID = 0x03
10
+ ACTIVATE_TAG = 0x04
11
+ HALT = 0x05
12
+ SET_POLLING = 0x06
13
+ SET_KEY = 0x07
14
+ SAVE_KEYS = 0x08
15
+ SET_NET_CFG = 0x09
16
+ REBOOT = 0x0A
17
+ GET_VERSION = 0x0B
18
+ UART_PASSTHRU = 0x0C
19
+
20
+ # MIFARE Classic
21
+ MF_READ_BLOCK = 0x20
22
+ MF_WRITE_BLOCK = 0x21
23
+ MF_READ_VALUE = 0x22
24
+ MF_WRITE_VALUE = 0x23
25
+ MF_INCREMENT = 0x24
26
+ MF_TRANSFER = 0x25
27
+ MF_RESTORE = 0x26
28
+ MF_TRANSFER_RESTORE = 0x27
29
+
30
+ # MIFARE Ultralight
31
+ MFU_READ_PAGE = 0x40
32
+ MFU_WRITE_PAGE = 0x41
33
+ MFU_GET_VERSION = 0x42
34
+ MFU_READ_SIG = 0x43
35
+ MFU_WRITE_SIG = 0x44
36
+ MFU_LOCK_SIG = 0x45
37
+ MFU_READ_COUNTER = 0x46
38
+ MFU_INCREMENT_COUNTER = 0x47
39
+ MFU_PASSWD_AUTH = 0x48
40
+ MFUC_AUTHENTICATE = 0x49
41
+ MFU_CHECKEVENT = 0x4A
42
+
43
+ # MIFARE DESFire
44
+ MFDF_GET_VERSION = 0x60
45
+ MFDF_SELECT_APP = 0x61
46
+ MFDF_APP_IDS = 0x62
47
+ MFDF_FILE_IDS = 0x63
48
+ MFDF_AUTH = 0x64
49
+ MFDF_AUTH_ISO = 0x65
50
+ MFDF_AUTH_AES = 0x66
51
+ MFDF_CREATE_APP = 0x67
52
+ MFDF_DELETE_APP = 0x68
53
+ MFDF_CHANGE_KEY = 0x69
54
+ MFDF_GET_KEY_SETTINGS = 0x6A
55
+ MFDF_CHANGE_KEY_SETTINGS = 0x6B
56
+ MFDF_CREATE_DATA_FILE = 0x6C
57
+ MFDF_WRITE_DATA = 0x6D
58
+ MFDF_READ_DATA = 0x6E
59
+ MFDF_CREATE_VALUE_FILE = 0x6F
60
+ MFDF_GET_VALUE = 0x70
61
+ MFDF_CREDIT = 0x71
62
+ MFDF_LIMITED_CREDIT = 0x72
63
+ MFDF_DEBIT = 0x73
64
+ MFDF_CREATE_RECORD_FILE = 0x74
65
+ MFDF_WRITE_RECORD = 0x75
66
+ MFDF_READ_RECORD = 0x76
67
+ MFDF_CLEAR_RECORDS = 0x77
68
+ MFDF_DELETE_FILE = 0x78
69
+ MFDF_GET_FREEMEM = 0x79
70
+ MFDF_FORMAT = 0x7A
71
+ MFDF_COMMIT_TRANSACTION = 0x7B
72
+ MFDF_ABORT_TRANSACTION = 0x7C
73
+
74
+ # ICODE
75
+ ICODE_INVENTORY_START = 0x90
76
+ ICODE_INVENTORY_NEXT = 0x91
77
+ ICODE_STAY_QUIET = 0x92
78
+ ICODE_READ_BLOCK = 0x93
79
+ ICODE_WRITE_BLOCK = 0x94
80
+ ICODE_LOCK_BLOCK = 0x95
81
+ ICODE_WRITE_AFI = 0x96
82
+ ICODE_LOCK_AFI = 0x97
83
+ ICODE_WRITE_DSFID = 0x98
84
+ ICODE_LOCK_DSFID = 0x99
85
+ ICODE_GET_SYSTEM_INFORMATION = 0x9A
86
+ ICODE_GET_MULTIPLE_BSS = 0x9B
87
+ ICODE_PASSWORD_PROTECT_AFI = 0x9C
88
+ ICODE_READ_EPC = 0x9D
89
+ ICODE_GET_NXP_SYSTEM_INFORMATION = 0x9E
90
+ ICODE_GET_RANDOM_NUMBER = 0x9F
91
+ ICODE_SET_PASSWORD = 0xA0
92
+ ICODE_WRITE_PASSWORD = 0xA1
93
+ ICODE_LOCK_PASSWORD = 0xA2
94
+ ICODE_PROTECT_PAGE = 0xA3
95
+ ICODE_LOCK_PAGE_PROTECTION = 0xA4
96
+ ICODE_GET_MULTIPLE_BPS = 0xA5
97
+ ICODE_DESTROY = 0xA6
98
+ ICODE_ENABLE_PRIVACY = 0xA7
99
+ ICODE_ENABLE_64BIT_PASSWORD = 0xA8
100
+ ICODE_READ_SIGNATURE = 0xA9
101
+ ICODE_READ_CONFIG = 0xAA
102
+ ICODE_WRITE_CONFIG = 0xAB
103
+ ICODE_PICK_RANDOM_ID = 0xAC
104
+ ICODE_SET_EAS = 0xAD
105
+ ICODE_RESET_EAS = 0xAE
106
+ ICODE_LOCK_EAS = 0xAF
107
+ ICODE_EAS_ALARM = 0xB0
108
+ ICODE_PASSWORD_PROTECT_EAS = 0xB1
109
+ ICODE_WRITE_EASID = 0xB2
110
+ ICODE_CUSTOM_CMD = 0xBF
111
+
112
+ # Special
113
+ ASYNC = 0xFE
114
+ ERROR = 0xFF
115
+
116
+
117
+ # Key type constants (from commands_binary.h)
118
+ KEY_TYPE_AES128 = 0x00
119
+ KEY_TYPE_AES192 = 0x01
120
+ KEY_TYPE_AES256 = 0x02
121
+ KEY_TYPE_DES = 0x03
122
+ KEY_TYPE_2K3DES = 0x04
123
+ KEY_TYPE_3K3DES = 0x05
124
+ KEY_TYPE_MIFARE = 0x06
@@ -0,0 +1,15 @@
1
+ class ProtocolError(Exception):
2
+ """Malformed frame, bad CRC, or length mismatch."""
3
+
4
+
5
+ class TransportError(Exception):
6
+ """Connection or I/O failure on UART or TCP transport."""
7
+
8
+
9
+ class CommandError(Exception):
10
+ """Device responded with CMD_ERROR (0xFF)."""
11
+
12
+ def __init__(self, cmd: int, error_code: int):
13
+ self.cmd = cmd
14
+ self.error_code = error_code
15
+ super().__init__(f"Command 0x{cmd:02X} failed with error code 0x{error_code:04X}")
pepper_c1/protocol.py ADDED
@@ -0,0 +1,148 @@
1
+ """Binary protocol framing for Eccel Peeper C1.
2
+
3
+ Frame layout:
4
+ [0xF5] [LEN_L] [LEN_H] [LEN_L^0xFF] [LEN_H^0xFF] [PAYLOAD...] [CRC_L] [CRC_H]
5
+
6
+ LEN = len(PAYLOAD) + 2 (includes the 2 CRC bytes)
7
+ CRC = CCITT-16 over PAYLOAD only, transmitted little-endian.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from enum import auto, Enum
13
+ from .exceptions import ProtocolError
14
+
15
+ STX = 0xF5
16
+
17
+ # CCITT-16 lookup table (ported from ccittcrc.h)
18
+ _CCITT_TABLE = [
19
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
20
+ 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
21
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
22
+ 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
23
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
24
+ 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
25
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
26
+ 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
27
+ 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
28
+ 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
29
+ 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
30
+ 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
31
+ 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
32
+ 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
33
+ 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
34
+ 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
35
+ 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
36
+ 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
37
+ 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
38
+ 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
39
+ 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
40
+ 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
41
+ 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
42
+ 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
43
+ 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
44
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
45
+ 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
46
+ 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
47
+ 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
48
+ 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
49
+ 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
50
+ 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,
51
+ ]
52
+
53
+
54
+ def calc_crc(data: bytes) -> int:
55
+ """Compute CCITT-16 CRC (initial value 0xFFFF)."""
56
+ crc = 0xFFFF
57
+ for byte in data:
58
+ temp = ((crc >> 8) ^ byte) & 0xFF
59
+ crc = _CCITT_TABLE[temp] ^ ((crc << 8) & 0xFFFF)
60
+ return crc
61
+
62
+
63
+ def build_frame(payload: bytes) -> bytes:
64
+ """Wrap payload in a protocol frame (STX + length + XOR-check + payload + CRC)."""
65
+ length = len(payload) + 2 # +2 for CRC bytes
66
+ len_l = length & 0xFF
67
+ len_h = (length >> 8) & 0xFF
68
+ crc = calc_crc(payload)
69
+ return bytes([
70
+ STX,
71
+ len_l, len_h,
72
+ len_l ^ 0xFF, len_h ^ 0xFF,
73
+ *payload,
74
+ crc & 0xFF, (crc >> 8) & 0xFF,
75
+ ])
76
+
77
+
78
+ def parse_frame(raw: bytes) -> bytes:
79
+ """Validate a complete raw frame and return the payload (without CRC).
80
+
81
+ Raises ProtocolError on any validation failure.
82
+ The caller is responsible for passing a complete frame starting with STX.
83
+ """
84
+ if len(raw) < 7:
85
+ raise ProtocolError("Frame too short")
86
+ if raw[0] != STX:
87
+ raise ProtocolError(f"Bad STX: 0x{raw[0]:02X}")
88
+ len_l, len_h = raw[1], raw[2]
89
+ if raw[3] != (len_l ^ 0xFF) or raw[4] != (len_h ^ 0xFF):
90
+ raise ProtocolError("Length XOR check failed")
91
+ declared_len = len_l | (len_h << 8)
92
+ if len(raw) != 5 + declared_len:
93
+ raise ProtocolError(f"Frame length mismatch: expected {5 + declared_len}, got {len(raw)}")
94
+ payload = raw[5: 5 + declared_len - 2]
95
+ crc_received = raw[-2] | (raw[-1] << 8)
96
+ crc_calc = calc_crc(payload)
97
+ if crc_calc != crc_received:
98
+ raise ProtocolError(f"CRC mismatch: calculated 0x{crc_calc:04X}, received 0x{crc_received:04X}")
99
+ return payload
100
+
101
+
102
+ class _State(Enum):
103
+ WAIT4STX = auto()
104
+ WAIT4LEN = auto()
105
+ RECEIVING = auto()
106
+
107
+
108
+ class FrameParser:
109
+ """Stateful incremental frame parser — mirrors the C implementation exactly."""
110
+
111
+ def __init__(self) -> None:
112
+ self.reset()
113
+
114
+ def reset(self) -> None:
115
+ self._state = _State.WAIT4STX
116
+ self._buf: list[int] = []
117
+ self._req_len = 0
118
+
119
+ def feed(self, data: bytes) -> list[bytes]:
120
+ """Feed bytes into the parser; returns a list of complete payload bytes objects."""
121
+ completed: list[bytes] = []
122
+ for byte in data:
123
+ if self._state is _State.WAIT4STX:
124
+ if byte == STX:
125
+ self._buf = []
126
+ self._state = _State.WAIT4LEN
127
+
128
+ elif self._state is _State.WAIT4LEN:
129
+ self._buf.append(byte)
130
+ if len(self._buf) == 4:
131
+ len_l, len_h, chk_l, chk_h = self._buf
132
+ if len_l == (chk_l ^ 0xFF) and len_h == (chk_h ^ 0xFF):
133
+ self._req_len = len_l | (len_h << 8)
134
+ self._buf = []
135
+ self._state = _State.RECEIVING
136
+ else:
137
+ self._state = _State.WAIT4STX
138
+
139
+ elif self._state is _State.RECEIVING:
140
+ self._buf.append(byte)
141
+ if len(self._buf) == self._req_len:
142
+ raw_payload = bytes(self._buf)
143
+ self._state = _State.WAIT4STX
144
+ payload_data = raw_payload[:-2]
145
+ crc_received = raw_payload[-2] | (raw_payload[-1] << 8)
146
+ if calc_crc(payload_data) == crc_received:
147
+ completed.append(payload_data)
148
+ return completed
pepper_c1/transport.py ADDED
@@ -0,0 +1,118 @@
1
+ """Transport layer abstraction for UART and TCP communication."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import socket
6
+ import time
7
+ from abc import ABC, abstractmethod
8
+
9
+ from .exceptions import TransportError
10
+ from .protocol import FrameParser, STX
11
+
12
+
13
+ class Transport(ABC):
14
+ """Abstract base for all transport backends."""
15
+
16
+ @abstractmethod
17
+ def write(self, data: bytes) -> None:
18
+ """Send raw bytes to the device."""
19
+
20
+ @abstractmethod
21
+ def _read_chunk(self, n: int) -> bytes:
22
+ """Read up to n bytes; may return fewer. Raises TransportError on failure."""
23
+
24
+ def read_frame(self, timeout: float = 2.0) -> bytes:
25
+ """Read bytes until a complete, valid frame payload is returned.
26
+
27
+ Returns the payload (without CRC) of the first valid frame received.
28
+ Raises TransportError on timeout or I/O error.
29
+ """
30
+ parser = FrameParser()
31
+ deadline = time.monotonic() + timeout
32
+ while time.monotonic() < deadline:
33
+ chunk = self._read_chunk(256)
34
+ if chunk:
35
+ completed = parser.feed(chunk)
36
+ if completed:
37
+ return completed[0]
38
+ raise TransportError("Timeout waiting for response frame")
39
+
40
+ @abstractmethod
41
+ def close(self) -> None:
42
+ """Release the underlying connection."""
43
+
44
+ def __enter__(self) -> "Transport":
45
+ return self
46
+
47
+ def __exit__(self, *_: object) -> None:
48
+ self.close()
49
+
50
+
51
+ class UARTTransport(Transport):
52
+ """UART transport using pyserial."""
53
+
54
+ def __init__(self, port: str, baudrate: int = 115200, timeout: float = 0.1,
55
+ post_open_delay: float = 2.0) -> None:
56
+ try:
57
+ import serial # type: ignore[import]
58
+ except ImportError as exc:
59
+ raise ImportError("pyserial is required for UARTTransport: pip install pyserial") from exc
60
+ try:
61
+ self._serial = serial.Serial(
62
+ port, baudrate=baudrate, timeout=timeout,
63
+ dsrdtr=False, rtscts=False,
64
+ )
65
+ self._serial.dtr = False
66
+ self._serial.rts = False
67
+ if post_open_delay > 0:
68
+ time.sleep(post_open_delay)
69
+ self._serial.reset_input_buffer()
70
+ except serial.SerialException as exc:
71
+ raise TransportError(f"Cannot open {port}: {exc}") from exc
72
+
73
+ def write(self, data: bytes) -> None:
74
+ try:
75
+ self._serial.write(data)
76
+ except Exception as exc:
77
+ raise TransportError(f"UART write error: {exc}") from exc
78
+
79
+ def _read_chunk(self, n: int) -> bytes:
80
+ try:
81
+ return self._serial.read(n)
82
+ except Exception as exc:
83
+ raise TransportError(f"UART read error: {exc}") from exc
84
+
85
+ def close(self) -> None:
86
+ if self._serial.is_open:
87
+ self._serial.close()
88
+
89
+
90
+ class TCPTransport(Transport):
91
+ """TCP transport using the standard socket library."""
92
+
93
+ def __init__(self, host: str, port: int, timeout: float = 2.0) -> None:
94
+ try:
95
+ self._sock = socket.create_connection((host, port), timeout=timeout)
96
+ self._sock.settimeout(0.1) # non-blocking reads inside read_frame loop
97
+ except OSError as exc:
98
+ raise TransportError(f"Cannot connect to {host}:{port}: {exc}") from exc
99
+
100
+ def write(self, data: bytes) -> None:
101
+ try:
102
+ self._sock.sendall(data)
103
+ except OSError as exc:
104
+ raise TransportError(f"TCP write error: {exc}") from exc
105
+
106
+ def _read_chunk(self, n: int) -> bytes:
107
+ try:
108
+ return self._sock.recv(n)
109
+ except socket.timeout:
110
+ return b""
111
+ except OSError as exc:
112
+ raise TransportError(f"TCP read error: {exc}") from exc
113
+
114
+ def close(self) -> None:
115
+ try:
116
+ self._sock.close()
117
+ except OSError:
118
+ pass
@@ -0,0 +1,139 @@
1
+ Metadata-Version: 2.1
2
+ Name: pepper_c1
3
+ Version: 0.1.0
4
+ Summary: Python driver for the Eccel Peeper C1 RFID reader (UART / TCP)
5
+ Author-email: Eccel Technology Ltd <marcin.baliniak@eccel.co.uk>
6
+ License: MIT
7
+ Project-URL: Homepage, https://www.eccel.co.uk
8
+ Project-URL: Product, https://eccel.co.uk/product/pepper-c1-usb/
9
+ Project-URL: Documentation, https://eccel.co.uk/product/pepper-c1-usb/
10
+ Keywords: rfid,nfc,mifare,desfire,icode,eccel,peeper,iso14443,iso15693
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.8
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Intended Audience :: Developers
22
+ Requires-Python: >=3.8
23
+ Description-Content-Type: text/markdown
24
+ Requires-Dist: pyserial>=3.5
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7; extra == "dev"
27
+ Requires-Dist: pytest-mock; extra == "dev"
28
+
29
+ # pepper_c1
30
+
31
+ Python driver for the **[Eccel Peeper C1](https://eccel.co.uk/product/pepper-c1-usb/)** RFID reader
32
+ made by [Eccel Technology Ltd](https://www.eccel.co.uk).
33
+
34
+ Supports communication over **UART** and **TCP**, and covers MIFARE Classic,
35
+ MIFARE Ultralight, MIFARE DESFire, and ICODE tag families.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ pip install pepper_c1
41
+ ```
42
+
43
+ ## Quick start
44
+
45
+ ```python
46
+ from pepper_c1 import PepperC1, UARTTransport, TCPTransport
47
+
48
+ # UART
49
+ with PepperC1(UARTTransport('/dev/ttyUSB0', baudrate=115200)) as reader:
50
+ print(reader.get_version())
51
+ print(reader.get_uid().hex())
52
+
53
+ # TCP
54
+ with PepperC1(TCPTransport('192.168.1.100', 1234)) as reader:
55
+ count = reader.get_tag_count()
56
+ if count:
57
+ uid = reader.activate_tag()
58
+ print(f"Tag UID: {uid.hex()}")
59
+ ```
60
+
61
+ ## MIFARE Classic example
62
+
63
+ ```python
64
+ from pepper_c1 import PepperC1, UARTTransport
65
+
66
+ with PepperC1(UARTTransport('/dev/ttyUSB0')) as reader:
67
+ reader.activate_tag()
68
+ block = reader.mf_read_block(4)
69
+ print(f"Block 4: {block.hex()}")
70
+ reader.mf_write_block(4, b'\x00' * 16)
71
+ reader.halt()
72
+ ```
73
+
74
+ ## MIFARE Ultralight example
75
+
76
+ ```python
77
+ from pepper_c1 import PepperC1, UARTTransport
78
+
79
+ with PepperC1(UARTTransport('/dev/ttyUSB0')) as reader:
80
+ reader.activate_tag()
81
+ page = reader.mfu_read_page(4)
82
+ print(f"Page 4: {page.hex()}")
83
+ ```
84
+
85
+ ## MIFARE DESFire example
86
+
87
+ ```python
88
+ from pepper_c1 import PepperC1, UARTTransport
89
+ from pepper_c1.commands import KEY_TYPE_AES128
90
+
91
+ with PepperC1(UARTTransport('/dev/ttyUSB0')) as reader:
92
+ # DESFire does not need activate_tag
93
+ reader.mfdf_select_app(bytes([0x00, 0x00, 0x00])) # PICC master app
94
+ # Load key into reader slot 0, then authenticate (key_no=0 on card, slot=0 in reader)
95
+ reader.set_key(0, KEY_TYPE_AES128, bytes(16)) # all-zero AES key
96
+ reader.mfdf_auth_aes(key_no=0, key_slot=0)
97
+ data = reader.mfdf_read_data(file_no=1, offset=0, length=32)
98
+ print(data.hex())
99
+ ```
100
+
101
+ ## Polling / async events
102
+
103
+ ```python
104
+ from pepper_c1 import PepperC1, UARTTransport
105
+
106
+ with PepperC1(UARTTransport('/dev/ttyUSB0')) as reader:
107
+ reader.set_polling(enable=True, interval_ms=500)
108
+ # Async tag events accumulate in reader.async_events
109
+ import time
110
+ time.sleep(5)
111
+ reader.set_polling(enable=False)
112
+ for event in reader.async_events:
113
+ print(f"Async event: {event.hex()}")
114
+ ```
115
+
116
+ ## Error handling
117
+
118
+ ```python
119
+ from pepper_c1 import PepperC1, UARTTransport, CommandError, TransportError
120
+
121
+ try:
122
+ with PepperC1(UARTTransport('/dev/ttyUSB0')) as reader:
123
+ reader.get_uid()
124
+ except TransportError as e:
125
+ print(f"Connection failed: {e}")
126
+ except CommandError as e:
127
+ print(f"Device error: {e}")
128
+ ```
129
+
130
+ ## Protocol
131
+
132
+ The Peeper C1 uses a binary framing protocol over serial or TCP:
133
+
134
+ ```
135
+ [0xF5] [LEN_L] [LEN_H] [LEN_L^0xFF] [LEN_H^0xFF] [PAYLOAD...] [CRC_L] [CRC_H]
136
+ ```
137
+
138
+ CRC is CCITT-16 computed over the payload only.
139
+ Low-level access is available via `PepperC1.send_command(cmd, data)`.
@@ -0,0 +1,10 @@
1
+ pepper_c1/__init__.py,sha256=z8opDf_jhCsrJZRFqgDENe6rQ18S1CTp7Cc-iaUduHk,717
2
+ pepper_c1/client.py,sha256=lUEte_KozKqLtRsrzP2B1P5ECQ0RUC8LCT-83m8Z3kI,13100
3
+ pepper_c1/commands.py,sha256=c8DUXpEa0taAI40Y_hbIwPuzf5nJUhZKi_Da0dAiAuY,3102
4
+ pepper_c1/exceptions.py,sha256=tFGnhUphDgMwGIkn9je1Tiw3DuKYs0yVRhrAP4Ni6OA,471
5
+ pepper_c1/protocol.py,sha256=Tn7dpVzmjaokm-fnJbJsKAPdC3psC8-ZfZwmlsSqWWI,6047
6
+ pepper_c1/transport.py,sha256=pmwrlPKyJl_81sMFS_puqY1ARbNLQrmYoEEKU626oec,3866
7
+ pepper_c1-0.1.0.dist-info/METADATA,sha256=PbnLYZZV7ZgVCIPrPza3vuh5KkrmcjDp3ZkLxcTXRrI,4331
8
+ pepper_c1-0.1.0.dist-info/WHEEL,sha256=BNRMDyzLkkcmlv0J8ppDQkk2VED33SesJDynr9ED1gc,91
9
+ pepper_c1-0.1.0.dist-info/top_level.txt,sha256=WDzEVpPDwdwToKTi0irqPqxkSogPBq329GnyZxbpEPg,10
10
+ pepper_c1-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.4)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ pepper_c1