Skip to content

Commit

Permalink
Merge pull request #190 from mexon/sample-python-script
Browse files Browse the repository at this point in the history
Add Python program to scan for reflashed LYWSD03MMC
  • Loading branch information
atc1441 authored Jun 10, 2021
2 parents 958071f + 07a475e commit 618b657
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
16 changes: 16 additions & 0 deletions contrib/python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# Quick Thermometer scan in Python

This is intended as a demo of how to read BLE announcements in Python. It is based on [bluepy](https://github.com/IanHarvey/bluepy).

## Usage

```
❯ pip3 install bluepy
[...]
❯ python3 scan-thermometer.py
{"timestamp": "2021-06-10T20:36:50+02:00", "mac": "A4:C1:38:XX:XX:XX", "temperature": 23.4, "humidity": 52, "battery_percent": 85, "battery_volt": 0.328, "count": 22}
```

The program terminates after reading one value, or after 10s.

The scan is performed in passive mode.
35 changes: 35 additions & 0 deletions contrib/python/scan-thermometer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from bluepy.btle import Scanner, DefaultDelegate, BTLEInternalError
import json
from datetime import datetime

class ScanDelegate(DefaultDelegate):
def __init__(self):
DefaultDelegate.__init__(self)

def handleDiscovery(self, dev, isNewDev, isNewData):
for (sdid, desc, val) in dev.getScanData():
if self.isTemperature(dev.addr, sdid, val):
print(json.dumps(self.parseData(val)))
exit()

def isTemperature(self, addr, sdid, val):
if sdid != 22:
return False
if len(val) != 30:
return False
return True

def parseData(self, val):
bytes = [int(val[i:i+2], 16) for i in range(0, len(val), 2)]
return {
'timestamp': datetime.now().astimezone().replace(microsecond=0).isoformat(),
'mac': ":".join(["{:02X}".format(bytes[i]) for i in range(2,8)]),
'temperature': (bytes[8] * 16 + bytes[9]) / 10,
'humidity': bytes[10],
'battery_percent': bytes[11],
'battery_volt': (bytes[12] * 16 + bytes[13]) / 1000,
'count': bytes[14],
}

scanner = Scanner().withDelegate(ScanDelegate())
scanner.scan(10.0, passive=True)

0 comments on commit 618b657

Please sign in to comment.