Advertisement
Guest User

Python json

a guest
Feb 9th, 2017
387
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. import time
  2. import sys
  3. import datetime
  4. from influxdb import InfluxDBClient
  5. import Adafruit_DHT
  6. import json
  7.  
  8. # Set this variables, influxDB should be localhost on Pi
  9. host = "localhost"
  10. port = 8086
  11. user = "pi"
  12. password = "Missyoujack1."
  13.  
  14. # The database we created
  15. dbname = "logger"
  16. # Sample period (s)
  17. interval = 1
  18.  
  19. # Allow user to set session and runno via args otherwise auto-generate
  20. if len(sys.argv) > 1:
  21. if (len(sys.argv) < 3):
  22. print "Must define session and runNo!!"
  23. sys.exit()
  24. else:
  25. session = sys.argv[1]
  26. runNo = sys.argv[2]
  27. else:
  28. session = "dev"
  29. now = datetime.datetime.now()
  30. runNo = now.strftime("%Y%m%d%H%M")
  31.  
  32. print "Session: ", session
  33. print "runNo: ", runNo
  34.  
  35. # Create the InfluxDB object
  36. client = InfluxDBClient(host, port, user, password, dbname)
  37.  
  38. # Run until keyboard out
  39. try:
  40. while True:
  41. # This gets a dict of the three values
  42. iso = time.ctime()
  43. humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, 4)
  44. if humidity is not None:
  45. humidity_1 = humidity
  46. if temperature is not None:
  47. temperature_1 = temperature
  48.  
  49. json_body = [
  50. {
  51. "measurement": session,
  52. "tags": {
  53. "run": runNo,
  54. },
  55. "time": iso,
  56. "fields": {
  57. "humidity" : format(humidity_1, '.2f'),
  58. "temperature" : format(temperature_1, '.2f')
  59.  
  60. }
  61. }
  62. ]
  63.  
  64. # Write JSON to InfluxDB
  65. client.write_points(json_body)
  66. # Wait for next sample
  67. time.sleep(interval)
  68.  
  69. except KeyboardInterrupt:
  70. pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement