mikecmills2

GroveStreams Python 3.2 Hello World 1

Nov 26th, 2013
694
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.54 KB | None | 0 0
  1. #GroveStreams.com Python 3.2 Feed Example
  2. #Demonstrates uploading two stream feeds within a URL and URL
  3. # encoding
  4.  
  5. #This example uploads two stream feeds, random temperature and humidity
  6. # samples every 10 seconds.
  7. #A full "how to" guide for this example can be found at:
  8. # https://www.grovestreams.com/developers/getting_started_helloworld_python.html
  9. #It relies and the GroveStreams API which can be found here:
  10. # https://www.grovestreams.com/developers/api.html#1
  11.  
  12. # License:
  13. # Copyright 2014 GroveStreams LLC.
  14. # Licensed under the Apache License, Version 2.0 (the "License");
  15. # you may not use this file except in compliance with the License.
  16. # You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
  17. #
  18. # Unless required by applicable law or agreed to in writing, software
  19. # distributed under the License is distributed on an "AS IS" BASIS,
  20. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21. # See the License for the specific language governing permissions and
  22. # limitations under the License.
  23.  
  24. #GroveStreams Setup:
  25.  
  26. #* Sign Up for Free User Account - https://www.grovestreams.com
  27. #* Create a GroveStreams organization
  28. #* Enter the GroveStreams api key under "GroveStreams Settings" below  
  29. #*    (Can be retrieved from a GroveStreams organization:
  30. #*     click the Api Keys toolbar button,
  31. #*     select your Api Key, and click View Secret Key)
  32.  
  33. import time
  34. import datetime
  35. import http.client
  36. import random
  37. import urllib.parse
  38.  
  39.  
  40. if __name__ == '__main__':
  41.    
  42.     #GroveStreams Settings
  43.     api_key = "YOUR_SECRET_API_KEY_HERE"    #Change This!!!
  44.    
  45.     component_id = "sensor1 - hello world"
  46.     base_url = '/api/feed?'
  47.    
  48.     conn = http.client.HTTPConnection('www.grovestreams.com')
  49.    
  50.     while True:
  51.        
  52.         temperature_val = random.randrange(-10, 40)
  53.         humidity_val = random.randrange(0, 100)
  54.        
  55.         #Upload the feed
  56.         try:    
  57.             #Let the GS servers set the sample times (encode parameters)
  58.             url = base_url + urllib.parse.urlencode({'compId' : component_id, 'temperature' : temperature_val, 'humidity' : humidity_val})
  59.            
  60.             #Alternative URL that includes the sample time
  61.             #now = datetime.datetime.now()
  62.             #sample_time = int(time.mktime(now.timetuple())) * 1000
  63.             #url = base_url + urllib.parse.urlencode({'compId' : component_id, 'time' : sample_time, 'temperature' : temperature_val, 'humidity' : humidity_val})
  64.            
  65.             #Alternative URL that uses the stream order to determine where
  66.             # to insert the samples
  67.             #url = base_url + urllib.parse.urlencode({'compId' : component_id, 'data' : [temperature_val, humidity_val]}, True)
  68.            
  69.             #The api_key token can be passed as a URL parameter or as cookies.
  70.             # We've chosen to pass it as a cookie to keep the URL length small as
  71.             # some devices have a URL size limit
  72.             headers = {"Connection" : "close", "Content-type": "application/json", "Cookie" : "api_key="+api_key}
  73.            
  74.             #GS limits feed calls to one per 10 seconds per outward facing router IP address
  75.             #Use the ip_addr and headers assignment below to work around this
  76.             # limit by setting the below to this device's IP address (an http 403 error could indicate you need the below)
  77.             #ip_addr = "192.168.1.72"
  78.             #headers = {"Connection" : "close", "Content-type": "application/json", "X-Forwarded-For": ip_addr, "Cookie" : "api_key="+api_key}
  79.            
  80.             print('Uploading feed to: ' + url)
  81.            
  82.             conn.request("PUT", url, "", headers)
  83.            
  84.             #Check for errors
  85.             response = conn.getresponse()
  86.             status = response.status
  87.            
  88.             if status != 200 and status != 201:
  89.                 try:
  90.                     if (response.reason != None):
  91.                         print('HTTP Failure Reason: ' + response.reason + ' body: ' + response.read().decode(encoding='UTF-8'))
  92.                     else:
  93.                         print('HTTP Failure Body: ' + response.read().decode(encoding='UTF-8'))
  94.                 except Exception:
  95.                     print('HTTP Failure Status: %d' % (status) )
  96.        
  97.         except Exception as e:
  98.             print('HTTP Failure: ' + str(e))
  99.        
  100.         finally:
  101.             if conn != None:
  102.                 conn.close()
  103.        
  104.         #Pause for ten seconds
  105.         time.sleep(10)
  106.  
  107.     # quit
  108.     exit(0)
Add Comment
Please, Sign In to add comment