コード例 #1
0
class ModbusTcpNode:
    def __init__(self):
        rospy.init_node("modbus_tcp_client_node", anonymous=True)
        rospy.Subscriber("/vacuum_gripper", Bool, self.callback)

        self.UNIT = 0x01
        self.client = ModbusClient("192.168.0.150", port=502)
        self.client.connect()
        rq = self.client.write_coil(0, False)
        rospy.loginfo("Initialize Modbus Tcp Node")

    def __del__(self):
        self.client.close()

    def callback(self, data):
        if data.data == True:
            rq = self.client.write_coil(0, True)
            rr = self.client.read_coils(0, 1, unit=self.UNIT)
        else:
            rq = self.client.write_coil(0, False)
            rr = self.client.read_coils(0, 1, unit=self.UNIT)

        if not rr.bits[0] == data.data:
            rospy.logerr("Failed to send the command. Please try agian")
        else:
            rospy.loginfo("Vaccum gripper is " +
                          ("activated" if data.data else "deactivated"))
コード例 #2
0
def read_states(host, port=MODBUS_PORT, uid=None):
    client = ModbusTcpClient(host, port)
    try:
        if uid is not None:
            result = client.read_coils(uid, 1)
            print('{:3d} : {}'.format(uid, _status(result.bits[0])))
        else:
            result = client.read_coils(0, MAX_COILS_COUNT)
            for i in range(len(result.bits)):
                print('{:3d} : {}'.format(i, _status(result.bits[i])))
    finally:
        client.close()
コード例 #3
0
def feeder_check(req):
    client = ModbusTcpClient('192.168.1.202', 5020)
    coil_y = client.read_coils(0, 1)
    coil_r = client.read_coils(1, 1)
    coil_b = client.read_coils(2, 1)
    coil_m = client.read_coils(3, 1)
    client.close()

    srv = feeder_srvResponse()
    srv.yellow = coil_y.bits[0]
    srv.red = coil_r.bits[0]
    srv.blue = coil_b.bits[0]
    srv.missing = coil_m.bits[0]
    return srv
コード例 #4
0
def turn_states(host, port=MODBUS_PORT, state=False, uid=None):
    client = ModbusTcpClient(host, port)
    try:
        if uid is not None:
            client.write_coil(uid, state)
            result = client.read_coils(uid, 1)
            print('{:3d} : {}'.format(uid, _status(result.bits[0])))
        else:
            values = [state for _ in range(MAX_COILS_COUNT)]
            client.write_coils(0, values)
            result = client.read_coils(0, MAX_COILS_COUNT)
            for i in range(len(result.bits)):
                print('{:3d} : {}'.format(i, _status(result.bits[i])))
    finally:
        client.close()
コード例 #5
0
def read_coils():
    form = ReusableForm(request.form)

    print form.errors
    if request.method == 'POST':
        ip = request.form['ip']
        port = request.form['port']
        address = request.form['address']
        value = request.form['value']
        unitId = request.form['unitId']
        print ip, " ", port, " ", address

        host = ip
        port = int(port)
        client = ModbusTcpClient(host, port)
        client.connect()

        rr = client.read_coils(int(address), int(value), unit=int(unitId))
        assert (rr.function_code < 0x80)  # test that we are not an error
        print(rr)
        print(rr.bits)

        if form.validate():
            flash(str(rr.bits))
        else:
            flash('Error')

    return render_template('read-coils.html', form=form)
コード例 #6
0
def loop_process():
    # Main Process (template = flip-flop)
    err_count = 0
    registre_count = 10

    while True:
        sleep(1)
        try:
            client = ModbusTcpClient(modbus_server_ip, modbus_server_port)

            coils = client.read_coils(0, count=registre_count, unit=UNIT)
            coils = coils.bits[:registre_count]
            # flipping booleans from list coils
            coils = [not i for i in coils]
            client.write_coils(0, coils)

            registers = client.read_holding_registers(0,
                                                      count=registre_count,
                                                      unit=UNIT)
            registers = registers.registers[:registre_count]
            registers = [i + 1 for i in registers]
            client.write_registers(0, registers, unit=UNIT)

            updateGPIO(coils, registers)
        except Exception as err:
            print('[error] %s' % err)
            err_count += 1
            if err_count == 5:
                print('[error] 5 errors happened in the process ! exiting...')
                sys.exit(1)
コード例 #7
0
def get_values(address,port):

	client = ModbusTcpClient(str(address), int(port))
	succeed = client.connect()

	if succeed:
		result = client.read_holding_registers(address=0,count=15,unit=1)
		result2 = client.read_coils(address=0,count=15,unit=1)
		client.close()
		results = {}
		for r in range(0,15):
			register = result.registers[r]
			results["r"+str(r)] = str(register)+"%"
			
			coil = result2.bits[r]
			if coil:
				coil='ON'
			else:
				coil='OFF'

			results["c"+str(r)] = coil

		#print(results)

		return jsonify(results)
	else:
		return render_template('index.html', error="Modbus slave is disconnected")
コード例 #8
0
ファイル: script.py プロジェクト: scroix/nodel-recipes
class ModbusPoll(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()
        self.client = None
        self.current = [True, True, True, True, True, True]

    def run(self):
        self.client = ModbusTcpClient(param_ipAddress)
        while not self.event.isSet():
            lock.acquire()
            try:
                result = self.client.read_coils(0, 6, unit=UNIT)
                for num in range(0, 5):
                    if (result.bits[num] != self.current[num]):
                        func = globals()['local_event_Input' + str(num + 1) +
                                         ('On'
                                          if self.current[num] else 'Off')]
                        func.emit()
                    self.current[num] = result.bits[num]
            except AttributeError:
                local_event_Error.emit('Could not connect to ADAM')
            except Exception, e:
                local_event_Error.emit(e)
            finally:
コード例 #9
0
def readMBcoils(clientIP, coil, number=1):
    from pymodbus.client.sync import ModbusTcpClient, ConnectionException

    client = ModbusTcpClient(clientIP)
    values = []
    try:
        rawresult = client.read_coils(coil, number)

    except ConnectionException:
        # print('we were unable to connect to the host')
        statuscode = 7
    else:
        # print(rawresult)
        try:
            resultregisters = rawresult.bits[0:number]
        except AttributeError:
            statuscode = rawresult.exception_code
        else:
            statuscode = 0
            values = resultregisters
    client.close()
    result = {
        'message': messagefrommbstatuscode(statuscode),
        'statuscode': statuscode,
        'values': values
    }
    return result
コード例 #10
0
    def run(self, measured_instrument):
        while self.running:
            c = ModbusTcpClient(measured_instrument.ip)
            start = time.time()
            while not c.connect():
                log.debug("Can't connect, retry in 0.5s")
                self.measurements.append((time.time(), measured_instrument.ip,
                                          measured_instrument.name,
                                          ((time.time() - start) * 1000), -2))
                time.sleep(0.5)

            if measured_instrument.type == "input_register":
                response = c.read_input_registers(
                    measured_instrument.address,
                    1,
                    unit=measured_instrument.unit)
                measured_instrument.setData(response.registers[0])

            if measured_instrument.type == "coil":
                response = c.read_coils(measured_instrument.address,
                                        1,
                                        unit=measured_instrument.unit)
                measured_instrument.setData(response.bits[0])
            c.close()
            self.measurements.append(
                (time.time(), measured_instrument.ip, measured_instrument.name,
                 ((time.time() - start) * 1000), 1))

            log.debug("Tick: {}".format(self.tick))
            time.sleep(self.tick)
コード例 #11
0
ファイル: controller.py プロジェクト: wichmann/spots
class ModbusModule():
    def __init__(self, io_module_name, ip):
        logger.debug('Creating new controller with name {} and address {}.'.format(io_module_name, ip))
        self.io_module_name = io_module_name
        self.ip_address = ip
        self.controller_type = CONTROLLER_TYPE.Modbus
        # build connection object
        self.client = ModbusClient(ip, port=config.DEFAULT_MODBUS_PORT)
        self.client.connect()

    def __del__(self):
        self.client.close()

    def __str__(self):
        return 'Controller "{}" at address {}'.format(self.io_module_name, self.ip_address)

    def get_bit(self, address):
        try:
            result = self.client.read_coils(address)
            bit_value = result.bits[0]
        except ConnectionException:
            logger.error('Could not connect to Modbus module "{}"!'
                         .format(self.io_module_name))
            bit_value = False
        return bit_value

    def set_bit(self, address, value):
        try:
            self.client.write_coil(address, value)
        except ConnectionException:
            logger.error('Could not connect to Modbus module "{}"!'
                         .format(self.io_module_name))
コード例 #12
0
ファイル: main.py プロジェクト: odjadane/industrial-networks
class OpenPlcModbus:
    def __init__(self):
        self.plc = ModbusClient('localhost', port=502)

    def get_counter_value(self):
        request = self.plc.read_holding_registers(1024, 1)
        value = request.registers[0]
        return value

    def get_motor_status(self):
        request = self.plc.read_coils(0, 1)
        status = request.bits[0]
        return status

    def turn_on(self, action):
        if action:
            self.plc.write_coil(1, True)
        else:
            self.plc.write_coil(1, False)

    def turn_off(self, action):
        if action:
            self.plc.write_coil(2, True)
        else:
            self.plc.write_coil(2, False)

    def close(self):
        self.plc.close()
コード例 #13
0
 def read_coils(self, command):
     parser = argument_parser()
     command = 'read_coils ' + command
     spec = parser.parse_args(command.split())
     response = _ModbusClient.read_coils(
         self, spec.address, spec.count, unit=spec.unit_id)
     return response
コード例 #14
0
def talker():
    rospy.init_node('modbus_client', anonymous=True)
    pub_feeder = rospy.Publisher('feeder', feeder_msg, queue_size=1)
    client = ModbusTcpClient('localhost', 5020)

    rate = rospy.Rate(10) # 10hz
    while not rospy.is_shutdown():
        coil1 = client.read_coils(0,1)
        coil2 = client.read_coils(1,1)
        coil3 = client.read_coils(2,1)
        msg = feeder_msg()
        msg.yellow =coil1.bits[0]
        msg.red =coil2.bits[0]
        msg.blue =coil3.bits[0]

        pub_feeder.publish(msg)
        rate.sleep()
コード例 #15
0
ファイル: Modbus_Test.py プロジェクト: UHH-ISS/honeygrove
 def testWriteCoilFalse(self):
     client = ModbusTcpClient("localhost", 502)
     client.write_coil(1, 1, unit=1)
     # Coil that is not 0 is True
     client.write_coil(1, 0, unit=1)
     result = client.read_coils(1, 1, unit=1)
     self.assertIs(result.bits[0], False)
     client.close()
コード例 #16
0
ファイル: motor.py プロジェクト: annabadsi/escapehome
def write_via_tcp_modbus(address, state):
    try:
        client = ModbusTcpClient(IP_ADDRESS, port=502, timeout=10)
        client.write_coil(address, state)
        result = client.read_coils(address, 1)
        log.debug(result)
        client.close()
    except RuntimeError as err:
        log.debug(err)
コード例 #17
0
ファイル: motor.py プロジェクト: annabadsi/escapehome
def read_via_tcp_modbus(address):
    try:
        client = ModbusTcpClient(IP_ADDRESS, port=502, timeout=10)
        result = client.read_coils(address, 1)
        log.debug(result)
        client.close()
        return result.bits[0]
    except RuntimeError as err:
        log.debug(err)
コード例 #18
0
def basic_client():
    client = ModbusTcpClient(HOST, port=PORT)
    try:
        client.write_coil(1, True)
    except ConnectionException as err:
        print("Ensure you have a server running, error: %s" % err)
        return
    result = client.read_coils(1, 1, unit=UNIT)
    print("Result of read_coils is %s" % result.bits[0])
    client.close()
コード例 #19
0
    def post(self):
        query = self.reqparse.parse_args()
        client = ModbusClient(query['ip'], query['port'])
        client.connect()

        data = None
        start_address = query['start_address']
        count = query['count']
        if query['type_prefix'] == ModbusTypePrefix.DISCRETE_INPUT.value:
            data = client.read_discrete_inputs(start_address, count, unit=1)
        elif query['type_prefix'] == ModbusTypePrefix.COIL.value:
            data = client.read_coils(start_address, count, unit=1)
        elif query['type_prefix'] == ModbusTypePrefix.INPUT_REGISTER.value:
            data = client.read_input_registers(start_address, count, unit=1)
        elif query['type_prefix'] == ModbusTypePrefix.HOLDING_REGISTER.value:
            data = client.read_holding_registers(start_address, count, unit=1)

        client.close()

        result = []

        print(data.registers)
        # if hasattr(data, 'bits'):
        #     d = data.bits
        # else:
        #     d = data.registers

        decoder = BinaryPayloadDecoder.fromRegisters(data.registers,
                                                     byteorder=Endian.Big,
                                                     wordorder=Endian.Big)
        # decoder.reset()
        # decoded = {
        #     'string': decoder.decode_string(8),
        #     'float': decoder.decode_32bit_float(),
        #     '16uint': decoder.decode_16bit_uint(),
        #     'ignored': decoder.skip_bytes(2),
        #     '8int': decoder.decode_8bit_int(),
        #     'bits': decoder.decode_bits(),
        # }
        e = decoder.decode_16bit_int()
        i = 0
        while e is not False:
            try:
                print e
                result.append({'address': i + start_address, 'value': e})
                i += 1
                e = decoder.decode_16bit_int()
            except:
                e = False

        # for i, v in enumerate(d):
        #     result.append({'address': i+start_address, 'value': v})

        reg_fields = {'address': fields.Integer, 'value': fields.Integer}
        return {'registers': [marshal(reg, reg_fields) for reg in result]}
コード例 #20
0
class Client:
    def __init__(self):
        self.client = None
        self.handle = None
        self.ip = '127.0.0.1'
        self.port = 502

    def setup(self, config):
        self.handle = config
        self.ip = config['ipv4']['value']
        self.port = config['port']['value']
        self.client = ModbusTcpClient(self.ip, self.port)

    def execute(self, fc, addr, length=1, values=None):
        result = None
        if fc == 1:
            temp = self.client.read_coils(addr, length)
            result = []
            for i in range(temp.byte_count):
                t2 = temp.bits[i * 16:(i + 1) * 16]
                result.append(''.join([str(int(x)) for x in t2]))
        elif fc == 2:
            temp = self.client.read_discrete_inputs(addr, length)
            result = []
            for i in range(temp.byte_count):
                t2 = temp.bits[i * 16:(i + 1) * 16]
                result.append(''.join([str(int(x)) for x in t2]))
        elif fc == 3:
            temp = self.client.read_holding_registers(addr, length).registers
            result = ['{0:016b}'.format(x) for x in temp]
        elif fc == 4:
            temp = self.client.read_input_registers(addr, length).registers
            result = ['{0:016b}'.format(x) for x in temp]
        elif fc == 5:
            if values:
                self.client.write_coil(addr, values[0])
        elif fc == 6:
            if values:
                self.client.write_register(addr, values[0])
        elif fc == 15:
            if values:
                self.client.write_coils(addr, values)
        elif fc == 16:
            if values:
                self.client.write_registers(addr, values)
        return result

    def update_config(self, conf):
        self.ip = conf['ipv4']['value']
        self.port = conf['port']['value']
        self.client = ModbusTcpClient(self.ip, self.port)
        self.handle = conf

    def connect(self):
        return self.client.connect()
コード例 #21
0
def check_gen():
    #
    # Opens up a Modbus Connection with the PLC and
    # checks coil at address 2 for a TRUE value.
    # When that occurs, pushes control to the
    # start_gen() function.
    #
    client = ModbusClient(target)
    while True:
        result = client.read_coils(2, 1)
        if result.bits[0]:
            start_gen()
コード例 #22
0
ファイル: charge_controller.py プロジェクト: gitj/PMC-Turbo
class ChargeController():
    def __init__(self, address):
        self.host,self.port = address
        self.device_name = '<unknown>'
        self.serial_number = '<unknown>'
        self.update_serial_number_and_device_name()
        self.readable_values = {}
        self.coil_register_indices = range(1, NUM_COIL_REGISTERS + 1)

    def update_serial_number_and_device_name(self):
        try:
            self.measure_eeprom()
            serial_number_bytes = [('%04x' % self.eeprom_measurement[k])[::-1] for k in range(57536, 57540)]
            self.serial_number = ''.join(serial_number_bytes)[::2]
            device_model = self.eeprom_measurement[0xE0CC]
            if device_model:
                self.device_name = 'TriStar-MPPT-60'
            else:
                self.device_name = 'TriStar-MPPT-45'
        except Exception:
            logger.exception("Could not get serial number or device name for %s:%d" % (self.host,self.port))

    def measure(self):
        self.client = ModbusTcpClient(host=self.host, port=self.port)
        measurement = OrderedDict(epoch=time.time())
        result = self.client.read_input_registers(0, NUM_REGISTERS, unit=0x01,)
        try:
            measurement.update(zip(range(NUM_REGISTERS), result.registers))
        except AttributeError as e:
            print e, result
            raise
        self.measurement = measurement
        self.client.close()
        return self.measurement

    def measure_eeprom(self):
        self.client = ModbusTcpClient(host=self.host, port=self.port)
        self.eeprom_measurement = OrderedDict(epoch=time.time())
        eeprom_measurement = self.client.read_input_registers(EEPROM_BATCH_1[0], EEPROM_BATCH_1[1] - EEPROM_BATCH_1[0],
                                                              unit=0x01).registers
        eeprom_measurement += self.client.read_input_registers(EEPROM_BATCH_2[0], EEPROM_BATCH_2[1] - EEPROM_BATCH_2[0],
                                                               unit=0x01).registers
        eeprom_measurement += self.client.read_input_registers(EEPROM_BATCH_3[0], EEPROM_BATCH_3[1] - EEPROM_BATCH_3[0],
                                                               unit=0x01).registers
        self.eeprom_measurement.update(zip(EEPROM_REGISTER_INDICES, eeprom_measurement))
        self.client.close()
        return self.eeprom_measurement

    def measure_coils(self):
        self.coil_measurement = OrderedDict(epoch=time.time())
        self.coil_measurement.update(
            zip(range(NUM_COIL_REGISTERS), self.client.read_coils(0, NUM_COIL_REGISTERS, unit=0x01).bits))
        return self.coil_measurement
コード例 #23
0
def run_sync_client():
    client = ModbusClient('localhost', port=5020)
    client.connect()

    for i in range(5):
        log.debug("Reading Coils")
        client.read_coils(1, 1 + i, unit=UNIT)
        # first param - address: The starting address to read from
        # second param - count: The number of coils to read
        time.sleep(0.1)
        # 100ms przerwy między Reading Coils
        log.debug("Reading Coils")
        client.read_coils(2, 3 + i, unit=UNIT)
        time.sleep(0.1)

        log.debug("Write to a Coil")
        client.write_coils(1, 4, unit=UNIT)
        time.sleep(5)
        # 5s przerwy między write coils
        log.debug("Write to a Coil")
        client.write_coil(4, 3, unit=UNIT)
        time.sleep(5)

    # log.debug("Read discrete inputs")
    # client.read_discrete_inputs(0, 8, unit=UNIT)
    # # first param - The starting address to read from
    # # second param - The number of discretes to read
    #
    # log.debug("Write to a holding register and read back")
    # client.write_register(1, 10, unit=UNIT)
    # # first param - The starting address to write to
    # # second param - The value to write to the specified address
    #
    # log.debug("Read back")
    # client.read_holding_registers(1, 1, unit=UNIT)
    # # first param - The starting address to read from
    # # second param - The number of registers to read

    client.close()
コード例 #24
0
ファイル: modbus_RTU.py プロジェクト: ddiggins/PRSCablebot
def run_sync_client():
    """ Main loop for Modbus communication """
    # Define client connection
    client = ModbusClient(method='rtu', port='/dev/tty0', timeout=1, baudrate=9600)
    client.connect()

    # Specify target device
    log.debug("Reading Coils")
    rr = client.read_coils(0, 16, unit=UNIT)
    log.debug(rr)

    # Close Client
    client.close()
コード例 #25
0
ファイル: modbus.py プロジェクト: annabadsi/escapehome
    def read(device_address=2):
        """
        This function reads the state of a device at the given address.
        For example: True, if the box is opened (False -> if the box is closed).
        """

        try:
            client = ModbusTcpClient(BOX_IP, port=502, timeout=10)
            result = client.read_coils(device_address, 1)
            logger.debug(result)
            client.close()
            return result.bits[0]
        except RuntimeError as err:
            logger.debug(err)
コード例 #26
0
class TestFacilityModbusClient(object):
    """Modbus client to communicate with robot test facility using the pymodbus lib"""
    _client = None

    def _is_connection_open(self):
        if self._client is None:
            return False
        else:
            return True

    def open(self):
        if self._is_connection_open():
            return
        self._client = ModbusTcpClient('169.254.60.99', 502)
        self._client.connect()

    def close(self):
        if not self._is_connection_open():
            return
        self._client.close()
        self._client = None

    def read(self, start_register, end_register):
        if not self._is_connection_open():
            raise NoOpenConnection("No open connection to server")
        return self._client.read_coils(start_register, end_register)

    def write(self, register, value):
        if not self._is_connection_open():
            raise NoOpenConnection("No open connection to server")
        response = self._client.write_coil(register, value)

    def set_T1_IO_to(self, flag):
        self.write(_OPERATION_MODE_T1_REGISTER, flag)

    def set_T2_IO_to(self, flag):
        self.write(_OPERATION_MODE_T2_REGISTER, flag)

    def set_Auto_IO_to(self, flag):
        self.write(_OPERATION_MODE_AUTO_REGISTER, flag)

    def set_Emergency_IO_to(self, flag):
        self.write(_EMERGENCY_REGISTER, flag)

    def set_Acknowledge_IO_to(self, flag):
        self.write(_ACKNOWLEDGE_REGISTER, flag)

    def set_Enabling_IO_to(self, flag):
        self.write(_ENABLING_REGISTER, flag)
コード例 #27
0
def LEDUpdateThread(pin, update_interval, e):
	print 'LEDUpdateThread'
	client = ModbusTcpClient(args.ip)
	GPIO.setup(pin, GPIO.OUT)
	while True:
		if not e.isSet():
			result = client.read_coils(0, 1)
			if result is not None:
				pin_status = result.bits[0]
				GPIO.output(pin, pin_status)
				print pin_status
			time.sleep(update_interval)
		else:
			break
	client.close()
	print 'LED thread stoped'
コード例 #28
0
ファイル: modbus.py プロジェクト: annabadsi/escapehome
    def send(device, value):
        """
        This function writes a new value to a device of the given ip address.
        The value has to be a boolean. For example: True, to open the box by the motor (False -> close the box).
        """
        logger.debug(
            'send method with device: {device} and value = {value}'.format(
                device=str(device), value=str(value)))

        try:
            client = ModbusTcpClient(BOX_IP, port=502, timeout=10)
            client.write_coil(int(device), value['value'])
            result = client.read_coils(int(device), 1)
            logger.debug(result)
            client.close()
        except RuntimeError as err:
            logger.debug(err)
コード例 #29
0
def gen_faults():
    """Shuts down emergency generators.

	'k' will complete the IP address for each PLC in the electrical distribution system. Each will be targeted by the
	attack:  10.100.1.101, 102, 103, and 104.
	"""
    for k in range(101, 105):
        target = GEN_OCTETS + str(k)
        print(" [+] Attacking ", target)
        print(" [+] Sending fault to generator")
        client = ModbusClient(target)
        result = client.read_coils(
            48, 1)  # Read status of each generator fault alarm
        if not result.bits[0]:  # If fault doesn't exist...
            client.write_coil(48, True)  # Set generator fault
        print(" [+] Complete")
        sleep(1)
コード例 #30
0
ファイル: modbus.py プロジェクト: bluesky92/data-diode
def get_modbus(properties):
    try:
        print("Performing an action which may throw an exception.")
        client = ModbusClient(properties['ip'], port=502)
        client.connect()
        log.debug(properties['registers'])
        log.debug(properties['coils'])
        modbus_values = {}

        # Get holding registers values
        modbus_registers = {}
        for i in properties['registers']:
            register_start_nb = i.split('-')[0]
            register_end_nb = i.split('-')[1]
            log.debug('Register start number : %s' % register_start_nb)
            log.debug('Register end number : %s' % register_end_nb)
            register_count = int(register_end_nb) - int(register_start_nb)
            log.debug('Number of registers to read : %s' % register_count)
            rr = client.read_holding_registers(int(register_start_nb),
                                               register_count,
                                               unit=0x01)
            modbus_registers[register_start_nb] = rr.registers
            log.debug('Registers values : %s' % rr.registers)

        # Get coils values
        modbus_coils = {}
        for i in properties['coils']:
            coil_start_nb = i.split('-')[0]
            coil_end_nb = i.split('-')[1]
            log.debug('Coil start number : ' + register_start_nb)
            log.debug('Coil end number : ' + register_end_nb)
            coil_count = int(coil_end_nb) - int(coil_start_nb)
            log.debug('Number of coils to read : ' + str(coil_count))
            rr = client.read_coils(int(coil_start_nb), coil_count, unit=0x01)
            modbus_coils[coil_start_nb] = rr.bits
            log.debug('Coils values : ' + str(rr.bits))
            log.debug('Modbus coils values : ' + str(modbus_coils))

        client.close()
        modbus_values['registers'] = modbus_registers
        modbus_values['coils'] = modbus_coils
        log.debug(str(modbus_values))
        return modbus_values

    except Exception:
        log.debug('Error connecting to %s' % properties['ip'])
コード例 #31
0
ファイル: modbus.py プロジェクト: arnaudsoullie/dyode
def get_modbus(properties):
    try:
        print "Performing an action which may throw an exception."
        client = ModbusClient(properties['ip'], port=502)
        client.connect()
        log.debug(properties['registers'])
        log.debug(properties['coils'])
        modbus_values = {}
        
        # Get holding registers values
        modbus_registers = {}
        for i in properties['registers']:
            register_start_nb = i.split('-')[0]
            register_end_nb = i.split('-')[1]
            log.debug('Register start number : %s' % register_start_nb)
            log.debug('Register end number : %s' % register_end_nb)
            register_count = int(register_end_nb) - int(register_start_nb)
            log.debug('Number of registers to read : %s' % register_count)
            rr = client.read_holding_registers(int(register_start_nb),register_count, unit=0x01)
            modbus_registers[register_start_nb] = rr.registers
            log.debug('Registers values : %s' % rr.registers)

        # Get coils values
        modbus_coils = {}
        for i in properties['coils']:
            coil_start_nb = i.split('-')[0]
            coil_end_nb = i.split('-')[1]
            log.debug('Coil start number : ' + register_start_nb)
            log.debug('Coil end number : ' + register_end_nb)
            coil_count = int(coil_end_nb) - int(coil_start_nb)
            log.debug('Number of coils to read : ' + str(coil_count))
            rr = client.read_coils(int(coil_start_nb),coil_count, unit=0x01)
            modbus_coils[coil_start_nb] = rr.bits
            log.debug('Coils values : ' + str(rr.bits))
            log.debug('Modbus coils values : ' + str(modbus_coils))

        client.close()
        modbus_values['registers'] = modbus_registers
        modbus_values['coils'] = modbus_coils
        log.debug(str(modbus_values))
        return modbus_values

    except Exception, error:
        log.debug('Error connecting to %s' % properties['ip'])
        log.debug(str(error))
コード例 #32
0
def RGBLEDUpdateThread(pins, update_interval, e):
	print 'RGBLEDUpdateThread'
	client = ModbusTcpClient(ip)
	
	# Setup pins mode
	for i in range(0, 3):
		GPIO.setup(pins[i], GPIO.OUT)

	while True:
		if not e.isSet():
			result = client.read_coils(10, 3)
			print 'RGB LED. R:', result.bits[0], 'G:', result.bits[1], 'B:', result.bits[2]
			for i in range(0, 3):
				GPIO.output(pins[i], result.bits[i])
			time.sleep(update_interval)
		else:
			break
	client.close()
	print 'RGB LED Stopped'
コード例 #33
0
ファイル: netfun.py プロジェクト: iinnovations/iicontrollibs
def readMBcoils(clientIP, coil, number=1):
    from pymodbus.client.sync import ModbusTcpClient, ConnectionException

    client = ModbusTcpClient(clientIP)
    values = []
    try:
        rawresult = client.read_coils(coil, number)

    except ConnectionException:
        # print('we were unable to connect to the host')
        statuscode = 7
    else:
        # print(rawresult)
        try:
            resultregisters = rawresult.bits[0:number]
        except AttributeError:
            statuscode = rawresult.exception_code
        else:
            statuscode = 0
            values = resultregisters
    client.close()
    result = {'message': messagefrommbstatuscode(statuscode), 'statuscode': statuscode, 'values':values}
    return result
コード例 #34
0
def plc_status_check(target):
    client = ModbusTcpClient(target, timeout=time_out)
    try:
        status = client.read_coils(0x00, count=3)
        if status.bits == [1, 0, 0, 0, 0, 0, 0, 0]:
            status = "Running"
        elif status.bits == [0, 1, 0, 0, 0, 0, 0, 0]:
            status = "Idle"
        elif status.bits == [0, 0, 1, 0, 0, 0, 0, 0]:
            status = "Stopped"
        else:
            status = "Broken"
        pass
    except ConnectionException:
        status = "No connection"
        pass
    except (ModbusIOException, ParameterException, ModbusException,
            InvalidMessageReceivedException, MessageRegisterException,
            NoSuchSlaveException, NotImplementedException):
        status = "Connection was forcibly closed by the remote host"
        pass
    client.close()
    return status
コード例 #35
0
    def activate(self):
        rospy.init_node('niryo_node', anonymous=False)
        while not rospy.is_shutdown():
            if (self.activate_plc == "Activated"):
                rospy.loginfo(
                    "Niryo will do other action, PLC will be deactivated")
                self.pub.publish("plc_deactivate")
            else:
                rospy.loginfo(
                    "PLC hasn't been activated, Niryo will activate PLC")
                self.pub.publish("Activate_plc")
            client = ModbusClient("192.168.1.7", port=502)
            client.connect()
            UNIT = 0x1
            print("Escritura de salidas")
            rq = client.write_coil(0, [True] * 8, unit=UNIT)
            rr = client.read_coils(0, 8, unit=UNIT)
            print("Las salidas Q0.0-Q0.7 ", rr.bits)

            print("Leer entradas")
            rr = client.read_discrete_inputs(0, 8, unit=UNIT)
            print("Las entradas I0.0-I0.7 son ", rr.bits)
            print("Escritura de un HR")
            rq = client.write_register(0, 15, unit=UNIT)
            rr = client.read_holding_registers(0, 1, unit=UNIT)
            print("HR0 = ", rr.registers)
            print("Escritura de varios HR")
            rq = client.write_registers(1, [35] * 10, unit=UNIT)
            rr = client.read_holding_registers(1, 10, unit=UNIT)
            print("HR0 = ", rr.registers)
            print("Escritura de varios HR")
            rq = client.write_registers(11, [43] * 5, unit=UNIT)
            rr = client.read_holding_registers(0, 15, unit=UNIT)
            print("HR0 = ", rr.registers)
            client.close()
            rospy.sleep(1)
コード例 #36
0
class clientthreads(threading.Thread):

    def __init__(self, vnic, ipaddr, port):
        threading.Thread.__init__(self)
        self.ipaddr = ipaddr  # ip address
        self.port = port  # port address
        self.vnic = vnic  # virtual nic
        self.mode = ""  # server or client
        self.state = ""  # up or down
        self.dest = ""  # destination address for client
        self.clientstop = threading.Event()
        self.server = ""
        self.client = ""
        self.framer = ""
        self.vnicm = ""
        self.runtime= 0
        self.delayr = random.uniform(0,5)
        self.delayw = random.uniform(0,60)
        self.firstdelay = 0
        self.pstart= ""


    def run(self):
        self.client = ModbusTcpClient(self.dest, self.port, source_address=(self.ipaddr, 0), retries=1, retry_on_empty=True)
        if(self.mode=="read"):
            self.clientintr()
        elif(self.mode=="write"):
            self.clientintw()
        else:
            print "wrong mode specified"

    def clientintr(self):  # instantiate server stuff
        while(not self.clientstop.is_set()):
            if(time.time() - self.pstart > self.runtime):
                print "stopping"
                break
            if(self.firstdelay < 1):
                print "Start RDelay is: " + str(self.delayr)
                time.sleep(self.delayr)
                self.firstdelay = 1
                print "Starting Reads"

            self.clientreads()
            print "\n\r-----read-----\n\r"
            print self.dest 
            print time.time() - self.pstart
            print "------------------\n\r"
    
    def clientintw(self):  # instantiate server stuff
        while(not self.clientstop.is_set()):
            if(time.time() - self.pstart > self.runtime):
                print "stopping"
                break
            if(self.firstdelay < 1):
                print "Start WDelay is: " + str(self.delayw)
                time.sleep(self.delayw)
                self.firstdelay = 1
                print "Starting Writes"

            self.clientwrites()
            print "\n\r-----write----\n\r"
            print self.dest 
            print time.time() - self.pstart
            print "------------------\n\r"


    def clientreads(self):
        self.client.read_coils(1, 10)
        self.client.read_discrete_inputs(1, 10)
        self.client.read_holding_registers(1, 10)
        self.client.read_input_registers(1, 10)
        time.sleep(5)

    def clientwrites(self):
        self.client.write_coil(1, True)
        self.client.write_register(1, 3)
        self.client.write_coils(1, [True]*10)
        self.client.write_registers(1, [3]*10)
        time.sleep(60)
    
    def alloc(self):  # Allocate ip address
        if (validateIP(self.ipaddr, self.vnicm)):
            cmdargs = [self.vnic, self.ipaddr]
            subprocess.call(["ifconfig"] + cmdargs)
        else:
            return 0

    def dealloc(self):  # De-allocate ip address
        cmdargs = [self.vnic]
        subprocess.call(["ifconfig"] + cmdargs + ["down"])

    def stop(self):
        self.clientstop.set()
        return
コード例 #37
0
ファイル: synch-client.py プロジェクト: scy-phy/minicps
        if args.type == 'HR':
            hr_read = client.read_holding_registers(args.offset,
                count=args.count)
            assert(hr_read.function_code < 0x80)
            print(hr_read.registers[0:args.count])

        # NOTE: read_holding_registers
        elif args.type == 'IR':
            ir_read = client.read_input_registers(args.offset,
                count=args.count)
            assert(ir_read.function_code < 0x80)
            print(ir_read.registers[0:args.count])

        # NOTE: read_discrete_inputs
        elif args.type == 'DI':
            di_read = client.read_discrete_inputs(args.offset,
                count=args.count)
            assert(di_read.function_code < 0x80)
            print(di_read.bits)

        # NOTE: read_discrete_inputs
        elif args.type == 'CO':
            co_read = client.read_coils(args.offset,
                count=args.count)
            assert(co_read.function_code < 0x80)
            print(co_read.bits)



    client.close()
コード例 #38
0
client = ModbusClient('127.0.0.1')

#---------------------------------------------------------------------------# 
# example requests
#---------------------------------------------------------------------------# 
# simply call the methods that you would like to use. An example session
# is displayed below along with some assert checks. Note that some modbus
# implementations differentiate holding/input discrete/coils and as such
# you will not be able to write to these, therefore the starting values
# are not known to these tests. Furthermore, some use the same memory
# blocks for the two sets, so a change to one is a change to the other.
# Keep both of these cases in mind when testing as the following will
# _only_ pass with the supplied async modbus server (script supplied).
#---------------------------------------------------------------------------# 
rq = client.write_coil(1, True)
rr = client.read_coils(1,1)
assert(rq.function_code < 0x80)     # test that we are not an error
assert(rr.bits[0] == True)          # test the expected value

rq = client.write_coils(1, [True]*8)
rr = client.read_coils(1,8)
assert(rq.function_code < 0x80)     # test that we are not an error
assert(rr.bits == [True]*8)         # test the expected value

rq = client.write_coils(1, [False]*8)
rr = client.read_discrete_inputs(1,8)
assert(rq.function_code < 0x80)     # test that we are not an error
assert(rr.bits == [True]*8)         # test the expected value

rq = client.write_register(1, 10)
rr = client.read_holding_registers(1,1)
コード例 #39
0
#    client = ModbusClient('localhost', retries=3, retry_on_empty=True)
#---------------------------------------------------------------------------# 
client = ModbusClient('localhost', port=5020)
#client = ModbusClient(method='ascii', port='/dev/pts/2', timeout=1)
# client = ModbusClient(method='rtu', port='/dev/ttyp0', timeout=1)
client.connect()

#---------------------------------------------------------------------------# 
# specify slave to query
#---------------------------------------------------------------------------# 
# The slave to query is specified in an optional parameter for each
# individual request. This can be done by specifying the `unit` parameter
# which defaults to `0x00`
#---------------------------------------------------------------------------#
log.debug("Reading Coils")
rr = client.read_coils(1, 1, unit=0x01)

#---------------------------------------------------------------------------# 
# example requests
#---------------------------------------------------------------------------# 
# simply call the methods that you would like to use. An example session
# is displayed below along with some assert checks. Note that some modbus
# implementations differentiate holding/input discrete/coils and as such
# you will not be able to write to these, therefore the starting values
# are not known to these tests. Furthermore, some use the same memory
# blocks for the two sets, so a change to one is a change to the other.
# Keep both of these cases in mind when testing as the following will
# _only_ pass with the supplied async modbus server (script supplied).
#---------------------------------------------------------------------------#
log.debug("Write to a Coil and read back")
rq = client.write_coil(0, True, unit=1)
コード例 #40
0
ファイル: modbus.py プロジェクト: jegger/roboflexms-test
class ModbusClass():
    connected=False
    
    def __init__(self, *kwargs):
        self.connect()
    
    def connect(self):
        '''Try to connect to the Modbus client
        (mostely internal)
        '''
        if not self.connected:
            self.client = ModbusClient('192.168.50.238', port=502)
            self.client.connect()
            self.connected=True
    
    def reset_safety(self, callback):
        '''Call this class to reset safety
        :param callback: callback which should be called at the end
        '''
        if not self.connected:
            self.connect()
        #write to bit 8480
        rq = self.client.write_coil(8480, True)
        time.sleep(0.5)
        rq = self.client.write_coil(8480, False)
        callback()
    
    def transfer_bahn_nr(self, nr):
        rq = self.client.write_register(532, nr)
        rq = self.client.write_coil(8483, True)
        time.sleep(0.5)
        rq = self.client.write_coil(8483, False)
        print "transfered"
    
    def transfer_array(self, array, callback):
        '''Call this function to move the array to the PLC
        :param array: array which should be transmitted
        :param callback: callback which should be called when finished
        '''
        #check array size
        c=0
        for cube in array:
            c+=1
        if c!= 106:
            print "Array size isn't suitable", c
            return   
        
        lis = array
        
        #write cubes into PLC
        c=0
        for cube in lis:
            print '-', (c/5)+1, cube
            #write x
            rq = self.client.write_register(c, cube['x'])
            c+=1
            #write y
            rq = self.client.write_register(c, cube['y'])
            c+=1
            #write z
            rq = self.client.write_register(c, cube['z'])
            c+=1
            #write rot
            rq = self.client.write_register(c, cube['typ'])
            c+=1
            #write type
            rq = self.client.write_register(c, cube['rot'])
            c+=1
        callback()
        
    def machine_is_building(self, *kwargs):
        '''Call this class to get the bool if the machine is working or not
        '''
        rq = self.client.read_coils(8481,1)
        return rq.bits[0]
    
    def read_active_bahn(self, *kwargs):
        rq = self.client.read_holding_registers(533, 1)
        return rq.registers[0]
コード例 #41
0
if __name__ == "__main__":
	
	print '=== Modbus client (RGB LED) ==='
	parser = argparse.ArgumentParser(description='Modbus client')
	parser.add_argument('ip',  default='localhost', help='IP adress of modbus server')
	args = parser.parse_args()
	
	client = ModbusTcpClient(args.ip)

	GPIO.setmode(GPIO.BCM)
	GPIO.setwarnings(False)
	for i in range(0, 3):
		GPIO.setup(LED_Pins[i], GPIO.OUT)
	
	try:
		while True:
			result = client.read_coils(10, 3)
			print 'R:', result.bits[0], 'G:', result.bits[1], 'B:', result.bits[2]
			for i in range(0, 3):
				GPIO.output(LED_Pins[i], result.bits[i])
			time.sleep(update_interval)
	except KeyboardInterrupt:
		print 'Stopping program'
	except Exception:
		traceback.print_exc(file=sys.stdout)	
	GPIO.cleanup()
	client.close()
	print 'Done'
	sys.exit(0)
コード例 #42
0
class InModbus(ApplicationSession):
    """
    Checks the state of the relays of the lights (eshl/eshl.wago.v1.switch) and
    makes three different RPCs to toggle/switch on/switch off the lights available.
    """
    def __init__(self, config=None):
        ApplicationSession.__init__(self, config)
        self.pfcIp = '192.168.1.52'
        self.modbusTcpPort = 502
        self.client = ModbusClient(self.pfcIp, self.modbusTcpPort)

#==============================================================================
#   Generates a blank Dataset with the current system timestamp
#==============================================================================
    def blankDataSetGen(self):
        blankDataset = {'K16': None,
                        'K17': None,
                        'K18': None,
                        'K19': None,
                        'K20': None,
                        'K21': None,
                        'TimestampSYS' : round(time.time() * 1000)
                        }
        return blankDataset

    def requestLoop(self):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client = self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            address = 0
            timestampSys = round(time.time() * 1000)

            result = self.client.read_coils(560, 6)
            relayState = {'K16': result.bits[0],
                           'K17': result.bits[1],
                           'K18': result.bits[2],
                           'K19': result.bits[3],
                           'K20': result.bits[4],
                           'K21': result.bits[5],
                           'TimestampSYS' : timestampSys}

            self.publish(u'eshl.wago.v1.switch', relayState)
        except ConnectionException as connErr:
            relayState = self.blankDataSetGen()
            self.publish(u'eshl.wago.v1.switch', relayState)
            print(str(connErr))
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)

    @inlineCallbacks
    def toggleSwitch(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("toggleSwitch {}".format(id))

            id = int(id)

            if (id >= 16 and id <= 21):
                id = 32768 + (id - 16)
            elif (id == 0):
                id = 32768 + 6
            else:
                return "unknown switch"

            self.client.write_coil(id, 1)
            yield sleep(0.1)
            self.client.write_coil(id, 0)

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    @inlineCallbacks
    def switchOn(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("switchOn {}".format(id))

            id = int(id)
            state = False

            result = self.client.read_coils(560, 6)

            if (id >= 16 and id <= 21):
                id = (id - 16)
                if(result.bits[id] is False):
                    self.client.write_coil(32768 + id, 1)
                    yield sleep(0.1)
                    self.client.write_coil(32768 + id, 0)
            elif (id == 0):
                for i in range(6):
                    if(result.bits[i] is False):
                        self.client.write_coil(32768 + i, 1)
                yield sleep(0.1)
                for i in range(6):
                    if(result.bits[i] is False):
                        self.client.write_coil(32768 + i, 0)
            else:
                return "unknown switch"

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    @inlineCallbacks
    def switchOff(self, id):
        try:
            if (self.client.connect() is False):
                print('not connected')
                self.client.connect()
                print('trying to connecto to ' + str(self.pfcIp))

            print("switchOff {}".format(id))

            id = int(id)
            state = True

            result = self.client.read_coils(560, 6)

            if (id >= 16 and id <= 21):
                id = (id - 16)
                if(result.bits[id] is True):
                    self.client.write_coil(32768 + id, 1)
                    yield sleep(0.1)
                    self.client.write_coil(32768 + id, 0)
            elif (id == 0):
                for i in range(6):
                    if(result.bits[i] is True):
                        self.client.write_coil(32768 + i, 1)
                yield sleep(0.1)
                for i in range(6):
                    if(result.bits[i] is True):
                        self.client.write_coil(32768 + i, 0)
            else:
                return "unknown switch"

            return "ok"
        except ConnectionException as connErr:
            return "connection error"
        except Exception as err:
            print("error: {}".format(err), file=sys.stdout)
            traceback.print_exc(file=sys.stdout)
            return "connection error"

    #==============================================================================
    #   Ensures that the requestLoop is called exactly once every second, sleeps for the rest of the time
    #==============================================================================
    def onJoin(self, details):
        ApplicationSession.onJoin(self, details)
        print("session ready")

        self.register(self.toggleSwitch, u'eshl.wago.v1.switch.toggle')
        self.register(self.switchOn, u'eshl.wago.v1.switch.on')
        self.register(self.switchOff, u'eshl.wago.v1.switch.off')

        self._loop = task.LoopingCall(self.requestLoop)
        self._requestLoopHandle = self._loop.start(1.0)

    def onLeave(self, details):
        ApplicationSession.onLeave(self, details)
        print("leaving")

        if(hasattr(self, "_loop") and self._loop):
            self._loop.stop()
コード例 #43
0
ファイル: ReadCoil.py プロジェクト: PredixParkTTC/PredixPark
from pymodbus.client.sync import ModbusTcpClient


client = ModbusTcpClient('127.0.0.1')
result = client.read_coils(0,1)
print result.bits[0]
client.close()