-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
273 lines (233 loc) · 9.41 KB
/
Copy pathmain.py
File metadata and controls
273 lines (233 loc) · 9.41 KB
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
267
268
269
270
271
272
273
# Imports go at the top
from microbit import *
import radio
import music
versionToken="pct"
messageBusMax=9 #min is 0, one digit avoids scrolling
roleWeight={"A":1,"B":2}
roleCounterMax={"A":3,"B":6}
roleDesc={"A":"perceptron input, weight:{}".format(roleWeight["A"]),
"B":"perceptron input, weight:{}".format(roleWeight["B"]),
"Z":"perceptron output, activation function: a+b>4",}
roleList=list(roleDesc.keys())
validOriginRolesPerDestination={"A":list(),
"B":list(),
"Z":("A","B")}
#
# this node's defeault config
#
currentRole=roleList[0]
messageBus=0
def errorHandler(halt=False,errorCode=0,desc="desc"):
if halt:
_="FATAL"
else:
_="WARN"
print(_+":{}:{}".format(errorCode,desc))
while True:
display.show(errorCode)
sleep(200)
display.show(Image.SAD)
sleep(2000)
if not halt:
break
class modelCls():
"""
perceptron. two inputs, possibly n-fold input some day
"""
def __init__(self,role,pktIn,pktOut):
if role in roleList:
self.role=role
self.counter={"A":0,"B":0}
self.out=0
self.pktIn=pktIn
self.pktOut=pktOut
self.outThreshold=7
else:
errorHandler(halt=True, errorCode=1, desc="FATAL:unexisting role {}".format(role))
def eventHandler(self,event,paramDict):
if event=="message":
#todo: validation
self.message(paramDict)
elif event=="button":
#todo: validation
self.button(paramDict)
pass
else:
errorHandler(halt=True, errorCode=1, desc="FATAL:unexisting event {}".format(event))
def updateOutput(self):
prevOut=self.out
counters_sum=self.counter["A"]+self.counter["B"]
if counters_sum >=self.outThreshold:
self.out=1
if self.out!=prevOut:
music.pitch(frequency=500,duration=250,wait=False)
else:
self.out=0
if self.out!=prevOut:
music.pitch(frequency=7000,duration=500,wait=False)
display.show(counters_sum)
for _ in range(5):
display.set_pixel(4,_,9*self.out)
def message(self,paramDict):
if self.role=="Z":
if paramDict["origin"] in self.counter.keys():
try:
self.counter[paramDict["origin"]]=int(paramDict["payload"])
self.updateOutput()
except Exception as e:
print("DEBUG:{}:model.message():{}".format(self.role,e))
else:
print("WARN:{}:model.message():paramDict[origin] '{}' not in self.counter.keys".format(self.role,paramDict["origin"]))
else:
print("DEBUG:{}:model.message():unimplemented message handler".format(self.role,))
pass
def button(self,paramDict):
if self.role in ("A","B"):
increment=1
increment*=roleWeight[self.role] #apply perceptron input's weight parameter
if paramDict["button"]=="a":
if self.counter[self.role]+increment > roleCounterMax[self.role]:
increment=0
else:
self.counter[self.role]+=increment
elif paramDict["button"]=="b":
if self.counter[self.role]-increment < 0:
increment=0
else:
self.counter[self.role]-=increment
else:
print("WARN:{}:model.button():paramDict[button] '{}' not implmented".format(self.role,paramDict["button"]))
increment=0 #just to strigger the beep
if increment==0:
#music.pitch(frequency=500,duration=150,wait=False) # no beep, pls!!
pass
#if increment!=0 #send even if nathing changed, just to recover lost sync with Z
display.show(self.counter[self.role])
encoded=pktOut.encode(self.counter[self.role])
radio.send(encoded)
else:
print("DEBUG:{}:model.button():paramDict[button] '{}' not implmented".format(self.role,paramDict["button"]))
def messageSend(roleDest,message):
print("DEBUG:{}:messageAttend({},{})".format(currentRole,roleDest,message))
def messageAttend(message):
print("DEBUG:{}:messageAttend({})".format(currentRole,message))
class pkt():
def encode(self,payload):
result=versionToken+","
result+="{},".format(messageBus)
result+="{},".format(currentRole) #from
result+=str(payload).replace(",","_coma_")
return result
def decode(self,OTAtext,validOriginRoles):
resultValid=False
resultDesc=""
resultFrom=""
resultPayload=""
parts=OTAtext.split(",")
try:
if parts[0]!=versionToken:
resultDesc="parts[versionToken]={}, expected:{}".format(parts[0],versionToken)
errorHandler(halt=False,errorCode=9,desc=resultDesc)
raise ValueError
if parts[1]!=str(messageBus):
resultDesc="parts[messageBus]:{}, expected:{}".format(parts[1],str(messageBus))
#errorHandler(halt=False,errorCode=9,desc=resultDesc) #too chatty
raise ValueError
if parts[2] in validOriginRoles:
resultFrom=parts[2]
else:
resultDesc="parts[originRoles]: {} not in '{}'".format(parts[2],str(validOriginRoles))
if parts[2] == currentRole:
errorHandler(halt=True,errorCode=1,desc="Role cloning: {}".format(currentRole))
raise ValueError
resultPayload=parts[3].replace("_coma_",",")
resultValid=True
resultDesc="OK"
except Exception as e:
print("DEBUG:pkt.decode:e;{},desc:{},OTAtext:'{}'".format(e,resultDesc,OTAtext))
return resultValid,resultDesc,resultFrom,resultPayload
def recibido_fila_columna_off():
display.set_pixel(4,0,0)
def recibido_fila_columna_on():
display.set_pixel(4,0,9)
def button_a_was_pressed(configAdj):#,model):
global model
if configAdj:
# config change: role in roleList
global currentRole
prevRole=currentRole
roleIndex=roleList.index(currentRole)
if roleIndex < len(roleList)-1:
currentRole=roleList[roleIndex+1]
else:
currentRole=roleList[0]
model=modelCls(currentRole,model.pktIn,model.pktOut)
pin_logo_is_touched()
print("INFO:button_a_was_pressed({}),newRole:{},prevRole,{}".format(configAdj,model.role,prevRole))
else:
#display.show("a")
#encoded=pktOut.encode("a")
#radio.send(encoded)
#recibido_fila_columna_off()
model.eventHandler(event="button",paramDict={"button":"a"})
#print("INFO:button_a_was_pressed({}),Role:{}".format(configAdj,currentRole))
def button_b_was_pressed(configAdj):#,model):
if configAdj:
# config change: messageBus in messageBusesList
global messageBus
messageBus+=1
if messageBus > messageBusMax:
messageBus=0
pin_logo_is_touched()
print("INFO:button_b_was_pressed({}),newbus:{}".format(configAdj,messageBus))
else:
#display.show("b")
#encoded=pktOut.encode("b")
#radio.send(encoded)
#recibido_fila_columna_off()
model.eventHandler(event="button",paramDict={"button":"b"})
#print("INFO:button_a_was_pressed({}),Role:{}".format(configAdj,currentRole))
def on_message(message):
validOriginRoles=validOriginRolesPerDestination[currentRole]
decoValid,decoDesc,fromRole,decoded=pktIn.decode(message,validOriginRoles)
print("DEBUG:on_message(pktIn.decode({})):{},'{}','{}'".format(message,decoValid,decoDesc,decoded))
if decoValid:
print("INFO:on_message():in from '{}': '{}'".format(fromRole,decoded))
#display.show(decoded)
#recibido_fila_columna_on()
model.message(paramDict={"origin":fromRole,"payload":decoded})
else:
print("DEBUG:on_message():pass".format(message,decoValid))
def pin_logo_is_touched():
keep_going=True #show Role and messageBus at least once
while keep_going:
display.show(currentRole)
sleep(500)
display.show(messageBus)
sleep(200)
keep_going=pin_logo.is_touched()
if keep_going:
print("DEBUG:pin_logo_is_touched(),Role:{},messageBus:{}".format(currentRole,messageBus))
display.clear()
if __name__=="__main__":
display.scroll(versionToken)
pktIn=pkt()
pktOut=pkt()
radio.on()
radio.config(group=153)#,power=6)
model=modelCls(currentRole,pktIn,pktOut)
pin_logo_is_touched()
model.updateOutput()
while True:
if button_a.was_pressed():
configAdj=pin1.is_touched() # pin1 asserted, config adjustment is in order
button_a_was_pressed(configAdj)#,model)
if button_b.was_pressed():
configAdj=pin1.is_touched() # pin1 asserted, config adjustment is in order
button_b_was_pressed(configAdj)#,model)
if pin_logo.is_touched():
pin_logo_is_touched()
message = radio.receive()
if message:
on_message(message)