1+ #include " pir.hpp"
2+
3+ #include < zephyr/drivers/gpio.h>
4+ #include < zephyr/logging/log.h>
5+
6+ #include " buzzverse/motion_sensor.pb.h"
7+
8+ LOG_MODULE_REGISTER (MotionSensor, LOG_LEVEL_DBG);
9+
10+ MotionSensor::MotionSensor (const struct gpio_dt_spec * gpio_spec)
11+ : m_gpio_spec(gpio_spec) {}
12+
13+ using Status = Sensor::Status;
14+
15+ Peripheral::Status MotionSensor::init () {
16+ if (!m_gpio_spec || !device_is_ready (m_gpio_spec->port )) {
17+ status = buzzverse_v1_Status_ComponentState_INITIALIZATION_FAILED;
18+ LOG_WRN (" MotionSensor: GPIO device not ready or spec invalid" );
19+ return Peripheral::Status::NOT_READY;
20+ }
21+
22+ int ret = gpio_pin_configure_dt (m_gpio_spec, GPIO_INPUT);
23+ if (ret != 0 ) {
24+ LOG_ERR (" MotionSensor: Failed to configure GPIO pin %d (err %d)" , m_gpio_spec->pin , ret);
25+ status = buzzverse_v1_Status_ComponentState_INITIALIZATION_FAILED;
26+ return Peripheral::Status::INIT_ERR;
27+ }
28+
29+ LOG_INF (" MotionSensor: GPIO ready on pin %d" , m_gpio_spec->pin );
30+ status = buzzverse_v1_Status_ComponentState_NORMAL;
31+ ready = true ;
32+ return Peripheral::Status::OK;
33+ }
34+
35+ Status MotionSensor::read_data (buzzverse_v1_MotionSensorData& data) const {
36+ int val = gpio_pin_get_dt (m_gpio_spec);
37+ if (val < 0 ) {
38+ LOG_ERR (" MotionSensor: GPIO read failed: %d" , val);
39+ return Status::READ_ERR;
40+ }
41+
42+ data.motion_detected = (val > 0 );
43+
44+ LOG_DBG (" MotionSensor: GPIO raw: %d, motion detected: %d" , val, data.motion_detected );
45+ return Status::OK;
46+ }
47+
48+ Status MotionSensor::get_packet (buzzverse_v1_Packet& packet) const {
49+ buzzverse_v1_MotionSensorData motion_data = buzzverse_v1_MotionSensorData_init_zero;
50+
51+ if (read_data (motion_data) != Sensor::Status::OK) {
52+ return Status::READ_ERR;
53+ }
54+
55+ packet = buzzverse_v1_Packet_init_default;
56+ packet.which_data = buzzverse_v1_Packet_motion_sensor_tag;
57+ packet.data .motion_sensor = motion_data;
58+ LOG_DBG (" Packet constructed with motion sensor data." );
59+ return Status::OK;
60+ }
61+
62+ void MotionSensor::get_status (buzzverse_v1_Status& status_message) const {
63+ status_message.motion_status = status;
64+ }
0 commit comments