Skip to content

Instantly share code, notes, and snippets.

@kyonmm
Last active June 1, 2017 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kyonmm/4a9bb0b94b0632a95133d607c6978a5b to your computer and use it in GitHub Desktop.
Save kyonmm/4a9bb0b94b0632a95133d607c6978a5b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, time, requests, json, hcsr04
# you can specify interval(seconds) as first argument
interval=5 if len(sys.argv)==1 else int(sys.argv[1])
# inifinite loop
while True:
start_time = time.time()
print "- reading distance "
distance = hcsr04.read_distance()
if distance:
print "distance: %.1f cm" % (distance)
headers = {'Content-Type': 'application/octet-stream'}
payload = {'distance': round(distance*10)/10, 'hoge': { 'fuga':round(distance*10)/100} }
print "- sending data to harvest"
binary_payload = b'd\x00\xb0\x04'
try:
r = requests.post('http://harvest.soracom.io', data=binary_payload, headers=headers, timeout=5)
print r
except requests.exceptions.ConnectTimeout:
print 'ERROR: connection timeout. Is 3G connection online?'
sys.exit(1)
if r.status_code == 400:
print 'ERROR: failed to submit data. Did you enable Harvest for your SIM?'
sys.exit(1)
print
# sleep until next loop
wait = start_time + interval - time.time()
if wait > 0:
time.sleep(wait)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment