0

i have am problem with a Python Script here. My Problem is, it works on a Raspberry 3 but it crashes under Ubuntu Server. The Script connects via vpn to a Teltonika RUT955 LTE Router and collects GPS data. It works without problems. Now i copy the script from the raspberry to my Ubuntu Server (not a VM) and the script crash. When i´m try the script on my Laptop (Linux Mint), it works. I have an other Ubuntu Server, but the same, it crashes.

My Python Version on my Raspi is 2.7.9, on my Ubuntu Server is 2.7.12

The Script crash at the function unpack. enter image description here

And heres my code:

 #!/usr/bin/env python

import socket
import threading
from time import gmtime, strftime
import ConfigParser
from optparse import OptionParser
import struct
import binascii
from datetime import datetime
import dbgps
import time


TCP_IP = '10.81.0.1'
TCP_PORT = 17050


def unpack(fmt, data):
    try:
        return struct.unpack(fmt, data)
    except struct.error:
        flen = struct.calcsize(fmt.replace('*', ''))
        alen = len(data)
        idx = fmt.find('*')
        before_char = fmt[idx-1]
        n = (alen-flen)/struct.calcsize(before_char)+1
        fmt = ''.join((fmt[:idx-1], str(n), before_char, fmt[idx+1:]))
        return struct.unpack(fmt, data)

class GPSTerminal:
    def __init__(self, socket):
        self.socket = socket[0]
        self.ip = socket[1][0]
        self.socket.settimeout(15)
        self.initVariables()

    def initVariables(self):
        self.imei = "unknown"
        self.sensorsDataBlocks = []
        self.error = []
        self.blockCount = 0
        self.raw = ''

        self.success = True
        self.dataBreak = 0
        self.possibleBreakCount = 5


    def startReadData(self):
        try:
            self.proceedConnection()
        except socket.timeout, e:
            self.success = False

    def proceedConnection(self):
        if self.isCorrectConnection():
            self.readIMEI()
            if self.imei:
                self.proceedData()
        else:
            self.error.append( "Incorrect connection data stream" )
            self.success = False

    def proceedData(self):
        self.time = datetime.now()
        self.data = self.readData()
        if self.data:
            Zeros, AVLLength, CodecID, BlockCount, Hexline = unpack("HLBBs*", self.data)
            print "test"

            self.Hexline = binascii.hexlify(Hexline)
            self.blockCount = BlockCount
            self.AVL = 0 # AVL ? Looks like data reading cursor
            proceed = 0
            AVLBlockPos = 0

            while proceed < BlockCount:
                try:
                    data = self.proceedBlockData()
                    if len(data) > 1: # Daten empfangen und in die DB schreiben
                        #dbgps.DBsendAlchemy("Update container_gps Set lon ='"+str(data['Lon'])+"', lat ='"+str(data['Lat'])+"', richtung='"+str(data['GpsCourse'])+"', Timestamp ='"+str(int(data['Timestamp']))+"' where IMEI='"+str(data['IMEI'])+"'")
                        #time.sleep(0.2)
                        print str(data['Lon'])
                    self.sensorsDataBlocks.append( data )
                except ValueError, e:
                    self.dataBreak += 1
                    self.reReadData(Hexline)
                    if self.dataBreak > self.possibleBreakCount :
                        self.error.append( "Data break" )
                        self.success = False
                        return
                    else:
                        self.AVL = AVLBlockPos
                        proceed -= 1
                proceed += 1
                AVLBlockPos = self.AVL
        else:
            self.error.append( "No data received" )
            self.success = False

    def readData(self, length = 8192):
        data = self.socket.recv(length)
        self.raw += data
        return data

    def reReadData(self, Hexline):
        HexlineNew = unpack("s*", self.readData())
        Hexline += HexlineNew[0]
        self.Hexline = binascii.hexlify(Hexline)

    def proceedBlockData(self):
        DateV = '0x'+ self.extract(16)
        DateS = round(long( DateV, 16) /1000, 0)
        Prio = self.extract_int(2)
        GpsLon = self.extract_int(8)
        GpsLat = self.extract_int(8)
        Lon = str(float(GpsLon)/10000000)
        Lat = str(float(GpsLat)/10000000)
        GpsH = self.extract_int(4)
        GpsCourse = self.extract_int(4)
        GpsSat = self.extract_int(2)
        GpsSpeed = self.extract_int(4)

        IOEventCode = self.extract_int(2)
        NumOfIO = self.extract_int(2)

        sensorDataResult = {}
        pais_count = 0
        for i in [1,2,4,8]:
            pc = 0
            data = self.readSensorDataBytes(i)
            for iocode in data.keys():
                pais_count+=1
                sensorDataResult[iocode] = data[iocode]
                pc += 1

        #return {'imei' : self.imei, 'date': DateS, 'Lon': Lon, 'Lat': Lat, 'GpsSpeed': GpsSpeed, 'GpsCourse': GpsCourse, 'sensorData': sensorDataResult}
        return {'IMEI' : self.imei, 'Timestamp': DateS, 'Lon': Lon, 'Lat': Lat, 'GpsSpeed': GpsSpeed, 'GpsCourse': GpsCourse}       

    def readSensorDataBytes(self, count):
        result = {}
        pairsCount = self.extract_int(2)
        i = 1
        while i <= pairsCount:
            IOCode = self.extract_int(2)
            IOVal = self.extract_int( count * 2)
            result[IOCode] = IOVal
            i+=1
        return result

    def extract(self, length):
        result = self.Hexline[ self.AVL : (self.AVL + length) ]
        self.AVL += length
        return result

    def extract_int(self, length):
        return int(self.extract(length), 16)

    def readIMEI(self):
        IMEI = self.readData(34)
        self.imei = IMEI
        self.socket.send(chr(01))

    def isCorrectConnection(self):

        hello = self.readData(2)
        return '(15,)' == str(struct.unpack("!H", hello ))

    def sendOKClient(self):
        self.socket.send(struct.pack("!L", self.blockCount))
        self.closeConnection()

    def sendFalse(self):
        self.socket.send(struct.pack("!L", 0))
        self.closeConnection()

    def closeConnection(self):
        self.socket.close()

    def getSensorData(self):
        return self.sensorsDataBlocks
    def getIp(self):
        return self.ip
    def getImei(self):
        return self.imei
    def isSuccess(self):
        return self.success

class ClientThread(threading.Thread):
    def __init__(self, group=None, target=None, name=None, *args, **kwargs):
        threading.Thread.__init__(self)
        self.socket = kwargs['socket']


    def run(self):
        client = self.socket
        if client:
            print "a"
            terminalClient = GPSTerminal(self.socket)
            print "b"
            terminalClient.startReadData()
            print "c"
            if terminalClient.isSuccess():
                terminalClient.sendOKClient()
            else:
                terminalClient.sendFalse()
                pass
            terminalClient.closeConnection()

if __name__ == "__main__":

    optParser = OptionParser()

    (options, args) = optParser.parse_args()
    config = ConfigParser.RawConfigParser()

    print "Server gestartet"

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    server.bind((TCP_IP, TCP_PORT))
    server.listen(5)

    while True:
        ClientThread(socket=server.accept(), config = config).start()
  • What does your data (in the struct) look like? Maybe also have a look at this question (except if you did already): https://stackoverflow.com/questions/29996458/struct-error-bad-char-in-struct-format – smagnan Aug 09 '18 at 10:16
  • Sorry, for my late response. I can delimit the problem, my problem is the socket connection, but i dont have any idea what is the difference on my raspberry and my ubuntu server on socket side. – griffinland Aug 16 '18 at 13:20

0 Answers0