1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.chabala.brick.controllab.sensor;
20
21
22
23
24 class SensorValueImpl implements SensorValue {
25 private final int analogValue;
26 private final int statusCode;
27
28 SensorValueImpl(byte high, byte low) {
29 analogValue = extractValue(high, low);
30 statusCode = extractStatus(low);
31 }
32
33
34 @Override
35 public int getAnalogValue() {
36 return analogValue;
37 }
38
39
40
41
42
43 @Override
44 public int getStatusCode() {
45 return statusCode;
46 }
47
48
49 private static final int HIGH_SHIFT = 2;
50 private static final int LOW_SHIFT = Byte.SIZE - HIGH_SHIFT;
51 private static final int STATUS_MASK = (1 << LOW_SHIFT) - 1;
52
53 private int extractValue(byte b1, byte b2) {
54 int high = Byte.toUnsignedInt(b1) << HIGH_SHIFT;
55 int low = Byte.toUnsignedInt(b2) >>> LOW_SHIFT;
56 return high + low;
57 }
58
59 private int extractStatus(byte b2) {
60 return b2 & STATUS_MASK;
61 }
62
63 @Override
64 public String toString() {
65 return "{" +
66 "value=" + String.format("0x%02X", analogValue) +
67 ", status=" + statusCode +
68 '}';
69 }
70 }