Example #1
20
def get_GPS_array():    
    com = UART(1,pins=(config.TX, config.RX),  baudrate=9600) 
    my_gps = MicropyGPS()
    time.sleep(2)
    if com.any():
        my_sentence = com.readline()
        for x in my_sentence:
            my_gps.update(chr(x)) 
        gps_array = convert_latlon(my_gps.latitude[0] + (my_gps.latitude[1] / 60), my_gps.longitude[0] + (my_gps.longitude[1] / 60))
        return gps_array
Example #2
1
def start_GPS():    
    com = UART(1,pins=("P11","P12"),  baudrate=9600) 
    my_gps = MicropyGPS()
    if config.LOG == 1:
        mount_sd()
        my_gps.start_logging('/sd/log.txt')
        my_gps.write_log('Restarted logging')

    while True:
        if com.any():
            my_sentence = com.readline()
            for x in my_sentence:
                my_gps.update(chr(x))
            print('Latitude: ' + my_gps.latitude_string() + ' Longitude: ' + my_gps.longitude_string() + ' Altitude: ' + str(my_gps.altitude))
            print('Lat / Lon: ' + str(my_gps.latitude[0] + (my_gps.latitude[1] / 60)) + ', ' + str(my_gps.longitude[0] + (my_gps.longitude[1] / 60)))
Example #3
0
class Serial:
    """ simple class to constantly read and write serial data
        for test purposes only"""
    def __init__(self, baudRate=115200):
        self.baudRate = baudRate
        print("here")
        # the next line creates the uart object and sets uart 1 to be used with pins
        # 1 and 3, which are normally dedicated to uart 0 and locked to REPL.
        # with this code we bypass that and allow communication via the USB cable

        self.uart = UART(1,
                         tx=1,
                         rx=3,
                         baudrate=self.baudRate,
                         bits=8,
                         parity=None,
                         stop=1)

        self.uart.init()

    def writeData(self, data2Write="m"):
        """write data to port without considering if there is anyone listening on the other side"""
        self.uart.write(data2Write)
        return

    def readData(self):
        if self.uart.any() > 0:
            self.uart.readline()

    def readDataPoll(self, timeout=100):  # amount2Read=0):
        """use poll method to see how many characters are available for reading, 
        read them, and return it
        OBS: need to learn what is the UART buffer size and implement controls on the PC side"""
        poll = uselect.poll()
        poll.register(self.uart, uselect.POLLIN)
        # set the duration for waiting
        poll.poll(timeout)

        # timeout=-1 polls the port indefintely. poll.poll returns  a list of tuples that need to be worked on
        amount2read = poll.poll()
        amount2read = (
            amount2read[0][1] + 4
        )  # +4 reads the trailing "/n/r" at the end of each line

        data = self.uart.read(amount2read)

        # print(data)
        # add if statement to make use of poll
        # readData = self.uart.read(amount2Read)
        # print(readData)
        return data
Example #4
0
def uart(epoch):
    uart = UART(2, 115200)
    uart.init(115200, bits=8, parity=0, stop=1, tx=4, rx=5)
    while True:
        pkt = uart.readline()  # read up to 5 bytes
        if (pkt != None):
            pkt = str(pkt)
            pkt = pkt.upper()
            pkt = pkt[2:-4]
            pkt = pkt.split(",")

            try:
                if len(pkt[0]) == 12 and len(pkt[1]) > 6 and len(
                        pkt[2]) > -3 and int(pkt[2]) <= 0:
                    if epoch:
                        flT = time() + 946684800
                    else:
                        flT = time_stamp(time.localtime())
                    m = {
                        'ts': flT,
                        'mac': pkt[0],
                        'data': pkt[1],
                        'rssi': int(pkt[2])
                    }
                    tags.insert(1, m)
                    if len(tags) > 20:
                        tags.pop()

                else:
                    # Malformed UART data
                    pass
            except:
                pass
def uart(epoch, decode):
    uart = UART(2, 115200)
    uart.init(115200, bits=8, parity=0, stop=1, tx=4, rx=5)
    while True:
        pkt = uart.readline()
        if (pkt != None):
            pkt = str(pkt)
            pkt = pkt.upper()
            pkt = pkt[2:-4]
            pkt = pkt.split(",")

            try:
                if len(pkt[0]) == 12 and len(pkt[1]) > 6 and len(
                        pkt[2]) > -3 and int(pkt[2]) <= 0:
                    if epoch:
                        flT = time.time() + 946684800
                    else:
                        flT = time_stamp(time.localtime())
                    m = {
                        'ts': flT,
                        'mac': pkt[0],
                        'data': pkt[1],
                        'rssi': int(pkt[2])
                    }
                    if decode:
                        d = decoder.decode(pkt[1])
                        m.update(d)
                    msgJson = ujson.dumps(m)
                    clientB.publish(topic=TOPIC + "ble" + pkt[0], msg=msgJson)
                else:
                    # Malformed UART data
                    pass
            except:
                pass
Example #6
0
def main():
    global saveTime
    com = UART(0, 9600)
    com.init(9600)

    gpsStr = b''
    gpsReading = False

    while True:
        data = com.readline()
        if data and (gpsReading or ('$GPRMC' in data)):
            gpsStr += data

            if '\n' in data:
                gpsReading = False
                lat, long, today, now = convertGPS(gpsStr)
                displayGPS(lat, long, today, now)

                if time.ticks_diff(time.ticks_ms(), saveTime) > interval:
                    saveGPS(lat, long, today, now)
                    saveTime = time.ticks_ms()

                gpsStr = b''
            else:
                gpsReading = True
Example #7
0
class Syringe_pump():
    def __init__(self, port):
        assert port.UART is not None, '! Pump needs port with UART.'
        self.uart = UART(port.UART, 9600)
        self.uart.init(9600, bits=8, parity=None, stop=1, timeout=100)
        self.uart.write('C')
        self.uart.write('Z')

    def infuse(self, val):
        self.uart.write('I,{}\n'.format(val))

    def check_for_serial(self):
        if self.uart.any():
            return self.uart.readline().decode("utf-8").strip('\n')
        else:
            return None

    def reset_volume(self):
        self.uart.write('Z')

    def retract(self):
        self.uart.write('R')

    def send_animal_number(self, number):
        self.uart.write('A,{}\n'.format(number))
Example #8
0
class MyTimeGps:
    _c = ""

    def __init__(self):
        try:
            self._ser = UART(2, tx=12, rx=34)
            self._ser.init(9600, bits=8, parity=None, stop=1)
        except:
            assert False, "*** error uart"
        print("---Time (GPS)----")

    def read(self):
        while True:
            time.sleep(.01)
            try:
                c = self._ser.readline().decode()
                s2 = c.split(',')
                if s2[0] == "$GPRMC":
                    break
            except:
                # no data
                pass
        return s2

    def last_sentence(self):
        return self._c
Example #9
0
class WaterLevel:
    def __init__(self, port):
        self.port = port
        self.uart = UART(port, 9600)
        self.uart.init(9600,
                       timeout=10)  # 9600, 1byte about 1ms, wait for 10ms
        self.buffer = RingBuffer(10)

    # return
    # False: no change
    # True: change, need read value
    def Check(self):
        count = self.uart.any()
        if count < 3:
            return False
            # At lease 3 bytes in buffer (For example:0mm)

        value_change = None

        while 1:  # maybe too many data in UART RX buffer
            data = self.uart.readline()
            if data:
                number_string = re.search(b'^\d+', data)
                if number_string:
                    number = int(number_string.group(0))
                    value_change = self.buffer.InsertData(number, True)

            else:
                break

        return value_change

    def GetValue(self):
        return self.buffer.GetAverage()
Example #10
0
def main():
    print("Connecting")
    do_connect()
    print("Connected")
    res = urequests.post(
        'http://ec2-18-205-17-12.compute-1.amazonaws.com:3000/dbhandler/data',
        data="Hello")
    print(res.text)
    uart = UART(0, 115200)
    x = ""
    #Until the ESP runs, the serial input to the ESP will be processed to be sent to the server
    while (True):
        #Chunks of Serial data in bytes
        chunk = uart.readline()
        if chunk is not None:
            #Convert the binary data to string
            chunk = chunk.decode('utf-8')

            #Combine chunks of data together
            x = x + chunk
            #One data entry ends after the newline character
            if x.find('\n') >= 0:
                try:
                    x = x.replace('ovf', '0.0')
                    #Parse string to JSON format
                    x = ujson.loads(x)
                    sendData(x)
                except ValueError:
                    print("ValueError: Discarding")
                #Reset for the next entry
                x = ""
Example #11
0
def getCO2():
    uart = UART(1, 9600, rx=15, tx=12)

    uart.init(9600, bits=8, parity=None, stop=1, timeout=200)

    uart.write(b'\xff\x01\x86\x00\x00\x00\x00\x00y')
    s = uart.readline(9)

    return ((s[2] * 256) + s[3])
def measure_start():
    uos.dupterm(None, 1)

    uart = UART(0)
    uart.init(115200)
    step = 0
    while step < 100:
        print(uart.readline())
        step += 1
        utime.sleep_ms(200)
Example #13
0
def Print_Serial_num():
    u = UART(2, baudrate=115200, bits=8, parity=None, stop=1, rx=26, tx=25,timeout=200)
    display.fill(1)
    display.show()
    while True:
    
        if u.readline()=='COM:Give me string'.encode():
      
            sleep_ms(10)
            u.write(machine_id[:6]+'\n')
            u.write(machine_id[6:]+'\n\r')
            u.write(machine_id[:6]+'\n')
            u.write(machine_id[6:]+'\n\r')
Example #14
0
class GPS_data():
    def __init__(self):
        self.uart = UART(1, pins=(config.TX, config.RX), baudrate=9600)
        self.gps_dev = MicropyGPS()

    def get_loc(self):
        coords = array.array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0])
        timestamp = (0, 0, 0)
        valid = False
        sentence = ''
        # read buffer to last line
        while self.uart.any():
            sentence = self.uart.readline()
        # if timed-out process last line
        if len(sentence) > 0:
            for x in sentence:
                self.gps_dev.update(chr(x))
            if config.DEBUG:
                print(sentence)
                print('Longitude', self.gps_dev.longitude)
                print('Latitude', self.gps_dev.latitude)
                print('UTC Timestamp:', self.gps_dev.timestamp)
                print('Fix Status:', self.gps_dev.fix_stat)
                print('Altitude:', self.gps_dev.altitude)
                print('Horizontal Dilution of Precision:', self.gps_dev.hdop)
                print('Satellites in Use by Receiver:',
                      self.gps_dev.satellites_in_use)
            if self.has_fix():
                valid = True
                timestamp = self.gps_dev.timestamp
                lat = int((self.gps_dev.latitude[0] +
                           (self.gps_dev.latitude[1] / 60) + 90) * 10000)
                lon = int((self.gps_dev.longitude[0] +
                           (self.gps_dev.longitude[1] / 60) + 180) * 10000)
                alt = int((self.gps_dev.altitude) * 10)
                lhdop = int((self.gps_dev.hdop) * 10)
                # encode location data
                coords[0] = lat
                coords[1] = (lat >> 8)
                coords[2] = (lat >> 16)
                coords[3] = lon
                coords[4] = (lon >> 8)
                coords[5] = (lon >> 16)
                coords[6] = alt
                coords[7] = (alt >> 8)
                coords[8] = lhdop
        return coords, timestamp, valid

    def has_fix(self):
        return (self.gps_dev.fix_stat > 0 and self.gps_dev.latitude[0] > 0)
Example #15
0
def do():
    uart = UART(2, tx=17, rx=16, timeout=10)
    uart.init(9600)
    if uart.any():
        uart.read()  # flush
    print('Loading bitstream')
    iceboot.boot('altair.bin')
    print('Done')
    print(uart)
    uart.write('J000000')
    utime.sleep_ms(1000)
    uart.write('\r\n')
    utime.sleep_ms(500)
    uart.write('\r\n')
    utime.sleep_ms(100)
    uart.write('Y\r\n')
    utime.sleep_ms(100)
    while uart.any():
        print(uart.readline())
    utime.sleep_ms(50)
    uart.write('10 PRINT "HI"\r\n')
    utime.sleep_ms(50)
    uart.write('20 FOR F=1 TO 10\r\n')
    utime.sleep_ms(50)
    uart.write('30 PRINT F\r\n')
    utime.sleep_ms(50)
    uart.write('40 NEXT F\r\n')
    utime.sleep_ms(50)
    uart.write('RUN\r\n')
    utime.sleep_ms(200)
    while uart.any():
        print(uart.readline())
    while True:
        while uart.any():
            print(uart.readline())
        utime.sleep_ms(100)
Example #16
0
def set_date_time():    
    com = UART(1,pins=(config.TX, config.RX),  baudrate=9600) 
    my_gps = MicropyGPS()
    time.sleep(2)
    if com.any():
        my_sentence = com.readline()
        for x in my_sentence:
            my_gps.update(chr(x)) 
        date = my_gps.date
        timestamp = my_gps.timestamp
        hour = timestamp[0]
        hour = hour + config.TIMEZONE
        if config.DAYLIGHT == 1:
            hour = hour + 1
        rtc = RTC(datetime=(int(date[2])+2000, int(date[1]), int(date[0]), int(timestamp[0]), int(timestamp[1]), int(timestamp[2]), 0, None)) 
        return rtc      
Example #17
0
class DOUBLE_GPS(object):
    GGA_MESSAGE = b"$GPGGA,141623.523,2143.963,S,04111.493,W,1,12,1.0,0.0,M,0.0,M,,*65\n"
    RMC_MESSAGE = b"$GPRMC,141623.523,A,2143.963,S,04111.493,W,,,301019,000.0,W*7B\n"
    UPDATE_RATE_1S = 'PMTK220,1000'

    def __init__(self, TX, RX, uart):
        self.uart = UART(uart, baudrate=9600)
        self.uart.init(9600, bits=8, tx=TX, rx=RX)
        self.flag = False

    def make_data_available(self, NMEA_sentence):
        self.uart.write(NMEA_sentence)

    def received_command(self):
        command = self.uart.readline()
        if (command != None):
            command, received_check_sum = command.split(b'*')
            command = command.strip(b'$')
            received_check_sum = received_check_sum[0:2]
            generated_check_sum = self.generate_checksum(command)
            command = command.decode()
            if command == self.UPDATE_RATE_1S:
                self.continuous_mode()
                self.flag = True
            return command
        else:
            return None

    def generate_checksum(self, command):
        checksum = 0
        for char in command:
            checksum ^= char
        return checksum

    def continuous_mode(self):
        self.my_timer = Timer(1)
        self.my_timer.init(period=1000,
                           mode=self.my_timer.PERIODIC,
                           callback=self.my_callback)

    def my_callback(self, timer):
        self.make_data_available(self.RMC_MESSAGE)

    def deinit(self):
        self.uart.deinit()
        if hasattr(self, 'my_timer'):
            self.my_timer.deinit()
Example #18
0
def do():
    killbits = [
        "M0 ", "041", "000", "000", "026", "200", "001", "016", "000", "032",
        "032", "032", "032", "011", "322", "010", "000", "333", "377", "172",
        "017", "127", "303", "010", "000", "X", "J0 "
    ]
    uart = UART(2, tx=17, rx=16, timeout=10)
    uart.init(9600)
    if uart.any():
        uart.read()  # flush
    print('Loading bitstream')
    iceboot.boot('altair.bin')
    print('Done')
    print(uart)
    for oword in killbits:
        uart.write(oword)
        utime.sleep_ms(100)
        while uart.any():
            print(uart.readline())
Example #19
0
def main():
    com = UART(0, 9600)
    com.init(9600)

    gpsStr = b''
    gpsReading = False

    while True:
        data = com.readline()
        if data and (gpsReading or ('$GPRMC' in data)) :
            gpsStr += data

            if '\n' in data:
                gpsReading = False
                lat, long, today, now = convertGPS(gpsStr)
                displayGPS(lat, long, today, now)

                gpsStr = b''
            else:
                gpsReading = True
Example #20
0
class SerialEthernet():
    def __init__(self, uartNumber, callback, bufferSize=60):
        self.uart = UART(uartNumber)
        self.callback = callback
        self._listening = False
        self._sendBuffer = bufferSize
        self._ip = None
        self._port = None
        self.send("AT+START")
        sleep(5)

    def _listen(self):
        while True:
            if (self.uart.any()):
                self.callback(self.uart.readline())

    def setIP(self, ip, port):
        self._ip = ip
        self._port = port
        self.send("AT+CONNECT")
        self.send(str(ip[0]))
        self.send(str(ip[1]))
        self.send(str(ip[2]))
        self.send(str(ip[3]))
        self.send(str(port))
        self.send("AT+SEND")

    def start(self):
        _thread.start_new_thread(self._listen, [])

    def send(self, msg):
        trials = ceil(len(msg) / self._sendBuffer)
        for t in range(trials):
            #print("t : ", t)
            #print(msg[t*(self._sendBuffer-1):(t+1)*(self._sendBuffer-1)])
            self.uart.write(msg[t * (self._sendBuffer - 1):(t + 1) *
                                (self._sendBuffer - 1)])
            sleep(0.2)
        self.uart.write("\r")
Example #21
0
class Positioning(object):
	def __init__(self, TX, RX, uart):
		self.uart = UART(uart, baudrate=9600)
		self.uart.init(9600,bits=8,tx=TX,rx=RX)
		self.gps = GPS(self.uart)

	def send_command(self, command):
		self.gps.send_command(command)

	def received_command(self):
		command = self.uart.readline()
		if(command != None):
			return command
		else:
			return None

	def get_latitude(self):
		self.gps.update()
		return self.gps.latitude

	def deinit(self):
		self.uart.deinit()
Example #22
0
lcd.rotation(2)
sensor.reset()
sensor.set_pixformat(sensor.RGB565)
sensor.set_framesize(sensor.QVGA)
#sensor.set_vflip(1)
#sensor.set_hmirror(1)
sensor.run(1)
sensor.skip_frames(time=2000)

fm.register(35, fm.fpioa.UART1_TX, force=True)
fm.register(34, fm.fpioa.UART1_RX, force=True)

uart = UART(UART.UART1, 115200, 8, 0, 0, timeout=1000, read_buf_len=4096)

while (True):
    img = sensor.snapshot()
    lcd.display(img)
    buf = uart.readline()
    if buf and len(buf) == 3:
        print(buf)
        img_buf = img.compress(quality=50)
        sz = img_buf.size()
        img_size1 = (sz & 0xFF0000) >> 16
        img_size2 = (sz & 0x00FF00) >> 8
        img_size3 = (sz & 0x0000FF) >> 0
        data_packet = bytearray([img_size1, img_size2, img_size3])
        uart.write(data_packet)
        uart.write(img_buf)
        data_packet = bytearray([0xAA, 0x55, 0xFF])
        uart.write(data_packet)
Example #23
0
        
        elif x[0] == '$GPRMC':
            #decodes lat and lon to degrees and mins
            nmea_dict['latitude'] = coordDecode(x[3], x[4])
            nmea_dict['longitude'] = coordDecode(x[5], x[6])
        
            # for speed, it can be calculated in MPH, KM/H, m/s Knots
            # 1 = MPH | 2 = KM/H | 3 = m/s | any other no. for knots
            nmea_dict['speed'] = speedCalc(x[7], 1)
        elif x[0] == '$GPZDA':
            # gets the date and time from GPS
            nmea_dict['date_time'] = '{}/{}/{} {}:{}:{}'.format(x[2], x[3], x[4][-2:],x[1][0:2], x[1][2:4], x[1][4:6])
    return nmea_dict

while 1:

    # create a list for NMEA sentences
    l=[]
    # Get NMEA sentence
    s = adaGPS.readline().decode('utf-8').strip().split(',')
    if s[0] == '$GPGGA':
        for x in nmea_list:
            l.append(s)
            s = adaGPS.readline().decode('utf-8').strip().split(',')
        data = nmeaDecode(l)
        fix = '{}, {}, {}'.format('Yes' if data['fix'] else 'No', data['fix_type'], data['satelites'])
        print('''
            Lat :  {}\tSpeed    : {}
            Lon : {}\tAltitude : {}
            UTC : {}\tFix      : {} Sats
            '''.format(data['latitude'],data['speed'], data['longitude'], data['altitude'], data['date_time'], fix))
Example #24
0
class loraNode:
    """RAK811 Interface Library - Converts inputs"""
    """given to serial commands for RAK811"""
    loraNodeSerialBaud = 115200
    serialLib = 0
    serial_write = None
    serial_read = None
    serLib = None
    abp = "abp"
    otaa = "otaa"
    EU868 = "EU868"
    US915 = "US915"
    KR920 = "KR920"
    AU915 = "AU915"
    AS923 = "AS923"
    IN865 = "IN865"

    SpreadFactors = {7: 5, 8: 4, 9: 3, 10: 2, 11: 1, 12: 0}

    def __init__(self, region=1):
        """Initialise The Library and connect to the module"""
        # Import the serial library for the respective platform

        from machine import UART
        self.serLib = UART(1, loraNodeSerialBaud)  # init with given baudrate
        self.serial_write = self.serLib.write
        self.serial_read = self.serLib.readline
        self.serialLib = 1

        self.serLib.readline()
        self.serLib.readline()
        self.serLib.readline()
        self.set_spreadingFactor(7)

        self.serLib.readline()

    ############
    # UART Functions
    ############
    def uart_tx(self, command):
        """Takes the command and sends it via UART via the correct library"""
        # First add at to the beginning
        command = "at+%s\r\n" % command
        #print(command)
        self.serial_write(str.encode(command))

        line = self.serLib.readline()
        #print(line)
        return line

    def uart_rx(self):
        line = self.serLib.readline()
        #print(line)
        return line
        """Returns serial data"""

    ############
    # Set Settings Functions
    ############
    def set_devAddr(self, devAddr):
        """Set Device Address"""
        command = "set_config=dev_addr:%s" % devAddr
        self.uart_tx(command)

    def set_devEUI(self, devEui):
        """Set Device EUI"""
        command = "set_config=dev_eui:%s" % devEui
        self.uart_tx(command)

    def set_appEUI(self, appEui):
        """Set Application EUI"""
        command = "set_config=app_eui:%s" % appEui
        self.uart_tx(command)

    def set_appKey(self, appKey):
        """Set Application Key"""
        command = "set_config=app_key:%s" % appKey
        self.uart_tx(command)

    def set_networkKey(self, nwsk):
        """Set Network Key"""
        command = "set_config=nwks_key:%s" % nwsk
        self.uart_tx(command)

    def set_appSessionKey(self, apsk):
        """Set Application Session Key"""
        command = "set_config=apps_key:%s" % apsk
        self.uart_tx(command)

    def set_loraPower(self, pwr):
        """Set Lora Power Level"""
        command = "set_config=pwr_level:%s" % pwr
        self.uart_tx(command)

    def set_adrMode(self, adr):
        """Set Adaptive Data Rate"""
        command = "set_config=adr:%s" % adr
        self.uart_tx(command)

    def set_spreadingFactor(self, sf):
        """Set Spreading Factor"""
        command = "dr=%s" % self.SpreadFactors[sf]
        self.uart_tx(command)

    def set_region(self, sf):
        """Set LoRaWAN Region"""
        command = "band=%s" % sf
        self.uart_tx(command)

    ############
    # Get Settings Functions
    ############

    def get_devAddr(self):
        """Get Device Address"""
        command = "get_config=dev_addr"

        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_devEUI(self):
        """Get Device EUI"""
        command = "get_config=dev_eui"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_appEUI(self):
        """Get Application EUI"""
        command = "get_config=app_eui"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_appKey(self):
        """Get Application Key"""
        command = "get_config=app_key"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_networkKey(self):
        """Get Network Key"""
        command = "get_config=nwks_key"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_appSessionKey(self):
        """Get Application Session Key"""
        command = "get_config=apps_key"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_loraPower(self):
        """Get Lora Power Level"""
        command = "get_config=pwr_level"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_adrMode(self):
        """Get Adaptive Data Rate"""
        command = "get_config=adr"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    def get_spreadingFactor(self):
        """Get Spreading Factor"""
        command = "get_config=dr"
        return str(self.uart_tx(command)).split("OK")[1].split("\\")[0]

    ############
    # LoRa Functions
    ############
    def join(self, mode):
        """Join"""
        if (mode == self.abp):
            command = "join=abp"
            self.uart_tx(command)
        elif (mode == self.otaa):
            command = "join=otaa"
            self.uart_tx(command)
            # Extra response from otaa join
            line = self.serLib.readline()
            return True

    def send_raw_packet(self, packet, port):
        """Send raw bytes packet"""

    def send_string_packet(self, string, port=1, pktType=0):
        """Send a string packet"""
        command = "send=%s,%s,%s" % (
            pktType, port, binascii.hexlify(string.encode()).decode("utf-8"))
        self.uart_tx(command)
        # There will be an extra response
        line = self.serLib.readline()
        return line

    def send_int_packet(self, int, port):
        """Send integer packet"""

    def recieve_packet(self):
        """Check To See if there is any response"""

    def reset_radio(self):
        """Reset the RAK811 Radio Module"""
        command = "reset=0"
        self.uart_tx(command)
        self.uart_rx()
        self.uart_rx()
        self.uart_rx()

    def lora_mode(self, mode):
        """Change between LoRaWAN & LoRaP2P Modes"""

    def lora_band(self, band):
        """Set LoRaWAN Region"""
        command = "band=" + band
        self.uart_tx(command)

    ############
    # GPIO Functions
    ############
    def gpio_setmode(self, pin, mode):
        """Set Pin GPIO Mode"""

    def gpio_read(self, pin):
        """Read RAK811 GPIO"""

    def gpio_write(self, pin, state):
        """RAK811 GPIO Write Command"""

    def gpio_adc(self, pin):
        """Read RAK811 ADC"""
Example #25
0
# Untitled - By: shts - 土 12 28 2019

import sensor, image, time
from fpioa_manager import fm
from machine import UART

# setup GPIO
fm.register(35, fm.fpioa.UART2_TX, force=True)
fm.register(34, fm.fpioa.UART2_RX, force=True)

cnt = 0

while (True):
    uart_Port = UART(UART.UART2,
                     115200,
                     8,
                     0,
                     0,
                     timeout=1000,
                     read_buf_len=4096)
    data_packet = "{} M5StickV : Hello World\n".format(cnt)
    uart_Port.write(data_packet)
    read_data = uart_Port.readline()
    print(read_data)
    time.sleep(0.001)
    cnt += 1
Example #26
0
                if(i == 5):
                    check = False
        
        print('Matrix:')#, matrix)
        return True

urt = UART(2, 9600)
urt.init(9600, bits=8, parity=None, stop=1, tx=17, rx=16)

#init buffer
buffer_data = CircularBuffer()


while True:
  if (urt.any()):
    dados = urt.readline()
    print('Dado:', dados)
    #_thread.start_new_thread(get_data_from_rfid, (True, dados))
    #_thread.start_new_thread(store_data, (True, 0))
    t1 = threading.Thread(target=get_data_from_rfid, args=(True, dados))
    t1.daemon = True  # set thread to daemon ('ok' won't be printed in this case)
    t1.start()
    
    t2 = threading.Thread(target=store_data, args=(True, 0))
    t2.daemon = True  # set thread to daemon ('ok' won't be printed in this case)
    t2.start()
    #buffer_data.print_queue()
    #print('Size:', buffer_data.size())
    #if(buffer_data.size() == 6):
    #    store_data()   
Example #27
0
#
# Copyright (c) 2006-2019, RT-Thread Development Team
#
# SPDX-License-Identifier: MIT License
#
# Change Logs:
# Date           Author       Notes
# 2019-06-13     SummerGift   first version
#

from machine import UART

uart = UART(1, 9600)  # init with given baudrate
uart.init(9600, bits=8, parity=None, stop=1)  # init with given parameters
uart.read(10)  # read 10 characters, returns a bytes object
uart.read()  # read all available characters
uart.readline()  # read a line
uart.readinto(buf)  # read and store into the given buffer
uart.write('abc')  # write the 3 characters
Example #28
0
class Modem(object):
    def __init__(self,
                 uart=None,
                 MODEM_PWKEY_PIN=None,
                 MODEM_RST_PIN=None,
                 MODEM_POWER_ON_PIN=None,
                 MODEM_TX_PIN=None,
                 MODEM_RX_PIN=None):

        # Pins
        self.MODEM_PWKEY_PIN = MODEM_PWKEY_PIN
        self.MODEM_RST_PIN = MODEM_RST_PIN
        self.MODEM_POWER_ON_PIN = MODEM_POWER_ON_PIN
        self.MODEM_TX_PIN = MODEM_TX_PIN
        self.MODEM_RX_PIN = MODEM_RX_PIN

        # Uart
        self.uart = uart

        self.initialized = False
        self.modem_info = None

    #----------------------
    #  Modem initializer
    #----------------------

    def initialize(self):

        logger.debug('Initializing modem...')

        if not self.uart:
            from machine import UART, Pin

            # Pin initialization
            MODEM_PWKEY_PIN_OBJ = Pin(
                self.MODEM_PWKEY_PIN,
                Pin.OUT) if self.MODEM_PWKEY_PIN else None
            MODEM_RST_PIN_OBJ = Pin(self.MODEM_RST_PIN,
                                    Pin.OUT) if self.MODEM_RST_PIN else None
            MODEM_POWER_ON_PIN_OBJ = Pin(
                self.MODEM_POWER_ON_PIN,
                Pin.OUT) if self.MODEM_POWER_ON_PIN else None
            #MODEM_TX_PIN_OBJ = Pin(self.MODEM_TX_PIN, Pin.OUT) # Not needed as we use MODEM_TX_PIN
            #MODEM_RX_PIN_OBJ = Pin(self.MODEM_RX_PIN, Pin.IN)  # Not needed as we use MODEM_RX_PIN

            # Status setup
            if MODEM_PWKEY_PIN_OBJ:
                MODEM_PWKEY_PIN_OBJ.value(0)
            if MODEM_RST_PIN_OBJ:
                MODEM_RST_PIN_OBJ.value(1)
            if MODEM_POWER_ON_PIN_OBJ:
                MODEM_POWER_ON_PIN_OBJ.value(1)

            # Setup UART
            self.uart = UART(1,
                             9600,
                             timeout=1000,
                             rx=self.MODEM_TX_PIN,
                             tx=self.MODEM_RX_PIN)
            logger.info('UART initialized')

        # Test AT commands
        retries = 0
        while True:
            try:
                self.modem_info = self.execute_at_command('modeminfo')
            except:
                retries += 1
                if retries < 3:
                    logger.info(
                        'Error in getting modem info, retrying.. (#{})'.format(
                            retries))
                    time.sleep(3)
                else:
                    raise
            else:
                break

        logger.info('Ok, modem "{}" is ready and accepting commands'.format(
            self.modem_info))

        # Set initialized flag and support vars
        self.initialized = True

        # Check if SSL is supported
        #self.ssl_available = self.execute_at_command('checkssl') == '+CIPSSL: (0-1)'

    #----------------------
    # Execute AT commands
    #----------------------
    def execute_at_command(self,
                           command,
                           data=None,
                           clean_output=True,
                           binary_output=False,
                           delay=False):

        # Commands dictionary. Not the best approach ever, but works nicely.
        commands = {
            'modeminfo': {
                'string': 'ATI',
                'timeout': 3,
                'end': 'OK'
            },
            'fwrevision': {
                'string': 'AT+CGMR',
                'timeout': 3,
                'end': 'OK'
            },
            'battery': {
                'string': 'AT+CBC',
                'timeout': 3,
                'end': 'OK'
            },
            'scan': {
                'string': 'AT+COPS=?',
                'timeout': 60,
                'end': 'OK'
            },
            'network': {
                'string': 'AT+COPS?',
                'timeout': 3,
                'end': 'OK'
            },
            'signal': {
                'string': 'AT+CSQ',
                'timeout': 3,
                'end': 'OK'
            },
            'checkreg': {
                'string': 'AT+CREG?',
                'timeout': 3,
                'end': None
            },
            'checkreg_2g': {
                'string': 'AT+CGREG?',
                'timeout': 3,
                'end': None
            },
            'setapn': {
                'string': 'AT+SAPBR=3,1,"APN","{}"'.format(data),
                'timeout': 3,
                'end': 'OK'
            },
            'setuser': {
                'string': 'AT+SAPBR=3,1,"USER","{}"'.format(data),
                'timeout': 3,
                'end': 'OK'
            },
            'setpwd': {
                'string': 'AT+SAPBR=3,1,"PWD","{}"'.format(data),
                'timeout': 3,
                'end': 'OK'
            },
            'initgprs': {
                'string': 'AT+SAPBR=3,1,"Contype","GPRS"',
                'timeout': 3,
                'end': 'OK'
            },  # Appeared on hologram net here or below
            'opengprs': {
                'string': 'AT+SAPBR=1,1',
                'timeout': 3,
                'end': 'OK'
            },
            'getbear': {
                'string': 'AT+SAPBR=2,1',
                'timeout': 3,
                'end': 'OK'
            },
            'inithttp': {
                'string': 'AT+HTTPINIT',
                'timeout': 3,
                'end': 'OK'
            },
            'sethttp': {
                'string': 'AT+HTTPPARA="CID",1',
                'timeout': 3,
                'end': 'OK'
            },
            'checkssl': {
                'string': 'AT+CIPSSL=?',
                'timeout': 3,
                'end': 'OK'
            },
            'enablessl': {
                'string': 'AT+HTTPSSL=1',
                'timeout': 3,
                'end': 'OK'
            },
            'disablessl': {
                'string': 'AT+HTTPSSL=0',
                'timeout': 3,
                'end': 'OK'
            },
            'initurl': {
                'string': 'AT+HTTPPARA="URL","{}"'.format(data),
                'timeout': 3,
                'end': 'OK'
            },
            'doget': {
                'string': 'AT+HTTPACTION=0',
                'timeout': 100,
                'end': '+HTTPACTION'
            },
            'setcontent': {
                'string': 'AT+HTTPPARA="CONTENT","{}"'.format(data),
                'timeout': 3,
                'end': 'OK'
            },
            'postlen': {
                'string': 'AT+HTTPDATA={},5000'.format(data),
                'timeout': 3,
                'end': 'DOWNLOAD'
            },  # "data" is data_lenght in this context, while 5000 is the timeout
            'dumpdata': {
                'string': data,
                'timeout': 1,
                'end': 'OK'
            },
            'dopost': {
                'string': 'AT+HTTPACTION=1',
                'timeout': 10,
                'end': '+HTTPACTION'
            },
            'getdata': {
                'string': 'AT+HTTPREAD',
                'timeout': 3,
                'end': 'OK'
            },
            'closehttp': {
                'string': 'AT+HTTPTERM',
                'timeout': 3,
                'end': 'OK'
            },
            'closebear': {
                'string': 'AT+SAPBR=0,1',
                'timeout': 3,
                'end': 'OK'
            }
        }

        # References:
        # https://github.com/olablt/micropython-sim800/blob/4d181f0c5d678143801d191fdd8a60996211ef03/app_sim.py
        # https://arduino.stackexchange.com/questions/23878/what-is-the-proper-way-to-send-data-through-http-using-sim908
        # https://stackoverflow.com/questions/35781962/post-api-rest-with-at-commands-sim800
        # https://arduino.stackexchange.com/questions/34901/http-post-request-in-json-format-using-sim900-module (full post example)

        # Sanity checks
        if command not in commands:
            raise Exception('Unknown command "{}"'.format(command))

        # Support vars
        command_string = commands[command]['string']
        excpected_end = commands[command]['end']
        timeout = commands[command]['timeout']
        processed_lines = 0

        # Execute the AT command
        command_string_for_at = "{}\r\n".format(command_string)
        logger.debug('Writing AT command "{}"'.format(
            command_string_for_at.encode('utf-8')))
        #while self.uart.any():
        #    self.uart.read(self.uart.any())
        self.uart.write(command_string_for_at)

        # Support vars
        pre_end = True
        output = b'' if binary_output else ''
        empty_reads = 0

        while True:

            line = self.uart.readline()
            if not line:
                time.sleep(1)
                empty_reads += 1
                if empty_reads > timeout:
                    raise Exception(
                        'Timeout for command "{}" (timeout={})'.format(
                            command, timeout))
                    #logger.warning('Timeout for command "{}" (timeout={})'.format(command, timeout))
                    #break
            else:
                logger.debug('Read "{}"'.format(
                    line if len(line) < 1000 else '--- LONG LINE ---c'))

                # Convert line to string
                line_str = ''
                try:
                    line_str = line.decode('utf-8')
                except UnicodeError as exc:
                    if not binary_output:
                        raise exc

                # Do we have an error?
                if line_str == 'ERROR\r\n':
                    raise GenericATError('Got generic AT error')

                # If we had a pre-end, do we have the expected end?
                if line_str == '{}\r\n'.format(excpected_end):
                    logger.debug('Detected exact end')
                    break
                if pre_end and line_str.startswith('{}'.format(excpected_end)):
                    logger.debug(
                        'Detected startwith end (and adding this line to the output too)'
                    )
                    output += line_str
                    break

                # Do we have a pre-end?
                if line_str == '\r\n':
                    pre_end = True
                    logger.debug('Detected pre-end')
                else:
                    pre_end = False

                # Keep track of processed lines and stop if exceeded
                processed_lines += 1

                # Save this line unless in particular conditions
                if command == 'getdata' and line_str.startswith('+HTTPREAD:'):
                    pass
                else:
                    output += line if binary_output else line_str

        # Remove the command string from the output
        output = output.replace(bytes(command_string, 'utf-8') + b'\r\r\n', b'') if binary_output else \
            output.replace(command_string+'\r\r\n', '')

        # ..and remove the last \r\n added by the AT protocol
        if output.endswith(b'\r\n' if binary_output else '\r\n'):
            output = output[:-2]

        # Also, clean output if needed
        if clean_output:
            output = output.replace('\r', '')
            output = output.replace('\n\n', '')
            if output.startswith('\n'):
                output = output[1:]
            if output.endswith('\n'):
                output = output[:-1]

        # Return
        if delay:
            logger.debug("delay after at command")
            time.sleep(5)
        return output

    #----------------------
    #  Function commands
    #----------------------

    def get_info(self):
        output = self.execute_at_command('modeminfo')
        return output

    def battery_status(self):
        output = self.execute_at_command('battery')
        return output

    def scan_networks(self):
        networks = []
        output = self.execute_at_command('scan')
        pieces = output.split('(', 1)[1].split(')')
        for piece in pieces:
            piece = piece.replace(',(', '')
            subpieces = piece.split(',')
            if len(subpieces) != 4:
                continue
            networks.append({
                'name': json.loads(subpieces[1]),
                'shortname': json.loads(subpieces[2]),
                'id': json.loads(subpieces[3])
            })
        return networks

    def get_current_network(self):
        output = self.execute_at_command('network')
        network = output.split(',')[-1]
        if network.startswith('"'):
            network = network[1:]
        if network.endswith('"'):
            network = network[:-1]
        # If after filtering we did not filter anything: there was no network
        if network.startswith('+COPS'):
            return None
        return network

    def get_signal_strength(self):
        # See more at https://m2msupport.net/m2msupport/atcsq-signal-quality/
        output = self.execute_at_command('signal')
        signal = int(output.split(':')[1].split(',')[0])
        signal_ratio = float(signal) / float(
            30)  # 30 is the maximum value (2 is the minimum)
        return signal_ratio

    def get_ip_addr(self):
        output = self.execute_at_command('getbear')
        output = output.split(
            '+'
        )[-1]  # Remove potential leftovers in the buffer before the "+SAPBR:" response
        pieces = output.split(',')
        if len(pieces) != 3:
            logger.info(
                'Cannot parse "{}" to get an IP address'.format(output))
            return None
        ip_addr = pieces[2].replace('"', '')
        if len(ip_addr.split('.')) != 4:
            raise Exception(
                'Cannot parse "{}" to get an IP address'.format(output))
        if ip_addr == '0.0.0.0':
            return None
        return ip_addr

    def connect(self, apn, user='', pwd=''):
        if not self.initialized:
            raise Exception('Modem is not initialized, cannot connect')

        # Are we already connected?
        if self.get_ip_addr():
            logger.debug('Modem is already connected, not reconnecting.')
            return

        # Closing bearer if left opened from a previous connect gone wrong:
        logger.debug(
            'Trying to close the bearer in case it was left open somehow..')
        try:
            self.execute_at_command('closebear')
        except Exception:
            pass

        # First, init gprs
        logger.debug('Connect step #1 (initgprs)')
        self.execute_at_command('initgprs')

        # Second, set the APN
        logger.debug('Connect step #2 (setapn)')
        self.execute_at_command('setapn', apn, delay=True)
        self.execute_at_command('setuser', user, delay=True)
        self.execute_at_command('setpwd', pwd, delay=True)

        # Then, open the GPRS connection.
        logger.debug('Connect step #3 (opengprs)')
        self.execute_at_command('opengprs', delay=True)

        # Ok, now wait until we get a valid IP address
        retries = 0
        max_retries = 5
        while True:
            retries += 1
            ip_addr = self.get_ip_addr()
            if not ip_addr:
                retries += 1
                if retries > max_retries:
                    raise Exception(
                        'Cannot connect modem as could not get a valid IP address'
                    )
                logger.debug('No valid IP address yet, retrying... (#')
                time.sleep(1)
            else:
                break

    def disconnect(self):

        # Close bearer
        try:
            self.execute_at_command('closebear')
        except GenericATError:
            pass

        # Check that we are actually disconnected
        ip_addr = self.get_ip_addr()
        if ip_addr:
            raise Exception(
                'Error, we should be disconnected but we still have an IP address ({})'
                .format(ip_addr))

    def http_request(self,
                     url,
                     mode='GET',
                     data=None,
                     content_type='application/json',
                     binary_output=False):

        # Protocol check.
        assert url.startswith(
            'http'
        ), 'Unable to handle communication protocol for URL "{}"'.format(url)

        # Are we  connected?
        if not self.get_ip_addr():
            raise Exception('Error, modem is not connected')

        # Close the http context if left open somehow
        logger.debug('Close the http context if left open somehow...')
        try:
            self.execute_at_command('closehttp')
        except Exception:
            pass

        # First, init and set http
        logger.debug('Http request step #1.1 (inithttp)')
        self.execute_at_command('inithttp')
        logger.debug('Http request step #1.2 (sethttp)')
        self.execute_at_command('sethttp')

        # Do we have to enable ssl as well?
        #        if self.ssl_available:
        #            if url.startswith('https://'):
        #                logger.debug('Http request step #1.3 (enablessl)')
        #                self.execute_at_command('enablessl')
        #            elif url.startswith('http://'):
        #                logger.debug('Http request step #1.3 (disablessl)')
        #                self.execute_at_command('disablessl')
        #        else:
        #            if url.startswith('https://'):
        #                raise NotImplementedError("SSL is only supported by firmware revisions >= R14.00")

        # Second, init and execute the request
        logger.debug('Http request step #2.1 (initurl)')
        self.execute_at_command('initurl', data=url)

        if mode == 'GET':

            logger.debug('Http request step #2.2 (doget)')
            output = self.execute_at_command('doget')
            response_status_code = output.split(',')[1]
            logger.debug(
                'Response status code: "{}"'.format(response_status_code))

        elif mode == 'POST':

            logger.debug('Http request step #2.2 (setcontent)')
            self.execute_at_command('setcontent', content_type)

            logger.debug('Http request step #2.3 (postlen)')
            self.execute_at_command('postlen', len(data))

            logger.debug('Http request step #2.4 (dumpdata)')
            self.execute_at_command('dumpdata', data)

            logger.debug('Http request step #2.5 (dopost)')
            output = self.execute_at_command('dopost')
            response_status_code = output.split(',')[1]
            logger.debug(
                'Response status code: "{}"'.format(response_status_code))

        else:
            raise Exception('Unknown mode "{}'.format(mode))

        # Third, get data
        logger.debug('Http request step #4 (getdata)')
        response_content = self.execute_at_command('getdata',
                                                   clean_output=False,
                                                   binary_output=binary_output)

        # Then, close the http context
        logger.debug('Http request step #4 (closehttp)')
        self.execute_at_command('closehttp')

        return Response(status_code=response_status_code,
                        content=response_content)
Example #29
0
#objeto SD
sd = sdcard.SDCard(spi, Pin(2,Pin.OUT))
oled.text('SD...OK', 0, 20)
oled.show()

# contador auxiliar para controlar numero de ciclos
cont = 1

while True:
    #lectura y escritura de SD
    # Ensure right baudrate
    #se monta el sistema de archivos en la sd
    os.mount(sd, '/fc')
    print('Filesystem check')
    print(os.listdir('/fc'))
    aux = gps.readline()
    gps_data = str(aux)#, "utf-8")
    filename = '/fc/gps_data.txt'
    
    oled.text('Escribiendo SD', 0, 30)
    oled.show()
    
    with open(filename,'w') as f:
        n = f.write(gps_data)
        print(n, 'bytes written')
    with open(filename,'r') as f:
        result1 = f.read()
        print(len(result1), 'bytes read')
    
    aux = mpu.read_sensors_scaled()
    aux = aux[0] + aux[1] + aux[2]
Example #30
0
print(uart0.read(2) == b'23')
print(uart0.read() == None)

uart0.write(b'123')
buf = bytearray(3)
print(uart1.readinto(buf, 1) == 1) 
print(buf)
print(uart1.readinto(buf) == 2)
print(buf)

# try initializing without the id
uart0 = UART(baudrate=1000000, pins=uart_pins[0][0])
uart0.write(b'1234567890')
time.sleep_ms(2) # because of the fifo interrupt levels
print(uart1.any() == 10)
print(uart1.readline() == b'1234567890')
print(uart1.any() == 0)

uart0.write(b'1234567890')
print(uart1.readall() == b'1234567890')

# tx only mode
uart0 = UART(0, 1000000, pins=('GP12', None))
print(uart0.write(b'123456') == 6)
print(uart1.read() == b'123456')
print(uart1.write(b'123') == 3)
print(uart0.read() == None)

# rx only mode
uart0 = UART(0, 1000000, pins=(None, 'GP13'))
print(uart0.write(b'123456') == 6)
Example #31
0
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)

# Updates from OpenMV send
curr_time = ''

# uart init
uart = UART(2, 115200)
uart.init(115200, bits=8, parity=None, stop=1)

while True:
    conn, addr = s.accept()
    time.sleep(0.1)
    # Update based on uart read
    read = uart.readline()
    if read == None:
        pass
    # At least do a type check for URL error
    else:
        curr_time = read.decode("ascii")
        curr_time = curr_time.rstrip()
    print('Got a connection from %s' % str(addr))
    request = conn.recv(1024)
    request = str(request)
    print('Content = %s' % request)
    music_on = request.find('/?music=on')
    if music_on == 6:
        print('Music Redirecting!')
        # Send the redirect request to youtube
        conn.send('HTTP/1.1 302 Found\n')