Compare commits

..

36 Commits

Author SHA1 Message Date
UpstreamData
26ae6ebfb2 bump version number 2022-07-19 11:19:32 -06:00
UpstreamData
e65cb0573d update miner factory to handle some types of stock fw S9s 2022-07-19 11:18:55 -06:00
UpstreamData
f8590b0c5f improve more typing 2022-07-18 14:46:17 -06:00
UpstreamData
43b4992cee improve logging and some documentation 2022-07-18 14:38:54 -06:00
UpstreamData
98e2cfae84 bump version number 2022-07-18 12:05:44 -06:00
UpstreamData
cb01c1a8ee update network to scan fast even if some miners are not responding properly 2022-07-18 12:05:22 -06:00
UpstreamData
36a273ec2b bump version number 2022-07-18 11:45:14 -06:00
UpstreamData
6a0dc03b9d update to a better way to handle settings 2022-07-18 11:44:22 -06:00
UpstreamData
ce7b006c8f bump version number 2022-07-18 11:23:15 -06:00
UpstreamData
88cc05bcea handle for BraiinsOS miners that dont have bosminer running for some reason 2022-07-18 11:21:40 -06:00
UpstreamData
ae749f4a90 add additional scan ports as backups in case 4028 doesn't respond 2022-07-18 10:03:39 -06:00
UpstreamData
36b30a2cdd added supported miners to the docs 2022-07-14 16:32:43 -06:00
UpstreamData
ae9f103578 bump version number 2022-07-14 11:49:34 -06:00
UpstreamData
13b583b739 fixed some bugs and added support for M20Sv10 and 20 2022-07-14 11:39:55 -06:00
UpstreamData
aaf0d7fa75 bump version number 2022-07-14 09:47:36 -06:00
UpstreamData
a8cbb6394e fix a bug with ints being passed to miner network 2022-07-14 09:45:21 -06:00
UpstreamData
ca6980b1ad update documentation and add docs from config 2022-07-13 16:17:08 -06:00
UpstreamData
c6c87a864d fix pyproject.toml 2022-07-13 14:29:06 -06:00
UpstreamData
ed17a0f436 update documentation and bump version number 2022-07-13 14:25:12 -06:00
UpstreamData
36fead3dd1 Update README.md 2022-07-13 11:57:33 -06:00
UpstreamData
ecb16c10ca Update README.md 2022-07-13 11:56:28 -06:00
UpstreamData
a540db3246 update docs requirements 2022-07-13 11:28:12 -06:00
UpstreamData
81a2f99fbf add jinja 2 to docs requirements to fix mkdocs bug 2022-07-13 11:22:00 -06:00
UpstreamData
1dd9f742ad Revert "dealete readthedocs.yaml"
This reverts commit 7bd6a0f136.
2022-07-13 11:18:56 -06:00
UpstreamData
7bd6a0f136 dealete readthedocs.yaml 2022-07-13 11:17:53 -06:00
UpstreamData
7297f12e88 update readthedocs info 2022-07-13 11:15:34 -06:00
UpstreamData
0e009c3a16 add readthedocs info 2022-07-13 11:12:29 -06:00
UpstreamData
95b0cc364b add miner data documentation 2022-07-13 11:08:12 -06:00
UpstreamData
2dcc4f0cfc add docs for miner factory and miner network 2022-07-13 10:52:42 -06:00
UpstreamData
d7e9498018 add docs for the rest of the APIs 2022-07-13 10:11:05 -06:00
UpstreamData
0324a21e79 add bmminer docs 2022-07-13 09:13:21 -06:00
UpstreamData
5700bd1c9c start adding some basic documentation 2022-07-12 16:25:05 -06:00
UpstreamData
abc6494f18 bump version number 2022-07-12 11:58:59 -06:00
UpstreamData
5de8fc064e fix a bug with hashrate parsing on braiins os devices with kh hashrates 2022-07-12 11:58:21 -06:00
UpstreamData
c9d620105b add support for braiins OS errors 2022-07-12 11:55:42 -06:00
UpstreamData
5d6fc5b26d add support for whatsminer error codes in get_data() 2022-07-12 11:41:38 -06:00
72 changed files with 2620 additions and 952 deletions

20
.readthedocs.yaml Normal file
View File

@@ -0,0 +1,20 @@
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
# Required
version: 2
# Set the version of Python and other tools you might need
build:
os: ubuntu-20.04
tools:
python: "3.9"
mkdocs:
configuration: mkdocs.yml
# Optionally declare the Python requirements required to build your docs
python:
install:
- requirements: docs/requirements.txt

View File

@@ -2,8 +2,12 @@
*A set of modules for interfacing with many common types of ASIC bitcoin miners, using both their API and SSH.*
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Code style: black](https://img.shields.io/pypi/v/pyasic.svg)](https://pypi.org/project/pyasic/)
[![Code style: black](https://img.shields.io/pypi/pyversions/pyasic.svg)](https://pypi.org/project/pyasic/)
[![pypi](https://img.shields.io/pypi/v/pyasic.svg)](https://pypi.org/project/pyasic/)
[![python](https://img.shields.io/pypi/pyversions/pyasic.svg)](https://pypi.org/project/pyasic/)
[![Read the Docs](https://img.shields.io/readthedocs/pyasic)](https://pyasic.readthedocs.io/en/latest/)
## Documentation
Documentation is located on Read the Docs as [pyasic](https://pyasic.readthedocs.io/en/latest/)
## Usage
### Standard Usage

24
docs/API/api.md Normal file
View File

@@ -0,0 +1,24 @@
# pyasic
## Miner APIs
Each miner has a unique 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 `BaseMiner` should have an API linked to it as `Miner.api`.
All API implementations inherit from [`BaseMinerAPI`][pyasic.API.BaseMinerAPI], which implements the basic communications protocols.
BaseMinerAPI 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 -
#### [BMMiner API][pyasic.API.bmminer.BMMinerAPI]
#### [BOSMiner API][pyasic.API.bosminer.BOSMinerAPI]
#### [BTMiner API][pyasic.API.btminer.BTMinerAPI]
#### [CGMiner API][pyasic.API.cgminer.CGMinerAPI]
#### [Unknown API][pyasic.API.unknown.UnknownAPI]
<br>
## BaseMinerAPI
::: pyasic.API.BaseMinerAPI
handler: python
options:
heading_level: 4

7
docs/API/bmminer.md Normal file
View File

@@ -0,0 +1,7 @@
# pyasic
## BMMinerAPI
::: pyasic.API.bmminer.BMMinerAPI
handler: python
options:
show_root_heading: false
heading_level: 4

7
docs/API/bosminer.md Normal file
View File

@@ -0,0 +1,7 @@
# pyasic
## BOSMinerAPI
::: pyasic.API.bosminer.BOSMinerAPI
handler: python
options:
show_root_heading: false
heading_level: 4

7
docs/API/btminer.md Normal file
View File

@@ -0,0 +1,7 @@
# pyasic
## BTMinerAPI
::: pyasic.API.btminer.BTMinerAPI
handler: python
options:
show_root_heading: false
heading_level: 4

7
docs/API/cgminer.md Normal file
View File

@@ -0,0 +1,7 @@
# pyasic
## CGMinerAPI
::: pyasic.API.cgminer.CGMinerAPI
handler: python
options:
show_root_heading: false
heading_level: 4

7
docs/API/unknown.md Normal file
View File

@@ -0,0 +1,7 @@
# pyasic
## UnknownAPI
::: pyasic.API.unknown.UnknownAPI
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,24 @@
# pyasic
## Miner Config
::: pyasic.config.MinerConfig
handler: python
options:
show_root_heading: false
heading_level: 4
## Pool Groups
::: pyasic.config._PoolGroup
handler: python
options:
show_root_heading: false
heading_level: 4
## Pools
::: pyasic.config._Pool
handler: python
options:
show_root_heading: false
heading_level: 4

8
docs/data/miner_data.md Normal file
View File

@@ -0,0 +1,8 @@
# pyasic
## Miner Data
::: pyasic.data.MinerData
handler: python
options:
show_root_heading: false
heading_level: 4

101
docs/index.md Normal file
View File

@@ -0,0 +1,101 @@
# pyasic
*A set of modules for interfacing with many common types of ASIC bitcoin miners, using both their API and SSH.*
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![pypi](https://img.shields.io/pypi/v/pyasic.svg)](https://pypi.org/project/pyasic/)
[![python](https://img.shields.io/pypi/pyversions/pyasic.svg)](https://pypi.org/project/pyasic/)
[![Read the Docs](https://img.shields.io/readthedocs/pyasic)](https://pyasic.readthedocs.io/en/latest/)
## Intro
Welcome to pyasic! Pyasic uses an asynchronous method of communicating with asic miners on your network, which makes it super fast.
[Supported Miner Types](miners/supported_types.md)
Getting started with pyasic is easy. First, find your miner (or miners) on the network by scanning for them or getting the correct class automatically for them if you know the IP.
<br>
## Scanning for miners
To scan for miners in pyasic, we use the class [`MinerNetwork`][pyasic.network.MinerNetwork], which abstracts the search, communication, identification, setup, and return of a miner to 1 command.
The command [`MinerNetwork().scan_network_for_miners()`][pyasic.network.MinerNetwork.scan_network_for_miners] returns a list that contains any miners found.
```python
import asyncio # asyncio for handling the async part
from pyasic.network import MinerNetwork # miner network handles the scanning
async def scan_miners(): # define async scan function to allow awaiting
# create a miner network
# you can pass in any IP and it will use that in a subnet with a /24 mask (255 IPs).
network = MinerNetwork("192.168.1.50") # this uses the 192.168.1.0-255 network
# scan for miners asynchronously
# this will return the correct type of miners if they are supported with all functionality.
miners = await network.scan_network_for_miners()
print(miners)
if __name__ == "__main__":
asyncio.run(scan_miners()) # run the scan asynchronously with asyncio.run()
```
<br>
## Creating miners based on IP
If you already know the IP address of your miner or miners, you can use the [`MinerFactory`][pyasic.miners.miner_factory.MinerFactory] to communicate and identify the miners.
The function [`MinerFactory().get_miner()`][pyasic.miners.miner_factory.MinerFactory.get_miner] will return any miner it found at the IP address specified, or an `UnknownMiner` if it cannot identify the miner.
```python
import asyncio # asyncio for handling the async part
from pyasic.miners.miner_factory import MinerFactory # miner factory handles miners creation
async def get_miners(): # define async scan function to allow awaiting
# get the miner with miner factory
# miner factory is a singleton, and will always use the same object and cache
# this means you can always call it as MinerFactory().get_miner()
miner_1 = await MinerFactory().get_miner("192.168.1.75")
miner_2 = await MinerFactory().get_miner("192.168.1.76")
print(miner_1, miner_2)
if __name__ == "__main__":
asyncio.run(get_miners()) # get the miners asynchronously with asyncio.run()
```
<br>
## Getting data from miners
Once you have your miner(s) identified, you will likely want to get data from the miner(s). You can do this using a built in function in each miner called `get_data()`.
This function will return a instance of the dataclass [`MinerData`][pyasic.data.MinerData] with all data it can gather from the miner.
Each piece of data in a [`MinerData`][pyasic.data.MinerData] instance can be referenced by getting it as an attribute, such as [`MinerData().hashrate`][pyasic.data.MinerData].
```python
import asyncio
from pyasic.miners.miner_factory import MinerFactory
async def gather_miner_data():
miner = await MinerFactory().get_miner("192.168.1.75")
miner_data = await miner.get_data()
print(miner_data) # all data from the dataclass
print(miner_data.hashrate) # hashrate of the miner in TH/s
if __name__ == "__main__":
asyncio.run(gather_miner_data())
```
You can do something similar with multiple miners, with only needing to make a small change to get all the data at once.
```python
import asyncio # asyncio for handling the async part
from pyasic.network import MinerNetwork # miner network handles the scanning
async def gather_miner_data(): # define async scan function to allow awaiting
network = MinerNetwork("192.168.1.50")
miners = await network.scan_network_for_miners()
# we need to asyncio.gather() all the miners get_data() functions to make them run together
all_miner_data = await asyncio.gather(*[miner.get_data() for miner in miners])
for miner_data in all_miner_data:
print(miner_data) # print out all the data one by one
if __name__ == "__main__":
asyncio.run(gather_miner_data())
```

View File

@@ -0,0 +1,59 @@
# pyasic
## X17 Models
## S17
::: pyasic.miners.antminer.bmminer.X17.S17.BMMinerS17
handler: python
options:
show_root_heading: false
heading_level: 4
## S17+
::: pyasic.miners.antminer.bmminer.X17.S17_Plus.BMMinerS17Plus
handler: python
options:
show_root_heading: false
heading_level: 4
## S17 Pro
::: pyasic.miners.antminer.bmminer.X17.S17_Pro.BMMinerS17Pro
handler: python
options:
show_root_heading: false
heading_level: 4
## S17e
::: pyasic.miners.antminer.bmminer.X17.S17e.BMMinerS17e
handler: python
options:
show_root_heading: false
heading_level: 4
## T17
::: pyasic.miners.antminer.bmminer.X17.T17.BMMinerT17
handler: python
options:
show_root_heading: false
heading_level: 4
## T17+
::: pyasic.miners.antminer.bmminer.X17.T17_Plus.BMMinerT17Plus
handler: python
options:
show_root_heading: false
heading_level: 4
## T17e
::: pyasic.miners.antminer.bmminer.X17.T17e.BMMinerT17e
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,52 @@
# pyasic
## X19 Models
## S19
::: pyasic.miners.antminer.bmminer.X19.S19.BMMinerS19
handler: python
options:
show_root_heading: false
heading_level: 4
## S19 Pro
::: pyasic.miners.antminer.bmminer.X19.S19_Pro.BMMinerS19Pro
handler: python
options:
show_root_heading: false
heading_level: 4
## S19a
::: pyasic.miners.antminer.bmminer.X19.S19a.BMMinerS19a
handler: python
options:
show_root_heading: false
heading_level: 4
## S19j
::: pyasic.miners.antminer.bmminer.X19.S19j.BMMinerS19j
handler: python
options:
show_root_heading: false
heading_level: 4
## S19j Pro
::: pyasic.miners.antminer.bmminer.X19.S19j_Pro.BMMinerS19jPro
handler: python
options:
show_root_heading: false
heading_level: 4
## T19
::: pyasic.miners.antminer.bmminer.X19.T19.BMMinerT19
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,26 @@
# pyasic
## X9 Models
## S9
::: pyasic.miners.antminer.bmminer.X9.S9.BMMinerS9
handler: python
options:
show_root_heading: false
heading_level: 4
## S9i
::: pyasic.miners.antminer.bmminer.X9.S9i.BMMinerS9i
handler: python
options:
show_root_heading: false
heading_level: 4
## T9
::: pyasic.miners.antminer.bmminer.X9.T9.BMMinerT9
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,26 @@
# pyasic
## A10X Models
## A1026
::: pyasic.miners.avalonminer.cgminer.A10X.A1026.CGMinerAvalon1026
handler: python
options:
show_root_heading: false
heading_level: 4
## A1047
::: pyasic.miners.avalonminer.cgminer.A10X.A1047.CGMinerAvalon1047
handler: python
options:
show_root_heading: false
heading_level: 4
## A1066
::: pyasic.miners.avalonminer.cgminer.A10X.A1066.CGMinerAvalon1066
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,26 @@
# pyasic
## A7X Models
## A721
::: pyasic.miners.avalonminer.cgminer.A7X.A721.CGMinerAvalon721
handler: python
options:
show_root_heading: false
heading_level: 4
## A741
::: pyasic.miners.avalonminer.cgminer.A7X.A741.CGMinerAvalon741
handler: python
options:
show_root_heading: false
heading_level: 4
## A761
::: pyasic.miners.avalonminer.cgminer.A7X.A761.CGMinerAvalon761
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,26 @@
# pyasic
## A8X Models
## A821
::: pyasic.miners.avalonminer.cgminer.A8X.A821.CGMinerAvalon821
handler: python
options:
show_root_heading: false
heading_level: 4
## A841
::: pyasic.miners.avalonminer.cgminer.A8X.A841.CGMinerAvalon841
handler: python
options:
show_root_heading: false
heading_level: 4
## A851
::: pyasic.miners.avalonminer.cgminer.A8X.A851.CGMinerAvalon851
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,10 @@
# pyasic
## A9X Models
## A921
::: pyasic.miners.avalonminer.cgminer.A9X.A921.CGMinerAvalon921
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## BMMiner Backend
::: pyasic.miners._backends.bmminer.BMMiner
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## BOSMiner Backend
::: pyasic.miners._backends.bosminer.BOSMiner
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## BTMiner Backend
::: pyasic.miners._backends.btminer.BTMiner
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## CGMiner Backend
::: pyasic.miners._backends.cgminer.CGMiner
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## Hiveon Backend
::: pyasic.miners._backends.hiveon.Hiveon
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## Miner Factory
::: pyasic.miners.miner_factory.MinerFactory
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,73 @@
# pyasic
## Supported Miners
Supported miner types are here on this list. If your miner (or miner version) is not on this list, please feel free to [open an issue on GitHub](https://github.com/UpstreamData/pyasic/issues) to get it added.
## Miner List
##### pyasic currently supports the following miners and subtypes:
* Braiins OS+ Devices:
* All devices supported by BraiinsOS+ are supported here.
* Stock Firmware Whatsminers:
* M3X Series:
* [M30S][pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30S]:
* [VE10][pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SVE10]
* [VG20][pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SVG20]
* [VE20][pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SVE20]
* [V50][pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SV50]
* [M30S+][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlus]:
* [VF20][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlusVF20]
* [VE40][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlusVE40]
* [VG60][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlusVG60]
* [M30S++][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus_Plus.BTMinerM30SPlusPlus]:
* [VG30][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus_Plus.BTMinerM30SPlusPlusVG30]
* [VG40][pyasic.miners.whatsminer.btminer.M3X.M30S_Plus_Plus.BTMinerM30SPlusPlusVG40]
* [M31S][pyasic.miners.whatsminer.btminer.M3X.M31S.BTMinerM31S]
* [M31S+][pyasic.miners.whatsminer.btminer.M3X.M31S_Plus.BTMinerM31SPlus]:
* [VE20][pyasic.miners.whatsminer.btminer.M3X.M31S_Plus.BTMinerM31SPlusVE20]
* [M32S][pyasic.miners.whatsminer.btminer.M3X.M32S.BTMinerM32S]
* M2X Series:
* [M20S][pyasic.miners.whatsminer.btminer.M2X.M20S.BTMinerM20S]:
* [V10][pyasic.miners.whatsminer.btminer.M2X.M20S.BTMinerM20SV10]
* [V20][pyasic.miners.whatsminer.btminer.M2X.M20S.BTMinerM20SV20]
* [M20S+][pyasic.miners.whatsminer.btminer.M2X.M20S_Plus.BTMinerM20SPlus]
* [M21][pyasic.miners.whatsminer.btminer.M2X.M21.BTMinerM21]
* [M21S][pyasic.miners.whatsminer.btminer.M2X.M21S.BTMinerM21S]:
* [V20][pyasic.miners.whatsminer.btminer.M2X.M21S.BTMinerM21SV20]
* [V60][pyasic.miners.whatsminer.btminer.M2X.M21S.BTMinerM21SV60]
* [M21S+][pyasic.miners.whatsminer.btminer.M2X.M21S_Plus.BTMinerM21SPlus]
* Stock Firmware Antminers:
* X19 Series:
* [S19][pyasic.miners.antminer.bmminer.X19.S19.BMMinerS19]
* [S19 Pro][pyasic.miners.antminer.bmminer.X19.S19_Pro.BMMinerS19Pro]
* [S19a][pyasic.miners.antminer.bmminer.X19.S19a.BMMinerS19a]
* [S19j][pyasic.miners.antminer.bmminer.X19.S19j.BMMinerS19j]
* [S19j Pro][pyasic.miners.antminer.bmminer.X19.S19j_Pro.BMMinerS19jPro]
* [T19][pyasic.miners.antminer.bmminer.X19.T19.BMMinerT19]
* X17 Series:
* [S17][pyasic.miners.antminer.bmminer.X17.S17.BMMinerS17]
* [S17+][pyasic.miners.antminer.bmminer.X17.S17_Plus.BMMinerS17Plus]
* [S17 Pro][pyasic.miners.antminer.bmminer.X17.S17_Pro.BMMinerS17Pro]
* [S17e][pyasic.miners.antminer.bmminer.X17.S17e.BMMinerS17e]
* [T17][pyasic.miners.antminer.bmminer.X17.T17.BMMinerT17]
* [T17+][pyasic.miners.antminer.bmminer.X17.T17_Plus.BMMinerT17Plus]
* [T17e][pyasic.miners.antminer.bmminer.X17.T17e.BMMinerT17e]
* X9 Series:
* [S9][pyasic.miners.antminer.bmminer.X9.S9.BMMinerS9]
* [S9i][pyasic.miners.antminer.bmminer.X9.S9i.BMMinerS9i]
* [T9][pyasic.miners.antminer.bmminer.X9.T9.BMMinerT9]
* Stock Firmware Avalonminers:
* A7X Series:
* [A721][pyasic.miners.avalonminer.cgminer.A7X.A721.CGMinerAvalon721]
* [A741][pyasic.miners.avalonminer.cgminer.A7X.A741.CGMinerAvalon741]
* [A761][pyasic.miners.avalonminer.cgminer.A7X.A761.CGMinerAvalon761]
* A8X Series:
* [A821][pyasic.miners.avalonminer.cgminer.A8X.A821.CGMinerAvalon821]
* [A841][pyasic.miners.avalonminer.cgminer.A8X.A841.CGMinerAvalon841]
* [A851][pyasic.miners.avalonminer.cgminer.A8X.A851.CGMinerAvalon851]
* A9X Series:
* [A921][pyasic.miners.avalonminer.cgminer.A9X.A921.CGMinerAvalon921]
* A10X Series:
* [A1026][pyasic.miners.avalonminer.cgminer.A10X.A1026.CGMinerAvalon1026]
* [A1047][pyasic.miners.avalonminer.cgminer.A10X.A1047.CGMinerAvalon1047]
* [A1066][pyasic.miners.avalonminer.cgminer.A10X.A1066.CGMinerAvalon1066]

View File

@@ -0,0 +1,75 @@
# pyasic
## M2X Models
## M20S
::: pyasic.miners.whatsminer.btminer.M2X.M20S.BTMinerM20S
handler: python
options:
show_root_heading: false
heading_level: 4
## M20SV10
::: pyasic.miners.whatsminer.btminer.M2X.M20S.BTMinerM20SV10
handler: python
options:
show_root_heading: false
heading_level: 4
## M20SV20
::: pyasic.miners.whatsminer.btminer.M2X.M20S.BTMinerM20SV20
handler: python
options:
show_root_heading: false
heading_level: 4
## M20S+
::: pyasic.miners.whatsminer.btminer.M2X.M20S_Plus.BTMinerM20SPlus
handler: python
options:
show_root_heading: false
heading_level: 4
## M21
::: pyasic.miners.whatsminer.btminer.M2X.M21.BTMinerM21
handler: python
options:
show_root_heading: false
heading_level: 4
## M21S
::: pyasic.miners.whatsminer.btminer.M2X.M21S.BTMinerM21S
handler: python
options:
show_root_heading: false
heading_level: 4
## M21SV20
::: pyasic.miners.whatsminer.btminer.M2X.M21S.BTMinerM21SV20
handler: python
options:
show_root_heading: false
heading_level: 4
## M21SV60
::: pyasic.miners.whatsminer.btminer.M2X.M21S.BTMinerM21SV60
handler: python
options:
show_root_heading: false
heading_level: 4
## M21S+
::: pyasic.miners.whatsminer.btminer.M2X.M21S_Plus.BTMinerM21SPlus
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,131 @@
# pyasic
## M3X Models
## M30S
::: pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30S
handler: python
options:
show_root_heading: false
heading_level: 4
## M30SVE10
::: pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SVE10
handler: python
options:
show_root_heading: false
heading_level: 4
## M30SVG20
::: pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SVG20
handler: python
options:
show_root_heading: false
heading_level: 4
## M30SVE20
::: pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SVE20
handler: python
options:
show_root_heading: false
heading_level: 4
## M30SV50
::: pyasic.miners.whatsminer.btminer.M3X.M30S.BTMinerM30SV50
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S+
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlus
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S+VF20
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlusVF20
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S+VE40
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlusVE40
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S+VG60
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus.BTMinerM30SPlusVG60
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S++
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus_Plus.BTMinerM30SPlusPlus
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S++VG30
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus_Plus.BTMinerM30SPlusPlusVG30
handler: python
options:
show_root_heading: false
heading_level: 4
## M30S+VG40
::: pyasic.miners.whatsminer.btminer.M3X.M30S_Plus_Plus.BTMinerM30SPlusPlusVG40
handler: python
options:
show_root_heading: false
heading_level: 4
## M31S
::: pyasic.miners.whatsminer.btminer.M3X.M31S.BTMinerM31S
handler: python
options:
show_root_heading: false
heading_level: 4
## M31S+
::: pyasic.miners.whatsminer.btminer.M3X.M31S_Plus.BTMinerM31SPlus
handler: python
options:
show_root_heading: false
heading_level: 4
## M31S+VE20
::: pyasic.miners.whatsminer.btminer.M3X.M31S_Plus.BTMinerM31SPlusVE20
handler: python
options:
show_root_heading: false
heading_level: 4
## M32S
::: pyasic.miners.whatsminer.btminer.M3X.M32S.BTMinerM32S
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,8 @@
# pyasic
## Miner Network
::: pyasic.network.MinerNetwork
handler: python
options:
show_root_heading: false
heading_level: 4

View File

@@ -0,0 +1,12 @@
# pyasic
## Miner Network Range
`MinerNetworkRange` is a class used by [`MinerNetwork`][pyasic.network.MinerNetwork] to handle any constructor stings.
The goal is to emulate what is produced by `ipaddress.ip_network` by allowing [`MinerNetwork`][pyasic.network.MinerNetwork] to get a list of hosts.
This allows this class to be the [`MinerNetwork.network`][pyasic.network.MinerNetwork] and hence be used for scanning.
::: pyasic.network.net_range.MinerNetworkRange
handler: python
options:
show_root_heading: false
heading_level: 4

3
docs/requirements.txt Normal file
View File

@@ -0,0 +1,3 @@
jinja2<3.1.0
mkdocs
mkdocstrings[python]

44
mkdocs.yml Normal file
View File

@@ -0,0 +1,44 @@
site_name: pyasic
repo_url: https://github.com/UpstreamData/pyasic
nav:
- Introduction: "index.md"
- Miners:
- Supported Miners: "miners/supported_types.md"
- Miner Factory: "miners/miner_factory.md"
- Backends:
- BMMiner: "miners/backends/bmminer.md"
- BOSMiner: "miners/backends/bosminer.md"
- BTMiner: "miners/backends/btminer.md"
- CGMiner: "miners/backends/cgminer.md"
- Hiveon: "miners/backends/hiveon.md"
- Classes:
- Antminer X9: "miners/antminer/X9.md"
- Antminer X17: "miners/antminer/X17.md"
- Antminer X19: "miners/antminer/X19.md"
- Avalon 7X: "miners/avalonminer/A7X.md"
- Avalon 8X: "miners/avalonminer/A8X.md"
- Avalon 9X: "miners/avalonminer/A9X.md"
- Avalon 10X: "miners/avalonminer/A10X.md"
- Whatsminer M2X: "miners/whatsminer/M2X.md"
- Whatsminer M3X: "miners/whatsminer/M3X.md"
- Network:
- Miner Network: "network/miner_network.md"
- Miner Network Range: "network/miner_network_range.md"
- Data:
- Miner Data: "data/miner_data.md"
- Config:
- Miner Config: "config/miner_config.md"
- Advanced:
- Miner APIs:
- Base: "API/api.md"
- BMMiner: "API/bmminer.md"
- BOSMiner: "API/bosminer.md"
- BTMiner: "API/btminer.md"
- CGMiner: "API/cgminer.md"
- Unknown: "API/unknown.md"
plugins:
- mkdocstrings
- search

View File

@@ -3,6 +3,7 @@ import json
import ipaddress
import warnings
import logging
from typing import Union
class APIError(Exception):
@@ -41,7 +42,11 @@ class BaseMinerAPI:
self.ip = ipaddress.ip_address(ip)
def get_commands(self) -> list:
"""Get a list of command accessible to a specific type of API on the miner."""
"""Get a list of command accessible to a specific type of API on the miner.
Returns:
A list of all API commands that the miner supports.
"""
return [
func
for func in
@@ -59,51 +64,75 @@ class BaseMinerAPI:
]
]
def _check_commands(self, *commands):
allowed_commands = self.get_commands()
return_commands = []
for command in [*commands]:
if command in allowed_commands:
return_commands.append(command)
else:
warnings.warn(
f"""Removing incorrect command: {command}
If you are sure you want to use this command please use API.send_command("{command}", ignore_errors=True) instead.""",
APIWarning,
)
return return_commands
async def multicommand(
self, *commands: str, ignore_x19_error: bool = False
) -> dict:
"""Creates and sends multiple commands as one command to the miner."""
"""Creates and sends multiple commands as one command to the miner.
Parameters:
*commands: The commands to send as a multicommand to the miner.
ignore_x19_error: Whether or not to ignore errors raised by x19 miners when using the "+" delimited style.
"""
logging.debug(f"{self.ip}: Sending multicommand: {[*commands]}")
# split the commands into a proper list
user_commands = [*commands]
allowed_commands = self.get_commands()
# make sure we can actually run the command, otherwise it will fail
commands = [command for command in user_commands if command in allowed_commands]
for item in list(set(user_commands) - set(commands)):
warnings.warn(
f"""Removing incorrect command: {item}
If you are sure you want to use this command please use API.send_command("{item}", ignore_errors=True) instead.""",
APIWarning,
)
# make sure we can actually run each command, otherwise they will fail
commands = self._check_commands(*commands)
# standard multicommand format is "command1+command2"
# doesnt work for S19 which is dealt with in the send command function
# doesnt work for S19 which uses the backup _x19_multicommand
command = "+".join(commands)
data = None
try:
data = await self.send_command(command, x19_command=ignore_x19_error)
except APIError:
try:
data = {}
# S19 handler, try again
for cmd in command.split("+"):
data[cmd] = []
data[cmd].append(await self.send_command(cmd))
except APIError as e:
raise APIError(e)
except Exception as e:
logging.warning(f"{self.ip}: API Multicommand Error: {e}")
if data:
logging.debug(f"{self.ip}: Received multicommand data.")
return data
logging.debug(f"{self.ip}: Handling X19 multicommand.")
data = await self._x19_multicommand(command.split("+"))
logging.debug(f"{self.ip}: Received multicommand data.")
return data
async def _x19_multicommand(self, *commands):
data = None
try:
data = {}
# send all commands individually
for cmd in commands:
data[cmd] = []
data[cmd].append(await self.send_command(cmd, x19_command=True))
except APIError as e:
raise APIError(e)
except Exception as e:
logging.warning(f"{self.ip}: API Multicommand Error: {e.__name__} - {e}")
return data
async def send_command(
self,
command: str or bytes,
parameters: str or int or bool = None,
command: Union[str, bytes],
parameters: Union[str, int, bool] = None,
ignore_errors: bool = False,
x19_command: bool = False,
) -> dict:
"""Send an API command to the miner and return the result."""
"""Send an API command to the miner and return the result.
Parameters:
command: The command to sent to the miner.
parameters: Any additional parameters to be sent with the command.
ignore_errors: Whether or not to raise APIError when the command returns an error.
x19_command: Whether this is a command for an x19 that may be an issue (such as a "+" delimited multicommand)
Returns:
The return data from the API command parsed from JSON into a dict.
"""
try:
# get reader and writer streams
reader, writer = await asyncio.open_connection(str(self.ip), self.port)
@@ -115,7 +144,7 @@ If you are sure you want to use this command please use API.send_command("{item}
# create the command
cmd = {"command": command}
if parameters is not None:
if parameters:
cmd["parameter"] = parameters
# send the command
@@ -133,9 +162,9 @@ If you are sure you want to use this command please use API.send_command("{item}
break
data += d
except Exception as e:
logging.warning(f"{self.ip}: API Command Error: {e}")
logging.warning(f"{self.ip}: API Command Error: {e.__name__} - {e}")
data = self.load_api_data(data)
data = self._load_api_data(data)
# close the connection
writer.close()
@@ -144,7 +173,7 @@ If you are sure you want to use this command please use API.send_command("{item}
# check for if the user wants to allow errors to return
if not ignore_errors:
# validate the command succeeded
validation = self.validate_command_output(data)
validation = self._validate_command_output(data)
if not validation[0]:
if not x19_command:
logging.warning(f"{self.ip}: API Command Error: {validation[1]}")
@@ -153,8 +182,7 @@ If you are sure you want to use this command please use API.send_command("{item}
return data
@staticmethod
def validate_command_output(data: dict) -> tuple:
"""Check if the returned command output is correctly formatted."""
def _validate_command_output(data: dict) -> tuple:
# check if the data returned is correct or an error
# if status isn't a key, it is a multicommand
if "STATUS" not in data.keys():
@@ -181,8 +209,7 @@ If you are sure you want to use this command please use API.send_command("{item}
return True, None
@staticmethod
def load_api_data(data: bytes) -> dict:
"""Convert API data from JSON to dict"""
def _load_api_data(data: bytes) -> dict:
str_data = None
try:
# some json from the API returns with a null byte (\x00) on the end

View File

@@ -6,17 +6,17 @@ class BMMinerAPI(BaseMinerAPI):
Each method corresponds to an API command in BMMiner.
BMMiner API documentation:
https://github.com/jameshilliard/bmminer/blob/master/API-README
[BMMiner API documentation](https://github.com/jameshilliard/bmminer/blob/master/API-README)
This class abstracts use of the BMMiner API, as well as the
methods for sending commands to it. The self.send_command()
methods for sending commands to it. The `self.send_command()`
function handles sending a command to the miner asynchronously, and
as such is the base for many of the functions in this class, which
rely on it to send the command for them.
:param ip: The IP of the miner to reference the API on.
:param port: The port to reference the API on. Default is 4028.
Parameters:
ip: The IP of the miner to reference the API on.
port: The port to reference the API on. Default is 4028.
"""
def __init__(self, ip: str, port: int = 4028) -> None:
@@ -24,58 +24,81 @@ class BMMinerAPI(BaseMinerAPI):
async def version(self) -> dict:
"""Get miner version info.
<details>
<summary>Expand</summary>
:return: Miner version information.
Returns:
Miner version information.
</details>
"""
return await self.send_command("version")
async def config(self) -> dict:
"""Get some basic configuration info.
<details>
<summary>Expand</summary>
:return: Some miner configuration information:
ASC Count <- the number of ASCs
PGA Count <- the number of PGAs
Pool Count <- the number of Pools
Strategy <- the current pool strategy
Log Interval <- the interval of logging
Device Code <- list of compiled device drivers
OS <- the current operating system
Failover-Only <- failover-only setting
Scan Time <- scan-time setting
Queue <- queue setting
Expiry <- expiry setting
Returns:
## Some miner configuration information:
* ASC Count <- the number of ASCs
* PGA Count <- the number of PGAs
* Pool Count <- the number of Pools
* Strategy <- the current pool strategy
* Log Interval <- the interval of logging
* Device Code <- list of compiled device drivers
* OS <- the current operating system
* Failover-Only <- failover-only setting
* Scan Time <- scan-time setting
* Queue <- queue setting
* Expiry <- expiry setting
</details>
"""
return await self.send_command("config")
async def summary(self) -> dict:
"""Get the status summary of the miner.
<details>
<summary>Expand</summary>
:return: The status summary of the miner.
Returns:
The status summary of the miner.
</details>
"""
return await self.send_command("summary")
async def pools(self) -> dict:
"""Get pool information.
<details>
<summary>Expand</summary>
:return: Miner pool information.
Returns:
Miner pool information.
</details>
"""
return await self.send_command("pools")
async def devs(self) -> dict:
"""Get data on each PGA/ASC with their details.
<details>
<summary>Expand</summary>
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
return await self.send_command("devs")
async def edevs(self, old: bool = False) -> dict:
"""Get data on each PGA/ASC with their details, ignoring
blacklisted and zombie devices.
"""Get data on each PGA/ASC with their details, ignoring blacklisted and zombie devices.
<details>
<summary>Expand</summary>
:param old: Include zombie devices that became zombies less
than 'old' seconds ago
Parameters:
old: Include zombie devices that became zombies less than 'old' seconds ago
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
if old:
return await self.send_command("edevs", parameters=old)
@@ -84,46 +107,70 @@ class BMMinerAPI(BaseMinerAPI):
async def pga(self, n: int) -> dict:
"""Get data from PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA number to get data from.
Parameters:
n: The PGA number to get data from.
:return: Data on the PGA n.
Returns:
Data on the PGA n.
</details>
"""
return await self.send_command("pga", parameters=n)
async def pgacount(self) -> dict:
"""Get data fon all PGAs.
<details>
<summary>Expand</summary>
:return: Data on the PGAs connected.
Returns:
Data on the PGAs connected.
</details>
"""
return await self.send_command("pgacount")
async def switchpool(self, n: int) -> dict:
"""Switch pools to pool n.
<details>
<summary>Expand</summary>
:param n: The pool to switch to.
Parameters:
n: The pool to switch to.
:return: A confirmation of switching to pool n.
Returns:
A confirmation of switching to pool n.
</details>
"""
return await self.send_command("switchpool", parameters=n)
async def enablepool(self, n: int) -> dict:
"""Enable pool n.
<details>
<summary>Expand</summary>
:param n: The pool to enable.
Parameters:
n: The pool to enable.
:return: A confirmation of enabling pool n.
Returns:
A confirmation of enabling pool n.
</details>
"""
return await self.send_command("enablepool", parameters=n)
async def addpool(self, url: str, username: str, password: str) -> dict:
"""Add a pool to the miner.
<details>
<summary>Expand</summary>
:param url: The URL of the new pool to add.
:param username: The users username on the new pool.
:param password: The worker password on the new pool.
Parameters:
url: The URL of the new pool to add.
username: The users username on the new pool.
password: The worker password on the new pool.
:return: A confirmation of adding the pool.
Returns:
A confirmation of adding the pool.
</details>
"""
return await self.send_command(
"addpool", parameters=f"{url},{username},{password}"
@@ -131,48 +178,73 @@ class BMMinerAPI(BaseMinerAPI):
async def poolpriority(self, *n: int) -> dict:
"""Set pool priority.
<details>
<summary>Expand</summary>
:param n: Pools in order of priority.
Parameters:
*n: Pools in order of priority.
:return: A confirmation of setting pool priority.
Returns:
A confirmation of setting pool priority.
</details>
"""
pools = f"{','.join([str(item) for item in n])}"
return await self.send_command("poolpriority", parameters=pools)
async def poolquota(self, n: int, q: int) -> dict:
"""Set pool quota.
<details>
<summary>Expand</summary>
:param n: Pool number to set quota on.
:param q: Quota to set the pool to.
Parameters:
n: Pool number to set quota on.
q: Quota to set the pool to.
:return: A confirmation of setting pool quota.
Returns:
A confirmation of setting pool quota.
</details>
"""
return await self.send_command("poolquota", parameters=f"{n},{q}")
async def disablepool(self, n: int) -> dict:
"""Disable a pool.
<details>
<summary>Expand</summary>
:param n: Pool to disable.
Parameters:
n: Pool to disable.
:return: A confirmation of diabling the pool.
Returns:
A confirmation of diabling the pool.
</details>
"""
return await self.send_command("disablepool", parameters=n)
async def removepool(self, n: int) -> dict:
"""Remove a pool.
<details>
<summary>Expand</summary>
:param n: Pool to remove.
Parameters:
n: Pool to remove.
:return: A confirmation of removing the pool.
Returns:
A confirmation of removing the pool.
</details>
"""
return await self.send_command("removepool", parameters=n)
async def save(self, filename: str = None) -> dict:
"""Save the config.
<details>
<summary>Expand</summary>
:param filename: Filename to save the config as.
Parameters:
filename: Filename to save the config as.
:return: A confirmation of saving the config.
Returns:
A confirmation of saving the config.
</details>
"""
if filename:
return await self.send_command("save", parameters=filename)
@@ -181,83 +253,123 @@ class BMMinerAPI(BaseMinerAPI):
async def quit(self) -> dict:
"""Quit BMMiner.
<details>
<summary>Expand</summary>
:return: A single "BYE" before BMMiner quits.
Returns:
A single "BYE" before BMMiner quits.
</details>
"""
return await self.send_command("quit")
async def notify(self) -> dict:
"""Notify the user of past errors.
<details>
<summary>Expand</summary>
:return: The last status and count of each devices problem(s).
Returns:
The last status and count of each devices problem(s).
</details>
"""
return await self.send_command("notify")
async def privileged(self) -> dict:
"""Check if you have privileged access.
<details>
<summary>Expand</summary>
:return: The STATUS section with an error if you have no
privileged access, or success if you have privileged access.
Returns:
The STATUS section with an error if you have no privileged access, or success if you have privileged access.
</details>
"""
return await self.send_command("privileged")
async def pgaenable(self, n: int) -> dict:
"""Enable PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA to enable.
Parameters:
n: The PGA to enable.
:return: A confirmation of enabling PGA n.
Returns:
A confirmation of enabling PGA n.
</details>
"""
return await self.send_command("pgaenable", parameters=n)
async def pgadisable(self, n: int) -> dict:
"""Disable PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA to disable.
Parameters:
n: The PGA to disable.
:return: A confirmation of disabling PGA n.
Returns:
A confirmation of disabling PGA n.
</details>
"""
return await self.send_command("pgadisable", parameters=n)
async def pgaidentify(self, n: int) -> dict:
"""Identify PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA to identify.
Parameters:
n: The PGA to identify.
:return: A confirmation of identifying PGA n.
Returns:
A confirmation of identifying PGA n.
</details>
"""
return await self.send_command("pgaidentify", parameters=n)
async def devdetails(self) -> dict:
"""Get data on all devices with their static details.
<details>
<summary>Expand</summary>
:return: Data on all devices with their static details.
Returns:
Data on all devices with their static details.
</details>
"""
return await self.send_command("devdetails")
async def restart(self) -> dict:
"""Restart BMMiner using the API.
<details>
<summary>Expand</summary>
:return: A reply informing of the restart.
Returns:
A reply informing of the restart.
</details>
"""
return await self.send_command("restart")
async def stats(self) -> dict:
"""Get stats of each device/pool with more than 1 getwork.
<details>
<summary>Expand</summary>
:return: Stats of each device/pool with more than 1 getwork.
Returns:
Stats of each device/pool with more than 1 getwork.
</details>
"""
return await self.send_command("stats")
async def estats(self, old: bool = False) -> dict:
"""Get stats of each device/pool with more than 1 getwork,
ignoring zombie devices.
"""Get stats of each device/pool with more than 1 getwork, ignoring zombie devices.
<details>
<summary>Expand</summary>
:param old: Include zombie devices that became zombies less
than 'old' seconds ago.
Parameters:
old: Include zombie devices that became zombies less than 'old' seconds ago.
:return: Stats of each device/pool with more than 1 getwork,
ignoring zombie devices.
Returns:
Stats of each device/pool with more than 1 getwork, ignoring zombie devices.
</details>
"""
if old:
return await self.send_command("estats", parameters=old)
@@ -266,92 +378,126 @@ class BMMinerAPI(BaseMinerAPI):
async def check(self, command: str) -> dict:
"""Check if the command command exists in BMMiner.
<details>
<summary>Expand</summary>
:param command: The command to check.
Parameters:
command: The command to check.
:return: Information about a command:
Exists (Y/N) <- the command exists in this version
Access (Y/N) <- you have access to use the command
Returns:
## Information about a command:
* Exists (Y/N) <- the command exists in this version
* Access (Y/N) <- you have access to use the command
</details>
"""
return await self.send_command("check", parameters=command)
async def failover_only(self, failover: bool) -> dict:
"""Set failover-only.
<details>
<summary>Expand</summary>
Parameters:
failover: What to set failover-only to.
:param failover: What to set failover-only to.
:return: Confirmation of setting failover-only.
Returns:
Confirmation of setting failover-only.
</details>
"""
return await self.send_command("failover-only", parameters=failover)
async def coin(self) -> dict:
"""Get information on the current coin.
<details>
<summary>Expand</summary>
:return: Information about the current coin being mined:
Hash Method <- the hashing algorithm
Current Block Time <- blocktime as a float, 0 means none
Current Block Hash <- the hash of the current block, blank
means none
LP <- whether LP is in use on at least 1 pool
Network Difficulty: the current network difficulty
Returns:
## Information about the current coin being mined:
* Hash Method <- the hashing algorithm
* Current Block Time <- blocktime as a float, 0 means none
* Current Block Hash <- the hash of the current block, blank means none
* LP <- whether LP is in use on at least 1 pool
* Network Difficulty: the current network difficulty
</details>
"""
return await self.send_command("coin")
async def debug(self, setting: str) -> dict:
"""Set a debug setting.
<details>
<summary>Expand</summary>
:param setting: Which setting to switch to. Options are:
Silent,
Quiet,
Verbose,
Debug,
RPCProto,
PerDevice,
WorkTime,
Normal.
Parameters:
setting: Which setting to switch to.
## Options are:
* Silent
* Quiet
* Verbose
* Debug
* RPCProto
* PerDevice
* WorkTime
* Normal
:return: Data on which debug setting was enabled or disabled.
Returns:
Data on which debug setting was enabled or disabled.
</details>
"""
return await self.send_command("debug", parameters=setting)
async def setconfig(self, name: str, n: int) -> dict:
"""Set config of name to value n.
<details>
<summary>Expand</summary>
:param name: The name of the config setting to set. Options are:
queue,
scantime,
expiry.
:param n: The value to set the 'name' setting to.
Parameters:
name: The name of the config setting to set.
## Options are:
* queue
* scantime
* expiry
n: The value to set the 'name' setting to.
:return: The results of setting config of name to n.
Returns:
The results of setting config of name to n.
</details>
"""
return await self.send_command("setconfig", parameters=f"{name},{n}")
async def usbstats(self) -> dict:
"""Get stats of all USB devices except ztex.
<details>
<summary>Expand</summary>
:return: The stats of all USB devices except ztex.
Returns:
The stats of all USB devices except ztex.
</details>
"""
return await self.send_command("usbstats")
async def pgaset(self, n: int, opt: str, val: int = None) -> dict:
"""Set PGA option opt to val on PGA n.
<details>
<summary>Expand</summary>
Options:
```
MMQ -
opt: clock
val: 160 - 230 (multiple of 2)
CMR -
opt: clock
val: 100 - 220
```
:param n: The PGA to set the options on.
:param opt: The option to set. Setting this to 'help'
returns a help message.
:param val: The value to set the option to.
Parameters:
n: The PGA to set the options on.
opt: The option to set. Setting this to 'help' returns a help message.
val: The value to set the option to.
:return: Confirmation of setting PGA n with opt[,val].
Returns:
Confirmation of setting PGA n with opt[,val].
</details>
"""
if val:
return await self.send_command("pgaset", parameters=f"{n},{opt},{val}")
@@ -360,75 +506,108 @@ class BMMinerAPI(BaseMinerAPI):
async def zero(self, which: str, summary: bool) -> dict:
"""Zero a device.
<details>
<summary>Expand</summary>
:param which: Which device to zero.
Setting this to 'all' zeros all devices.
Setting this to 'bestshare' zeros only the bestshare values
for each pool and global.
:param summary: Whether or not to show a full summary.
Parameters:
which: Which device to zero. Setting this to 'all' zeros all devices. Setting this to 'bestshare' zeros only the bestshare values for each pool and global.
summary: Whether or not to show a full summary.
:return: the STATUS section with info on the zero and optional
summary.
Returns:
the STATUS section with info on the zero and optional summary.
</details>
"""
return await self.send_command("zero", parameters=f"{which},{summary}")
async def hotplug(self, n: int) -> dict:
"""Enable hotplug.
<details>
<summary>Expand</summary>
:param n: The device number to set hotplug on.
Parameters:
n: The device number to set hotplug on.
:return: Information on hotplug status.
Returns:
Information on hotplug status.
</details>
"""
return await self.send_command("hotplug", parameters=n)
async def asc(self, n: int) -> dict:
"""Get data for ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to get data for.
Parameters:
n: The device to get data for.
:return: The data for ASC device n.
Returns:
The data for ASC device n.
</details>
"""
return await self.send_command("asc", parameters=n)
async def ascenable(self, n: int) -> dict:
"""Enable ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to enable.
Parameters:
n: The device to enable.
:return: Confirmation of enabling ASC device n.
Returns:
Confirmation of enabling ASC device n.
</details>
"""
return await self.send_command("ascenable", parameters=n)
async def ascdisable(self, n: int) -> dict:
"""Disable ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to disable.
Parameters:
n: The device to disable.
:return: Confirmation of disabling ASC device n.
Returns:
Confirmation of disabling ASC device n.
</details>
"""
return await self.send_command("ascdisable", parameters=n)
async def ascidentify(self, n: int) -> dict:
"""Identify ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to identify.
Parameters:
n: The device to identify.
:return: Confirmation of identifying ASC device n.
Returns:
Confirmation of identifying ASC device n.
</details>
"""
return await self.send_command("ascidentify", parameters=n)
async def asccount(self) -> dict:
"""Get data on the number of ASC devices and their info.
<details>
<summary>Expand</summary>
:return: Data on all ASC devices.
Returns:
Data on all ASC devices.
</details>
"""
return await self.send_command("asccount")
async def ascset(self, n: int, opt: str, val: int = None) -> dict:
"""Set ASC n option opt to value val.
<details>
<summary>Expand</summary>
Sets an option on the ASC n to a value. Allowed options are:
```
AVA+BTB -
opt: freq
val: 256 - 1024 (chip frequency)
@@ -462,14 +641,16 @@ class BMMinerAPI(BaseMinerAPI):
opt: clock
val: 0 - 15
```
Parameters:
n: The ASC to set the options on.
opt: The option to set. Setting this to 'help' returns a help message.
val: The value to set the option to.
:param n: The ASC to set the options on.
:param opt: The option to set. Setting this to 'help' returns a
help message.
:param val: The value to set the option to.
:return: Confirmation of setting option opt to value val.
Returns:
Confirmation of setting option opt to value val.
</details>
"""
if val:
return await self.send_command("ascset", parameters=f"{n},{opt},{val}")
@@ -478,14 +659,22 @@ class BMMinerAPI(BaseMinerAPI):
async def lcd(self) -> dict:
"""Get a general all-in-one status summary of the miner.
<details>
<summary>Expand</summary>
:return: An all-in-one status summary of the miner.
Returns:
An all-in-one status summary of the miner.
</details>
"""
return await self.send_command("lcd")
async def lockstats(self) -> dict:
"""Write lockstats to STDERR.
<details>
<summary>Expand</summary>
:return: The result of writing the lock stats to STDERR.
Returns:
The result of writing the lock stats to STDERR.
</details>
"""
return await self.send_command("lockstats")

View File

@@ -6,60 +6,80 @@ class BOSMinerAPI(BaseMinerAPI):
Each method corresponds to an API command in BOSMiner.
BOSMiner API documentation:
https://docs.braiins.com/os/plus-en/Development/1_api.html
[BOSMiner API documentation](https://docs.braiins.com/os/plus-en/Development/1_api.html)
This class abstracts use of the BOSMiner API, as well as the
methods for sending commands to it. The self.send_command()
methods for sending commands to it. The `self.send_command()`
function handles sending a command to the miner asynchronously, and
as such is the base for many of the functions in this class, which
rely on it to send the command for them.
:param ip: The IP of the miner to reference the API on.
:param port: The port to reference the API on. Default is 4028.
Parameters:
ip: The IP of the miner to reference the API on.
port: The port to reference the API on. Default is 4028.
"""
def __init__(self, ip, port=4028):
def __init__(self, ip: str, port: int = 4028):
super().__init__(ip, port)
async def asccount(self) -> dict:
"""Get data on the number of ASC devices and their info.
<details>
<summary>Expand</summary>
:return: Data on all ASC devices.
Returns:
Data on all ASC devices.
</details>
"""
return await self.send_command("asccount")
async def asc(self, n: int) -> dict:
"""Get data for ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to get data for.
Parameters:
n: The device to get data for.
:return: The data for ASC device n.
Returns:
The data for ASC device n.
</details>
"""
return await self.send_command("asc", parameters=n)
async def devdetails(self) -> dict:
"""Get data on all devices with their static details.
<details>
<summary>Expand</summary>
:return: Data on all devices with their static details.
Returns:
Data on all devices with their static details.
</details>
"""
return await self.send_command("devdetails")
async def devs(self) -> dict:
"""Get data on each PGA/ASC with their details.
<details>
<summary>Expand</summary>
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
return await self.send_command("devs")
async def edevs(self, old: bool = False) -> dict:
"""Get data on each PGA/ASC with their details, ignoring
blacklisted and zombie devices.
"""Get data on each PGA/ASC with their details, ignoring blacklisted and zombie devices.
<details>
<summary>Expand</summary>
:param old: Include zombie devices that became zombies less
than 'old' seconds ago
Parameters:
old: Include zombie devices that became zombies less than 'old' seconds ago
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
if old:
return await self.send_command("edevs", parameters="old")
@@ -69,40 +89,62 @@ class BOSMinerAPI(BaseMinerAPI):
async def pools(self) -> dict:
"""Get pool information.
:return: Miner pool information.
<details>
<summary>Expand</summary>
Returns:
Miner pool information.
</details>
"""
return await self.send_command("pools")
async def summary(self) -> dict:
"""Get the status summary of the miner.
:return: The status summary of the miner.
<details>
<summary>Expand</summary>
Returns:
The status summary of the miner.
</details>
"""
return await self.send_command("summary")
async def stats(self) -> dict:
"""Get stats of each device/pool with more than 1 getwork.
:return: Stats of each device/pool with more than 1 getwork.
<details>
<summary>Expand</summary>
Returns:
Stats of each device/pool with more than 1 getwork.
</details>
"""
return await self.send_command("stats")
async def version(self) -> dict:
"""Get miner version info.
:return: Miner version information.
<details>
<summary>Expand</summary>
Returns:
Miner version information.
</details>
"""
return await self.send_command("version")
async def estats(self, old: bool = False) -> dict:
"""Get stats of each device/pool with more than 1 getwork,
ignoring zombie devices.
"""Get stats of each device/pool with more than 1 getwork, ignoring zombie devices.
<details>
<summary>Expand</summary>
:param old: Include zombie devices that became zombies less
than 'old' seconds ago.
Parameters:
old: Include zombie devices that became zombies less than 'old' seconds ago.
:return: Stats of each device/pool with more than 1 getwork,
ignoring zombie devices.
Returns:
Stats of each device/pool with more than 1 getwork, ignoring zombie devices.
</details>
"""
if old:
return await self.send_command("estats", parameters=old)
@@ -111,98 +153,109 @@ class BOSMinerAPI(BaseMinerAPI):
async def check(self, command: str) -> dict:
"""Check if the command command exists in BOSMiner.
<details>
<summary>Expand</summary>
:param command: The command to check.
Parameters:
command: The command to check.
:return: Information about a command:
Exists (Y/N) <- the command exists in this version
Access (Y/N) <- you have access to use the command
Returns:
## Information about a command:
* Exists (Y/N) <- the command exists in this version
* Access (Y/N) <- you have access to use the command
</details>
"""
return await self.send_command("check", parameters=command)
async def coin(self) -> dict:
"""Get information on the current coin.
<details>
<summary>Expand</summary>
:return: Information about the current coin being mined:
Hash Method <- the hashing algorithm
Current Block Time <- blocktime as a float, 0 means none
Current Block Hash <- the hash of the current block, blank
means none
LP <- whether LP is in use on at least 1 pool
Network Difficulty: the current network difficulty
Returns:
## Information about the current coin being mined:
* Hash Method <- the hashing algorithm
* Current Block Time <- blocktime as a float, 0 means none
* Current Block Hash <- the hash of the current block, blank means none
* LP <- whether LP is in use on at least 1 pool
* Network Difficulty: the current network difficulty
</details>
"""
return await self.send_command("coin")
async def lcd(self) -> dict:
"""Get a general all-in-one status summary of the miner.
<details>
<summary>Expand</summary>
:return: An all-in-one status summary of the miner.
Returns:
An all-in-one status summary of the miner.
</details>
"""
return await self.send_command("lcd")
async def switchpool(self, n: int) -> dict:
# BOS has not implemented this yet, they will in the future
raise NotImplementedError
# return await self.send_command("switchpool", parameters=n)
async def enablepool(self, n: int) -> dict:
# BOS has not implemented this yet, they will in the future
raise NotImplementedError
# return await self.send_command("enablepool", parameters=n)
async def disablepool(self, n: int) -> dict:
# BOS has not implemented this yet, they will in the future
raise NotImplementedError
# return await self.send_command("disablepool", parameters=n)
async def addpool(self, url: str, username: str, password: str) -> dict:
# BOS has not implemented this yet, they will in the future
raise NotImplementedError
# return await self.send_command("addpool", parameters=f"{url},{username},{password}")
async def removepool(self, n: int) -> dict:
# BOS has not implemented this yet, they will in the future
raise NotImplementedError
# return await self.send_command("removepool", parameters=n)
async def fans(self) -> dict:
"""Get fan data.
<details>
<summary>Expand</summary>
:return: Data on the fans of the miner.
Returns:
Data on the fans of the miner.
</details>
"""
return await self.send_command("fans")
async def tempctrl(self) -> dict:
"""Get temperature control data.
<details>
<summary>Expand</summary>
:return: Data about the temp control settings of the miner.
Returns:
Data about the temp control settings of the miner.
</details>
"""
return await self.send_command("tempctrl")
async def temps(self) -> dict:
"""Get temperature data.
<details>
<summary>Expand</summary>
:return: Data on the temps of the miner.
Returns:
Data on the temps of the miner.
</details>
"""
return await self.send_command("temps")
async def tunerstatus(self) -> dict:
"""Get tuner status data
<details>
<summary>Expand</summary>
:return: Data on the status of autotuning.
Returns:
Data on the status of autotuning.
</details>
"""
return await self.send_command("tunerstatus")
async def pause(self) -> dict:
"""Pause mining.
<details>
<summary>Expand</summary>
:return: Confirmation of pausing mining.
Returns:
Confirmation of pausing mining.
</details>
"""
return await self.send_command("pause")
async def resume(self) -> dict:
"""Resume mining.
<details>
<summary>Expand</summary>
:return: Confirmation of resuming mining.
Returns:
Confirmation of resuming mining.
</details>
"""
return await self.send_command("resume")

View File

@@ -10,7 +10,7 @@ from passlib.handlers.md5_crypt import md5_crypt
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from pyasic.API import BaseMinerAPI, APIError
from pyasic.settings import WHATSMINER_PWD
from pyasic.settings import PyasicSettings
### IMPORTANT ###
@@ -29,9 +29,12 @@ def _crypt(word: str, salt: str) -> str:
'\s*\$(\d+)\$([\w\./]*)\$'. If this format is not used, a
ValueError is raised.
:param word: The word to be encrypted.
:param salt: The salt to encrypt the word.
:return: An MD5 hash of the word with the salt.
Parameters:
word: The word to be encrypted.
salt: The salt to encrypt the word.
Returns:
An MD5 hash of the word with the salt.
"""
# compile a standard format for the salt
standard_salt = re.compile("\s*\$(\d+)\$([\w\./]*)\$")
@@ -50,11 +53,11 @@ def _crypt(word: str, salt: str) -> str:
def _add_to_16(string: str) -> bytes:
"""Add null bytes to a string until the length is a multiple 16
:param string: The string to lengthen to a multiple of 16 and
encode.
Parameters:
string: The string to lengthen to a multiple of 16 and encode.
:return: The input string as bytes with a multiple of 16 as the
length.
Returns:
The input string as bytes with a multiple of 16 as the length.
"""
while len(string) % 16 != 0:
string += "\0"
@@ -67,10 +70,12 @@ def parse_btminer_priviledge_data(token_data: dict, data: dict):
Parses data from the BTMiner privileged API using the the token
from the API in an AES format.
:param token_data: The token information from self.get_token().
:param data: The data to parse, returned from the API.
Parameters:
token_data: The token information from self.get_token().
data: The data to parse, returned from the API.
:return: A decoded dict version of the privileged command output.
Returns:
A decoded dict version of the privileged command output.
"""
# get the encoded data from the dict
enc_data = data["enc"]
@@ -97,10 +102,12 @@ def create_privileged_cmd(token_data: dict, command: dict) -> bytes:
command as a dict of {'command': cmd}, with cmd being any command
that the miner API accepts.
:param token_data: The token information from self.get_token().
:param command: The command to turn into a privileged command.
Parameters:
token_data: The token information from self.get_token().
command: The command to turn into a privileged command.
:return: The encrypted privileged command to be sent to the miner.
Returns:
The encrypted privileged command to be sent to the miner.
"""
# add token to command
command["token"] = token_data["host_sign"]
@@ -132,7 +139,7 @@ class BTMinerAPI(BaseMinerAPI):
Each method corresponds to an API command in BMMiner.
This class abstracts use of the BTMiner API, as well as the
methods for sending commands to it. The self.send_command()
methods for sending commands to it. The `self.send_command()`
function handles sending a command to the miner asynchronously, and
as such is the base for many of the functions in this class, which
rely on it to send the command for them.
@@ -148,12 +155,18 @@ class BTMinerAPI(BaseMinerAPI):
this automatically for you and will decode the output to look like
a normal output from a miner API.
:param ip: The IP of the miner to reference the API on.
:param port: The port to reference the API on. Default is 4028.
:param pwd: The admin password of the miner. Default is admin.
Parameters:
ip: The IP of the miner to reference the API on.
port: The port to reference the API on. Default is 4028.
pwd: The admin password of the miner. Default is admin.
"""
def __init__(self, ip, port=4028, pwd: str = WHATSMINER_PWD):
def __init__(
self,
ip: str,
port: int = 4028,
pwd: str = PyasicSettings().global_whatsminer_password,
):
super().__init__(ip, port)
self.admin_pwd = pwd
self.current_token = None
@@ -165,19 +178,6 @@ class BTMinerAPI(BaseMinerAPI):
ignore_errors: bool = False,
**kwargs,
) -> dict:
"""Send a command to the miner API.
Send a command using an asynchronous connection, load the data,
parse encoded data if needed, and return the result.
:param command: The command to send to the miner.
:param parameters: Parameters to pass to the command.
:param ignore_errors: Ignore the E (Error) status code from the
API.
:return: The data received from the API after sending the
command.
"""
# check if command is a string
# if its bytes its encoded and needs to be sent raw
if isinstance(command, str):
@@ -209,7 +209,7 @@ class BTMinerAPI(BaseMinerAPI):
except Exception as e:
logging.info(f"{str(self.ip)}: {e}")
data = self.load_api_data(data)
data = self._load_api_data(data)
# close the connection
writer.close()
@@ -225,18 +225,21 @@ class BTMinerAPI(BaseMinerAPI):
if not ignore_errors:
# if it fails to validate, it is likely an error
validation = self.validate_command_output(data)
validation = self._validate_command_output(data)
if not validation[0]:
raise APIError(validation[1])
# return the parsed json as a dict
return data
async def get_token(self):
async def get_token(self) -> dict:
"""Gets token information from the API.
<details>
<summary>Expand</summary>
:return: An encoded token and md5 password, which are used
for the privileged API.
Returns:
An encoded token and md5 password, which are used for the privileged API.
</details>
"""
# get the token
data = await self.send_command("get_token")
@@ -278,22 +281,28 @@ class BTMinerAPI(BaseMinerAPI):
pool_3: str = None,
worker_3: str = None,
passwd_3: str = None,
):
) -> dict:
"""Update the pools of the miner using the API.
<details>
<summary>Expand</summary>
Update the pools of the miner using the API, only works after
changing the password of the miner using the Whatsminer tool.
:param pool_1: The URL to update pool 1 to.
:param worker_1: The worker name for pool 1 to update to.
:param passwd_1: The password for pool 1 to update to.
:param pool_2: The URL to update pool 2 to.
:param worker_2: The worker name for pool 2 to update to.
:param passwd_2: The password for pool 2 to update to.
:param pool_3: The URL to update pool 3 to.
:param worker_3: The worker name for pool 3 to update to.
:param passwd_3: The password for pool 3 to update to.
:return: A dict from the API to confirm the pools were updated.
Parameters:
pool_1: The URL to update pool 1 to.
worker_1: The worker name for pool 1 to update to.
passwd_1: The password for pool 1 to update to.
pool_2: The URL to update pool 2 to.
worker_2: The worker name for pool 2 to update to.
passwd_2: The password for pool 2 to update to.
pool_3: The URL to update pool 3 to.
worker_3: The worker name for pool 3 to update to.
passwd_3: The password for pool 3 to update to.
Returns:
A dict from the API to confirm the pools were updated.
</details>
"""
# get the token and password from the miner
token_data = await self.get_token()
@@ -336,27 +345,36 @@ class BTMinerAPI(BaseMinerAPI):
# send the command
return await self.send_command(enc_command)
async def restart(self):
async def restart(self) -> dict:
"""Restart BTMiner using the API.
<details>
<summary>Expand</summary>
Restart BTMiner using the API, only works after changing
the password of the miner using the Whatsminer tool.
:return: A reply informing of the restart.
Returns:
A reply informing of the restart.
</details>
"""
command = {"cmd": "restart_btminer"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def power_off(self, respbefore: bool = True):
async def power_off(self, respbefore: bool = True) -> dict:
"""Power off the miner using the API.
<details>
<summary>Expand</summary>
Power off the miner using the API, only works after changing
the password of the miner using the Whatsminer tool.
:param respbefore: Whether to respond before powering off.
:return: A reply informing of the status of powering off.
Parameters:
respbefore: Whether to respond before powering off.
Returns:
A reply informing of the status of powering off.
</details>
"""
if respbefore:
command = {"cmd": "power_off", "respbefore": "true"}
@@ -366,26 +384,36 @@ class BTMinerAPI(BaseMinerAPI):
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def power_on(self):
async def power_on(self) -> dict:
"""Power on the miner using the API.
<details>
<summary>Expand</summary>
Power on the miner using the API, only works after changing
the password of the miner using the Whatsminer tool.
:return: A reply informing of the status of powering on.
Returns:
A reply informing of the status of powering on.
</details>
"""
command = {"cmd": "power_on"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def reset_led(self):
async def reset_led(self) -> dict:
"""Reset the LED on the miner using the API.
<details>
<summary>Expand</summary>
Reset the LED on the miner using the API, only works after
changing the password of the miner using the Whatsminer tool.
:return: A reply informing of the status of resetting the LED.
Returns:
A reply informing of the status of resetting the LED.
</details>
"""
command = {"cmd": "set_led", "param": "auto"}
token_data = await self.get_token()
@@ -398,17 +426,23 @@ class BTMinerAPI(BaseMinerAPI):
period: int = 2000,
duration: int = 1000,
start: int = 0,
):
) -> dict:
"""Set the LED on the miner using the API.
<details>
<summary>Expand</summary>
Set the LED on the miner using the API, only works after
changing the password of the miner using the Whatsminer tool.
:param color: The LED color to set, either 'red' or 'green'.
:param period: The flash cycle in ms.
:param duration: LED on time in the cycle in ms.
:param start: LED on time offset in the cycle in ms.
:return: A reply informing of the status of setting the LED.
Parameters:
color: The LED color to set, either 'red' or 'green'.
period: The flash cycle in ms.
duration: LED on time in the cycle in ms.
start: LED on time offset in the cycle in ms.
Returns:
A reply informing of the status of setting the LED.
</details>
"""
command = {
"cmd": "set_led",
@@ -421,14 +455,18 @@ class BTMinerAPI(BaseMinerAPI):
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def set_low_power(self):
async def set_low_power(self) -> dict:
"""Set low power mode on the miner using the API.
<details>
<summary>Expand</summary>
Set low power mode on the miner using the API, only works after
changing the password of the miner using the Whatsminer tool.
:return: A reply informing of the status of setting low power
mode.
Returns:
A reply informing of the status of setting low power mode.
</details>
"""
command = {"cmd": "set_low_power"}
token_data = await self.get_token()
@@ -436,46 +474,62 @@ class BTMinerAPI(BaseMinerAPI):
return await self.send_command(enc_command)
async def update_firmware(self): # noqa - static
"""Not implemented."""
# to be determined if this will be added later
# requires a file stream in bytes
return NotImplementedError
async def reboot(self):
async def reboot(self) -> dict:
"""Reboot the miner using the API.
<details>
<summary>Expand</summary>
:return: A reply informing of the status of the reboot.
Returns:
A reply informing of the status of the reboot.
</details>
"""
command = {"cmd": "reboot"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def factory_reset(self):
async def factory_reset(self) -> dict:
"""Reset the miner to factory defaults.
<details>
<summary>Expand</summary>
:return: A reply informing of the status of the reset.
Returns:
A reply informing of the status of the reset.
</details>
"""
command = {"cmd": "factory_reset"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def update_pwd(self, old_pwd: str, new_pwd: str):
async def update_pwd(self, old_pwd: str, new_pwd: str) -> dict:
"""Update the admin user's password.
<details>
<summary>Expand</summary>
Update the admin user's password, only works after changing the
password of the miner using the Whatsminer tool. New password
has a max length of 8 bytes, using letters, numbers, and
underscores.
:param old_pwd: The old admin password.
:param new_pwd: The new password to set.
:return: A reply informing of the status of setting the
password.
Parameters:
old_pwd: The old admin password.
new_pwd: The new password to set.
Returns:
A reply informing of the status of setting the password.
"""
# check if password length is greater than 8 bytes
if len(new_pwd.encode("utf-8")) > 8:
return APIError(
raise APIError(
f"New password too long, the max length is 8. "
f"Password size: {len(new_pwd.encode('utf-8'))}"
)
@@ -484,19 +538,25 @@ class BTMinerAPI(BaseMinerAPI):
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def set_target_freq(self, percent: int):
async def set_target_freq(self, percent: int) -> dict:
"""Update the target frequency.
<details>
<summary>Expand</summary>
Update the target frequency, only works after changing the
password of the miner using the Whatsminer tool. The new
frequency must be between -10% and 100%.
:param percent: The frequency % to set.
:return: A reply informing of the status of setting the
frequency.
Parameters:
percent: The frequency % to set.
Returns:
A reply informing of the status of setting the frequency.
</details>
"""
if not -10 < percent < 100:
return APIError(
raise APIError(
f"Frequency % is outside of the allowed "
f"range. Please set a % between -10 and "
f"100"
@@ -506,88 +566,122 @@ class BTMinerAPI(BaseMinerAPI):
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def enable_fast_boot(self):
async def enable_fast_boot(self) -> dict:
"""Turn on fast boot.
<details>
<summary>Expand</summary>
Turn on fast boot, only works after changing the password of
the miner using the Whatsminer tool.
:return: A reply informing of the status of enabling fast boot.
Returns:
A reply informing of the status of enabling fast boot.
</details>
"""
command = {"cmd": "enable_btminer_fast_boot"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def disable_fast_boot(self):
async def disable_fast_boot(self) -> dict:
"""Turn off fast boot.
<details>
<summary>Expand</summary>
Turn off fast boot, only works after changing the password of
the miner using the Whatsminer tool.
:return: A reply informing of the status of disabling fast boot.
Returns:
A reply informing of the status of disabling fast boot.
</details>
"""
command = {"cmd": "disable_btminer_fast_boot"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def enable_web_pools(self):
async def enable_web_pools(self) -> dict:
"""Turn on web pool updates.
<details>
<summary>Expand</summary>
Turn on web pool updates, only works after changing the
password of the miner using the Whatsminer tool.
:return: A reply informing of the status of enabling web pools.
Returns:
A reply informing of the status of enabling web pools.
</details>
"""
command = {"cmd": "enable_web_pools"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def disable_web_pools(self):
async def disable_web_pools(self) -> dict:
"""Turn off web pool updates.
<details>
<summary>Expand</summary>
Turn off web pool updates, only works after changing the
password of the miner using the Whatsminer tool.
:return: A reply informing of the status of disabling web
pools.
Returns:
A reply informing of the status of disabling web pools.
</details>
"""
command = {"cmd": "disable_web_pools"}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def set_hostname(self, hostname: str):
async def set_hostname(self, hostname: str) -> dict:
"""Set the hostname of the miner.
<details>
<summary>Expand</summary>
Set the hostname of the miner, only works after changing the
password of the miner using the Whatsminer tool.
Parameters:
hostname: The new hostname to use.
Returns:
:param hostname: The new hostname to use.
:return: A reply informing of the status of setting the
hostname.
A reply informing of the status of setting the hostname.
</details>
"""
command = {"cmd": "set_hostname", "hostname": hostname}
token_data = await self.get_token()
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def set_power_pct(self, percent: int):
async def set_power_pct(self, percent: int) -> dict:
"""Set the power percentage of the miner.
<details>
<summary>Expand</summary>
Set the power percentage of the miner, only works after changing
the password of the miner using the Whatsminer tool.
:param percent: The power percentage to set.
:return: A reply informing of the status of setting the
power percentage.
Parameters:
percent: The power percentage to set.
Returns:
A reply informing of the status of setting the power percentage.
</details>
"""
if not 0 < percent < 100:
return APIError(
raise APIError(
f"Power PCT % is outside of the allowed "
f"range. Please set a % between 0 and "
f"100"
@@ -597,22 +691,29 @@ class BTMinerAPI(BaseMinerAPI):
enc_command = create_privileged_cmd(token_data, command)
return await self.send_command(enc_command)
async def pre_power_on(self, complete: bool, msg: str):
async def pre_power_on(self, complete: bool, msg: str) -> dict:
"""Configure or check status of pre power on.
<details>
<summary>Expand</summary>
Configure or check status of pre power on, only works after
changing the password of the miner using the Whatsminer tool.
:param complete: check whether pre power on is complete.
:param msg: the message to check.
"wait for adjust temp" or
"adjust complete" or
"adjust continue"
:return: A reply informing of the status of pre power on.
Parameters:
complete: check whether pre power on is complete.
msg: ## the message to check.
* `wait for adjust temp`
* `adjust complete`
* `adjust continue`
Returns:
A reply informing of the status of pre power on.
</details>
"""
if not msg == "wait for adjust temp" or "adjust complete" or "adjust continue":
return APIError(
raise APIError(
"Message is incorrect, please choose one of "
'["wait for adjust temp", '
'"adjust complete", '
@@ -629,77 +730,126 @@ class BTMinerAPI(BaseMinerAPI):
#### END privileged COMMANDS ####
async def summary(self):
async def summary(self) -> dict:
"""Get the summary status from the miner.
<details>
<summary>Expand</summary>
:return: Summary status of the miner.
Returns:
Summary status of the miner.
</details>
"""
return await self.send_command("summary")
async def pools(self):
async def pools(self) -> dict:
"""Get the pool status from the miner.
<details>
<summary>Expand</summary>
:return: Pool status of the miner.
Returns:
Pool status of the miner.
</details>
"""
return await self.send_command("pools")
async def devs(self):
async def devs(self) -> dict:
"""Get data on each PGA/ASC with their details.
<details>
<summary>Expand</summary>
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
return await self.send_command("devs")
async def edevs(self):
"""Get data on each PGA/ASC with their details, ignoring
blacklisted and zombie devices.
async def edevs(self) -> dict:
"""Get data on each PGA/ASC with their details, ignoring blacklisted and zombie devices.
<details>
<summary>Expand</summary>
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
return await self.send_command("edevs")
async def devdetails(self):
async def devdetails(self) -> dict:
"""Get data on all devices with their static details.
<details>
<summary>Expand</summary>
:return: Data on all devices with their static details.
Returns:
Data on all devices with their static details.
</details>
"""
return await self.send_command("devdetails")
async def get_psu(self):
async def get_psu(self) -> dict:
"""Get data on the PSU and power information.
<details>
<summary>Expand</summary>
:return: Data on the PSU and power information.
Returns:
Data on the PSU and power information.
</details>
"""
return await self.send_command("get_psu")
async def version(self):
"""Get version data for the miner.
async def version(self) -> dict:
"""Get version data for the miner. Wraps `self.get_version()`.
<details>
<summary>Expand</summary>
Get version data for the miner. This calls another function,
self.get_version(), but is named version to stay consistent
with the other miner APIs.
:return: Version data for the miner.
Returns:
Version data for the miner.
</details>
"""
return await self.get_version()
async def get_version(self):
async def get_version(self) -> dict:
"""Get version data for the miner.
<details>
<summary>Expand</summary>
:return: Version data for the miner.
Returns:
Version data for the miner.
</details>
"""
return await self.send_command("get_version")
async def status(self):
async def status(self) -> dict:
"""Get BTMiner status and firmware version.
<details>
<summary>Expand</summary>
:return: BTMiner status and firmware version.
Returns:
BTMiner status and firmware version.
</details>
"""
return await self.send_command("status")
async def get_miner_info(self):
async def get_miner_info(self) -> dict:
"""Get general miner info.
<details>
<summary>Expand</summary>
:return: General miner info.
Returns:
General miner info.
</details>
"""
return await self.send_command("get_miner_info")

View File

@@ -6,8 +6,7 @@ class CGMinerAPI(BaseMinerAPI):
Each method corresponds to an API command in GGMiner.
CGMiner API documentation:
https://github.com/ckolivas/cgminer/blob/master/API-README
[CGMiner API documentation](https://github.com/ckolivas/cgminer/blob/master/API-README)
This class abstracts use of the CGMiner API, as well as the
methods for sending commands to it. The self.send_command()
@@ -15,111 +14,163 @@ class CGMinerAPI(BaseMinerAPI):
as such is the base for many of the functions in this class, which
rely on it to send the command for them.
:param ip: The IP of the miner to reference the API on.
:param port: The port to reference the API on. Default is 4028.
Parameters:
ip: The IP of the miner to reference the API on.
port: The port to reference the API on. Default is 4028.
"""
def __init__(self, ip, port=4028):
def __init__(self, ip: str, port: int = 4028):
super().__init__(ip, port)
async def version(self) -> dict:
"""Get miner version info.
<details>
<summary>Expand</summary>
:return: Miner version information.
Returns:
Miner version information.
</details>
"""
return await self.send_command("version")
async def config(self) -> dict:
"""Get some basic configuration info.
<details>
<summary>Expand</summary>
:return: Some miner configuration information:
ASC Count <- the number of ASCs
PGA Count <- the number of PGAs
Pool Count <- the number of Pools
Strategy <- the current pool strategy
Log Interval <- the interval of logging
Device Code <- list of compiled device drivers
OS <- the current operating system
Returns:
## Some miner configuration information:
* ASC Count <- the number of ASCs
* PGA Count <- the number of PGAs
* Pool Count <- the number of Pools
* Strategy <- the current pool strategy
* Log Interval <- the interval of logging
* Device Code <- list of compiled device drivers
* OS <- the current operating system
* Failover-Only <- failover-only setting
* Scan Time <- scan-time setting
* Queue <- queue setting
* Expiry <- expiry setting
</details>
"""
return await self.send_command("config")
async def summary(self) -> dict:
"""Get the status summary of the miner.
<details>
<summary>Expand</summary>
:return: The status summary of the miner.
Returns:
The status summary of the miner.
</details>
"""
return await self.send_command("summary")
async def pools(self) -> dict:
"""Get pool information.
<details>
<summary>Expand</summary>
:return: Miner pool information.
Returns:
Miner pool information.
</details>
"""
return await self.send_command("pools")
async def devs(self) -> dict:
"""Get data on each PGA/ASC with their details.
<details>
<summary>Expand</summary>
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
return await self.send_command("devs")
async def edevs(self, old: bool = False) -> dict:
"""Get data on each PGA/ASC with their details, ignoring
blacklisted and zombie devices.
"""Get data on each PGA/ASC with their details, ignoring blacklisted and zombie devices.
<details>
<summary>Expand</summary>
:param old: Include zombie devices that became zombies less
than 'old' seconds ago
Parameters:
old: Include zombie devices that became zombies less than 'old' seconds ago
:return: Data on each PGA/ASC with their details.
Returns:
Data on each PGA/ASC with their details.
</details>
"""
if old:
return await self.send_command("edevs", parameters="old")
return await self.send_command("edevs", parameters=old)
else:
return await self.send_command("edevs")
async def pga(self, n: int) -> dict:
"""Get data from PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA number to get data from.
Parameters:
n: The PGA number to get data from.
:return: Data on the PGA n.
Returns:
Data on the PGA n.
</details>
"""
return await self.send_command("pga", parameters=n)
async def pgacount(self) -> dict:
"""Get data fon all PGAs.
<details>
<summary>Expand</summary>
:return: Data on the PGAs connected.
Returns:
Data on the PGAs connected.
</details>
"""
return await self.send_command("pgacount")
async def switchpool(self, n: int) -> dict:
"""Switch pools to pool n.
<details>
<summary>Expand</summary>
:param n: The pool to switch to.
Parameters:
n: The pool to switch to.
:return: A confirmation of switching to pool n.
Returns:
A confirmation of switching to pool n.
</details>
"""
return await self.send_command("switchpool", parameters=n)
async def enablepool(self, n: int) -> dict:
"""Enable pool n.
<details>
<summary>Expand</summary>
:param n: The pool to enable.
Parameters:
n: The pool to enable.
:return: A confirmation of enabling pool n.
Returns:
A confirmation of enabling pool n.
</details>
"""
return await self.send_command("enablepool", parameters=n)
async def addpool(self, url: str, username: str, password: str) -> dict:
"""Add a pool to the miner.
<details>
<summary>Expand</summary>
:param url: The URL of the new pool to add.
:param username: The users username on the new pool.
:param password: The worker password on the new pool.
Parameters:
url: The URL of the new pool to add.
username: The users username on the new pool.
password: The worker password on the new pool.
:return: A confirmation of adding the pool.
Returns:
A confirmation of adding the pool.
</details>
"""
return await self.send_command(
"addpool", parameters=f"{url},{username},{password}"
@@ -127,48 +178,73 @@ class CGMinerAPI(BaseMinerAPI):
async def poolpriority(self, *n: int) -> dict:
"""Set pool priority.
<details>
<summary>Expand</summary>
:param n: Pools in order of priority.
Parameters:
*n: Pools in order of priority.
:return: A confirmation of setting pool priority.
Returns:
A confirmation of setting pool priority.
</details>
"""
pools = f"{','.join([str(item) for item in n])}"
return await self.send_command("poolpriority", parameters=pools)
async def poolquota(self, n: int, q: int) -> dict:
"""Set pool quota.
<details>
<summary>Expand</summary>
:param n: Pool number to set quota on.
:param q: Quota to set the pool to.
Parameters:
n: Pool number to set quota on.
q: Quota to set the pool to.
:return: A confirmation of setting pool quota.
Returns:
A confirmation of setting pool quota.
</details>
"""
return await self.send_command("poolquota", parameters=f"{n},{q}")
async def disablepool(self, n: int) -> dict:
"""Disable a pool.
<details>
<summary>Expand</summary>
:param n: Pool to disable.
Parameters:
n: Pool to disable.
:return: A confirmation of diabling the pool.
Returns:
A confirmation of diabling the pool.
</details>
"""
return await self.send_command("disablepool", parameters=n)
async def removepool(self, n: int) -> dict:
"""Remove a pool.
<details>
<summary>Expand</summary>
:param n: Pool to remove.
Parameters:
n: Pool to remove.
:return: A confirmation of removing the pool.
Returns:
A confirmation of removing the pool.
</details>
"""
return await self.send_command("removepool", parameters=n)
async def save(self, filename: str = None) -> dict:
"""Save the config.
<details>
<summary>Expand</summary>
:param filename: Filename to save the config as.
Parameters:
filename: Filename to save the config as.
:return: A confirmation of saving the config.
Returns:
A confirmation of saving the config.
</details>
"""
if filename:
return await self.send_command("save", parameters=filename)
@@ -177,83 +253,123 @@ class CGMinerAPI(BaseMinerAPI):
async def quit(self) -> dict:
"""Quit CGMiner.
<details>
<summary>Expand</summary>
:return: A single "BYE" before CGMiner quits.
Returns:
A single "BYE" before CGMiner quits.
</details>
"""
return await self.send_command("quit")
async def notify(self) -> dict:
"""Notify the user of past errors.
<details>
<summary>Expand</summary>
:return: The last status and count of each devices problem(s).
Returns:
The last status and count of each devices problem(s).
</details>
"""
return await self.send_command("notify")
async def privileged(self) -> dict:
"""Check if you have privileged access.
<details>
<summary>Expand</summary>
:return: The STATUS section with an error if you have no
privileged access, or success if you have privileged access.
Returns:
The STATUS section with an error if you have no privileged access, or success if you have privileged access.
</details>
"""
return await self.send_command("privileged")
async def pgaenable(self, n: int) -> dict:
"""Enable PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA to enable.
Parameters:
n: The PGA to enable.
:return: A confirmation of enabling PGA n.
Returns:
A confirmation of enabling PGA n.
</details>
"""
return await self.send_command("pgaenable", parameters=n)
async def pgadisable(self, n: int) -> dict:
"""Disable PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA to disable.
Parameters:
n: The PGA to disable.
:return: A confirmation of disabling PGA n.
Returns:
A confirmation of disabling PGA n.
</details>
"""
return await self.send_command("pgadisable", parameters=n)
async def pgaidentify(self, n: int) -> dict:
"""Identify PGA n.
<details>
<summary>Expand</summary>
:param n: The PGA to identify.
Parameters:
n: The PGA to identify.
:return: A confirmation of identifying PGA n.
Returns:
A confirmation of identifying PGA n.
</details>
"""
return await self.send_command("pgaidentify", parameters=n)
async def devdetails(self) -> dict:
"""Get data on all devices with their static details.
<details>
<summary>Expand</summary>
:return: Data on all devices with their static details.
Returns:
Data on all devices with their static details.
</details>
"""
return await self.send_command("devdetails")
async def restart(self) -> dict:
"""Restart CGMiner using the API.
<details>
<summary>Expand</summary>
:return: A reply informing of the restart.
Returns:
A reply informing of the restart.
</details>
"""
return await self.send_command("restart")
async def stats(self) -> dict:
"""Get stats of each device/pool with more than 1 getwork.
<details>
<summary>Expand</summary>
:return: Stats of each device/pool with more than 1 getwork.
Returns:
Stats of each device/pool with more than 1 getwork.
</details>
"""
return await self.send_command("stats")
async def estats(self, old: bool = False) -> dict:
"""Get stats of each device/pool with more than 1 getwork,
ignoring zombie devices.
"""Get stats of each device/pool with more than 1 getwork, ignoring zombie devices.
<details>
<summary>Expand</summary>
:param old: Include zombie devices that became zombies less
than 'old' seconds ago.
Parameters:
old: Include zombie devices that became zombies less than 'old' seconds ago.
:return: Stats of each device/pool with more than 1 getwork,
ignoring zombie devices.
Returns:
Stats of each device/pool with more than 1 getwork, ignoring zombie devices.
</details>
"""
if old:
return await self.send_command("estats", parameters=old)
@@ -262,92 +378,126 @@ class CGMinerAPI(BaseMinerAPI):
async def check(self, command: str) -> dict:
"""Check if the command command exists in CGMiner.
<details>
<summary>Expand</summary>
:param command: The command to check.
Parameters:
command: The command to check.
:return: Information about a command:
Exists (Y/N) <- the command exists in this version
Access (Y/N) <- you have access to use the command
Returns:
## Information about a command:
* Exists (Y/N) <- the command exists in this version
* Access (Y/N) <- you have access to use the command
</details>
"""
return await self.send_command("check", parameters=command)
async def failover_only(self, failover: bool) -> dict:
"""Set failover-only.
<details>
<summary>Expand</summary>
Parameters:
failover: What to set failover-only to.
:param failover: What to set failover-only to.
:return: Confirmation of setting failover-only.
Returns:
Confirmation of setting failover-only.
</details>
"""
return await self.send_command("failover-only", parameters=failover)
async def coin(self) -> dict:
"""Get information on the current coin.
<details>
<summary>Expand</summary>
:return: Information about the current coin being mined:
Hash Method <- the hashing algorithm
Current Block Time <- blocktime as a float, 0 means none
Current Block Hash <- the hash of the current block, blank
means none
LP <- whether LP is in use on at least 1 pool
Network Difficulty: the current network difficulty
Returns:
## Information about the current coin being mined:
* Hash Method <- the hashing algorithm
* Current Block Time <- blocktime as a float, 0 means none
* Current Block Hash <- the hash of the current block, blank means none
* LP <- whether LP is in use on at least 1 pool
* Network Difficulty: the current network difficulty
</details>
"""
return await self.send_command("coin")
async def debug(self, setting: str) -> dict:
"""Set a debug setting.
<details>
<summary>Expand</summary>
:param setting: Which setting to switch to. Options are:
Silent,
Quiet,
Verbose,
Debug,
RPCProto,
PerDevice,
WorkTime,
Normal.
Parameters:
setting: Which setting to switch to.
## Options are:
* Silent
* Quiet
* Verbose
* Debug
* RPCProto
* PerDevice
* WorkTime
* Normal
:return: Data on which debug setting was enabled or disabled.
Returns:
Data on which debug setting was enabled or disabled.
</details>
"""
return await self.send_command("debug", parameters=setting)
async def setconfig(self, name: str, n: int) -> dict:
"""Set config of name to value n.
<details>
<summary>Expand</summary>
:param name: The name of the config setting to set. Options are:
queue,
scantime,
expiry.
:param n: The value to set the 'name' setting to.
Parameters:
name: The name of the config setting to set.
## Options are:
* queue
* scantime
* expiry
n: The value to set the 'name' setting to.
:return: The results of setting config of name to n.
Returns:
The results of setting config of name to n.
</details>
"""
return await self.send_command("setconfig", parameters=f"{name},{n}")
async def usbstats(self) -> dict:
"""Get stats of all USB devices except ztex.
<details>
<summary>Expand</summary>
:return: The stats of all USB devices except ztex.
Returns:
The stats of all USB devices except ztex.
</details>
"""
return await self.send_command("usbstats")
async def pgaset(self, n: int, opt: str, val: int = None) -> dict:
"""Set PGA option opt to val on PGA n.
<details>
<summary>Expand</summary>
Options:
```
MMQ -
opt: clock
val: 160 - 230 (multiple of 2)
CMR -
opt: clock
val: 100 - 220
```
:param n: The PGA to set the options on.
:param opt: The option to set. Setting this to 'help'
returns a help message.
:param val: The value to set the option to.
Parameters:
n: The PGA to set the options on.
opt: The option to set. Setting this to 'help' returns a help message.
val: The value to set the option to.
:return: Confirmation of setting PGA n with opt[,val].
Returns:
Confirmation of setting PGA n with opt[,val].
</details>
"""
if val:
return await self.send_command("pgaset", parameters=f"{n},{opt},{val}")
@@ -356,75 +506,108 @@ class CGMinerAPI(BaseMinerAPI):
async def zero(self, which: str, summary: bool) -> dict:
"""Zero a device.
<details>
<summary>Expand</summary>
:param which: Which device to zero.
Setting this to 'all' zeros all devices.
Setting this to 'bestshare' zeros only the bestshare values
for each pool and global.
:param summary: Whether or not to show a full summary.
Parameters:
which: Which device to zero. Setting this to 'all' zeros all devices. Setting this to 'bestshare' zeros only the bestshare values for each pool and global.
summary: Whether or not to show a full summary.
:return: the STATUS section with info on the zero and optional
summary.
Returns:
the STATUS section with info on the zero and optional summary.
</details>
"""
return await self.send_command("zero", parameters=f"{which},{summary}")
async def hotplug(self, n: int) -> dict:
"""Enable hotplug.
<details>
<summary>Expand</summary>
:param n: The device number to set hotplug on.
Parameters:
n: The device number to set hotplug on.
:return: Information on hotplug status.
Returns:
Information on hotplug status.
</details>
"""
return await self.send_command("hotplug", parameters=n)
async def asc(self, n: int) -> dict:
"""Get data for ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to get data for.
Parameters:
n: The device to get data for.
:return: The data for ASC device n.
Returns:
The data for ASC device n.
</details>
"""
return await self.send_command("asc", parameters=n)
async def ascenable(self, n: int) -> dict:
"""Enable ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to enable.
Parameters:
n: The device to enable.
:return: Confirmation of enabling ASC device n.
Returns:
Confirmation of enabling ASC device n.
</details>
"""
return await self.send_command("ascenable", parameters=n)
async def ascdisable(self, n: int) -> dict:
"""Disable ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to disable.
Parameters:
n: The device to disable.
:return: Confirmation of disabling ASC device n.
Returns:
Confirmation of disabling ASC device n.
</details>
"""
return await self.send_command("ascdisable", parameters=n)
async def ascidentify(self, n: int) -> dict:
"""Identify ASC device n.
<details>
<summary>Expand</summary>
:param n: The device to identify.
Parameters:
n: The device to identify.
:return: Confirmation of identifying ASC device n.
Returns:
Confirmation of identifying ASC device n.
</details>
"""
return await self.send_command("ascidentify", parameters=n)
async def asccount(self) -> dict:
"""Get data on the number of ASC devices and their info.
<details>
<summary>Expand</summary>
:return: Data on all ASC devices.
Returns:
Data on all ASC devices.
</details>
"""
return await self.send_command("asccount")
async def ascset(self, n: int, opt: str, val: int = None) -> dict:
"""Set ASC n option opt to value val.
<details>
<summary>Expand</summary>
Sets an option on the ASC n to a value. Allowed options are:
```
AVA+BTB -
opt: freq
val: 256 - 1024 (chip frequency)
@@ -458,14 +641,16 @@ class CGMinerAPI(BaseMinerAPI):
opt: clock
val: 0 - 15
```
Parameters:
n: The ASC to set the options on.
opt: The option to set. Setting this to 'help' returns a help message.
val: The value to set the option to.
:param n: The ASC to set the options on.
:param opt: The option to set. Setting this to 'help' returns a
help message.
:param val: The value to set the option to.
:return: Confirmation of setting option opt to value val.
Returns:
Confirmation of setting option opt to value val.
</details>
"""
if val:
return await self.send_command("ascset", parameters=f"{n},{opt},{val}")
@@ -474,14 +659,22 @@ class CGMinerAPI(BaseMinerAPI):
async def lcd(self) -> dict:
"""Get a general all-in-one status summary of the miner.
<details>
<summary>Expand</summary>
:return: An all-in-one status summary of the miner.
Returns:
An all-in-one status summary of the miner.
</details>
"""
return await self.send_command("lcd")
async def lockstats(self) -> dict:
"""Write lockstats to STDERR.
<details>
<summary>Expand</summary>
:return: The result of writing the lock stats to STDERR.
Returns:
The result of writing the lock stats to STDERR.
</details>
"""
return await self.send_command("lockstats")

View File

@@ -1,5 +1,5 @@
from dataclasses import dataclass, asdict
from typing import List, Literal
from typing import Literal, List
import random
import string
@@ -13,9 +13,10 @@ import time
class _Pool:
"""A dataclass for pool information.
:param url: URL of the pool.
:param username: Username on the pool.
:param password: Worker password on the pool.
Attributes:
url: URL of the pool.
username: Username on the pool.
password: Worker password on the pool.
"""
url: str = ""
@@ -25,7 +26,8 @@ class _Pool:
def from_dict(self, data: dict):
"""Convert raw pool data as a dict to usable data and save it to this class.
:param data: The raw config data to convert.
Parameters:
data: The raw config data to convert.
"""
for key in data.keys():
if key == "url":
@@ -36,10 +38,11 @@ class _Pool:
self.password = data[key]
return self
def as_x19(self, user_suffix: str = None):
def as_x19(self, user_suffix: str = None) -> dict:
"""Convert the data in this class to a dict usable by an X19 device.
:param user_suffix: The suffix to append to username.
Parameters:
user_suffix: The suffix to append to username.
"""
username = self.username
if user_suffix:
@@ -48,7 +51,12 @@ class _Pool:
pool = {"url": self.url, "user": username, "pass": self.password}
return pool
def as_avalon(self, user_suffix: str = None):
def as_avalon(self, user_suffix: str = None) -> str:
"""Convert the data in this class to a string usable by an Avalonminer device.
Parameters:
user_suffix: The suffix to append to username.
"""
username = self.username
if user_suffix:
username = f"{username}{user_suffix}"
@@ -56,10 +64,11 @@ class _Pool:
pool = ",".join([self.url, username, self.password])
return pool
def as_bos(self, user_suffix: str = None):
def as_bos(self, user_suffix: str = None) -> dict:
"""Convert the data in this class to a dict usable by an BOSMiner device.
:param user_suffix: The suffix to append to username.
Parameters:
user_suffix: The suffix to append to username.
"""
username = self.username
if user_suffix:
@@ -73,9 +82,10 @@ class _Pool:
class _PoolGroup:
"""A dataclass for pool group information.
:param quota: The group quota.
:param group_name: The name of the pool group.
:param pools: A list of pools in this group.
Attributes:
quota: The group quota.
group_name: The name of the pool group.
pools: A list of pools in this group.
"""
quota: int = 1
@@ -91,7 +101,8 @@ class _PoolGroup:
def from_dict(self, data: dict):
"""Convert raw pool group data as a dict to usable data and save it to this class.
:param data: The raw config data to convert.
Parameters:
data: The raw config data to convert.
"""
pools = []
for key in data.keys():
@@ -105,24 +116,31 @@ class _PoolGroup:
self.pools = pools
return self
def as_x19(self, user_suffix: str = None):
"""Convert the data in this class to a dict usable by an X19 device.
def as_x19(self, user_suffix: str = None) -> List[dict]:
"""Convert the data in this class to a list usable by an X19 device.
:param user_suffix: The suffix to append to username.
Parameters:
user_suffix: The suffix to append to username.
"""
pools = []
for pool in self.pools[:3]:
pools.append(pool.as_x19(user_suffix=user_suffix))
return pools
def as_avalon(self, user_suffix: str = None):
def as_avalon(self, user_suffix: str = None) -> str:
"""Convert the data in this class to a dict usable by an Avalonminer device.
Parameters:
user_suffix: The suffix to append to username.
"""
pool = self.pools[0].as_avalon(user_suffix=user_suffix)
return pool
def as_bos(self, user_suffix: str = None):
def as_bos(self, user_suffix: str = None) -> dict:
"""Convert the data in this class to a dict usable by an BOSMiner device.
:param user_suffix: The suffix to append to username.
Parameters:
user_suffix: The suffix to append to username.
"""
group = {
"name": self.group_name,
@@ -136,21 +154,22 @@ class _PoolGroup:
class MinerConfig:
"""A dataclass for miner configuration information.
:param pool_groups: A list of pool groups in this config.
:param temp_mode: The temperature control mode.
:param temp_target: The target temp.
:param temp_hot: The hot temp (100% fans).
:param temp_dangerous: The dangerous temp (shutdown).
:param minimum_fans: The minimum numbers of fans to run the miner.
:param fan_speed: Manual fan speed to run the fan at (only if temp_mode == "manual").
:param asicboost: Whether or not to enable asicboost.
:param autotuning_enabled: Whether or not to enable autotuning.
:param autotuning_wattage: The wattage to use when autotuning.
:param dps_enabled: Whether or not to enable dynamic power scaling.
:param dps_power_step: The amount of power to reduce autotuning by when the miner reaches dangerous temp.
:param dps_min_power: The minimum power to reduce autotuning to.
:param dps_shutdown_enabled: Whether or not to shutdown the miner when `dps_min_power` is reached.
:param dps_shutdown_duration: The amount of time to shutdown for (in hours).
Attributes:
pool_groups: A list of pool groups in this config.
temp_mode: The temperature control mode.
temp_target: The target temp.
temp_hot: The hot temp (100% fans).
temp_dangerous: The dangerous temp (shutdown).
minimum_fans: The minimum numbers of fans to run the miner.
fan_speed: Manual fan speed to run the fan at (only if temp_mode == "manual").
asicboost: Whether or not to enable asicboost.
autotuning_enabled: Whether or not to enable autotuning.
autotuning_wattage: The wattage to use when autotuning.
dps_enabled: Whether or not to enable dynamic power scaling.
dps_power_step: The amount of power to reduce autotuning by when the miner reaches dangerous temp.
dps_min_power: The minimum power to reduce autotuning to.
dps_shutdown_enabled: Whether or not to shutdown the miner when `dps_min_power` is reached.
dps_shutdown_duration: The amount of time to shutdown for (in hours).
"""
pool_groups: List[_PoolGroup] = None
@@ -174,27 +193,28 @@ class MinerConfig:
dps_shutdown_enabled: bool = None
dps_shutdown_duration: float = None
def as_dict(self):
def as_dict(self) -> dict:
"""Convert the data in this class to a dict."""
data_dict = asdict(self)
for key in asdict(self).keys():
if data_dict[key] is None:
del data_dict[key]
return data_dict
def as_toml(self):
def as_toml(self) -> str:
"""Convert the data in this class to toml."""
return toml.dumps(self.as_dict())
def as_yaml(self):
def as_yaml(self) -> str:
"""Convert the data in this class to yaml."""
return yaml.dump(self.as_dict(), sort_keys=False)
def from_raw(self, data: dict):
"""Convert raw config data as a dict to usable data and save it to this class.
This should be able to handle any raw config file from any miner supported by pyasic.
:param data: The raw config data to convert.
Parameters:
data: The raw config data to convert.
"""
pool_groups = []
for key in data.keys():
@@ -256,7 +276,8 @@ class MinerConfig:
def from_dict(self, data: dict):
"""Convert an output dict of this class back into usable data and save it to this class.
:param data: The raw config data to convert.
Parameters:
data: The dict config data to convert.
"""
pool_groups = []
for group in data["pool_groups"]:
@@ -270,21 +291,24 @@ class MinerConfig:
def from_toml(self, data: str):
"""Convert output toml of this class back into usable data and save it to this class.
:param data: The raw config data to convert.
Parameters:
data: The toml config data to convert.
"""
return self.from_dict(toml.loads(data))
def from_yaml(self, data: str):
"""Convert output yaml of this class back into usable data and save it to this class.
:param data: The raw config data to convert.
Parameters:
data: The yaml config data to convert.
"""
return self.from_dict(yaml.load(data, Loader=yaml.SafeLoader))
def as_x19(self, user_suffix: str = None) -> str:
"""Convert the data in this class to a config usable by an X19 device.
:param user_suffix: The suffix to append to username.
Parameters:
user_suffix: The suffix to append to username.
"""
cfg = {
"pools": self.pool_groups[0].as_x19(user_suffix=user_suffix),
@@ -301,14 +325,20 @@ class MinerConfig:
return json.dumps(cfg)
def as_avalon(self, user_suffix: str = None) -> str:
cfg = self.pool_groups[0].as_avalon()
"""Convert the data in this class to a config usable by an Avalonminer device.
Parameters:
user_suffix: The suffix to append to username.
"""
cfg = self.pool_groups[0].as_avalon(user_suffix=user_suffix)
return cfg
def as_bos(self, model: str = "S9", user_suffix: str = None) -> str:
"""Convert the data in this class to a config usable by an BOSMiner device.
:param model: The model of the miner to be used in the format portion of the config.
:param user_suffix: The suffix to append to username.
Parameters:
model: The model of the miner to be used in the format portion of the config.
user_suffix: The suffix to append to username.
"""
cfg = {
"format": {

View File

@@ -4,34 +4,44 @@ from datetime import datetime
@dataclass
class MinerData:
"""A Dataclass to standardize data returned from miners (specifically AnyMiner().get_data())
"""A Dataclass to standardize data returned from miners (specifically `AnyMiner().get_data()`)
:param ip: The IP of the miner as a str.
:param datetime: The time and date this data was generated.
:param model: The model of the miner as a str.
:param hostname: The network hostname of the miner as a str.
:param hashrate: The hashrate of the miner in TH/s as a int.
:param left_board_temp: The temp of the left PCB as an int.
:param left_board_chip_temp: The temp of the left board chips as an int.
:param center_board_temp: The temp of the center PCB as an int.
:param center_board_chip_temp: The temp of the center board chips as an int.
:param right_board_temp: The temp of the right PCB as an int.
:param right_board_chip_temp: The temp of the right board chips as an int.
:param wattage: Current power draw of the miner as an int.
:param wattage_limit: Power limit of the miner as an int.
:param fan_1: The speed of the first fan as an int.
:param fan_2: The speed of the second fan as an int.
:param fan_3: The speed of the third fan as an int.
:param fan_4: The speed of the fourth fan as an int.
:param left_chips: The number of chips online in the left board as an int.
:param center_chips: The number of chips online in the left board as an int.
:param right_chips: The number of chips online in the left board as an int.
:param ideal_chips: The ideal number of chips in the miner as an int.
:param pool_split: The pool split as a str.
:param pool_1_url: The first pool url on the miner as a str.
:param pool_1_user: The first pool user on the miner as a str.
:param pool_2_url: The second pool url on the miner as a str.
:param pool_2_user: The second pool user on the miner as a str.
Attributes:
ip: The IP of the miner as a str.
datetime: The time and date this data was generated.
model: The model of the miner as a str.
hostname: The network hostname of the miner as a str.
hashrate: The hashrate of the miner in TH/s as a float.
left_board_hashrate: The hashrate of the left board of the miner in TH/s as a float.
center_board_hashrate: The hashrate of the center board of the miner in TH/s as a float.
right_board_hashrate: The hashrate of the right board of the miner in TH/s as a float.
temperature_avg: The average temperature across the boards. Calculated automatically.
env_temp: The environment temps as a float.
left_board_temp: The temp of the left PCB as an int.
left_board_chip_temp: The temp of the left board chips as an int.
center_board_temp: The temp of the center PCB as an int.
center_board_chip_temp: The temp of the center board chips as an int.
right_board_temp: The temp of the right PCB as an int.
right_board_chip_temp: The temp of the right board chips as an int.
wattage: Current power draw of the miner as an int.
wattage_limit: Power limit of the miner as an int.
fan_1: The speed of the first fan as an int.
fan_2: The speed of the second fan as an int.
fan_3: The speed of the third fan as an int.
fan_4: The speed of the fourth fan as an int.
left_chips: The number of chips online in the left board as an int.
center_chips: The number of chips online in the left board as an int.
right_chips: The number of chips online in the left board as an int.
total_chips: The total number of chips on all boards. Calculated automatically.
ideal_chips: The ideal number of chips in the miner as an int.
perecent_ideal: The percent of total chips out of the ideal count. Calculated automatically.
nominal: The nominal amount of chips in the miner. Calculated automatically.
pool_split: The pool split as a str.
pool_1_url: The first pool url on the miner as a str.
pool_1_user: The first pool user on the miner as a str.
pool_2_url: The second pool url on the miner as a str.
pool_2_user: The second pool user on the miner as a str.
errors: A list of errors on the miner.
"""
ip: str
@@ -69,6 +79,7 @@ class MinerData:
pool_1_user: str = "Unknown"
pool_2_url: str = ""
pool_2_user: str = ""
errors: list = field(default_factory=list)
def __post_init__(self):
self.datetime = datetime.now()

View File

@@ -0,0 +1,2 @@
from .whatsminer import WhatsminerError
from .bos import BraiinsOSError

View File

@@ -0,0 +1,11 @@
from dataclasses import dataclass, asdict
@dataclass
class BraiinsOSError:
"""A Dataclass to handle error codes of BraiinsOS+ miners."""
error_message: str
def asdict(self):
return asdict(self)

View File

@@ -0,0 +1,152 @@
from dataclasses import dataclass, field, asdict
@dataclass
class WhatsminerError:
"""A Dataclass to handle error codes of Whatsminers."""
error_code: int
error_message: str = field(init=False)
@property
def error_message(self): # noqa - Skip PyCharm inspection
if self.error_code in ERROR_CODES:
return ERROR_CODES[self.error_code]
return "Unknown error type."
@error_message.setter
def error_message(self, val):
pass
def asdict(self):
return asdict(self)
ERROR_CODES = {
110: "Intake fan speed error.",
111: "Exhaust fan speed error.",
120: "Intake fan speed error. Fan speed deviates by more than 2000.",
121: "Exhaust fan speed error. Fan speed deviates by more than 2000.",
130: "Intake fan speed error. Fan speed deviates by more than 3000.",
131: "Exhaust fan speed error. Fan speed deviates by more than 3000.",
140: "Fan speed too high.",
200: "Power probing error. No power found.",
201: "Power supply and configuration file don't match.",
202: "Power output voltage error.",
203: "Power protecting due to high environment temperature.",
204: "Power current protecting due to high environment temperature.",
205: "Power current error.",
206: "Power input low voltage error.",
207: "Power input current protecting due to bad power input.",
210: "Power error.",
213: "Power input voltage and current do not match power output.",
216: "Power remained unchanged for a long time.",
217: "Power set enable error.",
218: "Power input voltage is lower than 230V for high power mode.",
233: "Power output high temperature protection error.",
234: "Power output high temperature protection error.",
235: "Power output high temperature protection error.",
236: "Power output high current protection error.",
237: "Power output high current protection error.",
238: "Power output high current protection error.",
239: "Power output high voltage protection error.",
240: "Power output low voltage protection error.",
241: "Power output current imbalance error.",
243: "Power input high temperature protection error.",
244: "Power input high temperature protection error.",
245: "Power input high temperature protection error.",
246: "Power input high voltage protection error.",
247: "Power input high voltage protection error.",
248: "Power input high current protection error.",
249: "Power input high current protection error.",
250: "Power input low voltage protection error.",
251: "Power input low voltage protection error.",
253: "Power supply fan error.",
254: "Power supply fan error.",
255: "Power output high power protection error.",
256: "Power output high power protection error.",
257: "Input over current protection of power supply on primary side.",
263: "Power communication warning.",
264: "Power communication error.",
267: "Power watchdog protection.",
268: "Power output high current protection.",
269: "Power input high current protection.",
270: "Power input high voltage protection.",
271: "Power input low voltage protection.",
272: "Excessive power supply output warning.",
273: "Power input too high warning.",
274: "Power fan warning.",
275: "Power high temperature warning.",
300: "Right board temperature sensor detection error.",
301: "Center board temperature sensor detection error.",
302: "Left board temperature sensor detection error.",
320: "Right board temperature reading error.",
321: "Center board temperature reading error.",
322: "Left board temperature reading error.",
329: "Control board temperature sensor communication error.",
350: "Right board temperature protecting.",
351: "Center board temperature protecting.",
352: "Left board temperature protecting.",
360: "Hashboard high temperature error.",
410: "Right board eeprom detection error.",
411: "Center board eeprom detection error.",
412: "Left board eeprom detection error.",
420: "Right board eeprom parsing error.",
421: "Center board eeprom parsing error.",
422: "Left board eeprom parsing error.",
430: "Right board chip bin type error.",
431: "Center board chip bin type error.",
432: "Left board chip bin type error.",
440: "Right board eeprom chip number X error.",
441: "Center board eeprom chip number X error.",
442: "Left board eeprom chip number X error.",
450: "Right board eeprom xfer error.",
451: "Center board eeprom xfer error.",
452: "Left board eeprom xfer error.",
510: "Right board miner type error.",
511: "Center board miner type error.",
512: "Left board miner type error.",
520: "Right board bin type error.",
521: "Center board bin type error.",
522: "Left board bin type error.",
530: "Right board not found.",
531: "Center board not found.",
532: "Left board not found.",
540: "Right board error reading chip id.",
541: "Center board error reading chip id.",
542: "Left board error reading chip id.",
550: "Right board has bad chips.",
551: "Center board has bad chips.",
552: "Left board has bad chips.",
560: "Right board loss of balance error.",
561: "Center board loss of balance error.",
562: "Left board loss of balance error.",
600: "Environment temperature is too high.",
610: "Environment temperature is too high for high performance mode.",
701: "Control board no support chip.",
710: "Control board rebooted as an exception.",
712: "Control board rebooted as an exception.",
800: "CGMiner checksum error.",
801: "System monitor checksum error.",
802: "Remote daemon checksum error.",
2010: "All pools are disabled.",
2020: "Pool 0 connection failed.",
2021: "Pool 1 connection failed.",
2022: "Pool 2 connection failed.",
2030: "High rejection rate on pool.",
2040: "The pool does not support asicboost mode.",
2310: "Hashrate is too low.",
2320: "Hashrate is too low.",
2340: "Hashrate loss is too high.",
2350: "Hashrate loss is too high.",
5070: "Right hashboard water velocity is abnormal.",
5071: "Center hashboard water velocity is abnormal.",
5072: "Left hashboard water velocity is abnormal.",
5110: "Right hashboard frequency up timeout.",
5111: "Center hashboard frequency up timeout.",
5112: "Left hashboard frequency up timeout.",
8410: "Software version error.",
100001: "/antiv/signature illegal.",
100002: "/antiv/dig/init.d illegal.",
100003: "/antiv/dig/pf_partial.dig illegal.",
}

View File

@@ -1,9 +1,9 @@
import logging
from pyasic.settings import DEBUG, LOGFILE
from pyasic.settings import PyasicSettings
def init_logger():
if LOGFILE:
if PyasicSettings().logfile:
logging.basicConfig(
filename="logfile.txt",
filemode="a",
@@ -18,7 +18,7 @@ def init_logger():
_logger = logging.getLogger()
if DEBUG:
if PyasicSettings().debug:
_logger.setLevel(logging.DEBUG)
logging.getLogger("asyncssh").setLevel(logging.DEBUG)
else:

View File

@@ -54,13 +54,11 @@ class BaseMiner:
)
return conn
except Exception as e:
# logging.warning(f"{self} raised an exception: {e}")
raise e
except OSError as e:
logging.warning(f"Connection refused: {self}")
raise e
except Exception as e:
# logging.warning(f"{self} raised an exception: {e}")
raise e
async def fault_light_on(self) -> bool:

View File

@@ -1,5 +1,6 @@
import ipaddress
import logging
from typing import Union
from pyasic.API.bmminer import BMMinerAPI
@@ -7,10 +8,12 @@ from pyasic.miners import BaseMiner
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
class BMMiner(BaseMiner):
"""Base handler for BMMiner based miners."""
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ipaddress.ip_address(ip)
@@ -19,10 +22,11 @@ class BMMiner(BaseMiner):
self.uname = "root"
self.pwd = "admin"
async def get_model(self) -> str or None:
async def get_model(self) -> Union[str, None]:
"""Get miner model.
:return: Miner model or None.
Returns:
Miner model or None.
"""
# check if model is cached
if self.model:
@@ -46,7 +50,8 @@ class BMMiner(BaseMiner):
async def get_hostname(self) -> str:
"""Get miner hostname.
:return: The hostname of the miner as a string or "?"
Returns:
The hostname of the miner as a string or "?"
"""
if self.hostname:
return self.hostname
@@ -72,12 +77,14 @@ class BMMiner(BaseMiner):
logging.warning(f"Failed to get hostname for miner: {self}")
return "?"
async def send_ssh_command(self, cmd: str) -> str or None:
async def send_ssh_command(self, cmd: str) -> Union[str, None]:
"""Send a command to the miner over ssh.
:param cmd: The command to run.
Parameters:
cmd: The command to run.
:return: Result of the command or None.
Returns:
Result of the command or None.
"""
result = None
@@ -101,10 +108,11 @@ class BMMiner(BaseMiner):
# return the result, either command output or None
return result
async def get_config(self) -> list or None:
async def get_config(self) -> Union[list, None]:
"""Get the pool configuration of the miner.
:return: Pool config data or None.
Returns:
Pool config data or None.
"""
# get pool data
pools = await self.api.pools()
@@ -120,6 +128,11 @@ class BMMiner(BaseMiner):
return pool_data
async def reboot(self) -> bool:
"""Reboot the miner.
Returns:
The result of rebooting the miner.
"""
logging.debug(f"{self}: Sending reboot command.")
_ret = await self.send_ssh_command("reboot")
logging.debug(f"{self}: Reboot command completed.")
@@ -128,6 +141,11 @@ class BMMiner(BaseMiner):
return False
async def get_data(self) -> MinerData:
"""Get data from the miner.
Returns:
A [`MinerData`][pyasic.data.MinerData] instance containing the miners data.
"""
data = MinerData(ip=str(self.ip), ideal_chips=self.nominal_chips * 3)
board_offset = -1
@@ -147,7 +165,7 @@ class BMMiner(BaseMiner):
data.mac = mac
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"summary", "pools", "stats", ignore_x19_error=True
)

View File

@@ -1,6 +1,7 @@
import ipaddress
import logging
import json
from typing import Union
import toml
@@ -9,11 +10,12 @@ from pyasic.miners import BaseMiner
from pyasic.API.bosminer import BOSMinerAPI
from pyasic.API import APIError
from pyasic.data.error_codes import BraiinsOSError
from pyasic.data import MinerData
from pyasic.config import MinerConfig
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
class BOSMiner(BaseMiner):
@@ -26,10 +28,11 @@ class BOSMiner(BaseMiner):
self.pwd = "admin"
self.config = None
async def send_ssh_command(self, cmd: str) -> str or None:
async def send_ssh_command(self, cmd: str) -> Union[str, None]:
"""Send a command to the miner over ssh.
:return: Result of the command or None.
Returns:
Result of the command or None.
"""
result = None
@@ -73,6 +76,7 @@ class BOSMiner(BaseMiner):
return False
async def restart_backend(self) -> bool:
"""Restart bosminer hashing process. Wraps [`restart_bosminer`][pyasic.miners._backends.bosminer.BOSMiner.restart_bosminer] to standardize."""
return await self.restart_bosminer()
async def restart_bosminer(self) -> bool:
@@ -93,7 +97,12 @@ class BOSMiner(BaseMiner):
return True
return False
async def get_config(self) -> None:
async def get_config(self) -> MinerConfig:
"""Gets the config for the miner and sets it as `self.config`.
Returns:
The config from `self.config`.
"""
logging.debug(f"{self}: Getting config.")
async with (await self._get_ssh_connection()) as conn:
logging.debug(f"{self}: Opening SFTP connection.")
@@ -109,7 +118,8 @@ class BOSMiner(BaseMiner):
async def get_hostname(self) -> str:
"""Get miner hostname.
:return: The hostname of the miner as a string or "?"
Returns:
The hostname of the miner as a string or "?"
"""
if self.hostname:
return self.hostname
@@ -128,10 +138,11 @@ class BOSMiner(BaseMiner):
logging.warning(f"Failed to get hostname for miner: {self}")
return "?"
async def get_model(self) -> str or None:
async def get_model(self) -> Union[str, None]:
"""Get miner model.
:return: Miner model or None.
Returns:
Miner model or None.
"""
# check if model is cached
if self.model:
@@ -165,10 +176,11 @@ class BOSMiner(BaseMiner):
logging.warning(f"Failed to get model for miner: {self}")
return None
async def get_version(self):
async def get_version(self) -> Union[str, None]:
"""Get miner firmware version.
:return: Miner firmware version or None.
Returns:
Miner firmware version or None.
"""
# check if version is cached
if self.version:
@@ -205,65 +217,21 @@ class BOSMiner(BaseMiner):
.as_bos(model=self.model.replace(" (BOS)", ""))
)
async with (await self._get_ssh_connection()) as conn:
await conn.run("/etc/init.d/bosminer stop")
logging.debug(f"{self}: Opening SFTP connection.")
async with conn.start_sftp_client() as sftp:
logging.debug(f"{self}: Opening config file.")
async with sftp.open("/etc/bosminer.toml", "w+") as file:
await file.write(toml_conf)
logging.debug(f"{self}: Restarting BOSMiner")
await conn.run("/etc/init.d/bosminer restart")
async def get_board_info(self) -> dict:
"""Gets data on each board and chain in the miner."""
logging.debug(f"{self}: Getting board info.")
devdetails = await self.api.devdetails()
if not devdetails.get("DEVDETAILS"):
print("devdetails error", devdetails)
return {0: [], 1: [], 2: []}
devs = devdetails["DEVDETAILS"]
boards = {}
offset = devs[0]["ID"]
for board in devs:
boards[board["ID"] - offset] = []
if not board["Chips"] == self.nominal_chips:
nominal = False
else:
nominal = True
boards[board["ID"] - offset].append(
{
"chain": board["ID"] - offset,
"chip_count": board["Chips"],
"chip_status": "o" * board["Chips"],
"nominal": nominal,
}
)
logging.debug(f"Found board data for {self}: {boards}")
return boards
async def get_bad_boards(self) -> dict:
"""Checks for and provides list of non working boards."""
boards = await self.get_board_info()
bad_boards = {}
for board in boards.keys():
for chain in boards[board]:
if not chain["chip_count"] == 63:
if board not in bad_boards.keys():
bad_boards[board] = []
bad_boards[board].append(chain)
return bad_boards
async def check_good_boards(self) -> str:
"""Checks for and provides list for working boards."""
devs = await self.api.devdetails()
bad = 0
chains = devs["DEVDETAILS"]
for chain in chains:
if chain["Chips"] == 0:
bad += 1
if not bad > 0:
return str(self.ip)
await conn.run("/etc/init.d/bosminer start")
async def get_data(self) -> MinerData:
"""Get data from the miner.
Returns:
A [`MinerData`][pyasic.data.MinerData] instance containing the miners data.
"""
data = MinerData(ip=str(self.ip), ideal_chips=self.nominal_chips * 3)
board_offset = -1
@@ -283,7 +251,7 @@ class BOSMiner(BaseMiner):
data.mac = mac
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
try:
miner_data = await self.api.multicommand(
"summary",
@@ -395,6 +363,30 @@ class BOSMiner(BaseMiner):
if wattage:
data.wattage = wattage
chain_status = tuner[0].get("TunerChainStatus")
if chain_status and len(chain_status) > 0:
board_map = {
0: "Left board",
1: "Center board",
2: "Right board",
}
offset = (
6
if chain_status[0]["HashchainIndex"] in [6, 7, 8]
else chain_status[0]["HashchainIndex"]
)
for board in chain_status:
_id = board["HashchainIndex"] - offset
if board["Status"] not in [
"Stable",
"Testing performance profile",
]:
_error = board["Status"]
_error = _error[0].lower() + _error[1:]
data.errors.append(
BraiinsOSError(f"{board_map[_id]} {_error}")
)
if devdetails:
boards = devdetails[0].get("DEVDETAILS")
if boards:
@@ -418,7 +410,7 @@ class BOSMiner(BaseMiner):
offset = 6 if boards[0]["ID"] in [6, 7, 8] else boards[0]["ID"]
for board in boards:
_id = board["ID"] - offset
hashrate = board["MHS 1m"]
hashrate = round(board["MHS 1m"] / 1000000, 2)
setattr(data, board_map[_id], hashrate)
return data

View File

@@ -1,5 +1,6 @@
import ipaddress
import logging
from typing import Union
from pyasic.API.btminer import BTMinerAPI
@@ -7,8 +8,9 @@ from pyasic.miners import BaseMiner
from pyasic.API import APIError
from pyasic.data import MinerData
from pyasic.data.error_codes import WhatsminerError
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
class BTMiner(BaseMiner):
@@ -18,7 +20,12 @@ class BTMiner(BaseMiner):
self.api = BTMinerAPI(ip)
self.api_type = "BTMiner"
async def get_model(self):
async def get_model(self) -> Union[str, None]:
"""Get miner model.
Returns:
Miner model or None.
"""
if self.model:
logging.debug(f"Found model for {self.ip}: {self.model}")
return self.model
@@ -30,7 +37,12 @@ class BTMiner(BaseMiner):
logging.warning(f"Failed to get model for miner: {self}")
return None
async def get_hostname(self) -> str or None:
async def get_hostname(self) -> Union[str, None]:
"""Get miner hostname.
Returns:
The hostname of the miner as a string or None.
"""
if self.hostname:
return self.hostname
try:
@@ -47,38 +59,12 @@ class BTMiner(BaseMiner):
logging.warning(f"Failed to get hostname for miner: {self}")
return None
async def get_board_info(self) -> dict:
"""Gets data on each board and chain in the miner."""
logging.debug(f"{self}: Getting board info.")
devs = await self.api.devs()
if not devs.get("DEVS"):
print("devs error", devs)
return {0: [], 1: [], 2: []}
devs = devs["DEVS"]
boards = {}
offset = devs[0]["ID"]
for board in devs:
boards[board["ID"] - offset] = []
if "Effective Chips" in board.keys():
if not board["Effective Chips"] in self.nominal_chips:
nominal = False
else:
nominal = True
boards[board["ID"] - offset].append(
{
"chain": board["ID"] - offset,
"chip_count": board["Effective Chips"],
"chip_status": "o" * board["Effective Chips"],
"nominal": nominal,
}
)
else:
logging.warning(f"Incorrect board data from {self}: {board}")
print(board)
logging.debug(f"Found board data for {self}: {boards}")
return boards
async def get_mac(self) -> str:
"""Get the mac address of the miner.
async def get_mac(self):
Returns:
The mac address of the miner as a string.
"""
mac = ""
data = await self.api.summary()
if data:
@@ -99,7 +85,12 @@ class BTMiner(BaseMiner):
return str(mac).upper()
async def get_data(self):
async def get_data(self) -> MinerData:
"""Get data from the miner.
Returns:
A [`MinerData`][pyasic.data.MinerData] instance containing the miners data.
"""
data = MinerData(ip=str(self.ip), ideal_chips=self.nominal_chips * 3)
mac = None
@@ -125,7 +116,7 @@ class BTMiner(BaseMiner):
data.hostname = hostname
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
try:
miner_data = await self.api.multicommand("summary", "devs", "pools")
if miner_data:
@@ -170,6 +161,15 @@ class BTMiner(BaseMiner):
data.wattage_limit = wattage_limit
if summary_data[0].get("Error Code Count"):
for i in range(summary_data[0]["Error Code Count"]):
if summary_data[0].get(f"Error Code {i}"):
data.errors.append(
WhatsminerError(
error_code=summary_data[0][f"Error Code {i}"]
)
)
if devs:
temp_data = devs.get("DEVS")
if temp_data:

View File

@@ -1,5 +1,6 @@
import ipaddress
import logging
from typing import Union
from pyasic.API.cgminer import CGMinerAPI
@@ -8,7 +9,7 @@ from pyasic.API import APIError
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
class CGMiner(BaseMiner):
@@ -21,7 +22,12 @@ class CGMiner(BaseMiner):
self.pwd = "admin"
self.config = None
async def get_model(self):
async def get_model(self) -> Union[str, None]:
"""Get miner model.
Returns:
Miner model or None.
"""
if self.model:
return self.model
try:
@@ -33,7 +39,12 @@ class CGMiner(BaseMiner):
return self.model
return None
async def get_hostname(self) -> str or None:
async def get_hostname(self) -> Union[str, None]:
"""Get miner hostname.
Returns:
The hostname of the miner as a string or "?"
"""
if self.hostname:
return self.hostname
try:
@@ -48,7 +59,15 @@ class CGMiner(BaseMiner):
except Exception:
return None
async def send_ssh_command(self, cmd):
async def send_ssh_command(self, cmd: str) -> Union[str, None]:
"""Send a command to the miner over ssh.
Parameters:
cmd: The command to run.
Returns:
Result of the command or None.
"""
result = None
async with (await self._get_ssh_connection()) as conn:
for i in range(3):
@@ -63,9 +82,11 @@ class CGMiner(BaseMiner):
return result
async def restart_backend(self) -> bool:
"""Restart cgminer hashing process. Wraps [`restart_cgminer`][pyasic.miners._backends.cgminer.CGMiner.restart_cgminer] to standardize."""
return await self.restart_cgminer()
async def restart_cgminer(self) -> bool:
"""Restart cgminer hashing process."""
commands = ["cgminer-api restart", "/usr/bin/cgminer-monitor >/dev/null 2>&1"]
commands = ";".join(commands)
_ret = await self.send_ssh_command(commands)
@@ -74,6 +95,7 @@ class CGMiner(BaseMiner):
return False
async def reboot(self) -> bool:
"""Reboots power to the physical miner."""
logging.debug(f"{self}: Sending reboot command.")
_ret = await self.send_ssh_command("reboot")
logging.debug(f"{self}: Reboot command completed.")
@@ -82,6 +104,7 @@ class CGMiner(BaseMiner):
return False
async def start_cgminer(self) -> None:
"""Start cgminer hashing process."""
commands = [
"mkdir -p /etc/tmp/",
'echo "*/3 * * * * /usr/bin/cgminer-monitor" > /etc/tmp/root',
@@ -92,6 +115,7 @@ class CGMiner(BaseMiner):
await self.send_ssh_command(commands)
async def stop_cgminer(self) -> None:
"""Restart cgminer hashing process."""
commands = [
"mkdir -p /etc/tmp/",
'echo "" > /etc/tmp/root',
@@ -101,14 +125,24 @@ class CGMiner(BaseMiner):
commands = ";".join(commands)
await self.send_ssh_command(commands)
async def get_config(self) -> None:
async def get_config(self) -> str:
"""Gets the config for the miner and sets it as `self.config`.
Returns:
The config from `self.config`.
"""
async with (await self._get_ssh_connection()) as conn:
command = "cat /etc/config/cgminer"
result = await conn.run(command, check=True)
self.config = result.stdout
print(str(self.config))
return self.config
async def get_data(self):
async def get_data(self) -> MinerData:
"""Get data from the miner.
Returns:
A [`MinerData`][pyasic.data.MinerData] instance containing the miners data.
"""
data = MinerData(ip=str(self.ip), ideal_chips=self.nominal_chips * 3)
board_offset = -1
@@ -128,7 +162,7 @@ class CGMiner(BaseMiner):
data.mac = mac
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"summary", "pools", "stats", ignore_x19_error=True
)

View File

@@ -8,3 +8,21 @@ class M20S(BaseMiner):
self.model = "M20S"
self.nominal_chips = 66
self.fan_count = 2
class M20SV10(BaseMiner):
def __init__(self, ip: str):
super().__init__()
self.ip = ip
self.model = "M20S"
self.nominal_chips = 105
self.fan_count = 2
class M20SV20(BaseMiner):
def __init__(self, ip: str):
super().__init__()
self.ip = ip
self.model = "M20S"
self.nominal_chips = 111
self.fan_count = 2

View File

@@ -1,4 +1,4 @@
from .M20S import M20S
from .M20S import M20S, M20SV10, M20SV20
from .M20S_Plus import M20SPlus
from .M21 import M21

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon1026 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon1026(CGMiner, Avalon1026):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon1047 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon1047(CGMiner, Avalon1047):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon1066 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon1066(CGMiner, Avalon1066):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon721 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon721(CGMiner, Avalon721):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon741 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon741(CGMiner, Avalon741):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon761 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon761(CGMiner, Avalon761):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon821 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon821(CGMiner, Avalon821):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon841 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon841(CGMiner, Avalon841):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon851 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon851(CGMiner, Avalon851):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -2,7 +2,7 @@ from pyasic.miners._backends import CGMiner # noqa - Ignore access to _module
from pyasic.miners._types import Avalon921 # noqa - Ignore access to _module
from pyasic.data import MinerData
from pyasic.settings import MINER_FACTORY_GET_VERSION_RETRIES as DATA_RETRIES
from pyasic.settings import PyasicSettings
import re
from pyasic.config import MinerConfig
import logging
@@ -67,7 +67,7 @@ class CGMinerAvalon921(CGMiner, Avalon921):
data.model = model
miner_data = None
for i in range(DATA_RETRIES):
for i in range(PyasicSettings().miner_get_data_retries):
miner_data = await self.api.multicommand(
"version", "summary", "pools", "stats"
)

View File

@@ -1,6 +1,7 @@
from typing import TypeVar, Tuple, List
from typing import TypeVar, Tuple, List, Union
from collections.abc import AsyncIterable
from pyasic.miners import BaseMiner
import httpx
from pyasic.miners.antminer import *
from pyasic.miners.avalonminer import *
@@ -10,9 +11,9 @@ from pyasic.miners._backends.cgminer import CGMiner # noqa - Ignore _module imp
from pyasic.miners._backends.bmminer import BMMiner # noqa - Ignore _module import
from pyasic.miners._backends.bosminer import BOSMiner # noqa - Ignore _module import
from pyasic.miners._backends.btminer import BTMiner # noqa - Ignore _module import
from pyasic.miners._backends.bosminer_old import (
from pyasic.miners._backends.bosminer_old import ( # noqa - Ignore _module import
BOSMinerOld,
) # noqa - Ignore _module import
)
from pyasic.miners.unknown import UnknownMiner
@@ -23,10 +24,7 @@ import ipaddress
import json
import logging
from pyasic.settings import (
MINER_FACTORY_GET_VERSION_RETRIES as GET_VERSION_RETRIES,
NETWORK_PING_TIMEOUT as PING_TIMEOUT,
)
from pyasic.settings import PyasicSettings
import asyncssh
@@ -123,6 +121,8 @@ MINER_CLASSES = {
"M20S": {
"Default": BTMinerM20S,
"BTMiner": BTMinerM20S,
"10": BTMinerM20SV10,
"20": BTMinerM20SV20,
},
"M20S+": {
"Default": BTMinerM20SPlus,
@@ -229,11 +229,13 @@ class Singleton(type):
class MinerFactory(metaclass=Singleton):
"""A factory to handle identification and selection of the proper class of miner"""
def __init__(self) -> None:
self.miners = {}
async def get_miner_generator(
self, ips: List[ipaddress.ip_address or str]
self, ips: List[Union[ipaddress.ip_address, str]]
) -> AsyncIterable[AnyMiner]:
"""
Get Miner objects from ip addresses using an async generator.
@@ -242,6 +244,9 @@ class MinerFactory(metaclass=Singleton):
Parameters:
ips: a list of ip addresses to get miners for.
Returns:
An async iterable containing miners.
"""
# get the event loop
loop = asyncio.get_event_loop()
@@ -256,8 +261,15 @@ class MinerFactory(metaclass=Singleton):
for miner in scanned:
yield await miner
async def get_miner(self, ip: ipaddress.ip_address or str) -> AnyMiner:
"""Decide a miner type using the IP address of the miner."""
async def get_miner(self, ip: Union[ipaddress.ip_address, str]) -> AnyMiner:
"""Decide a miner type using the IP address of the miner.
Parameters:
ip: An `ipaddress.ip_address` or string of the IP to find the miner.
Returns:
A miner class.
"""
if isinstance(ip, str):
ip = ipaddress.ip_address(ip)
# check if the miner already exists in cache
@@ -270,13 +282,12 @@ class MinerFactory(metaclass=Singleton):
ver = None
# try to get the API multiple times based on retries
for i in range(GET_VERSION_RETRIES):
for i in range(PyasicSettings().miner_factory_get_version_retries):
try:
# get the API type, should be BOSMiner, CGMiner, BMMiner, BTMiner, or None
new_model, new_api, new_ver = await asyncio.wait_for(
self._get_miner_type(ip), timeout=PING_TIMEOUT
self._get_miner_type(ip), timeout=10
)
# keep track of the API and model we found first
if new_api and not api:
api = new_api
@@ -284,13 +295,11 @@ class MinerFactory(metaclass=Singleton):
model = new_model
if new_ver and not ver:
ver = new_ver
# if we find the API and model, don't need to loop anymore
if api and model:
break
except asyncio.TimeoutError:
pass
logging.warning(f"{ip}: Get Miner Timed Out")
# make sure we have model information
if model:
if not api:
@@ -298,12 +307,10 @@ class MinerFactory(metaclass=Singleton):
if model not in MINER_CLASSES.keys():
if "avalon" in model:
print(model)
if model == "avalon10":
miner = CGMinerAvalon1066(str(ip))
else:
miner = CGMinerAvalon821(str(ip))
miner = UnknownMiner(str(ip))
return miner
if api not in MINER_CLASSES[model].keys():
api = "Default"
@@ -343,32 +350,26 @@ class MinerFactory(metaclass=Singleton):
async def _get_miner_type(
self, ip: ipaddress.ip_address or str
) -> Tuple[str or None, str or None, str or None]:
data = None
model = None
api = None
ver = None
devdetails = None
version = None
try:
# get device details and version data
data = await self._send_api_command(str(ip), "devdetails+version")
# validate success
validation = await self._validate_command(data)
if not validation[0]:
raise APIError(validation[1])
# copy each part of the main command to devdetails and version
devdetails = data["devdetails"][0]
version = data["version"][0]
except APIError:
# if getting data fails we need to check again
data = None
# if data is None then get it a slightly different way
if not data:
try:
# try devdetails and version separately (X19s mainly require this)
# get devdetails and validate
@@ -393,6 +394,44 @@ class MinerFactory(metaclass=Singleton):
# catch APIError and let the factory know we cant get data
logging.warning(f"{ip}: API Command Error: {e}")
return None, None, None
except OSError as e:
# miner refused connection on API port, we wont be able to get data this way
# try ssh
try:
async with asyncssh.connect(
str(ip),
known_hosts=None,
username="root",
password="admin",
server_host_key_algs=["ssh-rsa"],
) as conn:
board_name = None
cmd = await conn.run("cat /tmp/sysinfo/board_name")
if cmd:
board_name = cmd.stdout.strip()
if board_name:
if board_name == "am1-s9":
model = "Antminer S9"
if board_name == "am2-s17":
model = "Antminer S17"
api = "BOSMiner+"
return model, api, None
except asyncssh.misc.PermissionDenied:
try:
url = f"http://{self.ip}/cgi-bin/get_system_info.cgi"
auth = httpx.DigestAuth("root", "root")
async with httpx.AsyncClient() as client:
data = await client.get(url, auth=auth)
if data.status_code == 200:
data = data.json()
if "minertype" in data.keys():
model = data["minertype"]
if "bmminer" in "\t".join(data.keys()):
api = "BMMiner"
except:
return None, None, None
# if we have devdetails, we can get model data from there
if devdetails:
@@ -440,24 +479,24 @@ class MinerFactory(metaclass=Singleton):
if "BOSminer+" in version["VERSION"][0].keys():
api = "BOSMiner+"
# check for avalonminers
if version["VERSION"][0].get("PROD"):
_data = version["VERSION"][0]["PROD"].split("-")
model = _data[0]
if len(data) > 1:
ver = _data[1]
elif version["VERSION"][0].get("MODEL"):
_data = version["VERSION"][0]["MODEL"].split("-")
model = f"AvalonMiner {_data[0]}"
if len(data) > 1:
ver = _data[1]
# if all that fails, check the Description to see if it is a whatsminer
if version.get("Description") and (
"whatsminer" in version.get("Description")
):
api = "BTMiner"
# check for avalonminers
if version["VERSION"][0].get("PROD"):
_data = version["VERSION"][0]["PROD"].split("-")
model = _data[0]
if len(data) > 1:
ver = _data[1]
elif version["VERSION"][0].get("MODEL"):
_data = version["VERSION"][0]["MODEL"].split("-")
model = f"AvalonMiner {_data[0]}"
if len(data) > 1:
ver = _data[1]
# if we have no model from devdetails but have version, try to get it from there
if version and not model:
# make sure version isn't blank
@@ -474,23 +513,6 @@ class MinerFactory(metaclass=Singleton):
elif "am2-s17" in version["STATUS"][0]["Description"]:
model = "Antminer S17"
# final try on a braiins OS bug with devdetails not returning
else:
try:
async with asyncssh.connect(
str(ip),
known_hosts=None,
username="root",
password="admin",
server_host_key_algs=["ssh-rsa"],
) as conn:
cfg = await conn.run("bosminer config --data")
if cfg:
cfg = json.loads(cfg.stdout)
model = cfg.get("data").get("format").get("model")
except asyncssh.misc.PermissionDenied:
pass
if model:
# whatsminer have a V in their version string (M20SV41), remove everything after it
if "V" in model:
@@ -507,7 +529,7 @@ class MinerFactory(metaclass=Singleton):
async def _validate_command(data: dict) -> Tuple[bool, str or None]:
"""Check if the returned command output is correctly formatted."""
# check if the data returned is correct or an error
if not data:
if not data or data == {}:
return False, "No API data."
# if status isn't a key, it is a multicommand
if "STATUS" not in data.keys():
@@ -536,9 +558,10 @@ class MinerFactory(metaclass=Singleton):
# get reader and writer streams
reader, writer = await asyncio.open_connection(str(ip), 4028)
except OSError as e:
if e.errno in [10061, 22] or e.winerror == 1225:
raise e
logging.warning(f"{str(ip)} - Command {command}: {e}")
return {}
# create the command
cmd = {"command": command}

View File

@@ -1,8 +1,24 @@
from pyasic.miners._backends import BTMiner # noqa - Ignore access to _module
from pyasic.miners._types import M20S # noqa - Ignore access to _module
from pyasic.miners._types import ( # noqa - Ignore access to _module
M20S,
M20SV10,
M20SV20,
)
class BTMinerM20S(BTMiner, M20S):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip
class BTMinerM20SV10(BTMiner, M20SV10):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip
class BTMinerM20SV20(BTMiner, M20SV20):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip

View File

@@ -1,4 +1,4 @@
from .M20S import BTMinerM20S
from .M20S import BTMinerM20S, BTMinerM20SV10, BTMinerM20SV20
from .M20S_Plus import BTMinerM20SPlus
from .M21 import BTMinerM21

View File

@@ -14,7 +14,7 @@ class BTMinerM30S(BTMiner, M30S):
self.ip = ip
class BTMinerM30SV50(BTMiner, M30SV50):
class BTMinerM30SVE10(BTMiner, M30SVE10):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip
@@ -32,7 +32,7 @@ class BTMinerM30SVE20(BTMiner, M30SVE20):
self.ip = ip
class BTMinerM30SVE10(BTMiner, M30SVE10):
class BTMinerM30SV50(BTMiner, M30SV50):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip

View File

@@ -13,13 +13,13 @@ class BTMinerM30SPlus(BTMiner, M30SPlus):
self.ip = ip
class BTMinerM30SPlusVE40(BTMiner, M30SPlusVE40):
class BTMinerM30SPlusVF20(BTMiner, M30SPlusVF20):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip
class BTMinerM30SPlusVF20(BTMiner, M30SPlusVF20):
class BTMinerM30SPlusVE40(BTMiner, M30SPlusVE40):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip

View File

@@ -12,13 +12,13 @@ class BTMinerM30SPlusPlus(BTMiner, M30SPlusPlus):
self.ip = ip
class BTMinerM30SPlusPlusVG40(BTMiner, M30SPlusPlusVG40):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip
class BTMinerM30SPlusPlusVG30(BTMiner, M30SPlusPlusVG30):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip
class BTMinerM30SPlusPlusVG40(BTMiner, M30SPlusPlusVG40):
def __init__(self, ip: str) -> None:
super().__init__(ip)
self.ip = ip

View File

@@ -1,70 +0,0 @@
import asyncio
from pyasic.network import MinerNetwork
from pyasic.miners._backends.bosminer import BOSMiner # noqa - Ignore access to _module
async def get_bos_bad_tuners(ip: str = "192.168.1.0", mask: int = 24):
# create a miner network
miner_network = MinerNetwork(ip, mask=mask)
# scan for miners
miners = await miner_network.scan_network_for_miners()
# create an empty list of tasks
tuner_tasks = []
# loop checks if the miner is a BOSMiner
for miner in miners:
# can only do this if its a subclass of BOSMiner
if BOSMiner in type(miner).__bases__:
tuner_tasks.append(_get_tuner_status(miner))
# run all the tuner status commands
tuner_status = await asyncio.gather(*tuner_tasks)
# create a list of all miners with bad board tuner status
bad_tuner_miners = []
for item in tuner_status:
# loop through and get each miners' bad board count
bad_boards = []
for board in item["tuner_status"]:
# if its not stable or still testing, its bad
if board["status"] not in [
"Stable",
"Testing performance profile",
"Tuning individual chips",
]:
# remove the part about the board refusing to start
bad_boards.append(
{
"board": board["board"],
"error": board["status"].replace(
"Hashchain refused to start: ", ""
),
}
)
# if this miner has bad boards, add it to the list of bad board miners
if len(bad_boards) > 0:
bad_tuner_miners.append({"ip": item["ip"], "boards": bad_boards})
# return the list of bad board miners
return bad_tuner_miners
async def _get_tuner_status(miner):
# run the tunerstatus command, since the miner will always be BOSMiner
tuner_status = await miner.api.tunerstatus()
# create a list to add the tuner data to
tuner_data = []
# if we have data, loop through to get the hashchain status
if tuner_status:
for board in tuner_status["TUNERSTATUS"][0]["TunerChainStatus"]:
tuner_data.append(
{"board": board["HashchainIndex"], "status": board["Status"]}
)
# return the data along with the IP or later tracking
return {"ip": str(miner.ip), "tuner_status": tuner_data}

View File

@@ -1,23 +1,36 @@
import ipaddress
import asyncio
import logging
from typing import Union, List, AsyncIterator
from pyasic.network.net_range import MinerNetworkRange
from pyasic.miners.miner_factory import MinerFactory
from pyasic.settings import (
NETWORK_PING_RETRIES as PING_RETRIES,
NETWORK_PING_TIMEOUT as PING_TIMEOUT,
NETWORK_SCAN_THREADS as SCAN_THREADS,
)
from pyasic.miners.miner_factory import MinerFactory, AnyMiner
from pyasic.settings import PyasicSettings
class MinerNetwork:
"""A class to handle a network containing miners. Handles scanning and gets miners via [`MinerFactory`][pyasic.miners.miner_factory.MinerFactory].
Parameters:
ip_addr: ### An IP address, range of IP addresses, or a list of IPs
* Takes a single IP address as an `ipadddress.ipaddress()` or a string
* Takes a string formatted as:
```f"{ip_range_1_start}-{ip_range_1_end}, {ip_address_1}, {ip_range_2_start}-{ip_range_2_end}, {ip_address_2}..."```
* Also takes a list of strings or `ipaddress.ipaddress` formatted as:
```[{ip_address_1}, {ip_address_2}, {ip_address_3}, ...]```
mask: A subnet mask to use when constructing the network. Only used if `ip_addr` is a single IP.
Defaults to /24 (255.255.255.0 or 0.0.0.255)
"""
def __init__(
self, ip_addr: str or None = None, mask: str or int or None = None
self, ip_addr: Union[str, None] = None, mask: Union[str, int, None] = None
) -> None:
self.network = None
self.ip_addr = ip_addr
self.connected_miners = {}
if isinstance(mask, str):
if mask.startswith("/"):
mask = mask.replace("/", "")
self.mask = mask
def __len__(self):
@@ -27,7 +40,11 @@ class MinerNetwork:
return str(self.network)
def get_network(self) -> ipaddress.ip_network:
"""Get the network using the information passed to the MinerNetwork or from cache."""
"""Get the network using the information passed to the MinerNetwork or from cache.
Returns:
The proper network to be able to scan.
"""
# if we have a network cached already, use that
if self.network:
return self.network
@@ -55,13 +72,19 @@ class MinerNetwork:
self.network = ipaddress.ip_network(
f"{default_gateway}/{subnet_mask}", strict=False
)
logging.debug(f"Setting MinerNetwork: {self.network}")
return self.network
async def scan_network_for_miners(self) -> None or list:
"""Scan the network for miners, and return found miners as a list."""
async def scan_network_for_miners(self) -> List[AnyMiner]:
"""Scan the network for miners, and return found miners as a list.
Returns:
A list of found miners.
"""
# get the network
local_network = self.get_network()
print(f"Scanning {local_network} for miners...")
logging.debug(f"Scanning {local_network} for miners")
# clear cached miners
MinerFactory().clear_cached_miners()
@@ -74,7 +97,7 @@ class MinerNetwork:
for host in local_network.hosts():
# make sure we don't exceed the allowed async tasks
if len(scan_tasks) < SCAN_THREADS:
if len(scan_tasks) < round(PyasicSettings().network_scan_threads / 3):
# add the task to the list
scan_tasks.append(self.ping_and_get_miner(host))
else:
@@ -90,16 +113,17 @@ class MinerNetwork:
# remove all None from the miner list
miners = list(filter(None, miners))
print(f"Found {len(miners)} connected miners...")
logging.debug(f"Found {len(miners)} connected miners")
# return the miner objects
return miners
async def scan_network_generator(self):
async def scan_network_generator(self) -> AsyncIterator[AnyMiner]:
"""
Scan the network for miners using an async generator.
Returns an asynchronous generator containing found miners.
Returns:
An asynchronous generator containing found miners.
"""
# get the current event loop
loop = asyncio.get_event_loop()
@@ -113,7 +137,7 @@ class MinerNetwork:
# for each ip on the network, loop through and scan it
for host in local_network.hosts():
# make sure we don't exceed the allowed async tasks
if len(scan_tasks) >= SCAN_THREADS:
if len(scan_tasks) >= round(PyasicSettings().network_scan_threads / 3):
# scanned is a loopable list of awaitables
scanned = asyncio.as_completed(scan_tasks)
# when we scan, empty the scan tasks
@@ -132,25 +156,33 @@ class MinerNetwork:
yield await miner
@staticmethod
async def ping_miner(ip: ipaddress.ip_address) -> None or ipaddress.ip_address:
return await ping_miner(ip)
async def ping_miner(ip: ipaddress.ip_address) -> Union[None, ipaddress.ip_address]:
tasks = [ping_miner(ip, port=port) for port in [4028, 4029, 8889]]
for miner in asyncio.as_completed(tasks):
miner = await miner
if miner:
return miner
@staticmethod
async def ping_and_get_miner(
ip: ipaddress.ip_address,
) -> None or ipaddress.ip_address:
return await ping_and_get_miner(ip)
) -> Union[None, AnyMiner]:
tasks = [ping_and_get_miner(ip, port=port) for port in [4028, 4029, 8889]]
for miner in asyncio.as_completed(tasks):
miner = await miner
if miner:
return miner
async def ping_miner(
ip: ipaddress.ip_address, port=4028
) -> None or ipaddress.ip_address:
for i in range(PING_RETRIES):
) -> Union[None, ipaddress.ip_address]:
for i in range(PyasicSettings().network_ping_retries):
connection_fut = asyncio.open_connection(str(ip), port)
try:
# get the read and write streams from the connection
reader, writer = await asyncio.wait_for(
connection_fut, timeout=PING_TIMEOUT
connection_fut, timeout=PyasicSettings().network_ping_timeout
)
# immediately close connection, we know connection happened
writer.close()
@@ -173,13 +205,13 @@ async def ping_miner(
async def ping_and_get_miner(
ip: ipaddress.ip_address, port=4028
) -> None or ipaddress.ip_address:
for i in range(PING_RETRIES):
) -> Union[None, AnyMiner]:
for i in range(PyasicSettings().network_ping_retries):
connection_fut = asyncio.open_connection(str(ip), port)
try:
# get the read and write streams from the connection
reader, writer = await asyncio.wait_for(
connection_fut, timeout=PING_TIMEOUT
connection_fut, timeout=PyasicSettings().network_ping_timeout
)
# immediately close connection, we know connection happened
writer.close()

View File

@@ -5,12 +5,12 @@ import ipaddress
class MinerNetworkRange:
"""A MinerNetwork that takes a range of IP addresses.
:param ip_range: A range of IP addresses to put in the network, or a list of IPs
Takes a string formatted as:
{ip_range_1_start}-{ip_range_1_end}, {ip_address_1},
{ip_range_2_start}-{ip_range_2_end}, {ip_address_2}...
Also takes a list of strings formatted as:
[{ip_address_1}, {ip_address_2}, {ip_address_3}, ...]
Parameters:
ip_range: ## A range of IP addresses to put in the network, or a list of IPs
* Takes a string formatted as:
```f"{ip_range_1_start}-{ip_range_1_end}, {ip_address_1}, {ip_range_2_start}-{ip_range_2_end}, {ip_address_2}..."```
* Also takes a list of strings or `ipaddress.ipaddress` formatted as:
```[{ip_address_1}, {ip_address_2}, {ip_address_3}, ...]```
"""
def __init__(self, ip_range: Union[str, list]):

View File

@@ -1,53 +1,26 @@
import toml
import os
NETWORK_PING_RETRIES: int = 3
NETWORK_PING_TIMEOUT: int = 5
NETWORK_SCAN_THREADS: int = 300
CFG_UTIL_REBOOT_THREADS: int = 300
CFG_UTIL_CONFIG_THREADS: int = 300
MINER_FACTORY_GET_VERSION_RETRIES: int = 3
WHATSMINER_PWD = "admin"
DEBUG = False
LOGFILE = False
settings_keys = {}
try:
with open(
os.path.join(os.path.dirname(__file__), "settings.toml"), "r"
) as settings_file:
settings = toml.loads(settings_file.read())
settings_keys = settings.keys()
except:
pass
if "ping_retries" in settings_keys:
NETWORK_PING_RETRIES: int = settings["ping_retries"]
if "ping_timeout" in settings_keys:
NETWORK_PING_TIMEOUT: int = settings["ping_timeout"]
if "scan_threads" in settings_keys:
NETWORK_SCAN_THREADS: int = settings["scan_threads"]
if "reboot_threads" in settings_keys:
CFG_UTIL_REBOOT_THREADS: int = settings["reboot_threads"]
if "config_threads" in settings_keys:
CFG_UTIL_CONFIG_THREADS: int = settings["config_threads"]
from dataclasses import dataclass
if "get_version_retries" in settings_keys:
MINER_FACTORY_GET_VERSION_RETRIES: int = settings["get_version_retries"]
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instances[cls]
if "whatsminer_pwd" in settings_keys:
WHATSMINER_PWD: str = settings["whatsminer_pwd"]
@dataclass
class PyasicSettings(metaclass=Singleton):
network_ping_retries: int = 1
network_ping_timeout: int = 3
network_scan_threads: int = 300
if "debug" in settings_keys:
DEBUG: int = settings["debug"]
miner_factory_get_version_retries: int = 1
if "logfile" in settings_keys:
LOGFILE: bool = settings["logfile"]
miner_get_data_retries: int = 1
global_whatsminer_password = "admin"
debug: bool = False
logfile: bool = False

View File

@@ -1,22 +0,0 @@
get_version_retries = 3
ping_retries = 3
ping_timeout = 3 # Seconds
scan_threads = 300
config_threads = 300
reboot_threads = 300
### IMPORTANT ###
# You need to change the password of the miners using the whatsminer
# tool or the privileged API will not work using admin as the password.
# If you change the password, you can pass that password here.
whatsminer_pwd = "admin"
logfile = true
### DEBUG MODE ###
# change this to debug = true
# to enable debug mode.
debug = false
# debug = true

View File

@@ -1,8 +1,11 @@
[tool.poetry]
name = "pyasic"
version = "0.10.1"
version = "0.12.4"
description = "A set of modules for interfacing with many common types of ASIC bitcoin miners, using both their API and SSH."
authors = ["UpstreamData <brett@upstreamdata.ca>"]
repository = "https://github.com/UpstreamData/pyasic"
documentation = "https://pyasic.readthedocs.io/en/latest/"
readme = "README.md"
[tool.poetry.dependencies]
python = "^3.9"