added warnings to notify when removing

This commit is contained in:
UpstreamData
2022-01-06 12:37:43 -07:00
parent ea1e8abeac
commit c751d53398
4 changed files with 43 additions and 24 deletions

View File

@@ -1,6 +1,7 @@
import asyncio import asyncio
import json import json
import ipaddress import ipaddress
import warnings
class APIError(Exception): class APIError(Exception):
@@ -17,6 +18,20 @@ class APIError(Exception):
return "Incorrect API parameters." return "Incorrect API parameters."
class APIWarning(Warning):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def __str__(self):
if self.message:
return f"{self.message}"
else:
return "Incorrect API parameters."
class BaseMinerAPI: class BaseMinerAPI:
def __init__(self, ip: str, port: int = 4028) -> None: def __init__(self, ip: str, port: int = 4028) -> None:
# api port, should be 4028 # api port, should be 4028
@@ -41,10 +56,14 @@ class BaseMinerAPI:
async def multicommand(self, *commands: str) -> dict: async def multicommand(self, *commands: str) -> dict:
"""Creates and sends multiple commands as one command to the miner.""" """Creates and sends multiple commands as one command to the miner."""
# split the commands into a proper list # split the commands into a proper list
commands = [*commands] user_commands = [*commands]
allowed_commands = self.get_commands() allowed_commands = self.get_commands()
# make sure we can actually run the command, otherwise it will fail # make sure we can actually run the command, otherwise it will fail
commands = [command for command in commands if command in allowed_commands] 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}") instead.""",
APIWarning)
# standard multicommand format is "command1+command2" # standard multicommand format is "command1+command2"
# doesnt work for S19 which is dealt with in the send command function # doesnt work for S19 which is dealt with in the send command function
command = "+".join(commands) command = "+".join(commands)
@@ -104,14 +123,15 @@ class BaseMinerAPI:
writer.close() writer.close()
await writer.wait_closed() await writer.wait_closed()
# validate the command suceeded # validate the command succeeded
if not self.validate_command_output(data): validation = self.validate_command_output(data)
raise APIError(data["STATUS"][0]["Msg"]) if not validation[0]:
raise APIError(validation[1])
return data return data
@staticmethod @staticmethod
def validate_command_output(data: dict) -> bool: def validate_command_output(data: dict) -> tuple[bool, str | None]:
"""Check if the returned command output is correctly formatted.""" """Check if the returned command output is correctly formatted."""
# check if the data returned is correct or an error # check if the data returned is correct or an error
# if status isn't a key, it is a multicommand # if status isn't a key, it is a multicommand
@@ -120,20 +140,20 @@ class BaseMinerAPI:
# make sure not to try to turn id into a dict # make sure not to try to turn id into a dict
if not key == "id": if not key == "id":
# make sure they succeeded # make sure they succeeded
if "STATUS" in data.keys(): if "STATUS" in data[key][0].keys():
if data[key][0]["STATUS"][0]["STATUS"] not in ["S", "I"]: if data[key][0]["STATUS"][0]["STATUS"] not in ["S", "I"]:
# this is an error # this is an error
return False return False, f"{key}: " + data[key][0]["STATUS"][0]["Msg"]
elif "id" not in data.keys(): elif "id" not in data.keys():
if data["STATUS"] not in ["S", "I"]: if data["STATUS"] not in ["S", "I"]:
return False return False, data["Msg"]
else: else:
# make sure the command succeeded # make sure the command succeeded
if data["STATUS"][0]["STATUS"] not in ("S", "I"): if data["STATUS"][0]["STATUS"] not in ("S", "I"):
# this is an error # this is an error
if data["STATUS"][0]["STATUS"] not in ("S", "I"): if data["STATUS"][0]["STATUS"] not in ("S", "I"):
return False return False, data["STATUS"][0]["Msg"]
return True return True, None
@staticmethod @staticmethod
def load_api_data(data: bytes) -> dict: def load_api_data(data: bytes) -> dict:

View File

@@ -132,8 +132,9 @@ class BTMinerAPI(BaseMinerAPI):
print(e) print(e)
# if it fails to validate, it is likely an error # if it fails to validate, it is likely an error
if not self.validate_command_output(data): validation = self.validate_command_output(data)
raise APIError(data["Msg"]) if not validation[0]:
raise APIError(validation[1])
# return the parsed json as a dict # return the parsed json as a dict
return data return data

View File

@@ -2,7 +2,7 @@ import asyncio
import ipaddress import ipaddress
import time import time
from API import APIError from API import APIError, APIWarning
from cfg_util.func.parse_data import safe_parse_api_data from cfg_util.func.parse_data import safe_parse_api_data
from cfg_util.func.ui import update_ui_with_data, update_prog_bar, set_progress_bar_len from cfg_util.func.ui import update_ui_with_data, update_prog_bar, set_progress_bar_len
from cfg_util.layout import window from cfg_util.layout import window
@@ -120,7 +120,8 @@ async def get_data(ip_list: list):
if data_point["IP"] in ordered_all_ips: if data_point["IP"] in ordered_all_ips:
ip_table_index = ordered_all_ips.index(data_point["IP"]) ip_table_index = ordered_all_ips.index(data_point["IP"])
ip_table_data[ip_table_index] = [ ip_table_data[ip_table_index] = [
data_point["IP"], data_point["host"], str(data_point['TH/s']) + " TH/s", data_point["temp"], data_point['user'], str(data_point['wattage']) + " W" data_point["IP"], data_point["host"], str(data_point['TH/s']) + " TH/s", data_point["temp"],
data_point['user'], str(data_point['wattage']) + " W"
] ]
window["ip_table"].update(ip_table_data) window["ip_table"].update(ip_table_data)
progress_bar_len += 1 progress_bar_len += 1
@@ -170,7 +171,8 @@ async def scan_and_get_data(network):
if data_point["IP"] in ordered_all_ips: if data_point["IP"] in ordered_all_ips:
ip_table_index = ordered_all_ips.index(data_point["IP"]) ip_table_index = ordered_all_ips.index(data_point["IP"])
ip_table_data[ip_table_index] = [ ip_table_data[ip_table_index] = [
data_point["IP"], data_point["host"], str(data_point['TH/s']) + " TH/s", data_point["temp"], data_point['user'], str(data_point['wattage']) + " W" data_point["IP"], data_point["host"], str(data_point['TH/s']) + " TH/s", data_point["temp"],
data_point['user'], str(data_point['wattage']) + " W"
] ]
window["ip_table"].update(ip_table_data) window["ip_table"].update(ip_table_data)
progress_bar_len += 1 progress_bar_len += 1
@@ -181,15 +183,10 @@ async def scan_and_get_data(network):
await update_ui_with_data("status", "") await update_ui_with_data("status", "")
async def get_formatted_data(ip: ipaddress.ip_address): async def get_formatted_data(ip: ipaddress.ip_address):
miner = await miner_factory.get_miner(ip) miner = await miner_factory.get_miner(ip)
try: try:
miner_data = await miner.api.multicommand("summary", "devs", "temps", "tunerstatus", "pools", "stats") miner_data = await miner.api.multicommand("summary", "devs", "temps", "tunerstatus", "pools", "stats")
except APIError: except APIError:
return {'TH/s': "Unknown", 'IP': str(miner.ip), 'host': "Unknown", 'user': "Unknown", 'wattage': 0} return {'TH/s': "Unknown", 'IP': str(miner.ip), 'host': "Unknown", 'user': "Unknown", 'wattage': 0}
host = await miner.get_hostname() host = await miner.get_hostname()
@@ -223,7 +220,8 @@ async def get_formatted_data(ip: ipaddress.ip_address):
if "stats" in miner_data.keys() and not miner_data["stats"][0]['STATS'] == []: if "stats" in miner_data.keys() and not miner_data["stats"][0]['STATS'] == []:
for temp in ["temp2", "temp1", "temp3"]: for temp in ["temp2", "temp1", "temp3"]:
if temp in miner_data["stats"][0]['STATS'][1].keys(): if temp in miner_data["stats"][0]['STATS'][1].keys():
if miner_data["stats"][0]['STATS'][1][temp] is not None and not miner_data["stats"][0]['STATS'][1][temp] == 0.0: if miner_data["stats"][0]['STATS'][1][temp] is not None and not miner_data["stats"][0]['STATS'][1][
temp] == 0.0:
temps = miner_data["stats"][0]['STATS'][1][temp] temps = miner_data["stats"][0]['STATS'][1][temp]
if "pools" not in miner_data.keys(): if "pools" not in miner_data.keys():

View File

@@ -17,7 +17,7 @@ class BTMiner(BaseMiner):
if host_data: if host_data:
return host_data["Msg"]["hostname"] return host_data["Msg"]["hostname"]
except APIError: except APIError:
return "BTMiner Unknown" return "BTMiner ?"
async def send_config(self, _): async def send_config(self, _):
return None # ignore for now return None # ignore for now