As the title says. I fully refer to the following articles. Thank you very much. The code is almost the same, so if you point out, we will delete it immediately.
Log the value of SwitchBot thermo-hygrometer with Raspberry Pi https://qiita.com/c60evaporator/items/7c3156a6bbb7c6c59052
There was a part that didn't work in my environment, so I'll put the code that worked as a private log.
You can check it from the smartphone application.
pi@raspberrypi:~ $ sudo hcitool lescan | grep EB:F6:31:8C:1F:E9
EB:F6:31:8C:1F:E9 (unknown)
EB:F6:31:8C:1F:E9 (unknown)
EB:F6:31:8C:1F:E9 (unknown)
What is this command?
NAME
hcitool - configure Bluetooth connections
DESCRIPTION
hcitool is used to configure Bluetooth connections and send some spe-
cial command to Bluetooth devices. If no command is given, or if the
option -h is used, hcitool prints some usage information and exits.
Use bluepy. Refer to the linked URL.
pi@raspberrypi:~ $ sudo install libglib2.0-dev
pi@raspberrypi:~ $ pip3 install bluepy
pi@raspberrypi:~ $ cd .local/lib/python3.7/site-packages/bluepy
pi@raspberrypi:~ $ sudo setcap 'cap_net_raw,cap_net_admin+eip' bluepy-helper
switchbot.py
from bluepy import btle
import struct
class SwitchbotScanDelegate(btle.DefaultDelegate):
def __init__(self, macaddr):
btle.DefaultDelegate.__init__(self)
self.sensorValue = None
self.macaddr = macaddr
def handleDiscovery(self, dev, isNewDev, isNewData):
if dev.addr == self.macaddr:
for (adtype, desc, value) in dev.getScanData():
if desc == '16b Service Data':
self._decodeSensorData(value)
def _decodeSensorData(self, valueStr):
valueBinary = bytes.fromhex(valueStr[4:])
batt = valueBinary[2] & 0b01111111
isTemperatureAboveFreezing = valueBinary[4] & 0b10000000
temp = ( valueBinary[3] & 0b00001111 ) / 10 + ( valueBinary[4] & 0b01111111 )
if not isTemperatureAboveFreezing:
temp = -temp
humid = valueBinary[5] & 0b01111111
self.sensorValue = {
'SensorType': 'SwitchBot',
'Temperature': temp,
'Humidity': humid,
'BatteryVoltage': batt
}
main.py
from bluepy import btle
from switchbot import SwitchbotScanDelegate
scanner = btle.Scanner().withDelegate(SwitchbotScanDelegate('eb:f6:31:8c:1f:e9'))
scanner.scan(5.0)
print(scanner.delegate.sensorValue)
pi@raspberrypi:~ $ python3 ./main.py
{'SensorType': 'SwitchBot', 'Temperature': 25.2, 'Humidity': 68, 'BatteryVoltage': 100}
Recommended Posts