123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- import re
- import json
- from UM.Settings.ContainerFormatError import ContainerFormatError
- from UM.Settings.InstanceContainer import InstanceContainer
- from UM.Logger import Logger
- from UM.i18n import i18nCatalog
- catalog = i18nCatalog("cura")
- from cura.ReaderWriters.ProfileReader import ProfileReader, NoProfileException
- class GCodeProfileReader(ProfileReader):
-
-
-
-
-
- version = 3
-
-
-
-
-
- escape_characters = {
- re.escape("\\\\"): "\\",
- re.escape("\\n"): "\n",
- re.escape("\\r"): "\r"
- }
-
- def __init__(self):
- super().__init__()
-
-
-
-
-
-
- def read(self, file_name):
- if file_name.split(".")[-1] != "gcode":
- return None
- prefix = ";SETTING_" + str(GCodeProfileReader.version) + " "
- prefix_length = len(prefix)
-
-
-
- serialized = ""
- try:
- with open(file_name, "r", encoding = "utf-8") as f:
- for line in f:
- if line.startswith(prefix):
-
- serialized += line[prefix_length : -1]
- except IOError as e:
- Logger.log("e", "Unable to open file %s for reading: %s", file_name, str(e))
- return None
- serialized = unescapeGcodeComment(serialized)
- serialized = serialized.strip()
- if not serialized:
- Logger.log("i", "No custom profile to import from this g-code: %s", file_name)
- raise NoProfileException()
-
- try:
- json_data = json.loads(serialized)
- except Exception as e:
- Logger.log("e", "Could not parse serialized JSON data from g-code %s, error: %s", file_name, e)
- return None
- profiles = []
- global_profile = readQualityProfileFromString(json_data["global_quality"])
-
-
-
- if global_profile.getMetaDataEntry("extruder", None) is not None:
- global_profile.setMetaDataEntry("extruder", None)
- profiles.append(global_profile)
- for profile_string in json_data.get("extruder_quality", []):
- profiles.append(readQualityProfileFromString(profile_string))
- return profiles
- def unescapeGcodeComment(string):
-
- pattern = re.compile("|".join(GCodeProfileReader.escape_characters.keys()))
-
- return pattern.sub(lambda m: GCodeProfileReader.escape_characters[re.escape(m.group(0))], string)
- def readQualityProfileFromString(profile_string):
-
- profile = InstanceContainer("")
- try:
- profile.deserialize(profile_string)
- except ContainerFormatError as e:
- Logger.log("e", "Corrupt profile in this g-code file: %s", str(e))
- return None
- except Exception as e:
- Logger.log("e", "Unable to serialise the profile: %s", str(e))
- return None
- return profile
|