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 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 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 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 show_pressure(): # Makes sure scrollphat buffer is clear sphd.clear() # Pressure value is fetched from weather module pressurevalue = (weather.pressure()) # Uses say_value() to speak the current pressure value speakpressure = ("The current pressure is " + str(round(pressurevalue / 1000, 1)) + " kilopascals") print(speakpressure) say_value(x=speakpressure) # Writes the currnet pressure value to scrollphat buffer sphd.write_string("Pressure: " + str(round(pressurevalue / 1000, 1)) + " kPa", 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 pressure(): """Pressure""" global weather data = { "pressure": weather.pressure() / 100.00 } return jsonify(data)
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 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 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 iothub_client_sample_run(): id = 0 iot.initialise(callback) while True: try: leds.on() openWeather.getWeather() humidity = 50 ## normalise light to something of 100% lightLevel = light.light(); if lightLevel > 1024: lightLevel = 1024 lightLevel = lightLevel * 100 / 1024 id += 1 msg_txt_formatted = msg_txt % (sensorLocation, humidity, round(weather.pressure()/100,2), round(weather.temperature(),2), lightLevel, 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 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 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 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 write(): try: p = round(weather.pressure(),2) c = light.light() print('{"light": '+str(c)+', "pressure": '+str(p)+' }') except KeyboardInterrupt: 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 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 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 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 __getPressure(self): """ Read pressure in Pa. Returns ------- touple Pressure reading in Pa. """ try: value = (weather.pressure(unit='Pa'), ) except: DinoLog.logMsg("ERROR - Envirophat fail to read pressure.") 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) ts = time.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
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
def get_data_points(): temp_cpu = get_cpu_temp() temperature = weather.temperature() pressure = round(weather.pressure(), 2) light_val = light.light() iso = time.ctime() json_body = [{ "measurement": "ambient_celcius", "tags": { "host": host }, "time": iso, "fields": { "value": temperature, "val": float(temperature) } }, { "measurement": "cpu_celcius", "tags": { "host": host }, "time": iso, "fields": { "value": temp_cpu, } }, { "measurement": "ambient_light", "tags": { "host": host }, "time": iso, "fields": { "value": light_val, } }, { "measurement": "ambient_pressure", "tags": { "host": host }, "time": iso, "fields": { "value": pressure, } }] return json_body
def update(timer): sphd.clear() t = weather.temperature() p = weather.pressure() # Record if timer % 60 == 0: log(t, p) # Draw if (timer / 10) % 2 == 0 or len(history['temperature']) < 5: s = round(t if (timer / 5) % 2 == 0 else p, 3) typography.write("%s" % s) else: graph.draw(history['temperature' if (timer / 5) % 2 == 0 else 'pressure']) sphd.show() # Trim history history['temperature'] = history['temperature'][-60:] history['pressure'] = history['pressure'][-60:]
def measure(self): leds.on() self.openWeather.getWeather() self.id += 1 humidity = 50 ## normalise light to something of 100% lightLevel = light.light(); if lightLevel > 1024: lightLevel = 1024 lightLevel = lightLevel * 100 / 1024 json = self.msg_txt % (self.sensorLocation, humidity, round(weather.pressure()/100,2), round(weather.temperature(),2), lightLevel, self.id) leds.off() return json
def append_row(session, workbookItemId): """ Appends a new row with current measurement values to the worksheet. """ url = 'https://graph.microsoft.com/v1.0/me/drive/items/{}/workbook/worksheets(\'Sheet1\')/tables(\'Table1\')/rows/add'.format( workbookItemId) # Get column values now = formatted_now_long() tempC = str(weather.temperature()) presHpa = str(weather.pressure(unit='hPa')) lum = str(light.light()) # Build data string data = '{ "values": [["' + now + '", "' + tempC + '", "' + presHpa + '", "' + lum + '"]]}' # Post the new row to the Graph API. session.post(url, data=data)
def main(): leds.on() cputemp = get_cpu_temperature() envtemp = weather.temperature() caltemp = envtemp - ((cputemp - envtemp) / 1.3) envdate = datetime.datetime.utcnow().strftime('%c') json = { "hostname": socket.gethostname(), "envdate": envdate, "light": light.light(), "temp": round((caltemp * 1.8 + 32), 2), "pressure": round(weather.pressure(), 2) } leds.off() print(json)
def getFrame(): raw_data = { "linux_time" : (time.time()), "a_x": round(motion.accelerometer().x, roundOff), "a_y": round(motion.accelerometer().y, roundOff), "a_z": round(motion.accelerometer().z, roundOff), "t": round(weather.temperature(), roundOff), "p": round(weather.pressure(), roundOff), "s1": round(ina219A.getShuntVoltage_mV(), roundOff), "b1": round(ina219A.getBusVoltage_V(), roundOff), "c1": round(ina219A.getCurrent_mA(), roundOff), "s2": round(ina219B.getShuntVoltage_mV(), roundOff), "b2": round(ina219B.getBusVoltage_V(), roundOff), "c2": round(ina219B.getCurrent_mA(), roundOff), "lat": round(gpsd.fix.latitude, roundOff), "lon": round(gpsd.fix.longitude, roundOff), "alt": round(gpsd.fix.altitude, roundOff), "sp": round(gpsd.fix.speed, roundOff)} frame.append(raw_data)
def read_sensor(): fields = [ 'timestamp', 'cpu_temp', 'weather_temp', 'weather_pressure', 'light_r', 'light_g', 'light_b', 'light_level' ] w = csv.DictWriter(sys.stdout, fieldnames=fields) lr, lg, lb = light.rgb() data = { 'timestamp': time.time(), 'cpu_temp': get_cpu_temp(), 'weather_temp': weather.temperature(), 'weather_pressure': weather.pressure(), 'light_r': lr, 'light_g': lg, 'light_b': lb, 'light_level': light.light() } w.writerow(data)
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 socket import time from envirophat import weather, leds , light HOST, PORT = '', 8888 listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((HOST, PORT)) listen_socket.listen(1) print 'Serving HTTP on port %s ...' % PORT while True: temperature = weather.temperature() pressure = weather.pressure() lightvalue = light.light() client_connection, client_address = listen_socket.accept() request = client_connection.recv(2048) first_line = request.split('\r\n') path = first_line[0].split(' ') path_clean = path[1].split('?') print request if path_clean[0] == "/pressure": humidi = "Pressure: %.2f hPa" % pressure http_response = \ "HTTP/1.1 200 OK\n"\ "Content-Type: text/xml\n\n"\ "<?xml version='1.0' encoding='UTF-8'?>"\