mikecmills2

GroveStreams Python 3.2 Hello World 2

Nov 26th, 2013
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.83 KB | None | 0 0
  1. #GroveStreams.com Python 3.2 Feed Example
  2. #Demonstrates uploading two stream feeds using compression, JSON, and
  3. # a short URL (The org and api_key values are passed as cookies instead
  4. # of as part of the URL)
  5. #The GS API being used will automatically create a component with
  6. # two Random streams if they do not already exist
  7.  
  8. #This example uploads two stream feeds, random temperature and humidity
  9. # samples every 10 seconds.
  10. #A full "how to" guide for this example can be found at:
  11. # https://www.grovestreams.com/developers/getting_started_helloworld_python.html
  12. #It relies and the GroveStreams API which can be found here:
  13. # https://www.grovestreams.com/developers/api.html#2
  14.  
  15. # License:
  16. # Copyright 2014 GroveStreams LLC.
  17. # Licensed under the Apache License, Version 2.0 (the "License");
  18. # you may not use this file except in compliance with the License.
  19. # You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
  20. #
  21. # Unless required by applicable law or agreed to in writing, software
  22. # distributed under the License is distributed on an "AS IS" BASIS,
  23. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  24. # See the License for the specific language governing permissions and
  25. # limitations under the License.
  26.  
  27. #GroveStreams Setup:
  28.  
  29. #* Sign Up for Free User Account - https://www.grovestreams.com
  30. #* Create a GroveStreams organization
  31. #* Enter the GroveStreams api key under "GroveStreams Settings" below  
  32. #*    (Can be retrieved from a GroveStreams organization:
  33. #*     click the Api Keys toolbar button,
  34. #*     select your Api Key, and click View Secret Key)
  35.  
  36. import time
  37. import datetime
  38. import json
  39. import http.client
  40. import io
  41. import gzip
  42. import random
  43.  
  44.  
  45. if __name__ == '__main__':
  46.    
  47.     #GroveStreams Settings
  48.     api_key = "YOUR_SECRET_API_KEY_HERE"    #Change This!!!
  49.    
  50.     component_id = "sensor1 - hello world"
  51.    
  52.     #Optionally compress the JSON feed body to decrease network bandwidth
  53.     compress = True
  54.     url = '/api/feed'
  55.    
  56.     #Connect to the server
  57.     conn = http.client.HTTPConnection('www.grovestreams.com')
  58.    
  59.     while True:
  60.        
  61.         temperature_val = random.randrange(-10, 40)
  62.         humidity_val = random.randrange(0, 100)
  63.        
  64.         #Assemble feed as a JSON string (Let the GS servers set the sample time)
  65.         samples = []
  66.         samples.append({'compId' : component_id,
  67.                         'streamId' : 'temperature',
  68.                         'data' : temperature_val })
  69.         samples.append({'compId' : component_id,
  70.                          'streamId' : 'humidity',
  71.                          'data' : humidity_val })
  72.        
  73.         #Uncomment below to include the sample time - milliseconds since epoch
  74.         #now = datetime.datetime.now()
  75.         #sample_time = int(time.mktime(now.timetuple())) * 1000
  76.         #samples = []
  77.         #samples.append({ 'compId': component_id, 'streamId' : 'temperature', 'data' : temperature_val, 'time' : sample_time })
  78.         #samples.append({ 'compId': component_id, 'streamId' : 'humidity', 'data' : humidity_val, 'time' : sample_time  })
  79.        
  80.         json_encoded = json.dumps(samples);
  81.        
  82.         try:      
  83.            
  84.             if compress:
  85.                 #Compress the JSON HTTP body
  86.                 body = gzip.compress(json_encoded.encode('utf-8'))
  87.                 print('Compressed feed ' + str(100*len(body) / len(json_encoded)) + '%')
  88.                
  89.                 headers = {"Content-Encoding" : "gzip" , "Connection" : "close",
  90.                            "Content-type" : "application/json", "Cookie" : "api_key="+api_key}
  91.                
  92.                 #GS limits feed calls to one per 10 seconds per outward facing router IP address
  93.                 #Use the ip_addr and headers assignment below to work around this
  94.                 # limit by setting the below to this device's IP address
  95.                 #ip_addr = "192.168.1.72"
  96.                 #headers = {"Content-Encoding" : "gzip" , "Connection" : "close", "Content-type" : "application/json", "X-Forwarded-For" : ip_addr, "Cookie" : "api_key="+api_key}
  97.                
  98.             else:
  99.                 #No Compression
  100.                 body = json_encoded
  101.                 headers = {"Connection" : "close", "Content-type" : "application/json",
  102.                            "Cookie" : "org="+org+";api_key="+api_key}
  103.  
  104.                 #GS limits calls to 10 per second per outward facing router IP address
  105.                 #Use the ip_addr and headers assignment below to work around this
  106.                 # limit by setting the below to this device's IP address
  107.                 #ip_addr = "192.168.1.72"
  108.                 #headers = {"Connection" : "close", "Content-type" : "application/json", "X-Forwarded-For" : ip_addr, "Cookie" : "api_key="+api_key}
  109.                
  110.             print('Uploading feed to: ' + url)
  111.            
  112.             #Upload the feed to GroveStreams
  113.             conn.request("PUT", url, body, headers)
  114.              
  115.             #Check for errors
  116.             response = conn.getresponse()
  117.             status = response.status
  118.            
  119.             if status != 200 and status != 201:
  120.                 try:
  121.                     if (response.reason != None):
  122.                         print('HTTP Failure Reason: ' + response.reason + ' body: ' + response.read().decode(encoding='UTF-8'))
  123.                     else:
  124.                         print('HTTP Failure Body: ' + response.read().decode(encoding='UTF-8'))
  125.                 except Exception as e:
  126.                     print('HTTP Failure Status : %d' % (status) )
  127.        
  128.         except Exception as e:
  129.             print('HTTP Failure: ' + str(e))
  130.        
  131.         finally:
  132.             if conn != None:
  133.                 conn.close()
  134.        
  135.         #Pause for ten seconds
  136.         time.sleep(10)
  137.          
  138.     # quit
  139.     exit(0)
Add Comment
Please, Sign In to add comment