-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsensor.py
More file actions
418 lines (403 loc) · 11.8 KB
/
Copy pathsensor.py
File metadata and controls
418 lines (403 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
import logging
from homeassistant.components.sensor import (
SensorEntity,
SensorDeviceClass,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
UnitOfTemperature,
UnitOfMass,
UnitOfLength,
UnitOfSpeed,
UnitOfTime,
UnitOfInformation,
PERCENTAGE,
REVOLUTIONS_PER_MINUTE,
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from typing import Dict, Any # Import Dict and Any for type hinting
from .const import DOMAIN
from .coordinator import FlashforgeDataUpdateCoordinator
from .entity import FlashforgeEntity
_LOGGER = logging.getLogger(__name__)
# Centralized sensor definitions: key: (name, unit, device_class, state_class, is_top_level, is_percentage)
SENSOR_DEFINITIONS = {
# Top-Level
"code": ("Status Code", None, None, SensorStateClass.MEASUREMENT, True, False),
"message": ("Status Message", None, None, None, True, False),
# Detail section
"status": ("Status", None, None, None, False, False),
"firmwareVersion": ("Firmware Version", None, None, None, False, False),
"chamberTemp": (
"Chamber Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"chamberTargetTemp": (
"Chamber Target Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"leftTemp": (
"Left Nozzle Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"leftTargetTemp": (
"Left Nozzle Target Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"rightTemp": (
"Right Nozzle Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"rightTargetTemp": (
"Right Nozzle Target Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"platTemp": (
"Platform Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"platTargetTemp": (
"Platform Target Temperature",
UnitOfTemperature.CELSIUS,
SensorDeviceClass.TEMPERATURE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"printProgress": (
"Print Progress",
PERCENTAGE,
None,
SensorStateClass.MEASUREMENT,
False,
True,
),
"printDuration": (
"Print Duration",
UnitOfTime.SECONDS,
SensorDeviceClass.DURATION,
SensorStateClass.MEASUREMENT,
False,
False,
),
"estimatedTime": (
"Estimated Time Remaining",
UnitOfTime.SECONDS,
SensorDeviceClass.DURATION,
SensorStateClass.MEASUREMENT,
False,
False,
),
"cumulativeFilament": (
"Cumulative Filament",
UnitOfLength.METERS,
SensorDeviceClass.DISTANCE,
SensorStateClass.TOTAL_INCREASING,
False,
False,
),
"cumulativePrintTime": (
"Cumulative Print Time",
UnitOfTime.MINUTES,
SensorDeviceClass.DURATION,
SensorStateClass.TOTAL_INCREASING,
False,
False,
),
"fillAmount": (
"Fill Amount",
None,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
"leftFilamentType": ("Left Filament Type", None, None, None, False, False),
"rightFilamentType": ("Right Filament Type", None, None, None, False, False),
"estimatedLeftLen": (
"Estimated Left Length",
UnitOfLength.MILLIMETERS,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
"estimatedLeftWeight": (
"Estimated Left Weight",
UnitOfMass.GRAMS,
SensorDeviceClass.WEIGHT,
SensorStateClass.MEASUREMENT,
False,
False,
),
"estimatedRightLen": (
"Estimated Right Length",
UnitOfLength.MILLIMETERS,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
"estimatedRightWeight": (
"Estimated Right Weight",
UnitOfMass.GRAMS,
SensorDeviceClass.WEIGHT,
SensorStateClass.MEASUREMENT,
False,
False,
),
"chamberFanSpeed": (
"Chamber Fan Speed",
REVOLUTIONS_PER_MINUTE,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
"coolingFanSpeed": (
"Cooling Fan Speed",
REVOLUTIONS_PER_MINUTE,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
# "externalFanStatus": ("External Fan Status", None, None, None, False, False), # Replaced by binary_sensor
# "internalFanStatus": ("Internal Fan Status", None, None, None, False, False), # Replaced by binary_sensor
"tvoc": (
"TVOC",
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS,
SensorStateClass.MEASUREMENT,
False,
False,
),
"remainingDiskSpace": (
"Remaining Disk Space",
UnitOfInformation.GIGABYTES,
SensorDeviceClass.DATA_SIZE,
SensorStateClass.MEASUREMENT,
False,
False,
),
"zAxisCompensation": (
"Z Axis Compensation",
UnitOfLength.MILLIMETERS,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
# Add more as needed...
# "autoShutdown": ("Auto Shutdown Status", None, None, None, False, False), # Replaced by binary_sensor
"autoShutdownTime": (
"Auto Shutdown Time",
UnitOfTime.MINUTES,
SensorDeviceClass.DURATION,
SensorStateClass.MEASUREMENT,
False,
False,
),
"currentPrintSpeed": (
"Current Print Speed",
UnitOfSpeed.MILLIMETERS_PER_SECOND,
SensorDeviceClass.SPEED,
SensorStateClass.MEASUREMENT,
False,
False,
),
"flashRegisterCode": ("Flash Register Code", None, None, None, False, False),
"location": ("Location", None, None, None, False, False),
"macAddr": ("MAC Address", None, None, None, False, False),
"measure": ("Build Volume", None, None, None, False, False),
"nozzleCnt": (
"Nozzle Count",
None,
None,
SensorStateClass.MEASUREMENT,
False,
False,
),
"nozzleModel": ("Nozzle Model", None, None, None, False, False),
"nozzleStyle": (
"Nozzle Style",
None,
None,
None,
False,
False,
), # Changed state_class to None
"pid": ("Printer ID (PID)", None, None, None, False, False),
"polarRegisterCode": ("Polar Register Code", None, None, None, False, False),
"printSpeedAdjust": (
"Print Speed Adjustment",
PERCENTAGE,
None,
SensorStateClass.MEASUREMENT,
False,
False, # already a whole-number %, not a 0-1 fraction
),
"printable_files": (
"Printable Files Count",
"files",
None,
SensorStateClass.MEASUREMENT,
True,
False,
),
"x_position": (
"X Position",
UnitOfLength.MILLIMETERS,
None,
SensorStateClass.MEASUREMENT,
True,
False,
),
"y_position": (
"Y Position",
UnitOfLength.MILLIMETERS,
None,
SensorStateClass.MEASUREMENT,
True,
False,
),
"z_position": (
"Z Position",
UnitOfLength.MILLIMETERS,
None,
SensorStateClass.MEASUREMENT,
True,
False,
),
}
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up Flashforge sensors from a config entry."""
coordinator = hass.data[DOMAIN][entry.entry_id]
sensors_to_add = []
for attribute_key, (
name,
unit,
device_class,
state_class,
is_top_level,
is_percentage,
) in SENSOR_DEFINITIONS.items():
value_exists = False
if is_top_level and attribute_key in coordinator.data:
value_exists = True
elif (
not is_top_level
and coordinator.data.get("detail")
and attribute_key in coordinator.data["detail"]
):
value_exists = True
if value_exists:
sensors_to_add.append(
FlashforgeSensor(
coordinator,
attribute_key,
name,
unit,
device_class,
state_class,
is_top_level,
is_percentage,
)
)
else:
_LOGGER.debug(f"Skipping sensor {attribute_key}, no data found.")
if sensors_to_add:
async_add_entities(sensors_to_add)
class FlashforgeSensor(FlashforgeEntity, SensorEntity):
"""A sensor for one JSON field from the printer."""
def __init__(
self,
coordinator: FlashforgeDataUpdateCoordinator,
attribute_key: str,
name: str,
unit,
device_class,
state_class,
is_top_level: bool,
is_percentage: bool,
):
super().__init__(coordinator, name_suffix=name, unique_id_key=attribute_key)
self._attribute_key = attribute_key
self._is_top_level = is_top_level
self._is_percentage = is_percentage
self._attr_device_class = device_class
self._attr_state_class = state_class
self._attr_native_unit_of_measurement = PERCENTAGE if is_percentage else unit
self._attr_suggested_unit_of_measurement = PERCENTAGE if is_percentage else unit
self._attr_extra_state_attributes: Dict[str, Any] = {}
self._attr_native_value: Any = None
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._attr_available = self.coordinator.last_update_success
raw_value = None
if self.coordinator.data:
if self._is_top_level:
raw_value = self.coordinator.data.get(self._attribute_key)
elif self.coordinator.data.get("detail"):
raw_value = self.coordinator.data.get("detail", {}).get(
self._attribute_key
)
if self._attribute_key == "printable_files":
files_list = raw_value if isinstance(raw_value, list) else []
self._attr_native_value = len(files_list)
self._attr_extra_state_attributes["files"] = files_list
elif self._is_percentage and raw_value is not None:
try:
self._attr_native_value = round(float(raw_value) * 100.0, 1)
except (ValueError, TypeError) as e:
_LOGGER.warning(
"Could not convert value '%s' to percentage for sensor %s (%s). Error: %s",
raw_value,
self._attribute_key,
self.name,
e,
exc_info=True,
)
self._attr_native_value = None
else:
self._attr_native_value = raw_value
self.async_write_ha_state()
@property
def native_value(self) -> Any:
"""Return the sensor value."""
return self._attr_native_value