-
Notifications
You must be signed in to change notification settings - Fork 0
/
scratra3.py
233 lines (195 loc) · 7.78 KB
/
scratra3.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
# scratra3
# greatdane ~ easy python implementation with scratch
# inspired by sinatra(sinatrarb.com) ~ code snippets from scratch.py(bit.ly/scratchpy)
# Bug fixes and updated for Python 3 by pinecone460: https://pineco.net https://github.com/pinecone460 https://scratch.mit.edu/users/pinecone460
# The MIT License (MIT)
# Copyright (c) 2013-2020 scratra, pinecone460
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import socket
from errno import *
from array import array
import threading
import shlex
# Errors from scratch.py
class ScratchConnectionError(Exception): pass
class ScratchNotConnected(ScratchConnectionError): pass
class ScratchConnectionRefused(ScratchConnectionError): pass
class ScratchConnectionEstablished(ScratchConnectionError): pass
class ScratchInvalidValue(Exception): pass
broadcast_map = {}
update_map = {}
start_list = []
end_list = []
scratchSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
runtime_quit = 0
scratchInterface = None
# Implementation for Scratch variables
class RemoteSensors:
sensor_values = {}
def __setitem__(self, sensor_name, value):
if isinstance(value, str):
v = Scratch.toScratchMessage('sensor-update "' + sensor_name +'" "'+value+'"')
self.sensor_values[sensor_name] = value
scratchSocket.send(v)
elif isinstance(value, int) or isinstance(value, float):
v = Scratch.toScratchMessage('sensor-update "' + sensor_name +'" ' + str(value))
self.sensor_values[sensor_name] = value
scratchSocket.send(v)
else:
raise ScratchInvalidValue(sensor_name + ': Incorrect attempted value')
def __getitem__(self, sensor_name):
return self.sensor_values[sensor_name]
# For general convenience, scratch interface
class Scratch:
# Variables interface
sensor = RemoteSensors()
var_values = {}
# Broadcast interface
def broadcast(self, *broadcasts):
for broadcast_name in broadcasts:
scratchSocket.send(self.toScratchMessage('broadcast "' + broadcast_name + '"'))
# Variable interface
def var(self, var_name):
return self.var_values[var_name]
@staticmethod
def toScratchMessage(cmd):
# Taken from chalkmarrow
n = len(cmd)
a = []
a.append(chr((n >> 24) & 0xFF))
a.append(chr((n >> 16) & 0xFF))
a.append(chr((n >> 8) & 0xFF))
a.append(chr(n & 0xFF))
final = (''.join(a) + cmd).encode('utf-8')
return final
@staticmethod
def atom(msg):
try:
return int(msg)
except:
try:
return float(msg)
except:
return msg.strip('"')
def run(host='localhost', poll=True, msg="Scratra -> Connected\n-> 'stop' to quit", console=True):
runClass(host, poll, msg, console).start()
# actual threading process
class runClass(threading.Thread):
def __init__(self, host, poll, msg, console):
self.host = host
self.poll = poll
self.msg = msg
self.console = console
threading.Thread.__init__(self)
def run(self):
host = self.host
poll = self.poll
port = 42001
console = self.console
while 1:
try: scratchSocket.connect((host, port))
# Except series from scratch.py
except socket.error as error:
(err, msge) = error
if err == EISCONN:
raise ScratchConnectionEstablished('Already connected to Scratch')
elif poll == True:
continue
elif err == ECONNREFUSED:
raise ScratchConnectionRefused('Connection refused, try enabling remote sensor connections')
else:
raise ScratchConnectionError(msge)
scratchInterface = Scratch()
break
if console:
run_console(self.msg).start()
for func in start_list:
func(scratchInterface)
while not runtime_quit:
try:
msg = scratchSocket.recv(1024).decode('utf-8')
except socket.error as xxx_todo_changeme:
(errno, message) = xxx_todo_changeme.args
raise ScratchConnectionError(errno, message)
if msg:
# If the message is not a sensor-update, but a broadcast
if msg.find('sensor-update')==-1 and 'broadcast' in msg:
msg = msg[15:-1]
if msg in broadcast_map:
for func in broadcast_map[msg]:
func(scratchInterface)
# Otherwise, it must be a sensor-update
else:
msg = msg[4:]
if 'sensor-update' in msg:
msg = shlex.split(msg)[1:]
i = 0
while i < len(msg)-1:
if scratchInterface.atom(msg[i]) in update_map:
scratchInterface.var_values[scratchInterface.atom(msg[i])] = scratchInterface.atom(msg[i+1])
for func in update_map[scratchInterface.atom(msg[i])]:
func(scratchInterface, scratchInterface.atom(msg[i+1]))
i+=2
class run_console(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run(self):
global runtime_quit
print(self.msg)
while not runtime_quit:
cmd = input('-> ')
if cmd == 'stop':
runtime_quit = 1
print('-> Quitting')
for func in end_list:
func(scratchInterface)
# For user convenience, decorator methods
# When Scratch broadcasts this...
# @broadcast('scratch_broadcast')
# def func(scratch): ....
class broadcast:
def __init__(self, broadcast):
self.b = broadcast
def __call__(self, func):
if self.b in broadcast_map:
broadcast_map[self.b].append(func)
else:
broadcast_map[self.b] = [func]
# When this variable is updated...
# @update('variable')
# def func(scratch, value): ...
class update:
def __init__(self, update):
self.u = update
def __call__(self, func):
if self.u in update_map:
update_map[self.u].append(func)
else:
update_map[self.u] = [func]
# When we start listening...
# @start
# def func(scratch): ...
def start(func):
if func not in start_list:
start_list.append(func)
# When we stop listening
# @end
# def func(scratch): ...
def end(func):
if func not in end_list:
end_list.append(func)