使用python从客户端发送和接收数据

时间:2016-07-06 11:52:34

标签: python python-2.7 sockets wifi tcpclient

我正在使用 RS485 to wifi router

以上Rs485通信模型。

Intailly我尝试使用arduino的简单代码。通过客户端每2S发送一次串行数据。

void setup()
{
Serial.begin(9600);  
}

void loop()
{
 Serial.println("SMCB1,1,1,1,1,2,3,4,5,6,6,7,8,9,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2"); 
  delay(2000);
}

我使用下面的python代码,从客户端1和客户端2接收数据

import socket

TCP_IP = '192.168.1.3'
TCTCP_IP1='192.168.1.2'
TCP_PORT = 8899
BUFFER_SIZE = 100
BUFFER_SIZE1=100
MESSAGE = "Hello, World!"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
s1.connect((TCTCP_IP1, TCP_PORT))

s.send(MESSAGE)
s1.send(MESSAGE)
data = s.recv(BUFFER_SIZE)
data1= s1.recv(BUFFER_SIZE)

s.close()
s1.close()
print "received data:", data
print "received data:", data1

现在我已经上传了Modbus RTU代码,我发送请求并试图获得响应。请求需要以十六进制格式发送。我试过有线通信似乎工作正常。 我在下面分享了请求格式。但是我能够阅读任何正在进行中阅读的过程

import socket

TCP_IP = '192.168.1.3'
TCTCP_IP1='192.168.1.2'
TCP_PORT = 8899
BUFFER_SIZE = 1000
BUFFER_SIZE1=1000

#MESSAGE = "01 03 00 00 00 1d 85 c3"
#MESSAGE1 = "02 03 00 00 00 1d 85 fo"

MESSAGE = "01030000001d85c3"
MESSAGE1 = "02030000001d85fo"

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

print "Before connect"

s.connect((TCP_IP, TCP_PORT))
s1.connect((TCTCP_IP1, TCP_PORT))

print "After connect"
print MESSAGE
print MESSAGE1

print "request before sending"
s.send(MESSAGE1)
s1.send(MESSAGE)
print "request after  sending"
data = s.recv(BUFFER_SIZE)
data1= s1.recv(BUFFER_SIZE)

s.close()
s1.close()
print "received data:", data
print "received data:", data1

现在我面临的问题我正在尝试发送请求,但我无法得到答复。通过有线通信,我可以获得数据。

1 个答案:

答案 0 :(得分:0)

我修改了代码,我得到了回复。需要帮助将数据转换为十进制格式。低估了收到的数据是否正确。我需要将整个数据转换为十进制格式。让我知道如何实现这个目标

import socket
TCP_IP = '192.168.1.3'
TCP_PORT = 8899
BUFFER_SIZE = 1000

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect((TCP_IP, TCP_PORT))

s.send('01030000001d85c3'.decode('hex'))

Decode_hex='01030000001d85c3'.decode('hex')
print Decode_hex
print "decode hex:",Decode_hex


data = s.recv(1024)
s.close()

print "data recieved :", data
d=data.encode('hex').upper()
print 'Hexa decimal value deceived:',repr(d)

mod_hex=data.encode('hex').upper()
print 'Hexa decimal value Modified:',repr(mod_hex)

#print 'received',d
decimal=int(d,20)
print "decimal converted value:",decimal

这是附加的文件

  

解码十六进制:收到的数据::被欺骗的六角十进制值:   ' 01033A0000000D00120041003400410056004B000000000000000000DF000000E1000000E700F800E600EC0000000000000000001F00010001000100DC496E'   Hexa十进制值修改:   ' 01033A0000000D00120041003400410056004B000000000000000000DF000000E1000000E700F800E600EC0000000000000000001F00010001000100DC496E'   十进制转换值:   214364598880234057828928146607817359105482384449559342919180352622648369076567392756173653847449417881349290133492250705920000000000003670016655364096025643555734