-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdht22_publisher.py
executable file
·137 lines (115 loc) · 4.07 KB
/
dht22_publisher.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
#!/usr/bin/env python
import configparser
import json
import logging
import os
import ssl
import sys
import time
from datetime import datetime
from logging.config import dictConfig
from pathlib import Path
from typing import Tuple
import Adafruit_DHT
import paho.mqtt.client as mqtt
log_level = 'DEBUG'
logging_configuration = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s %(levelname)s %(filename)s:%(lineno)d - %(funcName)s: %(message)s',
},
'short': {
'format': '%(filename)s:%(lineno)d - %(funcName)s: %(message)s',
},
},
'handlers': {
'default': {
'level': log_level,
'class': 'logging.StreamHandler',
'formatter': 'standard'
},
'syslog': {
'level': log_level,
'class': 'logging.handlers.SysLogHandler',
'address': '/dev/log',
'formatter': 'short',
},
},
'loggers': {
'': {
'handlers': ['default', 'syslog'],
'level': log_level,
'propagate': False
},
},
'root': {
'level': log_level,
'handlers': ['default', 'syslog'],
'propagate': False,
}
}
logger = logging.getLogger('dht22_publisher')
def get_config() -> configparser.ConfigParser:
config_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'config.ini'
)
if not Path(config_path):
sys.stderr.write('Cannot open config {}'.format(config_path))
raise FileNotFoundError
config = configparser.ConfigParser()
config.read(config_path)
return config
def build_mqtt_client(config: configparser.ConfigParser) -> mqtt.Client:
"""Specific for AWS IoT Broker"""
config_section = 'mqtt'
endpoint = config.get(config_section, 'endpoint')
ca_path = 'AmazonRootCA1.pem'
cert_path = config.get(config_section, 'cert_path')
key_path = config.get(config_section, 'key_path')
client_id = config.get(config_section, 'client_id')
port = int(config.get(config_section, 'port', fallback=8883))
mqtt_client = mqtt.Client(client_id=client_id)
mqtt_client.tls_set(ca_certs=ca_path,
certfile=cert_path,
keyfile=key_path,
cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_TLSv1_2)
mqtt_client.connect(endpoint, port)
return mqtt_client
def get_humidity_and_temperature(pin: int) -> Tuple[datetime, float, float]:
"""Temperature in celsius, humidity in percentage"""
timestamp = datetime.utcnow()
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302, pin)
return timestamp, humidity, temperature
def main():
dictConfig(logging_configuration)
config = get_config()
mqtt_client = build_mqtt_client(config)
mqtt_client.on_connect = lambda client, userdata, flags, rc: logger.debug('Connected to MQTT: %s'.format(rc))
mqtt_client.loop_start()
pin = int(config.get('main', 'dht22_pin'))
location = config.get('main', 'location')
topic = config.get('mqtt', 'topic')
sleep_interval = int(config.get('main', 'sleep_interval'))
while True:
timestamp, humidity, temperature = get_humidity_and_temperature(pin)
humidity = round(humidity, 3)
temperature = round(temperature, 3)
logger.debug("Data from DHT Sensor: %s, humitidity=%s, temperature=%s", timestamp, humidity, temperature)
data = {
'timestamp': timestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ'),
'location': location,
'temperature': round(temperature, 3),
'humidity': round(humidity, 3)
}
logger.debug('Going to send this data: %s', data)
logger.debug('Publishing...')
response = mqtt_client.publish(topic, json.dumps(data), qos=1)
response.wait_for_publish()
logger.debug('Published, going to sleep for %s seconds', sleep_interval)
time.sleep(sleep_interval)
if __name__ == '__main__':
main()