c4002-python 0.2.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.
c4002/__init__.py ADDED
@@ -0,0 +1,33 @@
1
+ """
2
+ c4002-python — Python library for DFRobot C4002 24GHz mmWave radar sensor.
3
+
4
+ DISCLAIMER:
5
+ This is an independent, community-developed open-source library.
6
+ It is not affiliated with, maintained by, or endorsed by DFRobot.
7
+ """
8
+
9
+ from c4002.constants import (
10
+ LED_KEEP,
11
+ LED_OFF,
12
+ LED_ON,
13
+ LedMode,
14
+ MotionDirection,
15
+ ResolutionMode,
16
+ TargetState,
17
+ )
18
+ from c4002.sensor import C4002Sensor, CalibrationStatus, TelemetryData
19
+
20
+ __version__ = "0.2.0"
21
+ __all__ = [
22
+ "LED_KEEP",
23
+ "LED_OFF",
24
+ "LED_ON",
25
+ "C4002Sensor",
26
+ "CalibrationStatus",
27
+ "LedMode",
28
+ "MotionDirection",
29
+ "ResolutionMode",
30
+ "TargetState",
31
+ "TelemetryData",
32
+ ]
33
+
c4002/constants.py ADDED
@@ -0,0 +1,99 @@
1
+ """
2
+ Constants for DFRobot C4002 (SEN0691) 24GHz mmWave radar sensor.
3
+
4
+ DISCLAIMER:
5
+ This is an unofficial, community-developed driver and is not affiliated
6
+ with, maintained by, or endorsed by DFRobot.
7
+ """
8
+
9
+ from enum import IntEnum
10
+
11
+ # Frame Header sequence: 0xFA 0xF5 0xAA 0xA5
12
+ FRAME_HEADER_BYTES = bytes([0xFA, 0xF5, 0xAA, 0xA5])
13
+
14
+ # Frame Types
15
+ FRAME_TYPE_WRITE_REQUEST = 0x00
16
+ FRAME_TYPE_READ_REQUEST = 0x01
17
+ FRAME_TYPE_WRITE_RESPOND = 0x02
18
+ FRAME_TYPE_READ_RESPOND = 0x03
19
+ FRAME_TYPE_NOTIFICATION = 0x04
20
+
21
+ # Command IDs
22
+ CMD_RESTART = 0x00
23
+ CMD_FACTORY_RESET = 0x80
24
+ CMD_GET_VERSION = 0x82
25
+ CMD_SET_REPORT_PERIOD = 0x83
26
+ CMD_SET_TARGET_DISAPPEAR_DELAY = 0x84
27
+ CMD_SET_DETECT_RANGE = 0x86
28
+ CMD_SET_LIGHT_THRESHOLD = 0x88
29
+ CMD_CONFIG_OUT_MODE = 0xA0
30
+ CMD_SET_LED_MODE = 0xA1
31
+ CMD_ENV_CALIBRATION = 0x60
32
+ CMD_SET_DISTANCE_DOOR = 0x62
33
+ CMD_SET_DISTANCE_DOOR_THRESHOLD = 0x63
34
+ CMD_GET_AND_SET_RESOLUTION_MODE = 0x66
35
+
36
+ # Notification Sub-Commands
37
+ NOTE_RESULT_CMD = 0x60
38
+ NOTE_CALIBRATION_CMD = 0x03
39
+
40
+ # Response Status Codes
41
+ RESP_SUCCEED = 0x01
42
+ RESP_CMD_ERR = 0x02
43
+ RESP_AUTH_ERR = 0x03
44
+ RESP_BUSY = 0x04
45
+ RESP_PARAMS_ERR = 0x05
46
+ RESP_DATA_LEN_ERR = 0x06
47
+ RESP_INTERNAL_ERR = 0x07
48
+
49
+
50
+ class TargetState(IntEnum):
51
+ """Detection state of the target."""
52
+ NO_TARGET = 0
53
+ STATIC_PRESENCE = 1
54
+ MOTION = 2
55
+
56
+ @property
57
+ def label(self) -> str:
58
+ labels = {
59
+ TargetState.NO_TARGET: "No Target",
60
+ TargetState.STATIC_PRESENCE: "Static Presence (Sitting/Breathing)",
61
+ TargetState.MOTION: "Motion Detected",
62
+ }
63
+ return labels.get(self, "Unknown")
64
+
65
+
66
+ class MotionDirection(IntEnum):
67
+ """Direction of moving target relative to the sensor."""
68
+ AWAY = 0
69
+ NO_DIRECTION = 1
70
+ APPROACHING = 2
71
+
72
+ @property
73
+ def label(self) -> str:
74
+ labels = {
75
+ MotionDirection.AWAY: "Moving Away",
76
+ MotionDirection.NO_DIRECTION: "Stationary / No Direction",
77
+ MotionDirection.APPROACHING: "Approaching",
78
+ }
79
+ return labels.get(self, "Unknown")
80
+
81
+
82
+ class ResolutionMode(IntEnum):
83
+ """Distance gate resolution mode."""
84
+ RESOLUTION_80CM = 0x00 # Up to 15 gates, max 11.6m
85
+ RESOLUTION_20CM = 0x01 # Up to 25 gates, max 4.9m
86
+
87
+
88
+ class LedMode(IntEnum):
89
+ """LED operating mode for C4002 onboard LEDs."""
90
+ OFF = 0x00
91
+ ON = 0x01
92
+ KEEP = 0xFF
93
+
94
+
95
+ # Convenience aliases
96
+ LED_OFF = LedMode.OFF
97
+ LED_ON = LedMode.ON
98
+ LED_KEEP = LedMode.KEEP
99
+
c4002/sensor.py ADDED
@@ -0,0 +1,380 @@
1
+ """
2
+ Driver for DFRobot C4002 (SEN0691) 24GHz mmWave radar sensor.
3
+
4
+ DISCLAIMER:
5
+ This is an independent, unofficial community-developed Python library.
6
+ It is not affiliated with, maintained by, or endorsed by DFRobot.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import logging
12
+ import struct
13
+ import time
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ try:
18
+ import serial
19
+ except ImportError:
20
+ serial = None # type: ignore
21
+
22
+ try:
23
+ from RPi import GPIO
24
+ HAS_GPIO = True
25
+ except (ImportError, RuntimeError):
26
+ HAS_GPIO = False
27
+
28
+ from c4002.constants import (
29
+ CMD_ENV_CALIBRATION,
30
+ CMD_SET_DETECT_RANGE,
31
+ CMD_SET_LED_MODE,
32
+ CMD_SET_REPORT_PERIOD,
33
+ CMD_SET_TARGET_DISAPPEAR_DELAY,
34
+ FRAME_HEADER_BYTES,
35
+ FRAME_TYPE_NOTIFICATION,
36
+ FRAME_TYPE_WRITE_REQUEST,
37
+ NOTE_CALIBRATION_CMD,
38
+ NOTE_RESULT_CMD,
39
+ LedMode,
40
+ MotionDirection,
41
+ TargetState,
42
+ )
43
+
44
+ logger = logging.getLogger(__name__)
45
+
46
+
47
+ @dataclass
48
+ class TelemetryData:
49
+ """Parsed sensor telemetry frame."""
50
+ target_state: TargetState
51
+ target_state_name: str
52
+ presence_detected: bool
53
+ ambient_light_lux: float
54
+ gate_bitmask: int
55
+ presence_countdown_s: int
56
+ presence_distance_m: float
57
+ presence_energy: int
58
+ motion_distance_m: float
59
+ motion_speed_m_s: float
60
+ motion_energy: int
61
+ motion_direction: MotionDirection
62
+ motion_direction_name: str
63
+
64
+
65
+ @dataclass
66
+ class CalibrationStatus:
67
+ """Status during environmental background noise calibration."""
68
+ is_calibrating: bool
69
+ countdown_s: int
70
+
71
+
72
+ class C4002Sensor:
73
+ """
74
+ Python interface for DFRobot C4002 mmWave Human Presence Module (SEN0691).
75
+
76
+ Communicates via 115200 baud UART and optional digital GPIO OUT pin.
77
+ """
78
+
79
+ def __init__(
80
+ self,
81
+ port: str = "/dev/serial0",
82
+ baudrate: int = 115200,
83
+ out_pin: int | None = None,
84
+ timeout: float = 1.0,
85
+ ) -> None:
86
+ """
87
+ Initialize the sensor instance.
88
+
89
+ :param port: UART serial port path (default '/dev/serial0' for Raspberry Pi)
90
+ :param baudrate: Serial baud rate (default 115200)
91
+ :param out_pin: BCM GPIO pin number connected to C4002 OUT pin (None to disable)
92
+ :param timeout: Serial read timeout in seconds
93
+ """
94
+ self.port = port
95
+ self.baudrate = baudrate
96
+ self.out_pin = out_pin
97
+ self.timeout = timeout
98
+ self.ser: Any = None
99
+
100
+ if self.out_pin is not None:
101
+ if not HAS_GPIO:
102
+ logger.warning(
103
+ "RPi.GPIO is not available in this environment. OUT pin monitoring disabled."
104
+ )
105
+ self.out_pin = None
106
+ else:
107
+ GPIO.setwarnings(False)
108
+ GPIO.setmode(GPIO.BCM)
109
+ GPIO.setup(self.out_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
110
+
111
+ def connect(self) -> None:
112
+ """Open the serial port connection."""
113
+ if serial is None:
114
+ raise ImportError(
115
+ "pyserial is required to connect to hardware. Install it via: pip install pyserial"
116
+ )
117
+ self.ser = serial.Serial(self.port, self.baudrate, timeout=self.timeout)
118
+ self.ser.flushInput()
119
+ logger.info("Connected to C4002 on %s at %d baud", self.port, self.baudrate)
120
+
121
+ def close(self) -> None:
122
+ """Close serial port and clean up GPIO resources."""
123
+ if self.ser and hasattr(self.ser, "is_open") and self.ser.is_open:
124
+ self.ser.close()
125
+ logger.info("Closed serial port %s", self.port)
126
+ if self.out_pin is not None and HAS_GPIO:
127
+ GPIO.cleanup(self.out_pin)
128
+
129
+ def __enter__(self) -> C4002Sensor:
130
+ self.connect()
131
+ return self
132
+
133
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
134
+ self.close()
135
+
136
+ def read_out_pin(self) -> bool | None:
137
+ """
138
+ Read the digital OUT pin if configured.
139
+ :return: True if HIGH (presence detected), False if LOW (clear), or None if unconfigured.
140
+ """
141
+ if self.out_pin is not None and HAS_GPIO:
142
+ return GPIO.input(self.out_pin) == GPIO.HIGH
143
+ return None
144
+
145
+ @staticmethod
146
+ def verify_checksum(packet: bytes) -> bool:
147
+ """
148
+ Validate packet checksum: sum of bytes [0..N-3] & 0xFFFF == uint16 LE at [N-2..N-1].
149
+ """
150
+ if len(packet) < 8:
151
+ return False
152
+ calc = sum(packet[:-2]) & 0xFFFF
153
+ recv = packet[-2] | (packet[-1] << 8)
154
+ return calc == recv
155
+
156
+ @classmethod
157
+ def parse_packet(cls, packet: bytes) -> TelemetryData | CalibrationStatus | None:
158
+ """
159
+ Parse a raw binary frame without requiring an open serial port.
160
+
161
+ Frame Layout (32 bytes standard notification):
162
+ [0..3] Header (FA F5 AA A5)
163
+ [4..5] Total length (uint16 LE)
164
+ [6] Reserved (0x00)
165
+ [7] Pack type (0x04 = Notification)
166
+ [8] Command ID (0x60 = Result, 0x03 = Calibration)
167
+ [9] Response code (0x01 = Success)
168
+ [10..11] Inner data length (uint16 LE)
169
+ [12..N] Payload
170
+ [N+1..] Checksum (uint16 LE)
171
+ """
172
+ if len(packet) < 14:
173
+ return None
174
+ if not packet.startswith(FRAME_HEADER_BYTES):
175
+ return None
176
+ if not cls.verify_checksum(packet):
177
+ logger.debug("Packet checksum mismatch")
178
+ return None
179
+
180
+ pack_type = packet[7]
181
+ cmd = packet[8]
182
+
183
+ # Normal detection notification (type 0x04, cmd 0x60)
184
+ if pack_type == FRAME_TYPE_NOTIFICATION and cmd == NOTE_RESULT_CMD:
185
+ payload = packet[12:-2]
186
+ if len(payload) < 18:
187
+ return None
188
+
189
+ status_val = payload[0]
190
+ light_raw = payload[1] | (payload[2] << 8)
191
+ gate_bitmask = payload[3] | (payload[4] << 8) | (payload[5] << 16) | (payload[6] << 24)
192
+ countdown = payload[7] | (payload[8] << 8)
193
+ pres_dist_cm = payload[9] | (payload[10] << 8)
194
+ pres_energy = payload[11]
195
+ motion_dist_cm = payload[12] | (payload[13] << 8)
196
+ motion_speed_raw = struct.unpack('<h', bytes([payload[14], payload[15]]))[0]
197
+ motion_energy = payload[16]
198
+ motion_dir_val = payload[17]
199
+
200
+ target_state = TargetState(status_val) if status_val in TargetState._value2member_map_ else TargetState.NO_TARGET
201
+ direction = MotionDirection(motion_dir_val) if motion_dir_val in MotionDirection._value2member_map_ else MotionDirection.NO_DIRECTION
202
+
203
+ return TelemetryData(
204
+ target_state=target_state,
205
+ target_state_name=target_state.label,
206
+ presence_detected=target_state != TargetState.NO_TARGET,
207
+ ambient_light_lux=round(light_raw * 0.1, 1),
208
+ gate_bitmask=gate_bitmask,
209
+ presence_countdown_s=countdown,
210
+ presence_distance_m=round(pres_dist_cm * 0.01, 2),
211
+ presence_energy=pres_energy,
212
+ motion_distance_m=round(motion_dist_cm * 0.01, 2),
213
+ motion_speed_m_s=round(motion_speed_raw * 0.01, 2),
214
+ motion_energy=motion_energy,
215
+ motion_direction=direction,
216
+ motion_direction_name=direction.label,
217
+ )
218
+
219
+ # Environmental calibration progress notification (cmd 0x03)
220
+ if pack_type == FRAME_TYPE_NOTIFICATION and cmd == NOTE_CALIBRATION_CMD:
221
+ countdown = packet[12] | (packet[13] << 8)
222
+ return CalibrationStatus(is_calibrating=True, countdown_s=countdown)
223
+
224
+ return None
225
+
226
+ def read_packet(self) -> TelemetryData | CalibrationStatus | None:
227
+ """
228
+ Synchronously synchronize to the next frame header and read the full packet.
229
+ :return: TelemetryData, CalibrationStatus, or None on timeout.
230
+ """
231
+ if not self.ser or not hasattr(self.ser, "is_open") or not self.ser.is_open:
232
+ raise RuntimeError("Serial port is not connected. Call connect() first.")
233
+
234
+ header_buf = bytearray()
235
+ start = time.time()
236
+
237
+ # Synchronize to 4-byte header
238
+ while len(header_buf) < 4:
239
+ if time.time() - start > self.timeout:
240
+ return None
241
+ b = self.ser.read(1)
242
+ if not b:
243
+ continue
244
+ header_buf.append(b[0])
245
+ if len(header_buf) == 4 and bytes(header_buf) != FRAME_HEADER_BYTES:
246
+ header_buf.pop(0)
247
+
248
+ # Read 2-byte total length
249
+ len_bytes = self.ser.read(2)
250
+ if len(len_bytes) < 2:
251
+ return None
252
+ total_len = len_bytes[0] | (len_bytes[1] << 8)
253
+
254
+ if total_len < 14 or total_len > 128:
255
+ return None
256
+
257
+ # Read remaining packet body
258
+ remaining_len = total_len - 6
259
+ remaining = self.ser.read(remaining_len)
260
+ if len(remaining) < remaining_len:
261
+ return None
262
+
263
+ full_packet = bytes(header_buf + len_bytes + remaining)
264
+ return self.parse_packet(full_packet)
265
+
266
+ def start_env_calibration(self, delay_time: int = 10, cont_time: int = 30) -> None:
267
+ """
268
+ Trigger automatic environmental background noise calibration.
269
+ :param delay_time: Seconds before calibration starts (0-65535s)
270
+ :param cont_time: Duration of background measurement (15-65535s)
271
+ """
272
+ data = [
273
+ CMD_ENV_CALIBRATION,
274
+ 0x00, # Read/Write request
275
+ 0x09, 0x00, # Data length
276
+ delay_time & 0xFF, (delay_time >> 8) & 0xFF,
277
+ cont_time & 0xFF, (cont_time >> 8) & 0xFF,
278
+ 0x01
279
+ ]
280
+ self._send_frame(data, 9, FRAME_TYPE_WRITE_REQUEST)
281
+
282
+ def set_report_period(self, period_100ms: int = 10) -> None:
283
+ """
284
+ Set sensor telemetry report period in units of 100ms (10 = 1.0s).
285
+ """
286
+ data = [
287
+ CMD_SET_REPORT_PERIOD,
288
+ 0x00,
289
+ 0x05, 0x00,
290
+ period_100ms & 0xFF
291
+ ]
292
+ self._send_frame(data, 5, FRAME_TYPE_WRITE_REQUEST)
293
+
294
+ def set_detect_range(self, closest_cm: int = 0, farthest_cm: int = 1100) -> None:
295
+ """
296
+ Set minimum and maximum detection range in centimeters (0 - 1100 cm).
297
+ """
298
+ farthest = min(max(farthest_cm, 0), 1100)
299
+ closest = max(closest_cm, 0)
300
+ data = [
301
+ CMD_SET_DETECT_RANGE,
302
+ 0x00,
303
+ 0x08, 0x00,
304
+ closest & 0xFF, (closest >> 8) & 0xFF,
305
+ farthest & 0xFF, (farthest >> 8) & 0xFF
306
+ ]
307
+ self._send_frame(data, 8, FRAME_TYPE_WRITE_REQUEST)
308
+
309
+ def set_target_disappear_delay(self, delay_s: int = 1) -> None:
310
+ """
311
+ Set delay time in seconds before reporting target disappearance (0 - 65535s).
312
+ """
313
+ data = [
314
+ CMD_SET_TARGET_DISAPPEAR_DELAY,
315
+ 0x00,
316
+ 0x06, 0x00,
317
+ delay_s & 0xFF, (delay_s >> 8) & 0xFF
318
+ ]
319
+ self._send_frame(data, 6, FRAME_TYPE_WRITE_REQUEST)
320
+
321
+ def set_led(
322
+ self,
323
+ run_led: int | bool = LedMode.OFF,
324
+ out_led: int | bool = LedMode.OFF,
325
+ ) -> None:
326
+ """
327
+ Configure the onboard RUN (operation) and OUT (detection) LEDs.
328
+
329
+ :param run_led: LedMode.OFF (or False), LedMode.ON (or True), or LedMode.KEEP
330
+ :param out_led: LedMode.OFF (or False), LedMode.ON (or True), or LedMode.KEEP
331
+ """
332
+ run_val = int(run_led)
333
+ out_val = int(out_led)
334
+ data = [
335
+ CMD_SET_LED_MODE,
336
+ 0x00, # Read/Write request
337
+ 0x06, 0x00, # Data length = 6
338
+ run_val & 0xFF,
339
+ out_val & 0xFF,
340
+ ]
341
+ self._send_frame(data, 6, FRAME_TYPE_WRITE_REQUEST)
342
+
343
+ def set_run_led(self, state: int | bool) -> None:
344
+ """
345
+ Configure the onboard blue RUN (operation/power) LED.
346
+
347
+ :param state: LedMode.OFF (False) or LedMode.ON (True)
348
+ """
349
+ self.set_led(run_led=state, out_led=LedMode.KEEP)
350
+
351
+ def set_out_led(self, state: int | bool) -> None:
352
+ """
353
+ Configure the onboard OUT (detection indicator) LED.
354
+
355
+ :param state: LedMode.OFF (False) or LedMode.ON (True)
356
+ """
357
+ self.set_led(run_led=LedMode.KEEP, out_led=state)
358
+
359
+ def turn_off_leds(self) -> None:
360
+ """Convenience method to turn off both onboard LEDs (stealth/dark mode)."""
361
+ self.set_led(run_led=LedMode.OFF, out_led=LedMode.OFF)
362
+
363
+
364
+ def _send_frame(self, data: list[int], data_len: int, msg_type: int) -> None:
365
+ """Internal helper to construct and transmit a validated command frame."""
366
+ total_len = data_len + 10
367
+ frame = bytearray([
368
+ FRAME_HEADER_BYTES[0], FRAME_HEADER_BYTES[1],
369
+ FRAME_HEADER_BYTES[2], FRAME_HEADER_BYTES[3],
370
+ total_len & 0xFF, (total_len >> 8) & 0xFF,
371
+ 0x00, msg_type
372
+ ])
373
+ frame.extend(data)
374
+ checksum = sum(frame) & 0xFFFF
375
+ frame.append(checksum & 0xFF)
376
+ frame.append((checksum >> 8) & 0xFF)
377
+
378
+ if self.ser and hasattr(self.ser, "is_open") and self.ser.is_open:
379
+ self.ser.flushInput()
380
+ self.ser.write(frame)
@@ -0,0 +1,284 @@
1
+ Metadata-Version: 2.5
2
+ Name: c4002-python
3
+ Version: 0.2.0
4
+ Summary: Unofficial Python driver and tools for DFRobot C4002 (SEN0691) 24GHz mmWave radar sensor
5
+ Project-URL: Homepage, https://github.com/nobudev7/c4002-python
6
+ Project-URL: Documentation, https://github.com/nobudev7/c4002-python#readme
7
+ Project-URL: Issues, https://github.com/nobudev7/c4002-python/issues
8
+ Project-URL: Repository, https://github.com/nobudev7/c4002-python.git
9
+ Author: nobudev7
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: POSIX :: Linux
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Software Development :: Embedded Systems
23
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
24
+ Requires-Python: >=3.8
25
+ Requires-Dist: pyserial>=3.5
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=7.0; extra == 'dev'
28
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
29
+ Provides-Extra: gpio
30
+ Requires-Dist: rpi-gpio>=0.7.1; extra == 'gpio'
31
+ Description-Content-Type: text/markdown
32
+
33
+ # c4002-python
34
+
35
+ [![Test & Lint](https://github.com/nobudev7/c4002-python/actions/workflows/test.yml/badge.svg)](https://github.com/nobudev7/c4002-python/actions/workflows/test.yml)
36
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
37
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
38
+
39
+ Python driver and CLI tools for the **DFRobot C4002 (SEN0691) 24GHz mmWave Human Presence Detection Module**.
40
+
41
+ Provides robust UART packet framing, real-time telemetry decoding (static presence, motion distance, speed, direction, ambient light), automated room background noise calibration, and optional digital OUT pin monitoring on Raspberry Pi and other Linux systems.
42
+
43
+ ---
44
+
45
+ > [!IMPORTANT]
46
+ > **Disclaimer**: This is an independent open-source library. It is not affiliated with, maintained by, or endorsed by DFRobot. All product names, logos, and brands are property of their respective owners.
47
+
48
+ ---
49
+
50
+ ![DFRobot C4002 mmWave Sensor](docs/images/c4002_sensor.jpeg)
51
+
52
+ ## Features
53
+
54
+ * **Complete Telemetry Decoding**: Parses 32-byte binary notification frames from the C4002 sensor.
55
+ * **Static Presence**: Detects stationary humans (breathing, sitting) with distance (m) and signal energy (0–100).
56
+ * **Motion Tracking**: Measures distance (m), speed (m/s), signal energy (0–100), and direction (Approaching / Away).
57
+ * **Ambient Light**: Decodes onboard light sensor intensity (Lux).
58
+ * **Gate Bitmasks & Hold Timers**: Reports active distance gates and presence disappearance countdown.
59
+ * **Auto Environmental Calibration**: Built-in routine to sample room reflections and store the background noise floor, preventing false triggers.
60
+ * **Reliable Checksum Verification**: Validates 16-bit packet checksums to reject corrupted data.
61
+ * **Hardware Agnostic**: Tested on Raspberry Pi Zero W, but works with any Raspberry Pi and standard USB-to-UART TTL serial converter on Linux, macOS, or Windows.
62
+ * **Optional GPIO Monitoring**: Support for the module's digital OUT pin via `RPi.GPIO` (falls back gracefully if GPIO is unavailable).
63
+
64
+ ---
65
+
66
+ ## Hardware Wiring
67
+
68
+ The C4002 operates at **3.6V – 5.5V** with **3.3V TTL UART logic**. It can be powered directly from the Raspberry Pi 5V power rail.
69
+
70
+ <!-- ![Raspberry Pi Wiring Diagram](docs/images/wiring_diagram.png) -->
71
+ ```
72
+ Raspberry Pi GPIO Header DFRobot C4002
73
+ ┌─────────────────────────┐ ┌─────────────┐
74
+ │ Pin 2 [5V] ├───────────────┤ VIN │
75
+ │ Pin 6 [GND] ├───────────────┤ GND │
76
+ │ Pin 8 [GPIO 14 / TXD] ├───────────────┤ RX │
77
+ │ Pin 10 [GPIO 15 / RXD] ├───────────────┤ TX │
78
+ │ Pin 11 [GPIO 17] ├───────────────┤ OUT (opt) │
79
+ └─────────────────────────┘ └─────────────┘
80
+ ```
81
+
82
+ ### Pinout Table (Raspberry Pi 40-Pin Header)
83
+
84
+ | C4002 Pin | Raspberry Pi Pin | Header Pin # | Description |
85
+ | :--- | :--- | :--- | :--- |
86
+ | **VIN** | 5V Power | Pin 2 or 4 | Power supply (3.6V – 5.5V) |
87
+ | **GND** | Ground | Pin 6, 9, or 14 | Common ground |
88
+ | **TX** | GPIO 15 (RXD0) | Pin 10 | Sensor TX $\rightarrow$ Pi RXD |
89
+ | **RX** | GPIO 14 (TXD0) | Pin 8 | Sensor RX $\leftarrow$ Pi TXD |
90
+ | **OUT** *(Optional)* | GPIO 17 | Pin 11 | Digital presence indicator (HIGH = presence) |
91
+
92
+
93
+ ### Raspberry Pi Serial Port Setup
94
+
95
+ Ensure the hardware UART is enabled and the serial login console is disabled:
96
+
97
+ 1. Run `sudo raspi-config`
98
+ 2. Navigate to **Interface Options** $\rightarrow$ **Serial Port**
99
+ 3. "Would you like a login shell to be accessible over serial?" $\rightarrow$ Select **No**
100
+ 4. "Would you like the serial port hardware to be enabled?" $\rightarrow$ Select **Yes**
101
+ 5. Reboot the Raspberry Pi: `sudo reboot`
102
+
103
+ The primary serial port will be accessible at `/dev/serial0`.
104
+
105
+ ---
106
+
107
+ ## Installation
108
+
109
+ ### Direct Install via pip (No git clone required)
110
+
111
+ Install directly into your Python environment from GitHub:
112
+
113
+ ```bash
114
+ # Standard installation
115
+ pip install git+https://github.com/nobudev7/c4002-python.git
116
+
117
+ # With optional Raspberry Pi GPIO support
118
+ pip install "c4002-python[gpio] @ git+https://github.com/nobudev7/c4002-python.git"
119
+ ```
120
+
121
+ ### From Source (For Local Development)
122
+
123
+ ```bash
124
+ git clone https://github.com/nobudev7/c4002-python.git
125
+ cd c4002-python
126
+ pip install -e .
127
+ ```
128
+
129
+ To include optional Raspberry Pi GPIO support:
130
+
131
+ ```bash
132
+ pip install -e ".[gpio]"
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Quick Start
138
+
139
+ ```python
140
+ import time
141
+ from c4002 import C4002Sensor, TargetState
142
+
143
+ # Initialize sensor on default serial port and optional GPIO 17
144
+ sensor = C4002Sensor(port="/dev/serial0", baudrate=115200, out_pin=17)
145
+ sensor.connect()
146
+
147
+ try:
148
+ while True:
149
+ data = sensor.read_packet()
150
+ if data and not getattr(data, "is_calibrating", False):
151
+ print(f"State: {data.target_state_name} | Light: {data.ambient_light_lux} Lux")
152
+ if data.presence_detected:
153
+ print(f" Presence: {data.presence_distance_m} m (Energy: {data.presence_energy}/100)")
154
+ if data.target_state == TargetState.MOTION:
155
+ print(f" Motion: {data.motion_distance_m} m at {data.motion_speed_m_s} m/s ({data.motion_direction_name})")
156
+ time.sleep(0.5)
157
+ except KeyboardInterrupt:
158
+ sensor.close()
159
+ ```
160
+
161
+ Using as a context manager:
162
+
163
+ ```python
164
+ with C4002Sensor(port="/dev/serial0") as sensor:
165
+ data = sensor.read_packet()
166
+ if data:
167
+ print("Presence:", data.presence_detected)
168
+ ```
169
+
170
+ ---
171
+
172
+ ## Onboard LED Control (Dark / Stealth Mode)
173
+
174
+ The C4002 module includes two onboard LEDs:
175
+ * **Blue RUN LED**: Operation / power indicator (blinks or stays solid blue).
176
+ * **OUT LED**: Detection indicator (lights up when presence/motion is detected).
177
+
178
+ You can control or completely disable both LEDs via software over UART:
179
+
180
+ ```python
181
+ from c4002 import C4002Sensor, LedMode
182
+
183
+ with C4002Sensor(port="/dev/serial0") as sensor:
184
+ # Turn off both LEDs (stealth/bedroom mode)
185
+ sensor.turn_off_leds()
186
+
187
+ # Or control each LED individually:
188
+ sensor.set_run_led(False) # Turn off blue RUN LED
189
+ sensor.set_out_led(False) # Turn off detection OUT LED
190
+ sensor.set_run_led(True) # Turn blue RUN LED back on
191
+ sensor.set_led(run_led=LedMode.OFF, out_led=LedMode.OFF)
192
+ ```
193
+
194
+ In the example scripts, pass the `--led-off` flag:
195
+
196
+ ```bash
197
+ python3 examples/basic_monitor.py --led-off
198
+ python3 examples/minute_aggregator.py --led-off
199
+ ```
200
+
201
+ > [!NOTE]
202
+ > Like sensor detection thresholds, the LED state is stored in volatile memory on the radar module. When the sensor is power-cycled (power disconnected or Raspberry Pi rebooted), the module reverts to its hardware default (RUN LED ON). Call `turn_off_leds()` on startup in your script or daemon to ensure it stays dark.
203
+
204
+ ---
205
+
206
+ ## Environmental Background Noise Calibration
207
+
208
+
209
+ Because 24GHz radar waves detect micro-movements, reflective objects (metal furniture, fans, moving curtains) can cause false presence triggers in an empty room.
210
+
211
+ The sensor features built-in automatic background noise calibration:
212
+
213
+ ```bash
214
+ python3 examples/auto_calibrate.py
215
+ ```
216
+
217
+ 1. Run the script.
218
+ 2. Step out of the room within 10 seconds.
219
+ 3. Keep the room empty for 30 seconds while the sensor samples static background reflections and stores dynamic noise thresholds.
220
+
221
+ ---
222
+
223
+ ## 1-Minute Time-Series Logging (Aggregation)
224
+
225
+ To log presence data into a CSV file for charting without missing transient movements (e.g., someone walking through the room for 10 seconds):
226
+
227
+ ```bash
228
+ python3 examples/minute_aggregator.py --output presence_1min_timeseries.csv
229
+ ```
230
+
231
+ * Samples sensor telemetry continuously at 1 Hz and aggregates into 1-minute rows.
232
+ * Generates metrics ideal for charting:
233
+ * `occupancy_pct`: Occupancy percentage (`0.0% – 100.0%`) during the minute.
234
+ * `avg_distance_m`: Mean presence distance (calculated only when presence is active).
235
+ * `max_motion_energy`: Peak movement energy (`0 – 100`) recorded in that window.
236
+ * `avg_light_lux`: Mean ambient light level.
237
+
238
+ ---
239
+
240
+ ## Telemetry Data Reference
241
+
242
+ `sensor.read_packet()` returns a `TelemetryData` object with the following attributes:
243
+
244
+ | Attribute | Type | Unit / Range | Description |
245
+ | :--- | :--- | :--- | :--- |
246
+ | `target_state` | `TargetState` | Enum (`0`, `1`, `2`) | `NO_TARGET`, `STATIC_PRESENCE`, or `MOTION` |
247
+ | `target_state_name` | `str` | String | Human-readable state name |
248
+ | `presence_detected` | `bool` | `True` / `False` | `True` if state is presence or motion |
249
+ | `ambient_light_lux` | `float` | Lux (0.0 – 6553.5) | Onboard ambient light intensity |
250
+ | `presence_distance_m` | `float` | Meters | Distance to static presence target |
251
+ | `presence_energy` | `int` | `0` – `100` | Reflected signal energy of static target |
252
+ | `presence_countdown_s` | `int` | Seconds | Delay countdown before presence clears |
253
+ | `motion_distance_m` | `float` | Meters | Distance to moving target |
254
+ | `motion_speed_m_s` | `float` | m/s | Radial speed of moving target |
255
+ | `motion_energy` | `int` | `0` – `100` | Reflected signal energy of motion target |
256
+ | `motion_direction` | `MotionDirection` | Enum (`0`, `1`, `2`) | `AWAY`, `NO_DIRECTION`, or `APPROACHING` |
257
+ | `gate_bitmask` | `int` | Bitmask | Bit flags representing active distance gates |
258
+
259
+ ---
260
+
261
+ ## Running Unit Tests
262
+
263
+ Unit tests run without physical hardware using recorded raw telemetry packets:
264
+
265
+ ```bash
266
+ # Using standard Python unittest
267
+ PYTHONPATH=src python3 -m unittest discover -s tests -p "test_*.py"
268
+
269
+ # Or using pytest (if installed)
270
+ PYTHONPATH=src pytest -v tests/
271
+ ```
272
+
273
+ ---
274
+
275
+ ## References & Documentation
276
+
277
+ * [DFRobot C4002 Product Wiki (SEN0691)](https://wiki.dfrobot.com/sen0691)
278
+ * [DFRobot Official Arduino C4002 Library](https://github.com/DFRobot/DFRobot_C4002)
279
+
280
+ ---
281
+
282
+ ## License
283
+
284
+ This project is licensed under the [MIT License](LICENSE).
@@ -0,0 +1,7 @@
1
+ c4002/__init__.py,sha256=8cbtf-VUDyDl-Io9SdwA-cob649GYeHjGOCSlZFrj1k,670
2
+ c4002/constants.py,sha256=awlRfUg6hRstLWV_SUHr-_vqqUQY50FwWUQQcyr3Ecs,2411
3
+ c4002/sensor.py,sha256=-Q2GXvXkyV_MKJM6Ccxs06FZH7c3hVsc6W2Fa32FnnI,13165
4
+ c4002_python-0.2.0.dist-info/METADATA,sha256=VnDVvKUp4WIZAN6rZEQT57w4isONGYx2Rcqj1Q8ZK0o,11511
5
+ c4002_python-0.2.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
6
+ c4002_python-0.2.0.dist-info/licenses/LICENSE,sha256=zcx4XwMH4zmzm-lobER5pmZ5RvHuEjj3BHiUpIpzY7s,1061
7
+ c4002_python-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nobu
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.