|
| 1 | +"""Provider-neutral numeric evidence for protected cloud command learning. |
| 2 | +
|
| 3 | +Probe values are NOT recommended settings or inferred operating limits. They |
| 4 | +may only be dispatched by an already protected shadow-learning workflow. Cloud |
| 5 | +rejections are evidence, not a reason to bypass interception or try every value. |
| 6 | +""" |
| 7 | + |
| 8 | +from decimal import Decimal, InvalidOperation |
| 9 | +import re |
| 10 | + |
| 11 | + |
| 12 | +_NUMBER = r"-?\d+(?:\.\d+)?" |
| 13 | +_RANGE = re.compile(rf"({_NUMBER})\s*(?:~|~|–|\bto\b|-)\s*({_NUMBER})", re.I) |
| 14 | + |
| 15 | + |
| 16 | +def decimal_value(value: object) -> Decimal | None: |
| 17 | + text = str(value).strip() |
| 18 | + if len(text) > 32 or not re.fullmatch(_NUMBER, text): |
| 19 | + return None |
| 20 | + try: |
| 21 | + number = Decimal(text) |
| 22 | + except InvalidOperation: |
| 23 | + return None |
| 24 | + return number if number.is_finite() and abs(number) <= 1_000_000_000 else None |
| 25 | + |
| 26 | + |
| 27 | +def numeric_learning_candidates(*, hint="", unit="", current="", fallback="1") -> list[dict]: |
| 28 | + """Return at most two distinct probes, with device-scoped range evidence. |
| 29 | +
|
| 30 | + Only an unambiguous single range is accepted from the provider hint. Voltage |
| 31 | + family, field name and cloud field ID never supply a range or register address. |
| 32 | + """ |
| 33 | + matches = list(_RANGE.finditer(str(hint))) |
| 34 | + minimum = maximum = None |
| 35 | + if len(matches) == 1: |
| 36 | + minimum, maximum = (decimal_value(v) for v in matches[0].groups()) |
| 37 | + if minimum is None or maximum is None or minimum > maximum: |
| 38 | + minimum = maximum = None |
| 39 | + start = decimal_value(current) |
| 40 | + source = "current" |
| 41 | + if start is None or (minimum is not None and not minimum <= start <= maximum): |
| 42 | + start = minimum if minimum is not None else decimal_value(fallback) |
| 43 | + source = "provider_hint" if minimum is not None else "probe_only" |
| 44 | + if start is None: |
| 45 | + return [] |
| 46 | + # Decimal precision can select a second probe in a sub-unit interval; |
| 47 | + # otherwise use a whole-unit separation, not a claimed device step. |
| 48 | + precision = min(start.as_tuple().exponent, 0) |
| 49 | + if minimum is not None: |
| 50 | + precision = min(precision, minimum.as_tuple().exponent, maximum.as_tuple().exponent) |
| 51 | + step = Decimal(1) |
| 52 | + if minimum is not None and maximum - minimum < step: |
| 53 | + step = Decimal(10) ** max(precision, -3) |
| 54 | + second = start + step |
| 55 | + if maximum is not None and second > maximum: |
| 56 | + second = start - step |
| 57 | + candidates = [start] |
| 58 | + if second != start and (minimum is None or minimum <= second <= maximum): |
| 59 | + candidates.append(second) |
| 60 | + evidence = {"kind": "number", "unit": str(unit or ""), "sample_source": source} |
| 61 | + if minimum is not None: |
| 62 | + evidence.update(minimum=str(minimum), maximum=str(maximum), range_source="provider_hint") |
| 63 | + return [dict(value=format(v, "f"), label="", source="numeric_probe", |
| 64 | + numeric_evidence=dict(evidence)) for v in candidates] |
| 65 | + |
| 66 | + |
| 67 | +def classify_numeric_encoding(samples: list[dict]) -> dict: |
| 68 | + """Prove the supported unsigned, zero-offset encoding across all samples.""" |
| 69 | + evidence = [s.get("numeric_evidence") for s in samples] |
| 70 | + if not evidence or any(not isinstance(e, dict) or e.get("kind") != "number" for e in evidence): |
| 71 | + return {"rejection_reason": "numeric_metadata_inconsistent"} |
| 72 | + if any(e != evidence[0] for e in evidence[1:]): |
| 73 | + return {"rejection_reason": "numeric_metadata_inconsistent"} |
| 74 | + pairs = [] |
| 75 | + routes = set() |
| 76 | + for sample in samples: |
| 77 | + observation = sample.get("observation", {}) |
| 78 | + routes.add(tuple(observation.get(k) for k in ("register", "function_code", "unit", "devcode", "devaddr"))) |
| 79 | + value = decimal_value(sample.get("requested_value")) |
| 80 | + words = sample.get("observation", {}).get("values") |
| 81 | + if value is None or not isinstance(words, (list, tuple)) or len(words) != 1: |
| 82 | + return {"rejection_reason": "unsupported_numeric_encoding"} |
| 83 | + if type(words[0]) is not int or not 0 <= words[0] <= 65535 or value < 0: |
| 84 | + return {"rejection_reason": "unsupported_numeric_encoding"} |
| 85 | + pairs.append((value, words[0])) |
| 86 | + if len(routes) != 1: |
| 87 | + return {"rejection_reason": "numeric_route_inconsistent"} |
| 88 | + if len({v for v, _ in pairs}) < 2: |
| 89 | + return {"rejection_reason": "numeric_needs_distinct_samples"} |
| 90 | + divisors = [d for d in (1, 10, 100, 1000) if all(v * d == raw for v, raw in pairs)] |
| 91 | + if len(divisors) != 1: |
| 92 | + return {"rejection_reason": "numeric_encoding_inconsistent"} |
| 93 | + divisor = divisors[0] |
| 94 | + result = dict(value_kind="scaled_u16" if divisor > 1 else "u16", word_count=1, |
| 95 | + combine="u16", advanced=False, requires_confirm=True, |
| 96 | + unsafe_while_running=False, safety_class="setting", confidence="high") |
| 97 | + if divisor > 1: |
| 98 | + result["divisor"] = divisor |
| 99 | + if evidence[0].get("unit"): |
| 100 | + result["unit"] = evidence[0]["unit"] |
| 101 | + for key in ("minimum", "maximum"): |
| 102 | + if key not in evidence[0]: |
| 103 | + continue |
| 104 | + bound = decimal_value(evidence[0][key]) |
| 105 | + if bound is None or bound * divisor != (bound * divisor).to_integral_value(): |
| 106 | + return {"rejection_reason": "numeric_range_not_representable"} |
| 107 | + raw_bound = int(bound * divisor) |
| 108 | + if not 0 <= raw_bound <= 65535: |
| 109 | + return {"rejection_reason": "numeric_range_not_representable"} |
| 110 | + result[key] = raw_bound |
| 111 | + if result.get("minimum", 0) > result.get("maximum", 65535): |
| 112 | + return {"rejection_reason": "numeric_range_not_representable"} |
| 113 | + return result |
0 commit comments