s0_detect.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import RPi.GPIO as g
  2. from time import sleep
  3. import time
  4. import json,socket
  5. configfile="config.json"
  6. cf=open(configfile,"r")
  7. log_conf=json.load(cf)
  8. cf.close()
  9. global devicename
  10. devicename=socket.gethostname()
  11. global lastcount
  12. lastcount=0
  13. if "device" in log_conf:
  14. devicename=log_conf['device']
  15. g.setmode(g.BCM)
  16. g.setup(1, g.IN,pull_up_down=g.PUD_UP)
  17. global revcount
  18. revcount = []
  19. def increaserev(channel):
  20. global revcount
  21. revcount.append(int(time.time()*1000))
  22. g.add_event_detect(1, g.RISING, callback=increaserev)
  23. while True:
  24. sleep(60)
  25. print "RPM is {0}".format(len(revcount))
  26. if len(revcount) > 0:
  27. rc=revcount[:]
  28. revtime=0
  29. for i in rc:
  30. if i > (revtime+100):
  31. revtime=i
  32. json_out={"time": i,"device": devicename,"payload":{"S0":{"timestamp": i,"sensor":"S0","i2c":0,"value":1}}}
  33. try:
  34. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  35. except:
  36. print("{}: could not connect to database".format(time.time()))
  37. else:
  38. try:
  39. s.connect(("banana", 24048))
  40. except:
  41. print("{}: could not connect to database".format(time.time()))
  42. else:
  43. s.sendall(json.dumps(json_out))
  44. s.close()
  45. revcount.remove(i)
  46. else:
  47. revcount.remove(i)
  48. # revcount = 0