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 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 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 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 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 plugin_init(config): """ Initialise the plugin. Args: config: JSON configuration document for the South service configuration category Returns: handle: JSON object to be used in future calls to the plugin Raises: """ data = copy.deepcopy(config) magnetometer = motion.magnetometer() state["magx"] = magnetometer[0] state["magy"] = magnetometer[1] state["magz"] = magnetometer[2] state["light"] = "white" state["inverted"] = "No" return data
def idle_work(): global last_hf_time, last_lf_time now = time.time() if hf_enabled and (now - last_hf_time > hf_interval): mag = motion.magnetometer() accel = motion.accelerometer() h = motion.heading() print "X%0.10f,%0.10f,%0.10f,%d,%d,%0d,%0.2f".format( accel.x, accel.y, accel.z, mag.x, mag.y, mag.z, h) last_hf_time = now if lf_enabled and (now - last_lf_time > lf_interval): t = round(weather.temperature(), 2) p = round(weather.pressure(), 2) c = light.light() r = rgb[0] g = rgb[1] b = rgb[2] print "Y%0.2f,%0.2f,%d,%d,%d,,%d".format(t, p, c, r, g, b) last_lf_time = now
def process_mag_req(message): global mag_sub global mag_sub_rate global mag_sub_ticks if message_list[3] == 'CMD=READ': # Get the values s_x, s_y, s_z = motion.magnetometer() # format the message message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=MAG,X=%.2f,Y=%.2f,Z=%.2f,SENSOR_REP_END" % (s_x,s_y,s_z) 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: mag_sub_rate = 250 else: mag_sub_rate = rate mag_sub_ticks = 0 mag_sub = True # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=MAG,CMD=SUB_START,RATE=1000,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=MAG,STATUS=OK|BUSY,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=MAG,STATUS=OK,SENSOR_REP_END" elif message_list[3] == 'CMD=SUB_STOP': mag_sub = False mag_sub_rate = 0 mag_sub_ticks = 0 # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=MAG,CMD=SUB_STOP,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=MAG,STATUS=OK,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=MAG,STATUS=OK,SENSOR_REP_END" else: # unknown Command message = "SENSOR_REP," + message_list[1] + ",SUB_DEV=MAG,ERROR=UNKNOWN_CMD,SENSOR_REP_END" # Send reply back to client return message
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
from envirophat import light, weather, motion unit = 'hPa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) def write(line): sys.stdout.write(line) sys.stdout.flush() write("--- DJRFF pHAT Monitoring ---") try: while True: 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
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 """ time_stamp = utils.local_timestamp() data = list() try: moving = False rgb = light.rgb() magnetometer = motion.magnetometer() if abs(magnetometer[0] - state["magx"]) > _MAGNETOMETER_THRESHOLD: moving = True state["magx"] = magnetometer[0] state["magy"] = magnetometer[1] state["magz"] = magnetometer[2] accelerometer = [round(x, 1) for x in motion.accelerometer()] if moving and state["light"] != "red" and rgb[0] > rgb[ 1] + _LIGHT_THRESHOLD and rgb[0] > rgb[2] + _LIGHT_THRESHOLD: data.append({ 'asset': 'game/points', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "red": _RED_POINTS, "green": 0.0, "blue": 0.0, "accelerometer": 0.0, "lateral": 0.0, "flip": 0.0 } }) state["light"] = "red" leds.on() elif moving and state["light"] != "green" and rgb[1] > rgb[ 0] + _LIGHT_THRESHOLD and rgb[1] > rgb[2] + _LIGHT_THRESHOLD: data.append({ 'asset': 'game/points', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "red": 0.0, "green": _GREEN_POINTS, "blue": 0.0, "accelerometer": 0.0, "lateral": 0.0, "flip": 0.0 } }) state["light"] = "green" leds.on() elif moving and state["light"] != "blue" and rgb[2] > rgb[ 0] + _LIGHT_THRESHOLD and rgb[2] > rgb[1] + _LIGHT_THRESHOLD: data.append({ 'asset': 'game/points', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "red": 0.0, "green": 0.0, "blue": _BLUE_POINTS, "accelerometer": 0.0, "lateral": 0.0, "flip": 0.0 } }) state["light"] = "blue" leds.on() elif moving: state["light"] = "white" leds.off() if abs(accelerometer[0]) > 0.1: data.append({ 'asset': 'game/points', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "red": 0.0, "green": 0.0, "blue": 0.0, "accelerometer": abs(accelerometer[0] * _LINEAR_FACTOR), "lateral": 0.0, "flip": 0.0 } }) if abs(accelerometer[1]) > 0.1: data.append({ 'asset': 'game/points', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "red": 0.0, "green": 0.0, "blue": 0.0, "accelerometer": 0.0, "lateral": abs(accelerometer[1] * _LATERAL_FACTOR), "flip": 0.0 } }) if state["inverted"] == "No" and accelerometer[2] < -0.2: data.append({ 'asset': 'game/points', 'timestamp': time_stamp, 'key': str(uuid.uuid4()), 'readings': { "red": 0.0, "green": 0.0, "blue": 0.0, "accelerometer": 0.0, "lateral": 0.0, "flip": _FLIP_PENALTY } }) state["inverted"] = "Yes" elif accelerometer[2] > 0.2: state["inverted"] = "No" except (Exception, RuntimeError) as ex: _LOGGER.exception("IoT Lab Game exception: {}".format(str(ex))) raise ex else: _LOGGER.debug("IoT Lab Game reading: {}".format(json.dumps(data))) return data
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
def getMagn(): return motion.magnetometer()
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)
def magnet(self): try: magnet = motion.magnetometer() return {"x": magnet[0], "y": magnet[1], "z": magnet[2]} except: Enviro.logger.debug('Could not get data from magnetometer')
def get(self): #sensorlist holds all the data fragments to be handed to plars. sensorlist = [] #timestamp for this sensor get. timestamp = time.time() if configure.bme: self.bme_temp.set(self.bme.temperature, timestamp) self.bme_humi.set(self.bme.humidity, timestamp) self.bme_press.set(self.bme.pressure, timestamp) self.bme_voc.set(self.bme.gas / 1000, timestamp) sensorlist.extend( (self.bme_temp, self.bme_humi, self.bme_press, self.bme_voc)) if configure.sensehat: magdata = sense.get_compass_raw() acceldata = sense.get_accelerometer_raw() self.sh_temp.set(sense.get_temperature(), timestamp) self.sh_humi.set(sense.get_humidity(), timestamp) self.sh_baro.set(sense.get_pressure(), timestamp) self.sh_magx.set(magdata["x"], timestamp) self.sh_magy.set(magdata["y"], timestamp) self.sh_magz.set(magdata["z"], timestamp) self.sh_accx.set(acceldata['x'], timestamp) self.sh_accy.set(acceldata['y'], timestamp) self.sh_accz.set(acceldata['z'], timestamp) sensorlist.extend((self.sh_temp, self.sh_baro, self.sh_humi, self.sh_magx, self.sh_magy, self.sh_magz, self.sh_accx, self.sh_accy, self.sh_accz)) if configure.pocket_geiger: data = self.radiation.status() rad_data = float(data["uSvh"]) # times 100 to convert to urem/h self.radiat.set(rad_data * 100, timestamp) sensorlist.append(self.radiat) if configure.amg8833: data = numpy.array(amg.pixels) high = numpy.max(data) low = numpy.min(data) self.amg_high.set(high, timestamp) self.amg_low.set(low, timestamp) sensorlist.extend((self.amg_high, self.amg_low)) if configure.envirophat: self.rgb = light.rgb() self.analog_values = analog.read_all() self.mag_values = motion.magnetometer() self.acc_values = [round(x, 2) for x in motion.accelerometer()] self.ep_temp.set(weather.temperature(), timestamp) self.ep_colo.set(light.light(), timestamp) self.ep_baro.set(weather.pressure(unit='hpa'), timestamp) self.ep_magx.set(self.mag_values[0], timestamp) self.ep_magy.set(self.mag_values[1], timestamp) self.ep_magz.set(self.mag_values[2], timestamp) self.ep_accx.set(self.acc_values[0], timestamp) self.ep_accy.set(self.acc_values[1], timestamp) self.ep_accz.set(self.acc_values[2], timestamp) sensorlist.extend((self.ep_temp, self.ep_baro, self.ep_colo, self.ep_magx, self.ep_magy, self.ep_magz, self.ep_accx, self.ep_accy, self.ep_accz)) # provides the basic definitions for the system vitals sensor readouts if configure.system_vitals: if not configure.pc: f = os.popen( "cat /sys/class/thermal/thermal_zone0/temp").readline() t = float(f[0:2] + "." + f[2:]) else: t = float(47) # update each fragment with new data and mark the time. self.cputemp.set(t, timestamp) self.cpuperc.set(float(psutil.cpu_percent()), timestamp) self.virtmem.set( float(psutil.virtual_memory().available * 0.0000001), timestamp) self.bytsent.set( float(psutil.net_io_counters().bytes_recv * 0.00001), timestamp) self.bytrece.set( float(psutil.net_io_counters().bytes_recv * 0.00001), timestamp) if self.generators: self.sinewav.set(float(self.sin_gen() * 100), timestamp) self.tanwave.set(float(self.tan_gen() * 100), timestamp) self.coswave.set(float(self.cos_gen() * 100), timestamp) self.sinwav2.set(float(self.sin2_gen() * 100), timestamp) # load the fragments into the sensorlist sensorlist.extend((self.cputemp, self.cpuperc, self.virtmem, self.bytsent, self.bytrece)) if self.generators: sensorlist.extend( (self.sinewav, self.tanwave, self.coswave, self.sinwav2)) configure.max_sensors[0] = len(sensorlist) if len(sensorlist) < 1: print("NO SENSORS LOADED") return sensorlist
leds.on() ingestUrl = os.getenv('INGEST_URL') unit = 'hPa' # Pressure unit, can be either hPa (hectopascals) or Pa (pascals) reading = {} 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)
#!/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 sys import time from envirophat import weather, leds, light, motion unit = 'hPa' try: while True: rgb = light.rgb() motion_magnetometer = motion.magnetometer() temperature = weather.temperature() temp = "Temp:{0: .2f}c".format(temperature) write(temp) time.sleep(0.1) except KeyboardInterrupt: pass
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
import time from envirophat import light, motion, weather, leds from google.cloud import firestore client = firestore.Client() collection = client.collection(u'readings') document = collection.document(time.time()) def rgb(): leds.on() result = light.rgb() leds.off() return result document.set({ u'light': light.light(), u'colour': rgb(), u'accelerometer': motion.accelerometer(), u'heading': motion.heading(), u'magnetometer': motion.magnetometer(), u'temperature': weather.temperature(), u'pressure': weather.pressure() })
#!/usr/bin/env python import time from envirophat import light, motion, weather, analog, leds 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)
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
import time from envirophat import light, weather, motion, analog def write(line): sys.stdout.write(line) sys.stdout.flush() write("--- Enviro pHAT Monitoring ---") try: while True: rgb = light.rgb() analog_values = analog.read_all() mag_values = motion.magnetometer() acc_values = [round(x,2) for x in motion.accelerometer()] output = """ Temp: {t}c Pressure: {p}Pa Light: {c} RGB: {r}, {g}, {b} Heading: {h} Magnetometer: {mx} {my} {mz} Accelerometer: {ax}g {ay}g {az}g Analog: 0: {a0}, 1: {a1}, 2: {a2}, 3: {a3} """.format( t = round(weather.temperature(),2), p = round(weather.pressure(),2),
def readMagnetometer(): magneticField = motion.magnetometer() print "magnetic field value = ", magneticField return magneticField