From f13f723a045553fa05793eab054e04745d16d256 Mon Sep 17 00:00:00 2001 From: Blake Blackshear Date: Wed, 26 Sep 2018 04:57:16 -0500 Subject: [PATCH] Add bitwise operations as template helpers (#16833) --- homeassistant/helpers/template.py | 12 ++++++++++++ tests/helpers/test_template.py | 30 ++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index d0d3fb457b1..c68aa311998 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -580,6 +580,16 @@ def regex_findall_index(value, find='', index=0, ignorecase=False): return re.findall(find, value, flags)[index] +def bitwise_and(first_value, second_value): + """Perform a bitwise and operation.""" + return first_value & second_value + + +def bitwise_or(first_value, second_value): + """Perform a bitwise or operation.""" + return first_value | second_value + + @contextfilter def random_every_time(context, values): """Choose a random value. @@ -617,6 +627,8 @@ ENV.filters['regex_match'] = regex_match ENV.filters['regex_replace'] = regex_replace ENV.filters['regex_search'] = regex_search ENV.filters['regex_findall_index'] = regex_findall_index +ENV.filters['bitwise_and'] = bitwise_and +ENV.filters['bitwise_or'] = bitwise_or ENV.globals['log'] = logarithm ENV.globals['sin'] = sine ENV.globals['cos'] = cosine diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 6f426c290c5..dc8106e0ed3 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -562,6 +562,36 @@ class TestHelpersTemplate(unittest.TestCase): """, self.hass) self.assertEqual('LHR', tpl.render()) + def test_bitwise_and(self): + """Test bitwise_and method.""" + tpl = template.Template(""" +{{ 8 | bitwise_and(8) }} + """, self.hass) + self.assertEqual(str(8 & 8), tpl.render()) + tpl = template.Template(""" +{{ 10 | bitwise_and(2) }} + """, self.hass) + self.assertEqual(str(10 & 2), tpl.render()) + tpl = template.Template(""" +{{ 8 | bitwise_and(2) }} + """, self.hass) + self.assertEqual(str(8 & 2), tpl.render()) + + def test_bitwise_or(self): + """Test bitwise_or method.""" + tpl = template.Template(""" +{{ 8 | bitwise_or(8) }} + """, self.hass) + self.assertEqual(str(8 | 8), tpl.render()) + tpl = template.Template(""" +{{ 10 | bitwise_or(2) }} + """, self.hass) + self.assertEqual(str(10 | 2), tpl.render()) + tpl = template.Template(""" +{{ 8 | bitwise_or(2) }} + """, self.hass) + self.assertEqual(str(8 | 2), tpl.render()) + def test_distance_function_with_1_state(self): """Test distance function with 1 state.""" self.hass.states.set('test.object', 'happy', {