-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathDeviceBase.java
More file actions
272 lines (226 loc) · 9.6 KB
/
DeviceBase.java
File metadata and controls
272 lines (226 loc) · 9.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/*
* Copyright (C) 2014 Ishraq Ibne Ashraf <[email protected]>
* Copyright (C) 2012-2013, 2019-2021 Matthias Bolte <[email protected]>
* Copyright (C) 2011 Olaf Lüke <[email protected]>
*
* Redistribution and use in source and binary forms of this file,
* with or without modification, are permitted. See the Creative
* Commons Zero (CC0 1.0) License for more details.
*/
package com.tinkerforge;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public abstract class DeviceBase {
static final byte DEVICE_IDENTIFIER_CHECK_PENDING = 0;
static final byte DEVICE_IDENTIFIER_CHECK_MATCH = 1;
static final byte DEVICE_IDENTIFIER_CHECK_MISMATCH = 2;
static final byte RESPONSE_EXPECTED_FLAG_INVALID_FUNCTION_ID = 0;
static final byte RESPONSE_EXPECTED_FLAG_ALWAYS_TRUE = 1; // getter
static final byte RESPONSE_EXPECTED_FLAG_TRUE = 2; // setter
static final byte RESPONSE_EXPECTED_FLAG_FALSE = 3; // setter, default
boolean replaced;
long uidNumber;
String uidString;
int deviceIdentifier;
String deviceDisplayName;
Object deviceIdentifierMutex = new Object();
byte deviceIdentifierCheck = DEVICE_IDENTIFIER_CHECK_PENDING; // protected by deviceIdentifierMutex
String wrongDeviceDisplayName = "?"; // protected by deviceIdentifierMutex
short[] apiVersion = new short[3];
byte[] responseExpected = new byte[256];
byte expectedResponseFunctionID = 0; // protected by requestMutex
byte expectedResponseSequenceNumber = 0; // protected by requestMutex
Object requestMutex = new Object();
LinkedBlockingQueue<byte[]> responseQueue = new LinkedBlockingQueue<byte[]>();
IPConnection ipcon = null;
IPConnection.DeviceCallbackListener[] callbacks = new IPConnection.DeviceCallbackListener[256];
IPConnection.DeviceHighLevelCallback[] highLevelCallbacks = new IPConnection.DeviceHighLevelCallback[256];
Object streamMutex = new Object();
public DeviceBase(String uid, IPConnection ipcon) {
long uidNumber = IPConnectionBase.base58Decode(uid);
if (uidNumber > 0xFFFFFFFFL) {
// convert from 64bit to 32bit
long value1 = uidNumber & 0xFFFFFFFFL;
long value2 = (uidNumber >> 32) & 0xFFFFFFFFL;
uidNumber = (value1 & 0x00000FFFL);
uidNumber |= (value1 & 0x0F000000L) >> 12;
uidNumber |= (value2 & 0x0000003FL) << 16;
uidNumber |= (value2 & 0x000F0000L) << 6;
uidNumber |= (value2 & 0x3F000000L) << 2;
}
if (uidNumber == 0) {
throw new IllegalArgumentException("UID '" + uid + "' is empty or maps to zero");
}
this.replaced = false;
this.uidNumber = uidNumber;
this.uidString = uid;
this.ipcon = ipcon;
for (int i = 0; i < responseExpected.length; i++) {
responseExpected[i] = RESPONSE_EXPECTED_FLAG_INVALID_FUNCTION_ID;
}
}
/**
* Returns the API version (major, minor, revision) of the bindings for
* this device.
*/
public short[] getAPIVersion() {
return apiVersion;
}
/**
* Returns the response expected flag for the function specified by the
* \c functionId parameter. It is *true* if the function is expected to
* send a response, *false* otherwise.
*
* For getter functions this is enabled by default and cannot be disabled,
* because those functions will always send a response. For callback
* configuration functions it is enabled by default too, but can be
* disabled via the SetResponseExpected function. For setter functions it
* is disabled by default and can be enabled.
*
* Enabling the response expected flag for a setter function allows to
* detect timeouts and other error conditions calls of this setter as well.
* The device will then send a response for this purpose. If this flag is
* disabled for a setter function then no response is sent and errors are
* silently ignored, because they cannot be detected.
*/
public boolean getResponseExpected(byte functionId) {
byte flag = responseExpected[IPConnectionBase.unsignedByte(functionId)];
if (flag == RESPONSE_EXPECTED_FLAG_INVALID_FUNCTION_ID) {
throw new IllegalArgumentException("Invalid function ID " + IPConnectionBase.unsignedByte(functionId));
}
return flag == RESPONSE_EXPECTED_FLAG_ALWAYS_TRUE ||
flag == RESPONSE_EXPECTED_FLAG_TRUE;
}
/**
* Changes the response expected flag of the function specified by
* the \c functionId parameter. This flag can only be changed for setter
* (default value: *false*) and callback configuration functions
* (default value: *true*). For getter functions it is always enabled.
*
* Enabling the response expected flag for a setter function allows to
* detect timeouts and other error conditions calls of this setter as
* well. The device will then send a response for this purpose. If this
* flag is disabled for a setter function then no response is sent and
* errors are silently ignored, because they cannot be detected.
*/
public void setResponseExpected(byte functionId, boolean responseExpected) {
int index = IPConnectionBase.unsignedByte(functionId);
byte flag = this.responseExpected[index];
if (flag == RESPONSE_EXPECTED_FLAG_INVALID_FUNCTION_ID) {
throw new IllegalArgumentException("Invalid function ID " + IPConnectionBase.unsignedByte(functionId));
}
if (flag == RESPONSE_EXPECTED_FLAG_ALWAYS_TRUE) {
throw new IllegalArgumentException("Response Expected flag cannot be changed for function ID " + IPConnectionBase.unsignedByte(functionId));
}
if (responseExpected) {
this.responseExpected[index] = RESPONSE_EXPECTED_FLAG_TRUE;
} else {
this.responseExpected[index] = RESPONSE_EXPECTED_FLAG_FALSE;
}
}
/**
* Changes the response expected flag for all setter and callback
* configuration functions of this device at once.
*/
public void setResponseExpectedAll(boolean responseExpected) {
byte flag = RESPONSE_EXPECTED_FLAG_FALSE;
if (responseExpected) {
flag = RESPONSE_EXPECTED_FLAG_TRUE;
}
for (int i = 0; i < this.responseExpected.length; i++) {
if (this.responseExpected[i] == RESPONSE_EXPECTED_FLAG_TRUE ||
this.responseExpected[i] == RESPONSE_EXPECTED_FLAG_FALSE) {
this.responseExpected[i] = flag;
}
}
}
void checkValidity() throws TinkerforgeException {
if (replaced) {
throw new DeviceReplacedException();
}
if (deviceIdentifierCheck == DEVICE_IDENTIFIER_CHECK_MATCH) {
return;
}
synchronized (deviceIdentifierMutex) {
if (deviceIdentifierCheck == DEVICE_IDENTIFIER_CHECK_PENDING) {
ByteBuffer bb = ipcon.createRequestPacket((byte)8, (byte)255, this); // getIdentity
byte[] response = sendRequest(bb.array(), 33);
bb = ByteBuffer.wrap(response, 31, response.length - 31);
bb.order(ByteOrder.LITTLE_ENDIAN);
int deviceIdentifier = IPConnectionBase.unsignedShort(bb.getShort());
if (deviceIdentifier == this.deviceIdentifier) {
deviceIdentifierCheck = DEVICE_IDENTIFIER_CHECK_MATCH;
} else {
deviceIdentifierCheck = DEVICE_IDENTIFIER_CHECK_MISMATCH;
try {
wrongDeviceDisplayName = DeviceFactory.getDeviceDisplayName(deviceIdentifier);
} catch (IllegalArgumentException e) {
wrongDeviceDisplayName = "Unknown Device [" + deviceIdentifier + "]";
}
}
}
if (deviceIdentifierCheck == DEVICE_IDENTIFIER_CHECK_MISMATCH) {
throw new WrongDeviceTypeException("UID " + uidString + " belongs to a " + wrongDeviceDisplayName +
" instead of the expected " + deviceDisplayName);
}
}
}
byte[] sendRequest(byte[] request, int expectedResponseLength) throws TinkerforgeException {
byte[] response = null;
if (IPConnectionBase.getResponseExpectedFromData(request)) {
byte functionID = IPConnectionBase.getFunctionIDFromData(request);
String functionName = "ID " + IPConnectionBase.unsignedByte(functionID);
synchronized (requestMutex) {
expectedResponseFunctionID = functionID;
expectedResponseSequenceNumber = IPConnectionBase.getSequenceNumberFromData(request);
try {
ipcon.sendRequest(request);
while (true) {
response = null;
try {
response = responseQueue.poll(ipcon.responseTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (response == null) {
throw new TimeoutException("Did not receive response in time for function " + functionName);
}
if (expectedResponseFunctionID == IPConnectionBase.getFunctionIDFromData(response) &&
expectedResponseSequenceNumber == IPConnectionBase.getSequenceNumberFromData(response)) {
// ignore old responses that arrived after the timeout expired, but before setting
// expectedResponseFunctionID and expectedResponseSequenceNumber back to 0
break;
}
}
} finally {
expectedResponseFunctionID = 0;
expectedResponseSequenceNumber = 0;
}
}
byte errorCode = IPConnectionBase.getErrorCodeFromData(response);
switch (errorCode) {
case 0:
if (expectedResponseLength == 0) {
// setter with response-expected enabled
expectedResponseLength = 8;
}
if (response.length != expectedResponseLength) {
throw new WrongResponseLengthException("Expected response of " + expectedResponseLength + " byte for function " + functionName + ", got " + response.length + " byte instead");
}
break;
case 1:
throw new InvalidParameterException("Got invalid parameter for function " + functionName);
case 2:
throw new NotSupportedException("Function " + functionName + " is not supported");
default:
throw new UnknownErrorCodeException("Function " + functionName + " returned an unknown error");
}
} else {
ipcon.sendRequest(request);
}
return response;
}
}