def detect_light_tcs3472(self): try: from envirophat import light light.light() self.sensor_tcs3472 = light #device test return True except: return False
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 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 show_light(): # Makes sure scrollphat buffer is clear sphd.clear() # variable is set to be the current light value lightvalue = light.light() # Uses say_value() to speak the current light level speaklight = ("The current light level is " + str(lightvalue)) print(speaklight) say_value(x=speaklight) # Light value is stored in scrollphat buffer lightoutput = (" Light: " + str(lightvalue)) sphd.write_string(lightoutput, 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 get_values(): global temperature global pressure global amblight temperature = weather.temperature() pressure = round(weather.pressure(), 2) amblight = light.light() json_response = { "prtg": { "result": [{ "channel": "temperature", "float": 1, "value": temperature }, { "channel": "pressure", "float": 1, "value": pressure }, { "channel": "ambient light", "float": 1, "value": amblight }] } } return json_response
def write(): try: p = round(weather.pressure(),2) c = light.light() print('{"light": '+str(c)+', "pressure": '+str(p)+' }') except KeyboardInterrupt: pass
def iothub_client_sample_run(): id = 0 iot.initialise(callback) while True: try: leds.on() openWeather.getWeather() humidity = 50 ## normalise light to something of 100% lightLevel = light.light(); if lightLevel > 1024: lightLevel = 1024 lightLevel = lightLevel * 100 / 1024 id += 1 msg_txt_formatted = msg_txt % (sensorLocation, humidity, round(weather.pressure()/100,2), round(weather.temperature(),2), lightLevel, id) iot.publish(msg_txt_formatted, id) leds.off() time.sleep(4) except IoTHubError as e: print("Unexpected error %s from IoTHub" % e) print_last_message_time(iot.iotHubClient) time.sleep(4) except KeyboardInterrupt: print("IoTHubClient sample stopped") return
def solar(): sun_data = open("sun_%d_%d_%d.txt" % (year, month, day), "ab") l = light.light() if time.localtime()[4] == 15: sun = "%d.%d %d" % ( time.localtime()[3], time.localtime()[4] + 10, l ) #This format allows me to import the txt file ... elif time.localtime()[4] == 30: #...to the Mac Grapher application sun = "%d.%d %d" % ( time.localtime()[3], time.localtime()[4] + 20, l ) #These adjustments coorespond time to a corrext x-axis position elif time.localtime()[4] == 45: sun = "%d.%d %d" % (time.localtime()[3], time.localtime()[4] + 30, l) else: sun = "%d.%d %d" % ( time.localtime()[3], time.localtime()[4], l ) #when minutes = 0, no need to convert to coordiante sun_data.write(sun) sun_data.write("\n") sun_data.close() os.system("scp %s %s@%s:~%s" % (sun_data.name, username, ip, directory)) return sun
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 harvest(): date = datetime.now() ##### Grab Sense Hat data ##### t = round((weather.temperature() - equartT), 1) p = round((weather.pressure() / 100), 1) l = light.light() ##### MySQL sign in ##### conn = pymysql.connect(user="******", passwd="userpassWD", host="192.168.x.x", database="sensors") cursor = conn.cursor() ##### Database insertion ##### ##### Global cursor #### cursor.execute(queryInsert("temperature", t, "Enviro pHAT", "room 1")) cursor.execute(queryInsert("pression", p, "Enviro pHAT", "room 1")) cursor.execute(queryInsert("light", l, "Enviro pHAT", "room 1")) ##### Disconnect the database ##### conn.commit() cursor.close() conn.close()
def lights_off(): global state state = 0 os.system( 'curl -s "http://*****:*****@PI-IP-ADD-RESS/api-all-off/" > /dev/null' ) print('Lights off! Room luminence is {0:.0f} lux.'.format(light.light()))
def get_environment(): data = {'boardTemp': weather.temperature(), 'atm': weather.pressure(), 'light': light.light()} data['cpuTemp'] = get_cpu_temperature() data['calibTemp'] = data['boardTemp'] - ((data['cpuTemp'] - data['boardTemp'])/FACTOR) # print data return 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 handle(self, *args, **options): """ Log the temperature, light (normalised) and moisture (normalised) to the database. """ if not running_on_raspberry_pi: # Just put some dummy data in temperature = 10 moisture = 0.5 light_level = 1.0 else: light_sensor_max = 65535 light_sensor_min = 0 light_level = (light.light() - light_sensor_min) / ( light_sensor_max - light_sensor_min) moisture_sensor_max = 4.455 moisture_sensor_min = 0 moisture = (analog.read(0) - moisture_sensor_min) / ( moisture_sensor_max - moisture_sensor_min) temperature = self.get_calibrated_temperature() print(f"Light level: {light_level}") print(f"Temperature: {temperature}") print(f"Soil moisture: {moisture}") sensor_data = SensorData( temperature=temperature, moisture=moisture, light=light_level, ) sensor_data.save()
def get_light(): """light""" global light data = { "light": light.light(), "rgb": light.rgb() } return jsonify(data)
def get_enviro_line(): return { 'temperature': weather.temperature(), 'pressure': weather.pressure(), 'light': light.light(), 'deviceId': DEVICE_ID, 'time': millis() }
def render_dashboard(): connection = sqlite3.connect(database_path) connection.row_factory = lambda cursor, row: row cursor = connection.cursor() cursor.execute("SELECT * FROM weather") # WHERE dateId LIKE ?", (date + '%',)) r = cursor.fetchall() connection.close() if (light.light() < 300): lightStatus = 'Light off' elif (light.light() < 600): lightStatus = 'Light on' elif (light.light() < 1100): lightStatus = "It's day time" else: lightStatus = 'Sunny day' return render_template('dashboard.html', result = r, len = len(r), round = round, currentTemp = round(weather.temperature(), 2), currentLightIntensity = light.light(), lightStatus = lightStatus)
def index(): """Video streaming home page.""" temp = weather.temperature() press = weather.pressure() li = light.light() return render_template('index.html', temperature=temp, pressure=press, light=li)
def environment(bot, update): output = """ Temp: {t}c Pressure: {p}Pa Light: {c} """.format(t=round(weather.temperature(), 2), p=round(weather.pressure(), 2), c=light.light()) bot.send_message(chat_id=update.message.chat_id, text=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 get_environment(): data = { 'board_temp': round(weather.temperature(), 2), 'pressure': round(weather.pressure(), 0), 'light': round(light.light(), 2) } data['cpu_temp'] = get_cpu_temperature() data['est_temp'] = round( data['board_temp'] - ((data['cpu_temp'] - data['board_temp']) / FACTOR), 2) return data
def perform_update(): """Update weather data and write entries to file(s). """ global currtime currtime = datetime.now().strftime('%H:%M:%S') lux = light.light() leds.on() get_condition() get_temps() write_file() # write_json() send_message() out.flush() leds.off()
def perform_update(): """Update weather data and write entries to file(s). """ global currtime currtime = datetime.now().strftime('%H:%M:%S') lux = light.light() leds.on() get_condition() get_temps() write_file() # write_json() # send_message() out.flush() leds.off()
def get_url_params(): t = weather.temperature() p = weather.pressure(unit='hPa') h = None l = light.light() # Python's datetmie doesn't have timezone info. # You may need to set system timezone as JST. (hint: sudo raspi-config) ts = time.strftime("%Y-%m-%dT%H:%M:%S%z") s = "dt=%s" % (ts) s += "&temperature=%f" % (t) s += "&pressure=%f" % (p) # s += "&humidity=%f" % (h) s += "&illuminance=%f" % (l) # s += "&voltage=#{v}" return s
def get_url_params(): t = weather.temperature() p = weather.pressure(unit='hPa') h = None l = light.light() # Python's datetmie doesn't have timezone info. # You may need to set system timezone as JST. (hint: sudo raspi-config) # FIXME: the code will post wrong datetime. should be keep in UTC??(is the hint wrong?) ts = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S%z") s = "dt=%s" % (ts) s += "&temperature=%f" % (t) s += "&pressure=%f" % (p) # s += "&humidity=%f" % (h) s += "&illuminance=%f" % (l) # s += "&voltage=#{v}" return s
def get_data_points(): temp_cpu = get_cpu_temp() temperature = weather.temperature() pressure = round(weather.pressure(), 2) light_val = light.light() iso = time.ctime() 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": "ambient_light", "tags": { "host": host }, "time": iso, "fields": { "value": light_val, } }, { "measurement": "ambient_pressure", "tags": { "host": host }, "time": iso, "fields": { "value": pressure, } }] return json_body
def measure(self): leds.on() self.openWeather.getWeather() self.id += 1 humidity = 50 ## normalise light to something of 100% lightLevel = light.light(); if lightLevel > 1024: lightLevel = 1024 lightLevel = lightLevel * 100 / 1024 json = self.msg_txt % (self.sensorLocation, humidity, round(weather.pressure()/100,2), round(weather.temperature(),2), lightLevel, self.id) leds.off() return json
def append_row(session, workbookItemId): """ Appends a new row with current measurement values to the worksheet. """ url = 'https://graph.microsoft.com/v1.0/me/drive/items/{}/workbook/worksheets(\'Sheet1\')/tables(\'Table1\')/rows/add'.format( workbookItemId) # Get column values now = formatted_now_long() tempC = str(weather.temperature()) presHpa = str(weather.pressure(unit='hPa')) lum = str(light.light()) # Build data string data = '{ "values": [["' + now + '", "' + tempC + '", "' + presHpa + '", "' + lum + '"]]}' # Post the new row to the Graph API. session.post(url, data=data)
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 main(): leds.on() cputemp = get_cpu_temperature() envtemp = weather.temperature() caltemp = envtemp - ((cputemp - envtemp) / 1.3) envdate = datetime.datetime.utcnow().strftime('%c') json = { "hostname": socket.gethostname(), "envdate": envdate, "light": light.light(), "temp": round((caltemp * 1.8 + 32), 2), "pressure": round(weather.pressure(), 2) } leds.off() print(json)
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 average_lux(): # Variables for calculating the average lux levels start_time = time.time() curr_time = time.time() collect_light_time = 60 collect_light_data = [] # Calculate the average lux level over 60 seconds print("Calculating average light level...") while curr_time - start_time < collect_light_time: curr_time = time.time() avg = light.light() collect_light_data.append(avg) time.sleep(1) # Take the last 45 data points taken over 60 seconds to calculate the average average_light = sum(collect_light_data[-45:]) / 45.0 now = whats_the_time() print("Average over {collect_time} seconds is: {average} lux. Last checked at {time}".format( collect_time=collect_light_time, average=average_light, time=now )) return average_light
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], 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)
def light(self): return light.light()
import time from envirophat import weather, leds , light HOST, PORT = '', 8888 listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) listen_socket.bind((HOST, PORT)) listen_socket.listen(1) print 'Serving HTTP on port %s ...' % PORT while True: temperature = weather.temperature() pressure = weather.pressure() lightvalue = light.light() client_connection, client_address = listen_socket.accept() request = client_connection.recv(2048) first_line = request.split('\r\n') path = first_line[0].split(' ') path_clean = path[1].split('?') print request if path_clean[0] == "/pressure": humidi = "Pressure: %.2f hPa" % pressure http_response = \ "HTTP/1.1 200 OK\n"\ "Content-Type: text/xml\n\n"\ "<?xml version='1.0' encoding='UTF-8'?>"\ "<SnomIPPhoneText track='no'>"\