Example #1
0
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
    #
    #   Returns:
    #    0: Pass
    #   -1: Exception
    
    tmpReturn = -1

    try:
        
        #Set Stat LED to default value, 0 for OFF, 2 for ON
        if (inSLED == 'ON'):
            res = GPIO.setSLED(2, 10, 90)
        else:
            res = GPIO.setSLED(0, 10, 90)

        res = ATC.sendAtCmd('AT#SLEDSAV',ATC.properties.CMD_TERMINATOR,0,20)
        if (res == -1): #Errored out, 1 if no error -1 if error
            return tmpReturn
            

        tmpReturn = 0        

    except:
        printException("Cellular_LED")
        JANUS_SER.sendUART("GPS LED exception. \r\n")  


    return tmpReturn
Example #2
0
def Class2List(inClass):
    #Takes the input class and converts it into a string list for writing
    # Input Parameter Definitions
    #   inClass: input class to convert to standard layout string for writing
    #
    #   Returns:
    #    String: Returns the created string
    #   -1: Exception
    
    ##  Standard Layout  
    ##    BAND = ''
    ##    NETWORK = ''
    ##    APN = ''
    ##    IP = ''
    ##    PORT = ''
    ##    PROTOCOL = ''
    ##    USERNAME = ''
    ##    PASSWORD = ''
    ##    SMS_ENABLED = ''
    ##    SMS = ''
    ##    INTERVAL = ''
    ##    LNA = ''
    ##    NOSWITCH = ''
    ##    IGNITION = ''
    ##    SLED = ''
    ##    ULED = ''
    ##    AUTOON = ''
    ##    IGNITIONFOLLOW = ''

    
    tmpReturn = -1
    try:
        #Create list in the form of the class, ending each with \r\n
        ConfigList = str("BAND = " + str(inClass.BAND) + "\r\n" +
                        "NETWORK = " + str(inClass.NETWORK) + "\r\n"
                        "APN = " + inClass.APN + "\r\n"
                        "IP = " + inClass.IP + "\r\n"
                        "PORT = " + inClass.PORT + "\r\n"
                        "PROTOCOL = " + inClass.PROTOCOL + "\r\n"
                        "USERNAME = "******"\r\n"
                        "PASSWORD = "******"\r\n"
                        "SMS_ENABLED = " + inClass.SMS_ENABLED + "\r\n"
                        "SMS = " + inClass.SMS + "\r\n"
                        "INTERVAL = " + inClass.INTERVAL + "\r\n"
                        "LNA = " + inClass.LNA + "\r\n"
                        "NOSWITCH = " + inClass.NOSWITCH + "\r\n"
                        "IGNITION = " + inClass.IGNITION + "\r\n"
                        "SLED = " + inClass.SLED + "\r\n"
                        "ULED = " + inClass.ULED + "\r\n"
                        "AUTOON = " + inClass.AUTOON + "\r\n"
                        "IGNITIONFOLLOW = " + inClass.IGNITIONFOLLOW)
        
        tmpReturn = ConfigList

    except:
        printException("Class2List")
        JANUS_SER.sendUART("Class2List exception. \r\n")  


    return tmpReturn
Example #3
0
def UpdateConfig():
    #Updates the current configuration file from the Config class. 
    # Input Parameter Definitions
    #   None
    #
    #   Returns:
    #    1: configuration file updated
    #   -1: Exception
    
    tmpReturn = -1

    try:

        JANUS_SER.sendUART("\r\nUpdating the configuration file: " + theFile + "\r\n")
        f = open(theFile,'w')
        #Create string list for writing
        List2 = Class2List(Config)
        
        f.write(List2)
        f.close()
        
        tmpReturn = 1

    except:
        printException("UpdateConfig")
        JANUS_SER.sendUART("UpdateConfig exception. \r\n")  

    return tmpReturn
Example #4
0
def send_CM(inSTR,connId,timeOut):
    # This function sends a string while in Command Mode
    #   Arguments:
    #   inSTR: String to send
    #   connId: Connection #
    #   timeOut: Amount of time alotted to send
    #
    #   Returns:
    #    0: Pass
    #    1: String argument empty
    #   -1: Exception
    #   -2: Timeout
    
    if (len(inSTR)==0):
        return 1

    try:

        res = MDM.send('AT#SSEND=' + str(connId) + '\r\n', 0)   

        #Start timeout counter        
        timerA = timers.timer(0)
        timerA.start(timeOut)

        prompt = '\r\n> '

        #Start looking for '\r\n>'
        while(1):

            properties.CMD_BUFFER = properties.CMD_BUFFER + MDM.receive(1)      
            pos1 = properties.CMD_BUFFER.find(prompt)   #look for prompt characters
            if (pos1>=0):
                properties.CMD_BUFFER = properties.CMD_BUFFER[0:pos1] + properties.CMD_BUFFER[pos1+len(prompt):len(properties.CMD_BUFFER)]
                res = MDM.send(inSTR, 0)
                res = MDM.sendbyte(0x1a, 0)       
                
                tempread = ''
                res = ''
                while(1):
                    tempread = MDM.read()
                    if (tempread != ''):
                        res = res + tempread

                    if (res.find('OK')>=0):
                        return (0)    #Pass
                    
                    if timerA.isexpired():
                        return (-2)    #Expired, can't find OK response

            if timerA.isexpired():
                return (-2)    #Expired, no prompt found

    except:
        printException("send_CM(" + inSTR + "," + connId + "," + timeOut + ")")
        JANUS_SER.sendUART("Send CM Exception. \r\n")  

    #Would return with something else before this if it passes without exception
    return (-1) 
Example #5
0
def SW_IGN_Status():
    # This function reads the status of the event triggers, then toggles GPIO2 in response to signal the MCU that we received the information.
    # We are reading the MCU's signaling because it can poll and latch the states more accurately than directly reading in the python flow.
    # This allows less errors when reading the states in real time as well as catching a wake up event.
    #   Arguments:
    #   none
    #
    #   Returns:
    #    0: Pass, Switch is triggered
    #    1: Pass, Ignition is triggered
    #    2: Pass, BOTH are triggered
    #   -1: Exception
    #   -2: Pass, Neither is triggered
    
    tmpReturn = -1

    try:        
        
        #GPIO.getIOvalue(GPIOnumber)
        #    7 - IIC SDA/IGNITION : Utilizing this as Event Ignition Flag, active LOW
        #    8 - IIC SCL/SWITCH : Utilizing this as Event N/O Switch Flag, active LOW

        #GPIO.setIOvalue(GPIOnumber, value)      
        #    10 - GPIO2 : Utilizing this as the event received verification, active HIGH
        
        IgnRead = GPIO.getIOvalue(7)        
        SwitchRead = GPIO.getIOvalue(8) 

        if (IgnRead == 0 and SwitchRead == 1):  #Ignition Active, based on signal from MCU
            res = GPIO.setIOvalue(10, 1)
            tmpReturn = 1
        elif (IgnRead == 1 and SwitchRead == 0): #Switch Active, based on signal from MCU
            res = GPIO.setIOvalue(10, 1)
            tmpReturn = 0
        elif (IgnRead == 0 and SwitchRead == 0): #Both Active, based on signal from MCU
            res = GPIO.setIOvalue(10, 1)
            tmpReturn = 2
        elif (IgnRead == 1 and SwitchRead == 1): #Neither Active, based on signal from MCU
            tmpReturn = -2

        if (tmpReturn != -1):
            res = GPIO.setIOvalue(10, 0) #Reset the GPIO signaling


    except:
        printException("SW_IGN Exception")
        JANUS_SER.sendUART("SW_IGN Exception \r\n")  

    #Return value of GPIO get
    return tmpReturn
Example #6
0
def init(LNA_Arg):
    # This function initializes the GPS
    #   Arguments:
    #   LNA_Arg: External LNA? TRUE or FALSE
    #
    #   Returns:
    #    0: Pass
    #   -1: Exception
    #   -2: AT command ERROR

    tmpReturn = -1

    try:

        res = ATC.sendAtCmd(
            "AT$GPSD?", ATC.properties.CMD_TERMINATOR, 0, 2
        )  # query if the modem is in "controlled" mode, required for this tracking unit.
        if res != "$GPSD: 2":
            res = ATC.sendAtCmd("AT$GPSD=2", ATC.properties.CMD_TERMINATOR, 0, 2)  # If it's not set, set it.

        # Check if the GPS command failed out
        if res == "ERROR":
            return -2

        if LNA_Arg == "TRUE":  # Query if we have an active GPS antenna with powered LNA
            res = ATC.sendAtCmd(
                "AT$GPSAT=1", ATC.properties.CMD_TERMINATOR, 0, 2
            )  # We do, so turn OFF the internal LNA to avoid oversaturation.
        else:
            res = ATC.sendAtCmd(
                "AT$GPSAT=0", ATC.properties.CMD_TERMINATOR, 0, 2
            )  # We do not, it's passive, so turn ON the internal LNA

        # Check if the GPS command failed out
        if res == "ERROR":
            return -2

        # Turn the GPS ON
        GPS.powerOnOff(1)

        # No errors
        tmpReturn = 0

    except:
        printException("GPS_Init")
        JANUS_SER.sendUART("GPS Init exception. \r\n")

    return tmpReturn
Example #7
0
def GPS_LED(inStatus, inActive):
    # This function initializes the IO
    #   Arguments:
    #   inStatus : GPS LED status. Pass in either 'ON' or 'OFF'
    #       OFF - LED always OFF
    #       ON - LED always ON
    #   inActive : GPS LED Usage. Pass in either 'ON' or 'OFF'
    #       OFF - LED is not used, ignore LED commands
    #       ON - LED is used, allow LED commands
    #
    #   Returns:
    #    0: Pass
    #   -1: Exception

    if (inActive == 'OFF'): #We are not using the LED, permanently turn it off and return as passing
        res = GPIO.setIOvalue(5, 0)
        return 0
    
    tmpReturn = -1

    try:
        
        #GPIO.setIOvalue(GPIOnumber, value)
        #    5 - GPS LED (User LED)
        if (inStatus == 'OFF'):
            res = GPIO.setIOvalue(5, 0)
        elif (inStatus == 'ON'):
            res = GPIO.setIOvalue(5, 1)

            
        if (res == -1):
            return tmpReturn    #Errored out, 1 if no error -1 if error
            

        tmpReturn = 0        

    except:
        printException("GPS_LED")
        JANUS_SER.sendUART("GPS LED exception. \r\n")  


    return tmpReturn
Example #8
0
def init(inSLED):
    # This function initializes the IO
    #   Arguments:
    #   inSLED : Stat LED. Pass in either 'ON' or 'OFF'
    #       OFF - LED always OFF
    #       ON - LED follows registration status
    #   
    #
    #   Returns:
    #    0: Pass
    #   -1: Exception

    #GPIO Connections:
    #    1 - Do not utilize (Required by GPS)
    #    2 - IGNITION, LOW when ignition is active
    #    3 - N/O Switch, HIGH when the switch is closed
    #    4 - Do not utilize (Required by GPS)
    #    5 - GPS LED (User LED)
    #    6 - Auto ON Control, pulse HIGH to toggle the MCU's operative state. use GPIO1 to verify the state
    #    7 - IIC SDA : Utilizing this as Wake up Event Ignition Flag. Pulled high externally
    #    8 - IIC SCL : Utilizing this as Wake up Event N/O Switch Flag. Pulled high externally
    #    9 - GPIO1 : Utilizing this for Auto-On Verification FROM the MCU, 1 for auto-on enabled, 0 for auto-on disabled
    #    10 - GPIO2 : Utilizing this for Wake up Event verification TO the MCU, 1 if Event has been seen/recorded, otherwise 0.

    
    tmpReturn = -1

    try:
        
        #Set Stat LED to default value, 0 for OFF, 2 for ON
        if (inSLED == 'ON'):
            res = GPIO.setSLED(2, 10, 90)
        else:
            res = GPIO.setSLED(0, 10, 90)

        if (res == -1): #Errored out, 1 if no error -1 if error
            return tmpReturn
        
        #Now set all used GPIO to proper states.
        #GPIO.setIOvalue(GPIOnumber, value)
        #We do not need the above command, setIODir works best for this.
        #GPIO.setIOdir(number, value, direction)
        
        a = GPIO.setIOdir(2, 0, 0)  #Input
        b = GPIO.setIOdir(3, 0, 0)  #Input
        c = GPIO.setIOdir(5, 0, 1)  #Output, LOW (LED OFF)
        d = GPIO.setIOdir(6, 1, 0)  #Output, LOW (Auto-on OFF during INIT, taken care of in the command flow)
        e = GPIO.setIOdir(7, 0, 0)  #Input
        f = GPIO.setIOdir(8, 0, 0)  #Input
        g = GPIO.setIOdir(9, 0, 0)  #Input
        h = GPIO.setIOdir(10, 0, 1)  #Output, LOW (Wake up Event verification default sate, event NOT found)

        if (    a == -1
            or b == -1
            or c == -1
            or d == -1
            or e == -1
            or f == -1
            or g == -1
            or h == -1
            ):
            return tmpReturn    #Errored out, 1 if no error -1 if error
            

        tmpReturn = 0        

    except:
        printException("IO_init")
        JANUS_SER.sendUART("IO Init exception. \r\n")  


    return tmpReturn
Example #9
0
def AutoONControl(inCommand, inSelection):
    # This function sends a signal to MCU to tell it whether or not to handle Auto On,
    # waits for response on GPIO1 to verify the MCU is in the proper state.
    #   Arguments:
    #   inCommand - Select what to do, enter 'READ' or 'SET'.
    #       READ - Checks the MCU signal to verify the mode
    #       SET - Utilizes inSelection to change the mode.
    #   inSelection - Select to have the MCU run Auto-On or not, enter 'ON' or 'OFF.
    #       OFF - Auto-On is Disabled
    #       ON - Auto-On is Enabled
    #
    #   Returns:
    #       InCommand: READ
    #           0: Pass, Auto-on OFF
    #           1: Pass, Auto-on ON
    #           -1: Exception
    #           -2: Time out
    #       InCommand: SET
    #           0: Pass, Auto-on OFF
    #           1: Pass, Auto-on ON
    #           -1: Exception
    #           -2: Time out
    
    tmpReturn = -1

    try:        
        
        #GPIO.getIOvalue(GPIOnumber)
        #MOD.sleep(20) #Delay 
        #    9 - GPIO1 : Used as MCU signal verification
        
        if (inCommand == 'READ'):
            res = GPIO.getIOvalue(9)
            return res

        #GPIO.setIOvalue(GPIOnumber, value)
        #    6 - Auto ON Control
        #    9 - GPIO1 : Used as MCU signal verification
        if (inSelection == 'ON'): 
            res = GPIO.setIOvalue(6, 1)

            #Set a Timer for a quick loop to verify, we do this because it's a "just in case" breakout as opposed to a simple delay and check.
            timerA = timers.timer(0)
            timerA.start(5)    #5 seconds is MORE than enough.

            IoVal = GPIO.getIOvalue(9)
            #JANUS_SER.sendUART("Value from MCU: " + str(IoVal) + "\r\n")
            
            while (IoVal != 1):
                IoVal = GPIO.getIOvalue(9)
                if timerA.isexpired():
                    return (-2) #Time out while finding the signal


            res = GPIO.setIOvalue(6, 0) #End the HIGH pulse, MCU only toggles on a high signal
            return IoVal #Return the read value          
                
        elif (inSelection == 'OFF'):
            res = GPIO.setIOvalue(6, 1)

            #Set a Timer for a quick loop to verify, we do this because it's a "just in case" breakout as opposed to a simple delay and check.
            timerA = timers.timer(0)
            timerA.start(5)    #5 seconds is MORE than enough.

            IoVal = GPIO.getIOvalue(9)
            JANUS_SER.sendUART("Value from MCU: " + str(IoVal) + "\r\n")
            
            while (IoVal != 0):
                IoVal = GPIO.getIOvalue(9)
                if timerA.isexpired():
                    return (-2) #Time out while finding the signal


            res = GPIO.setIOvalue(6, 0) #End the HIGH pulse, MCU only toggles on a high signal  
            return IoVal #Return the read value


    except:
        printException("SW_IGN Exception")
        JANUS_SER.sendUART("SW_IGN Exception \r\n")  

    #Return Error value
    return tmpReturn
Example #10
0
def init():
    #Initializes the configuration for application use
    # Input Parameter Definitions
    #   None
    #
    #   Returns:
    #    0: Defaults being used
    #    1: Saved Configuration file values being used
    #   -1: Exception, main app will load defaults

    JANUS_SER.sendUART("Initializing The Configuration. \r\n")
    
    tmpReturn = -1
    #This will first check if there is a configuration file. If there is not one it will create one with the default configuration, transposing that default configuration
    #To the application's class for usage. If there is one it will read the configuration and load it into the application's class for usage.

    #Fill the default values from the user entered data. This data will be used if there are issues with the configuration file
    res = FillDefault()

    # Check if the configuration file exists (this is only really for the first runthrough)
    try:
        f = open(theFile,'r')
        NoFile = 'False'
    except:
        #No file found, flag it
        JANUS_SER.sendUART("Configuration file does not exist. \r\n")
        NoFile = 'True'
        
    #If successful the file is now open for reading, otherwise create a new default file

    try:
        if (NoFile == 'True'):
            #No file found, create one from the default configuration
            JANUS_SER.sendUART("Creating File With Default Values. \r\n")
            f = open(theFile,'w')

            #Create a string list to write to the file
            DefaultList = Class2List(DefaultConfig)
            f.write(DefaultList)
            f.close()
            
            JANUS_SER.sendUART("Settings file created.\r\n")

##            #Before we finish, let's read it back and populate the Config fields
##            #Otherwise if we were to save after loading defaults, we may accidentally write
##            #blank information to the file
##            f = open(theFile,'r')
##            filedump = f.read()
##            f.close()
##
##            list1 = filedump.split('\r\n')       
##            res = List2Config(list1)

            #Return 0 to indicate we are using default values
            if (res == 0):
                tmpReturn = 0
            
        else:
            #Read the file
            JANUS_SER.sendUART("File Found, loading values. \r\n")
            filedump = f.read()
            f.close()
            
            list1 = filedump.split('\r\n')       
            res = List2Config(list1)

            #Return 1 to indicate configuration file values are being loaded
            if (res == 0):
                tmpReturn = 1
        
    except:
        JANUS_SER.sendUART("Error with file manipulation. \r\n")

    return tmpReturn
Example #11
0
def FillDefault():
    #Fills out the default list from the user entered information below.
    # Input Parameter Definitions
    #   None
    #
    #   Returns:
    #    0: Pass
    #   -1: Exception

    
    tmpReturn = -1

    try:
##############################################################################################
##Begin User Entered Values
##############################################################################################

        ## BAND
        ## Please refer to AT Command guide for AT#BND
        ## If Terminal used in North America (BAND = '3')
        DefaultConfig.BAND = '3'

        ## NETWORK
        ## If Terminal used on ATT / Cingular in North America (NETWORK = 'ATT')
        ## Else (NETWORK = 'GSM')
        DefaultConfig.NETWORK = 'ATT'

        ## APN
        ## Gateway Address for GPRS traffic
        ## This setting is GSM Provider and possible customer specific when a VPN is used
        ## This demo is defaulted with 'internet' that is used for ATT wireless settings from pre-Cingular days
        ## You MUST obtain the APN setting for your GSM account.  Please call GSM provider!  Janus can't help you with this.
        DefaultConfig.APN = 'gprs02.motient.net'

        ## IP
        ## IP address of server on the Internet which Terminus will connect to send and receive data
        ## Address in this example is not operational for customer evaluation.  Customer must have their own server
        ## setup to interact with this demo.
        ## IP = 'xxx.xxx.xxx.xxx'
        DefaultConfig.IP = '12.237.120.180'

        ## PORT
        ## PORT number of server on the Internet which Terminus will connect to send and receive data
        ## PORT number in this example is not operational for customer evaluation.  Customer must have their own server
        ## setup to interact with this demo.
        DefaultConfig.PORT = '7777'

        ## PROTOCOL
        ## If customer is using TCPIP (PROTOCOL = 'TCPIP')
        ## Else leave blank (PROTOCOL = '')
        DefaultConfig.PROTOCOL = 'UDP'

        ## GPRS USER NAME
        ## If GSM Provider requires GPRS User Name (USERNAME = '******')
        ## Else leave blank (USERNAME = '')
        DefaultConfig.USERNAME = ''

        ## GPRS PASSWORD
        ## If GSM Provider requires GPRS Password (PASSWORD = '******')
        ## Else leave blank (PASSWORD = '')
        DefaultConfig.PASSWORD = ''

        ## SMS_ENABLED
        ## SMS Enabled? (SMS_ENABLED = 'TRUE' or 'FALSE')
        DefaultConfig.SMS_ENABLED = 'TRUE'

        ## SMS
        ## SMS Designation phone number (SMS = '+16305551212')
        ## Although this number is put into the settings and checked for validity when pulled in from the configuration file, it's not used.
        ## For simplicity, the SMS functions of this demo take the incoming SMS and parse the originating phone number, replying to that phone number.
        DefaultConfig.SMS = '+16305551212'

        ## INTERVAL
        ## How many seconds the demo will wait before sending new GPS data to server. Valid range is 1 to 86400
        ## In this demo, GPS data will be sent every 10 seconds (INTERVAL = '10')
        DefaultConfig.INTERVAL = '10'

        ## Antenna LNA
        ## Does the external antenna have an LNA that needs to be powered, meaning is it an active antenna (bias voltage supplied by the tracker)?
        ## If the antenna is not an active type, enter 'FALSE', otherwise 'TRUE'
        DefaultConfig.LNA = 'TRUE'

        ## Switch Input
        ## Are we utilizing the input N/O switch?
        ## If we are going to use/monitor the switch, enter 'TRUE', otherwise 'FALSE'
        DefaultConfig.NOSWITCH = 'TRUE'

        ## Ignition Input
        ## Are we utilizing the Ignition input?
        ## If we are going to use/monitor the ignition, enter 'TRUE', otherwise 'FALSE'
        DefaultConfig.IGNITION = 'TRUE'

        ## Cellular Stat LED
        ## Do we want it active, or not?
        ## If we are going to have it active, enter 'ON', otherwise 'OFF'
        DefaultConfig.SLED = 'ON'

        ## GPS/User LED
        ## Do we want it active, or not?
        ## If we are going to have it active, enter 'ON', otherwise 'OFF'
        DefaultConfig.ULED = 'ON'

        ## Auto-On Control
        ## Do we want it active, or not?
        ## If we are going to have it active, enter 'ON', otherwise 'OFF'
        DefaultConfig.AUTOON = 'OFF'

        ## Ignition Follow Control
        ## This flag controls if we will be following the ignition signal for being on and reporting.
        ## If this is set, the unit will continue to report until the Ignition line becomes inactive.
        ## At that point, it will send a final report showing this, and then shut down.
        ## Note that this should only be used if AUTOON is OFF, otherwise the unit will just continue to
        ## automatically power up and power down if the ignition signal is inactive (car/truck is off).
        ## This is useful for power savings also, since the unit will be idle until it's needed,
        ## drawing minimal current from the battery.
        ## If we are going to have it active, enter 'TRUE', otherwise 'FALSE'
        DefaultConfig.IGNITIONFOLLOW = 'TRUE'


##############################################################################################
##End User Entered Values
##############################################################################################


        #Now we fill the "Config" class with the default values to initialize the class. All the data will be updated from the configuration file when List2Class is run.
        #However, in the case that the configuration file becomes corrupt, unreadable, or doesn't contain valid data, the default values shall be used.
        Config.BAND = DefaultConfig.BAND
        Config.NETWORK = DefaultConfig.NETWORK
        Config.APN = DefaultConfig.APN
        Config.IP = DefaultConfig.IP
        Config.PORT = DefaultConfig.PORT
        Config.PROTOCOL = DefaultConfig.PROTOCOL
        Config.USERNAME = DefaultConfig.USERNAME
        Config.PASSWORD = DefaultConfig.PASSWORD
        Config.SMS_ENABLED = DefaultConfig.SMS_ENABLED
        Config.SMS = DefaultConfig.SMS
        Config.INTERVAL = DefaultConfig.INTERVAL
        Config.LNA = DefaultConfig.LNA
        Config.NOSWITCH = DefaultConfig.NOSWITCH
        Config.IGNITION = DefaultConfig.IGNITION
        Config.SLED = DefaultConfig.SLED
        Config.ULED = DefaultConfig.ULED
        Config.AUTOON = DefaultConfig.AUTOON
        Config.IGNITIONFOLLOW = DefaultConfig.IGNITIONFOLLOW

        tmpReturn = 0


    except:
        printException("FillDefault")
        JANUS_SER.sendUART("FillDefault exception. \r\n")  


    return tmpReturn   
Example #12
0
def List2Config(inList):
    #Takes the input List and converts it into the Config class for application usage.
    #If an entry pulled from the configuration file is unrecognizable/incorrect/entered wrong it will bypass and use the default value.
    # Input Parameter Definitions
    #   inList: input list derived from the read configuration file
    #
    #   Returns:
    #    0: Pass
    #    1: Configuration file length not valid
    #   -1: Exception
    
    ##  Standard Layout  
    ##    BAND = ''
    ##    NETWORK = ''
    ##    APN = ''
    ##    IP = ''
    ##    PORT = ''
    ##    PROTOCOL = ''
    ##    USERNAME = ''
    ##    PASSWORD = ''
    ##    SMS_ENABLED = ''
    ##    SMS = ''
    ##    INTERVAL = ''
    ##    LNA = ''
    ##    NOSWITCH = ''
    ##    IGNITION = ''
    ##    SLED = ''
    ##    ULED = ''
    ##    AUTOON = ''
    ##    IGNITIONFOLLOW = ''

    
    tmpReturn = -1

    try:
        
        if (len(inList)> 0):
            JANUS_SER.sendUART(str(len(inList)) + " of 18 entries found \r\n")  
            for x in inList:
                #JANUS_SER.sendUART(str(x) + "\r\n")  
                #We know the "=" will be found at 0 and 2 characters after it will start until the
                #end of the line. It's split previously by \r\n so there is no \r\n to locate at the end
                posbegin = x.find('=',0,len(x))

                #We have our position, now let's find the entry type and data
                entryType = x[0:posbegin-1]
                entryData = x[posbegin+2:len(x)]

                if (entryType == "BAND"):
                    #Verify BAND is a number between 0 and 3
                    try:
                        if ((int(entryData) < 0) or (int(entryData) > 3)):
                            JANUS_SER.sendUART("BAND out of range: " + str(entryData) + "\r\n")
                            JANUS_SER.sendUART("Using Default Value: " + str(Config.BAND) + "\r\n")
                        else:
                            #Passes, use the value
                            Config.BAND = entryData
                    except:
                        JANUS_SER.sendUART("BAND not a valid integer: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.BAND) + "\r\n")
                elif (entryType == "NETWORK"):
                    if ((entryData != 'ATT') and (entryData != 'GSM')):
                        JANUS_SER.sendUART("NETWORK not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.NETWORK) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.NETWORK = entryData
                elif (entryType == "APN"):
                    #Not sure on how to test this yet, just use the value
                    Config.APN = entryData
                elif (entryType == "IP"):
                    tmp_list = entryData.split('.')
                    #Does IP address have 4 Octets?
                    if (len(tmp_list)==4):
                        errorflag = 0
                        for y in tmp_list:
                            #Verify each octet is a number between 0 and 255
                            try:
                                if ((int(y) < 0) or (int(y) > 255)):
                                    JANUS_SER.sendUART("Octet " + str(y) + " out of range: " + str(entryData) + "\r\n")
                                    JANUS_SER.sendUART("Using Default Value: " + str(Config.IP) + "\r\n")
                                    errorflag = 1
                            except:
                                JANUS_SER.sendUART("Octet " + str(y) + " not a valid integer: " + str(entryData) + "\r\n")
                                JANUS_SER.sendUART("Using Default Value: " + str(Config.IP) + "\r\n")
                                errorflag = 1
                        if (errorflag == 0):
                            #Passes without error, use the value
                            Config.IP = entryData
                    else:
                        JANUS_SER.sendUART("IP does not have enough octets " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.IP) + "\r\n")
                elif (entryType == "PORT"):
                    #Verify PORT is a number between 0 and 65535
                    try:
                        if ((int(entryData) < 0) or (int(entryData) > 65535)):
                            JANUS_SER.sendUART("PORT out of range: " + str(entryData) + "\r\n")
                            JANUS_SER.sendUART("Using Default Value: " + str(Config.PORT) + "\r\n")
                        else:
                            #Passes, use the value
                            Config.PORT = entryData
                    except:
                            JANUS_SER.sendUART("PORT not a valid integer: " + str(entryData) + "\r\n")
                            JANUS_SER.sendUART("Using Default Value: " + str(Config.PORT) + "\r\n")
                elif (entryType == "PROTOCOL"):
                    if ((entryData != 'UDP') and (entryData != 'TCPIP')):
                        JANUS_SER.sendUART("PROTOCOL not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.PROTOCOL) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.PROTOCOL = entryData
                elif (entryType == "USERNAME"):
                    Config.USERNAME = entryData
                elif (entryType == "PASSWORD"):
                    Config.PASSWORD = entryData
                elif (entryType == "SMS_ENABLED"):
                    if ((entryData != 'TRUE') and (entryData != 'FALSE')):
                        JANUS_SER.sendUART("SMS_ENABLED not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.SMS_ENABLED) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.SMS_ENABLED = entryData
                elif (entryType == "SMS"):
                    tmpEntry = entryData.find('+',0,len(entryData))
                    if (tmpEntry != -1):
                        #Check length, should be 12 +xxxxxxxxxxx
                        if (len(entryData) == 12):
                            Config.SMS = entryData
                        else:
                            JANUS_SER.sendUART("SMS number not a valid length: " + str(entryData) + "\r\n")
                            JANUS_SER.sendUART("Using Default Value: " + str(Config.SMS) + "\r\n")
                    else:
                        JANUS_SER.sendUART("SMS number not a valid format: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.SMS) + "\r\n")
                elif (entryType == "INTERVAL"):
                    #INTERVAL is a number in seconds between 1 and 86400 (One Day Maximum)
                    try:
                        if ((int(entryData) < 1) or (int(entryData) > 86400)):
                            JANUS_SER.sendUART("INTERVAL out of range: " + str(entryData) + "\r\n")
                            JANUS_SER.sendUART("Using Default Value: " + str(Config.INTERVAL) + "\r\n")
                        else:
                            #Passes, use the value
                            Config.INTERVAL = entryData
                    except:
                        JANUS_SER.sendUART("INTERVAL not a valid integer: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.INTERVAL) + "\r\n")
                elif (entryType == "LNA"):
                    if ((entryData != 'TRUE') and (entryData != 'FALSE')):
                        JANUS_SER.sendUART("LNA not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.LNA) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.LNA = entryData
                elif (entryType == "NOSWITCH"):
                    if ((entryData != 'TRUE') and (entryData != 'FALSE')):
                        JANUS_SER.sendUART("NOSWITCH not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.NOSWITCH) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.NOSWITCH = entryData
                elif (entryType == "IGNITION"):
                    if ((entryData != 'TRUE') and (entryData != 'FALSE')):
                        JANUS_SER.sendUART("IGNITION not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.IGNITION) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.IGNITION = entryData
                elif (entryType == "SLED"):
                    if ((entryData != 'ON') and (entryData != 'OFF')):
                        JANUS_SER.sendUART("SLED not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.SLED) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.SLED = entryData
                elif (entryType == "ULED"):
                    if ((entryData != 'ON') and (entryData != 'OFF')):
                        JANUS_SER.sendUART("ULED not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.ULED) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.ULED = entryData
                elif (entryType == "AUTOON"):
                    if ((entryData != 'ON') and (entryData != 'OFF')):
                        JANUS_SER.sendUART("AUTOON not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.AUTOON) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.AUTOON = entryData
                elif (entryType == "IGNITIONFOLLOW"):
                    if ((entryData != 'TRUE') and (entryData != 'FALSE')):
                        JANUS_SER.sendUART("IGNITIONFOLLOW not valid: " + str(entryData) + "\r\n")
                        JANUS_SER.sendUART("Using Default Value: " + str(Config.IGNITIONFOLLOW) + "\r\n")
                    else:
                        #Passes, use the value
                        Config.IGNITIONFOLLOW = entryData   
                else:
                    JANUS_SER.sendUART("Unrecognized Entry, Not Set: " + str(entryType) + "\r\n")

            tmpReturn = 0
        else:
            tmpReturn = 1

    except:
        printException("String2Class")
        JANUS_SER.sendUART("String2Class exception. \r\n")  


    return tmpReturn
Example #13
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 #14
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 #15
0
def main():

    try: 

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

        res = JANUS_SER.init("115200",'8N1')
        if (res == -1):
            return
  
        #Set Network specific settings
        res = NETWORK.initGsmNetwork(myApp.NETWORK,myApp.BAND)
        if (res == -1):
            return

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

        #Inform Application that a Data Connection is not available
        JANUS_SER.set_DCD(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):

            MOD.watchdogReset()

            #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

            #############################################################################################################################
            ## Opening Socket Connection to Server
            #############################################################################################################################

            res = GPRS.openSocket(myApp.IP,myApp.PORT,1,myApp.USERNAME,myApp.PASSWORD,myApp.PROTOCOL,0)

            #Inform Application that a Data Connection is not available
            DCD = MDM.getDCD()
            if (DCD == 1):
                JANUS_SER.set_DCD(1)
                #Forward CONNECT Message to Serial Port
                JANUS_SER.sendUART('\r\nCONNECT\r\n') 

            ##Loop while Socket connected
            while(1):

                MOD.watchdogReset()

                #Forward serial port data to socket connection
                DCD = MDM.getDCD()
                if (DCD == 1):
                    #Get data from serial port
                    res = JANUS_SER.readUART()
                    if (len(res)!=0):
                        #Forward data to open socket
                        res = MDM.send(res,1)

                #Forward  socket data to serial port
                DCD = MDM.getDCD()
                if (DCD == 1):
                    #Get data from open socket connection
                    res = MDM.receive(1)
                    if (len(res)!=0):
                        #Forward socket data to serial port
                        JANUS_SER.sendUART(res) 

                #When socket is closed exit loop via this path
                #Will guarantee that '\r\nNO CARRIER\r\n' is sent every time
                DCD = MDM.getDCD()
                if (DCD == 0):
                    #Inform Application that a Data Connection is not available
                    JANUS_SER.set_DCD(0)
                    ATC.delaySec(1)
                    #Get any remaining data from closed socket connection
                    res = MDM.receive(1)
                    if (len(res)!=0):
                        #Forward socket data to serial port
                        JANUS_SER.sendUART(res)
                    break
    except:
        print "Script encountered an exception"
        print "Exception Type: " + str(sys.exc_type)
        print "MODULE -> TerminusS2E"
        
    return
Example #16
0
##--------------------------------------------------------------------------------------------------------------------
## End of Application Specific Configuration
##--------------------------------------------------------------------------------------------------------------------


##--------------------------------------------------------------------------------------------------------------------
## Main Function
##--------------------------------------------------------------------------------------------------------------------

try:

    main()
    print "Main Script Exit"

    #Inform Application that a Data Connection is not available
    JANUS_SER.set_DCD(0)
    
    #Reboot or Script will not restart until a power cycle occurs
    ATC.reboot()

except:

    print "Main Script encountered an exception"
    print "Exception Type: " + str(sys.exc_type)
    print "MODULE -> TerminusS2E"
     
    #Inform Application that a Data Connection is not available
    JANUS_SER.set_DCD(0)
    
    #Reboot or Script will not restart until a power cycle occurs
    ATC.reboot()