Example #1
0
def get_press(altitude):

 # enable SenseHat modules
    from sense_hat import SenseHat
    
    sense=SenseHat()
    raw_pressure1 = sense.get_pressure()
    time.sleep(0.1) 
    raw_pressure2 = sense.get_pressure()
    time.sleep(0.1) 
    raw_pressure3 = sense.get_pressure()
    raw_pressure=(raw_pressure1+raw_pressure2+raw_pressure3)/3
    pressure = raw_pressure/math.pow(1 - 0.0065*altitude/288.15,5.25588)
    #print(pressure)
    return pressure
class SensorHatLogger:

    """
    Logs the hostname, time (unixtime), temperature, humidity, and pressure to Kafka in JSON format. The data is
    generated by a Raspberry Pi with a Sense Hat: https://www.raspberrypi.org/products/sense-hat/
    
    This captures a read approx. every 10 seconds.

    TODO: https://github.com/initialstate/wunderground-sensehat/wiki/Part-3.-Sense-HAT-Temperature-Correction
    
    """

    def __init__(self):
        self.producer = KafkaProducer(bootstrap_servers='hdp01.woolford.io:6667')
        self.sense = SenseHat()
        self.sensor_record = dict()

    def read_values_from_sensor(self):
        self.sensor_record['host'] = socket.gethostname()
        self.sensor_record['timestamp'] = int(time.time())
        self.sensor_record['temperature'] = self.sense.get_temperature()
        self.sensor_record['humidity'] = self.sense.get_humidity()
        self.sensor_record['pressure'] = self.sense.get_pressure()

    def send_record_to_kafka(self):
        sensor_record_json = json.dumps(self.sensor_record)
        self.producer.send("temperature_humidity_json", sensor_record_json)

    def run(self):
        self.read_values_from_sensor()
        self.send_record_to_kafka()
def get_sensors(precision):
	sense = SenseHat()
	data = {}
	data['temperature'] = round(sense.get_temperature(), precision)
	data['pressure'] = round(sense.get_pressure(), precision)
	data['humidity'] = round(sense.get_humidity(), precision)
	return data
Example #4
0
def sense_data():
    sense = SenseHat()
    comx, comy, comz = sense.get_compass_raw().values()
    accx, accy, accz = sense.get_accelerometer_raw().values()
    gyrox, gyroy, gyroz = sense.get_accelerometer_raw().values()
    temperature = sense.get_temperature_from_humidity()
    humidity = sense.get_humidity()
    pressure = sense.get_pressure()

    timestamp = datetime.now().isoformat()

    if accy > 0.1 :
        drop_flg = 1
    else:
        drop_flg = 0
            

    message = { "deviceid": deviceid, \
                "timestamp" : timestamp, \
                "temperature" : temperature, \
                "humidity" : humidity, \
                "pressure" : pressure, \
                "comx" : comx, \
                "comy" : comy, \
                "comz" : comz, \
                "gyrox" : gyrox, \
                "gyroy" : gyroy, \
                "gyroz" : gyroz, \
                "accx" : accx, \
                "accy" : accy, \
                "accz" : accz, \
                "drop" : drop_flg
                 }
    print accx, accy, accz, drop_flg
    return message
Example #5
0
	def readSensor(self):
		from sense_hat import SenseHat
		senseHat = SenseHat()
		self.humidity   = senseHat.get_humidity()
		self.tempH      = senseHat.get_temperature_from_humidity()
		self.pressure   = senseHat.get_pressure() + PRESSURE_OFFSET
		self.tempP      = senseHat.get_temperature_from_pressure()
		self.mesureTime = time.time()
Example #6
0
class Sensor :
    def __init__(self) :
        self.sensor_id = "sensor hat"
        self.fileplace = 'tempplace.conf'
        self.total_count = 0
        self.device_file = "/dev/null"
        self.sense = SenseHat()
        self.place = self.readplacename()

    def reinit(self) :
        self.__init__()

    def sensorid(self) :
        return self.sensor_id

    def total_count(self) :
        return self.total_count

    def placename(self):
        return self.place

    def setplacename(self, name):
        self.place = setplace_db(name)

    def readplacename(self):
        self.place = getplace_db()
        return self.place

    def read_temp(self):
        temp = "null"
        tt = self.sense.get_temperature()
        th = self.sense.get_temperature_from_humidity()
        tf = self.sense.get_temperature_from_pressure()

        tf = float(tt)
        tf = tf - 10.0 # Fattore di correzione
        tt = round(tt, 2)
        tc = round(tf, 2)
        th = round(th, 2)
        tf = round(tf, 2)

        self.total_count += 1
        return str(tc)

    def read_pressure(self):
        p = self.sense.get_pressure()
        p = round(p, 2)
        self.total_count += 1
        return str(p)

    def read_humidity(self):
        h = self.sense.get_humidity()
        h = round(h, 2)
        self.total_count += 1
        return str(h)

    def sensordebug(self):
        return 'Sense Hat'
Example #7
0
def get_press(altitude):
 # enable SenseHat modules
    from sense_hat import SenseHat
    
    sense=SenseHat()
    raw_pressure = sense.get_pressure()
    pressure = raw_pressure/math.pow(1 - 0.0065*altitude/288.15,5.25588)
    #print(pressure)
    return pressure
Example #8
0
class SenseLogger:
    def __init__(self):
        self.sense = SenseHat()
        self.filename = "./logs/Senselogg-"+str(datetime.now())+".csv"
        self.file_setup(self.filename)

    def write_line(self, line):
        with open(self.filename, "a") as f:
            f.write(line + "\n")
        
    def log_data(self):
        sense_data = self.get_sense_data()
        line = ",".join(str(value) for value in sense_data)
        self.write_line(line)

    def file_setup(self, filename):
        header = ["datetime", "temp_h", "temp_p", "humidity", "pressure", "pitch",
                  "roll", "yaw", "mag_x", "mag_y", "mag_z",
                  "accel_x", "accel_y", "accel_z",
                  "gyro_x", "gyro_y", "gyro_z"]

        with open(filename, "w") as f:
            f.write(",".join(str(value) for value in header)+ "\n")

    def get_sense_data(self):
        sense_data = []
        sense_data.append(datetime.now())
        sense_data.append(self.sense.get_temperature_from_humidity())
        sense_data.append(self.sense.get_temperature_from_pressure())
        sense_data.append(self.sense.get_humidity())
        sense_data.append(self.sense.get_pressure())

        o = self.sense.get_orientation()
        yaw = o["yaw"]
        pitch = o["pitch"]
        roll = o["roll"]
        sense_data.extend([pitch, roll, yaw])

        mag = self.sense.get_compass_raw()
        x = mag["x"]
        y = mag["y"]
        z = mag["z"]
        sense_data.extend([x, y, z])    

        acc = self.sense.get_accelerometer_raw()
        x = acc["x"]
        y = acc["y"]
        z = acc["z"]
        sense_data.extend([x, y, z])  

        gyro = self.sense.get_gyroscope_raw()
        x = gyro["x"]
        y = gyro["y"]
        z = gyro["z"]
        sense_data.extend([x, y, z])

        return sense_data
Example #9
0
class SensorClient(object):

	def __init__(self, broker, broker_port):
		self.sense=SenseHat()
		self.broker=broker
		self.broker_port=broker_port
		self.client_id=uname()[1]
		
		sub_topics=	{	"temperature"	:	lambda: self.sense.get_temperature(),
					"humidity"	:	lambda: self.sense.get_humidity(),
					"pressure"	:	lambda:	self.sense.get_pressure() }

		self.topics={}
		root_topic="%s/sensehat"%self.client_id
		for sub_topic in sub_topics.keys():
			topic="%s/%s"%(root_topic, sub_topic)
			self.topics[topic]=sub_topics[sub_topic]
			

	def on_connect(self, client, userdate, flags, rc):
		for topic in sorted(self.topics):
			print "Subscribing to %s"%(topic)
			client.subscribe( topic )
		self.publish_sensor_topics()

	# If we recieve the payload of '?' (question-mark)
	# Then publish the value to the topic
	def on_message(self, client, userdata, msg):
		if msg.payload=="?":
			try:
				self.publish_topic( msg.topic )
			except Exception as e:
				print "Error when trying to publish '%s' ?"%msg.topic
		else:
			print "Ignoring message %s=%s"%(msg.topic, msg.payload)
		
	
	def publish_topic( self, topic ):
		topic_value=self.topics[topic]() # execute the Lambda to fetch value
		print "Publishing %s=%s"%(topic, topic_value)
		self.mqtt_client.publish( topic, topic_value )

	# Publish all topics (called when we first connect)
	def publish_sensor_topics(self):
		for topic in sorted(self.topics):
			self.publish_topic( topic )

	def run(self):
		self.mqtt_client=mqtt.Client( self.client_id )
		self.mqtt_client.on_message=self.on_message
		self.mqtt_client.on_connect=self.on_connect
		self.mqtt_client.connect(broker, broker_port)
		self.mqtt_client.loop_forever()
Example #10
0
 def update(self):
     """Get the latest data from Sense HAT."""
     from sense_hat import SenseHat
     sense = SenseHat()
     temp_from_h = sense.get_temperature_from_humidity()
     temp_from_p = sense.get_temperature_from_pressure()
     t_cpu = get_cpu_temp()
     t_total = (temp_from_h + temp_from_p) / 2
     t_correct = t_total - ((t_cpu - t_total) / 1.5)
     t_correct = get_average(t_correct)
     self.temperature = t_correct
     self.humidity = sense.get_humidity()
     self.pressure = sense.get_pressure()
Example #11
0
def root():
    sense = SenseHat()
    temp1 = sense.get_temperature()   
    temp2 = sense.get_temperature_from_pressure() 
    pressure = sense.get_pressure()
    north = sense.get_compass()
    accel_only = sense.get_accelerometer()
    acc_raw = sense.get_accelerometer_raw()
    temp = "Temp {:10.4f}".format(temp1) + " {:10.4f}".format(temp2) 
    other = "Pres {:10.4f}".format(pressure) + " Compas {:10.4f}".format(north)
    acc1 = "p: {pitch}, r: {roll}, y: {yaw}".format(**accel_only)
    acc2 = "x: {x}, y: {x}, z: {z}".format(**acc_raw)
    print temp + "\n" + other + "\n" + acc1 + "\n" + acc2 + "\n"
def sensors():

    from sense_hat import SenseHat

    sense = SenseHat()

    tempC = sense.get_temperature()  # obtains temperature in Celsius from sensor
    tempC = round(tempC, 1)
    tempF = c_to_f(tempC)  # conversion from Celsius to Fahrenheit
    tempF = round(tempF, 1)

    print "\nThe temperature at the Sense Hat is", tempC, "C or", tempF, "F"

    humidity = sense.get_humidity()
    humidity = round(humidity, 1)

    print "The relative humidity at the Sense Hat is", humidity, "%"

    pressure = sense.get_pressure()
    pressure = round(pressure, 1)

    print "The atmospheric pressure at the Sense Hat is", pressure, "mbar\n"

    # outputing the temp, humidity, and pressure to the matrix
    sense.clear()  # clear the 8x8 matrix
    sense.set_rotation(0)  # sets orientation of Sense Hat matrix

    # setting colors for the scrolling text on the matrix
    red = (255, 0, 0)
    green = (0, 255, 0)
    blue = (0, 0, 255)

    speed = 0.02  # speed of text scroll (0.10 is default)
    sleep = 0.2  # time of pause in seconds

    sense.show_message("Temp:", text_colour=red, scroll_speed=speed)
    sense.show_message(str(tempC), text_colour=red, scroll_speed=speed)
    sense.show_message("C", text_colour=red, scroll_speed=speed)
    sense.show_message("or", text_colour=red, scroll_speed=speed)
    sense.show_message(str(tempF), text_colour=red, scroll_speed=speed)
    sense.show_message("F", text_colour=red, scroll_speed=speed)
    time.sleep(sleep)
    sense.show_message("Humidity:", text_colour=green, scroll_speed=speed)
    sense.show_message(str(humidity), text_colour=green, scroll_speed=speed)
    sense.show_message("%", text_colour=green, scroll_speed=speed)
    time.sleep(sleep)
    sense.show_message("Pressure:", text_colour=blue, scroll_speed=speed)
    sense.show_message(str(pressure), text_colour=blue, scroll_speed=speed)
    sense.show_message("mbar", text_colour=blue, scroll_speed=speed)

    sense.clear()
def lab_temp(): 
	import sys 
	from sense_hat import SenseHat

	sense = SenseHat()

	temperature = sense.get_temperature()
	pressure = sense.get_pressure()
	humidity = sense.get_humidity()

	if temperature is not None and pressure is not None and humidity is not None: 
		return render_template("lab_temp.html",temp=temperature, pres=pressure, hum=int(humidity)) 
	else: 
		return render_template("no_sensor.html") 
Example #14
0
def get_metrics():

    if settings.SENSE_HAT:
        try:
            from sense_hat import SenseHat
        except ImportError:
            raise SystemExit('[ERROR] Please make sure sense_hat is installed properly')

    sense = SenseHat()
    data = {}
    data['temperature'] = sense.get_temperature();
    data['humidity'] = sense.get_humidity();
    data['pressure'] = sense.get_pressure();

    return data;
class Sens_data():
    def __init__(self):
        self.sense = SenseHat()

    def get_temperature(self):
        return "%.2f" % self.sense.get_temperature()

    def get_humidity(self):
        return "%.2f" % self.sense.get_humidity()

    def get_pressure(self):
        return "%.2f" % self.sense.get_pressure()

    def get_timestamp(self):
        return str(int(time.time()))
Example #16
0
class Environmental(base_environmental.EnvironmentalBase):

    """
    Raspberry Pi Sense HAT environmental sensors
    """

    def __init__(self):
        self.sense = SenseHat()

    def get_temperature(self):
        return self.sense.get_temperature()

    def get_humidity(self):
        return self.sense.get_humidity()

    def get_pressure(self):
        return self.sense.get_pressure()
Example #17
0
class TemperatureEventEmitter(EventEmitter):
    def __init__(self, servers, topic, identifier):
        EventEmitter.__init__(self, servers, topic)

        self.contents = dict()
        self.contents["id"] = identifier
        
        self.event["@timestamp"] = datetime.utcnow()
        self.event["data"] = self.contents
        
        self.sense = SenseHat()

    def update_event(self):
        self.event["@timestamp"] = datetime.utcnow()
        self.event["data"]["temperature"] = round( (self.sense.get_temperature_from_pressure()+self.sense.get_temperature_from_humidity())/2,1)
        self.event["data"]["pressure"] = round(self.sense.get_pressure(),1)
        self.event["data"]["humidity"] = round(self.sense.get_humidity(),1)
        self.send() 
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() 
Example #19
0
def show_tph():
    sense = SenseHat()
    t = 0
    h = 0
    p = 0

    # sometimes it will get 0 from get_pressure(), will retry
    retry = 0
    while p < 1 and retry < 5:
        p = sense.get_pressure()
        time.sleep(1)
        retry = retry + 1

    t = sense.get_temperature()
    h = sense.get_humidity()
    t = round(t, 1)
    p = round(p, 0)
    h = round(h, 0)

    msg = "p{0} h{1} t{2}".format(p,h,t)
    return msg
Example #20
0
def show_tph():
    sense = SenseHat()
    t = 0
    h = 0
    p = 0
    while p < 1:
        p = sense.get_pressure()
        time.sleep(1)

    t = sense.get_temperature()
    h = sense.get_humidity()
    t = round(t, 1)
    p = round(p, 0)
    h = round(h, 0)

    msg = "P{0}H{1}".format(p,h)
    msg1 = "T{0}".format(t)

    sense.set_rotation(rotate_degree)
    sense.show_message(msg, text_colour=cadetblue)
    sense.show_message(msg1, text_colour=red)
Example #21
0
def getCurrentReading():

    if (not readingSense.value):
        #   flag the sensehat as busy
        readingSense.value = True
        # get the new reading
        sense = SenseHat()
        orientation = sense.get_orientation()

        #   correct the pitch
        if (orientation['roll'] <= 90 or orientation['roll'] >= 270):
            orientation['pitch'] = 360 - orientation['pitch']
        else:
            orientation['pitch'] = orientation['pitch'] - 180
        
        #   generate the reading
        newReading = {
            'time' : datetime.now(),
            'temperature': round(sense.get_temperature(),1),
            'pressure': round(sense.get_pressure(),1),
            'humidity': round(sense.get_humidity(),1),
            'roll': round(orientation['roll'],1),
            'pitch': round(orientation['pitch'], 1),
            'yaw': round(orientation['yaw'],1)
        }

        #   remove all other readings from the currentReading list
        while (len(currentReading) > 0):
            currentReading.pop()
        
        #   save the current reading
        currentReading.append(newReading)
        #   flag the sensehat as not busy
        readingSense.value = False

    if (len(currentReading) > 0):
        return currentReading[0];
    else:
        return None
Example #22
0
def get_current_data():
    if(enable_sense_hat):
        sense = SenseHat()
        sense.clear()
        t = sense.get_temperature()
        p = sense.get_pressure()
        h = sense.get_humidity()
        tp = sense.get_temperature_from_pressure()
        data = {
            'temperature':str(round(t, 1)),
            'pressure':str(round(p,1)),
            'humidity':str(round(h,1)),
            'temperatureP':str(round(tp,1)),
            'datetime' : datetime.now()
        }
    else:
         data = {
            'temperature': 0,
            'pressure':0,
            'humidity':0,
            'temperatureP':0,
            'datetime' : datetime.now()
         }
    return data
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)
from sense_hat import SenseHat

from time import sleep

sense = SenseHat()

sense.set_rotation(90)

sense.clear(0, 0, 0,)


while True:
    sense.show_message(" %s F" % round(sense.get_temperature() * 1.8 + 32))
    sleep(1)
    sense.show_message(" %s prh" % round((sense.get_humidity)()))
    sleep(1)
    sense.show_message(" %s''" % round((sense.get_pressure() * 0.0295301), 2))
    sleep(1)
Example #25
0
#!/usr/bin/python
from sense_hat import SenseHat
import time

ap = SenseHat()
temp = ap.get_temperature()
temp_f = 1.8 * round(temp, 1) + 32
humidity = round(ap.get_humidity(), 1)
pressure = round(ap.get_pressure(), 1)

sensors_file = 'sensors.prom'
path = '/tmp/sensors.prom'
new_sensors = open(path, 'w')

#print("Temp: %s F" % temp_f)               # Show temp on console
new_sensors.write("Temp %s\n" % temp_f)

#print("Humidity: %s %%rH" % humidity)        # Show humidity on console
new_sensors.write("Humidity %s\n" % humidity)

#print("Pressure: %s Millibars" % pressure)    # Show pressure on console
new_sensors.write("Pressure %s\n" % pressure)

#ap.set_rotation(180)        # Set LED matrix to scroll from right to left

#ap.show_message("%.1f C" % temp, scroll_speed=0.10, text_colour=[0, 255, 0])

#time.sleep(1)           # Wait 1 second

#ap.show_message("%.1f %%rH" % humidity, scroll_speed=0.10, text_colour=[255, 0, 0])
Example #26
0
station=config.get('Query','station')

myAltitude=config.get('Baro','myAltitude')
Altitude=float(myAltitude)
## setup influx session
client = InfluxDBClient(host=(influxHost), port=8086, username=(influxUser), password=(influxPass), database=(influxDB))
#DEBUG
#print("useSensehat is "+useSensehat)
#END DEBUG
if useSensehat == "1":
    #DEBUG
    #print("useSensehat is triggered "+useSensehat)
    #END DEBUG
    sense = SenseHat()
    #Convert to inHG
    pressure = (sense.get_pressure()*0.029529983071445)
    #Convert to Mean Sea Level Pressure
    baroX=pressure/pow(1-((Altitude)/44330.0),5.255)
    baro=round((baroX),4)
    #DEBUG
    #print( baro)
    #END DEBUG
    baroJSON = [{"measurement":"SenseHat",

        "fields":
        {
        "Barometer":(baro)
        }
        },
        ]
Example #27
0
def application(environ, start_response):

    with open('ip_devices.json') as data_file:
    	devices = json.load(data_file)

    print environ['PATH_INFO']

    #solar stuff
    solar = get_solar()
    currentPower = solar['sitesOverviews']['siteEnergyList'][0]['siteOverview']['currentPower']['power']
    print currentPower

    #meter stuff
    kWh = get_kWh()
    print kWh

    #sense hat stuff
    sense=SenseHat()

    temp_c = sense.get_temperature()
    humidity = sense.get_humidity()
    pressure_mb = sense.get_pressure()
    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 temp_f
    print humidity
    print pressure_in

    html1 = '<html><header><h1>Pi Monitoring System</h1><h2>Power & Environment</h2><title>Pi in the Basement</title></header><body>'
    html2 = '<table border="1"><tr><td><strong>Current Solar Output (W)</strong></td><td>'
    html3 = '</td></tr><tr><td><strong>Meter Reading (kWh)</strong></td><td>'
    html4 = '</td></tr><tr><td><strong>Basement Temp (F)</strong></td><td>'
    html5 = '</td></tr><tr><td><strong>Basement Humidity (%)</strong></td><td>'
    html6 = '</td></tr><tr><td><strong>Basement Pressure (in)</strong></td><td>'
    html7 = '</td></tr></table>'

    table1 = html1 + html2 + str(currentPower) + html3 + str(kWh) + html4 + str(temp_f) + html5 + str(humidity) + html6 + str(pressure_in)+ html7

    htmlclose = '</body></html>'
    html8 = '<h2>Network</h2>'
    html9 = '<table border="1">'
    table_rows = '<tr><th>Device</th><th>Status</th><th>Age (min)</th></tr>'
#    for (host, status) in Intra_pings.items():
#        table_rows += "<tr><td><strong>{}</strong></td><td>{}</td></tr>".format(host, status)

    # for key in Intra_pings:
    #     if Intra_pings[key]['Status'] == 'up':
    #         table_rows += '<tr><td><strong>' + key + '</strong></td><td   bgcolor="#00FF00">' + Intra_pings[key]['Status'] + "</td></tr>"
    #     elif Intra_pings[key]['Status'] == 'down':
    #         table_rows += '<tr><td><strong>' + key + '</strong></td><td   bgcolor="#FF0000">' + Intra_pings[key]['Status'] + "</td></tr>"

    for name in devices:
	print table_rows
	ping_status    = r.get('ping.' + str(name) + '.status')

	date_object = datetime.now() - datetime.strptime(r.get('ping.' + str(name) + '.timestamp'), '%Y-%m-%d %H:%M:%S')
	ping_minutes_ago = str((datetime.now() - datetime.strptime(r.get('ping.' + str(name) + '.timestamp'), '%Y-%m-%d %H:%M:%S')).seconds / 60)

    #ping_timestamp = r.get('ping.' + str(name) + '.timestamp')
    # ping_timestamp = r.get('ping.' + str(name) + '.timestamp')
	if ping_status == 'up':
		table_rows += '<tr><td><strong>' + str(name) + '</strong></td><td   bgcolor="#00FF00">' + ping_status + "</td><td>" + ping_minutes_ago + "</td></tr>"
	elif ping_status == 'down':
		table_rows += '<tr><td><strong>' + str(name) + '</strong></td><td   bgcolor="#FF0000">' + ping_status + "</td><td>" + ping_minutes_ago + "</td></tr>"


    html14 = '</td></tr></table>'
    #htmltime = '<h2>Time:</h2>'
    html15 = '<h2>Current picture</h2><img src="http://127.0.0.1:6600" alt="Pi Camera Picture">'
#    html15 = '<h2>Current picture</h2><img src="image.jpg" alt="Pi Camera Picture">'
#    html15 = '<h2>Current picture</h2><img src="/home/pi/projects/webServer/image.jpg" alt="Pi Camera Picture" style="width:304px;height:228px;">'
    htmlclose = '</body></html>'

    table2 = html8 + html9 + table_rows + html14

    # response_body
    response_body = table1 + table2 + html15 + htmlclose
    status = '200 OK'

    # Some header magic, create response

    response_headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))]

#    if '.jpg' in str(environ['PATH_INFO']):
#	response_headers = [('Content-type', 'image/jpg'), ('Content-Length', str(len(response_body)))]

#print response_headers

	#response_headers = [('Content-Type', 'image/jpeg'), ('Content-Length', str(len(response_body)))]
    start_response(status, response_headers)

    return [response_body]
Example #28
0
sense.set_rotation(180)
var = 1

X = [255, 0, 0]  # Red
O = [255, 255, 255]  # White

question_mark = [
    O, O, O, O, O, O, O, O, O, X, X, O, O, X, X, O, O, X, X, O, O, X, X, O, O,
    O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, X, O, O, O, O, X, O, O, O,
    X, X, X, X, O, O, O, O, O, X, X, O, O, O
]

while (1 == 1):
    print("%s Temperature" % sense.temp)
    print("%s Temp - humidity sensor" % sense.get_temperature_from_humidity())
    print("%s Temp - pressure sensor" % sense.get_temperature_from_pressure())
    print("%s Pressure: in Millibars" % sense.get_pressure())
    print("%s Humidity" % sense.get_humidity())

    north = sense.get_compass()
    print("%s Degrees to north" % north)

    raw = sense.get_accelerometer_raw()
    print("Acc intensity in Gs x: {x}, y: {y}, z: {z}".format(**raw))

    m = '%.1f' % sense.temp
    sense.show_message(m, text_colour=[255, 0, 0])
    print("*********")
    sense.set_pixels(question_mark)
    time.sleep(1)
class Monitor:
    def __init__(self, databaseName='VirtualSenseHat.db'):
        self.sense = SenseHat()
        self.pb = Pushbullet(ACCESS_TOKEN)
        self.databaseName = databaseName
        self.database = Database(self.databaseName)
        self.connection = sqlite3.connect(databaseName)
        self.cursor = self.connection.cursor()
        self.configFilename = 'config.json'
        self.startTime = datetime.now(timezone)
        self.fakeTime = self.startTime

    def initRange(self):
        with open(self.configFilename, "r") as file:
            self.range = json.load(file)

        self.minTemp = self.range["min_temperature"]
        self.maxTemp = self.range["max_temperature"]
        self.minHumidity = self.range["min_humidity"]
        self.maxHumidity = self.range["max_humidity"]

    def readSenseHatData(self):
        self.timestamp = datetime.now(timezone)
        self.date = self.timestamp.date()
        time = self.timestamp.time()
        self.temperature = self.sense.get_temperature()
        self.humidity = self.sense.get_humidity()

        if self.temperature == 0 or self.humidity <= 0:
            self.readSenseHatData()

    def CheckDatabase(self):
        self.cursor.execute("""SELECT * FROM pushbullet_data ORDER BY
                            date DESC LIMIT 1""")
        result = self.cursor.fetchone()[0]
        strdate = self.date.strftime(DATE_FORMAT)
        if result == strdate:
            return True
        else:
            return False

    def send_notification_via_pushbullet(self, title, body):
        """ Sending notification via pushbullet.
            Args:
                title (str) : Title of text.
                body (str) : Body of text.
        """
        data = {"type": "note", "title": title, "body": body}

        response = requests.post("https://api.pushbullet.com/v2/pushes",
                                 data=json.dumps(data),
                                 headers={
                                     "Authorization": "Bearer " + ACCESS_TOKEN,
                                     "Content-Type": "application/json"
                                 })
        print("Notification sent.")

    def evaluateStatus(self, item, value, min, max, unit):
        if value < min:
            status = item + " is below minimum ({} {})".format(min, unit)
        elif value > max:
            status = item + " is above maximum ({} {})".format(max, unit)
        else:
            return ""
        return status

    def startMonitoring(self):
        logging.debug('Start monitoring...')
        while (True):
            self.readSenseHatData()
            t1 = self.sense.get_temperature_from_humidity()
            t2 = self.sense.get_temperature_from_pressure()
            t_cpu = get_cpu_temp()
            h = self.sense.get_humidity()
            p = self.sense.get_pressure()
            # Calculates the real temperature compesating CPU heating.
            t = (t1 + t2) / 2
            t_corr = t - ((t_cpu - t) / 1.5)
            t_corr = get_smooth(t_corr)
            self.temperature = t_corr

            self.database.insertSenseHatData(self.timestamp.date(),
                                             self.timestamp.time(),
                                             self.temperature, self.humidity)

            if self.CheckDatabase() is False:
                sendstatus = "All Good"
                temperatureStatus = self.evaluateStatus(
                    "Temperature", int(self.temperature), self.minTemp,
                    self.maxTemp, "*C")
                humidityStatus = self.evaluateStatus("Humidity",
                                                     int(self.humidity),
                                                     self.minHumidity,
                                                     self.maxHumidity, "%")
                if temperatureStatus == "" and humidityStatus == "":
                    sendstatus = "All Good"
                elif temperatureStatus != "" and humidityStatus != "":
                    sendstatus = temperatureStatus + " and " + humidityStatus
                elif temperatureStatus != "" and humidityStatus == "":
                    sendstatus = temperatureStatus
                elif temperatureStatus == "" and humidityStatus != "":
                    sendstatus = humidityStatus

                body = """Currently the temperature is {:.2f}*C and the
                        humidity is {:.2f}% \nStatus Report: {}""".format(
                    self.temperature, self.humidity, sendstatus)
                printDevice = self.pb.devices[0]
                self.database.insertPushbulletData(
                    self.date.strftime(DATE_FORMAT))
                push = printDevice.push_note("Weather Update", body)

            logging.debug('\nWaiting for 1 minute...\n')
            time.sleep(60)

    def stopMonitoring(self):
        logging.debug('Stop monitoring...\nStop writing to the database...')
        self.database.closeDatabase()
Example #30
0
# sense.show_message("IoT Sensor Pack")
# sense.show_message(str(datetime.datetime.now()))

def signal_handler(signal, frame):
    print("Shutting down.")
    sense.clear()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

sense.clear()

try:
    while True:
        t = sense.get_temperature()
        p = sense.get_pressure()
        h = sense.get_humidity()

        t = round(t, 1)
        p = round(p, 1)
        h = round(h, 1)

        print("T: %d    P: %d     H: %d" % (t, p, h))

        sense.show_message("T: %d P: %d H: %d" % (t, p, h))
        time.sleep(5)

except KeyboardInterrupt:
    print("Breaking out.")
    sense.clear()
Example #31
0
sense = SenseHat()

# Connect to the broker over MQTT port
client.username_pw_set("admin", "admin")
client.tls_set("ca.crt")
client.connect("192.168.99.75", port=8883, keepalive=60)
client.loop_start()  # Keep the connection open

# Publish a message to the "Capstone" topic
running = True
while running:

    # Get temperature from sensor and convert it to Farenheit
    tempF = format(((sense.get_temperature() * 1.8) + 32), '.2f')
    humidity = format(sense.get_humidity(), '.2f')
    psi = format(sense.get_pressure() * 0.0145038, '.2f')

    # Send multiple values as a dictionary
    data = {
        'Temperature (Farenheit)': tempF,
        'Humidity (% relative)': humidity,
        'Pressure (psi)': psi
    }

    # Publish the message to the Capstone topic
    client.publish("Capstone", payload=str(data), qos=0)

#	data = {'tempC':sense.get_temperature(), 'humidity':sense.get_humidity()}
#+	msgs=[{'topic':"Capstone", 'payload':"The temperature is now"+" "\
#		 + format(tempC, '.2f')+" degrees F"}]
Example #32
0
OFFSET_X = offset['x']
OFFSET_Y = offset['y']
OFFSET_Z = offset['z']

offset = sense.get_orientation()
OFFSET_PITCH = offset['pitch']
OFFSET_ROLL = offset['roll']
OFFSET_YAW = offset['yaw']


positionX = 0
positionY = 0
positionZ = 0
while (True):
    humidity = sense.get_humidity()
    print("Pressure: {} mbar".format(sense.get_pressure()))
    print("")
    print("ORIENTATION")
    print("===========")
    print("Orientation in rad/s:")
    orientation = sense.get_orientation()
    orientationRad = sense.get_orientation_radians()
    print("==> Pitch (X): {}".format(orientation['pitch'] - OFFSET_PITCH))
    print("==>  Roll (Z): {}".format(orientation['roll'] - OFFSET_ROLL))
    print("==>   Yaw (Y): {}".format(orientation['yaw'] - OFFSET_YAW))
    print("")
    print("ACCELEROMETER DATA DELTA: RAW")
    print("=======================")
    accel = sense.get_accelerometer_raw()
    print("==> X: {}".format(accel['x'] - OFFSET_X))
    print("==> Y: {}".format(accel['y'] - OFFSET_Y))
sense = SenseHat()

#firebase = firebase.FirebaseApplication("https://estacionmeteorologicaverano.firebaseio.com", None)
#file = open('data' + '.txt','w')

time.sleep(1)
sense.clear(0, 240, 21)
time.sleep(2)
sense.clear(0, 0, 0)
current_time = datetime.datetime.now().isoformat()
for i in range(10):
    with open('/home/pi/Documents/data' + str(current_time) + '.txt', 'a') as file:
		temp = round(sense.get_temperature(), 1)
		hum = round(sense.get_humidity(), 1)
		pres = round(sense.get_pressure(), 1)
		ori = sense.get_orientation()
		mag = sense.get_compass_raw()
		acc = sense.get_accelerometer_raw()
		gyro = sense.get_gyroscope_raw()
		data = {
				'temperature':temp,
				'humidity':hum,
				'pressure':pres,
				'orientation':ori,
				'compass':mag,
				'acceleration':acc,
				'gyroscope':gyro,
				'time': datetime.datetime.now().isoformat()
				}
		file.write(str(data) + ',\n')
Example #34
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sense_hat import SenseHat
from time import sleep

sh = SenseHat()

try:
    while True:
        th = sh.get_temperature()
        tp = sh.get_temperature_from_pressure()
        p = sh.get_pressure()
        h = sh.get_humidity()

        th = round(th, 1)
        tp = round(tp, 1)
        p = round(p, 1)
        h = round(h, 1)

        print(
            "Temp (H) = %s°C    Temp (P) = %s°C    Prsr = %smb   Hmdt = %s%%" %
            (th, tp, p, h))
        sleep(1)

except KeyboardInterrupt:
    print("Exiting...")
Example #35
0
        "tags": {
            "source": "sensehat"
        },
        "time": t,
        "fields": {
            "value": sense.get_humidity()
        }
    })
    points.append({
        "measurement": "pressure",
        "tags": {
            "source": "sensehat"
        },
        "time": t,
        "fields": {
            "value": sense.get_pressure()
        }
    })
    try:
        client.write_points(points, retention_policy='cleanup')
    except:
        logging.error("influxdb write not successful")
    time.sleep(120)

# TODO: Spawn another thread for the display
# try:
#     current_item = 0
#     # Start on the default
#     current_stopper = threading.Event()
#     current_thread = actions[0](current_stopper)
#     current_thread.start()
Example #36
0
t = 0
i = 1
O = (0, 0, 0)
pixels = [O]*64
dry = False
stink = False
# Main Loop
while True:
    try:
        t = t+1
        threshold_dry = 120*37/30
        threshold_stinky = 180*1020/1000
        temp = hat.get_temperature()
        hum = hat.get_humidity()
        temp_p = hat.get_temperature_from_pressure()
        pressure = hat.get_pressure()
        timestamp = datetime.now()        
        
        temp_mean = (temp+temp_p)/2
        acc_dryness = acc_dryness + temp_mean/hum
        acc_stinkness = acc_stinkness + pressure/1000
        
        
        if (acc_dryness >= threshold_dry) & (dry==False):
            color = (0, 255, 0)
            dry = True
            SUBJECT = "Perfect ND Status (BGSE IoT prototype)"
            TO = "*****@*****.**"
            FROM = "*****@*****.**"
            text = "Dear client,\n \n Announcement: Your clothes are already dry, ready for you to pick up and nicely fold them. You have "+str(round(threshold_stinky-acc_stinkness))+"min to take them before they become too stinky to be worn. \n\n Please pick up them as soon as possible.\n\n Yours sincerely,\n PerfectND Communication Managers: Jose and Roger\n\n This message was created automatically from Raspberry Pi, thank you for trusting our company."
            BODY = string.join((
Example #37
0
from multiprocessing import Pool
from multiprocessing import cpu_count
import time
import math
from sense_hat import SenseHat
import psutil
import subprocess
import os

# sense hat API
sense = SenseHat()
sense.get_pressure()

# data lists
cpu_temperature = []
sh_pressure = []
sh_temperature_p = []
sh_temperature_h = []
timestamp = []

print("Insert run time:")
runtime = int(input())

#timer
start_time = time.time()
now = start_time


def recursive_stress():
    for i in range(0, 100):
        i * i
Example #38
0
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print('successfully sent the mail')
    except:
        print("failed to send mail")

while(True):
	
	p = sense.get_pressure()
	t = sense.get_temperature()
	h = sense.get_humidity()

	p = round(p,1)
	t = round(t,1)
	h = round(h,1)

	measurements = "Temp: " + str(t) + "," "Pressure: " + str(p) + "," "Humidity: " + str(h)
	temp = str(t)

	if (h >= 40) and (h <= 60):
		normal_hum = True
	else:
		normal_hum = False
Example #39
0
def my_read_handler():
    sense = SenseHat()
    sense.clear()
    pressure = sense.get_pressure()
    sense.show_letter("E", [0, 0, 255], [0, 0, 0])
    blynk.virtual_write(5, int(pressure))
Example #40
0
        accel_yaw = accel['yaw']

        gyro_x = gyroraw['x']
        gyro_y = gyroraw['y']
        gyro_z = gyroraw['z']
        gyro_pitch = gyro['pitch']
        gyro_roll = gyro['roll']
        gyro_yaw = gyro['yaw']

        pitch = ori['pitch']
        roll = ori['roll']
        yaw = ori['yaw']

        temperatura = sense.get_temperature()
        temperatura2 = sense.get_temperature_from_humidity()
        pressione = sense.get_pressure()
        umidita = sense.get_humidity()

        print(str(datetime.now()) + " - lettura sensori")

    except:
        print(str(datetime.now()) + " - Eccezione lettura sensori")

    # ---------- Calcola la posizione della ISS               ---------------
    # ---------- Take picture                     ---------------
    # calcoliamo la posizione in questo momento
    try:
        iss.compute()
        print(str(datetime.now()) + " - calcolo posizione ISS")
    except:
        print(str(datetime.now()) + " - Errore calcolo posizione ISS")
Example #41
0
# -*- coding: utf-8 -*-
import os
import time
import datetime

from sense_hat import SenseHat

if __name__ == "__main__":
    s = SenseHat()
    temp = min(
        [s.get_temperature_from_humidity(),
         s.get_temperature_from_pressure()]) - 4.0  # correction
    hum = s.get_humidity()
    s.rotation = 180
    pres = s.get_pressure() / 1000.0
    s.low_light = True
    t = datetime.datetime.now().strftime("%b %d, %Y. %H:%M")

    for i in range(0, 29 - 8):
        p = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "img_{}.png".format(i))
        s.load_image(p)
        time.sleep(0.3)
    time.sleep(1)
    for i in reversed(range(0, 29 - 8)):
        p = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                         "img_{}.png".format(i))
        s.load_image(p)
        time.sleep(0.3)
    time.sleep(1)
Example #42
0
import time
from sense_hat import SenseHat, ACTION_PRESSED, ACTION_HELD, ACTION_RELEASED
import sys
sys.path.insert(0, "/home/pi/workspace/iot/Common")
from SensorMsg import SensorMsg

sensor = SenseHat()
sensorMsg = SensorMsg()
sensorMsg.setDeviceID(102)
sensorMsg.setDeviceLatitude(42.504905)
sensorMsg.setDeviceLongitude(-71.236539)

while True:

    temp = sensor.get_temperature()
    pressure = sensor.get_pressure()
    humidity = sensor.get_humidity()
    orientation = sensor.get_orientation()

    #round to nearest 1/10th
    temp = round(temp, 1)
    pressure = round(pressure, 1)
    humidity = round(humidity, 1)
    #convert temp to fahrenheit
    temp = temp * 1.8 + 32

    sensorMsg.setSensorType(1)
    sensorMsg.setSensorValue(temp)
    sensorMsg.updateTime()

    msg = sensorMsg.toString()
Example #43
0
from sense_hat import SenseHat

# We can change the name of our object as long as we are consisted within each script
sense = SenseHat()

# this function will retrieve a value from the sensor, we can assign it to a variable
pressure_mbars = sense.get_pressure()

# we can use basic math to manipulate variables
pressure_atm = pressure_mbars / 1013.25

# The print function can be used to report to the terminal our variables
print("Pressure: {} Millibars ({} atm)".format(pressure_mbars, pressure_atm))
Example #44
0
from dbconfig import *
import mysql.connector
from datetime import datetime
from sense_hat import SenseHat

# Create SenseHat object

sense = SenseHat()

date_v = datetime.now()
humi_v = sense.get_humidity()
tmph_v = sense.get_temperature()
tmpp_v = sense.get_temperature_from_pressure()
pres_v = sense.get_pressure()

# Connect to MySQL

sql = mysql.connector.connect(user=MYSQL_USER,
                              password=MYSQL_PWD,
                              host=MYSQL_HOST,
                              database=DATABASE_NAME)
cursor = sql.cursor()

updatetime = datetime.now()

data = (TABLE_NAME, READ_DATE, READ_HUMI, READ_TMPH, READ_TMPP, READ_PRES,
        date_v, humi_v, tmph_v, tmpp_v, pres_v)

update_query = "INSERT INTO %s (%s, %s, %s, %s, %s) VALUES ('%s','%s','%s','%s','%s')" % data

cursor.execute(update_query)
Example #45
0
class InputModule(AbstractInput):
    """A sensor support class that measures."""
    def __init__(self, input_dev, testing=False):
        super().__init__(input_dev, testing=testing, name=__name__)

        self.sensor = None

        if not testing:
            self.try_initialize()

    def initialize(self):
        """Initialize the Sense HAT sensor class."""
        from sense_hat import SenseHat

        self.sensor = SenseHat()

    def get_measurement(self):
        """Get measurements and store in the database."""
        if not self.sensor:
            self.logger.error(
                "Error 101: Device not set up. See https://kizniche.github.io/Mycodo/Error-Codes#error-101 for more info."
            )
            return

        self.return_dict = copy.deepcopy(measurements_dict)

        if self.is_enabled(0):
            try:
                self.value_set(0, self.sensor.get_temperature())
            except Exception as e:
                self.logger.error(
                    "Temperature (temperature sensor) read failure: {}".format(
                        e))

        if self.is_enabled(1):
            try:
                self.value_set(1, self.sensor.get_temperature_from_humidity())
            except Exception as e:
                self.logger.error(
                    "Temperature (humidity sensor) read failure: {}".format(e))

        if self.is_enabled(2):
            try:
                self.value_set(2, self.sensor.get_temperature_from_pressure())
            except Exception as e:
                self.logger.error(
                    "Temperature (pressure sensor) read failure: {}".format(e))

        if self.is_enabled(3):
            try:
                self.value_set(3, self.sensor.get_humidity())
            except Exception as e:
                self.logger.error("Humidity read failure: {}".format(e))

        if self.is_enabled(4):
            try:
                self.value_set(4, self.sensor.get_pressure())
            except Exception as e:
                self.logger.error("Pressure read failure: {}".format(e))

        if self.is_enabled(5):
            try:
                self.value_set(5, self.sensor.get_compass())
            except Exception as e:
                self.logger.error("Compass read failure: {}".format(e))

        if self.is_enabled(6) or self.is_enabled(7) or self.is_enabled(8):
            magnetism = self.sensor.get_compass_raw()
            if self.is_enabled(6):
                try:
                    self.value_set(6, magnetism["x"])
                except Exception as e:
                    self.logger.error(
                        "Compass raw x read failure: {}".format(e))
            if self.is_enabled(7):
                try:
                    self.value_set(7, magnetism["y"])
                except Exception as e:
                    self.logger.error(
                        "Compass raw y read failure: {}".format(e))
            if self.is_enabled(8):
                try:
                    self.value_set(8, magnetism["z"])
                except Exception as e:
                    self.logger.error(
                        "Compass raw z read failure: {}".format(e))

        if self.is_enabled(9) or self.is_enabled(10) or self.is_enabled(11):
            gyroscope = self.sensor.get_gyroscope()
            if self.is_enabled(9):
                try:
                    self.value_set(9, gyroscope["pitch"])
                except Exception as e:
                    self.logger.error(
                        "Gyroscope pitch read failure: {}".format(e))
            if self.is_enabled(10):
                try:
                    self.value_set(10, gyroscope["roll"])
                except Exception as e:
                    self.logger.error(
                        "Gyroscope roll read failure: {}".format(e))
            if self.is_enabled(11):
                try:
                    self.value_set(11, gyroscope["yaw"])
                except Exception as e:
                    self.logger.error(
                        "Gyroscope yaw read failure: {}".format(e))

        if self.is_enabled(12) or self.is_enabled(13) or self.is_enabled(14):
            acceleration = self.sensor.get_accelerometer_raw()
            if self.is_enabled(12):
                try:
                    self.value_set(12, acceleration["x"])
                except Exception as e:
                    self.logger.error(
                        "Acceleration x read failure: {}".format(e))
            if self.is_enabled(13):
                try:
                    self.value_set(13, acceleration["y"])
                except Exception as e:
                    self.logger.error(
                        "Acceleration y read failure: {}".format(e))
            if self.is_enabled(14):
                try:
                    self.value_set(14, acceleration["z"])
                except Exception as e:
                    self.logger.error(
                        "Acceleration z read failure: {}".format(e))

        return self.return_dict
Example #46
0
                         y=0,
                         z=10)

# Text
arialFont = pi3d.Font("fonts/FreeMonoBoldOblique.ttf", (221, 0, 170, 255))
mystring = pi3d.String(font=arialFont, string="Something", z=4)
mystring.set_shader(flatsh)

# Fetch key presses
mykeys = pi3d.Keyboard()

orientation = sense.get_orientation_degrees()
ORIGINAL_YAW = orientation['yaw']
ORIGINAL_PITCH = orientation['pitch']
ORIGINAL_ROLL = orientation['roll']
ORIGINAL_PRESSURE = sense.get_pressure()

while DISPLAY.loop_running():
    CAMERA.reset()
    cylinder.draw(shinesh, [patimg, shapebump, shapshine], 4.0, 0.1)
    pressure = sense.get_pressure()
    #mystring = pi3d.String(font=arialFont, string='%.2f' % pressure, z=9)
    #mystring.set_shader(flatsh)
    #print(str(pressure))
    mystring.draw()

    orientation = sense.get_orientation_degrees()
    CAMERA.rotateY(ORIGINAL_YAW - orientation['yaw'])
    CAMERA.rotateX(ORIGINAL_PITCH - orientation['pitch'])
    CAMERA.rotateZ(ORIGINAL_ROLL - orientation['roll'])
Example #47
0
class Worker(QObject):
    signalStatus = pyqtSignal(str)
    updateButtons = pyqtSignal(bool, bool)
    updateLcd = pyqtSignal(float, float, float)
    updateGraphs = pyqtSignal(float, float, float, float)

    def __init__(self, parent=None):
        super(self.__class__, self).__init__(parent)
        self.filename = "log.txt"
        self.temperature = 0
        self.humidity = 0
        self.pressure = 0
        self.interval = 5
        self.sense = SenseHat()
        self.sense.set_imu_config(False, False, True)
        self.debugMode = False
        self.stopEvent = threading.Event()

    @pyqtSlot()
    def start(self):
        self.updateButtons.emit(False, True)
        self.stopEvent.clear()
        while not self.stopEvent.is_set():
            self.rotate_display()
            if self.debugMode == False:
                self.temperature = self.sense.get_temperature()
                self.humidity = self.sense.get_humidity()
                self.pressure = self.sense.get_pressure()

            self.updateLcd.emit(self.temperature, self.humidity, self.pressure)
            self.updateGraphs.emit(self.temperature, self.humidity, self.pressure, self.interval)
            self.show_temperature_on_led_matrix(self.temperature)
            self.log_to_file(self.temperature, self.humidity, self.pressure, self.filename)
            self.stopEvent.wait(timeout=(self.interval))

    def stop(self):
        self.stopEvent.set()

    def update_temperature(self, value):
        if self.debugMode == True:
            self.temperature = value

    def update_humidity(self, value):
        if self.debugMode == True:
            self.humidity = value

    def update_pressure(self, value):
        if self.debugMode == True:
            self.pressure = value

    def update_interval(self, value):
        self.interval = value

    def update_debug_mode(self, value):
        self.debugMode = value
        if value == True:
            self.filename = "log_debug.txt"
        else:
            self.filename = "log.txt"

    def log_to_file(self, temperature, humidity, pressure, filename):
        temperatureString = "{:.1f}°C".format(temperature)
        humidityString = "{:.0f}%".format(humidity)
        pressureString = "{:.0f}mbar".format(pressure)
        timeString = time.strftime("%d/%m/%Y %H:%M:%S")
        file = open(filename, "a")
        file.write(timeString + " | " + "Temperature: " + temperatureString + " | " + "Humidity: " + humidityString
                   + " | " + "Pressure: " + pressureString + "\n")
        file.close()

    def show_temperature_on_led_matrix(self, temp):
        positiveDegreeValue = 255 - temp * 5
        negativeDegreeValue = 255 + temp * 5

        if temp >= 0 and temp < 50:
            tempGrade = (255, positiveDegreeValue, positiveDegreeValue)

        elif temp < 0 and temp > -50:
            tempGrade = (negativeDegreeValue, negativeDegreeValue, 255)

        elif temp >= 50:
            tempGrade = (255, 0, 0)

        elif temp <= -50:
            tempGrade = (0, 0, 255)

        tempToString = "{:.1f}".format(temp)

        self.sense.show_message(tempToString + "c", back_colour=[0, 0, 0], text_colour=tempGrade)

    def rotate_display(self):
        x = round(self.sense.get_accelerometer_raw()['x'], 0)
        y = round(self.sense.get_accelerometer_raw()['y'], 0)

        rotation = 0
        if x == -1:
            rotation = 90
        elif y == -1:
            rotation = 180
        elif x == 1:
            rotation = 270

        self.sense.set_rotation(rotation)
Example #48
0
import datetime
from time import sleep

s = SenseHat()
s.low_light = True

start_time = datetime.datetime.now()
now_time = datetime.datetime.now()
duration = datetime.timedelta(seconds=5)

with open("vejrdata.csv", "w") as file:
    file.write("time , Temperature , Pressure, Humidity \n")

while now_time < start_time + duration:
    t = s.get_temperature()
    p = s.get_pressure()
    h = s.get_humidity()
    now_time = datetime.datetime.now()

with open("Vejrrapport.csv", "a") as file:
    file.write("%s, %s C, %s Millibars, %s %%rH \n" % (now_time, t, p, h))
    sleep(0.1)

yellow = (255, 255, 0)
blue = (0, 0, 255)
white = (255, 255, 255)
nothing = (0, 0, 0)
grey = (169, 169, 169)
cyan = (240, 248, 255)

    wind_speed = data['wind']['speed']
    sunrise = datetime.fromtimestamp(data['sys']['sunrise'])
    sunset = datetime.fromtimestamp(data['sys']['sunset'])
    return weather, temp, humidity, wind_speed, sunrise, sunset


if __name__ == '__main__':
    try:
        mqttc = mqtt.Client()
        mqttc.connect(BROKER_URL, 1883, 60)
        while True:
            weather, temp, humidity, wind_speed, sunrise, sunset = get_weather(get_location())
            mqttc.publish('umgebung/wetter', str(weather))
            mqttc.publish('umgebung/temperatur', str(temp))
            mqttc.publish('umgebung/luftfeuchtigkeit', str(humidity))
            mqttc.publish('umgebung/windgeschwindigkeit', str(wind_speed))
            mqttc.publish('umgebung/sonnenaufgang', str(sunrise))
            mqttc.publish('umgebung/sonnenuntergang', str(sunset))
            mqttc.publish('wohnzimmer/temperatur', str(sense.get_temperature()))
            mqttc.publish('wohnzimmer/luftdruck', str(sense.get_pressure()))
            mqttc.publish('wohnzimmer/luftfeuchtigkeit', str(sense.get_humidity()))
            # überprüfe, ob das Steuerkreuz nach unten gedrückt wurde
            for event in sense.stick.get_events():
                if 'down' in event.direction:
                    exit()
            time.sleep(CYCLE_TIME)
    except KeyboardInterrupt:
        mqttc.disconnect()
        sense.clear()
        print('Tschüß!')
Example #50
0
"""Create an instance for SMTP Client connector"""
conn = SmtpClientConnector.SmtpClientConnector()
"""Connect securely"""
myMQTTClient.connect()
"""Publish the relevant data set"""
myMQTTClient.publish("sensor/info", "connected", 0)
"""Infinitely Publish the Sensor Data to the AWS IoT Cloud Service"""
while 1:
    now = datetime.utcnow()  # get the current time in UTC time format
    now_str = now.strftime(
        '%Y-%m-%dT%H:%M:%SZ')  # format my date-time module as per my needs.
    instance = SenseHat()  # Create an instance of SenseHat
    result_temp = instance.get_temperature(
    )  # Get the Temperature from Sensehat
    result_humd = instance.get_humidity()  # Get the Humidity from Sensehat
    result_press = instance.get_pressure()  # Get the Pressure from Sensehat
    """Structuring my Payload in the desired format."""
    payload = '{ "timestamp": "' + now_str + '","temperature": ' + str(
        result_temp) + '","pressure": '
    +str(result_press) + ',"humidity": ' + str(result_humd) + '}'

    print(payload)  # print the payload data on the user console
    """Publish the Topic and the Payload Info to the AWS IoT Cloud Service"""
    myMQTTClient.publish("sensor/data", payload, 0)
    """Actuator - Sensehat --> Show the message on the LED Screen"""
    instance.show_message('Low')

    print("No Email Triggered.")  # print the message on the console
    sleep(5)  # wait for 5 seconds

    if result_temp >= 39:
from sense_hat import SenseHat

from time import sleep

import math

sense = SenseHat()

sense.clear(0, 0, 0,)

while True:
        sense.show_message(
            " %s''" %
            round(sense.get_pressure() * 0.0295301), 2)
        sleep(1)
# From here: https://github.com/BenIanGifford/sense-hat/blob/master/sense_repeat_pres_inches.py
Example #52
0
from sense_hat import SenseHat
import time
from time import asctime

sense = SenseHat()

while True:
  temp=round(sense.get_temperature()*1.8+32)
  humidity=round(sense.get_humidity())
  pressure=round(sense.get_pressure())
  message='T=%dF,H=%d,P=%d'%(temp,humidity,pressure)
  sense.show_message(message,scroll_speed=(0.06),text_colour=[200,240,200],back_colour=[0,0,0]
  time.sleep(4)
  log=open('weather.txt,"a")
  now=str(asctime())
  log.write(now+''+message+'\n')        '''saves measured values in text file'''
  print(message)
  log.close()
  time.sleep(5) 
    0,
    1,
    0,
    1,
    1,
    1,
    0,
    0,
    0,
    1
]

blank = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

barometerTimer = 0  #Initialize counter
currentPressure = int(mToi(sense.get_pressure()) * 100) / 100.

pressureArray = [
]  #Define array for barometric pressure - will be a sliding window that updates every minute
pressureArray = initBarometer(
    pressureArray, barometerInterval
)  #Start with the same value every minute. Eventually we'll be able to look back once a minute to the value a barometerInterval ago.
#print (pressureArray, len(pressureArray))

hourColour = [255, 0, 0]  # red
minuteColour = [0, 255, 255]  # cyan
empty = [0, 0, 0]  # off / black
white = [255, 255, 255]  # white
green = [0, 255, 0]  # green
red = [255, 0, 0]  # red
dotColor = white  #assume initial stable barometric pressure
Example #54
0
class PiSenseHat(object):
    """Raspberry Pi 'IoT Sense Hat API Driver Class'."""

    # Constructor
    def __init__(self):
        self.sense = SenseHat()
        # enable all IMU functions
        self.sense.set_imu_config(True, True, True)

    # Pressure
    def getPressure(self):
        return self.sense.get_pressure()

    # Temperature
    def getTemperature(self):
        return self.sense.get_temperature()

    # Humidity
    def getHumidity(self):
        return self.sense.get_humidity()

    def getHumidityTemperature(self):
        return self.sense.get_temperature_from_humidity()

    def getPressureTemperature(self):
        return self.sense.get_temperature_from_pressure()

    def getOrientationRadians(self):
        return self.sense.get_orientation_radians()

    def getOrientationDegrees(self):
        return self.sense.get_orientation_degrees()

    # degrees from North
    def getCompass(self):
        return self.sense.get_compass()

    def getAccelerometer(self):
        return self.sense.get_accelerometer_raw()

    def getEnvironmental(self):
        sensors = {'name' : 'sense-hat', 'environmental':{}}
        return sensors

    def getJoystick(self):
        sensors = {'name' : 'sense-hat', 'joystick':{}}
        return sensors

    def getInertial(self):
        sensors = {'name' : 'sense-hat', 'inertial':{}}

    def getAllSensors(self):
        sensors = {'name' : 'sense-hat', 'environmental':{}, 'inertial':{}, 'joystick':{}}
        sensors['environmental']['pressure'] = { 'value':self.sense.get_pressure(), 'unit':'mbar'}
        sensors['environmental']['temperature'] = { 'value':self.sense.get_temperature(), 'unit':'C'}
        sensors['environmental']['humidity'] = { 'value':self.sense.get_humidity(), 'unit': '%RH'}
        accel = self.sense.get_accelerometer_raw()
        sensors['inertial']['accelerometer'] = { 'x':accel['x'], 'y':accel['y'], 'z': accel['z'], 'unit':'g'}
        orientation = self.sense.get_orientation_degrees()
        sensors['inertial']['orientation'] = { 'compass':self.sense.get_compass(), 'pitch':orientation['pitch'], 'roll':orientation['roll'], 'yaw': orientation['yaw'], 'unit':'degrees'}
        return sensors
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)
Example #56
0
    if color == 1:
        sense.set_pixel(
            xpos, ypos,
            (0, random.randint(100, 255), random.randint(100, 255)))
    elif color == 2:
        sense.set_pixel(
            xpos, ypos,
            (random.randint(100, 255), 0, random.randint(100, 255)))
    else:
        sense.set_pixel(
            xpos, ypos,
            (random.randint(100, 255), random.randint(100, 255), 0))
    time.sleep(0.02)

temp = sense.get_temperature()
pressure = sense.get_pressure()
humidity = sense.get_humidity()

w = (255, 255, 255)
b = (0, 0, 0)

temp_picture = [
    b, w, w, w, b, b, b, b, b, w, b, w, b, b, b, b, b, w, w, w, b, b, b, b, b,
    w, b, w, b, w, w, w, b, w, b, w, b, b, w, b, b, w, w, w, b, b, w, b, b, w,
    w, w, b, b, w, b, b, b, w, b, b, b, b, b
]

#sense.set_rotation(0)
sense.set_pixels(temp_picture)
time.sleep(4)
Example #57
0
from sense_hat import SenseHat

from time import sleep

sense = SenseHat()

sense.set_rotation(90)

sense.clear(
    0,
    0,
    0,
)

while True:
    sense.show_message(" %s F" % round(sense.get_temperature() * 1.8 + 32))
    sleep(1)
    sense.show_message(" %s prh" % round((sense.get_humidity)()))
    sleep(1)
    sense.show_message(" %s''" % round((sense.get_pressure() * 0.0295301), 2))
    sleep(1)
class WeatherStation(CarouselContainer):
    """Weather Station controlling class, setups and manages station run time."""

    # Constants
    SMOOTH_READINGS_NUMBER = 3
    READINGS_PRINT_TEMPLATE = 'Temp: %sC (%sF), Humidity: %s%%, Pressure: %s inHg'

    def __init__(self):
        super(WeatherStation, self).__init__()

        self._sense_hat = None
        self._log_timer = None
        self._upload_timer = None
        self._update_timer = None
        self._last_readings = None

    @property
    def carousel_items(self):
        return DEFAULT_WEATHER_ENTITIES

    @property
    def current_style(self):
        return self.current_item.current_style

    def activate_sensors(self):
        """Activates sensors by requesting first values and assigning handlers."""
        self._sense_hat = SenseHat()

        # Scroll Init message over HAT screen
        self._show_message('Init Sensors', (255, 255, 0), (0, 0, 255))

        # Init sensors, to be sure first effective run uses correct sensors values
        self._sense_hat.get_humidity()
        self._sense_hat.get_pressure()

        # Setup Sense Hat stick
        self._sense_hat.stick.direction_up = self._change_weather_entity
        self._sense_hat.stick.direction_down = self._change_weather_entity
        self._sense_hat.stick.direction_left = self._change_weather_entity
        self._sense_hat.stick.direction_right = self._change_weather_entity
    
    def start_station(self):
        """Launches multiple threads to handle configured behavior."""
        if Config.LOG_TO_CONSOLE and Config.LOG_INTERVAL:
            self._log_results(first_time=True)

        if Config.WEATHER_UPLOAD and Config.UPLOAD_INTERVAL:
            self._upload_results(first_time=True)

        if Config.UPDATE_DISPLAY and Config.UPDATE_INTERVAL:
            self._update_display()

    def stop_station(self):
        """Tries to stop active threads and clean up screen."""
        if self._sense_hat:
            self._sense_hat.clear()

        if self._log_timer:
            self._log_timer.cancel()

        if self._upload_timer:
            self._upload_timer.cancel()

        if self._update_timer:
            self._update_timer.cancel()

    @staticmethod
    def to_fahrenheit(value):
        """Converts celsius temperature to fahrenheit."""
        return (value * 1.8) + 32

    @staticmethod
    def calculate_dew_point(temp, hum):
        """
        Calculates dewpoint in celsius, uses simplified formula less accurate but obvious.
        https://en.wikipedia.org/wiki/Dew_point#Calculating_the_dew_point
        """
        return temp - (100 - hum) / 5

    def get_temperature(self):
        """
        Gets temperature and adjusts it with environmental impacts (like cpu temperature).
                
        There are some issues, getting an accurate temperature reading from the
        Sense HAT is improbable, see here:
        https://www.raspberrypi.org/forums/viewtopic.php?f=104&t=111457
        We need to take CPU temp into account. The Pi foundation recommendeds using the following:
        http://yaab-arduino.blogspot.co.uk/2016/08/accurate-temperature-reading-sensehat.html        
        """
        
        # Get temp readings from both sensors
        humidity_temp = self._sense_hat.get_temperature_from_humidity()
        pressure_temp = self._sense_hat.get_temperature_from_pressure()
        
        # avg_temp becomes the average of the temperatures from both sensors
        # We need to check for pressure_temp value is not 0, to not ruin avg_temp calculation
        avg_temp = (humidity_temp + pressure_temp) / 2 if pressure_temp else humidity_temp
        
        # Get the CPU temperature
        cpu_temp = self._get_cpu_temp()
        
        # Calculate temperature compensating for CPU heating
        adj_temp = avg_temp - (cpu_temp - avg_temp) / 1.5
        
        # Average out value across the last three readings
        return self._get_smooth(adj_temp)

    def get_humidity(self):
        """Gets humidity sensor value."""
        return self._sense_hat.get_humidity()

    def get_pressure(self):
        """Gets humidity sensor value and converts pressure from millibars to inHg before posting."""
        return self._sense_hat.get_pressure() * 0.0295300
    
    def get_sensors_data(self):
        """Returns sensors data tuple."""

        temp_in_celsius = self.get_temperature()

        return (
            round(temp_in_celsius, 1), 
            round(self.to_fahrenheit(temp_in_celsius), 1), 
            round(self.get_humidity(), 0), 
            round(self.get_pressure(), 1)
        )    

    def _change_weather_entity(self, event):
        """Internal. Switches to next/previous weather entity or next/previous visual style."""
        
        # We need to handle release event state
        if event.action == ACTION_RELEASED:
            self._sense_hat.clear()

            if event.direction == DIRECTION_UP:
                next_entity = self.next_item
                self._show_message(next_entity.entity_messsage, next_entity.positive_color)
            elif event.direction == DIRECTION_DOWN:
                previous_entity = self.previous_item
                self._show_message(previous_entity.entity_messsage, previous_entity.positive_color)
            elif event.direction == DIRECTION_LEFT:
                self.current_item.previous_item
            else:
                self.current_item.next_item

            self._update_display(loop=False)

    def _show_message(self, message, message_color, background_color=(0, 0, 0)):
        """Internal. Shows message by scrolling it over HAT screen."""

        # Need to be sure we revert any changes to rotation
        self._sense_hat.rotation = 0
        self._sense_hat.show_message(message, Config.SCROLL_TEXT_SPEED, message_color, background_color)
    
    def _log_results(self, first_time=False):
        """Internal. Continuously logs sensors values."""

        if not first_time:
            print(self.READINGS_PRINT_TEMPLATE % self.get_sensors_data())

        self._log_timer = self._start_timer(Config.LOG_INTERVAL, self._log_results)

    def _update_display(self, loop=True):
        """Internal. Continuously updates screen with new sensors values."""

        sensors_data = self.get_sensors_data()

        if self.current_item.entity_type is WeatherEntityType.TEMPERATURE:
            pixels = self.current_item.show_pixels(sensors_data[0])
        elif self.current_item.entity_type is WeatherEntityType.HUMIDITY:
            pixels = self.current_item.show_pixels(sensors_data[2])
        else:
            pixels = self.current_item.show_pixels(sensors_data[3])

        self._sense_hat.set_rotation(self.current_style.rotation)
        self._sense_hat.set_pixels(pixels)

        if loop:
            self._update_timer = self._start_timer(Config.UPDATE_INTERVAL, self._update_display)

    def _upload_results(self, first_time=False):
        """Internal. Continuously uploads new sensors values to Weather Underground."""

        if not first_time:
            print('Uploading data to Weather Underground')
            sensors_data = self.get_sensors_data()

            # Build a weather data object http://wiki.wunderground.com/index.php/PWS_-_Upload_Protocol
            weather_data = {
                'action': 'updateraw',
                'ID': Config.STATION_ID,
                'PASSWORD': Config.STATION_KEY,
                'dateutc': 'now',
                'tempf': str(sensors_data[1]),
                'humidity': str(sensors_data[2]),
                'baromin': str(sensors_data[3]),
                'dewptf': str(self.to_fahrenheit(self.calculate_dew_point(sensors_data[0], sensors_data[2])))
            }

            try:
                upload_url = Config.WU_URL + '?' + urlencode(weather_data)
                response = urllib2.urlopen(upload_url)
                html = response.read()
                print('Server response: ', html)
                
                # Close response object
                response.close()
            except:
                print('Could not upload to Weather Underground')
                logging.warning('Could not upload to Weather Underground', exc_info=True)

        self._upload_timer = self._start_timer(Config.UPLOAD_INTERVAL, self._upload_results)

    def _start_timer(self, interval, callback):
        """Internal. Starts timer with given interval and callback function."""
        
        timer = Timer(interval, callback)
        timer.daemon = True
        timer.start()

        return timer

    def _get_cpu_temp(self):
        """"
        Internal.
        Executes a command at the OS to pull in the CPU temperature.
        Thanks to https://www.raspberrypi.org/forums/viewtopic.php?f=104&t=111457
        """
        
        res = os.popen('vcgencmd measure_temp').readline()
        return float(res.replace('temp=', '').replace("'C\n", ''))

    def _get_smooth(self, value):
        """Moving average to smooth reading."""
        
        # We use deque here as it is more efficient for in/out behaviour than regular list/tuple
        if not self._last_readings:
            self._last_readings = deque((value, ) * self.SMOOTH_READINGS_NUMBER, self.SMOOTH_READINGS_NUMBER)
        else:
            self._last_readings.appendleft(value)
            
        # Average last temperature readings
        return sum(self._last_readings) / self.SMOOTH_READINGS_NUMBER
BUCKET_NAME = ":partly_sunny: " + CITY + " Weather"
BUCKET_KEY = "sensehat"
ACCESS_KEY = "Your_Access_Key"
SENSOR_LOCATION_NAME = "Office"
MINUTES_BETWEEN_SENSEHAT_READS = 0.1
# ---------------------------------

streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY)
  
sense = SenseHat()  
  
while True:
  # Read the sensors
  temp_c = sense.get_temperature()
  humidity = sense.get_humidity() 
  pressure_mb = sense.get_pressure() 

  # Format the data
  temp_f = temp_c * 9.0 / 5.0 + 32.0
  temp_f = float("{0:.2f}".format(temp_f))
  humidity = float("{0:.2f}".format(humidity))
  pressure_in = 0.03937008*(pressure_mb)
  pressure_in = float("{0:.2f}".format(pressure_in))

  # 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)
Example #60
0
from sense_hat import SenseHat

sense = SenseHat()
# print("Temperature (C): ", round(sense.get_temperature(), 2))
print("{0:<18} {1}".format("Temperature (C):", round(sense.get_temperature(),
                                                     2)))

print("{0:<18} {1}".format("Pressure (?):", round(sense.get_pressure(), 2)))
print("{0:<18} {1}".format("Humidity (%):", round(sense.get_humidity(), 2)))
# print("Pressure: ", round(sense.get_pressure(), 2))
# print("Humidity (%):", round(sense.get_humidity(), 2))