-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscratch_handler.py
executable file
·215 lines (169 loc) · 6.34 KB
/
scratch_handler.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
#!/usr/bin/env python3
from array import array
from time import sleep
import threading
import socket
import sys
import struct
__version__ = "2.0.6"
if "-e" in sys.argv:
import pifacedigital_emulator as pfio
sys.argv.remove("-e")
else:
import pifacedigitalio as pfio
PORT = 42001
DEFAULT_HOST = '127.0.0.1'
BUFFER_SIZE = 175
SOCKET_TIMEOUT = 1
MAX_NUM_SOCKET_RESTART = 5
MAX_NUM_EMPTY_DATA = 5
SCRATCH_SENSOR_NAME_INPUT = (
'piface-input1',
'piface-input2',
'piface-input3',
'piface-input4',
'piface-input5',
'piface-input6',
'piface-input7',
'piface-input8')
SCRATCH_SENSOR_NAME_OUTPUT = (
'piface-output1',
'piface-output2',
'piface-output3',
'piface-output4',
'piface-output5',
'piface-output6',
'piface-output7',
'piface-output8')
class ScratchListener(threading.Thread):
def __init__(self, host):
threading.Thread.__init__(self)
self.last_zero_bit_mask = 0
self.last_one_bit_mask = 0
self.pifacedigital = pfio.PiFaceDigital()
self.host = host
def stop(self):
self.alive = False
def run(self):
self.alive = True
# for restarting
num_empty_data = 0
num_socket_start = 0
global scratch_socket
while self.alive:
try:
data = scratch_socket.recv(BUFFER_SIZE).decode('utf-8','replace')
data = data[4:] # get rid of the length info
except socket.timeout: # if we timeout, re-loop
continue
except: # exit on any other errrors
break
data = data.split(" ")
if data[0] == 'sensor-update':
data = data[1:]
print('received sensor-update:', data)
self.sensor_update(data)
elif data[0] == 'broadcast':
data = data[1:]
print('received broadcast:', data)
else:
print('received something:', data)
if data == ['']:
num_empty_data += 1
if num_empty_data >= MAX_NUM_EMPTY_DATA:
if num_socket_start >= MAX_NUM_SOCKET_RESTART:
print("Max number of restart attempts reached, "
"giving up.")
break
else:
# global scratch_socket
scratch_socket.shutdown(socket.SHUT_RD)
scratch_socket.close()
print("Restarting the scratch handler in 5 seconds.")
sleep(4)
scratch_socket = create_socket(self.host, PORT)
num_socket_start +=1
# make scratch aware of the input pins
broadcast_all_input_pins()
def sensor_update(self, data):
index_is_data = False # ignore the loop contents if not sensor
zero_bit_mask = 0 # bit mask showing where zeros should be written
one_bit_mask = 0 # bit mask showing where ones should be written
we_should_update_piface = False
# go through all of the sensors that have been updated
for i in range(len(data)):
if index_is_data:
index_is_data = False
continue
sensor_name = data[i].strip('"')
# if this sensor is a piface output then reflect
# that update on the board
if sensor_name in SCRATCH_SENSOR_NAME_OUTPUT:
we_should_update_piface = True
pin_index = SCRATCH_SENSOR_NAME_OUTPUT.index(sensor_name)
sensor_value = int(data[i + 1])
index_is_data = True
# could this be made more efficient by sending a single write
if sensor_value == 0:
zero_bit_mask ^= (1 << pin_index)
else:
one_bit_mask ^= (1 << pin_index)
if we_should_update_piface:
old_pin_bitp = self.pifacedigital.output_port.value
new_pin_bitp = old_pin_bitp & ~zero_bit_mask # set the zeros
new_pin_bitp |= one_bit_mask # set the ones
# write the new bit pattern
if new_pin_bitp != old_pin_bitp:
self.pifacedigital.output_port.value = new_pin_bitp
def input_handler(event):
"""Callback function for when inputs are changed."""
broadcast_pin_update(event.pin_num, event.direction ^ 1)
def broadcast_pin_update(pin_index, value):
sensor_name = SCRATCH_SENSOR_NAME_INPUT[pin_index]
bcast_str = 'sensor-update "%s" %d' % (sensor_name, value)
print('sending:', bcast_str)
send_scratch_command(bcast_str)
def send_scratch_command(cmd):
global scratch_socket
length = len(cmd).to_bytes(4, byteorder='big')
scratch_socket.send(length + cmd.encode("utf-8"))
def create_socket(host, port):
try:
scratch_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
scratch_sock.connect((host, port))
except socket.error:
print("There was an error connecting to Scratch!")
print("Could not find MESH session at %s:%s" % (host, port))
sys.exit(1)
scratch_sock.settimeout(SOCKET_TIMEOUT)
return scratch_sock
def broadcast_all_input_pins():
for i in range(len(SCRATCH_SENSOR_NAME_INPUT)):
broadcast_pin_update(i, 0)
if __name__ == '__main__':
# has the hostname been given?
host = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_HOST
# setup the socket
print('Connecting...', end=" ")
global scratch_socket
scratch_socket = create_socket(host, PORT)
print('Connected.')
pfd = pfio.PiFaceDigital()
# hook each input to the callback function
#ifm = pifacecommon.InputFunctionMap()
inputlistener = pfio.InputEventListener(chip=pfd)
for i in range(len(SCRATCH_SENSOR_NAME_INPUT)):
inputlistener.register(i, pfio.IODIR_BOTH, input_handler)
broadcast_all_input_pins() # make scratch aware of the input pins
scratchlistener = ScratchListener(host)
scratchlistener.start()
try:
inputlistener.activate()
except KeyboardInterrupt:
print("kb int")
print("ending main thread")
# print("Stopping...", end=" ")
# scratchlistener.stop()
# scratchlistener.join()
# pfio.deinit()
# print("Done.")