|
| 1 | +from filament import GenericFilament |
| 2 | +from reader.scan_result import ScanResult |
| 3 | +from tag.ndef_tag_processor import NDEF_URI_PREFIX_MAP, NdefRecord, NdefTagProcessor |
| 4 | +import urllib.parse |
| 5 | + |
| 6 | +from . import constants as Constants |
| 7 | + |
| 8 | + |
| 9 | +class SpooleaseTagProcessor(NdefTagProcessor): |
| 10 | + def __init__(self, config: dict): |
| 11 | + super().__init__(config) |
| 12 | + |
| 13 | + def process_ndef( |
| 14 | + self, scan_result: ScanResult, ndef_records: list[NdefRecord] |
| 15 | + ) -> GenericFilament | None: |
| 16 | + for record in ndef_records: |
| 17 | + if record.tnf == 0x01 and record.type == "U": |
| 18 | + filament = self.__parse_spoolease_payload(record.payload) |
| 19 | + if filament is not None: |
| 20 | + return filament |
| 21 | + return None |
| 22 | + |
| 23 | + def __parse_spoolease_payload(self, payload: bytes) -> GenericFilament | None: |
| 24 | + if payload is None or not isinstance(payload, (bytes, bytearray)): |
| 25 | + self.logger.error( |
| 26 | + "SpoolEase payload parsing failed: Invalid payload parameter" |
| 27 | + ) |
| 28 | + return None |
| 29 | + |
| 30 | + try: |
| 31 | + url = self.__decode_uri_payload(payload) |
| 32 | + parsed = urllib.parse.urlparse(url) |
| 33 | + |
| 34 | + if ( |
| 35 | + parsed.netloc.lower() != "tag.spoolease.io" |
| 36 | + or not parsed.path.startswith("/S1") |
| 37 | + ): |
| 38 | + self.logger.error( |
| 39 | + "SpoolEase payload parsing failed: Unsupported URL '%s'", url |
| 40 | + ) |
| 41 | + return None |
| 42 | + |
| 43 | + query = urllib.parse.parse_qs(parsed.query, keep_blank_values=False) |
| 44 | + |
| 45 | + raw_material = (query.get("M", ["PLA"])[0] or "PLA").upper() |
| 46 | + material = Constants.FILAMENT_TYPE_ALIASES.get(raw_material, raw_material) |
| 47 | + subtype = query.get("MS", [""])[0] or "" |
| 48 | + brand = query.get("B", ["Generic"])[0] or "Generic" |
| 49 | + color_field = query.get("CC", ["FFFFFFFF"])[0] or "FFFFFFFF" |
| 50 | + |
| 51 | + hotend_min_temp_c = self.__parse_required_int(query, "NN") |
| 52 | + hotend_max_temp_c = self.__parse_required_int(query, "NX") |
| 53 | + weight_grams = self.__parse_optional_int(query, "WL", 1000) |
| 54 | + |
| 55 | + if hotend_max_temp_c < hotend_min_temp_c: |
| 56 | + self.logger.error( |
| 57 | + "SpoolEase payload parsing failed: Invalid temperature values" |
| 58 | + ) |
| 59 | + return None |
| 60 | + |
| 61 | + colors = self.__parse_colors(color_field) |
| 62 | + extra_data = Constants.FILAMENT_TYPE_TO_EXTENDED_DATA.get(material) |
| 63 | + |
| 64 | + bed_temp_c = extra_data.bed_temp_c if extra_data is not None else 0.0 |
| 65 | + drying_temp_c = extra_data.drying_temp_c if extra_data is not None else 0.0 |
| 66 | + drying_time_hours = ( |
| 67 | + extra_data.drying_time_hours if extra_data is not None else 0.0 |
| 68 | + ) |
| 69 | + |
| 70 | + return GenericFilament( |
| 71 | + source_processor=self.name, |
| 72 | + unique_id=GenericFilament.generate_unique_id( |
| 73 | + "SpoolEase", brand, material, subtype, *colors, weight_grams |
| 74 | + ), |
| 75 | + manufacturer=brand, |
| 76 | + type=material, |
| 77 | + modifiers=[subtype] if subtype else [], |
| 78 | + colors=colors, |
| 79 | + diameter_mm=1.75, |
| 80 | + weight_grams=weight_grams, |
| 81 | + hotend_min_temp_c=hotend_min_temp_c, |
| 82 | + hotend_max_temp_c=hotend_max_temp_c, |
| 83 | + bed_temp_c=bed_temp_c, |
| 84 | + drying_temp_c=drying_temp_c, |
| 85 | + drying_time_hours=drying_time_hours, |
| 86 | + manufacturing_date="0001-01-01", |
| 87 | + ) |
| 88 | + except ValueError as e: |
| 89 | + self.logger.error("SpoolEase payload parsing failed: %s", e) |
| 90 | + return None |
| 91 | + except Exception as e: |
| 92 | + self.logger.exception("SpoolEase payload parsing failed: %s", e) |
| 93 | + return None |
| 94 | + |
| 95 | + def __decode_uri_payload(self, payload: bytes) -> str: |
| 96 | + if len(payload) < 1: |
| 97 | + raise ValueError("Invalid NDEF URI payload") |
| 98 | + |
| 99 | + prefix = NDEF_URI_PREFIX_MAP.get(payload[0], "") |
| 100 | + suffix = payload[1:].decode("utf-8", errors="ignore") |
| 101 | + return (prefix + suffix).strip() |
| 102 | + |
| 103 | + def __parse_required_int(self, query: dict[str, list[str]], key: str) -> int: |
| 104 | + values = query.get(key) |
| 105 | + if not values or values[0] == "": |
| 106 | + raise ValueError(f"Missing required field '{key}'") |
| 107 | + return int(values[0]) |
| 108 | + |
| 109 | + def __parse_optional_int( |
| 110 | + self, query: dict[str, list[str]], key: str, default: int |
| 111 | + ) -> int: |
| 112 | + values = query.get(key) |
| 113 | + if not values or values[0] == "": |
| 114 | + return default |
| 115 | + return int(values[0]) |
| 116 | + |
| 117 | + def __parse_colors(self, color_field: str) -> list[int]: |
| 118 | + colors = [] |
| 119 | + alpha = 0xFF |
| 120 | + |
| 121 | + for i, color_code in enumerate(color_field.split(";")): |
| 122 | + if len(colors) >= 5: |
| 123 | + break |
| 124 | + |
| 125 | + color_code = color_code.strip() |
| 126 | + if not color_code: |
| 127 | + continue |
| 128 | + |
| 129 | + rgb, parsed_alpha = self.__parse_rgba_hex(color_code) |
| 130 | + colors.append((parsed_alpha << 24) | rgb) |
| 131 | + |
| 132 | + if i == 0: |
| 133 | + alpha = parsed_alpha |
| 134 | + |
| 135 | + if not colors: |
| 136 | + colors = [(alpha << 24) | 0xFFFFFF] |
| 137 | + |
| 138 | + return colors |
| 139 | + |
| 140 | + def __parse_rgba_hex(self, value: str) -> tuple[int, int]: |
| 141 | + hex_str = str(value).strip() |
| 142 | + if hex_str.startswith("#"): |
| 143 | + hex_str = hex_str[1:] |
| 144 | + |
| 145 | + if len(hex_str) == 6: |
| 146 | + return int(hex_str, 16), 0xFF |
| 147 | + if len(hex_str) == 8: |
| 148 | + return int(hex_str[:6], 16), int(hex_str[6:], 16) |
| 149 | + |
| 150 | + raise ValueError(f"Unsupported RGBA hex length: {len(hex_str)}") |
0 commit comments