API Example: Get Stream Samples


This script retrieves stream samples. It returns the samples as a json array.

# GroveStreams.com Python 3.7 Example
# Demonstrates getting data from a stream using the GroveStreams API
 
 
# License:
# Copyright 2019 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.

import requests
import datetime


def checkResponse(response):
    if response.status_code != 200 and response.status_code != 201:

        if (response.reason != None):
            raise Exception("HTTP Failure Reason: " + response.reason + " body: " +  response.content.decode('utf-8'))
        else:
            raise Exception("HTTP Failure Body: " +  response.content.decode('utf-8'))
                  

def main():
    
    #CHANGE THESE!!!!!!
    api_key = '4cc9b56f-c542-3d01-8909-31fe29911249'
    compId = "device11"     
    streamId  = "temp"
    

    # Download the last stream value
    urlBase = "https://grovestreams.com/api/"

    response = requests.get(urlBase + "comp/" + compId + "/stream/" + streamId + "/last_value?api_key=" + api_key)
    checkResponse(response)     
    json = response.json()
    print(str(json))
    print("Last Value: " + str(json[0]["data"]))
    epochTime = json[0]["time"] / 1000
    print("Last Value Time: " + datetime.datetime.fromtimestamp(epochTime).strftime('%Y-%m-%d %H:%M:%S.%f'))
   
    #Download the high for the day
    response = requests.get(urlBase + "comp/" + compId + "/stream/" + streamId + "/cycle/day/stat/MAX/last_value?api_key=" + api_key)
    checkResponse(response)     
    json = response.json()
    print(str(json))
    print("Day High Value: " + str(json[0]["data"]))
    epochTime = json[0]["time"] / 1000
    print("Day High Time: " + datetime.datetime.fromtimestamp(epochTime).strftime('%Y-%m-%d %H:%M:%S.%f'))
  
    #Download a time range of samples
    startDate = int(datetime.datetime(2019, 7, 29).timestamp() * 1000)
    endDate = int(datetime.datetime(2019, 7, 30).timestamp() * 1000)
    response = requests.get(urlBase + "comp/" + compId + "/stream/" + streamId + "/feed?api_key=" + api_key + "&sd=" + str(startDate) + "&ed=" + str(endDate))
    checkResponse(response)     
    json = response.json()
    print(str(json))
   

if __name__ == "__main__":
    try:    
        main()
    except Exception as e:
        print(str(e))
# quit
exit(0)