pythontcp发送字符串_python通过TCP套接字发送/接收十六进制数据

I have a ethenet access control device that is said to be able to communicate via TCP.

How can i send a pachet by entering the HEX data, since this is what i have from their manual (a standard format for the communication packets sent and received after each command)

Can you please show some example code or links to get started....

standard return packet from the terminal

Size (bytes)

BS (0x08) : ASCII Character 1

STX (0x02) : ASCII Character 1

LENGTH : length from BS to ETX 4

TID : system unique I.D. 1

RESULT 1

DATA : returned parameter N

CHECKSUM : byte sum from BS to DATA 1

ETX (0x03) : ASCII Character 1

Standard command packet to the terminal

Size (bytes)

ACK (0x06) : ASCII Character 1

STX (0x02) : ASCII Character 1

LENGTH : length from ACK to ETX 4

TID : system unique I.D. (ex: 1) 1

COMMAND 1

Access Key(Optional) 6

DATA : command parameter N

CHECKSUM : byte sum from ACK to DATA 1

ETX (0x03) : ASCII Character 1

This packet starts from ACK.

In this packet, multiple byte value must be started from MSB.

For example, if length was 10, LENGTH is 0x00 0x00 0x00 0x0a.

解决方案

I'd use struct.pack to prepare the string of bytes to send, from the data you want to send. Be sure to start the packing format with > to mean you want big-endian ordering and standard sizes, since they document that so clearly!

So (I don't know what the "optional" means for the access key, I'll assume it means that the field can be all-zero bytes if you have no access key), if "data" is already a string of bytes and "command" a small unsigned integer for example, something like...:

def stringfor(command, data, accesskey='\0'*6, tid=1):

length = 16 + len(data)

prefix = struct.pack('>BBIBB6s', 6, 2, length, tid, command, accesskey)

checksum = sum(ord(c) for c in prefix) &0xFF

return prefix + chr(checksum) + chr(3)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值