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
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
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()
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'
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
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()
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()
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")
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()
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()
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)
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
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
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 execute(self): sense = SenseHat() humidity = sense.get_humidity() return dict(humidity=humidity)
topic = argv[2] sense = SenseHat() sense.clear() l = Light(sense) previous_ts = timestamp() msgs = list() try: while True: # Round the values to one decimal place t = round(sense.get_temperature(), 8) p = round(sense.get_pressure(), 8) h = round(sense.get_humidity(), 8) ts = timestamp() sensor_id = random.choice(SENSORS) # increase qos if there will be more that one broker # msgs.append({ # 'topic': MQTT_PATH, 'qos': 1, # 'payload': "{sensor},{time},{t}C,{h}%,{p}hPa" # .format(sensor=sensor_id, time=ts, t=t, h=h, p=p)}) msgs.append({ 'topic': topic, 'payload': "{sensor},{time},{t}C,{h}%,{p}hPa".format(sensor=sensor_id,
from sense_hat import SenseHat import digit, time sense = SenseHat() sense.clear() sense.set_rotation(180) while True: hum = int(round(sense.get_humidity(),0)) sense.set_pixels(digit.makedigit(hum)) # Check every minute time.sleep(60)
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üß!')
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 < 20 and t < 26.7: hintergrundFarbe = [255, 0, 0] else: hintergrundFarbe = [0, 255, 0] msg = "Temperature = %s, Pressure=%s, Humidity=%s" % (t, p, h) sense.show_message(msg, scroll_speed=0.05, back_colour=hintergrundFarbe)
from math import floor # Lab 2 Step 3 # Created by Jack Harold 09/25/20 # Base code from http://projects.raspberrypi.org/en/projects/sense-hat-ransom-sparkles/ sense = SenseHat() x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) temp = floor(sense.get_temperature()) pressure = floor(sense.get_pressure()) humidity = floor(sense.get_humidity()) print("Currently " + str(temp) + " decrees C") print("Currently " + str(pressure) + "mbar") print("Currently " + str(humidity) + "% humidity") def update_pixel(): x = randint(0, 7) y = randint(0, 7) r = randint(0, 255) g = randint(0, 255) b = randint(0, 255) sense.set_pixel(x, y, r, g, b) return
def __init__(self): sense = SenseHat() sense.clear() self.temp = round(sense.get_temperature(), 1) self.temp_humid = round(sense.get_humidity(), 1)
from sense_hat import SenseHat from time import sleep from random import randint sense = SenseHat() sense.set_rotation(180) # r = 255 # g = 0 # b = 255 while True: temperatur = round(sense.get_temperature_from_humidity(), 1) druck = round(sense.get_pressure(), 1) feuchte = round(sense.get_humidity(), 1) print(temperatur) print(druck) print(feuchte) ausgabe = ('Temperatur: %s C ' % str(temperatur) + 'Luftdruck: %s hPa ' % str(druck) + 'Luftfeuchtigkeit: %s %%' % str(feuchte)) #ausgabe = ('Werte: ' + str(temperatur)+ 'C' + str(druck) + 'hPa' + str(feuchte) + '%%') sense.show_message(ausgabe, scroll_speed=0.1) # sense.show_letter ('1', text_colour = (255, 0,255), back_colour = (0, 255,0)) # sleep (1) # sense.show_letter ('A') #sense.show_message ('Hallo ihr Ficker', text_colour = (255,0,0), scroll_speed = 0.2) #sense.clear (r,g,b)
#!/usr/bin/env.python import math import time import json import paho.mqtt.publish as publish from sense_hat import SenseHat sense = SenseHat() MQTT_HOST = 'mqtt.beia-telemetrie.ro' MQTT_TOPIC = 'odsi/vlc' while True: payload_dict = { "TEMP": sense.get_temperature(), "HUMID": sense.get_humidity(), "PRESS": sense.get_pressure() } try: publish.single(MQTT_TOPIC, qos=1, hostname=MQTT_HOST, payload=json.dumps(payload_dict)) except: time.sleep(0.01) #TODO local storage time.sleep(10)
#!/usr/bin/env python from sense_hat import SenseHat from time import sleep import sys sh = SenseHat() sh.clear() # sh.show_message("Starting Weather detection") try: while True: temperature = sh.get_temperature() pressure = sh.get_pressure() humidity = sh.get_humidity() t = round(temperature, 2) p = round(pressure, 2) h = round(humidity, 2) #sh.show_message("The temperature is %d, the pressure is %d, and the humidity is %d." % (temperature, pressure, humidity)) sh.show_message("Temp: %s, Pressure: %s, Humidity: %s." % (t, p, h)) sleep(1) except KeyboardInterrupt: print("Exiting...") sh.clear()
def index(): sense = SenseHat() temp = round(sense.get_temperature(), 1) kosteus = round(sense.get_humidity(), 1) paine = round(sense.get_pressure(), 1) currentDT = datetime.datetime.now() date = currentDT.strftime("%Y-%m-%d") clock = currentDT.strftime("%H:%M:%S") huono = 'Bad value!' hyvä = 'Good value!' heading = sense.get_compass() pohjoinen = 'North' east = 'East' south = 'South' west = 'West' mydb = mysql.connector.connect(host="localhost", user="******", passwd="salasana123", database="sensehat") mycursor = mydb.cursor() sqlform = "Insert into luvut(pvm,clock,temperature,humidity,pressure) values(%s, %s, %s, %s, %s)" sql = [(date, clock, temp, kosteus, paine)] mycursor.executemany(sqlform, sql) mydb.commit() mycursor.execute( "SELECT ROUND(AVG(temperature),2) FROM luvut WHERE pvm=CURDATE()") mytemp = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(pressure),2) FROM luvut WHERE pvm=CURDATE()") mypres = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(humidity),2) FROM luvut WHERE pvm=CURDATE()") myhum = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(temperature),2) FROM luvut WHERE pvm=CURDATE()- INTERVAL 1 DAY" ) yetemp = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(pressure),2) FROM luvut WHERE pvm=CURDATE()- INTERVAL 1 DAY" ) yepres = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(humidity),2) FROM luvut WHERE pvm=CURDATE() - INTERVAL 1 DAY" ) yehum = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(temperature),2) FROM luvut WHERE pvm=CURDATE()- INTERVAL 2 DAY" ) twotemp = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(pressure),2) FROM luvut WHERE pvm=CURDATE()- INTERVAL 2 DAY" ) twopres = mycursor.fetchall() mycursor.execute( "SELECT ROUND(AVG(humidity),2) FROM luvut WHERE pvm=CURDATE() - INTERVAL 2 DAY" ) twohum = mycursor.fetchall() if temp <= 16: arvo = huono else: if temp >= 17: arvo = hyvä if kosteus <= 22: kostarvo = hyvä else: if kosteus >= 23: kostarvo = huono if paine <= 1010: painearvo = hyvä else: if paine >= 1011: painearvo = huono if heading < 45 or heading > 315: ilmansuunta = pohjoinen elif heading < 135: ilmansuunta = east elif heading < 225: ilmansuunta = south else: ilmansuunta = west return render_template('index.html', temp=temp, kosteus=kosteus, paine=paine, date=date, clock=clock, mytemp=mytemp, myhum=myhum, mypres=mypres, yetemp=yetemp, yehum=yehum, yepres=yepres, arvo=arvo, painearvo=painearvo, kostarvo=kostarvo, ilmansuunta=ilmansuunta, twotemp=twotemp, twohum=twohum, twopres=twopres)
from sense_hat import SenseHat import firebase_admin from firebase_admin import credentials, firestore import time print('running') # firebase cred = credentials.Certificate( "/home/pi/Desktop/labo-3-firebase-nmdgent-jefverme/sensehat_dashboard/config/labo-iot-firebase-adminsdk-c3rpv-23eb19a6ee.json" ) firebase_admin.initialize_app(cred) # connect to firestore db = firestore.client() # sensehat sense = SenseHat() sense.set_imu_config(False, False, False) sense.clear() while True: data = { u'temperature': sense.get_temperature(), u'humidity': sense.get_humidity(), } db.collection(u'raspberry_collection').document(u'sensor-data').set(data) time.sleep(60)
SLEEP_START=1 SLEEP_DURATION=8 #Displayed Pixel will be red if above RED_TEMP. It will transition to blue as the temp aproaches BLUE_TEM$ #Below BLUE_TEMP, pixel will be white (Usually indicating freezing) RED_TEMP = 32.0 BLUE_TEMP = 0.0 #------------------------------------------------------- sense = SenseHat() #Get time and weather---------------------------------- cTime = time.localtime() cTemp = sense.get_temperature() cPres = sense.get_pressure() cHumi = sense.get_humidity() cDatetime = str(datetime.now()) #Get conditions soup = BeautifulSoup(requests.get("https://weather.com/weather/today/l/a620a61ecfab914ca71b8b470703a7e2d913180d5b13298f3d251c61d76fd985").content,"html.parser") cConditions = soup.find("div",{'data-testid':'wxPhrase'}).text #------------------------------------------------------ print("Current temperature: {} C".format(cTemp)) #Record weather--------------------------------------------- fileName= '/home/pi/weatherPi/weather_data/'+str(cTime[0])+'_weatherData.csv'
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY) def get_or_create_feed(key, name, description=''): try: return aio.feeds(key) except RequestError as e: print("Got an error when tried to get feed", name, e) feed = Feed(key=key, name=name, description=description) return aio.create_feed(feed) sense = SenseHat() sense.clear() humidity = round(sense.get_humidity(), 1) print("Humidity", humidity) pressure = round(sense.get_pressure(), 1) print("Pressure", pressure) temp_humidity = round(sense.get_temperature_from_humidity(), 1) temp_pressure = round(sense.get_temperature_from_pressure(), 1) temp_avg = round((temp_humidity + temp_pressure) / 2, 1) print("Temperature {0:.1f} (H {1:.1f} / P {2:.1f})".format( temp_avg, temp_humidity, temp_pressure)) humidity_feed = get_or_create_feed("bedroom-humidity", "Bedroom Humidity") pressure_feed = get_or_create_feed("bedroom-pressure", "Bedroom Pressure") temp_humidity_feed = get_or_create_feed("bedroom-temperature-h", "Bedroom Temperature (H)", "Temperature from Humidity sensor") temp_pressure_feed = get_or_create_feed("bedroom-temperature-p",
def weather(): sense = SenseHat() sense.clear() # Get temperature, humidity, pressure, and calculate dewpoint celcius = round(sense.get_temperature(), 1) fahrenheit = round(1.8 * celcius + 32, 1) humidity = round(sense.get_humidity(), 1) pressure = round(sense.get_pressure(), 1) dewpoint = round( 243.04 * (log(humidity / 100) + ((17.625 * celcius) / (243.04 + celcius))) / (17.625 - log(humidity / 100) - (17.625 * celcius) / (243.04 + celcius)), 1) # Get orientation data acceleration = sense.get_accelerometer_raw() x = round(acceleration['x'], 2) y = round(acceleration['y'], 2) z = round(acceleration['z'], 2) # Set screen color based on temperature if fahrenheit > 20 and fahrenheit < 80: bg_color = [0, 0, 155] # blue elif fahrenheit > 81 and fahrenheit < 90: bg_color = [0, 155, 0] # Green elif fahrenheit > 91 and fahrenheit < 100: bg_color = [155, 155, 0] # Yellow elif fahrenheit > 101 and fahrenheit < 102: bg_color = [255, 127, 0] # Orange elif fahrenheit > 103 and fahrenheit < 104: bg_color = [155, 0, 0] # Red elif fahrenheit > 105 and fahrenheit < 109: bg_color = [255, 0, 0] # Bright Red elif fahrenheit > 110 and fahrenheit < 120: bg_color = [155, 155, 155] # White else: bg_color = [0, 155, 0] # Green result = ' Temp. F ' + str(fahrenheit) + ' Temp. C ' + str( celcius) + ' Hum. ' + str(humidity) + ' Press. ' + str( pressure) + ' DewPoint ' + str(dewpoint) print(result) result_list = [(datetime.datetime.now(), celcius, fahrenheit, humidity, pressure, dewpoint, x, y, z)] # Log input with open('weather_logs.csv', 'a', newline='') as csv_file: writer = csv.writer(csv_file) writer.writerows(result_list) # Print the data logged 5 times for x in range(5): # set orientation acceleration = sense.get_accelerometer_raw() x = round(acceleration['x'], 0) y = round(acceleration['y'], 0) if x == -1: sense.set_rotation(90) elif y == 1: sense.set_rotation(0) elif y == -1: sense.set_rotation(180) else: sense.set_rotation(180) # print result variable to the PiHAT screen sense.show_message(result, scroll_speed=0.10, back_colour=bg_color, text_colour=[155, 155, 155])
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()
else: print("Connection failed") Connected=False broker_address="mqtt.beia-telemetrie.ro" port=1883 user="" password="" client=mqttClient.Client("Python") client.username_pw_set(user,password=password) client.on_connect=on_connect client.connect(broker_address, port=port) client.loop_start() while Connected!=True: time.sleep(0.1) try: while True: temp=sense.get_temperature() print(temp) umiditate=sense.get_humidity() print(umiditate) presiune=sense.get_pressure() print(presiune) payload_dict={"TEMPERATURE" : temp, "HUMIDITY": umiditate, "PRESSURE": presiune} client.publish{"training/rpi/cristiana-visan",json.dumps(payload_dict)} time.sleep(10) except KeyboardInterrupt: client.disconnect() client.loop_stop()
client = mqtt.Client() 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"}]
# If statement to search the json array # The sense hat displays Data Detection - Green or No data - Red, # depending on the information stored in the URL array while True: r = requests.get(url=URL) data = r.json() flightData = data["aircraft"] print("Aircraft data: " + str(flightData)) temp = round(sense.get_temperature(), 2) press = round(sense.get_pressure(), 2) hum = round(sense.get_humidity(), 2) cputemp = get_temp() disk = get_disk_usage() mem = get_memory_usage() usage = get_cpu_usage() if flightData: sense.show_message("Data Detection!", text_colour=green) status = 1 writeData(status, temp, press, hum, cputemp, disk, mem, usage) else: sense.show_message("No Data", text_colour=red) status = 0 writeData(status, temp, press, hum, cputemp, disk, mem, usage)
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);
class SenseManager(object): def __init__(self, log_mgr, channel): self.log_mgr = log_mgr self.channel = channel self.sense = SenseHat() self.turn_off_display() self.log_mgr.info(self.__class__.__name__, "SenseManager initialized") # Acquire single measure from single channel def read_channel(self): val = None # Acquiring from SenseHat sensors: Temperature, Pressure, Humidity if (self.channel == 1): val = self.sense.get_temperature() elif (self.channel == 2): val = self.sense.get_pressure() else: val = self.sense.get_humidity() self.light_up_pixel() # One digit round val = round(val, 2) return val # ------------------------------------------------------------------------------------------------ # METODI DEDICATI PER IL SENSE-HAT # ------------------------------------------------------------------------------------------------ # Alla pressione del pulsante del sense-hat il programma termina def show_green_sign(self): self.sense.set_pixels(green_sign) # Alla pressione del pulsante del sense-hat il programma termina def turn_off_display(self): self.sense.set_pixels(display_off) def light_up_pixel(self): meas_color = [] pix = [] if (self.channel == 1): meas_color = [255, 0, 0] elif (self.channel == 2): meas_color = [0, 255, 0] else: meas_color = [0, 0, 255] pix = self.next_pixel() self.sense.set_pixel(pix[0], pix[1], meas_color) def next_pixel(self): global X global x global y pix = [] while (self.sense.get_pixel(x, y) != X): x = x + 1 if (x == 8): x = 0 y = y + 1 if (y == 8): self.turn_off_display() x = 0 y = 0 pix.append(x) pix.append(y) return pix
args = parser.parse_args() host = args.host topic = args.topic myAWSIoTMQTTClient = AWSIoTMQTTClient('device') myAWSIoTMQTTClient.configureEndpoint(host, 8883) myAWSIoTMQTTClient.configureCredentials('./creds/root-CA.crt', './creds/metrics.private.key', './creds/metrics.cert.pem') myAWSIoTMQTTClient.connect() print('Connected!') while True: time.sleep(1) message = {} sense.clear() message['temperature'] = round(sense.get_temperature(), 3) * 1000 message['pressure'] = round(sense.get_pressure(), 3) * 1000 message['humidity'] = round(sense.get_humidity(), 3) * 1000 message['createdAt'] = datetime.datetime.now().isoformat() messageJson = json.dumps(message) try: myAWSIoTMQTTClient.publish(topic, messageJson, 1) except: print('Failed to send metrics...')
class Sensors(): """Obtain data from the Atmospheric sensors.""" def __init__(self, MQ7_Ro, MQ2_Ro): # Gas sensor ajustments self.MQ7_Ro = MQ7_Ro # Sensor resistance at 100 ppm of CO self.MQ2_Ro = MQ2_Ro # Sensor resistance at 1000 ppm of H2 # Initializing self.spi_comm = spiCommunicator(SPICLK, SPIMOSI, SPIMISO, SPICS) self.sense = SenseHat() print("* Initializing sensors. Please wait 20 seconds...") sys.stdout.flush() self.sense.set_rotation(ROTATION) self.sense.show_message("INITIALIZING...", text_colour=TEXT_COLOUR, scroll_speed=TEXT_SPEED) self.sense.show_letter("-", [255, 0, 0]) time.sleep(20) # Execute a first measurement in order to avoid error data from sensors self.getSensorData() def calibration(self, mq_channel): """ Assuming that the sensor is in clean air, this function calculates the sensor resistance in clean air, and divide it by RO_CLEAN_AIR_FACTOR. Input: mq_channel -> Analog channel where the MQ sensor is connected Output: Ro of the sensor """ ro = 0.0 for i in range(CALIBRATION_SAMPLE_TIMES): ro += self.getResistance(self.spi_comm.read(mq_channel), mq_channel) time.sleep(CALIBRATION_SAMPLE_INTERVAL/1000.0) ro = ro/CALIBRATION_SAMPLE_TIMES if(mq_channel == MQ7_CHANNEL): ro = ro/MQ7_RO_CLEAN_AIR_FACTOR elif(mq_channel == MQ2_CHANNEL): ro = ro/MQ2_RO_CLEAN_AIR_FACTOR return ro def getSensorData(self): """ Obtain the data from the different sensors and return it. Output: Current sensor data """ data = {} mq7_Rs = self.read(MQ7_CHANNEL) mq2_Rs = self.read(MQ2_CHANNEL) # Avoid Rs to be 0 if mq7_Rs == 0: mq7_Rs = 0.001 if mq2_Rs == 0: mq2_Rs = 0.001 # Gas sensors data["CO"] = self.getGasPPM(float(mq7_Rs)/self.MQ7_Ro, MQ7_CHANNEL) data["LPG"] = self.getGasPPM(float(mq2_Rs)/self.MQ2_Ro, MQ7_CHANNEL) # Calculate the real temperature compensating the CPU heating temp1 = self.sense.get_temperature_from_humidity() temp2 = self.sense.get_temperature_from_pressure() temp_cpu = self.getCPUTemperature() temp = (temp1+temp2)/2 real_temp = temp - ((temp_cpu-temp)/CPU_TEMP_FACTOR) # Environment sensors data["Temperature"] = real_temp data["Humidity"] = self.sense.get_humidity() data["Pressure"] = self.sense.get_pressure() # Set screen colors: self.setScreen(data["CO"], data["LPG"]) return data def setScreen(self, CO, LPG): """ Set SenseHat screen depending on the CO and LPG levels. Input: CO -> CO gas level. LPG -> LPG level. """ O = [0, 0, 0] X = COLOURS_LEVELS[4] Y = COLOURS_LEVELS[4] for i in reversed(range(0,4)): if CO < LIMITS['CO'][i]: X = COLOURS_LEVELS[i] if LPG < LIMITS['LPG'][i]: Y = COLOURS_LEVELS[i] screen = [ O, O, X, X, X, O, O, O, O, O, X, X, X, O, O, O, O, O, X, X, X, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, Y, Y, Y, O, O, O, O, O, Y, Y, Y, O, O, O, O, O, Y, Y, Y, O, O, O ] self.sense.set_pixels(screen) def getCPUTemperature(self): """ Calculate CPU temperature. Output: Current CPU temperature """ command_res = os.popen("vcgencmd measure_temp").readline() t = float(command_res.replace("temp=","").replace("'C\n","")) return(t) def read(self, mq_channel): """ Calculate the current sensor resistance which depens on the different concentration of the target gas. Input: mq_channel -> Analog channel where the MQ sensor is connected Output: Rs of the sensor """ Rs = 0.0 for i in range(READ_SAMPLE_TIMES): adc_value = self.spi_comm.read(mq_channel) Rs += self.getResistance(adc_value, mq_channel) time.sleep(READ_SAMPLE_INTERVAL/1000.0) Rs = Rs/READ_SAMPLE_TIMES return Rs def getResistance(self, adc_value, mq_channel): """ Calculate the current resistance of the sensor given its current voltage. Input: adc_value -> Raw value form the ADC. Voltage = adc*Vref/1024 mq_channel -> Analog channel where the MQ sensor is connected Output: Current resistance of the sensor """ resistance = 0.0 if adc_value == 0: # Avoid division by 0 adc_value = 1 if(mq_channel == MQ7_CHANNEL): resistance = float(MQ7_RL*(1024.0-adc_value)/float(adc_value)) elif(mq_channel == MQ2_CHANNEL): resistance = float(MQ2_RL*(1024.0-adc_value)/float(adc_value)) return resistance def getGasPPM(self, rs_ro_ratio, mq_channel): """ Calculate the ppm of the target gases. Input: rs_ro_ratio -> Value obtained of the division Rs/Ro mq_channel -> Analog channel where the MQ sensor is connected Output: Current gas percentage in the environment """ percentage = 0 if(mq_channel == MQ7_CHANNEL): percentage = self.getMQPPM(rs_ro_ratio, CO_Curve) elif(mq_channel == MQ2_CHANNEL): percentage = self.getMQPPM(rs_ro_ratio, LPG_Curve) return percentage def getMQPPM(self, rs_ro_ratio, mq_curve): """ Calculate the ppm of the target gas using the slope and a point form the line obtained aproximating the sensitivity characteristic curve. x = (y-n)/m Input: rs_ro_ratio -> Value obtained of the division Rs/Ro mq_curve -> Line obtained using two points form the sensitivity characteristic curve Output: Current gas percentage in the environment """ return (math.pow(10, (math.log10(rs_ro_ratio)-mq_curve[1]) / mq_curve[0]))
import sqlite3 from sense_hat import SenseHat import time conn = sqlite3.connect('/home/pi/pi-sql/infoscreen.db') sense = SenseHat() sense.clear() c = conn.cursor() # Create table c.execute('''CREATE TABLE roomdata (time real,temprature real, pressure real, humidity real)''') conn.commit() while True: time.sleep(10) data = [(time.time(), sense.get_temperature(), sense.get_pressure(), sense.get_humidity())] c.executemany('INSERT INTO roomdata VALUES (?,?,?,?)', data) print("INSERTED: ",data) conn.commit()
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)
level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%Y-%m-%d, %H:%M:%S,') sh = SenseHat() # Connect to Sense HAT sh.low_light = 1 # set LED light intensity to low h_old = 0 col = [0, 0, 255] #header logging.info('Date_Time,Temperature,Humidity,Pressure') while True: # Main loop #Read the sensor data h = sh.get_humidity() # Take humidity reading t = sh.get_temperature() # Take temperature reading p = sh.get_pressure() # Take barometric pressure reading #Log the sensor values logging.info(str(h) + str(',') + str(t) + str(',') + str(p)) # Log value to file #set LED for status; avoid disturbing during dark hours :-) if (datetime.today().hour > 8 and datetime.today().hour < 18): if h > h_old: # If humidity has increased... col = [210, 0, 0] # Set to red else: # If humidity has decreased... col = [0, 210, 0] # Set to green h = int(round(h, 0)) # Round to a whole percent i = numToMatrix(h, col) # Create 2-digit image for matrix
class DataLogger: def __init__(self): self.buffer = 10 self.sense = SenseHat() self.batch_data = [] self.filename = "./logs/Datalogg-" + str(datetime.now()) + ".csv" self.file_setup(self.filename) def log_data(self): sense_data = self.get_sense_data() output_string = ",".join(str(value) for value in sense_data) self.batch_data.append(output_string) if len(self.batch_data) >= self.buffer: print("Writing to file..") with open(self.filename, "a") as f: for line in self.batch_data: f.write(line + "\n") self.batch_data = [] 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
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 ArduinoManager(): __instance = None ''' Implementing Singleton to have a single instance of the arduino connection to avoid override and conflict ''' @staticmethod def getInstance(): """ Static access method. """ if ArduinoManager.__instance == None: logging.info("Creating first Arduino Manager instance") ArduinoManager() return ArduinoManager.__instance #Constructor def __init__(self): ArduinoManager.__instance = self self.portNumber = PortManager.getArduinoPort() self.ser = sl.Serial(self.portNumber, 9600) self.sensehat = SenseHat() logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG) logging.info("Sending Arduino Instance") #Method to get LDR values def getLdrValues(self): sleep(2) while (True): logging.info("Connecting to Arduino") self.ser.write( b'a' ) #Send data to arduino. Activate arduino read pin and write to serial logging.info("Requested data from Arduino...waiting for response") data = self.ser.readline() return (str(data.decode("utf-8")).rstrip("\n\r")) #Method to get Soil Moisture values def getSoilMoistureValues(self): sleep(2) while (True): logging.info("Connecting to Arduino") self.ser.write( b'b' ) #Send data to arduino. Activate arduino read pin and write to serial logging.info("Requested data from Arduino...waiting for response") data = self.ser.readline() return (str(data.decode("utf-8")).rstrip("\n\r")) #Method to get Temperature value def getTemperature(self): return (self.sensehat.get_temperature()) #Method to get humidity values def getHumidity(self): return (self.sensehat.get_humidity()) #Uncomment the below code for I2C ''' coeffH0 = self.i2cBus.read_byte_data(self.humidAddr, 0x30) coeffH1 = self.i2cBus.read_byte_data(self.humidAddr, 0x31) H0_rH= float(coeffH0/2.0) H1_rH = float(coeffH1/2.0) valH0T0a = self.i2cBus.read_byte_data(self.humidAddr, 0x36) valH0T0b = self.i2cBus.read_byte_data(self.humidAddr, 0x37) H0_T0_OUT = (valH0T0b<<self.bits ) | valH0T0a if H0_T0_OUT & (1 << 16 - 1): H0_T0_OUT -= (1 << 16) #print("H0_T0_OUT = " + str(H0_T0_OUT)) valH1T1a = self.i2cBus.read_byte_data(self.humidAddr, 0x3A) valH1T1b = self.i2cBus.read_byte_data(self.humidAddr, 0x3B) H1_TO_OUT = (valH1T1b<<self.bits ) | valH1T1a if H1_TO_OUT & (1 << 16 - 1): H1_TO_OUT -= (1 << 16) rawH1T1a = self.i2cBus.read_byte_data(self.humidAddr, 0x28) rawH1T1b = self.i2cBus.read_byte_data(self.humidAddr, 0x29) H_T_OUT = (rawH1T1b<<self.bits) | rawH1T1a if H_T_OUT & (1 << 16 - 1): H_T_OUT -= (1 << 16) hper = float(((H1_rH-H0_rH)*(H_T_OUT-H0_T0_OUT))/(H1_TO_OUT-H0_T0_OUT))+H0_rH return hper ''' #Method to issue commands to Servo motor def servoCommand(self): logging.info("Issuing command to water") self.ser.write(b's') return True
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)
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 if (h > 56 and h < 60) or (h > 40 and h < 44): bc = orange
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]
if temperature_average >= MAX_Temperature: sense.show_message("MAX Temp", text_colour=[255, 0, 0], back_colour=[255, 255, 255], scroll_speed=0.02) elif temperature_average <= MIN_Temperature: sense.show_message("MIN Temp", text_colour=[255, 0, 0], back_colour=[255, 255, 255], scroll_speed=0.02) else: sense.show_message("Temp OK", text_colour=[0, 255, 0], back_colour=[255, 255, 255], scroll_speed=0.02) if round(sense.get_humidity(), 4) >= MAX_Humidity: sense.show_message("MAX %rH", text_colour=[255, 0, 0], back_colour=[255, 255, 255], scroll_speed=0.02) elif round(sense.get_humidity(), 4) <= MAX_Humidity: sense.show_message("MIN %rH", text_colour=[255, 0, 0], back_colour=[255, 255, 255], scroll_speed=0.02) else: sense.show_message("%rH OK", text_colour=[0, 255, 0], back_colour=[255, 255, 255], scroll_speed=0.02)
#!/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])
class Greenhouse_Bluetooth: def __init__(self): self.sense = SenseHat() self.configFilename = 'config.json' self.list = [] 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 initPairedDevices(self): p = sp.Popen(["bt-device", "--list"], stdin=sp.PIPE, stdout=sp.PIPE, close_fds=True) (stdout, stdin) = (p.stdout, p.stdin) data = stdout.readlines() for binary in data: string1 = binary.decode('ascii') start = string1.find('(') if start != -1: start += 1 end = string1.index(')') length = end - start String = string1[start:start + length] self.list.append(String) 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 main(self): time1 = datetime.now(timezone) time3 = datetime.now(timezone) print("Starting up please wait a moment...") while True: time.sleep(60) time1 = datetime.now(timezone) humidity = self.sense.get_humidity() 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) temperature = t_corr sendstatus = "All Good" temperatureStatus = self.evaluateStatus("Temperature", int(temperature), self.minTemp, self.maxTemp, "*C") humidityStatus = self.evaluateStatus("Humidity", int(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 nearby_devices = bluetooth.discover_devices() minute1 = time1.strftime("%M") time_1 = int(minute1) for macAddress in nearby_devices: print("Found device with mac-address: " + macAddress) if macAddress in self.list: minute3 = time3.strftime("%M") time_3 = int(minute3) if ((time_1 - time_3) >= 2) or ((time_1 - time_3) <= (-50)): body = """Currently the temperature is {:.2f}*C and the humidity is {:.2f}% \nStatus Report: {}""".format( temperature, humidity, sendstatus) self.send_notification_via_pushbullet("Update", body) time3 = datetime.now(timezone) print("Waiting for 1 minute...")
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)
from sense_hat import SenseHat sense = SenseHat() # Assign the 'SenseHat()' function to a variable of sense. sense.clear() # Clear the screen using the 'clear()' function from sense. humidity = sense.get_humidity() # Get the humidity reading from sense and # assign it to the variable humidity. print(humidity) # Then print the humidity reading from the variable humidity.
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, 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()
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) streamer.log(":sweat_drops: " + SENSOR_LOCATION_NAME + " Humidity(%)", humidity)
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