Debian Codegraph @

src/mopeka_iot_ble/parser.py

raw
1 """Parser for Gmopeka_iot BLE advertisements.
2
3 Thanks to https://github.com/spbrogan/mopeka_pro_check for
4 help decoding the advertisements.
5
6 MIT License applies.
7 """
8
9 from __future__ import annotations
10
11 import logging
12 from dataclasses import dataclass
13 from bluetooth_data_tools import short_address
14 from bluetooth_sensor_state_data import BluetoothData
15 from home_assistant_bluetooth import BluetoothServiceInfo
16 from sensor_state_data import (
17 BinarySensorDeviceClass,
18 SensorDeviceClass,
19 SensorLibrary,
20 Units,
21 )
22
23 from .models import MediumType
24
25 _LOGGER = logging.getLogger(__name__)
26
27
28 # converting sensor value to height
29 MOPEKA_TANK_LEVEL_COEFFICIENTS = {
30 MediumType.PROPANE: (0.573045, -0.002822, -0.00000535),
31 MediumType.AIR: (0.153096, 0.000327, -0.000000294),
32 MediumType.FRESH_WATER: (0.600592, 0.003124, -0.00001368),
33 MediumType.WASTE_WATER: (0.600592, 0.003124, -0.00001368),
34 MediumType.LIVE_WELL: (0.600592, 0.003124, -0.00001368),
35 MediumType.BLACK_WATER: (0.600592, 0.003124, -0.00001368),
36 MediumType.RAW_WATER: (0.600592, 0.003124, -0.00001368),
37 MediumType.GASOLINE: (0.7373417462, -0.001978229885, 0.00000202162),
38 MediumType.DIESEL: (0.7373417462, -0.001978229885, 0.00000202162),
39 MediumType.LNG: (0.7373417462, -0.001978229885, 0.00000202162),
40 MediumType.OIL: (0.7373417462, -0.001978229885, 0.00000202162),
41 MediumType.HYDRAULIC_OIL: (0.7373417462, -0.001978229885, 0.00000202162),
42 }
43
44 MOPEKA_MANUFACTURER = 89
45 MOKPEKA_PRO_SERVICE_UUID = "0000fee5-0000-1000-8000-00805f9b34fb"
46
47
48 @dataclass
49 class MopekaDevice:
50 model: str
51 name: str
52 adv_length: int
53
54
55 DEVICE_TYPES = {
56 0x3: MopekaDevice("M1017", "Pro Check", 10),
57 0x4: MopekaDevice("Pro-200", "Pro-200", 10),
58 0x5: MopekaDevice("Pro H20", "Pro Check H2O", 10),
59 0x6: MopekaDevice("M1017", "Lippert BottleCheck", 10),
60 0x8: MopekaDevice("M1015", "Pro Plus", 10),
61 0x9: MopekaDevice("M1015", "Pro Plus with Cellular", 10),
62 0xA: MopekaDevice("TD40/TD200", "TD40/TD200", 10),
63 0xB: MopekaDevice("TD40/TD200", "TD40/TD200 with Cellular", 10),
64 0xC: MopekaDevice("M1017", "Pro Check Universal", 10),
65 }
66
67
68 def hex(data: bytes) -> str:
69 """Return a string object containing two hexadecimal digits for each byte in the instance."""
70 return "b'{}'".format("".join(f"\\x{b:02x}" for b in data)) # noqa: E231
71
72
73 def battery_to_voltage(battery: int) -> float:
74 """Convert battery value to voltage"""
75 return battery / 32.0
76
77
78 def battery_to_percentage(battery: int) -> float:
79 """Convert battery value to percentage."""
80 return round(max(0, min(100, (((battery / 32.0) - 2.2) / 0.65) * 100)), 1)
81
82
83 def temp_to_celsius(temp: int) -> int:
84 """Convert temperature value to celsius."""
85 return temp - 40
86
87
88 def tank_level_to_mm(tank_level: int) -> int:
89 """Convert tank level value to mm."""
90 return tank_level * 10
91
92
93 def tank_level_and_temp_to_mm(
94 tank_level: int, temp: int, medium: MediumType = MediumType.PROPANE
95 ) -> int:
96 """Get the tank level in mm for a given fluid type."""
97 coefs = MOPEKA_TANK_LEVEL_COEFFICIENTS[medium]
98 return int(tank_level * (coefs[0] + (coefs[1] * temp) + (coefs[2] * (temp**2))))
99
100
101 class MopekaIOTBluetoothDeviceData(BluetoothData):
102 """Data for Mopeka IOT BLE sensors."""
103
104 def __init__(self, medium_type: MediumType = MediumType.PROPANE) -> None:
105 super().__init__()
106 self._medium_type = medium_type
107
108 def _start_update(self, service_info: BluetoothServiceInfo) -> None:
109 """Update from BLE advertisement data."""
110 _LOGGER.debug(
111 "Parsing Mopeka IOT BLE advertisement data: %s, MediumType is: %s",
112 service_info,
113 self._medium_type,
114 )
115 manufacturer_data = service_info.manufacturer_data
116 service_uuids = service_info.service_uuids
117 address = service_info.address
118 if (
119 MOPEKA_MANUFACTURER not in manufacturer_data
120 or MOKPEKA_PRO_SERVICE_UUID not in service_uuids
121 ):
122 _LOGGER.debug("Not a Mopeka IOT BLE advertisement: %s", service_info)
123 return
124 data = manufacturer_data[MOPEKA_MANUFACTURER]
125 model_num = data[0]
126 if not (device_type := DEVICE_TYPES.get(model_num)):
127 _LOGGER.debug("Unsupported Mopeka IOT BLE advertisement: %s", service_info)
128 return
129 adv_length = device_type.adv_length
130 if len(data) != adv_length:
131 return
132
133 self.set_device_manufacturer("Mopeka IOT")
134 self.set_device_type(device_type.model)
135 self.set_device_name(f"{device_type.name} {short_address(address)}")
136 battery = data[1]
137 battery_voltage = battery_to_voltage(battery)
138 battery_percentage = battery_to_percentage(battery)
139 button_pressed = bool(data[2] & 0x80 > 0)
140 temp = data[2] & 0x7F
141 temp_celsius = temp_to_celsius(temp)
142 tank_level = ((int(data[4]) << 8) + data[3]) & 0x3FFF
143 tank_level_mm = tank_level_and_temp_to_mm(tank_level, temp, self._medium_type)
144 reading_quality = data[4] >> 6
145 accelerometer_x = data[8]
146 accelerometer_y = data[9]
147
148 self.update_predefined_sensor(SensorLibrary.TEMPERATURE__CELSIUS, temp_celsius)
149 self.update_predefined_sensor(
150 SensorLibrary.BATTERY__PERCENTAGE, battery_percentage
151 )
152 self.update_predefined_sensor(
153 SensorLibrary.VOLTAGE__ELECTRIC_POTENTIAL_VOLT,
154 battery_voltage,
155 name="Battery Voltage",
156 key="battery_voltage",
157 )
158 self.update_predefined_binary_sensor(
159 BinarySensorDeviceClass.OCCUPANCY,
160 button_pressed,
161 key="button_pressed",
162 name="Button pressed",
163 )
164 self.update_sensor(
165 "tank_level",
166 Units.LENGTH_MILLIMETERS,
167 tank_level_mm if reading_quality >= 1 else None,
168 SensorDeviceClass.DISTANCE,
169 "Tank Level",
170 )
171 self.update_sensor(
172 "accelerometer_x",
173 None,
174 accelerometer_x,
175 None,
176 "Position X",
177 )
178 self.update_sensor(
179 "accelerometer_y",
180 None,
181 accelerometer_y,
182 None,
183 "Position Y",
184 )
185 self.update_sensor(
186 "reading_quality_raw",
187 None,
188 reading_quality,
189 None,
190 "Reading quality raw",
191 )
192 self.update_sensor(
193 "reading_quality",
194 Units.PERCENTAGE,
195 round(reading_quality / 3 * 100),
196 None,
197 "Reading quality",
198 )
199 # Reading stars = (3-reading_quality) * "★" + (reading_quality * "⭐")