示例#1
0
def test_wifi():
    _kh.get_database()

    # Not super cool but oh well.

    def _dummy_popen(n):
        l = n.split(' ')
        if l[0] == 'uci':
            return open(os.path.join(testdir, 'uci_export.txt'))
        if l[0] == 'ubus':
            return open(os.path.join(testdir, 'hostapd_get_clients.txt'))
        raise NotImplementedError(l)

    with patch('os.popen', new=_dummy_popen):
        u = _wifi.OpenWrtWifiDeviceTracker()
        u.update()
        assert _prdb_kh.WifiDevice.get_named('iphone5').on
        assert len(u._devices) == 1

    def _dummy_popen2(n):
        l = n.split(' ')
        if l[0] == 'ubus':
            return open(os.path.join(testdir, 'hostapd_get_clients_2.txt'))
        raise NotImplementedError

    with patch('os.popen', new=_dummy_popen2):
        u.update_wifi(t=time.time() + 123)
        u.update_state(t=time.time() + 123)
        assert not _prdb_kh.WifiDevice.get_named('iphone5').on
示例#2
0
def test_mpower():
    _kh.get_database()
    canned_responses = [
        ['GET', '127.0.0.1/sensors', ''], ['POST', '127.0.0.1/login.cgi', ''],
        [
            'GET', '127.0.0.1/sensors',
            '{"sensors":[{"port":1,"output":1,"power":6.90647006,"energy":2439.0625,"enabled":1,"current":0.045182228,"voltage":229.729611635,"powerfactor":0.665382709,"relay":1,"lock":0},{"port":2,"output":1,"power":4.429039955,"energy":1568.4375,"enabled":1,"current":0.027162194,"voltage":229.959799289,"powerfactor":0.709076065,"relay":1,"lock":0},{"port":3,"output":1,"power":2.548347473,"energy":4356.5625,"enabled":1,"current":0.032032728,"voltage":230.385804176,"powerfactor":0.345309876,"relay":1,"lock":0},{"port":4,"output":1,"power":0.0,"energy":483.125,"enabled":1,"current":0.0,"voltage":229.517921447,"powerfactor":0.0,"relay":1,"lock":0},{"port":5,"output":1,"power":4.104837775,"energy":1443.4375,"enabled":1,"current":0.025354385,"voltage":230.2452147,"powerfactor":0.703156989,"relay":1,"lock":0},{"port":6,"output":0,"power":2.033658504,"energy":1260.625,"enabled":1,"current":0.102739334,"voltage":230.123321533,"powerfactor":0.086016278,"relay":1,"lock":0}],"status":"success"}'
        ]
    ]

    def _request(method, url, data=None):
        exp_method, exp_url, ret_data = canned_responses.pop(0)
        assert exp_method == method
        assert exp_url == url
        return ret_data

    with patch('kodinhenki.mpower.request', new=_request):
        p = _mpower.get_updater('127.0.0.1', 'x')
        p.update()

    assert not canned_responses
    assert _prdb_kh.MPower.get_named('x_1').on
    assert _prdb_kh.MPower.get_named('x_1').output
    assert not _prdb_kh.MPower.get_named('x_4').on
    assert _prdb_kh.MPower.get_named('x_4').output
    assert not _prdb_kh.MPower.get_named('x_6').output

    with patch('kodinhenki.mpower.request', return_value='') as req:
        p1 = _prdb_kh.MPower.get_named('x_1')
        p1.set('output', False)
        assert not p1.output
        assert req.called
示例#3
0
def start():
    process.start({
        # 'xbmc': 'XBMC.app/Contents',
        #    'kodi': 'Kodi.app/Contents',
        # 'emacs': 'Emacs.app/Contents',
    })
    user_active.start('poro')

    def _f(o, key, old, new, **kwargs):
        if o.id == '.kh.home.' and key == 'state_name':
            if old == 'ProjectorState':
                # _set_volume(3) # separate audio setup now
                pass
            if old == 'AwayState':
                _itunes_play()
            # TimeoutState is bit questionable..
            # it is the 'default' if e.g. poro is not connected,
            # so do nothing there for now.
            if new == 'NightState':
                _monitor_off()
                # _itunes_pause()
                # Hmm. Good idea? Maybe not, if listening to stuff on bed.
            elif new == 'AwayState':
                _monitor_off()
                _itunes_pause()
                _lock_screen()
            elif new == 'ProjectorState':
                # Further away from computer -> more volume
                # _set_volume(10) # separate audio setup now
                _itunes_pause()
                _monitor_off()  # on different machine

    kh.get_database().object_changed.connect(_f)
示例#4
0
def test_wifi():
    _kh.get_database()
    # Not super cool but oh well.

    def _dummy_popen(n):
        l = n.split(' ')
        if l[0] == 'uci':
            return open(os.path.join(testdir, 'uci_export.txt'))
        if l[0] == 'ubus':
            return open(os.path.join(testdir, 'hostapd_get_clients.txt'))
        raise NotImplementedError(l)
    with patch('os.popen', new=_dummy_popen):
        u = _wifi.OpenWrtWifiDeviceTracker()
        u.update()
        assert _prdb_kh.WifiDevice.get_named('iphone5').on
        assert len(u._devices) == 1

    def _dummy_popen2(n):
        l = n.split(' ')
        if l[0] == 'ubus':
            return open(os.path.join(testdir, 'hostapd_get_clients_2.txt'))
        raise NotImplementedError
    with patch('os.popen', new=_dummy_popen2):
        u.update_wifi(t=time.time() + 123)
        u.update_state(t=time.time() + 123)
        assert not _prdb_kh.WifiDevice.get_named('iphone5').on
示例#5
0
def test_mpower():
    _kh.get_database()
    canned_responses = [['GET', '127.0.0.1/sensors',  ''],
                        ['POST', '127.0.0.1/login.cgi',  ''],
                        ['GET', '127.0.0.1/sensors',
                         '{"sensors":[{"port":1,"output":1,"power":6.90647006,"energy":2439.0625,"enabled":1,"current":0.045182228,"voltage":229.729611635,"powerfactor":0.665382709,"relay":1,"lock":0},{"port":2,"output":1,"power":4.429039955,"energy":1568.4375,"enabled":1,"current":0.027162194,"voltage":229.959799289,"powerfactor":0.709076065,"relay":1,"lock":0},{"port":3,"output":1,"power":2.548347473,"energy":4356.5625,"enabled":1,"current":0.032032728,"voltage":230.385804176,"powerfactor":0.345309876,"relay":1,"lock":0},{"port":4,"output":1,"power":0.0,"energy":483.125,"enabled":1,"current":0.0,"voltage":229.517921447,"powerfactor":0.0,"relay":1,"lock":0},{"port":5,"output":1,"power":4.104837775,"energy":1443.4375,"enabled":1,"current":0.025354385,"voltage":230.2452147,"powerfactor":0.703156989,"relay":1,"lock":0},{"port":6,"output":0,"power":2.033658504,"energy":1260.625,"enabled":1,"current":0.102739334,"voltage":230.123321533,"powerfactor":0.086016278,"relay":1,"lock":0}],"status":"success"}']]

    def _request(method, url, data=None):
        exp_method, exp_url, ret_data = canned_responses.pop(0)
        assert exp_method == method
        assert exp_url == url
        return ret_data

    with patch('kodinhenki.mpower.request', new=_request):
        p = _mpower.get_updater('127.0.0.1', 'x')
        p.update()

    assert not canned_responses
    assert _prdb_kh.MPower.get_named('x_1').on
    assert _prdb_kh.MPower.get_named('x_1').output
    assert not _prdb_kh.MPower.get_named('x_4').on
    assert _prdb_kh.MPower.get_named('x_4').output
    assert not _prdb_kh.MPower.get_named('x_6').output

    with patch('kodinhenki.mpower.request', return_value='') as req:
        p1 = _prdb_kh.MPower.get_named('x_1')
        p1.set('output', False)
        assert not p1.output
        assert req.called
示例#6
0
def test_user_active():
    _old = _prdb.set_lock_check_enabled(True)
    with _prdb.lock:
        kodinhenki.drop_database()  # in case previous thing played with it
        kodinhenki.get_database()  # declare schema again
    o = user_active.start('ua')
    with _prdb.lock:
        o.o.get('on')
    o.stop()
    _prdb.set_lock_check_enabled(_old)
示例#7
0
def test_user_active():
    _old = _prdb.set_lock_check_enabled(True)
    with _prdb.lock:
        kodinhenki.drop_database() # in case previous thing played with it
        kodinhenki.get_database() # declare schema again
    o = user_active.start('ua')
    with _prdb.lock:
        o.o.get('on')
    o.stop()
    _prdb.set_lock_check_enabled(_old)
示例#8
0
def start_server(db=None, ip='::1', port=kh.PORT):
    db = db or kh.get_database()
    si = pysyma.si.HNCPSystemInterface()
    # ip is ignored
    s = si.create_socket(port=port)
    p = pysyma.shsp.SHSP(sys=s)
    s.set_dncp_unicast_listen(p)
    return _shared_start(db, si, p, port=s.get_port())
示例#9
0
def _test_wemo(caplog):
    _old = _prdb.set_lock_check_enabled(True)
    if caplog: caplog.setLevel(logging.DEBUG)
    with _prdb.lock:
        kodinhenki.drop_database()  # in case previous thing played with it
        db = kodinhenki.get_database(
        )  # not really used, but needed to populate schema
        w = dt.get()
    device_seen = Mock()
    discover.device_seen.connect(device_seen)
    r = event.start_ipv4_receiver(port=8989, remote_ip='1.2.3.4')
    switch = [None]

    def _event_received(**kwargs):
        print('event.received', kwargs)

    event.received.connect(_event_received)
    _event_subscribed = Mock()
    event.subscribed.connect(_event_subscribed)

    def _device_added(o):
        print('device.added', o)
        #o.services['basicevent'].populate()
        #o.services['basicevent'].GetSerialNo()
        print(o.services['basicevent'].GetBinaryState())
        #print(o.services['basicevent'].GetLogFileURL())
        url = urljoin(o.url, o.services['basicevent'].event_sub_url)
        s = event.Subscription(url, r)
        assert s.next_update_in_seconds() < 0
        s.update()
        assert s.next_update_in_seconds() > 0
        if isinstance(o, device.WemoSwitch):
            switch[0] = o

    device.device_added.connect(_device_added)

    def _device_seen(address, url, **kwargs):
        print('device.seen', address, url)

    discover.device_seen.connect(_device_seen)
    o = discover.start()
    assert discover.device_seen.wait(1)
    o.stop()
    assert device_seen.called
    if caplog is None:
        assert _event_subscribed.called or event.subscribed.wait(timeout=60)
        assert switch[0]
        switch = switch[0]
        print('toggling on')
        with _prdb.lock:
            switch.turn_on()
        time.sleep(1)
        print('toggling off')
        with _prdb.lock:
            switch.turn_off()
        time.sleep(1)
        print('done')
    _prdb.set_lock_check_enabled(_old)
示例#10
0
def test_process():
    kh.drop_database()  # in case previous thing played with it
    db = kh.get_database()
    pm = process.ProcessMonitor({'zsh': 'zsh', 'x': 'dghswaedherh'})
    #assert pm.next_update_in_seconds() < 0 # n/a - always constant
    pm.update()
    assert pm.next_update_in_seconds() > 0
    assert _prdb_kh.Process.get_named('zsh').get('on')
    assert not _prdb_kh.Process.get_named('x').get('on')
示例#11
0
def test_hue():
    _kh.get_database()

    def _request(o, mode='GET', address=None, data=None):
        if mode == 'GET' and address == '/api/username/lights/':
            return json.loads(get_light)
        if mode == 'GET' and address == '/api/username/sensors/':
            return json.loads(get_sensor)

        raise NotImplementedError('%s %s %s' % (mode, address, data))

    def _connect(o):
        o.username = '******'

    with patch('phue.Bridge.request', new=_request),\
            patch('phue.Bridge.connect', new=_connect):
        h = _hue.get_updater('127.0.0.1')
        h.update()
    assert _prdb_kh.HueBulb.get_named('Living').on is False
示例#12
0
def test_hue():
    _kh.get_database()

    def _request(o, mode='GET', address=None, data=None):
        if mode == 'GET' and address == '/api/username/lights/':
            return json.loads(get_light)
        if mode == 'GET' and address == '/api/username/sensors/':
            return json.loads(get_sensor)

        raise NotImplementedError('%s %s %s' % (mode, address, data))

    def _connect(o):
        o.username = '******'

    with patch('phue.Bridge.request', new=_request),\
            patch('phue.Bridge.connect', new=_connect):
        h = _hue.get_updater('127.0.0.1')
        h.update()
    assert _prdb_kh.HueBulb.get_named('Living').on is False
示例#13
0
def test_process():
    kh.drop_database() # in case previous thing played with it
    db = kh.get_database()
    pm = process.ProcessMonitor({'zsh': 'zsh',
                                 'x': 'dghswaedherh'})
    #assert pm.next_update_in_seconds() < 0 # n/a - always constant
    pm.update()
    assert pm.next_update_in_seconds() > 0
    assert _prdb_kh.Process.get_named('zsh').get('on')
    assert not _prdb_kh.Process.get_named('x').get('on')
示例#14
0
def _test_wemo(caplog):
    _old = _prdb.set_lock_check_enabled(True)
    if caplog: caplog.setLevel(logging.DEBUG)
    with _prdb.lock:
        kodinhenki.drop_database() # in case previous thing played with it
        db = kodinhenki.get_database() # not really used, but needed to populate schema
        w = dt.get()
    device_seen = Mock()
    discover.device_seen.connect(device_seen)
    r = event.start_ipv4_receiver(port=8989, remote_ip='1.2.3.4')
    switch = [None]
    def _event_received(**kwargs):
        print('event.received', kwargs)
    event.received.connect(_event_received)
    _event_subscribed = Mock()
    event.subscribed.connect(_event_subscribed)
    def _device_added(o):
        print('device.added', o)
        #o.services['basicevent'].populate()
        #o.services['basicevent'].GetSerialNo()
        print(o.services['basicevent'].GetBinaryState())
        #print(o.services['basicevent'].GetLogFileURL())
        url = urljoin(o.url, o.services['basicevent'].event_sub_url)
        s = event.Subscription(url, r)
        assert s.next_update_in_seconds() < 0
        s.update()
        assert s.next_update_in_seconds() > 0
        if isinstance(o, device.WemoSwitch):
            switch[0] = o
    device.device_added.connect(_device_added)
    def _device_seen(address, url, **kwargs):
        print('device.seen', address, url)
    discover.device_seen.connect(_device_seen)
    o = discover.start()
    assert discover.device_seen.wait(1)
    o.stop()
    assert device_seen.called
    if caplog is None:
        assert _event_subscribed.called or event.subscribed.wait(timeout=60)
        assert switch[0]
        switch = switch[0]
        print('toggling on')
        with _prdb.lock:
            switch.turn_on()
        time.sleep(1)
        print('toggling off')
        with _prdb.lock:
            switch.turn_off()
        time.sleep(1)
        print('done')
    _prdb.set_lock_check_enabled(_old)
示例#15
0
    def __init__(self, name, **kw):
        self.__dict__.update(**kw)
        self.o = _prdb_kh.LightSensor.new_named(name, value=None)
        self.smbus = smbus.SMBus(self.smbus_number)

    def locked_next_update_in_seconds(self):
        return self.update_interval

    def locked_update(self):
        data = self.smbus.read_i2c_block_data(self.i2c_address, 0x11)
        lx = int((data[1] + (256 * data[0])) / 1.2)
        if self.o.value is not None and \
           abs(lx-self.o.value) < INTERESTING_DELTA:
            return
        self.o.value = lx


def start(name, **kw):
    u = LightSensor(name, **kw)
    _updater.add(u)
    return u


if __name__ == '__main__':
    import kodinhenki
    kodinhenki.get_database()
    ls = LightSensor('foo')
    ls.locked_update()
    print(ls.o.value)
示例#16
0
def _object_added(**kwargs):
    _debug('object_added %s', kwargs)


def _object_changed(o, key, old, new, **kwargs):
    _debug('object_change: %s/%s: %s=>%s %s', o.id, key, old, new, kwargs)
    h.some_object_changed()


if __name__ == '__main__':
    p = khserver.create_shared_argparser('start')
    args = khserver.parse_shared(p)

    _prdb_kh.Home.set_create_owner_instance_callback(Home)
    _debug('creating official database instance')
    db = kh.get_database()
    # Autorotate > megabyte sized ones
    if not os.path.exists(LOGDIR):
        os.mkdir(LOGDIR)
    logger = db.new_logger_to_directory(LOGDIR, autorotate=1000000)
    h = _prdb_kh.Home.new_named().get_owner()
    db.object_added.connect(_object_added)
    db.object_changed.connect(_object_changed)

    # Up to this point we do not have threads really running, so start
    # caring about locking only now..
    _prdb_kh.set_lock_check_enabled(True)

    with _prdb_kh.lock:
        khserver.start()
        if socket.gethostname() == 'poro.lan':
示例#17
0
def start(db=None, **kw):
    db = db or kh.get_database()
    si = pysyma.si.HNCPSystemInterface()
    p = si.create_dncp(pysyma.shsp.SHSP, **kw)
    return _shared_start(db, si, p)
示例#18
0
def _object_added(**kwargs):
    _debug('object_added %s', kwargs)


def _object_changed(o, key, old, new, **kwargs):
    _debug('object_change: %s/%s: %s=>%s %s', o.id, key, old, new, kwargs)
    h.some_object_changed()


if __name__ == '__main__':
    p = khserver.create_shared_argparser('start')
    args = khserver.parse_shared(p)

    _prdb_kh.Home.set_create_owner_instance_callback(Home)
    _debug('creating official database instance')
    db = kh.get_database()
    # Autorotate > megabyte sized ones
    if not os.path.exists(LOGDIR):
        os.mkdir(LOGDIR)
    logger = db.new_logger_to_directory(LOGDIR, autorotate=1000000)
    h = _prdb_kh.Home.new_named().get_owner()
    db.object_added.connect(_object_added)
    db.object_changed.connect(_object_changed)

    # Up to this point we do not have threads really running, so start
    # caring about locking only now..
    _prdb_kh.set_lock_check_enabled(True)

    with _prdb_kh.lock:
        khserver.start()
        if socket.gethostname() == 'poro.lan':
示例#19
0
        self.fd = os.open(self.path, os.O_RDONLY | os.O_NONBLOCK)
    def get_value(self):
        #f.seek(0)
        os.lseek(self.fd, 0, os.SEEK_SET)
        s = os.read(self.fd, 1024)
        s = int(s.strip())
        return s
    def loop(self):
        p = select.poll()
        p.register(self.fd, select.POLLPRI)
        while True:
            v = self.get_value()
            with _prdb_kh.lock:
                v = v and True or False
                self.o.on = v
            r = p.poll()

def start(name, **kw):
    ms = MotionSensor(name, **kw)
    t = threading.Thread(target=ms.loop)
    t.daemon = True
    t.start()
    return dict(t=t, ms=ms)

if __name__ == '__main__':
    import kodinhenki
    kodinhenki.get_database()
    ms = MotionSensor('ms')
    print(ms.get_value())