Example #1
0
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
Example #2
0
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
    #   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

    ##  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
    ##    INTERVAL
    ##    NOSWITCH
    ##    IGNITION
    ##    SLED
    ##    ULED
    ##    AUTOON

    tmpReturn = -1

    try:
        
        #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 == 'NOSWITCH = TRUE'):
                JANUS_CONFIG.Config.NOSWITCH = 'TRUE'
                JANUS_SER.sendUART("Switch Report : " + JANUS_CONFIG.Config.NOSWITCH + "\r\n")
                res = sendSMS("Switch Report : " + JANUS_CONFIG.Config.NOSWITCH,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'NOSWITCH = FALSE'):
                JANUS_CONFIG.Config.NOSWITCH = 'FALSE'
                JANUS_SER.sendUART("Switch Report : " + JANUS_CONFIG.Config.NOSWITCH + "\r\n")
                res = sendSMS("Switch Report : " + JANUS_CONFIG.Config.NOSWITCH,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'IGNITION = TRUE'):
                JANUS_CONFIG.Config.IGNITION = 'TRUE'
                JANUS_SER.sendUART("Ignition Report : " + JANUS_CONFIG.Config.IGNITION + "\r\n")
                res = sendSMS("Ignition Report : " + JANUS_CONFIG.Config.IGNITION,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'IGNITION = FALSE'):
                JANUS_CONFIG.Config.IGNITION = 'FALSE'
                JANUS_SER.sendUART("Ignition Report : " + JANUS_CONFIG.Config.IGNITION + "\r\n")
                res = sendSMS("Ignition Report : " + JANUS_CONFIG.Config.IGNITION,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'SLED = ON'):
                JANUS_CONFIG.Config.SLED = 'ON'
                JANUS_SER.sendUART("Cellular LED : " + JANUS_CONFIG.Config.SLED + "\r\n")
                res = sendSMS("Cellular LED : " + JANUS_CONFIG.Config.SLED,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'SLED = OFF'):
                JANUS_CONFIG.Config.SLED = 'OFF'
                JANUS_SER.sendUART("Cellular LED : " + JANUS_CONFIG.Config.SLED + "\r\n")
                res = sendSMS("Cellular LED : " + JANUS_CONFIG.Config.SLED,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'ULED = ON'):
                JANUS_CONFIG.Config.ULED = 'ON'
                JANUS_SER.sendUART("User LED : " + JANUS_CONFIG.Config.ULED + "\r\n")
                res = sendSMS("User LED : " + JANUS_CONFIG.Config.ULED,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'ULED = OFF'):
                JANUS_CONFIG.Config.ULED = 'OFF'
                JANUS_SER.sendUART("User LED : " + JANUS_CONFIG.Config.ULED + "\r\n")
                res = sendSMS("User LED : " + JANUS_CONFIG.Config.ULED,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'AUTOON = ON'):
                JANUS_CONFIG.Config.AUTOON = 'ON'
                JANUS_SER.sendUART("Auto ON : " + JANUS_CONFIG.Config.AUTOON + "\r\n")
                res = sendSMS("Auto ON : " + JANUS_CONFIG.Config.AUTOON,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'AUTOON = OFF'):
                JANUS_CONFIG.Config.AUTOON = 'OFF'
                JANUS_SER.sendUART("Auto ON : " + JANUS_CONFIG.Config.AUTOON + "\r\n")
                res = sendSMS("Auto ON : " + JANUS_CONFIG.Config.AUTOON,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd.find("INTERVAL") !=-1):
                #We have a GPS reporting interval change, make sure the value is between 1 and 86400
                #INTERVAL = xxx
                NewInterval = ReceivedCmd[+11:len(ReceivedCmd)]

                #Store original interval
                OrigInterval = JANUS_CONFIG.Config.INTERVAL

                #Change configuration interval
                JANUS_CONFIG.Config.INTERVAL = NewInterval

                if (int(JANUS_CONFIG.Config.INTERVAL) < 1 or int(JANUS_CONFIG.Config.INTERVAL) > 86400):
                    JANUS_SER.sendUART("Interval not in range (1 - 86400).\r\n")
                    res = sendSMS("Interval out of range (1 - 86400) : " + JANUS_CONFIG.Config.INTERVAL,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                    #Return the configuration to the original state
                    JANUS_CONFIG.Config.INTERVAL = OrigInterval
                    tmpReturn = -2
                else:
                    JANUS_SER.sendUART("Report Interval : " + JANUS_CONFIG.Config.INTERVAL + "\r\n")
                    res = sendSMS("Report Interval : " + JANUS_CONFIG.Config.INTERVAL,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                    tmpReturn = 0                    
            elif (ReceivedCmd == 'IGNITIONFOLLOW = TRUE'):
                JANUS_CONFIG.Config.IGNITIONFOLLOW = 'TRUE'
                JANUS_SER.sendUART("Ignition Follow : " + JANUS_CONFIG.Config.IGNITIONFOLLOW + "\r\n")
                res = sendSMS("Ignition Follow : " + JANUS_CONFIG.Config.IGNITIONFOLLOW,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            elif (ReceivedCmd == 'IGNITIONFOLLOW = FALSE'):
                JANUS_CONFIG.Config.IGNITIONFOLLOW = 'FALSE'
                JANUS_SER.sendUART("Ignition Follow : " + JANUS_CONFIG.Config.IGNITIONFOLLOW + "\r\n")
                res = sendSMS("Ignition Follow : " + JANUS_CONFIG.Config.IGNITIONFOLLOW,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = 0
            else:
                JANUS_SER.sendUART("Unrecognized/Unsupported Command Received: " + ReceivedCmd + "\r\n")
                res = sendSMS("Unrecognized/Unsupported Command Received: " + ReceivedCmd,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                tmpReturn = -2
                
            #Did we timeout or get an ERROR during the SMS sending?
            if (res.find("timeOut")!=-1 or res.find("ERROR") != -1):
                tmpReturn = -4

            #If we sucessfully changed the configuration amd sent the message, update and save the configuration file.
            if (tmpReturn == 0):
                res = JANUS_CONFIG.UpdateConfig()
                if (res == -1):
                    JANUS_SER.sendUART("Configuration Save Error.\r\n\r\n")
                    res = sendSMS("Configuration Save Error.",SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
                    return
                else:
                    JANUS_SER.sendUART("Configuration file updated.\r\n\r\n")

        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
            JANUS_SER.sendUART("Status Query :\r\n")

            #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, GLL will be used

            CurrentLocation = GPS.getLastRMC()
            QueryResponse = str("Unit: " + ATC.properties.IMEI+ "\r\n" +
                            "Switch Reporting: " + JANUS_CONFIG.Config.NOSWITCH + "\r\n" +
                            "Ignition Reporting: " + JANUS_CONFIG.Config.IGNITION + "\r\n" +
                            "Status LED: " + JANUS_CONFIG.Config.SLED + "\r\n" +
                            "User LED: " + JANUS_CONFIG.Config.ULED + "\r\n" +
                            "Auto ON: " + JANUS_CONFIG.Config.AUTOON + "\r\n" +
                            "Report Interval: " + JANUS_CONFIG.Config.INTERVAL + "\r\n" +
                            "Ignition Follow: " + JANUS_CONFIG.Config.IGNITIONFOLLOW + "\r\n" +
                            "Current Location: " + CurrentLocation + "\r\n")

            JANUS_SER.sendUART(QueryResponse)
            res = sendSMS(QueryResponse,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
            tmpReturn = 0

            #Did we timeout or get an ERROR during the SMS sending?
            if (res.find("timeOut")!=-1 or res.find("ERROR") != -1):
                tmpReturn = -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,3,2)

            #Pass it to the UART and also send an SMS with the response.         
            JANUS_SER.sendUART(ATCMDResponse + "\r\n")
            res = sendSMS(ATCMDResponse,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
            tmpReturn = 0

            #Did we timeout or get an ERROR during the SMS sending?
            if (res.find("timeOut")!=-1 or res.find("ERROR") != -1):
                tmpReturn = -4

            #Did we get an ERROR from the AT command?
            if (ATCMDResponse.find("ERROR") != -1):
                tmpReturn = -2

        else:
            #Unrecognized SMS
            JANUS_SER.sendUART("Unrecognized/Unsupported SMS Received: " + inStr + "\r\n")
            tmpReturn = -3

            res = sendSMS("Unrecognized/Unsupported SMS Received: " + inStr,SMSInfo.OriginatingPN,ATC.properties.CMD_TERMINATOR,3,180)
            tmpReturn = 0

            #Did we timeout or get an ERROR during the SMS sending? Otherwise just return the -3
            if (res.find("timeOut")!=-1 or res.find("ERROR") != -1):
                tmpReturn = -4            
            
    except:
        printException("SMSCommand()")

    return tmpReturn
Example #3
0
def main():

    try:
        # Set Global Watchdog timeout in Seconds
        MOD.watchdogEnable(300)

        #Initialize the serial interface @ 115200, we must do this or nothing comes out the serial port
        res = JANUS_SER.init("115200",'8N1')
        if (res == -1):
            return

        JANUS_SER.sendUART("Beginning the Terminus Tracker Demo Program. \r\n\r\n")
        
        #Initialize the configuration, returns 0 for defaults, 1 for normal.
        ConfigLoad = JANUS_CONFIG.init()

        #Transpose the configuration list to myApp for usage here
        #We transpose only the main Config class to handle updates
        if (ConfigLoad == 0):
            myApp = JANUS_CONFIG.Config
            JANUS_SER.sendUART("Defaults Loaded.\r\n")
        elif (ConfigLoad == 1):
            myApp = JANUS_CONFIG.Config
            JANUS_SER.sendUART("Configuration File Loaded.\r\n")
        else:
            myApp = JANUS_CONFIG.Config
            JANUS_SER.sendUART("Configuration ERROR. Defaults Loaded.\r\n")

        #Initialize the I/O, turn on the stat LED
        res = JANUS_IO.init(myApp.SLED)
        if (res == -1):
            return

        #Read if Auto-On is active or not, 1 is active, 0 is inactive.  
        res = JANUS_IO.AutoONControl('READ', myApp.AUTOON)

        JANUS_SER.sendUART("\r\nAuto On: " + myApp.AUTOON + "\r\n")        

        #If Auto-on is OFF and we want it ON, set it.  
        if (res == 0 and myApp.AUTOON == 'ON'):
            res = JANUS_IO.AutoONControl('SET', myApp.AUTOON)            
            if (res == -1):
                return #Errored out
            elif (res == -2):
                JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n")
            elif (res == 1):
                JANUS_SER.sendUART("Auto ON Enabled. \r\n")

        #If Auto-on is ON and we want it OFF, set it.
        if (res == 1 and myApp.AUTOON == 'OFF'):
            res = JANUS_IO.AutoONControl('SET', myApp.AUTOON)
            if (res == -1):
                return #Errored out
            elif (res == -2):
                JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n")
            elif (res == 0):
                JANUS_SER.sendUART("Auto ON Disabled. \r\n")

        #If Auto-on is OFF, and we have it set as OFF. Let's see what caused this wake up and report it.
        #Although we can read IGN/SW directly, we check the MCU instead because they
        #May not be active as this point even though the MCU caught it.
    
        WakeupCause = ''
        if (res == 0 and myApp.AUTOON == 'OFF'):
            res = JANUS_IO.SW_IGN_Status()
            if (res == -1):
                return #Errored out
            elif (res == 0):
                JANUS_SER.sendUART("Wake up cause: N/O Switch \r\n")
                WakeupCause = 'Switch'
            elif (res == 1):
                JANUS_SER.sendUART("Wake up cause: Ignition \r\n")
                WakeupCause = 'Ignition'
            elif (res == 2):
                JANUS_SER.sendUART("Wake up cause: Both the Ignition and N/O Switch \r\n")
                WakeupCause = 'Both'
            elif (res == -2):
                JANUS_SER.sendUART("Wake up cause: Unknown \r\n")
                WakeupCause = 'Unknown'

                
        JANUS_SER.sendUART("\r\nInitializing Module GPRS. \r\n")
        #Set Network specific settings, wait for SIM card to be ready
        res = NETWORK.initGsmNetwork(myApp.NETWORK,myApp.BAND)
        if (res == -1):
            return

        #Init GPRS
        GPRS.init('1',myApp.APN)

        JANUS_SER.sendUART("GPRS Initialized. \r\n")
        
        ################################################################
        #### BEGIN Newly Added Config Stuff
        ################################################################

        #Initalize GPS
        JANUS_SER.sendUART("\r\nInitializing Module GPS. \r\n")
        res = JANUS_GPS.init(myApp.LNA)
        
        if (res != 0):
            JANUS_SER.sendUART("Failed to Initialize GPS, ERROR: " + res + "\r\n\r\n")
            return

        JANUS_SER.sendUART("GPS Initialized. \r\n\r\n")

        #Setup SMS
        if (myApp.SMS_ENABLED == 'TRUE'):
            JANUS_SER.sendUART("SMS Enabled, Initializing. \r\n")
            JANUS_SMS.configSMS()
            JANUS_SER.sendUART("SMS Initialized. \r\n\r\n")
        ################################################################
        #### END Newly Added Config Stuff
        ################################################################        

        # 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()

            JANUS_SER.sendUART("Registering Module. \r\n")
            #Wait until module is registered to GSM Network
            res = NETWORK.isGsmRegistered(180)  #Wait 180 seconds for module to obtain GSM registration
            if (res == -1):
                return
            
            #Wait until module is attached to GPRS    
            res = NETWORK.isGprsAttached(180)  #Wait 180 seconds for module to obtain GPRS Attachment
            if (res == -1):
                return

            JANUS_SER.sendUART("Module Registered Successfully. \r\n\r\n")
            #############################################################################################################################
            ## Opening Socket Connection to Server
            ## We are opening in Command Mode to have the best control
            #############################################################################################################################

            #Update Unit information
            res = ATC.getUnitInfo()

            # Start timeout timer            
            timerB = timers.timer(0)
            timerB.start(int(myApp.INTERVAL))

            SwitchPos = 'Open' #Default State for Switch
            IgnPos = 'Inactive' #Default State for Switch

            FirstTimeThrough = 'TRUE' #Initialize flag for the first time running the connection/loop
            SENDSTRING = [] #Initialize the string list being sent to the server
            StringCount = 0
            # 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):
       
                while (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.
                    GPSPositionTemp = ''
                    GPSPositionTemp = GPS.getLastRMC()
                    GPSPositionTemp = GPSPositionTemp.rstrip()

                    #Update switch and ignition information
                    #We simply clear after the report is sent, so by default it's sent as Open/Inactive until it's read as the opposite.
                    #We're polling the MCU signals and then signaling back "we got the information" so we only read once, giving us one or both events to report
                        #    0: Pass, Switch is triggered
                        #    1: Pass, Ignition is triggered
                        #    2: Pass, BOTH are triggered
                        #   -1: Exception
                        #   -2: Pass, Neither is triggered

                    EventCheck = JANUS_IO.SW_IGN_Status()
                    if (EventCheck == 0): #Switch has been triggered
                        SwitchPos = 'Closed'
                        #JANUS_SER.sendUART("SwitchPos : " + SwitchPos + "\r\n")  

                    elif (EventCheck == 1): #Ignition has been triggered
                        IgnPos = 'Active'
                        #JANUS_SER.sendUART("IgnPos : " + IgnPos + "\r\n")

                    elif (EventCheck == 2): #Both have been triggered
                        SwitchPos = 'Closed'
                        IgnPos = 'Active'
                        #JANUS_SER.sendUART("IgnPos : " + IgnPos + "\r\n")
                        #JANUS_SER.sendUART("SwitchPos : " + SwitchPos + "\r\n")
                        
                    if (myApp.SMS_ENABLED == 'TRUE'):
                        res = JANUS_SMS.CheckNewSMS()
                        #If a new SMS is found and is valid, pass it to the command logic
                        if (res != '0'):
                            #We have received a new SMS, let's find what it wants us to do.
                            #JANUS_SER.sendUART("SMS Data : " + str(res) + "\r\n")
                            res = JANUS_SMS.SMSCommand(str(res))
                            #    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 (res == -1):
                                return

                            #If the STAT LED was updated via SMS, let's adjust it                            
                            res = JANUS_IO.Cellular_LED(myApp.SLED)

                            #AUTO ON Run time Change.
                            #Read current Auto-On status, 1 is active, 0 is inactive.  
                            res = JANUS_IO.AutoONControl('READ', myApp.AUTOON)    

                            #The below will be ignored if there is no change
                            #If Auto-on is OFF and we want it ON, set it.  
                            if (res == 0 and myApp.AUTOON == 'ON'):
                                res = JANUS_IO.AutoONControl('SET', myApp.AUTOON)            
                                if (res == -1):
                                    return #Errored out
                                elif (res == -2):
                                    JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n")
                                elif (res == 1):
                                    JANUS_SER.sendUART("Auto ON Enabled. \r\n")

                            #If Auto-on is ON and we want it OFF, set it.
                            if (res == 1 and myApp.AUTOON == 'OFF'):
                                res = JANUS_IO.AutoONControl('SET', myApp.AUTOON)
                                if (res == -1):
                                    return #Errored out
                                elif (res == -2):
                                    JANUS_SER.sendUART("Timed out while waiting for MCU response. \r\n")
                                elif (res == 0):
                                    JANUS_SER.sendUART("Auto ON Disabled. \r\n")                          

                        elif (res == '-1'):
                            #Exception
                            return

                    #If interval timer expires then send packet to server
                    if (timerB.isexpired() or FirstTimeThrough == 'TRUE'):
                        
                        #The first time we drop into this loop we want to send data immediately, after that it's timer based sends.
                        FirstTimeThrough = 'FALSE' #Disable the flag
                        
                    #######################
                    ##BEGIN BUILDING STRING
                        #If we were woken up by one of the inputs, add it to the string to be sent
                        #This section can be used/altered to perhaps only display the wake up event for a certain amount of sends.
                        if (WakeupCause != ''):
                            WakeupString = WakeupCause
                            #JANUS_SER.sendUART("Wake up Event : " + WakeupCause + "\r\n")
                            #res = GPRS.send_CM("Wake up Event : " + WakeupCause + "\r\n",1,10)
                            #WakeupCause = '' #Clear the cause so it only gets reported the first time
                        else:
                            WakeupString = ''

                        #Build String to send to customer server, adjusts depending on what we want reported. Can only be one of these.
                        #CW Google Earth format
                        #STA = NMEA + ',' + IMEI + ',' + String1 + ',' + String2 + ',' + String3
                        #Strings 1/2/3 should remain in all sentences sent, but become null ('') when not being sent.
                        #The Strings follow a standard display format for the demo, so only send the actual information based on this format:
                        #String 1 will display in the Demo as "Switch"
                        #String 2 will display in the Demo as "Ignition"
                        #String 3 will display in the Demo as "Wake up Event"
                        if (myApp.NOSWITCH == 'TRUE' and myApp.IGNITION == 'TRUE'):
                            STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + SwitchPos + ',' + IgnPos + ',' + WakeupString
                        elif (myApp.NOSWITCH == 'TRUE' and myApp.IGNITION == 'FALSE'):
                            STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + SwitchPos + ',' + "" + ',' + WakeupString
                        elif (myApp.NOSWITCH == 'FALSE' and myApp.IGNITION == 'TRUE'):
                            STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + "" + ',' + IgnPos + ',' + WakeupString
                        elif (myApp.NOSWITCH == 'FALSE' and myApp.IGNITION == 'FALSE'):
                           STA = GPSPositionTemp + ',' + ATC.properties.IMEI + ',' + "" + ',' + "" + ',' + WakeupString

                        #Concatenate string, this allows store and forward during disconnects.
                        #STA is refreshed every time through, SENDSTRING is only cleared after a successful send
                        #Let's say 100B per string
                        #Max string length is 16kB, giving us (safely) 100 data points to store.
                        #This can be improved upon by utilizing a list, since each element in a list is capable of 16kB
                        #with a possible 4000 elements (keeping in mind overall memory limits)
                        if (StringCount < 100):
                            SENDSTRING.append(STA)
                            StringCount = StringCount+1
                        else:
                            JANUS_SER.sendUART("Store and forward limit reached (100). \r\n\r\n")
                    #######################
                    ##END BUILDING STRING

                        ###############################################################
                        ##### Socket Open Check
                        #If socket closed, open it
                        DCD = MDM.getDCD()
                        #Check for a valid SS too
                        res = ATC.sendAtCmd('AT#SS',ATC.properties.CMD_TERMINATOR,0,20)

                        #If there is not a valid DCD OR the socket status shows that there is no socket open.
                        #We check for both because DCD seems to get stuck on 1 under certain conditions and we cannot set it, yet SS works fine.
                        if (DCD == 0 or res == "#SS: 1,0"): 
                            JANUS_SER.sendUART("Opening socket to server: " + myApp.IP + ":" + myApp.PORT + "\r\n")
                            #Connect to customer's server
                            res = GPRS.openSocket(myApp.IP,myApp.PORT,1,myApp.USERNAME,myApp.PASSWORD,myApp.PROTOCOL,1)
                            if (res != 0):
                                JANUS_SER.sendUART("Connection failed to open. \r\n")
                                #Turn OFF the LED permanently until we have a valid connection
                                res = JANUS_IO.GPS_LED('OFF', myApp.ULED)
                            elif (res == 0):
                                JANUS_SER.sendUART("Socket opened successfully.\r\n")
                                #Turn ON the LED to show we have a valid connection
                                res = JANUS_IO.GPS_LED('ON', myApp.ULED)
                                JANUS_SER.sendUART("Polling GPS receiver for current location every " +  myApp.INTERVAL + " second(s)\r\n")                             

                            #Do not return, end of this loop will handle the service checking
                        ###############################################################
                        ##### Socket Open Check
                        try:
                            #If socket open upload data
                            DCD = MDM.getDCD()
                            #Check for a valid SS too
                            res = ATC.sendAtCmd('AT#SS',ATC.properties.CMD_TERMINATOR,0,20)

                            #If there is a valid DCD AND the socket status shows that there is a valid socket connection too.
                            #We check for both because DCD seems to get stuck on 1 under certain conditions and we cannot set it, yet SS works fine.
                            if (DCD == 1 and res != "#SS: 1,0"):

                                #Update the GPS LED. This will turn the LED on/off during run time if it has been updated via SMS.
                                #Defaulted to ON
                                res = JANUS_IO.GPS_LED('ON', myApp.ULED)

                                #####Placeholder for built string OLD spot

                                #Strip the last entry of the pipe
                                #Pop the last item out, remove the last byte (the pipe) then append it back to the list.
                                #This covers single sends and block sends
##                                LastItem = SENDSTRING.pop(StringCount-1)
##                                ItemLength = len(LastItem)
##                                LastItem = LastItem[0:ItemLength-1]
##                                SENDSTRING.append(LastItem)

                                JANUS_SER.sendUART("Sending data: \r\n")

                                res = 0
                                x = 0
                                while (res == 0 and x < StringCount):
                                    #Send Data
                                    JANUS_SER.sendUART(str(SENDSTRING[x]) + "\r\n")
                                    res = GPRS.send_CM(SENDSTRING[x],1,10)
                                    x = x+1

                                if (res == 1):
                                    JANUS_SER.sendUART("\r\n\r\nData Empty, Error receiving info from GPS module\r\n")
                                    return
                                if (res == -2):
                                    JANUS_SER.sendUART("\r\n\r\nTimed out while sending data, checking socket connection\r\n") #Do not return, drop to service checks
                                    #Add the pipe to the end again since this got disconnected mid-send procedure and will become a store and forward send.
##                                    LastItem = SENDSTRING.pop(StringCount-1)
##                                    LastItem = LastItem + '|'
##                                    SENDSTRING.append(LastItem)
                                else:
                                    JANUS_SER.sendUART("\r\n\r\nData Sent Successfully.\r\n\r\n")
                                    #Blink OFF the LED to indicate data was sent
                                    res = JANUS_IO.GPS_LED('OFF', myApp.ULED)
                                    res = JANUS_IO.GPS_LED('ON', myApp.ULED)


                                    if (IgnPos == 'Inactive' and myApp.AUTOON == 'OFF' and myApp.IGNITIONFOLLOW == 'TRUE'):
                                        #Special Case, auto-on is not active and we want to only be active while the ignition is active.
                                        #Inigition has dropped, we've sent the last data packet, now shut the unit down
                                        res = ATC.sendAtCmd('AT#SHDN',ATC.properties.CMD_TERMINATOR,0,20)

                                    #Put the Switch and Ignition I/O back to default, clear the list and counter
                                    SwitchPos = 'Open'
                                    IgnPos = 'Inactive'
                                    SENDSTRING = []
                                    StringCount = 0
                                
                                #Exit data mode
                                #DEBUG.sendMsg('Exiting data mode\r\n') 
                                #res = ATC.exitSocketDataMode()

                                #Close Socket
                                #Pass in: sockNum
                                #res = ATC.closeSocket('1')
                                #DEBUG.sendMsg('Connection closed\r\n') 

                                break

                            else:
                                JANUS_SER.sendUART("\r\nConnection not available, checking status.\r\n")

                                #Wait until module is registered to GSM Network
                                #res = NETWORK.isGsmRegistered(180)  #Wait 180 seconds for module to obtain GSM registration
                                #if (res == -1):
                                #    ATC.reboot()

                                #Wait until module is attached to GPRS    
                                #res = NETWORK.isGprsAttached(180)  #Wait 180 seconds for module to obtain GPRS Attachment
                                #if (res == -1):
                                #    ATC.reboot()

                                #What is the signal strength?
                                res = ATC.sendAtCmd('AT+CSQ',ATC.properties.CMD_TERMINATOR,0,5)
                                JANUS_SER.sendUART("Signal Strength (AT+CSQ): " + res + "\r\n")

                                #Still registered?
                                res = ATC.sendAtCmd('AT+CREG?',ATC.properties.CMD_TERMINATOR,0,5)
                                JANUS_SER.sendUART("Registration Check (AT+CREG?): " + res + "\r\n")

                                #GPRS Available?
                                res = ATC.sendAtCmd('AT+CGREG?',ATC.properties.CMD_TERMINATOR,0,5)
                                JANUS_SER.sendUART("GPRS  Availability (AT+CGREG?): " + res + "\r\n")                                

                                #Is a PDP context activated?
                                res = ATC.sendAtCmd('AT#SGACT?',ATC.properties.CMD_TERMINATOR,0,20)
                                JANUS_SER.sendUART("PDP Context status (AT#SGACT?): " + res + "\r\n\r\n")

                                break                             

                        except:
                            JANUS_SER.sendUART("Script encountered an exception while uploading data to server\r\n")
                            JANUS_SER.sendUART("Exception Type: " + str(sys.exc_type) + "\r\n")
                            JANUS_SER.sendUART("MODULE -> LobosTrack\r\n")
                            break

                ## Re-Start timeout timer
                timerB = timers.timer(0)
                timerB.start(int(myApp.INTERVAL))

                #DEBUG.CLS()   #Clear screen command for VT100 terminals

    except:
        print "Script encountered an exception"
        print "Exception Type: " + str(sys.exc_type)
        print "MODULE -> TerminusS2E"
        
    return
Example #4
0
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