Commit 6cce62b2 authored by Guillaume Seguin's avatar Guillaume Seguin

Merge branch 'master' of github.com:kliment/Printrun

parents 16934b24 598d39e2
...@@ -36,12 +36,11 @@ from .utils import install_locale, run_command, get_command_output, \ ...@@ -36,12 +36,11 @@ from .utils import install_locale, run_command, get_command_output, \
format_time, format_duration, RemainingTimeEstimator, \ format_time, format_duration, RemainingTimeEstimator, \
get_home_pos, parse_build_dimensions, parse_temperature_report get_home_pos, parse_build_dimensions, parse_temperature_report
install_locale('pronterface') install_locale('pronterface')
from printrun.power import powerset_print_start, powerset_print_stop from .settings import Settings, BuildDimensionsSetting
from .power import powerset_print_start, powerset_print_stop
from printrun import gcoder from printrun import gcoder
from .rpc import ProntRPC from .rpc import ProntRPC
from functools import wraps
if os.name == "nt": if os.name == "nt":
try: try:
import _winreg import _winreg
...@@ -59,355 +58,11 @@ except: ...@@ -59,355 +58,11 @@ except:
tempreading_exp = re.compile("(^T:| T:)") tempreading_exp = re.compile("(^T:| T:)")
def dosify(name): REPORT_NONE = 0
return os.path.split(name)[1].split(".")[0][:8] + ".g" REPORT_POS = 1
REPORT_TEMP = 2
def setting_add_tooltip(func):
@wraps(func)
def decorator(self, *args, **kwargs):
widget = func(self, *args, **kwargs)
helptxt = self.help or ""
sep, deftxt = "", ""
if len(helptxt):
sep = "\n"
if helptxt.find("\n") >= 0:
sep = "\n\n"
if self.default is not "":
deftxt = _("Default: ")
resethelp = _("(Control-doubleclick to reset to default value)")
if len(repr(self.default)) > 10:
deftxt += "\n " + repr(self.default).strip("'") + "\n" + resethelp
else:
deftxt += repr(self.default) + " " + resethelp
helptxt += sep + deftxt
if len(helptxt):
widget.SetToolTipString(helptxt)
return widget
return decorator
class Setting(object):
DEFAULT_GROUP = "Printer"
hidden = False
def __init__(self, name, default, label = None, help = None, group = None):
self.name = name
self.default = default
self._value = default
self.label = label
self.help = help
self.group = group if group else Setting.DEFAULT_GROUP
def _get_value(self):
return self._value
def _set_value(self, value):
raise NotImplementedError
value = property(_get_value, _set_value)
def set_default(self, e):
import wx
if e.CmdDown() and e.ButtonDClick() and self.default is not "":
confirmation = wx.MessageDialog(None, _("Are you sure you want to reset the setting to the default value: {0!r} ?").format(self.default), _("Confirm set default"), wx.ICON_EXCLAMATION | wx.YES_NO | wx.NO_DEFAULT)
if confirmation.ShowModal() == wx.ID_YES:
self._set_value(self.default)
else:
e.Skip()
@setting_add_tooltip
def get_label(self, parent):
import wx
widget = wx.StaticText(parent, -1, self.label or self.name)
widget.set_default = self.set_default
return widget
@setting_add_tooltip
def get_widget(self, parent):
return self.get_specific_widget(parent)
def get_specific_widget(self, parent):
raise NotImplementedError
def update(self):
raise NotImplementedError
def __str__(self):
return self.name
def __repr__(self):
return self.name
class HiddenSetting(Setting):
hidden = True
def _set_value(self, value):
self._value = value
value = property(Setting._get_value, _set_value)
class wxSetting(Setting):
widget = None
def _set_value(self, value):
self._value = value
if self.widget:
self.widget.SetValue(value)
value = property(Setting._get_value, _set_value)
def update(self):
self.value = self.widget.GetValue()
class StringSetting(wxSetting):
def get_specific_widget(self, parent):
import wx
self.widget = wx.TextCtrl(parent, -1, str(self.value))
return self.widget
class ComboSetting(wxSetting):
def __init__(self, name, default, choices, label = None, help = None, group = None):
super(ComboSetting, self).__init__(name, default, label, help, group)
self.choices = choices
def get_specific_widget(self, parent):
import wx
self.widget = wx.ComboBox(parent, -1, str(self.value), choices = self.choices, style = wx.CB_DROPDOWN)
return self.widget
class SpinSetting(wxSetting):
def __init__(self, name, default, min, max, label = None, help = None, group = None, increment = 0.1):
super(SpinSetting, self).__init__(name, default, label, help, group)
self.min = min
self.max = max
self.increment = increment
def get_specific_widget(self, parent):
from wx.lib.agw.floatspin import FloatSpin
self.widget = FloatSpin(parent, -1, min_val = self.min, max_val = self.max, digits = 0)
self.widget.SetValue(self.value)
orig = self.widget.GetValue
self.widget.GetValue = lambda: int(orig())
return self.widget
class FloatSpinSetting(SpinSetting):
def get_specific_widget(self, parent):
from wx.lib.agw.floatspin import FloatSpin
self.widget = FloatSpin(parent, -1, value = self.value, min_val = self.min, max_val = self.max, increment = self.increment, digits = 2)
return self.widget
class BooleanSetting(wxSetting):
def _get_value(self):
return bool(self._value)
def _set_value(self, value):
self._value = value
if self.widget:
self.widget.SetValue(bool(value))
value = property(_get_value, _set_value)
def get_specific_widget(self, parent):
import wx
self.widget = wx.CheckBox(parent, -1)
self.widget.SetValue(bool(self.value))
return self.widget
class StaticTextSetting(wxSetting):
def __init__(self, name, label = " ", text = "", help = None, group = None):
super(StaticTextSetting, self).__init__(name, "", label, help, group)
self.text = text
def update(self):
pass
def _get_value(self):
return ""
def _set_value(self, value):
pass
def get_specific_widget(self, parent): class Status(object):
import wx
self.widget = wx.StaticText(parent, -1, self.text)
return self.widget
class BuildDimensionsSetting(wxSetting):
widgets = None
def _set_value(self, value):
self._value = value
if self.widgets:
self._set_widgets_values(value)
value = property(wxSetting._get_value, _set_value)
def _set_widgets_values(self, value):
build_dimensions_list = parse_build_dimensions(value)
for i in range(len(self.widgets)):
self.widgets[i].SetValue(build_dimensions_list[i])
def get_widget(self, parent):
from wx.lib.agw.floatspin import FloatSpin
import wx
build_dimensions = parse_build_dimensions(self.value)
self.widgets = []
w = lambda val, m, M: self.widgets.append(FloatSpin(parent, -1, value = val, min_val = m, max_val = M, digits = 2))
addlabel = lambda name, pos: self.widget.Add(wx.StaticText(parent, -1, name), pos = pos, flag = wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border = 5)
addwidget = lambda *pos: self.widget.Add(self.widgets[-1], pos = pos, flag = wx.RIGHT, border = 5)
self.widget = wx.GridBagSizer()
addlabel(_("Width"), (0, 0))
w(build_dimensions[0], 0, 2000)
addwidget(0, 1)
addlabel(_("Depth"), (0, 2))
w(build_dimensions[1], 0, 2000)
addwidget(0, 3)
addlabel(_("Height"), (0, 4))
w(build_dimensions[2], 0, 2000)
addwidget(0, 5)
addlabel(_("X offset"), (1, 0))
w(build_dimensions[3], -2000, 2000)
addwidget(1, 1)
addlabel(_("Y offset"), (1, 2))
w(build_dimensions[4], -2000, 2000)
addwidget(1, 3)
addlabel(_("Z offset"), (1, 4))
w(build_dimensions[5], -2000, 2000)
addwidget(1, 5)
addlabel(_("X home pos."), (2, 0))
w(build_dimensions[6], -2000, 2000)
self.widget.Add(self.widgets[-1], pos = (2, 1))
addlabel(_("Y home pos."), (2, 2))
w(build_dimensions[7], -2000, 2000)
self.widget.Add(self.widgets[-1], pos = (2, 3))
addlabel(_("Z home pos."), (2, 4))
w(build_dimensions[8], -2000, 2000)
self.widget.Add(self.widgets[-1], pos = (2, 5))
return self.widget
def update(self):
values = [float(w.GetValue()) for w in self.widgets]
self.value = "%.02fx%.02fx%.02f%+.02f%+.02f%+.02f%+.02f%+.02f%+.02f" % tuple(values)
class Settings(object):
def __baudrate_list(self): return ["2400", "9600", "19200", "38400", "57600", "115200", "250000"]
def __init__(self, root):
# defaults here.
# the initial value determines the type
self._add(StringSetting("port", "", _("Serial port"), _("Port used to communicate with printer")))
self._add(ComboSetting("baudrate", 115200, self.__baudrate_list(), _("Baud rate"), _("Communications Speed")))
self._add(BooleanSetting("tcp_streaming_mode", False, _("TCP streaming mode"), _("When using a TCP connection to the printer, the streaming mode will not wait for acks from the printer to send new commands. This will break things such as ETA prediction, but can result in smoother prints.")), root.update_tcp_streaming_mode)
self._add(BooleanSetting("rpc_server", True, _("RPC server"), _("Enable RPC server to allow remotely querying print status")), root.update_rpc_server)
self._add(SpinSetting("bedtemp_abs", 110, 0, 400, _("Bed temperature for ABS"), _("Heated Build Platform temp for ABS (deg C)"), "Printer"))
self._add(SpinSetting("bedtemp_pla", 60, 0, 400, _("Bed temperature for PLA"), _("Heated Build Platform temp for PLA (deg C)"), "Printer"))
self._add(SpinSetting("temperature_abs", 230, 0, 400, _("Extruder temperature for ABS"), _("Extruder temp for ABS (deg C)"), "Printer"))
self._add(SpinSetting("temperature_pla", 185, 0, 400, _("Extruder temperature for PLA"), _("Extruder temp for PLA (deg C)"), "Printer"))
self._add(SpinSetting("xy_feedrate", 3000, 0, 50000, _("X && Y manual feedrate"), _("Feedrate for Control Panel Moves in X and Y (mm/min)"), "Printer"))
self._add(SpinSetting("z_feedrate", 100, 0, 50000, _("Z manual feedrate"), _("Feedrate for Control Panel Moves in Z (mm/min)"), "Printer"))
self._add(SpinSetting("e_feedrate", 100, 0, 1000, _("E manual feedrate"), _("Feedrate for Control Panel Moves in Extrusions (mm/min)"), "Printer"))
self._add(StringSetting("slicecommand", "python skeinforge/skeinforge_application/skeinforge_utilities/skeinforge_craft.py $s", _("Slice command"), _("Slice command"), "External"))
self._add(StringSetting("sliceoptscommand", "python skeinforge/skeinforge_application/skeinforge.py", _("Slicer options command"), _("Slice settings command"), "External"))
self._add(StringSetting("final_command", "", _("Final command"), _("Executable to run when the print is finished"), "External"))
self._add(StringSetting("error_command", "", _("Error command"), _("Executable to run when an error occurs"), "External"))
self._add(HiddenSetting("project_offset_x", 0.0))
self._add(HiddenSetting("project_offset_y", 0.0))
self._add(HiddenSetting("project_interval", 2.0))
self._add(HiddenSetting("project_pause", 2.5))
self._add(HiddenSetting("project_scale", 1.0))
self._add(HiddenSetting("project_x", 1024))
self._add(HiddenSetting("project_y", 768))
self._add(HiddenSetting("project_projected_x", 150.0))
self._add(HiddenSetting("project_direction", "Top Down"))
self._add(HiddenSetting("project_overshoot", 3.0))
self._add(HiddenSetting("project_z_axis_rate", 200))
self._add(HiddenSetting("project_layer", 0.1))
self._add(HiddenSetting("project_prelift_gcode", ""))
self._add(HiddenSetting("project_postlift_gcode", ""))
self._add(HiddenSetting("pause_between_prints", True))
self._add(HiddenSetting("default_extrusion", 5.0))
self._add(HiddenSetting("last_extrusion", 5.0))
self._add(HiddenSetting("total_filament_used", 0.0))
_settings = []
def __setattr__(self, name, value):
if name.startswith("_"):
return object.__setattr__(self, name, value)
if isinstance(value, Setting):
if not value.hidden:
self._settings.append(value)
object.__setattr__(self, "_" + name, value)
elif hasattr(self, "_" + name):
getattr(self, "_" + name).value = value
else:
setattr(self, name, StringSetting(name = name, default = value))
def __getattr__(self, name):
if name.startswith("_"):
return object.__getattribute__(self, name)
return getattr(self, "_" + name).value
def _add(self, setting, callback = None, validate = None,
alias = None, autocomplete_list = None):
setattr(self, setting.name, setting)
if callback:
setattr(self, "__" + setting.name + "_cb", callback)
if validate:
setattr(self, "__" + setting.name + "_validate", validate)
if alias:
setattr(self, "__" + setting.name + "_alias", alias)
if autocomplete_list:
setattr(self, "__" + setting.name + "_list", autocomplete_list)
def _set(self, key, value):
try:
value = getattr(self, "__%s_alias" % key)()[value]
except KeyError:
pass
except AttributeError:
pass
try:
getattr(self, "__%s_validate" % key)(value)
except AttributeError:
pass
t = type(getattr(self, key))
if t == bool and value == "False": setattr(self, key, False)
else: setattr(self, key, t(value))
try:
cb = None
try:
cb = getattr(self, "__%s_cb" % key)
except AttributeError:
pass
if cb is not None: cb(key, value)
except:
logging.warning((_("Failed to run callback after setting \"%s\":") % key) +
"\n" + traceback.format_exc())
return value
def _tabcomplete(self, key):
try:
return getattr(self, "__%s_list" % key)()
except AttributeError:
pass
try:
return getattr(self, "__%s_alias" % key)().keys()
except AttributeError:
pass
return []
def _all_settings(self):
return self._settings
class Status:
def __init__(self): def __init__(self):
self.extruder_temp = 0 self.extruder_temp = 0
...@@ -453,6 +108,8 @@ class pronsole(cmd.Cmd): ...@@ -453,6 +108,8 @@ class pronsole(cmd.Cmd):
self.status = Status() self.status = Status()
self.dynamic_temp = False self.dynamic_temp = False
self.compute_eta = None self.compute_eta = None
self.statuscheck = False
self.status_thread = None
self.p = printcore.printcore() self.p = printcore.printcore()
self.p.recvcb = self.recvcb self.p.recvcb = self.recvcb
self.p.startcb = self.startcb self.p.startcb = self.startcb
...@@ -475,7 +132,11 @@ class pronsole(cmd.Cmd): ...@@ -475,7 +132,11 @@ class pronsole(cmd.Cmd):
self.temps = {"pla": "185", "abs": "230", "off": "0"} self.temps = {"pla": "185", "abs": "230", "off": "0"}
self.bedtemps = {"pla": "60", "abs": "110", "off": "0"} self.bedtemps = {"pla": "60", "abs": "110", "off": "0"}
self.percentdone = 0 self.percentdone = 0
self.posreport = ""
self.tempreadings = "" self.tempreadings = ""
self.userm114 = 0
self.userm105 = 0
self.m105_waitcycles = 0
self.macros = {} self.macros = {}
self.history_file = "~/.pronsole-history" self.history_file = "~/.pronsole-history"
self.rc_loaded = False self.rc_loaded = False
...@@ -643,6 +304,10 @@ class pronsole(cmd.Cmd): ...@@ -643,6 +304,10 @@ class pronsole(cmd.Cmd):
return stop return stop
def kill(self): def kill(self):
self.statuscheck = False
if self.status_thread:
self.status_thread.join()
self.status_thread = None
if self.rpc_server is not None: if self.rpc_server is not None:
self.rpc_server.shutdown() self.rpc_server.shutdown()
...@@ -709,6 +374,7 @@ class pronsole(cmd.Cmd): ...@@ -709,6 +374,7 @@ class pronsole(cmd.Cmd):
return return
self.log(_("Exiting program. Goodbye!")) self.log(_("Exiting program. Goodbye!"))
self.p.disconnect() self.p.disconnect()
self.kill()
sys.exit() sys.exit()
def help_exit(self): def help_exit(self):
...@@ -1039,7 +705,6 @@ class pronsole(cmd.Cmd): ...@@ -1039,7 +705,6 @@ class pronsole(cmd.Cmd):
def connect_to_printer(self, port, baud): def connect_to_printer(self, port, baud):
try: try:
self.p.connect(port, baud) self.p.connect(port, baud)
return True
except SerialException as e: except SerialException as e:
# Currently, there is no errno, but it should be there in the future # Currently, there is no errno, but it should be there in the future
if e.errno == 2: if e.errno == 2:
...@@ -1057,6 +722,10 @@ class pronsole(cmd.Cmd): ...@@ -1057,6 +722,10 @@ class pronsole(cmd.Cmd):
else: else:
self.logError(traceback.format_exc()) self.logError(traceback.format_exc())
return False return False
self.statuscheck = True
self.status_thread = threading.Thread(target = self.statuschecker)
self.status_thread.start()
return True
def do_connect(self, l): def do_connect(self, l):
a = l.split() a = l.split()
...@@ -1141,6 +810,42 @@ class pronsole(cmd.Cmd): ...@@ -1141,6 +810,42 @@ class pronsole(cmd.Cmd):
self.log("Blocks until printer is online") self.log("Blocks until printer is online")
self.log("Warning: if something goes wrong, this can block pronsole forever") self.log("Warning: if something goes wrong, this can block pronsole forever")
# --------------------------------------------------------------
# Printer status monitoring
# --------------------------------------------------------------
def statuschecker_inner(self, do_monitoring = True):
if self.p.online:
if self.p.writefailures >= 4:
self.logError(_("Disconnecting after 4 failed writes."))
self.status_thread = None
self.disconnect()
return
if do_monitoring:
if self.sdprinting:
self.p.send_now("M27")
if self.m105_waitcycles % 10 == 0:
self.p.send_now("M105")
self.m105_waitcycles += 1
cur_time = time.time()
wait_time = 0
while time.time() < cur_time + self.monitor_interval - 0.25:
if not self.statuscheck:
break
time.sleep(0.25)
# Safeguard: if system time changes and goes back in the past,
# we could get stuck almost forever
wait_time += 0.25
if wait_time > self.monitor_interval - 0.25:
break
# Always sleep at least a bit, if something goes wrong with the
# system time we'll avoid freezing the whole app this way
time.sleep(0.25)
def statuschecker(self):
while self.statuscheck:
self.statuschecker_inner()
# -------------------------------------------------------------- # --------------------------------------------------------------
# File loading handling # File loading handling
# -------------------------------------------------------------- # --------------------------------------------------------------
...@@ -1471,9 +1176,27 @@ class pronsole(cmd.Cmd): ...@@ -1471,9 +1176,27 @@ class pronsole(cmd.Cmd):
self.log("Final command output:") self.log("Final command output:")
self.log(output.rstrip()) self.log(output.rstrip())
def recvcb(self, l): def recvcb_report(self, l):
if tempreading_exp.findall(l): isreport = REPORT_NONE
if "ok C:" in l or "Count" in l \
or ("X:" in l and len(gcoder.m114_exp.findall(l)) == 6):
self.posreport = l
if self.userm114 > 0:
self.userm114 -= 1
else:
isreport = REPORT_POS
if "ok T:" in l or tempreading_exp.findall(l):
self.tempreadings = l self.tempreadings = l
if self.userm105 > 0:
self.userm105 -= 1
else:
self.m105_waitcycles = 0
isreport = REPORT_TEMP
return isreport
def recvcb(self, l):
report_type = self.recvcb_report(l)
if report_type == REPORT_TEMP:
self.status.update_tempreading(l) self.status.update_tempreading(l)
tstring = l.rstrip() tstring = l.rstrip()
if tstring != "ok" and not self.listing and not self.monitoring: if tstring != "ok" and not self.listing and not self.monitoring:
......
...@@ -33,7 +33,7 @@ except ImportError: import json ...@@ -33,7 +33,7 @@ except ImportError: import json
from . import pronsole from . import pronsole
from . import printcore from . import printcore
from .utils import install_locale, setup_logging, \ from .utils import install_locale, setup_logging, dosify, \
iconfile, configfile, format_time, format_duration, \ iconfile, configfile, format_time, format_duration, \
hexcolor_to_float, parse_temperature_report, \ hexcolor_to_float, parse_temperature_report, \
prepare_command, check_rgb_color, check_rgba_color prepare_command, check_rgb_color, check_rgba_color
...@@ -45,8 +45,7 @@ except: ...@@ -45,8 +45,7 @@ except:
logging.error(_("WX is not installed. This program requires WX to run.")) logging.error(_("WX is not installed. This program requires WX to run."))
raise raise
from printrun.gui.widgets import SpecialButton, MacroEditor, \ from .gui.widgets import SpecialButton, MacroEditor, PronterOptions, ButtonEdit
PronterOptions, ButtonEdit
winsize = (800, 500) winsize = (800, 500)
layerindex = 0 layerindex = 0
...@@ -58,12 +57,12 @@ pronterface_quitting = False ...@@ -58,12 +57,12 @@ pronterface_quitting = False
class PronterfaceQuitException(Exception): class PronterfaceQuitException(Exception):
pass pass
from printrun.gui import MainWindow from .gui import MainWindow
from printrun.excluder import Excluder from .excluder import Excluder
from pronsole import dosify, wxSetting, HiddenSetting, StringSetting, SpinSetting, FloatSpinSetting, BooleanSetting, StaticTextSetting from .settings import wxSetting, HiddenSetting, StringSetting, SpinSetting, \
FloatSpinSetting, BooleanSetting, StaticTextSetting
from printrun import gcoder from printrun import gcoder
from .pronsole import REPORT_NONE, REPORT_POS, REPORT_TEMP
tempreading_exp = re.compile("(^T:| T:)")
class Tee(object): class Tee(object):
def __init__(self, target): def __init__(self, target):
...@@ -141,14 +140,8 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -141,14 +140,8 @@ class PronterWindow(MainWindow, pronsole.pronsole):
self.filename = filename self.filename = filename
self.statuscheck = False
self.status_thread = None
self.capture_skip = {} self.capture_skip = {}
self.capture_skip_newline = False self.capture_skip_newline = False
self.tempreadings = ""
self.userm114 = 0
self.userm105 = 0
self.m105_waitcycles = 0
self.fgcode = None self.fgcode = None
self.excluder = None self.excluder = None
self.slicep = None self.slicep = None
...@@ -327,10 +320,6 @@ class PronterWindow(MainWindow, pronsole.pronsole): ...@@ -327,10 +320,6 @@ class PronterWindow(MainWindow, pronsole.pronsole):
pronsole.pronsole.kill(self) pronsole.pronsole.kill(self)
global pronterface_quitting global pronterface_quitting
pronterface_quitting = True pronterface_quitting = True
self.statuscheck = False
if self.status_thread:
self.status_thread.join()
self.status_thread = None
self.p.recvcb = None self.p.recvcb = None
self.p.disconnect() self.p.disconnect()
if hasattr(self, "feedrates_changed"): if hasattr(self, "feedrates_changed"):
...@@ -969,61 +958,40 @@ Printrun. If not, see <http://www.gnu.org/licenses/>.""" ...@@ -969,61 +958,40 @@ Printrun. If not, see <http://www.gnu.org/licenses/>."""
# Statusbar handling # Statusbar handling
# -------------------------------------------------------------- # --------------------------------------------------------------
def statuschecker_inner(self):
status_string = ""
if self.sdprinting or self.uploading or self.p.printing:
secondsremain, secondsestimate, progress = self.get_eta()
if self.sdprinting or self.uploading:
if self.uploading:
status_string += _("SD upload: %04.2f%% |") % (100 * progress,)
status_string += _(" Line# %d of %d lines |") % (self.p.queueindex, len(self.p.mainqueue))
else:
status_string += _("SD printing: %04.2f%% |") % (self.percentdone,)
elif self.p.printing:
status_string += _("Printing: %04.2f%% |") % (100 * float(self.p.queueindex) / len(self.p.mainqueue),)
status_string += _(" Line# %d of %d lines |") % (self.p.queueindex, len(self.p.mainqueue))
if progress > 0:
status_string += _(" Est: %s of %s remaining | ") % (format_duration(secondsremain),
format_duration(secondsestimate))
status_string += _(" Z: %.3f mm") % self.curlayer
elif self.loading_gcode:
status_string = self.loading_gcode_message
wx.CallAfter(self.statusbar.SetStatusText, status_string)
wx.CallAfter(self.gviz.Refresh)
# Call pronsole's statuschecker inner loop function to handle
# temperature monitoring and status loop sleep
pronsole.pronsole.statuschecker_inner(self, self.settings.monitor)
try:
while not self.sentlines.empty():
gc = self.sentlines.get_nowait()
wx.CallAfter(self.gviz.addgcodehighlight, gc)
self.sentlines.task_done()
except Queue.Empty:
pass
def statuschecker(self): def statuschecker(self):
while self.statuscheck: pronsole.pronsole.statuschecker(self)
string = ""
if self.sdprinting or self.uploading or self.p.printing:
secondsremain, secondsestimate, progress = self.get_eta()
if self.sdprinting or self.uploading:
if self.uploading:
string += _("SD upload: %04.2f%% |") % (100 * progress,)
string += _(" Line# %d of %d lines |") % (self.p.queueindex, len(self.p.mainqueue))
else:
string += _("SD printing: %04.2f%% |") % (self.percentdone,)
elif self.p.printing:
string += _("Printing: %04.2f%% |") % (100 * float(self.p.queueindex) / len(self.p.mainqueue),)
string += _(" Line# %d of %d lines |") % (self.p.queueindex, len(self.p.mainqueue))
if progress > 0:
string += _(" Est: %s of %s remaining | ") % (format_duration(secondsremain),
format_duration(secondsestimate))
string += _(" Z: %.3f mm") % self.curlayer
elif self.loading_gcode:
string = self.loading_gcode_message
wx.CallAfter(self.statusbar.SetStatusText, string)
wx.CallAfter(self.gviz.Refresh)
if self.p.online:
if self.p.writefailures >= 4:
self.logError(_("Disconnecting after 4 failed writes."))
self.status_thread = None
self.disconnect()
return
if self.settings.monitor and self.p.online:
if self.sdprinting:
self.p.send_now("M27")
if self.m105_waitcycles % 10 == 0:
self.p.send_now("M105")
self.m105_waitcycles += 1
cur_time = time.time()
wait_time = 0
while time.time() < cur_time + self.monitor_interval - 0.25:
if not self.statuscheck:
break
time.sleep(0.25)
# Safeguard: if system time changes and goes back in the past,
# we could get stuck almost forever
wait_time += 0.25
if wait_time > self.monitor_interval - 0.25:
break
# Always sleep at least a bit, if something goes wrong with the
# system time we'll avoid freezing the whole app this way
time.sleep(0.25)
try:
while not self.sentlines.empty():
gc = self.sentlines.get_nowait()
wx.CallAfter(self.gviz.addgcodehighlight, gc)
self.sentlines.task_done()
except Queue.Empty:
pass
wx.CallAfter(self.statusbar.SetStatusText, _("Not connected to printer.")) wx.CallAfter(self.statusbar.SetStatusText, _("Not connected to printer."))
# -------------------------------------------------------------- # --------------------------------------------------------------
...@@ -1072,13 +1040,10 @@ Printrun. If not, see <http://www.gnu.org/licenses/>.""" ...@@ -1072,13 +1040,10 @@ Printrun. If not, see <http://www.gnu.org/licenses/>."""
self.p.send_now("M26 S0") self.p.send_now("M26 S0")
if not self.connect_to_printer(port, baud): if not self.connect_to_printer(port, baud):
return return
self.statuscheck = True
if port != self.settings.port: if port != self.settings.port:
self.set("port", port) self.set("port", port)
if baud != self.settings.baudrate: if baud != self.settings.baudrate:
self.set("baudrate", str(baud)) self.set("baudrate", str(baud))
self.status_thread = threading.Thread(target = self.statuschecker)
self.status_thread.start()
if self.predisconnect_mainqueue: if self.predisconnect_mainqueue:
self.recoverbtn.Enable() self.recoverbtn.Enable()
...@@ -1675,8 +1640,8 @@ Printrun. If not, see <http://www.gnu.org/licenses/>.""" ...@@ -1675,8 +1640,8 @@ Printrun. If not, see <http://www.gnu.org/licenses/>."""
except: except:
traceback.print_exc() traceback.print_exc()
def update_pos(self, l): def update_pos(self):
bits = gcoder.m114_exp.findall(l) bits = gcoder.m114_exp.findall(self.posreport)
x = None x = None
y = None y = None
z = None z = None
...@@ -1693,24 +1658,13 @@ Printrun. If not, see <http://www.gnu.org/licenses/>.""" ...@@ -1693,24 +1658,13 @@ Printrun. If not, see <http://www.gnu.org/licenses/>."""
if z is not None: self.current_pos[2] = z if z is not None: self.current_pos[2] = z
def recvcb(self, l): def recvcb(self, l):
isreport = False report_type = self.recvcb_report(l)
if "ok C:" in l or "Count" in l \ isreport = report_type != REPORT_NONE
or ("X:" in l and len(gcoder.m114_exp.findall(l)) == 6): if report_type == REPORT_POS:
self.posreport = l self.update_pos()
self.update_pos(l) elif report_type == REPORT_TEMP:
if self.userm114 > 0:
self.userm114 -= 1
else:
isreport = True
if "ok T:" in l or tempreading_exp.findall(l):
self.tempreadings = l
wx.CallAfter(self.tempdisp.SetLabel, self.tempreadings.strip().replace("ok ", "")) wx.CallAfter(self.tempdisp.SetLabel, self.tempreadings.strip().replace("ok ", ""))
self.update_tempdisplay() self.update_tempdisplay()
if self.userm105 > 0:
self.userm105 -= 1
else:
self.m105_waitcycles = 0
isreport = True
tstring = l.rstrip() tstring = l.rstrip()
if not self.p.loud and (tstring not in ["ok", "wait"] and not isreport): if not self.p.loud and (tstring not in ["ok", "wait"] and not isreport):
wx.CallAfter(self.addtexttolog, tstring + "\n") wx.CallAfter(self.addtexttolog, tstring + "\n")
......
# This file is part of the Printrun suite.
#
# Printrun is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Printrun is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Printrun. If not, see <http://www.gnu.org/licenses/>.
from functools import wraps
def setting_add_tooltip(func):
@wraps(func)
def decorator(self, *args, **kwargs):
widget = func(self, *args, **kwargs)
helptxt = self.help or ""
sep, deftxt = "", ""
if len(helptxt):
sep = "\n"
if helptxt.find("\n") >= 0:
sep = "\n\n"
if self.default is not "":
deftxt = _("Default: ")
resethelp = _("(Control-doubleclick to reset to default value)")
if len(repr(self.default)) > 10:
deftxt += "\n " + repr(self.default).strip("'") + "\n" + resethelp
else:
deftxt += repr(self.default) + " " + resethelp
helptxt += sep + deftxt
if len(helptxt):
widget.SetToolTipString(helptxt)
return widget
return decorator
class Setting(object):
DEFAULT_GROUP = "Printer"
hidden = False
def __init__(self, name, default, label = None, help = None, group = None):
self.name = name
self.default = default
self._value = default
self.label = label
self.help = help
self.group = group if group else Setting.DEFAULT_GROUP
def _get_value(self):
return self._value
def _set_value(self, value):
raise NotImplementedError
value = property(_get_value, _set_value)
def set_default(self, e):
import wx
if e.CmdDown() and e.ButtonDClick() and self.default is not "":
confirmation = wx.MessageDialog(None, _("Are you sure you want to reset the setting to the default value: {0!r} ?").format(self.default), _("Confirm set default"), wx.ICON_EXCLAMATION | wx.YES_NO | wx.NO_DEFAULT)
if confirmation.ShowModal() == wx.ID_YES:
self._set_value(self.default)
else:
e.Skip()
@setting_add_tooltip
def get_label(self, parent):
import wx
widget = wx.StaticText(parent, -1, self.label or self.name)
widget.set_default = self.set_default
return widget
@setting_add_tooltip
def get_widget(self, parent):
return self.get_specific_widget(parent)
def get_specific_widget(self, parent):
raise NotImplementedError
def update(self):
raise NotImplementedError
def __str__(self):
return self.name
def __repr__(self):
return self.name
class HiddenSetting(Setting):
hidden = True
def _set_value(self, value):
self._value = value
value = property(Setting._get_value, _set_value)
class wxSetting(Setting):
widget = None
def _set_value(self, value):
self._value = value
if self.widget:
self.widget.SetValue(value)
value = property(Setting._get_value, _set_value)
def update(self):
self.value = self.widget.GetValue()
class StringSetting(wxSetting):
def get_specific_widget(self, parent):
import wx
self.widget = wx.TextCtrl(parent, -1, str(self.value))
return self.widget
class ComboSetting(wxSetting):
def __init__(self, name, default, choices, label = None, help = None, group = None):
super(ComboSetting, self).__init__(name, default, label, help, group)
self.choices = choices
def get_specific_widget(self, parent):
import wx
self.widget = wx.ComboBox(parent, -1, str(self.value), choices = self.choices, style = wx.CB_DROPDOWN)
return self.widget
class SpinSetting(wxSetting):
def __init__(self, name, default, min, max, label = None, help = None, group = None, increment = 0.1):
super(SpinSetting, self).__init__(name, default, label, help, group)
self.min = min
self.max = max
self.increment = increment
def get_specific_widget(self, parent):
from wx.lib.agw.floatspin import FloatSpin
self.widget = FloatSpin(parent, -1, min_val = self.min, max_val = self.max, digits = 0)
self.widget.SetValue(self.value)
orig = self.widget.GetValue
self.widget.GetValue = lambda: int(orig())
return self.widget
class FloatSpinSetting(SpinSetting):
def get_specific_widget(self, parent):
from wx.lib.agw.floatspin import FloatSpin
self.widget = FloatSpin(parent, -1, value = self.value, min_val = self.min, max_val = self.max, increment = self.increment, digits = 2)
return self.widget
class BooleanSetting(wxSetting):
def _get_value(self):
return bool(self._value)
def _set_value(self, value):
self._value = value
if self.widget:
self.widget.SetValue(bool(value))
value = property(_get_value, _set_value)
def get_specific_widget(self, parent):
import wx
self.widget = wx.CheckBox(parent, -1)
self.widget.SetValue(bool(self.value))
return self.widget
class StaticTextSetting(wxSetting):
def __init__(self, name, label = " ", text = "", help = None, group = None):
super(StaticTextSetting, self).__init__(name, "", label, help, group)
self.text = text
def update(self):
pass
def _get_value(self):
return ""
def _set_value(self, value):
pass
def get_specific_widget(self, parent):
import wx
self.widget = wx.StaticText(parent, -1, self.text)
return self.widget
class BuildDimensionsSetting(wxSetting):
widgets = None
def _set_value(self, value):
self._value = value
if self.widgets:
self._set_widgets_values(value)
value = property(wxSetting._get_value, _set_value)
def _set_widgets_values(self, value):
build_dimensions_list = parse_build_dimensions(value)
for i in range(len(self.widgets)):
self.widgets[i].SetValue(build_dimensions_list[i])
def get_widget(self, parent):
from wx.lib.agw.floatspin import FloatSpin
import wx
build_dimensions = parse_build_dimensions(self.value)
self.widgets = []
w = lambda val, m, M: self.widgets.append(FloatSpin(parent, -1, value = val, min_val = m, max_val = M, digits = 2))
addlabel = lambda name, pos: self.widget.Add(wx.StaticText(parent, -1, name), pos = pos, flag = wx.ALIGN_CENTER_VERTICAL | wx.RIGHT, border = 5)
addwidget = lambda *pos: self.widget.Add(self.widgets[-1], pos = pos, flag = wx.RIGHT, border = 5)
self.widget = wx.GridBagSizer()
addlabel(_("Width"), (0, 0))
w(build_dimensions[0], 0, 2000)
addwidget(0, 1)
addlabel(_("Depth"), (0, 2))
w(build_dimensions[1], 0, 2000)
addwidget(0, 3)
addlabel(_("Height"), (0, 4))
w(build_dimensions[2], 0, 2000)
addwidget(0, 5)
addlabel(_("X offset"), (1, 0))
w(build_dimensions[3], -2000, 2000)
addwidget(1, 1)
addlabel(_("Y offset"), (1, 2))
w(build_dimensions[4], -2000, 2000)
addwidget(1, 3)
addlabel(_("Z offset"), (1, 4))
w(build_dimensions[5], -2000, 2000)
addwidget(1, 5)
addlabel(_("X home pos."), (2, 0))
w(build_dimensions[6], -2000, 2000)
self.widget.Add(self.widgets[-1], pos = (2, 1))
addlabel(_("Y home pos."), (2, 2))
w(build_dimensions[7], -2000, 2000)
self.widget.Add(self.widgets[-1], pos = (2, 3))
addlabel(_("Z home pos."), (2, 4))
w(build_dimensions[8], -2000, 2000)
self.widget.Add(self.widgets[-1], pos = (2, 5))
return self.widget
def update(self):
values = [float(w.GetValue()) for w in self.widgets]
self.value = "%.02fx%.02fx%.02f%+.02f%+.02f%+.02f%+.02f%+.02f%+.02f" % tuple(values)
class Settings(object):
def __baudrate_list(self): return ["2400", "9600", "19200", "38400", "57600", "115200", "250000"]
def __init__(self, root):
# defaults here.
# the initial value determines the type
self._add(StringSetting("port", "", _("Serial port"), _("Port used to communicate with printer")))
self._add(ComboSetting("baudrate", 115200, self.__baudrate_list(), _("Baud rate"), _("Communications Speed")))
self._add(BooleanSetting("tcp_streaming_mode", False, _("TCP streaming mode"), _("When using a TCP connection to the printer, the streaming mode will not wait for acks from the printer to send new commands. This will break things such as ETA prediction, but can result in smoother prints.")), root.update_tcp_streaming_mode)
self._add(BooleanSetting("rpc_server", True, _("RPC server"), _("Enable RPC server to allow remotely querying print status")), root.update_rpc_server)
self._add(SpinSetting("bedtemp_abs", 110, 0, 400, _("Bed temperature for ABS"), _("Heated Build Platform temp for ABS (deg C)"), "Printer"))
self._add(SpinSetting("bedtemp_pla", 60, 0, 400, _("Bed temperature for PLA"), _("Heated Build Platform temp for PLA (deg C)"), "Printer"))
self._add(SpinSetting("temperature_abs", 230, 0, 400, _("Extruder temperature for ABS"), _("Extruder temp for ABS (deg C)"), "Printer"))
self._add(SpinSetting("temperature_pla", 185, 0, 400, _("Extruder temperature for PLA"), _("Extruder temp for PLA (deg C)"), "Printer"))
self._add(SpinSetting("xy_feedrate", 3000, 0, 50000, _("X && Y manual feedrate"), _("Feedrate for Control Panel Moves in X and Y (mm/min)"), "Printer"))
self._add(SpinSetting("z_feedrate", 100, 0, 50000, _("Z manual feedrate"), _("Feedrate for Control Panel Moves in Z (mm/min)"), "Printer"))
self._add(SpinSetting("e_feedrate", 100, 0, 1000, _("E manual feedrate"), _("Feedrate for Control Panel Moves in Extrusions (mm/min)"), "Printer"))
self._add(StringSetting("slicecommand", "python skeinforge/skeinforge_application/skeinforge_utilities/skeinforge_craft.py $s", _("Slice command"), _("Slice command"), "External"))
self._add(StringSetting("sliceoptscommand", "python skeinforge/skeinforge_application/skeinforge.py", _("Slicer options command"), _("Slice settings command"), "External"))
self._add(StringSetting("final_command", "", _("Final command"), _("Executable to run when the print is finished"), "External"))
self._add(StringSetting("error_command", "", _("Error command"), _("Executable to run when an error occurs"), "External"))
self._add(HiddenSetting("project_offset_x", 0.0))
self._add(HiddenSetting("project_offset_y", 0.0))
self._add(HiddenSetting("project_interval", 2.0))
self._add(HiddenSetting("project_pause", 2.5))
self._add(HiddenSetting("project_scale", 1.0))
self._add(HiddenSetting("project_x", 1024))
self._add(HiddenSetting("project_y", 768))
self._add(HiddenSetting("project_projected_x", 150.0))
self._add(HiddenSetting("project_direction", "Top Down"))
self._add(HiddenSetting("project_overshoot", 3.0))
self._add(HiddenSetting("project_z_axis_rate", 200))
self._add(HiddenSetting("project_layer", 0.1))
self._add(HiddenSetting("project_prelift_gcode", ""))
self._add(HiddenSetting("project_postlift_gcode", ""))
self._add(HiddenSetting("pause_between_prints", True))
self._add(HiddenSetting("default_extrusion", 5.0))
self._add(HiddenSetting("last_extrusion", 5.0))
self._add(HiddenSetting("total_filament_used", 0.0))
_settings = []
def __setattr__(self, name, value):
if name.startswith("_"):
return object.__setattr__(self, name, value)
if isinstance(value, Setting):
if not value.hidden:
self._settings.append(value)
object.__setattr__(self, "_" + name, value)
elif hasattr(self, "_" + name):
getattr(self, "_" + name).value = value
else:
setattr(self, name, StringSetting(name = name, default = value))
def __getattr__(self, name):
if name.startswith("_"):
return object.__getattribute__(self, name)
return getattr(self, "_" + name).value
def _add(self, setting, callback = None, validate = None,
alias = None, autocomplete_list = None):
setattr(self, setting.name, setting)
if callback:
setattr(self, "__" + setting.name + "_cb", callback)
if validate:
setattr(self, "__" + setting.name + "_validate", validate)
if alias:
setattr(self, "__" + setting.name + "_alias", alias)
if autocomplete_list:
setattr(self, "__" + setting.name + "_list", autocomplete_list)
def _set(self, key, value):
try:
value = getattr(self, "__%s_alias" % key)()[value]
except KeyError:
pass
except AttributeError:
pass
try:
getattr(self, "__%s_validate" % key)(value)
except AttributeError:
pass
t = type(getattr(self, key))
if t == bool and value == "False": setattr(self, key, False)
else: setattr(self, key, t(value))
try:
cb = None
try:
cb = getattr(self, "__%s_cb" % key)
except AttributeError:
pass
if cb is not None: cb(key, value)
except:
logging.warning((_("Failed to run callback after setting \"%s\":") % key) +
"\n" + traceback.format_exc())
return value
def _tabcomplete(self, key):
try:
return getattr(self, "__%s_list" % key)()
except AttributeError:
pass
try:
return getattr(self, "__%s_alias" % key)().keys()
except AttributeError:
pass
return []
def _all_settings(self):
return self._settings
...@@ -117,6 +117,9 @@ def get_command_output(command, replaces): ...@@ -117,6 +117,9 @@ def get_command_output(command, replaces):
blocking = False) blocking = False)
return p.stdout.read() return p.stdout.read()
def dosify(name):
return os.path.split(name)[1].split(".")[0][:8] + ".g"
class RemainingTimeEstimator(object): class RemainingTimeEstimator(object):
drift = None drift = None
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment