21ba31b17be79a468a6b4293882f1d54f6c23189
1 # This code is copyright ...... under the GPL v2.
2 # This code is derived from scratch_gpio_handler by Simon Walters, which
3 # is derived from scratch_handler by Thomas Preston
4 # Version 0.1: It's kind of working.
18 from Tkinter import Tk
19 from tkSimpleDialog import askstring
25 DEFAULT_HOST
= '127.0.0.1'
26 BUFFER_SIZE
= 240 #used to be 100
28 DEVICES
= ['/dev/ttyACM0']
29 #DRUM_DEVICE = '/dev/ttyACM0'
30 #GUITAR_DEVICE = '/dev/ttyUSB1'
31 #MARACAS_DEVICE = '/dev/ttyACM1'
32 ARDUINO_BAUD_RATE
= 57600
34 BROADCAST_NAMES
= {'guitar': 'guitar',
42 SENSOR_NAMES
= {'guitar': 'guitar_pitch'}
44 #DRUM_INSTRUMENT_NAMES = {0: 'cymbal',
50 #DRUM_VALUE_NAMES = {0: 'drum-volume',
56 #GUITAR_INSTRUMENT_NAMES = {0: 'guitar'}
57 #GUITAR_VALUE_NAMES = {0: 'guitar_pitch'}
59 #MARACAS_INSTRUMENT_NAMES = {0: 'maracas', 2: 'maracas'}
60 #MARACAS_VALUE_NAMES = {0: 'maracas_vigour', 2: 'maracas_vigour'}
62 logging
.basicConfig(level
= logging
.INFO
)
63 #logging.basicConfig(level = logging.DEBUG)
65 class MyError(Exception):
66 def __init__(self
, value
):
70 return repr(self
.value
)
72 class ScratchSender(threading
.Thread
):
73 def __init__(self
, socket
):
74 threading
.Thread
.__init
__(self
)
75 self
.scratch_socket
= socket
76 self
._stop
= threading
.Event()
78 def join(self
,timeout
=None):
83 threading
.Thread
.join(self
, timeout
)
89 return self
._stop
.isSet()
93 while not self
.stopped():
94 time
.sleep(0.01) # be kind to cpu - not certain why :)
96 def send_scratch_command(self
, cmd
):
99 a
.append(chr((n
>> 24) & 0xFF))
100 a
.append(chr((n
>> 16) & 0xFF))
101 a
.append(chr((n
>> 8) & 0xFF))
102 a
.append(chr(n
& 0xFF))
103 self
.scratch_socket
.send(a
.tostring() + cmd
)
106 class ArduinoListener(threading
.Thread
):
107 def __init__(self
, device
, speed
, sender
, instruments
, values
):
108 threading
.Thread
.__init
__(self
)
109 self
.arduino_device
= serial
.Serial(device
, speed
, timeout
=0.5)
110 self
._stop
= threading
.Event()
111 self
.scratch_sender
= sender
112 self
.instruments
= instruments
115 def join(self
,timeout
=None):
120 threading
.Thread
.join(self
, timeout
)
126 return self
._stop
.isSet()
129 self
.arduino_device
.readline() # discard the first (partial) line
130 while not self
.stopped():
131 logging
.debug('Thread waiting for a signal')
133 device_line
= self
.arduino_device
.readline()
135 instrument
, instrument_value_string
= device_line
.rstrip().split(',', 1)
136 instrument_value
= int(instrument_value_string
)
137 logging
.info('Instrument: %s, Value: %d' % (instrument
, instrument_value
))
138 if instrument
in self
.values
:
140 logging
.info("sensor-update %s %d" % (self
.values
[instrument
], (instrument_value
* 100) / 1024))
141 self
.scratch_sender
.send_scratch_command("sensor-update %s %d" % (self
.values
[instrument
], (instrument_value
* 100) / 1024))
145 if isinstance(self
.instruments
[instrument
], dict):
146 broadcast
= self
.instruments
[instrument
][instrument_value
]
148 broadcast
= self
.instruments
[instrument
]
150 logging
.info("broadcast %s" % broadcast
)
151 self
.scratch_sender
.send_scratch_command('broadcast %s' % broadcast
)
156 except serial
.SerialException
:
157 logging
.error('Serial exception')
158 logging
.debug('Thread run() exiting')
162 def create_socket(host
, port
):
165 logging
.info('Connecting to Scratch')
166 scratch_sock
= socket
.socket(socket
.AF_INET
, socket
.SOCK_STREAM
)
167 scratch_sock
.connect((host
, port
))
170 logging
.warning("There was an error connecting to Scratch!")
171 logging
.warning("I couldn't find a Mesh session at host: %s, port: %s" % (host
, port
) )
177 def cleanup_threads(threads
):
178 logging
.debug("Stopping %d threads" % len(threads
))
179 #for thread in threads:
181 #logging.debug("Threads stopped")
182 for thread
in threads
:
184 logging
.debug("Threads joined")
186 if __name__
== '__main__':
187 if len(sys
.argv
) > 1:
193 cycle_trace
= 'start'
195 if (cycle_trace
== 'disconnected'):
196 logging
.info("Scratch disconnected")
197 cleanup_threads(listeners
+ sender
)
199 cycle_trace
= 'start'
201 if (cycle_trace
== 'start'):
203 logging
.info('Connecting to Scratch...')
204 the_socket
= create_socket(host
, PORT
)
205 logging
.info('Connected to Scratch')
206 the_socket
.settimeout(SOCKET_TIMEOUT
)
207 sender
= ScratchSender(the_socket
)
209 #for device in DEVICES:
210 #listeners.append(ArduinoListener(device, ARDUINO_BAUD_RATE, sender, BROADCAST_NAMES, SENSOR_NAMES))
212 listeners
= [ArduinoListener(device
, ARDUINO_BAUD_RATE
, sender
, BROADCAST_NAMES
, SENSOR_NAMES
) for device
in DEVICES
]
213 cycle_trace
= 'running'
214 logging
.info("Listeners running....")
216 for listener
in listeners
:
223 except KeyboardInterrupt:
224 logging
.warning("Interrrupted")
225 cleanup_threads(listeners
+ [sender
])