]> git.basschouten.com Git - openhab-addons.git/blob
749f95435c1e13fcb6cf3f50372332b8e0dc6fa2
[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.silvercrestwifisocket.internal.handler;
14
15 import java.net.SocketException;
16 import java.util.HashMap;
17 import java.util.Map;
18 import java.util.Set;
19
20 import org.openhab.binding.silvercrestwifisocket.internal.SilvercrestWifiSocketBindingConstants;
21 import org.openhab.binding.silvercrestwifisocket.internal.discovery.SilvercrestWifiSocketDiscoveryService;
22 import org.openhab.binding.silvercrestwifisocket.internal.entities.SilvercrestWifiSocketResponse;
23 import org.openhab.binding.silvercrestwifisocket.internal.runnable.SilvercrestWifiSocketUpdateReceiverRunnable;
24 import org.openhab.core.thing.Thing;
25 import org.osgi.service.component.ComponentContext;
26 import org.osgi.service.component.annotations.Component;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * The {@link SilvercrestWifiSocketMediatorImpl} is responsible for receiving all the UDP packets and route correctly to
32  * each handler.
33  *
34  * @author Jaime Vaz - Initial contribution
35  */
36 @Component(service = SilvercrestWifiSocketMediator.class)
37 public class SilvercrestWifiSocketMediatorImpl implements SilvercrestWifiSocketMediator {
38
39     private final Logger logger = LoggerFactory.getLogger(SilvercrestWifiSocketMediatorImpl.class);
40
41     private final Map<Thing, SilvercrestWifiSocketHandler> handlersRegistredByThing = new HashMap<>();
42
43     private SilvercrestWifiSocketUpdateReceiverRunnable receiver;
44     private Thread receiverThread;
45
46     private SilvercrestWifiSocketDiscoveryService silvercrestDiscoveryService;
47
48     /**
49      * Called at the service activation.
50      *
51      * @param componentContext the componentContext
52      */
53     protected void activate(final ComponentContext componentContext) {
54         logger.debug("Mediator has been activated by OSGI.");
55         this.initMediatorWifiSocketUpdateReceiverRunnable();
56     }
57
58     /**
59      * Called at the service deactivation.
60      *
61      * @param componentContext the componentContext
62      */
63     protected void deactivate(final ComponentContext componentContext) {
64         if (this.receiver != null) {
65             this.receiver.shutdown();
66         }
67     }
68
69     /**
70      * This method is called by the {@link SilvercrestWifiSocketUpdateReceiverRunnable}, when one new message has been
71      * received.
72      *
73      * @param receivedMessage the {@link SilvercrestWifiSocketResponse} message.
74      */
75     @Override
76     public void processReceivedPacket(final SilvercrestWifiSocketResponse receivedMessage) {
77         logger.debug("Received packet from: {} with content: [{}]", receivedMessage.getHostAddress(),
78                 receivedMessage.getType());
79
80         SilvercrestWifiSocketHandler handler = this.getHandlerRegistredByMac(receivedMessage.getMacAddress());
81
82         if (handler != null) {
83             // deliver message to handler.
84             handler.newReceivedResponseMessage(receivedMessage);
85             logger.debug("Received message delivered with success to handler of mac {}",
86                     receivedMessage.getMacAddress());
87         } else {
88             logger.debug("There is no handler registered for mac address:{}", receivedMessage.getMacAddress());
89             // notify discovery service of thing found!
90             this.silvercrestDiscoveryService.discoveredWifiSocket(receivedMessage.getMacAddress(),
91                     receivedMessage.getHostAddress());
92         }
93     }
94
95     /**
96      * Regists one new {@link Thing} and the corresponding {@link SilvercrestWifiSocketHandler}.
97      *
98      * @param thing the {@link Thing}.
99      * @param handler the {@link SilvercrestWifiSocketHandler}.
100      */
101     @Override
102     public void registerThingAndWifiSocketHandler(final Thing thing, final SilvercrestWifiSocketHandler handler) {
103         this.handlersRegistredByThing.put(thing, handler);
104     }
105
106     /**
107      * Unregists one {@link SilvercrestWifiSocketHandler} by the corresponding {@link Thing}.
108      *
109      * @param thing the {@link Thing}.
110      */
111     @Override
112     public void unregisterWifiSocketHandlerByThing(final Thing thing) {
113         SilvercrestWifiSocketHandler handler = this.handlersRegistredByThing.get(thing);
114         if (handler != null) {
115             this.handlersRegistredByThing.remove(thing);
116         }
117     }
118
119     /**
120      * Utilitary method to get the registered thing handler in mediator by the mac address.
121      *
122      * @param macAddress the mac address of the thing of the handler.
123      * @return {@link SilvercrestWifiSocketHandler} if found.
124      */
125     private SilvercrestWifiSocketHandler getHandlerRegistredByMac(final String macAddress) {
126         SilvercrestWifiSocketHandler searchedHandler = null;
127         for (SilvercrestWifiSocketHandler handler : this.handlersRegistredByThing.values()) {
128             if (macAddress.equals(handler.getMacAddress())) {
129                 searchedHandler = handler;
130                 // don't spend more computation. Found the handler.
131                 break;
132             }
133         }
134         return searchedHandler;
135     }
136
137     /**
138      * Inits the mediator WifiSocketUpdateReceiverRunnable thread. This thread is responsible to receive all
139      * packets from Wifi Socket devices, and redirect the messages to mediator.
140      */
141     private void initMediatorWifiSocketUpdateReceiverRunnable() {
142         // try with handler port if is null
143         if ((this.receiver == null) || ((this.receiverThread != null)
144                 && (this.receiverThread.isInterrupted() || !this.receiverThread.isAlive()))) {
145             try {
146                 this.receiver = new SilvercrestWifiSocketUpdateReceiverRunnable(this,
147                         SilvercrestWifiSocketBindingConstants.WIFI_SOCKET_DEFAULT_UDP_PORT);
148                 this.receiverThread = new Thread(this.receiver);
149                 this.receiverThread.start();
150                 logger.debug("Invoked the start of receiver thread.");
151             } catch (SocketException e) {
152                 logger.debug("Cannot start the socket with default port...");
153             }
154         }
155     }
156
157     /**
158      * Returns all the {@link Thing} registered.
159      *
160      * @return all the {@link Thing}.
161      */
162     @Override
163     public Set<Thing> getAllThingsRegistred() {
164         return this.handlersRegistredByThing.keySet();
165     }
166
167     @Override
168     public void setDiscoveryService(final SilvercrestWifiSocketDiscoveryService discoveryService) {
169         this.silvercrestDiscoveryService = discoveryService;
170     }
171 }