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
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'
Beispiel #4
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()
Beispiel #5
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") 
Beispiel #8
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()))
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()
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() 
Beispiel #12
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)
Beispiel #13
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
Beispiel #14
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
Beispiel #15
0
	def do_GET(self):
		self.send_response(200)
		self.send_header('Content-type','text/html')
		self.end_headers()
		# Send the html message

		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

	        #data = {}
		#data['key'] = 'value'
	        #json_data = json.dumps(data)

		self.wfile.write(temp_f)
	        return
Beispiel #16
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
Beispiel #17
0
from sense_hat import SenseHat
from time import sleep

sense = SenseHat()

INTERVAL = 3

while True:
    temp = round(sense.get_temperature(), 2)
    hum = round(sense.get_humidity(), 2)
    pres = round(sense.get_pressure(), 2)
    print(temp)
    sleep(INTERVAL)
Beispiel #18
0
    "auth-key": "a-sr7gke-peofyfalld",
    "auth-token": "0EhF(z4xL9NwlxchVh",
    "port": 8883,
    "keepalive": 60,
}

myClient = ibmiotf.application.Client(options)

myClient.connect()

while True:
    humidity = sense.get_humidity()
    pressure = sense.get_pressure()

    myData = {
        "Temperature": sense.get_temperature(),
        "Humidity": humidity,
        "Pressure": pressure
    }
    print(myData)

    myClient.publishEvent("SensorHome", "D001", "PreTemHu", "json", myData)

    for event in sense.stick.get_events():
        joyStickEventData = {
            "Direction": event.direction,
            "Action": event.action
        }
        print(joyStickEventData)
        myClient.publishEvent("SensorHome", "D002", "joyStickEvent", "json",
                              joyStickEventData)
Beispiel #19
0
#!/usr/bin/env python2.7

from sense_hat import SenseHat
sense = SenseHat()
sense.clear()
print 'Press Ctrl-C to quit.'

    tempc = sense.get_temperature()
    tempc = round(tempc, 1)
    temp = sense.get_temperature()
    temp = round(temp, 1)
    temp = ((temp / 5) * 9) + 32  # Convert to Farhenheit
    humidity = sense.get_humidity()
    humidity = round(humidity, 1)
    pressure = sense.get_pressure()
    pressure = round(pressure, 1)

    TD = 243.04 * (math.log(humidity / 100) + ((17.625 * tempc) / (243.04 + tempc))) / (
    17.625 - math.log(humidity / 100) - ((17.625 * tempc) / (243.04 + tempc)))
    TD = round(TD, 1)
    
    print "Temp (F): ", temp
    print "Humidity: ", humidity
    print "DewPoint: ", TD
    print "Pressure: ", pressure, "\n"
    time.sleep(2)
Beispiel #20
0
#Same thing what we did for hour is what we will do for minute 
for index in range(0, 4):
    clockImage.extend(numberDisplay[int(minute/10)][index])
    clockImage.extend(numberDisplay[int(minute%10)][index])
    
#Now we have our final 'for' loop the entire clockImage array, this loop is designed to swap 
#out of every number with our RGB values. We achieve this by just checking whether
#there is a number 0 or 1 inside that index. If it’s 0 we output our empty variable value
#to that number. Otherwise, we check to see if we are dealing with the first 32 pixels 
#(which is the top half of the LED matrix), if we are in the top half we grab the RGB values 
#from our hourColor variable. Otherwise, we utilize the RGB values from the minuteColor variable.

for index in range(0, 64):
    if (clockImage[index]):
        if index < 32:
            clockImage[index] = hourHandColor
        else:
            clockImage[index] = minuteHandColor
    else:
        clockImage[index] = emptyColor

#In a While Loop what is being continued till we manuelly exit it. 

while True:
  sense.set_rotation(270) #the rotation for sensehat display
  temp = sense.get_temperature() #obtaining the temperature # from the sensor
  temp = round(((temp/5)*9)+32) #rounding and converting the celcius to fehrenheit
  sense.show_message("%.1f F" % temp) #Display a message on the sensehat to show temperature (%.1f)
  sense.set_pixels(clockImage) #calling in the clockImage to display the result.
  sleep(10) #Calling in to sleep or what you call a delay for 10 sec.
Beispiel #21
0
def getData():
    time = datetime.now().strftime("%H:%M:%S")
    sense = SenseHat()
    temp = round(sense.get_temperature(), 1)
    return time, temp
from time import sleep
import socket
sense = SenseHat()
sense.clear()

def setup_udp_socket():
    # Setup UDP socket for broadcasting
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

    # Set a timeout so the socket does not block
    # indefinitely when trying to receive data.
    s.settimeout(0.2)

    #socket.bind(("", 44444))
    return s

s = setup_udp_socket()


while True:
    bg = (0,0,0)
    temp = str(sense.get_temperature())

    # Broadcast byte encoded message to port 37020 via UDP Socket
    # .encode() converts message to bytes for udp to broadcast
    s.sendto(temp.encode(), ('<broadcast>', 19993))

    sense.show_message(temp, scroll_speed=0.05, back_colour=bg)
    sleep(1)
client.tls_set(
    ca_certs=root_cert_filepath
)  # Replace this with 3rd party cert if that was used when creating registry
client.connect('mqtt.googleapis.com', 8883)
client.loop_start()

# Could set this granularity to whatever we want based on device, monitoring needs, etc
temperature = 0
humidity = 0
pressure = 0

sense = SenseHat()

for i in range(1, 11):
    cur_temp = sense.get_temperature()
    cur_pressure = sense.get_pressure()
    cur_humidity = sense.get_humidity()

    if cur_temp == temperature and cur_humidity == humidity and cur_pressure == pressure:
        time.sleep(1)
        continue

    temperature = cur_temp
    pressure = cur_pressure
    humidity = cur_humidity

    payload = '{{ "ts": {}, "temperature": {}, "pressure": {}, "humidity": {} }}'.format(
        int(time.time()), temperature, pressure, humidity)

    # Uncomment following line when ready to publish
Beispiel #24
0
class senseHAT:
    def __init__(self):
        self.sense = SenseHat()
        self.red = (255, 0 , 0)
        self.green = (0, 255, 0)
        self.blue = (0, 0, 255)
        self.lightGreen = (70, 255, 102)
        self.black = (0, 0, 0)
        self.white = (255, 255, 255)
    
    # Display a message using user input with orange text & black background
    def displayText(self):
        textColor = (253, 95, 0)
        message = input('Enter a message to display: ')

        self.sense.show_message(message, text_colour = textColor, back_colour = self.black)

    # Given any word, this method will display each char every x seconds in red
    def displayChars(self, word, x):
        for letter in word:
            self.sense.show_letter(letter, text_colour = self.red)
            sleep(x)
    
    # Lights the entire board light green
    def makeOneColor(self):
        self.sense.clear(self.lightGreen)
    
    # Makes a happy face by setting individual pixels
    def onePixel(self):
        self.sense.set_pixel(2, 2, self.blue)
        self.sense.set_pixel(4, 2, self.blue)
        self.sense.set_pixel(3, 4, self.lightGreen)
        self.sense.set_pixel(1, 5, self.red)
        self.sense.set_pixel(2, 6, self.red)
        self.sense.set_pixel(3, 6, self.red)
        self.sense.set_pixel(4, 6, self.red)
        self.sense.set_pixel(5, 5, self.red)

    # Lights up entire LED Board based on list
    def manyPixels(self):
        matrix = []

        # Appends black or white into matrix based on number value
        while len(matrix) < 64:
            randNum = randint(0, 1)

            if randNum == 0:
                matrix.append(self.black)
            
            matrix.append(self.white)
        
        self.sense.set_pixels(matrix)
    
    # Given an orientation, LED Matrix will either be flipped horizontally, vertically, or rotated
    def setOrientation(self, option):
        w = (150, 150, 150)
        e = self.white
        b = self.blue
        option = option.lower()

        image = [
            e,e,e,e,e,e,e,e,
            e,e,e,e,e,e,e,e,
            w,w,w,e,e,w,w,w,
            w,w,b,e,e,w,w,b,
            w,w,w,e,e,w,w,w,
            e,e,e,e,e,e,e,e,
            e,e,e,e,e,e,e,e,
            e,e,e,e,e,e,e,e
        ]

        if option == 'horizontal':
                self.sense.flip_h(image)
        elif option == 'vertical':
                self.sense.flip_v(image)
        elif option == 'rotate':
            rotation = int(input('Enter degrees to rotate: '))
            self.sense.set_rotation(rotation)
        else:
            self.sense.set_pixels(image)

    # Output environment details to LED Matrix
    def getEnvironment(self):
        # get_temperature() returns celsius... convert this to farenheit
        temp = round(self.sense.get_temperature() * 1.8 + 32, 2)
        humidty = round(self.sense.get_humidity(), 2)
        pressure = round(self.sense.get_pressure(), 2)

        tempMessage = "Temperature: " + str(temp) + "F"
        humidtyMessage = "Humidity: " + str(humidty) + "%"
        pressureMessage = "Pressue: " + str(pressure) + "millibars"

        self.sense.show_message(tempMessage)
        sleep(1)
        self.sense.show_message(humidtyMessage)
        sleep(1)
        self.sense.show_message(pressureMessage)
        sleep(1)

        # Will water freeze right now?
        if temp <= 32:
            self.sense.show_message('Water will freeze at current temp')
        else:
            self.sense.show_message('Water will not freeze right now')
    
    # Detecting Movement using IMU
    def detectMovement(self):
        while True:
            acceleration = self.sense.get_accelerometer_raw()

            x = acceleration['x']
            y = acceleration['y']
            z = acceleration['z']

            x = abs(x)
            y = abs(y)
            z = abs(z)

            if x > 1 or y > 1 or z > 1:
                self.sense.show_letter('!', self.red)
            else:
                self.sense.clear()
                

    # Using the joystick
    def joystick(self):
        choice = input(
            'Enter the key of what you want to do: \n 1 - Show on terminal directions \n 2 - Show on LED Matrix \n '
        )

        if choice == '1':
            while True:
                for event in self.sense.stick.get_events():
                    print(event.direction, event.action)
        elif choice == '2':
            e = self.black
            w = self.white

            self.sense.clear()
            while True:
                for event in self.sense.stick.get_events():
                    if event.action == 'pressed':

                        if event.direction == 'up':
                            self.sense.show_letter('U')
                        elif event.direction == 'down':
                            self.sense.show_letter('D')
                        elif event.direction == 'left':
                            self.sense.show_letter('L')
                        elif event.direction == 'right':
                            self.sense.show_letter('R')
                        elif event.direction == 'middle':
                            self.sense.show_letter('M')
                        
                        sleep(0.5)
                        self.sense.clear()
Beispiel #25
0
from sense_hat import SenseHat
import time
from datetime import datetime
from gpiozero import CPUTemperature


sense = SenseHat()

sense.set_rotation(180)

while True:
    cpu = CPUTemperature().temperature
    thermo = sense.get_temperature()
    temp = thermo-((cpu-thermo)/3)
    humidity = sense.get_humidity()
    pressure = sense.get_pressure()
    if (cpu>70):
        sense.show_message("CPU TEMPERATURE CRITICAL %cpu C" % temp, scroll_speed=0.06, text_colour=[255, 0, 0])        
    sense.show_message("%.0f C" % temp, scroll_speed=0.06, text_colour=[100, 0, 0])
    sense.show_message("%.0f %%rH" % humidity, scroll_speed=0.06, text_colour=[10, 10, 100])
    sense.show_message("%.1f hPa" % pressure, scroll_speed=0.06, text_colour=[0, 100, 0])
    sense.show_message(datetime.now().strftime('%d/%m %H:%M'), scroll_speed=0.06, text_colour= [100,100,100])
Beispiel #26
0
    r = requests.get(
        'http://api.openweathermap.org/data/2.5/weather?zip=94085,us&APPID=3cf4cd87d12e4025c0636ed5097aef1e&units=imperial'
    )
    response = r.json()

    cloud = response['clouds']['all']
    temp = response['main']['temp']
    sunrise = datetime.datetime.fromtimestamp(response['sys']['sunrise'])
    sunset = datetime.datetime.fromtimestamp(response['sys']['sunset'])
    visibility = response['visibility']

    currentTime = datetime.datetime.now()

    selectedTint = 1
    if use_local_temp:
        temp = sense.get_temperature() * 1.8 + 32

    #print "Current time " + str(currentTime.time())
    #print "Cloud cover : " + str(cloud)
    #print "Temp :" + str(temp)
    #print "Sunrise : " + str(sunrise)
    #print "Sunset  : " + str(sunset)
    #print "Visibility: " + str(visibility)

    if (currentTime.time().hour < (sunrise.hour - morn_even_offset)):
        print "Clearing glass for morning"
        selectedTint = 1

    elif (currentTime.time().hour > (sunset.hour + morn_even_offset)):
        print "Clearing glass post sunset"
        selectedTint = 1
	    # print('command on')
            global currBgColor
	    currBgColor="red"
	    sense.set_pixels(getPixelMap("red", sense.get_temperature()))
            pass
        elif command == "off":
            # TODO insert your code herei
	    # print('command off')
            global currBgColor
	    currBgColor="green"
	    sense.set_pixels(getPixelMap("green", sense.get_temperature()))
            pass

try:
    gatewayOptions = {"org": "xnf2sg", "type": "raspiGateway", "id": "rpi123", "auth-method": "token", "auth-token": "password"}
    gatewayCli = ibmiotf.gateway.Client(gatewayOptions)

    gatewayCli.connect()
    gatewayCli.deviceCommandCallback = myCommandCallback 
    gatewayCli.subscribeToDeviceCommands(deviceType='raspiGateway', deviceId='rpi123', command='display',format='json',qos=2)

    while True:
        temp = sense.get_temperature() # TODO insert your code here
        myData = {"d": { "temperature" : temp} } # TODO insert your code here
	sense.set_pixels(getPixelMap(currBgColor, sense.get_temperature()))
        gatewayCli.publishDeviceEvent("senseHAT", "senrpi123", "Event", "json", myData, qos=1 )
        time.sleep(2)

except ibmiotf.ConnectionException  as e:
    print(e)
class GyroClear(object):
    #Initialize class variables here
    b = (255, 255, 0)  # background - gold
    f = (0, 0, 255)  # foreground - blue
    c = (0, 0, 0)  # clear
    e = (0, 255, 0)  # eraser colour (green)
    a = [
        b,
        b,
        b,
        f,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        f,
        b,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        f,
        f,
        f,
        f,
        f,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
    ]
    s = [
        b,
        b,
        f,
        f,
        f,
        f,
        b,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        f,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        f,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        b,
        f,
        f,
        f,
        f,
        b,
        b,
    ]
    p = [
        b,
        f,
        f,
        f,
        f,
        f,
        b,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        f,
        f,
        f,
        f,
        f,
        b,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
        b,
        f,
        b,
        b,
        b,
        b,
        b,
        b,
    ]

    def __init__(self):
        super(GyroClear, self).__init__()
        self.__sense = SenseHat()
        self.__eraser_row = 0
        self.__eraser_col = 0
        self.__letters = [GyroClear.a, GyroClear.s, GyroClear.p]
        self.__current_letter = 0
        self.__current_state = self.__letters[self.__current_letter]

    def count_letter_blocks(self):
        """ Return number of letter blocks in the current letter
        
        It counts the number of elements that don't match the background
        colour. The current letter is stored in self.__current_state].
        """

        count = 0
        for e in self.__current_state:
            if e != GyroClear.b:
                count += 1
        print('Count is {0}'.format(count))
        return count

    def show_letter(self, letter):
        self.__sense.show_letter(letter)
        time.sleep(2)

    def clear_display(self):
        self.__sense.clear()

    def display_letters(self):
        for letter in range(len(self.__letters)):
            self.__sense.set_pixels(self.__letters[letter])
            time.sleep(2)

    def display_current_board(self):
        self.__sense.set_pixels(self.__current_state)

    def display_current_readings(self):
        temp = self.__sense.get_temperature()
        self.__sense.show_message("Th: ")
        self.__sense.show_message(str(int(temp)))
        temp = self.__sense.get_temperature_from_pressure()
        self.__sense.show_message("Tp: ")
        self.__sense.show_message(str(int(temp)))
        pressure = self.__sense.get_pressure()
        self.__sense.show_message("P: ")
        self.__sense.show_message(str(int(pressure)))
        humidity = self.__sense.get_humidity()
        self.__sense.show_message("H: ")
        self.__sense.show_message(str(int(humidity)))

    def next_letter(self):
        """ Move the game to the next level

        Returns False when there are no move letters.
        """
        next_level = True

        if self.__current_letter >= (len(self.__letters) - 1):
            next_level = False
        else:
            self.__current_letter += 1
            self.__current_state = self.__letters[self.__current_letter]

        return next_level

    def getArrayIndex(self, x, y):
        """ Return index in list relative to logical 8x8 matrix """
        index = y * 8 + x
        print('Index: {0}'.format(index))
        return index

    def move_eraser(self):
        """ Move the eraser based on pitch and roll from the Gyro

        This is the brains of the game. It using values from the Gyro to move
        the eraser around the board. If it finds a block that is not the
        background colour, then appropriate updates are made.

        Return True of a block was erased.
        """

        block_erased = False
        old_x = self.__eraser_row
        old_y = self.__eraser_col
        pitch = self.__sense.get_orientation()['pitch']
        roll = self.__sense.get_orientation()['roll']

        if 1 < pitch < 179 and self.__eraser_row != 0:
            self.__eraser_row -= 1
        elif 359 > pitch > 179 and self.__eraser_row != 7:
            self.__eraser_row += 1
        if 1 < roll < 179 and self.__eraser_col != 7:
            self.__eraser_col += 1
        elif 359 > roll > 179 and self.__eraser_col != 0:
            self.__eraser_col -= 1

        old_index = self.getArrayIndex(old_x, old_y)
        print('old_index is {0} from {1},{2}'.format(old_index, old_x, old_y))
        new_index = self.getArrayIndex(self.__eraser_row, self.__eraser_col)
        print('new_index is {0} from {1},{2}'.format(new_index,
                                                     self.__eraser_row,
                                                     self.__eraser_col))
        # If new index is not background colour, then we have found a new block
        # to erase.
        if self.__current_state[new_index] != GyroClear.b:
            block_erased = True
            # Update current state to make this index background colour.
            self.__current_state[new_index] = GyroClear.b

        # Update the pixels on the sense hat display
        self.__sense.set_pixel(old_x, old_y, GyroClear.b)
        self.__sense.set_pixel(self.__eraser_row, self.__eraser_col,
                               GyroClear.e)

        return block_erased

    def play_game(self):
        have_level = True
        while have_level:
            self.display_current_board()
            count = game.count_letter_blocks()
            while count > 0:
                erased = self.move_eraser()
                if erased:
                    count -= 1
                time.sleep(0.25)
                print('count is {0}'.format(count))
            have_level = self.next_letter()
        self.__sense.show_message('Enter secret message here',
                                  text_colour=GyroClear.f,
                                  back_colour=GyroClear.b)
#firebase
cred = credentials.Certificate(
    "../config/labo-i-firebase-adminsdk-nr652-7d2e873b71.json")
firebase_admin.initialize_app(cred)

#connect firestore
db = firestore.client()

#sensehat

sense = SenseHat()

sense.set_imu_config(False, False, False)

sense.clear()

while True:
    waarden = {
        u'pressure': sense.get_pressure(),
        u'temperature': sense.get_temperature()
    }

    db.collection(COLLECTION).document(DOCUMENT).set(waarden)
    cTime = datetime.now()
    print('[{0}] Updated firestore with current environment values!'.format(
        cTime))
    # repeat every 2 minutes

    time.sleep(120)
Beispiel #30
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]
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)
class TempSensorAdaptor(object):
    '''
    classdocs
    '''
    rateInSec = 10.0
    alertDiff = 10.0
    curDegree = 0.0
    nominalTemp = 10.0
    sense=None

    '''
    Initial all the variable I need
    '''
    def __init__(self, a, r):
        '''
        Constructor
        '''
        self.sense = SenseHat()
        self.tempActuatorEmulator = TempActuatorEmulator()
        self.alertDiff = a
        self.rateInSec = r
        self.sensorData = SensorData
        self.connector = SmtpClientConnector()
        self.config = ConfigUtil('../../../config/ConnectedDevicesConfig.props')
        self.config.loadConfig()
        self.nominalTemp = self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE, 'nominalTemp')
#         self.nominalTemp = self.config.getProperty()
        _thread.start_new_thread(self.run())
    
    '''
    Connect to senseHat and obtain the environment temperature.
    '''
    def readTempFromSH(self):
        self.sense.clear()
        self.curDegree = self.sense.get_temperature()
    
    '''
    Store the temperature into SenseData.
    '''
    def addTempToSensorData(self):
        self.sensorData.addValue(self.sensorData, self.curDegree)
        now = datetime.datetime.now()
        print(str(now) + "\t" + str(self.curDegree))
        print(str(now) + "\t" + str(self.sensorData.getAvgValue(self.sensorData)))
        print("\n")
    
    '''
    Determine whether or not the particular temperature is higher or lower than the average temperature and then alert the user by sending email.
    '''
    def alert(self):
        if (abs(self.sensorData.getValue(self.sensorData) - self.sensorData.getAvgValue(self.sensorData)) >= self.alertDiff):
            # Start to send email
            logging.info('\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')
            print("Starting sending email...")
            output = self.sensorData.__str__(self.sensorData)
            self.connector.publishMessage("Excessive Temp", output)
    
    '''
    Determine whether or not the new temperature value is higher or lower than the nominal temperature which is set in ConnectedDevicesConfig
    '''
    def adjust(self):
        if self.sensorData.getValue(self.sensorData) < float(self.nominalTemp) or self.sensorData.getValue(self.sensorData) > float(self.nominalTemp):
            self.actuatorData = ActuatorData()
            self.actuatorData.updateData(1, 1, 0, "adjust", self.sensorData.getValue(self.sensorData))
            self.tempActuatorEmulator.processMessage(self.actuatorData)
    
    '''
    Start a new thread to do the task.
    '''
    def run(self):
        while True:
            self.readTempFromSH()
            self.addTempToSensorData()
            self.alert()
            self.adjust()
            sleep(self.rateInSec)
# File: 06_environment.py
# Author: Raphael Holzer
# Date: 26. 11. 2018

from sense_hat import SenseHat

sense = SenseHat()
red = (255, 0, 0)
blue = (0, 0, 255)

h = int(sense.get_humidity())
t = int(sense.get_temperature())
p = int(sense.get_pressure())

print('humidity =', h)
print('pressure =', p)
print('temperature =', t)
print('temp from pressure =', sense.get_temperature_from_pressure())
print('temp from humidity =', sense.get_temperature_from_humidity())

while True:
    sense.show_message('t=' + str(t), text_colour=red)
    sense.show_message('p=' + str(p))
    sense.show_message('h=' + str(h), text_colour=blue)
Beispiel #34
0
class TempSensorAdapterTask(threading.Thread):
    '''
    Threaded Class which reads the temperature data from the SenseHAT.
    Stores the data in the SensorData class.
    '''
    LOOP_FOREVER = False
    enableCoAP   = False
    threadStop   = False

    def __init__(self, loop_param, sleep_param, pUtil: PersistenceUtil.PersistenceUtil,coAPClient: CoAPClientConnector.CoAPClientConnector):
        '''
        Constructor
        '''
        #Init asyncio event loop
        self.loop = asyncio.new_event_loop()

        #Init the threadx
        threading.Thread.__init__(self, args=(self.loop,))

        self.loop_limit     = loop_param
        self.sleep_time     = sleep_param

        #Creating a SensorData instance and setting it's name
        self.sensorData = SensorData.SensorData()
        self.sensorData.setName("Temperature Sensor Data")

        #SenseHat instance to interact with the senseHAT
        self.sense = SenseHat()

        #clearing matrix
        self.sense.clear()

        #MQTT client
        self.coAP = coAPClient

        #PersistenceUtil
        self.pUtil = pUtil

    def run(self):
        '''
        Method to read new data from the senseHat.
        Data is then pushed to the SensorData instance
        '''
        i = 0
        
        while i < self.loop_limit or self.LOOP_FOREVER == True:
            i = i+1
            
            #break and kill thread if activated
            if self.threadStop:
                break

            #Read from senseHAT     
            humData = self.sense.get_temperature()

            #Add data to sensorData
            self.sensorData.addValue(humData)
            humString = self.generateString()

            if self.enableCoAP:
                #publish data to the MQTT topic
                self.coAP.sendSensorDataPUT(self.loop, self.sensorData)

            #Passing the Json on redis
            self.pUtil.writeSensorDataDbmsListener(self.sensorData)

            #Log the data and send the sensorData instance in the SensorDataManager
            logging.info(humString) 
            sleep(self.sleep_time)      

        return True 

    def stop(self) -> bool:
        logging.info("Quitting Thread")
        self.threadStop = True
        return True
        
    def generateString(self) -> str:
        '''
        Generate a detailed string from a sensorData instance and returns it.
        '''
        msgString  = "\nHumidity from the sense_HAT API:"
        msgString += "\n\tTime : " + self.sensorData.timestamp
        msgString += "\n\tCurrent : " + repr(self.sensorData.getCurrentValue())
        msgString += "\n\tAverage : " + repr(self.sensorData.getAverageValue())
        msgString += "\n\tSamples : " + repr(self.sensorData.getCount())
        return msgString

        
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)
Beispiel #36
0
from sense_hat import SenseHat

hat = SenseHat()
hat_temp = hat.get_temperature()

converted_temp = (hat_temp * 1.8) + 32

print(
    "The sense hat says that it is currently {} celsius which is also {} fahrenheit"
    .format(hat_temp, converted_temp))

hat.show_message(str(converted_temp),
                 text_colour=[255, 255, 0],
                 back_colour=[139, 0, 139])
hat.clear()
from sense_hat import SenseHat

sense = SenseHat()
sense.clear()

temp = sense.get_temperature()
print(temp)

Beispiel #38
0
    membar.max = 100.0

    yawbar = HatBar(2, sense, [64, 64, 64])
    rollbar = HatBar(3, sense, [64, 64, 64])
    pitchbar = HatBar(4, sense, [64, 64, 64])

    tempbar = HatBar(5, sense, [128, 128, 0])
    humbar = HatBar(6, sense, [64, 0, 64])
    prbar = HatBar(7, sense, [0, 128, 128])

    while(True):
        cpubar.draw(getCPU())
        membar.draw(getRAM())

        orientation = sense.get_gyroscope()

        yawbar.draw(orientation['yaw'])
        rollbar.draw(orientation['roll'])
        pitchbar.draw(orientation['pitch'])

        tempbar.draw(sense.get_temperature())
        humbar.draw(sense.get_pressure())
        prbar.draw(sense.get_humidity())

        print(cpubar.curr, membar.curr, tempbar.curr, humbar.curr, prbar.curr, sep="|")

        # Print the actual values to stdout
        # print(cpubar.curr, membar.curr, sep="|")

        # Wait
        time.sleep(.25)
Beispiel #39
0
# Connect to the broker over MQTT port
client.username_pw_set("admin", "admin")
<<<<<<< HEAD
client.connect("192.168.98.75", port=1883, keepalive=60)
=======
client.connect("192.168.99.75", port=1883, keepalive=60)
>>>>>>> e914ad557f5cd8f96de952634208e3e46b22d12e
client.loop_start() # Keep the connection open


# Publish a message to the "Capstone" topic
running = True
while running:
<<<<<<< HEAD
	# Get temperature from sensor and convert it to Farenheit
	tempF = format(((sense.get_temperature() * 1.8) + 32 - 20), '.2f')
=======

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

	# Send multiple values as a dictionary
	data = {'Temperature (Farenheit)':tempF}

	# Publish the message to the Capstone topic
<<<<<<< HEAD
	client.publish("MyHome", payload = str(data), qos=0)
	time.sleep(10)
#connect to database file
dbconnect = sqlite3.connect("mydatabase.db")
#If we want to access columns by name we need to set
#row_factory to sqlite3.Row class
dbconnect.row_factory = sqlite3.Row
#now we create a cursor to work with db
cursor = dbconnect.cursor()

#Create 'temps' table if not existing
cursor.execute(
    '''CREATE TABLE IF NOT EXISTS temps (tdate DATE, ttime TIME, zone TEXT, temperature NUMERIC);'''
)
dbconnect.commit()
todayDate = str(datetime.today().strftime('%Y-%m-%d'))  #get today's date
nowTime = str(datetime.now().time().strftime('%H:%M:%S'))  #get now time
temperature = round(sense.get_temperature())  #get temperature from SENSE HAT
rooms = ['kitchen', 'greenhouse', 'garage']  #some rooms to use
for i in range(9):
    #execute insert statement
    cursor.execute('''insert into temps values (?, ?, ?, ?)''',
                   (todayDate, nowTime, rooms[i % 3], temperature))
dbconnect.commit()

#Create new 'sensor' table if not existing
cursor.execute(
    '''CREATE TABLE IF NOT EXISTS sensors (sensorID NUMERIC, type TEXT, zone TEXT);'''
)
dbconnect.commit()
#execute insert statement
cursor.execute('''insert into sensors values (1, 'door', 'kitchen')''')
cursor.execute('''insert into sensors values (2, 'temperature', 'kitchen')''')
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)
Beispiel #42
0
 def getTempValue(self):
     sense = SenseHat()
     temp = sense.get_temperature()
     return str(temp)
Beispiel #43
0
    # set the rotation
    sh.set_rotation(rot)


# create a datetime variable to store the start time
start_time = datetime.datetime.now()
# create a datetime variable to store the current time
# (these will be almost the same at the start)
now_time = datetime.datetime.now()
# run a loop for 2 minutes
photo_counter = 1
sh.set_pixels(img1)
while (now_time < start_time + datetime.timedelta(minutes=10)):
    try:
        # Read some data from the Sense Hat, rounded to 4 decimal places
        temperature = round(sh.get_temperature(), 4)
        humidity = round(sh.get_humidity(), 4)

        # get latitude and longitude
        lat, lon = get_latlon()
        # Save the data to the file
        logger.info("%s,%s,%s,%s,%s", photo_counter, humidity, temperature,
                    lat, lon)
        # use zfill to pad the integer value used in filename to 3 digits (e.g. 001, 002...)
        cam.capture(dir_path + "/photo_" + str(photo_counter).zfill(3) +
                    ".jpg")
        photo_counter += 1
        active_status()
        sleep(15)
        active_status()
        sleep(15)
    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üß!')
Beispiel #45
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)

    # pixel display
    def set_pixel(self, x, y, color):
        # red = (255, 0, 0)
        # green = (0, 255, 0)
        # blue = (0, 0, 255)
        self.sense.set_pixel(x, y, color)

    # clear pixel display
    def clear_display(self):
        self.sense.clear()

    # 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': {},
            'location': {}
        }  # add location
        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'
        }

        sensors['location']['lat'] = {
            'value': 0
        }  # initialize these with 0 values to start
        sensors['location']['lon'] = {'value': 0}
        sensors['location']['alt'] = {'value': 0}
        sensors['location']['sats'] = {'value': 0}
        sensors['location']['speed'] = {'value': 0}

        return sensors
Beispiel #46
0
# Shows temp (rounded to nearest degree) on SenseHat LEDs
# Using small 3x5 characters, so we can fit two digits without scrolling
# TBD: we still have 3 lines free on the LED matrix: 
# We could fit a little 'degrees' symbol if digits were shifted down.....

from smallhex import to_dec_chars
from sense_hat import SenseHat
from time import sleep

sense=SenseHat()
sense.set_rotation(180)
sense.low_light = True
while True:
	temp = int( round( sense.get_temperature() ) )
	sense.set_pixels( to_dec_chars( temp ) )
	sleep(5)

Beispiel #47
0
        break

    # Main loop
    try:
        orientation = sh.get_orientation_degrees()
        compass = sh.get_compass()
        compass_raw = sh.get_compass_raw()
        gyro = sh.get_gyroscope()
        gyro_raw = sh.get_gyroscope_raw()
        accelerometer_raw = sh.get_accelerometer_raw()
        camera.capture(debug_capture=True)

        util.add_csv_data(csvfile, (
            now,
            sh.get_humidity(),
            sh.get_temperature(),
            sh.get_temperature_from_humidity(),
            sh.get_temperature_from_pressure(),
            sh.get_pressure(),
            orientation['roll'],
            orientation['pitch'],
            orientation['yaw'],
            compass,
            compass_raw['x'],
            compass_raw['y'],
            compass_raw['z'],
            gyro['roll'],
            gyro['pitch'],
            gyro['yaw'],
            gyro_raw['x'],
            gyro_raw['y'],
Beispiel #48
0
from sense_hat import SenseHat
sense = SenseHat()

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)

    if t > 18.3 and t < 26.7:
        bg = [0, 100, 0]  # green
    else:
        bg = [100, 0, 0]  # red

    msg = "Temperature = {0}, Pressure = {1}, Humidity - {2}".format(t, p, h)
    print(msg)
    sense.show_message(msg, scroll_speed=0.20, back_colour=bg)
    
Beispiel #49
0
class InputModule(AbstractInput):
    """ A sensor support class that measures """
    def __init__(self, input_dev, testing=False):
        super(InputModule, self).__init__(input_dev,
                                          testing=testing,
                                          name=__name__)

        self.sensor = None

        if not testing:
            self.initialize_input()

    def initialize_input(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("Input not set up")
            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
Beispiel #50
0
MQTT_KEEPALIVE_INTERVAL = 30

# Cloud Configuration (Host, Certification file, Private Key)
MQTT_HOST = "aoscy1wztqxzf.iot.ap-southeast-1.amazonaws.com"
CA_ROOT_CERT_FILE = "./root-CA.crt"
THING_CERT_FILE = "./MyCertificate.pem.crt"
THING_PRIVATE_KEY = "./MyPrivate.pem.key"

# MQTT Toppic setting
MQTT_TOPIC1 = "hat/sensors"
MQTT_TOPIC2 = "hat/joystick"
MQTT_TOPIC3 = "hat/magnetometer"

# Sensors Message Form
MQTT_MSG1 = "Temperature: {0:.0f}C, Humidity: {1:0.2f}%, Pressure: {2:.0f}mbar".format(
    sense.get_temperature(), sense.get_humidity(), sense.get_pressure())


# Define callback function for publishing
def on_publish(client, userdata, mid):
    print("A message published successfully!")


# Initiate MQTT Client
mqttc = mqtt.Client()

# Register publish callback function
mqttc.on_publish = on_publish

# Configure TLS Set
mqttc.tls_set(CA_ROOT_CERT_FILE,
 def update_temp(self):
     device_sensor = SenseHat()
     self.device_last_temp = device_sensor.get_temperature()
     self.device_last_time = time.time()
     return self.device_last_temp
sense.clear()
sense.set_pixels(cell)

#Wait until the enter button is pressed on the Sense Hat

wait = input("Press<enter> to continue")

sense.clear(0,0,255)
#Blow now
time.sleep(10)
sense.clear(255,0,0)

#Collect data for the first experiment

humidity_start = round(sense.get_humidity(),2)
temp_start = round(sense.get_temperature(),2)

#Start exercise
sense.clear(255,255,0)
time.sleep(15)

sense.clear(0,0,255)
#Blow now
time.sleep(10)
sense.clear(255,0,0)

humidity_end = round(sense.get_humidity(),2)
temp_end = round(sense.get_temperature(),2)

print("Humidity at the start of the test: %s %%rH" % humidity_start)
print("Temperature: %s C" % temp_start)
from sense_hat import SenseHat
from time import sleep

sense = SenseHat()

while True:
    sleep(5)
    myfile = open('weather.txt', 'a')
    myfile.write(str(sense.get_temperature()))
    myfile.write('\n')
    myfile.close()
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)
Beispiel #55
0
class TempSensorAdaptor(Thread):

    curTemp = 0
    updateTime = 0
    rateInSec = 0
    sensorData = 0
    senseHat = 0
    connector = 0
    alertDiff = 0
    senseHatLed = 0
    actuatorData = 0
    TAE = 0

    def __init__(self):
        Thread.__init__(self)
        self.highVal = 30
        self.lowVal = 0
        self.updateTime = 2
        self.senseHat = SenseHat()
        self.sensorData = SensorData()
        self.actuatorData = ActuatorData()
        self.connector = Connector()
        self.alertDiff = 10
        
        
        self.config = ConfigUtil('D:/git/repository/iot-device/apps/data/ConnectedDevicesConfig.props')
        self.config.loadConfig()
        print('Configuration data...\n' + str(self.config))

    def getCurrValue(self):

        return self.currValue

    def setEnableTempEmulator(self, flag):
        self.enableTempEmulator = flag

    def run(self):
        while True:
            TAE = TempActuatorEmulator()
            TAE.start()
            self.curTemp = self.senseHat.get_temperature()
            self.sensorData.addValue(self.curTemp)
            print('\n--------------------')
            print('New sensor readings: \n')
            print(' ' + str(self.sensorData))
            
            print('New actuator readings: \n')
            print(' ' + str(self.actuatorData))

            if (abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))) > self.alertDiff):
                print('\n Current temp exceeds average by > ' + str(self.alertDiff) + '. Triggering alert...')
                try:
                    self.connector.publishMessage('Exceptional sensor data [test]', self.sensorData)
                except Exception as e:
                    print("Failed to send email\n" + str(e))
                    
                print('\n Actuator activating...')
                if (self.curTemp > float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))):
                    self.actuatorData.addValue(1, abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))))
                else:
                    self.actuatorData.addValue(2, abs(self.curTemp - float(self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY))))
            
            
                
                # LED Display
                #self.senseHatLed.displayMsg(abs(self.curTemp - self.config.getProperty(ConfigConst.CONSTRAINED_DEVICE,ConfigConst.TEMP_KEY)))
               
                
            else:
                self.actuatorData.addValue(0, 0)
            
        self.enableTempEmulator.updateData(self.actuatorData)    
        sleep(self.updateTime)
Beispiel #56
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

import os, csv, time

from sense_hat import SenseHat

sense = SenseHat()

# read sensor data
hum_temp ="{:.3f}".format(sense.get_temperature())
#sense.show_message("H:%s" % hum_temp)

pres_temp = "{:.3f}".format(sense.get_temperature_from_pressure())
#sense.show_message("P:%s" % pres_temp)

# save temp values into csv file
 
filePath =os.path.dirname(os.path.abspath(__file__))+ "/tempValues.csv"
print filePath

try:	
	f = open(filePath, "a")
	writer = csv.writer(f)

	# Check if file is empty and needs headline
	if os.path.getsize(filePath) == 0:
		print "File was empty, create header:"
		headLine = ["Time","Temp from Hum-Sensor", "Temp from Preas-Sensor"]
		print headLine
		writer.writerow(headLine)
Beispiel #57
0
# hello.py

from time import sleep
from sense_hat import SenseHat
sense = SenseHat()

sense.set_rotation(0)

sense.show_message("Hello, world!",scroll_speed=0.05, text_colour=[255,255,50], back_colour=[0,0,50])
sleep(2)
sense.clear()

sense.set_pixel(0,0,[255,0,0])
sense.set_pixel(0,1,[0,255,0])
sleep(2)
sense.clear()

t=sense.get_temperature() # celcius
p=sense.get_pressure() # millibars
h=sense.get_humidity() # percent
msg = "Temp: {0}, Press: {1}, Humid: {2}".format(round(t,1),round(p),round(h))
sense.show_message(msg)


# eof


# --------- User Settings ---------
CITY = "Nashville"
BUCKET_NAME = ":partly_sunny: " + CITY + " Weather"
BUCKET_KEY = "sensehat"
ACCESS_KEY = "Your_Access_Key"
SENSOR_LOCATION_NAME = "Office"
MINUTES_BETWEEN_SENSEHAT_READS = 0.1
# ---------------------------------

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

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

  # 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)
Beispiel #59
0
from sense_hat import SenseHat
import sys
import time
import json
sense = SenseHat()

sense.set_rotation(180)
if len(sys.argv) > 1:
    sense.show_message(sys.argv[1], scroll_speed=0.03)
else:
    sense.show_message("Starting measurements", scroll_speed=0.05)

while True:
	humidity = "{0:.2f}".format(sense.get_humidity()) 
#	print("Humidity: %s %%rH" % humidity)

	temp = "{0:.2f}".format(sense.get_temperature())
#	print("Temperature: %s C" % temp)

	pressure = "{0:.2f}".format(sense.get_pressure())
#	print("Pressure: %s Millibars" % pressure)
	
	data = [{"title": "Temperature", "value": temp}, { "title": "Humidity", 
"value": humidity }, { "title": "Pressure", "value": pressure }]
	with open('data.txt', 'w') as outfile:
    		json.dump(data, outfile)
	time.sleep(10);