This repository has been archived by the owner on Feb 23, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.py
227 lines (171 loc) · 5.58 KB
/
server.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import logging
import os
import paho.mqtt.client as mqtt
import pytoml
import socket
import stat
import subprocess
import sys
import shutil
import time
logging.basicConfig(
format='%(asctime)s [%(threadName)s] - [%(levelname)s] - %(message)s',
level=logging.INFO,
filename='serverlogs.log',
filemode='w'
)
_logger = logging.getLogger('SatConnectServer')
_logger.addHandler(logging.StreamHandler())
_mqttClient = None
_snipsConf = None
def checkRights():
global _running
if os.getuid() != 0:
_logger.error('Please start this tool with sudo')
_running = False
raise KeyboardInterrupt
def chmod():
st = os.stat('snipsRestart.sh')
os.chmod('snipsRestart.sh', st.st_mode | stat.S_IEXEC)
def getIp():
global MY_IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
MY_IP = s.getsockname()[0]
s.close()
_logger.info('Server ip: {}'.format(MY_IP))
def checkAndLoadSnipsConfigurations():
global _snipsConf, _running
if os.path.isfile('/etc/snips.toml'):
backupConfs()
with open('/etc/snips.toml') as confFile:
_snipsConf = pytoml.load(confFile)
_logger.info('Configurations loaded')
else:
_logger.error('Snips configuration file not found! Make sure to install Snips prior to use this tool')
_running = False
raise KeyboardInterrupt
connectMqtt()
def backupConfs():
if '--remove-backup' in sys.argv and os.path.isfile('backup.txt'):
_logger.info('Backup flagged for deletion, deleting...')
os.remove('backup.txt')
if not os.path.isfile('backup.txt'):
_logger.info('Creating configuration backup')
with open('backup.txt', 'w') as f:
for line in open('/etc/snips.toml'):
f.write(line)
_logger.info('Backup made')
else:
_logger.info('Backup already available')
def connectMqtt():
global _mqttClient, _coreIp, _running
try:
if _mqttClient is not None:
_mqttClient.loop_stop()
_mqttClient.disconnect()
_mqttClient = mqtt.Client()
_mqttClient.connect('localhost', 1883)
_mqttClient.on_message = onMessage
_mqttClient.subscribe('satConnect/server/checkAvailability')
_mqttClient.subscribe('satConnect/server/addSatellite')
_mqttClient.loop_start()
except socket.error:
_logger.error("Couldn't connect to mqtt localhost server, aborting")
_running = False
raise KeyboardInterrupt
def checkNameAvailability(name):
global _snipsConf
_logger.warning('Checking name availability for satellite "{}"'.format(name))
name = '{}@mqtt'.format(name)
if 'audio' not in _snipsConf['snips-hotword'] or name not in _snipsConf['snips-hotword']['audio']:
_logger.info('Satellite name "{}" is free'.format(name))
return True
_logger.warning('Satellite name "{}" is already declared'.format(name))
return False
def addSatellite(name):
global _snipsConf
_logger.info('Adding satellite')
try:
if 'bind' not in _snipsConf['snips-audio-server']:
_snipsConf['snips-audio-server']['bind'] = 'default@mqtt'
if 'audio' not in _snipsConf['snips-hotword']:
_snipsConf['snips-hotword']['audio'] = ['default@mqtt']
name = '{}@mqtt'.format(name)
if name not in _snipsConf['snips-hotword']['audio']:
_snipsConf['snips-hotword']['audio'].append(name)
f = open('/etc/snips.toml', 'w')
pytoml.dump(_snipsConf, f)
f.close()
restartSnips()
except:
_logger.error('Updating and restarting Snips after adding satellite failed')
_mqttClient.publish('satConnect/server/confUpdateFailed', json.dumps({}))
def removeSatellite(name):
global _snipsConf
_logger.info('Removing satellite')
try:
if 'audio' not in _snipsConf['snips-hotword']:
_snipsConf['snips-hotword']['audio'] = ['default@mqtt']
if name in _snipsConf['snips-hotword']['audio']:
del _snipsConf['snips-hotword']['audio'][name]
f = open('/etc/snips.toml', 'w')
pytoml.dump(_snipsConf, f)
f.close()
restartSnips()
except:
_logger.error('Updating and restarting Snips after satellite deletion failed')
_mqttClient.publish('satConnect/server/confUpdateFailed', json.dumps({}))
def restartSnips(afterConnect=True):
global _running
_logger.info('Restarting local Snips')
if afterConnect:
if _mqttClient is None:
connectMqtt()
subprocess.call(['./snipsRestart.sh'])
_mqttClient.publish('satConnect/server/confUpdated', json.dumps({}))
_logger.info('All done!')
_running = False
def onMessage(client, userData, message):
payload = json.loads(message.payload)
if message.topic == 'satConnect/server/checkAvailability':
if not checkNameAvailability(payload['name']):
_mqttClient.publish('satConnect/satellites/notAvailable', json.dumps({}))
else:
_mqttClient.publish('satConnect/satellites/available', json.dumps({}))
elif message.topic == 'satConnect/server/addSatellite':
addSatellite(payload['name'])
elif message.topic == 'satConnect/server/disconnect':
removeSatellite(payload['name'])
_running = False
if __name__ == '__main__':
_logger.info('Starting up Snips SatConnect Server')
_running = True
try:
checkRights()
chmod()
if '--restore-backup' in sys.argv:
_logger.info('Was asked to restore a backup of the configs')
if not os.path.isfile('backup.txt'):
_logger.error("Couldn't find any backup file, stopping...")
raise KeyboardInterrupt
else:
shutil.copy('backup.txt', '/etc/snips.toml')
_logger.info('Backup restored')
restartSnips(False)
else:
getIp()
checkAndLoadSnipsConfigurations()
while _running:
time.sleep(0.1)
except KeyboardInterrupt:
_running = False
pass
finally:
_logger.info('\nShutting down Snips SatConnect Server')
if _mqttClient is not None:
_mqttClient.loop_stop()
_mqttClient.disconnect()