-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathAM2302.py
More file actions
58 lines (45 loc) · 1.71 KB
/
AM2302.py
File metadata and controls
58 lines (45 loc) · 1.71 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
"""An Accessory for the AM2302 temperature and humidity sensor.
Assumes the DHT22 module is in a package called sensors.
Also, make sure pigpiod is running.
The DHT22 module was taken from
https://www.raspberrypi.org/forums/viewtopic.php?f=37&t=71336
"""
import asyncio
import time
import random
import pigpio
import sensors.DHT22 as DHT22
from pyhap.accessory import Accessory, Category
import pyhap.loader as loader
class AM2302(Accessory):
category = Category.SENSOR
def __init__(self, *args, pin=4, **kwargs):
super().__init__(*args, **kwargs)
self.pin = pin
self.temp_char = self.get_service("TemperatureSensor")\
.get_characteristic("CurrentTemperature")
self.humidity_char = self.get_service("HumiditySensor")\
.get_characteristic("CurrentRelativeHumidity")
self.sensor = DHT22.sensor(pigpio.pi(), pin)
def _set_services(self):
super()._set_services()
self.add_service(
loader.get_serv_loader().get("TemperatureSensor"))
self.add_service(
loader.get_serv_loader().get("HumiditySensor"))
def __getstate__(self):
state = super().__getstate__()
state["sensor"] = None
return state
def __setstate__(self, state):
self.__dict__.update(state)
self.sensor = DHT22.sensor(pigpio.pi(), self.pin)
async def run(self):
while not stop_event.is_set():
await asyncio.sleep(10)
self.sensor.trigger()
await acyncio.sleep(0.2)
t = self.sensor.temperature()
h = self.sensor.humidity()
self.temp_char.set_value(t)
self.humidity_char.set_value(h)