🐛 fix python2 circular imports

This commit is contained in:
thelastWallE 2021-11-21 02:41:27 +01:00
parent 683e074943
commit df0d01907b
5 changed files with 92 additions and 94 deletions

View File

@ -25,7 +25,8 @@ import sys
from octoprint.server import NO_CONTENT
from octoprint.util import is_hidden_path
from octoprint.util import get_formatted_size
from octoprint_klipper import util, cfgUtils, logger
from octoprint_klipper import cfgUtils
from octoprint_klipper.util import *
from octoprint.util.comm import parse_firmware_line
from octoprint.access.permissions import Permissions, ADMIN_GROUP
from .modules import KlipperLogAnalyzer
@ -78,7 +79,7 @@ class KlipperPlugin(
self._settings.global_set(
["serial", "additionalPorts"], additional_ports)
self._settings.save()
logger.log_info(
log_info(
self,
"Added klipper serial port {} to list of additional ports.".format(klipper_port)
)
@ -185,7 +186,7 @@ class KlipperPlugin(
def on_settings_migrate(self, target, current):
settings = self._settings
if current is None:
util.migrate_old_settings(settings)
migrate_old_settings(settings)
if current is not None and current < 3:
self.migrate_settings_3(settings)
@ -194,7 +195,7 @@ class KlipperPlugin(
self.migrate_settings_4(settings)
def migrate_settings_3(self, settings):
util.migrate_settings_configuration(
migrate_settings_configuration(
settings,
"shortStatus_navbar",
"navbar",
@ -204,8 +205,8 @@ class KlipperPlugin(
if settings.has(["configuration", "configpath"]):
cfg_path = settings.get(["configuration", "configpath"])
new_cfg_path, baseconfig = os.path.split(cfg_path)
logger.log_info(self, "migrate setting for 'configuration/config_path': " + cfg_path + " -> " + new_cfg_path)
logger.log_info(self, "migrate setting for 'configuration/baseconfig': printer.cfg -> " + baseconfig)
log_info(self, "migrate setting for 'configuration/config_path': " + cfg_path + " -> " + new_cfg_path)
log_info(self, "migrate setting for 'configuration/baseconfig': printer.cfg -> " + baseconfig)
settings.set(["configuration", "config_path"], new_cfg_path)
settings.set(["configuration", "baseconfig"], baseconfig)
settings.remove(["configuration", "configpath"])
@ -213,16 +214,16 @@ class KlipperPlugin(
settings.has(["configuration", "reload_command"])
and settings.get(["configuration", "reload_command"]) == "manually"
):
logger.log_info(self, "migrate setting for 'configuration/restart_onsave': True -> False")
log_info(self, "migrate setting for 'configuration/restart_onsave': True -> False")
settings.set(["configuration", "restart_onsave"], False)
settings.remove(["configuration", "reload_command"])
if settings.has(["config"]):
logger.log_info(self, "remove old setting for 'config'")
log_info(self, "remove old setting for 'config'")
settings.remove(["config"])
if settings.has(["configuration", "old_config"]):
logger.log_info(self, "remove old setting for 'configuration/old_config'")
log_info(self, "remove old setting for 'configuration/old_config'")
settings.remove(["configuration", "old_config"])
@ -316,54 +317,54 @@ class KlipperPlugin(
def on_event(self, event, payload):
if event == "UserLoggedIn":
logger.log_info(self, "Klipper: Standby")
log_info(self, "Klipper: Standby")
if event == "Connecting":
logger.log_info(self, "Klipper: Connecting ...")
log_info(self, "Klipper: Connecting ...")
elif event == "Connected":
logger.log_info(self, "Klipper: Connected to host")
logger.log_info(
log_info(self, "Klipper: Connected to host")
log_info(
self,
"Connected to host via {} @{}bps".format(payload["port"], payload["baudrate"]))
elif event == "Disconnected":
logger.log_info(self, "Klipper: Disconnected from host")
log_info(self, "Klipper: Disconnected from host")
elif event == "Error":
logger.log_error(self, payload["error"])
log_error(self, payload["error"])
def processAtCommand(self, comm_instance, phase, command, parameters, tags=None, *args, **kwargs):
if command != "SWITCHCONFIG":
return
config = parameters
logger.log_info(self, "SWITCHCONFIG detected config:{}".format(config))
log_info(self, "SWITCHCONFIG detected config:{}".format(config))
return None
# -- GCODE Hook
def process_sent_GCODE(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
if cmd == "SAVE_CONFIG":
logger.log_info(self, "SAVE_CONFIG detected")
util.send_message(self, type = "reload", subtype = "config")
log_info(self, "SAVE_CONFIG detected")
send_message(self, type = "reload", subtype = "config")
def on_parse_gcode(self, comm, line, *args, **kwargs):
if "FIRMWARE_VERSION" in line:
printerInfo = parse_firmware_line(line)
if "FIRMWARE_VERSION" in printerInfo:
logger.log_info(self, "Firmware version: {}".format(
log_info(self, "Firmware version: {}".format(
printerInfo["FIRMWARE_VERSION"]))
elif "// probe" in line or "// Failed to verify BLTouch" in line:
msg = line.strip('/')
logger.log_info(self, msg)
log_info(self, msg)
self.write_parsing_response_buffer()
elif "//" in line:
# add lines with // to a buffer
self._message = self._message + line.strip('/')
if not self._parsing_response:
util.update_status(self, "info", self._message)
update_status(self, "info", self._message)
self._parsing_response = True
elif "!!" in line:
msg = line.strip('!')
logger.log_error(self, msg)
log_error(self, msg)
self.write_parsing_response_buffer()
else:
self.write_parsing_response_buffer()
@ -373,7 +374,7 @@ class KlipperPlugin(
# write buffer with // lines after a gcode response without //
if self._parsing_response:
self._parsing_response = False
logger.log_info(self, self._message)
log_info(self, self._message)
self._message = ""
def get_api_commands(self):
@ -388,7 +389,7 @@ class KlipperPlugin(
logpath = os.path.expanduser(
self._settings.get(["configuration", "logpath"])
)
if util.file_exist(self, logpath):
if file_exist(self, logpath):
for f in glob.glob(self._settings.get(["configuration", "logpath"]) + "*"):
filesize = os.path.getsize(f)
filemdate = time.strftime("%d.%m.%Y %H:%M",time.localtime(os.path.getctime(f)))
@ -546,7 +547,7 @@ class KlipperPlugin(
Filecontent = data.get("DataToSave", [])
saved = cfgUtils.save_cfg(self, Filecontent, filename)
if saved == True:
util.send_message(self, type = "reload", subtype = "configlist")
send_message(self, type = "reload", subtype = "configlist")
return flask.jsonify(saved = saved)
# restart klipper
@ -560,7 +561,7 @@ class KlipperPlugin(
# Restart klippy to reload config
self._printer.commands(reload_command)
logger.log_info(self, "Restarting Klipper.")
log_info(self, "Restarting Klipper.")
return flask.jsonify(command = reload_command)
# APIs end

View File

@ -4,7 +4,7 @@ import os, time, sys
import io
import flask
from octoprint_klipper import util, logger
from octoprint_klipper.util import *
from flask_babel import gettext
from shutil import copy, copyfile
@ -36,7 +36,7 @@ def list_cfg_files(self, path):
)
cfg_path = os.path.join(cfg_path, "*.cfg")
cfg_files = glob.glob(cfg_path)
logger.log_debug(self, "list_cfg_files Path: " + cfg_path)
log_debug(self, "list_cfg_files Path: " + cfg_path)
for f in cfg_files:
filesize = os.path.getsize(f)
@ -52,7 +52,7 @@ def list_cfg_files(self, path):
mdate= time.strftime("%d.%m.%Y %H:%M", filemdate),
url= url,
))
logger.log_debug(self, "list_cfg_files " + str(len(files)) + ": " + f)
log_debug(self, "list_cfg_files " + str(len(files)) + ": " + f)
return files
@ -75,13 +75,13 @@ def get_cfg(self, file):
self._settings.get(["configuration", "configpath"])
)
file = os.path.join(cfg_path, self._settings.get(["configuration", "baseconfig"]))
if util.file_exist(self, file):
logger.log_debug(self, "get_cfg_files Path: " + file)
if file_exist(self, file):
log_debug(self, "get_cfg_files Path: " + file)
try:
with io.open(file, "r", encoding='utf-8') as f:
response['config'] = f.read()
except IOError as Err:
logger.log_error(
log_error(
self,
gettext("Error: Klipper config file not found at:")
+ " {}".format(file)
@ -91,7 +91,7 @@ def get_cfg(self, file):
response['text'] = Err
return response
except UnicodeDecodeError as Err:
logger.log_error(
log_error(
self,
gettext("Decode Error:")
+"\n"
@ -121,7 +121,7 @@ def save_cfg(self, content, filename):
bool: True if the configuration file was saved successfully. Otherwise False
"""
logger.log_debug(
log_debug(
self,
"Save klipper config"
)
@ -135,15 +135,15 @@ def save_cfg(self, content, filename):
filepath = os.path.join(configpath, filename)
logger.log_debug(self, "Writing Klipper config to {}".format(filepath))
log_debug(self, "Writing Klipper config to {}".format(filepath))
try:
with io.open(filepath, "w", encoding='utf-8') as f:
f.write(content)
except IOError:
logger.log_error(self, "Error: Couldn't open Klipper config file: {}".format(filepath))
log_error(self, "Error: Couldn't open Klipper config file: {}".format(filepath))
return False
else:
logger.log_debug(self, "Written Klipper config to {}".format(filepath))
log_debug(self, "Written Klipper config to {}".format(filepath))
return True
finally:
copy_cfg_to_backup(self, filepath)
@ -168,13 +168,13 @@ def check_cfg_ok(self, data):
dataToValidated.read_string(data)
except configparser.Error as error:
show_error_message(self, error)
logger.log_debug(self, 'check_cfg: NOK!')
log_debug(self, 'check_cfg: NOK!')
return False
else:
if not is_float_ok(self, dataToValidated):
logger.log_debug(self, "check_cfg: NOK!")
log_debug(self, "check_cfg: NOK!")
return False
logger.log_debug(self, "check_cfg: OK")
log_debug(self, "check_cfg: OK")
return True
@ -187,7 +187,7 @@ def show_error_message(self, error):
else:
error.message = error.message.replace('file:', 'Klipper Configuration', 1)
error.message = error.message.replace("'", '', 2)
logger.log_error(
log_error(
self,
('Error: Invalid Klipper config file:\n' + '{}'.format(str(error))),
)
@ -211,12 +211,12 @@ def is_float_ok(self, dataToValidated):
if dataToValidated.has_option(y, x):
a_float = dataToValidated.getfloat(y, x)
except ValueError as error:
logger.log_error(
log_error(
self,
"Error: Invalid Value for <b>" + x + "</b> in Section: <b>" + y + "</b>\n"
+ "{}".format(str(error))
)
util.send_message(
send_message(
self,
type = "PopUp",
subtype = "warning",
@ -245,13 +245,13 @@ def copy_cfg(self, file, dst):
try:
copy(file, dst)
except IOError:
logger.log_error(
log_error(
self,
"Error: Klipper config file not found at: {}".format(file)
)
return False
else:
logger.log_debug(
log_debug(
self,
"File copied: "
+ file
@ -279,23 +279,23 @@ def copy_cfg_to_backup(self, src):
try:
os.mkdir(cfg_path)
except OSError:
logger.log_error(self, "Error: Creation of the backup directory {} failed".format(cfg_path))
log_error(self, "Error: Creation of the backup directory {} failed".format(cfg_path))
return False
else:
logger.log_debug(self, "Directory {} created".format(cfg_path))
log_debug(self, "Directory {} created".format(cfg_path))
dst = os.path.join(cfg_path, filename)
logger.log_debug(self, "copy_cfg_to_backup:" + src + " to " + dst)
log_debug(self, "copy_cfg_to_backup:" + src + " to " + dst)
if src == dst:
return False
try:
copyfile(src, dst)
except IOError:
logger.log_error(
log_error(
self,
"Error: Couldn't copy Klipper config file to {}".format(dst)
)
return False
else:
logger.log_debug(self, "CfgBackup " + dst + " written")
log_debug(self, "CfgBackup " + dst + " written")
return True

View File

@ -1,33 +0,0 @@
from octoprint_klipper import util
def log_info(self, message):
self._octoklipper_logger.info(message)
util.send_message(
self,
type = "log",
subtype = "info",
title = message,
payload = message
)
def log_debug(self, message):
self._octoklipper_logger.debug(message)
self._logger.info(message)
util.send_message(
self,
type = "console",
subtype = "debug",
title = message,
payload = message
)
def log_error(self, error):
self._octoklipper_logger.error(error)
self._logger.error(error)
util.send_message(
self,
type = "log",
subtype = "error",
title = error,
payload = error
)

View File

@ -15,7 +15,7 @@
import flask
import optparse, datetime
from .. import logger
from octoprint_klipper.util import log_error
class KlipperLogAnalyzer():
MAXBANDWIDTH=25000.
@ -82,7 +82,7 @@ class KlipperLogAnalyzer():
out.append(keyparts)
f.close()
except IOError:
logger.log_error(self, "Couldn't open log file: {}".format(logname))
log_error(self, "Couldn't open log file: {}".format(logname))
print("Couldn't open log file")
return out

View File

@ -1,4 +1,34 @@
from octoprint_klipper import logger
def log_info(self, message):
self._octoklipper_logger.info(message)
send_message(
self,
type = "log",
subtype = "info",
title = message,
payload = message
)
def log_debug(self, message):
self._octoklipper_logger.debug(message)
self._logger.info(message)
send_message(
self,
type = "console",
subtype = "debug",
title = message,
payload = message
)
def log_error(self, error):
self._octoklipper_logger.error(error)
self._logger.error(error)
send_message(
self,
type = "log",
subtype = "error",
title = error,
payload = error
)
def migrate_old_settings(self, settings):
'''
@ -29,10 +59,10 @@ def migrate_settings(self, settings, old, new, new2=""):
""" ''''''
if settings.has(old):
if new2 != "":
logger.log_info(self, "migrate setting for '" + old + "' -> '" + new + "/" + new2 + "'")
log_info(self, "migrate setting for '" + old + "' -> '" + new + "/" + new2 + "'")
settings.set([new, new2], settings.get(old))
else:
logger.log_info(self, "migrate setting for '" + old + "' -> '" + new + "'")
log_info(self, "migrate setting for '" + old + "' -> '" + new + "'")
settings.set([new], settings.get(old))
settings.remove(old)
@ -48,7 +78,7 @@ def migrate_settings_configuration(self, settings, new, old):
"""
if settings.has(["configuration", old]):
logger.log_info(self, "migrate setting for 'configuration/" + old + "' -> 'configuration/" + new + "'")
log_info(self, "migrate setting for 'configuration/" + old + "' -> 'configuration/" + new + "'")
settings.set(["configuration", new], settings.get(["configuration", old]))
settings.remove(["configuration", old])
@ -68,7 +98,7 @@ def file_exist(self, filepath):
'''
from os import path
if not path.isfile(filepath):
logger.log_debug(self, "File: <br />" + filepath + "<br /> does not exist!")
log_debug(self, "File: <br />" + filepath + "<br /> does not exist!")
send_message(
self,
type = "PopUp",