From 05a4ae6f04d6db8f6db72de1b756f53b78fe0a90 Mon Sep 17 00:00:00 2001 From: Upstream Data Date: Tue, 30 Apr 2024 11:49:47 -0600 Subject: [PATCH] bug: reformat, and fix miner listener. --- pyasic/config/__init__.py | 5 +- pyasic/miners/factory.py | 4 +- pyasic/miners/listener.py | 51 ++++++++++++-------- pyasic/settings/__init__.py | 7 +-- pyasic/ssh/antminer.py | 1 + pyasic/web/antminer.py | 70 +++++++++++++-------------- pyasic/web/auradine.py | 96 ++++++++++++++++++------------------- tests/config_tests/fans.py | 2 +- 8 files changed, 124 insertions(+), 112 deletions(-) diff --git a/pyasic/config/__init__.py b/pyasic/config/__init__.py index 10dcf082..7cc18038 100644 --- a/pyasic/config/__init__.py +++ b/pyasic/config/__init__.py @@ -25,8 +25,9 @@ from pyasic.misc import merge_dicts @dataclass class MinerConfig: - """Represents the configuration for a miner including pool configuration, + """Represents the configuration for a miner including pool configuration, fan mode, temperature settings, mining mode, and power scaling.""" + pools: PoolConfig = field(default_factory=PoolConfig.default) fan_mode: FanModeConfig = field(default_factory=FanModeConfig.default) temperature: TemperatureConfig = field(default_factory=TemperatureConfig.default) @@ -110,7 +111,7 @@ class MinerConfig: } def as_boser(self, user_suffix: str = None) -> dict: - """"Generates the configuration in the format suitable for BOSer.""" + """ "Generates the configuration in the format suitable for BOSer.""" return { **self.fan_mode.as_boser(), **self.temperature.as_boser(), diff --git a/pyasic/miners/factory.py b/pyasic/miners/factory.py index 5477b6e0..39f3b176 100644 --- a/pyasic/miners/factory.py +++ b/pyasic/miners/factory.py @@ -557,9 +557,7 @@ class MinerFactory: if mtype == MinerTypes.ANTMINER: # could still be mara auth = httpx.DigestAuth("root", "root") - res = await self.send_web_command( - ip, "/kaonsu/v1/brief", auth=auth - ) + res = await self.send_web_command(ip, "/kaonsu/v1/brief", auth=auth) if res is not None: mtype = MinerTypes.MARATHON return mtype diff --git a/pyasic/miners/listener.py b/pyasic/miners/listener.py index 29dfcbba..ad147d09 100644 --- a/pyasic/miners/listener.py +++ b/pyasic/miners/listener.py @@ -21,22 +21,33 @@ class MinerListenerProtocol(asyncio.Protocol): def __init__(self): self.responses = {} self.transport = None + self.new_miner = None + + async def get_new_miner(self): + try: + while self.new_miner is None: + await asyncio.sleep(0) + return self.new_miner + finally: + self.new_miner = None def connection_made(self, transport): self.transport = transport - @staticmethod - def datagram_received(data, _addr): + def datagram_received(self, data, _addr): + if data == b"OK\x00\x00\x00\x00\x00\x00\x00\x00": + return m = data.decode() if "," in m: ip, mac = m.split(",") + if "/" in ip: + ip = ip.replace("[", "").split("/")[0] else: d = m[:-1].split("MAC") ip = d[0][3:] mac = d[1][1:] - new_miner = {"IP": ip, "MAC": mac.upper()} - MinerListener().new_miner = new_miner + self.new_miner = {"IP": ip, "MAC": mac.upper()} def connection_lost(self, _): pass @@ -45,32 +56,32 @@ class MinerListenerProtocol(asyncio.Protocol): class MinerListener: def __init__(self, bind_addr: str = "0.0.0.0"): self.found_miners = [] - self.new_miner = None - self.stop = False + self.stop = asyncio.Event() self.bind_addr = bind_addr async def listen(self): - self.stop = False - loop = asyncio.get_running_loop() - transport_14235, _ = await loop.create_datagram_endpoint( + transport_14235, protocol_14235 = await loop.create_datagram_endpoint( MinerListenerProtocol, local_addr=(self.bind_addr, 14235) ) - transport_8888, _ = await loop.create_datagram_endpoint( + transport_8888, protocol_8888 = await loop.create_datagram_endpoint( MinerListenerProtocol, local_addr=(self.bind_addr, 8888) ) + try: + while not self.stop.is_set(): + tasks = [ + asyncio.create_task(protocol_14235.get_new_miner()), + asyncio.create_task(protocol_8888.get_new_miner()), + ] + await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) + for t in tasks: + if t.done(): + yield t.result() - while True: - if self.new_miner: - yield self.new_miner - self.found_miners.append(self.new_miner) - self.new_miner = None - if self.stop: - transport_14235.close() - transport_8888.close() - break - await asyncio.sleep(0) + finally: + transport_14235.close() + transport_8888.close() async def cancel(self): self.stop = True diff --git a/pyasic/settings/__init__.py b/pyasic/settings/__init__.py index 9804b014..4f02cd31 100644 --- a/pyasic/settings/__init__.py +++ b/pyasic/settings/__init__.py @@ -46,9 +46,10 @@ _settings = { # defaults ssl_cxt = httpx.create_ssl_context() -#this function configures socket options like SO_LINGER and returns an AsyncHTTPTransport instance to perform asynchronous HTTP requests -#using those options. -#SO_LINGER controls what happens when you close a socket with unsent data - it allows specifying linger time for the data to be sent. + +# this function configures socket options like SO_LINGER and returns an AsyncHTTPTransport instance to perform asynchronous HTTP requests +# using those options. +# SO_LINGER controls what happens when you close a socket with unsent data - it allows specifying linger time for the data to be sent. def transport(verify: Union[str, bool, SSLContext] = ssl_cxt): l_onoff = 1 l_linger = get("so_linger_time", 1000) diff --git a/pyasic/ssh/antminer.py b/pyasic/ssh/antminer.py index 4ca08bd4..d901b67e 100644 --- a/pyasic/ssh/antminer.py +++ b/pyasic/ssh/antminer.py @@ -9,6 +9,7 @@ class AntminerModernSSH(BaseSSH): Args: ip (str): The IP address of the Antminer device. """ + def __init__(self, ip: str): super().__init__(ip) self.pwd = settings.get("default_antminer_ssh_password", "root") diff --git a/pyasic/web/antminer.py b/pyasic/web/antminer.py index 2d16fc88..9a7a8118 100644 --- a/pyasic/web/antminer.py +++ b/pyasic/web/antminer.py @@ -28,7 +28,7 @@ from pyasic.web.base import BaseWebAPI class AntminerModernWebAPI(BaseWebAPI): def __init__(self, ip: str) -> None: """Initialize the modern Antminer API client with a specific IP address. - + Args: ip (str): IP address of the Antminer device. """ @@ -45,14 +45,14 @@ class AntminerModernWebAPI(BaseWebAPI): **parameters: Any, ) -> dict: """Send a command to the Antminer device using HTTP digest authentication. - + Args: command (str | bytes): The CGI command to send. ignore_errors (bool): If True, ignore any HTTP errors. allow_warning (bool): If True, proceed with warnings. privileged (bool): If set to True, requires elevated privileges. **parameters: Arbitrary keyword arguments to be sent as parameters in the request. - + Returns: dict: The JSON response from the device or an empty dictionary if an error occurs. """ @@ -84,12 +84,12 @@ class AntminerModernWebAPI(BaseWebAPI): self, *commands: str, ignore_errors: bool = False, allow_warning: bool = True ) -> dict: """Execute multiple commands simultaneously. - + Args: *commands (str): Multiple command strings to be executed. ignore_errors (bool): If True, ignore any HTTP errors. allow_warning (bool): If True, proceed with warnings. - + Returns: dict: A dictionary containing the results of all commands executed. """ @@ -111,11 +111,11 @@ class AntminerModernWebAPI(BaseWebAPI): self, client: httpx.AsyncClient, command: str ) -> dict: """Helper function for handling individual commands in a multicommand execution. - + Args: client (httpx.AsyncClient): The HTTP client to use for the request. command (str): The command to be executed. - + Returns: dict: A dictionary containing the response of the executed command. """ @@ -137,7 +137,7 @@ class AntminerModernWebAPI(BaseWebAPI): async def get_miner_conf(self) -> dict: """Retrieve the miner configuration from the Antminer device. - + Returns: dict: A dictionary containing the current configuration of the miner. """ @@ -145,10 +145,10 @@ class AntminerModernWebAPI(BaseWebAPI): async def set_miner_conf(self, conf: dict) -> dict: """Set the configuration for the miner. - + Args: conf (dict): A dictionary of configuration settings to apply to the miner. - + Returns: dict: A dictionary response from the device after setting the configuration. """ @@ -156,10 +156,10 @@ class AntminerModernWebAPI(BaseWebAPI): async def blink(self, blink: bool) -> dict: """Control the blinking of the LED on the miner device. - + Args: blink (bool): True to start blinking, False to stop. - + Returns: dict: A dictionary response from the device after the command execution. """ @@ -169,7 +169,7 @@ class AntminerModernWebAPI(BaseWebAPI): async def reboot(self) -> dict: """Reboot the miner device. - + Returns: dict: A dictionary response from the device confirming the reboot command. """ @@ -177,7 +177,7 @@ class AntminerModernWebAPI(BaseWebAPI): async def get_system_info(self) -> dict: """Retrieve system information from the miner. - + Returns: dict: A dictionary containing system information of the miner. """ @@ -185,7 +185,7 @@ class AntminerModernWebAPI(BaseWebAPI): async def get_network_info(self) -> dict: """Retrieve network configuration information from the miner. - + Returns: dict: A dictionary containing the network configuration of the miner. """ @@ -193,7 +193,7 @@ class AntminerModernWebAPI(BaseWebAPI): async def summary(self) -> dict: """Get a summary of the miner's status and performance. - + Returns: dict: A summary of the miner's current operational status. """ @@ -201,7 +201,7 @@ class AntminerModernWebAPI(BaseWebAPI): async def get_blink_status(self) -> dict: """Check the status of the LED blinking on the miner. - + Returns: dict: A dictionary indicating whether the LED is currently blinking. """ @@ -217,7 +217,7 @@ class AntminerModernWebAPI(BaseWebAPI): protocol: int, ) -> dict: """Set the network configuration of the miner. - + Args: ip (str): IP address of the device. dns (str): DNS server IP address. @@ -225,7 +225,7 @@ class AntminerModernWebAPI(BaseWebAPI): subnet_mask (str): Network subnet mask. hostname (str): Hostname of the device. protocol (int): Network protocol used. - + Returns: dict: A dictionary response from the device after setting the network configuration. """ @@ -243,7 +243,7 @@ class AntminerModernWebAPI(BaseWebAPI): class AntminerOldWebAPI(BaseWebAPI): def __init__(self, ip: str) -> None: """Initialize the old Antminer API client with a specific IP address. - + Args: ip (str): IP address of the Antminer device. """ @@ -260,14 +260,14 @@ class AntminerOldWebAPI(BaseWebAPI): **parameters: Any, ) -> dict: """Send a command to the Antminer device using HTTP digest authentication. - + Args: command (str | bytes): The CGI command to send. ignore_errors (bool): If True, ignore any HTTP errors. allow_warning (bool): If True, proceed with warnings. privileged (bool): If set to True, requires elevated privileges. **parameters: Arbitrary keyword arguments to be sent as parameters in the request. - + Returns: dict: The JSON response from the device or an empty dictionary if an error occurs. """ @@ -297,12 +297,12 @@ class AntminerOldWebAPI(BaseWebAPI): self, *commands: str, ignore_errors: bool = False, allow_warning: bool = True ) -> dict: """Execute multiple commands simultaneously. - + Args: *commands (str): Multiple command strings to be executed. ignore_errors (bool): If True, ignore any HTTP errors. allow_warning (bool): If True, proceed with warnings. - + Returns: dict: A dictionary containing the results of all commands executed. """ @@ -326,7 +326,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def get_system_info(self) -> dict: """Retrieve system information from the miner. - + Returns: dict: A dictionary containing system information of the miner. """ @@ -334,10 +334,10 @@ class AntminerOldWebAPI(BaseWebAPI): async def blink(self, blink: bool) -> dict: """Control the blinking of the LED on the miner device. - + Args: blink (bool): True to start blinking, False to stop. - + Returns: dict: A dictionary response from the device after the command execution. """ @@ -347,7 +347,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def reboot(self) -> dict: """Reboot the miner device. - + Returns: dict: A dictionary response from the device confirming the reboot command. """ @@ -355,7 +355,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def get_blink_status(self) -> dict: """Check the status of the LED blinking on the miner. - + Returns: dict: A dictionary indicating whether the LED is currently blinking. """ @@ -363,7 +363,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def get_miner_conf(self) -> dict: """Retrieve the miner configuration from the Antminer device. - + Returns: dict: A dictionary containing the current configuration of the miner. """ @@ -371,10 +371,10 @@ class AntminerOldWebAPI(BaseWebAPI): async def set_miner_conf(self, conf: dict) -> dict: """Set the configuration for the miner. - + Args: conf (dict): A dictionary of configuration settings to apply to the miner. - + Returns: dict: A dictionary response from the device after setting the configuration. """ @@ -382,7 +382,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def stats(self) -> dict: """Retrieve detailed statistical data of the mining operation. - + Returns: dict: Detailed statistics of the miner's operation. """ @@ -390,7 +390,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def summary(self) -> dict: """Get a summary of the miner's status and performance. - + Returns: dict: A summary of the miner's current operational status. """ @@ -398,7 +398,7 @@ class AntminerOldWebAPI(BaseWebAPI): async def pools(self) -> dict: """Retrieve current pool information associated with the miner. - + Returns: dict: Information about the mining pools configured in the miner. """ diff --git a/pyasic/web/auradine.py b/pyasic/web/auradine.py index 7b58e5b0..bda5b19c 100644 --- a/pyasic/web/auradine.py +++ b/pyasic/web/auradine.py @@ -31,7 +31,7 @@ from pyasic.web.base import BaseWebAPI class AuradineWebAPI(BaseWebAPI): def __init__(self, ip: str) -> None: """Initializes the API client for interacting with Auradine mining devices. - + Args: ip (str): IP address of the Auradine miner. """ @@ -43,7 +43,7 @@ class AuradineWebAPI(BaseWebAPI): async def auth(self) -> str | None: """Authenticate and retrieve a web token from the Auradine miner. - + Returns: str | None: A token if authentication is successful, None otherwise. """ @@ -76,14 +76,14 @@ class AuradineWebAPI(BaseWebAPI): **parameters: Any, ) -> dict: """Send a command to the Auradine miner, handling authentication and retries. - + Args: command (str | bytes): The specific command to execute. ignore_errors (bool): Whether to ignore HTTP errors. allow_warning (bool): Whether to proceed with warnings. privileged (bool): Whether the command requires privileged access. **parameters: Additional parameters for the command. - + Returns: dict: The JSON response from the device. """ @@ -125,12 +125,12 @@ class AuradineWebAPI(BaseWebAPI): self, *commands: str, ignore_errors: bool = False, allow_warning: bool = True ) -> dict: """Execute multiple commands simultaneously on the Auradine miner. - + Args: *commands (str): Commands to execute. ignore_errors (bool): Whether to ignore errors during command execution. allow_warning (bool): Whether to proceed despite warnings. - + Returns: dict: A dictionary containing responses for all commands executed. """ @@ -157,7 +157,7 @@ class AuradineWebAPI(BaseWebAPI): async def factory_reset(self) -> dict: """Perform a factory reset on the Auradine miner. - + Returns: dict: A dictionary indicating the result of the reset operation. """ @@ -165,7 +165,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_fan(self) -> dict: """Retrieve the current fan status from the Auradine miner. - + Returns: dict: A dictionary containing the current fan status. """ @@ -173,11 +173,11 @@ class AuradineWebAPI(BaseWebAPI): async def set_fan(self, fan: int, speed_pct: int) -> dict: """Set the speed of a specific fan on the Auradine miner. - + Args: fan (int): The index of the fan to control. speed_pct (int): The speed percentage to set for the fan. - + Returns: dict: A dictionary indicating the result of the operation. """ @@ -185,11 +185,11 @@ class AuradineWebAPI(BaseWebAPI): async def firmware_upgrade(self, url: str = None, version: str = "latest") -> dict: """Upgrade the firmware of the Auradine miner. - + Args: url (str, optional): The URL to download the firmware from. version (str, optional): The version of the firmware to upgrade to, defaults to 'latest'. - + Returns: dict: A dictionary indicating the result of the firmware upgrade. """ @@ -199,7 +199,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_frequency(self) -> dict: """Retrieve the current frequency settings of the Auradine miner. - + Returns: dict: A dictionary containing the frequency settings. """ @@ -207,11 +207,11 @@ class AuradineWebAPI(BaseWebAPI): async def set_frequency(self, board: int, frequency: float) -> dict: """Set the frequency for a specific board on the Auradine miner. - + Args: board (int): The index of the board to configure. frequency (float): The frequency in MHz to set for the board. - + Returns: dict: A dictionary indicating the result of setting the frequency. """ @@ -219,7 +219,7 @@ class AuradineWebAPI(BaseWebAPI): async def ipreport(self) -> dict: """Generate an IP report for the Auradine miner. - + Returns: dict: A dictionary containing the IP report details. """ @@ -227,7 +227,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_led(self) -> dict: """Retrieve the current LED status from the Auradine miner. - + Returns: dict: A dictionary containing the current status of the LED settings. """ @@ -235,10 +235,10 @@ class AuradineWebAPI(BaseWebAPI): async def set_led(self, code: int) -> dict: """Set the LED code on the Auradine miner. - + Args: code (int): The code that determines the LED behavior. - + Returns: dict: A dictionary indicating the result of the operation. """ @@ -246,13 +246,13 @@ class AuradineWebAPI(BaseWebAPI): async def set_led_custom(self, code: int, led_1: int, led_2: int, msg: str) -> dict: """Set custom LED configurations including messages. - + Args: code (int): The LED code to set. led_1 (int): The first LED indicator number. led_2 (int): The second LED indicator number. msg (str): The message to display or represent with LEDs. - + Returns: dict: A dictionary indicating the result of the custom LED configuration. """ @@ -262,7 +262,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_mode(self) -> dict: """Retrieve the current operational mode of the Auradine miner. - + Returns: dict: A dictionary containing the current mode settings. """ @@ -270,10 +270,10 @@ class AuradineWebAPI(BaseWebAPI): async def set_mode(self, **kwargs) -> dict: """Set the operational mode of the Auradine miner. - + Args: **kwargs: Mode settings specified as keyword arguments. - + Returns: dict: A dictionary indicating the result of the mode setting operation. """ @@ -281,7 +281,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_network(self) -> dict: """Retrieve the network configuration settings of the Auradine miner. - + Returns: dict: A dictionary containing the network configuration details. """ @@ -289,10 +289,10 @@ class AuradineWebAPI(BaseWebAPI): async def set_network(self, **kwargs) -> dict: """Set the network configuration of the Auradine miner. - + Args: **kwargs: Network settings specified as keyword arguments. - + Returns: dict: A dictionary indicating the result of the network configuration. """ @@ -300,10 +300,10 @@ class AuradineWebAPI(BaseWebAPI): async def password(self, password: str) -> dict: """Change the password used for accessing the Auradine miner. - + Args: password (str): The new password to set. - + Returns: dict: A dictionary indicating the result of the password change operation. """ @@ -315,7 +315,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_psu(self) -> dict: """Retrieve the status of the power supply unit (PSU) from the Auradine miner. - + Returns: dict: A dictionary containing the PSU status. """ @@ -323,10 +323,10 @@ class AuradineWebAPI(BaseWebAPI): async def set_psu(self, voltage: float) -> dict: """Set the voltage for the power supply unit of the Auradine miner. - + Args: voltage (float): The voltage level to set for the PSU. - + Returns: dict: A dictionary indicating the result of setting the PSU voltage. """ @@ -334,7 +334,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_register(self) -> dict: """Retrieve registration information from the Auradine miner. - + Returns: dict: A dictionary containing the registration details. """ @@ -342,10 +342,10 @@ class AuradineWebAPI(BaseWebAPI): async def set_register(self, company: str) -> dict: """Set the registration information for the Auradine miner. - + Args: company (str): The company name to register the miner under. - + Returns: dict: A dictionary indicating the result of the registration operation. """ @@ -353,7 +353,7 @@ class AuradineWebAPI(BaseWebAPI): async def reboot(self) -> dict: """Reboot the Auradine miner. - + Returns: dict: A dictionary indicating the result of the reboot operation. """ @@ -361,7 +361,7 @@ class AuradineWebAPI(BaseWebAPI): async def restart_gcminer(self) -> dict: """Restart the GCMiner application on the Auradine miner. - + Returns: dict: A dictionary indicating the result of the GCMiner restart operation. """ @@ -369,7 +369,7 @@ class AuradineWebAPI(BaseWebAPI): async def restart_api_server(self) -> dict: """Restart the API server on the Auradine miner. - + Returns: dict: A dictionary indicating the result of the API server restart operation. """ @@ -377,7 +377,7 @@ class AuradineWebAPI(BaseWebAPI): async def temperature(self) -> dict: """Retrieve the current temperature readings from the Auradine miner. - + Returns: dict: A dictionary containing temperature data. """ @@ -385,11 +385,11 @@ class AuradineWebAPI(BaseWebAPI): async def timedate(self, ntp: str, timezone: str) -> dict: """Set the time and date settings for the Auradine miner. - + Args: ntp (str): The NTP server to use for time synchronization. timezone (str): The timezone setting. - + Returns: dict: A dictionary indicating the result of setting the time and date. """ @@ -397,7 +397,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_token(self) -> dict: """Retrieve the current authentication token for the Auradine miner. - + Returns: dict: A dictionary containing the authentication token. """ @@ -405,10 +405,10 @@ class AuradineWebAPI(BaseWebAPI): async def update_pools(self, pools: list[dict]) -> dict: """Update the mining pools configuration on the Auradine miner. - + Args: pools (list[dict]): A list of dictionaries, each representing a pool configuration. - + Returns: dict: A dictionary indicating the result of the update operation. """ @@ -416,7 +416,7 @@ class AuradineWebAPI(BaseWebAPI): async def voltage(self) -> dict: """Retrieve the voltage settings of the Auradine miner. - + Returns: dict: A dictionary containing the voltage details. """ @@ -424,7 +424,7 @@ class AuradineWebAPI(BaseWebAPI): async def get_ztp(self) -> dict: """Retrieve the zero-touch provisioning status from the Auradine miner. - + Returns: dict: A dictionary containing the ZTP status. """ @@ -432,10 +432,10 @@ class AuradineWebAPI(BaseWebAPI): async def set_ztp(self, enable: bool) -> dict: """Enable or disable zero-touch provisioning (ZTP) on the Auradine miner. - + Args: enable (bool): True to enable ZTP, False to disable. - + Returns: dict: A dictionary indicating the result of the ZTP setting operation. """ diff --git a/tests/config_tests/fans.py b/tests/config_tests/fans.py index 35bd1461..b0d33f54 100644 --- a/tests/config_tests/fans.py +++ b/tests/config_tests/fans.py @@ -72,4 +72,4 @@ class TestFanConfig(unittest.TestCase): ): conf = fan_mode() boser_conf = conf.as_boser() - self.assertEqual(conf, FanModeConfig.from_boser(boser_conf)) \ No newline at end of file + self.assertEqual(conf, FanModeConfig.from_boser(boser_conf))