利用 Web 串接主機附近周邊藍芽(含 meshtastic client)
- pip install bleak (這個比較簡單)
----另外一個為 pybluez2 (pybluez)
2.程式
import streamlit as st
import asyncio
from bleak import BleakScannerasync def fetch_data():devices = await BleakScanner.discover()for device in devices:st.write(device)#st.write("aaa")#return dataasync 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 BleakClientif "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_optionreturn 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)
-------