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 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_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 process_analog_req(message): global analog_sub global analog_sub_rate global analog_sub_ticks if message_list[3] == 'CMD=READ': # Get the values s_a1, s_a2, s_a3, s_a4 = analog.read_all() # format the message message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,A1=%.2f,A2=%.2f,A3=%.2f,A4=%.2f,SENSOR_REP_END" % (s_a1,s_a2,s_a3,s_a4) 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: analog_sub_rate = 250 else: analog_sub_rate = rate analog_sub_ticks = 0 analog_sub = True # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,CMD=SUB_START,RATE=1000,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,STATUS=OK|BUSY,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,STATUS=OK,SENSOR_REP_END" elif message_list[3] == 'CMD=SUB_STOP': analog_sub = False analog_sub_rate = 0 analog_sub_ticks = 0 # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,CMD=SUB_STOP,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,STATUS=OK,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=ANALOG,STATUS=OK,SENSOR_REP_END" else: # unknown Command message = "SENSOR_REP," + message_list[1] + ",SUB_DEV=ANALOG,ERROR=UNKNOWN_CMD,SENSOR_REP_END" # Send reply back to client return message
def disp_OLED(): # Draw a black filled box to clear the image. draw.rectangle((0, 0, width, height), outline=0, fill=0) # Shell scripts for system monitoring from here : https://unix.stackexchange.com/questions/119126/command-to-display-memory-usage-disk-usage-and-cpu-load cmd = "hostname -I | cut -d\' \' -f1" IP = subprocess.check_output(cmd, shell=True) rgb = light.rgb() analog_values = analog.read_all() humidity, temp2 = Adafruit_DHT.read_retry(11, 17) #currentDT = datetime.datetime.now() #tm = currentDT.strftime("%m-%d-%y") # Days since watering d2 = datetime.datetime.strptime('1-1-18', '%m-%d-%y') d_diff = abs((datetime.datetime.now() - d2).days) t = int(weather.temperature() * 9 / 5.0 + 32) t2 = int((temp2 * 9 / 5.0 + 32)) hd = int(round(humidity, 0)) lgt = light.light() soil = int(((analog_values[0] * 100) / 434) * 100) # 128 x 32 draw.text((x, top), "Lst: " + str(d_diff), font=font, fill=255) draw.text((60, top), "Lgt: " + str(lgt), font=font, fill=255) draw.text((x, top + 8), "Tmp1: " + str(t), font=font, fill=255) draw.text((60, top + 8), "Tmp2: " + str(t2), font=font, fill=255) draw.text((x, top + 16), "Soil: " + str(soil), font=font, fill=255) draw.text((60, top + 16), "Humd: " + str(hd) + "%", font=font, fill=255) draw.text((x, top + 25), "IP: " + str(IP), font=font, fill=255) # Display image. disp.image(image) disp.display()
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 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
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
import sys 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() 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],
while GPIO.input(ECHO) == 0: pulse_start = time.time() while GPIO.input(ECHO) == 1: pulse_end = time.time() pulse_duration = (pulse_end - pulse_start) distance = pulse_duration * 17150 distance = round(distance, 2) if distance > 2 and distance < 400: # Check whether the distance is within range w, h = draw.textsize(str(distance)+"cm") draw_rotated_text(disp.buffer,str(distance - 0.5) + "cm", (120-w, 280), text_rotation, font, fill=(255, 255, 255)) else: w, h = draw.textsize("Out of range") draw_rotated_text(disp.buffer, "Out of range", (120 - w, 280), text_rotation, font,fill=(255, 0, 0)) mx, my, mz, mu = analog.read_all() w, h = draw.textsize("A1: "+str(mx)+" V") draw_rotated_text(disp.buffer, "A1 :"+str(mx)+" V", (120 - w, 180), text_rotation, font_mid, fill=(255, 0, 0)) w, h = draw.textsize("A2: "+str(my)+" V") draw_rotated_text(disp.buffer, "A2: "+str(my)+" V", (120 - w, 150), text_rotation, font_mid, fill=(255, 0, 0)) w, h = draw.textsize("A3: "+str(mz)+" V") draw_rotated_text(disp.buffer, "A3: " + str(mz)+" V", (120 - w, 120), text_rotation, font_mid, fill=(255, 0, 0)) w, h = draw.textsize("A4: "+str(mu)+" V") draw_rotated_text(disp.buffer, "A4: " + str(mu)+" V", (120 - w, 90), text_rotation, font_mid, fill=(255, 0, 0)) #sens_mag = motion.magnetometer() #Magnetometer: {mx} {my} {mz} #sens_mag = motion.magnetometer() #mx = mag_values[0] #my = mag_values[1] #mz = mag_values[2]
def read_analog(inp): if inp == 4: return analog.read_all() else: return analog.read(inp)
def analog(self): try: return analog.read_all() except: Enviro.logger.debug('Could not get analog 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 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