def update(self): """Get the latest data from Enviro pHAT.""" from envirophat import analog, leds, light, motion, weather # Light sensor reading: 16-bit integer self.light = light.light() if self.use_leds: # pylint: disable=no-value-for-parameter leds.on() # the three color values scaled agains the overall light, 0-255 self.light_red, self.light_green, self.light_blue = light.rgb() if self.use_leds: # pylint: disable=no-value-for-parameter leds.off() # accelerometer readings in G self.accelerometer_x, self.accelerometer_y, self.accelerometer_z = \ motion.accelerometer() # raw magnetometer reading self.magnetometer_x, self.magnetometer_y, self.magnetometer_z = \ motion.magnetometer() # temperature resolution of BMP280 sensor: 0.01°C self.temperature = round(weather.temperature(), 2) # pressure resolution of BMP280 sensor: 0.16 Pa, rounding to 0.1 Pa # with conversion to 100 Pa = 1 hPa self.pressure = round(weather.pressure() / 100.0, 3) # Voltage sensor, reading between 0-3.3V self.voltage_0, self.voltage_1, self.voltage_2, self.voltage_3 = \ analog.read_all()
def show_temperature(delay): clear() temp = weather.temperature() write_string("%.2f" % temp + "c", kerning=False) show() time.sleep(delay) g.labels(host=host).set(temp)
def sbc_rpi0_envirophat(): update = {} update["phatlightrgb"] = light.rgb() update["phatlight"] = light.light() update["phattemperature"] = round(weather.temperature(), 1) update["phatpressure"] = round(weather.pressure(unit='hPa'), 1) update["phataltitude"] = round(weather.altitude(qnh=1020), 1) update["phatanalog"] = analog.read_all() update["phatmagnetometer"] = str(motion.magnetometer()) update["phataccelerometer"] = str(motion.accelerometer()) update["phatheading"] = round(motion.heading(), 1) update["soiltemp"] = round( therm200_convert_analog(update["phatanalog"][2]), 1) update["soilmoist"] = round(vh400_convert_analog(update["phatanalog"][1]), 1) update["relhum"] = round(vghumid_convert_analog(update["phatanalog"][0]), 1) (result, mid) = mqttc.publish(hass_autogen_topic + "/" + cid + "/state", json.dumps(update), qos=1, retain=True) return update
def temperature_reading(): """ Retrieve temperature in celsius :return: temperature :rtype: float """ temperature = weather.temperature() return float("{0:.2f}".format(temperature))
def temperature(): """Temperature""" global weather data = { "temperature": weather.temperature() - float(os.environ.get("correction", 0)) } return jsonify(data)
def show_temp(): # Makes sure scrollphat buffer is clear sphd.clear() # Declares local variable "degrees", fetches value form weather module and rounds to 1 decimal place degrees = round(weather.temperature(), 1) # Section that controls speach output # "speaktemp" string is set speaktemp = ("The temperature is currently " + str(degrees) + " degrees celcius") print(speaktemp) # "speaktemp" is passed into say_value() function say_value(speaktemp) # Section taht controls scrollphat output # "temperature" string is set temperature = (' Temp: ' + str(degrees) + 'C') # "temperature" string is written to sphd buffer sphd.write_string(temperature, brightness=0.25) # Length of buffer is calculated length = sphd.get_buffer_shape()[0] - 17 # Scrolls for the total length value for x in range(length): sphd.show() sphd.scroll(1) time.sleep(0.03) # Sleeps for 1 second once complete time.sleep(1) # Clears buffer and runs show() to clear display sphd.clear() sphd.show() # Makes sure all button LED's are turned off touchphat.all_off()
def get_environment(): data = {'boardTemp': weather.temperature(), 'atm': weather.pressure(), 'light': light.light()} data['cpuTemp'] = get_cpu_temperature() data['calibTemp'] = data['boardTemp'] - ((data['cpuTemp'] - data['boardTemp'])/FACTOR) # print data return data
def getFrame(): raw_data = { "time" : (time.time()), "flight_mode": 0, "squib_deployed": 0, "a_x": round(motion.accelerometer().x, roundOff), "a_y": round(motion.accelerometer().y, roundOff), "a_z": round(motion.accelerometer().z, roundOff), "temp": round(weather.temperature(), roundOff), "pressure": round(weather.pressure(), roundOff), "s1": round(ina219A.getShuntVoltage_mV(), roundOff), "volt_b1": round(ina219A.getBusVoltage_V(), roundOff), "current_1": round(ina219A.getCurrent_mA(), roundOff), "s2": round(ina219B.getShuntVoltage_mV(), roundOff), "volt_b2": round(ina219B.getBusVoltage_V(), roundOff), "current_2": round(ina219B.getCurrent_mA(), roundOff), "gps_lat" : 12, "gps_lon" : 13, "gps_alt" : 14, "gps_spd" : 15, #"gps_lat": round(gpsd.fix.latitude, roundOff), #"gps_lon": round(gpsd.fix.longitude, roundOff), #"gps_alt": round(gpsd.fix.altitude, roundOff), #"gps_spd": round(gpsd.fix.speed, roundOff), "mag_x": round(motion.magnetometer().x, roundOff), "mag_y": round(motion.magnetometer().y, roundOff), "mag_z": round(motion.magnetometer().z, roundOff) } frame.append(raw_data)
def publish_Sensor_Values_to_MQTT(): threading.Timer(3.0, publish_Sensor_Values_to_MQTT).start() global toggle if toggle == 0: Pressure_Value = weather.pressure(unit='hPa') Pressure_light = light.light() Pressure_Data = {} Pressure_Data['Sensor_ID'] = "Sensor-1" Pressure_Data['Pressure'] = Pressure_Value Pressure_Data['Light'] = Pressure_light Pressure_json_data = json.dumps(Pressure_Data) print("Publishing fake Pressure Value: " + str(Pressure_Value) + "...") print("Publishing light amount: " + str(Pressure_light) + "...") publish_To_Topic(MQTT_Topic_Pressure, Pressure_json_data) toggle = 1 else: Temperature_Value = weather.temperature() - 17 Temperature_colour = light.rgb() Temperature_Data = {} Temperature_Data['Sensor_ID'] = "Sensor-1" Temperature_Data['Temperature'] = Temperature_Value Temperature_Data['Colour'] = Temperature_colour temperature_json_data = json.dumps(Temperature_Data) print("Publishing Temperature Value: " + str(Temperature_Value) + "...") print("Publishing light colour: " + str(Temperature_colour) + "...") publish_To_Topic(MQTT_Topic_Temperature, temperature_json_data) toggle = 0
def harvest(): date = datetime.now() ##### Grab Sense Hat data ##### t = round((weather.temperature() - equartT), 1) p = round((weather.pressure() / 100), 1) l = light.light() ##### MySQL sign in ##### conn = pymysql.connect(user="******", passwd="userpassWD", host="192.168.x.x", database="sensors") cursor = conn.cursor() ##### Database insertion ##### ##### Global cursor #### cursor.execute(queryInsert("temperature", t, "Enviro pHAT", "room 1")) cursor.execute(queryInsert("pression", p, "Enviro pHAT", "room 1")) cursor.execute(queryInsert("light", l, "Enviro pHAT", "room 1")) ##### Disconnect the database ##### conn.commit() cursor.close() conn.close()
def read_enviro_temp(): temp_raw = round(weather.temperature(), 2) temp_cpu = get_cpu_temperature() temp_calibrated = temp_raw - ( (temp_cpu - temp_raw) / 0.7 ) ## open air correction value 1.2 , in stokke 0.7 return temp_calibrated
def iothub_client_sample_run(): id = 0 iot.initialise(callback) while True: try: leds.on() openWeather.getWeather() id += 1 ## normalise light to something of 100% lightLevel = light.light() if lightLevel > 1024: lightLevel = 1024 lightLevel = lightLevel * 100 / 1024 msg_txt_formatted = msg_txt % (sensorLocation, lightLevel, round(weather.pressure() / 100, 2), round(weather.temperature(), 2), id) iot.publish(msg_txt_formatted, id) leds.off() time.sleep(4) except IoTHubError as e: print("Unexpected error %s from IoTHub" % e) print_last_message_time(iot.iotHubClient) time.sleep(4) except KeyboardInterrupt: print("IoTHubClient sample stopped") return
def disp_stats(): write("--- Enviro pHAT Monitoring ---") rgb = light.rgb() analog_values = analog.read_all() mag_values = motion.magnetometer() acc_values = [round(x, 2) for x in motion.accelerometer()] # DHT Type 11, Pin 17 (Line 41 Github) humidity, temp2 = Adafruit_DHT.read_retry(11, 17) currentDT = datetime.datetime.now() output = """ Time: {tm}; Temp: {t}c; Plant Temp: {t2}c; Humd: {hd}%; Pressure: {p}Pa; Light: {c}, RGB: {r}, {g}, {b}; Soil: {a0}% """.format(tm=currentDT.strftime("%Y-%m-%d %H:%M:%S"), t=abs(weather.temperature() * 9 / 5.0 + 32), t2=abs((temp2 * 9 / 5.0 + 32)), hd=round(humidity, 0), p=round(weather.pressure(), 0), c=light.light(), r=rgb[0], g=rgb[1], b=rgb[2], h=motion.heading(), a0=round((analog_values[0] * 100) / 434, 2) * 100, a1=analog_values[1], a2=analog_values[2], a3=analog_values[3], mx=mag_values[0], my=mag_values[1], mz=mag_values[2], ax=acc_values[0], ay=acc_values[1], az=acc_values[2]) #output = output.replace("\n","\n\033[K") write(output)
def display_temp(): scrollphathd.clear() temp = weather.temperature() - TEMP_OFFSET scrollphathd.write_string(' {}c'.format(str(int(temp))), y=1, font=font3x5, brightness=BRIGHTNESS)
def get_values(): global temperature global pressure global amblight temperature = weather.temperature() pressure = round(weather.pressure(), 2) amblight = light.light() json_response = { "prtg": { "result": [{ "channel": "temperature", "float": 1, "value": temperature }, { "channel": "pressure", "float": 1, "value": pressure }, { "channel": "ambient light", "float": 1, "value": amblight }] } } return json_response
def run(self): print '[CarMonitor::EnviroPoller] Starting...' try: while not self.stopRequest.isSet(): temperature = weather.temperature() pressure = weather.pressure() accelerometer = motion.accelerometer() magnetometer = motion.magnetometer() heading = motion.heading() self.enviroData = { 'temperature': temperature, 'pressure': pressure, 'accelerometer': { 'x': accelerometer.x, 'y': accelerometer.y, 'z': accelerometer.z }, 'magnetometer': { 'x': magnetometer.x, 'y': magnetometer.y, 'z': magnetometer.z }, 'heading': heading } time.sleep(.5) except StopIteration: pass
def run(): with SocketIO('4d36143b.ngrok.io', 80, LoggingNamespace) as socketIO: print 'got connection' # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): time.sleep(0.5) # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array pil_img = Image.fromarray(image) buff = BytesIO() pil_img.save(buff, format="JPEG") base64_image = base64.b64encode(buff.getvalue()).decode('utf-8') # clear the stream in preparation for the next frame rawCapture.truncate(0) # print base64_image temperature = 32 + round(weather.temperature()) air_pressure = weather.pressure() altitude = weather.altitude() output = json.dumps({ 'image': base64_image, 'username': '******', 'business': '1', 'temperature': temperature, 'air_pressure': air_pressure, 'altitude': altitude }) socketIO.emit('stream', output)
def get_enviro_line(): return { 'temperature': weather.temperature(), 'pressure': weather.pressure(), 'light': light.light(), 'deviceId': DEVICE_ID, 'time': millis() }
def main(): try: while True: temp = weather.temperature() print(temp) sys.stdout.flush() time.sleep(10) except Keyboard: close()
def index(): """Video streaming home page.""" temp = weather.temperature() press = weather.pressure() li = light.light() return render_template('index.html', temperature=temp, pressure=press, light=li)
def on_message(client, userdata, msg): print(msg.topic + " " + str(msg.payload)) if msg.topic == ch and msg.payload == "query-temp": leds.on() temp = weather.temperature() res = {"temp": temp} client.publish(ch, json.dumps(res)) sleep(0.3) leds.off()
def environment(bot, update): output = """ Temp: {t}c Pressure: {p}Pa Light: {c} """.format(t=round(weather.temperature(), 2), p=round(weather.pressure(), 2), c=light.light()) bot.send_message(chat_id=update.message.chat_id, text=output)
def publish_sensor_data(hostname, root): messages = [] for i, data in enumerate(analog.read_all()): messages.append(('%s/analog/%d' % (root, i), str(data), 0, True)) messages.append((root+'/light/light', str(light.light()), 0, True)) messages.append((root+'/light/rgb', str(light.rgb()), 0, True)) messages.append((root+'/motion/accelerometer', str(motion.accelerometer()), 0, True)) messages.append((root+'/motion/heading', str(motion.heading()), 0, True)) messages.append((root+'/weather/pressure', str(weather.pressure()), 0, True)) messages.append((root+'/weather/temperature', str(weather.temperature()), 0, True)) publish.multiple(messages), hostname=hostname)
def get_sensor_data(): data = {} data['analog'] = analog.read_all() data['accelerometer'] = tuple(motion.accelerometer()) data['heading'] = motion.heading() data['leds'] = leds.is_on() data['light'] = light.light() data['rgb'] = light.rgb() data['pressure'] = weather.pressure() data['temperature'] = weather.temperature() return data
def get_environment(): data = { 'board_temp': round(weather.temperature(), 2), 'pressure': round(weather.pressure(), 0), 'light': round(light.light(), 2) } data['cpu_temp'] = get_cpu_temperature() data['est_temp'] = round( data['board_temp'] - ((data['cpu_temp'] - data['board_temp']) / FACTOR), 2) return data
def run_measurements(client): """Measures accelerometer activity continously and stores an aggregated sum once per minute""" print_sample_time = 60 # How often data will be published to InfluxDB [seconds] last_print_time = datetime.datetime.now() limit = 350 # Minimum distance between two subsequent measurements to be counted as activity. [G] last_sample_x = 0 last_sample_y = 0 last_sample_z = 0 activity_x = 0 activity_y = 0 activity_z = 0 leds.on() # Turn on LEDs to indicate measurement try: while True: x, y, z = motion.accelerometer() if x > limit: activity_x += x if y > limit: activity_y += y if z > limit: activity_z += z # Probably unnecessary # x_dist = x - last_sample_x # y_dist = y - last_sample_y # z_dist = z - last_sample_z # # if x_dist > limit: # activity_x += x_dist # if y_dist > limit: # activity_y += y_dist # if z_dist > limit: # activity_z += z_dist time_dist = datetime.datetime.now() - last_print_time if time_dist.total_seconds() >= print_sample_time: last_print_time = datetime.datetime.now() activity_tot = activity_x + activity_y + activity_z temp = weather.temperature() publish_data(client, activity_tot, temp) activity_x = 0 activity_y = 0 activity_z = 0 except KeyboardInterrupt: leds.off() # Shut off LEDs out.close() # Close log client.close() # Close influx connection
def process_bmp_req(message): global bmp_sub global bmp_sub_rate global bmp_sub_ticks if message_list[3] == 'CMD=READ': # # Get the values # temp = round(weather.temperature(),2) pressure = round(weather.pressure(),2) altitude = round(weather.altitude(),2) # # format the message # message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=BMP,TEMP=%.2f,PRES=%.2f,ALT=%.2f,SENSOR_REP_END" % (temp,pressure,altitude) elif message_list[3] == 'CMD=SUB_START': rate_message_list = message_list[4].split('=') if rate_message_list[0] == 'RATE': rate = int(rate_message_list[1]) if rate < 250: bmp_sub_rate = 250 else: bmp_sub_rate = rate bmp_sub_ticks = 0 bmp_sub = True # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=BMP,CMD=SUB_START,RATE=1000,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=BMP,STATUS=OK|BUSY,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=BMP,STATUS=OK,SENSOR_REP_END" elif message_list[3] == 'CMD=SUB_STOP': bmp_sub = False bmp_sub_rate = 0 bmp_sub_ticks = 0 # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=BMP,CMD=SUB_STOP,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=BMP,STATUS=OK,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=BMP,STATUS=OK,SENSOR_REP_END" else: # unknown Command message = "SENSOR_REP," + message_list[1] + ",SUB_DEV=BMP,ERROR=UNKNOWN_CMD,SENSOR_REP_END" # # Send reply back to client # return message
def temperature(): temp_data = open("temp_%d_%d_%d.txt" % (year, month, day), "ab") fahrenheit = 1.8 * (weather.temperature( ) - 11) + 32 #11 is a constant to account for the CPU temp difference temp = "%d %d" % (time.localtime()[3], fahrenheit) temp_data.write(temp) temp_data.write("\n") temp_data.close() os.system("scp %s %s@%s:~%s" % (temp_data.name, username, ip, directory)) return temp
def get_temps(): """Get measured temperatures from envirophat and raspberry pi CPU sensor. Calculate offset measured temp. Format for further use. """ global cpu_temp global temp global tempmed global temp_calibrated cpu_temp = vcgencmd.measure_temp() temp = weather.temperature() temp_calibrated = temp - ((cpu_temp - temp)/factor) tempmed = '{:.1f}'.format(round(temp_calibrated, 2))
def get_calibrated_temperature(self): """ The temperature of the Raspberry Pi CPU can affect the envirophat sensor. We try to factor this in using the following formula: temp_calibrated = temp_c — ((cpu_temp_c — temp_c)/FACTOR) https://medium.com/@InitialState/tutorial-review-enviro-phat-for-raspberry-pi-4cd6d8c63441 """ FACTOR = 1.5 pi_temp_output = subprocess.run(["vcgencmd", "measure_temp"], capture_output=True).stdout pi_temp = float(str(pi_temp_output).split("=")[1].split("'")[0]) env_temp = weather.temperature() calibrated_temperature = env_temp - ((pi_temp - env_temp) / FACTOR) return int(calibrated_temperature)
def __getTemperature(self): """ Read temperature in degree celsius. Returns ------- touple Temperature in degree Celsius. """ try: value = (weather.temperature(), ) except: DinoLog.logMsg("ERROR - Envirophat fail to read temperature.") value = (None, ) return value
def get_url_params(): t = weather.temperature() p = weather.pressure(unit='hPa') h = None l = light.light() # Python's datetmie doesn't have timezone info. # You may need to set system timezone as JST. (hint: sudo raspi-config) # FIXME: the code will post wrong datetime. should be keep in UTC??(is the hint wrong?) ts = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S%z") s = "dt=%s" % (ts) s += "&temperature=%f" % (t) s += "&pressure=%f" % (p) # s += "&humidity=%f" % (h) s += "&illuminance=%f" % (l) # s += "&voltage=#{v}" return s
write("--- Enviro pHAT Monitoring ---") try: while True: rgb = light.rgb() analog_values = analog.read_all() output = """ Temp: {t}c Pressure: {p}Pa Light: {c} RGB: {r}, {g}, {b} Heading: {h} Analog: 0: {a0}, 1: {a1}, 2: {a2}, 3: {a3} """.format( t = round(weather.temperature(),2), p = round(weather.pressure(),2), c = light.light(), r = rgb[0], g = rgb[1], b = rgb[2], h = motion.heading(), a0 = analog_values[0], a1 = analog_values[1], a2 = analog_values[2], a3 = analog_values[3] ) output = output.replace("\n","\n\033[K") write(output) lines = len(output.split("\n")) write("\033[{}A".format(lines - 1))
#!/usr/bin/env python from envirophat import light, motion, weather, analog, leds import time while True: print("LEDs on...") leds.on() time.sleep(1) print("LEDs off...") leds.off() print("Light...") print(light.rgb()) print("Motion...") print(motion.heading()) print(motion.magnetometer()) print(motion.accelerometer()) print("Weather...") print(weather.temperature()) print(weather.pressure()) print("Analog...") print(analog.values()) time.sleep(1)
import time from envirophat import weather, leds print("""This example will detect motion using the accelerometer. Press Ctrl+C to exit. """) threshold = None try: while True: temperature = weather.temperature() if threshold is None: threshold = temperature + 2 print("{} degrees celcius".format(temperature)) if temperature > threshold: leds.on() else: leds.off() time.sleep(0.1) except KeyboardInterrupt: pass