예제 #1
0
    def _helper(self, data):
        """
        This factory is used to generate the correct request object
        from a valid request packet. This decodes from a list of the
        currently implemented request types.

        :param data: The request packet to decode
        :returns: The decoded request or illegal function request object
        """
        function_code = byte2int(data[0])
        request = self.__lookup.get(function_code, lambda: None)()
        if not request:
            log.event("Modbus, Illegal Function Request[%d]" % function_code)
            request = IllegalFunctionRequest(function_code)
        else:
            fc_string = "%s: %s" % (str(
                self.__lookup[function_code]).split('.')[-1].rstrip("'>"),
                                    function_code)
            log.event("Modbus, Request[%s]" % fc_string)
        request.decode(data[1:])

        if hasattr(request, 'sub_function_code'):
            lookup = self.__sub_lookup.get(request.function_code, {})
            subtype = lookup.get(request.sub_function_code, None)
            if subtype: request.__class__ = subtype

        return request
예제 #2
0
    def _helper(self, data):
        """
        This factory is used to generate the correct request object
        from a valid request packet. This decodes from a list of the
        currently implemented request types.

        :param data: The request packet to decode
        :returns: The decoded request or illegal function request object
        """
        function_code = byte2int(data[0])
        request = self.__lookup.get(function_code, lambda: None)()
        if not request:
            _logger.debug("Factory Request[%d]" % function_code)
            request = IllegalFunctionRequest(function_code)
        else:
            fc_string = "%s: %s" % (
                str(self.__lookup[function_code]).split('.')[-1].rstrip(
                    "'>"),
                function_code
            )
            _logger.debug("Factory Request[%s]" % fc_string)
        request.decode(data[1:])

        if hasattr(request, 'sub_function_code'):
            lookup = self.__sub_lookup.get(request.function_code, {})
            subtype = lookup.get(request.sub_function_code, None)
            if subtype: request.__class__ = subtype

        return request
예제 #3
0
    def _helper(self, data, client_address=None):
        '''
        This factory is used to generate the correct request object
        from a valid request packet. This decodes from a list of the
        currently implemented request types.

        :param data: The request packet to decode
        :returns: The decoded request or illegal function request object
        '''
        function_code = byte2int(data[0])
        if client_address != None :
           extra = {
                'ip_source'   : client_address[0],
                'port_source' : client_address[1],
                'fonction_code' : function_code,
	    		'requete' : str(data)
            }
        else :
            extra = {
                'fonction_code' : function_code,
	    		'requete' : str(data)
            }
        #_logger.debug("test:"+ str(data))
        _logger.debug("traité " + str(extra),extra=extra)
        request = self.__lookup.get(function_code, lambda: None)()
        if not request:
            request = IllegalFunctionRequest(function_code)
        request.decode(data[1:])

        if hasattr(request, 'sub_function_code'):
            lookup = self.__sub_lookup.get(request.function_code, {})
            subtype = lookup.get(request.sub_function_code, None)
            if subtype: request.__class__ = subtype

        return request
예제 #4
0
    def _helper(self, data):
        '''
        This factory is used to generate the correct request object
        from a valid request packet. This decodes from a list of the
        currently implemented request types.

        :param data: The request packet to decode
        :returns: The decoded request or illegal function request object
        '''
        function_code = ord(data[0])
        _logger.debug("Factory Request[%d]" % function_code)
        request = self.__lookup.get(function_code, lambda: None)()
        if not request:
            request = IllegalFunctionRequest(function_code)
        request.decode(data[1:])
        return request
예제 #5
0
파일: test_init.py 프로젝트: tpaulus/core
async def test_pb_service_write(hass, do_write, caplog, mock_modbus):
    """Run test for service write_register."""

    func_name = {
        CALL_TYPE_WRITE_COIL: mock_modbus.write_coil,
        CALL_TYPE_WRITE_COILS: mock_modbus.write_coils,
        CALL_TYPE_WRITE_REGISTER: mock_modbus.write_register,
        CALL_TYPE_WRITE_REGISTERS: mock_modbus.write_registers,
    }

    data = {
        ATTR_HUB: TEST_MODBUS_NAME,
        ATTR_UNIT: 17,
        ATTR_ADDRESS: 16,
        do_write[DATA]: do_write[VALUE],
    }
    await hass.services.async_call(DOMAIN, do_write[SERVICE], data, blocking=True)
    assert func_name[do_write[FUNC]].called
    assert func_name[do_write[FUNC]].call_args[0] == (
        data[ATTR_ADDRESS],
        data[do_write[DATA]],
    )
    mock_modbus.reset_mock()

    for return_value in [
        ExceptionResponse(0x06),
        IllegalFunctionRequest(0x06),
        ModbusException("fail write_"),
    ]:
        caplog.set_level(logging.DEBUG)
        func_name[do_write[FUNC]].return_value = return_value
        await hass.services.async_call(DOMAIN, do_write[SERVICE], data, blocking=True)
        assert func_name[do_write[FUNC]].called
        assert caplog.messages[-1].startswith("Pymodbus:")
        mock_modbus.reset_mock()
예제 #6
0
    def _helper(self, data):
        '''
        This factory is used to generate the correct request object
        from a valid request packet. This decodes from a list of the
        currently implemented request types.

        :param data: The request packet to decode
        :returns: The decoded request or illegal function request object
        '''
        function_code = byte2int(data[0])
        _logger.debug("Factory Request[%d]" % function_code)
        request = self.__lookup.get(function_code, lambda: None)()
        if not request:
            request = IllegalFunctionRequest(function_code)
        request.decode(data[1:])

        if hasattr(request, 'sub_function_code'):
            lookup = self.__sub_lookup.get(request.function_code, {})
            subtype = lookup.get(request.sub_function_code, None)
            if subtype: request.__class__ = subtype

        return request
예제 #7
0
    def _helper(self, data):
        '''
        This factory is used to generate the correct request object
        from a valid request packet. This decodes from a list of the
        currently implemented request types.

        :param data: The request packet to decode
        :returns: The decoded request or illegal function request object
        '''
        function_code = byte2int(data[0])
        _logger.debug("Factory Request[%d]" % function_code)
        request = self.__lookup.get(function_code, lambda: None)()
        if not request:
            request = IllegalFunctionRequest(function_code)
        request.decode(data[1:])

        if hasattr(request, 'sub_function_code'):
            lookup = self.__sub_lookup.get(request.function_code, {})
            subtype = lookup.get(request.sub_function_code, None)
            if subtype: request.__class__ = subtype

        return request
예제 #8
0
async def test_pb_service_write_coil(hass, caplog, mock_modbus):
    """Run test for service write_coil."""

    # Pymodbus write single, response OK.
    data = {
        ATTR_HUB: TEST_MODBUS_NAME,
        ATTR_UNIT: 17,
        ATTR_ADDRESS: 16,
        ATTR_STATE: False,
    }
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coil.called
    assert mock_modbus.write_coil.call_args[0] == (
        data[ATTR_ADDRESS],
        data[ATTR_STATE],
    )
    mock_modbus.reset_mock()

    # Pymodbus write single, response error or exception
    caplog.set_level(logging.DEBUG)
    mock_modbus.write_coil.return_value = ExceptionResponse(0x06)
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coil.called
    assert caplog.messages[-1].startswith("Pymodbus:")
    mock_modbus.reset_mock()

    mock_modbus.write_coil.return_value = IllegalFunctionRequest(0x06)
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coil.called
    assert caplog.messages[-1].startswith("Pymodbus:")
    mock_modbus.reset_mock()

    mock_modbus.write_coil.side_effect = ModbusException("fail write_")
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coil.called
    assert caplog.messages[-1].startswith("Pymodbus:")
    mock_modbus.reset_mock()

    # Pymodbus write multiple, response OK.
    data[ATTR_STATE] = [True, False, True]
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coils.called
    assert mock_modbus.write_coils.call_args[0] == (
        data[ATTR_ADDRESS],
        data[ATTR_STATE],
    )
    mock_modbus.reset_mock()

    # Pymodbus write multiple, response error or exception
    mock_modbus.write_coils.return_value = ExceptionResponse(0x06)
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coils.called
    assert caplog.messages[-1].startswith("Pymodbus:")
    mock_modbus.reset_mock()

    mock_modbus.write_coils.return_value = IllegalFunctionRequest(0x06)
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coils.called
    assert caplog.messages[-1].startswith("Pymodbus:")
    mock_modbus.reset_mock()

    mock_modbus.write_coils.side_effect = ModbusException("fail write_")
    await hass.services.async_call(DOMAIN,
                                   SERVICE_WRITE_COIL,
                                   data,
                                   blocking=True)
    assert mock_modbus.write_coils.called
    assert caplog.messages[-1].startswith("Pymodbus:")
    mock_modbus.reset_mock()
예제 #9
0
    with mock.patch("homeassistant.helpers.event.dt_util.utcnow",
                    return_value=now):
        assert await async_setup_component(hass, DOMAIN, config) is True
        await hass.async_block_till_done()
    now = now + timedelta(seconds=DEFAULT_SCAN_INTERVAL + 60)
    with mock.patch("homeassistant.helpers.event.dt_util.utcnow",
                    return_value=now):
        async_fire_time_changed(hass, now)
        await hass.async_block_till_done()


@pytest.mark.parametrize(
    "do_return,do_exception,do_expect",
    [
        [ReadResult([7]), None, "7"],
        [IllegalFunctionRequest(0x99), None, STATE_UNAVAILABLE],
        [ExceptionResponse(0x99), None, STATE_UNAVAILABLE],
        [ReadResult([7]),
         ModbusException("fail read_"), STATE_UNAVAILABLE],
    ],
)
@pytest.mark.parametrize(
    "do_type",
    [CALL_TYPE_REGISTER_HOLDING, CALL_TYPE_REGISTER_INPUT],
)
async def test_pb_read_value(hass, caplog, do_type, do_return, do_exception,
                             do_expect, mock_pymodbus):
    """Run test for different read."""

    # the purpose of this test is to test the special
    # return values from pymodbus:
예제 #10
0
        },
    ],
)
@pytest.mark.parametrize(
    "do_return",
    [
        {
            VALUE: ReadResult([0x0001]),
            DATA: ""
        },
        {
            VALUE: ExceptionResponse(0x06),
            DATA: "Pymodbus:"
        },
        {
            VALUE: IllegalFunctionRequest(0x06),
            DATA: "Pymodbus:"
        },
        {
            VALUE: ModbusException("fail write_"),
            DATA: "Pymodbus:"
        },
    ],
)
async def test_pb_service_write(hass, do_write, do_return, caplog,
                                mock_modbus_with_pymodbus):
    """Run test for service write_register."""

    func_name = {
        CALL_TYPE_WRITE_COIL: mock_modbus_with_pymodbus.write_coil,
        CALL_TYPE_WRITE_COILS: mock_modbus_with_pymodbus.write_coils,
예제 #11
0
            FUNC: CALL_TYPE_WRITE_COIL,
        },
        {
            DATA: ATTR_STATE,
            VALUE: [True, False, True],
            SERVICE: SERVICE_WRITE_COIL,
            FUNC: CALL_TYPE_WRITE_COILS,
        },
    ],
)
@pytest.mark.parametrize(
    "do_return",
    [
        {VALUE: ReadResult([0x0001]), DATA: ""},
        {VALUE: ExceptionResponse(0x06), DATA: "Pymodbus:"},
        {VALUE: IllegalFunctionRequest(0x06), DATA: "Pymodbus:"},
        {VALUE: ModbusException("fail write_"), DATA: "Pymodbus:"},
    ],
)
async def test_pb_service_write(
    hass, do_write, do_return, caplog, mock_modbus_with_pymodbus
):
    """Run test for service write_register."""

    func_name = {
        CALL_TYPE_WRITE_COIL: mock_modbus_with_pymodbus.write_coil,
        CALL_TYPE_WRITE_COILS: mock_modbus_with_pymodbus.write_coils,
        CALL_TYPE_WRITE_REGISTER: mock_modbus_with_pymodbus.write_register,
        CALL_TYPE_WRITE_REGISTERS: mock_modbus_with_pymodbus.write_registers,
    }