Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reformat code with black #13

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions hass_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@
from pprint import pprint
import json

dut = Dut.SurePetConnect( user, pw, debug = True, cache_file = cache_file )
dut = Dut.SurePetConnect(user, pw, debug=True, cache_file=cache_file)


print( '--- state (decoded JSON):' )
pprint( json.loads( dut.state ) )
print("--- state (decoded JSON):")
pprint(json.loads(dut.state))

print( '\n--- state attributes:' )
pprint( dut.state_attributes )
print("\n--- state attributes:")
pprint(dut.state_attributes)
73 changes: 43 additions & 30 deletions home_assistant/sure_petflap.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
from datetime import timedelta
import json


def is_hass_component():
try:
import homeasssistant

return True
except ImportError:
return False


if is_hass_component():
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle
Expand All @@ -21,10 +24,9 @@ def is_hass_component():

import voluptuous as vol

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
})
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string}
)
else:
# Assume not running within home assistant. This *does* mean that you
# won't be able to run this test script if you have homeassistant
Expand All @@ -34,26 +36,28 @@ def is_hass_component():
from sure_petcare.utils import gen_device_id

# dummy dependencies
class Entity( object ):
class Entity(object):
pass

def Throttle( *args, **kwargs ):
def decorator( f ):
def Throttle(*args, **kwargs):
def decorator(f):
return f

return decorator


#REQUIREMENTS = ['sure_petcare']
# REQUIREMENTS = ['sure_petcare']


_LOGGER = logging.getLogger(__name__)

CONF_device_id = 'device_id'
CONF_device_id = "device_id"

SCAN_INTERVAL = timedelta(seconds=300)
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=600)
MIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=120)


def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the sensor platform."""
username = config.get(CONF_USERNAME)
Expand All @@ -66,23 +70,28 @@ class SurePetConnect(Entity):

def __init__(self, username, password, **kwargs):
"""Initialize the sensor."""
_LOGGER.debug('Initializing...')
_LOGGER.debug("Initializing...")
# 1.25V is a fairly conservative guess for alkalines. If you use
# rechargeables, you may need to change this.
self.FULL_BATTERY_VOLTAGE = 1.6 # volts
self.LOW_BATTERY_VOLTAGE = 1.25 # volts
self.battery = [-1] *60
self.battery[0] = 1 # Initialize average so we have a mean
self.FULL_BATTERY_VOLTAGE = 1.6 # volts
self.LOW_BATTERY_VOLTAGE = 1.25 # volts
self.battery = [-1] * 60
self.battery[0] = 1 # Initialize average so we have a mean
self.battery_pos = -1
self.sure = SurePetFlap(email_address=username, password=password, device_id=gen_device_id(), **kwargs)
self.sure = SurePetFlap(
email_address=username,
password=password,
device_id=gen_device_id(),
**kwargs
)
self._state = None
self._attributes = []
self.update()

@property
def name(self):
"""Return the name of the sensor."""
return 'SurePet Connect'
return "SurePet Connect"

@property
def state(self):
Expand All @@ -92,15 +101,15 @@ def state(self):
@property
def unit_of_measurement(self):
"""Return the unit of measurement."""
return ''
return ""

@Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)
def update(self):
"""Fetch new state data for the sensor.

This is the only method that should fetch new data for Home Assistant.
"""
_LOGGER.debug('Returning current state...')
_LOGGER.debug("Returning current state...")
flap_status = {}
with self.sure:
# Update only data required
Expand All @@ -113,22 +122,26 @@ def update(self):
self.sure.update_router_status()
for pet in self.sure.pets:
pet_status = self.sure.get_current_status(pet)
flap_status[str(self.sure.pets[pet]['name'])] = pet_status
self.battery_pos = (self.battery_pos + 1) % len(self.battery) #Loop around
flap_status[str(self.sure.pets[pet]["name"])] = pet_status
self.battery_pos = (self.battery_pos + 1) % len(self.battery) # Loop around
# NB: Units have changed. Earlier versions reported the raw voltage
# direct from the Sure backend which was the sum of the four
# batteries. The current API reports voltage per battery, making
# it easier to set thresholds based on battery chemistry.
bat_left = self.sure.battery - self.LOW_BATTERY_VOLTAGE
bat_full = self.FULL_BATTERY_VOLTAGE - self.LOW_BATTERY_VOLTAGE
self.battery[self.battery_pos] = int(bat_left/bat_full*100)
flap_status['avg_battery'] = int(self.mean([ i for i in self.battery if i > 0]))
flap_status['battery'] = self.battery[self.battery_pos]
flap_status['flap_online'] = self.sure.flap_status[self.sure.default_flap]['online']
flap_status['hub_online'] = self.sure.router_status[self.sure.default_router]['online']
flap_status['lock_status'] = self.sure.lock_mode()
flap_status['locked'] = self.sure.locked()
_LOGGER.debug('State: ' + str(flap_status))
self.battery[self.battery_pos] = int(bat_left / bat_full * 100)
flap_status["avg_battery"] = int(self.mean([i for i in self.battery if i > 0]))
flap_status["battery"] = self.battery[self.battery_pos]
flap_status["flap_online"] = self.sure.flap_status[self.sure.default_flap][
"online"
]
flap_status["hub_online"] = self.sure.router_status[self.sure.default_router][
"online"
]
flap_status["lock_status"] = self.sure.lock_mode()
flap_status["locked"] = self.sure.locked()
_LOGGER.debug("State: " + str(flap_status))
self._state = json.dumps(flap_status)
self._attributes = flap_status

Expand All @@ -140,6 +153,6 @@ def state_attributes(self):
"""

return self._attributes

def mean(self, numbers):
return float(sum(numbers)) / max(len(numbers), 1)
24 changes: 13 additions & 11 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from setuptools import setup

setup(name='sure_petcare',
version='0.1',
description='Library to access sure connect catflat',
url='http://github.com/rcastberg/sure_petcare',
author='Rene Castberg',
author_email='[email protected]',
license='GPL',
install_requires=['requests'],
packages=['sure_petcare'],
scripts=['sp_cli.py'],
zip_safe=False)
setup(
name="sure_petcare",
version="0.1",
description="Library to access sure connect catflat",
url="http://github.com/rcastberg/sure_petcare",
author="Rene Castberg",
author_email="[email protected]",
license="GPL",
install_requires=["requests"],
packages=["sure_petcare"],
scripts=["sp_cli.py"],
zip_safe=False,
)
94 changes: 52 additions & 42 deletions sp_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@

import sure_petcare

def main( argv ):

def main(argv):
description = """\
Sure Petcare Connect CLI

Expand Down Expand Up @@ -44,31 +45,36 @@ def main( argv ):
your pets, flap or household. Note that --update is mutually exclusive with any
other option (other than --email or --pass)."""

parser = argparse.ArgumentParser( description = description, formatter_class = argparse.RawDescriptionHelpFormatter )
parser.add_argument( '-e', '--email',
help = 'account email address' )
parser.add_argument( '-p', '--pass', dest = 'pw',
help = 'account password' )
parser.add_argument( '--update', action = 'store_true',
help = 'update cache from Sure servers. Mutually exclusive with commands/queries.' )
parser.add_argument( '-c', '--cache-file',
help = 'Cache file to use if not default' )
parser.add_argument( 'cmd', nargs = '*',
help = 'One of ' + ', '.join( sorted(CMDS.keys()) ) )
parser = argparse.ArgumentParser(
description=description, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument("-e", "--email", help="account email address")
parser.add_argument("-p", "--pass", dest="pw", help="account password")
parser.add_argument(
"--update",
action="store_true",
help="update cache from Sure servers. Mutually exclusive with commands/queries.",
)
parser.add_argument("-c", "--cache-file", help="Cache file to use if not default")
parser.add_argument(
"cmd", nargs="*", help="One of " + ", ".join(sorted(CMDS.keys()))
)
args = parser.parse_args()

if args.update and args.cmd:
exit( '--update and commands/queries are mutually exclusive' )
exit("--update and commands/queries are mutually exclusive")

if not args.update and not args.cmd:
parser.print_help()
exit()

debug = os.environ.get( 'SPDEBUG' ) is not None
sp = sure_petcare.SurePetFlap( email_address = args.email,
password = args.pw,
cache_file = args.cache_file,
debug = debug )
debug = os.environ.get("SPDEBUG") is not None
sp = sure_petcare.SurePetFlap(
email_address=args.email,
password=args.pw,
cache_file=args.cache_file,
debug=debug,
)

if args.update:
# Either update and write the cache, or...
Expand All @@ -77,80 +83,84 @@ def main( argv ):
else:
# ... execute queries on cached data
if args.cmd[0] in CMDS:
CMDS[args.cmd[0]]( sp, args )
CMDS[args.cmd[0]](sp, args)
else:
exit( 'Unknown command: %s' % (args.cmd[0],) )
exit("Unknown command: %s" % (args.cmd[0],))


CMDS = {}
def cmd( f ):
if f.__name__.startswith( 'cmd_' ):


def cmd(f):
if f.__name__.startswith("cmd_"):
fn = f.__name__[4:]
CMDS[fn] = f
else:
raise ValueError( 'bad use of @cmd decorator: %s' % (f.__name__,) )
raise ValueError("bad use of @cmd decorator: %s" % (f.__name__,))
return f


@cmd
def cmd_ls_house( sp, args ):
def cmd_ls_house(sp, args):
"""
List households
"""
for hid, hdata in sp.households.items():
default_flag = (hid == sp.default_household) and '(active)' or ''
print( '%s\t%s %s' % (hid, hdata['name'], default_flag,) )
default_flag = (hid == sp.default_household) and "(active)" or ""
print("%s\t%s %s" % (hid, hdata["name"], default_flag))


@cmd
def cmd_ls_pets( sp, args ):
def cmd_ls_pets(sp, args):
"""
For each pet in household, show location (inside, outside, unknown)
"""
for pid, pdata in sp.pets.items():
print( '%s (%s) is %s' % (pdata['name'], pid, sp.get_current_status( pid ),) )
print("%s (%s) is %s" % (pdata["name"], pid, sp.get_current_status(pid)))


@cmd
def cmd_ls_flaps( sp, args ):
def cmd_ls_flaps(sp, args):
"""
For each pet in household, show location (inside, outside, unknown)
"""
for flap_id, name in sp.household['flaps'].items():
bat = sp.get_battery( flap_id = flap_id )
lck = sp.lock_mode( flap_id )
print( '%s (%s) at %05.3fV is %s' % (name, flap_id, bat, lck,) )
for flap_id, name in sp.household["flaps"].items():
bat = sp.get_battery(flap_id=flap_id)
lck = sp.lock_mode(flap_id)
print("%s (%s) at %05.3fV is %s" % (name, flap_id, bat, lck))


@cmd
def cmd_pet_tl( sp, args ):
def cmd_pet_tl(sp, args):
"""
For each pet in household, show location (inside, outside, unknown)
"""
try:
name = args.cmd[1]
except IndexError:
exit('need pet name (enclose in quotes if necessary)')
exit("need pet name (enclose in quotes if necessary)")

sp.print_timeline( name = name )
sp.print_timeline(name=name)


@cmd
def cmd_set_hid( sp, args ):
def cmd_set_hid(sp, args):
"""
Set default household ID
"""
try:
hid = int(args.cmd[1])
except (ValueError, IndexError,):
exit( 'need valid household ID' )
except (ValueError, IndexError):
exit("need valid household ID")

if hid in sp.households:
with sp:
sp.default_household = hid
if sp.update_required:
sp.update()
else:
exit( 'Household ID %s not known' % (hid,) )
exit("Household ID %s not known" % (hid,))


if __name__ == '__main__':
main( sys.argv )
if __name__ == "__main__":
main(sys.argv)
Loading