def read(self, n, request): # if request[3:5]==b'06' or request[3:5]==b'16': # normal=1 # else: # normal=0 # n=n+2 message = bytearray() while len(message) < n: if self.debug: minimalmodbus._print_out('\nMinimalModbus debug mode. CurrentMessage {}, Message length: {}, Expected Length{}'. \ format(str(message), len(message), n)) message += self._socket.recv(1024) # if normal==0: # extra=message[-6:-4] # extraVal=ord(minimalmodbus._hexdecode(extra.decode())) # del message[-6:-4] #crappy implementation of modbus # crc=message[-4:-2] # readcrc=ord(minimalmodbus._hexdecode(crc.decode())) # modifiedcrc=minimalmodbus._hexencode(minimalmodbus._numToOneByteString(readcrc+extraVal)) # message[-4:-2]=modifiedcrc.encode() return (message)
def open(self): self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #self._socket.connect(("192.168.20.119", 4001)) try: self._socket.connect((self.gatewayAddress, self.gatewayPort)) minimalmodbus._print_out('\nConnected to RS485 gateway at {}'. \ format(self.port)) except socket.error as e: minimalmodbus._print_out('\nMinimalModbus debug mode. Error while connecting to RS485 gateway at {}: {}'. \ format(self.port, e))
def getTemperatureAndHumidity(instrument, delay): time.sleep(delay) minimalmodbus._print_out('\nTemperature (degC):') minimalmodbus._print_out(repr(instrument.read_register(ModbusRegisters.TEMP_REG_NUM, 2, 4, True)))#FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\nHumidity (%):') minimalmodbus._print_out(repr(instrument.read_register(ModbusRegisters.HUM_REG_NUM, 2, 4, False)))#FC 4: Read Register
parser.add_argument("-j", "--json", action="count", default=0, help='Encode out to json') parser.add_argument("-t", "--test", action="count", default=0) parser.add_argument("-e", "--emu", action="count", default=0) args = parser.parse_args() if (args.port == None): data = {} data["ports"] = serial_ports() if (args.json): if (args.emu): minimalmodbus._print_out("{\"ports\":[\"COM99\"]}") exit() json_data = json.dumps(data) minimalmodbus._print_out(json_data) else: minimalmodbus._print_out("Need set the port, Ex: -port COM3") minimalmodbus._print_out("Avaible:") ports_data = json.dumps(data["ports"]) minimalmodbus._print_out(ports_data) exit() if (args.address == None): minimalmodbus._print_out("Need set the address, Ex: -address 1") exit() PORTNAME = args.port[0] #PORTNAME = '/dev/ttyUSB0'
# as none of the modules in the standard library handles python 2.6 to 3.x MODE = minimalmodbus.MODE_RTU BAUDRATE = DEFAULT_BAUDRATE PORT_NAME = DEFAULT_PORT_NAME for arg in sys.argv: if arg.startswith('-ascii'): MODE = minimalmodbus.MODE_ASCII elif arg.startswith('-rtu'): MODE = minimalmodbus.MODE_RTU elif arg.startswith('-b'): if len(arg) < 3: minimalmodbus._print_out( 'Wrong usage of the -b option. Use -b9600') sys.exit() BAUDRATE = int(arg[2:]) elif arg.startswith('-D'): if len(arg) < 3: minimalmodbus._print_out( 'Wrong usage of the -D option. Use -D/dev/ttyUSB0 or -DCOM4') sys.exit() PORT_NAME = arg[2:] ################################ ## Create instrument instance ## ################################ instrument = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDRESS, MODE) instrument.serial.baudrate = BAUDRATE
def getEsp8266ResetPeriod(instrument): minimalmodbus._print_out('\nEsp8266ResetPeriod:') esp8266ResetPeriod = instrument.read_register(ModbusRegistersConf.ESP8266_HOLD_RESET_PERIOD_REG_NUM, 0, 3, False); minimalmodbus._print_out(repr(esp8266ResetPeriod))#FC 3: Read Holding Register return esp8266ResetPeriod
def getSlaveAddress(instrument): minimalmodbus._print_out('\nSlaveAddress:') slaveAddress = instrument.read_register(ModbusRegistersConf.SLAVE_ADDRESS_REG_NUM, 0, 3, False); minimalmodbus._print_out(repr(slaveAddress))#FC 3: Read Holding Register return slaveAddress
def main(): ################################# ## Read command line arguments ## ################################# # Do manual parsing of command line, # as none of the modules in the standard library handles python 2.6 to 3.x MODE = minimalmodbus.MODE_RTU BAUDRATE = DEFAULT_BAUDRATE PORT_NAME = DEFAULT_PORT_NAME for arg in sys.argv: if arg.startswith('-ascii'): MODE = minimalmodbus.MODE_ASCII elif arg.startswith('-rtu'): MODE = minimalmodbus.MODE_RTU elif arg.startswith('-b'): if len(arg) < 3: minimalmodbus._print_out('Wrong usage of the -b option. Use -b9600') sys.exit() BAUDRATE = int(arg[2:]) elif arg.startswith('-D'): if len(arg) < 3: minimalmodbus._print_out('Wrong usage of the -D option. Use -D/dev/ttyUSB0 or -DCOM4') sys.exit() PORT_NAME = arg[2:] ################################ ## Create instrument instance ## ################################ instrument = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDRESS, MODE) instrument.serial.baudrate = BAUDRATE instrument.serial.timeout = TIMEOUT instrument.debug = False instrument.precalculate_read_size = True text = '\n' text += '###############################################################\n' text += '## Hardware test with Delta DTB4824 ##\n' text += '## Minimalmodbus version: {:8} ##\n'.format(minimalmodbus.__version__) text += '## ##\n' text += '## Modbus mode: {:15} ##\n'.format(instrument.mode) text += '## Python version: {}.{}.{} ##\n'.format(sys.version_info[0], sys.version_info[1], sys.version_info[2]) text += '## Baudrate (-b): {:>5} bits/s ##\n'.format(instrument.serial.baudrate) text += '## Platform: {:15} ##\n'.format(sys.platform) text += '## ##\n' text += '## Port name (-D): {:15} ##\n'.format(instrument.serial.port) text += '## Slave address: {:<15} ##\n'.format(instrument.address) text += '## Timeout: {:0.3f} s ##\n'.format(instrument.serial.timeout) text += '## Full file path: ' + os.path.abspath(__file__) + '\n' text += '###############################################################\n' minimalmodbus._print_out(text) minimalmodbus._print_out(repr(instrument)) if RUN_VERIFY_EXAMPLES: ######################################################################################### ## Examples from page 11 in the "DTB Series Temperature Controller Instruction Sheet", ## ## version 2010-04-20 ## ######################################################################################### instrument.debug = False # Read two registers starting at 0x1000. This is process value (PV) and setpoint (SV). # Should send '\x01\x03\x10\x00\x00\x02\xc0\xcb' OK! minimalmodbus._print_out('\nReading register 0x1000 and 0x1001:') minimalmodbus._print_out(repr(instrument.read_registers(0x1000, 2))) # Read 9 bits starting at 0x0810. # Should send '\x01\x02\x08\x10\x00\x09\xbb\xa9' OK! minimalmodbus._print_out('\nReading 9 bits starting at 0x0810:') minimalmodbus._print_out(repr(instrument._performCommand(2, '\x08\x10\x00\x09'))) # Write value 800 to register 0x1001. This is a setpoint of 80.0 degrees (Centigrades, dependent on setting). # Should send '\x01\x06\x10\x01\x03\x20\xdd\xe2' OK! instrument.write_register(0x1001, 0x0320, functioncode=6) # Response from instrument: '\x01\x06\x10\x01\x03 \xdd\xe2' OK! # Note that the slave will indicate an error if the CoSH parameter in the controller # does not allow writing. # ASCII mode: Request ':010610010320C5\r\n' # Response ':010610010320C5\r\n' # Write 1 to one bit at 0x0810. This is "Communication write in enabled". # Should send '\x01\x05\x08\x10\xff\x00\x8f\x9f' OK! instrument.write_bit(0x0810, 1) # Response from instrument: '\x01\x05\x08\x10\xff\x00\x8f\x9f' OK! #instrument.read_register(0x1001) # ASCII mode: Request ':010310010001EA\r\n' # Response ':0103020320D7\r\n' if RUN_READOUT_PRESENT_SETTINGS: ############################### ## Read out present settings ## ############################### instrument.debug = False minimalmodbus._print_out('\nPV: ' + str(instrument.read_register(0x1000))) minimalmodbus._print_out('Setpoint: ' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('Sensor type: ' + str(instrument.read_register(0x1004))) minimalmodbus._print_out('Control method: ' + str(instrument.read_register(0x1005))) minimalmodbus._print_out('Heating/cooling selection: ' + str(instrument.read_register(0x1006))) minimalmodbus._print_out('Output 1 value: ' + str(instrument.read_register(0x1012, 1))) minimalmodbus._print_out('Output 2 value: ' + str(instrument.read_register(0x1013, 1))) minimalmodbus._print_out('System alarm setting: ' + str(instrument.read_register(0x1023))) minimalmodbus._print_out('LED status: ' + str(instrument.read_register(0x102A))) minimalmodbus._print_out('Pushbutton status: ' + str(instrument.read_register(0x102B))) minimalmodbus._print_out('Firmware version: ' + str(instrument.read_register(0x102F))) minimalmodbus._print_out('LED AT: ' + str(instrument.read_bit(0x0800))) minimalmodbus._print_out('LED Out1: ' + str(instrument.read_bit(0x0801))) minimalmodbus._print_out('LED Out2: ' + str(instrument.read_bit(0x0802))) minimalmodbus._print_out('RUN/STOP setting: ' + str(instrument.read_bit(0x0814))) if RUN_START_AND_STOP_REGULATOR: ################################################### ## Start and stop the regulator, change setpoint ## ################################################### instrument.debug = False SLEEP_TIME = 2 instrument.write_bit(0x0814, 0) # Stop setpoint_value = 25 instrument.write_register(0x1001,setpoint_value, 1, functioncode=6) minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) time.sleep(SLEEP_TIME) instrument.write_bit(0x0814, 1) # Run minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) time.sleep(SLEEP_TIME) setpoint_value = 35 instrument.write_register(0x1001,setpoint_value, 1, functioncode=6) minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) time.sleep(SLEEP_TIME) instrument.write_bit(0x0814, 0) # Stop minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) if RUN_MEASURE_ROUNDTRIP_TIME: #################################################### ## Measure roundtrip time ## ## Loop setpoint value (20 to 50 deg C, and back) ## #################################################### instrument.debug = False NUMBER_OF_VALUES = 100 START_VALUE = 200 STOP_VALUE = 500 STEPSIZE = 5 value = START_VALUE step = STEPSIZE text = '\nSetting the SP value {} times. Baudrate {} bits/s.'.format(NUMBER_OF_VALUES, instrument.serial.baudrate) minimalmodbus._print_out(text) start_time = time.time() for i in range(NUMBER_OF_VALUES): if value > STOP_VALUE or value < START_VALUE: step = -step value += step instrument.write_register(0x1001, value, functioncode=6) time_per_value = (time.time() - start_time)*float(SECONDS_TO_MILLISECONDS)/NUMBER_OF_VALUES text = 'Time per value: {:0.1f} ms.'.format(time_per_value) minimalmodbus._print_out(text) if RUN_VERIFY_TWO_INSTRUMENTS: ####################################################### ## Verify that two instruments can use the same port ## ####################################################### instrument.debug = False minimalmodbus._print_out('\nInstrument1 SP:') minimalmodbus._print_out(str(instrument.read_register(0x1001, 1))) instrument2 = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDRESS, MODE) instrument2.debug = False instrument2.serial.baudrate = BAUDRATE instrument2.serial.timeout = TIMEOUT minimalmodbus._print_out('\nInstrument2 SP:') minimalmodbus._print_out(str(instrument2.read_register(0x1001, 1)))
def getCo2(instrument, delay): time.sleep(delay) minimalmodbus._print_out('\nCO2(ppm):') minimalmodbus._print_out(repr(instrument.read_register(ModbusRegisters.CO2_REG_NUM, 0, 4, False)))#FC 4: Read Register
# as none of the modules in the standard library handles python 2.6 to 3.x MODE = minimalmodbus.MODE_RTU BAUDRATE = DEFAULT_BAUDRATE PORT_NAME = DEFAULT_PORT_NAME for arg in sys.argv: if arg.startswith('-ascii'): MODE = minimalmodbus.MODE_ASCII elif arg.startswith('-rtu'): MODE = minimalmodbus.MODE_RTU elif arg.startswith('-b'): if len(arg) < 3: minimalmodbus._print_out('Wrong usage of the -b option. Use -b9600') sys.exit() BAUDRATE = int(arg[2:]) elif arg.startswith('-D'): if len(arg) < 3: minimalmodbus._print_out('Wrong usage of the -D option. Use -D/dev/ttyUSB0 or -DCOM4') sys.exit() PORT_NAME = arg[2:] ################################ ## Create instrument instance ## ################################ instrument = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDRESS, MODE) instrument.serial.baudrate = BAUDRATE instrument.serial.timeout = TIMEOUT
""" # Exceptions - parameters: 4, 24, 32, 33, 34, 52(!) minimalmodbus._checkInt(paramnumber, minvalue=1, maxvalue=52, description='parameter number') ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING PIXSYS ATR620 MODBUS MODULE') PORTNAME = '/dev/ttyUSB0' ADDRESS = 2 minimalmodbus._print_out('Port: ' + str(PORTNAME) + ', Address: ' + str(ADDRESS)) a = PixsysATR620(PORTNAME, ADDRESS) a.debug = False minimalmodbus._print_out('SP1: {0}'.format( a.get_sp_loop1())) #minimalmodbus._print_out( 'SP1 target: {0}'.format( a.get_sptarget_loop1() )) minimalmodbus._print_out('SP2: {0}'.format( a.get_sp_loop2()))
The bits value (int). """ payloadToSlave = minimalmodbus._numToTwoByteString(registeraddress) + \ minimalmodbus._numToTwoByteString(4) payloadFromSlave = self._performCommand(functioncode, payloadToSlave) minimalmodbus._checkResponseByteCount(payloadFromSlave) registerdata = payloadFromSlave[1:] return int(minimalmodbus._hexlify(registerdata)) ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING HHC-R4I4D MODBUS MODULE') PORTNAME = '/dev/ttyUSB0' ADDRESS = 1 minimalmodbus._print_out('Port: ' + str(PORTNAME) + ', Address: ' + str(ADDRESS)) instr = RelayModule(PORTNAME, ADDRESS) instr.debug = False minimalmodbus._print_out('Digital inputs: {0}'.format( instr.get_digital_inputs())) instr.set_relay_output(1, 1) minimalmodbus._print_out('Relay 1 output: {0}'.format( instr.get_relay_output(1)))
def set_ch_status(self, channel): """Enable channel.""" mask = 1 << channel reg = self.read_register(214, 0, 4) value = reg and mask self.write_register(214, value) ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING ADAM4117 MODBUS MODULE') # Assume ADAM4117 controller connected to /dev/ttyO1 # Default Modbus @:1, serial port parameter: 9600,8,n,1 a = Apm303('/dev/ttymxc1', 1) a.debug = True a.handle_local_echo = False minimalmodbus._print_out('Burn-out channel 0 {0}'.format( a.get_burnout_ch0())) minimalmodbus._print_out('Burn-out channel 1 {0}'.format( a.get_burnout_ch1())) minimalmodbus._print_out('Burn-out channel 2 {0}'.format( a.get_burnout_ch2())) minimalmodbus._print_out('Burn-out channel 3 {0}'.format(
reg_name = 'Measurement Index' self.write_register(int(HOLDING_REGISTER[reg_name][REGISTER_ADDRESS_COL])-1, value, functioncode = 6) if __name__ == '__main__': usage = 'Usage: python %s <serial_port> <modbus_id>' % sys.argv[0] #serial_by_id = '/dev/ttyUSB0' #modbus_id = 2 if len(sys.argv) > 2: serial_by_id = sys.argv[1] modbus_id = sys.argv[2] else: minimalmodbus._print_out('Python Script Param Error!') minimalmodbus._print_out(usage) sys.exit(0) minimalmodbus._print_out('Testing Delta PVI PRI-H5 with serial port: %s and modbus ID: %s' % (serial_by_id, modbus_id)) instr = DeltaPRIH5(serial_by_id,int(modbus_id)) instr.serial.baudrate = 9600 instr.serial.bytesize = 8 instr.serial.parity = 'N' instr.serial.stopbits = 1 instr.serial.timeout = 0.1 #instr.debug=True instr.set_register_measurement_index()
# """Return the brake type of wind turbine.""" # return self.read_register(7, 0, 3) # def set_modbus_ad(self,modbus_ad): """Set the modbus address of the Aeolos controller""" """Register address: 0x1999 """ self.write_registers(6553, modbus_ad, 0) ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out( 'TESTING Aeolos Modbus Wind and Solar hybrid controller') # Assume Aeolos controller connected to /dev/ttyS1 # Default Modbus @:1, serial port parameter: 19200,8,n,1 a = Aeolos('/dev/ttyS1', 1) a.debug = True a.handle_local_echo = False minimalmodbus._print_out('Battery voltage {0}'.format(a.get_vbat())) minimalmodbus._print_out('Solar voltage {0}'.format(a.get_vsolar())) minimalmodbus._print_out('Solar current {0}'.format(a.get_isolar())) minimalmodbus._print_out('Wind voltage {0}'.format(a.get_vwind())) minimalmodbus._print_out('Wind current (before) {0}'.format( a.get_iwind_before())) minimalmodbus._print_out('Wind current (after) {0}'.format( a.get_iwind_after()))
def get_threshold_alarm1(self): """Return the threshold value for Alarm1.""" return self.read_register(10241, 1) def is_set_alarmsummary(self): """Return True if some alarm is triggered.""" return self.read_register(10213, 1) > 0 ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING MURPHY MPC-10 MODBUS MODULE') a = MPC10Controller('/dev/ttyUSB0', 1) a.debug = False minimalmodbus._print_out('Engine RPM: {0}'.format(a.get_engine_rpm())) minimalmodbus._print_out('System Voltage: {0}'.format(a.get_voltage())) minimalmodbus._print_out('Controller State: {0}'.format(a.get_controller_state())) minimalmodbus._print_out('Controller Mode: {0}'.format(a.get_mode())) minimalmodbus._print_out('Ambient temp: {0}'.format(a.get_ambient_temp())) minimalmodbus._print_out('Shutdown Status 1: {0}'.format(a.get_active_shutdown_status_1())) minimalmodbus._print_out('Shutdown Status 2: {0}'.format(a.get_active_shutdown_status_2())) minimalmodbus._print_out('Shutdown Status 3: {0}'.format(a.get_active_shutdown_status_3())) minimalmodbus._print_out('MPC10 Serial: {0}'.format(a.get_serial_number())) minimalmodbus._print_out('Start Temperature: {0}'.format(a.get_start_temperature())) minimalmodbus._print_out('Stop Temperature: {0}'.format(a.get_stop_temperature()))
## Alarms def get_threshold_alarm1(self): """Return the threshold value for Alarm1.""" return self.read_register(10241, 1) def is_set_alarmsummary(self): """Return True if some alarm is triggered.""" return self.read_register(10213, 1) > 0 ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING EUROTHERM 3500 MODBUS MODULE') a = Eurotherm3500('/dev/cvdHeatercontroller', 1) a.debug = False minimalmodbus._print_out('SP1: {0}'.format(a.get_sp_loop1())) minimalmodbus._print_out('SP1 target: {0}'.format(a.get_sptarget_loop1())) minimalmodbus._print_out('SP2: {0}'.format(a.get_sp_loop2())) minimalmodbus._print_out('SP-rate Loop1 disabled: {0}'.format(a.is_sprate_disabled_loop1())) minimalmodbus._print_out('SP1 rate: {0}'.format(a.get_sprate_loop1())) minimalmodbus._print_out('OP1: {0}%'.format(a.get_op_loop1())) minimalmodbus._print_out('OP2: {0}%'.format(a.get_op_loop2())) minimalmodbus._print_out('Alarm1 threshold: {0}'.format(a.get_threshold_alarm1())) minimalmodbus._print_out('Alarm summary: {0}'.format(a.is_set_alarmsummary())) minimalmodbus._print_out('Manual mode Loop1: {0}'.format(a.is_manual_loop1())) minimalmodbus._print_out('Inhibit Loop1: {0}'.format(a.is_inhibited_loop1()))
def main(): ################################# ## Read command line arguments ## ################################# # Do manual parsing of command line, # as none of the modules in the standard library handles python 2.6 to 3.x MODE = minimalmodbus.MODE_RTU BAUDRATE = DEFAULT_BAUDRATE PORT_NAME = DEFAULT_PORT_NAME for arg in sys.argv: if arg.startswith('-ascii'): MODE = minimalmodbus.MODE_ASCII elif arg.startswith('-rtu'): MODE = minimalmodbus.MODE_RTU elif arg.startswith('-b'): if len(arg) < 3: minimalmodbus._print_out( 'Wrong usage of the -b option. Use -b9600') sys.exit() BAUDRATE = int(arg[2:]) elif arg.startswith('-D'): if len(arg) < 3: minimalmodbus._print_out( 'Wrong usage of the -D option. Use -D/dev/ttyUSB0 or -DCOM4' ) sys.exit() PORT_NAME = arg[2:] ################################ ## Create instrument instance ## ################################ instrument = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDRESS, MODE) instrument.serial.baudrate = BAUDRATE instrument.serial.timeout = TIMEOUT instrument.debug = False instrument.precalculate_read_size = True text = '\n' text += '###############################################################\n' text += '## Hardware test with Delta DTB4824 ##\n' text += '## Minimalmodbus version: {:8} ##\n'.format( minimalmodbus.__version__) text += '## ##\n' text += '## Modbus mode: {:15} ##\n'.format( instrument.mode) text += '## Python version: {}.{}.{} ##\n'.format( sys.version_info[0], sys.version_info[1], sys.version_info[2]) text += '## Baudrate (-b): {:>5} bits/s ##\n'.format( instrument.serial.baudrate) text += '## Platform: {:15} ##\n'.format( sys.platform) text += '## ##\n' text += '## Port name (-D): {:15} ##\n'.format( instrument.serial.port) text += '## Slave address: {:<15} ##\n'.format( instrument.address) text += '## Timeout: {:0.3f} s ##\n'.format( instrument.serial.timeout) text += '## Full file path: ' + os.path.abspath(__file__) + '\n' text += '###############################################################\n' minimalmodbus._print_out(text) minimalmodbus._print_out(repr(instrument)) if RUN_VERIFY_EXAMPLES: ######################################################################################### ## Examples from page 11 in the "DTB Series Temperature Controller Instruction Sheet", ## ## version 2010-04-20 ## ######################################################################################### instrument.debug = False # Read two registers starting at 0x1000. This is process value (PV) and setpoint (SV). # Should send '\x01\x03\x10\x00\x00\x02\xc0\xcb' OK! minimalmodbus._print_out('\nReading register 0x1000 and 0x1001:') minimalmodbus._print_out(repr(instrument.read_registers(0x1000, 2))) # Read 9 bits starting at 0x0810. # Should send '\x01\x02\x08\x10\x00\x09\xbb\xa9' OK! minimalmodbus._print_out('\nReading 9 bits starting at 0x0810:') minimalmodbus._print_out( repr(instrument._performCommand(2, '\x08\x10\x00\x09'))) # Write value 800 to register 0x1001. This is a setpoint of 80.0 degrees (Centigrades, dependent on setting). # Should send '\x01\x06\x10\x01\x03\x20\xdd\xe2' OK! instrument.write_register(0x1001, 0x0320, functioncode=6) # Response from instrument: '\x01\x06\x10\x01\x03 \xdd\xe2' OK! # Note that the slave will indicate an error if the CoSH parameter in the controller # does not allow writing. # ASCII mode: Request ':010610010320C5\r\n' # Response ':010610010320C5\r\n' # Write 1 to one bit at 0x0810. This is "Communication write in enabled". # Should send '\x01\x05\x08\x10\xff\x00\x8f\x9f' OK! instrument.write_bit(0x0810, 1) # Response from instrument: '\x01\x05\x08\x10\xff\x00\x8f\x9f' OK! #instrument.read_register(0x1001) # ASCII mode: Request ':010310010001EA\r\n' # Response ':0103020320D7\r\n' if RUN_READOUT_PRESENT_SETTINGS: ############################### ## Read out present settings ## ############################### instrument.debug = False minimalmodbus._print_out('\nPV: ' + str(instrument.read_register(0x1000))) minimalmodbus._print_out('Setpoint: ' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('Sensor type: ' + str(instrument.read_register(0x1004))) minimalmodbus._print_out('Control method: ' + str(instrument.read_register(0x1005))) minimalmodbus._print_out('Heating/cooling selection: ' + str(instrument.read_register(0x1006))) minimalmodbus._print_out('Output 1 value: ' + str(instrument.read_register(0x1012, 1))) minimalmodbus._print_out('Output 2 value: ' + str(instrument.read_register(0x1013, 1))) minimalmodbus._print_out('System alarm setting: ' + str(instrument.read_register(0x1023))) minimalmodbus._print_out('LED status: ' + str(instrument.read_register(0x102A))) minimalmodbus._print_out('Pushbutton status: ' + str(instrument.read_register(0x102B))) minimalmodbus._print_out('Firmware version: ' + str(instrument.read_register(0x102F))) minimalmodbus._print_out('LED AT: ' + str(instrument.read_bit(0x0800))) minimalmodbus._print_out('LED Out1: ' + str(instrument.read_bit(0x0801))) minimalmodbus._print_out('LED Out2: ' + str(instrument.read_bit(0x0802))) minimalmodbus._print_out('RUN/STOP setting: ' + str(instrument.read_bit(0x0814))) if RUN_START_AND_STOP_REGULATOR: ################################################### ## Start and stop the regulator, change setpoint ## ################################################### instrument.debug = False SLEEP_TIME = 2 instrument.write_bit(0x0814, 0) # Stop setpoint_value = 25 instrument.write_register(0x1001, setpoint_value, 1, functioncode=6) minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) time.sleep(SLEEP_TIME) instrument.write_bit(0x0814, 1) # Run minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) time.sleep(SLEEP_TIME) setpoint_value = 35 instrument.write_register(0x1001, setpoint_value, 1, functioncode=6) minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) time.sleep(SLEEP_TIME) instrument.write_bit(0x0814, 0) # Stop minimalmodbus._print_out('\nSetpoint:' + str(instrument.read_register(0x1001, 1))) minimalmodbus._print_out('RUN/STOP setting:' + str(instrument.read_bit(0x0814))) if RUN_MEASURE_ROUNDTRIP_TIME: #################################################### ## Measure roundtrip time ## ## Loop setpoint value (20 to 50 deg C, and back) ## #################################################### instrument.debug = False NUMBER_OF_VALUES = 100 START_VALUE = 200 STOP_VALUE = 500 STEPSIZE = 5 value = START_VALUE step = STEPSIZE text = '\nSetting the SP value {} times. Baudrate {} bits/s.'.format( NUMBER_OF_VALUES, instrument.serial.baudrate) minimalmodbus._print_out(text) start_time = time.time() for i in range(NUMBER_OF_VALUES): if value > STOP_VALUE or value < START_VALUE: step = -step value += step instrument.write_register(0x1001, value, functioncode=6) time_per_value = (time.time() - start_time ) * float(SECONDS_TO_MILLISECONDS) / NUMBER_OF_VALUES text = 'Time per value: {:0.1f} ms.'.format(time_per_value) minimalmodbus._print_out(text) if RUN_VERIFY_TWO_INSTRUMENTS: ####################################################### ## Verify that two instruments can use the same port ## ####################################################### instrument.debug = False minimalmodbus._print_out('\nInstrument1 SP:') minimalmodbus._print_out(str(instrument.read_register(0x1001, 1))) instrument2 = minimalmodbus.Instrument(PORT_NAME, SLAVE_ADDRESS, MODE) instrument2.debug = False instrument2.serial.baudrate = BAUDRATE instrument2.serial.timeout = TIMEOUT minimalmodbus._print_out('\nInstrument2 SP:') minimalmodbus._print_out(str(instrument2.read_register(0x1001, 1)))
repr(registertype), repr(list(REGISTER_START.keys())))) # Calculate register address address = REGISTER_START[registertype] + \ patternnumber * REGISTER_OFFSET_PER_PATTERN[registertype] + \ stepnumber * REGISTER_OFFSET_PER_STEP[registertype] return address ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING OMEGA CN7500 MODBUS MODULE') PORTNAME = '/dev/tty.usbserial-FTFO1057' ADDRESS = 10 minimalmodbus._print_out('Port: ' + str(PORTNAME) + ', Address: ' + str(ADDRESS)) instr = OmegaCN7500(PORTNAME, ADDRESS) minimalmodbus._print_out('Control: {0}'.format( instr.get_control_mode())) minimalmodbus._print_out('SP: {0}'.format( instr.get_setpoint())) minimalmodbus._print_out('PV: {0}'.format( instr.get_pv()))
def get_threshold_alarm1(self): """Return the threshold value for Alarm1.""" return self.read_register(10241, 1) def is_set_alarmsummary(self): """Return True if some alarm is triggered.""" return self.read_register(10213, 1) > 0 ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out( 'TESTING EUROTHERM 3500 MODBUS MODULE') a = Eurotherm3500('/dev/cvdHeatercontroller', 1) a.debug = False minimalmodbus._print_out( 'SP1: {0}'.format( a.get_sp_loop1() )) minimalmodbus._print_out( 'SP1 target: {0}'.format( a.get_sptarget_loop1() )) minimalmodbus._print_out( 'SP2: {0}'.format( a.get_sp_loop2() )) minimalmodbus._print_out( 'SP-rate Loop1 disabled: {0}'.format( a.is_sprate_disabled_loop1() )) minimalmodbus._print_out( 'SP1 rate: {0}'.format( a.get_sprate_loop1() )) minimalmodbus._print_out( 'OP1: {0}%'.format( a.get_op_loop1() )) minimalmodbus._print_out( 'OP2: {0}%'.format( a.get_op_loop2() )) minimalmodbus._print_out( 'Alarm1 threshold: {0}'.format( a.get_threshold_alarm1() )) minimalmodbus._print_out( 'Alarm summary: {0}'.format( a.is_set_alarmsummary() )) minimalmodbus._print_out( 'Manual mode Loop1: {0}'.format( a.is_manual_loop1() )) minimalmodbus._print_out( 'Inhibit Loop1: {0}'.format( a.is_inhibited_loop1() ))
#!/usr/bin/env python import minimalmodbus import omegacn7500 import settings instr = omegacn7500.OmegaCN7500(settings.port,settings.rimsaddressint) # port name, slave address minimalmodbus._print_out( 'Control: {0}'.format( instr.get_control_mode() )) minimalmodbus._print_out( 'SP: {0}'.format( instr.get_setpoint() )) minimalmodbus._print_out( 'PV: {0}'.format( instr.get_pv() )) minimalmodbus._print_out( 'OP1: {0}'.format( instr.get_output1() )) minimalmodbus._print_out( 'Is running: {0}'.format( instr.is_running() )) minimalmodbus._print_out( 'Start pattern: {0}'.format( instr.get_start_pattern_no() )) minimalmodbus._print_out('DONE!')
def close(self): self._socket.close() if self.debug: minimalmodbus._print_out('\nMinimalModbus debug mode. Disconnected from RS485 gateway at {}'. \ format(self.port))
# Calculate register address address = REGISTER_START[registertype] + \ patternnumber * REGISTER_OFFSET_PER_PATTERN[registertype] + \ stepnumber * REGISTER_OFFSET_PER_STEP[registertype] return address ######################## ## Testing the module ## ######################## if __name__ == '__main__': minimalmodbus._print_out('TESTING OMEGA CN7500 MODBUS MODULE') PORTNAME = '/dev/tty.usbserial-FTFO1057' ADDRESS = 10 minimalmodbus._print_out( 'Port: ' + str(PORTNAME) + ', Address: ' + str(ADDRESS) ) instr = OmegaCN7500(PORTNAME, ADDRESS) minimalmodbus._print_out( 'Control: {0}'.format( instr.get_control_mode() )) minimalmodbus._print_out( 'SP: {0}'.format( instr.get_setpoint() )) minimalmodbus._print_out( 'PV: {0}'.format( instr.get_pv() )) minimalmodbus._print_out( 'OP1: {0}'.format( instr.get_output1() )) minimalmodbus._print_out( 'Is running: {0}'.format( instr.is_running() )) minimalmodbus._print_out( 'Start pattern: {0}'.format( instr.get_start_pattern_no() ))
def _communicate(self, request, number_of_bytes_to_read): """Talk to the slave via a serial port. Args: request (str): The raw request that is to be sent to the slave. number_of_bytes_to_read (int): number of bytes to read Returns: The raw data (string) returned from the slave. Raises: TypeError, ValueError, IOError Note that the answer might have strange ASCII control signs, which makes it difficult to print it in the promt (messes up a bit). Use repr() to make the string printable (shows ASCII values for control signs.) Will block until reaching *number_of_bytes_to_read* or timeout. If the attribute :attr:`Instrument.debug` is :const:`True`, the communication details are printed. If the attribute :attr:`Instrument.close_port_after_each_call` is :const:`True` the serial port is closed after each call. Timing:: Request from master (Master is writing) | | Response from slave (Master is reading) | | ----W----R----------------------------W-------R---------------------------------------- | | | |<----- Silent period ------>| | | | Roundtrip time ---->|-------|<-- The resolution for Python's time.time() is lower on Windows than on Linux. It is about 16 ms on Windows according to http://stackoverflow.com/questions/157359/accurate-timestamping-in-python For Python3, the information sent to and from pySerial should be of the type bytes. This is taken care of automatically by MinimalModbus. """ minimalmodbus._checkString(request, minlength=1, description='request') minimalmodbus._checkInt(number_of_bytes_to_read) if self.debug: minimalmodbus._print_out('\nMinimalModbus debug mode. Writing to instrument (expecting {} bytes back): {!r} ({})'. \ format(number_of_bytes_to_read, request, minimalmodbus._hexlify(request))) if self.close_port_after_each_call: self.serial.open() #self.serial.flushInput() TODO if sys.version_info[0] > 2: request = bytes(request, encoding='latin1' ) # Convert types to make it Python3 compatible # Sleep to make sure 3.5 character times have passed minimum_silent_period = minimalmodbus._calculate_minimum_silent_period( self.serial.baudrate) time_since_read = time.time() - _LATEST_READ_TIMES.get( self.serial.port, 0) if time_since_read < minimum_silent_period: sleep_time = minimum_silent_period - time_since_read if self.debug: template = 'MinimalModbus debug mode. Sleeping for {:.1f} ms. ' + \ 'Minimum silent period: {:.1f} ms, time since read: {:.1f} ms.' text = template.format( sleep_time * _SECONDS_TO_MILLISECONDS, minimum_silent_period * _SECONDS_TO_MILLISECONDS, time_since_read * _SECONDS_TO_MILLISECONDS) minimalmodbus._print_out(text) time.sleep(sleep_time) elif self.debug: template = 'MinimalModbus debug mode. No sleep required before write. ' + \ 'Time since previous read: {:.1f} ms, minimum silent period: {:.2f} ms.' text = template.format( time_since_read * _SECONDS_TO_MILLISECONDS, minimum_silent_period * _SECONDS_TO_MILLISECONDS) minimalmodbus._print_out(text) # Write request latest_write_time = time.time() self.serial.write(request) # Read and discard local echo if self.handle_local_echo: localEchoToDiscard = self.serial.read(len(request)) if self.debug: template = 'MinimalModbus debug mode. Discarding this local echo: {!r} ({} bytes).' text = template.format(localEchoToDiscard, len(localEchoToDiscard)) minimalmodbus._print_out(text) if localEchoToDiscard != request: template = 'Local echo handling is enabled, but the local echo does not match the sent request. ' + \ 'Request: {!r} ({} bytes), local echo: {!r} ({} bytes).' text = template.format(request, len(request), localEchoToDiscard, len(localEchoToDiscard)) raise IOError(text) # Read response answer = self.serial.read(number_of_bytes_to_read, request) _LATEST_READ_TIMES[self.serial.port] = time.time() if self.close_port_after_each_call: self.serial.close() if sys.version_info[0] > 2: answer = str(answer, encoding='latin1' ) # Convert types to make it Python3 compatible if self.debug: template = 'MinimalModbus debug mode. Response from instrument: {!r} ({}) ({} bytes), ' + \ 'roundtrip time: {:.1f} ms. Timeout setting: {:.1f} ms.\n' text = template.format( answer, minimalmodbus._hexlify(answer), len(answer), (_LATEST_READ_TIMES.get(self.serial.port, 0) - latest_write_time) * _SECONDS_TO_MILLISECONDS, self.serial.timeout * _SECONDS_TO_MILLISECONDS) minimalmodbus._print_out(text) if len(answer) == 0: raise IOError('No communication with the instrument (no answer)') return answer
def getAmberRedThreshold(instrument): minimalmodbus._print_out('\nAmberRedThreshold:') amberRedThreshold = instrument.read_register(ModbusRegistersConf.AMBERRED_THRESHOLD_REG_NUM, 0, 3, False); minimalmodbus._print_out(repr(amberRedThreshold))#FC 3: Read Holding Register return amberRedThreshold
def getSgp30Parameters(instrument, delay): time.sleep(delay) minimalmodbus._print_out('\nTVOC(ppb):') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.TVOC_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\neCO2(ppm):') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.ECO2_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\nTVOC Average(ppb):') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.TVOC_AVG_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\neCO2 Average(ppm):') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.ECO2_AVG_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\nTVOC base:') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.TVOC_BASE_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\neCO2 base:') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.ECO2_BASE_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\nEthanol raw (ppm):') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.ETHANOL_BASE_REG_NUM, 0, 4, False))) #FC 4: Read Register time.sleep(delay) minimalmodbus._print_out('\nH2 raw (ppm):') minimalmodbus._print_out( repr( instrument.read_register(ModbusRegisters.H2RAW_BASE_REG_NUM, 0, 4, False))) #FC 4: Read Register
def getTemperatureOffset(instrument): minimalmodbus._print_out('\nTemperatureOffset:') temperatureOffset = instrument.read_register(ModbusRegistersConf.SHT31_TEMPERATURE_OFFSET_REG_NUM, 0, 3, False); minimalmodbus._print_out(repr(temperatureOffset))#FC 3: Read Holding Register return temperatureOffset
self.write_register(999, 1991) number_registers = 3 s = None while s is None: try: s = self.read_registers(1000, number_registers, functioncode=3) except: pass self.write_register(999, 1191) l = l + s return l if __name__ == '__main__': minimalmodbus._print_out('HERU FTX MODBUS REGISTER') a = HeruFTX('/dev/ttyUSB0', 1) #port, slaveadress a.mode = minimalmodbus.MODE_RTU a.serial.stopbits = 1 a.serial.timeout = 0.2 #Timeout might be adjusted to allow full reading of message a.debug = False a.precalculate_read_size = False print("---------------") print("| Coil Status |") print("---------------") minimalmodbus._print_out('{:40}{:20}{}'.format('Register name', 'Value', 'Description\n')) l = a.coil_status() description = [ ' ',
def getGreenAmberThreshold(instrument): minimalmodbus._print_out('\nGreenAmberThreshold:') greenAmberThreshold = instrument.read_register(ModbusRegistersConf.GREENAMBER_THRESHOLD_REG_NUM, 0, 3, False); minimalmodbus._print_out(repr(greenAmberThreshold))#FC 3: Read Holding Register return greenAmberThreshold
int(HOLDING_REGISTER[reg_name][REGISTER_ADDRESS_COL]) - 1, value, functioncode=6) if __name__ == '__main__': usage = 'Usage: python %s <serial_port> <modbus_id>' % sys.argv[0] #serial_by_id = '/dev/ttyUSB0' #modbus_id = 2 if len(sys.argv) > 2: serial_by_id = sys.argv[1] modbus_id = sys.argv[2] else: minimalmodbus._print_out('Python Script Param Error!') minimalmodbus._print_out(usage) sys.exit(0) minimalmodbus._print_out( 'Testing Delta PVI PRI-H5 with serial port: %s and modbus ID: %s' % (serial_by_id, modbus_id)) instr = DeltaPRIH5(serial_by_id, int(modbus_id)) instr.serial.baudrate = 9600 instr.serial.bytesize = 8 instr.serial.parity = 'N' instr.serial.stopbits = 1 instr.serial.timeout = 0.1 #instr.debug=True