-
Notifications
You must be signed in to change notification settings - Fork 0
/
CallOutRespond
executable file
·220 lines (167 loc) · 7.06 KB
/
CallOutRespond
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
#!/usr/bin/python3
# License GPL 2. Copyright Paul D. Gilbert, 2018
"""
Run on BTs gizmo to find gizmo at registration distribution and load BTconfig.
This progam should be set up to start automatically when the LED control
gizmo's system is booted. It needs a setting to find other modules, e.g.
export PYTHONPATH=/path/to/Vcourse/lib
Other configuration can also be done with this utility, but might typically be
done before registration.
Boat specific configuration for the gizmo ("FLEET" and "BT_ID" ) is written to BTconfig.
RC specific configuration ("RC_PORT" and "RC_IP") is also written to BTconfig.
GPS harware specific configuration is written to GPSconfig.
See CallOut for other details.
"""
import socket
import time
import json
#import logging
import smp
import LEDs
#logFormat ='(%(threadName)-9s) %(message)s'
#logging.basicConfig(level=logging.DEBUG, format=logFormat,)
#logging.basicConfig(level=logging.INFO, format=logFormat,)
def reportBTconfig() :
"""response to Registation udp broadcast 'report config' """
BTconfig.update({"hn": hn}) # config + hostname
try :
sockTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP
sockTCP.connect(REG) #Registration IP, port
l = smp.snd(sockTCP, str(BTconfig))
print(str(l))
print(str(BTconfig))
sockTCP.close()
except :
raise Exception('error in reportBTconfig')
LEDs.ok('green Roger.')
def restartBT() :
"""
This restarts the BT program. It is needed in the case where any config files have
changed, so that BT loads the new configuration/
"""
import os
import signal
import time
import sys
import subprocess
pidfile = os.getenv("HOME") + '/.BT.pid'
pid = ['', os.getenv("PWD")] # for case process is not running
try:
with open(pidfile, 'r') as f: pid = f.read().splitlines()
except:
print('pid file ' + pidfile+ ' read error. Process probably not running.')
try:
os.kill(int(pid[0]), signal.SIGTERM)
os.remove(pidfile)
time.sleep(5)
except:
print('kill failed. Process probably not running.')
print('Will attempt to start process in pwd.')
npid = subprocess.Popen('BT', cwd=pid[1]).pid
def resetBTconfig() :
"""
This is in response to Registation udp broadcast 'requestBTconfig' which means BT should
request a new BTconfig from Registation. This is a bit round-about,
but otherwise BT needs a TCP listening process.
"""
BTconfig.update({"hn": hn}) # config + hostname
try :
sockTCP = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP
#sockTCP.connect(("10.42.0.254", 9006)) #Registration IP, port
sockTCP.connect(REG) #Registration IP, port
l = smp.snd(sockTCP, str(BTconfig))
cf = eval(smp.rcv(sockTCP) ) # new config str to dict
#Next puts hn in echo, but also ensures a received conf does not accidentally
#cause a changed hn to be recorded in BTconfig. (In theory it would never be
#used, but is still confusing.)
cf.update({"hn": hn})
l = smp.snd(sockTCP, str(cf)) # echo
sockTCP.close()
except :
#return {}
raise Exception('error in resetBTconfig')
LEDs.ok('green Roger.')
return cf
################################################################################
if __name__ == '__main__':
######## init ########
LEDs.off('lights out')
shutdown = False
#REG = ("10.42.0.254", 9006) # Registration IP and port
path = './'
with open(path + 'REGconfig','r') as f: REGconfig = json.load(f)
REG = (REGconfig['REG_HOST'], REGconfig['REG_PORT'])
sockUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sockUDP.bind(('', 5005)) #UDP_IP, PORT
try: BTconfig = json.load(open('BTconfig'))
except : BTconfig = {}
# there may be the same boat # in two fleets, but bt+fl is unique
bt = BTconfig['BT_ID']
fl = BTconfig['FLEET']
btfl = bt + ',' + fl
hn = socket.gethostname()
try: GPSconfig = json.load(open('GPSconfig')) #Typically "127.0.0.1", 2947 is default port.
except : GPSconfig = {} #This is a problem, but it can be set by broadcast.
print('hn: ' + hn)
print('btfl: ' + btfl)
print('sockUDP: ' + str(sockUDP))
print('BTconfig: '+ str(BTconfig))
print('CallOutRespond init finished.')
######## run ########
while not shutdown:
# time.sleep(5) misses udp?
data, addr = sockUDP.recvfrom(1024) # buffer size is 1024 bytes
data = data.decode()
data = data.split("::")
called = data.pop(0)
request = data[0]
# in some cases there will be more sections in data
if (btfl in called or hn in called ) :
# Gizmo specific, not 'all'
if "checkout" in request :
LEDs.checkout('blue red green checkout sequence.')
LEDs.off('lights out')
print('doing checkout flash sequence')
elif "checkin" in request :
LEDs.checkin('red flash.')
LEDs.off('lights out')
print('doing checkin flash')
elif "report config" in request :
print('doing reportBTconfig')
print(str(BTconfig))
reportBTconfig()
LEDs.ok('green Roger.')
elif "requestBTconfig" in request :
#This is a update or reset of the BTconfig.
cf = resetBTconfig()
print('cf for update: ' + str(cf))
BTconfig.update(cf)
bt = BTconfig['BT_ID']
fl = BTconfig['FLEET']
btfl = bt + ',' + fl
print('re-writing BTconfig: ' + str(BTconfig))
with open('BTconfig', 'w') as f: json.dump(BTconfig, f)
LEDs.ok('green Roger.')
restartBT()
if btfl in called or hn in called or 'all' in called :
if "flash" in request :
LEDs.ok('green Roger.')
elif "setRC" in request :
if 1 < len(data) : # in theory alway true, but otherwise bad broadcasts cause crash
fl = data[1] # from UDP broadcast, not TCP connection
if fl == BTconfig['FLEET'] :
BTconfig.update(eval(data[2]))
with open('BTconfig', 'w') as f: json.dump(BTconfig, f)
LEDs.ok('green Roger.')
restartBT()
elif "setREG" in request :
#This is using udp broadcast to reset address used for tcp.
if 1 < len(data) : # in theory alway true, but otherwise bad broadcasts cause crash
REG = eval(data[2])
print(str(data[1]))
print(str(data[2]))
print(str(REG))
LEDs.ok('green Roger.')
# never get here unless shutdown mechanism is activated
sockUDP.close()
LEDs.cleanup('clean up for shutdown')