def main_without_pppd(): # Initialize the Initial State streamer # Start the program by opening the cellular connection and creating a bucket for our data print("Starting streamer...") streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY, buffer_size=20) # Wait long enough for the request to complete sleep(5) while True: # Make sure there's a GPS fix if checkForFix(): # Get lat and long if getCoord(): latitude, longitude = getCoord() coord = "movv lat:" + str(latitude) + "," + "movv lgt:" + str( longitude) print coord # Buffer the coordinates to be streamed streamer.log("Coordinates", coord) sleep(SECONDS_BETWEEN_READS) print "streaming location to Initial State" # Flush the streaming queue and send the data streamer.flush() print "streaming complete"
def main(): streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) # Start temperature stream thread try: thread.start_new_thread(stream_temp, (streamer, )) except: print "Error: unable to start temperature streamer thread" # Door sensor door_status = 1 while True: ## if the switch is open if (io.input(door_pin) == True and door_status != 0): streamer.log(":door: Door", "Open") print "Door Open" streamer.flush() door_status = 0 ## if the switch is closed if (io.input(door_pin) == False and door_status != 1): streamer.log(":door: Door", "Close") print "Door Closed" streamer.flush() door_status = 1 time.sleep(2)
def monitor_tilt(): streamer = Streamer(bucket_name="Boiling", bucket_key="HG9YAAUM5DX4", access_key="ist_QX41bivamY4BhpNUbQwSIfuePaW23bGb") temperature_buffer = [] gravity_buffer = [] while True: beacons = distinct(blescan.parse_events(sock, 100)) for beacon in beacons: print(temperature_buffer) print(gravity_buffer) if beacon['uuid'] in TILTS.keys(): temperature_buffer.append(beacon['major']) gravity_buffer.append(beacon['minor']) if len(temperature_buffer) >= 1: print("f") temperature_average = round( float(sum(temperature_buffer)) / float(len(temperature_buffer)), 3) gravity_average = round( float(sum(gravity_buffer)) / 1000 * float(len(gravity_buffer)), 3) print("Temp Avg:") print(temperature_average) print("Gravity Avg:") print(gravity_average) streamer.log("Temperature", temperature_average) streamer.log("Gravity", gravity_average) del temperature_buffer[:] del gravity_buffer[:] time.sleep(1)
def run(self): self.logger.write("readingsThread started") try: streamer = Streamer(bucket_name="HandheldPi Stream", access_key="y8ZCpNZ5ZYQQLfU5zKqdZrSEyizKFc17") con = sqlite.connect('/home/pi/handheldPi/handheldPi.db') while True: cur = con.cursor() humidity, temperature = Adafruit_DHT.read_retry(11, 23) cur.execute( "INSERT INTO readings (reading_date, reading_time, reading_type, value) VALUES (date('now'), time('now'), 'temperature', ?)", (temperature, )) cur.execute( "INSERT INTO readings (reading_date, reading_time, reading_type, value) VALUES (date('now'), time('now'), 'humidity', ?)", (humidity, )) con.commit() streamer.log("Temperature", temperature) streamer.log("Humidity", humidity) time.sleep(5) except sqlite.Error, e: if con: con.rollback() print("Error %s:" % e.args[0]) self.logger.write("Error %s:" % e.args[0]) con.close() exit(1)
def post_data_to_initialstate(field_name, sensor_value): streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=IS_ACCESS_KEY) # send some data streamer.log(field_name, sensor_value) # flush and close the stream streamer.close()
def initial_report(temp, humi, config): from ISStreamer.Streamer import Streamer streamer = Streamer(bucket_name=config["bucket_name"], bucket_key=config["bucket_key"], access_key=config["access_key"]) streamer.log("Temperature", round(temp, 1)) streamer.log("Humidity", round(humi, 1)) print("Initial State Committed")
def logToInitialState(self): utcnow = datetime.utcnow() bucketKey = "{0} - coffee_scale_data".format(self.environment) streamer = Streamer(bucket_name="{0} - Coffee Scale Data".format(self.environment), bucket_key=bucketKey, access_key=self.initialStateKey) if self.potIsLifted(): streamer.log("Coffee Pot Lifted", True) streamer.log("Coffee Weight", self._currentWeight) streamer.close()
def logToInitialState(self): utcnow = datetime.utcnow() bucketKey = "{0} - coffee_scale_data".format(self.environment) streamer = Streamer(bucket_name="{0} - Coffee Scale Data".format( self.environment), bucket_key=bucketKey, access_key=self.initialStateKey) if self.potIsLifted(): streamer.log("Coffee Pot Lifted", True) streamer.log("Coffee Weight", self._currentWeight) streamer.close()
def send_value(t): # Streamer constructor, this will create a bucket called Python Stream Example # you'll be able to see this name in your list of logs on initialstate.com # your access_key is a secret and is specific to you, don't share it! streamer = Streamer(bucket_name="Temperature Perros-Guirec", bucket_key="VFSWQRTVFX56", access_key="TpxF1xIFECwXn4XuGsGYvHHAhLY1kJHU") streamer.log("temp", t) streamer.log("temperature Perros-Guirec", t) # Once you're finished, close the stream to properly dispose streamer.close() return
def main(): if len(sys.argv) != 2: print "Usage: " + sys.argv[0] + " <pid>" exit() pid = sys.argv[1] streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) if psutil.pid_exists(int(pid)) == False: print "Error: That process doesn't exist! Exiting ..." exit() else: streamer.log(PROCESS_NAME,"Running") streamer.flush() while True: if psutil.pid_exists(int(pid)) == False: streamer.log(PROCESS_NAME,"Exited") streamer.flush() exit() else: streamer.log(PROCESS_NAME,"Running") process = Popen(['hostname', '-I'], stdout=PIPE) output, _error = process.communicate() streamer.log(PROCESS_NAME + " IP Address", output.rstrip()) streamer.flush() time.sleep(60*MINUTES_BETWEEN_READS)
def main_with_pppd(): global STREAM_COUNT # Initialize the Initial State streamer # Start the program by opening the cellular connection and creating a bucket for our data if openPPPD(): print( "\n\n\nOK ALRIGHT THEN! Everything looks good! Starting ISS streamer..." ) streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY, buffer_size=20) # Wait long enough for the request to complete for c in range(INIT_DELAY): print("Starting in T-minus {} second".format(INIT_DELAY - c)) sleep(1) while True: # Close the cellular connection if closePPPD(): READ_COUNT = 0 # reset counter after closing connection sleep(1) # The range is how many data points we'll collect before streaming for i in range(DATA_POINT): # Make sure there's a GPS fix if checkForFix(): # Get lat and long print("i = {}".format(i)) if getCoord(): READ_COUNT += 1 latitude, longitude = getCoord() coord = "lat:" + str(latitude) + "," + "lgt:" + str( longitude) print coord # Buffer the coordinates to be streamed print( "Saving read #{} into buffer.".format(READ_COUNT)) streamer.log("Coordinates", coord) sleep(SECONDS_BETWEEN_READS) # 1 second # Turn the cellular connection on every 2 reads if i == DATA_POINT - 1: sleep(1) print "opening connection" if openPPPD(): STREAM_COUNT += 1 print("Streaming location to Initial State") # streamer.log("Read Count",str(READ_COUNT)) streamer.log("Stream Count", str(STREAM_COUNT)) # Flush the streaming buffer queue and send the data streamer.flush() # flush all the 4 readings to ISS print("Streaming complete")
def initialstate_stream_reading(reading): if "initialstate.enabled" not in configs or configs[ "initialstate.enabled"] != 1: return try: from ISStreamer.Streamer import Streamer streamer = Streamer(bucket_name=configs["initialstate.bucket_name"], bucket_key=configs["initialstate.bucket_key"], access_key=configs["initialstate.access_key"]) streamer.log(key=configs["initialstate.item_key"], value=reading) streamer.flush() streamer.close() log.log_restarts("sent initialstate reading") except Exception as ex: log.log_errors("problem streaming reading to initialstate!")
def sender_is(): if IS: global gpspoll streamer = Streamer(bucket_name="GPS Tracker", bucket_key=ID, access_key="00000000000000000000000000000000") while 1: time.sleep(5) streamer.log("Satellites", gpspoll.sats) if gpspoll.mode > 0: streamer.log("Location", "{lat},{long}".format( lat=gpspoll.lat, long=gpspoll.long)) streamer.log("Altitude", gpspoll.alt) streamer.log("Error", max(gpspoll.accx, gpspoll.accz)) streamer.log("Error (vertical)", gpspoll.accy) debug("I told IS my location.") else: debug("I'm not telling IS my location.")
def main(): sense = SenseHat() conditions = get_conditions() astronomy = get_astronomy() if ('current_observation' not in conditions) or ('moon_phase' not in astronomy): print "Error! Wunderground API call failed, check your STATE and CITY and make sure your Wunderground API key is valid!" if 'error' in conditions['response']: print "Error Type: " + conditions['response']['error']['type'] print "Error Description: " + conditions['response']['error']['description'] exit() else: streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(":house: Location",conditions['current_observation']['display_location']['full']) while True: # -------------- Sense Hat -------------- # Read the sensors temp_c = sense.get_temperature() humidity = sense.get_humidity() pressure_mb = sense.get_pressure()
def sender_is(): if IS: global gpspoll streamer = Streamer(bucket_name="GPS Tracker", bucket_key=ID, access_key="00000000000000000000000000000000") while 1: time.sleep(5) streamer.log("Satellites", gpspoll.sats) if gpspoll.mode > 0: streamer.log( "Location", "{lat},{long}".format(lat=gpspoll.lat, long=gpspoll.long)) streamer.log("Altitude", gpspoll.alt) streamer.log("Error", max(gpspoll.accx, gpspoll.accz)) streamer.log("Error (vertical)", gpspoll.accy) debug("I told IS my location.") else: debug("I'm not telling IS my location.")
def main(): # Wait for ntpd to run for sync of the clock found_ntpd = False cnt = 0 while found_ntpd == False: for proc in psutil.process_iter(): if proc.name() == "ntpd": found_ntpd = True cnt += 1 if cnt == 60: # assume that ntpd has already run if not found in 60 seconds found_ntpd = True time.sleep(1) time.sleep(60 * MINUTES_DELAY) streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(PROCESS_NAME, "Exited") streamer.flush()
def main(argv): bucket = '' access_key = '' try: opts, args = getopt.getopt(argv,"hb:k:",["bucket_name=", "access_key="]) except getopt.GetoptError: print('example_command_line.py -b <bucket_name> -k <access_key>') for opt, arg in opts: if opt == '-h': print('example_command_line.py -b <bucket_name> -k <access_key>') elif opt in ("-b", "--bucket_name"): bucket = arg elif opt in ("-k", "--access_key"): access_key = arg streamer = Streamer(bucket_name=bucket, access_key=access_key) try: while 1: log = '' try: if (sys.version_info < (2,7,0)): sys.stderr.write("You need at least python 2.7.0 to use the ISStreamer") exit(1) elif (sys.version_info >= (3,0)): log = input() else: log = raw_input() except EOFError: break parts = log.split(',') if len(parts) == 2: streamer.log(parts[0].strip(), parts[1].strip()) else: print("format should be \"key, value\"") except KeyboardInterrupt: streamer.close()
def main(): if len(sys.argv) != 2: print("Usage: " + sys.argv[0] + " <pid>") exit() pid = sys.argv[1] streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) if not psutil.pid_exists(int(pid)): print("Error: That process doesn't exist! Exiting ...") exit() else: streamer.log(PROCESS_NAME, "Running") streamer.flush() while True: if not psutil.pid_exists(int(pid)): streamer.log(PROCESS_NAME, "Exited") streamer.flush() exit() else: streamer.log(PROCESS_NAME, "Running") streamer.flush() time.sleep(60 * MINUTES_BETWEEN_READS)
def main(argv): bucket = "" access_key = "" try: opts, args = getopt.getopt(argv, "hb:k:", ["bucket_name=", "access_key="]) except getopt.GetoptError: print("example_command_line.py -b <bucket_name> -k <access_key>") for opt, arg in opts: if opt == "-h": print("example_command_line.py -b <bucket_name> -k <access_key>") elif opt in ("-b", "--bucket_name"): bucket = arg elif opt in ("-k", "--access_key"): access_key = arg streamer = Streamer(bucket_name=bucket, access_key=access_key) try: while 1: log = "" try: if sys.version_info < (2, 7, 0): sys.stderr.write("You need at least python 2.7.0 to use the ISStreamer") exit(1) elif sys.version_info >= (3, 0): log = input() else: log = raw_input() except EOFError: break parts = log.split(",") if len(parts) == 2: streamer.log(parts[0].strip(), parts[1].strip()) else: print('format should be "key, value"') except KeyboardInterrupt: streamer.close()
def main(): curr_conditions = get_current_conditions() if ('data' not in curr_conditions): print "Error! AirQual API call failed, check your GPS coordinates and make sure your AirQual API key is valid!\n" print curr_conditions exit() else: streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) while True: curr_conditions = get_current_conditions() if ('data' not in curr_conditions): print "Error! AirQual API call failed. Skipping a reading then continuing ...\n" print curr_conditions else: streamer.log(":house: Location", LATITUDE + "," + LONGITUDE) if 'aqius' in curr_conditions['data']['current']['pollution'] and isFloat(curr_conditions['data']['current']['pollution']['aqius']): streamer.log("AQIUS",curr_conditions['data']['current']['pollution']['aqius']) if 'mainus' in curr_conditions['data']['current']['pollution']: streamer.log("MAINUS",curr_conditions['data']['current']['pollution']['mainus']) streamer.flush() time.sleep(60*MINUTES_BETWEEN_READS)
def main(): streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) # Start temperature stream thread try: thread.start_new_thread(stream_temp, (streamer, )) except: print "Error: unable to start temperature streamer thread" # Door sensor door_status = 1 while True: ## if the switch is open if (io.input(door_pin) == True and door_status != 0): streamer.log(":door: Door", "Open") print "Door Open" streamer.flush() door_status = 0 ## if the switch is closed if (io.input(door_pin) == False and door_status != 1): streamer.log(":door: Door", "Close") print "Door Closed" streamer.flush() door_status = 1 time.sleep(2)
def StartLog(): global logFile, lfOpen, Logging, streamOpen, fName, SampleC, logHeader, streamer if (((lfOpen) or (streamOpen)) and (Logging == False)): root.wm_title("DAQCplate Data Logger - LOGGING") Header = "Time," for i in range(8): if (DAQCpresent[i] == 1): desc = ['', '', '', '', '', '', '', ''] desc = daqc[i].a2dDescriptors() for k in range(8): if (desc[k] != ''): Header = Header + 'DAQC' + str(i) + '.' + desc[k] + ',' desc = ['', '', '', '', '', '', '', ''] desc = daqc[i].dinDescriptors() for k in range(8): if (desc[k] != ''): Header = Header + 'DAQC' + str(i) + '.' + desc[k] + ',' Header = Header[:-1] logHeader = Header if (lfOpen): logFile = open(fName, 'w') # logFile.write(Header) # logFile.write('\n') if (streamOpen): streamer = Streamer(bucket_name=StreamBucket.get(), bucket_key=StreamIdentifier.get(), access_key=StreamKey.get()) streamer.log("Pi-Plates", "DACQ Log Stream Starting") Logging = True SampleC = int(SampleCount.get()) else: showerror( "Logging", "You must open a log file or a stream before you can start logging" )
def streamTemp(): streamer = Streamer(bucket_name=BUCKET_NAME,bucket_key=BUCKET_KEY,access_key=ACCESS_KEY) while True: tempC = readTemp() tempF = tempC * 9.0 / 5.0 + 32.0 if tempF > TEMPERATURE_TOO_HIGH_F: streamer.log("Status", ":fire: :exclamation:") if tempF < TEMPERATURE_TOO_LOW_F: streamer.log("Status", ":snowflake: :exclamation:") streamer.log("Temperature(F)", tempF) streamer.flush() print "Temperature: " + str(tempF) + " F" time.sleep(TEMPERATURE_DELAY)
def streamTemp(): streamer = Streamer(bucket_name=BUCKET_NAME,bucket_key=BUCKET_KEY,access_key=ACCESS_KEY) while True: tempC = readTemp() tempF = tempC * 9.0 / 5.0 + 32.0 if tempF > TEMPERATURE_TOO_HIGH_F: streamer.log("Status", ":fire: :exclamation:") if tempF < TEMPERATURE_TOO_LOW_F: streamer.log("Status", ":snowflake: :exclamation:") streamer.log("Temperature(F)", tempF) streamer.flush() print("Temperature: " + str(tempF) + " F") time.sleep(TEMPERATURE_DELAY)
# Import time for delays import time # Streamer constructor, this will create a bucket called Python Stream Example # you'll be able to see this name in your list of logs on initialstate.com # your access_key is a secret and is specific to you, don't share it! streamer = Streamer(bucket_name="Sofie.py", bucket_key="Sofie", access_key="ist_kh_4Iv3IJuAd4mH82Km0H0yHD5CU9QJh") # example data logging for num in range(1, 20): time.sleep(0.1) if num % 1 == 0: streamer.log("Number", "2") if num % 2 == 0: streamer.log("Naam", "Sofie") if num % 3 == 0: streamer.log("Energie", "40") if num % 4 == 0: streamer.log("myNumber", "51.16257, 4.99084") ## This is just an example, try something of your own! ## ideas: ## - solve world hunger, one bug fix at a time ## - create the worlds first widget ## - build an army of bug-free robot kittens # Once you're finished, close the stream to properly dispose streamer.close()
data_time = time.mktime(dt.timetuple()) - 7200 #streamer = Streamer(bucket_name= "Machine 8", bucket_key= "SNSQ7RXYS8GF", access_key= "w5fQGZJFbysVOi2Hw9jQeKLYYAhJdQb7") streamer = Streamer(bucket_name="Testing2", bucket_key="ET8L9R3LVVA3", access_key="w5fQGZJFbysVOi2Hw9jQeKLYYAhJdQb7", debug_level=1) for x in range(0, 15): idx_number = x + 1 if idx_number >= 9: idx_number += 1 string = "idx" + ` idx_number ` for y in range(1, 6): data = result[x][y] streamer.log(string, data, data_time) print result[0][0] print data_time cursor.close() cnx.close() except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print "Something is wrong with your user name or password" logging.info("Something is wrong with your user name or password") elif err.errno == errorcode.ER_BAD_DB_ERROR: print "Database does not exist" logging.info("Database does not exist") else:
os.system('modprobe w1-therm') base_dir = '/sys/bus/w1/devices/' #get all 1wire serial devices in a list device_folder = glob.glob(base_dir + '28*') #expect two sensors for the master thermostat node #sensor 0 == 1 ROOM_AMBIENT_HIGH #sensor 1 == 2 DUCT_SENSE # if len(device_folder) != 2: print "ERROR NUM_SENSORS NOT TWO(2)" exit() else: device_file = [device_folder[0] + '/w1_slave',device_folder[1] + '/w1_slave'] dummy = read_temp(0) dummy = read_temp(1) sensor1 = read_temp(0) sensor2 = read_temp(1) with open("/var/www/html/1wire-1-RM_AMBIENT.html", "w") as text_file: text_file.write("[{0}]".format(sensor1)) with open("/var/www/html/1wire-2-DUCT.html", "w") as text_file: text_file.write("[{0}]".format(sensor2)) streamer.log("ThermostatAmbient","%.2f" % sensor1) streamer.log("ThermostatDUCT","%.2f" % sensor2) pistreamer.log("ThermostatAmbient","%.2f" % sensor1) pistreamer.log("ThermostatDUCT","%.2f" % sensor2) print("AMBIENT: %s" % sensor1) print("DUCT: %s" % sensor2)
def main(): sense = SenseHat() curr_conditions = get_current_conditions() if ('currently' not in curr_conditions): print "Error! Dark Sky API call failed, check your GPS coordinates and make sure your Dark Sky API key is valid!\n" print curr_conditions exit() else: streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) while True: # -------------- Sense Hat -------------- # Read the sensors temp_c = sense.get_temperature() humidity = sense.get_humidity() pressure_mb = sense.get_pressure() # Format the data temp_f = temp_c * 9.0 / 5.0 + 32.0 temp_f = float("{0:.2f}".format(temp_f)) temp_c = float("{0:.2f}".format(temp_c)) humidity = float("{0:.2f}".format(humidity)) pressure_in = 0.0295301*(pressure_mb) pressure_in = float("{0:.2f}".format(pressure_in)) pressure_mb = float("{0:.2f}".format(pressure_mb)) # Print and stream if (METRIC_UNITS): print SENSOR_LOCATION_NAME + " Temperature(C): " + str(temp_c) print SENSOR_LOCATION_NAME + " Pressure(mb): " + str(pressure_mb) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)", temp_c) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure (mb)", pressure_mb) else: print SENSOR_LOCATION_NAME + " Temperature(F): " + str(temp_f) print SENSOR_LOCATION_NAME + " Pressure(IN): " + str(pressure_in) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)", temp_f) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure (IN)", pressure_in) print SENSOR_LOCATION_NAME + " Humidity(%): " + str(humidity) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity) # -------------- Dark Sky -------------- curr_conditions = get_current_conditions() if ('currently' not in curr_conditions): print "Error! Dark Sky API call failed. Skipping a reading then continuing ...\n" print curr_conditions else: streamer.log(":house: Location",GPS_COORDS) if 'humidity' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['humidity']): streamer.log(":droplet: Humidity(%)", curr_conditions['currently']['humidity']*100) if 'temperature' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['temperature']): streamer.log("Temperature",curr_conditions['currently']['temperature']) if 'apparentTemperature' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['apparentTemperature']): streamer.log("Feels Like",curr_conditions['currently']['apparentTemperature']) if 'dewPoint' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['dewPoint']): streamer.log("Dewpoint",curr_conditions['currently']['dewPoint']) if 'windSpeed' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['windSpeed']): streamer.log(":dash: Wind Speed",curr_conditions['currently']['windSpeed']) if 'windGust' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['windGust']): streamer.log(":dash: Wind Gust",curr_conditions['currently']['windGust']) if 'windBearing' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['windBearing']): streamer.log(":dash: Wind Direction",wind_dir_icon(curr_conditions['currently']['windBearing'])) if 'pressure' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['pressure']): streamer.log("Pressure",curr_conditions['currently']['pressure']) if 'precipIntensity' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['precipIntensity']): streamer.log(":umbrella: Precipitation Intensity",curr_conditions['currently']['precipIntensity']) if 'precipProbability' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['precipProbability']): streamer.log(":umbrella: Precipitation Probabiity(%)",curr_conditions['currently']['precipProbability']*100) if 'cloudCover' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['cloudCover']): streamer.log(":cloud: Cloud Cover(%)",curr_conditions['currently']['cloudCover']*100) if 'uvIndex' in curr_conditions['currently'] and isFloat(curr_conditions['currently']['uvIndex']): streamer.log(":sunny: UV Index:",curr_conditions['currently']['uvIndex']) if 'summary' in curr_conditions['currently']: streamer.log(":cloud: Weather Summary",curr_conditions['currently']['summary']) if 'hourly' in curr_conditions: streamer.log("Today's Forecast",curr_conditions['hourly']['summary']) if 'daily' in curr_conditions: if 'data' in curr_conditions['daily']: if 'moonPhase' in curr_conditions['daily']['data'][0]: moon_phase = curr_conditions['daily']['data'][0]['moonPhase'] streamer.log(":crescent_moon: Moon Phase",moon_icon(moon_phase)) streamer.log(":cloud: Weather Conditions",weather_status_icon(curr_conditions['currently']['icon'],moon_phase)) streamer.flush() time.sleep(60*MINUTES_BETWEEN_READS)
import time from ISStreamer.Streamer import Streamer logger = Streamer(bucket_name="Stream Example", debug_level=2) logger.log("My Messages", "Stream Starting") for num in range(1, 1000): time.sleep(0.001) logger.log("My Numbers", num) if num%2 == 0: logger.log("My Booleans", False) else: logger.log("My Booleans", True) if num%3 == 0: logger.log("My Events", "pop") if num%10 == 0: logger.log("My Messages", "Stream Half Done") logger.log("My Messages", "Stream Done") logger.close()
def main(): sense = SenseHat() conditions = get_conditions() astronomy = get_astronomy() streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(":house: Location",conditions['current_observation']['display_location']['full']) while True: # -------------- Sense Hat -------------- # Read the sensors temp_c = sense.get_temperature() humidity = sense.get_humidity() pressure_mb = sense.get_pressure() # Format the data temp_f = temp_c * 9.0 / 5.0 + 32.0 temp_f = float("{0:.2f}".format(temp_f)) humidity = float("{0:.2f}".format(humidity)) pressure_in = 0.0295301*(pressure_mb) pressure_in = float("{0:.2f}".format(pressure_in)) # Print and stream print SENSOR_LOCATION_NAME + " Temperature(F): " + str(temp_f) print SENSOR_LOCATION_NAME + " Humidity(%): " + str(humidity) print SENSOR_LOCATION_NAME + " Pressure(IN): " + str(pressure_in) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)", temp_f) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure (IN)", pressure_in) # -------------- Wunderground -------------- conditions = get_conditions() astronomy = get_astronomy() if ((conditions != False) and (astronomy != False)): humidity_pct = conditions['current_observation']['relative_humidity'] humidity = humidity_pct.replace("%","") # Stream valid conditions to Initial State streamer.log(":cloud: " + CITY + " Weather Conditions",weather_status_icon(conditions, astronomy)) streamer.log(":crescent_moon: Moon Phase",moon_icon(astronomy['moon_phase']['phaseofMoon'])) streamer.log(":dash: " + CITY + " Wind Direction",wind_dir_icon(conditions, astronomy)) if isFloat(conditions['current_observation']['temp_f']): streamer.log(CITY + " Temperature(F)",conditions['current_observation']['temp_f']) if isFloat(conditions['current_observation']['dewpoint_f']): streamer.log(CITY + " Dewpoint(F)",conditions['current_observation']['dewpoint_f']) if isFloat(conditions['current_observation']['wind_mph']): streamer.log(":dash: " + CITY + " Wind Speed(MPH)",conditions['current_observation']['wind_mph']) if isFloat(conditions['current_observation']['wind_gust_mph']): streamer.log(":dash: " + CITY + " Wind Gust(MPH)",conditions['current_observation']['wind_gust_mph']) if isFloat(humidity): streamer.log(":droplet: " + CITY + " Humidity(%)",humidity) if isFloat(conditions['current_observation']['pressure_in']): streamer.log(CITY + " Pressure(IN)",conditions['current_observation']['pressure_in']) if isFloat(conditions['current_observation']['precip_1hr_in']): streamer.log(":umbrella: " + CITY + " Precip 1 Hour(IN)",conditions['current_observation']['precip_1hr_in']) if isFloat(conditions['current_observation']['precip_today_in']): streamer.log(":umbrella: " + CITY + " Precip Today(IN)",conditions['current_observation']['precip_today_in']) if isFloat(conditions['current_observation']['solarradiation']): streamer.log(":sunny: " + CITY + " Solar Radiation (watt/m^2)",conditions['current_observation']['solarradiation']) if isFloat(conditions['current_observation']['UV']): streamer.log(":sunny: " + CITY + " UV Index:",conditions['current_observation']['UV']) streamer.flush() time.sleep(60*MINUTES_BETWEEN_READS)
import serial import pynmea2 import time from ISStreamer.Streamer import Streamer serialStream = serial.Serial("/dev/ttyAMA0", 9600, timeout=0.5) # construct a streamer instance with information to append to or create # a bucket and an ini file location that contains the Initial State # Account Access Key. streamer = Streamer(bucket_name="GPS Tracker", ini_file_location="./isstreamer.ini") try: while True: sentence = serialStream.readline() if sentence.find('GGA') > 0: data = pynmea2.parse(sentence) streamer.log("Location", "{lat},{lon}".format(lat=data.latitude,lon=data.longitude)) streamer.log("Altitude ({unit})".format(unit=data.altitude_units), data.altitude) except KeyboardInterrupt: streamer.close()
port='/dev/ttyUSB1',\ baudrate=9600,\ parity=serial.PARITY_NONE,\ stopbits=serial.STOPBITS_ONE,\ bytesize=serial.EIGHTBITS,\ timeout=3) count = 1 while True: if ser.inWaiting() > 70: input = ser.readline() #print input try: tag=input.split(" ")[2] print "File written" streamer.log("DO",DO) streamer.log("Salinity",PSU) streamer.log("watertemp",temp) streamer.log("conductivity",conduct) streamer.log("depth_m",pressure) streamer.close() print "Data pushed to InitialState" print time.strftime('%X %Z %Z') except: print "not a packet with data" time.sleep(8) # sudo chmod 777 /dev/ttyUSB1 #screen -dmS vr2c.nomad python /home/udooer/nomad/nomad/vr2c.nomad.py
# This is a custom 'getting started' script, made with care for. # If you have any questions, please email us! [email protected] ##### # Import the ISStreamer module from ISStreamer.Streamer import Streamer # Import time for delays import time # Streamer constructor, this will create a bucket called Python Stream Example # you'll be able to see this name in your list of logs on initialstate.com # your access_key is a secret and is specific to you, don't share it! streamer = Streamer(bucket_name="Python Stream Example", bucket_key="python_example", access_key="******** # example data logging streamer.log("My Messages", "Stream Starting") for num in range(1, 20): time.sleep(0.1) streamer.log("My Numbers", num) if num%2 == 0: streamer.log("My Booleans", False) else: streamer.log("My Booleans", True) if num%3 == 0: streamer.log("My Events", "pop") if num%10 == 0: streamer.log("My Messages", "Stream Half Done") streamer.log("My Messages", "Stream Done") ## This is just an example, try something of your own! ## ideas:
#! /usr/bin/env python import time from ISStreamer.Streamer import Streamer import serial import requests import json inputcount = 0 sensor_id = 0 output_yn = "Y" streamer = Streamer(bucket_name="Stream Example", bucket_key="MFS123", access_key="[place acess key here]") streamer.log("My Messages", "Waiting for temp") #print("Started"); ser = serial.Serial('/dev/ttyUSB0', 9600) while True: streamer.log("My Messages", "Value Aquired") streamer.log("Input Count", inputcount) #print("Got a reading. Input count %d" % inputcount) output_yn = 'Y' sensor_output = ser.readline().strip() #Discard the first reading from the serial input is it seems to be badly formed if inputcount > 0: #print("First reading to write") data = json.loads(sensor_output)
windData = ser.readline() time.sleep(0.5) ser.write('0M1!') ser.readline() ser.readline() ser.write('0D0!') airData = ser.readline() RWD = windData.split("+")[1] RWS = windData.split("+")[2] Atemp = airData.split("+")[1] Humidity = airData.split("+")[2] dpoint = airData.split("+")[3] bpressure = airData.split("+")[4] print("data") print(RWD) print(RWS) print(Atemp) print(Humidity) print(dpoint) print(bpressure) print(" collected") streamer.log("RWD, d",RWD) streamer.log("RWS, m/s",RWS) streamer.log("BP, hPa",bpressure) streamer.log("RH, %", Humidity) streamer.log("Air Temp, C",Atemp) streamer.log("DP, C",dpoint) time.sleep(60) #screen -dmS weather.nomad python /home/udooer/nomad/nomad/atmospheric.nomad.py #to do - take 1 minute average of samples @ 10 seconds? 5 seconds?
class EventProcessor: def __init__(self): self._measured = False self.done = False self._measureCnt = 0 self._events = list(range(WEIGHT_SAMPLES)) self.bottles = 0 self._bottlesPrev = -1 self._doorStatus = False self._takeMeasurement = False self.streamer = Streamer(bucket_name=BUCKET_NAME,bucket_key=BUCKET_KEY,access_key=ACCESS_KEY) def mass(self, event): # Take measurement ony when the door closes if (self._doorStatus == True and event.doorStatus == False): self._takeMeasurement = True self._measureCnt = 0 self.streamer.log(":door: Door", "Closed") self.streamer.flush() print("Door Closed") print("Starting measurement ...") time.sleep(2) # Door is opened, ensure no measurement is being taken if (self._doorStatus == False and event.doorStatus == True): self._takeMeasurement = False self.streamer.log(":door: Door", "Open") self.streamer.flush() print("Door Opened") if (self._takeMeasurement == True and event.totalWeight > 2): self._events[self._measureCnt] = event.totalWeight*2.20462 self._measureCnt += 1 if self._measureCnt == WEIGHT_SAMPLES: self._sum = 0 for x in range(0, WEIGHT_SAMPLES-1): self._sum += self._events[x] self._weight = self._sum/WEIGHT_SAMPLES self._weightBottles = self._weight - WEIGHT_BASE self.bottles = int(round(self._weightBottles / WEIGHT_BOTTLE)) self._measureCnt = 0 print(str(self._weight) + " lbs total, " + str(self._weightBottles) + " lbs in bottles") if self.bottles < FRIDGE_EMPTY: self.streamer.log("Status", ":scream: :exclamation:") elif self.bottles < FRIDGE_GETTING_LOW: self.streamer.log("Status", ":worried: :exclamation:") else: self.streamer.log("Status", ":beers: :thumbsup:") self.streamer.flush() if (self.bottles != self._bottlesPrev) and (self.bottles >= 0): self.streamer.log(":beer: Bottles Present", self.bottles) self.streamer.flush() if (self._bottlesPrev != -1) and (self._bottlesPrev > self.bottles): for x in range(0, self._bottlesPrev-self.bottles): print("Bottle removed") self.streamer.log(":beers: Bottle Removed", ":beers:") self.streamer.flush() self._bottlesPrev = self.bottles print(str(self.bottles) + " Bottles") print("Measurement complete!") self._takeMeasurement = False if not self._measured: self._measured = True self._doorStatus = event.doorStatus @property def weight(self): if not self._events: return 0 histogram = collections.Counter(round(num, 1) for num in self._events) return histogram.most_common(1)[0][0]
# --------------------------------- grovepi.pinMode(PIR_SENSOR_PIN,"INPUT") streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) lastValue = "-" proximity = 1000 lastProximity = 0 compromised = False while True: try: # Detect motion and log when there are changes if grovepi.digitalRead(PIR_SENSOR_PIN): if lastValue != "active": lastValue = "active" streamer.log (ROOM_NAME + " Motion", lastValue) streamer.flush() print 'Motion Detected' else: if lastValue != "inactive": lastValue = "inactive" streamer.log (ROOM_NAME + " Motion", lastValue) streamer.flush() print '-' # If distance value from Ultrasonic is less than 60 cm, log it proximity = grovepi.ultrasonicRead(USR_SENSOR_PIN) if proximity < 60: if proximity != lastProximity: if not compromised: streamer.log(OBJECT_NAME + " Compromised", OBJECT_EMOJI_TOKEN)
def isFloat(string): try: float(string) return True except ValueError: return False streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) while True: try: [temp_c, hum] = grovepi.dht(DHT_SENSOR_PIN, DHT_SENSOR_TYPE) if isFloat(temp_c): if CONVERT_TO_FAHRENHEIT: temp_f = temp_c * 9.0 / 5.0 + 32.0 # print("Temperature(F) = ", temp_f) streamer.log("Temperature(F)", temp_f) else: # print("Temperature(C) = ", temp_c) streamer.log("Temperature(C)", temp_c) if (isFloat(hum)) and (hum >= 0): # print("Humidity(%) = ", hum) streamer.log(":sweat_drops: Humidity(%)", hum) streamer.flush() except IOError: print("Error") time.sleep(60 * MINUTES_BETWEEN_READS)
SECONDS_BETWEEN_READS = .2 # --------------------------------- streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) proximity = 1000 lastProximity = 0 compromised = False while True: try: # If distance value from Ultrasonic is less than 60 cm, log it proximity = grovepi.ultrasonicRead(USR_SENSOR_PIN) if proximity < 60: if proximity != lastProximity: if not compromised: streamer.log(OBJECT_NAME + " Compromised", OBJECT_EMOJI_TOKEN) compromised = True streamer.log ("Proximity to " + OBJECT_NAME + "(cm)", proximity) streamer.flush() print proximity lastProximity = proximity # Safe distance away else: proximity = 1000 compromised = False if lastProximity != 1000: streamer.log ("Proximity to " + OBJECT_NAME + "(cm)", proximity) streamer.flush() print proximity lastProximity = proximity
def main(): # --------- local Path --------- configPath = os.path.dirname(os.path.abspath( sys.argv[0])) + '/WlanThermoInitialstate.cfg' # --------- local Tags --------- force_data = False NoSendCPU = False NoSendPit = False delTemp = False bExit = False # -------------- Kommandozeilen Parameter -------------- for x in range(1, len(sys.argv)): if sys.argv[x] == '/dT' or sys.argv[x] == '/fa': delTemp = True bExit = sys.argv[x] == '/dT' elif sys.argv[x] == '/ft': force_data = True elif sys.argv[x] == '/nc': NoSendCPU = True elif sys.argv[x] == '/np': NoSendPit = True elif '/eC' == sys.argv[x][:3]: arg = sys.argv[x] cfgpath = arg.split('=') if os.path.isfile(cfgpath[1]): configPath = cfgpath[1] else: print('Parameter /eC File %s not exists!' % cfgpath[1]) else: print('Wrong Parameter %s in Commandline' % sys.argv[x]) exit() #print('ConfigPath: ' + configPath) # -------------- Konfiguration -------------- cfg = ConfigParser.ConfigParser() cfg.read(configPath) myfile = cfg.get('Local', 'Temp_File') s = cfg.get('Options', 'notSendCPU') sendCPU = (s.upper() != 'TRUE') and not NoSendCPU s = cfg.get('Options', 'notSendPit') sendPit = (s.upper() != 'TRUE') and not NoSendPit BUCKET_NAME = cfg.get('Initialstate', 'BUCKET_NAME') BUCKET_KEY = cfg.get('Initialstate', 'BUCKET_KEY') ACCESS_KEY = cfg.get('Initialstate', 'ACCESS_KEY') WlanThermoURL = cfg.get('WlanThermo', 'URL') # -------------- Loeschen der Temporaeren Datei -------------- if delTemp: delete_loc_json(myfile) if bExit: exit() # -------------- WlanThermo -------------- #neue Daten lesen values = get_values(WlanThermoURL) # -------------- alte Daten von file lesen -------------- values_old = read_loc_json(myfile) # -------------- pruefen auf inhalt -------------- force_new_data = ('temp_unit' not in values_old) # -------------- Manipulieren einzelner Werte -------------- values['cpu_load'] = round(values['cpu_load'], 2) if values['temp_unit'] == 'celsius': values['temp_unit'] = "C" else: values['temp_unit'] = "F" # -------------- Runden der Temparaturen -------------- for x in values['channel']: values['channel'][x]['temp'] = round(values['channel'][x]['temp'], 1) #erneute Pruefung der aktualdaten zur weiteren ausfuehrung if ('temp_unit' not in values): print "Error! Wlanthermo app.php reading failed!" exit() else: # init ISStreamer streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) # Variablen durcharbeiten for x in values: #alle Basis Elemente durcharbeiten if ('pit' == str(x)[:3]): #pitmaster signale if sendPit: for y in values[x]: new_data = False if force_new_data: new_data = True elif force_data: if str(y) == 'setpoint': new_data = True else: new_data = not (values[x][y] == values_old[x][y]) if 'timestamp' in y: new_data = False if new_data: name = str(x) + '_' + str(y) value = values[x][y] streamer.log(name, value) elif (x == 'channel'): #alle Temperatur Kanaele durcharbeiten for y in values[x]: for z in values[x][y]: new_data = False if force_new_data: new_data = True elif force_data: if (values[x][y]['state'] == 'ok'): if str(z)[:4] == 'temp': new_data = True else: new_data = not (values[x][y][z] == values_old[x][y][z]) if new_data: name = str(x)[:2] + str('0' + y)[:2] + '_' + str(z) value = values[x][y][z] streamer.log(name, value) elif ('cpu' == str(x)[:3]): if sendCPU: new_data = False if force_new_data: new_data = True else: new_data = not (values[x] == values_old[x]) if new_data: name = str(x) value = values[x] streamer.log(name, value) else: # alle anderen Signale new_data = False if force_new_data: new_data = True elif (x == 'timestamp'): new_data = False else: new_data = not (values[x] == values_old[x]) if new_data: name = str(x) value = values[x] streamer.log(name, value) try: streamer.flush() except Exception: print('Daten senden nicht moeglich!') exit( ) # hier wird abgebrochen, damit der Zischenspeicher mit Initialstate synchron bleibt. # schreiben der lokalen Datei write_loc_json(values, myfile)
BUCKET_KEY = "pir022016" ACCESS_KEY = "PLACE YOUR INITIAL STATE ACCESS KEY HERE" # Set the time between sensor reads SECONDS_BETWEEN_READS = .2 # --------------------------------- grovepi.pinMode(PIR_SENSOR_PIN,"INPUT") streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) lastValue = "-" while True: try: # Detect motion and log when there are changes if grovepi.digitalRead(PIR_SENSOR_PIN): if lastValue != "active": lastValue = "active" streamer.log (ROOM_NAME + " Motion", lastValue) streamer.flush() print 'Motion Detected' else: if lastValue != "inactive": lastValue = "inactive" streamer.log (ROOM_NAME + " Motion", lastValue) streamer.flush() print '-' time.sleep(SECONDS_BETWEEN_READS) except IOError: print "Error"
else: hum_score = (hum_baseline + hum_offset) / hum_baseline * (hum_weighting * 100) # Calculate gas_score as the distance from the gas_baseline. if gas_offset > 0: gas_score = (gas / gas_baseline) * (100 - (hum_weighting * 100)) else: gas_score = 100 - (hum_weighting * 100) # Calculate air_quality_score. air_quality_score = hum_score + gas_score print( "Gas: {0:.2f} Ohms,humidity: {1:.2f} %RH,air quality: {2:.2f}". format(gas, hum, air_quality_score)) # Send the data to Initial State. streamer.log("Temperature", temp) streamer.log("Pressure", press) streamer.log("Humidity", hum) streamer.log("Air Quality", air_quality_score) streamer.close() time.sleep(period) except KeyboardInterrupt: pass
def main(): conditions = get_conditions() astronomy = get_astronomy() streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(":house: Location",conditions['current_observation']['display_location']['full']) while True: # -------------- Read GrovePi Sensors -------------- try: [temp_c,hum] = grovepi.dht(DHT_SENSOR_PIN,DHT_SENSOR_TYPE) if isFloat(temp_c): if (CONVERT_TO_FAHRENHEIT): temp_f = temp_c * 9.0 / 5.0 + 32.0 # print("Temperature(F) = ", temp_f) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)", temp_f) else: # print("Temperature(C) = ", temp_c) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)", temp_c) if ((isFloat(hum)) and (hum >= 0)): # print("Humidity(%) = ", hum) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", hum) except IOError: print ("Error") # -------------- Wunderground -------------- conditions = get_conditions() astronomy = get_astronomy() if ((conditions != False) and (astronomy != False)): humidity_pct = conditions['current_observation']['relative_humidity'] humidity = humidity_pct.replace("%","") # Stream valid conditions to Initial State streamer.log(":cloud: " + CITY + " Weather Conditions",weather_status_icon(conditions, astronomy)) streamer.log(":crescent_moon: Moon Phase",moon_icon(astronomy['moon_phase']['phaseofMoon'])) streamer.log(":dash: " + CITY + " Wind Direction",wind_dir_icon(conditions, astronomy)) if isFloat(conditions['current_observation']['temp_f']): streamer.log(CITY + " Temperature(F)",conditions['current_observation']['temp_f']) if isFloat(conditions['current_observation']['dewpoint_f']): streamer.log(CITY + " Dewpoint(F)",conditions['current_observation']['dewpoint_f']) if isFloat(conditions['current_observation']['wind_mph']): streamer.log(":dash: " + CITY + " Wind Speed(MPH)",conditions['current_observation']['wind_mph']) if isFloat(conditions['current_observation']['wind_gust_mph']): streamer.log(":dash: " + CITY + " Wind Gust(MPH)",conditions['current_observation']['wind_gust_mph']) if isFloat(humidity): streamer.log(":droplet: " + CITY + " Humidity(%)",humidity) if isFloat(conditions['current_observation']['pressure_in']): streamer.log(CITY + " Pressure(IN)",conditions['current_observation']['pressure_in']) if isFloat(conditions['current_observation']['precip_1hr_in']): streamer.log(":umbrella: " + CITY + " Precip 1 Hour(IN)",conditions['current_observation']['precip_1hr_in']) if isFloat(conditions['current_observation']['precip_today_in']): streamer.log(":umbrella: " + CITY + " Precip Today(IN)",conditions['current_observation']['precip_today_in']) if isFloat(conditions['current_observation']['solarradiation']): streamer.log(":sunny: " + CITY + " Solar Radiation (watt/m^2)",conditions['current_observation']['solarradiation']) if isFloat(conditions['current_observation']['UV']): streamer.log(":sunny: " + CITY + " UV Index:",conditions['current_observation']['UV']) streamer.flush() time.sleep(60*MINUTES_BETWEEN_READS)
class EventProcessor: def __init__(self): self._measured = False self.done = False self._measureCnt = 0 self._events = range(WEIGHT_SAMPLES) self.bottles = 0 self._bottlesPrev = -1 self._doorStatus = False self._takeMeasurement = False self.streamer = Streamer(bucket_name=BUCKET_NAME,bucket_key=BUCKET_KEY,access_key=ACCESS_KEY) def mass(self, event): # Take measurement ony when the door closes if (self._doorStatus == True and event.doorStatus == False): self._takeMeasurement = True self._measureCnt = 0 self.streamer.log("Door", "Closed") self.streamer.flush() print "Door Closed" print "Starting measurement ..." time.sleep(2) # Door is opened, ensure no measurement is being taken if (self._doorStatus == False and event.doorStatus == True): self._takeMeasurement = False self.streamer.log("Door", "Open") self.streamer.flush() print "Door Opened" if (self._takeMeasurement == True and event.totalWeight > 2): self._events[self._measureCnt] = event.totalWeight*2.20462 self._measureCnt += 1 if self._measureCnt == WEIGHT_SAMPLES: self._sum = 0 for x in range(0, WEIGHT_SAMPLES-1): self._sum += event.totalWeight*2.20462 self._weight = self._sum/WEIGHT_SAMPLES self._weightBottles = self._weight - WEIGHT_BASE self.bottles = int(round(self._weightBottles / WEIGHT_BOTTLE)) self._measureCnt = 0 print str(self._weight) + " lbs total, " + str(self._weightBottles) + " lbs in bottles" if (self.bottles != self._bottlesPrev) and (self.bottles >= 0): self.streamer.log("Bottles Present", self.bottles) self.streamer.flush() if (self._bottlesPrev != -1) and (self._bottlesPrev > self.bottles): for x in range(0, self._bottlesPrev-self.bottles): print "Bottle removed" self.streamer.log("Bottle Removed", "1") self.streamer.flush() self._bottlesPrev = self.bottles print str(self.bottles) + " Bottles" print "Measurement complete!" self._takeMeasurement = False if not self._measured: self._measured = True self._doorStatus = event.doorStatus @property def weight(self): if not self._events: return 0 histogram = collections.Counter(round(num, 1) for num in self._events) return histogram.most_common(1)[0][0]
from ISStreamer.Streamer import Streamer # Provide a client_key from local ini file, override buffer and flush for optimal streaming streamer = Streamer( bucket_name="Example Performance Metrics", bucket_key="compute_metrics", buffer_size=100, ini_file_location="./isstreamer.ini", debug_level=1, ) sample_rate_in_ms = 100 for x in range(1000): streamer.log("sample", x) # Get total CPU usage cpu_percent = psutil.cpu_percent() streamer.log("cpu_total", cpu_percent) # Get individual CPU usage cpu_percents = psutil.cpu_percent(percpu=True) streamer.log_object(cpu_percents, key_prefix="cpu") # Get the virtual memory usage memory = psutil.virtual_memory() streamer.log_object(memory, key_prefix="virtual_mem") # Get the swap memory usage swap = psutil.swap_memory() streamer.log_object(swap, key_prefix="swap_mem")
fileLogger = logging.FileHandler("/tmp/server.log") fileLogger.setLevel(logging.WARN) fileLogger.setFormatter(formatter) rootLogger.addHandler(fileLogger) with open('config.json') as f: config = json.load(f) BUCKET_NAME = config['bucket_name'] BUCKET_KEY = config['bucket_key'] ACCESS_KEY = config['access_key'] PREFIX_KEY = config['item_prefix'] i2c = busio.I2C(board.SCL, board.SDA) sensor = adafruit_am2320.AM2320(i2c) streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) while True: try: rh = sensor.relative_humidity temp = sensor.temperature logging.info("logging temp as {temp} rh as {rh}".format(temp=temp, rh=rh)) streamer.log("{prefix}_rh".format(prefix=PREFIX_KEY), rh) streamer.log("{prefix}_temp".format(prefix=PREFIX_KEY), temp) except: logging.exception("everything broke") time.sleep(60)
windData = ser.readline() time.sleep(0.5) ser.write('0M1!') ser.readline() ser.readline() ser.write('0D0!') airData = ser.readline() RWD = windData.split("+")[1] RWS = windData.split("+")[2] Atemp = airData.split("+")[1] Humidity = airData.split("+")[2] dpoint = airData.split("+")[3] bpressure = airData.split("+")[4] print("data") print(RWD) print(RWS) print(Atemp) print(Humidity) print(dpoint) print(bpressure) print(" collected") streamer.log("RWD, d", RWD) streamer.log("RWS, m/s", RWS) streamer.log("BP, hPa", bpressure) streamer.log("RH, %", Humidity) streamer.log("Air Temp, C", Atemp) streamer.log("DP, C", dpoint) time.sleep(60) #screen -dmS weather.nomad python /home/udooer/nomad/nomad/atmospheric.nomad.py #to do - take 1 minute average of samples @ 10 seconds? 5 seconds?
# Sensor should be set to Adafruit_DHT.DHT11, # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. sensor = Adafruit_DHT.AM2302 # Example using a Beaglebone Black with DHT sensor # connected to pin P8_11. #pin = 'P8_11' # Example using a Raspberry Pi with DHT sensor # connected to pin 23. pin = 4 while True: # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity) else: print 'Failed to get reading. Try again!' #log to Initial State streamer.log("Temperature", temperature) streamer.log("Humidity", humidity) sleep(900)
X, X, X, X, X, X, X, X, X, X, ] while var > 0: temp = sense.get_temperature() temp = round(temp, 1) logger.log("Teperature C", temp) humidity = sense.get_humidity() humidity = round(humidity, 1) logger.log("Humidity :", humidity) pressure = sense.get_pressure() pressure = round(pressure, 1) logger.log("Pressure:", pressure) var = var - 1 logger.log("Seconds Until Script Exit", var) sense.set_pixels(creeper_pixels) time.sleep(5) sense.set_pixels(black_pixels) time.sleep(25) sense.clear() if var == 0: sys.exit()
def main(): sense = SenseHat() conditions = get_conditions() astronomy = get_astronomy() if ('current_observation' not in conditions) or ('moon_phase' not in astronomy): print "Error! Wunderground API call failed, check your STATE and CITY and make sure your Wunderground API key is valid!" if 'error' in conditions['response']: print "Error Type: " + conditions['response']['error']['type'] print "Error Description: " + conditions['response']['error']['description'] exit() else: streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(":house: Location",conditions['current_observation']['display_location']['full']) while True: # -------------- Sense Hat -------------- # Read the sensors temp_c = sense.get_temperature() humidity = sense.get_humidity() pressure_mb = sense.get_pressure() cpu_temp = subprocess.check_output("vcgencmd measure_temp", shell=True) array = cpu_temp.split("=") array2 = array[1].split("'") cpu_tempc = float(array2[0]) cpu_tempc = float("{0:.2f}".format(cpu_tempc)) cpu_tempf = float(array2[0]) * 9.0 / 5.0 + 32.0 cpu_tempf = float("{0:.2f}".format(cpu_tempf)) temp_calibrated_c = temp_c - ((cpu_tempc - temp_c)/5.466) # Format the data temp_f = temp_calibrated_c * 9.0 / 5.0 + 32.0 temp_f = float("{0:.2f}".format(temp_f)) temp_calibrated_c = float("{0:.2f}".format(temp_calibrated_c)) humidity = float("{0:.2f}".format(humidity)) pressure_in = 0.0295301*(pressure_mb) pressure_in = float("{0:.2f}".format(pressure_in)) pressure_mb = float("{0:.2f}".format(pressure_mb)) # Print and stream if (METRIC_UNITS): print SENSOR_LOCATION_NAME + " Temperature(C): " + str(temp_calibrated_c) print SENSOR_LOCATION_NAME + " Pressure(mb): " + str(pressure_mb) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)", temp_calibrated_c) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure (mb)", pressure_mb) print(cpu_tempc) streamer.log("CPU Temperature",cpu_tempc) else: print SENSOR_LOCATION_NAME + " Temperature(F): " + str(temp_f) print SENSOR_LOCATION_NAME + " Pressure(IN): " + str(pressure_in) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)", temp_f) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure (IN)", pressure_in) print(cpu_tempf) streamer.log("CPU Temperature",cpu_tempf) print SENSOR_LOCATION_NAME + " Humidity(%): " + str(humidity) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity) # -------------- Wunderground -------------- conditions = get_conditions() astronomy = get_astronomy() if ('current_observation' not in conditions) or ('moon_phase' not in astronomy): print "Error! Wunderground API call failed. Skipping a reading then continuing ..." else: humidity_pct = conditions['current_observation']['relative_humidity'] humidity = humidity_pct.replace("%","") # Stream valid conditions to Initial State streamer.log(":cloud: " + CITY + " Weather Conditions",weather_status_icon(conditions, astronomy)) streamer.log(":crescent_moon: Moon Phase",moon_icon(astronomy['moon_phase']['phaseofMoon'])) streamer.log(":dash: " + CITY + " Wind Direction",wind_dir_icon(conditions, astronomy)) if (METRIC_UNITS): if isFloat(conditions['current_observation']['temp_c']): streamer.log(CITY + " Temperature(C)",conditions['current_observation']['temp_c']) if isFloat(conditions['current_observation']['dewpoint_c']): streamer.log(CITY + " Dewpoint(C)",conditions['current_observation']['dewpoint_c']) if isFloat(conditions['current_observation']['wind_kph']): streamer.log(":dash: " + CITY + " Wind Speed(KPH)",conditions['current_observation']['wind_kph']) if isFloat(conditions['current_observation']['wind_gust_kph']): streamer.log(":dash: " + CITY + " Wind Gust(KPH)",conditions['current_observation']['wind_gust_kph']) if isFloat(conditions['current_observation']['pressure_mb']): streamer.log(CITY + " Pressure(mb)",conditions['current_observation']['pressure_mb']) if isFloat(conditions['current_observation']['precip_1hr_metric']): streamer.log(":umbrella: " + CITY + " Precip 1 Hour(mm)",conditions['current_observation']['precip_1hr_metric']) if isFloat(conditions['current_observation']['precip_today_metric']): streamer.log(":umbrella: " + CITY + " Precip Today(mm)",conditions['current_observation']['precip_today_metric']) else: if isFloat(conditions['current_observation']['temp_f']): streamer.log(CITY + " Temperature(F)",conditions['current_observation']['temp_f']) if isFloat(conditions['current_observation']['dewpoint_f']): streamer.log(CITY + " Dewpoint(F)",conditions['current_observation']['dewpoint_f']) if isFloat(conditions['current_observation']['wind_mph']): streamer.log(":dash: " + CITY + " Wind Speed(MPH)",conditions['current_observation']['wind_mph']) if isFloat(conditions['current_observation']['wind_gust_mph']): streamer.log(":dash: " + CITY + " Wind Gust(MPH)",conditions['current_observation']['wind_gust_mph']) if isFloat(conditions['current_observation']['pressure_in']): streamer.log(CITY + " Pressure(IN)",conditions['current_observation']['pressure_in']) if isFloat(conditions['current_observation']['precip_1hr_in']): streamer.log(":umbrella: " + CITY + " Precip 1 Hour(IN)",conditions['current_observation']['precip_1hr_in']) if isFloat(conditions['current_observation']['precip_today_in']): streamer.log(":umbrella: " + CITY + " Precip Today(IN)",conditions['current_observation']['precip_today_in']) if isFloat(conditions['current_observation']['solarradiation']): streamer.log(":sunny: " + CITY + " Solar Radiation (watt/m^2)",conditions['current_observation']['solarradiation']) if isFloat(humidity): streamer.log(":droplet: " + CITY + " Humidity(%)",humidity) if isFloat(conditions['current_observation']['UV']): streamer.log(":sunny: " + CITY + " UV Index:",conditions['current_observation']['UV']) streamer.flush() time.sleep(60*MINUTES_BETWEEN_READS)
GPIO.output(11, GPIO.LOW) GPIO.output(13, GPIO.HIGH) prev_input = 2 postLog() elif (state == 3): GPIO.output(7, GPIO.LOW) GPIO.output(11, GPIO.LOW) GPIO.output(13, GPIO.LOW) postLog() else: GPIO.output(7, GPIO.HIGH) GPIO.output(11, GPIO.HIGH) GPIO.output(13, GPIO.HIGH) postLog() streamer.log("button_1", "pressed") sleep(0.2); ##when button 2 is pressed if(GPIO.input(18) == True): if( state == 1 or 2 and prev_input != 1): GPIO.output(7, GPIO.LOW) GPIO.output(11, GPIO.LOW) GPIO.output(13, GPIO.LOW) prev_input = 1 state = 3 inc = 0 postLog() elif (state == 0 and prev_input != 0): GPIO.output(7, GPIO.LOW) GPIO.output(11, GPIO.LOW)
# --------------------------------- ambient_temp = float("{0:.2f}".format(ambient_temp)) ground_temp = float("{0:.2f}".format(ground_temp)) humidity = float("{0:.2f}".format(humidity)) pressure = float("{0:.2f}".format(pressure)) wind_speed = float("{0:.2f}".format(wind_speed)) wind_gust = float("{0:.2f}".format(wind_gust)) wind_average = float("{0:.2f}".format(wind_average)) air_quality = float("{0:.2f}".format(air_quality)) print("uploading to IS") streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Ambient Temp (C)", ambient_temp) streamer.log(":earth_americas: " + SENSOR_LOCATION_NAME + " Ground Temp (C)", ground_temp) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Air Quality", air_quality) streamer.log(":droplet: " + SENSOR_LOCATION_NAME + " Pressure(mb)", pressure) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity) streamer.log(":cloud_tornado: " + SENSOR_LOCATION_NAME + " Wind Direction", wind_average) streamer.log(":wind_blowing_face: " + SENSOR_LOCATION_NAME + " Wind Speed", wind_speed) streamer.log(":wind_blowing_face: " + SENSOR_LOCATION_NAME + " Wind Gust", wind_gust) streamer.log(":cloud_rain: " + SENSOR_LOCATION_NAME + " Rainfall", rainfall) streamer.flush()
ACCESS_KEY = "INSERT ACCESS KEY HERE" MINUTES_BETWEEN_READS = 1 # --------------------------------- # BH1750 settings i2c = board.I2C() sensor = adafruit_bh1750.BH1750(i2c) sensor.resolution = 1 # Initial State settings streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) previousReading = 0 while True: if (sensor.lux > 5 and previousReading == 0): previousReading = 1 print("high prev reading", str(previousReading)) print(sensor.lux) streamer.log("Lux", 1) streamer.flush() elif (sensor.lux < 5 and previousReading == 1): previousReading = 0 streamer.log("Lux", 0) print("prev reading", str(previousReading)) print("low light", str(sensor.lux)) streamer.flush()
# ########################################## # This script is an example # of how to hit the stream limit # on a free account, who's cap is set # prorated for when then plan is selected. # ########################################### from math import ceil import time, calendar, datetime from ISStreamer.Streamer import Streamer now = datetime.datetime.now() days_in_month = calendar.monthrange(now.year, now.month)[1] days_left_in_month = float(days_in_month - now.day) unrounded_prorate = (days_left_in_month / days_in_month) # roudn the proration up and multiply it by the current free tier allowance estimated_cap = int((ceil(unrounded_prorate*100) / 100.0) * 25000) print("Estimated Cap: {}".format(estimated_cap)) stream = Streamer(bucket_name="Testing Cap", bucket_key="cap_testing", buffer_size=100, ini_file_location="./isstreamer.ini", debug_level=2) for x in range(1, estimated_cap): # throttle every 100 events if (x%100 == 0): time.sleep(1) stream.log("event", x) stream.close()
base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def read_temp_raw(): f = open(device_file, 'r') lines = f.readlines() f.close() return lines def read_temp(): lines = read_temp_raw() while lines[0].strip()[-3:] != 'YES': time.sleep(0.2) lines = read_temp_raw() equals_pos = lines[1].find('t=') if equals_pos != -1: temp_string = lines[1][equals_pos+2:] temp_c = float(temp_string) / 1000.0 return temp_c while True: #print(read_temp()) #time.sleep(1) temp_c = read_temp() temp_f = temp_c * 9.0 /5.0 + 32.0 streamer.log('temperature (C)', temp_c) streamer.log('temperature (F)', temp_f) time.sleep(60)
SENSOR_LOCATION_NAME = "Office" MINUTES_BETWEEN_SENSEHAT_READS = 0.1 # --------------------------------- streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) sense = SenseHat() while True: # Read the sensors temp_c = sense.get_temperature() humidity = sense.get_humidity() pressure_mb = sense.get_pressure() # Format the data temp_f = temp_c * 9.0 / 5.0 + 32.0 temp_f = float("{0:.2f}".format(temp_f)) humidity = float("{0:.2f}".format(humidity)) pressure_in = 0.03937008*(pressure_mb) pressure_in = float("{0:.2f}".format(pressure_in)) # Print and stream print SENSOR_LOCATION_NAME + " Temperature(F): " + str(temp_f) print SENSOR_LOCATION_NAME + " Humidity(%): " + str(humidity) print SENSOR_LOCATION_NAME + " Pressure(IN): " + str(pressure_in) streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)", temp_f) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity) streamer.log(":cloud: " + SENSOR_LOCATION_NAME + " Pressure(IN)", pressure_in) streamer.flush() time.sleep(60*MINUTES_BETWEEN_SENSEHAT_READS)
"WNW" : ":arrow_upper_left:", "WSW" : ":arrow_lower_left:", } return icon.get(conditions['current_observation']['wind_dir'],":crescent_moon:") conditions = get_conditions() astronomy = get_astronomy() if ('current_observation' not in conditions) or ('moon_phase' not in astronomy): print "Error! Wunderground API call failed, check your STATE and CITY and make sure your Wunderground API key is valid!" if 'error' in conditions['response']: print "Error Type: " + conditions['response']['error']['type'] print "Error Description: " + conditions['response']['error']['description'] exit() else: streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY) streamer.log(":house: Location",conditions['current_observation']['display_location']['full']) while True: conditions = get_conditions() astronomy = get_astronomy() if ('current_observation' not in conditions) or ('moon_phase' not in astronomy): print "Error! Wunderground API call failed. Skipping a reading then continuing ..." else: humidity_pct = conditions['current_observation']['relative_humidity'] humidity = humidity_pct.replace("%","") # Stream valid conditions to Initial State streamer.log(":clock3: Updated Time",astronomy['moon_phase']['current_time']['hour'] + ":" + astronomy['moon_phase']['current_time']['minute']) streamer.log(":cloud: " + CITY + " Weather Conditions",weather_status_icon(conditions, astronomy)) streamer.log(":crescent_moon: Moon Phase",moon_icon(astronomy['moon_phase']['phaseofMoon'])) streamer.log(":dash: " + CITY + " Wind Direction",wind_dir_icon(conditions, astronomy)) if (METRIC_UNITS):
import time from ISStreamer.Streamer import Streamer logger = Streamer(bucket_name="Stream Example", debug_level=2, offline=True) logger.log("My Messages", "Stream Starting") for num in range(1, 1000): time.sleep(0.001) logger.log("My Numbers", num) if num % 2 == 0: logger.log("My Booleans", False) else: logger.log("My Booleans", True) if num % 3 == 0: logger.log("My Events", "pop") if num % 10 == 0: logger.log("My Messages", "Stream Half Done") logger.log("My Messages", "Stream Done") logger.close()
from ISStreamer.Streamer import Streamer from time import sleep # Sensor should be set to Adafruit_DHT.DHT11, # Adafruit_DHT.DHT22, or Adafruit_DHT.AM2302. sensor = Adafruit_DHT.DHT22 # Example using a Raspberry Pi with DHT sensor # connected to GPIO 3. pin = 3 streamer = Streamer(bucket_key="shwu1", access_key="PLACE YOUR INITIAL STATE ACCESS KEY HERE") while True: # Try to grab a sensor reading. Use the read_retry method which will retry up # to 15 times to get a sensor reading (waiting 2 seconds between each retry). humidity, temperature = Adafruit_DHT.read_retry(sensor, pin) # Note that sometimes you won't get a reading and # the results will be null (because Linux can't # guarantee the timing of calls to read the sensor). # If this happens try again! if humidity is not None and temperature is not None: temperatureF = 9.0/5.0*temperature+32 streamer.log("Actual Temperature",temperatureF) print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)) sleep(900) else: print('Failed to get reading. Try again!')