]> git.basschouten.com Git - openhab-addons.git/blob
13f40fdb86c1e845ffc81bf1b11be911e0d9ed5d
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.yioremote.internal.utils;
14
15 import java.io.IOException;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.eclipse.jetty.websocket.api.Session;
20 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
21 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError;
22 import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
23 import org.eclipse.jetty.websocket.api.annotations.WebSocket;
24 import org.slf4j.Logger;
25 import org.slf4j.LoggerFactory;
26
27 /**
28  * The {@link Websocket} is responsible for the Websocket Connection
29  *
30  * @author Michael Loercher - Initial contribution
31  */
32
33 @NonNullByDefault
34 @WebSocket
35 public class Websocket {
36
37     private @Nullable Session session;
38     private final Logger logger = LoggerFactory.getLogger(Websocket.class);
39     private @Nullable WebsocketInterface websocketHandler;
40
41     public void addMessageHandler(WebsocketInterface yioremotedockwebsocketinterfacehandler) {
42         this.websocketHandler = yioremotedockwebsocketinterfacehandler;
43     }
44
45     @OnWebSocketMessage
46     public void onText(Session session, String receivedMessage) {
47         if (websocketHandler != null) {
48             websocketHandler.onMessage(receivedMessage);
49         }
50     }
51
52     @OnWebSocketConnect
53     public void onConnect(Session session) {
54         this.session = session;
55         if (websocketHandler != null) {
56             websocketHandler.onConnect(true);
57         }
58     }
59
60     @OnWebSocketError
61     public void onError(Throwable cause) {
62         logger.warn("WebSocketError {}", cause.getMessage());
63         if (websocketHandler != null) {
64             websocketHandler.onError();
65         }
66     }
67
68     public void sendMessage(String str) {
69         if (session != null) {
70             try {
71                 session.getRemote().sendString(str);
72             } catch (IOException e) {
73                 logger.warn("Error during sendMessage function {}", e.getMessage());
74             }
75         }
76     }
77 }