0

This is my first time using stack overflow, if I did something wrong, forgive me, please I have to control a thermal chamber by Modbus and got a sample code in python 2.7

import socket
session = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
session.connect((HOST,PORT))
array = [1, 6, 0, 2, 11, 184, 47, 72]   
#ID,Write,Register,how many registers->2,data,data,CRC,CRC
binstring = ''
for item in array:
    binstring += chr(item)
session.send(binstring)

the binstring in debug mode is '\\x01\\x06\\x00\\x02\\x0b\\xb8/H'

I try to modify the for loop as below (python3.6)

for i in range(len(array)):
    array[i] = bytes([array[i]])  #method1
    array[i]=str(array[i]).encode('utf-8')  #method2
binstring= array[0]+array[1]+array[2]+array[3]+array[1]+array[4]+array[5]+array[6]+array[7]

binstring in method1 debug mode: b'\x01\x06\x00\x02\x06\x0b\xb8/H'

binstring in method2 debug mode: b'16026111844772'

Both 2 methods not work... Also try to modify the send function

#session.send(binstring)
session.sendall(binstring)

I need more suggestions

Thank you

KKC
  • 1
  • 1
  • 1
    It's helpful if you provide a little background and describe what you mean by "not work" (e.g. are you getting an error?). It looks like you are attempting to communicate with a Modbus RTU device via UDP (!); If that is the case you are probably best using [bytearray](https://stackoverflow.com/a/18311133/11810946) (your examples are a little confusing without an explanation of your goal). Note that if may be beneficial to look at existing [Modbus packages](https://stackoverflow.com/a/21459211/11810946). – Brits Aug 25 '22 at 06:03
  • Hi Brits, Thanks for your response, I am not an English native speaker, so I can't present very exactly, the "not work" means I send the binstring to thermal chamber(to set target temperature 30 degree Celsius), but the control panel still show 70, not 30. after that, I can't get any response from thermal chamber also. and I found there is a stupid "typo" in my code, but is not major reason. there is a extra array[1] in binstring. – KKC Aug 26 '22 at 00:53
  • In the final solution and work in my case: for i in range(len(array)): binstring +=bytes([array[I]]) – KKC Aug 26 '22 at 00:59
  • Great to hear that you have got it working. Unfortunately without details of your objective it was difficult to help (but fully understand the language barrier!). I suspect `bytearray` (`binstring = bytearray([1, 6, 0, 2, 11, 184, 47, 72])`) might be a slightly simpler solution. I'll vote to close this issue off. – Brits Aug 26 '22 at 01:42

0 Answers0