1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.uwb.support.fira;
18 
19 import com.google.uwb.support.base.ProtocolVersion;
20 
21 import java.nio.ByteBuffer;
22 
23 /** Provides parameter versioning for Fira. */
24 public class FiraProtocolVersion extends ProtocolVersion {
25     private static final int FIRA_PACKED_BYTE_COUNT = 2;
26 
FiraProtocolVersion(int major, int minor)27     public FiraProtocolVersion(int major, int minor) {
28         super(major, minor);
29     }
30 
fromString(String protocol)31     public static FiraProtocolVersion fromString(String protocol) {
32         String[] parts = protocol.split("\\.", -1);
33         if (parts.length != 2) {
34             throw new IllegalArgumentException("Invalid protocol version: " + protocol);
35         }
36 
37         return new FiraProtocolVersion(Integer.parseInt(parts[0]), Integer.parseInt(parts[1]));
38     }
39 
toBytes()40     public byte[] toBytes() {
41         return ByteBuffer.allocate(bytesUsed())
42                 .put((byte) getMajor())
43                 .put((byte) getMinor())
44                 .array();
45     }
46 
fromBytes(byte[] data, int startIndex)47     public static FiraProtocolVersion fromBytes(byte[] data, int startIndex) {
48         int major = data[startIndex] & 0xFF;
49         int minor = data[startIndex + 1] & 0xFF;
50         return new FiraProtocolVersion(major, minor);
51     }
52 
53     /**
54      * Construct the FiraProtocolVersion from a 2-octet value (received as a Little-Endian short),
55      * that contains the major, minor and maintenance version numbers.
56      * - Octet[0], Bits 0-7: Major version.
57      * - Octet[1], Bits 4-7: Minor version.
58      * - Octet[1], Bits 0-3: Maintenance version.
59      */
fromLEShort(short version)60     public static FiraProtocolVersion fromLEShort(short version) {
61         int major = version & 0xFF;
62         int minor = (version >> 12) & 0x0F;
63         // We don't currently store or use the maintenance version number.
64         return new FiraProtocolVersion(major, minor);
65     }
66 
bytesUsed()67     public static int bytesUsed() {
68         return FIRA_PACKED_BYTE_COUNT;
69     }
70 }
71