-
-
Notifications
You must be signed in to change notification settings - Fork 37.4k
Expand file tree
/
Copy pathgateway.py
More file actions
155 lines (129 loc) · 5.08 KB
/
gateway.py
File metadata and controls
155 lines (129 loc) · 5.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
"""Code to handle a Motion Gateway."""
import asyncio
import contextlib
import logging
import socket
from motionblinds import DEVICE_TYPES_WIFI, AsyncMotionMulticast, MotionGateway
from homeassistant.components import network
from .const import DEFAULT_INTERFACE
_LOGGER = logging.getLogger(__name__)
def device_name(blind):
"""Construct common name part of a device."""
if blind.device_type in DEVICE_TYPES_WIFI:
return blind.blind_type
return f"{blind.blind_type} {blind.mac[12:]}"
class ConnectMotionGateway:
"""Class to async connect to a Motion Gateway."""
def __init__(self, hass, multicast=None, interface=None):
"""Initialize the entity."""
self._hass = hass
self._multicast = multicast
self._gateway_device = None
self._interface = interface
@property
def gateway_device(self):
"""Return the class containing all connections to the gateway."""
return self._gateway_device
def update_gateway(self):
"""Update all information of the gateway."""
self.gateway_device.GetDeviceList()
self.gateway_device.Update()
for blind in self.gateway_device.device_list.values():
blind.Update_from_cache()
async def async_connect_gateway(
self,
host: str,
key: str,
blind_type_list: dict[str, int] | None = None,
) -> bool:
"""Connect to the Motion Gateway."""
_LOGGER.debug("Initializing with host %s (key %s)", host, key[:3])
self._gateway_device = MotionGateway(
ip=host, key=key, multicast=self._multicast, blind_type_list=blind_type_list
)
try:
# update device info and get the connected sub devices
await self._hass.async_add_executor_job(self.update_gateway)
except TimeoutError:
_LOGGER.error(
"Timeout trying to connect to Motion Gateway with host %s", host
)
return False
_LOGGER.debug(
"Motion gateway mac: %s, protocol: %s detected",
self.gateway_device.mac,
self.gateway_device.protocol,
)
return True
def check_interface(self):
"""Check if the current interface supports multicast."""
with contextlib.suppress(socket.timeout):
return self.gateway_device.Check_gateway_multicast()
return False
async def async_get_interfaces(self):
"""Get list of interface to use."""
interfaces = [DEFAULT_INTERFACE, "0.0.0.0"]
enabled_interfaces = []
default_interface = DEFAULT_INTERFACE
adapters = await network.async_get_adapters(self._hass)
for adapter in adapters:
if ipv4s := adapter["ipv4"]:
ip4 = ipv4s[0]["address"]
interfaces.append(ip4)
if adapter["enabled"]:
enabled_interfaces.append(ip4)
if adapter["default"]:
default_interface = ip4
if len(enabled_interfaces) == 1:
default_interface = enabled_interfaces[0]
# Prioritize default interface regardless of how many NICs are present
if default_interface != DEFAULT_INTERFACE:
interfaces.remove(default_interface)
interfaces.insert(0, default_interface)
if self._interface is not None:
interfaces.remove(self._interface)
interfaces.insert(0, self._interface)
return interfaces
async def async_check_interface(self, host, key):
"""Connect to the Motion Gateway."""
interfaces = await self.async_get_interfaces()
for interface in interfaces:
_LOGGER.debug(
"Checking Motionblinds interface '%s' with host %s", interface, host
)
check_multicast = AsyncMotionMulticast(interface=interface)
try:
await check_multicast.Start_listen()
except socket.gaierror:
continue
except OSError:
continue
self._gateway_device = MotionGateway(
ip=host, key=key, multicast=check_multicast
)
# Fail fast per interface instead of waiting for full socket timeout
try:
async with asyncio.timeout(5):
result = await self._hass.async_add_executor_job(self.check_interface)
except TimeoutError:
result = False
try:
check_multicast.Stop_listen()
except socket.gaierror:
continue
if result:
_LOGGER.debug(
"Success using Motionblinds interface '%s' with host %s",
interface,
host,
)
return interface
_LOGGER.error(
(
"Could not find working interface for Motionblinds host %s, using"
" interface '%s'"
),
host,
self._interface,
)
return self._interface