### Install pyasic using Poetry Source: https://github.com/upstreamdata/pyasic/blob/master/README.md Installs pyasic and its development dependencies using the recommended Poetry package manager. This is suitable for developers contributing to the project. ```shell poetry install --with dev pre-commit install ``` -------------------------------- ### Build Documentation Locally with Poetry Source: https://github.com/upstreamdata/pyasic/blob/master/README.md Installs documentation dependencies and builds the project's documentation locally. This allows developers to preview changes to the documentation. ```shell poetry install --with docs python docs/generate_miners.py poetry run mkdocs serve ``` -------------------------------- ### Control Miner Fault Light with pyasic Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Illustrates how to use `pyasic` to control specific miner functions, such as turning on the fault indicator light. This example connects to a miner and invokes the `fault_light_on()` method, demonstrating basic miner control capabilities. ```python import asyncio from pyasic import get_miner async def set_fault_light(): miner = await get_miner("192.168.1.20") await miner.fault_light_on() if __name__ == "__main__": asyncio.run(set_fault_light()) ``` -------------------------------- ### Get and Send Miner Configuration using Pyasic Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Demonstrates how to retrieve the current configuration of a miner using `get_config()` and then send an updated configuration back using `send_config()`. This function requires the `asyncio` library and the `pyasic` library. ```python import asyncio from pyasic import get_miner async def set_fault_light(): miner = await get_miner("192.168.1.20") # get config cfg = await miner.get_config() # send config await miner.send_config(cfg) if __name__ == "__main__": asyncio.run(set_fault_light()) ``` -------------------------------- ### Get Pyasic Setting Source: https://github.com/upstreamdata/pyasic/blob/master/docs/settings/settings.md Retrieves the current value of a specific Pyasic global setting. ```APIDOC ## GET /settings/{key} ### Description Retrieves the current value of a specific Pyasic global setting. ### Method GET ### Endpoint `/settings/{key}` ### Parameters #### Path Parameters - **key** (string) - Required - The name of the setting to retrieve. ### Response #### Success Response (200) - **value** (any) - The current value of the requested setting. #### Response Example ```json { "value": "some_setting_value" } ``` ``` -------------------------------- ### Get Data from a Single Miner with pyasic Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Demonstrates how to connect to a single ASIC miner using its IP address and retrieve its data. It requires the `asyncio` library for asynchronous operations and `pyasic.get_miner` to establish the connection. The output includes the miner's overall data and its hashrate. ```python import asyncio from pyasic import get_miner async def gather_miner_data(): miner = await get_miner("192.168.1.75") if miner is not None: miner_data = await miner.get_data() print(miner_data) print(miner_data.hashrate) # hashrate of the miner in TH/s if __name__ == "__main__": asyncio.run(gather_miner_data()) ``` -------------------------------- ### Apply Miner Configuration with Pyasic Source: https://context7.com/upstreamdata/pyasic/llms.txt This Python code snippet demonstrates how to apply a new mining configuration to an ASIC miner using the Pyasic library. It covers modifying pool settings, power tune modes, fan speeds, and temperature thresholds. Ensure the Pyasic library is installed and the miner's IP address is correct. The function takes no direct arguments but operates on a hardcoded IP address and returns a boolean indicating success. ```python import asyncio from pyasic import get_miner from pyasic.config import MinerConfig from pyasic.config.pools import PoolConfig, PoolUrl from pyasic.config.mining import MiningModePowerTune from pyasic.config.fans import FanModeManual from pyasic.config.temperature import TemperatureConfig async def configure_miner(): miner = await get_miner("192.168.1.100") # Get current config as starting point config = await miner.get_config() # Modify pool configuration config.pools.pool_1.url = "stratum+tcp://pool.example.com:3333" config.pools.pool_1.user = "myusername.worker001" config.pools.pool_1.password = "x" # Set power limit mode (3000W) config.mining_mode = MiningModePowerTune(power=3000) # Set manual fan speed (80%) config.fan_mode = FanModeManual(speed=80) # Set temperature thresholds config.temperature = TemperatureConfig( target=70, hot=80, dangerous=90 ) # Send configuration to miner await miner.send_config(config, user_suffix=None) print(f"Configuration applied to {miner.ip}") # Verify configuration was applied await asyncio.sleep(2) new_config = await miner.get_config() print(f"New pool: {new_config.pools.pool_1.url}") print(f"New power limit: {new_config.mining_mode.power if hasattr(new_config.mining_mode, 'power') else 'N/A'}") return True if __name__ == "__main__": asyncio.run(configure_miner()) ``` -------------------------------- ### Get Miner Configuration with PyAsic Source: https://context7.com/upstreamdata/pyasic/llms.txt Retrieve the current configuration settings of a mining device, including pool assignments, power management, fan control, and temperature thresholds. This function connects to a miner, fetches its configuration, and prints details about the pools, mining modes, fan settings, and temperature limits. It utilizes `pyasic.get_miner` and requires `asyncio`. The full configuration can also be exported as a dictionary. ```python import asyncio from pyasic import get_miner async def get_miner_configuration(): miner = await get_miner("192.168.1.100") # Get current configuration config = await miner.get_config() # Access pool configuration print(f"Pool 1: {config.pools.pool_1.url}") print(f"Pool 1 User: {config.pools.pool_1.user}") print(f"Pool 2: {config.pools.pool_2.url}") print(f"Pool 3: {config.pools.pool_3.url}") # Access mining mode settings print(f"Mining Mode: {type(config.mining_mode).__name__}") if hasattr(config.mining_mode, 'power'): print(f"Power Limit: {config.mining_mode.power} W") # Access fan mode print(f"Fan Mode: {type(config.fan_mode).__name__}") if hasattr(config.fan_mode, 'speed'): print(f"Fan Speed: {config.fan_mode.speed}%") # Access temperature settings print(f"Target Temperature: {config.temperature.target}°C") print(f"Hot Temperature: {config.temperature.hot}°C") print(f"Dangerous Temperature: {config.temperature.dangerous}°C") # Export configuration as dictionary config_dict = config.as_dict() print(f"Full config: {config_dict}") return config if __name__ == "__main__": asyncio.run(get_miner_configuration()) ``` -------------------------------- ### MinerFactory - Create and Manage Miners Source: https://github.com/upstreamdata/pyasic/blob/master/docs/miners/miner_factory.md The MinerFactory is the primary way to create miner types in pyasic. It offers methods to get single miners, clear the cache, and retrieve multiple miners. ```APIDOC ## MinerFactory Class ### Description Provides methods for creating and managing miner instances. ### Methods #### `get_miner(ip: str, port: int = 4028, ssh_port: int = 22, retry: int = 1, delay: int = 5, timeout: int = 15, **kwargs)` Retrieves a miner instance for the given IP address. This is the main method to get a miner object. - **ip** (str) - Required - The IP address of the miner. - **port** (int) - Optional - The HTTP port of the miner. Defaults to 4028. - **ssh_port** (int) - Optional - The SSH port of the miner. Defaults to 22. - **retry** (int) - Optional - Number of retries for connection. Defaults to 1. - **delay** (int) - Optional - Delay in seconds between retries. Defaults to 5. - **timeout** (int) - Optional - Connection timeout in seconds. Defaults to 15. #### `clear_cached_miners()` Clears the internal cache of miner instances. #### `get_multiple_miners(ips: list[str], port: int = 4028, ssh_port: int = 22, retry: int = 1, delay: int = 5, timeout: int = 15, **kwargs)` Retrieves multiple miner instances for a list of IP addresses. - **ips** (list[str]) - Required - A list of IP addresses of the miners. - **port** (int) - Optional - The HTTP port of the miners. Defaults to 4028. - **ssh_port** (int) - Optional - The SSH port of the miners. Defaults to 22. - **retry** (int) - Optional - Number of retries for connection. Defaults to 1. - **delay** (int) - Optional - Delay in seconds between retries. Defaults to 5. - **timeout** (int) - Optional - Connection timeout in seconds. Defaults to 15. #### `get_miner_generator(ips: list[str], port: int = 4028, ssh_port: int = 22, retry: int = 1, delay: int = 5, timeout: int = 15, **kwargs)` Returns an AsyncGenerator that yields miner instances for a list of IP addresses. - **ips** (list[str]) - Required - A list of IP addresses of the miners. - **port** (int) - Optional - The HTTP port of the miners. Defaults to 4028. - **ssh_port** (int) - Optional - The SSH port of the miners. Defaults to 22. - **retry** (int) - Optional - Number of retries for connection. Defaults to 1. - **delay** (int) - Optional - Delay in seconds between retries. Defaults to 5. - **timeout** (int) - Optional - Connection timeout in seconds. Defaults to 15. ### Request Example ```python import pyasic # Get a single miner miner = pyasic.get_miner("192.168.1.100") # Get multiple miners miners = pyasic.miner_factory.get_multiple_miners(["192.168.1.100", "192.168.1.101"]) # Use miner generator # async for miner in pyasic.miner_factory.get_miner_generator(["192.168.1.100"]): # print(miner) # Clear cache pyasic.miner_factory.clear_cached_miners() ``` ### Response - **Miner Instance** - An instance of a `BaseMiner` subclass specific to the detected miner model. ### Error Handling - Connection errors or invalid IP addresses will raise exceptions. ``` -------------------------------- ### Get Data from Multiple Miners with pyasic Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Shows how to scan a subnet for multiple ASIC miners and retrieve data from all of them concurrently. This method utilizes `pyasic.network.MinerNetwork` and `asyncio.gather` for efficient data collection from various miners on the network. It prints aggregated data from all scanned miners. ```python import asyncio from pyasic.network import MinerNetwork async def gather_miner_data(): network = MinerNetwork.from_subnet("192.168.1.50/24") miners = await network.scan() all_miner_data = await asyncio.gather(*[miner.get_data() for miner in miners]) for miner_data in all_miner_data: print(miner_data) if __name__ == "__main__": asyncio.run(gather_miner_data()) ``` -------------------------------- ### Get Miner Endpoint Source: https://github.com/upstreamdata/pyasic/blob/master/docs/miners/miner_factory.md Retrieves a specific miner instance using its IP address. This is the primary function for obtaining a miner object. ```APIDOC ## GET /get_miner ### Description Retrieves a miner instance based on the provided IP address and optional connection parameters. ### Method GET ### Endpoint `/get_miner` (Implicitly called via `pyasic.get_miner()`) ### Parameters #### Query Parameters - **ip** (str) - Required - The IP address of the miner. - **port** (int) - Optional - The HTTP port of the miner. Defaults to 4028. - **ssh_port** (int) - Optional - The SSH port of the miner. Defaults to 22. - **retry** (int) - Optional - Number of retries for connection. Defaults to 1. - **delay** (int) - Optional - Delay in seconds between retries. Defaults to 5. - **timeout** (int) - Optional - Connection timeout in seconds. Defaults to 15. ### Request Example ```python import pyasic miner_ip = "192.168.1.100" miner = pyasic.get_miner(ip=miner_ip, port=4028, timeout=20) ``` ### Response #### Success Response (200) - **miner_instance** (`pyasic.miners.base.AnyMiner`) - An object representing the miner, with methods to interact with it. ``` -------------------------------- ### Get Miner by IP Address - pyasic Miner Instantiation Source: https://context7.com/upstreamdata/pyasic/llms.txt Instantiates a specific miner by its IP address with automatic type detection and identification. Supports retrieving a single miner or multiple miners concurrently using `asyncio.gather`. Dependencies: `asyncio`, `pyasic.get_miner`. ```python import asyncio from pyasic import get_miner async def get_specific_miners(): # Get single miner miner = await get_miner("192.168.1.100") print(f"Miner: {miner.model} at {miner.ip}") # Get multiple miners concurrently using asyncio.gather miners = await asyncio.gather( get_miner("192.168.1.100"), get_miner("192.168.1.101"), get_miner("192.168.1.102"), ) # Process results for miner in miners: if miner is not None: print(f"Type: {miner.make}, Model: {miner.raw_model}, Firmware: {miner.firmware}") else: print("Miner not found or unreachable") return miners if __name__ == "__main__": asyncio.run(get_specific_miners()) ``` -------------------------------- ### Get Single Miner Operational Data with PyAsic Source: https://context7.com/upstreamdata/pyasic/llms.txt Retrieve detailed operational metrics from a single mining device. This function connects to a specified miner IP, fetches its current data including hashrate, temperature, power consumption, and status, and prints these metrics. It requires the `pyasic` library and `asyncio` for asynchronous operations. Dependencies include network connectivity to the miner. ```python import asyncio from pyasic import get_miner async def get_single_miner_data(): miner = await get_miner("192.168.1.100") if miner is None: print("Miner not found") return # Get complete data snapshot data = await miner.get_data() # Access specific metrics print(f"IP Address: {data.ip}") print(f"Model: {data.model}") print(f"Hashrate: {data.hashrate} TH/s") print(f"Power Consumption: {data.wattage} W") print(f"Power Limit: {data.wattage_limit} W") print(f"Efficiency: {data.efficiency} J/TH") print(f"Average Temperature: {data.temperature_avg}°C") print(f"Total Chips: {data.total_chips}/{data.expected_chips}") print(f"Chip Health: {data.percent_expected_chips}%") print(f"Uptime: {data.uptime} seconds") print(f"Is Mining: {data.is_mining}") # Access hashboard details for idx, board in enumerate(data.hashboards): print(f"Board {idx}: {board.hashrate} TH/s, {board.temp}°C, {board.chips} chips") # Access fan speeds for idx, fan in enumerate(data.fans): print(f"Fan {idx}: {fan.speed} RPM") # Check for errors if data.errors: for error in data.errors: print(f"Error: {error.error_message}") return data if __name__ == "__main__": asyncio.run(get_single_miner_data()) ``` -------------------------------- ### Get Fleet Miner Data with PyAsic Source: https://context7.com/upstreamdata/pyasic/llms.txt Efficiently retrieve data from multiple miners simultaneously using network scanning and asynchronous operations. This function discovers miners on a subnet, collects data from all found devices concurrently, and aggregates fleet-wide statistics like total hashrate and power consumption. It leverages `pyasic.network.MinerNetwork` and `asyncio.gather`. The output can be exported to various formats like JSON, CSV, and InfluxDB. ```python import asyncio from pyasic.network import MinerNetwork async def get_fleet_data(): # Discover miners network = MinerNetwork.from_subnet("192.168.1.0/24") miners = await network.scan() print(f"Collecting data from {len(miners)} miners...") # Gather data from all miners concurrently all_data = await asyncio.gather(*[miner.get_data() for miner in miners]) # Aggregate statistics total_hashrate = sum(data.hashrate for data in all_data if data.hashrate) total_power = sum(data.wattage for data in all_data if data.wattage) avg_efficiency = total_power / total_hashrate if total_hashrate else 0 print(f"Fleet Statistics:") print(f"Total Hashrate: {total_hashrate:.2f} TH/s") print(f"Total Power: {total_power} W") print(f"Average Efficiency: {avg_efficiency:.2f} J/TH") # Calculate fleet average using MinerData addition from pyasic.data import MinerData avg_data = sum(all_data, start=MinerData("0.0.0.0")) / len(all_data) print(f"Average Hashrate per Miner: {avg_data.hashrate:.2f} TH/s") print(f"Average Temperature: {avg_data.temperature_avg}°C") # Export to different formats for data in all_data: json_data = data.as_json() csv_data = data.as_csv() influx_data = data.as_influxdb(measurement_name="miner_metrics") # Process exports as needed return all_data if __name__ == "__main__": asyncio.run(get_fleet_data()) ``` -------------------------------- ### Miner Web APIs Overview Source: https://github.com/upstreamdata/pyasic/blob/master/docs/web/api.md This section provides an overview of the Web API communication with ASIC miners. Each miner has a unique Web API, and the available commands can differ. All API implementations inherit from `BaseWebAPI`. ```APIDOC ## Miner Web APIs Each miner has a unique Web API that is used to communicate with it. Each of these API types has commands that differ between them, and some commands have data that others do not. Each miner that is a subclass of `pyasic.miners.base.BaseMiner` may have an API linked to it as `Miner.web`. All API implementations inherit from `pyasic.web.BaseWebAPI`, which implements the basic communications protocols. `pyasic.web.BaseWebAPI` should never be used unless inheriting to create a new miner API class for a new type of miner (which should be exceedingly rare). Use these instead - - [AntminerModerNWebAPI][pyasic.web.antminer.AntminerModernWebAPI] - [AntminerOldWebAPI][pyasic.web.antminer.AntminerOldWebAPI] - [AuradineWebAPI][pyasic.web.auradine.AuradineWebAPI] - [ePICWebAPI][pyasic.web.epic.ePICWebAPI] - [GoldshellWebAPI][pyasic.web.goldshell.GoldshellWebAPI] - [InnosiliconWebAPI][pyasic.web.innosilicon.InnosiliconWebAPI] - [MaraWebAPI][pyasic.web.marathon.MaraWebAPI] - [VNishWebAPI][pyasic.web.vnish.VNishWebAPI] ``` -------------------------------- ### Scan for Bitcoin ASICs using pyasic Source: https://github.com/upstreamdata/pyasic/blob/master/README.md Demonstrates how to use the pyasic library to scan a network subnet for Bitcoin ASIC miners. It utilizes asyncio for asynchronous operations and the MinerNetwork class for discovery. ```python import asyncio from pyasic.network import MinerNetwork async def scan_miners(): network = MinerNetwork.from_subnet("192.168.1.50/24") miners = await network.scan() print(miners) if __name__ == "__main__": asyncio.run(scan_miners()) ``` -------------------------------- ### Convert Miner Data to Multiple Formats with pyasic Source: https://context7.com/upstreamdata/pyasic/llms.txt Demonstrates retrieving miner data and converting it into dictionary, JSON, CSV, and InfluxDB line protocol formats. It also shows how to access computed metrics like efficiency, timestamps, and expected chip/hashrate percentages. Requires the pyasic library and an asyncio event loop. ```python import asyncio from pyasic import get_miner async def export_miner_data(): miner = await get_miner("192.168.1.100") data = await miner.get_data() # Convert to dictionary data_dict = data.as_dict() print("Dictionary format:") print(f"IP: {data_dict['ip']}, Hashrate: {data_dict['hashrate']}") # Convert to JSON json_output = data.as_json() print("\nJSON format (truncated):") print(json_output[:200] + "...") # Convert to CSV (no headers) csv_output = data.as_csv() print("\nCSV format (truncated):") print(csv_output[:200] + "...") # Convert to InfluxDB line protocol influx_output = data.as_influxdb( measurement_name="miner_data", level_delimiter="." ) print("\nInfluxDB line protocol:") print(influx_output[:200] + "...") # Access computed fields print("\nComputed metrics:") print(f"Datetime: {data.datetime}") print(f"Timestamp: {data.timestamp}") print(f"Efficiency: {data.efficiency} J/TH") print(f"Efficiency (fractional): {data.efficiency_fract} J/TH") print(f"Nominal chip count: {data.nominal}") print(f"Chip percentage: {data.percent_expected_chips}%") print(f"Hashrate percentage: {data.percent_expected_hashrate}%") print(f"Power percentage: {data.percent_expected_wattage}%") # Access all available fields all_fields = data.fields() print(f"\nAll available fields ({len(all_fields)} total):") print(sorted(all_fields)) return data if __name__ == "__main__": asyncio.run(export_miner_data()) ``` -------------------------------- ### Control Miner Mining State (Stop/Resume) with PyAsic Source: https://context7.com/upstreamdata/pyasic/llms.txt Demonstrates how to stop and resume mining operations on an ASIC miner using the pyasic library. It includes checking the initial status, stopping, verifying the stop, resuming, and verifying the resumed state. Requires network access to the miner. ```python import asyncio from pyasic import get_miner async def control_mining_state(): miner = await get_miner("192.168.1.100") # Check current mining status data = await miner.get_data() print(f"Initial mining status: {data.is_mining}") print(f"Initial hashrate: {data.hashrate} TH/s") # Stop mining print("Stopping mining operations...") success = await miner.stop_mining() if success: print("Mining stopped successfully") # Wait and verify mining has stopped await asyncio.sleep(5) data = await miner.get_data() print(f"Mining status: {data.is_mining}") print(f"Hashrate: {data.hashrate}") # Resume mining await asyncio.sleep(10) print("Resuming mining operations...") success = await miner.resume_mining() if success: print("Mining resumed successfully") # Wait for hashrate to stabilize await asyncio.sleep(30) data = await miner.get_data() print(f"Mining status: {data.is_mining}") print(f"Hashrate: {data.hashrate} TH/s") return success if __name__ == "__main__": asyncio.run(control_mining_state()) ``` -------------------------------- ### Reboot Miner Backend and System with Pyasic Source: https://context7.com/upstreamdata/pyasic/llms.txt This Python code snippet demonstrates how to restart the mining backend (e.g., cgminer, bminer) and perform a full system reboot on an ASIC miner using Pyasic. It includes options to check the mining status and hashrate after a backend restart. The full system reboot functionality is commented out but shows how to initiate it and wait for the miner to come back online. The function operates on a hardcoded miner IP address and returns a boolean indicating the success of the last attempted operation. ```python import asyncio from pyasic import get_miner async def control_miner_operations(): miner = await get_miner("192.168.1.100") # Restart mining backend (cgminer/bmminer/etc) without full reboot print("Restarting mining backend...") success = await miner.restart_backend() if success: print("Mining backend restarted successfully") # Wait for backend to initialize await asyncio.sleep(30) # Verify miner is mining again data = await miner.get_data() print(f"Mining status: {data.is_mining}") print(f"Hashrate: {data.hashrate} TH/s") # Full system reboot (uncomment to execute) # print("Rebooting miner system...") # success = await miner.reboot() # if success: # print("Miner reboot initiated") # # Wait for reboot (typically 60-120 seconds) # await asyncio.sleep(120) # # Verify miner is back online # new_miner = await get_miner("192.168.1.100") # if new_miner: # print("Miner is back online") return success if __name__ == "__main__": asyncio.run(control_miner_operations()) ``` -------------------------------- ### Adjust Miner Power Limit with PyAsic Source: https://context7.com/upstreamdata/pyasic/llms.txt Shows how to dynamically set a power limit for ASIC miners that support this feature using pyasic. It retrieves current power statistics, sets a new limit, and then verifies the updated stats. This function may fail on miners that do not support power tuning. ```python import asyncio from pyasic import get_miner async def adjust_power_limit(): miner = await get_miner("192.168.1.100") # Get current power stats data = await miner.get_data() print(f"Current power: {data.wattage} W") print(f"Current limit: {data.wattage_limit} W") print(f"Current hashrate: {data.hashrate} TH/s") print(f"Current efficiency: {data.efficiency} J/TH") # Set new power limit to 2800W new_limit = 2800 print(f"\nSetting power limit to {new_limit}W...") success = await miner.set_power_limit(new_limit) if success: print("Power limit updated successfully") # Wait for miner to adjust await asyncio.sleep(60) # Get new stats data = await miner.get_data() print(f"\nNew power: {data.wattage} W") print(f"New limit: {data.wattage_limit} W") print(f"New hashrate: {data.hashrate} TH/s") print(f"New efficiency: {data.efficiency} J/TH") else: print("Failed to set power limit (may not be supported)") return success if __name__ == "__main__": asyncio.run(adjust_power_limit()) ``` -------------------------------- ### BaseWebAPI Source: https://github.com/upstreamdata/pyasic/blob/master/docs/web/api.md The `BaseWebAPI` class provides the foundational communication protocols for all miner Web APIs. It is intended for inheritance when creating new miner API classes. ```APIDOC ## BaseWebAPI ::: pyasic.web.BaseWebAPI handler: python options: heading_level: 4 ``` -------------------------------- ### Configure PyAsic Global Settings Source: https://context7.com/upstreamdata/pyasic/llms.txt Illustrates how to configure and update global settings for the pyasic library. This includes modifying network timeouts, retry counts, API function timeouts, and default passwords for various miner types. Changes affect subsequent operations. ```python from pyasic import settings # Display current settings print("Current Settings:") print(f"Network ping timeout: {settings.get('network_ping_timeout')}s") print(f"Network ping retries: {settings.get('network_ping_retries')}") print(f"API function timeout: {settings.get('api_function_timeout')}s") print(f"Factory get timeout: {settings.get('factory_get_timeout')}s") # Update network timeout settings for slower networks settings.update("network_ping_timeout", 5) settings.update("network_ping_retries", 3) settings.update("api_function_timeout", 10) print("\nUpdated timeout settings for slower network") # Configure default passwords for different miner types settings.update("default_antminer_web_password", "custom_password") settings.update("default_whatsminer_rpc_password", "custom_rpc_pwd") settings.update("default_goldshell_web_password", "goldshell_pwd") settings.update("default_braiins_web_password", "braiins_pwd") print("Updated default passwords for miner types") # Set scan concurrency limit (None = unlimited, or specify max concurrent scans) settings.update("network_scan_semaphore", 50) print("Limited network scan concurrency to 50 simultaneous connections") # Configure data retrieval retries settings.update("get_data_retries", 3) print("Set data retrieval retries to 3 attempts") ``` -------------------------------- ### Gather Data from Multiple Miners using MinerNetwork Source: https://github.com/upstreamdata/pyasic/blob/master/README.md This code demonstrates how to efficiently gather data from multiple miners on a subnet. It utilizes `MinerNetwork.from_subnet()` to create a network object and `network.scan()` to discover miners. Subsequently, `asyncio.gather()` is used to concurrently fetch data from all discovered miners, improving performance. ```python import asyncio from pyasic.network import MinerNetwork async def gather_miner_data(): network = MinerNetwork.from_subnet("192.168.1.50/24") miners = await network.scan() all_miner_data = await asyncio.gather(*[miner.get_data() for miner in miners]) for miner_data in all_miner_data: print(miner_data) ``` -------------------------------- ### Manage Miner Fault Light with Pyasic Source: https://context7.com/upstreamdata/pyasic/llms.txt This Python code snippet shows how to control the fault light LED on an ASIC miner using Pyasic. It includes checking the current status, turning the light on, and turning it off. The function operates on a hardcoded miner IP address and returns a boolean indicating the success of the last operation (turning the light off). Proper error handling for network or device issues is recommended in production environments. ```python import asyncio from pyasic import get_miner async def manage_fault_light(): miner = await get_miner("192.168.1.100") # Check current light status is_on = await miner.check_light() print(f"Fault light currently: {'ON' if is_on else 'OFF'}") # Turn fault light on success = await miner.fault_light_on() if success: print("Fault light turned ON successfully") # Wait for visibility await asyncio.sleep(5) # Verify light is on is_on = await miner.check_light() print(f"Light status: {'ON' if is_on else 'OFF'}") # Turn fault light off success = await miner.fault_light_off() if success: print("Fault light turned OFF successfully") return success if __name__ == "__main__": asyncio.run(manage_fault_light()) ``` -------------------------------- ### Perform Arithmetic Operations on MinerData Instances Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Shows how to use the `MinerData` dataclass for calculations, such as averaging data from multiple miners. It demonstrates adding `MinerData` objects together and dividing by a scalar to compute average values across a list of miner data instances. ```python from pyasic import MinerData # examples of miner data d1 = MinerData("192.168.1.1") d2 = MinerData("192.168.1.2") list_of_miner_data = [d1, d2] average_data = sum(list_of_miner_data, start=MinerData("0.0.0.0"))/len(list_of_miner_data) ``` -------------------------------- ### Discover Miners on Subnet - pyasic Network Scan Source: https://context7.com/upstreamdata/pyasic/llms.txt Scans a network subnet to automatically discover and instantiate miner objects. It supports CIDR notation for subnet specification and returns typed miner instances. Dependencies include `asyncio` and `pyasic.network`. ```python import asyncio from pyasic.network import MinerNetwork async def scan_network(): # Create network from subnet notation (supports CIDR) network = MinerNetwork.from_subnet("192.168.1.0/24") # Scan asynchronously and return typed miner instances miners = await network.scan() # Display discovered miners for miner in miners: print(f"Found: {miner.model} at {miner.ip}") return miners if __name__ == "__main__": discovered_miners = asyncio.run(scan_network()) ``` -------------------------------- ### AnyMiner Type Source: https://github.com/upstreamdata/pyasic/blob/master/docs/miners/miner_factory.md Describes the AnyMiner type, which serves as a placeholder for typing miner return values. ```APIDOC ## AnyMiner Type Variable ### Description `AnyMiner` is a type variable used for typing function return values that are expected to be a subclass of `BaseMiner`. It indicates that the function will return an instance of some arbitrary miner class. ### Type `pyasic.miners.base.AnyMiner` ### Usage Used in function signatures to denote that a function returns an instance of any recognized miner class. ### Example ```python from typing import TypeVar import pyasic # Define a function that returns a miner instance # The return type hint uses AnyMiner # def get_specific_miner(ip: str) -> pyasic.miners.base.AnyMiner: # return pyasic.get_miner(ip) ``` ``` -------------------------------- ### Scan for Miners on the Network (Python) Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Discovers and retrieves a list of supported ASIC miners on the network using the MinerNetwork class. It scans a specified subnet and returns a list of Miner objects. This function requires the asyncio library for asynchronous operations. ```python import asyncio from pyasic.network import MinerNetwork async def scan_miners(): network = MinerNetwork.from_subnet("192.168.1.50/24") miners = await network.scan() print(miners) if __name__ == "__main__": asyncio.run(scan_miners()) ``` -------------------------------- ### Gather Data from a Single Miner using get_data() Source: https://github.com/upstreamdata/pyasic/blob/master/README.md This snippet shows how to retrieve data from a single identified miner. It uses `get_miner()` to obtain a miner object and then calls the `get_data()` method on it. The returned `MinerData` object contains all gatherable information, accessible as attributes like `hashrate`. ```python import asyncio from pyasic import get_miner async def gather_miner_data(): miner = await get_miner("192.168.1.75") if miner is not None: miner_data = await miner.get_data() print(miner_data) print(miner_data.hashrate) if __name__ == "__main__": asyncio.run(gather_miner_data()) ``` -------------------------------- ### Scan Custom IP Ranges - pyasic Network Scan Source: https://context7.com/upstreamdata/pyasic/llms.txt Creates network scans using flexible IP range specifications, including hyphenated octets and lists of ranges. It supports real-time results via an async generator and can scan multiple specific IP ranges concurrently. Dependencies: `asyncio`, `pyasic.network`. ```python import asyncio from pyasic.network import MinerNetwork async def scan_custom_range(): # Scan multiple ranges: 192.168.1-2.50-100 network = MinerNetwork.from_address("192.168.1-2.50-100") # Use async generator for real-time results async for miner in network.scan_network_generator(): if miner is not None: print(f"Discovered: {miner.ip} - {miner.make}") # Alternative: scan multiple specific ranges networks = MinerNetwork.from_list([ "192.168.1.1-50", "192.168.2.1-50", "10.0.0.100-150" ]) miners = await networks.scan() return miners if __name__ == "__main__": asyncio.run(scan_custom_range()) ``` -------------------------------- ### CGMinerAvalon851 Class for Avalon 851 Miner Source: https://github.com/upstreamdata/pyasic/blob/master/docs/miners/avalonminer/A8X.md This Python class, CGMinerAvalon851, is dedicated to controlling the Avalon 851 ASIC miner. It exposes methods for handling shutdowns, managing power modes, setting operational parameters, and applying presets. As part of the pyasic library, it facilitates programmatic interaction with the miner. ```python from pyasic.miners.avalonminer.cgminer.A8X.A851 import CGMinerAvalon851 ``` -------------------------------- ### Calculate Average Miner Data using MinerData Dataclass Source: https://github.com/upstreamdata/pyasic/blob/master/README.md This snippet demonstrates the utility of the `MinerData` dataclass for performing calculations across multiple miner data instances. It shows how to initialize `MinerData` objects, aggregate them using `sum()`, and calculate the average by dividing by the count. This is useful for obtaining combined statistics from a group of miners. ```python from pyasic import MinerData d1 = MinerData("192.168.1.1") d2 = MinerData("192.168.1.2") list_of_miner_data = [d1, d2] average_data = sum(list_of_miner_data, start=MinerData("0.0.0.0"))/len(list_of_miner_data) ``` -------------------------------- ### Handle Miner Errors and Diagnostics with pyasic Source: https://context7.com/upstreamdata/pyasic/llms.txt This snippet shows how to handle potential API errors and access diagnostic information from miners using pyasic. It includes checks for errors reported by the miner, chip health, hashrate, temperature, and mining status. Dependencies include asyncio, pyasic, and pyasic.errors.APIError. ```python import asyncio from pyasic import get_miner from pyasic.errors import APIError async def handle_miner_errors(): try: miner = await get_miner("192.168.1.100") if miner is None: print("Miner not found or unreachable") return # Get miner data with error information data = await miner.get_data() # Check for errors if data.errors: print(f"Found {len(data.errors)} errors:") for error in data.errors: print(f" - Code: {error.error_code}") print(f" Message: {error.error_message}") if hasattr(error, 'error_type'): print(f" Type: {error.error_type}") else: print("No errors detected") # Check health metrics if data.total_chips and data.expected_chips: chip_health = (data.total_chips / data.expected_chips) * 100 if chip_health < 95: print(f"WARNING: Chip health at {chip_health:.1f}%") print(f"Missing {data.expected_chips - data.total_chips} chips") if data.hashrate and data.expected_hashrate: hashrate_health = (float(data.hashrate) / float(data.expected_hashrate)) * 100 if hashrate_health < 95: print(f"WARNING: Hashrate at {hashrate_health:.1f}% of expected") # Check temperature warnings if data.temperature_avg and data.temperature_avg > 80: print(f"WARNING: High temperature detected: {data.temperature_avg}°C") # Check if mining if not data.is_mining: print("WARNING: Miner is not currently mining") return data except APIError as e: print(f"API Error: {e}") except Exception as e: print(f"Unexpected error: {e}") if __name__ == "__main__": asyncio.run(handle_miner_errors()) ``` -------------------------------- ### Update Default Antminer Web Password in Pyasic Settings Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Shows how to update default settings within the Pyasic library, specifically the default web password for Antminer. This is useful for managing multiple miners with consistent credentials. It relies on the `pyasic` library's `settings` module. ```python from pyasic import settings settings.update("default_antminer_web_password", "my_pwd") ``` -------------------------------- ### Perform Arithmetic Operations on MinerData Objects with pyasic Source: https://context7.com/upstreamdata/pyasic/llms.txt This snippet demonstrates how to aggregate and average MinerData objects using arithmetic operations. It fetches data from multiple miners, sums their data, calculates averages, and prints the results. Dependencies include the asyncio library and pyasic. ```python import asyncio from pyasic import get_miner, MinerData async def aggregate_miner_data(): # Get multiple miners miner1 = await get_miner("192.168.1.100") miner2 = await get_miner("192.168.1.101") miner3 = await get_miner("192.168.1.102") # Collect data data1 = await miner1.get_data() data2 = await miner2.get_data() data3 = await miner3.get_data() print("Individual miner data:") print(f"Miner 1: {data1.hashrate} TH/s, {data1.wattage} W") print(f"Miner 2: {data2.hashrate} TH/s, {data2.wattage} W") print(f"Miner 3: {data3.hashrate} TH/s, {data3.wattage} W") # Add miner data together total_data = data1 + data2 + data3 print(f"\nTotal (sum): {total_data.hashrate} TH/s, {total_data.wattage} W") # Calculate average using sum and division miner_list = [data1, data2, data3] average_data = sum(miner_list, start=MinerData("0.0.0.0")) / len(miner_list) print(f"\nAverage: {average_data.hashrate} TH/s, {average_data.wattage} W") print(f"Average temperature: {average_data.temperature_avg}°C") print(f"Average efficiency: {average_data.efficiency} J/TH") # Division for calculating fleet averages fleet_data = data1 + data2 + data3 per_miner_avg = fleet_data / 3 print(f"\nPer-miner average: {per_miner_avg.hashrate} TH/s") return average_data if __name__ == "__main__": asyncio.run(aggregate_miner_data()) ``` -------------------------------- ### Update Pyasic Setting Source: https://github.com/upstreamdata/pyasic/blob/master/docs/settings/settings.md Updates the value of a specific Pyasic global setting. ```APIDOC ## PUT /settings ### Description Updates the value of a specific Pyasic global setting. ### Method PUT ### Endpoint `/settings` ### Parameters #### Request Body - **key** (string) - Required - The name of the setting to update. - **value** (any) - Required - The new value for the setting. ### Request Example ```json { "key": "network_ping_timeout", "value": 5 } ``` ### Response #### Success Response (200) Indicates the setting was updated successfully. No response body is typically returned. #### Response Example ```json { "message": "Setting updated successfully." } ``` ``` -------------------------------- ### Retrieve Specific Miner by IP Address (Python) Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Fetches a specific ASIC miner identified by its IP address using the get_miner function. It can also retrieve multiple miners concurrently using asyncio.gather for improved performance. If the miner cannot be identified, it returns an UnknownMiner object. ```python import asyncio from pyasic import get_miner async def get_miners(): miner_1 = await get_miner("192.168.1.75") miner_2 = await get_miner("192.168.1.76") print(miner_1, miner_2) tasks = [get_miner("192.168.1.75"), get_miner("192.168.1.76")] miners = await asyncio.gather(*tasks) print(miners) if __name__ == "__main__": asyncio.run(get_miners()) ``` -------------------------------- ### Gather Data from Identified Miner (Python) Source: https://github.com/upstreamdata/pyasic/blob/master/docs/index.md Retrieves operational data from an identified ASIC miner using its get_data() method. The returned data is an instance of the MinerData dataclass, allowing access to metrics like hashrate via attribute access (e.g., MinerData().hashrate). ```python # Example of how to use get_data() after obtaining a miner object # Assume 'miner' is an instance of a Miner class obtained from get_miner() or network.scan() # import asyncio # from pyasic import get_miner # # async def gather_miner_data(miner_ip): # miner = await get_miner(miner_ip) # if miner: # miner_data = await miner.get_data() # print(f"Hashrate: {miner_data.hashrate}") # print(f"Power Usage: {miner_data.power_usage}") # # Access other attributes as needed # # if __name__ == "__main__": # asyncio.run(gather_miner_data("192.168.1.75")) ``` -------------------------------- ### CGMinerAvalon821 Class for Avalon 821 Miner Source: https://github.com/upstreamdata/pyasic/blob/master/docs/miners/avalonminer/A8X.md This Python class, CGMinerAvalon821, is designed to interact with the Avalon 821 ASIC miner. It allows for control over various parameters such as shutdowns, power modes, setpoints, and presets. No external dependencies are explicitly mentioned for this class itself, but it's part of the pyasic library. ```python from pyasic.miners.avalonminer.cgminer.A8X.A821 import CGMinerAvalon821 ``` -------------------------------- ### CGMinerAvalon841 Class for Avalon 841 Miner Source: https://github.com/upstreamdata/pyasic/blob/master/docs/miners/avalonminer/A8X.md The CGMinerAvalon841 Python class provides an interface for managing the Avalon 841 ASIC miner. It supports functionalities including shutdown commands, power mode adjustments, setpoint configurations, and preset selections. This class is part of the pyasic library and assumes underlying CGMiner compatibility. ```python from pyasic.miners.avalonminer.cgminer.A8X.A841 import CGMinerAvalon841 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.