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 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 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 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 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 get_light(): """light""" global light data = { "light": light.light(), "rgb": light.rgb() } return jsonify(data)
def color_sensing(accurate = True): if(accurate): leds.on() time.sleep(0.5) color = light.rgb() time.sleep(0.5) if(accurate): leds.off() return color
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 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 run(): while True: try: temperature = round(weather.temperature() - config.TEMP_CALIBRATION, 2) pressure = round(weather.pressure() - config.PRESSURE_CALIBRATION, 2) light_intensity = light.light() r, g, b = light.rgb() payload = { 'location': config.LOCATION_NAME, 'poll_frequency_in_seconds': config.POLL_FREQUENCY, 'temperature': temperature, 'temperature_units': 'c', 'pressure': pressure, 'pressure_units': 'hPA', 'light_intensity': light_intensity, 'light_colour': '%s %s %s' % (r, g, b), 'date_polled': datetime.now() } output = """ Location: {location} Temperature: {temperature} c Pressure: {pressure} hPA Light Intensity: {light_intensity} Light RGB: r: {r}, g: {g}, b: {b} """.format( location=config.LOCATION_NAME, temperature=temperature, pressure=pressure, light_intensity=light_intensity, r=r, g=g, b=b ) print(output) if config.SUBMIT_TO_ENDPOINT: headers = {"Authorization": "Bearer %s" % config.WEATHER_ENDPOINT_AUTH_TOKEN} requests.post(config.WEATHER_ENDPOINT_URL, json=json.dumps(payload), headers=headers) except Exception as e: print("Error getting sense data: %s" % e) time.sleep(config.POLL_FREQUENCY)
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 process_light_req(message): global lux_sub global lux_sub_rate global lux_sub_ticks if message_list[3] == 'CMD=READ': # Get the values s_red, s_green, s_blue = light.rgb() s_lux = light.light() # format the message message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LUX,RED=%.2f,GREEN=%.2f,BLUE=%.2f,LUX=%.2f,SENSOR_REP_END" % (s_red,s_green,s_blue, s_lux) 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: lux_sub_rate = 250 else: lux_sub_rate = rate lux_sub_ticks = 0 lux_sub = True # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=LUX,CMD=SUB_START,RATE=1000,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LUX,STATUS=OK|BUSY,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LUX,STATUS=OK,SENSOR_REP_END" elif message_list[3] == 'CMD=SUB_STOP': lux_sub = False lux_sub_rate = 0 lux_sub_ticks = 0 # SENSOR_REQ,DEV=ENVIRO_PHAT,SUB_DEV=LUX,CMD=SUB_STOP,SENSOR_REQ_END # SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LUX,STATUS=OK,SENSOR_REP_END message = "SENSOR_REP,DEV=ENVIRO_PHAT,SUB_DEV=LUX,STATUS=OK,SENSOR_REP_END" else: # unknown Command message = "SENSOR_REP," + message_list[1] + ",SUB_DEV=LUX,ERROR=UNKNOWN_CMD,SENSOR_REP_END" # Send reply back to client return message
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)
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 "M%0.10f,%0.10f,%0.10f,%d,%d,%d,%0.2f" % ( 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): rgb = light.rgb() t = round(weather.temperature(), 2) p = round(weather.pressure(), 2) c = light.light() r = rgb[0] g = rgb[1] b = rgb[2] print "E%0.2f,%0.2f,%d,%d,%d,%d" % (t, p, c, r, g, b) last_lf_time = now
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 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
#!/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)
try: while True: current_temp = weather.temperature() print("Current Temperature is", current_temp) #time.sleep(8) #Sense any movement# readings.append(motion.accelerometer().z) readings = readings[-4:] z = sum(readings) / len(readings) time.sleep(0.3) #read the amount of light# amount_of_light = light.light() r, g, b = light.rgb() print("Amount of light", amount_of_light) print("Colour", r, g, b) time.sleep(1) """Check for motion or movement""" if last_z > 0 and abs(z - last_z) > threshold: print("Motion Detected!!!") catch_a_ghost() leds.on() last_z = z time.sleep(0.01) leds.off() """Check for a change in temperature""" if current_temp - start_temp > 5:
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
#!/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 get_data_points(): temp_cpu = get_cpu_temp() cpu_usage = get_cpu_usage() temperature = weather.temperature() pressure = round(weather.pressure(), 2) light_val = light.light() rgb = light.rgb() iso = datetime.datetime.now() iso = iso - datetime.timedelta(hours=2) iso = iso.isoformat() 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": "cpu_usage", "tags": {"host": host}, "time": iso, "fields": { "value": cpu_usage, } }, { "measurement": "ambient_light", "tags": {"host": host}, "time": iso, "fields": { "value": light_val, } }, { "measurement": "rgb_sensor", "tags": {"colour": "Red"}, "time": iso, "fields": { "value": rgb[0], } }, { "measurement": "rgb_sensor", "tags": {"colour": "Green"}, "time": iso, "fields": { "value": rgb[1], } }, { "measurement": "rgb_sensor", "tags": {"colour": "Blue"}, "time": iso, "fields": { "value": rgb[2], } }, { "measurement": "ambient_pressure", "tags": {"host": host}, "time": iso, "fields": { "value": pressure, } } ] return json_body
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
wind_dir_deg real, lux_indoor real, rgb_indoor text, temp_indoor real, pressure real );''') while True: line = sys.stdin.readline() if not line: break try: data = json.loads(line) data['time'] = str(time.time()).split('.')[0] data['lux_indoor'] = light.light() leds.on() data['rgb_indoor'] = str(light.rgb())[1:-1].replace(' ', '') leds.off() data['temp_indoor'] = weather.temperature() data['pressure'] = weather.pressure() logger.debug(json.dumps(data)) cursor.execute( "insert into weather values(:time, :rain_mm, :wind_max_m_s, :wind_avg_m_s, :humidity, :temperature_C, :wind_dir_deg, :lux_indoor, :rgb_indoor, :temp_indoor, :pressure)", data) except KeyError: pass except ValueError: pass
#! /usr/bin/env python3 from prometheus_client import start_http_server, Summary, Gauge import random import time from envirophat import weather, light temp_gauge = Gauge('kitchen_temp', 'Temperature in the kitchen') light_gauge = Gauge('kitchen_light', 'Light in the kitchen', ['color']) pressure_gauge = Gauge('kitchen_pressure', 'Pressure in the kitchen') # Unused envirophat functions # motion.magnetometer() # motion.heading() if __name__ == '__main__': start_http_server(8000) while True: temp_gauge.set(round(weather.temperature(), 1)) light_gauge.labels('red').set(light.rgb()[0]) light_gauge.labels('green').set(light.rgb()[1]) light_gauge.labels('blue').set(light.rgb()[2]) pressure_gauge.set(round(weather.pressure(), 1)) time.sleep(5)
#!/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 getRGB(): ## returns list: Red, Green, Blue ## values 0 - 255 return light.rgb()
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],
#!/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()
if temp_output != -1: temp_string = lines[1].strip()[temp_output + 2:] temp_c = float(temp_string) / 1000.0 return temp_c conn = sqlite3.connect('server.db') c = conn.cursor() GPIO.setmode(GPIO.BCM) GPIO.setup(22, GPIO.OUT) GPIO.output(22, GPIO.HIGH) try: lux = light.light() rgb = str(light.rgb())[1:-1].replace(' ', '') temp = int(weather.temperature()) press = int(weather.pressure()) water1 = analog.read(0) waterTemp = read_temp() if water1 < 0.5: r = requests.get('http://127.0.0.1:5000/relay/1/0') else: r = requests.get('http://127.0.0.1:5000/relay/1/1') datavals = [('light', lux), ('rgb', rgb), ('temp', temp), ('press', press), ('water1', water1), ('watertemp', waterTemp)] c.executemany('INSERT INTO sensor_log (sensor, value) VALUES (?, ?)', datavals)
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