Skip to content

Instantly share code, notes, and snippets.

@ma2shita
Created November 4, 2019 03:33
Show Gist options
  • Save ma2shita/04bde58c3a72d2d057ca4999cabbd325 to your computer and use it in GitHub Desktop.
Save ma2shita/04bde58c3a72d2d057ca4999cabbd325 to your computer and use it in GitHub Desktop.
"""
[Unit]
Description=Garage reporter using HTTP with SORACOM Unified Endpoint
After=network-online.target
[Service]
Type=simple
WorkingDirectory=/home/pi/switchbot
ExecStart=/home/pi/switchbot/bin/python3 -B garage_reporter_with_soracom_unified.py
ExecStop=/bin/kill -INT ${MAINPID}
Restart=always
RestartSec=5s
StartLimitBurst=10
[Install]
WantedBy=default.target
"""
import time
import json
import urllib.request
import VL53L0X
THING_NAME = "GarageSwitchBot1"
HEADER = {'Content-Type': 'application/json'}
URL = "http://unified.soracom.io"
THRESHOLD = 0.95
def main():
tof = VL53L0X.VL53L0X(i2c_bus=1, i2c_address=0x29)
tof.open()
tof.start_ranging()
prev = 0
while True:
dists = list(map(lambda _: tof.get_distance(), range(5))) # measurement 5 times
#print(dists, flush=True)
curr = max(dists)
a = [curr, prev]
prev = curr
if (1 - (min(a) / max(a))) > THRESHOLD:
v = {"thing_name": THING_NAME, "distance_mm": curr}
payload = json.dumps(v, ensure_ascii=False).encode('UTF-8')
print(payload, flush=True)
req = urllib.request.Request(URL, payload, HEADER)
with urllib.request.urlopen(req) as res:
_ = res.read()
#else:
#print("skip", flush=True)
time.sleep(3)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment