-
Notifications
You must be signed in to change notification settings - Fork 3
/
zw_driver.dart
202 lines (177 loc) · 6.08 KB
/
zw_driver.dart
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
import 'dart:async';
import 'package:zwave/src/zw_decoder.dart';
import 'package:zwave/zw_exception.dart';
import 'package:logging/logging.dart';
typedef MessageHandler = void Function(List<int> data);
/// [ZwDriver] handles low level communication with the Z-Wave controller.
/// Low level ACK (acknowledge) and NAK (corrupt message) responses
/// are automatically sent and higher level message data is forwarded
/// to the provided request/response handlers.
class ZwDriver implements ZwDecodeListener {
final void Function(List<int> data) _sendData;
final Duration sendTimeout;
/// [requestHandler] processes requests
/// sent from the Z-Wave controller or from physical devices in the network.
MessageHandler? requestHandler;
/// [defaultResponseHandler] processes responses
/// sent from the Z-Wave controller or from physical devices in the network.
/// If a response handler is specified when [send] is called, then
/// that handler (rather than this handler) will receive the next response.
/// This handler will receive any subsequent responses.
MessageHandler? defaultResponseHandler;
Completer<void>? _sendCompleter;
Completer<List<int>>? _responseCompleter;
Timer? _responseTimer;
int _handleRequestExceptionCount = 0;
int _handleDefaultResponseExceptionCount = 0;
ZwDriver(this._sendData, {int? sendTimeoutMsForTesting})
: sendTimeout = Duration(milliseconds: sendTimeoutMsForTesting ?? 1600);
/// Send the specified message and return a [Future]
/// that completes when the message is acknowledged
/// or completes with an error if the message is canceled or corrupted.
Future<void> send(List<int> data,
{Completer<List<int>>? responseCompleter, Duration? responseTimeout}) {
if (data == null || data.isEmpty) _error('invalid data');
if (responseCompleter != null && responseTimeout == null)
_error('must specify responseTimeout with responseCompleter');
if (_sendCompleter != null) _error('only one send at a time');
if (_responseCompleter != null) _error('only one send/response at a time');
_logFiner('==>', data, 'REQ');
_sendData(data);
_sendCompleter = Completer<void>();
_responseCompleter = responseCompleter;
// From section 6.2.2 of the Serial API Host Appl. Prg. Guide
// Data frame sender timeout is 1600 ms
return _sendCompleter!.future.timeout(sendTimeout, onTimeout: () {
_logger.warning('send timeout $data');
_sendCompleter = null;
_responseCompleter = null;
throw ZwException.sendTimeout;
}).then((_) {
_sendCompleter = null;
if (_responseCompleter != null && responseTimeout != null) {
_responseTimer = Timer(responseTimeout, () {
_logger.warning('response timeout $data');
_responseCompleter!.completeError(ZwException.responseTimeout);
_responseCompleter = null;
_responseTimer = null;
});
}
});
}
void sendAck() {
const ackMsg = <int>[ACK];
_logFinest('==>', ackMsg, 'ACK');
_sendData(ackMsg);
}
void sendNak() {
const nakMsg = <int>[NAK];
_logFinest('==>', nakMsg, 'NAK');
_sendData(nakMsg);
}
@override
void handleAck() {
if (_sendCompleter != null) {
_sendCompleter!.complete();
_sendCompleter = null;
} else {
_logger.warning('unexpected ACK');
}
}
@override
void handleNak() {
if (_sendCompleter != null) {
_errorWaitingForAck(ZwException.sendCorrupted);
} else {
_logger.warning('unexpected NAK');
}
}
@override
void handleCan() {
if (_sendCompleter != null) {
_errorWaitingForAck(ZwException.sendCanceled);
} else {
_logger.warning('unexpected CAN');
}
}
@override
void handleDataFrame(List<int> dataFrame) {
switch (dataFrame[2]) {
case REQ_TYPE:
sendAck();
_handleRequest(dataFrame);
break;
case RES_TYPE:
sendAck();
_handleResponse(dataFrame);
break;
default:
_logger.warning('unknown message type: ${dataFrame[2]} $dataFrame');
const cancelMsg = <int>[CAN];
_logFinest('==>', cancelMsg, 'CAN');
_sendData(cancelMsg);
break;
}
}
void _handleRequest(List<int> dataFrame) {
if (requestHandler != null) {
try {
requestHandler!(dataFrame);
} catch (error, trace) {
++_handleRequestExceptionCount;
_logger.warning(
'request handler failed'
' ($_handleRequestExceptionCount): $dataFrame',
error,
_handleRequestExceptionCount < 5 ? trace : null);
}
} else {
_logger.warning('Unexpected request: $dataFrame');
}
}
void _handleResponse(List<int> dataFrame) {
if (_responseCompleter != null) {
_responseTimer?.cancel();
_responseTimer = null;
_responseCompleter!.complete(dataFrame);
_responseCompleter = null;
} else if (defaultResponseHandler != null) {
try {
defaultResponseHandler!(dataFrame);
} catch (error, trace) {
++_handleDefaultResponseExceptionCount;
_logger.warning(
'default response handler failed'
' ($_handleDefaultResponseExceptionCount): $dataFrame',
error,
_handleDefaultResponseExceptionCount < 5 ? trace : null);
}
} else {
_logger.warning('Unexpected response: $dataFrame');
}
}
@override
void handleInvalidDataFrame() {
_logger.warning('invalid data frame');
sendNak();
}
void _errorWaitingForAck(ZwException exception) {
_logger.warning(exception.message);
_sendCompleter!.completeError(exception);
_sendCompleter = null;
_responseCompleter = null;
_responseTimer?.cancel();
_responseTimer = null;
}
}
final Logger _logger = Logger('ZwDriver');
void _error(String message) {
_logger.warning(message);
throw ZwException(message);
}
void _logFiner(String label, data, String tag) {
if (_logger.level <= Level.FINER) _logger.finer('$label $data $tag');
}
void _logFinest(String label, data, String tag) {
if (_logger.level <= Level.FINEST) _logger.finest('$label $data $tag');
}