Support for Multiple modbus hubs (#19726)

* modbus: support multiple modbus hub

* update data after entities added

* pass hub object to each entity. and save hub to hass.data but not in module level

* add hub_client setup log

* don't update when adding device, because hub_client is not ready right now

* support restore last state

* remove useless func

* compatible with python35

* removed unrelated style changes

* Update flexit for multi-device modbus

* change how hubs are referenced in the configuration

* Also update climate/modbus.py

* Remove unwanted whitescapce

* Defined common constants centrally

* Update DOMAIN in climate and switch components

* Removed unnecessary vol.schema

* Make hub name optional

* Add name property to ModbusHub
This commit is contained in:
Ben Van Mechelen authored and Charles Garwood committed 2019-02-11 14:00:37 -05:00
1 parent 49ecca9cb9
commit 861d58f58f
6 files changed
+163 -94

No files matched your search

+73 -51
View File
@@ -12,19 +12,27 @@ import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (
EVENT_HOMEASSISTANT_START, EVENT_HOMEASSISTANT_STOP,
CONF_HOST, CONF_METHOD, CONF_PORT, CONF_TYPE, CONF_TIMEOUT, ATTR_STATE)
CONF_HOST, CONF_METHOD, CONF_NAME, CONF_PORT, CONF_TYPE, CONF_TIMEOUT,
ATTR_STATE)
DOMAIN = 'modbus'
REQUIREMENTS = ['pymodbus==1.5.2']
CONF_HUB = 'hub'
# Type of network
CONF_BAUDRATE = 'baudrate'
CONF_BYTESIZE = 'bytesize'
CONF_STOPBITS = 'stopbits'
CONF_PARITY = 'parity'
SERIAL_SCHEMA = {
DEFAULT_HUB = 'default'
BASE_SCHEMA = vol.Schema({
vol.Optional(CONF_NAME, default=DEFAULT_HUB): cv.string
})
SERIAL_SCHEMA = BASE_SCHEMA.extend({
vol.Required(CONF_BAUDRATE): cv.positive_int,
vol.Required(CONF_BYTESIZE): vol.Any(5, 6, 7, 8),
vol.Required(CONF_METHOD): vol.Any('rtu', 'ascii'),
@@ -33,20 +41,18 @@ SERIAL_SCHEMA = {
vol.Required(CONF_STOPBITS): vol.Any(1, 2),
vol.Required(CONF_TYPE): 'serial',
vol.Optional(CONF_TIMEOUT, default=3): cv.socket_timeout,
}
})
ETHERNET_SCHEMA = {
ETHERNET_SCHEMA = BASE_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_PORT): cv.port,
vol.Required(CONF_TYPE): vol.Any('tcp', 'udp', 'rtuovertcp'),
vol.Optional(CONF_TIMEOUT, default=3): cv.socket_timeout,
}
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Any(SERIAL_SCHEMA, ETHERNET_SCHEMA)
}, extra=vol.ALLOW_EXTRA)
DOMAIN: vol.All(cv.ensure_list, [vol.Any(SERIAL_SCHEMA, ETHERNET_SCHEMA)])
}, extra=vol.ALLOW_EXTRA,)
_LOGGER = logging.getLogger(__name__)
@@ -54,71 +60,79 @@ SERVICE_WRITE_REGISTER = 'write_register'
SERVICE_WRITE_COIL = 'write_coil'
ATTR_ADDRESS = 'address'
ATTR_HUB = 'hub'
ATTR_UNIT = 'unit'
ATTR_VALUE = 'value'
SERVICE_WRITE_REGISTER_SCHEMA = vol.Schema({
vol.Optional(ATTR_HUB, default=DEFAULT_HUB): cv.string,
vol.Required(ATTR_UNIT): cv.positive_int,
vol.Required(ATTR_ADDRESS): cv.positive_int,
vol.Required(ATTR_VALUE): vol.All(cv.ensure_list, [cv.positive_int])
})
SERVICE_WRITE_COIL_SCHEMA = vol.Schema({
vol.Optional(ATTR_HUB, default=DEFAULT_HUB): cv.string,
vol.Required(ATTR_UNIT): cv.positive_int,
vol.Required(ATTR_ADDRESS): cv.positive_int,
vol.Required(ATTR_STATE): cv.boolean
})
HUB = None
def setup_client(client_config):
"""Set up pymodbus client."""
client_type = client_config[CONF_TYPE]
if client_type == 'serial':
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
return ModbusClient(method=client_config[CONF_METHOD],
port=client_config[CONF_PORT],
baudrate=client_config[CONF_BAUDRATE],
stopbits=client_config[CONF_STOPBITS],
bytesize=client_config[CONF_BYTESIZE],
parity=client_config[CONF_PARITY],
timeout=client_config[CONF_TIMEOUT])
if client_type == 'rtuovertcp':
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.transaction import ModbusRtuFramer
return ModbusClient(host=client_config[CONF_HOST],
port=client_config[CONF_PORT],
framer=ModbusRtuFramer,
timeout=client_config[CONF_TIMEOUT])
if client_type == 'tcp':
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
return ModbusClient(host=client_config[CONF_HOST],
port=client_config[CONF_PORT],
timeout=client_config[CONF_TIMEOUT])
if client_type == 'udp':
from pymodbus.client.sync import ModbusUdpClient as ModbusClient
return ModbusClient(host=client_config[CONF_HOST],
port=client_config[CONF_PORT],
timeout=client_config[CONF_TIMEOUT])
assert False
def setup(hass, config):
"""Set up Modbus component."""
# Modbus connection type
client_type = config[DOMAIN][CONF_TYPE]
hass.data[DOMAIN] = hub_collect = {}
# Connect to Modbus network
# pylint: disable=import-error
if client_type == 'serial':
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
client = ModbusClient(method=config[DOMAIN][CONF_METHOD],
port=config[DOMAIN][CONF_PORT],
baudrate=config[DOMAIN][CONF_BAUDRATE],
stopbits=config[DOMAIN][CONF_STOPBITS],
bytesize=config[DOMAIN][CONF_BYTESIZE],
parity=config[DOMAIN][CONF_PARITY],
timeout=config[DOMAIN][CONF_TIMEOUT])
elif client_type == 'rtuovertcp':
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from pymodbus.transaction import ModbusRtuFramer as ModbusFramer
client = ModbusClient(host=config[DOMAIN][CONF_HOST],
port=config[DOMAIN][CONF_PORT],
framer=ModbusFramer,
timeout=config[DOMAIN][CONF_TIMEOUT])
elif client_type == 'tcp':
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
client = ModbusClient(host=config[DOMAIN][CONF_HOST],
port=config[DOMAIN][CONF_PORT],
timeout=config[DOMAIN][CONF_TIMEOUT])
elif client_type == 'udp':
from pymodbus.client.sync import ModbusUdpClient as ModbusClient
client = ModbusClient(host=config[DOMAIN][CONF_HOST],
port=config[DOMAIN][CONF_PORT],
timeout=config[DOMAIN][CONF_TIMEOUT])
else:
return False
global HUB
HUB = ModbusHub(client)
for client_config in config[DOMAIN]:
client = setup_client(client_config)
name = client_config[CONF_NAME]
hub_collect[name] = ModbusHub(client, name)
_LOGGER.debug('Setting up hub: %s', client_config)
def stop_modbus(event):
"""Stop Modbus service."""
HUB.close()
for client in hub_collect.values():
client.close()
def start_modbus(event):
"""Start Modbus service."""
HUB.connect()
for client in hub_collect.values():
client.connect()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_modbus)
# Register services for modbus
@@ -134,13 +148,14 @@ def setup(hass, config):
unit = int(float(service.data.get(ATTR_UNIT)))
address = int(float(service.data.get(ATTR_ADDRESS)))
value = service.data.get(ATTR_VALUE)
client_name = service.data.get(ATTR_HUB)
if isinstance(value, list):
HUB.write_registers(
hub_collect[client_name].write_registers(
unit,
address,
[int(float(i)) for i in value])
else:
HUB.write_register(
hub_collect[client_name].write_register(
unit,
address,
int(float(value)))
@@ -150,7 +165,8 @@ def setup(hass, config):
unit = service.data.get(ATTR_UNIT)
address = service.data.get(ATTR_ADDRESS)
state = service.data.get(ATTR_STATE)
HUB.write_coil(unit, address, state)
client_name = service.data.get(ATTR_HUB)
hub_collect[client_name].write_coil(unit, address, state)
hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_modbus)
@@ -160,10 +176,16 @@ def setup(hass, config):
class ModbusHub:
"""Thread safe wrapper class for pymodbus."""
def __init__(self, modbus_client):
def __init__(self, modbus_client, name):
"""Initialize the modbus hub."""
self._client = modbus_client
self._lock = threading.Lock()
self._name = name
@property
def name(self):
"""Return the name of this hub."""
return self._name
def close(self):
"""Disconnect client."""