Sending hex over serial with python

user2199192 picture user2199192 · Mar 22, 2013 · Viewed 49.1k times · Source

This weekend I am going to make a little project. Got a solarcell inverter (Danfoss ULX 3600i) which I will try to connect to my linux machine, to see if I can grab the data from it, how much energy created eg for stats. There is an input for RJ45 connection on it, but with RS485.

I got the cables to connect it through my usb port in the pc with an RS485 converter in between the pc and the inverter.

I am then writing a small python code to make request. However I cant figure out how to send the data correctly.

import serial
import struct

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=19200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS
)

print(ser.isOpen())
thestring = "7E FF 03 00 01 00 02 0A 01 C8 04 D0 01 02 80 00 00 00 00 8E E7 7E"
data = struct.pack(hex(thestring))
#data = struct.pack(hex, 0x7E, 0xFF, 0x03, 0x00, 0x01, 0x00, 0x02, 0x0A, 0x01, 0xC8,      0x04, 0xD0, 0x01, 0x02, 0x80, 0x00, 0x00, 0x00, 0x00, 0x8E, 0xE7, 0x7E)

ser.write(data)
s = ser.read(1)
print(s)
ser.close()

The inverter is using the Danfoss ComLynx protocol (on page 26 is the data I am trying to send):

EDIT: I now can send a request as the LED light on the Adam 4520 RS485 converter is blinking once, however no data back, but get this error when I do a CTRL+C in terminal:

dontommy@dtbeast:~/workspace/python_scripting/src$ ./sollar.py 
True
^CTraceback (most recent call last):
  File "./sollar.py", line 30, in <module>
    s = ser.readline().decode('utf-8')
  File "/usr/local/lib/python3.2/dist-packages/serial/serialposix.py", line 446, in read
    ready,_,_ = select.select([self.fd],[],[], self._timeout)
KeyboardInterrupt

Answer

Vorsprung picture Vorsprung · Mar 26, 2013

Rewrite "thestring" as

thestring = "\x7E\xFF\x03\x00\x01\x00\x02\x0A\x01\xC8\x04\xD0\x01\x02\x80\x00\x00\x00\x00\x8E\xE7\z7E"

You won't need to pack it, you can say data=thestring and send it. This will only work if the various ids in the document match exactly what is on your equipment

You need to figure out how the python "struct" works, how to encode binary and how to put two 4 bit values into one 8 bit byte: clue, see the >> and << operators and the struct pack "B" format