]> git.basschouten.com Git - openhab-addons.git/blob
446ebd626e60573ab0844022c258ab660c754be2
[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 import org.eclipse.jdt.annotation.NonNullByDefault;
21 import org.openhab.binding.gpstracker.internal.message.dto.LocationMessage;
22 import org.openhab.binding.gpstracker.internal.message.dto.TransitionMessage;
23
24 /**
25  * Handler for notification messages between trackers.
26  *
27  * @author Gabor Bicskei - Initial contribution
28  */
29 @NonNullByDefault
30 public class NotificationHandler {
31     /**
32      * Location notifications need to be sent to the own tracker. Only the last location is saved for each tracker
33      * in the group.
34      */
35     private Map<String, LocationMessage> locationNotifications = new HashMap<>();
36
37     /**
38      * TransitionMessage notification to send out to the own tracker. Notifications are saved in order they were
39      * received.
40      */
41     private Map<String, List<TransitionMessage>> transitionNotifications = new HashMap<>();
42
43     /**
44      * Handling notification sent by other trackers.
45      *
46      * @param msg Notification message.
47      */
48     public void handleNotification(LocationMessage msg) {
49         synchronized (this) {
50             String trackerId = msg.getTrackerId();
51             if (msg instanceof TransitionMessage) {
52                 List<TransitionMessage> transitionMessages = transitionNotifications.computeIfAbsent(trackerId,
53                         k -> new ArrayList<>());
54                 if (transitionMessages != null) {
55                     transitionMessages.add((TransitionMessage) msg);
56                 }
57             } else {
58                 locationNotifications.put(trackerId, msg);
59             }
60         }
61     }
62
63     /**
64      * Collect all notifications about friend trackers.
65      *
66      * @return List of notification messages from friend trackers need to sent out
67      */
68     public List<LocationMessage> getNotifications() {
69         List<LocationMessage> ret;
70         synchronized (this) {
71             ret = new ArrayList<>(locationNotifications.values());
72             transitionNotifications.values().forEach(ret::addAll);
73             locationNotifications.clear();
74             transitionNotifications.clear();
75         }
76         return ret;
77     }
78 }