-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhass_agent_sensor_dummy.py
executable file
·313 lines (207 loc) · 8.18 KB
/
hass_agent_sensor_dummy.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
#!/usr/bin/python3
## install packages:
## sudo apt install python3-influxdb python3-yaml
## pip3 install paho-mqtt
import sys
import time
import math
import influxdb
import socket
import datetime
import paho.mqtt.client as mqtt
import yaml
HOSTNAME= socket.gethostname()
conf={}
mqtt_client= None
mqtt_state_topic= 'undefined'
mqtt_avail_topic= 'undefined'
influx= None
def do_measurement():
## do fake measurment values
seconds= time.time() # time in seconds
# print( "t= ", seconds, 1.0*(seconds % 3600)/3600, 1.0*(seconds % 1800)/1800, 1.0*(seconds % 2400)/2400 )
temperature= 15.0 + 20.0* math.sin( 2.0*math.pi*(seconds % 3600)/3600 ) # one sine per hour
pressure= 900.0 + 100.0 * math.sin( 2.0*math.pi*(seconds % 1800)/1800 ) # one sine per half hour
humidity= 0.8 + .2 * math.sin ( 2.0*math.pi*(seconds % 2400)/2400 ) # 1.5 sine per hour
temperature= round( temperature, 1 )
pressure= round( pressure, 1)
humidity= round( humidity, 3 )
return temperature,pressure,humidity
def parse_config():
global conf
with open("mqtt-agent.yaml", 'r') as stream:
try:
conf = yaml.load(stream, Loader=yaml.SafeLoader)
except yaml.YAMLError as exc:
print(exc)
print("Unable to parse configuration file mqtt-agent.yaml")
sys.exit(1)
if not 'name' in conf:
# use hostname instead
conf['name']= HOSTNAME
if not 'location' in conf:
# use hostname instead
conf['location']= HOSTNAME
if 'mqttServer' in conf:
print( "Home Assistant MQTT enabled" )
if 'influxServer' in conf:
print( "InfluxDB enabled" )
#print( "conf: ", conf )
def mqtt_announce():
global mqtt_client, mqtt_state_topic, mqtt_avail_topic
print( "mqtt_announce" )
mqtt_state_topic= 'homeassistant/sensor/dummy_bme280_{}/state'.format(HOSTNAME)
mqtt_avail_topic= 'homeassistant/sensor/dummy_bme280_{}/avail'.format(HOSTNAME)
# temperature
topic= 'homeassistant/sensor/{}/temperature/config'.format(conf['name'])
strings= ['{']
strings.extend(['"device_class": "temperature"',', '])
strings.extend(['"name": "Temperature {}"'.format(conf['name']),', '])
strings.extend(['"unique_id": "temperature_{}"'.format(conf['name']),', '])
strings.extend(['"state_topic": "{}"'.format(mqtt_state_topic),', '])
strings.extend(['"availability_topic": "{}"'.format(mqtt_avail_topic),', '])
strings.extend(['"unit_of_measurement": "°C"',', '])
strings.extend(['"value_template": "{{ value_json.temperature }}"',', '])
strings.extend(['"expire_after": {}'.format(370)])
strings.extend(['}'])
payload= ''.join(strings)
print( "publish " + topic + " : " + payload )
mqtt_client.publish( topic, payload )
# pressure
topic= 'homeassistant/sensor/{}/pressure/config'.format(conf['name'])
strings= ['{']
strings.extend(['"device_class": "pressure"',', '])
strings.extend(['"name": "Pressure {}"'.format(conf['name']),', '])
strings.extend(['"unique_id": "pressure_{}"'.format(conf['name']),', '])
strings.extend(['"state_topic": "{}"'.format(mqtt_state_topic),', '])
strings.extend(['"availability_topic": "{}"'.format(mqtt_avail_topic),', '])
strings.extend(['"unit_of_measurement": "hPa"',', '])
strings.extend(['"value_template": "{{ value_json.pressure }}"',', '])
strings.extend(['"expire_after": {}'.format(370)])
strings.extend(['}'])
payload= ''.join(strings)
print( "publish " + topic + " : " + payload )
mqtt_client.publish( topic, payload )
# humidity
topic= 'homeassistant/sensor/{}/humidity/config'.format(conf['name'])
strings= ['{']
strings.extend(['"device_class": "humidity"',', '])
strings.extend(['"name": "Humidity {}"'.format(conf['name']),', '])
strings.extend(['"unique_id": "humidity_{}"'.format(conf['name']),', '])
strings.extend(['"state_topic": "{}"'.format(mqtt_state_topic),', '])
strings.extend(['"availability_topic": "{}"'.format(mqtt_avail_topic),', '])
strings.extend(['"unit_of_measurement": "%"',', '])
strings.extend(['"value_template": "{{ value_json.humidity }}"',', '])
strings.extend(['"expire_after": {}'.format(370)])
strings.extend(['}'])
payload= ''.join(strings)
print( "publish " + topic + " : " + payload )
mqtt_client.publish( topic, payload )
print( "publish ", mqtt_avail_topic, "online" )
mqtt_client.publish( mqtt_avail_topic, "online" )
## callbacks for mqtt
# The callback for when the client receives a CONNACK response from the server.
def mqtt_callback_connect( client, userdata, flags, rc ):
global mqtt_client, mqtt_state_topic
print("Connected with result code "+str(rc))
sys.stdout.flush()
(result, mid) = client.subscribe( "homeassistant/status" )
print("Got subscription result for "+"homeassistant/status"+":"+str(result))
mqtt_announce()
# The callback for when a PUBLISH message is received from the server.
def mqtt_callback_message(client, userdata, msg):
# ignore retained messages
if 1 == msg.retain:
return
print("Received command: "+msg.topic+" "+str(msg.payload) )
sys.stdout.flush()
if "homeassistant/status" == msg.topic:
print( "home assistant status message:", msg.topic )
# report ourselves as available to home assistant
if b'online' == msg.payload:
# re-report ourselves available to home assistant and report current state
mqtt_announce()
def mqtt_callback_disconnect(client, userdata, rc):
print( "Disconnect from MQTT" )
if rc != 0:
print( "Unexpected disconnection." )
def init_mqtt():
global conf, mqtt_client
mqtt_client = mqtt.Client()
mqtt_client.on_connect = mqtt_callback_connect
mqtt_client.on_message = mqtt_callback_message
mqtt_client.on_disconnect = mqtt_callback_disconnect
print("Starting mqtt-agent.py")
if conf['mqttUser'] and conf['mqttPass']:
mqtt_client.username_pw_set( username=conf['mqttUser'], password=conf['mqttPass'] )
mqtt_client.connect( conf['mqttServer'], conf['mqttPort'], 60 )
print("Listen to MQTT messages...")
sys.stdout.flush()
print( 'initialized mqtt' )
mqtt_client.loop_start()
def finalize_mqtt():
global mqtt_client, mqtt_avail_topic
print( "stopping MQTT" )
print( "publish ", mqtt_avail_topic, "offline" )
mqtt_client.publish( mqtt_avail_topic, "offline" )
mqtt_client.disconnect()
mqtt_client.loop_stop()
print( "MQTT stopped" )
def send_mqtt( temperature, pressure, humidity ):
global conf, mqtt_client, mqtt_state_topic
payload= '{ "temperature": %f, "pressure": %f, "humidity": %f }' % (temperature,pressure,humidity)
#print( "mqtt publish ", mqtt_state_topic, " : ", payload )
mqtt_client.publish( mqtt_state_topic, payload )
def init_influx():
global influx
# init Influx connection
influx = influxdb.InfluxDBClient( host= conf['influxServer'], port= conf['influxPort'], username= conf['influxUser'], password= conf['influxPass'], database=conf['influxDB'] )
#influx.create_database('temperature')
list= influx.get_list_database()
print( "list of influx databases")
print( list )
def send_influx( temperature, pressure, humidity ):
global influx
# send to influx db
jsonpoint = [
{
"measurement": "Dummy BME280 Sensor",
"tags": {
"source": conf['name'],
"hostname": HOSTNAME,
"location": conf['location'],
},
"time": "%s" %(datetime.datetime.utcnow()),
"fields": {
"temperature": temperature,
"pressure": pressure,
"humidity": humidity
}
},
]
#print( " json ", jsonpoint )
influx.write_points( jsonpoint )
def main():
global conf, mqtt_client, mqtt_state_topic
parse_config()
if 'mqttServer' in conf:
init_mqtt()
if 'influxServer' in conf:
init_influx()
try:
while(True):
temperature, pressure, humidity = do_measurement()
print( "Temperature : ", temperature, "C ", "Pressure : ", pressure, "hPa ", "Humidity : ", humidity*100.0, "%" )
if 'mqttServer' in conf:
send_mqtt( temperature, pressure, humidity )
if 'influxServer' in conf:
send_influx( temperature, pressure, humidity )
time.sleep(120)
except KeyboardInterrupt:
print( "Keyboard interrupt" )
except:
print( "unexpected error" )
if 'mqttServer' in conf:
finalize_mqtt()
if __name__=="__main__":
main()