Skip to content

Commit

Permalink
tidy up of a few files
Browse files Browse the repository at this point in the history
  • Loading branch information
jblance committed Jan 6, 2023
1 parent 30b35b9 commit 33ff5af
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 231 deletions.
224 changes: 0 additions & 224 deletions mppsolar/devices/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,228 +45,6 @@ def __str__(self):
"""
return f"{self._classname} device - name: {self._name}, port: {self._port}, protocol: {self._protocol}"

# TODO: remove commented code once certain nothing has broken
# def get_port_type(self, port):
# if port is None:
# return PORT_TYPE_UNKNOWN

# port = port.lower()
# # check for test type port
# if "test" in port:
# log.debug("port matches test")
# return PORT_TYPE_TEST
# # mqtt
# elif "mqtt" in port:
# log.debug("port matches mqtt")
# return PORT_TYPE_MQTT
# # USB type ports
# elif "hidraw" in port:
# log.debug("port matches hidraw")
# return PORT_TYPE_USB
# elif "mppsolar" in port:
# log.debug("port matches mppsolar")
# return PORT_TYPE_USB
# # ESP type ports
# elif "esp" in port:
# log.debug("port matches esp")
# return PORT_TYPE_ESP32
# # JKBLE type ports
# elif ":" in port:
# # all mac addresses currently return as JKBLE
# log.debug("port matches jkble ':'")
# return PORT_TYPE_JKBLE
# elif "jkble" in port:
# log.debug("port matches jkble")
# return PORT_TYPE_JKBLE
# elif "daly" in port:
# log.debug("port matches daly")
# return PORT_TYPE_DALYSERIAL
# elif "vserial" in port:
# log.debug("port matches vserial")
# return PORT_TYPE_VSERIAL
# elif "serial" in port:
# log.debug("port matches serial")
# return PORT_TYPE_SERIAL
# elif "ttyusb" in port:
# log.debug("port matches ttyusb")
# return PORT_TYPE_SERIAL
# else:
# return PORT_TYPE_UNKNOWN

# def set_protocol(self, *args, **kwargs):
# """
# Set the protocol for this device
# """
# protocol = get_kwargs(kwargs, "protocol")
# log.debug(f"Protocol {protocol}")
# if protocol is None:
# self._protocol = None
# self._protocol_class = None
# return
# protocol_id = protocol.lower()
# # Try to import the protocol module with the supplied name (may not exist)
# try:
# proto_module = importlib.import_module("mppsolar.protocols." + protocol_id, ".")
# except ModuleNotFoundError:
# log.error(f"No module found for protocol {protocol_id}")
# self._protocol = None
# self._protocol_class = None
# return
# # Find the protocol class - classname must be the same as the protocol_id
# try:
# self._protocol_class = getattr(proto_module, protocol_id)
# except AttributeError:
# log.error(f"Module {proto_module} has no attribute {protocol_id}")
# self._protocol = None
# self._protocol_class = None
# return
# # Instantiate the class
# # TODO: fix protocol instantiate
# self._protocol = self._protocol_class(
# "init_var", proto_keyword="value", second_keyword=123
# )

# def set_port(self, *args, **kwargs):
# port = get_kwargs(kwargs, "port")
# baud = get_kwargs(kwargs, "baud", 2400)
# porttype = get_kwargs(kwargs, "porttype")

# if porttype:
# log.info(f"Port overide - using port '{porttype}'")
# port_type = self.get_port_type(porttype)
# else:
# port_type = self.get_port_type(port)

# if port_type == PORT_TYPE_TEST:
# log.info("Using testio for communications")
# from mppsolar.inout.testio import TestIO

# self._port = TestIO(device_path=port)

# elif port_type == PORT_TYPE_USB:
# log.info("Using hidrawio for communications")
# from mppsolar.inout.hidrawio import HIDRawIO

# self._port = HIDRawIO(device_path=port)

# elif port_type == PORT_TYPE_ESP32:
# log.info("Using esp32io for communications")
# from mppsolar.inout.esp32io import ESP32IO

# self._port = ESP32IO(device_path=port)

# elif port_type == PORT_TYPE_JKBLE:
# log.info("Using jkbleio for communications")
# from mppsolar.inout.jkbleio import JkBleIO

# self._port = JkBleIO(device_path=port)

# elif port_type == PORT_TYPE_SERIAL:
# log.info("Using serialio for communications")
# from mppsolar.inout.serialio import SerialIO

# self._port = SerialIO(device_path=port, serial_baud=baud)

# elif port_type == PORT_TYPE_DALYSERIAL:
# log.info("Using dalyserialio for communications")
# from mppsolar.inout.dalyserialio import DalySerialIO

# self._port = DalySerialIO(device_path=port, serial_baud=baud)

# elif port_type == PORT_TYPE_VSERIAL:
# log.info("Using vserialio for communications")
# from mppsolar.inout.vserialio import VSerialIO

# self._port = VSerialIO(device_path=port, serial_baud=baud, records=30)

# elif port_type == PORT_TYPE_MQTT:

# mqtt_broker = get_kwargs(kwargs, "mqtt_broker", "localhost")
# # mqtt_port = get_kwargs(kwargs, "mqtt_port", 1883)
# # mqtt_user = get_kwargs(kwargs, "mqtt_user")
# # mqtt_pass = get_kwargs(kwargs, "mqtt_pass")
# log.info(f"Using mqttio for communications broker {mqtt_broker}")

# from mppsolar.inout.mqttio import MqttIO

# self._port = MqttIO(
# client_id=self._name,
# mqtt_broker=mqtt_broker,
# # mqtt_port=mqtt_port,
# # mqtt_user=mqtt_user,
# # mqtt_pass=mqtt_pass,
# )

# else:
# self._port = None

# def list_commands(self):
# # print(f"{'Parameter':<30}\t{'Value':<15} Unit")
# if self._protocol is None:
# log.error("Attempted to list commands with no protocol defined")
# return {"ERROR": ["Attempted to list commands with no protocol defined", ""]}
# result = {}
# result["_command"] = "command help"
# result[
# "_command_description"
# ] = f"List available commands for protocol {str(self._protocol._protocol_id, 'utf-8')}"
# for command in self._protocol.COMMANDS:
# if "help" in self._protocol.COMMANDS[command]:
# info = (
# self._protocol.COMMANDS[command]["description"]
# + self._protocol.COMMANDS[command]["help"]
# )
# else:
# info = self._protocol.COMMANDS[command]["description"]
# result[command] = [info, ""]
# return result

# def list_outputs(self):
# import pkgutil

# print("device list outouts")
# pkgpath = __file__
# pkgpath = pkgpath[: pkgpath.rfind("/")]
# pkgpath += "/../outputs"
# # print(pkgpath)
# result = {}
# result["_command"] = "outputs help"
# result["_command_description"] = "List available output modules"
# for _, name, _ in pkgutil.iter_modules([pkgpath]):
# # print(name)
# _module_class = importlib.import_module("mppsolar.outputs." + name, ".")
# _module = getattr(_module_class, name)
# # print(_module())
# result[name] = (str(_module()), "", "")
# # print(result)
# return result

# def run_commands(self, commands) -> dict:
# """
# Run multiple commands sequentially
# :param commands: List of commands to run, either with or without an alias.
# If an alias is provided, it will be substituted in place of cmd name in the returned dict
# Additional elements in the tuple will be passed to run_command as ordered
# Example: ['QPIWS', ...] or [('QPIWS', 'ALIAS'), ...] or [('QPIWS', 'ALIAS', True), ...] or mix and match
# :return: Dictionary of responses
# """
# responses = {}
# for i, command in enumerate(commands):
# if isinstance(command, str):
# responses[command] = self.run_command(command)
# elif isinstance(command, tuple) and len(command) > 0:
# if len(command) == 1: # Treat as string
# responses[command[0]] = self.run_command(command[0])
# elif len(command) == 2:
# responses[command[1]] = self.run_command(command[0])
# else:
# responses[command[1]] = self.run_command(command[0], *command[2:])
# else:
# responses["Command {:d}".format(i)] = {
# "ERROR": ["Unknown command format", "(Indexed from 0)"]
# }
# return responses

def run_command(self, command) -> dict:
"""
generic method for running a 'raw' command
Expand All @@ -289,8 +67,6 @@ def run_command(self, command) -> dict:

if command == "list_commands":
return self._protocol.list_commands()
if command == "list_outputs":
return self.list_outputs()
if command == "get_status":
return self.get_status()
if command == "get_settings":
Expand Down
8 changes: 5 additions & 3 deletions mppsolar/outputs/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


def list_outputs():
print("outputs list outputs")
# print("outputs list outputs")
pkgpath = __file__
pkgpath = pkgpath[: pkgpath.rfind("/")]
pkgpath += "/../outputs"
Expand All @@ -22,10 +22,12 @@ def list_outputs():
try:
_module_class = importlib.import_module("mppsolar.outputs." + name, ".")
_module = getattr(_module_class, name)
result[name] = (str(_module()), "", "")
except ModuleNotFoundError as e:
log.error(f"Error in module {name}: {e}")
# log.error(f"Error in module {name}: {e}")
result[f"{name}*"] = (f"ERROR: {e}", "", "")
# print(_module())
result[name] = (str(_module()), "", "")

# print(result)
return result

Expand Down
1 change: 0 additions & 1 deletion mppsolar/outputs/json_udp.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from . import to_json
from .baseoutput import baseoutput
from ..helpers import get_kwargs
from ..helpers import key_wanted

log = logging.getLogger("json_udp")

Expand Down
7 changes: 5 additions & 2 deletions mppsolar/protocols/jk02.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,9 @@
"help": " -- example setCellOVP3.65",
"type": "SETTER",
"response_type": "POSITIONAL",
"response": [["ack", "Command execution", {"NAK": "Failed", "ACK": "Successful"}]],
"response": [
["ack", "Command execution", {"NAK": "Failed", "ACK": "Successful"}]
],
"test_responses": [
bytes.fromhex(
"55aaeb9002b52e0d280dfa0c2e0d2f0d220d220d130d190d1d0d1d0d170d1f0d160dfb0c1f0d00000000000000000000000000000000ffff00001c0d350004029b00c600a000b300bc00cc00be00b100b4002d013d01b000a100ab00b200ad0000000000000000000000000000000000000000000000bcd1000000000000000000001e0116013c010000000000636b0c0300400d030000000000dc4d010064000000781e16000101480a000000000000000000000000070101000000980400000000260141400000000037feffff00000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080"
Expand All @@ -151,8 +153,9 @@ class jk02(jkAbstractProtocol):
JK02 - Handler for JKBMS 2 byte data communication
- e.g. ASAS = ??V
"""

def __str__(self):
return "JKBMS BLE 2 byte data communication protocol handler"
return "JK02 - JKBMS BLE 2 byte data communication protocol handler"

def __init__(self, *args, **kwargs) -> None:
super().__init__()
Expand Down
3 changes: 2 additions & 1 deletion mppsolar/protocols/jk04.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,9 @@ class jk04(jkAbstractProtocol):
JK04 - Handler for JKBMS 4 byte data communication
- e.g. 5b566240 = 3.5365V
"""

def __str__(self):
return "JKBMS BLE 4 byte data communication protocol handler"
return "JK04 - JKBMS BLE 4 byte data communication protocol handler"

def __init__(self, *args, **kwargs) -> None:
super().__init__()
Expand Down

0 comments on commit 33ff5af

Please sign in to comment.