Example #1
0
class lives:
    def __init__(self, ledPins):
        self.led1 = LED(ledPins[0])
        self.led2 = LED(ledPins[1])
        self.count = 3  # The default
        self.led1.on()
        self.led2.on()

    def update(self):
        if self.count >= 1:
            self.count = self.count - 1
        if (self.count == 3):
            self.led1.on()
            self.led2.on()
        elif (self.count == 2):
            self.led1.on()
            self.led2.off()
        elif (self.count == 1):
            self.led1.off()
            self.led2.off()
        elif (self.count == 0):
            self.led1.off()
            self.led2.off()

    def reset(self):
        self.count = 3
        self.led1.on()
        self.led2.on()
Example #2
0
    def send(self, data, port=2):
        """
    Send data over the network.
    """
        if (port < 2) or (port > len(self.s)):
            raise ValueError('Unknown LoRa port')
        if not self.s[port]: raise OSError('No socket')

        rts = True
        try:
            self.s[port].send(data)
            LED.blink(2, 0.1, 0x0000ff)
            # print("Sending data")
            # print(data)
        except OSError as e:
            if e.errno == 11:
                print("Caught exception while sending")
                print("errno: ", e.errno)
            rts = False

        LED.off()
        data = self.s[port].recv(64)
        # print("Received data:", data)
        if self.callback and data:
            self.callback(port, data)
        return rts
Example #3
0
def runMe():
  global lora, sleep_time, oled
  global useDust

  setup() # Setup network & sensors

  while True:

    toSleep = time()
    dData = DoDust()
    mData = DoMeteo()

    # Send packet
    if lora != None:
      if  lora.send(DoPack(dData,mData,LocUpdate())):
        LED.off()
      else:
        display(" LoRa send ERROR")
        LED.blink(5,0.2,0x9c5c00,False)

    toSleep = sleep_time - (time() - toSleep)
    if useDust:
      if toSleep > 30:
        toSleep -= 15
        useDust.Standby()   # switch off laser and fan
      elif toSleep < 15: toSleep = 15
    if not ProgressBar(0,63,128,2,toSleep,0xebcf5b,10):
      display('stopped SENSING', (0,0), clear=True)
      LED.blink(5,0.3,0xff0000,True)
    if STOP:
      sleep(60)
      oled.poweroff()
      # and put ESP in deep sleep: machine.deepsleep()
      return False
Example #4
0
def DoDust():
  global useDust, Dust, dust, nl, STOP, STOPPED, useGPS, lastGPS
  dData = {}
  display('PM sensing',(0,0),clear=True,prt=False)
  if useDust and (useDust.mode != useDust.NORMAL):
    useDust.Normal()
    if not showSleep(secs=15,text='starting up fan'):
      display('stopped SENSING', (0,0), clear=True)
      LED.blink(5,0.3,0xff0000,True)
      return [0,0,0]
    else:
      if useGPS != None:
        display("G:%.4f/%.4f" % (lastGPS[LAT],lastGPS[LON]))
      display('measure PM')
  if useDust:
    LED.blink(3,0.1,0x005500)
    # display('%d sec sample' % sample_time,prt=False)
    try:
      STOPPED = False
      try:
        SleepThread(sample_time,'%d sec sample' % sample_time)
      except:
        STOPPED = True
        display('%d sec sample' % sample_time)
      dData = useDust.getData()
      for cnt in range(10):
        if STOPPED: break
        STOP = True
        print('waiting for thread')
        sleep(2)
      STOP = False
    except Exception as e:
      display("%s ERROR" % Dust[dust])
      print(e)
      LED.blink(3,0.1,0xff0000)
      dData = {}
    LED.blink(3,0.1,0x00ff00)

  if len(dData):
    for k in dData.keys():
        if dData[k] == None: dData[k] = 0
    try:
      if 'pm1' in dData.keys():   #  and dData['pm1'] > 0:
        display(" PM1 PM2.5 PM10", (0,0), clear=True)
        display("% 2.1f % 5.1f% 5.1f" % (dData['pm1'],dData['pm25'],dData['pm10']))
      else:
        display("ug/m3 PM2.5 PM10", (0,0), clear=True)
        display("     % 5.1f % 5.1f" % (dData['pm25'],dData['pm10']))
        dData['pm1'] = 0
    except:
      dData = {}
  if not dData:
    display("No PM values")
    LED.blink(5,0.1,0xff0000,True)
    dData = [0,0,0]
  else:
    dData = [round(dData['pm1'],1),round(dData['pm25'],1),round(dData['pm10'],1)]
    LED.off()
  return dData
Example #5
0
    def connect(self, dev_eui, app_eui, app_key, ports=1, callback=None):
        """
    Connect device to LoRa.
    Set the socket and lora instances.
    """

        dev_eui = unhexlify(dev_eui)
        app_eui = unhexlify(app_eui)
        app_key = unhexlify(app_key)
        self.callback = callback  # call back routine on LoRa reply callback(port,response)
        # Disable blue blinking and turn LED off
        LED.heartbeat(False)
        LED.off()

        # Initialize LoRa in LORAWAN mode
        self.lora = LoRa(mode=LoRa.LORAWAN)

        # Join a network using OTAA (Over the Air Activation)
        self.lora.join(activation=LoRa.OTAA,
                       auth=(dev_eui, app_eui, app_key),
                       timeout=0)

        # Wait until the module has joined the network
        count = 0
        while not self.lora.has_joined():
            LED.blink(1, 2.5, 0xff0000)
            if count > 20:
                return False
            print("Trying to join: ", count)
            count += 1

        # Create a LoRa socket
        LED.blink(2, 0.1, 0x009900)
        self.s = []
        self.s.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW))

        # Set the LoRaWAN data rate
        self.s[0].setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

        # Make the socket non-blocking
        self.s[0].setblocking(False)

        print("Success after %d tries" % count)
        # print("Create LoRaWAN socket")

        # Create a raw LoRa socket
        # default port 2
        self.s.append(None)
        for nr in range(ports):
            print("Setting up port %d" % (nr + 2))
            self.s.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW))
            self.s[nr + 2].setblocking(False)
            if nr: self.s[nr + 2].bind(nr + 2)
        LED.off()
        return True
Example #6
0
def main():
	
	action = request.values['action']

	led = LED(17)

	if action == 'on':
		led.on()

	if action == 'off':
		led.off()

	return 'success'
Example #7
0
    def connect(self, dev_eui, app_eui, app_key):
        """
    Connect device to LoRa.
    Set the socket and lora instances.
    """

        dev_eui = unhexlify(dev_eui)
        app_eui = unhexlify(app_eui)
        app_key = unhexlify(app_key)

        # Disable blue blinking and turn LED off
        LED.heartbeat(False)
        LED.off()

        # Initialize LoRa in LORAWAN mode
        self.lora = LoRa(mode=LoRa.LORAWAN)

        # Join a network using OTAA (Over the Air Activation)
        self.lora.join(activation=LoRa.OTAA,
                       auth=(dev_eui, app_eui, app_key),
                       timeout=0)

        # Wait until the module has joined the network
        count = 0
        while not self.lora.has_joined():
            LED.blink(1, 2.5, 0xff0000)
            # print("Trying to join: " ,  count)
            count = count + 1

        # Create a LoRa socket
        LED.blink(2, 0.1)
        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # Set the LoRaWAN data rate
        self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

        # Make the socket non-blocking
        self.s.setblocking(False)

        # print ("Joined! ",  count)
        # print("Create LoRaWAN socket")

        # Create a raw LoRa socket
        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.s.setblocking(False)
Example #8
0
    def send(self, data):
        """
    Send data over the network.
    """

        try:
            self.s.send(data)
            LED.blink(2, 0.1, 0x00ff00)
            print("Sending data:")
            print(data)
        except OSError as e:
            if e.errno == 11:
                print("Caught exception while sending")
                print("errno: ", e.errno)

        LED.off()
        data = self.s.recv(64)
        print("Received data:", data)

        return data
Example #9
0
def DoMeteo():
  global useMeteo, nl, LF
  global Meteo, meteo
  global M_SDA, M_SCL
  mData = [0,0,0,0,0]; sData = ""
  if not useMeteo or not meteo: return mData

  # Measure temp oC, rel hum %, pres pHa, gas Ohm, aqi %
  LED.blink(3,0.1,0x002200,False)
  error = None
  try: 
    nr = indexBus(i2cPINs,i2c,(M_SDA,M_SCL))
    if (meteo == 4) and (not useMeteo.gas_base): # BME680
      display("AQI base: wait"); nl -= LF
    i2c[nr].init(nr, pins=i2cPINs[nr]) # SPI oled causes bus errors
    sleep(1)
    try:
      mData[TEMP] = float(useMeteo.temperature) # string '20.12'
      sData += "%4.1f " % round(mData[TEMP],1)
    except:
      mData[TEMP] = 0; error = TEMP
      sData += "  ?  "
    try:
      mData[HUM] = float(useMeteo.humidity)     # string '25'
      sData += "%2d " % round(mData[HUM])
    except:
      mData[HUM] = 0; error = HUM
      sData += " ? "
    try:
      mData[PRES] = float(useMeteo.pressure)    # string '1021.60'
      sData += "%4d " % round(mData[PRES])
    except:
      mData[PRES] = 0; error = PRES
      sData += "   ? "
    if meteo == 4: # BME680
      try:
        mData[GAS] = float(useMeteo.gas)        # Ohm 29123
        # sData += "%4.1f " % round(mData[GAS]/1000.0,1)
      except:
        mData[GAS] = 0; error = GAS
        #sData += "  ?  "
      try:
        mData[AQI] = round(float(useMeteo.AQI),1) # 0-100% ok
        sData += "%2d" % round(mData[AQI])
      except:
        mData[AQI] = 0; error = AQI
        sData += " ?"
      rectangle(0,nl,128,LF,0)
  except Exception as e:
    display("%s ERROR" % Meteo[meteo])
    print(e)
    LED.blink(5,0.1,0xff00ff,True)
    return [0,0,0,0,0]
  if error != None:
    print("no value for %s" % ['oC','RH','hPa','gas','AQI'][error])
    LED.blink(5,0.1,0xff0099,True)

  LED.off()
  nl += 6  # oled spacing
  display("  C hum%% pHa%s" % (' AQI' if mData[GAS] > 0 else ''))
  display("o",(8,-5),prt=False)
  display(sData)
  return mData # temp, hum, pres, gas, aqia
'''
功能介绍: LED闪烁例程

版本: v1
版本说明: 
    逐行控制高低电平与延迟
'''
import utime
from led import LED

# 声明一个LED对象 (P2)
led = LED(0)

while True:
    # 点亮LED
    led.on()
    # 延时 500ms
    utime.sleep_ms(500)
    # 关闭LED
    led.off()
    # 延时500ms
    utime.sleep_ms(500)
# start all
def buzzing(buzz):
    while buzz.status == "ON":
        buzz.blink()
    else:
        return


try:
    thread.start_new_thread(buzzing, (buzz, ))
    while True:
        distance = sensor.read()
        if distance == -1:
            print "Distance Is Out Of Range"
            warningLed.off()
            dangerLed.off()
        else:
            buzz.setDelay(float(distance * 0.03))
            if distance <= 22 and distance >= 12:
                warningLed.on()
                dangerLed.off()
            elif distance < 12:
                warningLed.off()
                dangerLed.on()
            else:
                warningLed.off()
                dangerLed.off()
            print "Distance:", distance, "cm"

except Exception: