Exemplo n.º 1
0
    def __init__(self, serial_id=2, baudrate=115200, **kwargs):
        """
		id: used for topics id (negotiation)
		advertised_topics: manage already negotiated topics
		subscribing_topics: topics to which will be subscribed are here
		serial_id: uart id
		baudrate: baudrate used for serial comm
		"""
        self.id = 101
        self.advertised_topics = dict()
        self.subscribing_topics = dict()
        self.serial_id = serial_id
        self.baudrate = baudrate

        if "serial" in kwargs:
            self.uart = kwargs.get("serial")
        elif "tx" in kwargs and "rx" in kwargs:
            self.uart = m.UART(self.serial_id, self.baudrate)
            self.uart.init(
                self.baudrate,
                tx=kwargs.get("tx"),
                rx=kwargs.get("rx"),
                bits=8,
                parity=None,
                stop=1,
                txbuf=0,
            )
        else:
            self.uart = m.UART(self.serial_id, self.baudrate)
            self.uart.init(self.baudrate, bits=8, parity=None, stop=1, txbuf=0)

        if sys.platform == "esp32":
            threading.start_new_thread(self._listen, ())
        else:
            threading.Thread(target=self._listen).start()
Exemplo n.º 2
0
def main():
    try:
        uos.dupterm(None, 1)  # disable REPL on UART(0)
        uart = machine.UART(0)
        uart.init(115200, timeout=3000, bits=8, parity=None, stop=1, rxbuf=128)
        while True:
            if uart.any():
                hostMsg = uart.readline()
                
                if hostMsg is not None:
                    strMsg = hostMsg.decode().strip('\r\n')
                    if '\x03' in strMsg:
                        raise Exception('Cto repl')
                    elif strMsg == '\x00':
                        raise Exception('STOP code')
                    else:
                        for i in range(len(strMsg)):
                            led.off()
                            time.sleep(0.05)
                            led.on()
                            time.sleep(0.1)
                        uart.write(strMsg+'\n')
                        
    except Exception as err:
        uart.write('Exception was raised')
        led.on()        
        
    finally:
        uos.dupterm(machine.UART(0, 115200), 1)
Exemplo n.º 3
0
def uartspeed(newbaud):
    global uart
    command("AT+IPR=" + str(newbaud))
    uart.deinit()
    if (newbaud==0):
        uart = machine.UART(uart_port, uart_default_baud, mode=UART.BINARY, timeout=uart_timeout)
    else:
        uart = machine.UART(uart_port, newbaud, mode=UART.BINARY, timeout=uart_timeout)
Exemplo n.º 4
0
def main():
    micropython.kbd_intr(-1)
    machine.UART(0, 9600).init(
        9600)  # 9600 baud rate recommended by LoLin NodeMcu board
    for line in sys.stdin:

        raw = line

        if not nic.isconnected():
            led.on()
            if not network.STAT_CONNECTING:
                nic.connect('bloomu')

        else:
            led.off()
            if gprmcREG.match(raw):
                raw = raw.split(',')
                raw.pop(0)
                dateTime = raw[8] + raw[0]
                dateTime = dateTime.replace('.', '')
                locData = {
                    "lat": raw[2] + raw[3],
                    "long": raw[4] + raw[5],
                    "speed": raw[6]
                }
                data = {dateTime: locData}
                urequests.patch(dataBaseURL,
                                data=json.dumps(data),
                                headers={"content-type": "application/json"})
                data = {dateTime: raw}
                urequests.patch(
                    "https://bloombus-163620.firebaseio.com/rawLog/.json",
                    data=json.dumps(data),
                    headers={"content-type": "application/json"})
Exemplo n.º 5
0
    def __init__(self, uart):
        self.uart = uart
        uart = machine.UART(1, baudrate=9600)

        utime.sleep_ms(100)
        self.buf = bytearray(2)
        self.t = 0
Exemplo n.º 6
0
 def __init__(self, port=8999):
     super().__init__(port=port, name='pymata')
     esp.uart_nostdio(1)
     self.gpio2 = machine.Pin(2)
     self.gpio2.init(machine.Pin.OUT)
     self.sport = machine.UART(0, 57600, timeout=0)
     self.reset()
 def __init__(self, txPin=None, rxPin=None):
     self._ser = None
     self._serWrite = lambda x: x
     self._serRead = doNothing
     self._serAvailable = doNothing
     self.sleep = doNothing
     self._recvBuf = bytearray([])
     if sys.platform.find("linux") >= 0:
         import serial
         self._ser = serial.Serial("/dev/ttyAMA0", 9600)
         self._serAvailable = self._ser.inWaiting
         self._serWrite = self._ser.write
         self._serRead = self._ser.read
         self.sleep = lambda t: time.sleep(t)
         self._ser.flushInput()
     elif sys.platform == "esp32":
         import machine
         import os
         self._os = os
         self._ser = machine.UART(1, baudrate=9600, rx=rxPin, tx=txPin)
         self._serAvailable = self._ser.any
         self._serWrite = self._ser.write
         self._serRead = self._ser.read
         self.sleep = lambda t: time.sleep(t)
     else:
         print("unsupport platform")
         exit()
Exemplo n.º 8
0
def getFromUart(command):
    '''Write a command to the UART bus and return the result value. Accepted commands are:
    - `ATON`: turn relay on
    - `ATOFF`: turn relay off
    - `ATPRINT`: print status informations (every second)
    - `ATZERO`: reset energy consumption counter
    - `ATRESET`: reset any counter
    - `ATPOWER`: get actual power consumption
    - `ATREAD`: get actual current consumption
    - `ATSTATE`: get relay status (0/1)

    Since `uart.read()` is non-blocking, '\\n' is expected as terminating character.'''

    uart = machine.UART(1, baudrate=9600, rx=16, tx=17, timeout=10)

    uart.write(command)

    res = bytes()
    startTime = time.ticks_ms()  # timeout for the loop below
    while b'\n' not in res:
        toAppend = uart.read()

        if toAppend:
            if res != b'':
                res += toAppend
            else:
                res = toAppend

        if time.ticks_diff(time.ticks_ms(), startTime) > READ_TIMEOUT:
            print('ERROR: read timeout')
            return b'ERROR: read timeout'

    res = res.decode('utf-8').replace('\n', '').encode()

    return res
Exemplo n.º 9
0
 def write_dev_value(self, addr, port, var_name, var_value):
     ser = 0
     ret = 'unknow error'
     try:
         count = 0
         while DynApp.serstat[port] != 0:
             utime.sleep_ms(200)
             count += 1
             if count > 25:
                 raise 'timeout'
                 return "open serial timeout"
         ser = machine.UART(port, baudrate=self.baudrate)
         ser.init(self.baudrate, self.bytesize, self.parity, self.stopbits,
                  self.timeout)
         if ser == 0:
             raise "open serial failed"
         else:
             DynApp.serstat[port] = 2
             func = getattr(self, var_name, None)
             if func:
                 ret = func(ser, addr, var_value)
             else:
                 raise 'wrong data:%s' % var_name
     except Exception as e:
         ret = e.message
     # if ser != 0 and ser.isOpen():
     # ser.deinit()
     DynApp.serstat[port] = 0
     return ret
Exemplo n.º 10
0
 def read_dev_value(self, addr, port=2):
     ser = 0
     try:
         count = 0
         if port not in DynApp.serstat:
             DynApp.serstat[port] = 0
         while DynApp.serstat[port] != 0:
             utime.sleep_ms(200)
             count += 1
             if count > 25:
                 raise 'timeout'
                 return "open serial timeout"
         ser = machine.UART(port, baudrate=self.baudrate)
         ser.init(baudrate=self.baudrate,
                  bits=self.bytesize,
                  parity=self.parity,
                  stop=self.stopbits,
                  timeout=self.timeout)
         if ser == 0:
             raise "open serial failed"
         DynApp.serstat[port] = 1
         value = self.read_device(addr, ser)
         if value is None or len(value) == 0:
             raise Exception("value is empty")
     except Exception as e:
         value = {'_status': 'offline', 'error': e}
         utime.sleep_ms(200)
     except DevError as e:
         value.update({'error': e.value})
         utime.sleep_ms(200)
     #  ser.deinit()
     DynApp.serstat[port] = 0
     return value
Exemplo n.º 11
0
 def __init__(self, x=1, baudrate=9600, timeout=2, use_query_mode=True):
     """Initialise and open serial port.
     """
     uart = machine.UART(x, baudrate)
     uart.init(baudrate, bits=8, parity=None, stop=1)
     self.uart = uart
     self.set_report_mode(active=not use_query_mode)
Exemplo n.º 12
0
def test(N=50):
    adc = machine.ADC(0)

    pcd8544_test.showText(0, 0, 'Midiendo')
    time.sleep(1)
    pcd8544_test.clear()
    N = 50

    uart = machine.UART(0, 9600)
    uart.init(9600)
    while True:
        media = 0
        for i in range(0, N):
            value = adc.read()
            media += value * 1.0
            time.sleep(0.1)
        value = media / N
        print(value)
        pcd8544_test.clear()
        pcd8544_test.showText(0, 0, str(value))
        sys.stdout.write('<')
        msg = sys.stdin.readline().rstrip()
        if len(msg) < 1:
            msg = sys.stdin.readline().rstrip()
        pcd8544_test.showText(0, 10, msg)
        print(msg)
        try:
            v = float(msg)
            cte = v * 1023 / value
            pcd8544_test.showText(0, 40, str(cte))
            print(cte)
        except Exception as e:
            print(str(e))
Exemplo n.º 13
0
 def __init__(self, rxpin=16, txpin=17):
     self.sensori = machine.UART(1)
     self.sensori.init(baudrate=9600,
                       bits=8,
                       parity=None,
                       stop=1,
                       rx=rxpin,
                       tx=txpin)
     self.nollapiste_kalibroitu = False
     self.co2_arvo = 0
     self.co2_keskiarvot = []
     self.co2_keskiarvoja = 20
     self.co2_keskiarvo = 0
     self.sensori_aktivoitu_klo = utime.time()
     self.arvo_luettu_klo = utime.time()
     self.mittausvali = '0_5000'
     self.esilammitysaika = 10  # tulee olla 180
     self.lukuvali = 10  # tulee olla 120
     self.LUKU_KOMENTO = bytearray(b'\xFF\x01\x86\x00\x00\x00\x00\x00\x79')
     self.KALIBROI_NOLLAPISTE = bytearray(
         b'\xFF\x01\x87\x00\x00\x00\x00\x00\x78')
     self.KALIBROI_SPAN = bytearray(b'\xFF\x01\x88\x07\xD0\x00\x00\x00\xA0')
     self.ITSEKALIBROINTI_ON = bytearray(
         b'\xFF\x01\x79\xA0\x00\x00\x00\x00\xE6')
     self.ITSEKALIBTOINTI_OFF = bytearray(
         b'\xFF\x01\x79\x00\x00\x00\x00\x00\x86')
     self.MITTAUSVALI_0_2000PPM = bytearray(
         b'\xFF\x01\x99\x00\x00\x00\x07\xD0\x8F')
     self.MITTAUSVALI_0_5000PPM = bytearray(
         b'\xFF\x01\x99\x00\x00\x00\x13\x88\xCB')
     self.MITTAUSVALI_0_10000PPM = bytearray(
         b'\xFF\x01\x99\x00\x00\x00\x27\x10\x2F')
Exemplo n.º 14
0
def esp_connect():
    fm.register(board_info.WIFI_RX, fm.fpioa.UART2_TX)
    fm.register(board_info.WIFI_TX, fm.fpioa.UART2_RX)
    uart = machine.UART(machine.UART.UART2,
                        115200,
                        timeout=1000,
                        read_buf_len=4096)
    try:
        nic = network.ESP8285(uart)
        nic.connect(SSID, SSID_PWD)
        if (nic.isconnected):
            print("ip:{}/{}".format(nic.ifconfig()[0], nic.ifconfig()[1]))
            return True
        else:
            sleep(1)  # retry
            if (nic.isconnected):
                print("ip:{}/{}".format(nic.ifconfig()[0], nic.ifconfig()[1]))
                return True
            else:
                print("network connection failed.\n")
                return False

    except:
        print(" try to connect ESP8286 TX to pin-{},RX to pin-{}".format(
            board_info.WIFI_TX, board_info.WIFI_RX))
        print(" ,and ESP8286 must be runing on AT command mode.\n")
        return False
Exemplo n.º 15
0
 def open(self):
     if self.__isMicropython:
         port = self.port
         for sub in (
                 "/dev/ttyS",
                 "/dev/ttyUSB",
                 "/dev/ttyACM",
                 "COM",
                 "UART",
         ):
             port = port.replace(sub, "")
         try:
             self.__portNum = int(port.strip())
         except ValueError:
             raise SerialException("Invalid port: %s" % self.port)
         try:
             import machine
             self.__lowlevel = machine.UART(
                 self.__portNum, self.baudrate, self.bytesize,
                 0 if self.parity == PARITY_EVEN else 1,
                 1 if self.stopbits == STOPBITS_ONE else 2)
             print("Opened machine.UART(%d)" % self.__portNum)
         except Exception as e:
             raise SerialException("UART%d: Failed to open:\n%s" %
                                   (self.__portNum, str(e)))
         return
     raise NotImplementedError
Exemplo n.º 16
0
 def __init__(self, checkInterval=250, callback=None):
     self.checking = False
     self.sending = False
     self.uart = machine.UART(1, tx=32, rx=33)
     self.timer = machine.Timer(8457)
     self.callback = callback
     self.checkInterval = checkInterval
Exemplo n.º 17
0
    def __init__(self,
                 id,
                 password,
                 contract_amperage,
                 collect_date,
                 *,
                 progress_func=None,
                 logger_name=__name__):
        global logger
        logger = logging.getLogger(logger_name)
        self.progress = progress_func if progress_func else lambda _: None

        self.uart = machine.UART(1, tx=0, rx=36)
        self.uart.init(115200, bits=8, parity=None, stop=1, timeout=2000)

        self.id = id
        self.password = password
        self.contract_amperage = int(contract_amperage)
        self.collect_date = int(collect_date)

        self.channel = None
        self.pan_id = None
        self.mac_addr = None
        self.lqi = None

        self.ipv6_addr = None
        self.power_coefficient = None
        self.power_unit = None

        self.timeout = 60
Exemplo n.º 18
0
def UART(config):
    config = dict(config)
    port = config.pop('port')
    uart = machine.UART(port)
    uart.init(**config)
    #uart.init(921000, bits=8, parity=None, stop=1)
    return uart
 def __init__(self, ble, name='TaxiMac'):
     self._name = name
     self._uart = machine.UART(1, 2400)  #inicializar para UART 1
     self._uart.init(baudrate=2400,
                     bits=8,
                     parity=None,
                     stop=1,
                     timeout=5000)
     self._cadena = []
     self._ble = ble
     self._ble.active(True)
     self._ble.irq(handler=self._irq)
     ((
         self._tx,
         self._rx,
     ), ) = self._ble.gatts_register_services((_UART_SERVICE, ))
     print("tx: {}, rx:{}".format(self._tx, self._rx))
     #((self._handle,),) = self._ble.gatts_register_services((_UART_SERVICE,))
     self._connections = set()
     #self._payload = bytearray('\x02\x01\x02') + self.adv_encode_name('axelukan')
     self._payload = bytearray('\x02\x01\x02') + bytearray(
         (len(bytes(self._name, 'ascii')) + 1, 0x09)) + bytes(
             self._name, 'ascii')
     print("payload:{}".format(self._payload))
     self._advertise()
Exemplo n.º 20
0
def setup_serial(bus=0, baudrate=9600, bits=8):
    # os.dupterm(None) # Kill the REPL?
    logger.debug("Setting up serial")
    uart = machine.UART(bus, baudrate)
    uart.init(baudrate, bits=bits, parity=None, stop=1)
    logger.debug("Serial done")
    return uart
Exemplo n.º 21
0
 def __init__(self):
     self._gps_uart = machine.UART(1, 9600)
     self.cfg = ConfigRepository()
     self._gps_uart.init(tx=self.cfg.get("gps_uart_tx"),
                         rx=self.cfg.get("gps_uart_rx"))
     self._gps = MicropyGPS()
     self._model = None
def selfTest(module_type):
    # CM

    # DM
    # test LED string(s)


def read5VSupply():
    supply5V = machine.ADC(3)
    conversion_factor = 3 * (3.3 / (65535))     # 5V supply into a divide-by-three resistive divider
    return (supply5V.read_u16() * conversion_factor)

def getChar():
    pass

def putChar(port):
    pass


from machine import UART, Pin
import time

uart1 = machine.UART(1, baudrate=9600, tx=Pin(8), rx=Pin(9))

uart0 = machine.UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))

txData = b'hello world\n\r'
uart1.write(txData)
time.sleep(0.1)
rxData = bytes()
while uart0.any() > 0:
    rxData += uart0.read(1)

print(rxData.decode('utf-8'))

#
# Main
#


# Determine if this is a Control Module or a Distribution Module by testing
# whether it is running Python or MicroPython.
# https://docs.micropython.org/en/latest/genrst/syntax.html
try:
    ([i := -1 for i in range(4)])
    module_type = "DM"      # MicroPython
Exemplo n.º 23
0
 def __init__(self):
     import machine
     self.original_term = os.dupterm()
     os.dupterm(None)  # disconnect the current serial port connection
     self.serial = machine.UART(0, 115200)
     self.poll = select.poll()
     self.poll.register(self.serial, select.POLLIN)
     self.write = self.serial.write
Exemplo n.º 24
0
    def __init__(self,
                 device_no,
                 tx_pin=None,
                 rx_pin=None,
                 timeout=None,
                 *args,
                 **kwargs):

        print("Creating logger")
        self.log = LogStub("Main.Nex.Protocol")

        if timeout is None:
            self.read_timeout = 0.1  # in milliseconds
        else:
            self.read_timeout = timeout

        assert self.read_timeout is not None

        self.init_args = {
            "baudrate": 9600,
            "bits": 8,
            "parity": None,
            "stop": 1,

            # UART takes timeout in milliseconds
            "timeout": int(self.read_timeout * 1000),
            "timeout_char": int(self.read_timeout * 1000),
        }

        if tx_pin:
            self.init_args["tx"] = tx_pin
        else:
            self.init_args["tx"] = 25

        if rx_pin:
            self.init_args["rx"] = rx_pin
        else:
            self.init_args["rx"] = 26

        print("Creating uart")

        self.uart = machine.UART(
            device_no,
            9600,
            tx=self.init_args["tx"],
            rx=self.init_args["rx"],
        )

        print("Configuring")

        print("uart init params:", self.init_args)

        self.uart.init(**self.init_args)

        self.probe_set_baud()

        print("Super call:", args, kwargs)
        super().__init__(*args, **kwargs)
Exemplo n.º 25
0
 def __init__(self):
     self.uart = machine.UART(1, tx=17, rx=16)
     self.uart.init(9600, bits=8, parity=None, stop=1)
     self.callback = None
     if self._reset() == 1:
         raise module.Module('Module lorawan not connect')
     self._timer = None
     self.uartString = ''
     time.sleep(2)
Exemplo n.º 26
0
 def connect(self):
     from fpioa_manager import fm
     import machine
     fm.register(35, fm.fpioa.UARTHS_RX, force=True)
     fm.register(34, fm.fpioa.UARTHS_TX, force=True)
     self.uart = machine.UART(machine.UART.UARTHS, 115200, 8, 0, 1, timeout=1000, read_buf_len=4096)
     self.uart.init()
     self.timer.start()
     return self.uart
Exemplo n.º 27
0
 def __init__(self, uartChannel, txPin, rxPin, timer=4, freq=5):
     self.txPin = txPin
     self.rxPin = rxPin
     self.uart = machine.UART(uartChannel)
     self.txTimer = timer
     self.connected = False
     self.payload = bytearray([])
     self.freq = freq
     self.oldbuffer = bytes([])
Exemplo n.º 28
0
def talktopico(msg, timeout=5000):
    try:
        uos.dupterm(None, 1)  # disable REPL on UART(0)
        uart = machine.UART(0)
        uart.init(230400,
                  timeout=3000,
                  bits=8,
                  parity=None,
                  stop=1,
                  rxbuf=128 * 16)
        uart.write('\n\n')
        # while uart.any():
        uart.read()
        uart.write(msg)
        yield from read_response(uart)
    except Exception as err:
        yield str(err)
    finally:
        uos.dupterm(machine.UART(0, 115200), 1)
Exemplo n.º 29
0
def init_uart():
    uart = machine.UART(2,
                        baudrate=9600,
                        rx=16,
                        tx=17,
                        timeout=10,
                        bits=8,
                        parity=None,
                        stop=1)
    return uart
Exemplo n.º 30
0
def start():
    uart = machine.UART(1, tx=25, rx=26, baudrate=9600)
    global pm
    pm = pms5003.PMS5003(uart,
                         lock,
                         active_mode=False,
                         interval_passive_mode=60)
    pms5003.set_debug(True)
    pm.registerCallback(printit)
    asyncio.create_task(testing())
    asyncio.get_event_loop().run_forever()