mikecmills2

GroveStreams Python 2.7 Hello World 2

Nov 26th, 2013
834
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.01 KB | None | 0 0
  1. #GroveStreams.com Python version 2.7 Feed Example
  2. #Demonstrates uploading two stream feeds using compression, JSON, and
  3. # a short URL (The api_key is passed as a cookie 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 httplib
  40. import StringIO
  41. import gzip
  42. import random
  43.  
  44. def compressBuf(buf):
  45.     #This method is used to compress a string
  46.     zbuf = StringIO.StringIO()
  47.     zfile = gzip.GzipFile(mode = 'wb',  fileobj = zbuf, compresslevel = 9)
  48.     zfile.write(buf)
  49.     zfile.close()
  50.     return zbuf.getvalue()
  51.  
  52. if __name__ == '__main__':
  53.    
  54.     #GroveStreams Settings
  55.     api_key = "YOUR_SECRET_API_KEY_HERE"    #Change This!!!
  56.    
  57.     component_id = "sensor1 - hello world"
  58.    
  59.     #Optionally compress the JSON feed body to decrease network bandwidth
  60.     compress = True
  61.     url = '/api/feed'
  62.    
  63.     #Connect to the server
  64.     conn = httplib.HTTPConnection('www.grovestreams.com')
  65.    
  66.     while True:
  67.        
  68.         temperature_val = random.randrange(-10, 40)
  69.         humidity_val = random.randrange(0, 100)
  70.        
  71.         #Assemble feed as a JSON string (Let the GS servers set the sample time)
  72.         samples = []
  73.         samples.append({ 'compId' : component_id,
  74.                         'streamId' : 'temperature',
  75.                         'data' : temperature_val })
  76.         samples.append({ 'compId' : component_id,
  77.                         'streamId' : 'humidity',
  78.                         'data' : humidity_val })
  79.        
  80.         #Uncomment below to include the sample time - milliseconds since epoch
  81.         #now = datetime.datetime.now()
  82.         #sample_time = int(time.mktime(now.timetuple())) * 1000
  83.         #samples = []
  84.         #samples.append({ 'compId': component_id, 'streamId' : 'temperature', 'data' : temperature_val, 'time' : sample_time })
  85.         #samples.append({ 'compId': component_id, 'streamId' : 'humidity', 'data' : humidity_val, 'time' : sample_time  })
  86.        
  87.         json_encoded = json.dumps(samples);
  88.        
  89.         try:      
  90.            
  91.             if compress:
  92.                 #Compress the JSON HTTP body
  93.                 body = compressBuf(json_encoded)
  94.  
  95.                 print('Compressed feed ' + str(100*len(body) / len(json_encoded)) + '%')
  96.                
  97.                 headers = {"Content-Encoding" : "gzip" , "Connection" : "close",
  98.                            "Content-type" : "application/json", "Cookie" : "api_key="+api_key}
  99.                
  100.                 #GS limits feed calls to one per 10 seconds per outward facing router IP address
  101.                 #Use the ip_addr and headers assignment below to work around this
  102.                 # limit by setting the below to this device's IP address
  103.                 #ip_addr = "192.168.1.72"
  104.                 #headers = {"Content-Encoding" : "gzip" , "Connection" : "close", "Content-type" : "application/json", "X-Forwarded-For" : ip_addr, "Cookie" : "api_key="+api_key}
  105.                
  106.             else:
  107.                 #No Compression
  108.                 body = json_encoded
  109.                 headers = {"Connection" : "close", "Content-type" : "application/json",
  110.                            "Cookie" : "api_key="+api_key}
  111.  
  112.                 #GS limits calls to 10 per second per outward facing router IP address
  113.                 #Use the ip_addr and headers assignment below to work around this
  114.                 # limit by setting the below to this device's IP address
  115.                 #ip_addr = "192.168.1.72"
  116.                 #headers = {"Connection" : "close", "Content-type" : "application/json", "X-Forwarded-For" : ip_addr, "Cookie" : "api_key="+api_key}
  117.                
  118.             print('Uploading feed to: ' + url)
  119.            
  120.             #Upload the feed to GroveStreams
  121.             conn.request("PUT", url, body, headers)
  122.              
  123.             #Check for errors
  124.             response = conn.getresponse()
  125.             status = response.status
  126.            
  127.             if status != 200 and status != 201:
  128.                 try:
  129.                     if (response.reason != None):
  130.                         print('HTTP Failure Reason: ' + response.reason + ' body: ' + response.read())
  131.                     else:
  132.                         print('HTTP Failure Body: ' + response.read())
  133.                 except Exception:
  134.                     print('HTTP Failure Status: %d' % (status) )
  135.        
  136.         except Exception as e:
  137.             print('HTTP Failure: ' + str(e))
  138.        
  139.         finally:
  140.             if conn != None:
  141.                 conn.close()
  142.        
  143.         #Pause for ten seconds
  144.         time.sleep(10)
  145.          
  146.     # quit
  147.     exit(0)
Add Comment
Please, Sign In to add comment