import serial
import gpio
gpio.setup(6, 'out') # TR Pin
pySerial = serial.Serial("/dev/ttyS1", baudrate=9600, timeout=None, bytesize=8, parity='N', stopbits=1, xonxoff=0, rtscts=0, dsrdtr=0)
# def init_gpio():
# gpio.log.setLevel(logging.WARNING)
def get_modbus_crc(int_array):
value = 0xFFFF
for i in range(len(int_array)):
value ^= int_array[i]
for j in range(8):
if (value & 0x01) == 1:
value = (value >> 1) ^ 0xA001
else:
value >>= 1
return [value & 0xff, (value >> 8) & 0xff]
# , port="/dev/ttyS1", baudrate=9600, timeout=10, write_timeout=10
def write_modbus(command_list):
full_command_list = command_list + get_modbus_crc(command_list)
read_count = full_command_list[5] * 2 + 5 if full_command_list[1] == 3 else len(full_command_list)
gpio.set(6, 1)
pySerial.write(full_command_list)
pySerial.flush()
gpio.set(6, 0)
read_data = pySerial.read(read_count)
data_list = list(read_data)
# pySerial.cancel_read()
# pySerial.cancel_write()
# pySerial.close()
return data_list
# port = serial.Serial("/dev/ttyS1", baudrate=9600, timeout=1, bytesize=8, parity='N', stopbits=1, xonxoff=0,rtscts=0,dsrdtr=0)
while True:
# cmd = '3,5,0,1,0,0,157,232'.encode()
# port.write('3,5,0,1,255,0,220,24'.encode()) # 開
# cmd = [3,5,0,1,0,0,157,232]
# command_list = [3,5,0,1,0,0]
command_list = [1,3,0,0,0,2]
print(format(command_list))
data_list = write_modbus(command_list)
print(format(data_list))
# command_list = [3,5,0,1,255,0]
# print(format(command_list))
# data_list = write_modbus(command_list)
# print(format(data_list))