Skip to content

Commit

Permalink
4.1.0 (#52)
Browse files Browse the repository at this point in the history
Remove API
Fix Webcam for OctoPrint 1.9.0
Consolidate cpu_info and cpu messages sent to SP servers
  • Loading branch information
jneilliii authored Mar 25, 2023
1 parent 9d748dd commit d6dfecd
Show file tree
Hide file tree
Showing 21 changed files with 2,672 additions and 2,404 deletions.
217 changes: 149 additions & 68 deletions octoprint_simplyprint/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,31 @@
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

import errno
import json
import requests
import threading
import sentry_sdk

# noinspection PyPackageRequirements
import flask
import serial
import tornado

from octoprint.events import Events
import octoprint.plugin
import octoprint.settings
from octoprint.util.commandline import CommandlineError

from octoprint_simplyprint.comm import SimplyPrintComm
from octoprint_simplyprint.local import cron
from octoprint_simplyprint.websocket import SimplyPrintWebsocket

SIMPLYPRINT_EVENTS = [
Events.PRINTER_STATE_CHANGED,
Events.TOOL_CHANGE,
Events.CONNECTING,
Events.CONNECTED,
Events.DISCONNECTING,
Events.DISCONNECTED,
Events.CLIENT_AUTHED,

Events.STARTUP,
Events.SHUTDOWN,
Expand Down Expand Up @@ -80,6 +85,29 @@
Events.FILE_REMOVED,
]

IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(
serial.SerialException,
lambda exc, logger, plugin, cb: logger == "octoprint.util.comm",
),
# KeyboardInterrupts
KeyboardInterrupt,
# IOErrors of any kind due to a full file system
(
IOError,
lambda exc, logger, plugin, cb: exc.errorgetattr(exc, "errno") # noqa: B009
and exc.errno in (getattr(errno, "ENOSPC"),), # noqa: B009
),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError,
# Tornado HTTPClientError
tornado.httpclient.HTTPClientError,
# error from windows for linux specific commands related to wifi
CommandlineError
]

class SimplyPrint(
octoprint.plugin.SettingsPlugin,
Expand All @@ -94,47 +122,97 @@ class SimplyPrint(
_files_analyzed = []

simply_print = None

host = "127.0.0.1"
port = "5000"

def initialize(self):
# Called once the plugin has been loaded by OctoPrint, all injections complete
self.simply_print = SimplyPrintComm(self)
sp_cls = SimplyPrintWebsocket
self.simply_print = sp_cls(self)

def on_startup(self, host, port):
# Initialize sentry.io for error tracking
self._initialize_sentry()
# Run startup thread and run the main loop in the background
self.simply_print.start_startup()
self.simply_print.start_main_loop()
self.simply_print.on_startup()

self.host = host
# Remember that this port is internal to OctoPrint, a proxy may exist.
self.port = port

ip = host

if port:
ip += str(port)

self._logger.info("Host is; " + str(host) + " and port is; " + str(port))
self.send_port_ip(None, ip)
if port != 5000 and port != 80 and port != 443:
self.send_port_ip(port)

# #~~ StartupPlugin mixin
def on_after_startup(self):

self._logger.info("SimplyPrint OctoPrint plugin started")

# If cron jobs don't exist, create them
if not cron.check_cron_jobs():
cron.create_cron_jobs()

# The "Startup" event is never picked up by the plugin, as the plugin is loaded AFTER startup
self.on_event("Startup", {})

def _initialize_sentry(self):
self._logger.debug("Initializing Sentry")

def _before_send(event, hint):
if "exc_info" not in hint:
# we only want exceptions
return None

handled = True
logger = event.get("logger", "")
plugin = event.get("extra", {}).get("plugin", None)
callback = event.get("extra", {}).get("callback", None)

for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True

exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(
exc, logger, plugin, callback
):
# exception ignored for logger, plugin and/or callback
return None

elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None

# if event.get("exception") and event["exception"].get("values"):
# handled = not any(
# map(
# lambda x: x.get("mechanism")
# and not x["mechanism"].get("handled", True),
# event["exception"]["values"],
# )
# )
#
# if handled:
# # error is handled, restrict further based on logger
# if logger != "" and not (
# logger.startswith("octoprint.plugins.SimplyPrint") or logger.startswith("octoprint.plugins.simplyprint")
# ):
# # we only want errors logged by our plugin's loggers
# return None

if logger.startswith("octoprint.plugins.SimplyPrint") or logger.startswith("octoprint.plugins.simplyprint"):
return event
else:
return None

sentry_sdk.init(
dsn="https://[email protected]/6611344",
traces_sample_rate=0.01,
before_send=_before_send,
release="SimplyPrint@{}".format(self._plugin_version)
)
if self._settings.get(["printer_id"]) != "":
sentry_sdk.set_user({"id": self._settings.get(["printer_id"])})

def on_shutdown(self):
if self.simply_print is not None:
# SimplyPrintComm will stop on next loop
self.simply_print.run_loop = False
self.simply_print.close()

@staticmethod
def get_settings_defaults():
Expand Down Expand Up @@ -163,9 +241,21 @@ def get_settings_defaults():
"gcode_scripts_backed_up": False,
},
"debug_logging": False,
"public_port": "80"
"public_port": "80",
# Websocket Default Settings
"websocket_ready": True,
"endpoint": "production",
"printer_token": "",
"ambient_temp": "85",
}

def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
new_printer_id = self._settings.get(["printer_id"])

if new_printer_id != "":
sentry_sdk.set_user({"id": self._settings.get(["printer_id"])})

def get_template_vars(self):
return {
"version": self._plugin_version
Expand All @@ -186,35 +276,23 @@ def get_api_commands(self):
return {
"setup": [], # Sets up SimplyPrintRPiSoftware
"uninstall": [], # Uninstalls SimplyPrintRPiSoftware
"message": ["payload"], # Inject websocket messages
}

@staticmethod
def _uninstall_sp():
# All we need to do here is remove cron jobs, nothing else
cron.remove_cron_jobs()

@staticmethod
def _install_background():
if not cron.check_cron_jobs():
cron.create_cron_jobs()

def on_api_command(self, command, data):
if command == "setup":
self._uninstall_sp()
elif command == "uninstall":
self._uninstall_sp()
if command == "message" and self.simply_print.test:
msg = json.dumps(data["payload"])
# Generally we do NOT want to access methods marked
# as private, however this is for testing only
self.simply_print._process_message(msg)
return

# Send public port to outside system
def send_port_ip(self, port=None, ip=None):
def send_port_ip(self, port=None):
self._settings.set(["public_port"], port)
self._settings.save()

def on_api_get(self, request):
import flask
import subprocess
# self.log(str(request))
# self.log(str(request.args))

if request.args is not None:
if request.args.get("install", default=None, type=None) is not None:
# Install
Expand Down Expand Up @@ -274,9 +352,14 @@ def on_event(self, event, payload):
if event in SIMPLYPRINT_EVENTS:
self.simply_print.on_event(event, payload)

# def gcode_sent(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
# if gcode and gcode == "M106":
# self._logger.info("Just sent M106: {cmd}".format(**locals()))
def gcode_sent(self, comm_instance, phase, cmd, cmd_type, gcode, *args, **kwargs):
# if gcode and gcode == "M106":
# self._logger.info("Just sent M106: {cmd}".format(**locals()))
tags = kwargs.get("tags", [])
if tags is None:
return
if "source:api" in tags or "plugin:octoprint_simplyprint" in tags:
self.simply_print.on_gcode_sent(cmd)

def gcode_received(self, comm_instance, line, *args, **kwargs):
if line.strip() not in ["echo:busy: paused for user", "echo:busy: processing", "Unknown M code: M118 simplyprint unpause", "simplyprint unpause"]:
Expand All @@ -290,24 +373,26 @@ def gcode_received(self, comm_instance, line, *args, **kwargs):
self._logger.debug("received line: echo:busy: processing, setting user_input_required False")
self.simply_print.user_input_required = False

self.simply_print.on_gcode_received(line)

return line

def process_at_command(self, comm, phase, command, parameters, tags=None, *args, **kwargs):
if command.lower() not in ["simplyprint", "pause"]:
return

url_parameters = ""
if command.lower() == "pause":
url_parameters += "&pause_message={}".format(parameters)
elif command.lower() == "simplyprint":
if parameters:
parameters_list = parameters.split(" ")
if parameters_list[0] == "layer":
url_parameters += "&layer={}".format(parameters_list[1])

if url_parameters != "":
self.simply_print.ping(url_parameters)

cmd = command.lower()
if cmd == "pause":
self.simply_print.on_pause_at_command(parameters)
elif cmd == "simplyprint":
params = parameters.strip().split(" ")
if params and params[0] == "layer":
try:
layer = int(params[1])
except Exception:
pass
else:
self.simply_print.on_layer_change(layer)
return

def get_update_information(self):
Expand Down Expand Up @@ -341,13 +426,9 @@ def get_update_information(self):


__plugin_name__ = "SimplyPrint Cloud"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_disabling_discouraged__ = """
Please uninstall SimplyPrint Cloud rather than just disable it, since it sets up some background scripts
that will continue to run if you disable it.
"""
__plugin_pythoncompat__ = ">=3.7,<4"
# Remember to bump the version in setup.py as well
__plugin_version__ = "3.1.2"
__plugin_version__ = "4.1.0rc1"


def __plugin_load__():
Expand All @@ -357,5 +438,5 @@ def __plugin_load__():
"octoprint.plugin.softwareupdate.check_config": __plugin_implementation__.get_update_information,
"octoprint.comm.protocol.atcommand.sending": __plugin_implementation__.process_at_command,
"octoprint.comm.protocol.gcode.received": __plugin_implementation__.gcode_received,
# "octoprint.comm.protocol.gcode.sent": __plugin_implementation__.gcode_sent
"octoprint.comm.protocol.gcode.sent": __plugin_implementation__.gcode_sent
}
2 changes: 1 addition & 1 deletion octoprint_simplyprint/comm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

from .simplyprint import SimplyPrintComm


2 changes: 2 additions & 0 deletions octoprint_simplyprint/comm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,5 @@
API_VERSION = "0.0.3"
WEBCAM_SNAPSHOT_URL = "https://livestream.simplyprint.io/"
SIMPLYPRINT_PLUGIN_INSTALL_URL = "https://github.com/SimplyPrint/OctoPrint-SimplyPrint/archive/master.zip"
WS_CHECK_ENDPOINT = f"https://api.simplyprint.io/ws_check.php"
TEST_WS_CHECK_ENDPOINT = f"https://testapi.simplyprint.io/ws_check.php"
1 change: 0 additions & 1 deletion octoprint_simplyprint/comm/get_ip.sh

This file was deleted.

Loading

0 comments on commit d6dfecd

Please sign in to comment.