Skip to content
This repository has been archived by the owner on Jan 5, 2021. It is now read-only.

Commit

Permalink
Finally get rid of the cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
iancmcc committed Aug 23, 2015
1 parent 1b45b0f commit a13c754
Show file tree
Hide file tree
Showing 5 changed files with 12 additions and 104 deletions.
30 changes: 4 additions & 26 deletions ouimeaux/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

from .discovery import UPnPLoopbackException
from .environment import Environment
from .config import get_cache, in_home, WemoConfiguration
from .config import in_home, WemoConfiguration
from .utils import matcher

reqlog = logging.getLogger("requests.packages.urllib3.connectionpool")
Expand All @@ -24,15 +24,10 @@ def _state(device, readable=False):

def scan(args, on_switch=NOOP, on_motion=NOOP, on_bridge=NOOP, on_maker=NOOP):
try:
env = Environment(on_switch, on_motion, on_bridge, on_maker, with_subscribers=False,
bind=args.bind, with_cache=args.use_cache)
env = Environment(on_switch, on_motion, on_bridge, on_maker,
with_subscribers=False, bind=args.bind)
env.start()
with get_cache() as c:
if c.empty:
args.use_cache = False
if (args.use_cache is not None and not args.use_cache) or (
env._config.cache is not None and not env._config.cache):
env.discover(args.timeout)
env.discover(args.timeout)
except KeyboardInterrupt:
sys.exit(0)
except UPnPLoopbackException:
Expand Down Expand Up @@ -288,16 +283,6 @@ def on_bridge(bridge):

scan(args, on_switch, on_motion, on_bridge, on_maker)

def clear(args):
for fname in 'cache', 'cache.db':
filename = in_home('.wemo', fname)
try:
os.remove(filename)
except OSError:
# File didn't exist; cache must be clear
pass
print "Device cache cleared."


def server(args):
from socketio.server import SocketIOServer
Expand Down Expand Up @@ -336,20 +321,13 @@ def wemo():
parser.add_argument("-e", "--exact-match", action="store_true",
default=False,
help="Disable fuzzy matching for device names")
parser.add_argument("-f", "--no-cache", dest="use_cache", default=None,
action="store_false",
help="Disable the device cache")
parser.add_argument("-v", "--human-readable", dest="human_readable",
action="store_true", default=False,
help="Print statuses as human-readable words")
parser.add_argument("-t", "--timeout", type=int, default=5,
help="Time in seconds to allow for discovery")
subparsers = parser.add_subparsers()

clearparser = subparsers.add_parser("clear",
help="Clear the device cache")
clearparser.set_defaults(func=clear)

statusparser = subparsers.add_parser("status",
help="Print status of WeMo devices")
statusparser.set_defaults(func=status)
Expand Down
61 changes: 0 additions & 61 deletions ouimeaux/config.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
from contextlib import contextmanager, closing
import os
import shelve
import gevent
from gevent.lock import RLock

import yaml
from ouimeaux.device import Device


def in_home(*path):
Expand Down Expand Up @@ -44,10 +38,6 @@ def __init__(self, filename=None):
#
# bind: 10.1.2.3:9090
# Whether to use a device cache (stored at ~/.wemo/cache)
#
# cache: true
# Web app bind address
#
# listen: 0.0.0.0:5000
Expand All @@ -63,57 +53,6 @@ def aliases(self):
def bind(self):
return self._parsed.get('bind', None)

@property
def cache(self):
return self._parsed.get('cache', None)

@property
def listen(self):
return self._parsed.get('listen', None)


class Cache(object):
def __init__(self, shelf):
self._shelf = shelf

@property
def empty(self):
return not self._shelf.get('devices')

def clear(self):
self._shelf.clear()

def add_device(self, device):
assert isinstance(device, Device)
d = self._shelf.setdefault('devices', {})
d[device.name] = device

def invalidate(self, device):
assert isinstance(device, Device)
d = self._shelf.setdefault('devices', {})
d.pop(device.name)
self._shelf.clear()
self._shelf['devices'] = d

@property
def devices(self):
try:
return self._shelf.setdefault('devices', {}).itervalues()
except ImportError:
self._shelf.clear()
return self.devices


_CACHE_LOCK = RLock()

@contextmanager
def get_cache():
ensure_directory(in_home('.wemo'))
filename = in_home('.wemo', 'cache')
_CACHE_LOCK.acquire(blocking=True)
try:
with closing(shelve.open(filename, writeback=True)) as cache:
yield Cache(cache)
finally:
_CACHE_LOCK.release()

21 changes: 6 additions & 15 deletions ouimeaux/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import gevent
import requests

from ouimeaux.config import get_cache, WemoConfiguration
from ouimeaux.config import WemoConfiguration
from ouimeaux.device import DeviceUnreachable
from ouimeaux.device.switch import Switch
from ouimeaux.device.insight import Insight
Expand All @@ -17,6 +17,7 @@
from ouimeaux.utils import matcher


_MARKER = object()
_NOOP = lambda *x: None
log = logging.getLogger(__name__)

Expand All @@ -33,7 +34,7 @@ class UnknownDevice(Exception):

class Environment(object):
def __init__(self, switch_callback=_NOOP, motion_callback=_NOOP, bridge_callback=_NOOP,
maker_callback=_NOOP, with_discovery=True, with_subscribers=True, with_cache=None,
maker_callback=_NOOP, with_discovery=True, with_subscribers=True, with_cache=_MARKER,
bind=None, config_filename=None):
"""
Create a WeMo environment.
Expand All @@ -50,13 +51,12 @@ def __init__(self, switch_callback=_NOOP, motion_callback=_NOOP, bridge_callback
@param bind: ip:port to which to bind the response server.
@type bind: str
"""
if with_cache is not _MARKER:
log.warn("with_cache argument is deprecated (and nonfunctional)")
self._config = WemoConfiguration(filename=config_filename)
self.upnp = UPnP(bind=bind or self._config.bind)
discovered.connect(self._found_device, self.upnp)
self.registry = SubscriptionRegistry()
if with_cache is None:
with_cache = (self._config.cache if self._config.cache is not None else True)
self._with_cache = with_cache
self._with_discovery = with_discovery
self._with_subscribers = with_subscribers
self._switch_callback = switch_callback
Expand All @@ -76,11 +76,6 @@ def start(self):
"""
Start the server(s) necessary to receive information from devices.
"""
if self._with_cache:
with get_cache() as c:
for dev in c.devices:
self._process_device(dev, cache=False)

if self._with_discovery:
# Start the server to listen to new devices
self.upnp.server.set_spawn(2)
Expand Down Expand Up @@ -146,7 +141,7 @@ def _found_device(self, sender, **kwargs):
log.info("Found device %r at %s" % (device, address))
self._process_device(device)

def _process_device(self, device, cache=None):
def _process_device(self, device):
if isinstance(device, Switch):
callback = self._switch_callback
registry = self._switches
Expand Down Expand Up @@ -178,10 +173,6 @@ def _process_device(self, device, cache=None):
device.ping()
except DeviceUnreachable:
return
else:
if cache if cache is not None else self._with_cache:
with get_cache() as c:
c.add_device(device)
devicefound.send(device)
callback(device)

Expand Down
2 changes: 1 addition & 1 deletion ouimeaux/examples/watch.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def motion(sender, **kwargs):
print "{} state is {state}".format(
sender.name, state="on" if kwargs.get('state') else "off")

env = Environment(with_cache=False)
env = Environment()
try:
env.start()
env.discover(10)
Expand Down
2 changes: 1 addition & 1 deletion ouimeaux/server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
def initialize(bind=None):
global ENV
if ENV is None:
ENV = Environment(with_cache=False, bind = bind)
ENV = Environment(bind=bind)
ENV.start()
gevent.spawn(ENV.discover, 10)

Expand Down

0 comments on commit a13c754

Please sign in to comment.