Пример #1
0
        """

        logging.debug('event received: {}'.format(event))
        # Lookup remote_id who registered with device
        remote_id = event.get('id', None)
        command = event.get('command', None)
        accessory = self.get_accessory(remote_id)
        accessory.receive_command(command)


def get_bridge(driver):
    with open(os.path.join(os.path.dirname(__file__), 'config.json')) as f:
        config = json.load(f)
    bridge = EasywaveBridge(driver, 'Bridge')
    for cover in config['covers']:
        acc_cover = Cover(driver,
                          cover['name'],
                          channel_id=cover['channel_id'],
                          remote_id=cover['remote_id'],
                          time_up=cover['time_up'],
                          time_down=cover['time_down'])
        bridge.add_accessory(acc_cover)
    return bridge


driver = AccessoryDriver(port=51826,
                         persist_file='~/homekit-easywave/accessory.state')
driver.add_accessory(accessory=get_bridge(driver))
signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()
Пример #2
0

def get_bridge(driver):
    """Call this method to get a Bridge instead of a standalone accessory."""
    bridge = Bridge(driver, 'Bridge')
    temp_sensor = TemperatureSensor(driver, 'Sensor 2')
    temp_sensor2 = TemperatureSensor(driver, 'Sensor 1')
    bridge.add_accessory(temp_sensor)
    bridge.add_accessory(temp_sensor2)

    return bridge


def get_accessory(driver):
    """Call this method to get a standalone Accessory."""
    return NeoPixelLightStrip_Fader(False, 144, True, 18, 800000, 10, 255,
                                    False, driver, 'NeoPixel')


# Start the accessory on port 51826
driver = AccessoryDriver(port=8476)

# Change `get_accessory` to `get_bridge` if you want to run a Bridge.
driver.add_accessory(accessory=get_accessory(driver))

# We want SIGTERM (kill) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGTERM, driver.signal_handler)

# Start it!
driver.start()
Пример #3
0
from os.path import expanduser

from accessories.basic_light import BasicLight
# from accessories.temperature_sensor import TemperatureSensor
from accessories.temp_sensor import TemperatureSensor

MQTTSERVER = "pi-server" # "192.168.1.132"
accessory_state = expanduser('~/Documents/2. Code/2. Python/HAP-MQTT/accessory.state')

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO,
                    format="[%(asctime)s] [%(module)-16s] [%(levelname)-8s] %(message)s",
                    datefmt="%I:%M:%S %p")

# Start the accessory on port 51826
driver = AccessoryDriver(port=51827,
                         persist_file=accessory_state)

mqtt_bridge = HapMqtt(MQTTSERVER, driver, "mqtt_bridge")

# get loaders
service_loader = loader.get_loader()
char_loader = loader.get_loader()

test = Accessory(driver, "Switch", aid=999196)
test.add_service(service_loader.get_service("Switch"))

accessories = list()
accessories.append(BasicLight("outside", MQTTSERVER, driver, "flood_1", aid=1111))
accessories.append(BasicLight("outside", MQTTSERVER, driver, "flood_2", aid=2222))
accessories.append(BasicLight("outside", MQTTSERVER, driver, "flood_3", aid=3333))
accessories.append(BasicLight("outside", MQTTSERVER, driver, "flood_4", aid=4444))
Пример #4
0
    # bulb = LightBulb("Desk LED", pin=16)
    # bridge.add_accessory(bulb)
    return bridge


def get_accessory():
    """Call this method to get a standalone Accessory."""
    acc = TemperatureSensor("MyTempSensor",
                            pincode=b"203-23-999",
                            mac=util.generate_mac())
    return acc


# The AccessoryDriver preserves the state of the accessory
# (by default, in the below file), so that you can restart it without pairing again.
if os.path.exists("accessory.pickle"):
    with open("accessory.pickle", "rb") as f:
        acc = pickle.load(f)
else:
    acc = get_accessory(
    )  # Change to get_bridge() if you want to run a Bridge.

# Start the accessory on port 51826
driver = AccessoryDriver(acc, 51826)
# We want KeyboardInterrupts and SIGTERM (kill) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGINT, driver.signal_handler)
signal.signal(signal.SIGTERM, driver.signal_handler)
# Start it!
driver.start()
Пример #5
0
def main():  # noqa: C901 pylint: disable=too-many-branches, too-many-statements, too-many-locals
    parser = argparse.ArgumentParser(prog='vwsfriend', description='TBD')
    parser.add_argument(
        '--version',
        action='version',
        version=
        f'%(prog)s {__version__} (using WeConnect-python {__weconnect_version__})'
    )
    parser.add_argument('-u',
                        '--username',
                        help='Username of VWsFriend UI',
                        required=False)
    parser.add_argument('-p',
                        '--password',
                        help='Password of VWsFriend UI',
                        required=False)
    parser.add_argument('--host',
                        help='Host of VWsFriend UI',
                        type=str,
                        required=False,
                        default='0.0.0.0')  # nosec
    parser.add_argument('--port',
                        help='Port of VWsFriend UI',
                        type=int,
                        choices=range(1, 65535),
                        metavar="[1-65535]",
                        required=False,
                        default=4000)
    weConnectGroup = parser.add_argument_group('WeConnect')
    weConnectGroup.add_argument('--weconnect-username',
                                dest='weConnectUsername',
                                help='Username of Volkswagen id',
                                required=False)
    weConnectGroup.add_argument('--weconnect-password',
                                dest='weConnectPassword',
                                help='Password of Volkswagen id',
                                required=False)
    defaultNetRc = os.path.join(os.path.expanduser("~"), ".netrc")
    weConnectGroup.add_argument(
        '--netrc',
        help=f'File in netrc syntax providing login (default: {defaultNetRc}).'
        ' Netrc is only used when username and password are not provided  as arguments',
        default=None,
        required=False)
    weConnectGroup.add_argument('-i',
                                '--interval',
                                help='Query interval in seconds',
                                type=NumberRangeArgument(imin=180),
                                required=False,
                                default=300)
    defaultTemp = os.path.join(tempfile.gettempdir(), 'weconnect.token')
    weConnectGroup.add_argument(
        '--tokenfile',
        help=f'file to store token (default: {defaultTemp})',
        default=defaultTemp)
    weConnectGroup.add_argument(
        '--no-token-storage',
        dest='noTokenStorage',
        help='Do not store token on filesystem (this'
        ' will cause a new login for every invokation!)',
        action='store_true')

    parser.add_argument(
        '--config-dir',
        dest='configDir',
        help='directory to store configuration files (default: ./)',
        default='./')
    parser.add_argument(
        '--demo',
        help='folder containing demo scenario, see README for more information'
    )
    parser.add_argument('--privacy',
                        help='Options to control privacy of the cars users',
                        default=[],
                        required=False,
                        action='append',
                        type=Privacy,
                        choices=list(Privacy))
    dbGroup = parser.add_argument_group('Database & visualization')

    dbGroup.add_argument(
        '--with-database',
        dest='withDatabase',
        help='Connect VWsFriend to database for visualization',
        action='store_true')
    dbGroup.add_argument('--database-url',
                         dest='dbUrl',
                         help='Database to connect to',
                         default='sqlite:///vwsfrienddevel.db')

    abrpGroup = parser.add_argument_group('ABRP: A better route planner')
    abrpGroup.add_argument(
        '--with-abrp',
        dest='withABRP',
        help=
        'Connect VWsFriend to ABRP (you need to add userTokens in the UI!)',
        action='store_true')

    homekitGroup = parser.add_argument_group('Homekit')
    homekitGroup.add_argument('--with-homekit',
                              dest='withHomekit',
                              help='Provide Apple Homekit functionality',
                              action='store_true')

    loggingGroup = parser.add_argument_group('Logging')
    loggingGroup.add_argument(
        '-v',
        '--verbose',
        action="append_const",
        help='Logging level (verbosity)',
        const=-1,
    )
    loggingGroup.add_argument(
        '--logging-format',
        dest='loggingFormat',
        help='Logging format configured for python logging '
        '(default: %%(asctime)s:%%(levelname)s:%%(module)s:%%(message)s)',
        default='%(asctime)s:%(levelname)s:%(module)s:%(message)s')
    loggingGroup.add_argument(
        '--logging-date-format',
        dest='loggingDateFormat',
        help='Logging format configured for python logging '
        '(default: %%Y-%%m-%%dT%%H:%%M:%%S%%z)',
        default='%Y-%m-%dT%H:%M:%S%z')
    loggingGroup.add_argument(
        '--hide-repeated-log',
        dest='hideRepeatedLog',
        help='Hide repeated log messages from the same module',
        action='store_true')

    loggingMailGroup = parser.add_argument_group(
        'Logging to Email (Errors only)')
    loggingMailGroup.add_argument('--logging-mail-from',
                                  dest='loggingMailFrom',
                                  help='Mail address to send mails from',
                                  required=False)
    loggingMailGroup.add_argument(
        '--logging-mail-to',
        dest='loggingMailTo',
        help='Mail address to send mails to (can be used multiple times)',
        required=False,
        action='append')
    loggingMailGroup.add_argument('--logging-mail-host',
                                  dest='loggingMailHost',
                                  help='Mail server host',
                                  required=False)
    loggingMailGroup.add_argument('--logging-mail-credentials',
                                  dest='loggingMailCredentials',
                                  help='Mail server credentials',
                                  required=False,
                                  nargs=2)
    loggingMailGroup.add_argument('--logging-mail-subject',
                                  dest='loggingMailSubject',
                                  help='Mail subject',
                                  required=False,
                                  default='VWsFriend Log')
    loggingMailGroup.add_argument('--logging-mail-notls',
                                  dest='loggingMailnotls',
                                  help='Mail do not use TLS',
                                  required=False,
                                  action='store_true')
    loggingMailGroup.add_argument('--logging-mail-testmail',
                                  dest='loggingMailTestmail',
                                  help='Try to send Testmail at startup',
                                  required=False,
                                  action='store_true')

    args = parser.parse_args()

    logLevel = LOG_LEVELS.index(DEFAULT_LOG_LEVEL)
    for adjustment in args.verbose or ():
        logLevel = min(len(LOG_LEVELS) - 1, max(logLevel + adjustment, 0))

    logging.basicConfig(level=LOG_LEVELS[logLevel],
                        format=args.loggingFormat,
                        datefmt=args.loggingDateFormat)
    logging.getLogger("pyhap").setLevel(level=LOG_LEVELS[logLevel])
    if args.hideRepeatedLog:
        for handler in logging.root.handlers:
            handler.addFilter(DuplicateFilter())
    # logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)

    if any(arg is not None for arg in [
            args.loggingMailFrom, args.loggingMailTo, args.loggingMailHost,
            args.loggingMailCredentials
    ]):
        if all(arg is not None for arg in [
                args.loggingMailFrom, args.loggingMailTo, args.loggingMailHost,
                args.loggingMailCredentials
        ]):
            secure = ()
            if args.loggingMailnotls:
                secure = None
            smtpHandler = logging.handlers.SMTPHandler(
                mailhost=args.loggingMailHost,
                fromaddr=args.loggingMailFrom,
                toaddrs=args.loggingMailTo,
                subject=args.loggingMailSubject,
                credentials=args.loggingMailCredentials,
                secure=secure)
            smtpHandler.setLevel(logging.INFO)
            smtpHandler.setFormatter(
                logging.Formatter("%(asctime)s %(levelname)-5s %(message)s"))
            LOG.addHandler(smtpHandler)
            if args.loggingMailTestmail:
                msg = f'vwsfriend {__version__} (using WeConnect-python {__weconnect_version__})'
                smtpHandler.emit(
                    logging.LogRecord('VWsFriend',
                                      logging.INFO,
                                      pathname=None,
                                      lineno=None,
                                      msg=msg,
                                      args=None,
                                      exc_info=None))
            smtpHandler.setLevel(logging.ERROR)
        else:
            LOG.error(
                'You need to provide all --logging-mail options to make mail work'
            )
            sys.exit(1)

    LOG.info('vwsfriend %s (using WeConnect-python %s)', __version__,
             __weconnect_version__)

    username = None
    password = None

    if args.username is not None and args.password is not None:
        username = args.username
        password = args.password
    else:
        if args.netrc is not None:
            netRcFilename = args.netrc
        else:
            netRcFilename = defaultNetRc
        try:
            secrets = netrc.netrc(file=args.netrc)
            username, _, password = secrets.authenticators("VWsFriend")
        except netrc.NetrcParseError as err:
            LOG.error('Authentification using .netrc failed: %s', err)
            sys.exit(1)
        except TypeError:
            LOG.error(
                'VWsFriend entry was not found in %s netrc-file. Create it or provide a username with --username and a password with --password'
                ' with --username', netRcFilename)
            sys.exit(1)
        except FileNotFoundError:
            LOG.error(
                '%s netrc-file was not found. Create it or provide a username with --username and a password with --password',
                netRcFilename)
            sys.exit(1)

    if args.weConnectUsername is not None and args.weConnectPassword is not None:
        weConnectUsername = args.weConnectUsername
        weConnectPassword = args.weConnectPassword
    else:
        if args.netrc is not None:
            netRcFilename = args.netrc
        else:
            netRcFilename = defaultNetRc
        try:
            secrets = netrc.netrc(file=args.netrc)
            weConnectUsername, _, weConnectPassword = secrets.authenticators(
                "volkswagen.de")
        except netrc.NetrcParseError as err:
            LOG.error('Authentification using .netrc failed: %s', err)
            sys.exit(1)
        except TypeError:
            weConnectUsername = username
            weConnectPassword = password
            LOG.warning(
                'volkswagen.de entry was not found in %s netrc-file. Create it or provide a username with --weconnect-username and a password with'
                ' --weconnect-password', netRcFilename)
        except FileNotFoundError:
            weConnectUsername = username
            weConnectPassword = password
            LOG.warning(
                '%s netrc-file was not found. Create it or provide a username with --weconnect-username and a password with --weconnect-password',
                netRcFilename)

    tokenfile = None
    if not args.noTokenStorage:
        tokenfile = args.tokenfile

    weConnect = None
    try:
        weConnect = weconnect.WeConnect(username=weConnectUsername,
                                        password=weConnectPassword,
                                        tokenfile=tokenfile,
                                        updateAfterLogin=False,
                                        loginOnInit=(args.demo is None),
                                        maxAgePictures=86400)

        connector = AgentConnector(weConnect=weConnect,
                                   dbUrl=args.dbUrl,
                                   interval=args.interval,
                                   withDB=args.withDatabase,
                                   withABRP=args.withABRP,
                                   configDir=args.configDir,
                                   privacy=args.privacy)

        driver = None
        if args.withHomekit:
            LOG.info('Starting up Homekit')
            # Start the accessory on port 51826
            driver = AccessoryDriver(
                pincode=None, persist_file=f'{args.configDir}/accessory.state')

            for characteristicKey, characteristic in CUSTOM_CHARACTERISTICS.items(
            ):
                driver.loader.char_types[characteristicKey] = characteristic

            bridge = VWsFriendBridge(
                driver=driver,
                weConnect=weConnect,
                accessoryConfigFile=f'{args.configDir}/accessory.config')
            driver.add_accessory(bridge)
            weConnectBridgeInitialized = False

            # Start it!
            hapThread = threading.Thread(target=driver.start)
            hapThread.start()

            # Enable status tracking:
            weConnect.enableTracker()

        ui = VWsFriendUI(weConnect=weConnect,
                         connector=connector,
                         homekitDriver=driver,
                         dbUrl=args.dbUrl,
                         configDir=args.configDir,
                         username=username,
                         password=password)
        ui.run(host=args.host, port=args.port)

        if args.demo is not None:
            utcDemoStart = datetime.utcnow().replace(tzinfo=timezone.utc,
                                                     microsecond=0)
            for file in sorted(os.listdir(args.demo)):
                fileNameRegex = r'(?P<number>\d+)_(?P<delay>\d+)s(_(?P<stage>[^\.]+))?.cache.json'
                match = re.search(fileNameRegex, file)
                if match is not None:
                    time.sleep(int(match.groupdict()['delay']))
                    stageFilePath = f'{args.demo}/{file}'
                    with open(stageFilePath, mode='r', encoding='utf8') as fp:
                        cacheString = fp.read()
                        cacheString = re.sub(
                            r'demodate\((?P<offset>[+-]?\d+)\)',
                            lambda m: str(utcDemoStart + timedelta(seconds=int(
                                m.groupdict()['offset']))).replace(
                                    '+00:00', 'Z'), cacheString)
                        cacheString = re.sub(
                            r'now\((?P<offset>[+-]?\d+)\)',
                            lambda m: str(datetime.now() + timedelta(
                                seconds=int(m.groupdict()['offset']))),
                            cacheString)
                        weConnect.fillCacheFromJsonString(cacheString,
                                                          maxAge=2147483647)
                        if args.withHomekit and not weConnectBridgeInitialized:
                            weConnectBridgeInitialized = True
                            bridge.update()
                        weConnect.update(updateCapabilities=True,
                                         updatePictures=False)
                        connector.commit()
                        if match.groupdict()['stage'] is not None:
                            LOG.info('Stage %s completed',
                                     match.groupdict()['stage'])
                        else:
                            LOG.info('Stage completed')
            LOG.info('Demo completed')
        else:
            starttime = time.time()
            permanentErrors = 0
            while True:
                try:
                    LOG.info('Updating data from WeConnect')
                    weConnect.update(updateCapabilities=True,
                                     updatePictures=True,
                                     force=True)
                    connector.commit()
                    if args.withHomekit and not weConnectBridgeInitialized:
                        weConnectBridgeInitialized = True
                        bridge.update()
                    sleeptime = args.interval - (
                        (time.time() - starttime) % args.interval)
                    permanentErrors = 0
                except weconnect.RetrievalError:
                    LOG.error(
                        'Retrieval error during update. Will try again after configured interval of %ds',
                        args.interval)
                except APICompatibilityError as e:
                    sleeptime = min((args.interval * pow(2, permanentErrors)),
                                    86400)
                    LOG.critical(
                        'There was a problem when communicating with WeConnect. If this problem persists please open a bug report: %s,'
                        ' will retry after %ds', e, sleeptime)
                    permanentErrors += 1
                #  Execute exactly every interval but if it misses its deadline only after the next interval
                time.sleep(sleeptime)

    except AuthentificationError as e:
        LOG.critical(
            'There was a problem when authenticating with WeConnect: %s', e)
    except APICompatibilityError as e:
        LOG.critical(
            'There was a problem when communicating with WeConnect.'
            ' If this problem persists please open a bug report: %s', e)
    finally:
        if weConnect is not None:
            weConnect.disconnect()
def test_external_zeroconf():
    zeroconf = MagicMock()
    with patch("pyhap.accessory_driver.HAPServer"), patch(
            "pyhap.accessory_driver.AccessoryDriver.persist"):
        driver = AccessoryDriver(port=51234, zeroconf_instance=zeroconf)
    assert driver.advertiser == zeroconf
            port = int(arg)
        if opt in ['-u', '--updates']:
            dev_updates = True

    logging.info("Bridge name: %s", bridge_name)

    loop = asyncio.get_event_loop()

    try:
        xknx = loop.run_until_complete(get_xknx(config_file, dev_updates))
    except Exception as e:
        logging.info('Exception for KNX: %s', e)
        logging.info('Exiting...')
        sys.exit(1)

    driver = AccessoryDriver(loop=loop,
                             port=port,
                             persist_file='homekit-knx-bridge.state')

    driver.add_accessory(
        accessory=get_bridge_from_config(driver, bridge_name, xknx))

    signal.signal(signal.SIGTERM, driver.signal_handler)

    driver.start()
    #driver.async_add_job(xknx.start())

    #driver.add_job(xknx.stop())
    #loop.run_until_complete(xknx.stop())
# driver.stop()
Пример #8
0
def test_auto_add_aid_mac(_persist_mock):
    acc = Accessory("Test Accessory")
    _driver = AccessoryDriver(acc, 51234, "192.168.1.1", "test.accessory")
    assert acc.aid == STANDALONE_AID
    assert acc.mac is not None
Пример #9
0
from accessories.netgear.netgear_HAP import add_WNDR_to_bridge
from accessories.sounder.sounds import add_SND_to_bridge
from lib.tls import get_logger

__maintainer__ = "Henk Jan van Aalderen"
__email__ = "*****@*****.**"
__status__ = "Development"

# setup logging for console and error log and generic log
logger = get_logger(__file__,
                    levelConsole=logging.INFO,
                    levelLogfile=logging.INFO)
logger.info('with HAP-python %s' % pyHAP_version)

loop = asyncio.get_event_loop()  # unique loop for application
driver = AccessoryDriver(port=51826, loop=loop)  # prevent renewing loop
bridge = fsBridge(driver, 'fsBridge')

add_SND_to_bridge(bridge, config=None)
if os.path.isfile("config/aios.json"):
    add_AIOS_to_bridge(bridge, config="./config/aios.json")
if os.path.isfile("config/deCONZ.json"):
    add_HUE_to_bridge(bridge, config="./config/deCONZ.json")
if os.path.isfile("config/hue.json"):
    add_HUE_to_bridge(bridge, config="./config/hue.json")
if os.path.isfile("config/fs20.json"):
    add_fs20_to_bridge(bridge, config="./config/fs20.json")
if os.path.isfile("config/p1DSMR.json"):
    add_p1DSMR_to_bridge(bridge, config="./config/p1DSMR.json")
if os.path.isfile("config/WNDR.json"):
    add_WNDR_to_bridge(bridge, config="./config/WNDR.json")
Пример #10
0
from pyhap.const import (CATEGORY_SWITCH)
logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")


class SW(Accessory):
    category = CATEGORY_SWITCH

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        serv_tv = self.add_preload_service('Switch')
        self.char_on = serv_tv.configure_char('On', setter_callback=self.sw)

    def sw(self, value):
        logging.info("スウィッチ: %s", value)
        sp2 = broadlink.sp2((net1["ip"], net1["port"]),
                            netaddr.EUI(net1["mac"]), net1["timeout"])
        sp2.auth()
        sp2.set_power(value)


def get_bridge(driver):
    bridge = Bridge(driver, 'Bridge')
    bridge.add_accessory(SW(driver, 'コーヒーメーカ'))
    return bridge


driver = AccessoryDriver(port=51826, persist_file='simple.state')
driver.add_accessory(accessory=get_bridge(driver))
signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()
Пример #11
0
 def start(self):
     drv = AccessoryDriver(port=self.port)
     self.accessory = PowerSwitch(self.mtda, drv, self.name)
     drv.add_accessory(self.accessory)
     drv.start_service()
Пример #12
0
        self.brightness = 100
        self.on = 1

    def set_bulb(self, value):
        logging.info("Bulb on value: %s", value)
        self.on = value
        self.notify()

    def set_brightness(self, value):
        logging.info("Bulb brightness value: %s", value)
        self.brightness = value
        self.notify()

    def notify(self):
        out = ",".join(map(str, [-1, -1, -1, self.on, self.brightness]))
        socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(
            out.encode("utf-8"), (TARGET_IP, TARGET_PORT)
        )


def get_bridge(driver):
    bridge = Bridge(driver, "Bridge")
    bridge.add_accessory(Light(driver, "Cube"))
    return bridge


driver = AccessoryDriver(port=51826, persist_file="~/cube.state")
driver.add_accessory(accessory=get_bridge(driver))
signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()
Пример #13
0
import signal
import argparse

from pyhap.accessory_driver import AccessoryDriver
from pyhap_vesync.utils.wrapper import Bridge

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='Vesync HomeKit Bridge. '
        'Allows you to setup a Etekcity Vesync account '
        'as a HomeKit Bridge for iOS devices.')
    parser.add_argument('-u',
                        '--username',
                        type=str,
                        required=True,
                        help='Vesync Username (usually an email address).')
    parser.add_argument('-p',
                        '--password',
                        type=str,
                        required=True,
                        help='Vesync Password')

    args = parser.parse_args()

    bridge = Bridge(args.username, args.password, 'Vesync Bridge')
    driver = AccessoryDriver(bridge, 51827)
    signal.signal(signal.SIGINT, driver.signal_handler)
    signal.signal(signal.SIGTERM, driver.signal_handler)
    driver.start()
Пример #14
0
1. Create AccessoryDriver Object.
2. Create the ThermoBeacon object and add it to an AccessoryDriver
"""
import logging
import os, signal

from pyhap.accessory_driver import AccessoryDriver
from ThermoBeacon import ThermoBeaconBridge

logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")

service_dir = '~/.hap-python/'

# Start the accessory on port 51826
driver = AccessoryDriver(port=51826,
                         persist_file = service_dir + '.accessory.state',
                         pincode=b'123-12-123')

bridge = ThermoBeaconBridge(driver,
                            config_file = os.path.expanduser(service_dir + 'beacons.json'))

#Run a Bridge
driver.add_accessory(accessory=bridge)

# We want SIGTERM (terminate) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGTERM, driver.signal_handler)

# Start it!
driver.start()
Пример #15
0
    async with server:
        await server.serve_forever()


# asyncio.run(run_server())

#
# def get_bridge(driver):
#     bridge = GardenBridge.GardenBridge(driver)
#
#     return bridge
#
#
glob.loader = Loader(path_char=HAP_PYTHON_CHARACTERISTICS_FILE,
                     path_service=HAP_PYTHON_SERVICES_FILE)

glob.driver = AccessoryDriver(port=51826,
                              persist_file=HAP_PYTHON_ACCESSORIES_FILE,
                              loader=glob.loader)

hub = load_hub_config(hub)

accessories = load_homekit_accessory_config(accessories)
setup_accessories(hub, accessories)

resource.setrlimit(resource.RLIMIT_NOFILE, (65536, 65536))

signal.signal(signal.SIGTERM, glob.driver.signal_handler)

glob.driver.start()
Пример #16
0
        if rfm69_enabled:
            radio_thread = Thread(target = radio_loop, name = "radio_thread")
            radio_thread.start()

        if awsiot_enabled:
            awsiot_thread = Thread(target = awsiot_loop, name = "awsiot_thread")
            awsiot_thread.start()

        if mqtt_enabled:
            mqtt_thread = Thread(target = mqtt_loop, name = "mqtt_thread")
            mqtt_thread.start()

        if homekit_enabled:
            # Start the accessory on port 51826
            driver = AccessoryDriver(port=51826, pincode=homekit_pin.encode('utf-8'))

            # We want SIGTERM (kill) to be handled by the driver itself,
            # so that it can gracefully stop the accessory, server and advertising.
            # signal.signal(signal.SIGTERM, driver.signal_handler)

            homekit_thread = Thread(target = _homekit_loop, args = (driver,), name = "homekit_thread")
            homekit_thread.start()

        sensor_thread = Thread(target = _sensor_loop, name = "sensor_thread")
        sensor_thread.start()

        loop.run_forever()

    except Exception:
        logger.exception("Exception occurred during loop")
Пример #17
0
def driver():
    with patch('pyhap.accessory_driver.HAPServer'), \
        patch('pyhap.accessory_driver.Zeroconf'), \
            patch('pyhap.accessory_driver.AccessoryDriver.persist'):
        yield AccessoryDriver()
Пример #18
0
def test_not_standalone_aid(_persist_mock):
    acc = Accessory("Test Accessory", aid=STANDALONE_AID + 1)
    with pytest.raises(ValueError):
        _driver = AccessoryDriver(acc, 51234, "192.168.1.1", "test.accessory")
Пример #19
0
        bulb = Bulb(devices[device]['address'].encode(),
                    password=password,
                    verbose=config['verbose']).connect()
        name = devices[device].get('name') or device
        bridge.add_accessory(OortColorBulb(driver, name, bulb))
        if devices[device]['color_switch'] == 'yes':
            bridge.add_accessory(
                OortColorBulbSwitch(driver, '{} color switch'.format(device),
                                    bulb))
    return bridge


config = load_config()
print(config)

# Start the accessory on port 51826
driver = AccessoryDriver(port=config['port'],
                         persist_file='/etc/oort/accessory.state')

# Change `get_accessory` to `get_bridge` if you want to run a Bridge.
driver.add_accessory(accessory=get_bridge(driver))

logging.info("Pairing PIN: %s", driver.state.pincode.decode())

# We want SIGTERM (terminate) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGTERM, driver.signal_handler)

# Start it!
driver.start()
Пример #20
0
client.connect("10.0.0.50", 1883, 60)
client.loop_start()
sleep(2)
log("MQTT Started", 2)
const.init = True
sleep(2)

for plant in const.plantArray:
    log("Send /StartUpHAP for " + plant, 2)
    client.publish(plant + "/StartUpHAP", "Start")
    sleep(2)

log("Waiting For Delayed Responses", 2)
sleep(10)

driver = AccessoryDriver(port=51826, persist_file='busy_home.state')
bridge = Bridge(driver, 'Bridge')
plantAccessories = []
for i in range(len(const.plantArray)):
    # send Array value as initial display_name, gets replaced by const.plantAccValues["name"] in class
    # this workaround is so that the class knows its array position in const.plantAccValues.
    # Passing it to class otherwise caused several errors
    const.currentPlant = i
    plantAccessories.append(Plant(driver, const.plantArray[i] + ' Irrigation'))
    plantAccessories[i].plantNum = i

for i in range(len(const.plantArray)):
    plantAccessories[i].char_active.set_value(1)
    bridge.add_accessory(plantAccessories[i])

# Error Switch
Пример #21
0
def main(getter, setter, port):
    driver = AccessoryDriver(port=port)
    driver.add_accessory(accessory=AirConditioner(getter, setter, driver,
                                                  'ElectraAirConditioner'))
    signal.signal(signal.SIGTERM, driver.signal_handler)
    return driver
Пример #22
0
def driver():
    """Patch AccessoryDriver without zeroconf or HAPServer."""
    with patch("pyhap.accessory_driver.HAPServer"), patch(
            "pyhap.accessory_driver.Zeroconf"), patch(
                "pyhap.accessory_driver.AccessoryDriver.persist"):
        yield AccessoryDriver()
Пример #23
0
import signal
import logging
import busio

from pyhap.accessory_driver import AccessoryDriver
from pyhap.const import CATEGORY_SWITCH
from adafruit_pca9685 import PCA9685
from board import SCL, SDA
from python_json_config import ConfigBuilder

from dusty.dusty import DustyBridge, DustySwitch

logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")
logger = logging.getLogger()

builder = ConfigBuilder()
config = builder.parse_config('config.json')

i2c = busio.I2C(SCL, SDA)
pca = PCA9685(i2c)
pca = PCA9685(i2c, reference_clock_speed=config.servo.reference_clock_speed)
pca.frequency = config.servo.frequency

driver = AccessoryDriver(port=config.dusty.port)
dusty_bridge = DustyBridge(driver, config.dusty.max_switches, pca, config)
driver.add_accessory(accessory=dusty_bridge)
signal.signal(signal.SIGTERM, driver.signal_handler)

driver.start()
Пример #24
0
    """Call this method to get a Bridge instead of a standalone accessory."""
    bridge = Bridge(display_name="Bridge")
    temp_sensor = TemperatureSensor("Termometer")
    temp_sensor2 = TemperatureSensor("Termometer2")
    bridge.add_accessory(temp_sensor)
    bridge.add_accessory(temp_sensor2)

    # Uncomment if you have RPi module and want a LED LightBulb service on pin 16.
    # from pyhap.accessories.LightBulb import LightBulb
    # bulb = LightBulb("Desk LED", pin=16)
    # bridge.add_accessory(bulb)
    return bridge


def get_accessory():
    """Call this method to get a standalone Accessory."""
    acc = TemperatureSensor("MyTempSensor")
    return acc


acc = get_accessory()  # Change to get_bridge() if you want to run a Bridge.

# Start the accessory on port 51826
driver = AccessoryDriver(acc, port=51826)
# We want KeyboardInterrupts and SIGTERM (kill) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGINT, driver.signal_handler)
signal.signal(signal.SIGTERM, driver.signal_handler)
# Start it!
driver.start()
Пример #25
0
        global hum
        result = instance.read()
        if result.is_valid():
            self.char_temp.set_value(result.temperature)
            hum=result.humidity

class HumiditySensor(Accessory):
    category = CATEGORY_SENSOR

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        serv_temp = self.add_preload_service('HumiditySensor')
        self.char_temp = serv_temp.configure_char('CurrentRelativeHumidity')

    @Accessory.run_at_interval(3)
    async def run(self):
        global hum
        self.char_temp.set_value(hum)


def get_bridge(driver):
    bridge = Bridge(driver, 'Bridge')
    bridge.add_accessory(TemperatureSensor(driver, '温度'))
    bridge.add_accessory(HumiditySensor(driver, '湿度'))
    return bridge
driver = AccessoryDriver(port=51826, persist_file='test.state')
driver.add_accessory(accessory=get_bridge(driver))
signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()
Пример #26
0
            [1280, 720, 25],
            [640, 360, 25],
            [480, 270, 25],
            [480, 270, 25],
            [320, 180, 25],
            [1280, 960, 25], # 4:3
            [1024, 768, 25],
            [640, 480, 25],
            [480, 360, 25],
            [320, 240, 25],
        ],
    },
    "audio": { #audio is left blank, because I don't have a mic hooked up.
        "codecs": [ ],
    },
    "srtp": True,
    "address": "172.24.0.30",
    "start_stream_cmd": STREAM_CMD,
}

# Start the accessory on port 51826
driver = AccessoryDriver(port=51826)
acc = PiCamera(options, driver, "Camera")
driver.add_accessory(accessory=acc)

# We want KeyboardInterrupts and SIGTERM (terminate) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGTERM, driver.signal_handler)
# Start it!
driver.start()
Пример #27
0
            RGB_Pri = [C, X, 0]
        elif 1 <= hPri <= 2:
            RGB_Pri = [X, C, 0]
        elif 2 <= hPri <= 3:
            RGB_Pri = [0, C, X]
        elif 3 <= hPri <= 4:
            RGB_Pri = [0, X, C]
        elif 4 <= hPri <= 5:
            RGB_Pri = [X, 0, C]
        elif 5 <= hPri <= 6:
            RGB_Pri = [C, 0, X]
        else:
            RGB_Pri = [0, 0, 0]

        m = v - C

        return int((RGB_Pri[0] + m) * 255), int((RGB_Pri[1] + m) * 255), int(
            (RGB_Pri[2] + m) * 255), int(w)


def get_accessory(driver):
    """Call this method to get a standalone Accessory."""
    return NeoPixelLightStrip(2, True, 18, 800000, 10, 255, False, driver,
                              'NeoPixel')


driver = AccessoryDriver(port=51826, persist_file='one_accessory.state')
driver.add_accessory(get_accessory(driver))

signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()