ImportError: no module named 'globals' and no module named 'util'



  • link text
    code:

    import globals as g
    from machine import UART
    import sys
    import util
    from util import log
    from utime import sleep_ms, ticks_ms, ticks_diff
    
    uart = None
    
    #####################################################################
    #                     Send AT Command To Modem
    #####################################################################
    def at(cmd):
        try:
            if uart.any() > 0:
                # get unsolicited modem response 
                a = get_modem_response()
    
                if len(a) > 0:
                    log("unsolicited modem response: {}".format(a))
                
                # process unsolicited results here
    
            log("  modem command: {}".format(cmd))
    
            # send command to modem
            n = uart.write(cmd + '\r')
            if n != len(cmd) + 1:
                log("error sending command to modem: n = {}".format(n))
                return []
    
            a = get_modem_response()
    
        except Exception as ex:
            sys.print_exception(ex)
            a = []
    
        return a    # return modem response lines in array
    
    
    #####################################################################
    #             Attach Cellular Modem To Packet Domain Service
    #####################################################################
    def attach():
        try:
            log("attach modem to packet domain service")
            a = at('AT+CGATT=1')
            if a[0] != 'OK':
                log("error attaching modem")
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                       Check Registration
    #####################################################################
    def check_registration():
        # return 0-5, 99-unknown
        # response: ['+CEREG: 2,4', 'OK']
        # response: ['+CEREG: 2,1,"2C29","0B54400F",7', 'OK']
        # 2,0 - not registered, not searching
        # 2,1 - registered, home network
        # 2,2 - not registered, searching
        # 2,3 - registration denied
        # 2,4 - unknown (out of coverage)
        # 2,5 - registered, roaming
    
        try:
            while True:
                log("check registration")
    
                a = at('AT+CEREG?')
                if a[1] != 'OK':
                    break
    
                s = a[0]
                if (s[0:7] != "+CEREG:"):
                    break
                
                a = s.split(",")
    
                if (a[0] != "+CEREG: 2"):
                    break
                
                reg = int(a[1])
                if reg == 1:
                    log("registered - home network")
                elif reg == 5:
                    log("registered - roaming")
                else:
                    log("not registered")
    
                return reg
    
        except Exception as ex:
            log("check registration exception")
            sys.print_exception(ex)
    
        # unknown registration
        log("error checking registration")
        return 99
    
    
    #####################################################################
    #             Detach Cellular Modem From Packet Domain Service
    #####################################################################
    def detach():
        try:
            log("detach modem from packet domain service")
            a = at('AT+CGATT=0')
            if a[0] != 'OK':
                log("error detaching modem")
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                       Disable LTE Modem
    #####################################################################
    def disable_modem():
        try:
            log("disable modem")
            at("AT+CFUN=4")     # disable both transmit and receive RF circuits
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                       Enable Modem
    #####################################################################
    def enable_modem():
        try:
            log("enabling modem")
            a = at("AT+CFUN=1")     # full functionality
            if a[0] != 'OK':
                log("error enabling modem")
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                Get CFUN - Modem Level of Functionality
    #####################################################################
    def get_cfun():
        # 0 - minimum functionality
        # 1 - full functionality
        # 4 - radios disabled but access to SIM allowed
        # -1 - unknown
        # note: if modem does +SHUTDOWN/+SYSSTART, CFUN will be reset to 0
        try:
            while True:
                a = at('AT+CFUN?')
                # response: ['+CFUN: 1', 'OK']
    
                if a[1] != 'OK':
                    break
    
                s = a[0]
                if (s[0:6] != "+CFUN:"):
                    break
                
                cfun = int(s[7])
                return cfun
    
        except Exception as ex:
            sys.print_exception(ex)
    
        return -1
    
    
    #####################################################################
    #                     Get Modem Response
    #####################################################################
    def get_modem_response():
        try:
            t0 = ticks_ms()
            
            while True:
                if uart.any() > 0:
                    # insure entire response has been received
                    sleep_ms(50)
                    break
    
                t1 = ticks_ms()
                tx = ticks_diff(t1, t0)
    
                if tx > 10000:
                    log("timeout error - no modem response after 10 secs")
                    return []
    
                sleep_ms(100)
    
            b = uart.read()
            s = str(b, 'utf-8')
            a = s.split('\r\n')
            a = list(filter(None, a))
    
            log("  modem response: {}".format(a))
    
        except Exception as ex:
            sys.print_exception(ex)
            a = []
    
        return a    # return modem response lines in array
    
    
    #####################################################################
    #                           Get SMS Mode
    #####################################################################
    def get_sms_mode():
        # return 0-PDU mode or unknown, 1-text mode
    
        try:
            log("get SMS mode")
            a = at('AT+CMGF?')
            # response: ['+CMGF: 1', 'OK']
            if (len(a) < 2) or (a[1] != 'OK'):
                return 0    # mode unknown
    
            s = a[0]
    
            if (s[0:6] != '+CMGF:'):
                return 0    # state unknown
            
            mode = int(s[7])
            return mode
    
        except Exception as ex:
            sys.print_exception(ex)
    
        return 0    # mode unknown
    
    
    #####################################################################
    #                            HTTP Post          
    #####################################################################
    def http_post(uri, header, m):
        # POST <uri> HTTP/1.1
        # <header>
        # Content-Length: <len(m)>
        # Content-Type: application/octet-stream
        # <blank line>
        try:
            log("HTTP post")
    
            while True:
                # note: init_modem() is used to do "AT+SQNHTTPCFG=..."
                n = len(m)
    
                # log("writing message: {0}".format(m))
                log("post message length: {0}".format(n))
    
                # AT+SQNHTTPSND=<prof_id>,<command>,<resource>,<data_len>[,<post_param>[,<extra_header_line>]]
                # prof_id=1, command=0 (POST), post_parm="2" (application/octet-stream), header="Host: <host_name>" 
    
                a = at('AT+SQNHTTPSND=1,0,"{0}",{1},"2","{2}"'.format(uri, n, header))
                if a[0] != '> ':
                    break
    
                uart.write(m)
                a = get_modem_response()
                if a[0] != 'OK':
                    break
    
                # modem responds with "+SQNHTTPRING: <prof_id,<http_status_code>,<content_type>,<data_size>"
                a = get_modem_response()
                s = a[0]
                if s[0:13] != "+SQNHTTPRING:":
                    break
    
                a = s.split(",")
                n = int(a[3])
                log("response message length: {0}".format(n))
    
                # get response
                cmd = 'AT+SQNHTTPRCV=1,0\r'
                log("  modem command: {0}".format(cmd))
                uart.write(cmd)
    
                wait_rx(5, 10000)   # wait for b'\r\n<<<'
                b = uart.read(5)
                # log(" modem response: {0}".format(b))
                if b[2:5] != b'<<<':
                    break
    
                wait_rx(n, 10000)   # wait for response
                b = uart.read(n)
                log(" modem response: {0}".format(b))
    
                a = get_modem_response()
                if a[0] != 'OK':
                    break
    
                log(b)
                return b
    
        except Exception as ex:
            sys.print_exception(ex)
    
        # some type of error occurred
        return b''
    
    
    #####################################################################
    #                     Get SIM Card ICCID Number
    #####################################################################
    def iccid():
        # modem must be registered to network to get ICCID
        try:
            log("get SIM card ICCID")
            a = at("AT+SQNCCID?")
            
            # example response: ['+SQNCCID: "89014103271203065543",""', 'OK']
            if a[1] != 'OK':
                return ''
    
            s = a[0]
            if s[0:9] != '+SQNCCID:':
                return ''
    
            a = s.split(",")
            n = len(a[0])
            r = a[0][11:n-1]
    
        except Exception as ex:
            sys.print_exception(ex)
            r = ''
    
        log("ICCID = {0}".format(r))
        return r    # ICCID as string
    
    
    #####################################################################
    #                       Get Modem IMEI Number
    #####################################################################
    def imei():
        try:
            log("get modem IMEI number")
            a = at("AT+CGSN=1")
            
            # example response: ['+CGSN: "354347094028575"', 'OK']
            if a[1] != 'OK':
                return ''
    
            s = a[0]
            if s[0:6] != '+CGSN:':
                return ''
    
            n = len(s)
            r = s[8:n-1]
    
        except Exception as ex:
            sys.print_exception(ex)
            r = ''
    
        log("IMEI = {0}".format(r))
        return r    # IMEI as string
    
    
    #####################################################################
    #                       Initialize Modem
    #####################################################################
    def init_modem():
        try:
            log("initializing modem")
    
            if uart == None:
                init_uart()
    
            enable_modem()
    
            # set profile #1 parameters for HTTP connection
            # prof_id=1 (profile), ip, port, auth_type=0 (None), username="", password="", 
            # ssl_enabled=0, timeout, cid=1 (PDN Context Identifier)
            server = g.oIni.host_ip     # note: host_name could also be used (auto DNS lookup)
            port = g.oIni.host_port
            timeout = 10    # secs to wait for response from server
            cmd = 'AT+SQNHTTPCFG=1,"{0}",{1},0,"","",0,{2},1'.format(server, port, timeout)
            a = at(cmd)
            if a[0] != 'OK':
                log("error initializing modem")
    
            set_sms_mode()
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #               Initialize Uart Connected To LTE Modem
    #####################################################################
    def init_uart():
        global uart
        # pins=(TXD, RXD, RTS, CTS)
        # FiPy: pins=('P20', 'P18', 'P19', 'P17')
        # GPy:  pins=('P5', 'P98', 'P7', 'P99')
        log("initializing UART")
        # rx_buffer_size: must be > 127, 200000 works, 250000 crashes, http_post seems to work with any size
        uart = UART(1, baudrate=921600, bits=8, parity=None, stop=1, timeout_chars=2, pins=('P5', 'P98', 'P7', 'P99'), rx_buffer_size=512)
    
    
    #####################################################################
    #           Is Cellular Modem Attached To Packet Domain Service
    #####################################################################
    def isattached():
        # returns: True/False
        try:
            a = at('AT+CGATT?')
            if a[0][0:9] == '+CGATT: 1':
                return True
    
        except Exception as ex:
            sys.print_exception(ex)
    
        return False
    
    
    #####################################################################
    #                           Reset Modem
    #####################################################################
    def reset_modem():
        try:
            log("reseting modem...")
            a = at('AT^RESET')
            # generates +SHUTDOWN ... +SYSSTART responses
            if a[0] != 'OK':
                log("error resetting modem")
    
            if a[1] != '+SHUTDOWN':
                log("error resetting modem")
    
            a = get_modem_response()
            if a[0] != '+SYSSTART':
                log("error resetting modem")
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                  Check Modem For Restart/Crash
    #####################################################################
    def restarted():
        # return True if modem has crashed / restarted
        try:
            # if CFUN != 1, modem has crashed / restarted
            r = get_cfun()
            if r != 1:
                return True
    
            # if SMS text mode is reset to zero, modem has crashed / restarted
            mode = get_sms_mode()
            if mode != 1:
                return True
    
            return False
    
        except Exception as ex:
            sys.print_exception(ex)
    
        return True
    
    
    #####################################################################
    #                       Set SMS Mode To Text
    #####################################################################
    def set_sms_mode():
        try:
            log("set SMS mode to text")
            a = at('AT+CMGF=1')     # set SMS mode to text
            if a[0] != 'OK':
                log("error setting SMS mode to text")
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                       Get Signal Strength
    #####################################################################
    def signal_strength():
        # 0-31, 99-unknown
        try:
            while True:
                log("check signal strength")
                a = at('AT+CSQ')
                # example response: ['+CSQ: 18,99', 'OK'] where 18 is signal strength
                if a[1] != 'OK':
                    break
    
                s = a[0]
                if (s[0:5] != "+CSQ:"):
                    break
                
                n = len(s)
                s = s[6:n-1]
                a = s.split(",")
                cell_signal = int(a[0])
    
                g.oStatus.cell_signal = cell_signal
                log("signal strength = {0}".format(cell_signal))
                return cell_signal
    
        except Exception as ex:
            sys.print_exception(ex)
    
        # unknown signal strength
        g.oStatus.cell_signal = 99
        log("signal strength unknown")
        return 99
    
    
    #####################################################################
    #             Delete Read, Sent, and Unsent SMS Messages
    #####################################################################
    def sms_delete():
        try:
            log("delete all READ, SENT, and UNSENT SMS messages")
            a = at('AT+CMGD=1,3')
            if a[0] != 'OK':
                log("error trying to delete read, sent, and unsent SMS messages")
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                     Delete All SMS Messages
    #####################################################################
    def sms_delete_all():
        # doesn't work until some time after lte.attach() is called
        try:
            log("delete all SMS messages")
            a = at('AT+CMGD=1,4')
            if a[0] != 'OK':
                log("error trying to delete all SMS messages")
            
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                     Process SMS Messages
    #####################################################################
    def sms_process(r):
        # example response:
        # ['+CMGL: 1,"REC READ","+19999999999",,"19/01/07,09:16:53-20"', 'Test3', '+CMGL: 2,"REC READ","+19999999999",,"19/01/07,11:12:30-20"', 'Test4', 'OK']
        
        try:
            for m in r:
                if (m[0:5] == "+CMGL"):
                    continue
                
                # process SMS messages
                
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                      Read Unread SMS Messages
    #####################################################################
    def sms_read():
        # response example: ['+CMGL: 1,"REC UNREAD","+1999999999",,"19/01/07,09:16:53-20"', 'Test3', 'OK']
        a = at('AT+CMGL="REC UNREAD"')
        return a
        
    
    #####################################################################
    #                       Read All SMS Messages
    #####################################################################
    def sms_read_all():
        # response example:
        # ['+CMGL: 1,"REC READ","+19999999999",,"19/01/07,09:16:53-20"', 'Test3', '+CMGL: 2,"REC READ","+19999999999",,"19/01/07,11:12:30-20"', 'Test4', 'OK']
        a = at('AT+CMGL="ALL"')
        return a
    
    
    #####################################################################
    #                       Wait For N Received Chars          
    #####################################################################
    def wait_rx(n, timeout=10000):
        # timeout in msecs
        t0 = ticks_ms()
        while True:
            if uart.any() >= n:
                break
    
            t1 = ticks_ms()
            tx = ticks_diff(t1, t0)
            if tx > timeout:
                return False
        
        return True
    
    
    #####################################################################
    #                    Wait For Specific Modem Response          
    #####################################################################
    def wait_response(response, msecs=10000):
        log('wait up to {0} msecs for modem response: {1}'.format(msecs, response))
        t0 = ticks_ms()
        while True:
            try:
                a = at('AT')
    
                for x in a:
                    if x == response:
                        log('****modem response found****: ' + response)
                        return True
    
                t1 = ticks_ms()
                tx = ticks_diff(t1, t0)
                log('{0} msecs'.format(tx))
    
                if tx > msecs:
                    log('modem response not found: ' + response)
                    return False
    
                sleep_ms(500)
    
            except Exception as ex:
                sys.print_exception(ex)
                
    
    #####################################################################
    #                           Test #1
    #####################################################################
    def test1():
        try:
            log("test basic modem functions")
    
            if uart == None:
                init_uart()
            
            while True:
                # reset_modem()
    
                enable_modem()
                set_sms_mode()
    
                imei()
                iccid()
    
                while True:
                    r = check_registration()
                    if (r == 1) or (r == 5):
                        # modem registered
                        iccid()
                        attach()
                        return
    
                    if restarted():
                        print('MODEM crash/restart detected')
                        return
    
                    print(signal_strength())
    
                    sleep_ms(1000)
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                         Example HTTP Get          
    #####################################################################
    def test2():
        try:
            log("test HTTP get")
    
            at('AT+SQNHTTPCFG=1,"httpbin.org",80,0,"","",0,120,1')
            # some sites require "User-Agent" header
            #   ex: at('AT+SQNHTTPQRY=1,0,"/","User-Agent: Test1"')
            at('AT+SQNHTTPQRY=1,0,"/get"')
            get_modem_response()
            at('AT+SQNHTTPRCV=1,0')
    
        except Exception as ex:
            sys.print_exception(ex)
    
    
    #####################################################################
    #                         Example HTTP Post          
    #####################################################################
    def test3(size=10):
        try:
            log("test HTTP post")
    
            while True:
                a = at('AT+SQNHTTPCFG=1,"httpbin.org",80,0,"","",0,120,1')
                if a[0] != 'OK':
                    break
    
                m = "X"*size
                log("writing message: {0}".format(m))
                log("post message length: {0}".format(size))
                
                a = at('AT+SQNHTTPSND=1,0,"/post",{0}'.format(size))
                if a[0] != '> ':
                    break
    
                uart.write(m)
                a = get_modem_response()
                if a[0] != 'OK':
                    break
    
                # modem responds with "+SQNHTTPRING: <prof_id,<http_status_code>,<content_type>,<data_size>"
                a = get_modem_response()
                s = a[0]
                if s[0:13] != "+SQNHTTPRING:":
                    break
    
                a = s.split(",")
                n = int(a[3])
                log("response message length: {0}".format(n))
    
                # get response
                cmd = 'AT+SQNHTTPRCV=1,0\r'
                log("  modem command: {0}".format(cmd))
                uart.write(cmd)
    
                wait_rx(5, 10000)   # wait for b'\r\n<<<'
                b = uart.read(5)
                log(" modem response: {0}".format(b))
                if b[2:5] != b'<<<':
                    break
    
                wait_rx(n, 10000)   # wait for response
                b = uart.read(n)
                log(" modem response: {0}".format(b))
    
                a = get_modem_response()
                if a[0] != 'OK':
                    break
    
                log(b)
                return b
    
        except Exception as ex:
            sys.print_exception(ex)
    
        # some type of error occurred
        return b''
    test1()
    

    I'm trying the code on the link but it doesn't recognize the global and util libraries. What can I do about this situation? Is it a firmware related situation? firmware: Pycom MicroPython 1.20.2.r0
    Can you guys help me?
    Thanks for all reply!!!



  • You can run globals without doing an import. For example

    if not 'lte' in globals(): lte=LTE()
    

    works on my gpy.



  • Hi,
    I think the guy made his own file with credentials etc called 'globals', and 'utils' with different utility functions. They are not included in the firmware by default

    Gijs


Log in to reply
 

Pycom on Twitter