From 302266c00577e9ebb11b91fd000ac397271b4662 Mon Sep 17 00:00:00 2001
From: BenediktO <benedikt_o@web.de>
Date: Mon, 27 Jul 2020 08:32:30 +0200
Subject: ir_nec: Add option for automatic polarity detection

Provide an option to have the decoder automatically detect the IR signal's
polarity. Stick with active-low by default for backwards compatibility,
because this auto-detect implementation assumes that the capture starts
with an idle phase.

[ gsi: rephrased message and implementation, auto-detect off by default ]
---
 decoders/ir_nec/pd.py | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)

(limited to 'decoders/ir_nec/pd.py')

diff --git a/decoders/ir_nec/pd.py b/decoders/ir_nec/pd.py
index 0d79865..3c272db 100644
--- a/decoders/ir_nec/pd.py
+++ b/decoders/ir_nec/pd.py
@@ -47,7 +47,7 @@ class Decoder(srd.Decoder):
     )
     options = (
         {'id': 'polarity', 'desc': 'Polarity', 'default': 'active-low',
-            'values': ('active-low', 'active-high')},
+            'values': ('auto', 'active-low', 'active-high')},
         {'id': 'tolerance', 'desc': 'Timing tolerance (%)', 'default': 5},
         {'id': 'cd_freq', 'desc': 'Carrier Frequency', 'default': 0},
         {'id': 'extended', 'desc': 'Extended NEC Protocol',
@@ -199,7 +199,12 @@ class Decoder(srd.Decoder):
             cd_count = int(self.samplerate / self.options['cd_freq']) + 1
         prev_ir = None
 
-        active = 0 if self.options['polarity'] == 'active-low' else 1
+        if self.options['polarity'] == 'auto':
+            # Take sample 0 as reference.
+            curr_level, = self.wait({'skip': 0})
+            active = 1 - curr_level
+        else:
+            active = 0 if self.options['polarity'] == 'active-low' else 1
         self.is_extended = self.options['extended'] == 'yes'
         want_addr_len = 16 if self.is_extended else 8
 
-- 
cgit v1.2.3-70-g09d2