コード例 #1
0
ファイル: sim7000e-test.py プロジェクト: rtxsc/gps-escooter
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"
コード例 #2
0
ファイル: sensors.py プロジェクト: tomsyd/piot-101
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
ファイル: airquality.py プロジェクト: Nitipart/airvisual
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)
コード例 #4
0
def main():
    streamer = Streamer(bucket_name=BUCKET_NAME,
                        bucket_key=BUCKET_KEY,
                        access_key=ACCESS_KEY)
    while True:
        cpu_temperature = get_cpu_temperature()
        if METRIC_UNITS:
            streamer.log("CPU Temperature(C)", cpu_temperature)
        else:
            cpu_temperature = cpu_temperature * 9.0 / 5.0 + 32.0
            streamer.log("CPU Temperature(F)",
                         str("{0:.2f}".format(cpu_temperature)))

        cpu_percents = psutil.cpu_percent(percpu=True)
        streamer.log_object(cpu_percents, key_prefix="cpu")

        cpu_percent = psutil.cpu_percent(percpu=False)
        streamer.log("CPU Usage", cpu_percent)

        disk = psutil.disk_usage('/')
        disk_total = disk.total / 2**30
        streamer.log("Disk Total(GB)", str("{0:.2f}".format(disk_total)))
        disk_used = disk.used / 2**30
        streamer.log("Disk Used(GB)", str("{0:.2f}".format(disk_used)))
        disk_free = disk.free / 2**30
        streamer.log("Disk Free(GB)", str("{0:.2f}".format(disk_free)))
        disk_percent_used = disk.percent
        streamer.log("Disk Used(%)", str("{0:.2f}".format(disk_percent_used)))

        mem = psutil.virtual_memory()
        mem_total = mem.total / 2**20
        streamer.log("Memory Total(MB)", str("{0:.2f}".format(mem_total)))
        mem_avail = mem.available / 2**20
        streamer.log("Memory Available(MB)", str("{0:.2f}".format(mem_avail)))
        mem_percent_used = mem.percent
        streamer.log("Memory Used(%)", str("{0:.2f}".format(mem_percent_used)))
        mem_used = mem.used / 2**20
        streamer.log("Memory Used(MB)", str("{0:.2f}".format(mem_used)))
        mem_free = mem.free / 2**20
        streamer.log("Memory Free(MB)", str("{0:.2f}".format(mem_free)))

        net = psutil.net_io_counters()
        net_bytes_sent = net.bytes_sent / 2**20
        streamer.log("Network MB Sent", str("{0:.2f}".format(net_bytes_sent)))
        net_bytes_recv = net.bytes_recv / 2**20
        streamer.log("Network MB Received",
                     str("{0:.2f}".format(net_bytes_recv)))
        net_errin = net.errin
        streamer.log("Network Errors Receiving", str(net_errin))
        net_errout = net.errout
        streamer.log("Network Errors Sending", str(net_errout))
        net_dropin = net.dropin
        streamer.log("Incoming Packets Dropped", str(net_dropin))
        net_dropout = net.dropout
        streamer.log("Outgoing Packets Dropped", str(net_dropout))

        streamer.flush()
        time.sleep(60 * MINUTES_BETWEEN_READS)
コード例 #5
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)
コード例 #6
0
ファイル: Feyre.py プロジェクト: iancaragol/Feyre
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()
コード例 #7
0
def main():
    streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY)
    while True:
        cpu_temperature = get_cpu_temperature()
        if METRIC_UNITS:
            streamer.log("CPU Temperature(C)",cpu_temperature)
        else:
            cpu_temperature = cpu_temperature * 9.0 / 5.0 + 32.0
            streamer.log("CPU Temperature(F)",str("{0:.2f}".format(cpu_temperature)))

        cpu_percents = psutil.cpu_percent(percpu=True)
        streamer.log_object(cpu_percents, key_prefix="cpu")

        cpu_percent = psutil.cpu_percent(percpu=False)
        streamer.log("CPU Usage",cpu_percent)

        disk = psutil.disk_usage('/')
        disk_total = disk.total / 2**30    
        streamer.log("Disk Total(GB)",str("{0:.2f}".format(disk_total))) 
        disk_used = disk.used / 2**30
        streamer.log("Disk Used(GB)",str("{0:.2f}".format(disk_used))) 
        disk_free = disk.free / 2**30
        streamer.log("Disk Free(GB)",str("{0:.2f}".format(disk_free))) 
        disk_percent_used = disk.percent
        streamer.log("Disk Used(%)",str("{0:.2f}".format(disk_percent_used))) 

        mem = psutil.virtual_memory()
        mem_total = mem.total / 2**20      
        streamer.log("Memory Total(MB)",str("{0:.2f}".format(mem_total))) 
        mem_avail = mem.available / 2**20      
        streamer.log("Memory Available(MB)",str("{0:.2f}".format(mem_avail))) 
        mem_percent_used = mem.percent
        streamer.log("Memory Used(%)",str("{0:.2f}".format(mem_percent_used))) 
        mem_used = mem.used / 2**20
        streamer.log("Memory Used(MB)",str("{0:.2f}".format(mem_used))) 
        mem_free = mem.free / 2**20
        streamer.log("Memory Free(MB)",str("{0:.2f}".format(mem_free))) 

        net = psutil.net_io_counters()
        net_bytes_sent = net.bytes_sent / 2**20      
        streamer.log("Network MB Sent",str("{0:.2f}".format(net_bytes_sent))) 
        net_bytes_recv = net.bytes_recv / 2**20      
        streamer.log("Network MB Received",str("{0:.2f}".format(net_bytes_recv))) 
        net_errin = net.errin    
        streamer.log("Network Errors Receiving",str(net_errin)) 
        net_errout = net.errout    
        streamer.log("Network Errors Sending",str(net_errout)) 
        net_dropin = net.dropin    
        streamer.log("Incoming Packets Dropped",str(net_dropin)) 
        net_dropout = net.dropout    
        streamer.log("Outgoing Packets Dropped",str(net_dropout)) 

        streamer.flush()
        time.sleep(60*MINUTES_BETWEEN_READS)
コード例 #8
0
ファイル: beerfridge.py プロジェクト: masomel/py-iot-apps
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
ファイル: beerfridge.py プロジェクト: RChloe/beerfridge
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)
コード例 #10
0
ファイル: sim7000e-test.py プロジェクト: rtxsc/gps-escooter
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")
コード例 #11
0
ファイル: reading.py プロジェクト: 2bitoperations/raspi-sump
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!")
コード例 #12
0
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()
コード例 #13
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()
コード例 #14
0
ファイル: monitor_process.py プロジェクト: nosson-p/project
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)
コード例 #15
0
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)
コード例 #16
0
ファイル: sensors.py プロジェクト: manasdas17/piot-101
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)
コード例 #17
0
def main():
    streamer = Streamer(bucket_name=BUCKET_NAME,
                        bucket_key=BUCKET_KEY,
                        access_key=ACCESS_KEY)
    while True:
        cpu_temp_c = get_cpu_temperature()
        temp_c = weather.temperature()
        temp_c_cal = temp_c - ((cpu_temp_c - temp_c) / 1.3)
        if (METRIC_UNITS):
            streamer.log(":desktop: CPU Temperature(C)", cpu_temp_c)
        else:
            cpu_temp_f = cpu_temp_c * 9.0 / 5.0 + 32.0
            streamer.log(":desktop: CPU Temperature(F)",
                         str("{0:.2f}".format(cpu_temp_f)))

        if isFloat(temp_c):
            if (METRIC_UNITS):
                # print("Temperature(C) = " + str(temp_c))
                if (temp_c > -15) and (temp_c < 100):
                    streamer.log(":sunny: " + SENSOR_NAME + " Temperature(C)",
                                 temp_c)
                    streamer.log(
                        ":sunny: Calibrated " + SENSOR_NAME +
                        " Temperature(C)", temp_c_cal)
            else:
                temp_f = temp_c * 9.0 / 5.0 + 32.0
                temp_f_cal = temp_c_cal * 9.0 / 5.0 + 32.0
                # print("Temperature(F) = " + str("{0:.2f}".format(temp_f)))
                if (temp_f > 0) and (temp_f < 110):
                    streamer.log(":sunny: " + SENSOR_NAME + " Temperature(F)",
                                 str("{0:.2f}".format(temp_f)))
                    streamer.log(
                        ":sunny: Calibrated " + SENSOR_NAME +
                        " Temperature(F)", str("{0:.2f}".format(temp_f_cal)))
            streamer.flush()
        time.sleep(60 * MINUTES_BETWEEN_READS)
コード例 #18
0
def main():

	streamer = Streamer(bucket_name="FireDash", bucket_key="python_example", access_key="ist_vg7IMJ1kf0T-YjoSjdZG-1Do8VA3tj6i")
	
	#Sending Startup Values to dashboard
	streamer.log("Status", "Online")
	streamer.log("Temperature", 0)
	streamer.log("Pressure", 0)
	streamer.log("Light", 0)
	streamer.log("FireLevel", 1)
	streamer.log("FireDetected", "Low")

	count = 0
	temp_sum = 0
	pressure_sum = 0
	light_sum = 0

	risk_rating = { 
		1: "Low", 
		2: "Moderate", 
		3: "High",
		4: "Critical", 
	}

	print("Stream Started")

	while True:
		print("Streaming")
		time.sleep(0.1) 

		count = count + 1

		#temperature sensor affected by surrounding residual heat
		#subtracting raw value from cpu temperature to get accurate results
		cpu_temp = get_cpu_temperature()
		raw_temp = weather.temperature()
		temp_fixed = raw_temp - ((cpu_temp-raw_temp)/1.3)

		#temperature, light and pressure as totaled for smoothing
		temp_sum = temp_sum + temp_fixed
		light_sum = light_sum + light.light()
		pressure_sum = pressure_sum + weather.pressure(unit = 'hPa') 

		#once allocated samples are taken, the value is averaged to get a more accurate reading
		if count == SAMPLE_RATE:
			
			temp_value = temp_sum/SAMPLE_RATE
			pressure_value = pressure_sum/SAMPLE_RATE
			light_value = light_sum/SAMPLE_RATE

			#smoothed data is sent to dash board for processing
			streamer.log("Temperature", round(temp_value,2))
			streamer.log("Pressure", round(pressure_value,2))
			streamer.log("Light", round(light_value,2))



			#calculates the risk of a fire present based on recieved data
			risk_level = calculate_risk(temp_value, pressure_value, light_value)
			streamer.log("FireLevel", risk_level)
			streamer.log("FireDetected", risk_rating.get(risk_level))

			streamer.flush()
			count = 0
			temp_sum = 0
			light_sum = 0
			pressure_sum = 0

	streamer.close()
コード例 #19
0
def main():
    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)
        streamer.log(":house: Location", GPS_COORDS)
        a = 1

    while True:

        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:
            if isFloat(curr_conditions['currently']['humidity']):
                streamer.log(":droplet: Humidity(%)",
                             curr_conditions['currently']['humidity'] * 100)

            if isFloat(curr_conditions['currently']['temperature']):
                streamer.log("Temperature",
                             curr_conditions['currently']['temperature'])

            if isFloat(curr_conditions['currently']['apparentTemperature']):
                streamer.log(
                    "Feels Like",
                    curr_conditions['currently']['apparentTemperature'])

            if isFloat(curr_conditions['currently']['dewPoint']):
                streamer.log("Dewpoint",
                             curr_conditions['currently']['dewPoint'])

            if isFloat(curr_conditions['currently']['windSpeed']):
                streamer.log(":dash: Wind Speed",
                             curr_conditions['currently']['windSpeed'])

            if isFloat(curr_conditions['currently']['windGust']):
                streamer.log(":dash: Wind Gust",
                             curr_conditions['currently']['windGust'])

            if isFloat(curr_conditions['currently']['windBearing']):
                streamer.log(
                    ":dash: Wind Direction",
                    wind_dir_icon(curr_conditions['currently']['windBearing']))

            if isFloat(curr_conditions['currently']['pressure']):
                streamer.log("Pressure",
                             curr_conditions['currently']['pressure'])

            if isFloat(curr_conditions['currently']['precipIntensity']):
                streamer.log(":umbrella: Precipitation Intensity",
                             curr_conditions['currently']['precipIntensity'])

            if isFloat(curr_conditions['currently']['precipProbability']):
                streamer.log(
                    ":umbrella: Precipitation Probabiity(%)",
                    curr_conditions['currently']['precipProbability'] * 100)

            if isFloat(curr_conditions['currently']['cloudCover']):
                streamer.log(":cloud: Cloud Cover(%)",
                             curr_conditions['currently']['cloudCover'] * 100)

            if isFloat(curr_conditions['currently']['uvIndex']):
                streamer.log(":sunny: UV Index:",
                             curr_conditions['currently']['uvIndex'])

            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:
                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)
コード例 #20
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()

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

        # -------------- 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)
コード例 #21
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)
コード例 #22
0
ファイル: smartscale.py プロジェクト: ceeace/smart-scale
class EventProcessor:
    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)

    def messageWeighFirst(self, weight, unit):
        weight = float("{0:.2f}".format(weight))
        msg = []
        msg.append("What do vegan zombies eat? Gggggrrrraaaaaaaiiiiinnnnnssssss❗️ You weigh " + str(weight) + " " + unit + "!")
        msg.append("Guys that wear skinny jeans took the phrase, getting into her pants, the wrong way. 👖 You weigh " + str(weight) + " " + unit + "!")
        msg.append("Why do watermelons have fancy weddings? Because they cantaloupe. 🍉 You weigh " + str(weight) + " " + unit + "!")
        msg.append("Why did the can crusher quit his job? Because it was soda pressing. 😜 You weigh " + str(weight) + " " + unit + "!")
        msg.append("My friend thinks he is smart. He told me an onion is the only food that makes you cry, so I threw a coconut at his face. You = " + str(weight) + " " + unit)
        msg.append("Turning vegan is a big missed steak. 😜 You weigh " + str(weight) + " " + unit + "!")
        msg.append("Is there anything more capitalist than a peanut with a top hat, cane, and monocle selling you other peanuts to eat? You weigh " + str(weight) + " " + unit + "!")
        msg.append("How has the guy who makes Capri Sun straw openings not been up for a job performance review? You weigh " + str(weight) + " " + unit + "!")
        msg.append("How do I like my eggs? Umm, in a cake. 🍰 You weigh " + str(weight) + " " + unit + "!")
        msg.append("Billy has 32 pieces of bacon and eats 28. What does he have now? Happiness. Billy has happiness. You weigh " + str(weight) + " " + unit + "!")
        msg.append("Diet day 1: I have removed all the bad food from the house. It was delicious. You weigh " + str(weight) + " " + unit + "!")
        msg.append("When I see you, I am happy, I love you not for what you look like, but for what you have inside. -Me to my fridge. You weigh " + str(weight) + " " + unit + "!")
        msg.append("Netflix has 7 letters. So does foooood. Coincidence? I think not. You weigh " + str(weight) + " " + unit + "!")
        msg.append("Studies show that if there is going to be free food, I will show up 100 percent of the time. You weigh " + str(weight) + " " + unit + "!")
        msg.append("I can multitask. I can eat breakfast and think about lunch at the same time. You weigh " + str(weight) + " " + unit + "!")
        return msg[randint(0, len(msg)-1)]

    def messageWeighLess(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append("You're getting so skinny that if someone slaps you, they'll get a paper cut. 👋 You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("Wow that Lean Cuisine really filled me up - Said No One Ever. 🍲 You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("Whoever said nothing tastes as good as skinny feels has clearly never had 🍕 or 🍷 or 🍰. You lost " + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " + unit + ").")
        msg.append("I know milk does a body good, but damn, how much have you been drinking? 😍 You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("Are you from Tennessee? Because you're the only ten I see! 😍 You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("If you were words on a page, you'd be what they call FINE PRINT! 📖 You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("If you were a transformer, you'd be a HOT-obot, and your name would be Optimus Fine! 😍 You lost " + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " + unit + ").")
        msg.append("WTF! (where's the food) 🍗 You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("It's a lot easier to stop eating carbs once you've come to terms with living a joyless life full of anger and sadness. U lost " + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " + unit + ")")
        msg.append("The Roomba just beat me to a piece of popcorn on the floor. This is how the war against the machines begins. U lost " + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " + unit + ")")
        msg.append("I won't be impressed with technology until I can download food. You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("I choked on a carrot today and all I could think was I bet a doughnut wouldn't have done this to me. U lost " + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " + unit + ")")
        msg.append("Asking me if I am hungry is like asking me if I want money. You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("I think my soulmate might be carbs. You lost " + str(abs(weightChange)) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("Great job! We made a video about your progress. Check it out at https://youtu.be/dQw4w9WgXcQ. U lost " + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " + unit + ").")
        return msg[randint(0, len(msg)-1)]

    def messageWeighMore(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append("You are in shape ... round is a shape 🍩. You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). I didn't want to sugarcoat it b/c I was afraid you would eat that too. 🍦")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). I hated telling you that b/c you apparently have enough on your plate. 🍽")
        msg.append("Stressed spelled backwards is desserts, but I bet you already knew that. 🍰 You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). You probably just forgot to go to the gym. That's like what, 8 years in a row now? 🏋")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). The good news is that you are getting easier to see! 🔭")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). YOLO! (You Obviously Love Oreos) 💛")
        msg.append("You should name your dog Five Miles so you can honestly say you walk Five Miles every day. 🐶 You gained " + str(weightChange) + " " + unit + " (" + str(weight) + " " + unit + ")")
        msg.append("Instead of a John, call your bathroom a Jim so you can honstely say you go to the Jim every morning. 🚽 You gained " + str(weightChange) + " " + unit + " (" + str(weight) + " " + unit + ")")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). The good news is that there is more of you to love! 💛")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). 💩")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). I gave up desserts once. It was the worst 20 minutes of my life. 🍪 ")
        msg.append("When you phone dings, do people think you are backing up? 🚚 You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("Always eat alone. If people never see you eat, they might believe you when you say you have a thyroid problem. You gained " + str(weightChange) + " " + unit + " (" + str(weight) + ")")
        msg.append("After exercising, I always eat a pizza ... just kidding, I don't exercise. 🍕 You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("If you are what you eat, perhaps you should eat a skinny person. 😱 You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("I never run with scissors. OK, those last two words were unnecessary. ✂️ You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        msg.append("You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + "). I am sure it is all muscle. 💪 ")
        msg.append("Yeah, I'm into fitness... Fit'ness whole burger in my mouth. 🍔👅 You gained " + str(weightChange) + " " + unit + " since last time (" + str(weight) + " " + unit + ").")
        return msg[randint(0, len(msg)-1)]

    def messageWeighSame(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append("Congratulations on nothing ... you practically weigh the same since last time. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("What do you call a fake noodle? An impasta. 🍝 Your weight didn't change much since last time. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("Bacon is low-carb and gluten-free ... just sayin'. 🐷 Your weight didn't change much since last time. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("I may look like I am deep in thought, but I'm really just thinking about what I'm going to eat later. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("I haven't eaten an apple in days. The doctors are closing in. My barricade won't last. Tell my family I love th-. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("Ban pre-shredded cheese. Make America grate again. 🧀 Your weight didn't change much since last time. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("If I share my food with you, it's either because I love you a lot or because it fell on the floor. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("The sad moment you lose a chip in the dip so you send in a recon chip and that breaks too. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("I only want two things: 1 - To lose weight. 2 - To eat. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("I enjoy long, romantic walks to the fridge. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("I just don't wanna look back and think, I could have eaten that. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("Most people want a perfect relationship. I just want a hamburger that looks like the one in commercials. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("Love is in the air ... or is that bacon? 🐷 Your weight didn't change much since last time. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        msg.append("That is too much bacon. -Said No One Ever 🐷 Your weight didn't change much since last time. " + str(weight) + " " + unit + " (" + str(weightChange) + " " + unit + " change)")
        return msg[randint(0, len(msg)-1)]

    def mass(self, event):
        if (event.totalWeight > 2):
            if self._measureCnt < WEIGHT_SAMPLES:
                if self._measureCnt == 1:
                    self.streamer.log("Update", "Measuring ...")
                    self.streamer.flush()

                if METRIC_UNITS:
                    self._events[self._measureCnt] = event.totalWeight
                    self._unit = "kg"
                else:
                    self._events[self._measureCnt] = event.totalWeight*2.20462
                    self._unit = "lb"
                self._measureCnt += 1
                if self._measureCnt == WEIGHT_SAMPLES:

                    # Average multiple measurements to get the weight and stream it
                    self._prevWeight = self._weight
                    self._sum = 0
                    for x in range(THROWAWAY_SAMPLES, WEIGHT_SAMPLES-1):
                        self._sum += self._events[x]
                    self._weight = self._sum/(WEIGHT_SAMPLES-THROWAWAY_SAMPLES)
                    if self._measured:
                        self._weightChange = self._weight - self._prevWeight
                        if self._weightChange < -0.4:
                            self._msg = self.messageWeighLess(self._weight, self._weightChange, self._unit)
                        elif self._weightChange > 0.4:
                            self._msg = self.messageWeighMore(self._weight, self._weightChange, self._unit)
                        else:
                            self._msg = self.messageWeighSame(self._weight, self._weightChange, self._unit)
                    else:
                        self._msg = self.messageWeighFirst(self._weight, self._unit)
                    print self._msg
                    self.streamer.log("Update", self._msg)
                    tmpVar = "Weight(" + self._unit + ")"
                    self.streamer.log(str(tmpVar), float("{0:.2f}".format(self._weight)))
                    tmpVar = time.strftime("%x %I:%M %p")
                    self.streamer.log("Weigh Date", tmpVar)
                    self.streamer.flush()

                    # Store a small history of weights and overwite any measurement less than 2 hours old (7200 seconds)
                    if self._weightCnt > 0:
                        if (time.time() - self._times[self._weightCnt-1]) < 7200:
                            self._tmpVar = time.time() - self._times[self._weightCnt-1]
                            self._weightCnt -= 1
                    self._weights[self._weightCnt] = self._weight
                    self._times[self._weightCnt] = time.time()
                    self._weightCnt += 1
                    # Send an extra update at the end of WEIGHT_HISTORY
                    if self._weightCnt == WEIGHT_HISTORY:
                        self._weightCnt = 0
                        self._weightChange = self._weights[WEIGHT_HISTORY-1] - self._weights[0]
                        self._weightChange = float("{0:.2f}".format(self._weightChange))
                        timeChange = (self._times[WEIGHT_HISTORY-1] - self._times[0])/86400
                        timeChange = float("{0:.1f}".format(timeChange))
                        if self._weightChange > 0:
                            self._msg = "🕒 You gained " + str(self._weightChange) + " " + self._unit + " in the last " + str(timeChange) + " days!"
                        else:
                            self._msg = "🕒 You lost " + str(abs(self._weightChange)) + " " + self._unit + " in the last " + str(timeChange) + " days!"
                        self.streamer.log("Update", self._msg)
                        self.streamer.flush()

                    # Keep track of the first complete measurement
                    if not self._measured:
                        self._measured = True
        else:
            self._measureCnt = 0

    @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]
コード例 #23
0
class EventProcessor:
    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)

    def mass(self, event):
        if (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._measureCnt = 0
                print str(self._weight) + " lbs"
                self._weightDiff = self._weight - self._lastMeasurement

                if (self._changeDetected):
                    if abs(self._weightDiff) < .1:
                        print "Weight stabilized, sending data ..."
                        self.streamer.log(WIIBOARD_NAME + "_weight",
                                          self._weight)
                        self.streamer.log(WIIBOARD_NAME + "_status",
                                          "Weight stabilized")

                        if ((self._weight - self._lastWeightSent) <
                                0) and (self._lastWeightSent != 0):
                            self.streamer.log(
                                WIIBOARD_NAME + "_decremented_weight",
                                abs(self._weight - self._lastWeightSent))
                        self.streamer.flush()
                        self._changeDetected = False
                        self._lastWeightSent = self._weight
                    self._lastMeasurement = self._weight

                if abs(self._weightDiff) > .3:
                    print "Change detected, waiting for stabilization ..."
                    self.streamer.log(WIIBOARD_NAME + "_status",
                                      "Change detected ...")
                    self.streamer.flush()
                    self._lastMeasurement = self._weight
                    self._changeDetected = True

            if not self._measured:
                self._measured = True

    @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]
コード例 #24
0
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)
コード例 #25
0
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)
コード例 #26
0
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)
コード例 #27
0
def main():
    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:
        # -------------- GrovePi Zero --------------
        # Read the sensors
        try:
            [temp_c, hum] = grovepi.dht(DHT_SENSOR_PIN, DHT_SENSOR_TYPE)
            airSensorVal = grovepi.analogRead(AIR_SENSOR_PIN)

            if isFloat(temp_c):
                if (METRIC_UNITS):
                    streamer.log(
                        ":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)",
                        temp_c)
                else:
                    temp_f = temp_c * 9.0 / 5.0 + 32.0
                    temp_f = float("{0:.2f}".format(temp_f))
                    streamer.log(
                        ":sunny: " + SENSOR_LOCATION_NAME + " Temperature(F)",
                        temp_f)
            if ((isFloat(hum)) and (hum >= 0)):
                streamer.log(
                    ":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)",
                    hum)

            if isFloat(airSensorVal):
                if airSensorVal > 700:
                    streamer.log(SENSOR_LOCATION_NAME + " Air Quality",
                                 ":fog: :bangbang:")
                elif airSensorVal > 300:
                    streamer.log(SENSOR_LOCATION_NAME + " Air Quality",
                                 ":foggy: :exclamation:")
                else:
                    streamer.log(SENSOR_LOCATION_NAME + " Air Quality",
                                 ":rainbow:")
                streamer.log(SENSOR_LOCATION_NAME + " Air Quality Sensor",
                             airSensorVal)
        except IOError:
            print("Error")

        # -------------- 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)
コード例 #28
0
ファイル: beerfridge.py プロジェクト: masomel/py-iot-apps
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]
コード例 #29
0
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()
コード例 #30
0
def main():
    city = input(
        "Enter the name of the City you require the Weather Conditions of:")
    address = "https://www.google.com/search?rlz=1C1HLDY_enUS874US874&ei=dengXeHcE8qd5wKj4aDIAw&q=" + city + "+coordinates&oq=" + city + "+&gs_l=psy-ab.3.0.0i67i70i251j0j0i67l3j0i131j0i67l3j0i131.10435.11689..12656...0.1..0.165.881.4j4......0....1..gws-wiz.......0i71j0i273.KfscqkpHNeY"
    web_page = requests.get(address)
    soup = BeautifulSoup(web_page.content,
                         "html.parser")  #Scraping Content from Google Search
    coords_class = soup.find_all(class_="BNeawe iBp4i AP7Wnd")
    required_coords = coords_class[0].find_all(
        class_="BNeawe iBp4i AP7Wnd"
    )  #Getting coords in a particular class in scraped data
    latitudes_longitude = []
    str_coords = str(required_coords)
    t = str_coords.replace(">", " ")
    t = t.replace("<", " ")
    t = t.replace(",", " ")
    t = t.replace("°", "")
    T = t.split(" ")
    latitudes_longitude.append(T[5])
    latitudes_longitude.append(T[6])
    latitudes_longitude.append(T[8])
    latitudes_longitude.append(T[9])
    coords = ""
    if (latitudes_longitude[1] == "S"):
        latitudes_longitude[0] = str(-1.0 * float(
            latitudes_longitude[0]))  #Converting Latitude to standard notation
    if (latitudes_longitude[3] == "W"):
        latitudes_longitude[2] = str(-1.0 * float(
            latitudes_longitude[2]))  #converting Longitude to standar notation
    coords = latitudes_longitude[0] + "," + latitudes_longitude[
        2]  #Adding Latitudes and Longitudes of a place in "coords" variable
    coords
    global GPS_COORDS
    GPS_COORDS = coords
    global DARKSKY_API_KEY

    DARKSKY_API_KEY = "c0974690b3b66a08fe5ea57c4926f420"  #Storing API key in DarkSky_API_KEY variable
    BUCKET_NAME = ":partly_sunny: " + city + " Weather"  #Storing Bucket Name
    BUCKET_KEY = "T57BL7K39XAX"  #Storing Buckey Key for Streamer Dashboard
    ACCESS_KEY = "ist_uOnFF2jMhg7iwAu9R5HqFVAVeTZoQk-q"  #Storing Access Key of Streamer Dashboard

    curr_conditions = get_current_conditions()
    if (
            'currently' not in curr_conditions
    ):  # Checking for connectivity to API and printing if connection is invalid
        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)  #Accessing the Streamer
    while True:
        curr_conditions = get_current_conditions()
        if ('currently' not in curr_conditions):
            print(
                "Error! Dark Sky API call failed. Skipping a reading then continuing ...\n"
            )  #Again checking connectivity
        else:
            streamer.log(":house: Location",
                         GPS_COORDS)  #Streaming the Location on the Dashboard
            webbrowser.open(
                'https://go.init.st/jp3ahqe'
            )  #Command to automatically open up default webbrowser

            #Streaming the Humidity on the Dashboard
            if 'humidity' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['humidity']):
                streamer.log(":droplet: Humidity(%)",
                             curr_conditions['currently']['humidity'] * 100)

            #Streaming the Temperature on the Dashboard
            if 'temperature' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['temperature']):
                streamer.log("Temperature",
                             curr_conditions['currently']['temperature'])

            #Streaming the Apparent Temperature on the Dashboard
            if 'apparentTemperature' in curr_conditions[
                    'currently'] and isFloat(
                        curr_conditions['currently']['apparentTemperature']):
                streamer.log(
                    "Apparent Temperature",
                    curr_conditions['currently']['apparentTemperature'])

            #Streaming the DewPoint on the Dashboard
            if 'dewPoint' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['dewPoint']):
                streamer.log("Dewpoint",
                             curr_conditions['currently']['dewPoint'])

            #Streaming the WindSpeed on the Dashboard
            if 'windSpeed' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['windSpeed']):
                streamer.log(":dash: Wind Speed",
                             curr_conditions['currently']['windSpeed'])

            #Streaming the Wind_Gust on the Dashboard
            if 'windGust' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['windGust']):
                streamer.log(":dash: Wind Gust",
                             curr_conditions['currently']['windGust'])

            #Streaming the Wind Direction on the Dashboard
            if 'windBearing' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['windBearing']):
                streamer.log(
                    ":dash: Wind Direction",
                    wind_dir_icon(curr_conditions['currently']['windBearing']))

            #Streaming the Pressure Condition on the Dashboard
            if 'pressure' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['pressure']):
                streamer.log("Pressure",
                             curr_conditions['currently']['pressure'])

            #Streaming the Precipitation Intensity on the Dashboard
            if 'precipIntensity' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['precipIntensity']):
                streamer.log(":umbrella: Precipitation Intensity",
                             curr_conditions['currently']['precipIntensity'])

            #Streaming the Precipitation Probability on the Dashboard
            if 'precipProbability' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['precipProbability']):
                streamer.log(
                    ":umbrella: Precipitation Probabiity(%)",
                    curr_conditions['currently']['precipProbability'] * 100)

            #Streaming the Cloud Cover on the Dashboard
            if 'cloudCover' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['cloudCover']):
                streamer.log(":cloud: Cloud Cover(%)",
                             curr_conditions['currently']['cloudCover'] * 100)

            #Streaming the Ultraviolet Index on the Dashboard
            if 'uvIndex' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['uvIndex']):
                streamer.log(":sunny: UV Index:",
                             curr_conditions['currently']['uvIndex'])

            #Streaming the Visibility on the Dashboard
            if 'visibility' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['visibility']):
                streamer.log(":sunny: Visibility:",
                             curr_conditions['currently']['visibility'])

            #Streaming the Ozone Level on the Dashboard
            if 'ozone' in curr_conditions['currently'] and isFloat(
                    curr_conditions['currently']['ozone']):
                streamer.log(":sunny: Ozone Level:",
                             curr_conditions['currently']['ozone'])

            #Streaming the Weather Summary on the Dashboard
            if 'summary' in curr_conditions['currently']:
                streamer.log(":cloud: Weather Summary",
                             curr_conditions['currently']['summary'])

            #Streaming the Forecast Message for today on the Dashboard
            if 'hourly' in curr_conditions:
                streamer.log("Today's Forecast",
                             curr_conditions['hourly']['summary'])

            #Streaming the Moon Phase and Weather Condition Icon on the Dashboard
            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()  #Refreshing the Stream
            streamer.close()  #Closing the Stream
        break
コード例 #31
0
ファイル: smartscale.py プロジェクト: anwa17/smart-scale
class EventProcessor:
    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)

    def messageWeighFirst(self, weight, unit):
        weight = float("{0:.2f}".format(weight))
        msg = []
        msg.append(
            "What do vegan zombies eat? Gggggrrrraaaaaaaiiiiinnnnnssssss❗️ You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "Guys that wear skinny jeans took the phrase, getting into her pants, the wrong way. 👖 You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "Why do watermelons have fancy weddings? Because they cantaloupe. 🍉 You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "Why did the can crusher quit his job? Because it was soda pressing. 😜 You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "My friend thinks he is smart. He told me an onion is the only food that makes you cry, so I threw a coconut at his face. You = "
            + str(weight) + " " + unit)
        msg.append("Turning vegan is a big missed steak. 😜 You weigh " +
                   str(weight) + " " + unit + "!")
        msg.append(
            "Is there anything more capitalist than a peanut with a top hat, cane, and monocle selling you other peanuts to eat? You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "How has the guy who makes Capri Sun straw openings not been up for a job performance review? You weigh "
            + str(weight) + " " + unit + "!")
        msg.append("How do I like my eggs? Umm, in a cake. 🍰 You weigh " +
                   str(weight) + " " + unit + "!")
        msg.append(
            "Billy has 32 pieces of bacon and eats 28. What does he have now? Happiness. Billy has happiness. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "Diet day 1: I have removed all the bad food from the house. It was delicious. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "When I see you, I am happy, I love you not for what you look like, but for what you have inside. -Me to my fridge. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "Netflix has 7 letters. So does foooood. Coincidence? I think not. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "Studies show that if there is going to be free food, I will show up 100 percent of the time. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "I can multitask. I can eat breakfast and think about lunch at the same time. You weigh "
            + str(weight) + " " + unit + "!")
        return msg[randint(0, len(msg) - 1)]

    def messageWeighLess(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append(
            "You're getting so skinny that if someone slaps you, they'll get a paper cut. 👋 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "Wow that Lean Cuisine really filled me up - Said No One Ever. 🍲 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "Whoever said nothing tastes as good as skinny feels has clearly never had 🍕 or 🍷 or 🍰. You lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ").")
        msg.append(
            "I know milk does a body good, but damn, how much have you been drinking? 😍 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "Are you from Tennessee? Because you're the only ten I see! 😍 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "If you were words on a page, you'd be what they call FINE PRINT! 📖 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "If you were a transformer, you'd be a HOT-obot, and your name would be Optimus Fine! 😍 You lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ").")
        msg.append("WTF! (where's the food) 🍗 You lost " +
                   str(abs(weightChange)) + " " + unit + " since last time (" +
                   str(weight) + " " + unit + ").")
        msg.append(
            "It's a lot easier to stop eating carbs once you've come to terms with living a joyless life full of anger and sadness. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "The Roomba just beat me to a piece of popcorn on the floor. This is how the war against the machines begins. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "I won't be impressed with technology until I can download food. You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "I choked on a carrot today and all I could think was I bet a doughnut wouldn't have done this to me. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "Asking me if I am hungry is like asking me if I want money. You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append("I think my soulmate might be carbs. You lost " +
                   str(abs(weightChange)) + " " + unit + " since last time (" +
                   str(weight) + " " + unit + ").")
        msg.append(
            "Great job! We made a video about your progress. Check it out at https://youtu.be/dQw4w9WgXcQ. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ").")
        return msg[randint(0, len(msg) - 1)]

    def messageWeighMore(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append("You are in shape ... round is a shape 🍩. You gained " +
                   str(weightChange) + " " + unit + " since last time (" +
                   str(weight) + " " + unit + ").")
        msg.append(
            "You gained " + str(weightChange) + " " + unit +
            " since last time (" + str(weight) + " " + unit +
            "). I didn't want to sugarcoat it b/c I was afraid you would eat that too. 🍦"
        )
        msg.append(
            "You gained " + str(weightChange) + " " + unit +
            " since last time (" + str(weight) + " " + unit +
            "). I hated telling you that b/c you apparently have enough on your plate. 🍽"
        )
        msg.append(
            "Stressed spelled backwards is desserts, but I bet you already knew that. 🍰 You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "You gained " + str(weightChange) + " " + unit +
            " since last time (" + str(weight) + " " + unit +
            "). You probably just forgot to go to the gym. That's like what, 8 years in a row now? 🏋"
        )
        msg.append("You gained " + str(weightChange) + " " + unit +
                   " since last time (" + str(weight) + " " + unit +
                   "). The good news is that you are getting easier to see! 🔭")
        msg.append("You gained " + str(weightChange) + " " + unit +
                   " since last time (" + str(weight) + " " + unit +
                   "). YOLO! (You Obviously Love Oreos) 💛")
        msg.append(
            "You should name your dog Five Miles so you can honestly say you walk Five Miles every day. 🐶 You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "Instead of a John, call your bathroom a Jim so you can honstely say you go to the Jim every morning. 🚽 You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append("You gained " + str(weightChange) + " " + unit +
                   " since last time (" + str(weight) + " " + unit +
                   "). The good news is that there is more of you to love! 💛")
        msg.append("You gained " + str(weightChange) + " " + unit +
                   " since last time (" + str(weight) + " " + unit + "). 💩")
        msg.append(
            "You gained " + str(weightChange) + " " + unit +
            " since last time (" + str(weight) + " " + unit +
            "). I gave up desserts once. It was the worst 20 minutes of my life. 🍪 "
        )
        msg.append(
            "When you phone dings, do people think you are backing up? 🚚 You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "Always eat alone. If people never see you eat, they might believe you when you say you have a thyroid problem. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + ")")
        msg.append(
            "After exercising, I always eat a pizza ... just kidding, I don't exercise. 🍕 You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "If you are what you eat, perhaps you should eat a skinny person. 😱 You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "I never run with scissors. OK, those last two words were unnecessary. ✂️ You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append("You gained " + str(weightChange) + " " + unit +
                   " since last time (" + str(weight) + " " + unit +
                   "). I am sure it is all muscle. 💪 ")
        msg.append(
            "Yeah, I'm into fitness... Fit'ness whole burger in my mouth. 🍔👅 You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        return msg[randint(0, len(msg) - 1)]

    def messageWeighSame(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append(
            "Congratulations on nothing ... you practically weigh the same since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "What do you call a fake noodle? An impasta. 🍝 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Bacon is low-carb and gluten-free ... just sayin'. 🐷 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "I may look like I am deep in thought, but I'm really just thinking about what I'm going to eat later. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "I haven't eaten an apple in days. The doctors are closing in. My barricade won't last. Tell my family I love th-. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Ban pre-shredded cheese. Make America grate again. 🧀 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "If I share my food with you, it's either because I love you a lot or because it fell on the floor. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "The sad moment you lose a chip in the dip so you send in a recon chip and that breaks too. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append("I only want two things: 1 - To lose weight. 2 - To eat. " +
                   str(weight) + " " + unit + " (" + str(weightChange) + " " +
                   unit + " change)")
        msg.append("I enjoy long, romantic walks to the fridge. " +
                   str(weight) + " " + unit + " (" + str(weightChange) + " " +
                   unit + " change)")
        msg.append(
            "I just don't wanna look back and think, I could have eaten that. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Most people want a perfect relationship. I just want a hamburger that looks like the one in commercials. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Love is in the air ... or is that bacon? 🐷 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "That is too much bacon. -Said No One Ever 🐷 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        return msg[randint(0, len(msg) - 1)]

    def mass(self, event):
        if (event.totalWeight > 2):
            if self._measureCnt < WEIGHT_SAMPLES:
                if self._measureCnt == 1:
                    self.streamer.log("Update", "Measuring ...")
                    self.streamer.flush()

                if METRIC_UNITS:
                    self._events[self._measureCnt] = event.totalWeight
                    self._unit = "kg"
                else:
                    self._events[
                        self._measureCnt] = event.totalWeight * 2.20462
                    self._unit = "lb"
                self._measureCnt += 1
                if self._measureCnt == WEIGHT_SAMPLES:

                    # Average multiple measurements to get the weight and stream it
                    self._prevWeight = self._weight
                    self._sum = 0
                    for x in range(THROWAWAY_SAMPLES, WEIGHT_SAMPLES - 1):
                        self._sum += self._events[x]
                    self._weight = self._sum / (WEIGHT_SAMPLES -
                                                THROWAWAY_SAMPLES)
                    if self._measured:
                        self._weightChange = self._weight - self._prevWeight
                        if self._weightChange < -0.4:
                            self._msg = self.messageWeighLess(
                                self._weight, self._weightChange, self._unit)
                        elif self._weightChange > 0.4:
                            self._msg = self.messageWeighMore(
                                self._weight, self._weightChange, self._unit)
                        else:
                            self._msg = self.messageWeighSame(
                                self._weight, self._weightChange, self._unit)
                    else:
                        self._msg = self.messageWeighFirst(
                            self._weight, self._unit)
                    print self._msg
                    self.streamer.log("Update", self._msg)
                    tmpVar = "Weight(" + self._unit + ")"
                    self.streamer.log(str(tmpVar),
                                      float("{0:.2f}".format(self._weight)))
                    tmpVar = time.strftime("%x %I:%M %p")
                    self.streamer.log("Weigh Date", tmpVar)
                    self.streamer.flush()

                    # Store a small history of weights and overwite any measurement less than 2 hours old (7200 seconds)
                    if self._weightCnt > 0:
                        if (time.time() -
                                self._times[self._weightCnt - 1]) < 7200:
                            self._tmpVar = time.time() - self._times[
                                self._weightCnt - 1]
                            self._weightCnt -= 1
                    self._weights[self._weightCnt] = self._weight
                    self._times[self._weightCnt] = time.time()
                    self._weightCnt += 1
                    # Send an extra update at the end of WEIGHT_HISTORY
                    if self._weightCnt == WEIGHT_HISTORY:
                        self._weightCnt = 0
                        self._weightChange = self._weights[
                            WEIGHT_HISTORY - 1] - self._weights[0]
                        self._weightChange = float("{0:.2f}".format(
                            self._weightChange))
                        timeChange = (self._times[WEIGHT_HISTORY - 1] -
                                      self._times[0]) / 86400
                        timeChange = float("{0:.1f}".format(timeChange))
                        if self._weightChange > 0:
                            self._msg = "🕒 You gained " + str(
                                self._weightChange
                            ) + " " + self._unit + " in the last " + str(
                                timeChange) + " days!"
                        else:
                            self._msg = "🕒 You lost " + str(
                                abs(self._weightChange)
                            ) + " " + self._unit + " in the last " + str(
                                timeChange) + " days!"
                        self.streamer.log("Update", self._msg)
                        self.streamer.flush()

                    # Keep track of the first complete measurement
                    if not self._measured:
                        self._measured = True
        else:
            self._measureCnt = 0

    @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]
コード例 #32
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]
コード例 #33
0
class EventProcessor:
    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)

    def messageWeighFirst(self, weight, unit):
        weight = float("{0:.2f}".format(weight))
        msg = []
        msg.append(
            "Don’t let a stumble in the road be the end of your journey You weigh "
            + str(weight) + " " + unit + "!")
        msg.append("When you eat crap, you feel crap. You weigh " +
                   str(weight) + " " + unit + "!")
        msg.append("Keep going. You weigh " + str(weight) + " " + unit + "!")
        msg.append("Take it one meal at a time. You weigh " + str(weight) +
                   " " + unit + "!")
        msg.append(
            "When you feel like quitting, think about why you started. You weigh "
            + str(weight) + " " + unit)
        msg.append("Every step is progress, no matter how small. You weigh " +
                   str(weight) + " " + unit + "!")
        msg.append("You will never win if you never begin. You weigh " +
                   str(weight) + " " + unit + "!")
        msg.append(
            "The secret of change is to focus all of your energy not on fighting the old, but on building the new. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append(
            "You get what you focus on, so focus on what you want. You weigh "
            + str(weight) + " " + unit + "!")
        msg.append("Decide. Commit. Succeed. You weigh " + str(weight) + " " +
                   unit + "!")
        msg.append("Keep an open mind and a closed refrigerator. You weigh " +
                   str(weight) + " " + unit + "!")
        msg.append(
            "Whatever you can do, or dream you can, begin it. Boldness has genius, power and magic in it. You weigh "
            + str(weight) + " " + unit + "!")
        return msg[randint(0, len(msg) - 1)]

    def messageWeighLess(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append("One pound at a time. You lost " + str(abs(weightChange)) +
                   " " + unit + " since last time (" + str(weight) + " " +
                   unit + ").")
        msg.append("You are your only limit. 🍲 You lost " +
                   str(abs(weightChange)) + " " + unit + " since last time (" +
                   str(weight) + " " + unit + ").")
        msg.append(
            "Success is no accident: it is hard work and perseverance. You lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ").")
        msg.append(
            "I know milk does a body good, but damn, how much have you been drinking? 😍 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "Are you from Tennessee? Because you're the only ten I see! 😍 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "If you were words on a page, you'd be what they call FINE PRINT! 📖 You lost "
            + str(abs(weightChange)) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "If you were a transformer, you'd be a HOT-obot, and your name would be Optimus Fine! 😍 You lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ").")
        msg.append("Don’t stop until you’re proud. You lost " +
                   str(abs(weightChange)) + " " + unit + " since last time (" +
                   str(weight) + " " + unit + ").")
        msg.append(
            "A little progress each day adds up to big results. U lost " +
            str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "Great job! We made a video about your progress. Check it out at https://youtu.be/dQw4w9WgXcQ. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ").")
        msg.append(
            "Don’t wait until you’ve reached your goal to be proud of yourself. Be proud of every step you take. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "The only place where success comes before work is in the dictionary. U lost "
            + str(abs(weightChange)) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        return msg[randint(0, len(msg) - 1)]

    def messageWeighMore(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append(
            "With the new day comes new strength and new thoughts. You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "There’s no such thing as failure: either you win, or you learn. You gained "
            + str(weightChange) + " " + unit + " since last time (" +
            str(weight) + " " + unit + ").")
        msg.append(
            "The past cannot be changed, the future is yet in your power. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "When you feel like quitting, think about why you started. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "Some people want it to happen. Some wish it would happen. Others make it happen. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "Only I can change my life. No one can do it for me. You gained " +
            str(weightChange) + " " + unit + " (" + str(weight) + " " + unit +
            ")")
        msg.append("The greatest wealth is health. You gained " +
                   str(weightChange) + " " + unit + " (" + str(weight) + " " +
                   unit + ")")
        msg.append(
            "Do what you don’t want to do to get what you want to get. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "You can be pitiful, or you can be powerful, but you can’t be both. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "To climb steep hills requires slow pace at first. You gained " +
            str(weightChange) + " " + unit + " (" + str(weight) + " " + unit +
            ")")
        msg.append(
            "Take care of your body. It’s the only place you have to live. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        msg.append(
            "Success is not final, failure is not fatal: it is the courage to continue that counts. You gained "
            + str(weightChange) + " " + unit + " (" + str(weight) + " " +
            unit + ")")
        return msg[randint(0, len(msg) - 1)]

    def messageWeighSame(self, weight, weightChange, unit):
        weight = float("{0:.2f}".format(weight))
        weightChange = float("{0:.2f}".format(weightChange))
        msg = []
        msg.append("The groundwork of all happiness is health You weigh. " +
                   str(weight) + " " + unit + " (" + str(weightChange) + " " +
                   unit + " change)")
        msg.append(
            "What do you call a fake noodle? An impasta. 🍝 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "The scale is merely a measure of my relationship with gravity. You weigh "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Eliminate the mindset of can’t — because you can do anything. You weigh "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append("If I don’t eat junk, I don’t gain weight. " + str(weight) +
                   " " + unit + " (" + str(weightChange) + " " + unit +
                   " change)")
        msg.append(
            "Ban pre-shredded cheese. Make America grate again. 🧀 Your weight didn't change much since last time. "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Success is the sum of small efforts — repeated day-in and day-out. You weigh "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "The mind is everything. We become what we think about. You weigh "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Success is nothing more than a few simple disciplines, practiced every day. You weigh "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        msg.append(
            "Whatever the mind can conceive and believe, it can achieve. You weigh "
            + str(weight) + " " + unit + " (" + str(weightChange) + " " +
            unit + " change)")
        return msg[randint(0, len(msg) - 1)]

    def mass(self, event):
        if (event.totalWeight > 2):
            if self._measureCnt < WEIGHT_SAMPLES:
                if self._measureCnt == 1:
                    print "Measuring ..."
                    self.streamer.log("Update", "Measuring ...")
                    self.streamer.flush()

                if METRIC_UNITS:
                    self._events[self._measureCnt] = event.totalWeight
                    self._unit = "kg"
                else:
                    self._events[
                        self._measureCnt] = event.totalWeight * 2.20462
                    self._unit = "lb"
                self._measureCnt += 1
                if self._measureCnt == WEIGHT_SAMPLES:

                    # Average multiple measurements to get the weight and stream it
                    self._prevWeight = self._weight
                    self._sum = 0
                    for x in range(THROWAWAY_SAMPLES, WEIGHT_SAMPLES - 1):
                        self._sum += self._events[x]
                    self._weight = self._sum / (WEIGHT_SAMPLES -
                                                THROWAWAY_SAMPLES)
                    if self._measured:
                        self._weightChange = self._weight - self._prevWeight
                        if self._weightChange < -0.4:
                            self._msg = self.messageWeighLess(
                                self._weight, self._weightChange, self._unit)
                        elif self._weightChange > 0.4:
                            self._msg = self.messageWeighMore(
                                self._weight, self._weightChange, self._unit)
                        else:
                            self._msg = self.messageWeighSame(
                                self._weight, self._weightChange, self._unit)
                    else:
                        self._msg = self.messageWeighFirst(
                            self._weight, self._unit)
                    print self._msg
                    self.streamer.log("Update", self._msg)
                    tmpVar = "Weight(" + self._unit + ")"
                    self.streamer.log(str(tmpVar),
                                      float("{0:.2f}".format(self._weight)))
                    tmpVar = time.strftime("%x %I:%M %p")
                    self.streamer.log("Weigh Date", tmpVar)
                    self.streamer.flush()

                    # Store a small history of weights and overwite any measurement less than 2 hours old (7200 seconds)
                    if self._weightCnt > 0:
                        if (time.time() -
                                self._times[self._weightCnt - 1]) < 7200:
                            self._tmpVar = time.time() - self._times[
                                self._weightCnt - 1]
                            self._weightCnt -= 1
                    self._weights[self._weightCnt] = self._weight
                    self._times[self._weightCnt] = time.time()
                    self._weightCnt += 1
                    # Send an extra update at the end of WEIGHT_HISTORY
                    if self._weightCnt == WEIGHT_HISTORY:
                        self._weightCnt = 0
                        self._weightChange = self._weights[
                            WEIGHT_HISTORY - 1] - self._weights[0]
                        self._weightChange = float("{0:.2f}".format(
                            self._weightChange))
                        timeChange = (self._times[WEIGHT_HISTORY - 1] -
                                      self._times[0]) / 86400
                        timeChange = float("{0:.1f}".format(timeChange))
                        if self._weightChange > 0:
                            self._msg = "🕒 You gained " + str(
                                self._weightChange
                            ) + " " + self._unit + " in the last " + str(
                                timeChange) + " days!"
                        else:
                            self._msg = "🕒 You lost " + str(
                                abs(self._weightChange)
                            ) + " " + self._unit + " in the last " + str(
                                timeChange) + " days!"
                        self.streamer.log("Update", self._msg)
                        self.streamer.flush()

                    # Keep track of the first complete measurement
                    if not self._measured:
                        self._measured = True
        else:
            self._measureCnt = 0

    @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]
コード例 #34
0
def main():
    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:
        # -------------- Read GrovePi Sensors --------------
        try:
            [temp_c,hum] = grovepi.dht(DHT_SENSOR_PIN,DHT_SENSOR_TYPE)
            if isFloat(temp_c):
                if (METRIC_UNITS):
                    # print("Temperature(C) = ", temp_c)
                    streamer.log(":sunny: " + SENSOR_LOCATION_NAME + " Temperature(C)", temp_c)        
                else:
                    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)
            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 ('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)
コード例 #35
0
                             conditions['current_observation']['UV'])
            streamer.flush()
        time.sleep(60 * MINUTES_BETWEEN_READS)


if __name__ == "__main__":
    main()

from sense_hat import SenseHat
from ISStreamer.Streamer import Streamer
logger = Streamer(bucket_name="Andy's Sense Hat Environment Stream",
                  access_key="Deleted for privacy")
import time
import sys

sense = SenseHat()
sense.clear()

while True:
    temp = sense.get_temperature() * 1.8 + 32
    temp = round(temp, 2)
    logger.log("Temperature F", temp)
    humidity = sense.get_humidity()
    humidity = round(humidity, 2)
    logger.log("Humidity :", humidity)
    pressure = sense.get_pressure()  #*0.029530128+1.06
    pressure = round(pressure, 2)
    logger.log("Pressure:", pressure)
    logger.flush()
    time.sleep(30)
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)
コード例 #37
0
                streamer1.log_object(bucket, key_prefix=kprefix, epoch=epoch00)

            elif bucket_name == iss_bucket_name2:
                streamer2.log_object(bucket, key_prefix=kprefix, epoch=epoch00)

            elif bucket_name == iss_bucket_name3:
                streamer3.log_object(bucket, key_prefix=kprefix, epoch=epoch00)

            time.sleep(0.25)

        else:
            b = {"tstamp": time.time()}
            streamer1.log_object(b)
            streamer2.log_object(b)
            streamer3.log_object(b)

            streamer1.flush()
            time.sleep(0.25)
            streamer2.flush()
            time.sleep(0.25)
            streamer3.flush()
            time.sleep(0.25)

except Exception as e:
    print(e)
    sys.exit()

except KeyboardInterrupt:
    print('[dequeue] intterupted by keyboard')
    sys.exit()
コード例 #38
0
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)
コード例 #39
0
class InitialState(threading.Thread):
    def _readConfig(self):

        update = False

        if not os.path.isdir(self._homeDir):
            print "Creating homeDir"
            os.makedirs(self._homeDir)

        if os.path.isfile(self._configFileName):
            self._config.read(self._configFileName)
        else:
            print "Config file not found"
            update = True

        if not self._config.has_section('REDIS'):
            print "Adding Redis part"
            update = True
            self._config.add_section("REDIS")

        if not self._config.has_option("REDIS", "ServerAddress"):
            print "No Server Address"
            update = True
            self._config.set("REDIS", "ServerAddress", "<ServerAddress>")

        if not self._config.has_option("REDIS", "ServerPort"):
            print "No Server Port"
            update = True
            self._config.set("REDIS", "ServerPort", "6379")

        if not self._config.has_section('INITIALSTATE'):
            print "Adding InitialState part"
            update = True
            self._config.add_section("INITIALSTATE")

        if not self._config.has_option("INITIALSTATE", "accessKey"):
            print "No accessKey"
            update = True
            self._config.set("INITIALSTATE", "accessKey", "<accessKey>")

        if not self._config.has_option("INITIALSTATE", "bucketKey"):
            print "No bucketKey"
            update = True
            self._config.set("INITIALSTATE", "bucketKey", "bucketKey")

        if not self._config.has_option("INITIALSTATE", "bucketName"):
            print "No bucketName"
            update = True
            self._config.set("INITIALSTATE", "bucketName", "bucketName")

        if update:
            with open(self._configFileName, 'w') as f:
                self._config.write(f)

    def __init__(self):

        threading.Thread.__init__(self)
        self.setDaemon(True)
        self._homeDir = os.path.expanduser("~/.sensomatic")
        self._configFileName = self._homeDir + '/config.ini'
        self._config = ConfigParser.ConfigParser()
        self._readConfig()
        self._redis = redis.StrictRedis(
            host=self._config.get("REDIS", "ServerAddress"),
            port=self._config.get("REDIS", "ServerPort"),
            db=0)

    def getData(self):
        data = {'timestamp': time.time()}
        for key in self._redis.keys():
            k = key.split('/')
            l = len(k)
            w = data
            for i in range(l):
                if k[i] not in w:
                    w[k[i]] = {}
                w = w[k[i]]
                if i == l - 1:
                    w['value'] = self._redis.get(key)
        return data

    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

    def pushData(self):
        d = self.getData()

        try:
            if "bathroom" in d:
                if "temperature" in d['bathroom']:
                    self.iss.log("Bathroom Temperature",
                                 float(d['bathroom']['temperature']['value']))
                    self.iss.log("Bathroom Humidity",
                                 float(d['bathroom']['humidity']['value']))
                    self.iss.log("Bathroom Combustible",
                                 float(d['bathroom']['combustible']['value']))
                if "washingmachine" in d['bathroom']:
                    self.iss.log(
                        "Bathroom Wachingmachine Power",
                        float(d['bathroom']['washingmachine']['current']
                              ['value']))
            if "ansiroom" in d:
                self.iss.log("Ansiroom Temperature",
                             float(d['ansiroom']['temperature']['value']))
                self.iss.log("Ansiroom Co2",
                             float(d['ansiroom']['co2']['value']))
            if "livingroom" in d:
                if "tank" in d['livingroom']:
                    self.iss.log(
                        "Livingroom Temperature",
                        float(d['livingroom']['tank']['airtemp']['value']))
                    self.iss.log(
                        "Livingroom Humidity",
                        float(d['livingroom']['tank']['humidity']['value']))
                    self.iss.log(
                        "Tank Temperature",
                        float(d['livingroom']['tank']['watertemp']['value']))
                    self.iss.log(
                        "Tank Heater",
                        float(d['livingroom']['tank']['heater']['value']))
            self.iss.flush()
        except:
            print "Trying to connect to InitialState"
            self.connectInitialState()

    def run(self):
        while True:
            self.pushData()
            time.sleep(60 * 15)  # 15 Minutes
コード例 #40
0
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)
コード例 #41
0
ファイル: weatherlog.py プロジェクト: Voder/weatherLog
class WeatherLogger(object):


    def __init__(self, path='~/weather/weather.log'):
        self.logger = serial.Serial('/dev/ttyUSB0', baudrate=19200, bytesize=8, stopbits=1, timeout=0 )
        self.path = path
        self.dbPath = 'weather.sqlite'
        self.streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY)
        self.streamer.log("Weatherlog Msg", "Start streaming...")


    def connectDB(self):
        self.dbConn = db.connect(self.dbPath)
        self.dbCursor = self.dbConn.cursor()

    def closeDB(self):
        self.dbConn.close()

    def readData(self):
        b = self.logger.inWaiting()
        if b > 0:
            return self.logger.read(b)
        return ''

    def readDataToDB(self, maxtime=180, sleeptime=30):
        if sleeptime < 1:
            return 'ERROR: sleeptime < 1 not allowed'
        t = maxtime
        while t > 0:
            t = t-sleeptime
            b = self.logger.inWaiting()
            if b > 0:
                data = self.logger.read(b)
                self.writeDataToDB(data)
                return data
            time.sleep(sleeptime)
        return ''

    def writeDataToDB(self, data):
        self.connectDB()
        # $1;1;;;;;;;;;;;;;;;;;;12,4;82;0,0;40;0;0
        dataArr = data.split(';')
        date = currentTime()
        temp = dataArr[19]
        hum = dataArr[20]
        wind = dataArr[21]
        rain = dataArr[22]
        rain_curr = dataArr[23]
        rowdata = (None, date, temp, hum, wind, rain, rain_curr)
        # save in db
        self.dbCursor.execute('insert into weatherdata values(?, ?, ?, ?, ?, ?, ?)', rowdata)
        self.dbConn.commit()
        self.closeDB()

    def writeDataToIS(self, data):
        dataArr = data.split(';')
        date = currentTime()
        temp = dataArr[19]
        hum = dataArr[20]
        wind = dataArr[21]
        rain = dataArr[22]
        rain_curr = dataArr[23]
        self.streamer.log("Temperatur(C)", temp)
        self.streamer.log("Luftfeuchtigkeit(%)", hum)
        self.streamer.log("Wind(km/h)", wind)
        self.streamer.log("Regen", rain_curr)
        self.streamer.log("Regenmenge", rain)
        self.streamer.flush()

    def writeDataToFile(self, data):
        with open(self.path,'a') as f:
            f.write(currentTime() + "\n")
            f.write(data)

    def logInfo(self):
        self.logger.write("?")
        time.sleep(1)
        ret = self.readData()
        if (len(ret) == 0):
            log('ERROR: Logger info could not be read!')
            return -1
        else:
            log(ret)
            return 1