Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import serial
- import crcmod # pip install --user crcmod
- import struct
- import binascii
- import time
- _modbus_crc = crc = crcmod.Crc(poly=0x18005)
- def modbus_crc(frame) :
- '''Generate the modbus CRC for given frame (without the CRC) as bytes().'''
- crc = _modbus_crc.new()
- crc.update(frame)
- # CRC returned in *LITTLE* endian, unless usual modbus
- return struct.pack('<H',crc.crcValue)
- def request_frame(unit, function, register, length) :
- '''Generate a modbus request frame.'''
- payload = struct.pack('>BBHH', unit, function, register, length)
- return payload + modbus_crc(payload)
- def error(what, msg, ret) :
- def ascii(raw) :
- return str(binascii.hexlify(raw), 'ascii')
- print(what)
- print('Frame sent: (%2d byte) %s'%(len(msg),ascii(msg)))
- print('Answer received: (%2d byte) %s'%(len(ret),ascii(ret)))
- def modbus_request(dev, unit, fct, reg, nregs) :
- # generate request frame, send to serial port
- msg = request_frame(unit, fct, reg, nregs)
- dev.write(msg)
- # request max of 1024 bytes, but only wait up to timeout (0.2sec)
- ret = dev.read(1024)
- # check returned packet for
- if len(ret) < 5 or (ret[-2:] != modbus_crc(ret[0:-2])) :
- error('Short message, or wrong CRC in answer.', ret, msg)
- return None
- if ret[0] != unit or ret[1] != fct :
- error('Reply has wrong unit of function.', ret, msg)
- return None
- return ret[3:-2] # only return payload
- # open serial port
- dev = serial.Serial('/dev/ttyUSB0', 9600, stopbits=2, parity='N', timeout=0.2)
- # query these registers, for a 1 phase meter, returns 2 16-bit values, which,
- # when concatenated, correspond to a 32bit IEEE float.
- for reg in 0x00, 0x06, 0x0c, 0x12, 0x18, 0x1e, 0x24, 0x46 :
- payload = modbus_request(dev, unit=1, fct=4, reg=reg, nregs=2)
- if payload is None :
- continue
- v = struct.unpack('>f', payload)[0]
- print('Float register %04x is %f.'%(reg, v))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement