Merge branch 'main' into CURA-11364_add_sentry_engine

This commit is contained in:
Casper Lamboo 2023-11-30 09:29:47 +01:00 committed by GitHub
commit 1dc350012d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
113 changed files with 2283 additions and 7199 deletions

View file

@ -6,7 +6,7 @@ import numpy
from string import Formatter
from enum import IntEnum
import time
from typing import Any, cast, Dict, List, Optional, Set
from typing import Any, cast, Dict, List, Optional, Set, Tuple
import re
import pyArcus as Arcus # For typing.
from PyQt6.QtCore import QCoreApplication
@ -68,7 +68,23 @@ class GcodeStartEndFormatter(Formatter):
self._default_extruder_nr: int = default_extruder_nr
self._additional_per_extruder_settings: Optional[Dict[str, Dict[str, any]]] = additional_per_extruder_settings
def get_field(self, field_name, args: [str], kwargs: dict) -> Tuple[str, str]:
# get_field method parses all fields in the format-string and parses them individually to the get_value method.
# e.g. for a string "Hello {foo.bar}" would the complete field "foo.bar" would be passed to get_field, and then
# the individual parts "foo" and "bar" would be passed to get_value. This poses a problem for us, because want
# to parse the entire field as a single expression. To solve this, we override the get_field method and return
# the entire field as the expression.
return self.get_value(field_name, args, kwargs), field_name
def get_value(self, expression: str, args: [str], kwargs: dict) -> str:
# The following variables are not settings, but only become available after slicing.
# when these variables are encountered, we return them as-is. They are replaced later
# when the actual values are known.
post_slice_data_variables = ["filament_cost", "print_time", "filament_amount", "filament_weight", "jobname"]
if expression in post_slice_data_variables:
return f"{{{expression}}}"
extruder_nr = self._default_extruder_nr
# The settings may specify a specific extruder to use. This is done by
@ -102,6 +118,7 @@ class GcodeStartEndFormatter(Formatter):
setting_function = SettingFunction(expression)
value = setting_function(container_stack, additional_variables=additional_variables)
return value

View file

@ -50,59 +50,6 @@ class MakerbotWriter(MeshWriter):
{"prefix": "thumbnail", "width": 90, "height": 90},
]
_META_VERSION = "3.0.0"
_PRINT_NAME_MAP = {
"UltiMaker Method": "fire_e",
"UltiMaker Method X": "lava_f",
"UltiMaker Method XL": "magma_10",
}
_EXTRUDER_NAME_MAP = {
"1XA": "mk14_hot",
"2XA": "mk14_hot_s",
"1C": "mk14_c",
"1A": "mk14",
"2A": "mk14_s",
}
_MATERIAL_MAP = {"2780b345-577b-4a24-a2c5-12e6aad3e690": "abs",
"88c8919c-6a09-471a-b7b6-e801263d862d": "abs-wss1",
"416eead4-0d8e-4f0b-8bfc-a91a519befa5": "asa",
"85bbae0e-938d-46fb-989f-c9b3689dc4f0": "nylon-cf",
"283d439a-3490-4481-920c-c51d8cdecf9c": "nylon",
"62414577-94d1-490d-b1e4-7ef3ec40db02": "pc",
"69386c85-5b6c-421a-bec5-aeb1fb33f060": "petg",
"0ff92885-617b-4144-a03c-9989872454bc": "pla",
"a4255da2-cb2a-4042-be49-4a83957a2f9a": "pva",
"a140ef8f-4f26-4e73-abe0-cfc29d6d1024": "wss1",
"77873465-83a9-4283-bc44-4e542b8eb3eb": "sr30",
"96fca5d9-0371-4516-9e96-8e8182677f3c": "im-pla",
"9f52c514-bb53-46a6-8c0c-d507cd6ee742": "abs",
"0f9a2a91-f9d6-4b6b-bd9b-a120a29391be": "abs",
"d3e972f2-68c0-4d2f-8cfd-91028dfc3381": "abs",
"495a0ce5-9daf-4a16-b7b2-06856d82394d": "abs-cf10",
"cb76bd6e-91fd-480c-a191-12301712ec77": "abs-wss1",
"a017777e-3f37-4d89-a96c-dc71219aac77": "abs-wss1",
"4d96000d-66de-4d54-a580-91827dcfd28f": "abs-wss1",
"0ecb0e1a-6a66-49fb-b9ea-61a8924e0cf5": "asa",
"efebc2ea-2381-4937-926f-e824524524a5": "asa",
"b0199512-5714-4951-af85-be19693430f8": "asa",
"b9f55a0a-a2b6-4b8d-8d48-07802c575bd1": "pla",
"c439d884-9cdc-4296-a12c-1bacae01003f": "pla",
"16a723e3-44df-49f4-82ec-2a1173c1e7d9": "pla",
"74d0f5c2-fdfd-4c56-baf1-ff5fa92d177e": "pla",
"64dcb783-470d-4400-91b1-7001652f20da": "pla",
"3a1b479b-899c-46eb-a2ea-67050d1a4937": "pla",
"4708ac49-5dde-4cc2-8c0a-87425a92c2b3": "pla",
"4b560eda-1719-407f-b085-1c2c1fc8ffc1": "pla",
"e10a287d-0067-4a58-9083-b7054f479991": "im-pla",
"01a6b5b0-fab1-420c-a5d9-31713cbeb404": "im-pla",
"f65df4ad-a027-4a48-a51d-975cc8b87041": "im-pla",
"f48739f8-6d96-4a3d-9a2e-8505a47e2e35": "im-pla",
"5c7d7672-e885-4452-9a78-8ba90ec79937": "petg",
"91e05a6e-2f5b-4964-b973-d83b5afe6db4": "petg",
"bdc7dd03-bf38-48ee-aeca-c3e11cee799e": "petg",
"54f66c89-998d-4070-aa60-1cb0fd887518": "nylon",
"002c84b3-84ac-4b5a-b57d-fe1f555a6351": "pva",
"e4da5fcb-f62d-48a2-aaef-0b645aa6973b": "wss1",
"77f06146-6569-437d-8380-9edb0d635a32": "sr30"}
# must be called from the main thread because of OpenGL
@staticmethod
@ -197,7 +144,7 @@ class MakerbotWriter(MeshWriter):
meta = dict()
meta["bot_type"] = MakerbotWriter._PRINT_NAME_MAP.get((name := global_stack.definition.name), name)
meta["bot_type"] = global_stack.definition.getMetaDataEntry("reference_machine_id")
bounds: Optional[AxisAlignedBox] = None
for node in nodes:
@ -239,12 +186,7 @@ class MakerbotWriter(MeshWriter):
meta["uuid"] = print_information.slice_uuid
materials = []
for extruder in extruders:
guid = extruder.material.getMetaData().get("GUID")
material_name = extruder.material.getMetaData().get("material")
material = self._MATERIAL_MAP.get(guid, material_name)
materials.append(material)
materials = [extruder.material.getMetaData().get("reference_material_id") for extruder in extruders]
meta["material"] = materials[0]
meta["materials"] = materials
@ -256,8 +198,7 @@ class MakerbotWriter(MeshWriter):
meta["model_counts"] = [{"count": 1, "name": node.getName()} for node in nodes]
tool_types = [MakerbotWriter._EXTRUDER_NAME_MAP.get((name := extruder.variant.getName()), name) for extruder in
extruders]
tool_types = [extruder.variant.getMetaDataEntry("reference_extruder_id") for extruder in extruders]
meta["tool_type"] = tool_types[0]
meta["tool_types"] = tool_types

View file

@ -3,21 +3,16 @@
# Date: August 28, 2018
# Modified: November 16, 2018 by Joshua Pope-Lewis
# Description: This plugin shows custom messages about your print on the Status bar...
# Please look at the 5 options
# - Scrolling (SCROLL_LONG_FILENAMES) if enabled in Marlin and you aren't printing a small item select this option.
# - Name: By default it will use the name generated by Cura (EG: TT_Test_Cube) - Type a custom name in here
# - Start Num: Choose which number you prefer for the initial layer, 0 or 1
# - Max Layer: Enabling this will show how many layers are in the entire print (EG: Layer 1 of 265!)
# - Add prefix 'Printing': Enabling this will add the prefix 'Printing'
# Description: This plugin is now an option in 'Display Info on LCD'
from ..Script import Script
from UM.Application import Application
from UM.Message import Message
class DisplayFilenameAndLayerOnLCD(Script):
def __init__(self):
super().__init__()
def initialize(self) -> None:
Message(title = "[Display Filename and Layer on LCD]", text = "This script is now an option in 'Display Info on LCD'. This post processor no longer works.").show()
def getSettingDataString(self):
return """{
"name": "Display Filename And Layer On LCD",
@ -26,40 +21,10 @@ class DisplayFilenameAndLayerOnLCD(Script):
"version": 2,
"settings":
{
"scroll":
"enable_script":
{
"label": "Scroll enabled/Small layers?",
"description": "If SCROLL_LONG_FILENAMES is enabled select this setting however, if the model is small disable this setting!",
"type": "bool",
"default_value": false
},
"name":
{
"label": "Text to display:",
"description": "By default the current filename will be displayed on the LCD. Enter text here to override the filename and display something else.",
"type": "str",
"default_value": ""
},
"startNum":
{
"label": "Initial layer number:",
"description": "Choose which number you prefer for the initial layer, 0 or 1",
"type": "int",
"default_value": 0,
"minimum_value": 0,
"maximum_value": 1
},
"maxlayer":
{
"label": "Display max layer?:",
"description": "Display how many layers are in the entire print on status bar?",
"type": "bool",
"default_value": true
},
"addPrefixPrinting":
{
"label": "Add prefix 'Printing'?",
"description": "This will add the prefix 'Printing'",
"label": "Deprecated/Obsolete",
"description": "This script is now included in 'Display Info on LCD'.",
"type": "bool",
"default_value": true
}
@ -67,43 +32,6 @@ class DisplayFilenameAndLayerOnLCD(Script):
}"""
def execute(self, data):
max_layer = 0
lcd_text = "M117 "
if self.getSettingValueByKey("name") != "":
name = self.getSettingValueByKey("name")
else:
name = Application.getInstance().getPrintInformation().jobName
if self.getSettingValueByKey("addPrefixPrinting"):
lcd_text += "Printing "
if not self.getSettingValueByKey("scroll"):
lcd_text += "Layer "
else:
lcd_text += name + " - Layer "
i = self.getSettingValueByKey("startNum")
for layer in data:
display_text = lcd_text + str(i)
layer_index = data.index(layer)
lines = layer.split("\n")
for line in lines:
if line.startswith(";LAYER_COUNT:"):
max_layer = line
max_layer = max_layer.split(":")[1]
if self.getSettingValueByKey("startNum") == 0:
max_layer = str(int(max_layer) - 1)
if line.startswith(";LAYER:"):
if self.getSettingValueByKey("maxlayer"):
display_text = display_text + " of " + max_layer
if not self.getSettingValueByKey("scroll"):
display_text = display_text + " " + name
else:
if not self.getSettingValueByKey("scroll"):
display_text = display_text + " " + name + "!"
else:
display_text = display_text + "!"
line_index = lines.index(line)
lines.insert(line_index + 1, display_text)
i += 1
final_lines = "\n".join(lines)
data[layer_index] = final_lines
Message(title = "[Display Filename and Layer on LCD]", text = "This post is now included in 'Display Info on LCD'. This script will exit.").show()
data[0] += "; [Display Filename and Layer on LCD] Did not run. It is now included in 'Display Info on LCD'.\n"
return data

View file

@ -0,0 +1,486 @@
# Display Filename and Layer on the LCD by Amanda de Castilho on August 28, 2018
# Modified: Joshua Pope-Lewis on November 16, 2018
# Display Progress on LCD by Mathias Lyngklip Kjeldgaard, Alexander Gee, Kimmo Toivanen, Inigo Martinez on July 31, 2019
# Show Progress was adapted from Display Progress by Louis Wooters on January 6, 2020. His changes are included here.
#---------------------------------------------------------------
# DisplayNameOrProgressOnLCD.py
# Cura Post-Process plugin
# Combines 'Display Filename and Layer on the LCD' with 'Display Progress'
# Combined and with additions by: GregValiant (Greg Foresi)
# Date: September 8, 2023
# NOTE: This combined post processor will make 'Display Filename and Layer on the LCD' and 'Display Progress' obsolete
# Description: Display Filename and Layer options:
# Status messages sent to the printer...
# - Scrolling (SCROLL_LONG_FILENAMES) if enabled in Marlin and you aren't printing a small item select this option.
# - Name: By default it will use the name generated by Cura (EG: TT_Test_Cube) - You may enter a custom name here
# - Start Num: Choose which number you prefer for the initial layer, 0 or 1
# - Max Layer: Enabling this will show how many layers are in the entire print (EG: Layer 1 of 265!)
# - Add prefix 'Printing': Enabling this will add the prefix 'Printing'
# - Example Line on LCD: Printing Layer 0 of 395 3DBenchy
# Display Progress options:
# - Display Total Layer Count
# - Disply Time Remaining for the print
# - Time Fudge Factor % - Divide the Actual Print Time by the Cura Estimate. Enter as a percentage and the displayed time will be adjusted. This allows you to bring the displayed time closer to reality (Ex: Entering 87.5 would indicate an adjustment to 87.5% of the Cura estimate).
# - Example line on LCD: 1/479 | ET 2h13m
# - Time to Pauses changes the M117/M118 lines to countdown to the next pause as 1/479 | TP 2h36m
# - 'Add M118 Line' is available with either option. M118 will bounce the message back to a remote print server through the USB connection.
# - 'Add M73 Line' is used by 'Display Progress' only. There are options to incluse M73 P(percent) and M73 R(time remaining)
# - Enable 'Finish-Time' Message - when enabled, takes the Print Time and calculates when the print will end. It takes into account the Time Fudge Factor. The user may enter a print start time. This is also available for Display Filename.
from ..Script import Script
from UM.Application import Application
from UM.Qt.Duration import DurationFormat
import UM.Util
import configparser
from UM.Preferences import Preferences
import time
import datetime
import math
from UM.Message import Message
class DisplayInfoOnLCD(Script):
def getSettingDataString(self):
return """{
"name": "Display Info on LCD",
"key": "DisplayInfoOnLCD",
"metadata": {},
"version": 2,
"settings":
{
"display_option":
{
"label": "LCD display option...",
"description": "Display Filename and Layer was formerly 'Display Filename and Layer on LCD' post-processor. The message format on the LCD is 'Printing Layer 0 of 15 3D Benchy'. Display Progress is similar to the former 'Display Progress on LCD' post-processor. The display format is '1/16 | ET 2hr28m'. Display Progress includes a fudge factor for the print time estimate.",
"type": "enum",
"options": {
"display_progress": "Display Progress",
"filename_layer": "Filename and Layer"
},
"default_value": "display_progress"
},
"format_option":
{
"label": "Scroll enabled/Small layers?",
"description": "If SCROLL_LONG_FILENAMES is enabled in your firmware select this setting.",
"type": "bool",
"default_value": false,
"enabled": "display_option == 'filename_layer'"
},
"file_name":
{
"label": "Text to display:",
"description": "By default the current filename will be displayed on the LCD. Enter text here to override the filename and display something else.",
"type": "str",
"default_value": "",
"enabled": "display_option == 'filename_layer'"
},
"startNum":
{
"label": "Initial layer number:",
"description": "Choose which number you prefer for the initial layer, 0 or 1",
"type": "int",
"default_value": 0,
"minimum_value": 0,
"maximum_value": 1,
"enabled": "display_option == 'filename_layer'"
},
"maxlayer":
{
"label": "Display max layer?:",
"description": "Display how many layers are in the entire print on status bar?",
"type": "bool",
"default_value": true,
"enabled": "display_option == 'filename_layer'"
},
"addPrefixPrinting":
{
"label": "Add prefix 'Printing'?",
"description": "This will add the prefix 'Printing'",
"type": "bool",
"default_value": true,
"enabled": "display_option == 'filename_layer'"
},
"display_total_layers":
{
"label": "Display total layers",
"description": "This setting adds the 'Total Layers' to the LCD message as '17/234'.",
"type": "bool",
"default_value": true,
"enabled": "display_option == 'display_progress'"
},
"display_remaining_time":
{
"label": "Display remaining time",
"description": "This will add the remaining printing time to the LCD message.",
"type": "bool",
"default_value": true,
"enabled": "display_option == 'display_progress'"
},
"add_m118_line":
{
"label": "Add M118 Line",
"description": "Adds M118 in addition to the M117. It will bounce the message back through the USB port to a computer print server (if a printer server like Octoprint or Pronterface is in use).",
"type": "bool",
"default_value": false
},
"add_m73_line":
{
"label": "Add M73 Line(s)",
"description": "Adds M73 in addition to the M117. For some firmware this will set the printers time and or percentage.",
"type": "bool",
"default_value": false,
"enabled": "display_option == 'display_progress'"
},
"add_m73_percent":
{
"label": " Add M73 Percentage",
"description": "Adds M73 with the P parameter. For some firmware this will set the printers 'percentage' of layers completed and it will count upward.",
"type": "bool",
"default_value": false,
"enabled": "add_m73_line and display_option == 'display_progress'"
},
"add_m73_time":
{
"label": " Add M73 Time",
"description": "Adds M73 with the R parameter. For some firmware this will set the printers 'print time' and it will count downward.",
"type": "bool",
"default_value": false,
"enabled": "add_m73_line and display_option == 'display_progress'"
},
"speed_factor":
{
"label": "Time Fudge Factor %",
"description": "When using 'Display Progress' tweak this value to get better estimates. ([Actual Print Time]/[Cura Estimate]) x 100 = Time Fudge Factor. If Cura estimated 9hr and the print actually took 10hr30min then enter 117 here to adjust any estimate closer to reality. This Fudge Factor is also used to calculate the print finish time.",
"type": "float",
"unit": "%",
"default_value": 100,
"enabled": "enable_end_message or display_option == 'display_progress'"
},
"countdown_to_pause":
{
"label": "Countdown to Pauses",
"description": "Instead of the remaining print time the LCD will show the estimated time to pause (TP).",
"type": "bool",
"default_value": false,
"enabled": "display_option == 'display_progress'"
},
"enable_end_message":
{
"label": "Enable 'Finish-Time' Message",
"description": "Get a message when you save a fresh slice. It will show the estimated date and time that the print would finish.",
"type": "bool",
"default_value": true,
"enabled": true
},
"print_start_time":
{
"label": "Print Start Time (Ex 16:45)",
"description": "Use 'Military' time. 16:45 would be 4:45PM. 09:30 would be 9:30AM. If you leave this blank it will be assumed that the print will start Now. If you enter a guesstimate of your printer start time and that time is before 'Now' the guesstimate will consider that the print will start tomorrow at the entered time. ",
"type": "str",
"default_value": "",
"unit": "hrs ",
"enabled": "enable_end_message"
}
}
}"""
def execute(self, data):
display_option = self.getSettingValueByKey("display_option")
add_m118_line = self.getSettingValueByKey("add_m118_line")
add_m73_line = self.getSettingValueByKey("add_m73_line")
add_m73_time = self.getSettingValueByKey("add_m73_time")
add_m73_percent = self.getSettingValueByKey("add_m73_percent")
# This is Display Filename and Layer on LCD---------------------------------------------------------
if display_option == "filename_layer":
max_layer = 0
lcd_text = "M117 "
if self.getSettingValueByKey("file_name") != "":
file_name = self.getSettingValueByKey("file_name")
else:
file_name = Application.getInstance().getPrintInformation().jobName
if self.getSettingValueByKey("addPrefixPrinting"):
lcd_text += "Printing "
if not self.getSettingValueByKey("scroll"):
lcd_text += "Layer "
else:
lcd_text += file_name + " - Layer "
i = self.getSettingValueByKey("startNum")
for layer in data:
display_text = lcd_text + str(i)
layer_index = data.index(layer)
lines = layer.split("\n")
for line in lines:
if line.startswith(";LAYER_COUNT:"):
max_layer = line
max_layer = max_layer.split(":")[1]
if self.getSettingValueByKey("startNum") == 0:
max_layer = str(int(max_layer) - 1)
if line.startswith(";LAYER:"):
if self.getSettingValueByKey("maxlayer"):
display_text = display_text + " of " + max_layer
if not self.getSettingValueByKey("scroll"):
display_text = display_text + " " + file_name
else:
if not self.getSettingValueByKey("scroll"):
display_text = display_text + " " + file_name + "!"
else:
display_text = display_text + "!"
line_index = lines.index(line)
lines.insert(line_index + 1, display_text)
if add_m118_line:
lines.insert(line_index + 2, str(display_text.replace("M117", "M118", 1)))
i += 1
final_lines = "\n".join(lines)
data[layer_index] = final_lines
if bool(self.getSettingValueByKey("enable_end_message")):
message_str = self.message_to_user(self.getSettingValueByKey("speed_factor") / 100)
Message(title = "Display Info on LCD - Estimated Finish Time", text = message_str[0] + "\n\n" + message_str[1] + "\n" + message_str[2] + "\n" + message_str[3]).show()
return data
# Display Progress (from 'Show Progress' and 'Display Progress on LCD')---------------------------------------
elif display_option == "display_progress":
# get settings
display_total_layers = self.getSettingValueByKey("display_total_layers")
display_remaining_time = self.getSettingValueByKey("display_remaining_time")
speed_factor = self.getSettingValueByKey("speed_factor") / 100
m73_time = False
m73_percent = False
if add_m73_line and add_m73_time:
m73_time = True
if add_m73_line and add_m73_percent:
m73_percent = True
# initialize global variables
first_layer_index = 0
time_total = 0
number_of_layers = 0
time_elapsed = 0
# if at least one of the settings is disabled, there is enough room on the display to display "layer"
first_section = data[0]
lines = first_section.split("\n")
for line in lines:
if line.startswith(";TIME:"):
tindex = lines.index(line)
cura_time = int(line.split(":")[1])
print_time = cura_time * speed_factor
hhh = print_time/3600
hr = round(hhh // 1)
mmm = round((hhh % 1) * 60)
orig_hhh = cura_time/3600
orig_hr = round(orig_hhh // 1)
orig_mmm = math.floor((orig_hhh % 1) * 60)
orig_sec = round((((orig_hhh % 1) * 60) % 1) * 60)
if add_m118_line: lines.insert(tindex + 3,"M118 Adjusted Print Time " + str(hr) + "hr " + str(mmm) + "min")
lines.insert(tindex + 3,"M117 ET " + str(hr) + "hr " + str(mmm) + "min")
# add M73 line at beginning
mins = int(60 * hr + mmm)
if m73_time:
lines.insert(tindex + 3, "M73 R{}".format(mins))
if m73_percent:
lines.insert(tindex + 3, "M73 P0")
# If Countdonw to pause is enabled then count the pauses
pause_str = ""
if bool(self.getSettingValueByKey("countdown_to_pause")):
pause_count = 0
for num in range(2,len(data) - 1, 1):
if "PauseAtHeight.py" in data[num]:
pause_count += 1
pause_str = f" with {pause_count} pause(s)"
# This line goes in to convert seconds to hours and minutes
lines.insert(tindex + 3, f";Cura Time Estimate: {cura_time}sec = {orig_hr}hr {orig_mmm}min {orig_sec}sec {pause_str}")
data[0] = "\n".join(lines)
data[len(data)-1] += "M117 Orig Cura Est " + str(orig_hr) + "hr " + str(orig_mmm) + "min\n"
if add_m118_line: data[len(data)-1] += "M118 Est w/FudgeFactor " + str(speed_factor * 100) + "% was " + str(hr) + "hr " + str(mmm) + "min\n"
if not display_total_layers or not display_remaining_time:
base_display_text = "layer "
else:
base_display_text = ""
layer = data[len(data)-1]
data[len(data)-1] = layer.replace(";End of Gcode" + "\n", "")
data[len(data)-1] += ";End of Gcode" + "\n"
# Search for the number of layers and the total time from the start code
for index in range(len(data)):
data_section = data[index]
# We have everything we need, save the index of the first layer and exit the loop
if ";LAYER:" in data_section:
first_layer_index = index
break
else:
for line in data_section.split("\n"):
if line.startswith(";LAYER_COUNT:"):
number_of_layers = int(line.split(":")[1])
elif line.startswith(";TIME:"):
time_total = int(line.split(":")[1])
# for all layers...
current_layer = 0
for layer_counter in range(len(data)-2):
current_layer += 1
layer_index = first_layer_index + layer_counter
display_text = base_display_text
display_text += str(current_layer)
# create a list where each element is a single line of code within the layer
lines = data[layer_index].split("\n")
if not ";LAYER:" in data[layer_index]:
current_layer -= 1
continue
# add the total number of layers if this option is checked
if display_total_layers:
display_text += "/" + str(number_of_layers)
# if display_remaining_time is checked, it is calculated in this loop
if display_remaining_time:
time_remaining_display = " | ET " # initialize the time display
m = (time_total - time_elapsed) // 60 # estimated time in minutes
m *= speed_factor # correct for printing time
m = int(m)
h, m = divmod(m, 60) # convert to hours and minutes
# add the time remaining to the display_text
if h > 0: # if it's more than 1 hour left, display format = xhxxm
time_remaining_display += str(h) + "h"
if m < 10: # add trailing zero if necessary
time_remaining_display += "0"
time_remaining_display += str(m) + "m"
else:
time_remaining_display += str(m) + "m"
display_text += time_remaining_display
# find time_elapsed at the end of the layer (used to calculate the remaining time of the next layer)
if not current_layer == number_of_layers:
for line_index in range(len(lines) - 1, -1, -1):
line = lines[line_index]
if line.startswith(";TIME_ELAPSED:"):
# update time_elapsed for the NEXT layer and exit the loop
time_elapsed = int(float(line.split(":")[1]))
break
# insert the text AFTER the first line of the layer (in case other scripts use ";LAYER:")
for l_index, line in enumerate(lines):
if line.startswith(";LAYER:"):
lines[l_index] += "\nM117 " + display_text
# add M73 line
mins = int(60 * h + m)
if m73_time:
lines[l_index] += "\nM73 R{}".format(mins)
if m73_percent:
lines[l_index] += "\nM73 P" + str(round(int(current_layer) / int(number_of_layers) * 100))
if add_m118_line:
lines[l_index] += "\nM118 " + display_text
break
# overwrite the layer with the modified layer
data[layer_index] = "\n".join(lines)
# If enabled then change the ET to TP for 'Time To Pause'
if bool(self.getSettingValueByKey("countdown_to_pause")):
time_list = []
time_list.append("0")
time_list.append("0")
this_time = 0
pause_index = 1
# Get the layer times
for num in range(2,len(data) - 1):
layer = data[num]
lines = layer.split("\n")
for line in lines:
if line.startswith(";TIME_ELAPSED:"):
this_time = (float(line.split(":")[1]))*speed_factor
time_list.append(str(this_time))
if "PauseAtHeight.py" in layer:
for qnum in range(num - 1, pause_index, -1):
time_list[qnum] = str(float(this_time) - float(time_list[qnum])) + "P"
pause_index = num-1
# Make the adjustments to the M117 (and M118) lines that are prior to a pause
for num in range (2, len(data) - 1,1):
layer = data[num]
lines = layer.split("\n")
for line in lines:
if line.startswith("M117") and "|" in line and "P" in time_list[num]:
M117_line = line.split("|")[0] + "| TP "
alt_time = time_list[num][:-1]
hhh = int(float(alt_time) / 3600)
if hhh > 0:
hhr = str(hhh) + "h"
else:
hhr = ""
mmm = ((float(alt_time) / 3600) - (int(float(alt_time) / 3600))) * 60
sss = int((mmm - int(mmm)) * 60)
mmm = str(round(mmm)) + "m"
time_to_go = str(hhr) + str(mmm)
if hhr == "": time_to_go = time_to_go + str(sss) + "s"
M117_line = M117_line + time_to_go
layer = layer.replace(line, M117_line)
if line.startswith("M118") and "|" in line and "P" in time_list[num]:
M118_line = line.split("|")[0] + "| TP " + time_to_go
layer = layer.replace(line, M118_line)
data[num] = layer
setting_data = ""
if bool(self.getSettingValueByKey("enable_end_message")):
message_str = self.message_to_user(speed_factor)
Message(title = "[Display Info on LCD] - Estimated Finish Time", text = message_str[0] + "\n\n" + message_str[1] + "\n" + message_str[2] + "\n" + message_str[3]).show()
return data
def message_to_user(self, speed_factor: float):
# Message the user of the projected finish time of the print
print_time = Application.getInstance().getPrintInformation().currentPrintTime.getDisplayString(DurationFormat.Format.ISO8601)
print_start_time = self.getSettingValueByKey("print_start_time")
# If the user entered a print start time make sure it is in the correct format or ignore it.
if print_start_time == "" or print_start_time == "0" or len(print_start_time) != 5 or not ":" in print_start_time:
print_start_time = ""
# Change the print start time to proper time format, or, use the current time
if print_start_time != "":
hr = int(print_start_time.split(":")[0])
min = int(print_start_time.split(":")[1])
sec = 0
else:
hr = int(time.strftime("%H"))
min = int(time.strftime("%M"))
sec = int(time.strftime("%S"))
#Get the current data/time info
yr = int(time.strftime("%Y"))
day = int(time.strftime("%d"))
mo = int(time.strftime("%m"))
date_and_time = datetime.datetime(yr, mo, day, hr, min, sec)
#Split the Cura print time
pr_hr = int(print_time.split(":")[0])
pr_min = int(print_time.split(":")[1])
pr_sec = int(print_time.split(":")[2])
#Adjust the print time if none was entered
print_seconds = pr_hr*3600 + pr_min*60 + pr_sec
#Adjust the total seconds by the Fudge Factor
adjusted_print_time = print_seconds * speed_factor
#Break down the adjusted seconds back into hh:mm:ss
adj_hr = int(adjusted_print_time/3600)
print_seconds = adjusted_print_time - (adj_hr * 3600)
adj_min = int(print_seconds) / 60
adj_sec = int(print_seconds - (adj_min * 60))
#Get the print time to add to the start time
time_change = datetime.timedelta(hours=adj_hr, minutes=adj_min, seconds=adj_sec)
new_time = date_and_time + time_change
#Get the day of the week that the print will end on
week_day = str(["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][int(new_time.strftime("%w"))])
#Get the month that the print will end in
mo_str = str(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"][int(new_time.strftime("%m"))-1])
#Make adjustments from 24hr time to 12hr time
if int(new_time.strftime("%H")) > 12:
show_hr = str(int(new_time.strftime("%H")) - 12) + ":"
show_ampm = " PM"
elif int(new_time.strftime("%H")) == 0:
show_hr = "12:"
show_ampm = " AM"
else:
show_hr = str(new_time.strftime("%H")) + ":"
show_ampm = " AM"
if print_start_time == "":
start_str = "Now"
else:
start_str = "and your entered 'print start time' of " + print_start_time + "hrs."
if print_start_time != "":
print_start_str = "Print Start Time................." + str(print_start_time) + "hrs"
else:
print_start_str = "Print Start Time.................Now."
estimate_str = "Cura Time Estimate.........." + str(print_time)
adjusted_str = "Adjusted Time Estimate..." + str(time_change)
finish_str = week_day + " " + str(mo_str) + " " + str(new_time.strftime("%d")) + ", " + str(new_time.strftime("%Y")) + " at " + str(show_hr) + str(new_time.strftime("%M")) + str(show_ampm)
return finish_str, estimate_str, adjusted_str, print_start_str

View file

@ -9,12 +9,13 @@ from ..Script import Script
import re
import datetime
from UM.Message import Message
class DisplayProgressOnLCD(Script):
def __init__(self):
super().__init__()
def initialize(self) -> None:
Message(title = "[Display Progress on LCD]", text = "This script is now an option in 'Display Info on LCD'. This post processor no longer works.").show()
def getSettingDataString(self):
return """{
"name": "Display Progress On LCD",
@ -23,176 +24,17 @@ class DisplayProgressOnLCD(Script):
"version": 2,
"settings":
{
"time_remaining":
"enable_script":
{
"label": "Time Remaining",
"description": "Select to write remaining time to the display.Select to write remaining time on the display using M117 status line message (almost all printers) or using M73 command (Prusa and Marlin 2 if enabled).",
"label": "Deprecated/Obsolete",
"description": "This script is now included in 'Display Info on LCD'.",
"type": "bool",
"default_value": false
},
"time_remaining_method":
{
"label": "Time Reporting Method",
"description": "How should remaining time be shown on the display? It could use a generic message command (M117, almost all printers), or a specialised time remaining command (M73, Prusa and Marlin 2).",
"type": "enum",
"options": {
"m117":"M117 - All printers",
"m73":"M73 - Prusa, Marlin 2",
"m118":"M118 - Octoprint"
},
"enabled": "time_remaining",
"default_value": "m117"
},
"update_frequency":
{
"label": "Update frequency",
"description": "Update remaining time for every layer or periodically every minute or faster.",
"type": "enum",
"options": {"0":"Every layer","15":"Every 15 seconds","30":"Every 30 seconds","60":"Every minute"},
"default_value": "0",
"enabled": "time_remaining"
},
"percentage":
{
"label": "Percentage",
"description": "When enabled, set the completion bar percentage on the LCD using Marlin's M73 command.",
"type": "bool",
"default_value": false
"default_value": true
}
}
}"""
# Get the time value from a line as a float.
# Example line ;TIME_ELAPSED:1234.6789 or ;TIME:1337
def getTimeValue(self, line):
list_split = re.split(":", line) # Split at ":" so we can get the numerical value
return float(list_split[1]) # Convert the numerical portion to a float
def outputTime(self, lines, line_index, time_left, mode):
# Do some math to get the time left in seconds into the right format. (HH,MM,SS)
time_left = max(time_left, 0)
m, s = divmod(time_left, 60)
h, m = divmod(m, 60)
# Create the string
if mode == "m117":
current_time_string = "{:d}h{:02d}m{:02d}s".format(int(h), int(m), int(s))
# And now insert that into the GCODE
lines.insert(line_index, "M117 Time Left {}".format(current_time_string))
elif mode == "m118":
current_time_string = "{:d}h{:02d}m{:02d}s".format(int(h), int(m), int(s))
# And now insert that into the GCODE
lines.insert(line_index, "M118 A1 P0 action:notification Time Left {}".format(current_time_string))
else:
mins = int(60 * h + m + s / 30)
lines.insert(line_index, "M73 R{}".format(mins))
def execute(self, data):
output_time = self.getSettingValueByKey("time_remaining")
output_time_method = self.getSettingValueByKey("time_remaining_method")
output_frequency = int(self.getSettingValueByKey("update_frequency"))
output_percentage = self.getSettingValueByKey("percentage")
line_set = {}
if output_percentage or output_time:
total_time = -1
previous_layer_end_percentage = 0
previous_layer_end_time = 0
for layer in data:
layer_index = data.index(layer)
lines = layer.split("\n")
for line in lines:
if (line.startswith(";TIME:") or line.startswith(";PRINT.TIME:")) and total_time == -1:
# This line represents the total time required to print the gcode
total_time = self.getTimeValue(line)
line_index = lines.index(line)
# In the beginning we may have 2 M73 lines, but it makes logic less complicated
if output_time:
self.outputTime(lines, line_index, total_time, output_time_method)
if output_percentage:
# Emit 0 percent to sure Marlin knows we are overriding the completion percentage
if output_time_method == "m118":
lines.insert(line_index, "M118 A1 P0 action:notification Data Left 0/100")
else:
lines.insert(line_index, "M73 P0")
elif line.startswith(";TIME_ELAPSED:"):
# We've found one of the time elapsed values which are added at the end of layers
# If we have seen this line before then skip processing it. We can see lines multiple times because we are adding
# intermediate percentages before the line being processed. This can cause the current line to shift back and be
# encountered more than once
if line in line_set:
continue
line_set[line] = True
# If total_time was not already found then noop
if total_time == -1:
continue
current_time = self.getTimeValue(line)
line_index = lines.index(line)
if output_time:
if output_frequency == 0:
# Here we calculate remaining time
self.outputTime(lines, line_index, total_time - current_time, output_time_method)
else:
# Here we calculate remaining time and how many outputs are expected for the layer
layer_time_delta = int(current_time - previous_layer_end_time)
layer_step_delta = int((current_time - previous_layer_end_time) / output_frequency)
# If this layer represents less than 1 step then we don't need to emit anything, continue to the next layer
if layer_step_delta != 0:
# Grab the index of the current line and figure out how many lines represent one second
step = line_index / layer_time_delta
# Move new lines further as we add new lines above it
lines_added = 1
# Run through layer in seconds
for seconds in range(1, layer_time_delta + 1):
# Time from start to decide when to update
line_time = int(previous_layer_end_time + seconds)
# Output every X seconds and after last layer
if line_time % output_frequency == 0 or line_time == total_time:
# Line to add the output
time_line_index = int((seconds * step) + lines_added)
# Insert remaining time into the GCODE
self.outputTime(lines, time_line_index, total_time - line_time, output_time_method)
# Next line will be again lower
lines_added = lines_added + 1
previous_layer_end_time = int(current_time)
if output_percentage:
# Calculate percentage value this layer ends at
layer_end_percentage = int((current_time / total_time) * 100)
# Figure out how many percent of the total time is spent in this layer
layer_percentage_delta = layer_end_percentage - previous_layer_end_percentage
# If this layer represents less than 1 percent then we don't need to emit anything, continue to the next layer
if layer_percentage_delta != 0:
# Grab the index of the current line and figure out how many lines represent one percent
step = line_index / layer_percentage_delta
for percentage in range(1, layer_percentage_delta + 1):
# We add the percentage value here as while processing prior lines we will have inserted
# percentage lines before the current one. Failing to do this will upset the spacing
percentage_line_index = int((percentage * step) + percentage)
# Due to integer truncation of the total time value in the gcode the percentage we
# calculate may slightly exceed 100, as that is not valid we cap the value here
output = min(percentage + previous_layer_end_percentage, 100)
# Now insert the sanitized percentage into the GCODE
if output_time_method == "m118":
lines.insert(percentage_line_index, "M118 A1 P0 action:notification Data Left {}/100".format(output))
else:
lines.insert(percentage_line_index, "M73 P{}".format(output))
previous_layer_end_percentage = layer_end_percentage
# Join up the lines for this layer again and store them in the data array
data[layer_index] = "\n".join(lines)
Message(title = "[Display Progress on LCD]", text = "This post is now included in 'Display Info on LCD'. This script will exit.").show()
data[0] += "; [Display Progress on LCD] Did not run. It is now included in 'Display Info on LCD'.\n"
return data

View file

@ -58,7 +58,6 @@ class CloudOutputDevice(UltimakerNetworkedPrinterOutputDevice):
# The minimum version of firmware that support print job actions over cloud.
PRINT_JOB_ACTIONS_MIN_VERSION = Version("5.2.12")
PRINT_JOB_ACTIONS_MIN_VERSION_METHOD = Version("2.700")
# Notify can only use signals that are defined by the class that they are in, not inherited ones.
# Therefore, we create a private signal used to trigger the printersChanged signal.
@ -214,7 +213,12 @@ class CloudOutputDevice(UltimakerNetworkedPrinterOutputDevice):
return
# Export the scene to the correct file type.
job = ExportFileJob(file_handler=file_handler, nodes=nodes, firmware_version=self.firmwareVersion)
job = ExportFileJob(
file_handler=file_handler,
nodes=nodes,
firmware_version=self.firmwareVersion,
print_type=self.printerType,
)
job.finished.connect(self._onPrintJobCreated)
job.start()
@ -319,19 +323,29 @@ class CloudOutputDevice(UltimakerNetworkedPrinterOutputDevice):
PrintJobUploadErrorMessage(message).show()
self.writeError.emit()
@pyqtProperty(bool, notify=_cloudClusterPrintersChanged)
def isMethod(self) -> bool:
"""Whether the printer that this output device represents is a Method series printer."""
if not self._printers:
return False
[printer, *_] = self._printers
return printer.pinterType in ("ultimaker_methodx", "ultimaker_methodxl")
@pyqtProperty(bool, notify=_cloudClusterPrintersChanged)
def supportsPrintJobActions(self) -> bool:
"""Whether the printer that this output device represents supports print job actions via the cloud."""
if not self._printers:
return False
if self.isMethod:
return True
version_number = self.printers[0].firmwareVersion.split(".")
if len(version_number)> 2:
firmware_version = Version([version_number[0], version_number[1], version_number[2]])
return firmware_version >= self.PRINT_JOB_ACTIONS_MIN_VERSION
else:
firmware_version = Version([version_number[0], version_number[1]])
return firmware_version >= self.PRINT_JOB_ACTIONS_MIN_VERSION_METHOD
firmware_version = Version([version_number[0], version_number[1], version_number[2]])
return firmware_version >= self.PRINT_JOB_ACTIONS_MIN_VERSION
@pyqtProperty(bool, constant = True)

View file

@ -16,9 +16,9 @@ from .MeshFormatHandler import MeshFormatHandler
class ExportFileJob(WriteFileJob):
"""Job that exports the build plate to the correct file format for the target cluster."""
def __init__(self, file_handler: Optional[FileHandler], nodes: List[SceneNode], firmware_version: str) -> None:
self._mesh_format_handler = MeshFormatHandler(file_handler, firmware_version)
def __init__(self, file_handler: Optional[FileHandler], nodes: List[SceneNode], firmware_version: str,
print_type: str) -> None:
self._mesh_format_handler = MeshFormatHandler(file_handler, firmware_version, print_type)
if not self._mesh_format_handler.is_valid:
Logger.log("e", "Missing file or mesh writer!")
return

View file

@ -19,10 +19,9 @@ I18N_CATALOG = i18nCatalog("cura")
class MeshFormatHandler:
"""This class is responsible for choosing the formats used by the connected clusters."""
def __init__(self, file_handler: Optional[FileHandler], firmware_version: str) -> None:
def __init__(self, file_handler: Optional[FileHandler], firmware_version: str, printer_type: str) -> None:
self._file_handler = file_handler or CuraApplication.getInstance().getMeshFileHandler()
self._preferred_format = self._getPreferredFormat(firmware_version)
self._preferred_format = self._getPreferredFormat(firmware_version, printer_type)
self._writer = self._getWriter(self.mime_type) if self._preferred_format else None
@property
@ -82,7 +81,7 @@ class MeshFormatHandler:
value = value.encode()
return value
def _getPreferredFormat(self, firmware_version: str) -> Dict[str, Union[str, int, bool]]:
def _getPreferredFormat(self, firmware_version: str, printer_type: str) -> Dict[str, Union[str, int, bool]]:
"""Chooses the preferred file format for the given file handler.
:param firmware_version: The version of the firmware.
@ -103,13 +102,11 @@ class MeshFormatHandler:
machine_file_formats = [file_type.strip() for file_type in machine_file_formats]
# Exception for UM3 firmware version >=4.4: UFP is now supported and should be the preferred file format.
if "application/x-ufp" not in machine_file_formats and Version(firmware_version) >= Version("4.4"):
if printer_type in (
"ultimaker3", "ultimaker3_extended") and "application/x-ufp" not in machine_file_formats and Version(
firmware_version) >= Version("4.4"):
machine_file_formats = ["application/x-ufp"] + machine_file_formats
# Exception for makerbot firmware version >=2.700: makerbot is supported
elif "application/x-makerbot" not in machine_file_formats and Version(firmware_version >= Version("2.700")):
machine_file_formats = ["application/x-makerbot"] + machine_file_formats
# Take the intersection between file_formats and machine_file_formats.
format_by_mimetype = {f["mime_type"]: f for f in file_formats}

View file

@ -146,7 +146,12 @@ class LocalClusterOutputDevice(UltimakerNetworkedPrinterOutputDevice):
self.writeStarted.emit(self)
# Export the scene to the correct file type.
job = ExportFileJob(file_handler=file_handler, nodes=nodes, firmware_version=self.firmwareVersion)
job = ExportFileJob(
file_handler=file_handler,
nodes=nodes,
firmware_version=self.firmwareVersion,
print_type=self.printerType,
)
job.finished.connect(self._onPrintJobCreated)
job.start()