(原) Pi0 + Python BLE

原创文章,请后转载,并注明出处。

在PiZeroW上运行的BLE服务,可以添加Wifi,重启,播报IP地址等。

import random,os
import binascii
from bluezero import async_tools, adapter, peripheral

PI_SRVC = '12341000-1234-1234-1234-123456789ABC'
PI_CMD_CHARA = '1001'
PI_INFO_CHARA = '1002'
cmd = ''

# 功能:获取CPU温度
def cmd_cpu_temp():
    p=os.popen('cat /sys/class/thermal/thermal_zone0/temp')
    temp=int(p.read())
    p.close()
    return list(temp.to_bytes(3, byteorder='little', signed=True))

# 功能:播报IP地址
def cmd_voice_ip():
    p=os.popen("/home/pi/tools/PlayIP")
    p.close()

# 功能:LED滚动
def cmd_led_scroll():
    p=os.popen("/home/pi/tools/led_scroll.sh")
    p.close()

# 功能: 重启动
def cmd_reboot():
    p=os.popen("mplayer -quiet /home/pi/sound/reboot.mp3;sudo reboot")
    p.close()

# 功能: 关机
def cmd_poweroff():
    p=os.popen("mplayer -quiet /home/pi/sound/power.mp3;sudo poweroff")
    p.close()

# 功能: 添加WIFI
def cmd_wifiset(value):
    wifi=value.split(":")
    if len(wifi)==3:
       wifi_name=wifi[1]
       wifi_pass=wifi[2]
    print(wifi_name, " ", wifi_pass)
    p=os.popen("/home/pi/tools/add_wifi.sh "+ wifi_name + " " + wifi_pass)
    p.close()


#  命令写入
def cmd_write(value, options):
    global cmd
    cmd = bytes(value).decode('utf-8')
    print('原始字节:', value)
    print('参数:', options)
    print('文本:', cmd)
    if cmd=="ip":
       cmd_voice_ip()
    elif cmd=="temp":
       cmd_cpu_temp()
    elif cmd=="led":
       cmd_led_scroll()
    elif cmd=="rst":
       cmd_reboot()
    elif cmd=="off":
       cmd_poweroff()
    elif cmd.find("wifi")==0:
       cmd_wifiset(cmd)
    else:
       pass

# 供信息回调:等待完成
def info_update(chara):
    global cmd
    if cmd=="":
       value=cmd_cpu_temp()
       chara.set_value(value)
    else:
       value = cmd
       chara.set_value(value.encode('utf-8'))
    cmd = ""
    return chara.is_notifying and value!=""

# 信息回调
def info_notify_callback(notifying, chara):
    if notifying:
        async_tools.add_timer_seconds(3, info_update, chara)

def main(adapter_address):
    server = peripheral.Peripheral( adapter_address, local_name='智能助手', appearance=1344) # 创建外设
    server.add_service( srv_id=1, uuid=PI_SRVC, primary=True)  # 添加服务
    # 添加特征:命令功能
    server.add_characteristic(srv_id=1, chr_id=3, uuid=PI_CMD_CHARA, value=[], notifying=False, flags=['write','write-without-response'],
                                write_callback=cmd_write, read_callback=None, notify_callback=None)
    # 添加特征:信息功能
    server.add_characteristic(srv_id=1, chr_id=2, uuid=PI_INFO_CHARA, value=[], notifying=False, flags=['notify'],
                                read_callback=None, write_callback=None, notify_callback=info_notify_callback )
    server.publish()  # 发布设备并启动事件循环

if __name__ == '__main__':
    main(list(adapter.Adapter.available())[0].address)  # 获取默认适配器地址并将其传递给main

相关文章