python sending udp packet - not always sent - python

I'm trying to send a repetitive messages - one every 0.5 sec and other every sec.
When executing the code below, it is not running - I can't see it in wireshark.
Any idea how to sole it?
import socket
import time
sock1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
LOCAL_IP = "1.1.1.1"
DST_IP1 = "224.1.1.1"
DST_PORT1 = 12345
DST_IP2 = "225.1.1.1"
DST_PORT2 = 22345
data1 = b'\x11\x22'
data1 = data1 + bytearray(30)
PERIOD = 500
Day=18
def updateTime(some inputs):
some proccess
return day
while True:
Day = updateTime(Day)
msg1=data1 + struct.pack('!B',Day)
msg2 = "some strings" + f'{Day:02d}' + "some more string"
basetime = datetime.now()
updated_time = datetime.now()
D = updated_time - basetime
while D.seconds < 1:
sock1.sendto(msg1,(DST_IP1, int(DST_PORT1))
time.sleep(int(PERIOD)/1000.0)
updated_time = datetime.now()
D = updated_time - basetime
sock2.sendto(msg2,(DST_IP2, int(DST_PORT2))

Related

udp client/server with resending messages

I have a client and a server. The server sends a random number to the client and if it is less than 4, the client responds unsuccessfully.
SERVER:
import random
from socket import *
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', 12000))
while True:
rand = random.randint(2, 4)
message, address = serverSocket.recvfrom(1024)
message = (message.decode()+" СЛУЧАЙНОЕ ЧИСЛО: "+str(rand)).upper()
print("Сервер готов!")
print("Случайное число: "+str(rand))
if rand < 4:
continue
serverSocket.sendto(message.encode(), address)
Client:
from time import *
from socket import *
localhost = '127.0.0.1'
for i in range(1, 11):
clientSocket = socket(AF_INET, SOCK_DGRAM)
date_current = ctime()
startTime = time()
clientSocket.settimeout(0.5)
try:
requestMessage = bytes("Ping " + str(i) + " " + date_current, 'utf8')
clientSocket.sendto(requestMessage, (localhost, 12000))
mess, rand = clientSocket.recvfrom(1024)
endTime = time()
rtt = endTime - startTime
print(mess.decode())
print("Ответ "+localhost+" подтверждено: "+str(float(rtt)))
print()
except:
print(requestMessage.decode())
print("Время вышло")
print()
I want the client to send a message to the server in case of failure and the server to regenerate the number and send it to the client until there is a response about luck (more than 4)

Blocking sockets in python

I'm trying to write a program. I writting gps tracking program in python. I want to listen to a continuous port. I wrote something for that. But it doesn't constantly log out or save data to the database. Where's the problem?
import socket
import MySQLdb
import sys
import thread
from datetime import datetime, timedelta
con = None
dbhost = 'localhost'
dbport = 3306
dbuser = "root"
dbpass = ""
dbname = "test_db"
def on_new_client(clientsocket,addr):
cik = 0
while cik != 1:
paketler = [20]
msg = clientsocket.recv(1024)
dosya = open('/etc/asdf/taxi.txt','a')
dosya.write('\n')
dosya.write(msg)
dosya.flush()
dosya.close()
message1 = msg.split("#")
i=0
j=len(message1)
while i < (j-1):
try:
liste= message1[i].split(";")
location= liste[0].split(",")
if(location[0]=='$DATA' and str(location[2])!='' and location[3]!='00002000' and len(liste)==14):
way= liste[13].split(",")
date_data= str(location[3])+" "+str(liste[1])
data = datetime.strptime(date_data,'%d%m%Y %H%M%S')
data = data + timedelta(hours=3)
datetim = data.strftime('%d-%m-%Y %H:%M:%S')
datetim = data.strftime('%Y-%m-%d %H:%M:%S')
stat = liste[12].split(",")
if (len(stat)==2 and stat[1]!=''):
#insert in db
elif(location[0]=='$GEOLOC' and str(location[2])!='' and len(liste)==14):
way= liste[13].split(",")
date_data= str(liste[1])+" "+str(liste[2])
data = datetime.strptime(date_data,'%d%m%Y %H%M%S')
data = data + timedelta(hours=3)
datetim = data.strftime('%d-%m-%Y %H:%M:%S')
datetim = data.strftime('%Y-%m-%d %H:%M:%S')
elif(location[0]=='$TRIP' and str(location[2])!='' and len(liste)==32):
date_data= str(location[3])+" "+str(liste[1])
data = datetime.strptime(date_data,'%d%m%Y %H%M%S')
data = data + timedelta(hours=3)
datetim = data.strftime('%d-%m-%Y %H:%M:%S')
datetim = data.strftime('%Y-%m-%d %H:%M:%S')
date_data= str(liste[11])+" "+str(liste[12])
data = datetime.strptime(date_data,'%d%m%Y %H%M%S')
data = data + timedelta(hours=3)
datetim2 = data.strftime('%d-%m-%Y %H:%M:%S')
datetim2 = data.strftime('%Y-%m-%d %H:%M:%S')
#insert in db
i = i+1
except:
print "Exit"
clientsocket.close()
cik = 1
break
print addr, ' >> ', msg
clientsocket.close()
s = socket.socket() # Create a socket object
host = '127.0.0.1' # Get local machine name
port = 1234 # Reserve a port for your service.
con = MySQLdb.connect(dbhost, dbuser, dbpass, dbname);
cur = con.cursor()
s.bind((host, port)) # Bind to the port
s.listen(5) # Now wait for client connection.
while True:
c, addr = s.accept() # Establish connection with client
thread.start_new_thread(on_new_client,(c,addr))
con.close()
s.close()
if msg > clientsocket.recv(1024) program is stop. I don't want the program to stop.

Why does my UDP pinger client only timeout?

I've made a UDP Pinger server side, however this UDP Pinger client only sends request time outs. I'm trying to make a pinger that sends 10 pings to the server.
import time
from socket import *
serverName = ''
serverPort = 12000
ClientSocket = socket(AF_INET, SOCK_DGRAM)
ClientSocket.settimeout(1)
ping = 1
message = 'ping'
counter = 10
i = 0
remain = counter - i
while counter < i :
i = i + 1
addr = ("", 120000)
start = time.time()
ClientSocket.sendto(message, (serverName,
serverPort))
while ping < 11:
try:
message, server = ClientSocket.recvfrom(1024)
end = time.time()
elapsed = end - start
print (message + " " + str(ping) + " " +
str(elapsed))
except timeout:
print ('REQUEST TIMED OUT')
ping = ping + 1

Python Script crash in Ubuntu Server but work under raspbian

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

Teltonika FM1100 and TCP listner

Hy, here i am...
i'm writing a tcp listner in python to read and communicate with teltonika devices but i've problems when after receiving imei code, i try to send the akcnowledgment to the device, so it does not send me AVL data.
here is a simply code:
#!/usr/bin/env python
import socket
import time
import binascii
#Variables______________________________________#
imei_known = 'XXXXXXXXXXXXXXX'
COM = 0
TCP_IP = '192.168.1.115'
TCP_PORT = 55001
BUFFER_SIZE = 5024
MESSAGE_NO_OK = '00'
MESSAGE_OK = '01'
msg_ok = MESSAGE_OK.encode('utf-8')
msg_no_ok = MESSAGE_NO_OK.encode('utf-8')
#gps elememts (to be review)
long = [0] * 8
lat = [0] * 8
angle = [0] * 4
speed = [0] * 4
sat = [0] * 2
#_____________________________________________________________#
print ('Server listening on port:',TCP_PORT)
print ('\nWaiting for data input from FM1100...')
#socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((TCP_IP, TCP_PORT))
server_socket.listen(5)
client_socket, addr = server_socket.accept()
print ('\nConnection address:', addr)
#infinite loop
while 1:
if COM == 0:
print ('\nCOM num = ',COM)
data = client_socket.recv(BUFFER_SIZE)
imei = data.decode("iso-8859-1")
lista = list(imei)
#vector of 15 elements for IMEI code
lista_2 = [0] * 15
for n in range (0,15):
lista_2 [n] = lista[n+2]
imei=''.join(lista_2)
print ('\nDevice\'s IMEI:', imei)
print ('\nComparing IMEI...')
if imei_known == imei:
print('\nDevice Recognized ')
print('\nSending data to client...')
client_socket.send(b'0x01')
data = ''
else:
client_socket.send(msg_no_ok)
print('\nDevice NOT Recognized')
break
print('\nWaiting for AVL data...')
you must reply to FM1100 in hexadecimal. Like this:
client_socket.send('\x01')

Categories