View Javadoc
1   /*
2    * Copyright © 2016 Greg Chabala
3    *
4    * This file is part of brick-control-lab.
5    *
6    * brick-control-lab is free software: you can redistribute it and/or modify
7    * it under the terms of the GNU Lesser General Public License as
8    * published by the Free Software Foundation, either version 3 of the
9    * License, or (at your option) any later version.
10   *
11   * brick-control-lab is distributed in the hope that it will be useful,
12   * but WITHOUT ANY WARRANTY; without even the implied warranty of
13   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   * GNU Lesser General Public License for more details.
15   *
16   * You should have received a copy of the GNU Lesser General Public License
17   * along with brick-control-lab.  If not, see http://www.gnu.org/licenses/.
18   */
19  package org.chabala.brick.controllab.sensor;
20  
21  /**
22   * {@inheritDoc}.
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      /** {@inheritDoc} */
34      @Override
35      public int getAnalogValue() {
36          return analogValue;
37      }
38  
39      /**
40       * {@inheritDoc}.
41       * bit 5 looks like 'in flux'.
42       */
43      @Override
44      public int getStatusCode() {
45          return statusCode;
46      }
47  
48      /** Analog value is 10 bits, so we steal 2 bits from the low byte. */
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; //000000xxxxxxxx00
55          int low = Byte.toUnsignedInt(b2) >>> LOW_SHIFT;  //00000000000000xx
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  }