Coder Social home page Coder Social logo

pyvera's People

Contributors

alanfischer avatar arjenfvellinga avatar brandond avatar colohan avatar dahlo avatar dependabot[bot] avatar digitlength avatar fabaff avatar guerrerotook avatar jamespcole avatar jnewland avatar jwater7 avatar markjenniskens avatar maximvelichko avatar patrik3k avatar pavoni avatar philhawthorne avatar rhooper avatar robjohnson189 avatar sdague avatar sresam89 avatar toggledbits avatar tsvi avatar vangorra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyvera's Issues

Vera thread dying?

Have seen cases where Vera stops updating. Suspect the poll thread has died - but no errors in the log.

Remotes recognised within Home Assistant

As it currently stands there appears to be no support for the use of Z- Wave “remote controllers” in HA via Vera. As an example I can use the Aeotec Minimote and create automations through HA, because it is recognised as a sensor. With the Fibaro KeyFob, it is not recognised at all… this means i have to create scenes on Vera for it to work, which is not ideal.

My intentions with my VeraPlus hub is for it to be used solely as a Z-Wave hub and nothing more.
be751f81a6a9fd1cb4368c1e07d6f235ad3ae4a2

thermostat support

... would be very nice as well. I have a couple of danfoss z-wave thermostats and of course would love to be able to control them via home-assistant.

Changing Thermostat Operation Mode broken

This is a followup to home-assistant/core#5828

Changing the Operation Mode for Thermostats seems to be broken. To ensure we're all on the same page I'm using Home Assistant 0.39.1, however this issue was first reported in Home Assistant 0.37.

I've increased the logging level, to see what is going on when changing the Operation Mode for my Living Room thermostat. For reference, it is a Remotec ZXT-120 IR controller paired with a Vera Lite. It works in Home Assistant 0.36.

Off -> Cool

17-02-27 20:43:31 DEBUG (Thread-10) [pyvera] Result of vera_request with payload {'id': 'lu_action', 'serviceId': ('urn:upnp-org:serviceId:HVAC_UserOperatingMode1',), 'action': 'SetSetModeTarget', 'NewModeTarget': 'CoolOn'}: ERROR: Device does not handle service/action

No action is taken from the ZXT-120

Device State Off - Setting Temp to 22

17-02-27 20:46:04 INFO (MainThread) [homeassistant.core] Bus:Handling <Event call_service[L]: service_data=temperature=34, entity_id=climate.living_room_ac, service=set_temperature, domain=climate, service_call_id=140218452162264-7>
17-02-27 20:46:04 DEBUG (Thread-12) [pyvera] Set variable: CurrentSetpoint using service_id: urn:upnp-org:serviceId:TemperatureSetpoint1
17-02-27 20:46:04 DEBUG (Thread-12) [pyvera] Result of vera_request with payload {'id': 'lu_action', 'serviceId': 'urn:upnp-org:serviceId:TemperatureSetpoint1', 'action': 'SetCurrentSetpoint', 'NewCurrentSetpoint': 34.0}: { "u:SetCurrentSetpointResponse": { "JobID": "17875" } }
17-02-27 20:46:04 INFO (Vera Poll Thread) [pyvera.subscribe] Poll returned
17-02-27 20:46:04 DEBUG (Thread-12) [pyvera] Set variable: CurrentSetpoint using service_id: urn:upnp-org:serviceId:TemperatureSetpoint1_Heat
17-02-27 20:46:04 DEBUG (Thread-12) [pyvera] Result of vera_request with payload {'id': 'lu_action', 'serviceId': 'urn:upnp-org:serviceId:TemperatureSetpoint1_Heat', 'action': 'SetCurrentSetpoint', 'NewCurrentSetpoint': 34.0}: { "u:SetCurrentSetpointResponse": { "JobID": "17876" } }
17-02-27 20:46:04 DEBUG (Thread-12) [pyvera] Set variable: CurrentSetpoint using service_id: urn:upnp-org:serviceId:TemperatureSetpoint1_Cool
17-02-27 20:46:04 DEBUG (Thread-12) [pyvera] Result of vera_request with payload {'id': 'lu_action', 'serviceId': 'urn:upnp-org:serviceId:TemperatureSetpoint1_Cool', 'action': 'SetCurrentSetpoint', 'NewCurrentSetpoint': 34.0}: { "u:SetCurrentSetpointResponse": { "JobID": "17877" } }
17-02-27 20:46:04 INFO (MainThread) [homeassistant.core] Bus:Handling <Event service_executed[L]: service_call_id=140218452162264-7>
17-02-27 20:46:04 DEBUG (MainThread) [homeassistant.components.websocket_api] WS 140217463741184: Sending {'id': 12, 'type': 'result', 'success': True, 'result': None}
17-02-27 20:46:04 INFO (Thread-7) [homeassistant.components.device_tracker.nmap_tracker] Scanning...
17-02-27 20:46:05 INFO (Vera Poll Thread) [pyvera.subscribe] Poll returned
17-02-27 20:46:05 INFO (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=climate.living_room_ac, old_state=<state climate.living_room_ac=Off; current_temperature=30, temperature=34.5, friendly_name=Living Room AC, fan_mode=Auto, battery_level=100%, unit_of_measurement=°C, operation_mode=Off, Vera Device Id=18, fan_list=['On', 'Auto', 'Cycle'], max_temp=35, min_temp=7, operation_list=['Heat', 'Cool', 'Auto Changeover', 'Off'] @ 2017-02-27T20:41:42.372612+11:00>, new_state=<state climate.living_room_ac=Off; current_temperature=30, temperature=34.0, friendly_name=Living Room AC, fan_mode=Auto, battery_level=100%, unit_of_measurement=°C, operation_mode=Off, Vera Device Id=18, fan_list=['On', 'Auto', 'Cycle'], max_temp=35, min_temp=7, operation_list=['Heat', 'Cool', 'Auto Changeover', 'Off'] @ 2017-02-27T20:41:42.372612+11:00>>
17-02-27 20:46:06 DEBUG (MainThread) [homeassistant.components.websocket_api] WS 140217463741184: Sending {'id': 2, 'type': 'event', 'event': {'time_fired': datetime.datetime(2017, 2, 27, 9, 46, 5, 965904, tzinfo=<UTC>), 'event_type': 'state_changed', 'data': {'entity_id': 'climate.living_room_ac', 'old_state': <state climate.living_room_ac=Off; current_temperature=30, temperature=34.5, friendly_name=Living Room AC, fan_mode=Auto, battery_level=100%, unit_of_measurement=°C, operation_mode=Off, Vera Device Id=18, fan_list=['On', 'Auto', 'Cycle'], max_temp=35, min_temp=7, operation_list=['Heat', 'Cool', 'Auto Changeover', 'Off'] @ 2017-02-27T20:41:42.372612+11:00>, 'new_state': <state climate.living_room_ac=Off; current_temperature=30, temperature=34.0, friendly_name=Living Room AC, fan_mode=Auto, battery_level=100%, unit_of_measurement=°C, operation_mode=Off, Vera Device Id=18, fan_list=['On', 'Auto', 'Cycle'], max_temp=35, min_temp=7, operation_list=['Heat', 'Cool', 'Auto Changeover', 'Off'] @ 2017-02-27T20:41:42.372612+11:00>}, 'origin': 'LOCAL'}}

No action is taken by the ZXT-120

Off -> Heat

17-02-27 20:47:44 DEBUG (MainThread) [homeassistant.components.websocket_api] WS 140217463741184: Received {'service_data': {'entity_id': 'climate.living_room_ac', 'operation_mode': 'Heat'}, 'type': 'call_service', 'service': 'set_operation_mode', 'domain': 'climate', 'id': 13}
17-02-27 20:47:44 INFO (MainThread) [homeassistant.core] Bus:Handling <Event call_service[L]: service_data=entity_id=climate.living_room_ac, operation_mode=Heat, service=set_operation_mode, domain=climate, service_call_id=140218452162264-8>
17-02-27 20:47:45 DEBUG (Thread-1) [pyvera] Result of vera_request with payload {'id': 'lu_action', 'serviceId': ('urn:upnp-org:serviceId:HVAC_UserOperatingMode1',), 'action': 'SetSetModeTarget', 'NewModeTarget': 'HeatOn'}: ERROR: Device does not handle service/action
17-02-27 20:47:45 INFO (MainThread) [homeassistant.core] Bus:Handling <Event service_executed[L]: service_call_id=140218452162264-8>
17-02-27 20:47:45 DEBUG (MainThread) [homeassistant.components.websocket_api] WS 140217463741184: Sending {'id': 13, 'type': 'result', 'success': True, 'result': None}
17-02-27 20:47:48 INFO (Thread-3) [homeassistant.components.device_tracker.nmap_tracker] Scanning...
17-02-27 20:47:49 DEBUG (Thread-5) [homeassistant.components.device_tracker.bluetooth_tracker] Bluetooth devices discovered = 0
17-02-27 20:47:49 DEBUG (Thread-5) [homeassistant.components.device_tracker.bluetooth_tracker] Scanning AC:37:43:79:4D:C1
17-02-27 20:47:50 DEBUG (Thread-5) [homeassistant.components.device_tracker.bluetooth_tracker] Scanning 60:92:17:AF:11:E3
17-02-27 20:47:50 INFO (Thread-3) [homeassistant.components.device_tracker.nmap_tracker] nmap scan successful
17-02-27 20:47:53 INFO (Vera Poll Thread) [pyvera.subscribe] Poll returned

No action is taken by the ZXT-120

So it seems there's an issue with whatever is throwing ERROR: Device does not handle service/action.

Hope this helps!

How to find switch by name?

Sorry - This isn't a problem with pyvera necessarily, but I haven't found any code examples or detailed docs to help me figure this out.. (my Python Newbie status is showing)..

The short version is that I need to find a device (switch for this example) by name, because I dont trust that devices[4] for example, would always return the same device, especially if I add/delete devices from my Vera.

So - using the example code on this site, I do:

controller = pyvera.VeraController("http://192.168.1.185:3480/")
devices = controller.get_devices('On/Off Switch')
devices
and I get:

devices
[VeraSwitch (id=6 category=On/Off Switch name=Kitchen Lights), VeraSwitch (id=31 category=On/Off Switch name=Porch light), VeraSwitch (id=64 category=On/Off Switch name=Pool pump), VeraSwitch (id=173 category=On/Off Switch name=Turtle Filter), VeraSwitch (id=174 category=On/Off Switch name=Christmas Lights)]

devices[1] is the Porch light, but I dont want to hardcode that in my python code because if I ever deleted kitchen lights, then the porch light would presumably become devices[0]..

In Powershell, I'd do something like:
$dev=$Devices | where {$_.name -eq "Porch Light"}
to return just the object in the list that I could then use the .is_switched_on() and other functions, but I can't figure out the python equivalent. I've tried to read substrings, etc.. but everything is giving me an error that seems to be related to the "VeraSwitch" type not being compatible with the string routines..

Where am I going wrong? Does someone have some simple example code or let me know where I'm going wrong? Even better - Is there a good forum for users of pyvera? I feel like this is NOT the place for such discussions, but I dont know where else to go.

Thanks in advance!!
Steve

Linear GD00Z-4 garage opener

Hello,

I have a Linear GD00Z-4 garage opener paired with Vera. However, it is not showing in my Home Assistant. When I browse http://vera_ip:3480/data_request?id=lu_sdata I can see the garage opener as one of devices. What I am missing? Any help will be much appreciated.

Netatmo Thermostat issue

I get a pyvera error whilst it's trying to figure out my netatmo thermostat that has been added to vera.

Error is:


Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(None)
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/helpers/entity.py", line 245, in async_update_ha_state
    attr = self.state_attributes or {}
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/components/climate/__init__.py", line 417, in state_attributes
    self._convert_for_display(self.current_temperature),
  File "/usr/local/lib/python3.5/dist-packages/homeassistant/components/climate/vera.py", line 112, in current_temperature
    return self.vera_device.get_current_temperature()
  File "/root/.homeassistant/deps/pyvera/__init__.py", line 841, in get_current_temperature
    return float(self.get_value('temperature'))
TypeError: float() argument must be a string or a number, not 'NoneType'

Thermostat xml from vera looks like:
&lt;device name="my thermostat" altid="" id="169" category="5" subcategory="-1" room="0" parent="0" ip="xxx.xxx.xxx.xxx" currentTemperature="22.2" batterylevel="100"/&gt;

VeraDimmer.get_color() and VeraDimmer.set_color() don't seem to be working

I am using PyVera CommitId: e2c527f (latest master at time of writing this).

I am using Vera Hub Plus with F/W: 1.7.3831 (latest F/W at time of writing this)
I had originally tried with F/W "1.7.3307". Both Firmware versions fail to let me get/set color.

I am using Philips Hue Light as example. I am able to get/set colors from the Vera app (3.17) on an IPhone.

I am able to get/set brightness and power.

I am willing to help resolve this if you know where to start looking. I used the example app "device_listener.py" to track color changes I made in the iphone Vera app and it did not show anything related to color in the payload. The payload from device_listener looked as follows and didn't change in value between color changes, but it does re-print the same payload when color changes:

"
Living Room_10: {u'category': 2, u'status': u'1', u'room': u'1', u'parent': u'6', u'altid': u'hueLamp_4', u'level': u'100', u'commFailure': u'0', u'name': u'Living Room', 'categoryName': u'Dimmable Switch', u'id': u'10', u'subcategory': u'-1'}
"

VeraLite dimmers and locks

For whatever reason, my VeraLite (UI 5, fw 1.5.672) returns different category names for dimmers and door locks than pyvera expects.

Specifically, instead of "Dimmable Switch", VeraLite returns "Dimmable Light" and instead of "Doorlock" it returns "Door lock".

Home Assistant can't find either my dimmers or my lock unless I change the strings in both pyvera/init.py and homeassistant/components/vera.py.

Let me know if you need more information or if I can help out.

variableset request--set the value of a state variable

It does not appear that there is a variableset request in current pyvera, so there seems to be no way to set the value of a state variable with it.

There is set_service_value(), but I feel this is misnamed. What this function actually does is execute a UPnP action, as long as its name begins with "Set", which not all do and that's a separate issue I mentioned in issue #108. It looks like there is a bit of a disconnect between what actions like "SetTarget" really do, and the ability to set values in state variables. The former and latter may appear on the surface to do the same thing, but they are notably different to Vera.

How, for example, might one set the CurrentLevel variable in service urn:micasaverde-com:serviceId:GenericSensor1 to 123? There seems to be no way... but one can do it easily:

http://ip_address:3480/data_request?id=variableset&DeviceNum=nnn&serviceId=urn:micasaverde-com:serviceId:GenericSensor1&Variable=CurrentLevel&Value=123

There should be a set_complex_value( device, serviceId, variable, value ) that does this. And IMO, set_service_value() should be deprecated--if issue #108 is addressed, call_service() could/should then be used instead.

I have a bit of code I wrote that you may want/use

I wrote the attached file and what it does is is leverages upnp to grab the available services their attributes and methods. it also grabs information from /data_request?id=invoke to fill in the missing bits. It auto generates code for classes for the different services that are available. and in these classes are the default attributes, properties and also methods that can be used for that specific service.

By utilizing the services list in a device when requesting the information from the Vera you are able to build the classes for the devices dynamically. But this should help to expose the whole of the Vera API.

I do not know if this is of interest to you or not. But if it is something you can use in whole, or a part there of. You are more then welcome to.

This is not a final written version it needs quite a bit of cleanup. but it is a good proof of concept.

It writes the files into %APPDATA%\MiCasaVerde_Vera in Windows and to ~.MiCasaVerde_Vera on linux.

Nice thing is it also creates any classes needed for the plugins as well. So no need to have to support a plugin by direct code
vera_build.zip

Vera Thermostat not reporting correct heat setpoint state in DeviceInfo area

I have two different model zwave thermostats (Trane and Honeywell) connected to Vera and pyvera is incorrectly reporting the "heat" setpoint for both of these devices when the thermostats run their internal schedulers. Vera is showing the correct information for both thermostats, but when pyvera parses the state information, it is not correctly parsing the returned values. I suspect this is because "CurrentSetpoint" is used as the variable name for 3 different state variables internally (see XML below).

veraxml.pdf

My python is pretty rudimentary but I've traced back the source of the problem to how the subscription registry updates the state information. Using pyvera's function

get_complex_value("CurrentSetpoint") directly from the controller returns the correct values for both thermostats' heat setpoint, but querying the state info from the subscription registry yields incorrect values:

devices
[VeraThermostat (id=37 category=Thermostat name=Upstairs Temp), VeraArmableDevice (id=37 category=Thermostat name=Upstairs Temp), VeraThermostat (id=55 category=Thermostat name=Downstairs Temp)]
devices[0].get_complex_value("CurrentSetpoint")
'66.00'
devices[2].get_complex_value("CurrentSetpoint")
'69.00'
devices[0].get_all_values()
{'name': 'Upstairs Temp', 'altid': '19', 'id': 37, 'category': 5, 'subcategory': 1, 'room': 0, 'parent': 1, 'fanmode': 'Auto', 'hvacstate': 'Idle', 'mode': 'HeatOn', 'setpoint': '78.00', 'heat': '78.00', 'cool': '78.00', 'status': '0', 'commFailure': '0', 'lasttrip': '1527243354', 'tripped': '0', 'armed': '0', 'armedtripped': '0', 'temperature': '70.00', 'state': -1, 'comment': '', 'categoryName': 'Thermostat'}
devices[2].get_all_values()
{'name': 'Downstairs Temp', 'altid': '35', 'id': 55, 'category': 5, 'subcategory': 1, 'room': 0, 'parent': 1, 'fanmode': 'Auto', 'hvacstate': 'Idle', 'mode': 'HeatOn', 'temperature': '69.00', 'setpoint': '78.00', 'heat': '78.00', 'cool': '78.00', 'status': '0', 'light': '0.2', 'state': -1, 'comment': '', 'categoryName': 'Thermostat'}

Looking at the information above, I believe that the subscription registry should be using the variable "AllSetpoints" from Vera and parse the first two numbers (heat, cool) to set the correct state information for Vera thermostats rather than using "CurrentSetpoint" which will set the 'setpoint' and 'heat' states to the 'cool' state since they all use the same variable name 'CurrentSetpoint' (how stupid is that?).

I'd make this change, but I'm still brushing up my python... if I can figure out a solution, I'll update it here, but any help would be appreciated...

Delayed or no function

Since last update of HomeAssistant I have been experiencing that when I in automation turns on a group of lights/switched from the Vera, there is a long delay or in some cases there is no function at all, do any of you others using this experiencing the same thing? First I thought this could be because I had some devices that didn't work in the zwave network but I have removed then and still very unreliable function with the Vera.

Rationalise `get_value` & `get_complex_value` and refactor.

I added this to continue the discussion here #88

get_value is a confusing name for a function that gets the summary state from the vera sdata call, and contains a .lower call to attempt (unsuccessfully) to unify the data that comes via the service calls and the sdata call.

get_complex_value gets data from the service calls - but via a rather ugly caching structure that should probably be rationalised, along the lines of what we;'ve done for the set data calls.

As a starting point we could rationalise the two function names, remove the .lower - fix the calls to get_value to have the correct case, and make sure the set calls all still work. And if we merged
#88 we can also remove get_strict_value.
Thoughts, feedback (and PRs) welcome.

Cover position not updated correctly

Again not sure if this is a pyvera or Hass issue.

But in Hass, if I open my curtain for 50% and then call (full) open (or close) the interface still shows position 50% afterwards. And a side effect is that the controls (arrow up and down) are both enabled, but one should be greyed out.

call_service() function does not accept action arguments

I feel like I'm missing something, because this is really basic, but here goes:

The call_service() function accepts a device, service Id, and action, but no parameters for the action in question. Many Vera actions have parameters. How are they to be passed?

The "complex" variable functions do not consider service Id

Ref this discussion: home-assistant/core#18491 (comment)

The "complex" functions in pyvera currently look up the variable name in the "states" substructure and operate on the first matching name. However, variable names are not unique in Vera. A state variable is uniquely identified only by the combination of service Id and variable name.

I recommend, in addition to providing forms of these functions with an additional serviceId argument, that the existing functions be extended to accept "service/variable" syntax for the name, and use the serviceId provided when given (i.e. make sure the selected state variable data matches both service Id and variable name).

The name-only usage should be deprecated. This means all pyvera "convenience" functions like is_tripped() and get_battery_level() should be amended to include the specific serviceId for the variable retrieved in their implementations. This should be the required practice for all such usage within pyvera, to remove ambiguity.

Device with Vera warning does not update

Using this as part of home assistant.

I have 3 Aeotec 6 in 1 multisensors. For some reason my Vera always displays "failed at setting user config" for these devices. However the settings have updated.

So the issue is, motion sensor reports stop getting sent to Home Assistant for these devices. The other sensors such as temperature and lux update in home assistant, but the motion detection does not. The motion detection does however report correctly in Vera.

I have a bunch of other sensors such as the 4 in 1 sensor and door window sensors. All these work perfectly.

So, not sure why pyvera isn't updating the status when motion is/isn't detected for these motion sensors.

Support for scenes

Probably this is more like a feature request, but should there be support for scenes? I'm trying to get Nodon wall switches working with Home Assistant without success. I'm not sure if those switches should even work if there is no support for the scenes of Vera.

Thermostat Unit problems

I have my thermostat in °C and they also show up correctly now (with 31.1) in home-assistant. However when I set them to for example 21°C in Home-Assistant they get set to 69.8 °C (21°C = 69.8°F)

Long-polling for immediate updates?

I was reading this thread, and it seems that vera has support for long-polling that would remove any delay in notifications or triggers. I believe pyvera has been implemented partially with this, but it does include an additional sleep(1)
https://github.com/pavoni/pyvera/blob/1fd6aca819381e67ca8fdc54a732fe4ddd92c590/pyvera/subscribe.py#L132
which wouldn't be implementing a proper long-poll. I believe either removing this sleep or only doing this sleep on http request errors would be beneficial. Would like to hear your input/ideas on this.

home-assistant is using pyvera-subscribe for device status as far as I can tell.

Use of Fibaro Zwave Key Fob Remote

Hi all,
Alan was working on this issue mid last year (# 97) and the fix provided was working fine up until the "Great Migration" of Home Assistant. It was never merged in the end as Alan was busy with other things and as a workround I simply used the modified sensor.py file as a Custom Component. I am not quite sure why it has stopped working as was wondering if it could actually be merged if resolved and not use it as CC anymore. Code attached

`"""
Support for Vera sensors.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.vera/
"""
import logging
from datetime import timedelta

from homeassistant.const import (
    TEMP_CELSIUS, TEMP_FAHRENHEIT)
from homeassistant.helpers.entity import Entity
from homeassistant.components.sensor import ENTITY_ID_FORMAT
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.util import convert
from homeassistant.components.vera import (
    VERA_CONTROLLER, VERA_DEVICES, VeraDevice)

DEPENDENCIES = ['vera']

_LOGGER = logging.getLogger(__name__)

SCAN_INTERVAL = timedelta(seconds=5)

EVENT_VERA_REMOTE = "vera_remote"

ATTR_BUTTON = "button"


def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Vera controller devices."""
    add_entities(
        [VeraSensor(device, hass.data[VERA_CONTROLLER])
         for device in hass.data[VERA_DEVICES]['sensor']], True)


class VeraSensor(VeraDevice, Entity):
    """Representation of a Vera Sensor."""

    def __init__(self, vera_device, controller):
        """Initialize the sensor."""
        self.current_value = None
        self._temperature_units = None
        self.last_changed_time = None
        VeraDevice.__init__(self, vera_device, controller)
        self.entity_id = ENTITY_ID_FORMAT.format(self.vera_id)

    @property
    def state(self):
        """Return the name of the sensor."""
        return self.current_value

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity, if any."""
        import pyvera as veraApi
        if self.vera_device.category == veraApi.CATEGORY_TEMPERATURE_SENSOR:
            return self._temperature_units
        if self.vera_device.category == veraApi.CATEGORY_LIGHT_SENSOR:
            return 'lx'
        if self.vera_device.category == veraApi.CATEGORY_UV_SENSOR:
            return 'level'
        if self.vera_device.category == veraApi.CATEGORY_HUMIDITY_SENSOR:
            return '%'
        if self.vera_device.category == veraApi.CATEGORY_POWER_METER:
            return 'watts'

    def update(self):
        """Update the state."""
        import pyvera as veraApi
        if self.vera_device.category == veraApi.CATEGORY_TEMPERATURE_SENSOR:
            self.current_value = self.vera_device.temperature

            vera_temp_units = (
                self.vera_device.vera_controller.temperature_units)

            if vera_temp_units == 'F':
                self._temperature_units = TEMP_FAHRENHEIT
            else:
                self._temperature_units = TEMP_CELSIUS

        elif self.vera_device.category == veraApi.CATEGORY_LIGHT_SENSOR:
            self.current_value = self.vera_device.light
        elif self.vera_device.category == veraApi.CATEGORY_UV_SENSOR:
            self.current_value = self.vera_device.light
        elif self.vera_device.category == veraApi.CATEGORY_HUMIDITY_SENSOR:
            self.current_value = self.vera_device.humidity
        elif (self.vera_device.category == veraApi.CATEGORY_SCENE_CONTROLLER or
              self.vera_device.category == veraApi.CATEGORY_REMOTE):
            value = self.vera_device.get_last_scene_id(True)
            time = self.vera_device.get_last_scene_time(True)

            if time is not None and time == self.last_changed_time:
                self.current_value = None
            else:
                self.current_value = value

                self.hass.bus.fire(EVENT_VERA_REMOTE, {
                    ATTR_ENTITY_ID: self.entity_id,
                    ATTR_BUTTON: self.current_value
                })

            self.last_changed_time = time
        elif self.vera_device.category == veraApi.CATEGORY_POWER_METER:
            power = convert(self.vera_device.power, float, 0)
            self.current_value = int(round(power, 0))
        elif self.vera_device.is_trippable:
            tripped = self.vera_device.is_tripped
            self.current_value = 'Tripped' if tripped else 'Not Tripped'
        else:
            self.current_value = 'Unknown'`

Constant JSONDecodeError exceptions

I use pyvera in my instance of Home Assistant (HA). I have consistently noticed that sometime between one and two days after starting HA, pyvera's subscription/polling feature stops working due to a single JSONDecodeError exception. I have created a pull request (#52) that will safely handle JSONDecodeError exceptions and allow polling to continue.

For reference, the stack trace always looks like this:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/pyvera/subscribe.py", line 118, in _run_poll_server
    controller.get_changed_devices(timestamp))
  File "/usr/local/lib/python3.5/site-packages/pyvera/__init__.py", line 218, in get_changed_devices
    result = self.data_request(payload, TIMEOUT*2).json()
  File "/usr/local/lib/python3.5/site-packages/requests/models.py", line 866, in json
    return complexjson.loads(self.text, **kwargs)
  File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python3/3.5.2_1/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The pull request works perfectly for me, and should hopefully help out anyone else who may or may not be experiencing this problem.

veraSecure and SMS messages?

I'm wondering if it might be worth getting the vera secure based on it having built-in wireless phone capability (it comes with a SIM card, or maybe I could provide my own?). The question is whether I could do anything with python to send an SMS message. I haven't seen the vera secure software, so maybe this is built in and doesn't need to be done in python ...

Vera 7.3 firmware Beta & pyvera

Does anyone who relies on or maintains pyvera plan on participating in the Vera 7.3 core firmware Beta testing?

This would be a great opportunity to not just get a jump on any potential backwards compatibility issues but also to provide input on improving the API.

This firmware update is quite massive in content, and provides major improvements for system reliability. I don't have a spare system to be able to test but am really looking forward to the upgrade - provided pyvera has been actively tested with it.

Excluding Vera Scenes and Devices configuration

Hi,

This thread I believe should be cross-linked here.

The reporter is correct that vera scene IDs and device IDs can share the same number - I was just about to ask whether there is an easy way to exclude all Vera Scenes and then add them in selectively like with other components, but it does not appear so and if I try to exclude scenes based on IDs as indicated above, I run into the same issue where the device and scene ID numbers overlap.

I've been running HA 0.82.1 and using the native Homekit support for everything except scenes for which I use the Homebrige plugin. Everything's been working great and reliably.

Vera Scene support for homekit was added in HA 0.83+ - but when I make the minor change of importing only 9 scenes from Vera, I am getting a strange error after about 1 hour in Home Assistant and Vera updates stop working (see below). Under HA 0.82.1 and earlier, I load the same vera devices and scenes, but do not get this error. I suspect it is because I have a LOT of Vera scenes that are configured within Vera for controlling IR components like stereo receivers, TVs, etc. This is why I was interested in excluding all scenes and then selectively adding the ones I want to use in HA -- and thus coming across this issue of device and scene ID conflicts.

Anyone have any suggestions or workarounds for 0.83+? Otherwise, I'll leave it running as is, but this is a must-have for my setup, so I'll need a longer-term solution as I'm stuck on 0.82.1.


Traceback (most recent call last):
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/connection.py", line 159, in _new_conn
(self._dns_host, self.port), self.timeout, **extra_kw)
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/util/connection.py", line 80, in create_connection
raise err
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/util/connection.py", line 70, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen
chunked=chunked)
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request
conn.request(method, url, **httplib_request_kw)
File "/Users/default/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1239, in request
self._send_request(method, url, body, headers, encode_chunked)
File "/Users/default/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1285, in _send_request
self.endheaders(body, encode_chunked=encode_chunked)
File "/Users/default/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1234, in endheaders
self._send_output(message_body, encode_chunked=encode_chunked)
File "/Users/default/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 1026, in _send_output
self.send(msg)
File "/Users/default/.pyenv/versions/3.6.5/lib/python3.6/http/client.py", line 964, in send
self.connect()
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/connection.py", line 181, in connect
conn = self._new_conn()
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/connection.py", line 168, in _new_conn
self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x1131a1518>: Failed to establish a new connection: [Errno 61] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/requests/adapters.py", line 449, in send
timeout=timeout
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/connectionpool.py", line 638, in urlopen
_stacktrace=sys.exc_info()[2])
File "/Users/default/Projects/homeassistant/lib/python3.6/site-packages/urllib3/util/retry.py", line 398, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host=‘[vera.localip]’, port=3480): Max retries exceeded with url: //data_request?output_format=json&DeviceNum=206&id=variableget&serviceId=urn%3Amica

During handling of the above exception, another exception occurred:

VeraDimmer.turn_on() overwrites previous brightness

Many dimmable bulbs and switches record their last known brightness so that, when switched on, they will restore their previous brightness. Some switches even have settings to turn on to a specific brightness when pressed. Even the Vera controller's native software will not overwrite the brightness when turning on a dimmable switch by default. pyvera's current behavior is to overwrite the last known brightness with the value 100%.

I would like to propose that the VeraDimmer class use the base class (VeraSwitch) function for switch_on and switch_off. This seems to be what Vera does and would allow calling those functions without overwriting the switch's 'previous brightness' memory.

I ran into this problem because Home Assistant uses pyvera, and only my dimmers controlled through the Vera plugin do not retain their previous brightness when switched on.

pyvera throwing exception error on dimmer state refresh

Not sure if this is only happening to me or to anyone else as well?
Maybe not many people are using Vera and HomeAssistant?

Under the get_brightness def, line 577 of the init.py file, there is a reference to the level variable as an integer (int(level)).

When refreshing the state of my dimmers from Vera, they return a % value (e.g. 20%) which causes an error in parsing the __init__py file as the 'level' variable is not an integer in that case but a string.

This generally happens every 2 or 3 days. Not sure why it occurs that infrequently.
I believe this has happened with all versions I've used so far - v0.39.x up to current v0.44.2 but I didn't notice earlier as I was always restarting Home Assistant while I was playing with it/setting things up. I've been using it for just over a month now.
I only really noticed this issue as I am graphing temperatures in grafana/InfluxDB and after this error, the temperature sensors in Vera stop updating in Home Assistant and therefore the graphs are blank.

I have implemented a workaround that forces the level variable to an integer if it is not already.
I am sure there are more elegant ways to get the same result?

I have added the following line to my local version today (line 577) above where the error normally occurs. This should strip the % character and change level to an integer if it is not already one.

level = int(level) if type(level) == int else float(level.strip('%'))

Full section (including extra line) is as follows (from line 565):

def get_brightness(self, refresh=False):
    """Get dimmer brightness.

    Refresh data from Vera if refresh is True, otherwise use local cache.
    Refresh is only needed if you're not using subscriptions.
    Converts the Vera level property for dimmable lights from a percentage
    to the 0 - 255 scale used by HA.
    """
    if refresh:
        self.refresh()
    brightness = 0
    level = self.get_value('level')
    level = int(level) if type(level) == int else float(level.strip('%'))
    percent = 0 if level is None else int(level)
    if percent > 0:
        brightness = round(percent * 2.55)
    return int(brightness)

Will report back in 2 days if that hasn't resolved my issue.
If it does, can we get something similar added into the main branch?

Thanks,
Alan

Polling loop/thread fragile, gets knocked out by common conditions too easily.

I use pyvera as part of my HomeAssistant installation. I've noticed that a restart of the Vera, either full reboot or restart of Luup (Vera's HA service), causes the polling loop to take an unhandled exception and quietly die. Luup restarts on Vera are very common--almost any device configuration change will cause one, and they occur spontaneously several times a day. That crashes the polling loop and HASS then goes "blind" to device changes on the Vera until HASS itself is restarted. Others have also reported this, for some time, apparently, so I went investigating. I've managed to fix this pretty easily, although perhaps not completely (more below), but I think the result is much more robust than the current implementation.

Apologies in advance for the text wall, but I want to be as clear and thorough as possible.

The observed conditions on my config Ubuntu 16.04.3, python 3.5.2, Home Assistant 0.63.3 with Vera Plus firmware 3232 are:

  1. As it's going down during Luup reload, Vera sometimes returns a nonsense/nonspec "{ status: 0 }" response (valid JSON) that does not contain any data that get_changed_devices() is looking for, resulting in an empty response that corrupts the timestamp values;
  2. Later in the reload, the Vera will return HTTP 500s;
  3. In the final stage of the reload, Vera will return HTTP 200s with valid JSON containing no device data but valid, unchanging loadtime and dataversion for several seconds, until it's settled, then normal operation resumes;
  4. The JSON library packed with HASSIO is throwing an exception that is not caught by the device polling loop (simplejson.errors.JSONDecodeError);
  5. The documentation for the JSON handling in the Response object (2.18.4) says that a ValueError may be thrown by the method, but the code does not have a specific handler for this advertised exception (see more below);
  6. There seems to be some general odd exception-handling problem (perhaps related to threading?) in which none of the exception handlers in the polling loop (even the default one) traps any exception thrown by get_changed_devices()--this is very odd and very troubling/counter-intuitive, and I have not yet figured out why this is, but my other fixes are an effective work-around for much of it.

Most of the loop's fragility is caused by get_changed_devices()'s reliance on the Response.json() method throwing some recognized exception. But there is so much variance in underlying implementations that it's a risky assumption (no guarantee the exception you're looking for is the one you'll get). For unexpected exceptions (e.g. ValueError), the loop's default exception handler passes the exception up, terminating the loop/thread. Also, if the data is parseable, but does not contain the expected values, there are no checks, so the remainder of the method corrupts the pass-through timestamp values. Tightening up the checks on the Response object before attempting to parse the data, and then also checking the parsed data after, yields tremendous benefits in stability, even without having an answer for the exceptional handling matter. Here's what I've done:

I changed my version of get_changed_devices() like this: it does not directly call Response.json() on the return value of data_request(), but first checks Response.status_code for a 200; anything other returns [ None, timestamp ] (returning the timestamp passed in, untouched, but no device data, which is effectively a no-op for the polling loop). If the HTTP status is OK, it parses the JSON at that point, and then goes on to check for the existence of loadtime and dataversion in the parsed data. If they do not exist, the [ None, timestamp ] list is returned; otherwise, the timestamp is updated and returned with the device data to the polling loop/caller.

This has made the polling loop very robust in my HASS/Vera installation--tons of reboots and restarts with reliable recovery. If you're interested in having these changes, let me know how you want to receive them.

Sensor values

Looks like something which made it into todays release of HA causes significant problems with sensor values. Had to back it out back to previous release. Light sensors, temp, all showing 'unknown' in HA.

I did run it in debug for a few mins to see if anything was there but I lost the output :(

No virtual switch support?

I tried to add some virtual switches to my controller (urn:schemas-upnp-org:device:VSwitch:1) and they don't seem to show up in Home Assistant. Are these just not supported?

I'm trying to avoid polling when using the minimote, by using scenes native to Vera that set virtual switches on/off so that their state will push directly to Home Assistant and my automations will be instant.

pyvera does not properly handle non-english device categories

See the issue here: home-assistant/core#9105

The device categories are of the form:

Contrôleur de scène
Météo
Détecteur
Détecteur de température
Appareil photo
Interrupteur On/Off
Panneau d'alarme
Sirène

I wonder if there is some request parameter that would return the categories in English, otherwise it seems we would have to add translations in pyvera. I havent found anything yet however...

Code snippet to support VeraSecure built in siren

Hi,
first off I'm a total noob on github so this is probably the wrong way to handle this. Secondly, big thanks for writing this library.

Now to the topic.
I have a VeraSecure controller that is connected to Home Assistant that is using your library. The VeraSecure have an built in siren that is triggered with the different modes. It can also be turned on and off via Luup calls. BUT the siren is now added as a generic device that can be armed.

The siren is not armed in that sense in Vera but tightly connected to the modes.

To automate siren and the usage of the siren the siren should be treated as a switch.

In init.py
When initiating all devices the siren is not recognised by the right category and is initilized as a VeraDevice.

My suggestion is to add the correct category on row 32

CATEGORY_POWER_METER = 21
CATEGORY_VERA_SIREN = 24
CATEGORY_UV_SENSOR = 28

And add the correct device class for it. Rows 160-170isch

            elif device_category == CATEGORY_SCENE_CONTROLLER:
                device = VeraSceneController(item, self)
            elif device_category == CATEGORY_VERA_SIREN:
                device = VeraSwitch(item, self)
            else:
                device = VeraDevice(item, self)
            self.devices.append(device)
            if device_category != CATEGORY_SWITCH and device_category != CATEGORY_VERA_SIREN and device.is_armable:
                self.devices.append(VeraArmableDevice(item, self))
        else:
            self.devices.append(VeraDevice(item, self))

Im runnig this myself and I can now controll and detect when the siren is invoked with no other changes.

Let me know if this is interesting and if you need more information.

Thanks for great job on this,
Patrik Ekström

IndexError in get_color

Here is the stack trace as reported here: home-assistant/core#8526

Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/pyvera/subscribe.py", line 129, in _run_poll_server
    self._event(device_data)
  File "/usr/local/lib/python3.6/site-packages/pyvera/subscribe.py", line 59, in _event
    self._event_device(device, device_data)
  File "/usr/local/lib/python3.6/site-packages/pyvera/subscribe.py", line 96, in _event_device
    callback(device)
  File "/usr/src/app/homeassistant/components/vera.py", line 147, in _update_callback
    self.update()
  File "/usr/src/app/homeassistant/components/light/vera.py", line 85, in update
    self._color = self.vera_device.get_color()
  File "/usr/local/lib/python3.6/site-packages/pyvera/__init__.py", line 660, in get_color
    val = [cur.split(',')[c] for c in ci]
  File "/usr/local/lib/python3.6/site-packages/pyvera/__init__.py", line 660, in <listcomp>
    val = [cur.split(',')[c] for c in ci]
IndexError: list index out of range

I'm not sure what's getting returned by CurrentColor that isn't in get_color_index. Do we try to understand exactly whats going on or just wrap 660 & 661 to catch IndexErrors?

try:
    val = [cur.split(',')[c] for c in ci]
    return [int(v.split('=')[1]) for v in val]
except IndexError:
    return None

More metadata about battery and communication status

I have like 6 Schlage Connects, and 3 of them are in various states of flakiness. When I look at HomeAssistant, there isn't really anything to indicate that there are problems iwth them, except for 1 that has 0% battery.

It'd be super useful to have additional metadata. I started poking around a VeraDoor object to see what kinda of data the API already has. A few fields seem relevant:

  • BatteryDate: seconds since epoch... for hte last time the battery changed?
  • CommFailure: seems to be 0 or 1
  • CommFailureDate: seconds since epoch since CommFailure?
  • PollOk: no idea, but it's an integer
  • LastPollSuccess: no idea what it considers a success, since most of the ones I'm seeing are pretty far back

Here's a snippet I'm playing with, based on the list-devices:

import sys
import time
import os
import IPython
from IPython import embed

# Import pyvera
import pyvera

# Parse Arguments
import argparse
parser = argparse.ArgumentParser(description='list-devices')
parser.add_argument('-u', '--url', help="Vera URL, e.g. http://192.168.1.161:3480", required=True)
args = parser.parse_args()

# Start the controller
controller, _ = pyvera.init_controller(args.url)

try:
    # Get a list of all the devices on the vera controller
    all_devices = controller.get_devices()

    # Print the devices out
    for device in all_devices:
        if type(device).__name__ == "VeraLock":
            #  embed()

            print('{} ({})'.format(device.name, device.device_id))
            poll_ok = device.get_complex_value('PollOk')
            if poll_ok is not None:
                print('PollOk: {}'.format(poll_ok))
                last_poll_success = device.get_complex_value('LastPollSuccess')
                if last_poll_success is not None:
                    print('LastPollSuccess: {}'.format(time.ctime(int(last_poll_success))))
            print('BatteryLevel: {}%'.format(device.battery_level))
            print('BatteryDate: {}'.format(time.ctime(int(device.get_complex_value('BatteryDate')))))
            comm_failure = device.get_strict_value('commFailure')
            print('CommFailure: {}'.format(comm_failure))
            if comm_failure != '0':
                print('CommFailureDate: {}'.format(time.ctime(int(device.get_complex_value('CommFailureTime')))))
            print('Status: {}'.format(device.get_value('status')))
            print()

finally:
    # Stop the subscription listening thread so we can quit
    controller.stop()

Exception relating to RGB

Thrown from Home-Assistant but appears to be in the pyvera library.

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/helpers/entity_component.py", line 161, in _async_setup_platform
    SLOW_SETUP_MAX_WAIT, loop=self.hass.loop)
  File "/usr/lib/python3.4/asyncio/tasks.py", line 377, in wait_for
    return fut.result()
  File "/usr/lib/python3.4/asyncio/futures.py", line 275, in result
    raise self._exception
  File "/usr/lib/python3.4/concurrent/futures/thread.py", line 54, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/components/light/vera.py", line 24, in setup_platform
    VeraLight(device, VERA_CONTROLLER) for device in VERA_DEVICES['light'])
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/helpers/entity_component.py", line 331, in schedule_add_entities
    self.async_schedule_add_entities, list(new_entities),
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/components/light/vera.py", line 24, in <genexpr>
    VeraLight(device, VERA_CONTROLLER) for device in VERA_DEVICES['light'])
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/components/light/vera.py", line 35, in __init__
    VeraDevice.__init__(self, vera_device, controller)
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/components/vera.py", line 144, in __init__
    self.update()
  File "/usr/local/lib/python3.4/dist-packages/homeassistant/components/light/vera.py", line 86, in update
    self._color = self.vera_device.get_color()
  File "/var/opt/homeassistant/deps/pyvera/__init__.py", line 652, in get_color
    ci = self.get_color_index(['R', 'G', 'B'], refresh)
  File "/var/opt/homeassistant/deps/pyvera/__init__.py", line 640, in get_color_index
    ci = [sup.split(',').index(c) for c in colors]
  File "/var/opt/homeassistant/deps/pyvera/__init__.py", line 640, in <listcomp>
    ci = [sup.split(',').index(c) for c in colors]
ValueError: 'R' is not in list```

Vera bug in dataversion handling across reloads loses device state

The polling loop uses long polls, but when Vera restarts Luup, it does not give consistent and accurate device-change data when given a pre-restart value of dataversion. Pull request for a simple patch to clear timestamp and force reload after an exception fixes this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.