Line data Source code
1 : /*
2 : * Package : mqtt_client
3 : * Author : S. Hamblett <steve.hamblett@linux.com>
4 : * Date : 30/06/2017
5 : * Copyright : S.Hamblett
6 : */
7 :
8 : part of mqtt_client;
9 :
10 : /// Message identifier handling
11 : class MessageIdentifierDispenser {
12 : Map<String, int> _idStorage = new Map<String, int>();
13 :
14 : /// Maximum message identifier
15 : static const int maxMessageIdentifier = 32768;
16 :
17 : /// Gets the next message identifier for the specified key.
18 : int getNextMessageIdentifier(String key) {
19 : // Only a single id can be dispensed at a time, regardless of the key.
20 : // Will revise to per-key locking if it proves bottleneck
21 : int retVal = 0;
22 6 : if (!_idStorage.containsKey(key)) {
23 6 : _idStorage[key] =
24 : 1; // add a new key, start at 1, 0 is reserved for by MQTT spec for invalid msg.
25 : retVal = 1;
26 : } else {
27 3 : int nextId = ++_idStorage[key];
28 1 : if (nextId == maxMessageIdentifier) {
29 : // overflow, wrap back to 1.
30 2 : nextId = _idStorage[key] = 1;
31 : }
32 : retVal = nextId;
33 : }
34 : return retVal;
35 : }
36 : }
|