]> git.basschouten.com Git - openhab-addons.git/blob
51ed3a1119bebe23f1e9de8b74deb099c7874257
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.fineoffsetweatherstation.internal.domain;
14
15 import java.util.Arrays;
16 import java.util.Map;
17 import java.util.TreeMap;
18 import java.util.stream.Collectors;
19
20 import org.apache.commons.lang3.StringUtils;
21 import org.openhab.binding.fineoffsetweatherstation.internal.Utils;
22
23 /**
24  * Class to collect debug details
25  *
26  * @author Andreas Berger - Initial contribution
27  */
28 public class DebugDetails {
29     final byte[] data;
30
31     private final Map<Integer, DebugSegment> segments = new TreeMap<>();
32
33     public DebugDetails(byte[] data, Command command, Protocol protocol) {
34         this.data = data;
35         addDebugDetails(0, 2, "header");
36         addDebugDetails(2, 1, "command: " + command.name());
37         addDebugDetails(3, command.getSizeBytes(), "size");
38         if (protocol == Protocol.ELV) {
39             addDebugDetails(data.length - 2, 1, "ELV checksum");
40         }
41         addDebugDetails(data.length - 1, 1, "checksum");
42     }
43
44     public void addDebugDetails(int start, int length, String description) {
45         segments.put(start, new DebugSegment(start, length, description));
46     }
47
48     @Override
49     public String toString() {
50         int padding = segments.values().stream().mapToInt(value -> value.length).max().orElse(0) * 2;
51         return "0x" + Utils.toHexString(data, data.length, "") + "\n" + segments.values().stream()
52                 .map(debugSegment -> debugSegment.toDebugString(padding)).collect(Collectors.joining("\n"));
53     }
54
55     private class DebugSegment {
56         final int start;
57         final int length;
58         final String description;
59
60         DebugSegment(int start, int length, String description) {
61             this.start = start;
62             this.length = length;
63             this.description = description;
64         }
65
66         @Override
67         public String toString() {
68             return toDebugString(0);
69         }
70
71         private String toDebugString(int padding) {
72             String result = "0x";
73             String hexString = Utils.toHexString(Arrays.copyOfRange(data, start, start + length), length, "");
74             result += StringUtils.rightPad(hexString, padding, " ");
75             result += ": " + description;
76             return result;
77         }
78     }
79 }