def wait4SIMReady(): #SIM status control - to avoid the 'sim busy' error # The following sequence loops forever until SIM card is ready for use rtnList = [-1,-1] #[return status,return data, exception] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: print 'SIM Verification Cycle' + "\r\n" rtnList = myATC.sendAtCmd('AT+CPBS?' ,myATC.properties.CMD_TERMINATOR,5) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList [0] == 1: if rtnList [1].find("+CPBS") < 0: print 'SIM busy! Please wait!' + "\r\n" while rtnList[1].find("+CPBS:") < 0 : rtnList = myATC.sendAtCmd('AT+CPBS?' ,myATC.properties.CMD_TERMINATOR,5) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList time.sleep(2) print 'SIM Ready' + "\r\n" except: print sys.exc_info() rtnList[0] = -1 return rtnList
def getNetworkInfo(): rtnList = [-1,-1] #[return status,return data, exception] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: rtnList = myATC.sendAtCmd('AT#SERVINFO',myATC.properties.CMD_TERMINATOR,2) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList [0] == 1: rtnList[1] = rtnList[1].replace('"','') rtnList[1] = rtnList[1].replace(':',',') rtnList[1] = rtnList[1].replace(' ','') SERVINFO_list = rtnList[1].split(',') properties.Carrier = SERVINFO_list[4] rtnList = myATC.sendAtCmd('AT#MONI',myATC.properties.CMD_TERMINATOR,2) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList [0] == 1: rtnList[1] = rtnList[1].replace(' ',',') rtnList[1] = rtnList[1].replace(':',',') MONI_list = rtnList[1].split(',') properties.CellId = MONI_list[10] except: print sys.exc_info() rtnList[0] = -1 return rtnList
def reboot(): rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: rtnList = myATC.sendAtCmd('AT&P0',myATC.properties.CMD_TERMINATOR,2) #Save Profile if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList rtnList = myATC.sendAtCmd('AT&W0',myATC.properties.CMD_TERMINATOR,2) #Save Settings if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList time.sleep(1) rtnList = myATC.sendAtCmd('AT#reboot',myATC.properties.CMD_TERMINATOR,2) #Reboot Telit Module if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList time.sleep(1) rtnList = wait4SIMReady() except: print sys.exc_info() rtnList[0] = -1 return rtnList
def getNetworkTime(timeOut): # This function forces the Network to update RTC with GSM Network Time rtnList = [-1,-1] #[return status,return data, exception] # return status: # -2: Timeout # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: rtnList = myATC.sendAtCmd("AT#NITZ=1",myATC.properties.CMD_TERMINATOR,2) #set NITZ command to update Network Time if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList rtnList = myATC.sendAtCmd("AT+COPS=2",myATC.properties.CMD_TERMINATOR,2) #set COPS command to force GSM Registration to disconnect if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList #Start timeout counter start = time.time() #Wait until GSM module is not registered to Network while (1): #MOD.watchdogrtnListet() rtnList = myATC.sendAtCmd('AT+CREG?',myATC.properties.CMD_TERMINATOR,5) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1] == "+CREG: 0,0"): break if (time.time() - start) > timeOut: rtnList[0] = -2 return rtnList rtnList = myATC.sendAtCmd("AT+COPS=0",myATC.properties.CMD_TERMINATOR,2) #set COPS command to force GSM Registration if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList rtnList = isRegistered(timeOut) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 0: rtnList[0] = 0 elif rtnList[0] == -2: #Timeout occurred rtnList[0] = -2 rtnList = myATC.sendAtCmd("AT+CCLK?",myATC.properties.CMD_TERMINATOR,2) #Query RTC Clock if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList except: print sys.exc_info() rtnList[0] = -1 return rtnList
def sendSMS(theSmsMsg,theDestination,theTerminator,retry,timeOut): #This function sends an SMS Message # Input Parameter Definitions # theSmsMsg: The text SMS Message # theTerminator: string or character at the end of AT Command # retry: How many times the command will attempt to retry if not successfully send # timeOut: number of [1/10 seconds] command could take to respond try: rtnList = [-1,-1] #[return status,return data] # return status: # -2: Timeout # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data #Note that the 145 being sent in with the destination address is the "type" of destination address, with 145 including a "+" for international while (retry != -1): rtnList[1] = MDM.send('AT+CMGS="' + str(theDestination) + '",145', 0) rtnList[1] = MDM.sendbyte(0x0d, 0) rtnList = ATC.mdmResponse('\r\n>', timeOut) rtnList[1] = MDM.send(theSmsMsg, 0) rtnList[1] = MDM.sendbyte(0x1a, 0) #Wait for AT command response rtnList = ATC.mdmResponse(theTerminator, timeOut) #Did AT command respond without error? pos1 = rtnList[1].rfind(theTerminator,0,len(rtnList[1])) if (pos1 != -1): retry = -1 rtnList = ATC.parseResponse(rtnList[1]) else: retry = retry - 1 rtnList[0] = 0 #no error, no data #If the function fails to find the proper response to the SMS send ('OK<cr><lf>') then we receive a timeout string: 'timeOut' except: print sys.exc_info() rtnList[0] = -1 return rtnList
def isRegistered(timeOut): # This function waits until the cellular module is registered to a Network rtnList = [-1,-1] #[return status,return data, exception] # return status: # -2: Timeout # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: #Start timeout counter start = time.time() #Wait until registered to GSM Network while True: rtnList = myATC.sendAtCmd('AT+CREG?',myATC.properties.CMD_TERMINATOR,5) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1][rtnList[1].rfind(',')+1:len(rtnList[1])] == '5' or rtnList[1][rtnList[1].rfind(',')+1:len(rtnList[1])] == '1'): rtnList[0] = 0 break if (time.time() - start) > timeOut: rtnList[0] = -2 break time.sleep(1) except: print sys.exc_info() rtnList[0] = -1 return rtnList
def openSocket(addr,port,sockNum,userID,userPassword,protocol,connMode): #Function Open a socket and responds with CONNECT/NO CARRIER/ERROR rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: #Close Socket rtnList = ATC.sendAtCmd('AT#SS',ATC.properties.CMD_TERMINATOR,180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList if (rtnList[1] !="#SS: 1,0"): rtnList = ATC.sendAtCmd('AT#SH=1',ATC.properties.CMD_TERMINATOR,180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #Activate PDP if needed rtnList = ATC.sendAtCmd('AT#SGACT?',ATC.properties.CMD_TERMINATOR,180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList if (rtnList[1] !="#SGACT: 1,1"): time.sleep(1) rtnList = ATC.sendAtCmd('AT#SGACT=1,1,"' + str(userID) + '","' + str(userPassword) + '"' ,ATC.properties.CMD_TERMINATOR,180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #Open Socket to Server in Data Mode if (str(protocol)=='TCP'): #TCP/IP requested #Test what connect method has been requested if connMode == '1': rtnList = ATC.sendAtCmd('AT#SD=1,0,' + str(port) + ',"' + str(addr) + '",0,0,' + str(connMode),ATC.properties.CMD_TERMINATOR,180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList else: rtnList = ATC.sendAtCmd('AT#SD=1,0,' + str(port) + ',"' + str(addr) + '",0,0,' + str(connMode),'CONNECT\r\n',180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList else: #UPD requested #Test what connect method has been requested if connMode == '1': rtnList = ATC.sendAtCmd('AT#SD=1,1,' + str(port) + ',"' + str(addr) + '",0,5559,' + str(connMode),ATC.properties.CMD_TERMINATOR,180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList else: rtnList = ATC.sendAtCmd('AT#SD=1,1,' + str(port) + ',"' + str(addr) + '",0,5559,' + str(connMode),'CONNECT\r\n',180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList except: print sys.exc_info() rtnList[0] = -1 return rtnList
def configSMS(): try: rtnList = [-1,-1] #[return status,return data] # return status: # -2: Timeout # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data #Enable TEXT format for SMS Message a = ATC.sendAtCmd('AT+CMGF=1',ATC.properties.CMD_TERMINATOR,5) #no indications, we will poll manually b = ATC.sendAtCmd('AT+CNMI=0,0,0,0,0',ATC.properties.CMD_TERMINATOR,5) #Storage location c = ATC.sendAtCmd('AT+CPMS="SM"',ATC.properties.CMD_TERMINATOR,5) #Received SMS extra information display d = ATC.sendAtCmd('AT+CSDH=0',ATC.properties.CMD_TERMINATOR,5) if ( a == -1 or b == -1 or c == -1 or d == -1 ): return rtnList #Errored out rtnList[0] = 0 #no error, no data except: print sys.exc_info() rtnList[0] = -1 return rtnList
def closeSocket(sockNum): rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: #Close Socket rtnList = ATC.sendAtCmd('AT#SH=' + str(sockNum),ATC.properties.CMD_TERMINATOR,20) except: print sys.exc_info() rtnList[0] = -1 return rtnList
def send_CM(inSTR,connId,timeOut): rtnList = [-1,-1] #[return status,return data] # return status: # -2: Timeout occurred # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data if (len(inSTR) == 0): rtnList[0] = 0 return rtnList try: #Define GPRS Settings, MUST change APN String in script for your Carrier Specific setting rtnList = ATC.sendAtCmd('AT#SSEND=' + str(connId),'\r\n> ',180) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList res = mySER.send(inSTR,10) res = mySER.sendbyte(0x1a,2) #Start timeout counter start = time.time() res = '' tmpByte = '' while True: tmpByte = mySER.readbyte() if tmpByte > -1: res += chr(tmpByte) if (res.find('\r\nOK\r\n')>=0): rtnList[0] = 0 break if (time.time() - start) > timeOut: rtnList[0] = -2 break except: print sys.exc_info() rtnList[0] = -1 return rtnList
def Cellular_LED(inSLED): # This function sets the cellular LED # Arguments: # inStatus : GPS LED status. Pass in either 'ON' or 'OFF' # OFF - LED always OFF # ON - LED function ON # try: rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data #Set Stat LED to default value, 0 for OFF, 2 for ON if (inSLED == 'ON'): rtnList[1] = GPIO.setSLED(2, 10, 90) else: rtnList[1] = GPIO.setSLED(0, 10, 90) if (rtnList[1] == -1): #Errored out return rtnList rtnList = myATC.sendAtCmd('AT#SLEDSAV',myATC.properties.CMD_TERMINATOR,0,20) if (rtnList[1] == -1): #Errored out return rtnList rtnList[0] = 0 #no error, no data except: print sys.exc_info() rtnList[0] = -1 return rtnList
def isDataAttached(CGMM, timeOut): # This function waits until module attaches to data service rtnList = [-1,-1] #[return status,return data, exception] # return status: # -2: Timeout # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data if (CGMM != "GE865") or (CGMM != "HE910"): rtnList[0] = 0 return rtnList try: #Start timeout counter start = time.time() #Wait until attached to GPRS service while True: rtnList = myATC.sendAtCmd('AT+CGREG?',myATC.properties.CMD_TERMINATOR,5) if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1][rtnList[1].rfind(',')+1:len(rtnList[1])] == '5' or rtnList[1][rtnList[1].rfind(',')+1:len(rtnList[1])] == '1'): rtnList[0] = 0 break if (time.time() - start) > timeOut: rtnList[0] = -2 break time.sleep(1) except: print sys.exc_info() rtnList[0] = -1 return rtnList
def init(PDPindex,APN): rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data try: #Define GPRS Settings, MUST change APN String in script for your Carrier Specific setting rtnList = ATC.sendAtCmd('AT+CGDCONT=' + str(PDPindex) + ',"IP","' + str(APN) + '","0.0.0.0",0,0' ,ATC.properties.CMD_TERMINATOR,20) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #How long does system wait before sending an under sized packet measured in 100ms settings rtnList = ATC.sendAtCmd('AT#DSTO=10' ,ATC.properties.CMD_TERMINATOR,20) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #escape guard time, after set time escape sequence is accepted, set in 20ms settings rtnList = ATC.sendAtCmd('ATS12=40' ,ATC.properties.CMD_TERMINATOR,20) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #disable the escape sequence from transmitting during a data session rtnList = ATC.sendAtCmd('AT#SKIPESC=1' ,ATC.properties.CMD_TERMINATOR,20) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #Set connect timeOuts and packet sizes for PDP#1 and Socket#1 rtnList = ATC.sendAtCmd('AT#SCFG=1,1,1500,600,100,10' ,ATC.properties.CMD_TERMINATOR,20) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": return rtnList #Sets the behavior of #SSEND and #SREVC, Socket#1 rtnList = ATC.sendAtCmd('AT#SCFGEXT=1,2,0,30,0,0' ,ATC.properties.CMD_TERMINATOR,20) except: print sys.exc_info() rtnList[0] = -1 return rtnList
def main(): try: rtnList = [-1, -1] # [return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data # 2: Error occurred # Initialize the serial interface @ 115200, we must do this or nothing comes out the serial port rtnList = mySER.init("115200", "8N1") if rtnList[0] == -1: return mySER.sendUART("Beginning the T2 SMS Query Program. \r\n\r\n") # Set Global Watchdog timeout in Seconds # MOD.watchdogEnable(300) # Get configuration from demoT2.conf file, transpose into new local myApp class myApp = conf.conf("/sys", "demoT2.conf") if myApp.CONF_STATUS != 0: mySER.sendUART("DemoT2 configuration error: " + str(myApp.CONF_STATUS)) return rtnList mySER.sendUART("Configuration Loaded.\r\n") rtnList = myIO.init() if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": raise UserWarning mySER.sendUART("\r\nInitializing Network Setup. \r\n") # Set Network specific settings, wait for SIM card to be ready rtnList = NETWORK.initNetwork(myApp.ENS) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": raise UserWarning # Initialize SOCKET communications rtnList = SOCKET.init("1", myApp.APN) if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": raise UserWarning mySER.sendUART("Network Setup Initialized. \r\n\r\n") mySER.sendUART("Initializing GPS \r\n") # Turn the GPS ON rtnList[1] = GPS.getPowerOnOff() while rtnList[1] != 1: GPS.powerOnOff(1) rtnList[1] = GPS.getPowerOnOff() mySER.sendUART("GPS Status: " + str(rtnList[1]) + "\r\n") mySER.sendUART("GPS Initialized. \r\n\r\n") mySER.sendUART("Initializing SMS. \r\n") # Setup SMS rtnList = mySMS.configSMS() if rtnList[0] == 0: mySER.sendUART("SMS Initialized. \r\n\r\n") else: return # Update Unit information rtnList = ATC.getUnitInfo() if (rtnList[0] == -1) or rtnList[1] == "ERROR": raise UserWarning # Loop forever, without this loop the script would run once and exit script mode. On reboot or power-on the script would run once more while 1: # MOD.watchdogReset() RegCheck = 0 # Initialize check mySER.sendUART("Checking Modem Registration. \r\n") # Wait until module is registered to GSM Network rtnList = NETWORK.isRegistered(180) # Wait 180 seconds for module to obtain GSM registration if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": raise UserWarning if rtnList[0] == 0: RegCheck = 1 mySER.sendUART("Modem Registered. Waiting for SMS. \r\n\r\n") # Loop forever, without this loop the script would run once and exit script mode. On reboot or power-on the script would run once more while RegCheck == 1: # MOD.watchdogReset() # Update NMEA Data # The following are available through the included GPS module: # GPS.getActualPosition(), returns all fields like AT$GPSACP would # GPS.getLastGGA() # GPS.getLastGLL() # GPS.getLastGSA() # GPS.getLastGSV() # GPS.getLastRMC() # GPS.getLastVTG() # GPS.getPosition(), this gives LAT/LONG in numeric format # For the purposes of this demo, RMC will be used # The returned value gives a \r\n at the end so we must strip it for proper usage. # sleep for 1 second to let the GPS catch up otherwise we eventually get a response that .rstrip errors on time.sleep(1) GPSPositionTemp = "" GPSPositionTemp = GPS.getLastRMC() GPSPositionTemp = GPSPositionTemp.rstrip() rtnList = mySMS.CheckNewSMS() # If a new SMS is found and is valid, pass it to the command logic if rtnList[0] == 1: # We have received a new SMS, let's find what it wants us to do. mySER.sendUART("SMS Received.\r\n") mySER.sendUART("SMS Data : " + str(rtnList[1]) + "\r\n") rtnList = mySMS.SMSCommand(rtnList[1]) # 0: Pass, action carried out and SMS sent back # -1: Exception # -2: Pass, Unrecognized change command or AT command received though # -3: Unrecognized SMS # -4: Error sending an SMS to the originating P/N if rtnList[0] == -1: return rtnList = NETWORK.isRegistered(10) # Check Registration on the fly if (rtnList[0] == -1) or (rtnList[0] == -2): RegCheck = 0 mySER.sendUART("\r\nRegistration not available, checking status.\r\n") # What is the signal strength? rtnList = ATC.sendAtCmd("AT+CSQ", ATC.properties.CMD_TERMINATOR, 0, 5) mySER.sendUART("Signal Strength (AT+CSQ): " + rtnList[1] + "\r\n") # Still registered? rtnList = ATC.sendAtCmd("AT+CREG?", ATC.properties.CMD_TERMINATOR, 0, 5) mySER.sendUART("Registration Check (AT+CREG?): " + rtnList[1] + "\r\n") break except UserWarning: print "Controlled Script exit" except: print sys.exc_info() rtnList[0] = -1 return
def CheckNewSMS(): # This function checks for a new SMS. If one is found it parses the information. try: rtnList = [-1,-1] #[return status,return data] # return status: # -2: Timeout # -1: Exception occurred # 0: No errors occurred, no SMS # 1: No errors occurred, return received SMS #Now try to list all newly received SMS. #Using this method because the sendatcommand method ends up parsing out info we need due to the multiple \r\n response. rtnList[1] = MDM.send('AT+CMGL="REC UNREAD"', 0) rtnList[1] = MDM.sendbyte(0x0d, 0) #Grab the response of the command rtnList = ATC.mdmResponse('OK', 10) res = rtnList[1] #Try to list all currently stored SMS's. This is just a check to see if we have old/already read messages. rtnList[1] = MDM.send('AT+CMGL="ALL"', 0) rtnList[1] = MDM.sendbyte(0x0d, 0) #Grab the response of the command rtnList = ATC.mdmResponse('OK', 10) res2 = rtnList[1] #Check for messages, search from 0 to the length of the AT Command response pos0 = res.find('+CMGL: 1',0,len(res)) GeneralCheck = res2.find('+CMGL:',0,len(res2)) if (pos0 != -1): #New message found, let's parse the useful information #first, let's split the received information so we can echo a response to the originating phone number #Below is the normal response we are parsing #+CMGL: <index>,<stat>,<oa/da>,<alpha>,<scts><CR><LF><data><CR><LF> #+CMGL: 1,"REC UNREAD","+xxxxxxxxxxx","test","12/06/06,15:59:50-20" #Data #Separate by \r\n to separate the SMS data parts1 = res.split('\r\n') #Now split by comma to get individual data from the main chunk of information parts2 = parts1[1].split(",") SMSInfo.index = parts2[0] SMSInfo.stat = parts2[1] SMSInfo.OriginatingPN = parts2[2] SMSInfo.alpha = parts2[3] SMSInfo.date = parts2[4] SMSInfo.time = parts2[5] SMSInfo.SMS = parts1[2] #Delete ALL SMS to ensure a clear buffer for the next read rtnList = ATC.sendAtCmd('AT+CMGD=1,4' ,ATC.properties.CMD_TERMINATOR,5) rtnList[1] = SMSInfo.SMS rtnList[0] = 1 #indicate data received return rtnList #Enter this AT command to ensure the buffer is empty and ready to receive new SMS messages if (GeneralCheck != -1): rtnList = ATC.sendAtCmd('AT+CMGD=1,4' ,ATC.properties.CMD_TERMINATOR,5) rtnList[0] = 0 #No errors, but no data received except: print sys.exc_info() rtnList[0] = -1 return rtnList
except UserWarning: print 'Controlled Script exit' except: print sys.exc_info() rtnList[0] = -1 return ##-------------------------------------------------------------------------------------------------------------------- ## Main Function ##-------------------------------------------------------------------------------------------------------------------- try: main() print "Main Script Exit" #Reboot or Script will not restart until a power cycle occurs ATC.reboot() except: print "Main Script encountered an exception" print sys.exc_info() #Reboot or Script will not restart until a power cycle occurs ATC.reboot()
def main(): try: # Set Global Watchdog timeout in Seconds MOD.watchdogEnable(300) ####################################### ## Initialization ####################################### rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data # 2: Error occurred #Initialize the serial interface @ 115200, we must do this or nothing comes out the serial port rtnList = mySER.init("115200",'8N1') if (rtnList[0] == -1): return mySER.sendUART("Beginning the serial bridge program. \r\n\r\n") # Set Global Watchdog timeout in Seconds #MOD.watchdogEnable(300) #Get configuration from demo.conf file, transpose into new local myApp class myApp = conf.conf('/sys','demo.conf') if myApp.CONF_STATUS != 0: mySER.sendUART("Demo configuration error: " + str(myApp.CONF_STATUS)) return rtnList mySER.sendUART("Configuration Loaded.\r\n") rtnList = myIO.init() if (rtnList[0] == -1) or (rtnList[0] == -2) or rtnList[1] == "ERROR": raise UserWarning mySER.sendUART("\r\nInitializing Network Setup. \r\n") #Set Network specific settings, wait for SIM card to be ready rtnList = NETWORK.initNetwork(myApp.ENS) if (rtnList[0] == -1) or (rtnList[0] == -2): raise UserWarning #Initialize SOCKET communications rtnList = SOCKET.init('1',myApp.APN) if (rtnList[0] == -1) or (rtnList[0] == -2): raise UserWarning mySER.sendUART("Network Setup Initialized. \r\n\r\n") #Update Unit information rtnList = ATC.getUnitInfo() if (rtnList[0] == -1): raise UserWarning # Loop forever, without this loop the script would run once and exit script mode. On reboot or power-on the script would run once more while (1): MOD.watchdogReset() ####################################### ## Registration ####################################### RegCheck = 0 #Initialize check DataCheck = 0 #Initialize Check #What is the signal strength? rtnList = ATC.sendAtCmd('AT+CSQ',ATC.properties.CMD_TERMINATOR,5) if (rtnList[0] == -1) or (rtnList[0] == -2): raise UserWarning mySER.sendUART("Signal Strength (AT+CSQ): " + rtnList[1] + "\r\n") #Wait until module is registered to GSM Network mySER.sendUART("Checking Modem Registration. \r\n") rtnList = NETWORK.isRegistered(180) #Wait 180 seconds for module to obtain GSM registration if (rtnList[0] == -1) or (rtnList[0] == -2): raise UserWarning if (rtnList[0] == 0): #Registered successfully RegCheck = 1 mySER.sendUART("Modem Registered. \r\n\r\n") #Wait until module is ready for data mySER.sendUART("Checking Data Availability. \r\n") rtnList = NETWORK.isDataAttached(myApp.CGMM, 180) #Wait 180 seconds for module to obtain GSM registration if (rtnList[0] == -1) or (rtnList[0] == -2): raise UserWarning if (rtnList[0] == 0): #Registered successfully DataCheck = 1 mySER.sendUART("Modem ready for data. \r\n\r\n") #check for exit prompt, let's use command EXITSCR rtnList = mySER.readUART() if (rtnList[1].find('EXITSCR') != -1): print '\r\nExit Command Found\r\n' return ####################################### ## Socket Connection ####################################### # Loop while we're registered/ready while (RegCheck == 1 and DataCheck == 1): #check for exit prompt, let's use command EXITSCR rtnList = mySER.readUART() if (rtnList[1].find('EXITSCR') != -1): print '\r\nExit Command Found\r\n' return rtnList = NETWORK.isRegistered(10) #Fast reg check if (rtnList[0] == -1) or (rtnList[0] == -2): #unavailable, drill down discretely and show the status RegCheck = 0 rtnList = ATC.sendAtCmd('AT+CREG?',ATC.properties.CMD_TERMINATOR,5) mySER.sendUART("Registration Unavailable, Status: " + rtnList[1] + "\r\n") break #exit loop rtnList = NETWORK.isDataAttached(myApp.CGMM, 10) #Fast data check if (rtnList[0] == -1) or (rtnList[0] == -2): #unavailable, drill down discretely and show the status DataCheck = 0 rtnList = ATC.sendAtCmd('AT+CGREG?',ATC.properties.CMD_TERMINATOR,5) mySER.sendUART("Data Unavailable, Status: " + rtnList[1] + "\r\n") break #exit loop #Open socket in online mode mySER.sendUART("Opening socket to server: " + myApp.IP + ":" + myApp.PORT + "\r\n") rtnList = SOCKET.openSocket(myApp.IP,myApp.PORT,1,myApp.USERNAME,myApp.PASSWORD,myApp.PROTOCOL,0) if (rtnList[0] == -1) or (rtnList[0] == -2): raise UserWarning #Check for open connection, this catches both online and command mode operations if (rtnList[1] == "OK" or rtnList[1] == "CONNECT"): mySER.sendUART("Socket opened successfully.\r\n") else: mySER.sendUART("Connection failed to open, trying again. \r\n") #Check for open socket DCD = MDM.getDCD() if (DCD == 1): #Set DCD on USIF0 SER.setDCD(1) #Forward CONNECT Message to Serial Port mySER.sendUART('\r\nConnected to Server\r\n') myIO.USER_LED('ON') ####################################### ## Data exchange loop ####################################### ##Loop while Socket connected. This loop operates on the notion that we are in online mode, so we are not using send_CM while(1): #Pet the watchdog MOD.watchdogReset() #Check for DCD active on MDM DCD = MDM.getDCD() if (DCD == 1): #Outbound #Get data from serial port, use function return rtnList = mySER.readUART() if (len(rtnList[1])!=0): #Forward data to open socket if it's not empty and not the exit script command #check for exit prompt, let's use command EXITSCR if (rtnList[1].find('EXITSCR') != -1): #exit found print '\r\nExit Command Found\r\n' print 'Exiting data mode\r\n' rtnList = SOCKET.exitDataMode() print 'Closing the socket\r\n' rtnList = SOCKET.closeSocket(1) return print rtnList[1] #Debug res = MDM.send(rtnList[1],1) #Inbound #Get data from open socket connection, straight MDM read res = MDM.read() if (len(res)!=0): #Forward socket data to serial port print res #Debug mySER.sendUART(res) #When socket is closed exit loop via this path #Will guarantee that '\r\nNO CARRIER\r\n' is sent every time if (DCD == 0): #Clear DCD on USIF0 SER.setDCD(0) myIO.USER_LED('OFF') #Get any remaining data from closed socket connection, straight MDM read res = MDM.read() if (len(res)!=0): #Forward socket data to serial port mySER.sendUART(res) break #exit loop to registration checks except UserWarning: print 'Controlled Script exit' except: print sys.exc_info() rtnList[0] = -1 return
def SMSCommand(inStr): # This function checks a newly received SMS for commands. # If it finds specific command, using the header "CMD: " it will parse the command out, adjust the configuration parameter, and then respond to the originating PN as verification. # If it finds an AT command, by simply finding AT it will take the command and carry it out, replying to the originating PN with the AT response. # Input Parameter Definitions # inStr: The received SMS ## Currently supported command list for things that can be altered. Simple list for now. ## The user may also query the unit's information with a simple STATUS ## SLED ## ULED try: rtnList = [-1,-1] #[return status,return data] # return status: # Returns: # 0: Pass, action carried out and SMS sent back # -1: Exception # -2: Pass, Unrecognized change command or AT command received though # -3: Unrecognized SMS # -4: Error sending an SMS to the originating P/N #Check for either change command or an AT command. Splitting ATCMD check into specifics because STATUS can trigger a generic AT check (alternative is to switch query word) changeCMD = inStr.find('CMD: ',0,len(inStr)) ATCMD = inStr.find('AT',0,len(inStr)) StatusQuery = inStr.find('STATUS',0,len(inStr)) if (changeCMD != -1): #Change command found, take the commad, find what it's adjusting and then send an SMS back to the originator for verification #We know that it should be found at 0, and 5 characters after the command should start "CMD: x". ReceivedCmd = inStr[+5:len(inStr)] if (ReceivedCmd == 'SLED = ON'): mySER.sendUART("Cellular LED : ON \r\n\r\n") rtnList = IO_HE910.Cellular_LED('ON') rtnList = sendSMS("Cellular LED : ON",SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = 0 elif (ReceivedCmd == 'SLED = OFF'): mySER.sendUART("Cellular LED : OFF \r\n\r\n") rtnList = IO_HE910.Cellular_LED('OFF') rtnList = sendSMS("Cellular LED : OFF",SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = 0 elif (ReceivedCmd == 'ULED = ON'): mySER.sendUART("User LED : ON \r\n\r\n") rtnList = IO_HE910.USER_LED('ON') rtnList = sendSMS("User LED : ON",SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = 0 elif (ReceivedCmd == 'ULED = OFF'): mySER.sendUART("User LED : OFF \r\n\r\n") rtnList = IO_HE910.USER_LED('OFF') rtnList = sendSMS("User LED : OFF",SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = 0 else: mySER.sendUART("Unrecognized/Unsupported Command Received: " + ReceivedCmd + "\r\n\r\n") rtnList = sendSMS("Unrecognized Command Received: " + ReceivedCmd,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = -2 #Did we timeout or get an ERROR during the SMS sending? if (rtnList[1].find("timeOut")!=-1 or rtnList[1].find("ERROR") != -1): rtnList[0] = -4 elif (StatusQuery != -1): #Status query for the module, pass back the current configuration values and location #This is the first elif to catch the STATUS check without accidentally triggering the general AT check mySER.sendUART("Status Query :\r\n") #Check the CELL LED Status to report rtnList = ATC.sendAtCmd('AT#GPIO=1,2' ,ATC.properties.CMD_TERMINATOR,5) #GPIO: 2,0 if (rtnList[1].find('#GPIO: 2') != -1): CELL_LED = 'ON' else: CELL_LED = 'OFF' #Check the GPS/USER LED Status to report rtnList = ATC.sendAtCmd('AT#GPIO=2,2' ,ATC.properties.CMD_TERMINATOR,5) #GPIO: 2,0 if (rtnList[1].find('#GPIO: 1,1') != -1): USER_LED = 'ON' else: USER_LED = 'OFF' #The following are available through the included GPS module: #GPS.getActualPosition(), returns all fields like AT$GPSACP would #GPS.getLastGGA() #GPS.getLastGLL() #GPS.getLastGSA() #GPS.getLastGSV() #GPS.getLastRMC() #GPS.getLastVTG() #GPS.getPosition(), this gives LAT/LONG in numeric format #For the purposes of this demo, RMC will be used CurrentLocation = GPS.getLastRMC() QueryResponse = str("Unit: " + ATC.properties.IMEI+ "\r\n" + "Status LED: " + CELL_LED + "\r\n" + "USER LED: " + USER_LED + "\r\n" + "Current Location: " + CurrentLocation + "\r\n") mySER.sendUART(QueryResponse) rtnList = sendSMS(QueryResponse,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = 0 #Did we timeout or get an ERROR during the SMS sending? if (rtnList[1].find("timeOut")!=-1 or rtnList[1].find("ERROR") != -1): rtnList[0] = -4 elif (ATCMD != -1): #AT command found, execute the command and pass back the response to the main program. #Using this instead of the sendatcommand method because it doesn't parse possibly useful information in an open ended response. #res = MDM.send(inStr, 0) #res = MDM.sendbyte(0x0d, 0) #Grab the response of the command in it's entirety #ATCMDResponse = ATC.mdmResponse(ATC.properties.CMD_TERMINATOR, 10) ATCMDResponse = ATC.sendAtCmd(inStr ,ATC.properties.CMD_TERMINATOR,5) #Did we get an ERROR from the AT command? if (ATCMDResponse[1].find("ERROR") != -1): rtnList[0] = -2 #Pass it to the UART and also send an SMS with the response. mySER.sendUART(ATCMDResponse[1] + "\r\n\r\n") rtnList = sendSMS(ATCMDResponse[1],SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = 0 #Did we timeout or get an ERROR during the SMS sending? if (rtnList[1].find("timeOut")!=-1 or rtnList[1].find("ERROR") != -1): rtnList[0] = -4 else: #Unrecognized SMS mySER.sendUART("Unrecognized/Unsupported Command Received: " + inStr + "\r\n\r\n") rtnList = sendSMS("Unrecognized/Unsupported SMS Received: " + inStr,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180) rtnList[0] = -3 #Did we timeout or get an ERROR during the SMS sending? Otherwise just return the -3 if (rtnList[1].find("timeOut")!=-1 or rtnList[1].find("ERROR") != -1): rtnList[0] = -4 except: print sys.exc_info() rtnList[0] = -1 return rtnList
def initNetwork(ENS): # This function sets all Network specific settings # Input Parameter Definitions # inSTR1: Cellular device model # inSTR2: AT#ENS, range(0:1) rtnList = [-1,-1] #[return status,return data] # return status: # -1: Exception occurred # 0: No errors occurred, no return data # 1: No errors occurred, return data reboot_needed = False try: rtnList = myATC.sendAtCmd("AT#SELINT?",myATC.properties.CMD_TERMINATOR,2) #query SELINT setting if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1] != "#SELINT: 2"): rtnList = myATC.sendAtCmd('AT#SELINT=2',myATC.properties.CMD_TERMINATOR,2) #use of most recent AT command set if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList reboot_needed = True if (ENS == "1"): #Set module to work on US ATT Network rtnList = myATC.sendAtCmd("AT#ENS?",myATC.properties.CMD_TERMINATOR,2) #query ENS setting if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1] != "#ENS: 1"): rtnList = myATC.sendAtCmd('AT#ENS=1',myATC.properties.CMD_TERMINATOR,2) #sets all ATT requirements if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList reboot_needed = True else: #Set module to work on US GSM Networks rtnList = myATC.sendAtCmd("AT#ENS?",myATC.properties.CMD_TERMINATOR,2) #query ENS setting if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1] != "#ENS: 0"): rtnList = myATC.sendAtCmd('AT#ENS=0',myATC.properties.CMD_TERMINATOR,2) #sets all ATT requirements if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList reboot_needed = True rtnList = myATC.sendAtCmd('AT#AUTOBND?',myATC.properties.CMD_TERMINATOR,2) #query AUTOBND setting if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList elif rtnList[0] == 1: if (rtnList[1] != "#AUTOBND: 2"): rtnList = myATC.sendAtCmd('AT#AUTOBND=2',myATC.properties.CMD_TERMINATOR,2) #enable Quad band system selection if (rtnList[0] == -1) or (rtnList[0] == -2) : return rtnList reboot_needed = True if (reboot_needed): rtnList = reboot() rtnList[0] = 0 except: print sys.exc_info() rtnList[0] = -1 return rtnList