Julius2342 / pyvlx

PyVLX - controling VELUX windows with Python via KLF 200
GNU Lesser General Public License v3.0
77 stars 27 forks source link

Rain Sensor #67

Closed pergolafabio closed 3 years ago

pergolafabio commented 3 years ago

Hi, just a question

Is there a away to know if the rain sensor is detecting rain? regading the state of the windows? open/closed?

thnx in advance

pergolafabio commented 3 years ago

@Julius2342 , i have found something usefull , seems we can have the state of the rainsensor with this command :

image

Seems if the Minvalue !=0 , then its raining

any idea how i can make a script to se this command with HA? maybe i can make a rest sensor for that

thnx in advance

Julius2342 commented 3 years ago

hmm, do not really understand how a "limitation" may be used to detect the state of a sensor?

May I ask you to enable full logging of packets and wait for next rain?

Best

pergolafabio commented 3 years ago

Yes offcourse , can i enable full logging with that monitor.py , or do you want me to enable debug in HA?

Or is there an easy way to send that command? The value should now be 0 , for the minvalue... If it's not 0 , then its raining

Julius2342 commented 3 years ago

Hmm, when reading the documentation it sounds like you have to poll the values.

(so send a "GW_SET_IMITATION_REQ" with correct values and then wait for notifications?)

But still don't get this why this should be a "limitation".

pergolafabio commented 3 years ago

Maybe it's a limitation that the window can only be opened in a ventilation mode, and not fully opened?

Can you make me an example .py file how i can send that command, then i can test it coming days...

Would be a nice feature to have a rain sensor in HA

pergolafabio commented 3 years ago

some more info from the openhab community , they use it

image

pergolafabio commented 3 years ago

@Julius2342 , can you perhaps make me an modified version like the monitor.py file below? but offcourse with that other new command? GW_SET_IMITATION_REQ i am not sure how i can implement in in that example file

thnx a lot!

https://github.com/Julius2342/pyvlx/blob/master/examples/monitor.py

so i can easly run it when it rains or not

pergolafabio commented 3 years ago

@Julius2342 , you have some time for me to create a test script to poll that specific value?

thnx, appreciated!

pergolafabio commented 3 years ago

@Julius2342 do you have time to update your code to make use of the new frame? :-)

mago0211 commented 3 years ago

Hi @pergolafabio , you can look to my "Quick And Dirty" adaption to read out the limits. https://github.com/mago0211/pyvlx/tree/thing

(Adapt config in https://github.com/mago0211/pyvlx/blob/thing/example.py#L16)

You can see in the debug output the Notification e.g. REC: <FrameGetLimitationStatusNotification node_id="1" session_id="1" min_value="63487" max_value="51200" originator="Originator.EMERGENCY" limit_time="255"/>

max_value is C800hex and mean 100% Since I implemented this there has been no rain here to test other values :-)

Can you test this code and reply to me if it works?

pergolafabio commented 3 years ago

ah cool, i am on vacation right now, will have a look when iam back :) thnx for sharing! can we have this output also in a sensor in HA?

pergolafabio commented 3 years ago

@mago0211 , is it also possible to modify the velux component of HA, load it as a custom, so the limitation value can be be added as an custom attribute of the cover?

Btw , was not able to test yet, back next week from vacation, is it still not raining at your place? :-)

mago0211 commented 3 years ago

@pergolafabio

I updated my version for easier usage.

can we have this output also in a sensor in HA?

Yes that is the plan but first i must integrate a clean solution here. The path to Integration into HA is far.

pergolafabio commented 3 years ago

Ok, I'll have a try next week!

pergolafabio commented 3 years ago

Maybe i can run already your script as a command line sensor in HA... Not sure about the connections if it's possible to run 2 connections to the klf

mago0211 commented 3 years ago

Not sure about the connections if it's possible to run 2 connections to the klf

Yes that's possible

pergolafabio commented 3 years ago

Hey @mago0211 , i am back from vacation, so want to test it out too i am running HassOS with a Velux custom component in manifest.kson file there is a line :

"requirements": ["pyvlx==0.2.18"],

how can i change it, so yours commit/PR of pyvlx will be installed?

pergolafabio commented 3 years ago

hey @mago0211 i succeeded installing your commit with this command : pip install git+https://github.com/mago0211/pyvlx.git@add_limitations but when i try to run it, i receive this error?

any idea?

image

mago0211 commented 3 years ago

Hey @mago0211 , i am back from vacation, so want to test it out too i am running HassOS with a Velux custom component in manifest.kson file there is a line :

"requirements": ["pyvlx==0.2.18"],

how can i change it, so yours commit/PR of pyvlx will be installed?

Sorry i don't know how you can use directly a git version. Maybe "requirements": ["git+https://github.com/mago0211/pyvlx.git@add_limitations"]

hey @mago0211 i succeeded installing your commit with this command : pip install git+https://github.com/mago0211/pyvlx.git@add_limitations but when i try to run it, i receive this error?

any idea?

image

I have seen that the example in Readme is wrong. I have improved it. limit = await pyvlx.nodes['velux_links'].get_limitations() logger.info(limit.min_value)

pergolafabio commented 3 years ago

aha that logger.info line is only needed if i run it as a script in HA, right? i think its working now, i see some info about limitation now

SEND: <FrameGetLimitationStatus node_ids="[2]" session_id="1" originator="Originator.USER" />
REC: <FrameGetLimitationStatusConfirmation session_id="1" status="1"/>
REC: <FrameGetLimitationStatusNotification node_id="2" session_id="1" min_value="b'\x00'" max_value="b'\xf7'" originator="Originator.EMERGENCY" limit_time="255"/>

1) is there an easy way to already capture that info and sent it to HA with some command line sensor? or some other way? 2) i also receive error below, nothing todo with the limitation though, some error about the loop :

Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000165F964D3A0>
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 746, in call_soon
    self._check_closed()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 510, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

here is the example code:


import asyncio
import logging

from pyvlx import PyVLX, PYVLXLOG

async def main(loop):
    PYVLXLOG.setLevel(logging.DEBUG)
    stream_handler = logging.StreamHandler()
    stream_handler.setLevel(logging.DEBUG)
    PYVLXLOG.addHandler(stream_handler)

    pyvlx = PyVLX(host="192.168.0.18", password="xxx", loop=loop)
    await pyvlx.load_nodes()
    limit = await pyvlx.nodes['velux_links'].get_limitation()
    #logger.info(limit.min_value)
    await pyvlx.disconnect()

if __name__ == '__main__':
    LOOP = asyncio.get_event_loop()
    LOOP.run_until_complete(main(LOOP))
    LOOP.close()
pergolafabio commented 3 years ago

still a small error in the readme, you have there "get.limitations" it should be "get.limitation" ?

mago0211 commented 3 years ago

Sorry i cannot see get.limitations in the readme? Which line do you mean?

pergolafabio commented 3 years ago

sorry, i was wrong , the readme was correct, but you post was incorrect :)

image

pergolafabio commented 3 years ago

Hey @mago0211 can you help me once again? if i try the above script it works, i can get the limitations values

but i dont want to have an extra script that makes another connection to the KLF, cause its instable

so i wanted to load the velux component as a custom compnent, there is a init.py file, i tried adding those lines as below

image

but that gives this error below... so where exactly do i need to add that variable? so its in the same loop? if it works, i can for now hardcode it, to do a rest call and update a sensor

offcourse in the end , it would be better if a rls is avaible later, to integrate it

thnx again, appreciated!!!


2021-08-02 19:22:59 ERROR (MainThread) [homeassistant.setup] Error during setup of component velux
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/setup.py", line 249, in _async_setup_component
    result = await task
  File "/config/custom_components/velux/__init__.py", line 31, in async_setup
    await hass.data[DATA_VELUX].async_start()
  File "/config/custom_components/velux/__init__.py", line 72, in async_start
    limit = await self.pyvlx.nodes['velux_links'].get_limitation()
AttributeError: 'Window' object has no attribute 'get_limitation'
mago0211 commented 3 years ago

@pergolafabio Hmm, you are sure that the right version of pyvlx is loaded in Home Assistant for me it looks like Home Assistant load the default pyvlx version and overwrite the 'dev' version? Maybe it is better you write an external process with mqtt forwarding?

@Julius2342 does not seem to like this feature so I think it would be better to use another alternative. It's a pity. I have found a little example for a pyvlx to mqtt bridge https://github.com/3s1d/vlx2mqtt.

pergolafabio commented 3 years ago

hi,

yeah, i am loading the correct version, i have modified the manifest.json file like this:

"requirements": ["pyvlx @ git+https://github.com/mago0211/pyvlx.git@add_limitations"],

cause if i try your example script from putty , i get the limitation in the log, so the correct pyvlx is loaded :-)

for the moment i am using a command line sensor, with this project :https://github.com/PLCHome/velux-klf200-api works verry well, if it rains, the minvalue = 93 , if its not raining its 0 , so my automations are based on that value

would be great if your PR gets merged, so we can have a rain sensor in HA why doesnt @Julius2342 like your PR? its working perfect?

but any idea how i can change that velux component to get a rain sensor? i can then load it as a custom component there are no many improvemenst anyway in the velux integration anyway

pergolafabio commented 3 years ago

using below nodescript to get a command line sensor in HA, already using it for several weeks now but its better if we can get this in pyvlx

const velux = require('velux-klf200-api')
velux.on('NTF',(data)=>{
  console.log(data.minValue.value)
  return velux.end()
})
velux.connect('192.168.0.18',{})
.then(()=>{
  return velux.login('xxx')
})
.then((data)=>{
  return velux.sendCommand({ api: velux.API.GW_GET_LIMITATION_STATUS_REQ , sessionID: 1, indexArrayCount: 1, indexArray: [2], parameterID: 0, limitationType: 0 })
})
.catch((err)=>{
  console.log(err)
  return velux.end()
})
pergolafabio commented 3 years ago

or @mago0211 , or maybe another script i can use with your limitation, that takes the same connection to the klf, thats already present when starting HA ? not sure if you intercept that connection

mago0211 commented 3 years ago

Hi, can you run the following lines and send me the output. v_node = await self.pyvlx.nodes['velux_links'] _LOGGER.info(dir(v_node)) It would also be helpful you can share the full custom_component code then I can try it here

pergolafabio commented 3 years ago

Ok, will try it later, but you can just download the velux folder from here :

https://github.com/home-assistant/core/tree/master/homeassistant/components/velux

Place that folder in your custom component folder...

Also you need to change the manifest.json file, otherwise the official pyvlx is still installed, so change that line into

"requirements": ["pyvlx @ git+https://github.com/mago0211/pyvlx.git@add_limitations"],

mago0211 commented 3 years ago

Ok, i try this local and it works. I have changed requirements in manifest.json to "requirements": ["git+https://github.com/mago0211/pyvlx.git@add_limitations#pyvlx==0.2.20"]

And also rename the custom component and domain to avelux (not sure if it is needed) and then i can read the limitations.

Off topic: It would be really easy to integrate this in HomeAssistant but we must wait for @Julius2342 to accept my PR and create a new version.

pergolafabio commented 3 years ago

Ok, and how do you read the limitation then in HA, what did you change in the code?

mago0211 commented 3 years ago

I have only add two lines in async_start like your example to test this out.

l = await self.pyvlx.nodes["Treppenhaus"].get_limitation()
_LOGGER.info(l.max_value)
pergolafabio commented 3 years ago

Hmm , gonna test again, strange

pergolafabio commented 3 years ago

Great!! that was it, seems indeed the manifest was wrong, and probably your new pyvlx was not installed

woot! gonna now hardcode to update a sensor, i hope this can be merged soon, so we have a rainsensor :)

pergolafabio commented 3 years ago

allthough, the get limitation , is that only fired on start up on HA? or does it change, is this a loop ?

mago0211 commented 3 years ago

the klf gateway do not send a message if the limitation was changend. You must be pool in loop the limitations.

pergolafabio commented 3 years ago

yeah, i noticed, it didnt log me when it started raining how can i lets say request every 5 min the limitation? can you help me with that ? probably just a few lines of extra code in that init.py file

pergolafabio commented 3 years ago

will something like this work?

    async def async_start(self):
        """Start velux component."""
        _LOGGER.debug("Velux interface started")
        await self.pyvlx.load_scenes()
        await self.pyvlx.load_nodes()
        limit = await self.pyvlx.nodes['velux_links'].get_limitation()
        _LOGGER.warning("Velux minValue : %d", limit.min_value)
        while True:
            limit = await self.pyvlx.nodes['velux_links'].get_limitation()
            _LOGGER.warning("Velux minValue : %d", limit.min_value)
            await asyncio.sleep(60)

i'm no coder at all :-)

mago0211 commented 3 years ago

Really dirty solution

    async def async_start(self):
        """Start velux component."""
        _LOGGER.debug("Velux interface started")
        await self.pyvlx.load_scenes()
        await self.pyvlx.load_nodes()

        import asyncio
        while True:
            try:
                s = await self.pyvlx.nodes["Treppenhaus"].get_limitation()
                s.min_value()
                await asyncio.sleep(60 * 5)
            except asyncio.CancelledError:
                break

The "right" solution need more work.

pergolafabio commented 3 years ago

dirty is good for now , lets try... :)

pergolafabio commented 3 years ago

seems HA doesnt finish the startup when, keeps on loading velux component why is this needed? s.min_value()

is that mystyped?

pergolafabio commented 3 years ago

if do this, it works, i see in event log every 10 sec the minValue, but HA doesnt start , it waits for the Velux component :-)

2021-08-06 16:28:07 WARNING (MainThread) [homeassistant.bootstrap] Waiting on integrations to complete setup: velux

    async def async_start(self):
        """Start velux component."""
        _LOGGER.debug("Velux interface started")
        await self.pyvlx.load_scenes()
        await self.pyvlx.load_nodes()
        import asyncio
        while True:
            try:
                s = await self.pyvlx.nodes["velux_links"].get_limitation()
                #s.min_value()
                _LOGGER.warning(s.min_value)
                await asyncio.sleep(10)
            except asyncio.CancelledError:
                break
pergolafabio commented 3 years ago

ok, fixed it dirty, created another async def that i call, now i have a rain sensor in HA !!

i hope @Julius2342 can merge it now

pergolafabio commented 3 years ago

Fixed in : https://github.com/Julius2342/pyvlx/pull/71

pergolafabio commented 3 years ago

hey @mago0211 you removed the branch from your github

is there a way that i can use the merged version now? there is no release yet

before i had :

"requirements": ["git+https://github.com/mago0211/pyvlx.git@add_limitations"]

AlecRust commented 3 years ago

71 doesn't add a rain sensor to Home Assistant right? Any ideas what issue I should follow for that being added? 🙂

Being able to use my Velux window's rain sensor instead of relying on forecast information would be a game changer.

pergolafabio commented 3 years ago

its not implemented yet, i think we need first a pyvlx release before @mago0211 can work with a new sensor for HA

you can always load it as custom with that specfici commit, untill now, cause its merged i just dont know how i can change the manifest file now with that speficic PR

mago0211 commented 3 years ago

hey @mago0211 you removed the branch from your github

is there a way that i can use the merged version now? there is no release yet

before i had :

"requirements": ["git+https://github.com/mago0211/pyvlx.git@add_limitations"]

Hi,

you can now use the master branch from this repo directly "requirements": ["git+https://github.com/Julius2342/pyvlx.git@master"]

mago0211 commented 3 years ago

71 doesn't add a rain sensor to Home Assistant right? Any ideas what issue I should follow for that being added? slightly_smiling_face

Being able to use my Velux window's rain sensor instead of relying on forecast information would be a game changer.

Hi, Yes that's are correct. Currently there is no issue open.

I hope i can start work for HA util next weeks. I can then inform here when it is available for HA.