def _battery(testCase=None): py = Pysense() try: if isinstance(testCase, Exception): raise testCase voltage = int(py.read_battery_voltage()*1000)/1000.0 logger.VOLTAGE = voltage except Exception as e: return 143 if testCase is not None: voltage = testCase if voltage < 0: return 143 if voltage > 4.4: perc = 100 else: # % = (voltage - min) / (max - min) voltage -= 3.311 perc = int((voltage / 0.8) * 100) if perc > 100: perc = 100 return perc
class AmbientSensor: def __init__(self, queue, period): self._dev_mpl = MPL3115A2() self._dev_si = SI7006A20() self._queue = queue self._period = period self._temp_calib = 5 self._ps = Pysense() Timer.Alarm(self._timer_handler, period, periodic=True) def _timer_handler(self, alarm): # temp_sensor = self._dev_si.temperature() temp_sensor = self._dev_mpl.temperature() # humidity_sensor = self._dev_si.humidity() pressure_sensor = self._dev_mpl.pressure() temp_calib = temp_sensor - self._temp_calib # humidity_calib = humidity_sensor / (pow(.95, self._temp_calib)) humidity_calib = self._dev_si.humid_ambient(temp_calib) self._queue.push_ambient(temp_calib, humidity_calib, pressure_sensor, self._ps.read_battery_voltage())
# set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 0) # Builds the bytearray to send the request py = Pysense() si = SI7006A20(py) lt = LTR329ALS01(py) li = LIS2HH12(py) mpp = MPL3115A2( py ) # Returns pressure in Pa. Mode may also be set to ALTITUDE, returning a value in meters for count in range(200000): print("Count=", count) vt = py.read_battery_voltage() print("Battery voltage: " + str(vt)) dew = si.dew_point() print("Dew point: " + str(dew) + " deg C") temp1 = mpp.temperature() print("Tempertaure1: " + str(temp1)) press1 = mpp.pressure() print("Pressure: " + str(press1)) #Pressure does not work too well temp2 = si.temperature() hum1 = si.humidity() print("Temperature: " + str(temp2) + " deg C and Relative Humidity: " + str(hum1) + " %RH") t_ambient = 24.4 relhum = si.humid_ambient(t_ambient) print("Humidity Ambient for " + str(t_ambient) + " deg C is " + str(relhum) + "%RH")
print("sending humidity: " + str(si.humidity())) client.publish(topic="mylescai/feeds/voltaic-fern-humidity", msg=str(si.humidity())) pycom.rgbled(blue) time.sleep(asleep) wdt.feed() #made it past the WLAN timeout loop error b, r = lt.light() print("sending channel blue lux: " + str(b) + " and red lux: " + str(r)) client.publish(topic="mylescai/feeds/voltaic-fern-blue-light", msg=str(b)) client.publish(topic="mylescai/feeds/voltaic-fern-red-light", msg=str(r)) pycom.rgbled(yellow) time.sleep(asleep) wdt.feed() #made it past the WLAN timeout loop error print("sending battery voltage: " + str(py.read_battery_voltage())) client.publish(topic="mylescai/feeds/voltaic-fern-battery", msg=str(py.read_battery_voltage())) pycom.rgbled(magenta) time.sleep(asleep) wdt.feed() # time.sleep(60) pycom.rgbled(liteblue) time.sleep(.3) wdt.feed() #made it past the WLAN timeout loop error # 4 minutes sleep machine.deepsleep( 1000 * 60 * 4 ) #time.sleep runs at 265mA with wifi enabled. sleep is just delay (in seconds)
### [0] Initialize threads params = [] #params.append((accelerometer.get_data, (None, 2), data, # ("acceleration", "pitch", "roll"), lock)) params.append((thermometer.get_data, None, data, ("temperature_t", "humidity", "dew_point"), lock)) params.append((barometer.get_data, None, data, ("altitude", "temperature_b", "pressure"), lock)) #params.append((lt.light, None, data, # ("blue", "red"), lock)) ### [1] Execute threads for param in params: _thread.start_new_thread(functions.threading, param) data["battery"] = py.read_battery_voltage() ### [2] Initialize socket sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) #sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) sock.setblocking(False) ### [3] Wait for threads to finish while data["nFinished"] < len(params): pass ### [4] Format the data and send it #request = functions.formatRequest(data) # """
msg="analog_sensor=" + str(y)) client.publish(topic=TOPIC_PUBLISH + ACCEL_Z_CH, msg="analog_sensor=" + str(z)) time.sleep_ms(10) #Limpar barramento I2C #Light Publish - Different Channels = Different sensitivity for wavelenght (ch0 ~450nm violet-blue and ch1 ~770nm red) lux_ch0, lux_ch1 = lt.light() client.publish(topic=TOPIC_PUBLISH + LIGHT0_CH, msg="lum,lux=" + str(lux_ch0)) client.publish(topic=TOPIC_PUBLISH + LIGHT1_CH, msg="lum,lux=" + str(lux_ch1)) time.sleep_ms(10) #Limpar barramento I2C #Altitude and Pressure press = mpp.pressure() client.publish(topic=TOPIC_PUBLISH + PRESS_CH, msg="bp,pa=" + str(press)) alt = 44330.77 * (1 - ((press / 101326)**0.1902632)) + REGION_ALT_OFFSET client.publish(topic=TOPIC_PUBLISH + ALTI_CH, msg="analog_sensor,m=" + str(alt)) time.sleep_ms(10) #Limpar barramento I2C #Battery client.publish(topic=TOPIC_PUBLISH + BATTERY_CH, msg="analog_sensor,v=" + str(py.read_battery_voltage())) if (switchRGB == '1'): pycom.rgbled(int((actualRGB[0] + actualRGB[1] + actualRGB[2]), 16)) else: #LED Flash to each time a complete write on MQTT has done if RGB LED switch is OFF RgbLedFlash(1, 0x005555, 50)
str(si.humid_ambient(t_ambient)) + "%RH") print("Light (channel Blue lux, channel Red lux): " + str(lt.light())) print("Acceleration: " + str(li.acceleration())) print("Roll: " + str(li.roll())) print("Pitch: " + str(li.pitch())) print("Battery voltage: " + str(py.read_battery_voltage())) """ while True: # Build message data lpp.reset() lpp.add_temperature(1, si.temperature()) lpp.add_relative_humidity(2, si.humidity()) lpp.add_barometric_pressure(3, int(mpp.pressure() / 100)) lpp.add_luminosity(4, lt.light()[0]) lpp.add_voltage(5, py.read_battery_voltage()) x, y, z = li.acceleration() lpp.add_accelerometer(1, x, y, z) s.setblocking(True) s.send(bytes(lpp.get_buffer())) s.setblocking(False) # Print if received data data = s.recv(64) print(data) # Print last RX LoRa stats print(lora.stats()) counter = counter + 1 print(counter) time.sleep(20)
print("Pressure: " + str(mpp.pressure())) print("Temperature: " + str(si.temperature()) + " deg C and Relative Humidity: " + str(si.humidity()) + " %RH") print("Dew point: " + str(si.dew_point()) + " deg C") t_ambient = 24.4 print("Humidity Ambient for " + str(t_ambient) + " deg C is " + str(si.humid_ambient(t_ambient)) + "%RH") print("Light (channel Blue lux, channel Red lux): " + str(lt.light())) print("Acceleration: " + str(li.acceleration())) print("Roll: " + str(li.roll())) print("Pitch: " + str(li.pitch())) print("Battery voltage: " + str(py.read_battery_voltage())) ### from network import LoRa import config # initialize LORAWAN mode for EU region lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # print DevEUI of the device, use this when provisioning it in your network server print("DevEUI: " + binascii.hexlify(lora.mac()).decode('utf-8').upper()) # OTAA authentication parameters, replace these with your own print("Joining network using OTAA (Over the Air Activation)")
import time py = Pysense() # ################################################################ # ######## main # ################################################################ pycom.heartbeat(False) gc.enable() py.setup_int_wake_up(True, True) wdt = WDT(timeout=1200000 ) # enable it with a timeout of 1 seconds (1000)*1200 (=20min) wdt.feed() battery_voltage = py.read_battery_voltage() if disable_low_power_on_usb == 1: if battery_voltage > 4.2: low_power_consumption_mode = 0 print("USB connection detected, disable low power mode (voltage=%s)" % (str(py.read_battery_voltage()))) sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1) sigfox_network = socket.socket(socket.AF_SIGFOX, socket.SOCK_RAW) sigfox_network.setblocking(True) sigfox_network.setsockopt(socket.SOL_SIGFOX, socket.SO_RX, True) # true=downlink device_id = binascii.hexlify(sigfox.id()) device_pac = binascii.hexlify(sigfox.pac()) if low_power_consumption_mode == 0: print("DEVICE ID : %s" % (device_id))
lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=lora_cb) # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate #s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # selecting confirmed type of messages s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True) # make the socket non-blocking s.setblocking(False) # send some data while True: for i in range(0, 0xff): light = lt.light() msg = struct.pack("ffffiifff", mp.temperature(), mp.altitude(), si.temperature(), si.humidity(), light[0], light[1], li.roll(), li.pitch(), py.read_battery_voltage()) #msg = struct.pack("ffffiifff", mp.temperature(), mp.pressure(), si.temperature(), si.humidity(), light[0], light[1], li.roll(), li.pitch(), py.read_battery_voltage()) print(msg) s.send(msg) time.sleep(60) # get any data received... data = s.recv(64) print(data)
altitude = mpa.altitude() # Get the altitude pybytes.send_signal(5, mpa.altitude() / 100) # Send the altitude using signal 5 pycom.rgbled(0x000000) # Turn off the LED light = lt.light() # Get the Light pybytes.send_signal(2, lt.light()) # Send the light using signal 2 pycom.rgbled(0x000000) # Turn off the LED Acceleration = li.acceleration() # Get the acceleration pybytes.send_signal( 3, li.acceleration()) # Send the acceleration using signal 3 pycom.rgbled(0x000000) # Turn off the LED battery = py.read_battery_voltage() # Get the battery voltage pybytes.send_signal( 6, py.read_battery_voltage()) # Send the battery using signal 6 pycom.rgbled(0x000000) # Turn off the LED post_event("temperature", si.temperature()) mpp = MPL3115A2(py, mode=PRESSURE) post_event("pressure", mpp.pressure() / 100) mpa = MPL3115A2(py, mode=ALTITUDE) post_event("altitude", mpa.altitude() / 100) post_event("humidity", si.humidity()) post_event("light", lt.light()) pycom.rgbled(0x000000) s.setblocking(True) pycom.rgbled(0x000014)
# str_send[3] = temp_bytes[1] # s.send(str_send) # # if button() == 1: # but_ant = 1 while True: print("Time Out!!") # send some data temp = int(si.temperature() * 10) print("Temp: ", temp, " C") temp_bytes = temp.to_bytes(2, 'big') str_send[2] = temp_bytes[0] str_send[3] = temp_bytes[1] v_bat = int(py.read_battery_voltage() * 100) print("V Battery: ", v_bat, " V") temp_v_bat = v_bat.to_bytes(2, 'big') str_send[6] = temp_v_bat[0] str_send[7] = temp_v_bat[1] s.send(str_send) time.sleep(300) # send some data # s.send(bytes([0x01, 0x02, 0x03])) # make the socket non-blocking # (because if there's no data received it will block forever...) # s.setblocking(False)
# join a network using ABP (Activation By Personalization) lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, LORA_NODE_DR) # make the socket non-blocking s.setblocking(False) while True: # Read the values from the sensors voltage = pysense.read_battery_voltage() temperature = mpl3115a2.temperature() humidity = si7006a20.humidity() pressure = mpl3115a2.pressure() # Read the light levels of both LTR329ALS01 sensors. Returns a tuple with two values for light levels in lux. # Light (channel Blue lux, channel Red lux) lightBlue = ltr329als01.light()[0] lightRed = ltr329als01.light()[1] roll = lis2hh12.roll() pitch = lis2hh12.pitch() # Debug sensor values #print('voltage:{}, temperature:{}, pressure:{}, light:{}, humidity:{}, roll:{}, pitch:{}'.format(voltage, temperature, pressure, light, humidity, roll, pitch)) print('voltage:{}, temperature:{}, humidity:{}, pressure:{}'.format(voltage, temperature, humidity ,pressure)) print()
while not lora.has_joined(): print('Waiting to join...') pycom.rgbled(red) time.sleep(0.1) pycom.rgbled(off) time.sleep(2) pycom.heartbeat(False) lora_channels.configure_channels(lora) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(True) button = Pin("G17", mode=Pin.IN, pull=Pin.PULL_UP) while (1): print("Battery Voltage: ", py.read_battery_voltage()) print("Altitude: ", mp.altitude()) print("Pressure: ", mpp.pressure()) print("Temperature: ", si.temperature()) print("Humidity: ", si.humidity()) print("Light: ", lt.light()) print("Acceleration: ", li.acceleration()) print("Roll: ", li.roll()) print("Pitch: ", li.pitch()) payload = Messages.build_ipso_message(py.read_battery_voltage(), mpp.pressure(), si.temperature(), lt.light()[0], si.humidity(), li.acceleration()) print("TX:", binascii.hexlify(payload))
) # Returns pressure in Pa. Mode may also be set to ALTITUDE, returning a value in meters print("MPL3115A2 temperature: " + str(mp.temperature())) import cayenneLPP lpp = cayenneLPP.CayenneLPP(size=100, sock=s) #lpp.addGPS(3, 52.37365, 4.88650, 2); while True: lpp.add_temperature(mp.temperature()) lpp.add_barometric_pressure(mpp.pressure() / 100) lpp.add_relative_humidity(si.humidity()) lpp.add_accelerometer(li.acceleration()[0], li.acceleration()[1], li.acceleration()[2]) lpp.add_luminosity(lt.light()[0], channel=20) lpp.add_luminosity(lt.light()[1], channel=21) lpp.add_analog_input(round(py.read_battery_voltage(), 1), channel=22) #lpp.add_generic(116,round(py.read_battery_voltage(),1),channel=23,precision=0.1) print("Battery voltage: " + str(py.read_battery_voltage())) print("Humidity " + str(si.humidity())) print("Pressure hPa: " + str(mpp.pressure() / 100)) print("MPL3115A2 temperature: " + str(mp.temperature())) lpp.send(reset_payload=True) time.sleep(30)
def main(): pycom.heartbeat(0) debug_flag = False #Init sensors py = Pysense() mp = MPL3115A2( py, mode=ALTITUDE ) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals #si = SI7006A20(py) lt = LTR329ALS01(py) li = LIS2HH12(py) #Init WLAN connection wlan = WLAN(mode=WLAN.STA) nets = wlan.scan() for net in nets: if net.ssid == 'gotechsummit': if debug_flag == True: print('Network found!') #debugging wlan.connect(net.ssid, auth=(net.sec, 'HackTime247'), timeout=5000) while not wlan.isconnected(): machine.idle() #to save energy if debug_flag == True: print("Connection Successful") #debug break #Init the UDP transmission UDP_IP_Josch = "10.0.24.199" UDP_IP_Niklas = "10.0.25.80" UDP_IP_Ulrich = "10.0.25.173" UDP_PORT = 5005 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) counter = 0 while 1: #temperature = mp.temperature() #temperature_2 = si.temperature() light = lt.light() acceleration = li.acceleration() battery = py.read_battery_voltage() a_vector = (acceleration[0]**2) + (acceleration[1]** 2) + (acceleration[2]**2) l_vector = (light[0]**2) + (light[1]**2) if a_vector > 3: MESSAGE = "ACCELERATION INTERRUPT" elif l_vector > 3: MESSAGE = "PACKAGE OPENING INTERRUPT" else: MESSAGE = str(counter) + ";" + str(light) + ";" + \ str(acceleration) + ";" + str(battery) sock.sendto(MESSAGE, (UDP_IP_Josch, UDP_PORT)) #sock.sendto(MESSAGE, (UDP_IP_Niklas, UDP_PORT)) #sock.sendto(MESSAGE, (UDP_IP_Ulrich, UDP_PORT)) if debug_flag == True: #print ("Temperature: " + str(temperature)) #print ("Temperature_2: " + str(temperature_2)) print("Light: " + str(light)) print("Accerlation: " + str(acceleration)) print("Battery: " + str(battery)) print("Successfully Sent Package #" + str(counter)) print("\n\n\n") counter = counter + 1 if debug_flag == True: for i in range(0, 4): pycom.rgbled(0x00ff00) time.sleep(0.2) pycom.rgbled(0xff0000) time.sleep(0.2) else: time.sleep(0.05)
class Node: _thread = None def __init__(self): self.lora = None self.s = None self.py = Pysense() # Instancia de Pysense self.acc = LIS2HH12(self.py) # Instancia del Acelerometro self.last = [0, 0, 0] # Último valor leído de aceleracion self.raw = [0, 0, 0] # Valor leído actual de aceleracion self.busy = 0 # Value has passed limit self.interval = 10 # Intervalo de toma de datos self.battery = None # Valor de la tensión de batería self.alarma = None # Alarma de toma de datos de aceleracion self.s_lock = _thread.allocate_lock() # Semaforo para envío #------------------------------------------------------------------------------# def connect(self, dev_eui, app_eui, app_key, dr=5): """ Connect device to LoRa. Set the socket and lora instances. """ # Disable blue blinking and turn LED off pycom.heartbeat(False) # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN, device_class=LoRa.CLASS_A, region=LoRa.EU868) # Set the 3 default channels to the same frequency (must be before sending the # OTAA join request) self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5) # Join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) #login for TheThingsNetwork see here: #https://www.thethingsnetwork.org/forum/t/lopy-otaa-example/4471 # Wait until the module has joined the network while not self.lora.has_joined(): print("Trying to join LoraWAN with OTAA") time.sleep(2.5) print("LoraWAN joined! ") print("Create LoRaWAN socket") self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # Set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, dr) # selecting confirmed type of messages self.s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True) # Make the socket non-blocking self.s.setblocking(False) #Crea la alarma tras la conexion self.alarma = Timer.Alarm( self.readsens, self.interval, periodic=True) #Alarma de toma de datos de aceleracion #------------------------------------------------------------------------------# def send(self, datalast, dataraw): """ Send data over the network. """ self.s_lock.acquire( ) # Espera a que el semáforo esté disponible (tiempo indefinido) try: data = datalast, dataraw self.s.send(str(data)) time.sleep(2) #Espera para posible recepción rx = self.s.recv(128) #Recepción de datos self.receive(rx=rx) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) self.s_lock.release() #Libera el semáforo _thread.exit() #Cierra el hilo #------------------------------------------------------------------------------# def receive(self, rx=None): if rx == None: pass else: if rx[0] == 73: #Orden de Cambio de intervalo (ASCII hex I=0x49 dec 73) print("Recibido cambio de intervalo %d" % (int.from_bytes(rx[1:], 'big'))) self.interval = int.from_bytes( rx[1:], 'big') #Decodifica el valor del nuevo intervalo self.alarma.cancel() #Cancela la alarma self.alarma = Timer.Alarm( self.readsens, self.interval, periodic=True ) #Vuelve a crear una alarma para el nuevo intervalo elif rx[0] == 67: #Orden de Cancelación de Lecturas (ASCII hex C=0x43 dec 67) print('Cancela las lecturas') self.alarma.cancel() elif rx[0] == 82: #Orden de Cambio Data Rate (ASCII hex R=0x52 dec 87) dr = int.from_bytes( rx[1:], 'big') #Decodifica el valor del nuevo data Rate self.connect(dr=dr) else: pass #------------------------------------------------------------------------------# #Función de lectura de medidas. El Acelerometro ya ha sido inicializado al #crear la instancia de la clase def readsens(self, alarma): self.raw = self.acc.acceleration( ) # Devuelve tuple con aceleracion en tres ejes (G) print("Aceleracion-> X:%fG Y:%fG Z:%fG" % (self.raw[0], self.raw[1], self.raw[2])) #Cálculos if (self.raw[2] > 1): print("Enviando datos") _thread.start_new_thread( self.send, (self.last, self.raw)) # Se crea un hilo para el envío de valores self._compare_update() self.battery = round(self.py.read_battery_voltage(), 2) if (self.battery < 3.3): print("Batería Crítica") _thread.start_new_thread( self.send, ("Batería", " Crítica" )) # Se crea un hilo para el envío de alarma de batería #------------------------------------------------------------------------------# def _compare_update(self): if self.raw is not self.last: self.last = self.raw else: pass
print("Reading sensor values...") sensor_data[cycles - 1][0] = time.time() sensor_data[cycles - 1][1] = si.temperature() sensor_data[cycles - 1][2] = si.humidity() sensor_data[cycles - 1][3] = li.acceleration() # print(lt.light()) # print(li.roll()) # print(li.pitch()) # print(li.yaw()) next_time += 10 time.sleep(max(0, next_time - time.time())) # Battery voltage print(py.read_battery_voltage()) # Final sensor data print(sensor_data) for i in range(0, len(sensor_data)): s = "" s += str(sensor_data[i][0]) s += "," s += str(sensor_data[i][1]) s += "," s += str(sensor_data[i][2]) s += "," s += str(sensor_data[i][3]) print(s)
# See https://docs.pycom.io for more information regarding library specifics from pysense import Pysense from LIS2HH12 import LIS2HH12 from SI7006A20 import SI7006A20 from LTR329ALS01 import LTR329ALS01 from MPL3115A2 import MPL3115A2,ALTITUDE,PRESSURE py = Pysense() mp = MPL3115A2(py,mode=ALTITUDE) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals si = SI7006A20(py) lt = LTR329ALS01(py) li = LIS2HH12(py) print(mp.temperature()) print(mp.altitude()) mpp = MPL3115A2(py,mode=PRESSURE) # Returns pressure in Pa. Mode may also be set to ALTITUDE, returning a value in meters print(mpp.pressure()) print(si.temperature()) print(si.humidity()) print(lt.light()) print(li.acceleration()) print(li.roll()) print(li.pitch()) print(py.read_battery_voltage())