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

View File

@ -4,7 +4,7 @@ import os, time, sys
import io import io
import flask import flask
from octoprint_klipper import util, logger from octoprint_klipper.util import *
from flask_babel import gettext from flask_babel import gettext
from shutil import copy, copyfile from shutil import copy, copyfile
@ -36,7 +36,7 @@ def list_cfg_files(self, path):
) )
cfg_path = os.path.join(cfg_path, "*.cfg") cfg_path = os.path.join(cfg_path, "*.cfg")
cfg_files = glob.glob(cfg_path) 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: for f in cfg_files:
filesize = os.path.getsize(f) filesize = os.path.getsize(f)
@ -52,7 +52,7 @@ def list_cfg_files(self, path):
mdate= time.strftime("%d.%m.%Y %H:%M", filemdate), mdate= time.strftime("%d.%m.%Y %H:%M", filemdate),
url= url, 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 return files
@ -75,13 +75,13 @@ def get_cfg(self, file):
self._settings.get(["configuration", "configpath"]) self._settings.get(["configuration", "configpath"])
) )
file = os.path.join(cfg_path, self._settings.get(["configuration", "baseconfig"])) file = os.path.join(cfg_path, self._settings.get(["configuration", "baseconfig"]))
if util.file_exist(self, file): if file_exist(self, file):
logger.log_debug(self, "get_cfg_files Path: " + file) log_debug(self, "get_cfg_files Path: " + file)
try: try:
with io.open(file, "r", encoding='utf-8') as f: with io.open(file, "r", encoding='utf-8') as f:
response['config'] = f.read() response['config'] = f.read()
except IOError as Err: except IOError as Err:
logger.log_error( log_error(
self, self,
gettext("Error: Klipper config file not found at:") gettext("Error: Klipper config file not found at:")
+ " {}".format(file) + " {}".format(file)
@ -91,7 +91,7 @@ def get_cfg(self, file):
response['text'] = Err response['text'] = Err
return response return response
except UnicodeDecodeError as Err: except UnicodeDecodeError as Err:
logger.log_error( log_error(
self, self,
gettext("Decode Error:") gettext("Decode Error:")
+"\n" +"\n"
@ -121,7 +121,7 @@ def save_cfg(self, content, filename):
bool: True if the configuration file was saved successfully. Otherwise False bool: True if the configuration file was saved successfully. Otherwise False
""" """
logger.log_debug( log_debug(
self, self,
"Save klipper config" "Save klipper config"
) )
@ -135,15 +135,15 @@ def save_cfg(self, content, filename):
filepath = os.path.join(configpath, 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: try:
with io.open(filepath, "w", encoding='utf-8') as f: with io.open(filepath, "w", encoding='utf-8') as f:
f.write(content) f.write(content)
except IOError: 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 return False
else: else:
logger.log_debug(self, "Written Klipper config to {}".format(filepath)) log_debug(self, "Written Klipper config to {}".format(filepath))
return True return True
finally: finally:
copy_cfg_to_backup(self, filepath) copy_cfg_to_backup(self, filepath)
@ -168,13 +168,13 @@ def check_cfg_ok(self, data):
dataToValidated.read_string(data) dataToValidated.read_string(data)
except configparser.Error as error: except configparser.Error as error:
show_error_message(self, error) show_error_message(self, error)
logger.log_debug(self, 'check_cfg: NOK!') log_debug(self, 'check_cfg: NOK!')
return False return False
else: else:
if not is_float_ok(self, dataToValidated): if not is_float_ok(self, dataToValidated):
logger.log_debug(self, "check_cfg: NOK!") log_debug(self, "check_cfg: NOK!")
return False return False
logger.log_debug(self, "check_cfg: OK") log_debug(self, "check_cfg: OK")
return True return True
@ -187,7 +187,7 @@ def show_error_message(self, error):
else: else:
error.message = error.message.replace('file:', 'Klipper Configuration', 1) error.message = error.message.replace('file:', 'Klipper Configuration', 1)
error.message = error.message.replace("'", '', 2) error.message = error.message.replace("'", '', 2)
logger.log_error( log_error(
self, self,
('Error: Invalid Klipper config file:\n' + '{}'.format(str(error))), ('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): if dataToValidated.has_option(y, x):
a_float = dataToValidated.getfloat(y, x) a_float = dataToValidated.getfloat(y, x)
except ValueError as error: except ValueError as error:
logger.log_error( log_error(
self, self,
"Error: Invalid Value for <b>" + x + "</b> in Section: <b>" + y + "</b>\n" "Error: Invalid Value for <b>" + x + "</b> in Section: <b>" + y + "</b>\n"
+ "{}".format(str(error)) + "{}".format(str(error))
) )
util.send_message( send_message(
self, self,
type = "PopUp", type = "PopUp",
subtype = "warning", subtype = "warning",
@ -245,13 +245,13 @@ def copy_cfg(self, file, dst):
try: try:
copy(file, dst) copy(file, dst)
except IOError: except IOError:
logger.log_error( log_error(
self, self,
"Error: Klipper config file not found at: {}".format(file) "Error: Klipper config file not found at: {}".format(file)
) )
return False return False
else: else:
logger.log_debug( log_debug(
self, self,
"File copied: " "File copied: "
+ file + file
@ -279,23 +279,23 @@ def copy_cfg_to_backup(self, src):
try: try:
os.mkdir(cfg_path) os.mkdir(cfg_path)
except OSError: 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 return False
else: 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) 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: if src == dst:
return False return False
try: try:
copyfile(src, dst) copyfile(src, dst)
except IOError: except IOError:
logger.log_error( log_error(
self, self,
"Error: Couldn't copy Klipper config file to {}".format(dst) "Error: Couldn't copy Klipper config file to {}".format(dst)
) )
return False return False
else: else:
logger.log_debug(self, "CfgBackup " + dst + " written") log_debug(self, "CfgBackup " + dst + " written")
return True 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 flask
import optparse, datetime import optparse, datetime
from .. import logger from octoprint_klipper.util import log_error
class KlipperLogAnalyzer(): class KlipperLogAnalyzer():
MAXBANDWIDTH=25000. MAXBANDWIDTH=25000.
@ -82,7 +82,7 @@ class KlipperLogAnalyzer():
out.append(keyparts) out.append(keyparts)
f.close() f.close()
except IOError: 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") print("Couldn't open log file")
return out 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): def migrate_old_settings(self, settings):
''' '''
@ -29,10 +59,10 @@ def migrate_settings(self, settings, old, new, new2=""):
""" '''''' """ ''''''
if settings.has(old): if settings.has(old):
if new2 != "": 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)) settings.set([new, new2], settings.get(old))
else: 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.set([new], settings.get(old))
settings.remove(old) settings.remove(old)
@ -48,7 +78,7 @@ def migrate_settings_configuration(self, settings, new, old):
""" """
if settings.has(["configuration", 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.set(["configuration", new], settings.get(["configuration", old]))
settings.remove(["configuration", old]) settings.remove(["configuration", old])
@ -68,7 +98,7 @@ def file_exist(self, filepath):
''' '''
from os import path from os import path
if not path.isfile(filepath): 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( send_message(
self, self,
type = "PopUp", type = "PopUp",