示例#1
0
 def test_get_time_prog(self, hthp: HtHeatpump, index: int):
     time_prog = hthp.get_time_prog(index, with_entries=False)
     assert isinstance(
         time_prog, TimeProgram), "'time_prog' must be of type TimeProgram"
     time_prog = hthp.get_time_prog(index, with_entries=True)
     assert isinstance(
         time_prog, TimeProgram), "'time_prog' must be of type TimeProgram"
示例#2
0
 def test_verify_param_action(self, cmdopt_device: str,
                              cmdopt_baudrate: int, action: set):
     hp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
     val = hp.verify_param_action
     assert isinstance(val, set)
     hp.verify_param_action = action
     assert hp.verify_param_action == action
     hp.verify_param_action = val
示例#3
0
 def test_verify_param_error(self, cmdopt_device: str,
                             cmdopt_baudrate: int):
     hp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
     val = hp.verify_param_error
     assert isinstance(val, bool)
     hp.verify_param_error = True
     assert hp.verify_param_error is True
     hp.verify_param_error = False
     assert hp.verify_param_error is False
     hp.verify_param_error = val
示例#4
0
def hthp(cmdopt_device, cmdopt_baudrate):
    #hthp = HtHeatpump(device="/dev/ttyUSB0", baudrate=115200)
    hthp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
    try:
        hthp.open_connection()
        hthp.login()
        yield hthp  # provide the heat pump instance
    finally:
        hthp.logout()  # try to logout for an ordinary cancellation (if possible)
        hthp.close_connection()
示例#5
0
 def test_get_last_fault(self, hthp: HtHeatpump):
     fault = hthp.get_last_fault()
     # (29, 20, datetime.datetime(...), "EQ_Spreizung")
     assert isinstance(fault, tuple), "'fault' must be of type tuple"
     assert len(fault) == 4
     index, error, dt, msg = fault
     assert isinstance(index, int), "'index' must be of type int"
     assert 0 <= index < hthp.get_fault_list_size()
     assert isinstance(error, int), "'error' must be of type int"
     assert error >= 0
     assert isinstance(dt,
                       datetime.datetime), "'dt' must be of type datetime"
     assert isinstance(msg, str), "'msg' must be of type str"
示例#6
0
 def test_get_time_progs(self, hthp: HtHeatpump):
     time_progs = hthp.get_time_progs()
     assert isinstance(time_progs,
                       List), "'time_progs' must be of type list"
     assert len(time_progs) > 0
     assert all(
         [isinstance(time_prog, TimeProgram) for time_prog in time_progs])
示例#7
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 n, v in values.items():
         assert n in HtParams
         assert v is not None
         assert HtParams[n].in_limits(v)
示例#8
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 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)
示例#9
0
 def test_get_version(self, hthp: HtHeatpump):
     version = hthp.get_version()
     # ( "3.0.20", 2321 )
     assert isinstance(version, tuple), "'version' must be of type tuple"
     assert len(version) == 2
     ver_str, ver_num = version
     assert isinstance(ver_str, str), "'ver_str' must be of type str"
     m = re.match(r"^(\d+).(\d+).(\d+)$", ver_str)
     assert m is not None, "invalid version string [{!r}]".format(ver_str)
     assert isinstance(ver_num, int), "'ver_num' must be of type int"
     assert ver_num > 0
     hthp.send_request(r"SP,NR=9")
     resp = hthp.read_response()
     m = re.match(r"^SP,NR=9,.*NAME=([^,]+).*VAL=([^,]+).*$", resp)
     assert m is not None, "invalid response for query of the software version [{!r}]".format(
         resp)
     assert ver_str == m.group(1).strip()
     assert ver_num == int(m.group(2))
示例#10
0
 def test_get_date_time(self, hthp: HtHeatpump):
     date_time = hthp.get_date_time()
     # (datetime.datetime(...), 2)  # 2 = Tuesday
     assert isinstance(date_time,
                       tuple), "'date_time' must be of type tuple"
     assert len(date_time) == 2
     dt, weekday = date_time
     assert isinstance(dt,
                       datetime.datetime), "'dt' must be of type datetime"
     assert isinstance(weekday, int), "'weekday' must be of type int"
     assert weekday in range(1, 8)
示例#11
0
 def test_get_fault_list_with_indices(self, hthp: HtHeatpump):
     size = hthp.get_fault_list_size()
     for cnt in range(size + 1):
         indices = random.sample(range(size), cnt)
         fault_list = hthp.get_fault_list(*indices)
         assert isinstance(fault_list,
                           list), "'fault_list' must be of type list"
         for entry in fault_list:
             assert isinstance(entry, dict), "'entry' must be of type dict"
             index = entry["index"]
             assert isinstance(index, int), "'index' must be of type int"
             assert 0 <= index < hthp.get_fault_list_size()
             error = entry["error"]
             assert isinstance(error, int), "'error' must be of type int"
             assert error >= 0
             dt = entry["datetime"]
             assert isinstance(
                 dt, datetime.datetime), "'dt' must be of type datetime"
             msg = entry["message"]
             assert isinstance(msg, str), "'msg' must be of type str"
示例#12
0
def hthp(cmdopt_device: str, cmdopt_baudrate: int):
    hthp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
    try:
        hthp.open_connection()
        yield hthp  # provide the heat pump instance
    finally:
        hthp.close_connection()
示例#13
0
 def test_get_fault_list_with_index(self, hthp: HtHeatpump):
     size = hthp.get_fault_list_size()
     assert isinstance(size, int), "'size' must be of type int"
     assert size >= 0
     for i in range(size):
         fault_list = hthp.get_fault_list(i)
         assert isinstance(fault_list,
                           list), "'fault_list' must be of type list"
         assert len(fault_list) == 1
         entry = fault_list[0]
         assert isinstance(entry, dict), "'entry' must be of type dict"
         index = entry["index"]
         assert isinstance(index, int), "'index' must be of type int"
         assert 0 <= index < hthp.get_fault_list_size()
         error = entry["error"]
         assert isinstance(error, int), "'error' must be of type int"
         assert error >= 0
         dt = entry["datetime"]
         assert isinstance(
             dt, datetime.datetime), "'dt' must be of type datetime"
         msg = entry["message"]
         assert isinstance(msg, str), "'msg' must be of type str"
示例#14
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)
示例#15
0
 def test_validate_param(self, hthp: HtHeatpump, name: str, param: HtParam):
     hthp.send_request(param.cmd())
     resp = hthp.read_response()
     m = re.match(
         r"^{},.*NAME=([^,]+).*VAL=([^,]+).*MAX=([^,]+).*MIN=([^,]+).*$".
         format(param.cmd()), resp)
     assert m is not None, "invalid response for query of parameter {!r} [{!r}]".format(
         name, resp)
     dp_name = m.group(1).strip()
     assert dp_name == name,\
         "data point name doesn't match with the parameter name {!r} [{!r}]".format(name, dp_name)
     dp_value = param.from_str(m.group(2))
     assert dp_value is not None, "data point value must not be None [{}]".format(
         dp_value)
     dp_max = param.from_str(m.group(3))
     assert dp_max == param.max_val,\
         "data point max value doesn't match with the parameter's one {!s} [{!s}]".format(param.max_val, dp_max)
     dp_min = param.from_str(m.group(4))
     if name == "Verdichter laeuft seit" and dp_min == 10:
         dp_min = 0  # seems to be incorrect for the data point "Verdichter laeuft seit" [10 == 0]
     assert dp_min == param.min_val,\
         "data point min value doesn't match with the parameter's one {!s} [{!s}]".format(param.min_val, dp_min)
示例#16
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)
示例#17
0
 def test_get_fault_list(self, hthp: HtHeatpump):
     fault_list = hthp.get_fault_list()
     # [ { "index": 29,  # fault list index
     #     "error": 20,  # error code
     #     "datetime": datetime.datetime(...),  # date and time of the entry
     #     "message": "EQ_Spreizung",  # error message
     #     },
     #   # ...
     #   ]
     assert isinstance(fault_list,
                       list), "'fault_list' must be of type list"
     for entry in fault_list:
         assert isinstance(entry, dict), "'entry' must be of type dict"
         index = entry["index"]
         assert isinstance(index, int), "'index' must be of type int"
         assert 0 <= index < hthp.get_fault_list_size()
         error = entry["error"]
         assert isinstance(error, int), "'error' must be of type int"
         assert error >= 0
         dt = entry["datetime"]
         assert isinstance(
             dt, datetime.datetime), "'dt' must be of type datetime"
         msg = entry["message"]
         assert isinstance(msg, str), "'msg' must be of type str"
示例#18
0
 def test_set_param_raises_ValueError(self, cmdopt_device: str,
                                      cmdopt_baudrate: int, name: str,
                                      param: HtParam):
     hp = HtHeatpump(device=cmdopt_device, baudrate=cmdopt_baudrate)
     with pytest.raises(ValueError):
         hp.set_param(name, param.min_val - 1,
                      ignore_limits=False)  # type: ignore
     with pytest.raises(ValueError):
         hp.set_param(name, param.max_val + 1,
                      ignore_limits=False)  # type: ignore
示例#19
0
 def test_get_time_prog_entry(self, hthp: HtHeatpump, index: int, day: int,
                              num: int):
     entry = hthp.get_time_prog_entry(index, day, num)
     assert isinstance(
         entry, TimeProgEntry), "'entry' must be of type TimeProgEntry"
示例#20
0
def reconnect(hthp: HtHeatpump):
    hthp.reconnect()
    hthp.login()
    yield
    hthp.logout()
示例#21
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
            Command line tool to create a backup of the Heliotherm heat pump data points.

            Example:

              $ python3 %(prog)s --baudrate 9600 --csv backup.csv
              'SP,NR=0' [Language]: VAL='0', MIN='0', MAX='4'
              'SP,NR=1' [TBF_BIT]: VAL='0', MIN='0', MAX='1'
              'SP,NR=2' [Rueckruferlaubnis]: VAL='1', MIN='0', MAX='1'
              ...
            '''),
        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",
                        type=str,
                        help="write the result to the specified JSON file")

    parser.add_argument("-c",
                        "--csv",
                        type=str,
                        help="write the result to the specified CSV file")

    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(
        "--without-values",
        action="store_true",
        help=
        "store heat pump data points without their current value (keep it blank)"
    )

    parser.add_argument(
        "--max-retries",
        default=2,
        type=int,
        choices=range(0, 11),
        help=
        "maximum number of retries for a data point request (0..10), default: %(default)s"
    )

    args = parser.parse_args()

    # activate logging with level DEBUG in verbose mode
    if args.verbose:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.WARNING)

    hp = HtHeatpump(args.device, baudrate=args.baudrate)
    start = timer()
    try:
        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]))

        result = {}
        for dp_type in ("SP", "MP"):  # for all known data point types
            result.update({dp_type: {}})
            i = 0  # start at zero for each data point type
            while True:
                success = False
                retry = 0
                while not success and retry <= args.max_retries:
                    data_point = "{},NR={:d}".format(dp_type, i)
                    # send request for data point to the heat pump
                    hp.send_request(data_point)
                    # ... and wait for the response
                    try:
                        resp = hp.read_response()
                        # search for pattern "NAME=...", "VAL=...", "MAX=..." and "MIN=..." inside the answer
                        m = re.match(
                            r"^{},.*NAME=([^,]+).*VAL=([^,]+).*MAX=([^,]+).*MIN=([^,]+).*$"
                            .format(data_point), resp)
                        if not m:
                            raise IOError(
                                "invalid response for query of data point {!r} [{}]"
                                .format(data_point, resp))
                        name, value, max, min = m.group(
                            1, 2, 3, 4)  # extract name, value, max and min
                        if args.without_values:
                            value = ""  # keep it blank (if desired)
                        print("{!r} [{}]: VAL={!r}, MIN={!r}, MAX={!r}".format(
                            data_point, name, value, min, max))
                        # store the determined data in the result dict
                        result[dp_type].update({
                            i: {
                                "name": name,
                                "value": value,
                                "min": min,
                                "max": max
                            }
                        })
                        success = True
                    except Exception as e:
                        retry += 1
                        _logger.warning(
                            "try #{:d}/{:d} for query of data point {!r} failed: {!s}"
                            .format(retry, args.max_retries + 1, data_point,
                                    e))
                        # try a reconnect, maybe this will help
                        hp.reconnect()  # perform a reconnect
                        try:
                            hp.login(0)  # and a new login
                        except Exception:
                            pass  # ignore a potential problem
                if not success:
                    _logger.error(
                        "query of data point {!r} failed after {:d} try/tries".
                        format(data_point, retry))
                    break
                else:
                    i += 1

        if args.json:  # write result to JSON file
            with open(args.json, 'w') as jsonfile:
                json.dump(result, jsonfile, indent=4, sort_keys=True)

        if args.csv:  # write result to CSV file
            with open(args.csv, 'w') as csvfile:
                fieldnames = ["type", "number", "name", "value", "min", "max"]
                writer = csv.DictWriter(csvfile,
                                        delimiter='\t',
                                        fieldnames=fieldnames)
                writer.writeheader()
                for dp_type, content in sorted(result.items(), reverse=True):
                    for i, data in content.items():
                        writer.writerow({
                            "type": dp_type,
                            "number": i,
                            "name": data["name"],
                            "value": data["value"],
                            "min": data["min"],
                            "max": data["max"]
                        })

    except Exception as ex:
        _logger.error(ex)
        sys.exit(1)
    finally:
        hp.logout()  # try to logout for an ordinary cancellation (if possible)
        hp.close_connection()
    end = timer()

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

    sys.exit(0)
示例#22
0
 def run(self):
     _logger.info("=== HtHttpDaemon.run() {}".format("=" * 100))
     global hp
     try:
         hp = HtHeatpump(args.device, baudrate=args.baudrate)
         hp.open_connection()
         hp.login()
         rid = hp.get_serial_number()
         _logger.info(
             "Connected successfully to heat pump with serial number: {:d}".
             format(rid))
         ver = hp.get_version()
         _logger.info("Software version: {} ({:d})".format(ver[0], ver[1]))
         hp.logout()
         server = HTTPServer((args.ip, args.port), HttpGetHandler)
         _logger.info("Starting server at: {}".format(
             server.server_address))
         server.serve_forever()  # start the server and wait for requests
     except Exception as ex:
         _logger.error(ex)
         sys.exit(2)
     finally:
         hp.logout(
         )  # try to logout for an ordinary cancellation (if possible)
         hp.close_connection()
示例#23
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
            Command line tool to query for the fault list of the heat pump.

            Example:

              $ python3 %(prog)s --device /dev/ttyUSB1
              #000 [2000-01-01T00:00:00]: 65534, Keine Stoerung
              #001 [2000-01-01T00:00:00]: 65286, Info: Programmupdate 1
              #002 [2000-01-01T00:00:00]: 65285, Info: Initialisiert
              #003 [2000-01-01T00:00:16]: 00009, HD Schalter
              #004 [2000-01-01T00:00:20]: 00021, EQ Motorschutz
            '''),
        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("-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(
        "-l",
        "--last",
        action="store_true",
        help="print only the last fault message of the heat pump")

    args = parser.parse_args()

    # activate logging with level INFO in verbose mode
    if args.verbose:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.ERROR)

    hp = HtHeatpump(args.device, baudrate=args.baudrate)
    start = timer()
    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]))

        if args.last:
            # query for the last fault message of the heat pump
            idx, err, dt, msg = hp.get_last_fault()
            print("#{:d} [{}]: {:d}, {}".format(idx, dt.isoformat(), err, msg))
        else:
            # query for the whole fault list of the heat pump
            lst = hp.get_fault_list()
            for idx, e in lst.items():
                print("#{:03d} [{}]: {:05d}, {}".format(
                    idx, e["datetime"].isoformat(), e["error"], e["message"]))

    except Exception as ex:
        _logger.error(ex)
        sys.exit(1)
    finally:
        hp.logout()  # try to logout for an ordinary cancellation (if possible)
        hp.close_connection()
    end = timer()

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

    sys.exit(0)
示例#24
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
            Command shell tool to send raw commands to the Heliotherm heat pump.

            For commands which deliver more than one response from the heat pump
            the expected number of responses can be defined by the argument "-r"
            or "--responses".

            Example:

              $ python3 %(prog)s --device /dev/ttyUSB1 "AR,28,29,30" -r 3
              > 'AR,28,29,30'
              < 'AA,28,19,14.09.14-02:08:56,EQ_Spreizung'
              < 'AA,29,20,14.09.14-11:52:08,EQ_Spreizung'
              < 'AA,30,65534,15.09.14-09:17:12,Keine Stoerung'
            '''),
        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(
        "-r",
        "--responses",
        default=1,
        type=int,
        help=
        "number of expected responses for each given command, default: %(default)s"
    )

    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(
        "cmd",
        type=str,
        nargs='+',
        help=
        "command(s) to send to the heat pump (without the preceding '~' and the trailing ';')"
    )

    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]))

        with Timer() as timer:
            for cmd in args.cmd:
                # write the given command to the heat pump
                print("> {!r}".format(cmd))
                hp.send_request(cmd)
                # and read all expected responses for this command
                for _ in range(args.responses):
                    resp = hp.read_response()
                    print("< {!r}".format(resp))
        exec_time = timer.elapsed

        # 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)
示例#25
0
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)
示例#26
0
def main():
    parser = argparse.ArgumentParser(
        description=textwrap.dedent('''\
            Command line tool to set the value of a specific parameter of the heat pump.

            Example:

              $ python3 %(prog)s --device /dev/ttyUSB1 "HKR Soll_Raum" "21.5"
              21.5
            '''),
        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("-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=1,
                        action=ParamNameAction,
                        help="parameter name (as defined in htparams.csv)")

    parser.add_argument("value",
                        type=str,
                        nargs=1,
                        help="parameter value (as string)")

    args = parser.parse_args()

    # activate logging with level INFO in verbose mode
    if args.verbose:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.ERROR)

    hp = HtHeatpump(args.device, baudrate=args.baudrate)
    start = timer()
    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]))

        # convert the passed value (as string) to the specific data type
        value = HtParams[args.name[0]].from_str(args.value[0])
        # set the parameter of the heat pump to the passed value
        value = hp.set_param(args.name[0], value)
        print(value)

    except Exception as ex:
        _logger.error(ex)
        sys.exit(1)
    finally:
        hp.logout()  # try to logout for an ordinary cancellation (if possible)
        hp.close_connection()
    end = timer()

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

    sys.exit(0)
示例#27
0
def main():
    parser = argparse.ArgumentParser(
        description = textwrap.dedent('''\
            Command line tool to get and set date and time on the Heliotherm heat pump.

            To change date and/or time on the heat pump the date and time has to be passed
            in ISO 8601 format (YYYY-MM-DDTHH:MM:SS) to the program. It is also possible to
            pass an empty string, therefore the current date and time of the host will be
            used. If nothing is passed to the program the current date and time on the heat
            pump will be returned.

            Example:

              $ python3 %(prog)s --device /dev/ttyUSB1 --baudrate 9600
              Tuesday, 2017-11-21T21:48:04
              $ python3 %(prog)s -d /dev/ttyUSB1 -b 9600 "2008-09-03T20:56:35"
              Wednesday, 2008-09-03T20:56:35
            '''),
        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(
        "-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(
        "datetime",
        type = str,
        nargs = '?',
        help = "date and time in ISO 8601 format (YYYY-MM-DDTHH:MM:SS), if empty current date and time will be used, "
               "if not specified current date and time on the heat pump will be returned")

    args = parser.parse_args()

    # activate logging with level INFO in verbose mode
    if args.verbose:
        logging.basicConfig(level=logging.INFO)
    else:
        logging.basicConfig(level=logging.ERROR)

    hp = HtHeatpump(args.device, baudrate=args.baudrate)
    start = timer()
    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]))
        if args.datetime is None:
            # get current date and time on the heat pump
            dt, wd = hp.get_date_time()
            print("{}, {}".format(WEEKDAYS[wd - 1], dt.isoformat()))
        else:
            # set current date and time on the heat pump
            if not args.datetime:
                # no date and time given, so use the current date and time on the host
                dt = datetime.datetime.now()
            else:
                # otherwise translate the given string to a valid datetime object
                dt = datetime.datetime.strptime(args.datetime, "%Y-%m-%dT%H:%M:%S")
            dt, wd = hp.set_date_time(dt)
            print("{}, {}".format(WEEKDAYS[wd - 1], dt.isoformat()))
    except Exception as ex:
        _logger.error(ex)
        sys.exit(1)
    finally:
        hp.logout()  # try to logout for an ordinary cancellation (if possible)
        hp.close_connection()
    end = timer()

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

    sys.exit(0)
示例#28
0
 def test_get_time_prog_entry_raises_IOError(self, hthp: HtHeatpump,
                                             index: int, day: int,
                                             num: int):
     with pytest.raises(IOError):
         hthp.get_time_prog_entry(index, day, num)
示例#29
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)
示例#30
0
 def test_get_time_prog_raises_IOError(self, hthp: HtHeatpump, index: int):
     with pytest.raises(IOError):
         hthp.get_time_prog(index, with_entries=False)
     with pytest.raises(IOError):
         hthp.get_time_prog(index, with_entries=True)