diff --git a/README.md b/README.md index d8782dfb..c261a37d 100644 --- a/README.md +++ b/README.md @@ -39,6 +39,7 @@ Hardware support is provided by specific GPIO, Sensor and Stream modules. It's e - HCSR04 ultrasonic range sensor (connected to the Raspberry Pi on-board GPIO) (`hcsr04`) - LM75 temperature sensor (`lm75`) - MCP3008 analog to digital converter (`mcp3008`) + - ADXl345 3-axis accelerometer up to ±16g (`adxl345`) ### Streams @@ -111,4 +112,4 @@ stream_modules: module: serial device: /dev/ttyUSB0 baud: 9600 -``` \ No newline at end of file +``` diff --git a/mqtt_io/modules/sensor/adxl345.py b/mqtt_io/modules/sensor/adxl345.py new file mode 100644 index 00000000..198657c0 --- /dev/null +++ b/mqtt_io/modules/sensor/adxl345.py @@ -0,0 +1,68 @@ +""" +ADXL345 Digital Accelerometer Sensor + +Mandatory: +- chip_addr + +Optional: +- output_g (set True if output in g). default:m*s² + +Output: +- x (in m*s²) +- y (in m*s²) +- z (in m*s²) +""" + +from json import dumps +from typing import cast + +from ...types import CerberusSchemaType, ConfigType, SensorValueType +from . import GenericSensor + +REQUIREMENTS = ("adxl345",) +CONFIG_SCHEMA: CerberusSchemaType = { + "chip_addr": dict(type="integer", required=True, empty=False), + "output_g": dict(type="boolean", required=False, empty=False), +} + + +class Sensor(GenericSensor): + """ + Implementation of Sensor class for the ADXL345 sensor. + """ + + SENSOR_SCHEMA: CerberusSchemaType = { + "type": dict( + type="string", + required=False, + empty=False, + default="all", + allowed=["all", "x", "y", "z"], + ) + } + + def setup_module(self) -> None: + # pylint: disable=import-outside-toplevel,attribute-defined-outside-init + # pylint: disable=import-error,no-member + from adxl345 import ADXL345 # type: ignore + + self.i2c_addr: int = self.config["chip_addr"] + self.adxl345 = ADXL345(self.i2c_addr) + + def get_value(self, sens_conf: ConfigType) -> SensorValueType: + sens_type = sens_conf["type"] + + if "output_g" in self.config and self.config["output_g"]: + all_axes = self.adxl345.get_axes(True) + else: + all_axes = self.adxl345.get_axes() + + return cast( + float, + dict( + x=all_axes["x"], + y=all_axes["y"], + z=all_axes["z"], + all_axes=dumps(all_axes), + )[sens_type], + )