| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import ipaddress |
| 5 |
import socket |
| 6 |
from typing import TYPE_CHECKING |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from .controller import GoveeController |
| 10 |
|
| 11 |
|
| 12 |
class GoveeControllerProtocol(asyncio.DatagramProtocol): |
| 13 |
"""Protocol handler for a single network interface.""" |
| 14 |
|
| 15 |
def __init__(self, controller: GoveeController, listening_address: str): |
| 16 |
self.controller = controller |
| 17 |
self.listening_address = listening_address |
| 18 |
self.transport = None |
| 19 |
|
| 20 |
def connection_made(self, transport): |
| 21 |
self.transport = transport |
| 22 |
sock = transport.get_extra_info("socket") |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
self.controller._logger.debug( |
| 29 |
"Protocol connected for listening address: %s", self.listening_address |
| 30 |
) |
| 31 |
|
| 32 |
broadcast_ip = ipaddress.ip_address(self.controller._broadcast_address) |
| 33 |
|
| 34 |
if broadcast_ip.is_multicast: |
| 35 |
|
| 36 |
try: |
| 37 |
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) |
| 38 |
sock.setsockopt( |
| 39 |
socket.IPPROTO_IP, |
| 40 |
socket.IP_MULTICAST_IF, |
| 41 |
socket.inet_aton(self.listening_address), |
| 42 |
) |
| 43 |
sock.setsockopt( |
| 44 |
socket.IPPROTO_IP, |
| 45 |
socket.IP_ADD_MEMBERSHIP, |
| 46 |
socket.inet_aton(self.controller._broadcast_address) |
| 47 |
+ socket.inet_aton(self.listening_address), |
| 48 |
) |
| 49 |
except OSError as exc: |
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
self.controller._logger.error( |
| 56 |
"Failed to configure multicast on %s: %s. " |
| 57 |
"Discovery on this interface will not work.", |
| 58 |
self.listening_address, |
| 59 |
exc, |
| 60 |
) |
| 61 |
|
| 62 |
def connection_lost(self, *args, **kwargs): |
| 63 |
self.controller._logger.debug("Disconnected from %s", self.listening_address) |
| 64 |
self.controller._protocol_disconnected(self) |
| 65 |
|
| 66 |
def datagram_received(self, data: bytes, addr: tuple): |
| 67 |
if data: |
| 68 |
self.controller._loop.create_task( |
| 69 |
self.controller._handle_datagram_received(data, addr, self) |
| 70 |
) |
| 71 |
|
| 72 |
def error_received(self, exc: Exception) -> None: |
| 73 |
|
| 74 |
or |
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
self.controller._logger.warning( |
| 80 |
"UDP error on interface %s: %r", self.listening_address, exc |
| 81 |
) |