-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsensors.py
1931 lines (1534 loc) · 56 KB
/
sensors.py
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import logging
import math
import os
import shlex
import signal
import struct
import subprocess
import time
from abc import abstractmethod, ABC
from enum import Enum, auto, IntEnum
# noinspection PyProtectedMember
from threading import Thread, Lock
from typing import Optional, List, Callable, Tuple
import RPi.GPIO as gpio
import cv2
import numpy as np
from raspberry_py.gpio import Component, CkPin
from raspberry_py.gpio.adc import AdcDevice
from raspberry_py.gpio.communication import LockingSerial
from raspberry_py.gpio.controls import TwoPoleButton
from raspberry_py.utils import IncrementalSampleAverager
class Photoresistor(Component):
"""
Photoresistor, to be connected via ADC.
"""
class State(Component.State):
"""
Photoresistor state.
"""
def __init__(
self,
light_level: Optional[float]
):
"""
Initialize the state.
:param light_level: Light level (0-100, unitless).
"""
self.light_level = light_level
def __eq__(
self,
other: object
) -> bool:
"""
Check equality with another state.
:param other: State.
:return: True if equal and False otherwise.
"""
if not isinstance(other, Photoresistor.State):
raise ValueError(f'Expected a {Photoresistor.State}')
return self.light_level == other.light_level
def __str__(
self
) -> str:
"""
Get string.
:return: String.
"""
return str(self.light_level)
def update_state(
self
):
"""
Update state.
"""
self.adc.update_state()
def get_light_level(
self
) -> float:
"""
Get light level.
:return: Light level.
"""
self.adc.update_state()
state: Photoresistor.State = self.state
return state.light_level
def __init__(
self,
adc: AdcDevice,
channel: int
):
"""
Initialize the photoresistor.
:param adc: Analog-to-digital converter.
:param channel: Analog-to-digital channel on which to monitor values from the photoresistor.
"""
super().__init__(Photoresistor.State(light_level=None))
self.adc = adc
self.channel = channel
# listen for events from the adc and update light level when they occur
self.adc.event(
lambda s: self.set_state(
Photoresistor.State(
light_level=s.channel_value[self.channel]
)
)
)
class Thermistor(Component):
"""
Thermistor, to be connected via ADC.
"""
class State(Component.State):
"""
Thermistor state.
"""
def __init__(
self,
temperature_f: Optional[float]
):
"""
Initialize the state.
:param temperature_f: Temperature (F).
"""
self.temperature_f = temperature_f
def __eq__(
self,
other: object
) -> bool:
"""
Check equality with another state.
:param other: State.
:return: True if equal and False otherwise.
"""
if not isinstance(other, Thermistor.State):
raise ValueError(f'Expected a {Thermistor.State}')
return self.temperature_f == other.temperature_f
def __str__(
self
) -> str:
"""
Get string.
:return: String.
"""
return f'{self.temperature_f} (F)'
@staticmethod
def convert_voltage_to_temperature(
input_voltage: float,
output_voltage: float
) -> float:
"""
Convert voltage to temperature.
:param input_voltage: Input voltage to thermistor.
:param output_voltage: Output voltage from thermistor.
:return: Temperature (F).
"""
rt = 10.0 * output_voltage / (input_voltage - output_voltage)
temp_k = 1 / (1 / (273.15 + 25) + math.log(rt / 10.0) / 3950.0)
temp_c = temp_k - 273.15
temp_f = temp_c * (9.0 / 5.0) + 32.0
return temp_f
def update_state(
self
):
"""
Update state.
"""
self.adc.update_state()
def get_temperature_f(
self
) -> float:
"""
Get temperature (F).
:return: Temperature (F).
"""
self.adc.update_state()
state: Thermistor.State = self.state
return state.temperature_f
def __init__(
self,
adc: AdcDevice,
channel: int
):
"""
Initialize the thermistor.
:param adc: Analog-to-digital converter.
:param channel: Analog-to-digital channel on which to monitor values from the thermistor.
"""
super().__init__(Thermistor.State(temperature_f=None))
self.adc = adc
self.channel = channel
# listen for events from the adc and update temperature when they occur
self.adc.event(
lambda s: self.set_state(
Thermistor.State(
temperature_f=self.convert_voltage_to_temperature(
input_voltage=self.adc.input_voltage,
output_voltage=adc.get_voltage(
digital_output=s.channel_value[self.channel]
)
)
)
)
)
class Hygrothermograph(Component):
"""
Hygrothermograph (DHT11).
"""
class State(Component.State):
"""
Hygrothermograph state.
"""
# noinspection PyArgumentList
class Status(Enum):
"""
State statuses.
"""
OK = auto()
CHECKSUM_ERROR = auto()
TIMEOUT_ERROR = auto()
INVALID_VALUE = auto()
def __init__(
self,
temperature_f: Optional[float],
humidity: Optional[float],
status: Status
):
"""
Initialize the state.
:param temperature_f: Temperature (F).
:param humidity: Humidity.
:param status: Status.
"""
self.temperature_f = temperature_f
self.humidity = humidity
self.status = status
def __eq__(
self,
other: object
) -> bool:
"""
Check equality with another state.
:param other: Other state.
:return: True if equal and False otherwise.
"""
if not isinstance(other, Hygrothermograph.State):
raise ValueError(f'Expected a {Hygrothermograph.State}')
return self.temperature_f == other.temperature_f and self.humidity == other.humidity and self.status == other.status
def __str__(self) -> str:
"""
Get string.
:return: String.
"""
return f'Temp (F): {self.temperature_f} (F), Humidity: {self.humidity}, Status: {self.status}'
WAKEUP_SECS = 0.02
TIMEOUT_SECS = 0.0001 # 100us
BIT_HIGH_TIME_THRESHOLD_SECS = 0.00005
def __init__(
self,
pin: int
):
"""
Initialize the hygrothermograph.
:param pin: GPIO pin connected to the SDA port of the hygrothermograph.
"""
super().__init__(Hygrothermograph.State(None, None, Hygrothermograph.State.Status.INVALID_VALUE))
self.pin = pin
self.bytes = [0, 0, 0, 0, 0]
def read(
self,
num_attempts: int = 1
):
"""
Read the sensor.
:param num_attempts: Number of attempts.
"""
for _ in range(0, num_attempts):
if self.__read_bytes__():
humidity = self.bytes[0] + self.bytes[1] * 0.1
temperature_c = self.bytes[2] + self.bytes[3] * 0.1
temperature_f = temperature_c * 9.0/5.0 + 32.0
checksum = (self.bytes[0] + self.bytes[1] + self.bytes[2] + self.bytes[3]) & 0xFF # only retain the lowest 8 bits
if self.bytes[4] == checksum:
state = Hygrothermograph.State(temperature_f, humidity, Hygrothermograph.State.Status.OK)
else:
state = Hygrothermograph.State(None, None, Hygrothermograph.State.Status.CHECKSUM_ERROR)
else:
state = Hygrothermograph.State(None, None, Hygrothermograph.State.Status.TIMEOUT_ERROR)
self.set_state(state)
if state.status == Hygrothermograph.State.Status.OK:
break
else:
time.sleep(0.1)
def __read_bytes__(
self
) -> bool:
"""
Read bytes from sensor.
:return: True if bytes were read and False if the read timed out.
"""
# output a high-low-high sequence to the component
gpio.setup(self.pin, gpio.OUT)
gpio.output(self.pin, gpio.HIGH)
time.sleep(0.5)
gpio.output(self.pin, gpio.LOW)
time.sleep(Hygrothermograph.WAKEUP_SECS)
gpio.output(self.pin, gpio.HIGH)
# wait for a low-high-low sequence input sequence
gpio.setup(self.pin, gpio.IN)
for value in [gpio.LOW, gpio.HIGH, gpio.LOW]:
if not self.wait_for(value):
return False
# read each byte bit-by-bit
self.bytes = [0, 0, 0, 0, 0]
bit_mask = 0x80 # 10000000
byte_idx = 0
for _ in range(0, 8 * len(self.bytes)):
# the chip communicates a 1 or 0 back to us by means of staying high for a long (1) or short (0) interval of
# time. wait for the high signal.
if not self.wait_for(gpio.HIGH):
return False
# now, time how long it stays high.
high_start = time.time()
if not self.wait_for(gpio.LOW):
return False
# if the time spent high exceeds the threshold, then record a 1 in the current bit location.
if time.time() - high_start > self.BIT_HIGH_TIME_THRESHOLD_SECS:
self.bytes[byte_idx] |= bit_mask
# shift mask to next bit or reset it to first bit if we're moving to the next byte
bit_mask >>= 1
if bit_mask == 0:
bit_mask = 0x80
byte_idx += 1
gpio.setup(self.pin, gpio.OUT)
gpio.output(self.pin, gpio.HIGH)
return True
def wait_for(
self,
value: int
) -> bool:
"""
Wait for a GPIO value on the SDA pin.
:param value: Value to wait for.
:return: True if value was received within the timeout limit and False if the wait timed out.
"""
t = time.time()
while time.time() - t < self.TIMEOUT_SECS:
if gpio.input(self.pin) == value:
break
else:
return False
return True
class InfraredMotionSensor(Component):
"""
Infrared motion sensor (HC SR501).
"""
class State(Component.State):
"""
State of sensor.
"""
def __init__(
self,
motion_detected: bool
):
"""
Initialize the state.
:param motion_detected: Motion is detected.
"""
self.motion_detected = motion_detected
def __eq__(
self,
other: object
) -> bool:
"""
Check equality with another state.
:param other: Other state.
:return: True if equal and False otherwise.
"""
if not isinstance(other, InfraredMotionSensor.State):
raise ValueError(f'Expected a {InfraredMotionSensor.State}')
return self.motion_detected == other.motion_detected
def __str__(
self
) -> str:
"""
Get string.
:return: String.
"""
return f'Motion detected: {self.motion_detected}'
def __init__(
self,
sensor_pin: int
):
"""
Initialize the sensor.
:param sensor_pin: Sensor pin.
"""
super().__init__(InfraredMotionSensor.State(False))
self.sensor_pin = sensor_pin
gpio.setup(sensor_pin, gpio.IN)
gpio.add_event_detect(
self.sensor_pin,
gpio.BOTH,
callback=lambda channel: self.set_state(
InfraredMotionSensor.State(gpio.input(self.sensor_pin) == gpio.HIGH)
),
bouncetime=10
)
class UltrasonicRangeFinder(Component):
"""
Ultrasonic range finder (HC SR04).
"""
SPEED_OF_SOUND_METERS_PER_SECOND = 340.0
TRIGGER_TIME_SECONDS = 10.0 * 1e-6
ECHO_TIMEOUT_SECONDS = 0.01
class State(Component.State):
"""
State of sensor.
"""
def __init__(
self,
distance_cm: Optional[float]
):
"""
Initialize the state.
:param distance_cm: Distance from surface (cm).
"""
self.distance_cm = distance_cm
def __eq__(
self,
other: object
) -> bool:
"""
Check equality with another state.
:param other: Other state.
:return: True if equal and False otherwise.
"""
if not isinstance(other, UltrasonicRangeFinder.State):
raise ValueError(f'Expected a {UltrasonicRangeFinder.State}')
return self.distance_cm == other.distance_cm
def __str__(
self
) -> str:
"""
Get string.
:return: String.
"""
return 'Distance: ' + 'None' if self.distance_cm is None else f'{self.distance_cm:.2f} cm'
def measure_distance_once(
self
) -> Optional[float]:
"""
Measure distance to surface.
:return: Distance (cm), or None if distance was unavailable or invalid.
"""
# signal the sensor to take a measurement
gpio.output(self.trigger_pin, gpio.HIGH)
time.sleep(UltrasonicRangeFinder.TRIGGER_TIME_SECONDS)
gpio.output(self.trigger_pin, gpio.LOW)
# wait for the echo pin to flip to high
wait_start_time = time.time()
while time.time() - wait_start_time < UltrasonicRangeFinder.ECHO_TIMEOUT_SECONDS:
if gpio.input(self.echo_pin) == gpio.HIGH:
echo_start_time = time.time()
break
else:
self.set_state(UltrasonicRangeFinder.State(distance_cm=None))
return None
# mark the time and wait for the echo pin to flip to low
while time.time() - echo_start_time < UltrasonicRangeFinder.ECHO_TIMEOUT_SECONDS:
if gpio.input(self.echo_pin) == gpio.LOW:
echo_end_time = time.time()
break
else:
self.set_state(UltrasonicRangeFinder.State(distance_cm=None))
return None
# measure the time that the echo pin was high and calculate distance accordingly
echo_time_seconds = echo_end_time - echo_start_time
total_distance_m = UltrasonicRangeFinder.SPEED_OF_SOUND_METERS_PER_SECOND * echo_time_seconds
surface_distance_cm = total_distance_m * 100.0 / 2.0
self.set_state(UltrasonicRangeFinder.State(distance_cm=surface_distance_cm))
return surface_distance_cm
def __measure_distance_repeatedly__(
self
):
"""
Measure distance repeatedly and update state accordingly. This will continue to measure until
`continue_measuring_distance` becomes False. This is not intended to be called directly; instead, call
`start_measuring_distance` and `stop_measuring_distance`.
"""
while self.continue_measuring_distance:
self.measure_distance_once()
time.sleep(self.measure_sleep_seconds)
def start_measuring_distance(
self
):
"""
Start measuring distance.
"""
self.stop_measuring_distance()
self.continue_measuring_distance = True
self.measure_distance_repeatedly_thread.start()
def stop_measuring_distance(
self
):
"""
Stop measuring distance.
"""
if self.measure_distance_repeatedly_thread.is_alive():
self.continue_measuring_distance = False
self.measure_distance_repeatedly_thread.join()
def __init__(
self,
trigger_pin: int,
echo_pin: int,
measurements_per_second: float
):
"""
Initialize the sensor.
:param trigger_pin: Trigger pin.
:param echo_pin: Echo pin.
:param measurements_per_second: Measurements per second.
"""
super().__init__(UltrasonicRangeFinder.State(None))
self.trigger_pin = trigger_pin
self.echo_pin = echo_pin
self.measurements_per_second = measurements_per_second
self.measure_sleep_seconds = 1.0 / self.measurements_per_second
self.continue_measuring_distance = True
self.measure_distance_repeatedly_thread = Thread(target=self.__measure_distance_repeatedly__)
gpio.setup(trigger_pin, gpio.OUT, initial=gpio.LOW)
gpio.setup(self.echo_pin, gpio.IN)
class Camera(Component):
"""
Camera.
"""
class DetectedFace:
"""
Detected face.
"""
def __init__(
self,
center_x: float,
center_y: float,
top_left_corner_x: float,
top_left_corner_y: float,
width: float,
height: float
):
"""
Initialize face.
:param center_x: Center x.
:param center_y: Center y.
:param top_left_corner_x: Top-left corner x.
:param top_left_corner_y: Top-left corner y.
:param width: Width.
:param height: Height.
"""
self.center_x = center_x
self.center_y = center_y
self.top_left_corner_x = top_left_corner_x
self.top_left_corner_y = top_left_corner_y
self.width = width
self.height = height
class State(Component.State):
"""
Camera state.
"""
def __init__(
self
):
"""
Not used.
"""
def __eq__(self, other: object) -> bool:
"""
Not used.
"""
return False
def __str__(self) -> str:
"""
Not used.
"""
return ''
def multiply_resolution(
self,
factor: int
):
"""
Multiply the frame width.
:param factor: Factor by which to multiply the frame width.
"""
with self.camera_lock:
width = self.width * factor
height = int(width * self.height_width_ratio)
self.camera.release()
self.camera = cv2.VideoCapture(self.device, cv2.CAP_V4L)
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
def get_frame_resolution(
self
) -> Tuple[float, float]:
"""
Get current frame resolution.
:return: 2-tuple of width/height.
"""
return self.camera.get(cv2.CAP_PROP_FRAME_WIDTH), self.camera.get(cv2.CAP_PROP_FRAME_HEIGHT)
def turn_on(
self
):
"""
Turn the camera on.
"""
with self.camera_lock:
self.on = True
def turn_off(
self
):
"""
Turn the camera off.
"""
with self.camera_lock:
self.on = False
def capture_image(
self
) -> str:
"""
Capture image.
:return: Base-64 encoded string of the byte content of the image.
"""
with self.camera_lock:
if self.on:
image_bytes = self.camera.read()[1]
else:
return ''
if self.run_face_detection:
detected_faces = self.detect_faces(image_bytes)
if self.circle_detected_faces:
image_bytes = self.circle_faces(image_bytes, detected_faces)
# encode as jpg -> base64 string, and strip the leading b' and trailing '
image_jpg_bytes = cv2.imencode('.jpg', image_bytes)[1]
base_64_string_jpg = str(base64.b64encode(image_jpg_bytes))[2:-1]
return base_64_string_jpg
def enable_face_detection(
self
):
"""
Enable face detection.
"""
self.run_face_detection = True
def disable_face_detection(
self
):
"""
Disable face detection.
"""
self.run_face_detection = False
def enable_face_circles(
self
):
"""
Enable face circles.
"""
self.circle_detected_faces = True
def disable_face_circles(
self
):
"""
Disable face circles.
"""
self.circle_detected_faces = False
def detect_faces(
self,
image_bytes: np.ndarray
) -> List[DetectedFace]:
"""
Detect faces within an image.
:param image_bytes: Image bytes within which to detect faces.
:return: List of detected faces.
"""
image_bytes_grayscale = cv2.cvtColor(image_bytes, cv2.COLOR_BGR2GRAY)
detected_faces = [
Camera.DetectedFace(
center_x=float(x + w / 2.0),
center_y=float(y + h / 2.0),
top_left_corner_x=x,
top_left_corner_y=y,
width=w,
height=h
)
for x, y, w, h in self.face_model.detectMultiScale(image_bytes_grayscale, 1.3, 5)
]
if self.face_detection_callback is not None and len(detected_faces) > 0:
self.face_detection_callback(detected_faces)
return detected_faces
@staticmethod
def circle_faces(
image_bytes: np.ndarray,
detected_faces: List[DetectedFace]
) -> np.ndarray:
"""
Circle detected faces within an image.
:param image_bytes: Image within which to circle faces.
:param detected_faces: List of detected faces.
:return: Image bytes with circles overlaid on faces.
"""
if len(detected_faces) > 0:
for detected_face in detected_faces:
image_bytes = cv2.circle(
image_bytes,
(int(detected_face.center_x), int(detected_face.center_y)),
int((detected_face.width + detected_face.height) / 4),
(0, 255, 0),
2
)
return image_bytes
def __init__(
self,
device: str,
width: int,
height: int,
fps: int,
run_face_detection: bool,
circle_detected_faces: bool,
face_detection_callback: Optional[Callable[[List[DetectedFace]], None]]
):
"""
Initialize camera.
:param device: Device (e.g., '/dev/video0').
:param width: Width.
:param height: Height.
:param fps: Frames per second.
:param run_face_detection: Whether to detect faces in captured images.
:param circle_detected_faces: Whether to circle detected faces in captured images.
:param face_detection_callback: Callback for face detections.
"""
super().__init__(Camera.State())
self.height_width_ratio = 0.75
if height / width != self.height_width_ratio:
width = height / self.height_width_ratio
self.device = device
self.width = width
self.height = height
self.fps = fps
self.run_face_detection = run_face_detection
self.circle_detected_faces = circle_detected_faces
self.face_detection_callback = face_detection_callback
self.camera = cv2.VideoCapture(self.device, cv2.CAP_V4L)
self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)
self.camera_lock = Lock()
self.face_model = cv2.CascadeClassifier(f'{os.path.dirname(__file__)}/haarcascade_frontalface_default.xml')
self.on = False
class MjpgStreamer(Component):
"""
A wrapper around the mjpg-streamer application found here: https://github.com/jacksonliam/mjpg-streamer
"""
class State(Component.State):
"""
State.
"""
def __init__(
self,
on: bool
):
"""
Initialize the state.
:param on: Whether the streamer is is.
"""
self.on = on
def __eq__(self, other: object) -> bool:
"""
Check equality.
:param other: Other.
:return: True if equal and False otherwise.
"""
if not isinstance(other, MjpgStreamer.State):
raise ValueError(f'Expected a {MjpgStreamer.State}')
return self.on == other.on
def __str__(self) -> str:
"""
Get string.
:return: String.
"""
return f'{self.on}'
def turn_on(
self
):
"""
Start the stream.
"""
self.set_state(MjpgStreamer.State(on=True))
def turn_off(