Advertisement
Guest User

Spark Query to "Tinker" via Python / cron

a guest
Jan 18th, 2014
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. #!/usr/bin/python
  2. # vim: ts=4 sw=4:expandtab:ai
  3.  
  4. DEBUG = True
  5.  
  6. #credentials for your spark core
  7. spark_api="https://api.spark.io"
  8. access_token="aaabbbcccdddeeefff1112223334445556667778"
  9. device_id="123456789abcdef123456789"
  10.  
  11. # The MARKER_FILE exists when the Spark is unreachable
  12. MARKER_FILE='spark_timeout.marker'
  13. # Logs succesful connections and data value from Spark (which must be running Tinker)
  14. OUTPUT_FILE='spark.log'
  15.  
  16. import requests
  17. import json
  18. import datetime
  19. import os
  20.  
  21. fOutput = open (OUTPUT_FILE, 'a')
  22.  
  23. # ---------------------------
  24. # Call the tinker "analogread" function on A0
  25. # ---------------------------
  26.  
  27. payload = {'access_token': access_token}
  28. function = "analogread"
  29. arguments = {'params': 'A0'}
  30. response = requests.post(spark_api + '/v1/devices/' + device_id + '/' + function , params=payload, data=arguments)
  31. if (DEBUG):
  32.     # Show the URL
  33.     print (response.url)
  34.  
  35.     print (response.text)
  36.     print (response.json())
  37.  
  38. if 'return_value' in response.json ().keys ():  # I got a valid 'return_value' from my call
  39.  
  40.     # Remove the MARKER_FILE if it exists - i.e. start logging data again
  41.     if os.path.isfile(MARKER_FILE):
  42.         os.remove (MARKER_FILE)
  43.         fOutput.write ("\n--- Spark came back online --- \n")
  44.  
  45.     avalue = response.json()['return_value']
  46.  
  47.     print ("A0 = {}".format (avalue) )
  48.  
  49.     fOutput.write ("{}, {} \n".format (datetime.datetime.now().strftime("%s"), avalue) )
  50.  
  51. else:
  52.     if not os.path.isfile(MARKER_FILE):  # i.e. This is the first failure, so log and create MARKER_FILE
  53.         print   ("Response code: {}:{} \n".format (response.status_code, response.text) )
  54.         print   ("JSON return_value: {} \n".format (response.json()['error']) )
  55.         fOutput.write ("{}, Response Code: {} \n".format (datetime.datetime.now().strftime("%s"), response.status_code) )
  56.         fOutput.write ("{}, error: {} \n".format (datetime.datetime.now().strftime("%s"), response.json()['error']) )
  57.         # Create a marker file indicating I've timed out
  58.         fError = open (MARKER_FILE, 'w')
  59.         fError.close ()
  60.  
  61. fOutput.close ()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement