Giter Club home page Giter Club logo

surepy's Introduction

surepy

Library & CLI to interact with the Sure Petcare API. surepy lets you monitor and control the Pet Door/Cat Flap Connect πŸšͺ and the Pet Feeder Connect 🍽 by Sure Petcare.


surepy features:

πŸ”‘ get an api token with your account credentials
πŸšͺ lock/unlock a door or flap
🐾 get the location of pets & devices
🐈 get the state and more attributes of pets & devices
πŸ•°οΈ get historic data & events of pets & devices
πŸ“¬ get a list of (past) notifications

Getting Started

surepy is available via pypi.org

python3 -m pip install --upgrade surepy
# or
pip install --upgrade surepy

there is also a small cli available

$ surepy --help
Usage: surepy [OPTIONS] COMMAND [ARGS]...

  surepy cli 🐾

  https://github.com/benleb/surepy

Options:
  --version         show surepy version
  -j, --json        enable json api response output
  -t, --token TEXT  api token
  --help            Show this message and exit.

Commands:
  devices       get devices
  locking       lock control
  notification  get notifications
  pets          get pets
  position      set pet position
  report        get pet/household report
  token         get a token

the cli is mainly intended for developing & debugging purposes and probably has bugs - be careful 🐾

Library example

import asyncio

from os import environ
from pprint import pprint
from typing import Dict, List

from surepy import Surepy
from surepy.entities import SurepyEntity
from surepy.entities.devices import SurepyDevice
from surepy.entities.pet import Pet


async def main():

    # # user/password authentication (gets a token in background)
    # surepy = Surepy(email=user, password=password)

    # token authentication (token supplied via SUREPY_TOKEN env var)
    token = environ.get("SUREPY_TOKEN")
    surepy = Surepy(auth_token=token)

    # list with all pets
    pets: List[Pet] = await surepy.get_pets()
    for pet in pets:
        print(f"\n\n{pet.name}: {pet.state} | {pet.location}\n")
        pprint(pet.raw_data())

    print(f"\n\n - - - - - - - - - - - - - - - - - - - -\n\n")

    # all entities as id-indexed dict
    entities: Dict[int, SurepyEntity] = await surepy.get_entities()

    # list with alldevices
    devices: List[SurepyDevice] = await surepy.get_devices()
    for device in devices:
        print(f"{device.name = } | {device.serial = } | {device.battery_level = }")
        print(f"{device.type = } | {device.unique_id = } | {device.id = }")
        print(f"{entities[device.parent_id].full_name = } | {entities[device.parent_id] = }\n")


asyncio.run(main())

Naming confusion for surepetcarebeta users 🐾 πŸ€ͺ 🀦

Sorry for the bad naming and resulting confusion and chaos πŸ™„ To "fix" this, I renamed surepetcarebeta to sureha.

Name Repo Type Description Need Help?
surepy 🐾 github.com/benleb/surepy Python Library Library to interact with the API of Sure Petcare. Also provides Classes for the various Sure Petcare Devicess. Use this if you write an own python tool/app and want to interact with the Sure Petcare API Issues
surepetcare HA Favicon github.com/home-assistant/core Home Assistant Integration Official Home Assistant Integration for the Sure Petcare Devices like Doors, Flaps, Feeders, ... Issues, HA Forum
sureha surepetcarebeta benleb/surepetcare github.com/benleb/sureha Home Assistant Integration Home Assistant Integration developed in my own repo without reviews from the HA Team. This can be installed via HACS and is something like a preview integration for advanced users. Usually this provides more (experimental) features and faster fixes but lacks the code quality (reviews) and such from HA Issues
pethublocal github.com/plambrechtsen/pethublocal Home Assistant Integration Home Assistant Integration developed by @plambrechtsen which works completely independent from Sure Petcare. Check outs his repo for more information! Issues, HA Forum

Used by

Feel free to add you project!

Acknowledgments

Meta

Ben Lebherz: cat lover 🐾 developer & maintainer - @benleb | @ben_leb

This project is licensed under the MIT License - see the LICENSE file for details

surepy's People

Contributors

ashleigh-hopkins avatar badnetmask avatar benleb avatar czandee avatar deepsourcebot avatar dependabot[bot] avatar epenet avatar fabaff avatar hadinh1306 avatar irinamaria avatar paxcodes avatar rogerselwyn avatar scop avatar therefromhere avatar tsyganov-ivan 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar

surepy's Issues

'devices' command in CLI only reports one item on 0.5.0, reported all devices on 0.4.0

Not a priority issue, but there might be an problem with the 'devices' command in the CLI on 0.5.0. Here is the output from 0.5.0:

bash-5.0# surepy devices
         β•·           β•·                  β•·          β•·
      ID β”‚ Household β”‚ Name             β”‚ Type     β”‚ Serial
╢────────┼───────────┼──────────────────┼──────────┼────────╴
  nnnnnn β”‚     nnnnn β”‚ Backdoor Catflap β”‚ Pet Flap β”‚ None
         β•΅           β•΅                  β•΅          β•΅

and here is the output from 0.4.0:

bash-5.0# surepy devices

 surepy 🐾 v0.4.0

                            Β· Devices Β·
         β•·           β•·          β•·                  β•·
      ID β”‚ Household β”‚ Type     β”‚ Name             β”‚       Serial
╢──────────────────────────────────────────────────────────────────
   nnnnn β”‚     nnnnn β”‚ Hub      β”‚ Benbie's Hub     β”‚ H002-nnnnnnn
  nnnnnn β”‚     nnnnn β”‚ Pet Flap β”‚ Backdoor Catflap β”‚            -
  nnnnnn β”‚     nnnnn β”‚ Feeder   β”‚ Zamira’s Feeder  β”‚ U003-nnnnnnn
  nnnnnn β”‚     nnnnn β”‚ Feeder   β”‚ Benbie’s Feeder  β”‚ U003-nnnnnnn
         β•΅           β•΅          β•΅                  β•΅

I do not have any Python knowledge, but I note there have been changes to the 'devices' command in the cli.py file recently. It would appear that the list of devices returned by SurePetcare() isn't being looped through correctly.

get_token() raise exception

Hello, recently I have this kind of errors. The API is unusable. I can't pinpoint where the problem lies. Did Surepetcare.io change anything on their side which need adaptation here?

🐾 · GET app.api.surehub.io/api/me/start: 401 | <ClientResponse(https://app.api.surehub.io/api/me/start) [401 Unauthorized]> <CIMultiDictProxy('Date': 'Sat, 03 Dec 2022 17:37:22 GMT', 'Content-Type': 'application/json', 'Content-Length': '63', 'Connection': 'keep-alive', 'Server': 'nginx', 'Cache-Control': 'no-cache, private', 'Access-Control-Allow-Origin': 'https://surepetcare.io', 'Vary': 'Origin', 'Content-Encoding': 'gzip', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'SAMEORIGIN', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block')>

Traceback (most recent call last): if response := await self.sac.call(method="GET", resource=MESTART_RESOURCE): File "/surepy/client.py", line 266, in call await self.call(method="GET", resource=resource, second_try=True) File "/surepy/client.py", line 217, in call self._auth_token = await self.get_token() File "/surepy/client.py", line 187, in get_token raise SurePetcareError()

seems some other users encounter the same problems.
benleb/sureha#35

Pet Door curfew no longer reporting lock status

I have a Pet Door and the curfew status has stopped reporting locked/unlocked correctly.
It was working until fairly recently thorough my integration but now always reports as unlocked, even though the Pet Door is physically locked by the curfew.

When I print the rawdata() from the device object (shown below) I can see that it is correctly reporting the curfew lock/unlock times. But despite running this after the curfew time (22:01) when the device should report as 'locked', it still is not doing so.

If I query the device.state, I get a response of <LockState.CURFEW: 4> rather than the locked/unlocked enumerations for the curfew values (which should be negative)

Logging into the surepetcare.io web page with the same user shows the device as locked with curfew.

Does anyone know what might be occuring?

{'control': {'curfew': {'enabled': True,
                        'lock_time': '21:49',
                        'unlock_time': '06:00'},
             'fast_polling': True},
 'created_at': '2019-01-09T20:21:37+00:00',
 'index': 1,
 'move': {'duration': 3174,
          'entry_device_id': 223590,
          'exit_device_id': 223590,
          'from': '2023-11-28T16:37:03+00:00',
          'to': '2023-11-28T17:29:57+00:00'},
 'name': 'Kitchen',
 'pairing_at': '2019-01-09T20:21:37+00:00',
 'parent': {'created_at': '2018-04-06T12:53:59+00:00',
            'updated_at': '2023-11-28T22:01:23+00:00',
            'version': 'ODA5MTA='},
 'parent_device_id': 81384,
 'product_id': 3,
 'status': {'battery': 6.3374999999999995,
            'learn_mode': False,
            'locking': {'curfew': {'delay_time': 0,
                                   'lock_time': '21:49',
                                   'locked': False,
                                   'permission': 2,
                                   'unlock_time': '06:00'},
                        'mode': 4},
            'online': True,
            'signal': {'device_rssi': -47.8, 'hub_rssi': -50},
            'version': {'lcd': {'firmware': 1, 'hardware': 1},
                        'rf': {'firmware': 0.16, 'hardware': 4}}},
 'updated_at': '2023-11-28T22:01:20+00:00',
 'version': 'Mzk1MTQ='}

Add scripts/service calls for Curfew, Pet Location, Exit Permissions for Flaps

The updated version of the repo allows user to configure service calls to set the lock_state of the pet door products.

On the official app its also possible to:

  • Set Pet status to inside/outside manually -> parameter "where", options (0,1,2)
  • Set up-to 4 curfews that restrict exit of pets towards outside (but they can re-enter) -> see picture for examples
  • Set pets as "inside only" pets, without access to the outside (but they can re-enter)

It would be great if these options can be executed via service calls in the future, via HA

image
image

Mark cat as inside/outside when they "look through"

Seems like since there are two coils, we should be able to mark the cat as inside or outside when they look through without actually going through. Case: cat is outside and you bring your cat in through another door, but the cat still shows up is outside since they didn't come in via the flap. Cat later looks through the flap, it should get marked as inside by that event, since we know it must be inside.

pet binary sensor not updating

firstly thanks for the great work that you've put in with making this work. since the latest update, my surepet devices are showing on home assistant. unfortunately though the pet binary senor doesn't update anymore, unless rebooting home assistant.
i'm now using the new config of

surepetcare: username: YOUR_SURE_PETCARE_LOGIN password: YOUR_SURE_PETCARE_PASSWORD

i've added the latest the latest update into my custom_components folder, but still no joy.
is there a way of re-adding scan_interval back to config?

SurePy initializes with 'TypeError: object of type 'int' has no len()'

The problem

I installed the Sure PetCare integration for Home Assistant and it seemed to work at first for my cat flap and the felaqua water fountain, but I keep getting the error TypeError: object of type 'int' has no len(). I have defined one household, with one pet and one person in the SurePetCare APP. Within the SurePetCare APP everything seems to work like a charm.
It seems as if the length of a string object should be determined, but the object is an integer, but I do not know.

The trouble seems to result from this line of the [surepy] repository:

responselen = len(response_data.get("data", 0))

What version of Home Assistant Core has the issue?

2022.10.2

What was the last working version of Home Assistant Core?

No response

What type of installation are you running?

Home Assistant OS

Integration causing the issue

Sure PetCare

Link to integration documentation on our website

No response

Diagnostics information

No response

Example YAML snippet

No response

Anything in the logs that might be useful for us?

Logger: homeassistant.components.surepetcare
Source: components/surepetcare/__init__.py:190
Integration: Sure Petcare (documentation, issues)

Unexpected error fetching surepetcare data: object of type 'int' has no len()
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 205, in _async_refresh
    self.data = await self._async_update_data()
  File "/usr/src/homeassistant/homeassistant/components/surepetcare/__init__.py", line 190, in _async_update_data
    return await self.surepy.get_entities(refresh=True)
  File "/usr/local/lib/python3.10/site-packages/surepy/__init__.py", line 400, in get_entities
    await self.get_latest_anonymous_drinks(household_id=household_id)
  File "/usr/local/lib/python3.10/site-packages/surepy/__init__.py", line 216, in get_latest_anonymous_drinks
    household_timeline = await self.get_household_timeline(household_id, entries=50)
  File "/usr/local/lib/python3.10/site-packages/surepy/__init__.py", line 266, in get_household_timeline
    if timeline := await self.sac.call(method="GET", resource=resource):
  File "/usr/local/lib/python3.10/site-packages/surepy/client.py", line 281, in call
    responselen = len(response_data.get("data", 0))
TypeError: object of type 'int' has no len()

### Additional information
Currently I have no devices or entities made available by this integration.

Installing blows up

When trying to instal surepy, I get the following error

uilding wheels for collected packages: pycares
  Building wheel for pycares (setup.py) ... error
  ERROR: Command errored out with exit status 1:
   command: /usr/local/opt/[email protected]/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/tmp/pip-wheel-savt1jz1
       cwd: /private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/
  Complete output (105 lines):
  running bdist_wheel
  running build
  running build_py
  creating build
  creating build/lib.macosx-10.14-x86_64-3.9
  creating build/lib.macosx-10.14-x86_64-3.9/pycares
  copying src/pycares/errno.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
  copying src/pycares/_version.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
  copying src/pycares/__init__.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
  copying src/pycares/utils.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
  copying src/pycares/__main__.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
  running build_ext
  generating cffi module 'build/temp.macosx-10.14-x86_64-3.9/_cares.c'
  creating build/temp.macosx-10.14-x86_64-3.9
  building '_cares' extension
  creating build/temp.macosx-10.14-x86_64-3.9/build
  creating build/temp.macosx-10.14-x86_64-3.9/build/temp.macosx-10.14-x86_64-3.9
  creating build/temp.macosx-10.14-x86_64-3.9/deps
  creating build/temp.macosx-10.14-x86_64-3.9/deps/c-ares
  creating build/temp.macosx-10.14-x86_64-3.9/deps/c-ares/src
  clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/usr/local/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DHAVE_CONFIG_H=1 -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 -D_DARWIN_USE_64_BIT_INODE=1 -I/usr/local/include -I/usr/local/opt/[email protected]/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/[email protected]/3.9.1_1/Frameworks/Python.framework/Versions/3.9/include/python3.9 -Ideps/c-ares/src -Ideps/c-ares/src/config_darwin -c build/temp.macosx-10.14-x86_64-3.9/_cares.c -o build/temp.macosx-10.14-x86_64-3.9/build/temp.macosx-10.14-x86_64-3.9/_cares.o
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:2682:55: error: too many arguments to function call, expected 6, have 7
    return ares_parse_ptr_reply(x0, x1, x2, x3, x4, x5, x6);
           ~~~~~~~~~~~~~~~~~~~~                         ^~
  /usr/local/include/ares.h:653:14: note: 'ares_parse_ptr_reply' declared here
  CARES_EXTERN int ares_parse_ptr_reply(const unsigned char *abuf,
               ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:2760:59: error: too many arguments to function call, expected 6, have 7
    { result = ares_parse_ptr_reply(x0, x1, x2, x3, x4, x5, x6); }
               ~~~~~~~~~~~~~~~~~~~~                         ^~
  /usr/local/include/ares.h:653:14: note: 'ares_parse_ptr_reply' declared here
  CARES_EXTERN int ares_parse_ptr_reply(const unsigned char *abuf,
               ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4403:14: error: no member named 'ttl' in 'struct ares_mx_reply'
    (void)((p->ttl) | 0);  /* check that 'struct ares_mx_reply.ttl' is an integer */
            ~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4419:14: error: no member named 'ttl' in 'struct ares_naptr_reply'
    (void)((p->ttl) | 0);  /* check that 'struct ares_naptr_reply.ttl' is an integer */
            ~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4459:14: error: no member named 'ttl' in 'struct ares_soa_reply'
    (void)((p->ttl) | 0);  /* check that 'struct ares_soa_reply.ttl' is an integer */
            ~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4473:14: error: no member named 'ttl' in 'struct ares_srv_reply'
    (void)((p->ttl) | 0);  /* check that 'struct ares_srv_reply.ttl' is an integer */
            ~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4486:14: error: no member named 'ttl' in 'struct ares_txt_ext'
    (void)((p->ttl) | 0);  /* check that 'struct ares_txt_ext.ttl' is an integer */
            ~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4498:14: error: no member named 'ttl' in 'struct ares_txt_reply'
    (void)((p->ttl) | 0);  /* check that 'struct ares_txt_reply.ttl' is an integer */
            ~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4757:12: error: no member named 'ttl' in 'ares_mx_reply'
    { "ttl", offsetof(struct ares_mx_reply, ttl),
             ^                              ~~~
  /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
  #define offsetof(t, d) __builtin_offsetof(t, d)
                         ^                     ~
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4758:48: error: no member named 'ttl' in 'struct ares_mx_reply'
             sizeof(((struct ares_mx_reply *)0)->ttl),
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4781:12: error: no member named 'ttl' in 'ares_naptr_reply'
    { "ttl", offsetof(struct ares_naptr_reply, ttl),
             ^                                 ~~~
  /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
  #define offsetof(t, d) __builtin_offsetof(t, d)
                         ^                     ~
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4782:51: error: no member named 'ttl' in 'struct ares_naptr_reply'
             sizeof(((struct ares_naptr_reply *)0)->ttl),
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4853:12: error: no member named 'ttl' in 'ares_soa_reply'
    { "ttl", offsetof(struct ares_soa_reply, ttl),
             ^                               ~~~
  /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
  #define offsetof(t, d) __builtin_offsetof(t, d)
                         ^                     ~
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4854:49: error: no member named 'ttl' in 'struct ares_soa_reply'
             sizeof(((struct ares_soa_reply *)0)->ttl),
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4871:12: error: no member named 'ttl' in 'ares_srv_reply'
    { "ttl", offsetof(struct ares_srv_reply, ttl),
             ^                               ~~~
  /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
  #define offsetof(t, d) __builtin_offsetof(t, d)
                         ^                     ~
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4872:49: error: no member named 'ttl' in 'struct ares_srv_reply'
             sizeof(((struct ares_srv_reply *)0)->ttl),
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4886:12: error: no member named 'ttl' in 'ares_txt_ext'
    { "ttl", offsetof(struct ares_txt_ext, ttl),
             ^                             ~~~
  /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
  #define offsetof(t, d) __builtin_offsetof(t, d)
                         ^                     ~
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4887:47: error: no member named 'ttl' in 'struct ares_txt_ext'
             sizeof(((struct ares_txt_ext *)0)->ttl),
                    ~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
  build/temp.macosx-10.14-x86_64-3.9/_cares.c:4898:12: error: no member named 'ttl' in 'ares_txt_reply'
    { "ttl", offsetof(struct ares_txt_reply, ttl),
             ^                               ~~~
  /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
  #define offsetof(t, d) __builtin_offsetof(t, d)
                         ^                     ~
  fatal error: too many errors emitted, stopping now [-ferror-limit=]
  20 errors generated.
  error: command '/usr/bin/clang' failed with exit code 1
  ----------------------------------------
  ERROR: Failed building wheel for pycares
  Running setup.py clean for pycares
Failed to build pycares
Installing collected packages: pycares, colorama, chardet, attrs, async-timeout, urllib3, termcolor, spinners, six, pygments, log-symbols, commonmark, certifi, cchardet, brotlipy, aiohttp, aiodns, rich, requests, halo, click, surepy
    Running setup.py install for pycares ... error
    ERROR: Command errored out with exit status 1:
     command: /usr/local/opt/[email protected]/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/tmp/pip-record-ugdhf7c2/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.9/pycares
         cwd: /private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/
    Complete output (105 lines):
    running install
    running build
    running build_py
    creating build
    creating build/lib.macosx-10.14-x86_64-3.9
    creating build/lib.macosx-10.14-x86_64-3.9/pycares
    copying src/pycares/errno.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
    copying src/pycares/_version.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
    copying src/pycares/__init__.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
    copying src/pycares/utils.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
    copying src/pycares/__main__.py -> build/lib.macosx-10.14-x86_64-3.9/pycares
    running build_ext
    generating cffi module 'build/temp.macosx-10.14-x86_64-3.9/_cares.c'
    creating build/temp.macosx-10.14-x86_64-3.9
    building '_cares' extension
    creating build/temp.macosx-10.14-x86_64-3.9/build
    creating build/temp.macosx-10.14-x86_64-3.9/build/temp.macosx-10.14-x86_64-3.9
    creating build/temp.macosx-10.14-x86_64-3.9/deps
    creating build/temp.macosx-10.14-x86_64-3.9/deps/c-ares
    creating build/temp.macosx-10.14-x86_64-3.9/deps/c-ares/src
    clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/usr/local/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DHAVE_CONFIG_H=1 -D_LARGEFILE_SOURCE=1 -D_FILE_OFFSET_BITS=64 -D_DARWIN_USE_64_BIT_INODE=1 -I/usr/local/include -I/usr/local/opt/[email protected]/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/[email protected]/3.9.1_1/Frameworks/Python.framework/Versions/3.9/include/python3.9 -Ideps/c-ares/src -Ideps/c-ares/src/config_darwin -c build/temp.macosx-10.14-x86_64-3.9/_cares.c -o build/temp.macosx-10.14-x86_64-3.9/build/temp.macosx-10.14-x86_64-3.9/_cares.o
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:2682:55: error: too many arguments to function call, expected 6, have 7
      return ares_parse_ptr_reply(x0, x1, x2, x3, x4, x5, x6);
             ~~~~~~~~~~~~~~~~~~~~                         ^~
    /usr/local/include/ares.h:653:14: note: 'ares_parse_ptr_reply' declared here
    CARES_EXTERN int ares_parse_ptr_reply(const unsigned char *abuf,
                 ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:2760:59: error: too many arguments to function call, expected 6, have 7
      { result = ares_parse_ptr_reply(x0, x1, x2, x3, x4, x5, x6); }
                 ~~~~~~~~~~~~~~~~~~~~                         ^~
    /usr/local/include/ares.h:653:14: note: 'ares_parse_ptr_reply' declared here
    CARES_EXTERN int ares_parse_ptr_reply(const unsigned char *abuf,
                 ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4403:14: error: no member named 'ttl' in 'struct ares_mx_reply'
      (void)((p->ttl) | 0);  /* check that 'struct ares_mx_reply.ttl' is an integer */
              ~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4419:14: error: no member named 'ttl' in 'struct ares_naptr_reply'
      (void)((p->ttl) | 0);  /* check that 'struct ares_naptr_reply.ttl' is an integer */
              ~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4459:14: error: no member named 'ttl' in 'struct ares_soa_reply'
      (void)((p->ttl) | 0);  /* check that 'struct ares_soa_reply.ttl' is an integer */
              ~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4473:14: error: no member named 'ttl' in 'struct ares_srv_reply'
      (void)((p->ttl) | 0);  /* check that 'struct ares_srv_reply.ttl' is an integer */
              ~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4486:14: error: no member named 'ttl' in 'struct ares_txt_ext'
      (void)((p->ttl) | 0);  /* check that 'struct ares_txt_ext.ttl' is an integer */
              ~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4498:14: error: no member named 'ttl' in 'struct ares_txt_reply'
      (void)((p->ttl) | 0);  /* check that 'struct ares_txt_reply.ttl' is an integer */
              ~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4757:12: error: no member named 'ttl' in 'ares_mx_reply'
      { "ttl", offsetof(struct ares_mx_reply, ttl),
               ^                              ~~~
    /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
    #define offsetof(t, d) __builtin_offsetof(t, d)
                           ^                     ~
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4758:48: error: no member named 'ttl' in 'struct ares_mx_reply'
               sizeof(((struct ares_mx_reply *)0)->ttl),
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4781:12: error: no member named 'ttl' in 'ares_naptr_reply'
      { "ttl", offsetof(struct ares_naptr_reply, ttl),
               ^                                 ~~~
    /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
    #define offsetof(t, d) __builtin_offsetof(t, d)
                           ^                     ~
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4782:51: error: no member named 'ttl' in 'struct ares_naptr_reply'
               sizeof(((struct ares_naptr_reply *)0)->ttl),
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4853:12: error: no member named 'ttl' in 'ares_soa_reply'
      { "ttl", offsetof(struct ares_soa_reply, ttl),
               ^                               ~~~
    /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
    #define offsetof(t, d) __builtin_offsetof(t, d)
                           ^                     ~
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4854:49: error: no member named 'ttl' in 'struct ares_soa_reply'
               sizeof(((struct ares_soa_reply *)0)->ttl),
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4871:12: error: no member named 'ttl' in 'ares_srv_reply'
      { "ttl", offsetof(struct ares_srv_reply, ttl),
               ^                               ~~~
    /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
    #define offsetof(t, d) __builtin_offsetof(t, d)
                           ^                     ~
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4872:49: error: no member named 'ttl' in 'struct ares_srv_reply'
               sizeof(((struct ares_srv_reply *)0)->ttl),
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4886:12: error: no member named 'ttl' in 'ares_txt_ext'
      { "ttl", offsetof(struct ares_txt_ext, ttl),
               ^                             ~~~
    /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
    #define offsetof(t, d) __builtin_offsetof(t, d)
                           ^                     ~
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4887:47: error: no member named 'ttl' in 'struct ares_txt_ext'
               sizeof(((struct ares_txt_ext *)0)->ttl),
                      ~~~~~~~~~~~~~~~~~~~~~~~~~~  ^
    build/temp.macosx-10.14-x86_64-3.9/_cares.c:4898:12: error: no member named 'ttl' in 'ares_txt_reply'
      { "ttl", offsetof(struct ares_txt_reply, ttl),
               ^                               ~~~
    /Library/Developer/CommandLineTools/usr/lib/clang/12.0.0/include/stddef.h:104:24: note: expanded from macro 'offsetof'
    #define offsetof(t, d) __builtin_offsetof(t, d)
                           ^                     ~
    fatal error: too many errors emitted, stopping now [-ferror-limit=]
    20 errors generated.
    error: command '/usr/bin/clang' failed with exit code 1
    ----------------------------------------
ERROR: Command errored out with exit status 1: /usr/local/opt/[email protected]/bin/python3.9 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/setup.py'"'"'; __file__='"'"'/private/tmp/pip-install-d4u3_tc3/pycares_fabdec947a284edba96e5fec04d1d80f/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/tmp/pip-record-ugdhf7c2/install-record.txt --single-version-externally-managed --compile --install-headers /usr/local/include/python3.9/pycares Check the logs for full command output.

Cat Flap entity picture changes only after hours / reloading

as mentioned in the sureha repo, the entity picture for the Cat Flap lock-status only changes after several hours or after reloading the integration / restarting HA.

benleb/sureha#54

it would be great, if the entity picture can change immediately with the state change of the sensors.
I am not sure, if this is related with SureHA or SurePy, because the picture will be pulled with SurePy ...

So sorry if this might be wrong here :)

Intermittent Errors With the SurePet HomeAssistant integrations on reboot of Home Assistant

Since Home Assistant v0.108.0 (or around) I've seen intermittent errors from the SurePet integration when restarting Home Assistant. Errors are as follows:

2020-04-16 21:00:02 ERROR (MainThread) [surepy] Can not load data from https://app.api.surehub.io/api/me/start
2020-04-16 21:00:02 ERROR (MainThread) [homeassistant.components.surepetcare] Unable to connect to surepetcare.io: Wrong !
2020-04-16 21:00:02 ERROR (MainThread) [homeassistant.setup] Setup failed for surepetcare: Integration failed to initialize.

The issue is intermittent and is generally fixed by restarting Home Assistant repeatedly until it comes up successfully. Once it is up it is completely reliable.

Thanks for a great integration and please let me know if I can provide more detail to assistant with identification and resolution.

SurePy.Client Get app.api.surehub.io/api/report/household/xyz/: 404

I was going through my HA logs, because I was searching for something non related to SurePy / SureHa when I noticed the following information (404 not found)

2024-01-06 10:30:05.039 INFO (MainThread) [surepy.client] 🐾 �[38;2;255;0;255m·�[0m GET app.api.surehub.io/api/report/household/232498: 404 | <ClientResponse(https://app.api.surehub.io/api/report/household/232498) [404 Not Found]>
<CIMultiDictProxy('Date': 'Sat, 06 Jan 2024 09:30:04 GMT', 'Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'nginx', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block')>

2024-01-06 10:30:05.039 DEBUG (MainThread) [custom_components.sureha] Finished fetching sureha_sensors data in 3.929 seconds (success: True)
2024-01-06 10:30:05.039 INFO (MainThread) [custom_components.sureha] 
2024-01-06 10:30:05.040 INFO (MainThread) [custom_components.sureha]  οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m /ᐠ ._. ᐟ\οΎ‰
2024-01-06 10:30:05.040 INFO (MainThread) [custom_components.sureha]   🐾   meeowww..! to the SureHA integration!
2024-01-06 10:30:05.040 INFO (MainThread) [custom_components.sureha]   🐾     code & issues: https://github.com/benleb/sureha
2024-01-06 10:30:05.040 INFO (MainThread) [custom_components.sureha]  οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m οΏ½[38;2;255;26;102mΒ·οΏ½[0m
2024-01-06 10:30:05.040 INFO (MainThread) [custom_components.sureha] 

I have to say, that the CatFlap seems to work - but the response and changes when a cat comes in and leave the house are delayed... and sometimes do not update at all.

this might be unrelated to the 404 error, but it might indicate a change on the API of SurePetcare.

I am using the SurePetcare integration from HA as well as SureHa in parallel, so I do see the same error for both integrations:

2024-01-06 10:30:07.418 INFO (MainThread) [surepy.client] 🐾 �[38;2;255;0;255m·�[0m GET app.api.surehub.io/api/report/household/232498: 404 | <ClientResponse(https://app.api.surehub.io/api/report/household/232498) [404 Not Found]>
<CIMultiDictProxy('Date': 'Sat, 06 Jan 2024 09:30:07 GMT', 'Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'nginx', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block')>

2024-01-06 10:30:07.419 DEBUG (MainThread) [homeassistant.components.surepetcare] Finished fetching surepetcare data in 1.615 seconds (success: True)
2024-01-06 10:30:09.097 INFO (MainThread) [surepy.client] 🐾 �[38;2;255;0;255m·�[0m GET app.api.surehub.io/api/report/household/232498: 404 | <ClientResponse(https://app.api.surehub.io/api/report/household/232498) [404 Not Found]>
<CIMultiDictProxy('Date': 'Sat, 06 Jan 2024 09:30:08 GMT', 'Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'nginx', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block')>

2024-01-06 10:30:09.097 DEBUG (MainThread) [custom_components.sureha] Finished fetching sureha_sensors data in 0.840 seconds (success: True)
2024-01-06 10:30:09.656 INFO (SyncWorker_4) [ynca.subunit] Subunit Subunit.MAIN initialization end.

Authentication Issues (via HomeAssistant

Not sure if this is from the underlying surepy library or not but thought it worth raising...

home-assistant/core#80245

For a week or so now I'm unable to get the HA integration to authenticate with the Sure Petcare APIs. The account definitely works so I know username and password are right. Details on the issue raised on the HomeAssistant page, but happy to provide more if needed.

Surepy CLI request token doesn't return token

When using CLI to get token, I get the following. What could be wrong?

────────────────────────────────────────────── myemail Β· Token ───────────────────────────────────────────────
<Command token>
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────


stabilize the cli & make it more pretty

the cli is currently a rough script without proper structure and mostly used for development. I think the code itself can be improved and the output (which values, style) should also be reviewed.

Add feeder data on integration

Hello,

Any chance of adding some more data from the feeder other than just battery life I have found the data that would be helpfull to be added i can supply access to an account with feeders if required.

Integration in Home Assistant

Hi,

I tried to include surepy via the entry of the configration.yaml into Home Assistant ... but I get always this error message when I restart HA:

Invalid config
The following integrations and platforms could not be set up:

surepetcare
Please check your config and logs.

-> logs:
Error during setup of component surepetcare
11:24:02 – (FEHLER) util/async_.py
Detected I/O inside the event loop. This is causing stability issues. Please report issue for surepetcare doing I/O at homeassistant/components/surepetcare/init.py, line 116: device_data = await surepy.device(device[CONF_ID])

11:24:02 – (WARNUNG) util/async_.py

Any tip is appreciated - thank you!

Disconnected Flap -> Connect status does not change

For debugging severe issues with my zigbee network after implementing / pairing the Sure Petcare flap with the hub, I disconnected the hub from the power - and removed the batteries from the flap.

The connection status for the Hub will be shown correctly in SureHA:
grafik

But the flap itself does not update the connection status, and is still shown as connected:
grafik

I would expect the flap to switch to disconnected, when the hub is offline - since the flap can't connect to the cloud then (especially, without its batteries ;) )

Pet State Changes Randomly

I originaly posted this on the issues page for HA and they adviced me to try sureHA and if it still happens to flag it here because they use this library.

I'm just reposting the same I did at the HA reposetory:
I have two Pets and as of late there states changes randomly (at the exact same time!)! My cats did not use the door and the Sure Pet App also didn't report any state changes!. The door itself did not aktivate at any point. It even does so when my cat is not even near the door. I restarted HA now multiple times the Flap Door as well. I even removed and re-installed the integration, still doesn't work. I also notived that in the log there apears an 404 Error every time surepet tries to connect to the Surepet.io website

Log entry:

2024-01-03 23:44:58.792 INFO (MainThread) [surepy.client] 🐾 �[38;2;255;0;255m·�[0m GET app.api.surehub.io/api/report/household/'XXXXX': 404 | <ClientResponse(https://app.api.surehub.io/api/report/household/'XXXXX') [404 Not Found]>
<CIMultiDictProxy('Date': 'Wed, 03 Jan 2024 22:44:58 GMT', 'Content-Length': '0', 'Connection': 'keep-alive', 'Server': 'nginx', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block')>

Interested in mentored sprints?

Hi Ben,

Came across your surepy repository and I am wondering if you'd be interested in being part of a mentored sprints event series (here for info) sometime in April.

How does it work? We work together to identify improvements and issues people can work on, and on the day of the event we get together and tackle issues.

We share your project on social media, and advertise you are seeking sponsors.

Let me know if this is something you'd be interested in.

Laura from Vancouver PyLadies
https://twitter.com/pyladiesvan
https://twitter.com/LGFunderburk

Add support for setting LED status

It's possible to control the hub LED status by sending HTTP PUT to:
https://app.api.surehub.io/api/device/<deviceid>/control
with a JSON body like :
{"led_mode":4}
I found LED modes:

  1. Off
  2. Bright Green
  3. invalid
  4. invalid
  5. Dimmed Green
  6. invalid

Could this be added to the lib?

Longer tokens are not supported

Hello,

I fetched a new token today, and it was 491 characters long. This is longer than token_seems_valid() accepts, so it was rejected. After editing the function to allow tokens of length up to 500 I was able to authenticate and use surepy as normal. I would add a PR, but I have no idea what is considered an acceptable length.

Thanks for making this module!

Create usage example

Would it be possible to generate a usage example as part of this project of how to use this within another python script? How to retrieve the state of a pet door for example would be most helpful.

There are only examples/docs for using CLI at present.

Generate Device ID method can crash

Looks like generate_device_id doesn't always generate valid random bytes, breaking the casting to int.

From Home Assistant CI: https://github.com/home-assistant/core/pull/40926/checks?check_run_id=1192119389#step:8:96

 venv/lib/python3.7/site-packages/surepy/__init__.py:71: in __init__
    self._device_id = self._generate_device_id()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

    @staticmethod
    def _generate_device_id() -> str:
        """Generate a "unique" client device ID based on MAC address."""
        random_bytes = ":".join(
            ("%12x" % random.randint(0, 0xFFFFFFFFFFFF))[i : i + 2]
            for i in range(0, 12, 2)
        )
    
>       mac_dec = int(random_bytes.replace(":", "").replace("-", ""), 16)
E       ValueError: invalid literal for int() with base 16: 'd4 d49085535'

Installation/setup error?

Installed surepy using pip and used the Library example code from the README.
I am getting a load of errors and am not sure what the issue is. I used my credentials for the Sure Pet account, but get thefollowing when I try to run this example.

Traceback (most recent call last): File "Z:\programming\python\surepy_testing\catflap_test.py", line 42, in <module> asyncio.run(main()) File "C:\Program Files\Python39\lib\asyncio\runners.py", line 44, in run return loop.run_until_complete(main) File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 642, in run_until_complete return future.result() File "Z:\programming\python\surepy_testing\catflap_test.py", line 24, in main pets: List[Pet] = await surepy.get_pets() File "C:\Users\rob_r\AppData\Roaming\Python\Python39\site-packages\surepy\__init__.py", line 297, in get_pets return [pet for pet in (await self.get_entities()).values() if isinstance(pet, Pet)] File "C:\Users\rob_r\AppData\Roaming\Python\Python39\site-packages\surepy\__init__.py", line 349, in get_entities if response := await self.sac.call(method="GET", resource=MESTART_RESOURCE): File "C:\Users\rob_r\AppData\Roaming\Python\Python39\site-packages\surepy\client.py", line 218, in call self._auth_token = await self.get_token() File "C:\Users\rob_r\AppData\Roaming\Python\Python39\site-packages\surepy\client.py", line 188, in get_token raise SurePetcareError() Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001888E364550> Traceback (most recent call last): File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 116, in __del__ self.close() File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 108, in close self._loop.call_soon(self._call_connection_lost, None) File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 746, in call_soon self._check_closed() File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 510, in _check_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed surepy.exceptions.SurePetcareError

documentation of the library

there are many comments in the code but no real documentation or docstrings currently which makes it hard for people unfamiliar with the code to use it

TypeError in Surepy

I'm getting the following error using SuraHa v0.2.0 on HA 2021.9.2. I noticed the error after upgrading to a commit release from yesterday, then updated to 0.2 today hoping to resolve it. I currently have no cats registered to a single cat flap.

2021-09-05 08:19:36 ERROR (MainThread) [custom_components.sureha] Unexpected error fetching sureha_sensors data: object of type 'int' has no len()
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 187, in _async_refresh
self.data = await self._async_update_data()
File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 147, in _async_update_data
return await self.update_method()
File "/config/custom_components/sureha/__init__.py", line 94, in async_update_data
return await spc.surepy.get_entities(refresh=True)
File "/usr/local/lib/python3.9/site-packages/surepy/__init__.py", line 389, in get_entities
await self.get_actions(household_id=household_id)
File "/usr/local/lib/python3.9/site-packages/surepy/__init__.py", line 169, in get_actions
await self.sac.call(method="GET", resource=resource) or {}
File "/usr/local/lib/python3.9/site-packages/surepy/client.py", line 284, in call
len(response_data.get("data", 0)),
TypeError: object of type 'int' has no len()
2021-09-05 08:19:36 WARNING (MainThread) [homeassistant.config_entries] Config entry 'Sure Petcare' for sureha integration not ready yet: object of type 'int' has no len(); Retrying in background

Doing some debugging, it looks like you are trying to put out a debug message at line 284, which when it does the call to the below resource, returns nothing - maybe because I have added no cats yet:

https://app.api.surehub.io/api/report/household/nnnnnn

I'll write a pull request to handle.

add more feeder support

we should use the same data/endpoint as used for felaqua (see #20) and provide the relevant values (food type/food remaining) for both bowls

commit poetry.lock to the repository?

According to poetry docs,

Committing [poetry.lock] to VC is important because it will cause anyone who sets up the project to use the exact same versions of the dependencies that you are using. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident the dependencies installed are still working even if your dependencies released many new versions since then.

I could make a PR with the poetry.lock I have but it would be best I think to commit whatever @benleb have in his dev environment already.

Pet profile

Not an issue, but a feature request :)

The application allows to set a pet as:

  • Normal
  • Indoor only (a pet that is not allowed to go out, but can get in if it happens to go out by another mean)

In the json payload of the web application these two appears respectively as

  • profile:2
  • profile:3

example of 'normal' pet

{
"1": {
"id": 123456,
"index": 1,
"profile": 2,
"version": "MTg=",
"created_at": "2020-07-02T06:24:56+00:00",
"updated_at": "2022-10-05T10:13:42+00:00"
}
}

Because of an issue with one of my cats, I discovered trough SurePet support that an 'Intruder' profile exists as well.
This would be a pet allowed to exit but not to come in.
The application does not allow you to set this (and does not displays it properly...
but in the json payload it appears as profile:5

Would be nice to be able to set these profiles with surepy :D

The webapp changes profiles with a PUT request to an url like this
https://app.api.surehub.io/api/device/111111/tag/123456
with payload
profile:id
(the tag and the ID above have the same value)

Not sure if other useful profiles exists...

Exception from set_curfew API (daylight saving change related?)

Just a heads up in case others hit this - I've been getting an exception from the set_curfew API since daylight saving changed for me today (in NZ, so changing out of daylight saving).

I'll look at adding a workaround, but I think this is a once-a-year issue that will go away in a few hours. I think I had a similar issue this time last year.

I think this is because the Sure API is doing some weird adjustment (possibly a bug) to correct for daylight saving changing. Via the website, if I manually set the curfew end time it's subtracting one hour from the requested end time.

e.g. If via the Sure app, I set Unlock time of 7:39, then it succeeds, but shows time on the website (and via the API data) at 6:39.

PUT https://app-api.production.surehub.io/api/device/123/control

request:

{
	"curfew": [
		{
			"enabled": true,
			"lock_time": "18:05",
			"unlock_time": "07:39"
		}
	]
}

200 response: (note unlock_time)

{
	"data": {
		"curfew": [
			{
				"enabled": true,
				"lock_time": "18:05",
				"unlock_time": "06:39"
			}
		],
		"locking": 0,
		"fast_polling": true
	}
}

I think this is a timezone bug from the backend of the Sure app. Maybe something like it's using midnight of current date (rather than current date-time) to figure out if daylight saving is in effect.

On our side, the issue is that we fail this check, because the response unlock_time doesn't match the request time here:

surepy/surepy/client.py

Lines 375 to 380 in 9806785

# check if the state is correctly updated
if state == desired_state:
return response
# return None
raise SurePetcareError("ERROR (UN)LOCKING DEVICE - PLEASE CHECK IMMEDIATELY!")

Potentially we could change this to a warning.

Surepy unlocking error

When trying to call the sevice for the cat flap to lock/unlock i get an unknown error. Looking at the logs outputs this:

  File "/usr/src/homeassistant/homeassistant/components/websocket_api/decorators.py", line 21, in _handle_async_response
    await func(hass, connection, msg)
  File "/usr/src/homeassistant/homeassistant/components/websocket_api/commands.py", line 482, in handle_execute_script
    await script_obj.async_run(msg.get("variables"), context=context)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 1209, in async_run
    await asyncio.shield(run.async_run())
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 345, in async_run
    await self._async_step(log_exceptions=False)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 363, in _async_step
    await getattr(self, handler)()
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 563, in _async_call_service_step
    await service_task
  File "/usr/src/homeassistant/homeassistant/core.py", line 1481, in async_call
    task.result()
  File "/usr/src/homeassistant/homeassistant/core.py", line 1516, in _execute_service
    await handler.job.target(service_call)
  File "/usr/src/homeassistant/homeassistant/components/surepetcare/__init__.py", line 102, in handle_set_lock_state
    await spc.set_lock_state(call.data[ATTR_FLAP_ID], call.data[ATTR_LOCK_STATE])
  File "/usr/src/homeassistant/homeassistant/components/surepetcare/__init__.py", line 162, in set_lock_state
    await self.surepy.unlock(flap_id)
AttributeError: 'Surepy' object has no attribute 'unlock' ```

Log error: "error while setting up sureha platform for sensor"

As mentioned in benleb/sureha#44
I am getting the following error in my logs, which is also showing a reference to SurePy:

Logger: homeassistant.components.sensor
Source: helpers/entity_platform.py:360
Integration: Sensor (documentation, issues)
First occurred: 5:01:34 PM (1 occurrences)
Last logged: 5:01:34 PM

Error while setting up sureha platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 360, in _async_setup_platform
    await asyncio.shield(task)
  File "/config/custom_components/sureha/sensor.py", line 64, in async_setup_entry
    entities.append(Flap(spc.coordinator, surepy_entity.id, spc))
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/config/custom_components/sureha/sensor.py", line 184, in __init__
    self._attr_entity_picture = self._surepy_entity.icon
                                ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/surepy/entities/devices.py", line 247, in icon
    if self.state == LockState.LOCKED_ALL:
       ^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/surepy/entities/devices.py", line 235, in state
    return LockState(self._data["status"]["locking"]["mode"])
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
KeyError: 'mode'

Lock In from CLI doesn't work

state = "locked in"

Howdy Ben! I think you're missing a line when attempting to lock the cats inside using the CLI. I suspect you need to add
lock_control = flap.lock_in
immediately before/after the line I've linked to above.

Incorrect use of self._breeds when populating self._species_breeds

The code in surepy/__init__.py is trying to check if the species was seen before but incorrectly checks that in self._breeds instead of self._species_breeds:

if breed["species_id"] not in self._breeds:

should be

if breed["species_id"] not in self._species_breeds:

New Features - Exit Permissions, Add/Remove Pet from a door

Hello there,
First, thanks for the work achieved so far. I've started to develop a domoticz plugin based on last version of your lib, using python 3.9.1 , and it's working well.

I would ask if you were kind to add some new features like this :

  • possibility to set exit permissions for each pet on Microchip Cat Flap Connect (on the small one, because you can't do that on the big one.)

I'm not sure that I had captured the correct parameters but I think so.
EXIT PERM DENIED https://app.api.surehub.io/api/device/[DeviceNumber]/tag/[PetID] request method : PUT {"profile":3}
EXIT PERM AUTHORIZED https://app.api.surehub.io/api/device/[DeviceNumber]/tag/[PetID] request method : PUT {"profile":2}

  • possibility to assign/unassign a pet from any door. (the pet id are stored on the server, and you can attach/detach them via the app from each door.) <- I'm using this as an enter+exit permissions on each door (big one + small one) and you don't need to remove/create the pet profile so it's easy to use this way.

I'm not sure that I had captured the correct parameters but I think so.
UNASSIGNED https://app.api.surehub.io/api/device/[DeviceNumber]/tag/[PetID] request method: DELETE {}
ASSIGN https://app.api.surehub.io/api/device/[DeviceNumber]/tag/[PetID] request method: PUT {}

  • gather the Exit permissions per pet on a door. (you can find them in the app submenu)

(For info ;p I'm using 4 doors (big + small) and 7 cats.)

Regards,
Ash,

Fixed number of entries

get_household_timeline will always return number of entries as a multiple of 25 as page_size=max_entries_per_page.

E.g. setting entries=1 returns 25 entries, where setting entries=26 returns 50 entries.

surepy/surepy/__init__.py

Lines 245 to 264 in 5d72298

async def get_household_timeline(
self, household_id: int | None = None, entries: int = 25
) -> list[dict[str, Any]]:
"""Fetch Felaqua water level information."""
# pagination as the api gives us at most 25 results per page
max_entries_per_page = 25
pages_to_fetch = ceil(entries / max_entries_per_page)
current_page = 1
household_timeline = []
while current_page <= pages_to_fetch:
resource = HOUSEHOLD_TIMELINE_RESOURCE.format(
BASE_RESOURCE=BASE_RESOURCE,
household_id=household_id,
page=current_page,
page_size=max_entries_per_page,
)

having issues logging in

Getting the following in HASS that I assume is a surepy issue (well, a sure petcare issue really I would guess)

2023-12-10 13:30:26.544 ERROR (MainThread) [surepy.client] 🐾 �[38;2;255;26;102m·�[0m GET app.api.surehub.io/api/me/start: 401 | <ClientResponse(https://app.api.surehub.io/api/me/start) [401 Unauthorized]>
2023-12-10 13:30:28.024 DEBUG (MainThread) [surepy.client] 🐾 �[38;2;0;255;0m·�[0m GET app.api.surehub.io/api/me/start | 6
2023-12-10 13:30:28.025 DEBUG (MainThread) [homeassistant.components.surepetcare] Finished fetching surepetcare data in 1.623 seconds (success: False)
2023-12-10 13:30:28.025 WARNING (MainThread) [homeassistant.config_entries] Config entry 'Sure Petcare' for surepetcare integration could not authenticate: Invalid username/password

Package dependency conflicts

I've just noticed in my dev environment that there is a conflict installing surepy. HA is asking for surepy==0.7.2, and sureha is asking for surepy>=0.7.2 so I don't think that is the direct issue. When I try to install surepy as below (because HA has upgraded the version of pip they are installing, so have added the use-deprecated parameter), I get the error at the bottom.:

pip install surepy --use-deprecated=legacy-resolver

ERROR: pip's legacy dependency resolver does not consider dependency conflicts when selecting packages. This behaviour is the source of the following dependency conflicts.
aiohttp 3.8.1 requires async-timeout<5.0,>=4.0.0a3, but you'll have async-timeout 3.0.1 which is incompatible.
homeassistant 2022.3.0.dev0 requires async_timeout==4.0.2, but you'll have async-timeout 3.0.1 which is incompatible.
Successfully installed Brotli-1.0.9 aiodns-3.0.0 async-timeout-3.0.1 cchardet-2.1.7 colorama-0.4.4 commonmark-0.9.1 pycares-4.1.2 pygments-2.11.2 rich-10.16.2 surepy-0.7.2

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.