]> git.basschouten.com Git - openhab-addons.git/blob
6b061e894ac411cd80293afd0f1123e1c8b6b80d
[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.logreader.internal.handler;
14
15 import static org.openhab.binding.logreader.internal.LogReaderBindingConstants.*;
16
17 import java.time.ZonedDateTime;
18 import java.util.regex.PatternSyntaxException;
19
20 import org.openhab.binding.logreader.internal.config.LogReaderConfiguration;
21 import org.openhab.binding.logreader.internal.filereader.api.FileReaderListener;
22 import org.openhab.binding.logreader.internal.filereader.api.LogFileReader;
23 import org.openhab.binding.logreader.internal.searchengine.SearchEngine;
24 import org.openhab.core.library.types.DateTimeType;
25 import org.openhab.core.library.types.DecimalType;
26 import org.openhab.core.library.types.StringType;
27 import org.openhab.core.thing.ChannelUID;
28 import org.openhab.core.thing.Thing;
29 import org.openhab.core.thing.ThingStatus;
30 import org.openhab.core.thing.ThingStatusDetail;
31 import org.openhab.core.thing.binding.BaseThingHandler;
32 import org.openhab.core.types.Command;
33 import org.openhab.core.types.RefreshType;
34 import org.openhab.core.types.State;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 /**
39  * The {@link LogReaderHandler} is responsible for handling commands, which are
40  * sent to one of the channels.
41  *
42  * @author Miika Jukka - Initial contribution
43  * @author Pauli Anttila - Rewrite
44  */
45 public class LogHandler extends BaseThingHandler implements FileReaderListener {
46     private final Logger logger = LoggerFactory.getLogger(LogHandler.class);
47
48     private LogReaderConfiguration configuration;
49
50     private LogFileReader fileReader;
51
52     private SearchEngine errorEngine;
53     private SearchEngine warningEngine;
54     private SearchEngine customEngine;
55
56     public LogHandler(Thing thing, LogFileReader fileReader) {
57         super(thing);
58         this.fileReader = fileReader;
59     }
60
61     @Override
62     public void handleCommand(ChannelUID channelUID, Command command) {
63         switch (channelUID.getId()) {
64             case CHANNEL_ERRORS:
65                 updateChannel(channelUID, command, errorEngine);
66                 break;
67
68             case CHANNEL_WARNINGS:
69                 updateChannel(channelUID, command, warningEngine);
70                 break;
71
72             case CHANNEL_CUSTOMEVENTS:
73                 updateChannel(channelUID, command, customEngine);
74                 break;
75
76             default:
77                 logger.debug("Unsupported command '{}' received for channel '{}'", command, channelUID);
78         }
79     }
80
81     @Override
82     public void initialize() {
83         configuration = getConfigAs(LogReaderConfiguration.class);
84
85         configuration.filePath = configuration.filePath.replaceFirst("\\$\\{OPENHAB_LOGDIR\\}",
86                 System.getProperty("openhab.logdir"));
87
88         logger.debug("Using configuration: {}", configuration);
89
90         clearCounters();
91
92         try {
93             warningEngine = new SearchEngine(configuration.warningPatterns, configuration.warningBlacklistingPatterns);
94             errorEngine = new SearchEngine(configuration.errorPatterns, configuration.errorBlacklistingPatterns);
95             customEngine = new SearchEngine(configuration.customPatterns, configuration.customBlacklistingPatterns);
96
97         } catch (PatternSyntaxException e) {
98             logger.debug("Illegal search pattern syntax '{}'. ", e.getMessage(), e);
99             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
100             return;
101         }
102
103         logger.debug("Start file reader");
104
105         try {
106             fileReader.registerListener(this);
107             fileReader.start(configuration.filePath, configuration.refreshRate);
108             updateStatus(ThingStatus.ONLINE);
109         } catch (Exception e) {
110             logger.debug("Exception occurred during initalization: {}. ", e.getMessage(), e);
111             shutdown();
112             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.CONFIGURATION_ERROR, e.getMessage());
113         }
114     }
115
116     @Override
117     public void dispose() {
118         logger.debug("Stopping thing");
119         shutdown();
120     }
121
122     private void updateChannel(ChannelUID channelUID, Command command, SearchEngine matcher) {
123         if (command instanceof DecimalType) {
124             matcher.setMatchCount(((DecimalType) command).longValue());
125         } else if (command instanceof RefreshType) {
126             updateState(channelUID.getId(), new DecimalType(matcher.getMatchCount()));
127         } else {
128             logger.debug("Unsupported command '{}' received for channel '{}'", command, channelUID);
129         }
130     }
131
132     private void clearCounters() {
133         if (errorEngine != null) {
134             errorEngine.clearMatchCount();
135         }
136         if (warningEngine != null) {
137             warningEngine.clearMatchCount();
138         }
139         if (customEngine != null) {
140             customEngine.clearMatchCount();
141         }
142     }
143
144     private void updateChannelIfLinked(String channelID, State state) {
145         if (isLinked(channelID)) {
146             updateState(channelID, state);
147         }
148     }
149
150     private void shutdown() {
151         logger.debug("Stop file reader");
152         fileReader.unregisterListener(this);
153         fileReader.stop();
154     }
155
156     @Override
157     public void fileNotFound() {
158         final String msg = String.format("Log file '%s' does not exist", configuration.filePath);
159         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, msg);
160     }
161
162     @Override
163     public void fileRotated() {
164         logger.debug("Log rotated");
165         updateChannelIfLinked(CHANNEL_LOGROTATED, new DateTimeType(ZonedDateTime.now()));
166     }
167
168     @Override
169     public void handle(String line) {
170         if (line == null) {
171             return;
172         }
173
174         if (!(thing.getStatus() == ThingStatus.ONLINE)) {
175             updateStatus(ThingStatus.ONLINE);
176         }
177
178         if (errorEngine.isMatching(line)) {
179             updateChannelIfLinked(CHANNEL_ERRORS, new DecimalType(errorEngine.getMatchCount()));
180             updateChannelIfLinked(CHANNEL_LASTERROR, new StringType(line));
181             triggerChannel(CHANNEL_NEWERROR, line);
182         }
183         if (warningEngine.isMatching(line)) {
184             updateChannelIfLinked(CHANNEL_WARNINGS, new DecimalType(warningEngine.getMatchCount()));
185             updateChannelIfLinked(CHANNEL_LASTWARNING, new StringType(line));
186             triggerChannel(CHANNEL_NEWWARNING, line);
187         }
188         if (customEngine.isMatching(line)) {
189             updateChannelIfLinked(CHANNEL_CUSTOMEVENTS, new DecimalType(customEngine.getMatchCount()));
190             updateChannelIfLinked(CHANNEL_LASTCUSTOMEVENT, new StringType(line));
191             triggerChannel(CHANNEL_NEWCUSTOM, line);
192         }
193     }
194
195     @Override
196     public void handle(Exception ex) {
197         final String msg = ex != null ? ex.getMessage() : "";
198         logger.debug("Error while trying to read log file: {}. ", msg, ex);
199         updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.OFFLINE.COMMUNICATION_ERROR, msg);
200     }
201 }