← index #6564Issue #16887
Related · medium · value 0.579
QUERY · ISSUE

GSM PPP is not Attaching to Micropython network.PPP

openby vijenderpandaopened 2020-10-22updated 2024-09-13
port-esp32

Kindly check ,
i followed to your last answer that we need to pass the authmode while connecting,
i have don that too , but still no luck

i am trying on ESP32 and SIM900A

class InitSimData():
def init(self):
self.gsm = machine.UART(1,tx=2, rx=4, timeout=1000, baudrate=9600)
time.sleep(interval)
self.check_sim()

    time.sleep(interval)
    self.register_sim()

    # time.sleep(interval)
    # self.getOPR()

    time.sleep(interval)
    self.attachGPRS()

    time.sleep(interval)
    self.rquestIPwithAPN()

    time.sleep(interval)
    self.getCGDCONT()

    # time.sleep(interval)
    # self.qosProfile()

    # time.sleep(interval)
    # self.qosProfilenext()


    time.sleep(interval)
    self.checkIP()

    time.sleep(interval)
    self.PDPcontext()


    time.sleep(interval)
    self.attachGSMtoPPP()


    

    
    
    

    
    

    


def check_sim(self):
    while True:
        self.gsm.write("AT\r\n")
        status = self.read_status()
        if status == "OK":
            print("Sim Initialized with status with status",status)
            return True
        else:
            pass
def register_sim(self):
    while True:
        self.gsm.write("AT+CREG?\r\n")
        status = self.read_status()
        if status == "+CREG: 0,1":
            print("Sim Registered with status with status",status)
            return True
        else:
            pass
def getOPR(self):
    while True:
        self.gsm.write("AT+COPS?\r\n")
        status = self.read_first()
        if status.startswith('+COPS'):
            print("Sim Operator Name is",status)
            return True
        else:
            pass

def attachGPRS(self):
    while True:
        self.gsm.write("AT+CGATT?\r\n")
        status = self.read_first()
        print("GPRS Status")
        if status == "+CGATT: 1":
            print("GPRS Attached with status with status", status)
            return True
        else:
            pass
def rquestIPwithAPN(self):
    self.gsm.write('AT+CGDCONT=1,"IP","portalnmms",\r\n')
    status = self.read_status()
    print("Checking status for CDGCONT response--",status)
    if status == 'OK':
        print("Sim Connected with APN and IP Address is ", status)
        return status
    else:
        self.rquestIPwithAPN()

def getCGDCONT(self):
    self.gsm.write('AT+CGDCONT=?\r\n')
    status = self.read_first()
    print("IP Details--",status)
    if status.startswith('+CGDCONT'):
        print("Sim Connected with IP---- ", status)
        return status
    else:
        time.sleep(1)
        self.getCGDCONT()

def getCGDCONTsec(self):
    self.gsm.write('AT+CGDCONT=?\r\n')
    status = self.read_status()
    print("IP Sec st Details--",status)
    if not status == '':
        print("Sim sec st Connected with IP---- ", status)
        return status
    else:
        time.sleep(1)
        self.getCGDCONT()

def qosProfile(self):
    """Define a QoS profile for PDP context 1, with
    Traffic Class 3 (background), maximum bit rate
    64 kb/s both for UL and for DL, no Delivery Order
    requirements, a maximum SDU size of 320
    octets, an SDU error ratio of 10-4
    , a residual bit
    error ratio of 10-5
    , delivery of erroneous SDUs
    allowed and Traffic Handling Priority 3."""

    self.gsm.write('AT+CGEQREQ=1,3,64,64,,,0,320,"1E4","1E5",1,,3\r\n')
    status = self.read_first()
    print("Qos Profile",status)
    if not status== '':
        print("Sim QOS Status---- ", status)
        return status
    else:
        time.sleep(1)
        self.qosProfile()

def PDPcontext(self):
    """PDP context 1 activation (alternatively with
        AT+CGDATA="PPP", 1 or ATD*99***1#)."""

    self.gsm.write('AT+CGDATA="PPP",1\r\n')
    status = self.read_first()
    print("CGDDATA PP ATTACHED ----", status)
    if status.startswith('CONNECT'):
        print("CGDDATA context 1 activation---- ", status)
        return status
    else:
        time.sleep(1)
        self.PDPcontext()

def checkIP(self):
    """Show address of PDP context 1. If PPP is used
        this command shall be sent from another AT
        command interface."""

    self.gsm.write('AT+CGPADDR=1\r\n')
    status = self.read_first()
    print("checkip method --",status)
    if status.startswith('+CGPADDR'):
        print("PDP context 1 activation---- ", status)
        return status
    else:
        time.sleep(1)
        self.checkIP()



def attachGSMtoPPP(self):
    import network
    GPRS=network.PPP(self.gsm)
    GPRS.active(True)
    GPRS.connect(authmode=GPRS.AUTH_PAP, username="", password="")
    if GPRS.isconnected():
        print(GPRS.ifconfig())
        return True
    else:
        time.sleep(0.5)
        self.attachGSMtoPPP()




        

        

def read_status(self):
    self.gsm.readline()
    status = self.gsm.readline()
    if status:
        status = status.decode().replace('\r\n','')
        return status
    else:
        print("Sim Module Not Connected or UART using by other device")
def read_first(self):
    status = self.gsm.readline()
    if status:
        status = status.decode().replace('\r\n','')
        return status
    else:
        print("Sim Module Not Connected or UART using by other device")

if name == "main":

print("Calling Main File")
time.sleep(10)
print("Starting the Sim Initailization Process")
sim = InitSimData()

-------------------------###########################------------ output logs are ----

gsm = machine.UART(1, rx=4, tx=2, baudrate=9600,timeout=1000)
gsm.write('AT\r\n')
4
print(gsm.readline())
b'\r\n'
print(gsm.readline())
b'OK\r\n'
print(gsm.read())
None
gsm.write('AT\r\n')
4
print(gsm.read())
b'\r\nOK\r\n'
gsm.write('AT+CGDCONT=1,"IP","portalnmms"\r\n')
32
print(gsm.read())
b'\r\nOK\r\n'
gsm.write('AT+CGDATA="PPP",1\r\n')
19
print(gsm.read())
b'\r\nERROR\r\n'

gsm.write('ATD99**1#\r\n')
13
print(gsm.read())
b'\r\n\r\nCONNECT\r\n\r\n'

GPRS=network.PPP(gsm)

GPRS.active(True)
True
GPRS.connect(authmode=GPRS.AUTH_PAP, username="", password="")
GPRS.isconnected()
False
GPRS.isconnected()
False
GPRS.isconnected()
False
GPRS.isconnected()

CANDIDATE · ISSUE

MIMXRT/PPP: Board crashes sometimes accessing a LTE modem.

openby robert-hhopened 2025-03-09updated 2025-03-21
bugports

Port, board and/or hardware

MIMXRT1020_EVK or other MIMXRT board

MicroPython version

MicroPython v1.25.0-preview.371.g27699edce.dirty on 2025-03-09; i.MX RT1020 EVK with MIMXRT1021DAG5A
This is based on PR #16876, which enabled PPP on MIMXRT boards.

Reproduction

Run the below ugly test script thrice without longer delays. It behaves weird at the second call and crashes at the third call. If one waits > 10 seconds between the second and third call, the crash does not happen.

"""
# Establish PPP on ESP32 using SIM7608E.
"""

import time
from network import PPP
from machine import UART, Pin
import socket
import ssl

quiet = False
# Set APN. Specific to your  cellular carrier.
apn = "internet.telekom"
baud_rate = 115200

# Create UART object for SIM76xx modem. Start with 115200 baud.
uart = UART(1, baudrate=115200, rxbuf=1024, txbuf=1024, timeout=200, timeout_char=200)

def wait_response(port, response):
    port.flush()
    resp_msg = None
    while msg := port.readline():
        if not quiet:
            print(msg)
        if response and msg.startswith(response):
            resp_msg = msg
    return resp_msg

def get_http_page(url):
    s = socket.socket()
    try:
        i = socket.getaddrinfo(url, 80)[0][-1]
        print('Connecting to socket...')
        print(s.connect(i))
        print('Send...')
        print(s.send(b"GET / HTTP/1.0\r\n\r\n"))
        print("Get...")
        print(s.recv(4096))
    except:
        print("Connect & xchange failed")
    print('Close socket...')
    s.close()

# Ping modem until it is on and ready
timeout = 10
while timeout > 0:
    uart.write('AT\r\n')
    resp = wait_response(uart, b'AT')
    if resp:
        break
    print(".", end="")
    time.sleep(2)
    timeout -= 1
else:
    print("Unable to establish connection with modem. Try the above again, or potentially check that the pinout is correct")
    raise Exception("Modem unavailable")

uart.write('AT+SIMCOMATI\r\n')
wait_response(uart, None)

uart.write('AT+CEREG=0\r\n')
wait_response(uart, None)

# Wait for registration, which may take a while
timeout = 120
while timeout > 0:
    uart.write('AT+CEREG?\r\n')
    resp = wait_response(uart, b"+CEREG")
    # Wait for "+CEREG=0,1"
    if resp and resp.strip().split(b',')[1] == b"1":
        break
    time.sleep_ms(1000)
    timeout -= 1
else:
    print("Cannot register to the network")
    raise Exception("Network unavailable")

# disable unsolicited messaged
uart.write('AT+CGEREP=0\r\n')
wait_response(uart, None)

# switch the baud rate
if baud_rate != 115200:
    uart.write('AT+IPR={}\r\n'.format(baud_rate))
    wait_response(uart, None)
    uart.init(baudrate=baud_rate, rxbuf=1024, txbuf=1024)

# Connect to network and establish PPP
uart.write('AT+CGDCONT=1,"IP","{}"\r\n'.format(apn))
wait_response(uart, None)
# Enable PPP
uart.write('ATD*99#\r\n')
resp = wait_response(uart, b"CONNECT")

if resp:
    # Hand modem object off to system PPP module
    ppp = PPP(uart)
    # GPRS.active(True)
    resp = ppp.connect(security=PPP.SEC_PAP, user="t-mobile", key="tm")
    # This will print out your IP, subnet, gateway, and dns
    print(ppp.ifconfig())
    # Check that you can use a socket
    addr = socket.getaddrinfo('micropython.org', 80)[0][-1]
    print(addr)
    get_http_page('micropython.org')
    #disconnect
    ppp.disconnect()

# stop session
print("Stop PPP session")
uart.write('+++')
wait_response(uart, None)
uart.write('ATH\r\n')
resp = wait_response(uart, None)
# Switch the baud rate back if needed
if baud_rate != 115200:
    uart.write('AT+IPR=115200\r\n')
    wait_response(uart, None)

# Reset the modem to clear the internal states.
# That fixes the non-connect on the second call.
# uart.write('AT+CRESET\r\n')
# wait_response(uart, None)

print("Test finished")

Expected behavior

Runs fine the same ways all three times.

Observed behavior

Crash. The call stack is below. It is every time the same when it crashes.

Image

Edit: Uncommenting the reset modem code at the end of the script prevents the bug, since then the sequence is like starting from power-on reset. But even without reset and strange internal state of the modem the board should not crash.

Additional Information

Behaves the same strange way with a RP2 PICO W and PPP enabled.

Code of Conduct

Yes, I agree

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied