]> git.basschouten.com Git - openhab-addons.git/blob
378a6b2e0418e58c594fdd02ae4f00c849b72bf9
[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.ipcamera.internal.onvif;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16 import org.eclipse.jdt.annotation.Nullable;
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 import io.netty.channel.ChannelDuplexHandler;
21 import io.netty.channel.ChannelHandlerContext;
22 import io.netty.handler.codec.http.HttpContent;
23 import io.netty.handler.codec.http.LastHttpContent;
24 import io.netty.util.CharsetUtil;
25 import io.netty.util.ReferenceCountUtil;
26
27 /**
28  * The {@link OnvifCodec} is used by Netty to decode Onvif traffic into message Strings.
29  *
30  *
31  * @author Matthew Skinner - Initial contribution
32  */
33 @NonNullByDefault
34 public class OnvifCodec extends ChannelDuplexHandler {
35     private final Logger logger = LoggerFactory.getLogger(getClass());
36     private String incomingMessage = "";
37     private OnvifConnection onvifConnection;
38
39     OnvifCodec(OnvifConnection onvifConnection) {
40         this.onvifConnection = onvifConnection;
41     }
42
43     @Override
44     public void channelRead(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
45         if (msg == null || ctx == null) {
46             return;
47         }
48         try {
49             if (msg instanceof HttpContent content) {
50                 incomingMessage += content.content().toString(CharsetUtil.UTF_8);
51             }
52             if (msg instanceof LastHttpContent) {
53                 onvifConnection.processReply(incomingMessage);
54                 ctx.close();
55             }
56         } finally {
57             ReferenceCountUtil.release(msg);
58         }
59     }
60
61     @Override
62     public void exceptionCaught(@Nullable ChannelHandlerContext ctx, @Nullable Throwable cause) {
63         if (ctx == null || cause == null) {
64             return;
65         }
66         logger.debug("Exception on ONVIF connection: {}", cause.getMessage());
67         ctx.close();
68     }
69 }