Пример #1
0
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)
Пример #2
0
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)
Пример #3
0
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()
Пример #4
0
 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)
Пример #5
0
def main():
    streamer = Streamer(bucket_name=args.bucket, access_key=apiKey)

    try:
        while True:
            resultLines = read_temp_raw(args.sensor)
            save_result(args.sensor, resultLines, streamer)
            print(INFO,"Cycle finished, sleeping %ss" %(args.delay))
            time.sleep(args.delay)
    except KeyboardInterrupt:
        streamer.close()
Пример #6
0
 def __init__(self):
     self._measured = False
     self.done = False
     self._measureCnt = 0
     self._events = range(WEIGHT_SAMPLES)
     self._lastMeasurement = 0
     self._lastWeightSent = 0
     self._changeDetected = False
     self._weightDiff = 0
     self.streamer = Streamer(bucket_name=BUCKET_NAME,
                              bucket_key=BUCKET_KEY,
                              access_key=ACCESS_KEY)
Пример #7
0
 def connectInitialState(self):
     try:
         self.iss = Streamer(
             bucket_name=self._config.get("INITIALSTATE", "bucketName"),
             bucket_key=self._config.get("INITIALSTATE", "bucketKey"),
             access_key=self._config.get("INITIALSTATE", "accessKey"),
             buffer_size=20)
         self.iss.log("Uplink", "Initial Connect")
         self.iss.flush()
     except:
         print "Error sending initial state. Sleep for one hour."
         time.sleep(60 * 60)  # one hour
Пример #8
0
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)
Пример #9
0
def main():
    streamer = Streamer(bucket_name=args.bucket,
                        access_key=apiKey,
                        bucket_key=args.bucket_key)

    try:
        while True:
            resultLines = read_temp_raw(args.sensor)
            save_result(args.sensor, resultLines, streamer)
            print(INFO, "Cycle finished, sleeping %ss" % (args.delay))
            time.sleep(args.delay)
    except KeyboardInterrupt:
        streamer.close()
Пример #10
0
 def configure(self, context):
     super().configure(context)
     try:
         kwargs = {'access_key': self.access_key()}
         if self.bucket_name():
             kwargs['bucket_name'] = self.bucket_name()
         if self.bucket_key():
             kwargs['bucket_key'] = self.bucket_key()
         if self.buffer_size():
             kwargs['buffer_size'] = self.buffer_size()
         self._streamer = Streamer(**kwargs)
     except Exception as e:
         self.logger.error("Failed to create streamer: {}".format(e))
         raise e
Пример #11
0
 def __init__(self):
     self._measured = False
     self.done = False
     self._measureCnt = 0
     self._events = range(WEIGHT_SAMPLES)
     self._weights = range(WEIGHT_HISTORY)
     self._times = range(WEIGHT_HISTORY)
     self._unit = "lb"
     self._weightCnt = 0
     self._prevWeight = 0
     self._weight = 0
     self._weightChange = 0
     self.streamer = Streamer(bucket_name=BUCKET_NAME,
                              bucket_key=BUCKET_KEY,
                              access_key=ACCESS_KEY)
Пример #12
0
def main():
    gpio.setmode(gpio.BCM)
    gpio.setup(4, gpio.IN)
    gpio.setup(19, gpio.OUT)
    gpio.setup(16, gpio.OUT)
    gpio.add_event_detect(4, gpio.RISING, callback=shutdown, bouncetime=200)
    mcp = setupSystem()
    streamer = Streamer(bucket_name="MoogTest",
                        bucket_key="5LRM9UG8CASH",
                        access_key="NCbUQzFnRPMVoXDSjUL40Paxs0ICSV0Q")

    while int(time.strftime("%H")) <= 23:
        avg, maxVal, stdDev, timeElapsed = dataCollect(len(arr), mcp)
        if avg == 0 and maxVal == 0 and stdDev == 0:
            gpio.output(16, gpio.HIGH)
        else:
            gpio.output(16, gpio.LOW)
        printInfo(avg, maxVal, stdDev, timeElapsed)
        #saveData()
        try:
            r = sendToGoogleScript(avg, maxVal, stdDev, timeElapsed)
            sendToIS(streamer, avg, maxVal, stdDev, timeElapsed)
        except ConnectionError as e:
            r = "No response."
            print("Connection error. Check network settings.")
            gpio.output(16, gpio.HIGH)
        if r != "No response.":
            gpio.output(16, gpio.LOW)
Пример #13
0
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)
Пример #14
0
async def send_data():
    stream_data = deepcopy(data.statsDict)
    stream_data['user_count'] = len(data.userSet)
    stream_data['server_count'] = len(bot.guilds)
    stream_data['total_command_count'] = await bot.cogs.get('StatsCog').get_total_helper(data.statsDict)

    streamer = Streamer(bucket_name="Feyre", bucket_key=bucket_key, access_key=access_key, buffer_size=200)
    streamer.log_object(stream_data)

    streamer.flush()
    streamer.close()
Пример #15
0
 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)
Пример #16
0
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() 
Пример #17
0
    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()
Пример #18
0
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
Пример #19
0
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")
Пример #20
0
    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)
Пример #21
0
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 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()
Пример #23
0
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"
Пример #24
0
 def __init__(self):
     self._measured = False
     self.done = False
     self._measureCnt = 0
     self._events = range(WEIGHT_SAMPLES)
     self._weights = range(WEIGHT_HISTORY)
     self._times = range(WEIGHT_HISTORY)
     self._unit = "lb"
     self._weightCnt = 0
     self._prevWeight = 0
     self._weight = 0
     self._weightChange = 0
     self.streamer = Streamer(bucket_name=BUCKET_NAME,bucket_key=BUCKET_KEY,access_key=ACCESS_KEY)
Пример #25
0
    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 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")
Пример #27
0
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!")
Пример #28
0
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"
        )
Пример #29
0
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 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()
Пример #31
0
class InitialStateLogObject(TerminatorBlock):
    """ Initial State block for logging objects
    """

    version = VersionProperty("1.0.0")
    access_key = StringProperty(title='Access Key',
                                default='[[INITIAL_STATE_ACCESS_KEY]]')
    bucket_name = StringProperty(title='Bucket Name', default='New Bucket')
    bucket_key = StringProperty(title='Bucket Key', default='')
    object = Property(title='Object', default='{{ $.to_dict() }}')
    buffer_size = IntProperty(title='Buffer Size', default=10)

    def __init__(self):
        super().__init__()
        self._streamer = None

    def configure(self, context):
        super().configure(context)
        try:
            kwargs = {'access_key': self.access_key()}
            if self.bucket_name():
                kwargs['bucket_name'] = self.bucket_name()
            if self.bucket_key():
                kwargs['bucket_key'] = self.bucket_key()
            if self.buffer_size():
                kwargs['buffer_size'] = self.buffer_size()
            self._streamer = Streamer(**kwargs)
        except Exception as e:
            self.logger.error("Failed to create streamer: {}".format(e))
            raise e

    def process_signals(self, signals):
        for s in signals:
            try:
                self._streamer.log_object(self.object(s))
            except Exception as e:
                self.logger.warning("Failed to log object: {}".format(e))
        self._streamer.flush()

    def stop(self):
        super().stop()
        self._streamer.close()
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()
Пример #33
0
def main():
   sensor = W1ThermSensor()

   pool_streamer = Streamer( bucket_name="Pool Temperature", access_key="PFphNne4eMOAMQ6EiIW5DT0BNWEIunAT", bucket_key="RPSVL4LX8S7H")
   pi_streamer = Streamer( bucket_name="Pi Temperature", access_key="PFphNne4eMOAMQ6EiIW5DT0BNWEIunAT", bucket_key="8YXAKKXW348W")

   try:
      while True:
         pi_temp = read_pi_temp()
         send_data_to_InitialState( "Onboard Pi Temperature", pi_temp, pi_streamer )
         print( "Pi onboard temperature is %.2f" % ( pi_temp ) )

         temp_in_fahrenheit = sensor.get_temperature( W1ThermSensor.DEGREES_F )
         send_data_to_InitialState( "Pool Temperature Sensor", temp_in_fahrenheit, pool_streamer )
         print( "Sensor %s has temperature %.2f" % ( sensor.id, temp_in_fahrenheit ) )

         time.sleep( delay )

   except KeyboardInterrupt:
      pool_streamer.close()
      pi_streamer.close()
# --------- User Settings ---------
PIR_SENSOR_PIN = 8
ROOM_NAME = "Office"
USR_SENSOR_PIN = 4
OBJECT_NAME = "Cookies"
OBJECT_EMOJI_TOKEN = ":cookie:"
# Initial State settings
BUCKET_NAME = ROOM_NAME + " Log"
BUCKET_KEY = "usrpir20"
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 = "-"
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:
Пример #35
0
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()
Пример #36
0
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]
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola

import Adafruit_DHT
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))
Пример #38
0
ACCESS_KEY = "PLACE YOUR INITIAL STATE ACCESS KEY HERE"
# Set the time between sensor reads
MINUTES_BETWEEN_READS = 1
CONVERT_TO_FAHRENHEIT = True
# ---------------------------------


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)
Пример #39
0
               
            WHERE mach_def.mach_name = 'IC000008' 
               
            ORDER BY sample_time DESC, spc_hist.idx ASC
               
            LIMIT 15;
            """)

            result = cursor.fetchall()

            dt = result[0][0]
            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()
Пример #40
0
		"West"     : ":arrow_left:",
		"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))
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)
Пример #42
0
#####
# This is a custom 'getting started' script, made with care for [email protected].
# 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="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!
Пример #43
0
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)
Пример #44
0
from ISStreamer.Streamer import Streamer

# --------- User Settings ---------
# Connect the PIR motion sensor to one of the digital pins (i.e. 2, 3, 4, 7, or 8)
PIR_SENSOR_PIN = 8
ROOM_NAME = "Office"
# Initial State settings
BUCKET_NAME = ROOM_NAME + " Log"
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)
# ##########################################
# 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()
Пример #46
0
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()
Пример #47
0
#! /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)
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)
Пример #49
0
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]
Пример #50
0
ACCESS_KEY = "09TvJl5gnYtOKqGtIiVCYkbyVpDqquyR"
SENSOR_LOCATION_NAME = "Demo"
# ---------------------------------

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)
Пример #51
0
if __name__ == "__main__":
    # time formats
    timestamp_fmt = '%Y-%m-%d %H:%M:%S %Z%z'
    date_fmt = '%m-%d-%Y'
    time_fmt = '%H:%M:%S'
    fileprefix_fmt = '%Y%m%d'

    # read and parse config file
    config = configparser.ConfigParser()
    config.read('config.ini')
    config.sections()

    cycle_time = int(config['local']['cycle_time'])
    fieldnames = [
        'log_datestamp', 'log_timestamp', 'workspace_id', 'username',
        'workspace_state', 'connection_state', 'user_state', 'spark_metric',
        'connection_mins', 'connection_hrs', 'conn_state_timestamp',
        'last_known_conn_timestamp'
    ]

    # create or append to a streamer instance
    streamer = Streamer(bucket_name=config['initalstate']['bucket_name'],
                        bucket_key=config['initalstate']['bucket_key'],
                        access_key=config['initalstate']['access_key'])

    daemon = Daemonize(app="orwell4awsws",
                       pid=config['local']['pid_file'],
                       action=main,
                       chdir=config['local']['app_dir'])
    daemon.start()
import psutil
import time
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
Пример #53
0
# TEMP, HUMIDITY & PRESSURE & PRECIPITATION & WIND 
# Node,
# Relative Wind Direction, Relative Wind Speed, Corrected Wind Direction, Pressure,
# RH,
# Temp,
# Dewpoint,
# Total Precipitation, Precipitation Intensity, Date and Time,
# Supply Voltage,
# Status,
# Checksum.

import serial
import time
from ISStreamer.Streamer import Streamer
streamer = Streamer(bucket_name="NomadBuoy", bucket_key="DQQTCP4FWSYK", access_key="LIrzTUCldL8wVbMSokjT27MNVSBui1Li")

#Seabird MicroCAT - 96008n1 - Conducitivity / DO / Pressure / TEMP / PSU
ser = serial.Serial(
    port='/dev/ttyUSB1',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
    timeout=3)
while True:
	time.sleep(1)
	ser.flushInput()
	ser.write('?!')
	ser.readline()
	ser.write('0M2!')
from sense_hat import SenseHat
import time
import sys
from ISStreamer.Streamer import Streamer

logger = Streamer(bucket_name="Sense Hat Environment Stream", access_key="zLahwAUqKbNKv6YvuT5JuO58EiUOavDa")

sense = SenseHat()
sense.clear()
var = 14400

O = (0, 255, 0)  # Green
X = (0, 0, 0)  # Black

creeper_pixels = [
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
    O,
Пример #55
0
import RPi.GPIO as GPIO ##import the gpio lib
from time import sleep ##import time for delays

##setup streamer
from ISStreamer.Streamer import Streamer
streamer = Streamer(bucket_name="Double Button LED", bucket_key="LED TESTS", access_key="")

counter = 0


GPIO.setwarnings(False) ## disables gpio messages that they are in use
GPIO.setmode(GPIO.BOARD) ## which pin config to use

GPIO.setup(16, GPIO.IN)
GPIO.setup(18, GPIO.IN)

GPIO.setup(7, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.output(7, GPIO.HIGH)
GPIO.output(11, GPIO.HIGH)
GPIO.output(13, GPIO.HIGH)
state = 0

inc = 1

prev_input = 2

## make a function to log with streamer
def postLog():
  streamer.log("state", state)
Пример #56
0
from sense_hat import SenseHat  
import time  
import sys  
from ISStreamer.Streamer import Streamer  
  
# --------- User Settings ---------
CITY = "Nashville"
BUCKET_NAME = ":partly_sunny: " + CITY + " Weather"
BUCKET_KEY = "sensehat"
ACCESS_KEY = "Your_Access_Key"
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))
Пример #57
0
from ISStreamer.Streamer import Streamer
import time

streamer = Streamer(bucket_name="test", debug_level=2)


def stress_test_loop(i, num):
    while i > 0:
        streamer.log("iterations_left_{n}".format(n=num), i)
        time.sleep(0.2)
        i = i - 1


stress_test_loop(50, 1)

streamer.close()
Пример #58
0
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()
Пример #59
0
import os, glob, time
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
from ISStreamer.Streamer import Streamer
streamer = Streamer(bucket_name="Temperature Monitor", bucket_key="Python_Temp_Monitor", access_key="INSERT API KEY HERE")

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()