Refactoring
This commit is contained in:
1 parent
f8100facf3
commit
91d50fe58c
11 files changed
+198
-107
No files matched your search
@@ -7,18 +7,25 @@ class Constants {
|
||||
static const String messageTopicConnectionStatusChanged = "connection_status_changed";
|
||||
static const String messageTopicSessionInfoUpdate = "status_info_updated";
|
||||
static const String messageTopicSessionStatusInfoUpdate = "session_status_info_updated";
|
||||
static const String messageTopicLocationStatusUpdated = "status_info_updated";
|
||||
static const String messageTopicLocationStatusUpdated = "location_status_updated";
|
||||
static const String messageTopicRankingUpdated = "ranking_updated";
|
||||
static const String messageTopicJobReceived = "job_received";
|
||||
static const String messageTopicJobDeleted = "job_deleted";
|
||||
static const String messageTopicRefreshBadges = "refresh_badges";
|
||||
static const String messageTopicUpdateBadges = "update_badges";
|
||||
static const String messageTopicMessageReceived = "message_received";
|
||||
static const String messageTopicPushContentView = "push_content_view";
|
||||
static const String messageTopicPopContentView = "pop_content_view";
|
||||
static const String messageTopicReplaceContentView = "replace_content_view";
|
||||
static const String messageTopicHideRightButton = "hide_right_button";
|
||||
static const String messageTopicPublishPayload = "publish_payload_message";
|
||||
static const String messageTopicConnectClient = "connect_client";
|
||||
static const String messageTopicDisconnectClient = "disconnect_client";
|
||||
static const String messageTopicRequestConnectionStatus = "request_connection_status";
|
||||
static const String messageTopicCurrentConnectionStatus = "current_connection_status";
|
||||
static const String messageShowPopup = "show_popup";
|
||||
|
||||
static const String prefsPreviousMqttSubscription = "previous_mqtt_subscription";
|
||||
|
||||
static const int stateAssigned = 0;
|
||||
static const int stateAccepted = 1;
|
||||
static const int stateFinished = 2;
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
class PublishPayloadMessage {
|
||||
final String topic;
|
||||
|
||||
final Map<String, dynamic> message;
|
||||
|
||||
PublishPayloadMessage({required this.topic, required this.message});
|
||||
}
|
||||
+118
-76
@@ -45,8 +45,6 @@ enum ConnectionStateEnum {
|
||||
}
|
||||
|
||||
class MqttCore {
|
||||
static late MqttCore instance;
|
||||
|
||||
late ConnectionStateEnum connectionState = ConnectionStateEnum.notConnected;
|
||||
|
||||
late bool _disconnectInProgress = false;
|
||||
@@ -57,7 +55,7 @@ class MqttCore {
|
||||
late String _fromServerTopic;
|
||||
late String _toServerTopic;
|
||||
|
||||
late MqttServerClient _mqttClient;
|
||||
MqttServerClient? _mqttClient;
|
||||
|
||||
late int _reconnectDelay = 0;
|
||||
|
||||
@@ -66,23 +64,23 @@ class MqttCore {
|
||||
Timer? _trackTimer;
|
||||
|
||||
MqttCore() {
|
||||
initMessages();
|
||||
|
||||
_disconnectInProgress = false;
|
||||
|
||||
_processBootstrap();
|
||||
}
|
||||
|
||||
static setup() {
|
||||
instance = MqttCore();
|
||||
}
|
||||
|
||||
diconnect() {
|
||||
_disconnect() {
|
||||
_disconnectInProgress = true;
|
||||
|
||||
_cancelReconnectTimer();
|
||||
|
||||
_cancelTrackTimer();
|
||||
|
||||
_mqttClient.disconnect();
|
||||
if (_mqttClient != null) {
|
||||
_mqttClient!.disconnect();
|
||||
}
|
||||
|
||||
connectionState = ConnectionStateEnum.notConnected;
|
||||
}
|
||||
@@ -95,25 +93,25 @@ class MqttCore {
|
||||
Util.logInfo("broker port: $_brokerPort");
|
||||
|
||||
_mqttClient = MqttServerClient.withPort(_brokerUri, clientId, _brokerPort);
|
||||
_mqttClient.logging(on: false);
|
||||
_mqttClient.keepAlivePeriod = 5;
|
||||
_mqttClient.disconnectOnNoResponsePeriod = 10;
|
||||
_mqttClient.autoReconnect = true;
|
||||
_mqttClient.onDisconnected = _clientDisconnected;
|
||||
_mqttClient.onAutoReconnect = _clientDisconnected;
|
||||
_mqttClient.onAutoReconnected = _clientConnected;
|
||||
_mqttClient.connectionMessage = MqttConnectMessage()
|
||||
_mqttClient!.logging(on: false);
|
||||
_mqttClient!.keepAlivePeriod = 5;
|
||||
_mqttClient!.disconnectOnNoResponsePeriod = 10;
|
||||
_mqttClient!.autoReconnect = true;
|
||||
_mqttClient!.onDisconnected = _clientDisconnected;
|
||||
_mqttClient!.onAutoReconnect = _clientDisconnected;
|
||||
_mqttClient!.onAutoReconnected = _clientConnected;
|
||||
_mqttClient!.connectionMessage = MqttConnectMessage()
|
||||
.withClientIdentifier(await Util.getAppUuid())
|
||||
.authenticateAs("app", "apppwd");
|
||||
|
||||
await _mqttClient.connect();
|
||||
await _mqttClient!.connect();
|
||||
|
||||
if (_mqttClient.connectionStatus?.state == MqttConnectionState.connected) {
|
||||
if (_mqttClient!.connectionStatus?.state == MqttConnectionState.connected) {
|
||||
Util.logInfo('Verbunden mit dem MQTT-Broker!');
|
||||
|
||||
_reconnectDelay = 0;
|
||||
|
||||
_setupSubscriptions();
|
||||
_setupMqtt();
|
||||
|
||||
_initSession();
|
||||
} else {
|
||||
@@ -130,79 +128,87 @@ class MqttCore {
|
||||
}
|
||||
|
||||
publishBinary(String topic, List<int> data) {
|
||||
var buffer = Uint8Buffer();
|
||||
buffer.addAll(data);
|
||||
if (_mqttClient != null) {
|
||||
var buffer = Uint8Buffer();
|
||||
buffer.addAll(data);
|
||||
|
||||
_mqttClient.publishMessage(topic, MqttQos.exactlyOnce, buffer);
|
||||
_mqttClient!.publishMessage(topic, MqttQos.exactlyOnce, buffer);
|
||||
|
||||
Util.logInfo("binary message send to $topic");
|
||||
Util.logInfo("binary message send to $topic");
|
||||
} else {
|
||||
Util.logException("publishBinary called while offline!");
|
||||
}
|
||||
}
|
||||
|
||||
publishMessage(String topic, String text) {
|
||||
var buffer = Uint8Buffer();
|
||||
buffer.addAll(GZipEncoder().encode(const Utf8Encoder().convert(text)) as Iterable<int>);
|
||||
publishText(String topic, String text) {
|
||||
if (_mqttClient != null) {
|
||||
var buffer = Uint8Buffer();
|
||||
buffer.addAll(utf8.encode(text));
|
||||
|
||||
var messageTopic = "$_toServerTopic$topic/$_clientId";
|
||||
_mqttClient!.publishMessage(topic, MqttQos.exactlyOnce, buffer);
|
||||
|
||||
_mqttClient.publishMessage(messageTopic, MqttQos.exactlyOnce, buffer);
|
||||
|
||||
Util.logInfo("message\n$text\nsend to $messageTopic");
|
||||
Util.logInfo("message\n$text\nsend to $topic");
|
||||
} else {
|
||||
Util.logException("publishBinary called while offline!");
|
||||
}
|
||||
}
|
||||
|
||||
void _setupSubscriptions() async {
|
||||
Util.logInfo('_setupSubscriptions called');
|
||||
void _setupMqtt() async {
|
||||
Util.logInfo('_setupMqtt called');
|
||||
|
||||
_mqttClient.updates?.listen((List<MqttReceivedMessage<MqttMessage>> messages) {
|
||||
_mqttClient!.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
|
||||
try {
|
||||
for (var mqttMessage in messages) {
|
||||
final MqttPublishMessage message = mqttMessage.payload as MqttPublishMessage;
|
||||
final MqttPublishMessage message = c[0].payload as MqttPublishMessage;
|
||||
String payload = utf8.decode(MqttPublishPayload.bytesToStringAsString(message.payload.message).codeUnits);
|
||||
var topic = message.variableHeader?.topicName;
|
||||
|
||||
if (message.variableHeader!.topicName.endsWith(_clientId)) {
|
||||
var messageBytes = message.payload.message;
|
||||
String payload = utf8.decode(GZipDecoder().decodeBytes(messageBytes));
|
||||
Util.logInfo('message received\ntopic: $topic\nmessage: $payload');
|
||||
|
||||
var topicArray = message.variableHeader?.topicName;
|
||||
var topicArraySplited = topicArray!.split("/");
|
||||
var topic = topicArraySplited[3];
|
||||
Map<String, dynamic> messageData = jsonDecode(payload);
|
||||
|
||||
Util.logInfo('message received\ntopic: $topic\nmessage: $payload');
|
||||
for (var entry in messageData.keys) {
|
||||
if (entry == 'payload') {
|
||||
var payload = messageData[entry];
|
||||
for (var payloadEntry in payload.keys) {
|
||||
var payloadData = payload[payloadEntry];
|
||||
|
||||
switch(topic) {
|
||||
case 'session':
|
||||
_sessionMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
switch (payloadEntry) {
|
||||
case 'session':
|
||||
_sessionMessageReceived(payloadData);
|
||||
break;
|
||||
|
||||
case 'location_status':
|
||||
_locationSatusMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
case 'location_status':
|
||||
_locationSatusMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
case 'ranking':
|
||||
_rankingMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
case 'ranking':
|
||||
_rankingMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
case 'job':
|
||||
_jobMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
case 'job':
|
||||
_jobMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
case 'job_del':
|
||||
_jobDeleteReceived(jsonDecode(payload));
|
||||
break;
|
||||
case 'job_del':
|
||||
_jobDeleteReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
case 'sync_request':
|
||||
_syncRequestReceived(jsonDecode(payload));
|
||||
break;
|
||||
case 'sync_request':
|
||||
_syncRequestReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
case "mssg":
|
||||
_messageMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
case "mssg":
|
||||
_messageMessageReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
case "upload_device_log":
|
||||
_messageUploadDeviceLogReceived(jsonDecode(payload));
|
||||
break;
|
||||
case "upload_device_log":
|
||||
_messageUploadDeviceLogReceived(jsonDecode(payload));
|
||||
break;
|
||||
|
||||
default:
|
||||
Util.logInfo('Unknown topic: $topic');
|
||||
break;
|
||||
default:
|
||||
Util.logInfo('Unknown topic: $topic');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -211,9 +217,21 @@ class MqttCore {
|
||||
}
|
||||
});
|
||||
|
||||
var fromServerTopic = "$_fromServerTopic#";
|
||||
_mqttClient.subscribe(fromServerTopic, MqttQos.exactlyOnce);
|
||||
Util.logInfo('subscribed to topic: $fromServerTopic');
|
||||
if (await Util.preferencesContainsKey(Constants.prefsPreviousMqttSubscription)) {
|
||||
String previousMqttSubscription = await Util.preferencesGetString(Constants.prefsPreviousMqttSubscription, "") as String;
|
||||
|
||||
if (previousMqttSubscription != _fromServerTopic) {
|
||||
Util.logInfo('topic changed -> unsubscribe from $previousMqttSubscription');
|
||||
_mqttClient!.unsubscribe(previousMqttSubscription);
|
||||
}
|
||||
|
||||
_mqttClient!.subscribe(_fromServerTopic, MqttQos.exactlyOnce);
|
||||
}
|
||||
|
||||
_mqttClient!.subscribe(_fromServerTopic, MqttQos.exactlyOnce);
|
||||
Util.preferencesSaveString(Constants.prefsPreviousMqttSubscription, _fromServerTopic);
|
||||
|
||||
Util.logInfo('subscribed to topic: $_fromServerTopic');
|
||||
|
||||
MessageService().publish<ConnectionStatus>(Constants.messageTopicConnectionStatusChanged, arguments: ConnectionStatus(status: ConnectionStatusEnum.connected));
|
||||
}
|
||||
@@ -388,7 +406,6 @@ class MqttCore {
|
||||
|
||||
var jsonMap = handshakeMessage.toJson();
|
||||
var json = Uri.encodeFull(jsonEncode(jsonMap));
|
||||
//var uri = "http://test-app-server.dns.army:8080/bootstrap?json=$json"; // Testserver bei Torben
|
||||
var uri = "https://test-app-server.assecutor.org/bootstrap?json=$json";
|
||||
Util.logInfo("Bootstrap request: $uri");
|
||||
|
||||
@@ -496,6 +513,31 @@ class MqttCore {
|
||||
message.received.ver = job.ver;
|
||||
message.received.utc = DateTime.now().millisecondsSinceEpoch;
|
||||
|
||||
MqttCore.instance.publishMessage('job_received', jsonEncode(message.toJson()));
|
||||
publishPayloadMessage('job', message.toJson());
|
||||
}
|
||||
|
||||
void initMessages() {
|
||||
MessageService().subscribe<PublishPayloadMessage>(Constants.messageTopicPublishPayload, this, (PublishPayloadMessage payloadMessage) {
|
||||
publishPayloadMessage(payloadMessage.topic, payloadMessage.message);
|
||||
});
|
||||
|
||||
MessageService().subscribe<DisconnectClientMessage>(Constants.messageTopicDisconnectClient, this, (DisconnectClientMessage disconnectClientMessage) {
|
||||
_disconnect();
|
||||
});
|
||||
|
||||
MessageService().subscribe<ConnectClientMessage>(Constants.messageTopicConnectClient, this, (ConnectClientMessage connectClientMessage) {
|
||||
_connectToBroker();
|
||||
});
|
||||
|
||||
MessageService().subscribe<RequestConnectionStatusMessage>(Constants.messageTopicRequestConnectionStatus, this, (RequestConnectionStatusMessage requestConnectionStatusMessage) {
|
||||
bool connected = false;
|
||||
if (_mqttClient != null && _mqttClient!.connectionStatus != null) {
|
||||
if (_mqttClient!.connectionStatus!.state == MqttConnectionState.connected) {
|
||||
connected = true;
|
||||
}
|
||||
}
|
||||
|
||||
MessageService().publish<CurrentConnectionStatusMessage>(Constants.messageTopicCurrentConnectionStatus, arguments: CurrentConnectionStatusMessage(state: connected));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user