forked from bskari/pi-rc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactive_control.py
executable file
·211 lines (173 loc) · 6.33 KB
/
interactive_control.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
#!/usr/bin/env python
"""Interactive control for the remote radio control Raspberry Pi."""
import argparse
import json
import pygame
import pygame.font
import socket
from common import dead_frequency
from common import server_up
# pylint: disable=global-statement
# pylint: disable=invalid-name
# pylint: disable=superfluous-parens
UP = LEFT = DOWN = RIGHT = False
QUIT = False
def load_configuration(configuration_file):
"""Generates a dict of JSON command messages for each movement."""
configuration = json.loads(configuration_file.read())
dead = dead_frequency(configuration['frequency'])
sync_command = {
'frequency': configuration['frequency'],
'dead_frequency': dead,
'burst_us': configuration['synchronization_burst_us'],
'spacing_us': configuration['synchronization_spacing_us'],
'repeats': configuration['total_synchronizations'],
}
base_command = {
'frequency': configuration['frequency'],
'dead_frequency': dead,
'burst_us': configuration['signal_burst_us'],
'spacing_us': configuration['signal_spacing_us'],
}
movement_to_command = {}
for key in (
'forward',
'forward_left',
'forward_right',
'left',
'reverse',
'reverse_left',
'reverse_right',
'right',
):
command_dict = base_command.copy()
command_dict['repeats'] = configuration[key]
movement_to_command[key] = command_dict
direct_commands = {
key: json.dumps([sync_command, movement_to_command[key]])
for key in movement_to_command
}
# We also need to add an idle command; just broadcast at the dead frequency
command_dict = [base_command.copy()]
command_dict[0]['frequency'] = dead
command_dict[0]['repeats'] = 20 # Doesn't matter
direct_commands['idle'] = json.dumps(command_dict)
return direct_commands
def get_keys():
"""Returns a tuple of (UP, DOWN, LEFT, RIGHT, changed) representing which
keys are UP or DOWN and whether or not the key states changed.
"""
change = False
key_to_global_name = {
pygame.K_LEFT: 'LEFT',
pygame.K_RIGHT: 'RIGHT',
pygame.K_UP: 'UP',
pygame.K_DOWN: 'DOWN',
pygame.K_ESCAPE: 'QUIT',
pygame.K_q: 'QUIT',
}
for event in pygame.event.get():
if event.type == pygame.QUIT:
global QUIT
QUIT = True
elif event.type in {pygame.KEYDOWN, pygame.KEYUP}:
down = (event.type == pygame.KEYDOWN)
change = (event.key in key_to_global_name)
if event.key in key_to_global_name:
globals()[key_to_global_name[event.key]] = down
return (UP, DOWN, LEFT, RIGHT, change)
def interactive_control(host, port, configuration):
"""Runs the interactive control."""
pygame.init()
size = (300, 400)
screen = pygame.display.set_mode(size)
# pylint: disable=too-many-function-args
background = pygame.Surface(screen.get_size())
clock = pygame.time.Clock()
black = (0, 0, 0)
white = (255, 255, 255)
big_font = pygame.font.Font(None, 40)
little_font = pygame.font.Font(None, 24)
pygame.display.set_caption('rc-pi interactive')
text = big_font.render('Use arrows to move', 1, white)
text_position = text.get_rect(centerx=size[0] / 2)
background.blit(text, text_position)
screen.blit(background, (0, 0))
pygame.display.flip()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
while not QUIT:
up, down, left, right, change = get_keys()
if change:
# Something changed, so send a new command
command = 'idle'
if up:
command = 'forward'
elif down:
command = 'reverse'
append = lambda x: command + '_' + x if command != 'idle' else x
if left:
command = append('left')
elif right:
command = append('right')
print(command)
try:
sock.sendto(configuration[command], (host, port))
except TypeError:
# Windows + Python 3 workaround?
sock.sendto(bytes(configuration[command], 'utf-8'), (host, port))
# Show the command and JSON
background.fill(black)
text = big_font.render(command, 1, white)
text_position = text.get_rect(centerx=size[0] / 2)
background.blit(text, text_position)
pretty = json.dumps(json.loads(configuration[command]), indent=4)
pretty_y_position = big_font.size(command)[1] + 10
for line in pretty.split('\n'):
text = little_font.render(line, 1, white)
text_position = text.get_rect(x=0, y=pretty_y_position)
pretty_y_position += little_font.size(line)[1]
background.blit(text, text_position)
screen.blit(background, (0, 0))
pygame.display.flip()
# Limit to 20 frames per second
clock.tick(60)
pygame.quit()
def make_parser():
"""Builds and returns an argument parser."""
parser = argparse.ArgumentParser(
description='Interactive controller for the Raspberry Pi RC.'
)
parser.add_argument(
dest='control_file',
help='JSON control file for the RC car.'
)
parser.add_argument(
'-p',
'--port',
dest='port',
help='The port to send control commands to.',
default=12345,
type=int
)
parser.add_argument(
'-s',
'--server',
dest='server',
help='The server to send control commands to.',
default='127.1'
)
return parser
def main():
"""Parses command line arguments and runs the interactive controller."""
parser = make_parser()
args = parser.parse_args()
with open(args.control_file) as configuration_file:
configuration = load_configuration(configuration_file)
print('Sending commands to ' + args.server + ':' + str(args.port))
frequency = json.loads(configuration['idle'])[0]['frequency']
if not server_up(args.server, args.port, frequency):
print('Server does not appear to be listening for messages, aborting')
return
interactive_control(args.server, args.port, configuration)
if __name__ == '__main__':
main()