예제 #1
0
파일: cli.py 프로젝트: PanicMan/pyess
def log_against_graphite(args):
    if not args.password:
        print("--password must be given for get_data")
        return
    result = {}
    graphyte.init(args.graphite, port=2003, protocol="udp")
    ip, name = autodetect_ess()
    ess = ESS(name, args.password)
    while True:
        time.sleep(10 if not args.once else 0)
        home = ess.get_state("home")
        common = ess.get_state("common")
        for key in home:
            for key2 in home[key]:
                try:
                    graphyte.send("home." + key + "." + key2,
                                  float(home[key][key2]))
                except:
                    pass
        for key in common:
            for key2 in common[key]:
                try:
                    graphyte.send("common." + key + "." + key2,
                                  float(common[key][key2]))
                except:
                    pass
        logger.info(datetime.datetime.now())
        if args.once:
            break
예제 #2
0
파일: cli.py 프로젝트: PanicMan/pyess
def get_data(args):
    if not args.password:
        print("--password must be given for get_data")
        return
    result = {}
    ip, name = autodetect_ess()
    ess = ESS(name, args.password)
    for i in STATE_URLS.keys():
        result[i] = ess.get_state(i)
    print(json.dumps(result))
예제 #3
0
파일: essmqtt.py 프로젝트: PanicMan/pyess
async def _main(arguments=None):
    parser = argparse.ArgumentParser(
        prog='pyess', description='Command line interface for pyess')
    parser.add_argument(
        '--loglevel',
        default='info',
        help='Log level',
        choices=['debug', 'info', 'warning', 'error', 'critical'],
    )
    # parser.add_argument("--action", default="list_ess", help="what to do", choices=actions.keys())
    parser.add_argument(
        "--ess_password",
        default=None,
        help="password (required for everything but get_password)")
    parser.add_argument("--mqtt_server",
                        default="192.168.1.220",
                        help="mqtt server")
    parser.add_argument("--mqtt_port",
                        default=1883,
                        type=int,
                        help="mqtt port")
    parser.add_argument("--mqtt_password", default=None, help="mqtt password")
    parser.add_argument("--mqtt_user", default=None, help="mqtt user")
    parser.add_argument("--once",
                        default=False,
                        type=bool,
                        help="no loop, only one pass")
    parser.add_argument("--interval_seconds",
                        default=10,
                        type=int,
                        help="update interval (default: 10 seconds)")

    args = parser.parse_args(arguments)
    ip, name = autodetect_ess()
    ess = await ESS.create(name, args.ess_password, ip)

    logging.basicConfig(level=args.loglevel.upper())

    async def switch_winter(state: bool):
        logger.info(f"switching winter mode to {state}")
        if state:
            await ess.winter_off()
        else:
            await ess.winter_on()

    async def switch_fastcharge(state: bool):
        logger.info(f"switching fast charge mode to {state}")
        if state:
            await ess.fastcharge_on()
        else:
            await ess.fastcharge_off()

    async def switch_active(state: bool):
        logger.info("switching ess {}".format("on" if state else "off"))
        if state:
            await ess.switch_on()
        else:
            await ess.switch_off()

    async def handle_control(client, control, path):
        async with client.filtered_messages(path) as messages:
            async for msg in messages:
                logger.info(f"control message received {msg}")
                try:
                    state = strtobool(msg.decode())
                    await control(state)
                except ValueError:
                    logger.warning(
                        f"ignoring incompatible value {msg} for switching")

    async with Client(args.mqtt_server,
                      port=args.mqtt_port,
                      logger=logger,
                      username=args.mqtt_user,
                      password=args.mqtt_password) as client:

        await client.subscribe('/ess/control/#')
        asyncio.create_task(
            handle_control(client, switch_winter, "/ess/control/winter_mode"))
        asyncio.create_task(
            handle_control(client, switch_fastcharge,
                           "/ess/control/fastcharge"))
        asyncio.create_task(
            handle_control(client, switch_active, "/ess/control/active"))

        await send_loop(client,
                        ess,
                        once=args.once,
                        interval_seconds=args.interval_seconds)
예제 #4
0
async def _main(arguments=None):
    parser = configargparse.ArgumentParser(
        prog='essmqtt',
        description='Mqtt connector for pyess',
        add_config_file_help=True,
        default_config_files=['/etc/essmqtt.conf', '~/.essmqtt.conf'],
        args_for_setting_config_path=["--config_file"],
    )

    parser.add_argument(
        '--loglevel',
        default='info',
        help='Log level',
        choices=['debug', 'info', 'warning', 'error', 'critical'],
    )

    parser.add_argument(
        "--ess_password",
        default=None,
        help="password (required for everything but get_password)")
    parser.add_argument("--mqtt_server",
                        default="192.168.1.220",
                        help="mqtt server")
    parser.add_argument("--mqtt_port",
                        default=1883,
                        type=int,
                        help="mqtt port")
    parser.add_argument("--mqtt_password", default=None, help="mqtt password")
    parser.add_argument("--mqtt_user", default=None, help="mqtt user")
    parser.add_argument(
        "--ess_host",
        default=None,
        help="hostname or IP of mqtt host (discover via mdns if not set)")
    parser.add_argument("--once",
                        default=False,
                        type=bool,
                        help="no loop, only one pass")
    parser.add_argument(
        "--common_divisor",
        default=1,
        type=int,
        help=
        "multiply interval_seconds for values below 'common' by this factor")
    parser.add_argument("--interval_seconds",
                        default=10,
                        type=int,
                        help="update interval (default: 10 seconds)")
    parser.add_argument("--hass_autoconfig_sensors",
                        default=None,
                        help="comma-separated list of sensors to advertise"
                        "for homassistant autconfig")

    args = parser.parse_args(arguments)
    if args.ess_host is None:
        ip, name = autodetect_ess()
    else:
        ip, name = args.ess_host, args.ess_host

    logging.basicConfig(level=args.loglevel.upper())

    ess = await ESS.create(name, args.ess_password, ip)

    async def switch_winter(state: bool):
        logger.info(f"switching winter mode to {state}")
        if state:
            await ess.winter_off()
        else:
            await ess.winter_on()

    async def switch_fastcharge(state: bool):
        logger.info(f"switching fast charge mode to {state}")
        if state:
            await ess.fastcharge_on()
        else:
            await ess.fastcharge_off()

    async def switch_active(state: bool):
        logger.info("switching ess {}".format("on" if state else "off"))
        if state:
            await ess.switch_on()
        else:
            await ess.switch_off()

    async def handle_control(client, control, path):
        async with client.filtered_messages(path) as messages:
            async for msg in messages:
                logger.info(f"control message received {msg}")
                try:
                    state = strtobool(msg.payload.decode())
                    await control(state)
                except ValueError:
                    logger.warning(
                        f"ignoring incompatible value {msg} for switching")

    if args.mqtt_server is not None:
        while True:
            try:
                await launch_main_loop(args, ess, handle_control,
                                       switch_active, switch_fastcharge,
                                       switch_winter)
            except (TimeoutError, asyncio_mqtt.error.MqttCodeError,
                    aiohttp.client_exceptions.ClientError, BrokenPipeError,
                    ConnectionError):
                logger.warning(
                    "Expected exception while talking go ESS or MQTT server, restarting in 60 seconds."
                    "Usually this means the server is slow to respond or unreachable."
                )
                await asyncio.sleep(60)
            except:
                raise

            ess = await ESS.create(name, args.ess_password, ip)

            if args.once:
                break

    else:
        pass
예제 #5
0
def test_online_ess(cache=[]):
    if not cache:
        ip, name = autodetect_ess()
        cache.append(ip)
        cache.append(name)
    return cache
예제 #6
0
async def _main(arguments=None):
    parser = configargparse.ArgumentParser(prog='essmqtt', description='Mqtt connector for pyess',
                                           add_config_file_help=True,
                                           default_config_files=['/etc/essmqtt.conf', '~/.essmqtt.conf'],
                                           args_for_setting_config_path=["--config_file"], )

    parser.add_argument(
        '--loglevel', default='info', help='Log level',
        choices=['debug', 'info', 'warning', 'error', 'critical'],
    )

    parser.add_argument("--ess_password", default=None, help="password (required for everything but get_password)")
    parser.add_argument("--mqtt_server", default="192.168.1.220", help="mqtt server")
    parser.add_argument("--mqtt_port", default=1883, type=int, help="mqtt port")
    parser.add_argument("--mqtt_password", default=None, help="mqtt password")
    parser.add_argument("--mqtt_user", default=None, help="mqtt user")
    parser.add_argument("--ess_host", default=None, help="hostname or IP of mqtt host (discover via mdns if not set)")
    parser.add_argument("--once", default=False, type=bool, help="no loop, only one pass")
    parser.add_argument("--common_divisor", default=1, type=int,
                        help="multiply interval_seconds for values below 'common' by this factor")
    parser.add_argument("--interval_seconds", default=10, type=int, help="update interval (default: 10 seconds)")
    parser.add_argument("--hass_autoconfig_sensors", default=None, help="comma-separated list of sensors to advertise"
                                                                        "for homassistant autconfig")

    args = parser.parse_args(arguments)
    if args.ess_host is None:
        ip, name = autodetect_ess()
    else:
        ip, name = args.ess_host, args.ess_host

    logging.basicConfig(level=args.loglevel.upper())

    ess = await ESS.create(name, args.ess_password, ip)

    async def switch_winter(state: bool):
        logger.info(f"switching winter mode to {state}")
        if state:
            await ess.winter_off()
        else:
            await ess.winter_on()

    async def switch_fastcharge(state: bool):
        logger.info(f"switching fast charge mode to {state}")
        if state:
            await ess.fastcharge_on()
        else:
            await ess.fastcharge_off()

    async def switch_active(state: bool):
        logger.info("switching ess {}".format("on" if state else "off"))
        if state:
            await ess.switch_on()
        else:
            await ess.switch_off()

    async def handle_control(client, control, path):
        async with client.filtered_messages(path) as messages:
            async for msg in messages:
                logger.info(f"control message received {msg}")
                try:
                    state = strtobool(msg.decode())
                    await control(state)
                except ValueError:
                    logger.warning(f"ignoring incompatible value {msg} for switching")

    if args.mqtt_server is not None:
        async with Client(args.mqtt_server, port=args.mqtt_port, logger=logger, username=args.mqtt_user,
                          password=args.mqtt_password) as client:
            # seems that a leading slash is frowned upon in mqtt, but we keep this for backwards compatibility
            await client.subscribe('/ess/control/#')
            asyncio.create_task(handle_control(client, switch_winter, "/ess/control/winter_mode"))
            asyncio.create_task(handle_control(client, switch_fastcharge, "/ess/control/fastcharge"))
            asyncio.create_task(handle_control(client, switch_active, "/ess/control/active"))

            # also subscribe without leading slash for better style
            await client.subscribe('ess/control/#')
            asyncio.create_task(handle_control(client, switch_winter, "ess/control/winter_mode"))
            asyncio.create_task(handle_control(client, switch_fastcharge, "ess/control/fastcharge"))
            asyncio.create_task(handle_control(client, switch_active, "ess/control/active"))
            if args.hass_autoconfig_sensors is not None:
                asyncio.ensure_future(
                    announce_loop(client, once=args.once, sensors=args.hass_autoconfig_sensors.split(",")))

            await send_loop(ess, client, once=args.once, interval_seconds=args.interval_seconds,
                            common_divisor=args.common_divisor)

    else:
        pass
예제 #7
0
def test_find_ess():
    mitm_for_ess("THE_ESS_NAME")
    res = autodetect_ess()
    assert res[0] == "127.0.0.1"
    assert res[1] == "THE_ESS_NAME"