コード例 #1
0
 def test_query(self, hthp: HtHeatpump):
     values = hthp.query()
     # { "HKR Soll_Raum": 21.0,
     #   "Stoerung": False,
     #   "Temp. Aussen": 8.8,
     #   # ...
     #   }
     assert isinstance(values, dict), "'values' must be of type dict"
     assert len(values) == len(HtParams)
     for n, v in values.items():
         assert n in HtParams
         assert v is not None
         assert HtParams[n].in_limits(v)
コード例 #2
0
 def test_query_with_names(self, hthp: HtHeatpump, names: List[str]):
     values = hthp.query(*names)
     # { "HKR Soll_Raum": 21.0,
     #   "Stoerung": False,
     #   "Temp. Aussen": 8.8,
     #   # ...
     #   }
     assert isinstance(values, dict), "'values' must be of type dict"
     assert not names or len(values) == len(set(names))
     for n, v in values.items():
         assert n in HtParams
         assert not names or n in names
         assert v is not None
         assert HtParams[n].in_limits(v)
コード例 #3
0
ファイル: htquery.py プロジェクト: Dannyboy001/htheatpump
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
            Command line tool to query for parameters of the Heliotherm heat pump.

            Example:

              $ python3 %(prog)s --device /dev/ttyUSB1 "Temp. Aussen" "Stoerung"
              Stoerung    : False
              Temp. Aussen: 5.0
            '''),
        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("--boolasint",
                        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"
    )

    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}".
                format(rid))
        ver = hp.get_version()
        if args.verbose:
            _logger.info("software version = {} ({:d})".format(ver[0], ver[1]))

        # query for the given parameter(s)
        with Timer() as timer:
            values = hp.query(*args.name)
        exec_time = timer.elapsed
        for name, val in values.items():
            if args.boolasint 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}}: {}".format(name,
                                                  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)
コード例 #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)