Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #GroveStreams.com Python version 2.7 Feed Example
- #Demonstrates uploading two stream feeds using compression, JSON, and
- # a short URL (The api_key is passed as a cookie instead
- # of as part of the URL)
- #The GS API being used will automatically create a component with
- # two Random streams if they do not already exist
- #This example uploads two stream feeds, random temperature and humidity
- # samples every 10 seconds.
- #A full "how to" guide for this example can be found at:
- # https://www.grovestreams.com/developers/getting_started_helloworld_python.html
- #It relies and the GroveStreams API which can be found here:
- # https://www.grovestreams.com/developers/api.html#2
- # License:
- # Copyright 2014 GroveStreams LLC.
- # Licensed under the Apache License, Version 2.0 (the "License");
- # you may not use this file except in compliance with the License.
- # You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
- #
- # Unless required by applicable law or agreed to in writing, software
- # distributed under the License is distributed on an "AS IS" BASIS,
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- # See the License for the specific language governing permissions and
- # limitations under the License.
- #GroveStreams Setup:
- #* Sign Up for Free User Account - https://www.grovestreams.com
- #* Create a GroveStreams organization
- #* Enter the GroveStreams api key under "GroveStreams Settings" below
- #* (Can be retrieved from a GroveStreams organization:
- #* click the Api Keys toolbar button,
- #* select your Api Key, and click View Secret Key)
- import time
- import datetime
- import json
- import httplib
- import StringIO
- import gzip
- import random
- def compressBuf(buf):
- #This method is used to compress a string
- zbuf = StringIO.StringIO()
- zfile = gzip.GzipFile(mode = 'wb', fileobj = zbuf, compresslevel = 9)
- zfile.write(buf)
- zfile.close()
- return zbuf.getvalue()
- if __name__ == '__main__':
- #GroveStreams Settings
- api_key = "YOUR_SECRET_API_KEY_HERE" #Change This!!!
- component_id = "sensor1 - hello world"
- #Optionally compress the JSON feed body to decrease network bandwidth
- compress = True
- url = '/api/feed'
- #Connect to the server
- conn = httplib.HTTPConnection('www.grovestreams.com')
- while True:
- temperature_val = random.randrange(-10, 40)
- humidity_val = random.randrange(0, 100)
- #Assemble feed as a JSON string (Let the GS servers set the sample time)
- samples = []
- samples.append({ 'compId' : component_id,
- 'streamId' : 'temperature',
- 'data' : temperature_val })
- samples.append({ 'compId' : component_id,
- 'streamId' : 'humidity',
- 'data' : humidity_val })
- #Uncomment below to include the sample time - milliseconds since epoch
- #now = datetime.datetime.now()
- #sample_time = int(time.mktime(now.timetuple())) * 1000
- #samples = []
- #samples.append({ 'compId': component_id, 'streamId' : 'temperature', 'data' : temperature_val, 'time' : sample_time })
- #samples.append({ 'compId': component_id, 'streamId' : 'humidity', 'data' : humidity_val, 'time' : sample_time })
- json_encoded = json.dumps(samples);
- try:
- if compress:
- #Compress the JSON HTTP body
- body = compressBuf(json_encoded)
- print('Compressed feed ' + str(100*len(body) / len(json_encoded)) + '%')
- headers = {"Content-Encoding" : "gzip" , "Connection" : "close",
- "Content-type" : "application/json", "Cookie" : "api_key="+api_key}
- #GS limits feed calls to one per 10 seconds per outward facing router IP address
- #Use the ip_addr and headers assignment below to work around this
- # limit by setting the below to this device's IP address
- #ip_addr = "192.168.1.72"
- #headers = {"Content-Encoding" : "gzip" , "Connection" : "close", "Content-type" : "application/json", "X-Forwarded-For" : ip_addr, "Cookie" : "api_key="+api_key}
- else:
- #No Compression
- body = json_encoded
- headers = {"Connection" : "close", "Content-type" : "application/json",
- "Cookie" : "api_key="+api_key}
- #GS limits calls to 10 per second per outward facing router IP address
- #Use the ip_addr and headers assignment below to work around this
- # limit by setting the below to this device's IP address
- #ip_addr = "192.168.1.72"
- #headers = {"Connection" : "close", "Content-type" : "application/json", "X-Forwarded-For" : ip_addr, "Cookie" : "api_key="+api_key}
- print('Uploading feed to: ' + url)
- #Upload the feed to GroveStreams
- conn.request("PUT", url, body, headers)
- #Check for errors
- response = conn.getresponse()
- status = response.status
- if status != 200 and status != 201:
- try:
- if (response.reason != None):
- print('HTTP Failure Reason: ' + response.reason + ' body: ' + response.read())
- else:
- print('HTTP Failure Body: ' + response.read())
- except Exception:
- print('HTTP Failure Status: %d' % (status) )
- except Exception as e:
- print('HTTP Failure: ' + str(e))
- finally:
- if conn != None:
- conn.close()
- #Pause for ten seconds
- time.sleep(10)
- # quit
- exit(0)
Add Comment
Please, Sign In to add comment