forked from bg1000/GarageQTPi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
288 lines (232 loc) · 9.62 KB
/
main.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
#!/usr/bin/python3
import os
import random
import yaml
import paho.mqtt.client as mqtt
import paho.mqtt
import re
import json
import logging
import voluptuous as vol
from voluptuous import Any
from lib.garage import GarageDoor
from lib.garage import TwoSwitchGarageDoor
DEFAULT_DISCOVERY = False
DEFAULT_DISCOVERY_PREFIX = "homeassistant"
DEFAULT_AVAILABILITY_TOPIC = "home-assistant/cover/availabilty"
DEFAULT_PAYLOAD_AVAILABLE = "online"
DEFAULT_PAYLOAD_NOT_AVAILABLE ="offline"
DEFAULT_STATE_MODE = "normally_open"
DEFAULT_INVERT_RELAY = False
print("GarageQTPi starting")
discovery_info = {}
garage_doors = []
# Update the mqtt state topic
def update_state(value, topic):
logging.info("State change triggered: %s -> %s" % (topic, value))
client.publish(topic, value, retain=True)
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
logging.info("Connected with result code: %s" % mqtt.connack_string(rc))
# notify subscribed clients that we are available
client.publish(availability_topic, payload_available, retain=True)
logging.info(
"Sent payload: '" +
CONFIG['mqtt']['payload_available'] +
"' to topic: '" +
CONFIG['mqtt']['availability_topic'] +
"'")
for config in CONFIG['doors']:
command_topic = config['command_topic']
logging.info("Listening for commands on %s" % command_topic)
client.subscribe(command_topic)
# Update each door state in case it changed while disconnected.
for door in garage_doors:
client.publish(door.state_topic, door.state, retain=True)
# Execute the specified command for a door
def execute_command(door, command):
try:
doorName = door.name
except BaseException:
doorName = door.id
logging.info("Executing command %s for door %s" % (command, doorName))
if command == "open" and door.state == 'Closed':
print('Commanded to OPEN when closed')
door.open()
elif command == "close" and door.state == 'Open':
print('Commanded to CLOSE when open')
door.close()
elif command == "stop": # NOT SUPPORTED
door.stop()
else:
logging.info("Invalid command: %s for state: %s" % (command, door.state))
CONFIG_SCHEMA = vol.Schema(
{
"logging": vol.Schema(
{
vol.Required("log_level"): Any('DEBUG', 'INFO', 'WARNING','ERROR', 'CRITICAL'),
vol.Required("show_timestamp"): bool
}),
"mqtt": vol.Schema(
{
vol.Required("host"): str,
vol.Required("port"): int,
vol.Required("user"): str,
vol.Required("password"): str,
vol.Optional("discovery", default = DEFAULT_DISCOVERY): Any(bool, None),
vol.Optional("discovery_prefix", default = DEFAULT_DISCOVERY_PREFIX): Any(str, None),
vol.Optional("availability_topic", default = DEFAULT_AVAILABILITY_TOPIC): Any(str, None),
vol.Optional("payload_available", default = DEFAULT_PAYLOAD_AVAILABLE): Any(str,None),
vol.Optional("payload_not_available", default = DEFAULT_PAYLOAD_NOT_AVAILABLE ): Any(str, None)
}
),
"doors": [vol.Schema(
{
vol.Required("id"): str,
vol.Optional("name"): Any(str, None),
vol.Required("relay"): int,
vol.Required("state"): int,
vol.Optional("open"): int,
vol.Optional("state_mode", default = DEFAULT_STATE_MODE): Any(None, 'normally_closed', 'normally_open'),
vol.Optional("invert_relay", default = DEFAULT_INVERT_RELAY): bool,
vol.Optional("state_topic"): str,
vol.Required("command_topic"): str
}
)]
})
#
# First look for config.yaml in /config which allows us to map a volume
# when running in docker. If not there look in the directory the script is
# running from. Using print statements here since logging isn't set up yet.
try:
with open('/config/config.yaml', 'r') as ymlfile:
file_CONFIG = yaml.load(ymlfile, Loader=yaml.FullLoader)
print("using configuration from /config/config.yaml")
except FileNotFoundError:
print("/config/config.yaml not found. Looking in script directory")
try:
with open(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'config.yaml'), 'r') as ymlfile:
file_CONFIG = yaml.load(ymlfile, Loader=yaml.FullLoader)
print("Using config.yaml from script directory")
except FileNotFoundError:
print("No config.yaml found. SensorScanner exiting.")
os._exit(1)
CONFIG = CONFIG_SCHEMA(file_CONFIG)
#
# setup logging and then log sucessful configuration validation
#
if CONFIG['logging']['show_timestamp']:
logging.basicConfig(format='%(asctime)s %(message)s',level=CONFIG["logging"]["log_level"])
else:
logging.basicConfig(level=CONFIG["logging"]["log_level"])
logging.info ("Config sucessfully validated against schema")
logging.info (json.dumps(CONFIG, indent = 4))
### SETUP MQTT ###
user = CONFIG['mqtt']['user']
password = CONFIG['mqtt']['password']
host = CONFIG['mqtt']['host']
port = int(CONFIG['mqtt']['port'])
if CONFIG['mqtt']['discovery'] is None:
discovery = DEFAULT_DISCOVERY
else:
discovery = CONFIG['mqtt']['discovery']
if CONFIG['mqtt']['discovery_prefix'] is None:
discovery_prefix = DEFAULT_DISCOVERY_PREFIX
else:
discovery_prefix = CONFIG['mqtt']['discovery_prefix']
#
# if availability values specified in config use them
# if not use defaults
#
if CONFIG['mqtt']['availability_topic'] is None:
availability_topic = DEFAULT_AVAILABILITY_TOPIC
else:
availability_topic = CONFIG['mqtt']['availability_topic']
if CONFIG['mqtt']['payload_available'] is None:
payload_available = DEFAULT_PAYLOAD_AVAILABLE
else:
payload_available = CONFIG['mqtt']['payload_available']
if CONFIG['mqtt']['payload_not_available'] is None:
payload_not_available = DEFAULT_PAYLOAD_NOT_AVAILABLE
else:
payload_not_available = CONFIG['mqtt']['payload_not_available']
# client = mqtt.Client(client_id="MQTTGarageDoor_" + binascii.b2a_hex(os.urandom(6)), clean_session=True, userdata=None, protocol=4)
client = mqtt.Client(client_id="MQTTGarageDoor_{:6s}".format(str(random.randint(
0, 999999))), clean_session=True, userdata=None, protocol=mqtt.MQTTv311)
client.on_connect = on_connect
client.username_pw_set(user, password=password)
# set a last will message so the broker will notify connected clients when
# we are not available
client.will_set(availability_topic, payload_not_available, retain=True)
logging.info(
"Set last will message: '" +
payload_not_available +
"' for topic: '" +
availability_topic +
"'")
client.connect(host, port, 60)
### SETUP END ###
### MAIN LOOP ###
if __name__ == "__main__":
# Create door objects and create callback functions
for doorCfg in CONFIG['doors']:
# If no name it set, then set to id
if 'name' not in doorCfg:
doorCfg['name'] = doorCfg['id']
elif doorCfg['name'] is None:
doorCfg['name'] = doorCfg['id']
# Sanitize id value for mqtt
doorCfg['id'] = re.sub(r'\W+', '', re.sub(r'\s', ' ', doorCfg['id']))
if discovery is True:
base_topic = discovery_prefix + "/cover/" + doorCfg['id']
config_topic = base_topic + "/config"
doorCfg['command_topic'] = base_topic + "/set"
doorCfg['state_topic'] = base_topic + "/state"
command_topic = doorCfg['command_topic']
state_topic = doorCfg['state_topic']
#
# If the open switch is specified use a two switch garage door
# otherwise use a door with only a closed switch.
# The interface is the same. The two switch garage door
# reports the states "open" and "closed"
#
if "open" in doorCfg and doorCfg["open"] is not None:
door = TwoSwitchGarageDoor(doorCfg)
else:
door = GarageDoor(doorCfg)
# Callback per door that passes a reference to the door
def on_message(client, userdata, msg, door=door):
execute_command(door, msg.payload.decode("utf-8"))
# Callback per door that passes the doors state topic
def on_state_change(value, topic=state_topic):
update_state(value, topic)
client.message_callback_add(command_topic, on_message)
# You can add additional listeners here and they will all be executed
# when the door state changes
door.onStateChange.addHandler(on_state_change)
# Publish initial door state
client.publish(state_topic, door.state, retain=True)
# Store Garage Door instance for use on reconnect
door.state_topic = state_topic
door.command_topic = command_topic
garage_doors.append(door)
# If discovery is enabled publish configuration
if discovery is True:
discovery_info["name"] = doorCfg['name']
discovery_info["command_topic"] = doorCfg['command_topic']
discovery_info["state_topic"] = doorCfg['state_topic']
discovery_info["availability_topic"] = availability_topic
discovery_info["payload_available"] = payload_available
discovery_info["payload_not_available"] = payload_not_available
client.publish(
config_topic,
json.dumps(discovery_info),
retain=True)
logging.info(
"Sent audodiscovery config: " +
json.dumps(
discovery_info,
indent=4))
logging.info("to topic: " + config_topic)
# Main loop
client.loop_forever()