Log the value of SwitchBot thermo-hygrometer with Raspberry Pi

Introduction

This article has the same content as ** Omron Environment Sensor (BAG type) article **. This article was conducted with a ** SwitchBot temperature / humidity sensor ** with a screen display at a low price.

What is SwitchBot?

A series of home IoT devices developed by Wonderlabs Inc., a manufacturer in Shenzhen, China. This time, the temperature and humidity sensors of the above series switchbot.jpg Use the. At a low price (about 2000 yen), the multi-functionality of data acquisition and screen display using smartphone apps and APIs is attractive.

Things necessary

** ・ RaspberryPi ** (Pi3Model B is used this time) **-Python execution environment ** (This time, pyenv uses Python 3.7.6) ** ・ SwitchBot temperature / humidity sensor **

procedure

** ① Check the Bluetooth connection between the Raspberry Pi and the sensor ** ** ② Get sensor measurements in Python ** ** ③ Hit the GAS API from Python to write data to the spreadsheet ** ** ④ Script execution regularly **

I referred to this. https://qiita.com/warpzone/items/11ec9bef21f5b965bce3

① Check the Bluetooth connection between the Raspberry pi and the sensor

Sensor recognition confirmation

** ・ Sensor setup ** Insert AAA batteries in the sensor

**-Scan for Bluetooth devices ** After checking the MAC address on SwitchBot Official App Execute the following command on Raspberry Pi

sudo hcitool lescan
LE Scan ...
AA:EE:BB:DD:55:77 (unknown)

If the MAC address confirmed by the application above appears, it is successful.

** ② Get sensor measurements in Python **

Recognition confirmation with bluepy

bluepy is a library for accessing Bluetooth Low Energy (BLE) in Python (class definition)

** ・ Installation of required packages ** Install the following

sudo install libglib2.0-dev

** ・ Install bluepy **

Install with pip with the following command

pip install bluepy

** ・ Grant permissions to bluepy ** You need to give bluepy Sudo privileges for scanning.

Go to the folder where bluepy is installed and

cd ~.pyenv/versions/3.7.6/lib/python3.7/site-packages/bluepy

Grant Sudo privileges to bluepy-helper with the following command

sudo setcap 'cap_net_raw,cap_net_admin+eip' bluepy-helper

Creating a sensor value acquisition script

Create the following script to get the sensor value

switchbot.py


from bluepy import btle
import struct

#Broadcast data acquisition delegate
class SwitchbotScanDelegate(btle.DefaultDelegate):
    #constructor
    def __init__(self, macaddr):
        btle.DefaultDelegate.__init__(self)
        #Variables for holding sensor data
        self.sensorValue = None
        self.macaddr = macaddr

    #Scan handler
    def handleDiscovery(self, dev, isNewDev, isNewData):
        #If you find a device with the target Mac address
        if dev.addr == self.macaddr:
            #Extract advertisement data
            for (adtype, desc, value) in dev.getScanData():  
                #Data retrieval is executed when the environment sensor is used.
                if desc == '16b Service Data':
                    #Extract sensor data
                    self._decodeSensorData(value)

    #Extract sensor data and convert to dict format
    def _decodeSensorData(self, valueStr):
        #Sensor data from character strings(4th and subsequent characters)Only take out and convert to binary
        valueBinary = bytes.fromhex(valueStr[4:])
        #Convert binary sensor data to numbers
        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
        #Store in dict type
        self.sensorValue = {
            'SensorType': 'SwitchBot',
            'Temperature': temp,
            'Humidity': humid,
            'BatteryVoltage': batt
        }

Same as the Omron environment sensor BAG version, the sensor value is acquired in the broadcast mode. Since the acquired data content was complicated, the above reference

Create main script

Create a main script to call the sensor value acquisition script

switchbot_toSpreadSheet.py


from bluepy import btle
from switchbot import SwitchbotScanDelegate

######Get the value of SwitchBot######
#switchbot.Set the sensor value acquisition delegate of py to execute at scan time
scanner = btle.Scanner().withDelegate(SwitchbotScanDelegate())
#Scan to get sensor value (timeout 5 seconds)
scanner.scan(5.0)
#Display the temperature as a trial
print(scanner.delegate.sensorValue['Temperature'])

#Describe the process of uploading to Google Spreadsheet in ④

Try running from the console

python switchbot_toSpreadSheet.py
25.49

You have now obtained the sensor readings in Python.

③ Hit the GAS API from Python to write data to the spreadsheet

[Omron Environment Sensor Article](https://qiita.com/c60evaporator/items/ed2ffde4c87001111c12#python%E3%81%8B%E3%82%89gas%E3%81%AEapi%E3%82%92%E5% 8F% A9% E3% 81% 84% E3% 81% A6% E3% 82% B9% E3% 83% 97% E3% 83% AC% E3% 83% 83% E3% 83% 89% E3% 82% B7% E3% 83% BC% E3% 83% 88% E3% 81% AB% E3% 83% 87% E3% 83% BC% E3% 82% BF% E6% 9B% B8% E3% 81% 8D% E8% BE% BC% E3% 81% BF) Please refer

④ Periodic execution of script

[Omron Environment Sensor Article](https://qiita.com/c60evaporator/items/ed2ffde4c87001111c12#%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%83 % 88% E3% 81% AE% E5% AE% 9A% E6% 9C% 9F% E5% AE% 9F% E8% A1% 8C) Please refer

Recommended Posts

Log the value of SwitchBot thermo-hygrometer with Raspberry Pi
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
Periodically log the value of Omron environment sensor with Raspberry Pi
Logging the value of Omron environment sensor with Raspberry Pi (USB type)
Make API of switchbot thermo-hygrometer with Node-RED
Inkbird IBS-TH1 value logged with Raspberry Pi
CSV output of pulse data with Raspberry Pi (CSV output)
Observe the Geminids meteor shower with Raspberry Pi 4
Get CPU information of Raspberry Pi with Python
Measure CPU temperature of Raspberry Pi with Python
GPGPU with Raspberry Pi
DigitalSignage with Raspberry Pi
Periodically notify the processing status of Raspberry Pi with python → Google Spreadsheet → LINE
Using the digital illuminance sensor TSL2561 with Raspberry Pi
Display images taken with the Raspberry Pi camera module
Try to visualize the room with Raspberry Pi, part 1
Let's operate GPIO of Raspberry Pi with Python CGI
Mutter plants with Raspberry Pi
Play with the Raspberry Pi Zero WH camera module Part 1
I tried running Movidius NCS with python of Raspberry Pi3
Your URL didn't respond with the value of the challenge parameter.
Production of temperature control system with Raspberry Pi and ESP32 (1)
I tried using the DS18B20 temperature sensor with Raspberry Pi
How to get temperature from switchBot thermo-hygrometer using raspberry Pi
The true value of Terraform automation starting with Oracle Cloud
I sent the data of Raspberry Pi to GCP (free)
Make a note of what you want to do in the future with Raspberry Pi
I tried to move ROS (Melodic) with the first Raspberry Pi (Stretch) at the beginning of 2021
Find the definition of the value of errno
Log in to Raspberry PI with ssh without password (key authentication)
Control the motor with a motor driver using python on Raspberry Pi 3!
Use vl53l0x with Raspberry Pi (python)
Servo motor control with Raspberry Pi
Extract the maximum value with pandas.
Find the optimal value of a function with a genetic algorithm (Part 2)
I learned how the infrared remote control works with Raspberry Pi
Serial communication with Raspberry Pi + PySerial
About the return value of pthread_mutex_init ()
Notify LINE of body temperature from BLE thermometer with Raspberry Pi # 1
OS setup with Raspberry Pi Imager
About the return value of the histogram.
Try L Chika with raspberry pi
VPN server construction with Raspberry Pi
Real-time classification of multiple objects in the camera image with deep learning of Raspberry Pi 3 B + & PyTorch
Graph display of household power consumption with 3GPI and Raspberry Pi
Solve the initial value problem of ordinary differential equations with JModelica
Try moving 3 servos with Raspberry Pi
Tips: [Python] Calculate the average value of the specified area with bedgraph
Using a webcam with Raspberry Pi
Building a distributed environment with the Raspberry PI series (Part 1: Summary of availability of diskless clients by model)
I made an npm package to get the ID of the IC card with Raspberry Pi and PaSoRi
Read the data of the NFC reader connected to Raspberry Pi 3 with Python and send it to openFrameworks with OSC
A memo to simply use the illuminance sensor TSL2561 with Raspberry Pi 2
Use Raspberry Pi to solve the problem of insufficient mobile Wi-Fi connection
[I touched the Raspberry Pi (1)] I summarized the basic operations of Minecraft Pi Edition (2015.5.23 pre-release)
CSV output of pulse data with Raspberry Pi (confirm analog input with python)
Let me show you the performance of the new Raspberry pi zero (v1.3)!
Get GrovePi + sensor value with Raspberry Pi and store it in kintone
Get the return value of an external shell script (ls) with python3
Production of temperature control system with Raspberry Pi and ESP32 (2) Production of transmission device
Measure SIM signal strength with Raspberry Pi