開發 meshtastic 聊天機器人(2)

利用 Web 串接主機附近周邊藍芽(含 meshtastic client)

  1. pip install bleak (這個比較簡單)
    ----另外一個為 pybluez2 (pybluez)
    2.程式
import streamlit as st
import asyncio
from bleak import BleakScanner

async def fetch_data():
    devices = await BleakScanner.discover()
    for device in devices:
        st.write(device)
    #st.write("aaa")
    #return data

async def main():
    await fetch_data()

if __name__ == "__main__":
    asyncio.run(main())

3.呈現結果(找到client)在这里插入图片描述

import streamlit as st
import asyncio
from collections import OrderedDict
from bleak import BleakScanner
from bleak import BleakClient

if "options" not in st.session_state.keys():  #藍芽清單
    st.session_state["options"]=[]

async def fetch_data():
    devices = await BleakScanner.discover(return_adv=True)
    devices = OrderedDict(
        sorted(devices.items(), key=lambda x: x[1][1].rssi, reverse=True)
    )
    list_option=[]
    for i, (addr, (dev, adv)) in enumerate(devices.items()):
        print(i, addr, dev.name, adv.rssi)
        list_option.append(str(addr))   #+"="+str(dev.name))  
       # st.write(device)
    #st.write(list_option)
    st.session_state["options"]=list_option
    return 


if st.button("搜尋附近藍芽設備"):
    asyncio.run(fetch_data())
    # fetch_data()
    #st.write(st.session_state["options"])
    
#if st.session_state["options"] != []:
choice = st.selectbox("選擇連線藍芽設備",st.session_state["options"])

if st.button("連線"):
    st.write("Ok")
    try:
        with BleakClient(choice) as client:
            if client.is_connected():
                try:
                    # Pair with the device (distinct from just connecting)
                    client.pair()
                    print("Paired device")
                except Exception as e:
                    print(e)
            else:
                print("Failed to connect to device")
    except Exception as e:
        print(e)

-------在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值