Skip to content

Commit

Permalink
fixup! feat: add experimental CoAP server implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
JKRhb committed Oct 30, 2022
1 parent 63b200e commit dba7547
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
4 changes: 3 additions & 1 deletion example/coap_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ FutureOr<void> main() async {
request,
CoapCode.content,
CoapMessageType.ack,
)..id = request.id;
)
..id = request.id
..payloadString = 'Hello World!';
print('Sending response: $response\n');
server
..sendResponse(response, request.source!, request.uriPort)
Expand Down
28 changes: 18 additions & 10 deletions lib/src/coap_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import 'package:typed_data/typed_data.dart';

import '../config/coap_config_default.dart';
import 'coap_config.dart';
import 'coap_empty_message.dart';
import 'coap_message.dart';
import 'coap_request.dart';
import 'coap_response.dart';
import 'stack/layer_stack.dart';
Expand Down Expand Up @@ -111,16 +113,16 @@ class _CoapUdpServer extends CoapServer {
return;
}
final data = Uint8Buffer()..addAll(datagram.data);
final decoder = _config.spec.newMessageDecoder(data);
if (decoder.isRequest) {
final request = decoder.decodeRequest();
if (request == null) {
final message = CoapMessage.fromUdpPayload(data);
if (message is CoapRequest && !message.hasFormatError) {
if (message.hasUnknownCriticalOption) {
_rejectMessage(message, datagram.address, datagram.port);
return;
}
request
message
..source = datagram.address
..uriPort = datagram.port;
streamController.sink.add(request);
streamController.sink.add(message);
}
});
}
Expand Down Expand Up @@ -155,9 +157,15 @@ class _CoapUdpServer extends CoapServer {
final InternetAddress address,
final int port,
) {
final encoder = _config.spec.newMessageEncoder();
final bytes = encoder.encodeResponse(response);
final buffer = Uint8List.fromList(bytes.toList(growable: false));
_socket.send(buffer, address, port);
_socket.send(response.toUdpPayload().toList(), address, port);
}

void _rejectMessage(
final CoapMessage message,
final InternetAddress address,
final int port,
) {
final resetMessage = CoapEmptyMessage.newRST(message);
_socket.send(resetMessage.toUdpPayload().toList(), address, port);
}
}

0 comments on commit dba7547

Please sign in to comment.