def show_altitude(): # Makes sure scrollphat buffer is clear sphd.clear() # Altitude value is fetched from weather module altitudevalue = weather.altitude(qnh=1032) # If statement controls if speach output will say "below" or "above" sea level if (altitudevalue <= 0): sealevel = " meters below sea level" elif (altitudevalue >= 1): sealevel = " meters above sea level" # Uses say_value() to speak the current atititude speakaltitude = ("You are roughly " + str(int(altitudevalue)) + sealevel) print(speakaltitude) say_value(x=speakaltitude) # Writes the current sphd.write_string("Altitude: " + str(int(altitudevalue)) + "m", 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 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 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 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 writedata(): with open(folder + 'meta.csv', 'a') as meta: writer = csv.writer(meta) timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) altitude = round(weather.altitude() + 90, 2) temperature = round(weather.temperature(), 2) heading = motion.heading() accx = round(motion.accelerometer()[0], 2) accy = round(motion.accelerometer()[1], 2) accz = round(motion.accelerometer()[2], 2) red = light.rgb()[0] green = light.rgb()[1] blue = light.rgb()[2] newrow = [ "{:04}".format(index), timestamp, altitude, temperature, red, green, blue, heading, accx, accy, accz ] print newrow writer.writerow(newrow)
def _get_data(): light_values = { 'sensor_type': 'TCS3472', 'level': light.light(), **dict(zip(["red", "green", "blue"], light.rgb())) } weather_values = { 'sensor_type': 'BMP280', 'altitude': weather.altitude(), # meters 'pressure': round(weather.pressure("Pa"), 2), # pascals 'temperature': round(weather.temperature(), 2) # celcius } motion_values = { 'sensor_type': 'LSM303D', **dict( zip(["acceleration_x", "acceleration_y", "acceleration_z"], [ round(x, 2) for x in motion.accelerometer() ])), # x, y and z acceleration as a vector in Gs. 'heading': motion.heading(), **dict( zip(["magnetic_field_x", "magnetic_field_y", "magnetic_field_z"], motion.magnetometer())) # raw x, y and z magnetic readings as a vector. } analog_values = { 'sensor_type': 'ADS1015', **{"channel_%i" % k: v for k, v in enumerate(analog.read_all())} } data = { 'created_at': datetime.utcnow().isoformat() + 'Z', 'light': light_values, 'weather': weather_values, 'motion': motion_values, 'analog': analog_values } return data
def readdata(): leds.on() rgb = light.rgb() analog_values = analog.read_all() mag_values = motion.magnetometer() acc_values = [round(x, 2) for x in motion.accelerometer()] ts = time.time() timestamp = datetime.datetime.fromtimestamp(ts).strftime( '%Y-%m-%d %H:%M:%S') data = {} data['altitude'] = weather.altitude() data['temperature'] = weather.temperature() data['pressure'] = weather.pressure(unit=unit) data['lux'] = light.light() data['red'] = rgb[0] data['green'] = rgb[1] data['blue'] = rgb[2] data['heading'] = motion.heading() data['timestamp'] = timestamp leds.off() return data
def get_data(): data = {'time': datetime.now()} if use_motion: # more efficiently extract values motion.heading() heading = motion._tilt_heading_degrees mag_values = motion._mag acc_values = motion._accel data['heading'] = heading data['magnetometer'] = [mag_values[0], mag_values[1], mag_values[2]] data['accelerometer'] = [acc_values[0], acc_values[1], acc_values[2]] if use_light: # more efficiently extract RGB and light value CH_CLEAR = 3 rgbc = light.raw() light_value = rgbc[CH_CLEAR] light_scaled = tuple([float(x) / rgbc[CH_CLEAR] for x in rgbc]) if rgbc[CH_CLEAR] > 0 else (0, 0, 0) rgb = [int(x * 255) for x in light_scaled][:CH_CLEAR] data['light'] = light_value data['rgb'] = rgb if use_weather: data['unit'] = unit data['altitude'] = weather.altitude(qnh=QNH) data['temperature'] = weather.temperature() data['pressure'] = weather.pressure(unit=unit) if use_analog: analog_values = analog.read_all() data['analog'] = [analog_values[0], analog_values[1], analog_values[2]] return data
#!/usr/bin/env python import sys import time import requests import json from envirophat import light, weather, motion, analog unit = 'hPa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) url = 'http://192.168.1.5/api/sensors/' headers = {'content-type': 'application/json'} while True: payload = { 'temperature': weather.temperature(), 'pressure': weather.pressure(unit=unit), 'altitude': weather.altitude(), 'light': light.light(), 'light_rgb': light.rgb(), } data = json.dumps(payload) print(data) response = requests.post(url, data=data, headers=headers) print(response) time.sleep(5)
def process_sensor_subs(tick): global bmp_sub global bmp_sub_rate global bmp_sub_ticks global lux_sub global lux_sub_rate global lux_sub_ticks global accel_sub global accel_sub_rate global accel_sub_ticks global heading_sub global heading_sub_rate global heading_sub_ticks global mag_sub global mag_sub_rate global mag_sub_ticks global analog_sub global analog_sub_rate global analog_sub_ticks if bmp_sub == True: bmp_sub_ticks += 250 if bmp_sub_ticks >= bmp_sub_rate: # # Get the values # temp = round(weather.temperature(),2) pressure = round(weather.pressure(),2) altitude = round(weather.altitude(),2) time_string = time.time() # # format the message # message = "SENSOR_PUB,DEV=ENVIRO_PHAT,SUB_DEV=BMP,TIME=%s,TEMP=%.2f,PRES=%.2f,ALT=%.2f,SENSOR_PUB_END" % (time_string,temp,pressure,altitude) pub_socket.send_string(message) bmp_sub_ticks = 0 if lux_sub == True: lux_sub_ticks += 250 if lux_sub_ticks >= lux_sub_rate: # # Get the values # s_red, s_green, s_blue = light.rgb() s_lux = light.light() time_string = time.time() # format the message message = "SENSOR_PUB,DEV=ENVIRO_PHAT,SUB_DEV=LUX,TIME=%s,RED=%.2f,GREEN=%.2f,BLUE=%.2f,LUX=%.2f,SENSOR_PUB_END" % (time_string,s_red,s_green,s_blue, s_lux) pub_socket.send_string(message) lux_sub_ticks = 0 if accel_sub == True: accel_sub_ticks += 250 if accel_sub_ticks >= accel_sub_rate: # # Get the values # s_x, s_y, s_z = motion.accelerometer() time_string = time.time() # format the message message = "SENSOR_PUB,DEV=ENVIRO_PHAT,SUB_DEV=ACCEL,TIME=%s,X=%.2f,Y=%.2f,Z=%.2f,SENSOR_PUB_END" % (time_string,s_x,s_y,s_z) pub_socket.send_string(message) accel_sub_ticks = 0 if heading_sub == True: heading_sub_ticks += 250 if heading_sub_ticks >= heading_sub_rate: # # Get the values # s_heading = motion.heading() time_string = time.time() # format the message message = "SENSOR_PUB,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,TIME=%s,HEADING=%.2f,SENSOR_PUB_END" % (time_string,s_heading) pub_socket.send_string(message) heading_sub_ticks = 0 if mag_sub == True: mag_sub_ticks += 250 if mag_sub_ticks >= mag_sub_rate: # # Get the values # s_x, s_y, s_z = motion.magnetometer() time_string = time.time() # format the message message = "SENSOR_PUB,DEV=ENVIRO_PHAT,SUB_DEV=MAG,TIME=%s,X=%.2f,Y=%.2f,Z=%.2f,SENSOR_PUB_END" % (time_string,s_x,s_y,s_z) pub_socket.send_string(message) mag_sub_ticks = 0 if analog_sub == True: analog_sub_ticks += 250 if analog_sub_ticks >= analog_sub_rate: # # Get the values # s_a1, s_a2, s_a3, s_a4 = analog.read_all() time_string = time.time() # format the message message = "SENSOR_PUB,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,TIME=%s,A1=%.2f,A2=%.2f,A3=%.2f,A4=%.2f,SENSOR_PUB_END" % (time_string,s_a1,s_a2,s_a3,s_a4) pub_socket.send_string(message) analog_sub_ticks = 0
reading['dev_eui'] = 'demo_device_2' reading['type'] = 'jp2002' reading['timestamp'] = datetime.datetime.utcnow().replace( microsecond=0).isoformat() r, g, b = light.rgb() ax, ay, az = motion.accelerometer() mx, my, mz = motion.magnetometer() reading['light'] = light.light() reading['rgb'] = '#{0:02x}{1:02x}{2:02x}'.format(r, g, b) reading['magnetometer'] = str(mx) + 'mx ' + str(my) + 'my ' + str(mz) + 'mz' reading['accelerometer'] = str(ax) + 'ax ' + str(ay) + 'ay ' + str(az) + 'az' reading['altitude'] = '{0:.2f}'.format(weather.altitude()) reading['temperature'] = '{0:.2f}'.format(weather.temperature()) reading['pressure'] = '{0:.2f}'.format(weather.pressure(unit=unit)) try: leds.off() result = requests.post(ingestUrl, data=json.dumps(reading)) leds.on() time.sleep(0.5) print(result) leds.off() except: print 'Network error' print(json.dumps(reading))
def home(): temperature = weather.temperature() *1.8 + 32 pressure = weather.pressure(unit="Pa") altitude = weather.altitude(qnh=1020) * 3.28084 return render_template("home.html", temperature=temperature, pressure=pressure, altitude=altitude)
interval = 12 #Interval in seconds in which the sensor data will be read and written into the database con = lite.connect('assets/db/enviro.db') try: while True: timestamp = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") lux = light.light() leds.on() rgb = str(light.rgb())[1:-1].replace(' ', '') leds.off() acc = str(motion.accelerometer())[1:-1].replace(' ', '') heading = motion.heading() temp = (weather.temperature() - 10) press = weather.pressure() altitude = weather.altitude() moisture = analog.read(0) writeout = ( (timestamp, lux, rgb, acc, heading, temp, press, altitude, moisture), ) with con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS " + plant_type + " (Date DATETIME, Brightness INT, LightColor TEXT, Motion FLOAT, Heading INT, Temperature FLOAT, Pressure FLOAT, Altitude INT, Moisture FLOAT)") cur.executemany("INSERT INTO " + plant_type + " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", writeout) time.sleep(interval) finally:
def plugin_poll(handle): """ Extracts data from the sensor and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a sensor reading in a JSON document, as a Python dict, if it is available None - If no reading is available Raises: Exception """ unit = 'hPa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) time_stamp = utils.local_timestamp() data = list() asset_prefix = handle['assetNamePrefix']['value'] try: if handle['rgbSensor']['value'] == 'true': rgb = light.rgb() data.append({ 'asset': '{}{}'.format(asset_prefix, handle['rgbSensorName']['value']), 'timestamp': time_stamp, 'readings': { "r": rgb[0], "g": rgb[1], "b": rgb[2] } }) if handle['magnetometerSensor']['value'] == 'true': magnetometer = motion.magnetometer() data.append({ 'asset': '{}{}'.format(asset_prefix, handle['magnetometerSensorName']['value']), 'timestamp': time_stamp, 'readings': { "x": magnetometer[0], "y": magnetometer[1], "z": magnetometer[2] } }) if handle['accelerometerSensor']['value'] == 'true': accelerometer = [round(x, 2) for x in motion.accelerometer()] data.append({ 'asset': '{}{}'.format(asset_prefix, handle['accelerometerSensorName']['value']), 'timestamp': time_stamp, 'readings': { "x": accelerometer[0], "y": accelerometer[1], "z": accelerometer[2] } }) if handle['weatherSensor']['value'] == 'true': altitude = weather.altitude() temperature = weather.temperature() pressure = weather.pressure(unit=unit) data.append({ 'asset': '{}{}'.format(asset_prefix, handle['weatherSensorName']['value']), 'timestamp': time_stamp, 'readings': { "altitude": altitude, "temperature": temperature, "pressure": pressure, } }) except Exception as ex: _LOGGER.exception("Enviro pHAT exception: {}".format(str(ex))) raise ex return data
def plugin_poll(handle): """ Extracts data from the sensor and returns it in a JSON document as a Python dict. Available for poll mode only. Args: handle: handle returned by the plugin initialisation call Returns: returns a sensor reading in a JSON document, as a Python dict, if it is available None - If no reading is available Raises: DataRetrievalError """ unit = 'hPa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) time_stamp = str(datetime.datetime.now(tz=datetime.timezone.utc)) data = list() try: rgb = light.rgb() magnetometer = motion.magnetometer() accelerometer = [round(x, 2) for x in motion.accelerometer()] altitude = weather.altitude( ) # Supply your local qnh for more accurate readings temperature = weather.temperature() pressure = weather.pressure(unit=unit) data.append({ 'asset': 'EnviroHat/rgb', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "r": rgb[0], "g": rgb[1], "b": rgb[2] } }) data.append({ 'asset': 'EnviroHat/magnetometer', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "x": magnetometer[0], "y": magnetometer[1], "z": magnetometer[2] } }) data.append({ 'asset': 'EnviroHat/accelerometer', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "x": accelerometer[0], "y": accelerometer[1], "z": accelerometer[2] } }) data.append({ 'asset': 'EnviroHat/weather', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "altitude": altitude, "pressure": pressure, "temperature": temperature } }) except (Exception, RuntimeError, pexpect.exceptions.TIMEOUT) as ex: _LOGGER.exception("EnviroHat exception: {}".format(str(ex))) raise exceptions.DataRetrievalError(ex) _LOGGER.debug("EnviroHat reading: {}".format(json.dumps(data))) return data
def get_cpu_temperature(): process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE) output, _error = process.communicate() return float(output[output.index('=') + 1:output.rindex("'")]) def adjust_temperature(sensor_temp): cpu_temp_c = get_cpu_temperature() temp_c_cal = sensor_temp - ((cpu_temp_c - sensor_temp) / 1.3) return temp_c_cal weather.altitude(qnh=1020) while True: temp = weather.temperature() temp = adjust_temperature(temp) pressure = weather.pressure(unit='hPa') print(temp, pressure) req = requests.post('http://192.168.1.23:8888/temperature', json={ 'temp': temp, 'pressure': pressure }) print('status:', req.status_code) time.sleep(60)
def getAltd(qnh = None): if qnh is None: return weather.altitude() else: return weather.altitude(qnh)
# FSYS - Alexander St. # This Flight System has the following purpose: # Supplying pressure, accelaration and heading data from Enviro pHAT to a file from envirophat import motion, weather from datetime import datetime t = open('FlightRecord', 'a') while True: t.write("\n " + str(datetime.now().time())) t.write("\n " + str(weather.pressure())) t.write("\n " + str(weather.altitude())) t.write("\n " + str(motion.accelerometer())) t.write("\n " + str(motion.heading())) t.write("\n ") t.close()
def getFrame(): try: altArray.append(round(weather.altitude(QNH), 1)) except: altArray.append(0) #update filter global k1 global k2 global k3 global k4 global k5 k2 += k3 k5 = k2 / (k2 + k4) k1 += (k5 * (altArray[-1] - k1)) k2 *= (1 - k5) corrAltArray.append(round(k1, 0)) raw_data = { "time": time.time(), "flight_mode": flightMode, "squib_deployed": squibDeployed, "QNH": QNH } try: raw_data["a_x"] = round(motion.accelerometer().x, roundOff) except: raw_data["a_x"] = 0.0 try: raw_data["a_y"] = round(motion.accelerometer().y, roundOff) except: raw_data["a_y"] = 0.0 try: raw_data["a_z"] = round(motion.accelerometer().z, roundOff) except: raw_data["a_z"] = 0.0 try: raw_data["temp"] = round(weather.temperature(), roundOff) except: raw_data["temp"] = 0.0 try: raw_data["pressure"] = round(weather.pressure(), roundOff) except: raw_data["pressure"] = 0.0 try: raw_data["volt_b1"] = round(ina219A.getBusVoltage_V(), roundOff) except: raw_data["volt_b1"] = 0.0 try: raw_data["current_1"] = round(ina219A.getCurrent_mA(), roundOff) except: raw_data["current_1"] = 0.0 try: raw_data["volt_b2"] = round(ina219B.getBusVoltage_V(), roundOff) except: raw_data["volt_b2"] = 0.0 try: raw_data["current_2"] = round(ina219B.getCurrent_mA(), roundOff) except: raw_data["current_2"] = 0.0 try: raw_data["gps_lat"] = round(gpsd.fix.latitude, roundOff) except: raw_data["gps_lat"] = 0 try: raw_data["gps_lon"] = round(gpsd.fix.longitude, roundOff) except: raw_data["gps_lon"] = 0 try: raw_data["gps_alt"] = round(gpsd.fix.altitude, roundOff) except: raw_data["gps_alt"] = 0 try: raw_data["gps_spd"] = round(gpsd.fix.speed, roundOff) except: raw_data["gps_spd"] = 0 try: raw_data["mag_x"] = round(motion.magnetometer().x, roundOff) except: raw_data["mag_x"] = 0.0 try: raw_data["mag_y"] = round(motion.magnetometer().y, roundOff) except: raw_data["mag_y"] = 0.0 try: raw_data["mag_z"] = round(motion.magnetometer().z, roundOff) except: raw_data["mag_z"] = 0.0 raw_data["altP"] = corrAltArray[-1] for key in raw_data.keys(): if (type(raw_data[key]) is not float) and (type(raw_data[key]) is not int): raw_data[key] = 0 if (raw_data[key] != raw_data[key]): raw_data[key] = 0 frame.append(raw_data)
rgb = light.rgb() mag_values = motion.magnetometer() acc_values = [round(x, 2) for x in motion.accelerometer()] output = """ Temp: {t:.2f}c Pressure: {p:.2f}{unit} Altitude: {a:.2f}m Light: {c} RGB: {r}, {g}, {b} Heading: {h} Magnetometer: {mx} {my} {mz} Accelerometer: {ax}g {ay}g {az}g """.format( unit=unit, a=weather.altitude( ), # Supply your local qnh for more accurate readings t=weather.temperature(), p=weather.pressure(unit=unit), c=light.light(), r=rgb[0], g=rgb[1], b=rgb[2], h=motion.heading(), 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")
def readAltitude(qnh): altitude = weather.altitude(qnh) print "altitude value (m) = ", pressure return float(pressure)