Skip to content

Commit

Permalink
Changes to allow Python 2/3 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
markwal committed May 3, 2020
1 parent 23ba898 commit 9593128
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 28 deletions.
2 changes: 1 addition & 1 deletion GPX
Submodule GPX updated 1 files
+109 −18 src/pymodule/gpxmodule.c
9 changes: 5 additions & 4 deletions octoprint_GPX/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def serial_factory(self, comm, port, baudrate, timeout, *args, **kwargs):
try:
import glob
ports = glob.glob("/dev/serial/by-id/*MakerBot_Industries_The_Replicator*")
if ports:
if ports is not None:
port = os.path.normpath(os.path.join("/dev/serial/by-id/", os.readlink(ports[0])))
except:
# oh well, it was worth a try
Expand Down Expand Up @@ -163,7 +163,7 @@ def on_settings_save(self, data, *args, **kwargs):
self._settings.set_float(["connection_pause"], float(self._settings.get(["connection_pause"])))
except TypeError:
self._settings.set_float(["connection_pause"], 2.0)
if self.printer:
if self.printer is not None:
self.printer.refresh_ini()

# EventHandlerPlugin
Expand All @@ -173,7 +173,7 @@ def on_event(self, event, payload, *args, **kwargs):
# ten minutes to heat up the print bed; we circumvent here by telling
# the bot to stop
if event == Events.PRINT_CANCELLED:
if self.printer:
if self.printer is not None:
# jump the queue with an abort
self.printer.cancel()

Expand All @@ -183,7 +183,7 @@ def on_print_progress(self, storage, path, progress, *args, **kwargs):
# attempt to override here with OctoPrint's notion
# avoid 100% since that triggers end_build and we'll let that happen
# explicitly
if progress < 100 and self.override_progress and self.printer:
if progress < 100 and self.override_progress and self.printer is not None:
self.printer.progress(progress)

# gcode processing hook
Expand Down Expand Up @@ -459,6 +459,7 @@ def __plugin_load__():
}

__plugin_name__ = "GPX"
__plugin_pythoncompat__ = ">=2.7,<4"

from ._version import get_versions
__version__ = get_versions()['version']
Expand Down
26 changes: 18 additions & 8 deletions octoprint_GPX/gpxprinter.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@
import os
import logging
import time
import Queue
try:
import queue
except ImportError:
import Queue as queue
import re
import datetime

from octoprint.filemanager import FileDestinations

gpx = False
try:
import gpx
except:
Expand All @@ -23,14 +27,14 @@ def __init__(self, gpx_plugin, port = None, baudrate = None, timeout = 0):
self._settings = gpx_plugin._settings
self._printer = gpx_plugin._printer
self._bot_cancelled = False
if not gpx:
if gpx is None:
self._logger.warn("Unable to import gpx module")
raise ValueError("Unable to import gpx module")
self.port = port
self.baudrate = self._baudrate = baudrate
self.timeout = timeout
self._logger.info("GPXPrinter created, port: %s, baudrate: %s" % (self.port, self.baudrate))
self.outgoing = Queue.Queue()
self.outgoing = queue.Queue()
self.baudrateError = False;
data_folder = gpx_plugin.get_plugin_data_folder()
self.profile_path = os.path.join(data_folder, "gpx.ini")
Expand Down Expand Up @@ -102,6 +106,9 @@ def write(self, data):
try:
rval = len(data)
data = data.strip()
str_data = data
if not isinstance(str_data, str):
str_data = data.decode('utf-8')
if (self.baudrate != self._baudrate):
try:
self._baudrate = self.baudrate
Expand All @@ -116,7 +123,7 @@ def write(self, data):
# look for a line number
# line number means OctoPrint is streaming gcode at us (gpx.ini flavor)
# no line number means OctoPrint is generating the gcode (reprap flavor)
match = self._regex_linenumber.match(data)
match = self._regex_linenumber.match(str_data)

# try to talk to the bot
try:
Expand All @@ -128,7 +135,7 @@ def write(self, data):
bo_retries = 0
while True:
try:
self._append(gpx.write("%s" % data))
self._append(gpx.write(data))
break
except gpx.BufferOverflow:
bo_retries += 1
Expand All @@ -153,7 +160,7 @@ def write(self, data):
self._bot_reports_build_cancelled()
return rval

def readline(self):
def readline_str(self):
try:
if (self.baudrateError):
if (self._baudrate != self.baudrate):
Expand All @@ -162,7 +169,7 @@ def readline(self):

try:
return self.outgoing.get_nowait()
except Queue.Empty:
except queue.Empty:
pass

if gpx.listing_files():
Expand All @@ -172,13 +179,16 @@ def readline(self):
timeout = 2 if gpx.waiting else self.timeout
try:
return self.outgoing.get(timeout=timeout)
except Queue.Empty:
except queue.Empty:
self._append(gpx.readnext())

except gpx.CancelBuild:
self._bot_reports_build_cancelled()
return '// echo: build cancelled'

def readline(self):
return self.readline_str().encode('utf-8')

def cancel(self):
self._logger.warn("Cancelling build %s", "by the printer" if self._bot_cancelled else "by OctoPrint")
if not self._bot_cancelled:
Expand Down
33 changes: 18 additions & 15 deletions octoprint_GPX/iniparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,26 @@ def read(self):
self.idx = idx = OrderedDict()
self.lines = lines = []
self.counter = 0
sectionname = None
sectionname = "None"
ini[sectionname] = {}
idx[sectionname] = OrderedDict()
with open(self.filename) as inifile:
for line in inifile:
line = line.strip()
self._logger.info(line)
lines.append(line);
m = self._regex_section.match(line)
if m:
if m is not None:
sectionname = m.group(1)
ini[sectionname] = {}
idx[sectionname] = OrderedDict()
else:
m = self._regex_name_value.match(line)
if m:
if m is not None:
itemname = m.group(1).strip()
if not itemname == 'None':
ini[sectionname][m.group(1).strip()] = m.group(3)
idx[sectionname][m.group(1).strip()] = line
ini[sectionname][itemname] = m.group(3)
idx[sectionname][itemname] = line
else:
self.counter += 1
idx[sectionname][self.counter] = line
Expand All @@ -53,13 +54,14 @@ def read(self):
# ini[section] = {}
# for (name, value) in config.items(section):
# ini[section][name] = value
self._logger.info(repr(ini))
return ini

def update(self, ini):
if not ini.items:
raise ValueError("Malformed update")
if ini.items is None:
raise ValueE("Malformed update")
for sectionname, section in ini.items():
if not section.items:
if section.items is None:
raise ValueError("Invalid section")
for option, value in section.items():
self._logger.info("option, value: %s, %s" % (option, repr(value)))
Expand All @@ -73,14 +75,15 @@ def update(self, ini):
if sectionname not in self.idx:
self.idx[sectionname] = OrderedDict()
line = self.idx[sectionname].get(option)
if value == '' or value == 'undefined' or value == 'None':
if value == '' or value == 'undefined' or value == 'None' or value is None:
self._logger.info("deleteing [{0}][{1}]".format(sectionname, option))
# means delete
if line is not None:
del self.idx[sectionname][option]
continue
if line is not None:
m = self._regex_name_value.match(line)
if m:
if m is not None:
g = m.groups("")
g = g[0:2] + (value,) + g[3:]
self.idx[sectionname][option] = "%s=%s%s%s%s" % g
Expand Down Expand Up @@ -108,13 +111,13 @@ def _write_section(self, inifile, section):

def write(self):
self._logger.info("Open %s" % self.filename)
with open(self.filename, 'wb') as inifile:
with open(self.filename, 'w') as inifile:
self._logger.info("Write %s" % self.filename)
count = 0
if None in self.idx:
count += self._write_section(inifile, self.idx[None])
for sectionname, section in self.idx.items():
if sectionname is not None:
if sectionname is not None and sectionname != 'None':
inifile.write("[%s]\n" % sectionname)
count += self._write_section(inifile, section)
if count == 0:
Expand All @@ -123,10 +126,10 @@ def write(self):

def dump(self):
for sectionname, section in self.idx.items():
if sectionname is not None:
print "[%s]" % sectionname
if sectionname is not None and sectionname != 'None':
print("[{0}]".format(sectionname))
for option, line in section.items():
print line
print(line)

def get(self, sectionname, itemname):
if sectionname in self.ini and itemname in self.ini[sectionname]:
Expand Down

0 comments on commit 9593128

Please sign in to comment.