Esempio n. 1
0
 def test_fast_query(self, hthp: HtHeatpump):
     values = hthp.fast_query()
     assert isinstance(values, dict), "'values' must be of type dict"
     assert len(values) == len(HtParams.of_type("MP"))
     for name, value in values.items():
         assert name in HtParams
         assert value is not None
         assert HtParams[name].in_limits(value)
Esempio n. 2
0
 def test_fast_query_with_names(self, hthp: HtHeatpump, names: List[str]):
     values = hthp.fast_query(*names)
     assert isinstance(values, dict), "'values' must be of type dict"
     assert not names or len(values) == len(set(names))
     for name, value in values.items():
         assert name in HtParams
         assert not names or name in names
         assert value is not None
         assert HtParams[name].in_limits(value)
Esempio n. 3
0
 def test_fast_query_in_several_pieces(self, hthp: HtHeatpump):
     args = []
     cmd = ""
     mp_data_points = [(name, param) for name, param in HtParams.items()
                       if param.dp_type == "MP"]
     while len(cmd) < 255 * 2:  # request has do be done in 3 parts
         name, param = random.choice(mp_data_points)
         cmd += ",{}".format(param.dp_number)
         args.append(name)
     values = hthp.fast_query(*args)
     assert isinstance(values, dict), "'values' must be of type dict"
     assert not args or len(values) == len(set(args))
     for name, value in values.items():
         assert name in HtParams
         assert not args or name in args
         assert value is not None
         assert HtParams[name].in_limits(value)
Esempio n. 4
0
def main():
    logging.basicConfig(
        level=logging.INFO,
        format="%(asctime)s %(levelname)s [%(name)s|%(funcName)s]: %(message)s",
    )

    hp = HtHeatpump("/dev/ttyUSB0", baudrate=115200)
    hp.open_connection()
    hp.login()

    rid = hp.get_serial_number()
    print("connected successfully to heat pump with serial number {:d}".format(
        rid))
    ver = hp.get_version()
    print("software version = {} ({:d})".format(ver[0], ver[1]))

    names = HtParams.of_type("MP").keys()

    t_query = t_fast_query = 0.0
    for i in range(10):
        start = timer()
        values = hp.query(*names)
        t_query += timer() - start
        start = timer()
        values = hp.fast_query(*names)
        t_fast_query += timer() - start
    i += 1
    t_query = t_query / i
    t_fast_query = t_fast_query / i

    print("\n" + "-" * 100)
    print("HtHeatpump.query({:d})      execution time: {:.3f} sec".format(
        len(names), t_query))
    print("HtHeatpump.fast_query({:d}) execution time: {:.3f} sec".format(
        len(names), t_fast_query))
    print("-> {:.3f} x faster".format(t_query / t_fast_query))

    while True:
        print("\n" + "-" * 100)
        rand_names = random.sample(names, random.randint(0, len(names)))
        print("{!s}".format(rand_names))
        # fast query for the given parameter(s)
        values = hp.fast_query(*rand_names)
        # print the current value(s) of the retrieved parameter(s)
        print(", ".join(
            map(lambda name: "{!r} = {}".format(name, values[name]), values)))
        # for name in sorted(values.keys()):
        #    print("{:{width}} [{},{:02d}]: {}".format(name,
        #                                              HtParams[name].dp_type,
        #                                              HtParams[name].dp_number,
        #                                              values[name],
        #                                              width=len(max(values.keys(), key=len))))
        for i in range(5, 0, -1):
            # print(i)
            sys.stdout.write("\rContinue in {:d}s ...".format(i))
            sys.stdout.flush()
            time.sleep(1)
        print("\rContinue in 0s ...")

    hp.logout()  # try to logout for an ordinary cancellation (if possible)
    hp.close_connection()

    sys.exit(0)
Esempio n. 5
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent("""\
            Command line tool to query for parameters of the Heliotherm heat pump the fast way.
            Note: Only parameters representing a "MP" data point are supported!

            Example:

              $ python3 htfastquery.py --device /dev/ttyUSB1 "Temp. Vorlauf" "Temp. Ruecklauf"
              Temp. Ruecklauf [MP,04]: 25.2
              Temp. Vorlauf   [MP,03]: 25.3
            """),
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=textwrap.dedent("""\
            DISCLAIMER
            ----------

              Please note that any incorrect or careless usage of this program as well as
              errors in the implementation can damage your heat pump!

              Therefore, the author does not provide any guarantee or warranty concerning
              to correctness, functionality or performance and does not accept any liability
              for damage caused by this program or mentioned information.

              Thus, use it on your own risk!
            """) + "\r\n",
    )

    parser.add_argument(
        "-d",
        "--device",
        default="/dev/ttyUSB0",
        type=str,
        help=
        "the serial device on which the heat pump is connected, default: %(default)s",
    )

    parser.add_argument(
        "-b",
        "--baudrate",
        default=115200,
        type=int,
        # the supported baudrates of the Heliotherm heat pump (HP08S10W-WEB):
        choices=[9600, 19200, 38400, 57600, 115200],
        help=
        "baudrate of the serial connection (same as configured on the heat pump), default: %(default)s",
    )

    parser.add_argument("-j",
                        "--json",
                        action="store_true",
                        help="output will be in JSON format")

    parser.add_argument(
        "--bool-as-int",
        action="store_true",
        help="boolean values will be stored as '0' and '1'",
    )

    parser.add_argument("-t",
                        "--time",
                        action="store_true",
                        help="measure the execution time")

    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="increase output verbosity by activating logging",
    )

    parser.add_argument(
        "name",
        type=str,
        nargs="*",
        help=
        "parameter name(s) to query for (as defined in htparams.csv) or omit to query for "
        "all known parameters representing a MP data point",
    )

    args = parser.parse_args()

    # activate logging with level DEBUG in verbose mode
    log_format = "%(asctime)s %(levelname)s [%(name)s|%(funcName)s]: %(message)s"
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG, format=log_format)
    else:
        logging.basicConfig(level=logging.WARNING, format=log_format)

    hp = HtHeatpump(args.device, baudrate=args.baudrate)
    try:
        hp.open_connection()
        hp.login()

        rid = hp.get_serial_number()
        if args.verbose:
            _LOGGER.info(
                "connected successfully to heat pump with serial number %d",
                rid)
        ver = hp.get_version()
        if args.verbose:
            _LOGGER.info("software version = %s (%d)", *ver)

        # fast query for the given parameter(s)
        with Timer() as timer:
            values = hp.fast_query(*args.name)
        exec_time = timer.elapsed
        for name, val in values.items():
            if args.bool_as_int and HtParams[
                    name].data_type == HtDataTypes.BOOL:
                values[name] = 1 if val else 0

        # print the current value(s) of the retrieved parameter(s)
        if args.json:
            print(json.dumps(values, indent=4, sort_keys=True))
        else:
            if len(values) > 1:
                for name in sorted(values.keys()):
                    print("{:{width}} [{},{:02d}]: {}".format(
                        name,
                        HtParams[name].dp_type,
                        HtParams[name].dp_number,
                        values[name],
                        width=len(max(values.keys(), key=len)),
                    ))
            elif len(values) == 1:
                print(next(iter(values.values())))

        # print execution time only if desired
        if args.time:
            print("execution time: {:.2f} sec".format(exec_time))

    except Exception as ex:
        _LOGGER.exception(ex)
        sys.exit(1)
    finally:
        hp.logout()  # try to logout for an ordinary cancellation (if possible)
        hp.close_connection()

    sys.exit(0)
Esempio n. 6
0
 def test_fast_query_with_names_raises_ValueError(self, cmdopt_device: str,
                                                  cmdopt_baudrate: int,
                                                  names: List[str]):
     hp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
     with pytest.raises(ValueError):
         hp.fast_query(*names)
Esempio n. 7
0
 def test_fast_query_with_names_raises_KeyError(self, cmdopt_device: str,
                                                cmdopt_baudrate: int):
     hp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
     with pytest.raises(KeyError):
         hp.fast_query("BlaBlaBla")