Skip to content

Instantly share code, notes, and snippets.

@wwj718
Created May 23, 2018 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wwj718/248f4e9daefa4c6016aaa20617bf8c67 to your computer and use it in GitHub Desktop.
Save wwj718/248f4e9daefa4c6016aaa20617bf8c67 to your computer and use it in GitHub Desktop.
from microbit import * # sleep, uart, button_a, display
import random
uart.init(115200)
def display_handler(data):
''' : String -> None '''
convert = {
'happy': Image.HAPPY,
'smile': Image.SMILE,
'sad': Image.SAD,
'heart': Image.HEART,
'heart_small': Image.HEART_SMALL,
'yes': Image.YES,
'no': Image.NO,
'confused': Image.CONFUSED,
'angry': Image.ANGRY,
'asleep': Image.ASLEEP,
'surprised': Image.SURPRISED,
'silly': Image.SILLY,
'meh': Image.MEH,
'fabulous': Image.FABULOUS
}
display.show(convert[data], wait=True, loop=False)
dic = {"type": "actuator"}
return str(dic) + "\n"
def get_sensors(data):
'''
here: sensor pub message
'''
# while True:
a = button_a.is_pressed()
b = button_b.is_pressed()
x = accelerometer.get_x()
y = accelerometer.get_y()
z = accelerometer.get_z()
dic = {
"id": "microbit",
"topic": "sensor",
"data": {
"button_a": a,
"button_b": b,
"x": x,
"y": y,
"z": z
}
}
return str(dic) + "\n"
def random_handler(data):
''' : Number -> None '''
number = random.randint(1, int(data))
display.show(str(number), wait=True, loop=False)
dic = {"type": "actuator"}
return str(dic) + "\n"
def scroll_handler(data):
''' : Number -> None '''
display.scroll(data, wait=True, loop=False)
dic = {"type": "actuator"}
return str(dic) + "\n"
def clear_handler(data):
''' : () -> None '''
display.clear()
dic = {"type": "actuator"}
return str(dic) + "\n"
match = {
'actuators/display': display_handler,
'sensor': get_sensors,
'actuators/random': random_handler,
'actuators/say': scroll_handler,
'actuators/clear': clear_handler
}
def get_topic_and_data(b):
# 两种请求都使用一样的结构,只是topic不同
try:
b = b.strip()
json_str = str(b, 'utf-8')
json = eval(json_str)
# :todo check key data, topic
if not json.get('topic'):
return
topic = str(json.get('topic'))
data = str(json.get('data'))
return topic, data
except:
display.show(str("!"))
return None
def on_callback_req(topic, data):
'''
对请求的响应
'''
handler = match[topic] # 请求数据也是一种topic: sensor
result = handler(data) # 统一返回
# uart.write(bytes(result, 'utf-8') + b"\r\n")
uart.write(bytes(result, 'utf-8'))
r_merge = b''
while True:
r = uart.readline()
if r:
r_merge += r
if r_merge.startswith(b'{') and r_merge.endswith(b'\r\n'):
d = get_topic_and_data(r_merge)
if d:
topic, data = d
on_callback_req(topic, data)
r_merge = b''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment