環境センサRS-BTEVS1のBLE AdvertisingData受信 – サンプルスクリプト[btevs1_widget_01.py]
サンプルスクリプト [btevs1_widget_01.py]
"""
Receive BLE AdvertisingData from RS-BTEVS1 and make widget on Windows11
Python 3.11 amd bleak 0.20.2(2023-04-19)
btevs1_test_06.py 1R0 7-July-2023
Copyright 2023 RATOC SYstems, Inc. Osaka Japan
"""
import asyncio
from bleak import BleakScanner
import time
from tkinter import Label # Tk
import tkinter.ttk as ttk
import tkinter as tk
# Get AdvertisementData
async def get_advdata():
global label
global scanner # = BleakScanner()
global prv_dsptxt
btevs1 = 'F5:7A:BC:3E:B5:0A'
print("wait AdvertisementData")
await scanner.start()
await asyncio.sleep(10.0)
await scanner.stop()
devices = scanner.discovered_devices_and_advertisement_data
print("Discover device: ", devices ) # Dict[ str, Tuple[BLEdevice,AdvertisementData]]
if devices != {}:
if btevs1 in devices:
tp = devices[ btevs1 ]
print("Tuple: ", tp[1])
if tp != None:
advd = tp[1] # get AdvertisingData
vd = advd.manufacturer_data.get(2912) # 2912 = 0x0B60 : RATOC Systems
if vd != None:
#print("v:", vd )
co2d = vd[0:0+2]
co2 =int.from_bytes(co2d, byteorder='little', signed=False)
tempd = vd[6:6+2]
temp =int.from_bytes(tempd, byteorder='little', signed=False)
temp = temp/10
hm = vd[8]
rsval = advd.rssi
dev_name = advd.local_name
print("RSSI:", rsval, dev_name )
print("CO2:", co2, "ppm Temp:", temp,"℃ ",hm, "%")
prv_dsptxt = "CO2 : "+str(co2)+"ppm" + "\r\n"+ " 温度:"+str(temp)+"℃ 湿度:"+str(hm) + "%"
now = time.strftime("%H:%M:%S")
print( now )
# dsp_txt = prv_dsptxt
# retuen dsp_txt
dsp_txt = prv_dsptxt
return dsp_txt
def tick():
global root
global label
global prv_dsptxt
now = time.strftime("%H:%M:%S")
now_sec = now[6:6+2]
if now_sec == "00":
dsp_txt= asyncio.run( get_advdata())
prv_dsptxt = dsp_txt
else:
dsp_txt = prv_dsptxt
now = time.strftime("%H:%M:%S")
label.config(text=dsp_txt, font=("Times",'20'))
root.title("BTEVS1 環境データ " + now )
label.after(1000, tick)
return now
# Set up Main Window
root=tk.Tk()
w = root.winfo_screenwidth()
h = root.winfo_screenheight()
w = w-450
h = h-250
now = time.strftime("%H:%M:%S")
root.title("BTEVS1 環境データ " + now )
root.geometry("400x150+"+str(w)+"+"+str(h))
# set up main frame and put it
frame = ttk.Frame(root)
#label_frame = tk.Label(frame)
#button_frame = tk.Button(frame)
frame.pack(fill = tk.BOTH, padx=20,pady=10)
scanner = BleakScanner()
dsp_txt= asyncio.run( get_advdata())
prv_dsptxt = dsp_txt
now = time.strftime("%H:%M:%S")
label = Label(frame, text=dsp_txt, font=("Times", '20'))
print("Loop Start","\r\n")
now = tick()
label.pack()
# main loop
root.mainloop()
print("end")