Skip to content

Commit 2996d97

Browse files
committed
fix: mu funktionen
1 parent 4ce68db commit 2996d97

1 file changed

Lines changed: 312 additions & 0 deletions

File tree

‎sd_protocols/message_unsynced.py‎

Lines changed: 312 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,312 @@
1+
from __future__ import annotations
2+
import re
3+
import logging
4+
from typing import Any, Dict, List, Optional, Tuple
5+
6+
from .pattern_utils import pattern_exists, is_in_tolerance
7+
8+
class MessageUnsyncedMixin:
9+
"""Mixin providing Message Unsynced (MU) signal decoding methods."""
10+
11+
def demodulate_mu(self, msg_data: Dict[str, Any], msg_type: str = "MU") -> List[Dict[str, Any]]:
12+
"""
13+
Demodulates a Message Unsynced (MU) message.
14+
15+
Args:
16+
msg_data: The parsed message data including P#, D, CP, etc.
17+
msg_type: The message type (e.g., "MU").
18+
19+
Returns:
20+
List of decoded messages.
21+
"""
22+
raw_data = msg_data.get('data', '')
23+
if not raw_data:
24+
self._logging(f"MU Demod: Invalid rawData D=: {raw_data}", 3)
25+
return []
26+
27+
# Parse P# patterns
28+
patterns_raw = {}
29+
for key, val in msg_data.items():
30+
if key.startswith('P') and key[1:].isdigit():
31+
try:
32+
pidx = str(int(key[1:]))
33+
patterns_raw[pidx] = float(val)
34+
except ValueError:
35+
pass
36+
37+
if not patterns_raw:
38+
# Some MU messages might not have patterns if they rely purely on hardcoded checks,
39+
# but usually they do.
40+
pass
41+
42+
decoded_messages = []
43+
44+
# Iterate over protocols with 'clockabs' property (MU protocols)
45+
mu_protocols = self.get_keys('clockabs')
46+
47+
for pid in mu_protocols:
48+
# Prepare working copy of raw_data and patterns
49+
# (Perl does this per protocol iteration because filterfunc might modify them)
50+
current_raw_data = raw_data
51+
current_patterns_raw = patterns_raw.copy()
52+
53+
# TODO: filterfunc support
54+
# if defined($hash->{protocolObject}->getProperty($id,'filterfunc')) ...
55+
56+
clock_abs = float(self.check_property(pid, 'clockabs', 1))
57+
58+
# Normalize patterns
59+
patterns = {}
60+
for pidx, pval in current_patterns_raw.items():
61+
patterns[pidx] = round(pval / clock_abs, 1)
62+
63+
# Check Start Pattern
64+
start_pattern = self.get_property(pid, 'start')
65+
start_str = ''
66+
message_start = 0
67+
68+
if start_pattern and isinstance(start_pattern, list):
69+
# Perl: if (($startStr=SIGNALduino_PatternExists(...)) eq -1)
70+
pstr = pattern_exists([float(x) for x in start_pattern], patterns, current_raw_data)
71+
72+
if pstr == -1:
73+
# self._logging(f"MU Demod: Protocol {pid} start pattern not found", 5)
74+
continue
75+
76+
start_str = str(pstr)
77+
idx = current_raw_data.find(start_str)
78+
if idx == -1:
79+
continue
80+
81+
message_start = idx
82+
# In Perl it slices substr($rawData, $message_start), but later it uses regex on the sliced data.
83+
# Here we can just note the start or slice it.
84+
# Perl: $rawData = substr($rawData, $message_start);
85+
current_raw_data = current_raw_data[message_start:]
86+
87+
88+
# Build Pattern Lookups and Signal Regex
89+
pattern_lookup = {}
90+
end_pattern_lookup = {}
91+
92+
signal_regex_parts = []
93+
match_failed = False
94+
95+
# Check one, zero, float
96+
for key in ['one', 'zero', 'float']:
97+
prop_val = self.get_property(pid, key)
98+
if not prop_val:
99+
continue
100+
101+
try:
102+
search_pattern = [float(x) for x in prop_val]
103+
except (ValueError, TypeError):
104+
match_failed = True
105+
break
106+
107+
symbol_map = {
108+
'one': '1',
109+
'zero': '0',
110+
'float': 'F'
111+
}
112+
representation = symbol_map.get(key, '')
113+
114+
pstr = pattern_exists(search_pattern, patterns, current_raw_data)
115+
116+
if pstr != -1:
117+
pstr = str(pstr)
118+
pattern_lookup[pstr] = representation
119+
120+
if len(pstr) > 0:
121+
short_pstr = pstr[:-1]
122+
if short_pstr not in end_pattern_lookup:
123+
end_pattern_lookup[short_pstr] = representation
124+
125+
# Build regex part
126+
# Perl: if ($key eq "one") { $signalRegex .= $return_text; } else { $signalRegex .= "|$return_text" ... }
127+
# This implies One is mandatory or main? Actually Perl logic loop:
128+
# for my $key (qw(one zero float) ) ... if ($key eq "one") { ... } else { ... }
129+
# This constructs (one_pattern|zero_pattern|float_pattern) but ensures 'one' is first?
130+
# Let's just collect valid patterns and join them with OR.
131+
signal_regex_parts.append(re.escape(pstr))
132+
133+
else:
134+
if key != 'float':
135+
# self._logging(f"MU Demod: Protocol {pid} key {key} not found", 5)
136+
match_failed = True
137+
break
138+
139+
if match_failed or not signal_regex_parts:
140+
continue
141+
142+
# Construct Regex
143+
# Perl: $regex="(?:$startStr)($signalRegex)"; where signalRegex is (one|zero|float){min,}
144+
145+
signal_or_group = "|".join(signal_regex_parts)
146+
if self.get_property(pid, 'reconstructBit'):
147+
# Add endPatternLookup keys
148+
extras = [re.escape(k) for k in end_pattern_lookup.keys()]
149+
if extras:
150+
signal_or_group += "|" + "|".join(extras)
151+
152+
length_min = self.check_property(pid, 'length_min', 0)
153+
# length_max = self.check_property(pid, 'length_max', '')
154+
155+
# Python re doesn't support variable length lookbehind or similar easily,
156+
# but here we are matching forward.
157+
# Perl loop: while ( $rawData =~ m/$regex/g)
158+
# regex = (?:$startStr)((?:p1|p2|...){min,})
159+
160+
# We already sliced raw_data to start at startStr if present.
161+
# So startStr is at the beginning of current_raw_data.
162+
# However, if startStr was found, it is consumed?
163+
# Perl: $rawData = substr($rawData, $message_start);
164+
# regex = "(?:$startStr)($signalRegex)";
165+
# So it matches startStr again at the beginning?
166+
# Wait, if we sliced it, the first chars ARE startStr.
167+
168+
# Let's try to match iteratively
169+
170+
full_regex_str = f"(?:{re.escape(start_str)})((?:{signal_or_group}){{ {length_min}, }})"
171+
if self.get_property(pid, 'reconstructBit'):
172+
# Perl: $signalRegex .= '(?:' . join('|',keys %endPatternLookupHash) . ')?';
173+
# This is appended to the repeating group? No.
174+
# Perl code:
175+
# $signalRegex .= qq[{$length_min,}];
176+
# if (defined(...reconstructBit...)) { $signalRegex .= '(?:' . join('|',keys %endPatternLookupHash) . ')?'; }
177+
# So it's ((?:p1|p2){min,}(?:partial)?)
178+
pass # Logic handled below manually or we construct regex precisely
179+
180+
# It seems cleaner to just use the regex to find the data part
181+
# Constructing complex regex in Python from dynamic parts
182+
183+
# Simplified approach:
184+
# 1. We are at start of potential message (startStr)
185+
# 2. Extract as many valid chunks as possible
186+
187+
# Re-implementing Perl's while loop over matches
188+
# The regex matches the *entire* message (start + data).
189+
190+
# Adjust signal_or_group for the repeating part
191+
signal_group_inner = "|".join(signal_regex_parts)
192+
193+
# Handle reconstructBit logic for regex end
194+
reconstruct_part = ""
195+
if self.get_property(pid, 'reconstructBit') and end_pattern_lookup:
196+
reconstruct_part = "(?:" + "|".join([re.escape(k) for k in end_pattern_lookup.keys()]) + ")?"
197+
198+
# We need to compile this regex
199+
# Note: Python f-string braces need escaping
200+
regex_pattern = f"(?:{re.escape(start_str)})((?:{signal_group_inner}){{{length_min},}}{reconstruct_part})"
201+
202+
try:
203+
matcher = re.compile(regex_pattern)
204+
except re.error as e:
205+
self._logging(f"MU Demod: Invalid regex for {pid}: {e}", 3)
206+
continue
207+
208+
# Perl iterates with /g
209+
for match in matcher.finditer(current_raw_data):
210+
data_part = match.group(1)
211+
212+
# Check length max
213+
length_max = self.check_property(pid, 'length_max', None)
214+
215+
# Determine signal width (number of chars per bit)
216+
# Perl uses unpack "(a$signal_width)*"
217+
signal_width = 0
218+
if self.get_property(pid, 'one'):
219+
signal_width = len(self.get_property(pid, 'one'))
220+
221+
if signal_width == 0:
222+
continue
223+
224+
# Split data_part into chunks
225+
chunks = [data_part[i:i+signal_width] for i in range(0, len(data_part), signal_width)]
226+
227+
# Handle the last chunk if it's partial (reconstructBit)
228+
last_chunk = chunks[-1]
229+
if len(last_chunk) < signal_width:
230+
# It might be a partial chunk
231+
pass
232+
233+
if length_max and len(chunks) > int(length_max):
234+
continue
235+
236+
bit_msg = []
237+
for chunk in chunks:
238+
if chunk in pattern_lookup:
239+
bit_msg.append(pattern_lookup[chunk])
240+
elif self.get_property(pid, 'reconstructBit') and chunk in end_pattern_lookup:
241+
bit_msg.append(end_pattern_lookup[chunk])
242+
else:
243+
# Should not happen if regex matched, unless regex was too loose
244+
pass
245+
246+
# Post Demodulation
247+
post_demod_method_name = self.check_property(pid, 'postDemodulation', None)
248+
if post_demod_method_name:
249+
method_name = post_demod_method_name.split('.')[-1]
250+
if hasattr(self, method_name):
251+
method = getattr(self, method_name)
252+
bit_msg_ints = [int(b) for b in bit_msg if b in '01'] # Filter 'F'?
253+
# Perl passes @bit_msg which contains '0','1','F'.
254+
# postDemodulation usually expects ints 0/1.
255+
# For now assuming 0/1.
256+
257+
try:
258+
# Convert to ints, handle 'F' if necessary (skip or map)
259+
# Most postDemo functions operate on bits.
260+
bit_msg_ints = [int(b) for b in bit_msg]
261+
rcode, ret_bits = method(f"Protocol_{pid}", bit_msg_ints)
262+
if rcode < 1:
263+
continue
264+
bit_msg = [str(b) for b in ret_bits]
265+
except ValueError:
266+
pass # Handle non-int bits
267+
268+
269+
# Formatting
270+
dispatch_bin = int(self.check_property(pid, 'dispatchBin', 0))
271+
272+
# Padding
273+
pad_with = int(self.check_property(pid, 'paddingbits', 4))
274+
while len(bit_msg) % pad_with > 0:
275+
bit_msg.append('0')
276+
277+
bit_str = "".join(bit_msg)
278+
279+
dmsg = ""
280+
if dispatch_bin == 1:
281+
dmsg = bit_str
282+
else:
283+
dmsg = self.bin_str_2_hex_str(bit_str)
284+
if self.check_property(pid, 'remove_zero', 0):
285+
dmsg = dmsg.lstrip('0')
286+
287+
preamble = self.check_property(pid, 'preamble', '')
288+
postamble = self.check_property(pid, 'postamble', '')
289+
290+
final_payload = f"{preamble}{dmsg}{postamble}"
291+
292+
# Module Match (Regex check)
293+
module_match = self.check_property(pid, 'modulematch')
294+
if module_match:
295+
if not re.search(module_match, final_payload):
296+
continue
297+
298+
decoded_messages.append({
299+
"protocol_id": pid,
300+
"payload": final_payload,
301+
"meta": {
302+
"bit_length": len(bit_str),
303+
"rssi": msg_data.get('R'),
304+
"clock": clock_abs
305+
}
306+
})
307+
308+
# Max repeats check?
309+
# Perl: last if ( $nrDispatch == AttrVal($name,'maxMuMsgRepeat', 4))
310+
# For now we yield all matches.
311+
312+
return decoded_messages

0 commit comments

Comments
 (0)