我在这里遇到Python脚本问题。 我的问题是,它可以在Raspberry 3上运行,但在Ubuntu Server下崩溃。 脚本通过vpn连接到Teltonika RUT955 LTE路由器并收集GPS数据。它可以正常工作。现在,我将脚本从树莓派复制到我的Ubuntu服务器(不是VM),脚本崩溃。 当我在笔记本电脑(Linux Mint)上尝试该脚本时,它将起作用。我有另一个Ubuntu Server,但是同样,它崩溃了。
我在Raspi上的Python版本是2.7.9,在Ubuntu服务器上是2.7.12
这是我的代码:
#!/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()