I am making program for communication with cash register, and while i was testing printer on it (printing numbers from 0 to 100), I noticed that every time i get this byte (0f in hex) and my thread either blocks or shuts down. My project is made of 2 programs, one is for communication with cash register and tcp, and other is just sitting on tcp port (will add DB later)
So here is the 4 threaded program:
#!/usr/bin/env python
import thread
import crcmod
import Queue
import serial
import socket
import time
#portovi
TCP_IP = '127.0.0.1'
TCP_PORT=5007
v =0
lockSerial = thread.allocate_lock()
lockTcp = thread.allocate_lock()
lockPrn = thread.allocate_lock()
serialBuff = []
tcpBuff = []
prnBuff = []
prnReady=1
stx = chr(0x02)
etx = chr(0x03)
ack = chr(0x06)
nack = chr(0x15)
prnCmd = ('PB','PD','PF','P'+chr(0xc2))
crc8 = crcmod.mkCrcFun(0x131, 0x00)
ser = serial.Serial( 0 , baudrate=19200, bytesize=8, parity='N', stopbits=2, timeout=None, xonxoff=0, rtscts=0, writeTimeout=None, dsrdtr=None)
ser.open()
ser.sendBreak()
sl = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sl.bind((TCP_IP, TCP_PORT))
sl.listen(1)
connl, addr = sl.accept()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT+1))
s.listen(1)
conn, addr = s.accept()
def toHex(s):
lst = []
for ch in s:
hv = hex(ord(ch)).replace('0x', '')
if len(hv) == 1:
hv = '0'+hv
lst.append(hv)
return reduce(lambda x,y:x+y, lst)
#hex2bit
def hex2bit(string):
novi = bin(int(string, 16))[2:]
if len(novi)<8:
pom=8-len(novi)
while pom!=0:
novi = str(0)+novi
pom=pom-1
return novi
def serialRecv():
messageSerRec = ''
global prnReady
while 1:
byte = ser.read()#shuts down here
if not toHex(byte)=='0f':#even if I change it it shuts down
if byte == ack:
print 'ACK'
elif byte == nack:
print 'NACK'
else:
if byte == stx:
messageSerRec = ''
elif byte == etx:
messageSerRecFin = messageSerRec[:-2]
chSum = int ('0x%s'%messageSerRec[-2:],0)
if chSum == crc8(messageSerRecFin):
lockSerial.acquire()
serialBuff.append(messageSerRecFin)
print "Serial Recv: ", messageSerRecFin
lockSerial.release()
ser.write(ack)
prnReady = 1
else: ser.write(nack)
else: messageSerRec = messageSerRec+byte
time.sleep(0.01)
def tcpSend():
while 1:
if serialBuff:
lockSerial.acquire()
conn.send(serialBuff[0])
print "Tcp Send: ", serialBuff[0]
serialBuff.remove(serialBuff[0])
lockSerial.release()
time.sleep(0.01)
def tcpRecv():
pom=""
while 1:
messageTcpRec = connl.recv(25)
i=0
if len(messageTcpRec)>0:
while i<len(messageTcpRec):
if not messageTcpRec[i]==';':
pom=pom+messageTcpRec[i]
else:
prnBuff.append(pom)
pom=""
i=i+1
print prnBuff
#if not messageTcpRec=="":
# print "Tcp Recv: ", messageTcpRec
# if messageTcpRec[:2] in prnCmd:
# lockPrn.acquire()
# prnBuff.append(messageTcpRec)
# lockPrn.release()
# elif tcpBuff:
# lockTcp.acquire()
# tcpBuff.append(messageTcpRec)
# lockTcp.release()
time.sleep(0.01)
def serialSend():
global prnReady
while 1:
#print "prnRdy=", prnReady
if tcpBuff:
print "tcpBuff:", tcpBuff[0]
lockTcp.acquire()
ser.write(stx+tcpBuff[0]+hex(crc8(tcpBuff[0]))[-2:].upper()+etx)
print "Serial Send: ", (tcpBuff[0])
tcpBuff.remove(tcpBuff[0])
lockTcp.release()
if prnBuff:
if prnReady == 1:
lockPrn.acquire()
ser.write(stx+prnBuff[0]+hex(crc8(prnBuff[0]))[-2:].upper()+etx)
print "Serial Send(prn): ", (prnBuff[0])
prnBuff.remove(prnBuff[0])
lockPrn.release()
prnReady = 0
time.sleep(0.01)
thread.start_new_thread(serialRecv,())
thread.start_new_thread(tcpSend,())
thread.start_new_thread(tcpRecv,())
thread.start_new_thread(serialSend,())
while 1:pass
s.close()
So thread serialRecv shuts of when it receives that byte
I've been trying to work this out for last 2-3 days and can't find solution.
Related
Why does my Python P2P client works over LAN but not the Internet and how can I fix this!
I would like to make a p2p messenger and I just don't know why the p2p functionality with UDP Hole Punching is not working. Please help!
Server:
This server holds peers ips and ports for the client.
The ping function pings the peers to check if they are still alive.
'''
import threading
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(("IP_ADDRESS", 8081))
addrs = []
print('Server started...')
def ping(addr):
try:
sock.sendto(b'ping', addr)
sock.settimeout(1)
data, addr = sock.recvfrom(1024)
sock.settimeout(None)
return True
except Exception as ex:
sock.settimeout(None)
return False
while True:
data, addr = sock.recvfrom(1024)
print(addr)
sock.sendto((addr[0]+' '+str(addr[1])).encode(), addr)
for a in addrs:
p = ping(a)
print(p, a)
if p:
sock.sendto((a[0]+' '+str(a[1])).encode(), addr)
addrs.append(addr)
sock.sendto(b'DONE', addr)
'''
Client:
import threading
import socket
import time
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.addrs = []
self.chat_logs = ''
self.peers = ''
self.self_data = ('0.0.0.0', 0)
def recv_thread(self):
while True:
try:
data, addr = self.sock.recvfrom(1024)
if data == b'ping':
self.sock.sendto(b'pong', addr)
else:
data = data.decode()
new_user = True
for a in self.addrs:
if a == addr:
new_user = False
if new_user == False:
self.chat_logs += addr[0]+':'+str(addr[1])+' - '+data+'\n'
else:
self.chat_logs += addr[0]+':'+str(addr[1])+' joined the p2p network... \n'
self.addrs.append(addr)
except Exception as ex:
print(ex)
def send_msg(self):
message = self.messageBox.text()
if len(message) > 0:
self.chat_logs += 'You - '+message+'\n'
self.chatBox.setPlainText(self.chat_logs)
for a in self.addrs:
try:
self.sock.sendto(message.encode(), a)
except:
self.addrs.remove(a)
def get_peers(self, host):
host = host.split(':')
host = (host[0], int(host[1]))
self.sock.sendto(b'PEERS', host)
self.self_data, addr = self.sock.recvfrom(512)
self.self_data = self.self_data.decode().split()
self.self_data = (self.self_data[0], int(self.self_data[1]))
while True:
data, addr = self.sock.recvfrom(512)
if data == b'DONE':
break
else:
data = data.decode().split()
self.addrs.append((data[0], int(data[1])))
print(self.addrs)
for a in self.addrs:
try:
self.sock.sendto(b'join', a)
except:
self.addrs.remove(a)
t = threading.Thread(target=self.recv_thread)
t.start()
def connect_to_pears_network(self):
dlg = CustomDialog()
if dlg.exec():
text = dlg.message.text()
if len(text) > 6:
self.get_peers(text)
else:
pass
I hope I did this post right this is my first time making a post.
Client:
#The program should send two strings and the server should return the interclassed string back
import socket
import time
import sys
HEADERSIZE=10
firstString = input("First string: ")
secondString = input("Second string: ")
host = "127.0.0.1"
port = 8888
firstString = f'{len(firstString):<{HEADERSIZE}}'+firstString
secondString = f'{len(secondString):<{HEADERSIZE}}'+secondString
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(bytes(firstString, 'utf-8'))
s.send(bytes(secondString, 'utf-8'))
fullMsg=''
while 1:
msg = s.recv(8)
if len(msg)<=0:
break
fullMsg += msg.decode('utf-8')
print(fullMsg)
s.close()
Server:
#trebuie trimisa si dimensiunea
import socket
def interclass(firstString , secondString):
i =0
j =0
interString=''
while i < len(firstString) and j < len(secondString):
if firstString[i] < secondString[j]:
interString+=firstString[i]
i=i+1
else:
interString+=secondString[j]
j=j+1
while i < len(firstString):
interString += firstString[i]
i=i+1
while j < len(secondString):
interString+=secondString[j]
j=j+1
return interString
host = "127.0.0.1"
port = 8888;
HEADERSIZE=10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
while True:
conn, addr = s.accept()
messages=[]
newMsg = True
fullMsg = ''
msgLength = -1
while True:
msg = conn.recv(16)
if len(msg)<=0:
break
msg = msg.decode('utf-8')
fullMsg += msg
if len(fullMsg)>=HEADERSIZE and newMsg == True:
newMsg = False
msgLength = int(fullMsg[:HEADERSIZE-1])
fullMsg = fullMsg[HEADERSIZE:HEADERSIZE+1+msgLength]
if not newMsg and len(fullMsg)>=msgLength:
messages.append(fullMsg[:msgLength])
fullMsg = fullMsg[msgLength:]
newMsg = True
interString = interclass(messages[0], messages[1])
conn.sendall(bytes(interString,'utf-8'))
conn.close()
The application works until I try the part where I try to send data from the server. It all blocks at the recv() command in the client. I searched all the internet for a solution and I tried making it a non-blocked socket and deal with exception... Still not working. I would appreciate some help. Thanks!!
I'm trying to develop a very simple client/server program, the server part is working properly but I've a problem with the client part but I can't understand why.
The client's work is very simple, just retrive the counter value from a external device, then I'm trying to send the retrieved data to the server part.
At the beginning the socket is working well, but some time when I should send the data I've got the server exception and after that the Client is not working.
I can't understand if the s.close() function is working properly.
UPDATE: the exception that I got is "errno 110 connection timed out"
Client:
import time, socket, struct, array, json
import Client_Axis
import sys
import serial
import os
import datetime
import re
import packet
import Config_mio
usbport = '/dev/ttyAMA0'
h = "/r/n"
if __name__=="__main__":
"""Main function that starts the server"""
curr_value = "0000000000"
prev_value = ""
line = '111111111111111'
error_counter = 0
people_in = 0
people_out = 0
txtDate = ""
no_updates_counter = 0
while True:
ser = None
try:
# print('1')
ser = serial.Serial('/dev/ttyAMA0', 9600, timeout=1)
# ser.open()
# print('2')
for line in ser.read():
line = ser.readline()
print(line[6:10])
curr_value = line
except:
print('Serial error')
# print('3')
pass
finally:
if ser:
ser.close()
try:
error_counter += 1
# print('1')
response = Client_Axis.Read_Axis_Camera_Occupancy()
content = response.split(",")
people_in_refresh = int(re.search(r'\d+', content[3]).group())
people_out_refresh = int(re.search(r'\d+', content[4]).group())
# print('2')
error_flag = 0
if people_in != people_in_refresh or people_out != people_out_refresh:
people_in = people_in_refresh
people_out = people_out_refresh
try:
# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect client to the server
s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
# Create message and send it to server
timestamp = str(time.time())
# msg = packet("c", timestamp, Config_mio.RbPi_Id, content[3], content[4], None)
msg = "c"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+str(people_in)+","+str(people_out)+","+"None"
# json_message = json.dumps(msg)
# s.send(json_message)
s.send(msg)
print "messaggio INVIATO"
# Close connection when data is sent
#s.close()
except:
print('Server connection error 1')
pass
finally:
s.close()
#AXIS_occup_old = AXIS_occup
#AXIS_occup = response.read()
#my_dict = json.loads(AXIS_occup)
# print(AXIS_occup)
# print(my_dict)
#del my_dict["timestamp"]
#AXIS_occup = my_dict
#error_counter = 0
# print('3')
except:
error_msg = "Error retrieving occupancy from: " + Config_mio.IP_AXIS_Add
error_flag = 1
if (error_flag == 1):
no_updates_counter = 0
print "Error detected: %s \r\n" % error_msg
print error_counter
if (error_counter > 200):
os.system("sudo reboot")
elif (line[6:10] != '1111' and prev_value != curr_value):
try:
# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect client to the server
s.connect((Config_mio.IP_Server_Add, Config_mio.ws_port))
# Create message and send it to server
timestamp = str(time.time())
msg = "r"+","+str(timestamp)+","+str(Config_mio.RbPi_Id)+","+"None"+","+"None"+","+str(line[6:10])
#msg = {"Id": raspberry_id,
# "Ranging": line[6:10],
# "timestamp": timestamp}
#json_message = json.dumps(msg)
#s.send(json_message)
s.send(msg)
print "Message : %s" % msg
# Close connection when data is sent
s.close()
except:
print('Server connection error 2')
pass
else:
no_updates_counter += 1
# Send message despite there are no changes in value
# This is a heartbeat message of 10 min
if (no_updates_counter > 200):
no_updates_counter = 0
AXIS_occup = ""
prev_value = curr_value
# Reboot device every day - routine
# We have 4 cases incase we miss few seconds
txtDate = str(datetime.datetime.fromtimestamp(time.time()))
if (txtDate[11:19] == "00:00:00"):
os.system("sudo reboot")
if (txtDate[11:19] == "00:00:01"):
os.system("sudo reboot")
if (txtDate[11:19] == "00:00:02"):
os.system("sudo reboot")
if (txtDate[11:19] == "00:00:03"):
os.system("sudo reboot")
# Kill time - 1 sec: Remove it for high speed localisation
time.sleep(1)
Server:
import socket
import json
import time
import Config_mio
import packet
import sqlite3 as lite
if __name__ == "__main__":
"""Main function that starts the server"""
# Creates TCP socket in the specified IP address and port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((Config_mio.IP_Server_Add, Config_mio.ws_port))
# Starts server, up to 10 clients are queued
s.listen(Config_mio.Max_Num_Clients)
while True:
conn, addr = s.accept()
#print "sono dopo ascolto"
msg = conn.recv(1024)
print "Data value:",msg
msg = msg.split(",")
if msg[0] == "c":
print "counter msg"
elif msg[0] == "r":
print "range msg",msg[1],msg[2],msg[5]
conn.close()
When I run the admin client after connecting some clients, my admin returns the ip addresses and port numbers fine. If i close the admin and rerun it nothing happens. This has me baffled. I am unsure why it is doing this
#Admin Client
from functools import partial
import ssl
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ts = ssl.wrap_socket(s, certfile="100298750.crt",
keyfile="100298750.key",
ca_certs="5cc515-root-ca.cer")
ts.connect(('192.168.0.5', 4001))
ts.send("Hello\r\n".encode())
if ts.recv(80).decode() == "Admin-Greetings\r\n":
print("The players currently online are:\n")
ts.send("Who\r\n".encode())
for data in iter(partial(ts.recv, 1000), b''):
print(data.decode())
ts.close()
Server
import threading
import socket
import math
import random
import ssl
addressList = []
def within(guess,goal,n):
absValue = abs(guess - goal)
if absValue <= n:
return True
else:
return False
def HandleAdmin(adminSocket,):
while True:
global addressList
(c,a) = adminSocket.accept()
ts = ssl.wrap_socket(c, certfile="5cc515_server.crt",
keyfile="5cc515_server.key",
server_side=True,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs="5cc515-root-ca.cer")
if ts.recv(80).decode() == 'Hello\r\n':
ts.send('Admin-Greetings\r\n'.encode())
if ts.recv(80).decode() == 'Who\r\n':
for i in addressList:
ts.send(i.encode())
ts.close()
return
def HandleClient(c,a):
global addressList
address, port = a
address = str(address) + ' ' + str(port) + '\r\n'
addressList.append(address)
scoreCount = 0
guess = 0
if(c.recv(80).decode()) == 'Hello\r\n':
c.send('Greetings\r\n'.encode())
goal = random.randrange(1,21)
while guess!= goal:
guess =c.recv(80).decode()
guess = int(guess[7:len(guess)-2])
if guess == goal:
c.send('Correct\r\n'.encode())
addressList.remove(address)
c.close()
elif within(guess, goal, 2) == True:
c.send('Close\r\n'.encode())
else:
c.send('Far\r\n'.encode())
else:
c.close()
return
clientSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
clientSocket.bind(("192.168.0.5",4000))
clientSocket.listen(5)
adminSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
adminSocket.bind(("192.168.0.5",4001))
adminSocket.listen(5)
handleAdminThread = threading.Thread(target = HandleAdmin,
args = (adminSocket,))
handleAdminThread.start()
while True:
(c,a) = clientSocket.accept()
clientThread = threading.Thread(target = HandleClient, args = (c,a))
clientThread.start()
If i close the admin and rerun it nothing happens. This has me
baffled. I am unsure why it is doing this
It is simply doing this because the HandleAdmin() server thread code has the line
return
at the end of its loop and thus exits after one run. Drop it, and it is alright.
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')