def test_percent(self): """Test initialization with percent value.""" self.assertEqual(Position(position_percent=0).position_percent, 0) self.assertEqual(Position(position_percent=5).position_percent, 5) self.assertEqual(Position(position_percent=50).position_percent, 50) self.assertEqual(Position(position_percent=95).position_percent, 95) self.assertEqual(Position(position_percent=100).position_percent, 100)
def test_position(self): """Test initiaization with position value.""" self.assertEqual(Position(position=0).position, 0) self.assertEqual(Position(position=10).position, 10) self.assertEqual(Position(position=1234).position, 1234) self.assertEqual(Position(position=12345).position, 12345) self.assertEqual(Position(position=51200).position, 51200)
def test_known(self): """Test 'known' property.""" self.assertTrue(Position(Parameter(raw=b'\x12\x00')).known) self.assertTrue(Position(Parameter(raw=b'\xC8\x00')).known) self.assertFalse(Position(Parameter(raw=b'\xF7\xFF')).known) # Well, not really know. But at least not unknown: self.assertTrue(Position(Parameter(raw=b'\xD2\x00')).known)
def test_open_closed(self): """Test open and closed property.""" position_open = Position(position_percent=0) self.assertFalse(position_open.closed) self.assertTrue(position_open.open) position_closed = Position(position_percent=100) self.assertTrue(position_closed.closed) self.assertFalse(position_closed.open) position_half = Position(position_percent=50) self.assertFalse(position_half.closed) self.assertFalse(position_half.open)
async def async_set_cover_position(self, **kwargs: Any) -> None: """Move the cover to a specific position.""" position_percent = 100 - kwargs[ATTR_POSITION] await self.node.set_position( Position(position_percent=position_percent), wait_for_completion=False )
async def handle(request): reqType = request.content_type if (reqType != 'application/json'): response = {'result': 'fail', 'reason': 'unsupported request type'} return web.json_response(response) message = await request.json() try: NODE = message['node'] POS = int(message['position']) except: response = { 'result': 'fail', 'reason': 'node or position not provided' } return web.json_response(response) try: await pyvlx.nodes[NODE].set_position(Position(position_percent=POS), wait_for_completion=False) except KeyError: response = {'result': 'fail', 'reason': 'device unknown'} return web.json_response(response) except Exception as e: response = { 'result': 'fail', 'reason': 'exception during execution', 'message': str(e) } return web.json_response(response) newPos = pyvlx.nodes[NODE].position data = {'result': 'ok', 'device': NODE, 'position': str(newPos)} return web.json_response(data)
async def url_set(request): try: NODE = request.match_info.get('device') POS = int(request.match_info.get('position')) except: response = { 'result': 'fail', 'reason': 'node or position not provided' } return web.json_response(response) try: await pyvlx.nodes[NODE].set_position(Position(position_percent=POS), wait_for_completion=False) except KeyError: response = {'result': 'fail', 'reason': 'device unknown'} return web.json_response(response) except Exception as e: response = { 'result': 'fail', 'reason': 'exception during execution', 'message': str(e) } return web.json_response(response) newPos = pyvlx.nodes[NODE].position data = {'result': 'ok', 'device': NODE, 'position': str(newPos)} return web.json_response(data)
async def async_set_cover_position(self, **kwargs): """Move the cover to a specific position.""" if ATTR_POSITION in kwargs: position_percent = 100 - kwargs[ATTR_POSITION] from pyvlx import Position await self.node.set_position( Position(position_percent=position_percent))
async def async_set_cover_tilt_position(self, **kwargs): """Move cover tilt to a specific position.""" position_percent = 100 - kwargs[ATTR_TILT_POSITION] orientation = Position(position_percent=position_percent) await self.node.set_orientation( orientation=orientation, wait_for_completion=False )
def test_frame_from_raw(self): """Test parse FrameCommandSendRequest from raw.""" frame = frame_from_raw(self.EXAMPLE_FRAME) self.assertTrue(isinstance(frame, FrameCommandSendRequest)) self.assertEqual(frame.node_ids, [1, 2, 3]) self.assertEqual(Position(frame.parameter).position_percent, 75) self.assertEqual(frame.session_id, 1000) self.assertEqual(frame.originator, Originator.RAIN)
def test_bytes(self): """Test FrameCommandSendRequest with NO_TYPE.""" frame = FrameCommandSendRequest( node_ids=[1, 2, 3], parameter=Position(position_percent=75), session_id=1000, originator=Originator.RAIN, ) self.assertEqual(bytes(frame), self.EXAMPLE_FRAME)
async def main(loop): global running global pyvlx, mqttc logging.debug(("klf200 : %s") % (VLX_HOST)) logging.debug(("MQTT broker : %s") % (MQTT_HOST)) logging.debug((" port : %s") % (str(MQTT_PORT))) logging.debug(("statustopic : %s") % (str(STATUSTOPIC))) # Connect to the broker and enter the main loop result = mqttc.connect(MQTT_HOST, MQTT_PORT, 60) while result != 0: logging.info("Connection failed with error code %s. Retrying", result) await asyncio.sleep(10) result = mqttc.connect(MQTT_HOST, MQTT_PORT, 60) mqttc.publish(STATUSTOPIC, "STARTED", retain=True) # seems as it must be prior to mqttc loop. otherwise mqtt will not receiving anything... pyvlx = PyVLX(host=VLX_HOST, password=VLX_PW, loop=loop) await pyvlx.load_nodes() # Define callbacks mqttc.on_connect = mqtt_on_connect mqttc.on_message = mqtt_on_message mqttc.on_disconnect = mqtt_on_disconnect mqttc.loop_start() await asyncio.sleep(2) mqttc.publish(STATUSTOPIC, "KLF200_available", retain=True) logging.debug(("vlx nodes : %s") % (len(pyvlx.nodes))) for node in pyvlx.nodes: logging.debug((" %s") % (node.name)) #register callbacks for node in pyvlx.nodes: if isinstance(node, OpeningDevice): node.register_device_updated_cb(vlx_cb) logging.debug(("watching: %s") % (node.name)) while running: await asyncio.sleep(1) #see if we received some mqtt commands for name, value in nodes.items(): if value >= 0: nodes[name] = -1 #mark execuded await pyvlx.nodes[name].set_position( Position(position_percent=value)) logging.info("Disconnecting from broker") # Publish a retained message to state that this client is offline mqttc.publish(STATUSTOPIC, "DISCONNECTED", retain=True) mqttc.disconnect() mqttc.loop_stop() await pyvlx.disconnect()
async def vlx_set_position(node, pos): if pos == "close": pos = "closed" pct = 0 if pos == "open" else 100 if pos == "closed" else eval( pos) if pos.isdigit() else None if pct is None: logger.error("invalid position for @%s: %s" % (node, pos)) return logger.info("setting position @%s: %s" % (node, pct)) await vlx.nodes[node].set_position(Position(position_percent=pct), wait_for_completion=False)
def test_str(self): """Test string representation of FrameCommandSendRequest.""" functional_para = {"fp3": Position(position=12345)} functional_parameter = {} for i in range(1, 17): key = "fp%s" % (i) if key in functional_para: functional_parameter[key] = functional_para[key] else: functional_parameter[key] = bytes(2) frame = FrameCommandSendRequest(node_ids=[1, 2, 3], parameter=Position(position=12345), **functional_parameter, session_id=1000, originator=Originator.RAIN) self.assertEqual( str(frame), '<FrameCommandSendRequest node_ids="[1, 2, 3]" parameter="24 %" ' 'functional_parameter="fp1: 0 %, fp2: 0 %, fp3: 24 %, fp4: 0 %, fp5: 0 %, fp6: 0 %, fp7: 0 %, ' 'fp8: 0 %, fp9: 0 %, fp10: 0 %, fp11: 0 %, fp12: 0 %, fp13: 0 %, fp14: 0 %, fp15: 0 %, fp16: 0 %, " ' 'session_id="1000" originator="Originator.RAIN"/>', )
def test_bytes(self): """Test FrameNodeStatePositionChangedNotification.""" frame = FrameNodeStatePositionChangedNotification() frame.node_id = 5 frame.state = 5 frame.current_position = Position(position=51200) frame.target = Position(position=51200) frame.current_position_fp1 = Position() frame.current_position_fp2 = Position() frame.current_position_fp3 = Position() frame.current_position_fp4 = Position() frame.remaining_time = 0 frame.timestamp = 1288634368 self.assertEqual(bytes(frame), self.EXAMPLE_FRAME)
def test_frame_from_raw(self): """Test parse FrameNodeStatePositionChangedNotification from raw.""" frame = frame_from_raw(self.EXAMPLE_FRAME) self.assertTrue( isinstance(frame, FrameNodeStatePositionChangedNotification)) self.assertEqual(frame.node_id, 5) self.assertEqual(frame.state, 5) self.assertEqual(Position(frame.current_position).position, 51200) self.assertEqual(Position(frame.target).position, 51200) self.assertEqual(Position(frame.current_position_fp1).position, 63487) self.assertEqual(Position(frame.current_position_fp2).position, 63487) self.assertEqual(Position(frame.current_position_fp3).position, 63487) self.assertEqual(Position(frame.current_position_fp4).position, 63487) self.assertEqual(frame.remaining_time, 0) self.assertEqual(frame.timestamp, 1288634368)
def test_exception(self): """Test wrong initialization of Position.""" with self.assertRaises(PyVLXException): Position(position=2.5) with self.assertRaises(PyVLXException): Position(position=-1) with self.assertRaises(PyVLXException): Position(position=51201) with self.assertRaises(PyVLXException): Position(position_percent=2.5) with self.assertRaises(PyVLXException): Position(position_percent=-1) with self.assertRaises(PyVLXException): Position(position_percent=101) with self.assertRaises(PyVLXException): Parameter(raw=b"\x00\x00\x00") with self.assertRaises(PyVLXException): Parameter(raw="\x00\x00")
async def main(loop): """Demonstrate functionality of PyVLX.""" pyvlx = PyVLX('pyvlx.yaml', loop=loop) # Alternative: # pyvlx = PyVLX(host="192.168.2.127", password="******", loop=loop) # Runing scenes: await pyvlx.load_scenes() await pyvlx.scenes["All Windows Closed"].run() # Changing position of windows: await pyvlx.load_nodes() await pyvlx.nodes['Bath'].open() await pyvlx.nodes['Bath'].close() await pyvlx.nodes['Bath'].set_position(Position(position_percent=45)) # Changing of on-off switches: # await pyvlx.nodes['CoffeeMaker'].set_on() # await pyvlx.nodes['CoffeeMaker'].set_off() # You can easily rename nodes: # await pyvlx.nodes["Window 10"].rename("Window 11") await pyvlx.disconnect()
def test_no_position(self): """Test empty Position object.""" self.assertEqual(Position().raw, b'\xF7\xFF')
async def main(loop): global running global pyvlx logging.debug("klf200 : %s" % VLX_HOST) logging.debug("MQTT broker : %s" % MQTT_HOST) if MQTT_LOGIN: logging.debug(" port : %s" % (str(MQTT_PORT))) logging.debug(" login : %s" % MQTT_LOGIN) logging.debug("statustopic : %s" % (str(STATUSTOPIC))) logging.debug("roottopic : %s" % (str(ROOT_TOPIC))) pyvlx = PyVLX(host=VLX_HOST, password=VLX_PW, loop=loop) await pyvlx.load_nodes() logging.debug("vlx nodes : %s" % (len(pyvlx.nodes))) for node in pyvlx.nodes: logging.debug(" %s" % node.name) # set login and password, if available if MQTT_LOGIN: mqttc.username_pw_set(MQTT_LOGIN, MQTT_PASSWORD) # Connect to the broker and enter the main loop result = mqttc.connect(MQTT_HOST, MQTT_PORT, 60) while result != 0: logging.info("Connection failed with error code %s. Retrying", result) await asyncio.sleep(10) result = mqttc.connect(MQTT_HOST, MQTT_PORT, 60) # Define callbacks mqttc.on_connect = mqtt_on_connect mqttc.on_message = mqtt_on_message mqttc.on_disconnect = mqtt_on_disconnect mqttc.loop_start() await asyncio.sleep(1) # register callbacks for node in pyvlx.nodes: if isinstance(node, OpeningDevice): node.register_device_updated_cb(vlx_cb) logging.debug("watching: %s" % node.name) while running: await asyncio.sleep(1) # see if we received some mqtt commands for name, value in nodes.items(): if str(value) == "UP": logging.debug("%s is going up", name) nodes[name] = -1 await pyvlx.nodes[name].open(wait_for_completion=False) continue if str(value) == "DOWN": logging.debug("%s is going down", name) nodes[name] = -1 await pyvlx.nodes[name].close(wait_for_completion=False) continue if str(value) == "STOP": logging.debug("%s is stopped", name) nodes[name] = -1 await pyvlx.nodes[name].stop(wait_for_completion=False) continue if int(float(value)) >= 0: logging.debug("setting %s to value %s" % (name, value)) nodes[name] = -1 # mark executed await pyvlx.nodes[name].set_position( Position(position_percent=int(float(value))), wait_for_completion=False) logging.info("Disconnecting from broker") # Publish a retained message to state that this client is offline mqttc.publish(ROOT_TOPIC + '/' + STATUSTOPIC, "DISCONNECTED", retain=True) mqttc.disconnect() mqttc.loop_stop() await pyvlx.disconnect()
def test_from_to_percent(self): """Test position percent output from position percent input""" self.assertEqual(Position.to_percent(Position.from_percent(0)), 0) self.assertEqual(Position.to_percent(Position.from_percent(1)), 1) self.assertEqual(Position.to_percent(Position.from_percent(25)), 25) self.assertEqual(Position.to_percent(Position.from_percent(50)), 50) self.assertEqual(Position.to_percent(Position.from_percent(75)), 75) self.assertEqual(Position.to_percent(Position.from_percent(99)), 99) self.assertEqual(Position.to_percent(Position.from_percent(100)), 100)
def test_to_percent(self): """Test position percent output from position int input""" self.assertEqual(Position.to_percent(Parameter.from_int(0)), 0) self.assertEqual(Position.to_percent(Parameter.from_int(1)), 0) self.assertEqual(Position.to_percent(Parameter.from_int(3)), 0) self.assertEqual(Position.to_percent(Parameter.from_int(256)), 1) self.assertEqual(Position.to_percent(Parameter.from_int(512)), 1) self.assertEqual(Position.to_percent(Parameter.from_int(5120)), 10) self.assertEqual(Position.to_percent(Parameter.from_int(12800)), 25) self.assertEqual(Position.to_percent(Parameter.from_int(25600)), 50) self.assertEqual(Position.to_percent(Parameter.from_int(38400)), 75) self.assertEqual(Position.to_percent(Parameter.from_int(50688)), 99) self.assertEqual(Position.to_percent(Parameter.from_int(51050)), 100) self.assertEqual(Position.to_percent(Parameter.from_int(51200)), 100)
def test_str(self): """Test string representation.""" self.assertEqual(str(Position(Parameter(raw=b'\xF7\xFF'))), "UNKNOWN") self.assertEqual(str(Position(position_percent=50)), "50 %")
def test_raw(self): """Test raw assignement.""" self.assertEqual(Position(Parameter(raw=b'\x00\x00')).raw, b'\x00\x00') self.assertEqual(Position(Parameter(raw=b'\x0A\x05')).raw, b'\x0A\x05') self.assertEqual(Position(Parameter(raw=b'\xC8\x00')).raw, b'\xC8\x00')
def test_conversion(self): """Test conversion from one form to other.""" self.assertEqual(Position(Parameter(raw=b'\x0A\x05')).position, 2565) self.assertEqual(Position(position_percent=50).position, 25600) self.assertEqual(Position(position=12345).position_percent, 24)