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 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 track(init_heading, i, motor, prev): acc = motion.accelerometer() heading = (motion.heading() + i) % 360 # handle tilt tilt = math.floor(90 * acc[0]) if tilt > 90: tilt = 90 elif tilt < -90: tilt = -90 if prev[0] is None or abs(tilt - prev[0]) > 3: motor.tilt(tilt) else: tilt = prev[0] # handle pan heading = heading - init_heading if heading < -90: heading = -90 elif heading > 90: heading = 90 if prev[1] is None or abs(heading - prev[1]) > .5: motor.pan(heading) else: heading = prev[1] return (tilt, heading)
def motion(self): try: return { "magnet": self.magnet(), "accelerometer": self.accel(), "heading": motion.heading() } except: Enviro.logger.debug('Could not get data from motion sensors')
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 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_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 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 getSensorData(): sensors = {} t = datetime.datetime.now() sensors["timestamp"] = str(t.strftime('%Y%m%d %H:%M')) sensors["device_name"] = "YOUR DEVICE NAME" sensors["city"] = 'YOUR CITY' sensors["lng"] = 'YOUR LONGITUDE' sensors["lat"] = 'YOUR LATITUDE' sensors["lux"] = light.light() leds.on() sensors["rgb"] = str(light.rgb())[1:-1].replace(' ', '') leds.off() sensors["accel"] = str(motion.accelerometer())[1:-1].replace(' ', '') sensors["heading"] = motion.heading() sensors["temperature"] = weather.temperature() sensors["pressure"] = weather.pressure() return sensors
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 process_heading_req(message): global heading_sub global heading_sub_rate global heading_sub_ticks if message_list[3] == 'CMD=READ': # Get the values s_heading = motion.heading() # format the message message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,HEADING=%.2f,SENSOR_REP_END" % (s_heading) 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: heading_sub_rate = 250 else: heading_sub_rate = rate heading_sub_ticks = 0 heading_sub = True # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,CMD=SUB_START,RATE=1000,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,STATUS=OK|BUSY,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,STATUS=OK,SENSOR_REP_END" elif message_list[3] == 'CMD=SUB_STOP': heading_sub = False heading_sub_rate = 0 heading_sub_ticks = 0 # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,CMD=SUB_STOP,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,STATUS=OK,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=HEADING,STATUS=OK,SENSOR_REP_END" else: # unknown Command message = "SENSOR_REP," + message_list[1] + ",SUB_DEV=HEADING,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, motion, weather, leds # define credentials in secret.py file # ADAFRUIT_IO_KEY = "" from secret import * # Create an instance of the REST client. aio = Client(ADAFRUIT_IO_USER, ADAFRUIT_IO_KEY) print('Start uploading to Adafruit IO') try: while True: now = datetime.utcnow() lux = light.light() leds.on() r,g,b = light.rgb() leds.off() acc = motion.accelerometer() heading = motion.heading() temp = weather.temperature() press = weather.pressure(unit='hPa') aio.send('env1-lux', lux) aio.send('env1-temp', temp) aio.send('env1-press', press) print("Posted to Adafruit IO: {:.2f}, {:.2f}, {:.2f}".format(lux, temp, press)) time.sleep(60)#yyyy-MM-dd HH:mm:ss except KeyboardInterrupt: leds.off() print('Stopped uploading to Adafruit IO')
def compass(): return (motion.heading() - north) % 360
def compass_calibration(): print "Point the Enviro pHAT with the text the right way up (relative to you) towards north and press ENTER" north = motion.heading()
from envirophat import motion from envirophat import light from envirophat import weather from envirophat import leds import time leds.off() while True: x, y, z = motion.accelerometer() r, g, b = light.rgb() results = { "lightR": r, "lightG": g, "lightB": b, "lightLevel": light.light(), "temperature": weather.temperature(), "pressure": weather.pressure(), "motionX": x, "motionY": y, "motionZ": z, "heading": motion.heading() } print(results) time.sleep(0.5)
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 = template.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(), a0=analog_values[0], 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], cnt=counter, conn_type=connect_type, device_name=device_name, rest_url=rest_url, ws_url=ws_url
#!/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)
def read_enviro_heading(): corr_heading = (motion.heading() - 10) % 360 ## verify North correction , 10 is a placeholder e_heading = corr_heading return e_heading
leds.on() rgb = str(light.rgb())[1:-1].replace(' ', '') leds.off() acc = str(motion.accelerometer())[1:-1].replace(' ', '') device_uuid = 'f9d84855-aa86-4f9d-b773-effc1029f700' session = boto3.Session(profile_name=PROFILE, region_name=REGION) client = session.client('dynamodb') r = client.put_item( TableName=TABLE, Item={ 'device_uuid': {'S': device_uuid}, 'timestamp': {'S': datetime.now().isoformat()}, 'account': {'S': args.account}, 'location': {'S': args.location}, 'data': {'M': { 'light': {'S': str(light.light())}, 'rgb': {'S': rgb}, 'motion': {'S': acc}, 'heading': {'S': str(motion.heading())}, 'temp': {'S': str(weather.temperature())}, 'pressure': {'S': str(weather.pressure())}, } } } ) print(r)
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
from envirophat import motion, analog, leds import time from i2clibraries import i2c_hmc5883l # INITIALISATION START compass = i2c_hmc5883l.i2c_hmc5883l(1) compass.setContinuousMode() compass.setDeclination(1, 47) # INITIALISATION DONE try: print('started compass') while True: (heading, minutes) = compass.getHeading() compareHeading = motion.heading() print(heading, compareHeading) time.sleep(.2) except KeyboardInterrupt: leds.off()
def getHead(): return motion.heading()
# 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()
#!/usr/bin/python3 from envirophat import leds, motion, light, weather, analog import time import datetime leds.on() print('{:%Y-%m-%d %H:%M:%S}'.format(datetime.datetime.now()), ",", light.light(), ",", light.rgb(), ",", weather.temperature(), ",", weather.pressure(unit='kPa'), ",", motion.heading(), ",", analog.read(0), ",", analog.read(1), ",", analog.read(2), ",", analog.read(3)) leds.off()
default='Unkown', help='Location to descibe where the Pi is') args = parser.parse_args() leds.on() rgb = str(light.rgb())[1:-1].replace(' ', '') leds.off() acc = str(motion.accelerometer())[1:-1].replace(' ', '') data = { 'location': args.location, 'time': datetime.utcnow().isoformat(), 'light': light.light(), 'rgb': rgb, 'motion': acc, 'heading': motion.heading(), 'temp': weather.temperature(), 'pressure': weather.pressure(), } # json_data = json.dumps(data) # print(json_data) client = MongoClient(MONGO_DB_URL) try: result = client.admin.command("ismaster") print("Connected to Mongo") except ConnectionFailure as e: print(e)
#!/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)
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)) time.sleep(1) except KeyboardInterrupt: pass
#!/usr/bin/python3 from envirophat import leds, motion, light, weather, analog import time leds.on() print("Starting collection") print("Light sensor = ", light.light()) print("RGB Ligt Sensor = ", light.rgb()) print("Temperature from pHat = ", weather.temperature()) print("Pressure from pHat = ", weather.pressure(unit='kPa')) print("Compass heading = ", motion.heading()) print("Analog sensor 0= ", analog.read(0)) print("Analog sensor 1= ", analog.read(1)) print("Analog sensor 2= ", analog.read(2)) print("Analog sensor 3= ", analog.read(3)) leds.off() input("Press Enter to continue ....")