]> git.basschouten.com Git - openhab-addons.git/blob
bc7e1eab66998f2e64daf95fb400994397b3845c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.gpstracker.internal.message;
14
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.List;
18 import java.util.Map;
19
20 /**
21  * Handler for notification messages between trackers.
22  *
23  * @author Gabor Bicskei - Initial contribution
24  */
25 public class NotificationHandler {
26     /**
27      * Location notifications need to be sent to the own tracker. Only the last location is saved for each tracker
28      * in the group.
29      */
30     private Map<String, LocationMessage> locationNotifications = new HashMap<>();
31
32     /**
33      * TransitionMessage notification to send out to the own tracker. Notifications are saved in order they were
34      * received.
35      */
36     private Map<String, List<TransitionMessage>> transitionNotifications = new HashMap<>();
37
38     /**
39      * Handling notification sent by other trackers.
40      *
41      * @param msg Notification message.
42      */
43     public void handleNotification(LocationMessage msg) {
44         synchronized (this) {
45             String trackerId = msg.getTrackerId();
46             if (msg instanceof TransitionMessage) {
47                 List<TransitionMessage> transitionMessages = transitionNotifications.computeIfAbsent(trackerId,
48                         k -> new ArrayList<>());
49                 transitionMessages.add((TransitionMessage) msg);
50             } else {
51                 locationNotifications.put(trackerId, msg);
52             }
53         }
54     }
55
56     /**
57      * Collect all notifications about friend trackers.
58      *
59      * @return List of notification messages from friend trackers need to sent out
60      */
61     public List<LocationMessage> getNotifications() {
62         List<LocationMessage> ret;
63         synchronized (this) {
64             ret = new ArrayList<>(locationNotifications.values());
65             transitionNotifications.values().forEach(ret::addAll);
66             locationNotifications.clear();
67             transitionNotifications.clear();
68         }
69         return ret;
70     }
71 }