Line data Source code
1 : /*
2 : * Package : mqtt_client
3 : * Author : S. Hamblett <steve.hamblett@linux.com>
4 : * Date : 14/08/2017
5 : * Copyright : S.Hamblett
6 : */
7 :
8 : part of mqtt_client;
9 :
10 : /// The MQTT connection class for the websocket interface
11 : class MqttWsConnection extends MqttConnection {
12 : /// Default constructor
13 1 : MqttWsConnection();
14 :
15 : /// Initializes a new instance of the MqttConnection class.
16 0 : MqttWsConnection.fromConnect(String server, int port) {
17 0 : connect(server, port);
18 : }
19 :
20 : /// Connect - overridden
21 : Future connect(String server, int port) {
22 1 : final Completer completer = new Completer();
23 : // Add the port if present
24 : Uri uri;
25 : try {
26 1 : uri = Uri.parse(server);
27 : } catch (FormatException) {
28 : final String message =
29 1 : "MqttWsConnection::The URI supplied for the WS connection is not valid - $server";
30 1 : throw new NoConnectionException(message);
31 : }
32 2 : if (uri.scheme != "ws") {
33 : final String message =
34 1 : "MqttWsConnection::The URI supplied for the WS has an incorrect scheme - $server";
35 1 : throw new NoConnectionException(message);
36 : }
37 : if (port != null) {
38 1 : uri = uri.replace(port: port);
39 : }
40 1 : final String uriString = uri.toString();
41 2 : MqttLogger.log("MqttWsConnection:: WS URL is $uriString");
42 : try {
43 : // Connect and save the socket.
44 2 : WebSocket.connect(uriString).then((socket) {
45 1 : client = socket;
46 2 : readWrapper = new ReadWrapper();
47 1 : _startListening();
48 1 : return completer.complete();
49 1 : }).catchError((e) => _onError(e));
50 : } catch (SocketException) {
51 : final String message =
52 0 : "MqttWsConnection::The connection to the message broker {$uriString} could not be made.";
53 0 : throw new NoConnectionException(message);
54 : }
55 1 : return completer.future;
56 : }
57 : }
|