Ejemplo n.º 1
0
    def calibrate(self):
        """ The microcontroller will send the value of CTRL_0 after setting the bit
            and then will send the following pattern through the data line:

               val | 1 | 0 | 1*| 0 | 1*| 0 | 1
               ms  | 1 | 1 | 1 | 1 | 8 | 1 | -

            The idea is to measure the real life duration of periods marked with *
            and substract them. That will remove any errors common to both measurements
            The result is 7 ms as generated by the PIC LF clock.
            It can be used to scale any future sleep value. """

        # setbits, but limit the number of received bytes to avoid confusion with pattern
        self._magic(CTRL_0_ADDR, 0xFF, 1 << 2, 0, 0)
        self.uart.deinit()
        self._pulses = pycom.pulses_get(COMM_PIN, 50)
        self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ))
        try:
            self.clk_cal_factor = (self._pulses[4][1] - self._pulses[1][1]) / EXP_RTC_PERIOD
        except:
            pass
        if self.clk_cal_factor > 1.25 or self.clk_cal_factor < 0.75:
            self.clk_cal_factor = 1
Ejemplo n.º 2
0
def takePhotoAndSaveToFile(filename=None, retry=True):
    global uart

    SDCard.mountSDCard()
    uart = UART(2, baudrate=BAUD, pins=(TX,RX), timeout_chars=5)
    uart.readall()
    setsize(VC0706_160x120)
    reset()
    uart.readall()
    if(not getversion()):
        print("Camera not found")
        return(0)

    if takephoto():
        if(filename == None):
            filename = ''.join(map(str,RTC().now()))+'.jpg';

        f = open('/sd/'+filename, 'wb');

        try:
            gc.collect()
            readbuffer(getbufferlength(), f)
            return filename
        except Exception as e:
            print(e)
            if(retry):
                try:
                    time.sleep(2)
                    f.close()
                    gc.collect()
                    return takePhotoAndSaveToFile(filename, False)
                except Exception as ee:
                    print(ee)
        finally:
            f.close()
            uart.deinit()
            gc.collect()
Ejemplo n.º 3
0
 def __init__(self):
     self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ))
     self.clk_cal_factor = 1
     self.uart.read()
     # enable the weak pull-ups control
     self.clearbits(OPTION_REG_ADDR, 1 << 7)
Ejemplo n.º 4
0
import sensor, image, lcd
import KPU as kpu
from fpioa_manager import fm
from machine import UART
from board import board_info

lcd.init()
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.set_windowing((224, 224))
sensor.set_vflip(1)
sensor.run(1)
fm.register(board_info.PIN15, fm.fpioa.UART1_TX)
fm.register(board_info.PIN17, fm.fpioa.UART1_RX)
uart_A = UART(UART.UART1, 115200, 8, None, 1, timeout=1000, read_buf_len=4096)

classes = ["racoon"]
task = kpu.load(0x600000)
anchor = (0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282,
          3.52778, 9.77052, 9.16828)
a = kpu.init_yolo2(task, 0.3, 0.3, 5, anchor)
while (True):
    img = sensor.snapshot().rotation_corr(z_rotation=90.0)
    a = img.pix_to_ai()
    code = kpu.run_yolo2(task, img)
    if code:
        for i in code:
            a = img.draw_rectangle(i.rect(), color=(0, 255, 0))
            a = img.draw_string(i.x(),
                                i.y(),
Ejemplo n.º 5
0
    def __run(self,
              file_path=None,
              baudrate=921600,
              port=None,
              resume=False,
              load_ffh=False,
              mirror=False,
              switch_ffh=False,
              bootrom=False,
              rgbled=0x050505,
              debug=False,
              pkgdebug=False,
              atneg=True,
              max_try=10,
              direct=True,
              atneg_only=False,
              info_only=False,
              expected_smod=None,
              verbose=False,
              load_fff=False):
        self.__wait_msg = False
        mirror = True if atneg_only else mirror
        recover = True if atneg_only else load_ffh
        resume = True if mirror or recover or atneg_only or info_only else resume
        verbose = True if debug else verbose
        load_fff = False if bootrom and switch_ffh else load_fff
        target_baudrate = baudrate
        baudrate = self.__modem_speed if self.__speed_detected else baudrate
        if debug:
            print(
                'mirror? {}  recover? {}  resume? {}  direct? {}  atneg_only? {} bootrom? {} load_fff? {}'
                .format(mirror, recover, resume, direct, atneg_only, bootrom,
                        load_fff))
        if debug:
            print('baudrate: {} target_baudrate: {}'.format(
                baudrate, target_baudrate))
        abort = True
        external = False
        self.__serial = None

        if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:

            self.__serial = UART(1,
                                 baudrate=115200 if recover
                                 and not self.__speed_detected else baudrate,
                                 pins=self.__pins,
                                 timeout_chars=100)
            self.__serial.read()
        else:
            if port is None:
                raise ValueError('serial port not specified')
            if debug: print('Setting port {}'.format(port))
            external = True
            br = 115200 if recover and not direct else baudrate
            if debug: print('Setting baudrate to {}'.format(br))
            self.__serial = serial.Serial(port,
                                          br,
                                          bytesize=serial.EIGHTBITS,
                                          timeout=1 if info_only else 0.1)
            self.__serial.reset_input_buffer()
            self.__serial.reset_output_buffer()

        if info_only:
            self.__serial.read()
            self.__serial.write(b'AT\r\n')
            self.__serial.write(b'AT\r\n')
            self.__serial.read()
            self.__serial.write(b"AT+CGSN\r\n")
            time.sleep(.5)
            shimei = self.read_rsp(2000)
            if verbose:
                self.__serial.write(b"AT!=\"showver\"\r\n")
            else:
                self.__serial.write(b"ATI1\r\n")
            time.sleep(.5)
            shver = self.read_rsp(2000)
            if shver is not None:
                self.print_pretty_response(shver)
            if shimei is not None:
                self.print_pretty_response(shimei, prefix='\nIMEI:')
            return True

        if debug: print('Initial prepartion complete...')

        if not mirror:
            if bootrom:
                if debug: print('Loading built-in recovery bootrom...')
                try:
                    # try compressed bootrom first
                    from sqnsbrz import bootrom
                except:
                    # fallback to uncompressed
                    from sqnsbr import bootrom
                blob = bootrom()
                blobsize = blob.get_size()
            else:
                if debug: print('Loading {}'.format(file_path))
                blobsize = os.stat(file_path)[6]
                if blobsize < 128:
                    print('Firmware file is too small!')
                    reconnect_uart()
                    sys.exit(1)
                if blobsize > 4194304:
                    if load_fff:
                        print(
                            "Firmware file is too big to load via FFF method. Using ON_THE_FLY"
                        )
                    load_fff = False
                blob = open(file_path, "rb")

        if not load_ffh:
            if not self.wakeup_modem(baudrate, port, 10, 1, debug):
                return False

        if not resume:

            # bind to AT channel
            self.__serial.write(b"AT+BIND=AT\r\n")
            time.sleep(.5)
            response = self.read_rsp(size=100)
            if debug: print("AT+BIND=AT returned {}".format(response))

            # disable echo
            self.__serial.write(b"ATE0\r\n")
            time.sleep(.5)
            response = self.read_rsp(size=100)
            if debug: print("ATE0 returned {}".format(response))

            self.__serial.read(100)
            if debug: print('Entering upgrade mode...')

            self.__serial.write(b"AT+SMOD?\r\n")
            response = self.return_pretty_response(self.read_rsp(size=7))
            self.__serial.read(100)
            if debug: print("AT+SMOD? returned {}".format(response))

            self.__serial.write(b"AT+SQNSUPGRADENTF=\"started\"\r\n")
            self.wait_for_modem()
            if not load_fff:
                self.__serial.write(b"AT+SMSWBOOT=3,1\r\n")
                resp = self.read_rsp(100)
                if debug: print('AT+SMSWBOOT=3,1 returned: {}'.format(resp))
                if b'ERROR' in resp:
                    time.sleep(5)
                    self.__serial.write(b"AT+SMSWBOOT=3,0\r\n")
                    resp = self.read_rsp(100)
                    if debug:
                        print('AT+SMSWBOOT=3,0 returned: {}'.format(resp))
                    if b'OK' in resp:
                        self.__serial.write(b"AT^RESET\r\n")
                        resp = self.read_rsp(100)
                        if debug: print('AT^RESET returned: {}'.format(resp))
                    else:
                        print('Received ERROR from AT+SMSWBOOT=3,1! Aborting!')
                        reconnect_uart()
                        sys.exit(1)
                time.sleep(3)
                resp = self.__serial.read()
                if debug: print("Response after reset: {}".format(resp))
                self.wait_for_modem()
                self.__serial.write(b"AT\r\n")

        else:
            self.__serial.read(100)
            if debug: print('Entering recovery mode')

            self.__serial.write(b"AT+SMOD?\r\n")
            response = self.return_pretty_response(self.read_rsp(size=7))
            self.__serial.read(100)
            if debug: print("AT+SMOD? returned {}".format(response))

        time.sleep(1)
        self.__serial.read()

        if (not recover) and (not direct):
            if mirror:
                time.sleep(.5)
                self.__serial.read(100)
                print(
                    'Going into MIRROR mode... please close this terminal to resume the upgrade via UART'
                )
                self.uart_mirror(rgbled)

            elif bootrom:
                if verbose: print('Starting STP')
            else:
                if verbose:
                    if load_fff:
                        print('Starting STP [FFF]')
                    else:
                        print('Starting STP ON_THE_FLY')

            self.__serial.read(100)
            if verbose: print("Sending AT+CFUN=4")
            resonse = self.__serial.write(b'AT+CFUN=4\r\n')
            if verbose: print("AT+CFUN=4 returned {}".format(response))
            self.__serial.read(100)

            if load_fff:
                if debug: print("Sending AT+SMSTPU")
                self.__serial.write(b'AT+SMSTPU\r\n')
            else:
                if debug: print("Sending AT+SMSTPU=\"ON_THE_FLY\"")
                self.__serial.write(b'AT+SMSTPU=\"ON_THE_FLY\"\r\n')

            response = self.read_rsp(size=4)
            if response != b'OK\r\n' and response != b'\r\nOK' and response != b'\nOK':
                raise OSError("Invalid answer '%s' from the device" % response)
                blob.close()

            self.__serial.read()
        elif recover and (not direct):
            if atneg:
                result = self.at_negotiation(baudrate, port, max_try, mirror,
                                             atneg_only, debug,
                                             target_baudrate)
                if result:
                    baudrate = target_baudrate
                    self.__modem_speed = target_baudrate
                    self.__speed_detected = True
                    if atneg_only:
                        return True
                    if mirror:
                        time.sleep(.5)
                        self.__serial.read(100)
                        print(
                            'Going into MIRROR mode... please close this terminal to resume the upgrade via UART'
                        )
                        self.uart_mirror(rgbled)
                    else:
                        self.__serial.write(b"AT+STP\n")
                        response = self.read_rsp(size=6)
                        if not b'OK' in response:
                            print('Failed to start STP mode!')
                            reconnect_uart()
                            sys.exit(1)
                else:
                    print('AT auto-negotiation failed! Exiting.')
                    return False
        else:
            if debug: print('Starting STP mode...')
            self.__serial.write(b"AT+STP\n")
            response = self.read_rsp(size=6)
            if not b'OK' in response:
                print('Failed to start STP mode!')
                reconnect_uart()
                sys.exit(1)

        try:
            if debug:
                if verbose: print('Starting STP code upload')
            if stp.start(blob,
                         blobsize,
                         self.__serial,
                         baudrate,
                         AT=False,
                         debug=debug,
                         pkgdebug=pkgdebug):
                blob.close()
                self.__serial.read()
                if switch_ffh:
                    if verbose:
                        print(
                            'Bootrom updated successfully, switching to recovery mode'
                        )
                    abort = False
                elif load_ffh:
                    if not self.wakeup_modem(baudrate, port, 100, 1, debug,
                                             'Waiting for updater to load...'):
                        return False
                    if verbose:
                        print(
                            'Upgrader loaded successfully, modem is in update mode'
                        )
                    return True
                else:
                    if verbose:
                        print('Code download done, returning to user mode')
                    abort = recover
            else:
                blob.close()
                print('Code download failed, aborting!')
                return False
        except:
            blob.close()
            print('Code download failed, aborting!')
            abort = True

        time.sleep(1.5)

        if not abort:
            self.__serial.read()
            if switch_ffh:
                self.__serial.write(b"AT+SMSWBOOT=0,1\r\n")
                resp = self.read_rsp(100)
                if debug: print("AT+SMSWBOOT=0,1 returned {}".format(resp))
                if b"ERROR" in resp:
                    time.sleep(5)
                    self.__serial.write(b"AT+SMSWBOOT=0,0\r\n")
                    resp = self.read_rsp(100)
                    if debug:
                        print('AT+SMSWBOOT=0,0 returned: {}'.format(resp))
                    if b'OK' in resp:
                        self.__serial.write(b"AT^RESET\r\n")
                        resp = self.read_rsp(100)
                        if debug: print('AT^RESET returned: {}'.format(resp))
                        return True
                    else:
                        print('Received ERROR from AT+SMSWBOOT=0,0! Aborting!')
                        return False
                return True
            else:
                if load_fff:
                    self.__serial.write(b"AT+SMUPGRADE\r\n")
                if not self.wakeup_modem(
                        baudrate, port, 100, 1, debug,
                        self.__get_wait_msg(load_fff=load_fff)):
                    print(
                        "Timeout while waiting for modem to finish updating!")
                    reconnect_uart()
                    sys.exit(1)

                start = time.time()
                while True:
                    self.__serial.read()
                    self.__serial.write(b"AT+SMUPGRADE?\r\n")
                    resp = self.read_rsp(1024)
                    if debug:
                        print("AT+SMUPGRADE? returned {} [timeout: {}]".format(
                            resp,
                            time.time() - start))

                    if resp == b'\x00' or resp == b'':
                        time.sleep(2)

                    if b'No report' in resp or b'on-going' in resp:
                        time.sleep(1)

                    if b'success' in resp or b'fail' in resp:
                        break

                    if time.time() - start >= 300:
                        raise OSError('Timeout waiting for modem to respond!')

                self.__serial.write(b"AT+SMSWBOOT?\r\n")
                resp = self.read_rsp(100)
                if debug: print("AT+SMSWBOOT? returned {}".format(resp))
                start = time.time()
                while (b"RECOVERY"
                       not in resp) and (b"FFH" not in resp) and (b"FFF"
                                                                  not in resp):
                    if debug: print("Timeout: {}".format(time.time() - start))
                    if time.time() - start >= 300:
                        reconnect_uart()
                        raise OSError('Timeout waiting for modem to respond!')
                    time.sleep(2)
                    if not self.wakeup_modem(
                            baudrate, port, 100, 1, debug,
                            self.__get_wait_msg(load_fff=load_fff)):
                        reconnect_uart()
                        raise OSError(
                            'Timeout while waiting for modem to finish updating!'
                        )
                    self.__serial.read()
                    self.__serial.write(b"AT+SMSWBOOT?\r\n")
                    resp = self.read_rsp(100)
                    if debug: print("AT+SMSWBOOT? returned {}".format(resp))
                self.__serial.read()
                self.__serial.write(b"AT+SMUPGRADE?\r\n")
                resp = self.read_rsp(1024)
                if debug: print("AT+SMUPGRADE? returned {}".format(resp))
                sqnup_result = self.return_upgrade_response(resp)
                if debug: print('This is my result: {}'.format(sqnup_result))
                if 'success' in sqnup_result:
                    if not load_fff:
                        self.special_print('Resetting.', end='', flush=True)
                        self.__serial.write(b"AT+SMSWBOOT=1,1\r\n")
                        if debug:
                            print("AT+SMSWBOOT=1,1 returned {}".format(resp))
                        if b"ERROR" in resp:
                            time.sleep(5)
                            self.__serial.write(b"AT+SMSWBOOT=1,0\r\n")
                            resp = self.read_rsp(100)
                            if debug:
                                print('AT+SMSWBOOT=1,0 returned: {}'.format(
                                    resp))
                            if b'OK' in resp:
                                self.__serial.write(b"AT^RESET\r\n")
                                resp = self.read_rsp(100)
                                if debug:
                                    print('AT^RESET returned: {}'.format(resp))
                                return True
                            else:
                                print(
                                    'Received ERROR from AT+SMSWBOOT=1,0! Aborting!'
                                )
                                return False
                        self.wait_for_modem(send=False,
                                            echo_char='.',
                                            expected=b'+SYSSTART')

                elif sqnup_result is not None:
                    print(
                        'Upgrade failed with result {}!'.format(sqnup_result))
                    print('Please check your firmware file(s)')
                else:
                    print("Invalid response after upgrade... aborting.")
                    reconnect_uart()
                    sys.exit(1)

                self.__serial.write(b"AT\r\n")
                self.__serial.write(b"AT\r\n")
                time.sleep(0.5)

                if 'success' in sqnup_result:
                    self.__serial.write(b"AT+SQNSUPGRADENTF=\"success\"\r\n")
                    self.__serial.read()
                    return True
                elif sqnup_result is None:
                    print(
                        'Modem upgrade was unsucessfull. Please check your firmware file(s)'
                    )
        return False
Ejemplo n.º 6
0
 def at_negotiation(self, baudrate, port, max_try, mirror, atneg_only,
                    debug, target_baudrate):
     MAX_TRY = max_try
     count = 0
     if debug:
         print(
             'Attempting AT auto-negotiation... with baudrate {} and target_baudrate {}'
             .format(baudrate, target_baudrate))
     else:
         print('Attempting AT auto-negotiation...')
     self.__serial.write(b"AT\r\n")
     response = self.read_rsp(size=20)
     if debug: print('{}'.format(response))
     while (not b'OK' in response) and (count < MAX_TRY):
         count = count + 1
         if debug: print('count={}'.format(count))
         time.sleep(1)
         self.__serial.read()
         self.__serial.write(b"AT\r\n")
         response = self.read_rsp(size=20)
         if debug: print('{}'.format(response))
     if b'OK' in response:
         self.__serial.read()
         cmd = "AT+IPR=%d\n" % target_baudrate
         if debug: print('Setting baudrate to {}'.format(target_baudrate))
         self.__serial.write(cmd.encode())
         response = self.read_rsp(size=6)
         if debug: print('{}'.format(response))
         if b'OK' in response:
             self.__modem_speed = target_baudrate
             self.__speed_detected = True
             if atneg_only:
                 return True
             if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
                 self.__serial = UART(1,
                                      baudrate=target_baudrate,
                                      pins=self.__pins,
                                      timeout_chars=100)
             else:
                 self.__serial = None
                 self.__serial = serial.Serial(port,
                                               target_baudrate,
                                               bytesize=serial.EIGHTBITS,
                                               timeout=0.1)
                 self.__serial.reset_input_buffer()
                 self.__serial.reset_output_buffer()
                 self.__serial.flush()
             self.__serial.read()
             if debug: print('Checking SMOD')
             self.__serial.write(b"AT+SMOD?\r\n")
             response = self.read_rsp(size=1)
             if b'0' in response:
                 if debug: print("AT+SMOD? returned {}".format(response))
                 self.__serial.read()
                 return True
             else:
                 print('ERROR in AT+SMOD returned {}'.format(response))
                 return False
         else:
             print('ERROR in AT+IPR={} returned {}'.format(
                 target_baudrate, response))
             return False
     else:
         print(
             'ERROR sending AT command... no response? {}'.format(response))
         return False
     time.sleep(1)
     return True
Ejemplo n.º 7
0
led = Pin(19, Pin.OUT)
led.on()

# Pin 16 is SSD1306 Display Enable
pin16 = Pin(16, Pin.OUT)
pin16.on()
displayi2c = I2C(scl=Pin(15), sda=Pin(4))
display = SSD1306_I2C(128, 64, displayi2c)
display.fill(0)

sensori2c = I2C(1, scl=Pin(22), sda=Pin(21), freq=50000)
vz = VZ89TE(sensori2c)
bme = BME680_I2C(sensori2c)
scd = SCD30(sensori2c)
mhz = MHZ19B(UART(1, tx=32, rx=33, baudrate=9600, timeout=1000))

print("Display Width: ", display.width)
print("Display Height: ", display.height)
print("I2C slave(s) found at adr ")
for ad in sensori2c.scan():
    print("%x " % ad)
print("Revision: ", vz.getRevision())
print("Year: ", vz.getRevision()["Year"])
print("Month: ", vz.getRevision()["Month"])
print("Day: ", vz.getRevision()["Day"])

CO2DISPMAX = 1000
CO2DISPMIN = 400

scd.start()
Ejemplo n.º 8
0
def wifi_reset():
    global uart
    wifi_enable(0)
    time.sleep_ms(200)
    wifi_enable(1)
    time.sleep(2)
    uart = UART(UART.UART2, 115200, timeout=1000, read_buf_len=4096)
    tmp = uart.read()
    uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
    print(uart.read())
    uart = UART(
        UART.UART2, 921600, timeout=1000, read_buf_len=10240
    )  # important! baudrate too low or read_buf_len too small will loose data
    uart.write("AT\r\n")
    tmp = uart.read()
    print(tmp)
    if not tmp.endswith("OK\r\n"):
        print("reset fail")
        return None
    try:
        nic = network.ESP8285(uart)
    except Exception:
        return None
    return nic
Ejemplo n.º 9
0
def wifi_init():
    global uart
    wifi_enable(0)
    time.sleep_ms(200)
    wifi_enable(1)
    time.sleep(2)
    uart = UART(UART.UART2, 115200, timeout=1000, read_buf_len=4096)
    tmp = uart.read()
    uart.write("AT+UART_CUR=921600,8,1,0,0\r\n")
    print(uart.read())
    uart = UART(UART.UART2, 921600, timeout=1000,
                read_buf_len=10240)  #实测模块波特率太低或者缓存长度太短会导致数据丢失。
    uart.write("AT\r\n")
    tmp = uart.read()
    print(tmp)
    if not tmp.endswith("OK\r\n"):
        print("reset fail")
        return None
    try:
        nic = network.ESP8285(uart)
    except Exception:
        return None
    return nic
Ejemplo n.º 10
0
# REPL duplication on UART0 for serial connection
from machine import UART
import os
uart0 = UART(0, 115200)
os.dupterm(uart0)

# Disable heartbeat LED
from pycom import heartbeat
heartbeat(False)

# Disable WiFi radio
from pycom import wifi_on_boot
wifi_on_boot(False)
Ejemplo n.º 11
0
Ver: 0.1
Last Update: 01/05/2018
Based on this work:
https://github.com/JurassicPork/DHT_PyCom/tree/pulses_get
code released with MIT License (MIT)
---------------------------------------------------------------------
"""
# from:
# https://github.com/JurassicPork/DHT_PyCom/tree/pulses_get
#
import pycom
import time
from machine import Pin
from dth import DTH
from machine import UART
uart = UART(1, 115200)

# connect the grove temperature/humidity (DHT11) sensor to digital connector J7 or J8
#  J7 connector: to I/O Pin 'P12'
#  J8 connector: to I/O Pin 'P11'

# Instantiate the DHT class with these parameters:
# 1) the pin number
# 2) type of sensor: 0 for DTH11, 1 for DTH22
th = DTH('P11',0)

# loop to read temperature / humidity from DHT11
#
time.sleep(2)
while True:
    # Call read() method, which will return DHTResult object with actual values and error code.
#
# Created: 06/04/16
#   - Joshua Vaughan
#   - [email protected]
#   - http://www.ucs.louisiana.edu/~jev9637
#
# Modified:
#   *
#
###############################################################################

import socket
import network
from machine import UART

uart = UART(0)
# uart.init(115200, bits=8, parity=None, stop=1) # init with given parameters

# Configuration constants
UDP_TIMEOUT = 0.0               # Timeout for UDP communications (s), if 0 go into nonblocking mode
UDP_PORT = 2390                 # Port to receive data on
RECV_BUFF_SIZE = 16             # Size of buffer for UDP data
SEND_TO_IP = '192.168.4.3'      # Address to send to
SEND_TO_PORT = 2390             # Port to send data to


# Blink the LED every 100ms to indicate we made it into the main.py file
for _ in range(10):
    time.sleep_ms(100)
    pin.value(not pin.value()) # Toggle the LED while trying to connect
    time.sleep_ms(100)
Ejemplo n.º 13
0
from machine import UART
import network
import socket
import time

WIFI_UNAME = "Jamal's iphone"
WIFI_PWORD = 'zoewantswifi'
WEBSITE = 'requestb.in'
PAGE = 'xfmsv4xf'

uart = UART(0, 9600)
uart.init(9600, bits=8, parity=None, stop=1)

wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
    wlan.connect(WIFI_UNAME, WIFI_PWORD)
    while not wlan.isconnected():
        pass

addr = socket.getaddrinfo(WEBSITE, 80)[0][-1]

while True:
    msg = uart.read()

    if msg:
        request_string = "POST /%s HTTP/1.0\r\nHost: %s\r\n\r\n" % (PAGE,
                                                                    WEBSITE)
        byte_string = bytes(request_string, 'utf8')
        s = socket.socket()
        s.connect(addr)
Ejemplo n.º 14
0
class SimpleDFPlayerMini:
    def __init__(self, uart_id, volume, mode):
        self._uart = UART(uart_id, baudrate=9600)
        self.resume()
        self.set_eq(1)
        self.set_vol(volume)
        self.set_mode(mode)
        self.pause()

    def _send_cmd(self, cmd, data_low=0, data_high=0):
        self._uart.write(b'\x7E')
        self._uart.write(b'\xFF')
        self._uart.write(b'\x06')
        self._uart.write(bytes([cmd]))
        self._uart.write(b'\x00')
        self._uart.write(bytes([data_high]))
        self._uart.write(bytes([data_low]))
        self._uart.write(b'\xEF')
        sleep_ms(200)

    def next_track(self):
        self._send_cmd(0x01)

    def prev_track(self):
        self._send_cmd(0x02)

    def sel_track(self, track_index):
        self._send_cmd(0x03, track_index)

    def inc_vol(self):
        self._send_cmd(0x04)

    def dec_vol(self):
        self._send_cmd(0x05)

    def set_vol(self, volume):
        self._send_cmd(0x06, volume)

    def set_eq(self, equalizer):
        self._send_cmd(0x07, equalizer)

    def set_mode(self, mode):
        self._send_cmd(0x08, mode)

    def suspend(self):
        self._send_cmd(0x0A)

    def resume(self):
        self._send_cmd(0x09, 1)

    def reset(self):
        self._send_cmd(0x0C)

    def play(self):
        self._send_cmd(0x0D)

    def pause(self):
        self._send_cmd(0x0E)

    def set_folder(self, folder_index):
        self._send_cmd(0x0F, folder_index)

    def enable_loop(self):
        self._send_cmd(0x11, 1)

    def disable_loop(self):
        self._send_cmd(0x11, 0)
Ejemplo n.º 15
0
# The MIT License (MIT)
# Copyright (c) 2020 Jan Cespivo, Jan Copak
# octopusLAB pubsub example

from examples.pubsub.ps_init import pubsub
from machine import UART

print("ESP32 + serial display pubsub test")

uart = UART(2, 115200)  #UART2 > #U2TXD(SERVO1/PWM1_PIN) #  9600/115200
# uart.write('C')      #test quick clear display


def display_send(bleuart):
    uart.write(bleuart)


pubsub.subscribe('bleuart', display_send)
Ejemplo n.º 16
0
from machine import UART
from network import LoRa
import socket
import binascii
import struct
import time
import config
import tools

DEBUG = config.DEBUG

speed = config.AUTO
update = config.UPDATE[speed]  # seconds between update

# Initialize GPS
com = UART(1, pins=(config.TX, config.RX), baudrate=9600)
my_gps = MicropyGPS()

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

# create an ABP authentication params
dev_addr = struct.unpack(">l",
                         binascii.unhexlify(config.DEV_ADDR.replace(' ',
                                                                    '')))[0]
nwk_swkey = binascii.unhexlify(config.NWK_SWKEY.replace(' ', ''))
app_swkey = binascii.unhexlify(config.APP_SWKEY.replace(' ', ''))

# join a network using ABP (Activation By Personalization)
lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))
Ejemplo n.º 17
0
from fpioa_manager import fm
from machine import UART
from board import board_info
from fpioa_manager import fm

# maixduino board_info PIN10/PIN11/PIN12/PIN13 or other hardware IO 12/11/10/3
fm.register(board_info.PIN10, fm.fpioa.UART1_TX, force=True)
fm.register(board_info.PIN11, fm.fpioa.UART1_RX, force=True)
fm.register(board_info.PIN12, fm.fpioa.UART2_TX, force=True)
fm.register(board_info.PIN13, fm.fpioa.UART2_RX, force=True)

uart_A = UART(UART.UART1, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)
uart_B = UART(UART.UART2, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)

write_bytes = b'hello world'
for i in range(20):
    uart_A.write(write_str)
    if uart_A.any():
        read_data = uart_B.read()
        if read_data:
            print("write_bytes = ", write_bytes)
            if read_data == write_bytes:
                print("baudrate:115200 bits:8 parity:0 stop:0 ---check Successfully")

uart_A.deinit()
uart_B.deinit()
del uart_A
del uart_B
Ejemplo n.º 18
0
mch = os.uname().machine
if 'LaunchPad' in mch:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
elif 'WiPy' in mch:
    uart_id_range = range(0, 2)
    uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]]
else:
    raise Exception('Board not supported!')

# just in case we have the repl duplicated on any of the uarts
os.dupterm(None)

for uart_id in uart_id_range:
    uart = UART(uart_id, 38400)
    print(uart)
    uart.init(57600, 8, None, 1, pins=uart_pins[uart_id][0])
    uart.init(baudrate=9600, stop=2, parity=UART.EVEN, pins=uart_pins[uart_id][1])
    uart.init(baudrate=115200, parity=UART.ODD, stop=0, pins=uart_pins[uart_id][0])
    uart = UART(baudrate=1000000)
    uart.sendbreak()

uart = UART(baudrate=1000000)
uart = UART()
print(uart)
uart = UART(baudrate=38400, pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=('GP12', 'GP13'))
print(uart)
uart = UART(pins=(None, 'GP17'))
Ejemplo n.º 19
0
class Serial:
    def __init__(self,
                 uart_id,
                 baudrate=38400,
                 data_bits=8,
                 stop_bits=1,
                 parity=None,
                 pins=None,
                 ctrl_pin=None):
        self._uart = UART(uart_id, baudrate=baudrate, bits=data_bits, parity=parity, \
                          stop=stop_bits, timeout_chars=50, pins=pins)
        if ctrl_pin is not None:
            self._ctrlPin = Pin(ctrl_pin, mode=Pin.OUT)
        else:
            self._ctrlPin = None
        self.char_time_ms = (1000 * (data_bits + stop_bits + 2)) // baudrate

    def _calculate_crc16(self, data):
        crc = 0xFFFF

        for char in data:
            crc = (crc >> 8) ^ Const.CRC16_TABLE[((crc) ^ char) & 0xFF]

        return struct.pack('<H', crc)

    def _bytes_to_bool(self, byte_list):
        bool_list = []
        for index, byte in enumerate(byte_list):
            bool_list.extend([bool(byte & (1 << n)) for n in range(8)])

        return bool_list

    def _to_short(self, byte_array, signed=True):
        response_quantity = int(len(byte_array) / 2)

        fmt = '>' + (('h' if signed else 'H') * response_quantity)

        return (byte_array)

    def _exit_read(self, response):
        if response[1] >= Const.ERROR_BIAS:
            if len(response) < Const.ERROR_RESP_LEN:
                return False
        elif (Const.READ_COILS <= response[1] <= Const.READ_INPUT_REGISTER):
            expected_len = Const.RESPONSE_HDR_LENGTH + 1 + response[
                2] + Const.CRC_LENGTH
            if len(response) < expected_len:
                return False
        elif len(response) < Const.FIXED_RESP_LEN:
            return False

        return True

    def _uart_read(self):
        response = bytearray()

        for x in range(1, 40):
            if self._uart.any():
                response.extend(self._uart.readall())
                # variable length function codes may require multiple reads
                if self._exit_read(response):
                    break
            time.sleep(0.05)

        return response

    def _send_receive(self, modbus_pdu, slave_addr, count):
        serial_pdu = bytearray()
        serial_pdu.append(slave_addr)
        serial_pdu.extend(modbus_pdu)

        crc = self._calculate_crc16(serial_pdu)
        serial_pdu.extend(crc)

        # flush the Rx FIFO
        self._uart.read()
        if self._ctrlPin:
            self._ctrlPin(1)
        self._uart.write(serial_pdu)
        if self._ctrlPin:
            while not self._uart.wait_tx_done(2):
                machine.idle()
            time.sleep_ms(1 + self.char_time_ms)
            self._ctrlPin(0)

        return self._validate_resp_hdr(self._uart_read(), slave_addr,
                                       modbus_pdu[0], count)

    def _validate_resp_hdr(self, response, slave_addr, function_code, count):

        if len(response) == 0:
            raise OSError('no data received from slave')

        resp_crc = response[-Const.CRC_LENGTH:]

        expected_crc = self._calculate_crc16(response[0:len(response) -
                                                      Const.CRC_LENGTH])

        if (resp_crc[0] != expected_crc[0]) or (resp_crc[1] !=
                                                expected_crc[1]):
            raise OSError('invalid response CRC')

        if (response[0] != slave_addr):
            raise ValueError('wrong slave address')

        if (response[1] == (function_code + Const.ERROR_BIAS)):
            raise ValueError('slave returned exception code: {:d}'.format(
                response[2]))

        hdr_length = (Const.RESPONSE_HDR_LENGTH +
                      1) if count else Const.RESPONSE_HDR_LENGTH

        return response[hdr_length:len(response) - Const.CRC_LENGTH]

    def read_coils(self, slave_addr, starting_addr, coil_qty):
        modbus_pdu = functions.read_coils(starting_addr, coil_qty)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        status_pdu = self._bytes_to_bool(resp_data)

        return status_pdu

    def read_discrete_inputs(self, slave_addr, starting_addr, input_qty):
        modbus_pdu = functions.read_discrete_inputs(starting_addr, input_qty)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        status_pdu = self._bytes_to_bool(resp_data)

        return status_pdu

    def read_holding_registers(self,
                               slave_addr,
                               starting_addr,
                               register_qty,
                               signed=True):
        modbus_pdu = functions.read_holding_registers(starting_addr,
                                                      register_qty)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        register_value = self._to_short(resp_data, signed)

        return register_value

    def read_input_registers(self,
                             slave_addr,
                             starting_address,
                             register_quantity,
                             signed=True):
        modbus_pdu = functions.read_input_registers(starting_address,
                                                    register_quantity)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        register_value = self._to_short(resp_data, signed)

        return resp_data

    def write_single_coil(self, slave_addr, output_address, output_value):
        modbus_pdu = functions.write_single_coil(output_address, output_value)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_SINGLE_COIL,
            output_address,
            value=output_value,
            signed=False)

        return operation_status

    def write_single_register(self,
                              slave_addr,
                              register_address,
                              register_value,
                              signed=True):
        modbus_pdu = functions.write_single_register(register_address,
                                                     register_value, signed)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_SINGLE_REGISTER,
            register_address,
            value=register_value,
            signed=signed)

        return operation_status

    def write_multiple_coils(self, slave_addr, starting_address,
                             output_values):
        modbus_pdu = functions.write_multiple_coils(starting_address,
                                                    output_values)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_MULTIPLE_COILS,
            starting_address,
            quantity=len(output_values))

        return operation_status

    def write_multiple_registers(self,
                                 slave_addr,
                                 starting_address,
                                 register_values,
                                 signed=True):
        modbus_pdu = functions.write_multiple_registers(
            starting_address, register_values, signed)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_MULTIPLE_REGISTERS,
            starting_address,
            quantity=len(register_values))

        return operation_status
Ejemplo n.º 20
0
def startSensors(uart = None, uart2 = None, i2c = None, spi = None, logger = None, hpma_pin=None, pms_pin=None, **kwargs):

	sensors = dict()

#	hpma_pin 	= Pin(16, Pin.OUT) #Se?al de activaci?n de transistor
	# pms_pin 	= Pin(4, Pin.OUT) #Se?al de activaci?n de transistor

	# Inicia sensor PMS7003

	try:
		pms_pin.value(1)
		pms = PMS7003(uart2)
		if(pms.init()):
			pmok=1
			sensors["pms7003"] = pms
			logger.success("Sensor PMS7003 inicializado")
	except Exception as e:
		print(repr(e))
		pms_pin.value(0)

	if not uart is None:
		sensors=startSPS30(1,sensors,uart,hpma_pin,logger)

	if not "sps30" in sensors:
		
		uart.deinit()
		uart 	= UART(2, baudrate=9600, rx=32, tx=17, timeout=1000)
		sensors	=startHPMA115S0(1, sensors,uart, hpma_pin,logger)

	if not "pms7003" in sensors and not "am2315" in sensors:
		print("iniciando AM2302")
		tmout = timee() + 2   # 2 segundos
		test = 0
		while True:
			try:
#			am2302_pin	= Pin(4, Pin.OUT) #Senal de activaci?n de transistor
				pms_pin.value(1)
				sleep(0.1)
				am2302 = DHT22(Pin(2))
				am2302.measure()
				sensors["am2302"] = am2302
#			print(sensors["am2302"].humidity())
#			print(sensors["am2302"].temperature())
				print("Sensor AM2302 inicializado")
				logger.success("Sensor AM2302 inicializado")
				break
			except Exception as e:
#					sys.print_exception(e)	
				print(repr(e))
			if (test == 3 or timee() > tmout):
				print("No se pudo iniciar AM2302")
				del am2302
				pms_pin.value(0)
#				sleep(0.5)
				break
			test = test + 1
#			pms_pin.value(0)
			sleep(0.5)

	if not i2c is None:
		# Inicia sensor AM2315
		tmout = timee() + 5   # 5 segundos
		test = 0
		while True:
			try:
				am2315 = AM2315( i2c = i2c )
				print("Iniciando sensor AM2315...")
				if(am2315.measure()):
					print("AM2315 inicializado")
					logger.success("Sensor AM2315 inicializado")
					sensors["am2315"] = am2315	
					break
			except Exception as e:
				print_exception(e)	
				print("No se pudo iniciar AM2315")
				print(repr(e))
				
			if (test == 5 or timee() > tmout):
				print("No se pudo iniciar AM2315")
				break
			test = test + 1
		
		try:
			# Inicia sensor INA219
			#Crea hilo para lectura del sensor am2315
			ina219 = INA219_(buffLen = 3, period = 5, sem = None, on_read = None, **kwargs)
			#Comienza lectura del sensor
			_thread.start_new_thread(ina219.run, ())
			sensors["ina219"] = ina219
		except Exception as e:
			print_exception(e)	
			print("No se pudo iniciar INA219")
			print(repr(e))

	if not spi is None:
		pass

	if not "am2302" in sensors and not "sps30-2" in sensors and not "pms7003" in sensors:
		try:
			uart2.deinit()
		except Exception as e:
			pass
		uart2 	= UART(1, baudrate=9600, rx=33, tx=2, timeout=1000)
		sensors=startHPMA115S0(2, sensors,uart2, pms_pin)
		
	return sensors
Ejemplo n.º 21
0
# Simple GPS module demonstration.
"""
This is a test program for the GOOUUU tech GT-U7 GPS board.


I'm using the micropyGPS library to receive updates.  Unfortunately,
the module, while getting fixes and sending time and locations, does
not seem to answer NMEA commands.

"""
from machine import UART, Pin
import utime as time

from micropyGPS import MicropyGPS

uart = UART(1, baudrate=9600)
uart.init(rx=21, tx=18)

mygps = MicropyGPS()


def send_command(command, add_checksum=True):
    """Send a command string to the GPS.  If add_checksum is True (the
    default) a NMEA checksum will automatically be computed and added.
    Note you should NOT add the leading $ and trailing * to the command
    as they will automatically be added!
    """
    uart.write('$')
    uart.write(command)
    print("sending: $" + command, end='')
    if add_checksum:
Ejemplo n.º 22
0
# boot.py -- run on boot-up
import os
from machine import UART

uart = UART(0, 115200)
os.dupterm(uart)
Ejemplo n.º 23
0
class uModBusSerial:
    def __init__(self,
                 uart_id,
                 baudrate=9600,
                 data_bits=8,
                 stop_bits=1,
                 parity=None,
                 pins=None,
                 ctrl_pin=None):
        pinsLen = len(pins)
        if pins == None or pinsLen < 2 or pinsLen > 4 or pinsLen == 3:
            raise ValueError(
                'pins should contain pin names/numbers for: tx, rx, [rts, cts]'
            )

        # need to read registers to get tx fifo empty
        if uart_id == 0:
            self.uart_base = 0x40034000
        else:
            self.uart_base = 0x40038000

        self.char_timeout = (25000 // baudrate) + 10

        tx = pins[0]
        rx = pins[1]
        if pinsLen == 4:
            rts = pins[2]
            cts = pins[3]
            self._uart = UART(uart_id, baudrate=baudrate, bits=data_bits, parity=parity, \
                          stop=stop_bits, tx=tx, rx=rx, rts=rts, cts=cts)
        else:
            self._uart = UART(uart_id, baudrate=baudrate, bits=data_bits, parity=parity, \
                            stop=stop_bits,tx=tx, rx=rx)
        #self._uart = UART(uart_id, baudrate=baudrate, bits=data_bits, parity=parity, \
        #                  stop=stop_bits, timeout_chars=10, pins=pins)
        if ctrl_pin is not None:
            self._ctrlPin = Pin(ctrl_pin, mode=Pin.OUT)
        else:
            self._ctrlPin = None
        self.char_time_ms = (1000 * (data_bits + stop_bits + 2)) // baudrate

    # function added because UART library is not completed
    def wait_tx_done(self, value):
        # check register to figure out if output uart tx is done
        # check buzy flag
        while (mem32[self.uart_base + 0x18] & 8) == 8:
            pass
        return True

    def read_timeOut(self):
        now = time.ticks_ms()
        value = b''
        while True:
            if (time.ticks_ms() - now) > self.char_timeout:
                break
            if self._uart.any():
                value = value + self._uart.read(1)
                now = time.ticks_ms()
        return value

    def _calculate_crc16(self, data):
        crc = 0xFFFF

        for char in data:
            crc = (crc >> 8) ^ Const.CRC16_TABLE[((crc) ^ char) & 0xFF]

        return struct.pack('<H', crc)

    def _bytes_to_bool(self, byte_list):
        bool_list = []
        for index, byte in enumerate(byte_list):
            bool_list.extend([bool(byte & (1 << n)) for n in range(8)])

        return bool_list

    def _to_short(self, byte_array, signed=True):
        response_quantity = int(len(byte_array) / 2)
        fmt = '>' + (('h' if signed else 'H') * response_quantity)

        return struct.unpack(fmt, byte_array)

    def _exit_read(self, response):
        if response[1] >= Const.ERROR_BIAS:
            if len(response) < Const.ERROR_RESP_LEN:
                return False
        elif (Const.READ_COILS <= response[1] <= Const.READ_INPUT_REGISTER):
            expected_len = Const.RESPONSE_HDR_LENGTH + 1 + response[
                2] + Const.CRC_LENGTH
            if len(response) < expected_len:
                return False
        elif len(response) < Const.FIXED_RESP_LEN:
            return False

        return True

    def _uart_read(self):
        response = bytearray()

        for x in range(1, 40):
            if self._uart.any():
                response.extend(self.read_timeOut())
                #response.extend(self._uart.readall())
                # variable length function codes may require multiple reads
                if self._exit_read(response):
                    break
            time.sleep(0.05)

        return response

    def _send_receive(self, modbus_pdu, slave_addr, count):
        serial_pdu = bytearray()
        serial_pdu.append(slave_addr)
        serial_pdu.extend(modbus_pdu)

        crc = self._calculate_crc16(serial_pdu)
        serial_pdu.extend(crc)

        # flush the Rx FIFO
        self.read_timeOut()
        if self._ctrlPin:
            self._ctrlPin(1)
        self._uart.write(serial_pdu)
        if self._ctrlPin:
            while not self.wait_tx_done(2):
                machine.idle()
            time.sleep_ms(1 + self.char_time_ms)
            self._ctrlPin(0)

        return self._validate_resp_hdr(self.read_timeOut(), slave_addr,
                                       modbus_pdu[0], count)

    def _validate_resp_hdr(self, response, slave_addr, function_code, count):

        if len(response) == 0:
            raise OSError('no data received from slave')

        resp_crc = response[-Const.CRC_LENGTH:]
        expected_crc = self._calculate_crc16(response[0:len(response) -
                                                      Const.CRC_LENGTH])
        if (resp_crc[0] != expected_crc[0]) or (resp_crc[1] !=
                                                expected_crc[1]):
            raise OSError('invalid response CRC')

        if (response[0] != slave_addr):
            raise ValueError('wrong slave address')

        if (response[1] == (function_code + Const.ERROR_BIAS)):
            raise ValueError('slave returned exception code: {:d}'.format(
                response[2]))

        hdr_length = (Const.RESPONSE_HDR_LENGTH +
                      1) if count else Const.RESPONSE_HDR_LENGTH

        return response[hdr_length:len(response) - Const.CRC_LENGTH]

    def read_coils(self, slave_addr, starting_addr, coil_qty):
        modbus_pdu = functions.read_coils(starting_addr, coil_qty)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        status_pdu = self._bytes_to_bool(resp_data)

        return status_pdu

    def read_discrete_inputs(self, slave_addr, starting_addr, input_qty):
        modbus_pdu = functions.read_discrete_inputs(starting_addr, input_qty)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        status_pdu = self._bytes_to_bool(resp_data)

        return status_pdu

    def read_holding_registers(self,
                               slave_addr,
                               starting_addr,
                               register_qty,
                               signed=True):
        modbus_pdu = functions.read_holding_registers(starting_addr,
                                                      register_qty)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        register_value = self._to_short(resp_data, signed)

        return register_value

    def read_input_registers(self,
                             slave_addr,
                             starting_address,
                             register_quantity,
                             signed=True):
        modbus_pdu = functions.read_input_registers(starting_address,
                                                    register_quantity)

        resp_data = self._send_receive(modbus_pdu, slave_addr, True)
        register_value = self._to_short(resp_data, signed)

        return register_value

    def write_single_coil(self, slave_addr, output_address, output_value):
        modbus_pdu = functions.write_single_coil(output_address, output_value)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_SINGLE_COIL,
            output_address,
            value=output_value,
            signed=False)

        return operation_status

    def write_single_register(self,
                              slave_addr,
                              register_address,
                              register_value,
                              signed=True):
        modbus_pdu = functions.write_single_register(register_address,
                                                     register_value, signed)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_SINGLE_REGISTER,
            register_address,
            value=register_value,
            signed=signed)

        return operation_status

    def write_multiple_coils(self, slave_addr, starting_address,
                             output_values):
        modbus_pdu = functions.write_multiple_coils(starting_address,
                                                    output_values)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_MULTIPLE_COILS,
            starting_address,
            quantity=len(output_values))

        return operation_status

    def write_multiple_registers(self,
                                 slave_addr,
                                 starting_address,
                                 register_values,
                                 signed=True):
        modbus_pdu = functions.write_multiple_registers(
            starting_address, register_values, signed)

        resp_data = self._send_receive(modbus_pdu, slave_addr, False)
        operation_status = functions.validate_resp_data(
            resp_data,
            Const.WRITE_MULTIPLE_REGISTERS,
            starting_address,
            quantity=len(register_values))

        return operation_status

    def close(self):
        if self._uart == None:
            return
        try:
            self._uart.deinit()
        except Exception:
            pass
    sensor.set_framesize(sensor.QVGA)  #QVGA=320x240
    sensor.set_windowing((224, 224))
    sensor.run(1)


m5stickv_init()

fm.register(board_info.BUTTON_A, fm.fpioa.GPIO1)
but_a = GPIO(GPIO.GPIO1, GPIO.IN, GPIO.PULL_UP)

fm.register(board_info.BUTTON_B, fm.fpioa.GPIO2)
but_b = GPIO(GPIO.GPIO2, GPIO.IN, GPIO.PULL_UP)

fm.register(35, fm.fpioa.UART2_TX, force=True)
fm.register(34, fm.fpioa.UART2_RX, force=True)
uart_Port = UART(UART.UART2, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)

task = kpu.load(0x200000)
#task = kpu.load("mbnet751.kmodel")#Within_SDCard
print(kpu.memtest())

set = kpu.set_layers(task, 29)

but_a_pressed = 0
but_b_pressed = 0

master_data = []
for i in range(768):
    master_data.append(0)
w_data = 0.99
Ejemplo n.º 25
0
import utime
from machine import UART
from machine import Pin
import Lcd1_14driver
import time
import vga1_bold_16x32 as font

txdata = "123456"
    
lora = UART(0,baudrate = 9600,tx = Pin(0),rx = Pin(1))
LCD = Lcd1_14driver.Lcd1_14()#driver of lcd display

def lcd_border():
        LCD.hline(10,10,220,LCD.blue)
        LCD.hline(10,125,220,LCD.blue)
        LCD.vline(10,10,115,LCD.blue)
        LCD.vline(230,10,115,LCD.blue)       
        LCD.lcd_show()
    
def infoDevice():
        LCD.fill(LCD.white) 
        LCD.lcd_show()
        lcd_border()
        
        LCD.text("SB-COMPONENTS",70,40,LCD.red)
        LCD.text("PICO LORA ",70,60,LCD.red)
        LCD.text("EXPANSION",70,80,LCD.red)  
        LCD.lcd_show()
        time.sleep(2)
        LCD.fill(0xFFFF)
        
Ejemplo n.º 26
0
 def detect_modem_state(self,
                        retry=5,
                        initial_delay=1000,
                        hangup=True,
                        debug=False):
     count = 0
     self.__serial = UART(1,
                          baudrate=921600,
                          pins=self.__pins,
                          timeout_chars=1)
     self.__modem_speed = 921600
     self.__serial.read()
     while count < retry:
         count += 1
         delay = initial_delay * count
         if debug: print("The current delay is {}".format(delay))
         self.__serial = UART(1,
                              baudrate=921600,
                              pins=self.__pins,
                              timeout_chars=10)
         self.__modem_speed = 921600
         #if True:
         if hangup and self.__hangup_modem(initial_delay, debug):
             self.__speed_detected = True
             self.__serial.write(b"AT+SMOD?\r\n")
             time.sleep_ms(delay)
             resp = self.__serial.read()
             if debug: print('Response (AT+SMOD?) {}'.format(resp))
             try:
                 return self.return_code(resp, debug)
             except:
                 pass
         else:
             self.__modem_speed = 921600
             self.__serial = UART(1,
                                  baudrate=921600,
                                  pins=self.__pins,
                                  timeout_chars=1)
             self.__serial.read()
             self.__serial.write(b"AT\r\n")
             time.sleep_ms(delay)
             resp = self.__serial.read()
             self.__check_resp(resp)
             if debug: print('Response (AT #3) {}'.format(resp))
             if resp is not None and b'OK' in resp:
                 self.__speed_detected = True
                 self.__serial.write(b"AT+SMOD?\r\n")
                 time.sleep_ms(delay)
                 resp = self.__serial.read()
                 try:
                     if debug: print('Response (AT+SMOD?) {}'.format(resp))
                     return self.return_code(resp, debug)
                 except:
                     pass
             self.__serial.write(b"AT\r\n")
             time.sleep_ms(delay)
             resp = self.__serial.read()
             self.__check_resp(resp)
             if debug: print('Response (AT #4) {}'.format(resp))
             if resp is not None and b'OK' in resp:
                 self.__speed_detected = True
                 self.__serial.write(b"AT+SMOD?\r\n")
                 time.sleep_ms(delay)
                 resp = self.__serial.read()
                 try:
                     return self.return_code(resp, debug)
                     if debug: print('Response (AT+SMOD?) {}'.format(resp))
                 except:
                     pass
             else:
                 if not self.__resp_921600:
                     self.__modem_speed = 115200
                     self.__serial = UART(1,
                                          baudrate=115200,
                                          pins=self.__pins,
                                          timeout_chars=10)
                     self.__serial.write(b"AT\r\n")
                     time.sleep_ms(delay)
                     resp = self.__serial.read()
                     if debug:
                         print('Response (AT #1 @ 115200) {}'.format(resp))
                     if resp is not None and b'OK' in resp:
                         self.__speed_detected = True
                         self.__serial.write(b"AT+SMOD?\r\n")
                         time.sleep_ms(delay)
                         resp = self.__serial.read()
                         try:
                             if debug:
                                 print(
                                     'Response (AT+SMOD?) {}'.format(resp))
                             return self.return_code(resp, debug)
                         except:
                             pass
                     self.__serial.write(b"AT\r\n")
                     time.sleep_ms(delay)
                     resp = self.__serial.read()
                     if debug:
                         print('Response (AT #2 @ 115200) {}'.format(resp))
                     if resp is not None and b'OK' in resp:
                         self.__speed_detected = True
                         self.__serial.write(b"AT+SMOD?\r\n")
                         time.sleep_ms(delay)
                         resp = self.__serial.read()
                         try:
                             if debug:
                                 print(
                                     'Response (AT+SMOD?) {}'.format(resp))
                             return self.return_code(resp, debug)
                         except:
                             pass
     return None
Ejemplo n.º 27
0
# Main program executed by micropython
from machine import UART, RTC
from esp32 import raw_temperature
import os
import uasyncio as asyncio
from sds import SDS
from collections import namedtuple
Time = namedtuple("Time", ["Hour", "Minute", "second"])

uart_gps = UART(2, 9600)
uart_sds = UART(1, 9600)
sreader_gps = asyncio.StreamReader(uart_gps)  # Create a StreamReader
from gps import GPS
# gps = AS_GPS(sreader_gps, local_offset=1)  # Instantiate GPS
gps = GPS(sreader_gps, local_offset=1)
rtc = RTC()


def log(what):
    print("{4:02d}:{5:02d}:{6:02d} ".format(*rtc.datetime()) + what)


def get_temprature(what=None):
    if what == "header":
        return " Temp."
    elif what == "unit":
        return "degreeC"
    elif what == "text":
        C = (raw_temperature() - 32) / 1.8
        return "{:5.2f}".format(C)
    else:
Ejemplo n.º 28
0
class sqnsupgrade:

    global sysname

    def __init__(self):

        self.__sysname = sysname
        self.__pins = None
        self.__connected = False
        self.__sdpath = None
        self.__resp_921600 = False
        self.__serial = None
        self.__kill_ppp_ok = False
        self.__modem_speed = None
        self.__speed_detected = False

        if 'GPy' in self.__sysname:
            self.__pins = ('P5', 'P98', 'P7', 'P99')
        else:
            self.__pins = ('P20', 'P18', 'P19', 'P17')

    def special_print(self, msg, flush=None, end='\n'):
        if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
            print(msg, end=end)
        else:
            print(msg, flush=flush, end=end)

    def read_rsp(self, size=None, timeout=-1):
        if timeout < 0:
            timeout = 20000
        elif timeout is None:
            timeout = 0
        if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
            while not self.__serial.any() and timeout > 0:
                time.sleep_ms(1)
                timeout -= 1
        else:
            while self.__serial.in_waiting <= 0 and timeout > 0:
                time.sleep(0.001)
                timeout -= 1

        if size is not None:
            rsp = self.__serial.read(size)
        else:
            rsp = self.__serial.read()
        if rsp is not None:
            return rsp
        else:
            return b''

    def print_pretty_response(self, rsp, flush=False, prefix=None):
        if prefix is not None: self.special_print(prefix, flush=flush, end=' ')
        lines = rsp.decode('ascii').split('\r\n')
        for line in lines:
            if 'OK' not in line and line != '':
                self.special_print(line, flush=flush)

    def return_pretty_response(self, rsp):
        ret_str = ''
        lines = rsp.decode('ascii').split('\r\n')
        for line in lines:
            if 'OK' not in line:
                ret_str += line
        return ret_str

    def return_upgrade_response(self, rsp):
        pretty = self.return_pretty_response(rsp)
        if "+SMUPGRADE:" in pretty:
            try:
                return pretty.split(':')[1].strip()
            except:
                pass
        return None

    def return_code(self, rsp, debug=False):
        ret_str = b''
        lines = rsp.decode('ascii').split('\r\n')
        for line in lines:
            if 'OK' not in line and len(line) > 0:
                try:
                    if debug:
                        print('Converting response: {} to int...'.format(line))
                    return int(line)
                except:
                    pass
        raise OSError('Could not decode modem state')

    def wait_for_modem(self, send=True, expected=b'OK', echo_char=None):
        rsp = b''
        start = time.time()
        while True:
            if send:
                self.__serial.write(b"AT\r\n")
            r = self.read_rsp(size=(len(expected) + 4), timeout=50)
            if r:
                rsp += r
            if expected in rsp:
                if echo_char is not None:
                    print()
                break
            else:
                if echo_char is not None:
                    self.special_print(echo_char, end='', flush=True)
                time.sleep(0.5)
            if time.time() - start >= 300:
                raise OSError('Timeout waiting for modem to respond!')

    def __check_file(self, file_path, debug=False):
        if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
            if file_path[
                    0] == '/' and not 'flash' in file_path and not file_path.split(
                        '/')[1] in os.listdir('/'):
                if self.__sdpath is None:
                    self.__sdpath = file_path.split('/')[1]
                    try:
                        sd = SD()
                        time.sleep(0.5)
                        os.mount(sd, '/{}'.format(self.__sdpath))
                    except Exception as ex:
                        print('Unable to mount SD card!')
                        return False
                else:
                    print('SD card already mounted on {}!'.format(
                        self.__sdpath))
                    return False
        try:
            size = os.stat(file_path)[6]
            if debug: print('File {} has size {}'.format(file_path, size))
            return True
        except Exception as ex:
            print('Exception when checking file {}... wrong file name?'.format(
                file_path))
            print('{}'.format(ex))
            return False
        return False

    def check_files(self, ffile, mfile=None, debug=False):
        if mfile is not None:
            if self.__check_file(mfile, debug):
                return self.__check_file(ffile, debug)
            else:
                return False
        else:
            return self.__check_file(ffile, debug)

    def __check_resp(self, resp, kill_ppp=False):
        if resp is not None:
            self.__resp_921600 = b'OK' in resp or b'ERROR' in resp
            self.__kill_ppp_ok = self.__kill_ppp_ok or (kill_ppp
                                                        and b'OK' in resp)

    def __hangup_modem(self, delay, debug):
        self.__serial.read()
        if not self.__kill_ppp_ok:
            self.__serial.write(b"+++")
            time.sleep_ms(1150)
            resp = self.__serial.read()
            if debug: print('Response (+++ #1): {}'.format(resp))
            self.__check_resp(resp, True)
        self.__serial.write(b"AT\r\n")
        time.sleep_ms(250)
        resp = self.__serial.read()
        if debug: print('Response (AT #1) {}'.format(resp))
        self.__check_resp(resp)
        if resp is not None:
            if b'OK' not in resp and not self.__kill_ppp_ok:
                self.__serial.write(b"AT\r\n")
                time.sleep_ms(250)
                resp = self.__serial.read()
                if debug: print('Response (AT #2) {}'.format(resp))
                self.__check_resp(resp)
                if resp is not None and b'OK' in resp:
                    return True
                self.__serial.write(b"+++")
                time.sleep_ms(1150)
                resp = self.__serial.read()
                if debug: print('Response (+++ #2): {}'.format(resp))
                self.__check_resp(resp, True)
            if resp is not None and b'OK' in resp:
                self.__serial.write(b"AT\r\n")
                time.sleep_ms(250)
                resp = self.__serial.read()
                if debug: print('Response (AT #2) {}'.format(resp))
                self.__check_resp(resp)
                if resp is not None and b'OK' in resp:
                    return True
        return False

    def detect_modem_state(self,
                           retry=5,
                           initial_delay=1000,
                           hangup=True,
                           debug=False):
        count = 0
        self.__serial = UART(1,
                             baudrate=921600,
                             pins=self.__pins,
                             timeout_chars=1)
        self.__modem_speed = 921600
        self.__serial.read()
        while count < retry:
            count += 1
            delay = initial_delay * count
            if debug: print("The current delay is {}".format(delay))
            self.__serial = UART(1,
                                 baudrate=921600,
                                 pins=self.__pins,
                                 timeout_chars=10)
            self.__modem_speed = 921600
            #if True:
            if hangup and self.__hangup_modem(initial_delay, debug):
                self.__speed_detected = True
                self.__serial.write(b"AT+SMOD?\r\n")
                time.sleep_ms(delay)
                resp = self.__serial.read()
                if debug: print('Response (AT+SMOD?) {}'.format(resp))
                try:
                    return self.return_code(resp, debug)
                except:
                    pass
            else:
                self.__modem_speed = 921600
                self.__serial = UART(1,
                                     baudrate=921600,
                                     pins=self.__pins,
                                     timeout_chars=1)
                self.__serial.read()
                self.__serial.write(b"AT\r\n")
                time.sleep_ms(delay)
                resp = self.__serial.read()
                self.__check_resp(resp)
                if debug: print('Response (AT #3) {}'.format(resp))
                if resp is not None and b'OK' in resp:
                    self.__speed_detected = True
                    self.__serial.write(b"AT+SMOD?\r\n")
                    time.sleep_ms(delay)
                    resp = self.__serial.read()
                    try:
                        if debug: print('Response (AT+SMOD?) {}'.format(resp))
                        return self.return_code(resp, debug)
                    except:
                        pass
                self.__serial.write(b"AT\r\n")
                time.sleep_ms(delay)
                resp = self.__serial.read()
                self.__check_resp(resp)
                if debug: print('Response (AT #4) {}'.format(resp))
                if resp is not None and b'OK' in resp:
                    self.__speed_detected = True
                    self.__serial.write(b"AT+SMOD?\r\n")
                    time.sleep_ms(delay)
                    resp = self.__serial.read()
                    try:
                        return self.return_code(resp, debug)
                        if debug: print('Response (AT+SMOD?) {}'.format(resp))
                    except:
                        pass
                else:
                    if not self.__resp_921600:
                        self.__modem_speed = 115200
                        self.__serial = UART(1,
                                             baudrate=115200,
                                             pins=self.__pins,
                                             timeout_chars=10)
                        self.__serial.write(b"AT\r\n")
                        time.sleep_ms(delay)
                        resp = self.__serial.read()
                        if debug:
                            print('Response (AT #1 @ 115200) {}'.format(resp))
                        if resp is not None and b'OK' in resp:
                            self.__speed_detected = True
                            self.__serial.write(b"AT+SMOD?\r\n")
                            time.sleep_ms(delay)
                            resp = self.__serial.read()
                            try:
                                if debug:
                                    print(
                                        'Response (AT+SMOD?) {}'.format(resp))
                                return self.return_code(resp, debug)
                            except:
                                pass
                        self.__serial.write(b"AT\r\n")
                        time.sleep_ms(delay)
                        resp = self.__serial.read()
                        if debug:
                            print('Response (AT #2 @ 115200) {}'.format(resp))
                        if resp is not None and b'OK' in resp:
                            self.__speed_detected = True
                            self.__serial.write(b"AT+SMOD?\r\n")
                            time.sleep_ms(delay)
                            resp = self.__serial.read()
                            try:
                                if debug:
                                    print(
                                        'Response (AT+SMOD?) {}'.format(resp))
                                return self.return_code(resp, debug)
                            except:
                                pass
        return None

    def get_imei(self):
        self.__serial = UART(1,
                             baudrate=921600,
                             pins=self.__pins,
                             timeout_chars=10)
        self.__serial.write(b"AT+CGSN\r\n")
        time.sleep(.5)
        imei_val = self.read_rsp(2000)
        return self.return_pretty_response(imei_val)

    def __get_power_warning(self):
        return "<<<=== DO NOT DISCONNECT POWER ===>>>"

    def __get_wait_msg(self, load_fff=True):
        if not self.__wait_msg:
            self.__wait_msg = True
            if load_fff:
                return "Waiting for modem to finish the update...\nThis might take several minutes!\n" + self.__get_power_warning(
                )
            else:
                return "Waiting for modem to finish the update...\n" + self.__get_power_warning(
                )
        return None

    def __run(self,
              file_path=None,
              baudrate=921600,
              port=None,
              resume=False,
              load_ffh=False,
              mirror=False,
              switch_ffh=False,
              bootrom=False,
              rgbled=0x050505,
              debug=False,
              pkgdebug=False,
              atneg=True,
              max_try=10,
              direct=True,
              atneg_only=False,
              info_only=False,
              expected_smod=None,
              verbose=False,
              load_fff=False):
        self.__wait_msg = False
        mirror = True if atneg_only else mirror
        recover = True if atneg_only else load_ffh
        resume = True if mirror or recover or atneg_only or info_only else resume
        verbose = True if debug else verbose
        load_fff = False if bootrom and switch_ffh else load_fff
        target_baudrate = baudrate
        baudrate = self.__modem_speed if self.__speed_detected else baudrate
        if debug:
            print(
                'mirror? {}  recover? {}  resume? {}  direct? {}  atneg_only? {} bootrom? {} load_fff? {}'
                .format(mirror, recover, resume, direct, atneg_only, bootrom,
                        load_fff))
        if debug:
            print('baudrate: {} target_baudrate: {}'.format(
                baudrate, target_baudrate))
        abort = True
        external = False
        self.__serial = None

        if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:

            self.__serial = UART(1,
                                 baudrate=115200 if recover
                                 and not self.__speed_detected else baudrate,
                                 pins=self.__pins,
                                 timeout_chars=100)
            self.__serial.read()
        else:
            if port is None:
                raise ValueError('serial port not specified')
            if debug: print('Setting port {}'.format(port))
            external = True
            br = 115200 if recover and not direct else baudrate
            if debug: print('Setting baudrate to {}'.format(br))
            self.__serial = serial.Serial(port,
                                          br,
                                          bytesize=serial.EIGHTBITS,
                                          timeout=1 if info_only else 0.1)
            self.__serial.reset_input_buffer()
            self.__serial.reset_output_buffer()

        if info_only:
            self.__serial.read()
            self.__serial.write(b'AT\r\n')
            self.__serial.write(b'AT\r\n')
            self.__serial.read()
            self.__serial.write(b"AT+CGSN\r\n")
            time.sleep(.5)
            shimei = self.read_rsp(2000)
            if verbose:
                self.__serial.write(b"AT!=\"showver\"\r\n")
            else:
                self.__serial.write(b"ATI1\r\n")
            time.sleep(.5)
            shver = self.read_rsp(2000)
            if shver is not None:
                self.print_pretty_response(shver)
            if shimei is not None:
                self.print_pretty_response(shimei, prefix='\nIMEI:')
            return True

        if debug: print('Initial prepartion complete...')

        if not mirror:
            if bootrom:
                if debug: print('Loading built-in recovery bootrom...')
                try:
                    # try compressed bootrom first
                    from sqnsbrz import bootrom
                except:
                    # fallback to uncompressed
                    from sqnsbr import bootrom
                blob = bootrom()
                blobsize = blob.get_size()
            else:
                if debug: print('Loading {}'.format(file_path))
                blobsize = os.stat(file_path)[6]
                if blobsize < 128:
                    print('Firmware file is too small!')
                    reconnect_uart()
                    sys.exit(1)
                if blobsize > 4194304:
                    if load_fff:
                        print(
                            "Firmware file is too big to load via FFF method. Using ON_THE_FLY"
                        )
                    load_fff = False
                blob = open(file_path, "rb")

        if not load_ffh:
            if not self.wakeup_modem(baudrate, port, 10, 1, debug):
                return False

        if not resume:

            # bind to AT channel
            self.__serial.write(b"AT+BIND=AT\r\n")
            time.sleep(.5)
            response = self.read_rsp(size=100)
            if debug: print("AT+BIND=AT returned {}".format(response))

            # disable echo
            self.__serial.write(b"ATE0\r\n")
            time.sleep(.5)
            response = self.read_rsp(size=100)
            if debug: print("ATE0 returned {}".format(response))

            self.__serial.read(100)
            if debug: print('Entering upgrade mode...')

            self.__serial.write(b"AT+SMOD?\r\n")
            response = self.return_pretty_response(self.read_rsp(size=7))
            self.__serial.read(100)
            if debug: print("AT+SMOD? returned {}".format(response))

            self.__serial.write(b"AT+SQNSUPGRADENTF=\"started\"\r\n")
            self.wait_for_modem()
            if not load_fff:
                self.__serial.write(b"AT+SMSWBOOT=3,1\r\n")
                resp = self.read_rsp(100)
                if debug: print('AT+SMSWBOOT=3,1 returned: {}'.format(resp))
                if b'ERROR' in resp:
                    time.sleep(5)
                    self.__serial.write(b"AT+SMSWBOOT=3,0\r\n")
                    resp = self.read_rsp(100)
                    if debug:
                        print('AT+SMSWBOOT=3,0 returned: {}'.format(resp))
                    if b'OK' in resp:
                        self.__serial.write(b"AT^RESET\r\n")
                        resp = self.read_rsp(100)
                        if debug: print('AT^RESET returned: {}'.format(resp))
                    else:
                        print('Received ERROR from AT+SMSWBOOT=3,1! Aborting!')
                        reconnect_uart()
                        sys.exit(1)
                time.sleep(3)
                resp = self.__serial.read()
                if debug: print("Response after reset: {}".format(resp))
                self.wait_for_modem()
                self.__serial.write(b"AT\r\n")

        else:
            self.__serial.read(100)
            if debug: print('Entering recovery mode')

            self.__serial.write(b"AT+SMOD?\r\n")
            response = self.return_pretty_response(self.read_rsp(size=7))
            self.__serial.read(100)
            if debug: print("AT+SMOD? returned {}".format(response))

        time.sleep(1)
        self.__serial.read()

        if (not recover) and (not direct):
            if mirror:
                time.sleep(.5)
                self.__serial.read(100)
                print(
                    'Going into MIRROR mode... please close this terminal to resume the upgrade via UART'
                )
                self.uart_mirror(rgbled)

            elif bootrom:
                if verbose: print('Starting STP')
            else:
                if verbose:
                    if load_fff:
                        print('Starting STP [FFF]')
                    else:
                        print('Starting STP ON_THE_FLY')

            self.__serial.read(100)
            if verbose: print("Sending AT+CFUN=4")
            resonse = self.__serial.write(b'AT+CFUN=4\r\n')
            if verbose: print("AT+CFUN=4 returned {}".format(response))
            self.__serial.read(100)

            if load_fff:
                if debug: print("Sending AT+SMSTPU")
                self.__serial.write(b'AT+SMSTPU\r\n')
            else:
                if debug: print("Sending AT+SMSTPU=\"ON_THE_FLY\"")
                self.__serial.write(b'AT+SMSTPU=\"ON_THE_FLY\"\r\n')

            response = self.read_rsp(size=4)
            if response != b'OK\r\n' and response != b'\r\nOK' and response != b'\nOK':
                raise OSError("Invalid answer '%s' from the device" % response)
                blob.close()

            self.__serial.read()
        elif recover and (not direct):
            if atneg:
                result = self.at_negotiation(baudrate, port, max_try, mirror,
                                             atneg_only, debug,
                                             target_baudrate)
                if result:
                    baudrate = target_baudrate
                    self.__modem_speed = target_baudrate
                    self.__speed_detected = True
                    if atneg_only:
                        return True
                    if mirror:
                        time.sleep(.5)
                        self.__serial.read(100)
                        print(
                            'Going into MIRROR mode... please close this terminal to resume the upgrade via UART'
                        )
                        self.uart_mirror(rgbled)
                    else:
                        self.__serial.write(b"AT+STP\n")
                        response = self.read_rsp(size=6)
                        if not b'OK' in response:
                            print('Failed to start STP mode!')
                            reconnect_uart()
                            sys.exit(1)
                else:
                    print('AT auto-negotiation failed! Exiting.')
                    return False
        else:
            if debug: print('Starting STP mode...')
            self.__serial.write(b"AT+STP\n")
            response = self.read_rsp(size=6)
            if not b'OK' in response:
                print('Failed to start STP mode!')
                reconnect_uart()
                sys.exit(1)

        try:
            if debug:
                if verbose: print('Starting STP code upload')
            if stp.start(blob,
                         blobsize,
                         self.__serial,
                         baudrate,
                         AT=False,
                         debug=debug,
                         pkgdebug=pkgdebug):
                blob.close()
                self.__serial.read()
                if switch_ffh:
                    if verbose:
                        print(
                            'Bootrom updated successfully, switching to recovery mode'
                        )
                    abort = False
                elif load_ffh:
                    if not self.wakeup_modem(baudrate, port, 100, 1, debug,
                                             'Waiting for updater to load...'):
                        return False
                    if verbose:
                        print(
                            'Upgrader loaded successfully, modem is in update mode'
                        )
                    return True
                else:
                    if verbose:
                        print('Code download done, returning to user mode')
                    abort = recover
            else:
                blob.close()
                print('Code download failed, aborting!')
                return False
        except:
            blob.close()
            print('Code download failed, aborting!')
            abort = True

        time.sleep(1.5)

        if not abort:
            self.__serial.read()
            if switch_ffh:
                self.__serial.write(b"AT+SMSWBOOT=0,1\r\n")
                resp = self.read_rsp(100)
                if debug: print("AT+SMSWBOOT=0,1 returned {}".format(resp))
                if b"ERROR" in resp:
                    time.sleep(5)
                    self.__serial.write(b"AT+SMSWBOOT=0,0\r\n")
                    resp = self.read_rsp(100)
                    if debug:
                        print('AT+SMSWBOOT=0,0 returned: {}'.format(resp))
                    if b'OK' in resp:
                        self.__serial.write(b"AT^RESET\r\n")
                        resp = self.read_rsp(100)
                        if debug: print('AT^RESET returned: {}'.format(resp))
                        return True
                    else:
                        print('Received ERROR from AT+SMSWBOOT=0,0! Aborting!')
                        return False
                return True
            else:
                if load_fff:
                    self.__serial.write(b"AT+SMUPGRADE\r\n")
                if not self.wakeup_modem(
                        baudrate, port, 100, 1, debug,
                        self.__get_wait_msg(load_fff=load_fff)):
                    print(
                        "Timeout while waiting for modem to finish updating!")
                    reconnect_uart()
                    sys.exit(1)

                start = time.time()
                while True:
                    self.__serial.read()
                    self.__serial.write(b"AT+SMUPGRADE?\r\n")
                    resp = self.read_rsp(1024)
                    if debug:
                        print("AT+SMUPGRADE? returned {} [timeout: {}]".format(
                            resp,
                            time.time() - start))

                    if resp == b'\x00' or resp == b'':
                        time.sleep(2)

                    if b'No report' in resp or b'on-going' in resp:
                        time.sleep(1)

                    if b'success' in resp or b'fail' in resp:
                        break

                    if time.time() - start >= 300:
                        raise OSError('Timeout waiting for modem to respond!')

                self.__serial.write(b"AT+SMSWBOOT?\r\n")
                resp = self.read_rsp(100)
                if debug: print("AT+SMSWBOOT? returned {}".format(resp))
                start = time.time()
                while (b"RECOVERY"
                       not in resp) and (b"FFH" not in resp) and (b"FFF"
                                                                  not in resp):
                    if debug: print("Timeout: {}".format(time.time() - start))
                    if time.time() - start >= 300:
                        reconnect_uart()
                        raise OSError('Timeout waiting for modem to respond!')
                    time.sleep(2)
                    if not self.wakeup_modem(
                            baudrate, port, 100, 1, debug,
                            self.__get_wait_msg(load_fff=load_fff)):
                        reconnect_uart()
                        raise OSError(
                            'Timeout while waiting for modem to finish updating!'
                        )
                    self.__serial.read()
                    self.__serial.write(b"AT+SMSWBOOT?\r\n")
                    resp = self.read_rsp(100)
                    if debug: print("AT+SMSWBOOT? returned {}".format(resp))
                self.__serial.read()
                self.__serial.write(b"AT+SMUPGRADE?\r\n")
                resp = self.read_rsp(1024)
                if debug: print("AT+SMUPGRADE? returned {}".format(resp))
                sqnup_result = self.return_upgrade_response(resp)
                if debug: print('This is my result: {}'.format(sqnup_result))
                if 'success' in sqnup_result:
                    if not load_fff:
                        self.special_print('Resetting.', end='', flush=True)
                        self.__serial.write(b"AT+SMSWBOOT=1,1\r\n")
                        if debug:
                            print("AT+SMSWBOOT=1,1 returned {}".format(resp))
                        if b"ERROR" in resp:
                            time.sleep(5)
                            self.__serial.write(b"AT+SMSWBOOT=1,0\r\n")
                            resp = self.read_rsp(100)
                            if debug:
                                print('AT+SMSWBOOT=1,0 returned: {}'.format(
                                    resp))
                            if b'OK' in resp:
                                self.__serial.write(b"AT^RESET\r\n")
                                resp = self.read_rsp(100)
                                if debug:
                                    print('AT^RESET returned: {}'.format(resp))
                                return True
                            else:
                                print(
                                    'Received ERROR from AT+SMSWBOOT=1,0! Aborting!'
                                )
                                return False
                        self.wait_for_modem(send=False,
                                            echo_char='.',
                                            expected=b'+SYSSTART')

                elif sqnup_result is not None:
                    print(
                        'Upgrade failed with result {}!'.format(sqnup_result))
                    print('Please check your firmware file(s)')
                else:
                    print("Invalid response after upgrade... aborting.")
                    reconnect_uart()
                    sys.exit(1)

                self.__serial.write(b"AT\r\n")
                self.__serial.write(b"AT\r\n")
                time.sleep(0.5)

                if 'success' in sqnup_result:
                    self.__serial.write(b"AT+SQNSUPGRADENTF=\"success\"\r\n")
                    self.__serial.read()
                    return True
                elif sqnup_result is None:
                    print(
                        'Modem upgrade was unsucessfull. Please check your firmware file(s)'
                    )
        return False

    def __check_br(self, br_only=False, verbose=False, debug=False):
        old_br = None
        old_sw = None
        if debug: print("Checking bootrom & application")
        self.__serial.write(b"AT!=\"showver\"\r\n")
        time.sleep(.5)
        shver = self.read_rsp(2000)
        if shver is not None:
            for line in shver.decode('ascii').split('\n'):
                if debug: print('Checking line {}'.format(line))
                if "Bootloader0" in line:
                    old_br = "[33080]" in line
                    if debug: print("old_br: {}".format(old_br))

                if "Software" in line:
                    old_sw = "[33080]" in line
                    if debug: print("old_sw: {}".format(old_sw))
        if old_br is None or old_sw is None:
            if debug: print("Returning: None")
            return None
        if old_br and (br_only or not old_sw):
            if debug: print("Returning: True")
            return True
        if debug: print("Returning: False")
        return False

    def wakeup_modem(self,
                     baudrate,
                     port,
                     max_try,
                     delay,
                     debug,
                     msg='Attempting AT wakeup...'):
        if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
            self.__serial = UART(1,
                                 baudrate=baudrate,
                                 pins=self.__pins,
                                 timeout_chars=10)
        MAX_TRY = max_try
        count = 0
        if msg is not None:
            if debug:
                print(msg + 'with baudrate {}'.format(baudrate))
            else:
                print(msg)

        self.__serial.read()
        self.__serial.write(b"AT\r\n")
        response = self.read_rsp(size=25)
        if debug: print('{}'.format(response))
        while (not b'OK' in response) and (count < MAX_TRY):
            count = count + 1
            if debug: print('count={}'.format(count))
            time.sleep(delay)
            self.__serial.read()
            self.__serial.write(b"AT\r\n")
            response = self.read_rsp(size=25)
            if debug: print('{}'.format(response))
        if 'FiPy' in sysname or 'GPy' in sysname:
            self.__serial = UART(1,
                                 baudrate=baudrate,
                                 pins=self.__pins,
                                 timeout_chars=100)
        return count < MAX_TRY

    def at_negotiation(self, baudrate, port, max_try, mirror, atneg_only,
                       debug, target_baudrate):
        MAX_TRY = max_try
        count = 0
        if debug:
            print(
                'Attempting AT auto-negotiation... with baudrate {} and target_baudrate {}'
                .format(baudrate, target_baudrate))
        else:
            print('Attempting AT auto-negotiation...')
        self.__serial.write(b"AT\r\n")
        response = self.read_rsp(size=20)
        if debug: print('{}'.format(response))
        while (not b'OK' in response) and (count < MAX_TRY):
            count = count + 1
            if debug: print('count={}'.format(count))
            time.sleep(1)
            self.__serial.read()
            self.__serial.write(b"AT\r\n")
            response = self.read_rsp(size=20)
            if debug: print('{}'.format(response))
        if b'OK' in response:
            self.__serial.read()
            cmd = "AT+IPR=%d\n" % target_baudrate
            if debug: print('Setting baudrate to {}'.format(target_baudrate))
            self.__serial.write(cmd.encode())
            response = self.read_rsp(size=6)
            if debug: print('{}'.format(response))
            if b'OK' in response:
                self.__modem_speed = target_baudrate
                self.__speed_detected = True
                if atneg_only:
                    return True
                if 'FiPy' in self.__sysname or 'GPy' in self.__sysname:
                    self.__serial = UART(1,
                                         baudrate=target_baudrate,
                                         pins=self.__pins,
                                         timeout_chars=100)
                else:
                    self.__serial = None
                    self.__serial = serial.Serial(port,
                                                  target_baudrate,
                                                  bytesize=serial.EIGHTBITS,
                                                  timeout=0.1)
                    self.__serial.reset_input_buffer()
                    self.__serial.reset_output_buffer()
                    self.__serial.flush()
                self.__serial.read()
                if debug: print('Checking SMOD')
                self.__serial.write(b"AT+SMOD?\r\n")
                response = self.read_rsp(size=1)
                if b'0' in response:
                    if debug: print("AT+SMOD? returned {}".format(response))
                    self.__serial.read()
                    return True
                else:
                    print('ERROR in AT+SMOD returned {}'.format(response))
                    return False
            else:
                print('ERROR in AT+IPR={} returned {}'.format(
                    target_baudrate, response))
                return False
        else:
            print(
                'ERROR sending AT command... no response? {}'.format(response))
            return False
        time.sleep(1)
        return True

    def uart_mirror(self, color):
        import pycom
        pycom.heartbeat(False)
        time.sleep(.5)
        pycom.rgbled(color)
        LTE.modem_upgrade_mode()

    def success_message(self, port=None, verbose=False, debug=False):
        print("Your modem has been successfully updated.")
        print("Here is the current firmware version:\n")
        self.show_info(port=port, verbose=verbose, debug=debug)

    def upgrade(self,
                ffile,
                mfile=None,
                baudrate=921600,
                retry=False,
                resume=False,
                debug=False,
                pkgdebug=False,
                verbose=False,
                load_fff=True,
                load_only=False):
        success = True
        if not retry and mfile is not None:
            if resume or self.__check_br(
                    br_only=True, verbose=verbose, debug=debug):
                success = False
                success = self.__run(bootrom=True,
                                     resume=resume,
                                     switch_ffh=True,
                                     direct=False,
                                     debug=debug,
                                     pkgdebug=pkgdebug,
                                     verbose=verbose)
                time.sleep(1)
            else:
                print('{} is not required. Resumining normal upgrade.'.format(
                    mfile))
                mfile = None
                success = True
        if debug: print('Success1? {}'.format(success))
        if success:
            if mfile is not None:
                success = False
                success = self.__run(file_path=mfile,
                                     load_ffh=True,
                                     direct=False,
                                     baudrate=baudrate,
                                     debug=debug,
                                     pkgdebug=pkgdebug,
                                     verbose=verbose)
                time.sleep(1)
                if load_only:
                    return True
            else:
                success = True
        else:
            print('Unable to upgrade bootrom.')
        if debug: print('Success2? {}'.format(success))
        if success:
            if self.__run(file_path=ffile,
                          resume=True if mfile is not None else resume,
                          baudrate=baudrate,
                          direct=False,
                          debug=debug,
                          pkgdebug=pkgdebug,
                          verbose=verbose,
                          load_fff=False if mfile else load_fff):
                if self.__check_br(verbose=verbose, debug=debug):
                    self.__run(bootrom=True,
                               debug=debug,
                               direct=False,
                               pkgdebug=pkgdebug,
                               verbose=verbose,
                               load_fff=True)
                self.success_message(verbose=verbose, debug=debug)
        else:
            print('Unable to load updater from {}'.format(mfile))

    def upgrade_uart(self,
                     ffh_mode=False,
                     mfile=None,
                     retry=False,
                     resume=False,
                     color=0x050505,
                     debug=False,
                     pkgdebug=False,
                     verbose=False,
                     load_fff=True):
        success = False
        try:
            success = hasattr(LTE, 'modem_upgrade_mode')
        except:
            success = False
        if not success:
            print('Firmware does not support LTE.modem_upgrade_mode()!')
            reconnect_uart()
            sys.exit(1)
        print('Preparing modem for upgrade...')
        if not retry and ffh_mode:
            success = False
            if self.__check_br(verbose=verbose, debug=debug):
                success = self.__run(bootrom=True,
                                     resume=resume,
                                     switch_ffh=True,
                                     direct=False,
                                     debug=debug,
                                     pkgdebug=pkgdebug,
                                     verbose=verbose)
                time.sleep(1)
            else:
                print('FFH mode is not necessary... ignoring!')
                print('Do not specify updater.elf when updating!')
                mfile = None
                ffh_mode = False
                success = True
        if success:
            if mfile is not None:
                success = False
                success = self.__run(file_path=mfile,
                                     load_ffh=True,
                                     direct=False,
                                     debug=debug,
                                     pkgdebug=pkgdebug,
                                     verbose=verbose)
                if debug: print('Success2? {}'.format(success))
                if success:
                    self.__run(mirror=True,
                               load_ffh=False,
                               direct=False,
                               rgbled=color,
                               debug=debug,
                               verbose=verbose)
                else:
                    print('Unable to load updater from {}'.format(mfile))
            else:
                self.__run(mirror=True,
                           load_ffh=ffh_mode,
                           direct=False,
                           rgbled=color,
                           debug=debug,
                           verbose=verbose)
        else:
            print('Unable to upgrade bootrom.')

    def show_info(self, port=None, debug=False, verbose=False):
        self.__run(port=port, debug=debug, info_only=True, verbose=verbose)

    def upgrade_ext(self,
                    port,
                    ffile,
                    mfile,
                    resume=False,
                    debug=False,
                    pkgdebug=False,
                    verbose=False,
                    load_fff=True):
        success = True
        if mfile is not None:
            success = False
            success = self.__run(file_path=mfile,
                                 load_ffh=True,
                                 port=port,
                                 debug=debug,
                                 pkgdebug=pkgdebug,
                                 verbose=verbose)
        if success:
            if self.__run(file_path=ffile,
                          resume=True if mfile is not None else resume,
                          direct=False,
                          port=port,
                          debug=debug,
                          pkgdebug=pkgdebug,
                          verbose=verbose,
                          load_fff=load_fff):
                self.success_message(port=port, verbose=verbose, debug=debug)
        else:
            print('Unable to load updater from {}'.format(mfile))
Ejemplo n.º 29
0
import sensor
import lcd
import time
import uos
import gc
import ulab as np
from fpioa_manager import *
from Maix import utils
from machine import UART

utils.gc_heap_size(250000)

# for Grove Port
fm.register(35, fm.fpioa.UART2_TX, force=True)
fm.register(34, fm.fpioa.UART2_RX, force=True)
uart_Port = UART(UART.UART2, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)


def get_feature(task):
    count = 20
    for i in range(3):
        for j in range(count):
            img = sensor.snapshot()
            if j < (count >> 1):
                img.draw_rectangle(1,
                                   46,
                                   222,
                                   132,
                                   color=br.get_color(255, 0, 0),
                                   thickness=3)
            lcd.display(img)
Ejemplo n.º 30
0
class DeepSleep:

    WPUA_ADDR = const(0x09)
    OPTION_REG_ADDR = const(0x0E)
    IOCAP_ADDR = const(0x1A)
    IOCAN_ADDR = const(0x1B)

    WAKE_STATUS_ADDR = const(0x40)
    MIN_BAT_ADDR = const(0x41)
    SLEEP_TIME_ADDR = const(0x42)
    CTRL_0_ADDR = const(0x45)

    EXP_RTC_PERIOD = const(7000)

    def __init__(self):
        self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ))
        self.clk_cal_factor = 1
        self.uart.read()
        # enable the weak pull-ups control
        self.clearbits(OPTION_REG_ADDR, 1 << 7)

    def _send(self, data):
        self.uart.write(bytes(data))

    def _start(self):
        self.uart.sendbreak(20)
        self._send([0x55])

    def _magic(self, address, and_val, or_val, xor_val, expected=None):
        self._start()
        self._send([address, and_val & 0xFF, or_val & 0xFF, xor_val & 0xFF])
        if expected is None:
            return self.uart.read()
        else:
            if expected > 0:
                return self.uart.read(expected)

    def _add_to_pin_mask(self, mask, pin):
        if pin == 'P10' or pin == 'G17':
            mask |= 0x01
        elif pin == 'P17' or pin == 'G31':
            mask |= 0x02
        elif pin == 'P18' or pin == 'G30':
            mask |= 0x08
        else:
            raise ValueError('Invalid Pin specified: {}'.format(pin))
        return mask

    def _create_pin_mask(self, pins):
        mask = 0
        if type(pins) is str:
            mask = self._add_to_pin_mask(mask, pins)
        else:
            for pin in pins:
                mask = self._add_to_pin_mask(mask, pin)
        return mask & PIN_MASK

    def poke(self, address, value):
        self._magic(address, 0, value, 0)

    def peek(self, address):
        return self._magic(address, 0xFF, 0, 0)[6]

    def setbits(self, address, mask):
        self._magic(address, 0xFF, mask, 0)

    def clearbits(self, address, mask):
        self._magic(address, ~mask, 0, 0)

    def togglebits(self, address, mask):
        self._magic(address, 0xFF, 0, mask)

    def calibrate(self):
        """ The microcontroller will send the value of CTRL_0 after setting the bit
            and then will send the following pattern through the data line:

               val | 1 | 0 | 1*| 0 | 1*| 0 | 1
               ms  | 1 | 1 | 1 | 1 | 8 | 1 | -

            The idea is to measure the real life duration of periods marked with *
            and substract them. That will remove any errors common to both measurements
            The result is 7 ms as generated by the PIC LF clock.
            It can be used to scale any future sleep value. """

        # setbits, but limit the number of received bytes to avoid confusion with pattern
        self._magic(CTRL_0_ADDR, 0xFF, 1 << 2, 0, 0)
        self.uart.deinit()
        self._pulses = pycom.pulses_get(COMM_PIN, 50)
        self.uart = UART(1, baudrate=10000, pins=(COMM_PIN, ))
        try:
            self.clk_cal_factor = (self._pulses[4][1] - self._pulses[1][1]) / EXP_RTC_PERIOD
        except:
            pass
        if self.clk_cal_factor > 1.25 or self.clk_cal_factor < 0.75:
            self.clk_cal_factor = 1

    def enable_auto_poweroff(self):
        self.setbits(CTRL_0_ADDR, 1 << 1)

    def enable_pullups(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(WPUA_ADDR, mask)

    def disable_pullups(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(WPUA_ADDR, mask)

    def enable_wake_on_raise(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(IOCAP_ADDR, mask)

    def disable_wake_on_raise(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(IOCAP_ADDR, mask)

    def enable_wake_on_fall(self, pins):
        mask = self._create_pin_mask(pins)
        self.setbits(IOCAN_ADDR, mask)

    def disable_wake_on_fall(self, pins):
        mask = self._create_pin_mask(pins)
        self.clearbits(IOCAN_ADDR, mask)

    def get_wake_status(self):
        # bits as they are returned from PIC:
        #   0: PIN 0 value after awake
        #   1: PIN 1 value after awake
        #   2: PIN 2 value after awake
        #   3: PIN 3 value after awake
        #   4: TIMEOUT
        #   5: POWER ON

        wake_r = self.peek(WAKE_STATUS_ADDR)
        return {'wake': wake_r & (TIMER_WAKE | POWER_ON_WAKE),
                'P10': wake_r & 0x01, 'P17': (wake_r & 0x02) >> 1,
                'P18': (wake_r & 0x08) >> 3}

    def set_min_voltage_limit(self, value):
        # voltage value passed in volts (e.g. 3.6) and round it to the nearest integer
        value = int(((256 * 2.048) + (value / 2)) / value)
        self.poke(MIN_BAT_ADDR, value)

    def go_to_sleep(self, seconds):
        gc.collect()
        while True:
            try:
                self.calibrate()
            except Exception:
                pass

            # the 1.024 factor is because the PIC LF operates at 31 KHz
            # WDT has a frequency divider to generate 1 ms
            # and then there is a binary prescaler, e.g., 1, 2, 4 ... 512, 1024 ms
            # hence the need for the constant

            # round to the nearest integer
            seconds = int((seconds / (1.024 * self.clk_cal_factor)) + 0.5)
            self.poke(SLEEP_TIME_ADDR, (seconds >> 16) & 0xFF)
            self.poke(SLEEP_TIME_ADDR + 1, (seconds >> 8) & 0xFF)
            self.poke(SLEEP_TIME_ADDR + 2, seconds & 0xFF)
            self.setbits(CTRL_0_ADDR, 1 << 0)

    def hw_reset(self):
        self.setbits(CTRL_0_ADDR, 1 << 4)
Ejemplo n.º 31
0
def peripheral_query(is_init, p_out_ctrla, p_out_ctrlb):
    import pycom
    import time
    import socket
    import binascii
    import struct
    import gc
    import sys
    import os
    import uio
    import ujson

    from machine import UART
    from machine import ADC
    from machine import I2C
    from machine import SPI
    from machine import Pin
    from tsl2591 import TSL2591

    with uio.open('/flash/configure.json', 'r', encoding="utf-8") as hdl:
        parsed_json = ujson.load(hdl)

    sht31 = parsed_json["firmware"]["sht31"]

    bias_nh3 = parsed_json["calibration"]["sensor_nh3"]["bias"]
    bias_so2 = parsed_json["calibration"]["sensor_so2"]["bias"]
    bias_h2s = parsed_json["calibration"]["sensor_h2s"]["bias"]

    di_nh3 = parsed_json["calibration"]["sensor_nh3"]["di"]
    di_so2 = parsed_json["calibration"]["sensor_so2"]["di"]
    di_h2s = parsed_json["calibration"]["sensor_h2s"]["di"]

    i0_nh3 = parsed_json["calibration"]["sensor_nh3"]["i0"]
    i0_so2 = parsed_json["calibration"]["sensor_so2"]["i0"]
    i0_h2s = parsed_json["calibration"]["sensor_h2s"]["i0"]

    vref = parsed_json["calibration"]["vref"]

    p_data = PeripheralData()
    print('[2]===================')

    adc0 = ADC(id=0)

    outer_iter = 0
    outer_iter_times = 20
    outer_buff_NH3 = []
    outer_buff_SO2 = []
    outer_buff_H2S = []

    while outer_iter < outer_iter_times:
        filtered_mvolts = _get_filtered_mvolts(adc0, vref)
        outer_buff_NH3.append(filtered_mvolts.NH3)
        outer_buff_SO2.append(filtered_mvolts.SO2)
        outer_buff_H2S.append(filtered_mvolts.H2S)
        outer_iter = outer_iter + 1
    buff_nh3 = sum(outer_buff_NH3) / outer_iter_times
    buff_so2 = sum(outer_buff_SO2) / outer_iter_times
    buff_h2s = sum(outer_buff_H2S) / outer_iter_times

    buff_nh3 = round((buff_nh3 - bias_nh3 - i0_nh3 * 47 * 0.624) * 50 /
                     (di_nh3 * 47 * 0.624), 1)
    adc0_str = '%.1f' % ((buff_nh3))
    p_data.NH3 = (buff_nh3)
    print('[2]NH3: ' + adc0_str)

    buff_so2 = round((buff_so2 - bias_so2 - i0_so2 * 47 * 0.624) * 20 /
                     (di_so2 * 47 * 0.624), 1)
    adc1_str = '%.1f' % ((buff_so2))
    p_data.SO2 = ((buff_so2))
    print('[2]SO2: ' + adc1_str)

    buff_h2s = round((buff_h2s - bias_h2s - i0_h2s * 47 * 0.624) * 50 /
                     (di_h2s * 47 * 0.624), 1)
    adc2_str = '%.1f' % ((buff_h2s))
    p_data.H2S = ((buff_h2s))
    print('[2]H2S: ' + adc2_str)
    adc0.deinit()
    time.sleep(0.01)

    adc3 = ADC(id=0)  # create an ADC object
    apin3 = adc3.channel(pin='P16')  # create an analog pin on P16
    adc3.vref(vref)
    adc3_str = '%.2f' % (apin3() * 220 / 4096)
    p_data.current = apin3() * 220 / 4096
    print('[2]Current@5V: ' + adc3_str + 'mA')
    adc3.deinit()

    p_out_ctrla.value(0)
    p_out_ctrlb.value(1)

    uart_mul = UART(1, baudrate=9600, pins=('P3', 'P4'))
    time.sleep(0.1)

    co2_set = is_init
    while co2_set == 0:
        uart_mul.write('K 2\r\n')
        time.sleep(0.05)
        dumm = uart_mul.readline()
        if dumm == bytes([]):
            print('[2]CO2 sensor no respose!')
            break
        else:
            dumm_str = dumm.decode('utf-8')
            if dumm_str == ' K 00002\r\n':
                print('[2]CO2 sensor polling set successfully...')
                time.sleep(0.05)
                co2_set = 1
            else:
                print('[2]CO2 sensor polling resetting...')
                time.sleep(0.05)
            uart_mul.write('M 00006\r\n')
            time.sleep(0.05)
            dumm_str = uart_mul.readall().decode('utf-8')
            if dumm_str == ' M 00006\r\n':
                print('[2]CO2 sensor key set successfully...')
            time.sleep(0.05)
    time.sleep(0.05)

    number = 0
    while number != 18:
        dummy = uart_mul.readall()
        uart_mul.write('Q\r\n')
        time.sleep(0.1)
        number = uart_mul.any()

    data_str = uart_mul.readall().decode("utf-8")
    print('[2]CO2_Filtered: ' + data_str[4:8])
    print('[2]CO2_Instant: ' + data_str[12:16])
    p_data.CO2 = int(data_str[4:8]) * 100 - 1600
    print('[2]CO2: ' + ('%d' % (p_data.CO2)))

    i2c = I2C(0, I2C.MASTER)
    i2c.init(I2C.MASTER, baudrate=100000, pins=('P9', 'P10'))
    time.sleep(0.05)
    #print(i2c.scan())

    if sht31 == 0:
        i2c.writeto(0x40, bytes([0xF3]))
        time.sleep(0.1)
        temperature_data = i2c.readfrom(0x40, 3)
        #print(temperature_data)
        time.sleep(0.1)
        temperature_value = _get_temperature_from_buffer(temperature_data)
        p_data.temp = temperature_value
        time.sleep(0.1)
        i2c.writeto(0x40, bytes([0xF5]))
        time.sleep(0.05)
        humidity_data = i2c.readfrom(0x40, 3)
        humidity_value = _get_humidity_from_buffer(humidity_data)
        p_data.humd = humidity_value

        humidity_value_str = '%.2f' % humidity_value
        temperature_value_str = '%.2f' % temperature_value
        print('[2]Humidity: ' + humidity_value_str)
        print('[2]Temperature: ' + temperature_value_str)
    else:
        i2c.writeto(0x44, bytes([0x24, 0x00]))
        time.sleep(0.02)
        combined_data = i2c.readfrom(0x44, 6)

        temperature_value = _get_sht31_temp_from_buffer(combined_data)
        p_data.temp = temperature_value

        humidity_value = _get_sht31_humidity_from_buffer(combined_data)
        p_data.humd = humidity_value

        humidity_value_str = '%.2f' % humidity_value
        temperature_value_str = '%.2f' % temperature_value
        print('[2]Humidity (SHT31): ' + humidity_value_str)
        print('[2]Temperature (SHT31): ' + temperature_value_str)

    lux_sensor = TSL2591(i2c)
    lux_flt = lux_sensor.lux
    p_data.lux = lux_flt
    print('[2]Light: ' + '%.2f' % lux_flt + 'lux')

    uart_mul = UART(1, baudrate=9600, pins=('P3', 'P4'))
    p_out_ctrla.value(1)
    p_out_ctrlb.value(0)
    time.sleep(0.1)
    ggflag = 0
    ddflag = 0
    while ggflag == 0 or ddflag == 0:
        while uart_mul.any() == 0:
            time.sleep(0.1)
        nmealine_bytes = uart_mul.readall()
        #print(nmealine_bytes)
        time.sleep(0.1)
        nmealine_all = nmealine_bytes.decode('utf-8')
        nmealine_all_split = nmealine_all.split('\r\n')
        for nmealine in nmealine_all_split:
            if (nmealine[0:6] == '$GNGGA') and (len(nmealine.split(',')) >=
                                                15) and (ggflag == 0):
                nmea_fields = nmealine.split(',')
                #print(nmea_fields)
                print('[2]Time: ' + nmea_fields[1])
                if nmea_fields[1] != '':
                    p_data.time = float(nmea_fields[1])
                print('[2]Lat: ' + nmea_fields[2] + nmea_fields[3])
                if nmea_fields[2] != '':
                    p_data.lat = float(nmea_fields[2])
                if nmea_fields[3] == 'S':
                    p_data.lat *= -1
                print('[2]Lon: ' + nmea_fields[4] + nmea_fields[5])
                if nmea_fields[4] != '':
                    p_data.Lon = float(nmea_fields[4])
                if nmea_fields[5] == 'W':
                    p_data.lon *= -1
                print('[2]Fix: ' + nmea_fields[6])
                print('[2]#Sat: ' + nmea_fields[7])
                print('[2]HDOP: ' + nmea_fields[8])
                print('[2]Alt: ' + nmea_fields[9])
                if nmea_fields[9] != '':
                    p_data.alt = float(nmea_fields[9])
                ggflag = 1
            elif (nmealine[0:6]
                  == '$GNRMC') and (len(nmealine.split(',')) >= 13) and (ddflag
                                                                         == 0):
                nmea_fields = nmealine.split(',')
                print('[2]Date: ' + nmea_fields[9])
                if nmea_fields[9] != '':
                    p_data.date = int(nmea_fields[9])
                ddflag = 1
    dummy = uart_mul.readall()
    p_data_bytes = PeripheralBytes(p_data)
    print('[2]===================')
    time.sleep(0.01)
    gc.collect()
    print(gc.mem_free())
    return p_data_bytes
Ejemplo n.º 32
0
class GROVEGPS:
    # dflt pins=(Tx-pin,Rx-pin): wiring Tx-pin -> Rx GPS module
    def __init__(self, port=1, baud=9600, debug=False, pins=('P3', 'P4')):
        try:
            self.ser = UART(port, baudrate=baud, pins=pins)
        except:
            self.ser = UART(port, baudrate=baud)
        self.ser.readall()
        self.raw_line = ""
        self.gga = []
        self.validation = []  # contains compiled regex
        self.debug = debug
        self.last_read = 0
        self.date = 0

        # compile regex once to use later
        for i in range(len(patterns) - 1):
            self.validation.append(re.compile(patterns[i]))

        self.clean_data()
        # self.get_date()  # attempt to get a date from GPS.

    def DEBUG(self, in_str):
        if self.debug:
            print(in_str)

    # convert to string and if needed wait a little
    def readCR(self, serial):
        if not self.last_read:
            serial.readall()
            self.last_read = ticks_ms()
        self.last_read = ticks_ms() - self.last_read
        if self.last_read < 200 and self.last_read >= 0:
            sleep_ms(200 - self.last_read)
        line = ''
        try:
            line = serial.readline().decode('utf-8')
        except:
            if self.debug: print('Read line error')
        self.last_read = ticks_ms()
        return line.strip()

    def clean_data(self):
        '''
    clean_data:
    ensures that all relevant GPS data is set to either empty string
    or -1.0, or -1, depending on appropriate type
    This occurs right after initialisation or
    after 50 attemps to reach GPS
    '''
        self.timestamp = ""
        self.lat = -1.0  # degrees minutes and decimals of minute
        self.NS = ""
        self.lon = -1.0
        self.EW = ""
        self.quality = -1
        self.satellites = -1
        self.altitude = -1.0

        self.latitude = -1.0  #degrees and decimals
        self.longitude = -1.0
        self.fancylat = ""  #

    def read(self):
        '''
    Attempts 50 times at most to get valid data from GPS
    Returns as soon as valid data is found
    If valid data is not found, then clean up data in GPS instance
    '''
        valid = False
        for i in range(50):
            # sleep_ms(500)
            self.raw_line = self.readCR(self.ser)
            if self.validate(self.raw_line):
                valid = True
                break

        if valid:
            return self.gga
        else:
            self.clean_data()
            return []

    # use GPS date/time to update RTC time
    def UpdateRTC(self):
        for i in range(20):
            if self.date: break
            self.read()
        day = int(self.date)
        if not day:
            return False
        hours = int(float(self.timestamp))
        millis = int(float(self.timestamp) * 1000) % 1000
        try:
            rtc = RTC()
            rtc.init((2000 + (day % 100), (day // 100) % 100, day // 10000,
                      hours // 10000, (hours // 100) % 100, hours % 100,
                      millis % 1000))
        except:
            return False
        return True

    def validate(self, in_line):
        '''
    Runs regex validation on a GPGAA sentence.
    Returns False if the sentence is mangled
    Return True if everything is all right and sets internal
    class members.
    '''
        if in_line == "":
            return False
        if in_line[:6] == "$GPRMC":  # got time/date line
            ind = in_line.split(',')
            if (len(ind) < 9) or (len(ind[9]) != 6): return False
            self.date = ind[9]
            return False
        if in_line[:6] != "$GPGGA":
            return False

        self.gga = in_line.split(",")
        self.DEBUG(self.gga)

        # Sometimes multiple GPS data packets come into the stream.
        # Take the data only after the last '$GPGGA' is seen
        try:
            ind = self.gga.index('$GPGGA', 5, len(self.gga))
            self.gga = self.gga[ind:]
        except ValueError:
            pass

        if len(self.gga) != 15:
            self.DEBUG("Failed: wrong number of parameters ")
            self.DEBUG(self.gga)
            return False

        for i in range(len(self.validation) - 1):
            if len(self.gga[i]) == 0:
                self.DEBUG("Failed: empty string %d" % i)
                return False
            test = self.validation[i].match(self.gga[i])
            if test == False:
                self.DEBUG("Failed: wrong format on parameter %d" % i)
                return False
            else:
                self.DEBUG("Passed %d" % i)

        try:
            self.timestamp = self.gga[1]
            self.lat = float(self.gga[2])
            self.NS = self.gga[3]
            self.lon = float(self.gga[4])
            self.EW = self.gga[5]
            self.quality = int(self.gga[6])
            self.satellites = int(self.gga[7])
            self.altitude = float(self.gga[9])

            self.latitude = self.lat // 100 + self.lat % 100 / 60
            if self.NS == "S":
                self.latitude = -self.latitude
            self.longitude = self.lon // 100 + self.lon % 100 / 60
            if self.EW == "W":
                self.longitude = -self.longitude
        except ValueError:
            self.DEBUG("FAILED: invalid value")

        return True

    def MyGPS(self):
        for cnt in range(20):
            self.read()
            if self.quality > 0: break
        if self.quality < 1:
            return None
        self.UpdateRTC()
        # 4 decimals: resolution of ~ 11 meter
        return {
            'date': self.date,
            'timestamp': self.timestamp,
            'longitude': round(self.longitude, 4),
            'latitude': round(self.latitude, 4),
            'altitude': int(self.altitude)
        }
Ejemplo n.º 33
0
#
# Hook up a FTDI USB-serial adapter to TX, RX, GND on board corresponding to
# desired UART. Open a terminal emulator on the FTDI and follow prompts from
# code below.
#

from machine import UART
from time import sleep

u = UART(1, 9600)

# clear any pending input
u.read()

print(u.any())

print("enter 5 characters (newline counts as a character)")
while True:
    if u.any() == 5:
        break
    sleep(0.1)

print(u.read(5))
print(u.any())
Ejemplo n.º 34
0
from machine import UART
import os
import time

mch = os.uname().machine
if "LaunchPad" in mch:
    uart_pins = [[("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")]]
elif "WiPy" in mch:
    uart_pins = [[("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")]]
else:
    raise Exception("Board not supported!")

# just in case we have stdio duplicated on any of the uarts
os.dupterm(None)

uart0 = UART(0, 1000000, pins=uart_pins[0][0])
uart1 = UART(1, 1000000, pins=uart_pins[1][0])

uart0_int_count = 0
uart1_int_count = 0


def uart0_handler(uart_o):
    global uart0_irq
    global uart0_int_count
    if uart0_irq.flags() & UART.RX_ANY:
        uart0_int_count += 1


def uart1_handler(uart_o):
    global uart1_irq
Ejemplo n.º 35
0
# This is the boot file operated once at start up
from machine import UART
import machine
import os

uart = UART(0, baudrate=115200)
os.dupterm(uart)

# machine.main('main.py')
Ejemplo n.º 36
0
import utime
from machine import I2C, Pin, UART, unique_id
import neopixel, machine


id = unique_id()
chipId='{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}'.format(id[0], id[1], id[2], id[3], id[4], id[5])
print('chipId shows: ', chipId)
i2c = machine.I2C(scl=Pin(22), sda=Pin(21))
print('i2c bus shows: ', i2c.scan())
uart2=UART(1,rx=26,tx=27,baudrate=9600)
uart1=UART(2,rx=0,tx=2,baudrate=9600)
utime.sleep(2)
print('uart1 shows:', uart1.read(32))
print('uart2 shows:', uart2.read(32))
RED = (255,0,0); GREEN = (0,255,0); BLUE = (0,0,255)
colors = [RED, GREEN, BLUE]
np = neopixel.NeoPixel(Pin(12), 1)
for color in colors:
	np[0] = color
	np.write()
	utime.sleep(1)
Ejemplo n.º 37
0
from machine import UART, Pin

bt = UART(0, 9600)

L1 = Pin(2, Pin.OUT)
L2 = Pin(3, Pin.OUT)
L3 = Pin(4, Pin.OUT)
L4 = Pin(5, Pin.OUT)

while True:

    br = bt.readline()

    if "ON1" in br:
        L1.value(0)
    elif "OFF1" in br:
        L1.value(1)

    elif "ON2" in br:
        L2.value(0)
    elif "OFF2" in br:
        L2.value(1)

    elif "ON3" in br:
        L3.value(0)
    elif "OFF3" in br:
        L3.value(1)

    elif "ON4" in br:
        L4.value(0)
    elif "OFF4" in br:
Ejemplo n.º 38
0
dat(1)

# freezing -> did we already send the sms ? don't send it twice
freezing = False

# set the clock
c = untplib.NTPClient()
rtclock = RTC()
clock_adjust()

# set the regex for the uart answers
re = ure.compile("\r\nOK\r\n")
er = ure.compile("\r\nERROR\r\n")

# config the uart and see if somethings answers
uart = UART(1, baudrate=115200, pins=(TX_PIN, RX_PIN))  # uart #, baudrate, pins tx,rx
uart.write('+++')
uart.write('AT+COPS?\r\n')
time.sleep(1)
while uart.any() != 0:
    print(uart.readall())

# get the battery
adc = ADC()
bat = adc.channel(pin=BAT_PIN)

# initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH, server=BLYNK_SERVER)

# register virtual pin 4 (the button on the blynk that sends the temp sms right away)
blynk.add_virtual_pin(4, write=v4_write_handler)
Ejemplo n.º 39
0
# Untitled - By: s8kevkla - Tue Jan 7 2020
import sensor, image, time, lcd
from fpioa_manager import fm
from machine import UART
from board import board_info

fm.register(board_info.PIN15, fm.fpioa.UART1_TX,
            force=True)  # Sets pin15 as new TX-pin
# fm.register(board_info.PIN17, fm.fpioa.UART1_RX, force=True)
# fm.register(board_info.PIN9, fm.fpioa.UART2_TX, force=True)
fm.register(board_info.PIN10, fm.fpioa.UART2_RX, force=True)

uart_A = UART(UART.UART1, 115200, 8, None, 1, timeout=1000, read_buf_len=4096)
uart_B = UART(UART.UART2, 115200, 8, None, 1, timeout=1000, read_buf_len=4096)

THRESHOLD = (0, 65)

sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
sensor.skip_frames(time=2000)  # Time for camera to initialize and stabilize
sensor.set_hmirror(0)  # Mirrors image
clock = time.clock()
lcd.init()

Found_centerline = False
Found_crossing = False
centerlines = 4
roadlength = 4
crossingsFound = 0
offCenterCrossing = False