-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.py
executable file
·271 lines (231 loc) · 9.32 KB
/
client.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
import socket
import time
import select
from dataclasses import dataclass
import serial
from threading import Thread
from functools import reduce
import ctypes as ct
import datetime
import sys
import logging
import os
from serial.serialutil import SerialException
import math
from video import video_send, audio_send
import options
VIDEO = options.VIDEO # Use webcam? Identical option in control.py
if VIDEO:
try:
os.popen('sudo pigpiod')
os.environ['GPIOZERO_PIN_FACTORY']='pigpio'
except:
pass
from gpiozero import Servo
import math
######### Logger Options ############
logging.basicConfig(filename='client_daemon_log.txt',
filemode='w',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s> %(message)s',
datefmt='%H:%M:%S',
level=logging.NOTSET)
logging.info('Starting up')
#####################################
############ Client Options #########
hole_time = 1 #seconds
keep_alive = "client keep alive"
msg_bytes = str.encode(keep_alive, 'ascii')
if host := os.getenv('FORWARDING_HOST'):
while 1:
try:
host = socket.gethostbyname(host)
break
except socket.gaierror as e:
logging.getLogger('socket').debug('unable to get host by name, typically due to networking not up yet? sleep 5 sec')
time.sleep(5)
serveraddy = (host, 25565)
elif host := os.getenv('FORWARDING_SERVER'):
serveraddy = (os.getenv('FORWARDING_SERVER'), 25565)
elif options.DIRECT_SOCKET:
serveraddy = ('127.0.0.1', 25565)
else:
logging.getLogger('Options').critical('Missing FORWARDING_HOST, or FORWARDING_SERVER env variable or direct socket option')
raise Exception('Missing FORWARDING_HOST, or FORWARDING_SERVER env variable or direct socket option')
buffSize = 1024
#####################################
######### Daemon Options ############
START_FRAME = 0xABCD
TIME_SEND = 0.05
log_interval = 10
#####################################
while 1:
try:
udp = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM, proto=socket.IPPROTO_UDP)
udp.bind(('0.0.0.0', 25566))
udp.setblocking(False)
break
except:
try:
udp.close()
except:
pass
logging.getLogger('socket').debug('Could not open socket, trying again in 5 sec.')
time.sleep(5)
logging.getLogger('socket').debug('Socket creation complete.')
now = time.time()
future = now
################################################### Daemon Setup ############################################
brecieve = ['cmd1', 'cmd2', 'speedR_meas', 'speedL_meas', 'batVoltage', 'boardTemp']
class Wheels(Thread):
def __init__(self):
super(Wheels, self).__init__()
self._data_turn = 0
self._data_speed = 0
self.time_log = 0
self.control_update_msg = str.encode('info update:', 'ascii')
self._data_set_time = time.time();
while 1:
try:
self.tty = serial.Serial('/dev/ttyUSB0', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)
break
except (SerialException, BrokenPipeError) as e:
print('serial connection retry in 5s')
print(f'{e}')
logging.getLogger('Wheels') \
.exception(f'serial connection retry in 5s\n{e}')
time.sleep(5)
def send(self):
msg = START_FRAME.to_bytes(2, 'little') \
+ self.data_turn.to_bytes(2, 'little', signed=True) \
+ self.data_speed.to_bytes(2, 'little', signed=True) \
+ ct.c_uint16(START_FRAME ^ self.data_turn ^ self.data_speed).value.to_bytes(2, 'little')
self.tty.write(msg)
def receive(self):
if self.tty.in_waiting:
data = self.tty.read_all()
if len(data) == 18:
incoming = [int.from_bytes(data[0:2], 'little', signed=False),
int.from_bytes(data[2:4], 'little', signed=True),
int.from_bytes(data[4:6], 'little', signed=True),
int.from_bytes(data[6:8], 'little', signed=True),
int.from_bytes(data[8:10], 'little', signed=True),
int.from_bytes(data[10:12], 'little', signed=True),
int.from_bytes(data[12:14], 'little', signed=True),
int.from_bytes(data[14:16], 'little', signed=False)]
checksum = int.from_bytes(data[16:18], 'little', signed=False)
if reduce(lambda x, y: x ^ y, incoming) & 0xFFFF == checksum:
self.propogate(data)
if incoming[5] == 30:
logging.getLogger('daemon').info('Low Battery Exit')
sys.exit()
if self.time_log < (now := time.time()):
self.time_log = now + log_interval
logging.getLogger('daemon').info(
' '.join([i + ': ' + str(j) for i, j in zip(brecieve, incoming[1:])])
)
def propogate(self, data):
global udp
global serveraddy
udp.sendto(self.control_update_msg + data, serveraddy)
def run(self):
try:
itime_send = 0
while True:
now = time.time()
self.receive()
if itime_send < now:
itime_send = now + TIME_SEND
self.send()
time.sleep(0.0001)
except:
logging.getLogger('daemon').exception('Exit due to:')
sys.exit()
def full_stop(self):
while not (math.isclose(self.data_speed, 0) and math.isclose(self.data_turn, 0)):
if abs(self.data_speed) > 50 or abs(self.data_turn) > 50:
self._data_turn -= math.copysign(50, self._data_turn)
self._data_speed -= math.copysign(50, self._data_turn)
else:
self._data_speed = 0
self._data_turn = 0
time.sleep(0.1)
def data_set(self, speed, turn):
"""We get the accel max and alpha max as rpm/s while we get dt between update calls to the function.
This means we can update by only accel/alpha * dt rather than the raw rpm/s.
dt has a time limit of 1 sec to prevent jerk from latency spike
Args:
speed (int | float): The next requested speed as rpm
"""
dt = time.time() - self._data_set_time
dt = 1 if dt > 1 else dt
limit = options.ACCEL_MAX * dt
if abs(speed - self._data_speed) > limit:
self._data_speed += math.copysign(limit, speed - self._data_speed)
else:
self._data_speed = speed
limit = options.ALPHA_MAX * dt
if abs(turn - self._data_turn) > limit:
self._data_turn += math.copysign(limit, turn - self._data_turn)
else:
self._data_turn = turn
self._data_set_time = time.time()
@property
def data_turn(self) -> int:
return int(self._data_turn)
@property
def data_speed(self) -> int:
return int(self._data_speed)
wheels = Wheels()
wheels.start()
if VIDEO:
# Servo stuff
syaw = Servo(19, min_pulse_width=.5/1000, max_pulse_width=2.5/1000, frame_width=20/1000)
spitch = Servo(12, min_pulse_width=.5/1000, max_pulse_width=2.5/1000, frame_width=20/1000)
syaw.value = 0
spitch.value = 0
vsend = video_send()
asend = audio_send()
try:
while True:
if future <= now:
try:
udp.sendto(msg_bytes, serveraddy)
future = now + hole_time
except socket.error as e:
print(f"Socket error {e}, Retrying in 3 seconds")
logging.getLogger("socket").info(f"Socket error {e}, Retrying in 3 seconds")
wheels.full_stop()
time.sleep(3)
ready_sockets, _, _ = select.select(
[udp], [], [], hole_time
)
if ready_sockets:
msgServer = udp.recv(buffSize)
header = msgServer[0:len(options.CONTROL_HEADER)] if len(msgServer) > len(options.CONTROL_HEADER) else None
if header:
msgServer = msgServer[len(options.CONTROL_HEADER):]
values = [int.from_bytes(msgServer[i:i+2], 'little', signed=True) for i in range(0, len(msgServer), 2)]
#checksum
if header and reduce(lambda x, y: x ^ y, values[:-1]) == values[-1]:
wheels.data_set(values[1], values[0])
speed = .13
if VIDEO:
syaw.value = syaw.value + values[4] * speed if abs(syaw.value + values[4] * speed) <= 1 else values[4]
spitch.value = spitch.value + values[5] * speed if abs(spitch.value + values[5] * speed) <= 1 else values[5]
else:
print('corrupt data', values[-1])
else:
print('no data')
logging.getLogger('socket').info("Initiating emergency stop due to no data!")
wheels.full_stop()
time.sleep(3)
now = time.time()
except:
wheels.full_stop()
if VIDEO:
vsend.terminate()
asend.terminate()
vsend.kill()
asend.kill()
logging.getLogger('socket').exception('Exit due to:')
sys.exit()