4
3

More than 3 years have passed since last update.

Raspberry Pi で SwitchBot 温湿度計の値をとる

Last updated at Posted at 2020-09-27

目的

掲題の通りです。以下の記事を存分に参考にしています。ありがとうございます。コードがほぼ同じなのでご指摘をいただいた場合は即削除します。

SwitchBot温湿度計の値をRaspberryPiでロギング
https://qiita.com/c60evaporator/items/7c3156a6bbb7c6c59052

私の環境で一部動かない箇所がありましたので、私的なログとして動作したコードを置いておきます。

環境

IMG_5275.jpg

SwitchBot 温湿度計の Mac Address を確認

スマートフォンのアプリケーションから確認できます。

IMG_5276.PNG IMG_5277.PNG

センサがデータを飛ばしているか確認

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)

このコマンドは何?

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.

Python で値を取得

bluepy を利用します。リンク先の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

Python スクリプト

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}
4
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
3