Example #1
0
def receiveReponse ( ):

    timeout = MOD.secCounter() + 10

    str = ""
    length = ""
    newlinepos = 0

    while ( MOD.secCounter() < timeout ):

        newlinepos = str.find("\n\r")

        if ( (newlinepos != -1) and not length ):

            newlinepos = newlinepos + 2
            pos = str.find("Content-Length:") + 15

            while ( str[pos] != '\n' ):
                length = "%s%s" % (length, str[pos])
                pos = pos + 1

            length = int(length) + newlinepos

        else:
            MOD.sleep(5)
            str = str + MDM.receive(1)

        if ( length and len(str) >= length ):
            return str[newlinepos:(newlinepos+length)]

    return 0
Example #2
0
def waitRegister():
    while(1):
        RX_API.resetWDT()
        r, d = sendAT('AT+CREG?', '+CREG: 0,1')
        if(r == 0):
            break
        MOD.sleep(20)
def SendPositionEvent(DeviceID,DateTimeStr,GPSLongitude,GPSLatitude):
    LocationC8YStr = '{"source": { "id": "'+DeviceID+'" },'
    LocationC8YStr = LocationC8YStr + '"text": "c8y_LocationUpdate",'
    LocationC8YStr = LocationC8YStr + '"time": "'+DateTimeStr
    LocationC8YStr = LocationC8YStr + '","type": "c8y_LocationUpdate",'
    LocationC8YStr = LocationC8YStr + '"c8y_Position": {"alt":0,"lng":'
    LocationC8YStr = LocationC8YStr + GPSLongitude
    LocationC8YStr = LocationC8YStr + ',"lat":'
    LocationC8YStr = LocationC8YStr + GPSLatitude
    LocationC8YStr = LocationC8YStr + '}'
    
    LocationC8YStr = LocationC8YStr + '}'
    PrintW('Sending Position to server now\r\n')
    FullPostString = 'POST /event/events HTTP/1.1\r\n'
    FullPostString = FullPostString + 'Host: '+CumulocityServer+'\r\n'
    FullPostString = FullPostString + 'Authorization: Basic ' + Device_B64_Authentication
    FullPostString = FullPostString + 'Content-Type: application/vnd.com.nsn.cumulocity.event+json\r\n'
    FullPostString = FullPostString + 'Cache-Control: no-cache\r\n'
    FullPostString = FullPostString + 'Connection: Close\r\n'
    FullPostString = FullPostString + 'Content-Length: '+str(len(LocationC8YStr))+'\r\n'
    FullPostString = FullPostString + '\r\n' 
    FullPostString = FullPostString + LocationC8YStr
    if(m_modemmanager.GetDCD()==0):
        PrintW('DCD is low')
        PrintW('Failed to send GPS position. No connection')
        return
    m_modemmanager.SendData(FullPostString)
    PrintW('Sending GPS postion to Server\r\n')
    PrintW('Post contents:\r\n'+FullPostString+'\r\n')
    MOD.sleep(2)
Example #4
0
def receiveReponse():

    timeout = MOD.secCounter() + 10

    str = ""
    length = ""
    newlinepos = 0

    while (MOD.secCounter() < timeout):

        newlinepos = str.find("\n\r")

        if ((newlinepos != -1) and not length):

            newlinepos = newlinepos + 2
            pos = str.find("Content-Length:") + 15

            while (str[pos] != '\n'):
                length = "%s%s" % (length, str[pos])
                pos = pos + 1

            length = int(length) + newlinepos

        else:
            MOD.sleep(5)
            str = str + MDM.receive(1)

        if (length and len(str) >= length):
            return str[newlinepos:(newlinepos + length)]

    return 0
Example #5
0
    def net(self):
        """	Funkcja Wprowadza komendy AT odpowiedzialne
			za komunikacje internetnetową"""
        b = ""
        i = 0
        a1, a2 = self.m_net
        list = map(\
         (lambda x,y,s=(self.settingsByKey): x + s[y][0] +'"\r'),\
         ('AT#USERID="','AT#PASSW="'),\
         ('gsmuser',"gsmpass")\
        )
        for a in a1, list, a2:
            for c in a:
                MDM.send(str(c), 10)
                i = 0
                while i < 20:
                    b = MDM.receive(10)
                    if not b:
                        i = i + 1
                        MOD.sleep(5)
                        continue
                    print "Network Initializer: ", c
                    isError(b)
                    break
                # self.ipAddr=b[:b.find("\r")]
                else:
                    print "ERROR to receive command responce."
Example #6
0
def exitSocketDataMode():

    try:
        #Exit data mode
        delaySec(11)         ##this time is based on esc sequence guard time
        #Start timeout counter        
        timerA = timers.timer(0)
        timerA.start(20)

        #Sending +++
        print 'Sending Data Mode escape sequence'
        res = MDM.send('+++', 10)


        #Wait for response
        res = ''
        while ((res.find("OK")<=-1) and (res != 'timeOut')):
            MOD.watchdogReset()
            res = res + MDM.receive(50)

            pass            
            if timerA.isexpired():
                res = 'timeOut'

    except:
        print 'Script encountered an exception.'
        print 'Exception Type: ' + str(sys.exc_type)
        print 'MODULE -> ATC'
        print 'METHOD -> exitSocketDataMode()'

    print res

    return res
Example #7
0
def mdmResponse(theTerminator, timeOut):
# This function waits for AT Command response and handles errors and ignores unsolicited responses

  # Input Parameter Definitions
  #   theTerminator: string or character at the end of a received string which indicates end of a response
  #   timeOut: number of seconds command could take to respond

    try:

        print 'Waiting for AT Command Response'

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

        #Wait for response
        res = ''
        while ((res.find(theTerminator)<=-1) and (res.find("ERROR")<=-1) and (res != 'timeOut')):
            MOD.watchdogReset()
            res = res + MDM.receive(10)

            pass            
            if timerA.isexpired():
                res = 'timeOut'

    except:
            print 'Script encountered an exception.'
            print 'Exception Type: ' + str(sys.exc_type)
            print 'MODULE -> ATC'
            print 'METHOD -> mdmResponse(' + theTerminator + ',' + timeOut + ')'

    return res
Example #8
0
def sendAndCheck(command="AT\r",
                 commit="OK",
                 s=10,
                 retryR=3,
                 retryS=1,
                 timeout=5):
    """
		Funkcja wysyła komendy AT oraz sprawdza ich
		wartość zwrotną. Wrazie nietrzymania wartości
		zwrotnej funkcja ponawia próbe jej odebrania.
		Wrazie przekroczenie limitu prób odebrania
		wartości zwrotnej ("retryR" razy). Funkcja
		ponawia próbe wywołania komendy AT (retryS razy)
	"""
    i = 0
    c = e = None
    while i < retryS:
        MDM.receive(1)
        # if a[:-1]!="\r": a+="\r"
        e = MDM.send(command, s)
        for a in range(0, retryR):
            c = MDM.receive(10)
            if c.find(commit) > -1: return 1
            MOD.sleep(timeout)
        i = i + 1
    return 0
Example #9
0
def configSMS():

    try:

        #Enable TEXT format for SMS Message
        res = sendAtCmd('AT+CMGF=1' ,properties.CMD_TERMINATOR,0,5)
        res = sendAtCmd('AT+CNMI=2,1' ,properties.CMD_TERMINATOR,0,5)

        #SIM status control - to avoid the 'sim busy' error
        print 'SIM Verification Cycle'
        SIM_status = sendAtCmd('AT+CPBS?' ,properties.CMD_TERMINATOR,0,5)

        if SIM_status.find("+CPBS")<0:
            print 'SIM busy! Please wait!\n'

        while SIM_status.find("+CPBS:")< 0 :
            SIM_status = sendAtCmd('AT+CPBS?' ,properties.CMD_TERMINATOR,0,5)
            MOD.sleep(2)
        print 'SIM Ready'

    except:
        print 'Script encountered an exception.'
        print 'Exception Type: ' + str(sys.exc_type)
        print 'MODULE -> ATC'
        print 'METHOD -> configSMS()'

    return
Example #10
0
 def sendATData(self, atcom, atres, trys=1, timeout=1, csd=1):
     mdm_timeout = int(self.config.get('TIMEOUT_MDM'))
     s = MDM.receive(mdm_timeout)
     result = -2
     while (1):
         if (csd):
             self.tryCSD()
         if (self.config.get('DEBUG_AT') == '1'):
             self.debug.send('DATA AT OUT: ' + atcom)
         s = ''
         MDM.send(atcom, mdm_timeout)
         timer = MOD.secCounter() + timeout
         while (1):
             s = s + MDM.receive(mdm_timeout)
             if (s.find(atres) != -1):
                 result = 0
                 break
             if (s.find('ERROR') != -1):
                 result = -1
                 break
             if (MOD.secCounter() > timer):
                 break
         if (self.config.get('DEBUG_AT') == '1'):
             self.debug.send('DATA AT IN: ' + s[2:])
         trys = trys - 1
         if ((trys <= 0) or (result == 0)):
             break
         MOD.sleep(15)
     return (result, s)
Example #11
0
 def sendATData(self, atcom, atres, trys = 1, timeout = 1, csd = 1):
     mdm_timeout = int(self.config.get('TIMEOUT_MDM'))
     s = MDM.receive(mdm_timeout)
     result = -2
     while(1):
         if(csd):
             self.tryCSD()
         if(self.config.get('DEBUG_AT') == '1'):
             self.debug.send('DATA AT OUT: ' + atcom)
         s = ''
         MDM.send(atcom, mdm_timeout)
         timer = MOD.secCounter() + timeout
         while(1):
             s = s + MDM.receive(mdm_timeout)
             if(s.find(atres) != -1):
                 result = 0
                 break
             if(s.find('ERROR') != -1):
                 result = -1
                 break
             if(MOD.secCounter() > timer):
                 break
         if(self.config.get('DEBUG_AT') == '1'):
             self.debug.send('DATA AT IN: ' + s[2:])
         trys = trys - 1
         if((trys <= 0) or (result == 0)):
             break
         MOD.sleep(15)
     return (result, s)
Example #12
0
    def sendATAndWait(self, mdm, atcom, atres, trys=1, timeout=1):
        mdm_timeout = int(self.config.get('TIMEOUT_MDM'))
        s = mdm.receive(mdm_timeout)
        result = -2
        while (1):
            self.debug.send('DATA AT OUT: ' + atcom)
            s = ''
            mdm.send(atcom, mdm_timeout)
            timer = MOD.secCounter() + timeout
            while (1):
                s = s + mdm.receive(mdm_timeout)
                if (s.find(atres) != -1):
                    result = 0
                    break
                if (s.find('ERROR') != -1):
                    result = -1
                    break
                if (MOD.secCounter() > timer):
                    break
            self.debug.send('DATA AT IN: ' + s[2:])
            trys = trys - 1
            if ((trys <= 0) or (result == 0)):
                break
            MOD.sleep(15)

        return (result, s)
Example #13
0
def wait4SIMReady():

    #SIM status control - to avoid the 'sim busy' error
    # The following sequence loops forever until SIM card is ready for use

    try:

        res = ATC.sendAtCmd("AT#SIMDET?",ATC.properties.CMD_TERMINATOR,0,2)             #query Sim detection style
        if (res.find("#SIMDET: 2")< 0):
            res = ATC.sendAtCmd('AT#SIMDET=2',ATC.properties.CMD_TERMINATOR,0,2)        #Ensure detection is automatic via SIMIN and not forced
            res = ATC.sendAtCmd('AT&P0',ATC.properties.CMD_TERMINATOR,0,2)              #Save Profile
            res = ATC.sendAtCmd('AT&W0',ATC.properties.CMD_TERMINATOR,0,2)              #Save Settings        

        print 'SIM Verification Cycle'
        SIM_status = ATC.sendAtCmd('AT+CPBS?' ,ATC.properties.CMD_TERMINATOR,0,5)       #We aren't using AT+CPIN? because there are too many possible answers
                                                                                        #This lets us know that the SIM is at least inserted
        if SIM_status.find("+CPBS")<0:
            print 'SIM busy! Please wait!\n'

        while SIM_status.find("+CPBS:")< 0 :
            SIM_status = ATC.sendAtCmd('AT+CPBS?' ,ATC.properties.CMD_TERMINATOR,0,5)
            MOD.sleep(2)
        print 'SIM Ready'

    except:
        printException("wait4SIMReady()")

    return
Example #14
0
    def checkConnection(self, bupsState):
        self.debug.send("Check connection")

        connected = core.FALSE
        if bupsState != None:
            connected = core.TRUE

        self.debug.send("Connected: " + str(connected))
        self.debug.send("Global Connected: " + str(self.globalConnected))

        if connected == core.TRUE:
            self.onConnectionTimeout = MOD.secCounter() + int(
                self.config.get(CONNECTION_TIMEOUT))

        # Если неопределённое состояние
        if self.globalConnected == None:
            if (connected == core.FALSE) and (MOD.secCounter() >
                                              self.onConnectionTimeout):
                self.sendToRecepients(NO_CONNECTION_TEXT)
                self.globalConnected = core.FALSE
            elif connected == core.TRUE:
                self.sendToRecepients(CONNECTED_TEXT)
                self.globalConnected = core.TRUE
        # Если находится в состоянии подключения
        # Отсылает СМС и устанавливает состояние не соединено
        elif self.globalConnected == core.TRUE:
            if (connected == core.FALSE) and (MOD.secCounter() >
                                              self.onConnectionTimeout):
                self.sendToRecepients(NO_CONNECTION_TEXT)
                self.globalConnected = core.FALSE
        # Если не подключен
        else:
            if connected == core.TRUE:
                self.sendToRecepients(CONNECTED_TEXT)
                self.globalConnected = core.TRUE
Example #15
0
def mdmResponse(theTerminator, timeOut):
# This function waits for AT Command response and handles errors and ignores unsolicited responses

  # Input Parameter Definitions
  #   theTerminator: string or character at the end of a received string that indicates end of a response
  #   timeOut: number of seconds command could take to respond

    try:

        print 'Waiting for AT Command Response'

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

        #Wait for response
        res = ''
        while ((res.find(theTerminator)<=-1) and (res.find("ERROR")<=-1) and (res != 'timeOut')):
            MOD.watchdogReset()
            res = res + MDM.receive(10)

            pass            
            if timerA.isexpired():
                res = 'timeOut'

    except:
        printException("mdmResponse()")

    return res
Example #16
0
    def readGasState(self):
        self.debug.send("Read gas state")

        data = []
        state = 0  # состояние: начало пакета(0), тревога(1)

        timeout = MOD.secCounter() + READ_MASTER_GAS_TIMEOUT
        gasState = None
        while (timeout > MOD.secCounter()):
            byte = self.serial.receivebyte(self.speed, '8N1', 0)
            # Ищет начало пакета
            if state == 0:
                if (byte == MASTER_GAS_NETWORK):
                    state = 1
                continue

            if state == 1:
                gasState = byte
                break
            else:
                state = 0

        self.debug.send("Gas state: " + str(gasState))

        # Очищает буффер модема, что бы не переполнился
        clean = self.serial.receive(self.speed, '8N1', 0)
        self.debug.send("Bytes to clean: " + str(len(clean)))

        return gasState
Example #17
0
def GetData(TIMEOUT_DWNLD):
    SER.send('Ready to wait for response\r')
    timeout = MOD.secCounter() + TIMEOUT_DWNLD
    timer = timeout - MOD.secCounter()
    HTML_UC_END = '</RESPONSE>'
    HTML_LC_END = '</response>'
    data = ''
    mesg = ''
    while ((data.find('NO CARRIER') == -1) and (timer >0) ):
        SER.send('...Downloading\r')
        datatmp = MDM.receive(5)
        data = data + datatmp
        timer = timeout - MOD.secCounter()
        wd.feed()

    if(data.find('HTTP/1.1 200') == -1):
        mesg = 'Update server ERROR: ' + data[0:12]
        SER.send(mesg)
        SER.send('\r')
        SER.send(data)
        SER.send('\r')
        data = -1

    else:
        mesg = 'Update server SUCCEFULL: ' + data[0:12]
        SER.send(mesg)
        SER.send('\r')

    Log.appendLog(mesg)        
    return data
Example #18
0
def isGprsAttached(timeOut):
# This function waits until the GPRS attaches

    exitLoop = -1
    
    try:

        #Start timeout counter        
        timerA = timers.timer(0)
        timerA.start(timeOut)
        
        #Wait until registered to GSM Network
        while (exitLoop == -1):
            MOD.watchdogReset()
            res = ATC.sendAtCmd('AT+CGREG?',ATC.properties.CMD_TERMINATOR,0,5)
            if (res[res.rfind(',')+1:len(res)] == '5' or res[res.rfind(',')+1:len(res)] == '1'):
                exitLoop = 0
                break
            if timerA.isexpired():
                break #Exit while
            
    except:

        printException("isGprsAttached()")

    return exitLoop
Example #19
0
def sendSMS(NUMBER, SMSText):
	TIMEOUT_CMD = 50
	Helper.writeLog('Starting sendSMS\r\n')
	
	res = Helper.sendCmd('AT+CMGF', '1', TIMEOUT_CMD) # select text format type
	Helper.writeLog('Finished AT+CMGF\r\n')
	
	res = Helper.sendCmd('AT+CNMI', '2,1', TIMEOUT_CMD) # alarm indicators
	Helper.writeLog('Finished AT+CNMI\r\n')
	
	res = Helper.sendCmd('AT+CMGS', NUMBER, TIMEOUT_CMD) # send the message without storing it
	Helper.writeLog('Finished AT+CMGS\r\n')
	
	if (res.find('>') == -1):
		return -1
	else:
		res = MDM.send(SMSText, 0)
		Helper.writeLog('Finished sending SMSText\r\n')
		
		res = MDM.sendbyte(0x1a, 0)
		Helper.writeLog('Finished CTRL+Z\r\n')
		
		for i in range(6):
			res=MDM.read()
			if(res.find("OK")!=-1):
				Helper.writeLog('Found and returning\r\n')
				return 1
			else:
				MOD.sleep(300)
		
		Helper.writeLog('REturning -1\r\n')
		return -1
Example #20
0
def eraseSector ( sector_address ):
	addr = mbytewrap(sector_address, 0x00)
	msg = '\x20%s' % addr

	writeEnable()
	writ = SPIobj.readwrite(msg)
	MOD.sleep(3) # Stay within safeties for sector erase (abs.max 450ms)
	return writ
Example #21
0
def eraseSector(sector_address):
    addr = mbytewrap(sector_address, 0x00)
    msg = '\x20%s' % addr

    writeEnable()
    writ = SPIobj.readwrite(msg)
    MOD.sleep(3)  # Stay within safeties for sector erase (abs.max 450ms)
    return writ
Example #22
0
def delAll():

    res = MDM.send("AT+CMGF=1\r", 0)
    res = MDM.receive(3)
    res = MDM.send("AT+CNMI=2,1\r", 0)
    res = MDM.receive(3)
    if res.find("OK") != -1:
        print "OK for AT+CNMI=2,1"
    else:
        print "ERROR for AT+CNMI=2,1"

    # SIM status control - to avoid the 'sim busy' error
    print "SIM Verification Cycle"
    a = MDM.send("AT+CPBS?\r", 0)
    SIM_status = MDM.receive(10)
    if SIM_status.find("+CPBS") < 0:
        print "SIM busy! Please wait!\n"
    while SIM_status.find("+CPBS:") < 0:
        a = MDM.send("AT+CPBS?\r", 0)
        SIM_status = MDM.receive(10)
        MOD.sleep(2)
    print "SIM Ready"

    # receive the list of all sms
    MDM.send('AT+CMGL="ALL"\r', 0)
    smslist = ""
    MemSMS = MDM.receive(20)
    smslist = MemSMS
    while MemSMS != "":
        MemSMS = MDM.receive(20)
        smslist = smslist + MemSMS

    # listsms = MemSMS.splitlines()
    listsms = smslist.split("\n")
    listIndex = []  # the list of index to delete
    for string in listsms:
        if string.find("+CMGL:") != -1:  # find the index of each sms
            start = string.find(":")
            end = string.find(",")
            myindex = string[(start + 1) : end]
            myindex = myindex.strip()
            listIndex.append(myindex)
        print string

    if listIndex == []:
        print "No SMS in SIM"

    # delete all sms
    for index in listIndex:
        print "Deleting sms index: " + index
        MDM.send("AT+CMGD=", 0)
        MDM.send(index, 0)
        MDM.send("\r", 0)
        res = MDM.receive(20)
        res = res.replace("\r\n", " ")
        print res

    return 1
Example #23
0
def reboot():
# This method does return a response.  After the AT#REBOOT command executes the GSM module will
# reset and the script will restart depending on the #STARTMODESCR settings.

    MOD.sleep(15)                                               #required to halt Python thread and allow NVM Flash to update
    print "Rebooting Terminus!"
    sendAtCmd('AT#REBOOT',properties.CMD_TERMINATOR,0,20)

    return
Example #24
0
def iterateCmd(comando, parametro, TIMEOUT_CMD, numCheck):
	while( numCheck >= 0):
		numCheck = numCheck -1
		res = sendCmd(comando, parametro, TIMEOUT_CMD)
		if(res.find('OK') != -1):
			return 1
		MOD.sleep(TIMEOUT_CMD)
		if(numCheck == 0):
			return -1
Example #25
0
def feed():
    b = GPIO.setIOvalue(11, 0)
    b = GPIO.setIOvalue(12, 0)
    MOD.sleep(10)
    b = GPIO.setIOvalue(11, 1)
    b = GPIO.setIOvalue(12, 1)
    msg = "Reseting External Watchdog"
    # Log.appendLog(msg)
    return 1
Example #26
0
def checkNetwork():
    MOD.sleep(20)
    REC_TIME = 200
    for _ in range(10):
        MDM.send("AT+CREG?\r",0)
        res = MDM.receive(REC_TIME)
        if (res.find('0,1')!=-1): return 1
        else: MOD.sleep(50)
    return 0
Example #27
0
def sendEscapeSequence():

    # Module doesn't care if it isn't in data mode
    # Must sleep AT LEAST  1 sec before and after escape sequence
    MOD.sleep(12)
    MDM.send("+++", 5)
    MOD.sleep(12)

    timeout = MOD.secCounter() + 5
    return _target(["OK"], timeout) != 0
Example #28
0
def sendEscapeSequence ( ):

    # Module doesn't care if it isn't in data mode
    # Must sleep AT LEAST  1 sec before and after escape sequence
    MOD.sleep(12)
    MDM.send("+++", 5)
    MOD.sleep(12)

    timeout = MOD.secCounter() + 5
    return _target(["OK"], timeout) != 0
Example #29
0
def iterateHTTPCmd(comando, parametro, TIMEOUT_CMD, numCheck):
    while( numCheck >= 0):
        numCheck = numCheck - 1
        res  = Helper.sendCmd(comando, parametro, TIMEOUT_CMD)
        SER.send(res + ' ' + comando + '=' + parametro)
        if(res.find('CONNECT') != -1) :
            return 1
        MOD.sleep(TIMEOUT_CMD)
        if(numCheck == 0):
            SER.send(res + ' ' + comando + '=' + parametro)
            return -1
Example #30
0
File: main.py Project: predat0r/GSM
def check_network():
    MOD.sleep(20)
    for _ in range(10):
        MDM.send("AT+CREG?\r",0)
        res = MDM.receive(200)
        print 'check registration'
        if res.find('0,1') != -1:
            print 'registration ok'
            return 1
        else: MOD.sleep(50)
    return 0
Example #31
0
def iterateCmd(comando, parametro, TIMEOUT_CMD, numCheck):
    while (numCheck >= 0):
        numCheck = numCheck - 1
        res = sendCmd(comando, parametro, TIMEOUT_CMD)
        SER.send(res + ' ' + comando + '=' + parametro)
        if (res.find('OK') != -1):
            return 1
        MOD.sleep(TIMEOUT_CMD)
        if (numCheck == 0):
            SER.send(res + ' ' + comando + '=' + parametro)
            return -1
Example #32
0
def toggleGPIO(id,z_on,z_off,anz):
    ra = ''
    while anz > 0:
        ra = GPIO.setIOdir(id,1,1)
        MOD.sleep(z_on)
        ra = GPIO.setIOdir(id,0,1)
        MOD.sleep(z_off)
        # flash continusly
        if ( anz != 99 ):
            anz = anz - 1
    return ra
Example #33
0
    def start(self):
        # Отсылает 10 раз 2 байта переинициализации
        self.debug.send("Start")
        for i in xrange(10):
            self.serial.sendbyte(0, self.speed, '8M1')
            self.serial.sendbyte(0, self.speed, '8E1')

        MOD.sleep(REBOOT_WAIT_TIMEOUT)

        self.recepients = self.recepientHelper.getRecepients()
        self.debug.send(str(self.recepients))
        self.work()
Example #34
0
def loop(gps_log_file):
    gps_data = get_formated_gps_data()
    
    if gps_log_file != None and gps_data != None and gps_data != "":
        if get_speed(gps_data) > SPEED_LOWER_LIMIT: # write only if speed is greater than 10 km/h
            gps_log_file.write("%s\n"%gps_data)
            gps_log_file.flush()
            MOD.watchdogReset()
        else:
            # close the log file
            gps_log_file.flush()
            gps_log_file.close()
Example #35
0
def rebootCounterProcessing(delta):
    global REBOOT_COUNTER
    global CALENDAR
    if((delta < 0) or (delta > 100)):
        delta = 5
    REBOOT_COUNTER = REBOOT_COUNTER + delta
    SER.send('Current reboot counter: %d\r' % REBOOT_COUNTER)
    if(REBOOT_COUNTER > int(CFG.get('REBOOTPERIOD'))):
        SER.send('Terminal reboot.\r')
        if(int(CFG.get('ALIVESMS')) > 0):
            CALENDAR = CALENDAR + 1
            calendar.writeCalendar(CALENDAR)
        MOD.sleep(30)
        gsm.reboot()
Example #36
0
def openSD(H):
    res = MDM2.send('AT#SD=1,0,80,' + H +',0\r', 0)
    timer = MOD.secCounter() + 30
    while (MOD.secCounter() < timer):
        res = MDM2.receive(10)
        a = SER.send('\r\nDEBUG: Back in openGPRS just did AT#SD=1,0,80....\r\n')
        a = SER.send(H)
        a = SER.send(res)
        if ((res.find('CONNECT') >= 0) ):
            timer = timer - 100
	    b = SER.send('\r\nsuccessfull connect, returning from openSD\r\n')
            return 1
        MOD.sleep(10)
    return -1
Example #37
0
def EnviarDatosMET(datos):
 global debug
 res=enviarAT('at#sd=1,0,6444,"192.168.0.1",0,6444,0',150,'CONNECT')
 if (res==1):
  if (debug==1):
   SER.send('\r\nCONECTADO... Pidiendo pagina.')
 elif (debug==1):
  SER.send('\r\nFallo la coneccion al servidor')
  MOD.sleep(10)
  resx = MDM.send('+++',10)
  MOD.sleep(10)
  res=enviarAT('at#sh=1',20,'OK')
  return -1
 res = MDM.send('GET /archivoquerecibedatos.php?id=telit&msg='+datos+' HTTP/1.0\r\n',10)
 res = MDM.send('Host: 192.168.0.1\r\n',10)
 res = MDM.send('\r\n\r\n',10)
 res3 = RecibirDesdeModem(100,'RCV_MSG')
 MOD.sleep(10)
 resx = MDM.send('+++',10)
 MOD.sleep(10)
 res=enviarAT('at#sh=1',50,'OK')
 if (res==1):
  if (debug==1):
   SER.send('\r\nSocket desconectado')
 elif (debug==1):
  SER.send('\r\nNO se pudo desconectar el socket')
  return -1
 if (res3==-1):
  if (debug==1):
   SER.send('\r\nNo se obtuvo la pagina de vuelta.')
  return -1
 elif (res3==1):
  if (debug==1):
   SER.send('\r\nSe obtuvo correctamente la pagina')
  return 1
Example #38
0
    def work(self):
        self.debug.send("Start work")
        while (core.TRUE):
            try:
                # Ожидает SMS
                if MOD.secCounter() > self.smsReadTimer:
                    self.debug.send("Get sms")
                    try:
                        smsList = self.smsManager.listSms()
                        for sms in smsList:
                            for recepient in self.recepients:
                                smsRec = sms.recepient.replace("+7", "8")
                                rec = recepient.replace("+7", "8")
                                if smsRec == rec:
                                    self.processSms(sms)
                    except:
                        pass

                    self.smsManager.deleteAll()
                    self.resetSmsTimer()

                # Отсылает 4 байта с тревогами на пульт(адрес пульта в INI)
                self.sendAlarms()
                self.resetWatchdog()
            except Exception, e:
                self.debug.send(str(e))
Example #39
0
def setup():
    initSettings()

    VOLT = Gauge.getBatteryVoltage()
    SER.send('Voltage: %s\n' % VOLT)

    # Don't start the network on a missing/near-empty battery
    if VOLT > 2500:
        initNetworkRelated()

    SER.send('Starting storage initialization at: %s\n' % MOD.secCounter())
    sector = Storage.initialize()
    SER.send('End at: %s. Sector: %s\n' % (MOD.secCounter(), sector))

    Module.CPUclock(0)  # Clock back to default (@26Mhz)
    SER.send('CPU back down\n')
Example #40
0
 def __init__(self, settings):
     self.timer = MOD.secCounter()
     self.settings = settings
     self.settingsByKey = settingsByKey = self.settings.byKey
     SER.set_speed('300')
     #self.charmParsed = settingsByKey['charm']
     self.name = settingsByKey['name']
     self.i = settingsByKey['id']
     self.serverAddr = settingsByKey['serverAddr']
     self.maxLate = settingsByKey['maxlate']
     self.desc = settingsByKey['desc']
     self.charm = settingsByKey['charm']
     self.mainLoop = None
     print self.timer
     # Komendy odpowiedzialne za komunikacje internetową
     SER.setDSR(0)
     SER.setCTS(0)
     SER.setDCD(0)
     self.time = 0
     self.SMS = SMS(self)
     self.ipAddr = ""
     self.getTime()
     atstart = settingsByKey["atstart"]
     if len(atstart): sendATlist(atstart)
     self.maxSMSinMEM = settingsByKey["sms_limit"]
     MDM.send(self.m_init, 10)
     MDM.receive(20)
Example #41
0
def sendAT(request, response, timeout = 2):
    MDM.send(request + '\r', 2)
    result = -2
    data = ''
    timer = MOD.secCounter() + timeout
    while(MOD.secCounter() < timer):
        rcv = MDM.read()
        if(len(rcv) > 0):
            data = data + rcv
            if(data.find(response) != -1):
                result = 0
                break
            if(data.find('ERROR') != -1):
                result = -1
                break
    return (result, data)
Example #42
0
def setup ( ):
	initSettings()

	VOLT = Gauge.getBatteryVoltage()
	SER.send('Voltage: %s\n' % VOLT)

	# Don't start the network on a missing/near-empty battery
	if VOLT > 2500:
		initNetworkRelated()

	SER.send('Starting storage initialization at: %s\n' % MOD.secCounter())
	sector = Storage.initialize()
	SER.send('End at: %s. Sector: %s\n' % (MOD.secCounter(), sector))

	Module.CPUclock(0) # Clock back to default (@26Mhz)
	SER.send('CPU back down\n')
Example #43
0
def sendAT(request, response="OK", timeout=3):
    MDM.send(request + "\r", 2)
    result = -2
    data = ""
    timer = MOD.secCounter() + timeout
    while MOD.secCounter() < timer:
        rcv = MDM.read()
        if len(rcv) > 0:
            data = data + rcv
            if data.find(response) != -1:
                result = 0
                break
            if data.find("ERROR") != -1:
                result = -1
                break
    return (result, data)
Example #44
0
    def __init__(self, config):
        self.config = config

        self.speed = config.get(SER_SP)
        self.serial = core.Serial()

        isDebug = config.get(DEBUG_SER) == "1"
        debugSpeed = config.get(DEBUG_SER_SP)
        debugBytetype = config.get(DEBUG_SER_OD)
        self.debug = core.Debug(isDebug, self.serial, debugSpeed,
                                debugBytetype)

        self.gsm = core.Gsm(config, self.serial, self.debug)
        self.gsm.simpleInit()

        self.smsManager = core.SmsManager(self.gsm, self.debug)
        self.smsManager.initContext()
        # Удаляет все СМС
        self.smsManager.deleteAll()
        self.smsReadTimer = 0
        self.resetSmsTimer()

        self.alarmParser = AlarmParser()
        self.alarmOne = AlarmStorage()
        self.alarmTwo = AlarmStorage()
        self.alarmThree = AlarmStorage()
        self.alarmFour = AlarmStorage()
        self.recepientHelper = RecepientHelper(self.config, self.gsm,
                                               self.debug)
        self.globalConnected = None

        # Таймаут отсутствия связи в неопределенном состоянии
        self.onConnectionTimeout = MOD.secCounter() + int(
            self.config.get(CONNECTION_TIMEOUT))
        self.initWatchdog()
Example #45
0
    def readBupsState(self):
        self.debug.send("Read bups state")

        data = []
        state = 0  # состояние: начало пакета(0), адрес бупс(1), тревога(2)

        timeout = MOD.secCounter() + READ_BUPS_TIMEOUT
        bupState = None
        while (timeout > MOD.secCounter()):
            byte = self.serial.receivebyte(self.speed, '8N1', 0)
            # Ищет начало пакета
            if state == 0:
                if (byte == BUPS_NETWORK):
                    state = 1
                continue

            # Если 7 бит у байта тревоги снят то это начало
            if state == 1:
                if ((byte & 0x80) > 0) and ((byte & 0x40)
                                            == 0) and ((byte & 0x20) == 0):
                    state = 2
                    data.append(byte)
                else:
                    state = 0
                continue

            # Продолжает получать байты пока в списке не будет 4 байта данных
            if state == 2:
                if (byte == BUPS_NETWORK):
                    state = 3
                continue

            if state == 3:
                state = 2
                data.append(byte)
                if len(data) >= 4:
                    bupState = BupsAlarmState(data[3], data[0], data[1],
                                              data[2])
                    break

        # Очищает буффер модема, что бы не переполнился
        clean = self.serial.receive(self.speed, '8N1', 0)
        self.debug.send("Bytes to clean: " + str(len(clean)))

        self.debug.send(str(bupState))

        return bupState
Example #46
0
def delaySec(seconds):

    try:

        if(seconds<=0): return    

        timerA = timers.timer(0)
        timerA.start(seconds)
        while 1:
            MOD.watchdogReset()
            if timerA.isexpired():
                break

    except:
        printException("delaySec()")

    return
Example #47
0
 def parseExec(self):
     # - Lista  funkcji które maja być wykonane po znalezieniu
     # - odpowiedniego kodu poprzedzonego znakiem "!".
     MOD.watchdogEnable(600)
     mopers = self.module.operations.get
     a = ""
     t = ""
     b = 0
     c_now = ""
     forward = self.forward
     c_now = forward(1)[1]
     while not b and c_now and (c_now != ';'):
         a = a + c_now
         b, c_now = forward()
     if b < 1: self.rt = mopers(a)(self.module)
     MOD.watchdogDisable()
     return 1
Example #48
0
 def send(self, msg):
     message = str(MOD.secCounter()) + ' # ' + msg + '\r\n'
     max_len = int(self.config.get('TCP_MAX_LENGTH'))
     print message
     if (self.config.get('DEBUG_SER') == '1'):
         SER.send(message)
     if (self.config.get('DEBUG_TCP') == '1'):
         if((len(self.tcpLogBuffer) + len(message)) < max_len):
             self.tcpLogBuffer = self.tcpLogBuffer + message
Example #49
0
 def send(self, msg):
     message = str(MOD.secCounter()) + ' # ' + msg + '\r\n'
     max_len = int(self.config.get('TCP_MAX_LENGTH'))
     print message
     if (self.config.get('DEBUG_SER') == '1'):
         SER.send(message)
     if (self.config.get('DEBUG_TCP') == '1'):
         if ((len(self.tcpLogBuffer) + len(message)) < max_len):
             self.tcpLogBuffer = self.tcpLogBuffer + message
Example #50
0
def generateLog():

    SER.send('\n\n<LOG>')

    while 1:
        message = Storage.read()

        if message == 0:
            break

        SER.send(message[0:1000])
        MOD.sleep(2)
        SER.send(message[1000:])

    # Next time we'll be writing in a new sector.
    Storage.incrementActiveSector()

    SER.send('</LOG>\n\n')
Example #51
0
def sendSMS(NUMBER, SMSText):
	TIMEOUT_CMD = 50
	res = scmd.sendCmd('AT+CMGF', '1', TIMEOUT_CMD) # select text format type
	res = scmd.sendCmd('AT+CNMI', '2,1', TIMEOUT_CMD) # alarm indicators
	res = scmd.sendCmd('AT+CSMP', '17,167,0,0', TIMEOUT_CMD) # select message parameter
	res = scmd.sendCmd('AT+CMGS', NUMBER, TIMEOUT_CMD) # send the message without storing it
	if (res.find('>') == -1):
		return -1
	else:
		res = MDM.send(SMSText, 0)
		res = MDM.sendbyte(0x1a, 0)
		for i in range(6):
			res=MDM.read()
			if(res.find("OK")!=-1):
				return 1
			else:
				MOD.sleep(300)
		return -1
Example #52
0
def receive(timeout=2):
    """Получить ответ от процессора

    Args:
        timeout: Время ожидания ответа в сек
    Returns:
        Сырые принятые данные
    """
    data = ''
    timer = MOD.secCounter() + timeout
    while (1):
        rcv = SER2.read()
        if (len(rcv) > 0):
            data = data + rcv
            if (data.endswith('\r') or data.endswith('\n')):
                return data
        if (MOD.secCounter() > timer):
            return ''
Example #53
0
File: util.py Project: wal99d/gaga
def elapsed():
    t = MOD.secCounter()

    global epoch
    if epoch < 0:
        epoch = t

    t = t - epoch

    return t
Example #54
0
 def getTime(self):
     # MDM.send("ATE\r",1)
     # MDM.receive(0)
     # MDM.send("AT+CCLK?\r",10)
     # cclk=MDM.read()
     # print cclk
     # self.time = parse_cclk_T(cclk)
     t = MOD.secCounter() % 86400
     self.time = t
     return t
Example #55
0
def _command(command, timeout=5):

    # Clear input buffer before reading
    MDM.receive(1)

    MDM.send(command, 5)
    MDM.send(CRLF, 5)

    #SER.send("%s \n" % (command))

    return MOD.secCounter() + timeout
Example #56
0
 def tryCSD(self):
     ring = MDM2.getRI()
     if (ring == 1):
         at_timeout = int(self.config.get('TIMEOUT_AT'))
         a, s = self.sendAT('ATA\r', 'CONNECT', 1, 10, 0)
         if (a == 0):
             self.debug.send('CSD CONNECTED')
             while (ring == 1):
                 rcv = self.serial.receive(
                     int(self.config.get('TCP_MAX_LENGTH')))
                 if (len(rcv) > 0):
                     self.sendMDM2(rcv)
                 rcv = self.receiveMDM2()
                 if (len(rcv) > 0):
                     self.serial.send(rcv)
                 ring = MDM2.getRI()
                 MOD.watchdogReset()
             self.debug.send('CSD DISCONNECTED')
         else:
             self.debug.send('CSD CONNECT ERROR')
Example #57
0
def ioProcessing():
    if((int(CFG.get('OUT1TIME')) > 0) and (MOD.secCounter() > OUT1_OFF_TIME) and (OUT1_STATE == 1)):
        executeCommand(command.Command('OUT1', '0'))
    global IN1_STATE
    IN1_STATE_NEW = GPIO.getIOvalue(4)
    if(IN1_STATE_NEW != IN1_STATE):
        if(IN1_STATE_NEW == 1):
            sendAlert(CFG.get('IN1ONTXT'))
        else:
            sendAlert(CFG.get('IN1OFFTXT'))
    IN1_STATE = IN1_STATE_NEW
def SendPositionProptery(DeviceID,GPSLongitude,GPSLatitude):
    #this function sends all mobile parameters to the cumulocity platform
    if(m_modemmanager.GetDCD()==0):
        PrintW('DCD is low')
        PrintW('Failed to send GPS position. No connection')
        return
    PostData = '{"c8y_Position": {"alt":0,"lng":'+GPSLongitude+',"lat":'+GPSLatitude+'}}'
    FullPostString = 'PUT /inventory/managedObjects/'+DeviceID+' HTTP/1.1\r\n'
    FullPostString = FullPostString + 'Host: '+CumulocityServer+'\r\n'
    FullPostString = FullPostString + 'Authorization: Basic '+Device_B64_Authentication+'\r\n'
    FullPostString = FullPostString + 'Content-Type: application/vnd.com.nsn.cumulocity.managedObject+json\r\n'
    FullPostString = FullPostString + 'Accept: application/vnd.com.nsn.cumulocity.managedObject+json\r\n'
    FullPostString = FullPostString + 'Cache-Control: no-cache\r\n'
    FullPostString = FullPostString + 'Connection: keep-alive\r\n'
    FullPostString = FullPostString + 'Content-Length: '+str(len(PostData))+'\r\n'
    FullPostString = FullPostString + '\r\n'
    FullPostString = FullPostString + PostData
    m_modemmanager.SendData(FullPostString)
    PrintW('Sending collected data to Data Server\r\n')
    PrintW('Post contents:\r\n'+FullPostString+'\r\n')
    MOD.sleep(2)