[ipcamera] Fix warnings and improve logging (#15703)

Signed-off-by: Kai Kreuzer <kai@openhab.org>
This commit is contained in:
Kai Kreuzer
2023-10-17 16:03:25 +02:00
committed by GitHub
parent 7cb94f9238
commit 1e090bddae
13 changed files with 121 additions and 142 deletions

View File

@@ -39,7 +39,6 @@ import org.slf4j.LoggerFactory;
/** /**
* The {@link Ffmpeg} class is responsible for handling multiple ffmpeg conversions which are used for many tasks * The {@link Ffmpeg} class is responsible for handling multiple ffmpeg conversions which are used for many tasks
* *
*
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@@ -90,7 +89,7 @@ public class Ffmpeg {
public void checkKeepAlive() { public void checkKeepAlive() {
if (keepAlive == 1) { if (keepAlive == 1) {
stopConverting(); stopConverting();
} else if (keepAlive <= -1 && !getIsAlive()) { } else if (keepAlive <= -1 && !isAlive()) {
logger.warn("HLS stream was not running, restarting it now."); logger.warn("HLS stream was not running, restarting it now.");
startConverting(); startConverting();
} }
@@ -124,9 +123,8 @@ public class Ffmpeg {
public void run() { public void run() {
try { try {
process = Runtime.getRuntime().exec(commandArrayList.toArray(new String[commandArrayList.size()])); process = Runtime.getRuntime().exec(commandArrayList.toArray(new String[commandArrayList.size()]));
Process localProcess = process;
if (localProcess != null) { InputStream errorStream = process.getErrorStream();
InputStream errorStream = localProcess.getErrorStream();
InputStreamReader errorStreamReader = new InputStreamReader(errorStream); InputStreamReader errorStreamReader = new InputStreamReader(errorStream);
BufferedReader bufferedReader = new BufferedReader(errorStreamReader); BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
String line = null; String line = null;
@@ -180,9 +178,8 @@ public class Ffmpeg {
break; break;
} }
} }
}
} catch (IOException e) { } catch (IOException e) {
logger.warn("An IO error occured trying to start FFmpeg:{}", e.getMessage()); logger.warn("An IO error occurred trying to start FFmpeg: {}", e.getMessage());
} finally { } finally {
switch (format) { switch (format) {
case GIF: case GIF:
@@ -217,7 +214,7 @@ public class Ffmpeg {
} }
} }
public boolean getIsAlive() { public boolean isAlive() {
Process localProcess = process; Process localProcess = process;
if (localProcess != null) { if (localProcess != null) {
if (localProcess.isAlive() && notFrozen) { if (localProcess.isAlive() && notFrozen) {

View File

@@ -120,13 +120,11 @@ public class ReolinkHandler extends ChannelDuplexHandler {
ipCameraHandler.logger.debug("The GetAiStateResponse could not be parsed"); ipCameraHandler.logger.debug("The GetAiStateResponse could not be parsed");
return; return;
} }
if (aiResponse[0].value.dog_cat != null) {
if (aiResponse[0].value.dog_cat.alarm_state == 1) { if (aiResponse[0].value.dog_cat.alarm_state == 1) {
ipCameraHandler.setChannelState(CHANNEL_ANIMAL_ALARM, OnOffType.ON); ipCameraHandler.setChannelState(CHANNEL_ANIMAL_ALARM, OnOffType.ON);
} else { } else {
ipCameraHandler.setChannelState(CHANNEL_ANIMAL_ALARM, OnOffType.OFF); ipCameraHandler.setChannelState(CHANNEL_ANIMAL_ALARM, OnOffType.OFF);
} }
}
if (aiResponse[0].value.face.alarm_state == 1) { if (aiResponse[0].value.face.alarm_state == 1) {
ipCameraHandler.setChannelState(CHANNEL_FACE_DETECTED, OnOffType.ON); ipCameraHandler.setChannelState(CHANNEL_FACE_DETECTED, OnOffType.ON);
} else { } else {

View File

@@ -50,7 +50,6 @@ import org.slf4j.LoggerFactory;
* *
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
public class IpCameraGroupHandler extends BaseThingHandler { public class IpCameraGroupHandler extends BaseThingHandler {
private final Logger logger = LoggerFactory.getLogger(getClass()); private final Logger logger = LoggerFactory.getLogger(getClass());

View File

@@ -123,7 +123,6 @@ import io.netty.util.concurrent.GlobalEventExecutor;
* *
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
public class IpCameraHandler extends BaseThingHandler { public class IpCameraHandler extends BaseThingHandler {
public final Logger logger = LoggerFactory.getLogger(getClass()); public final Logger logger = LoggerFactory.getLogger(getClass());
@@ -515,8 +514,8 @@ public class IpCameraHandler extends BaseThingHandler {
return; return;
} else if (ffmpegSnapshotGeneration) { // Use RTSP stream creating snapshots to know camera is online. } else if (ffmpegSnapshotGeneration) { // Use RTSP stream creating snapshots to know camera is online.
Ffmpeg localSnapshot = ffmpegSnapshot; Ffmpeg localSnapshot = ffmpegSnapshot;
if (localSnapshot != null && !localSnapshot.getIsAlive()) { if (localSnapshot != null && !localSnapshot.isAlive()) {
cameraCommunicationError("FFmpeg Snapshots Stopped: Check your camera can be reached."); cameraCommunicationError("FFmpeg Snapshots Stopped: Check that your camera can be reached.");
return; return;
} }
return; // ffmpeg snapshot stream is still alive return; // ffmpeg snapshot stream is still alive
@@ -882,9 +881,7 @@ public class IpCameraHandler extends BaseThingHandler {
ffmpegRecord = new Ffmpeg(this, format, cameraConfig.getFfmpegLocation(), inputOptions, rtspUri, ffmpegRecord = new Ffmpeg(this, format, cameraConfig.getFfmpegLocation(), inputOptions, rtspUri,
cameraConfig.getMp4OutOptions(), cameraConfig.getFfmpegOutput() + mp4Filename + ".mp4", cameraConfig.getMp4OutOptions(), cameraConfig.getFfmpegOutput() + mp4Filename + ".mp4",
cameraConfig.getUser(), cameraConfig.getPassword()); cameraConfig.getUser(), cameraConfig.getPassword());
Ffmpeg localRecord = ffmpegRecord; ffmpegRecord.startConverting();
if (localRecord != null) {
localRecord.startConverting();
if (mp4History.isEmpty()) { if (mp4History.isEmpty()) {
mp4History = mp4Filename; mp4History = mp4Filename;
} else if (!"ipcamera".equals(mp4Filename)) { } else if (!"ipcamera".equals(mp4Filename)) {
@@ -894,7 +891,6 @@ public class IpCameraHandler extends BaseThingHandler {
mp4History = mp4History.substring(0, endIndex); mp4History = mp4History.substring(0, endIndex);
} }
} }
}
setChannelState(CHANNEL_MP4_HISTORY, new StringType(mp4History)); setChannelState(CHANNEL_MP4_HISTORY, new StringType(mp4History));
break; break;
case RTSP_ALARMS: case RTSP_ALARMS:
@@ -930,10 +926,7 @@ public class IpCameraHandler extends BaseThingHandler {
} }
ffmpegRtspHelper = new Ffmpeg(this, format, cameraConfig.getFfmpegLocation(), inputOptions, input, ffmpegRtspHelper = new Ffmpeg(this, format, cameraConfig.getFfmpegLocation(), inputOptions, input,
filterOptions, "-f null -", cameraConfig.getUser(), cameraConfig.getPassword()); filterOptions, "-f null -", cameraConfig.getUser(), cameraConfig.getPassword());
localAlarms = ffmpegRtspHelper; ffmpegRtspHelper.startConverting();
if (localAlarms != null) {
localAlarms.startConverting();
}
break; break;
case MJPEG: case MJPEG:
if (ffmpegMjpeg == null) { if (ffmpegMjpeg == null) {
@@ -1448,7 +1441,7 @@ public class IpCameraHandler extends BaseThingHandler {
} }
public void cameraConfigError(String reason) { public void cameraConfigError(String reason) {
// wont try to reconnect again due to a config error being the cause. // won't try to reconnect again due to a config error being the cause.
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, reason); updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, reason);
dispose(); dispose();
} }
@@ -1640,13 +1633,13 @@ public class IpCameraHandler extends BaseThingHandler {
} }
if (ffmpegMotionAlarmEnabled || ffmpegAudioAlarmEnabled) { if (ffmpegMotionAlarmEnabled || ffmpegAudioAlarmEnabled) {
localFfmpeg = ffmpegRtspHelper; localFfmpeg = ffmpegRtspHelper;
if (localFfmpeg == null || !localFfmpeg.getIsAlive()) { if (localFfmpeg == null || !localFfmpeg.isAlive()) {
setupFfmpegFormat(FFmpegFormat.RTSP_ALARMS); setupFfmpegFormat(FFmpegFormat.RTSP_ALARMS);
} }
} }
// check if the thread has frozen due to camera doing a soft reboot // check if the thread has frozen due to camera doing a soft reboot
localFfmpeg = ffmpegMjpeg; localFfmpeg = ffmpegMjpeg;
if (localFfmpeg != null && !localFfmpeg.getIsAlive()) { if (localFfmpeg != null && !localFfmpeg.isAlive()) {
logger.debug("MJPEG was not being produced by FFmpeg when it should have been, restarting FFmpeg."); logger.debug("MJPEG was not being produced by FFmpeg when it should have been, restarting FFmpeg.");
setupFfmpegFormat(FFmpegFormat.MJPEG); setupFfmpegFormat(FFmpegFormat.MJPEG);
} }

View File

@@ -28,7 +28,6 @@ import io.netty.util.ReferenceCountUtil;
/** /**
* The {@link OnvifCodec} is used by Netty to decode Onvif traffic into message Strings. * The {@link OnvifCodec} is used by Netty to decode Onvif traffic into message Strings.
* *
*
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
@@ -66,11 +65,11 @@ public class OnvifCodec extends ChannelDuplexHandler {
} }
if (evt instanceof IdleStateEvent) { if (evt instanceof IdleStateEvent) {
IdleStateEvent e = (IdleStateEvent) evt; IdleStateEvent e = (IdleStateEvent) evt;
logger.trace("IdleStateEvent received {}", e.state()); logger.trace("IdleStateEvent received: {}", e.state());
onvifConnection.setIsConnected(false); onvifConnection.setIsConnected(false);
ctx.close(); ctx.close();
} else { } else {
logger.trace("Other ONVIF netty channel event occured {}", evt); logger.trace("Other ONVIF netty channel event occurred: {}", evt);
} }
} }

View File

@@ -67,8 +67,6 @@ import io.netty.handler.timeout.IdleStateHandler;
/** /**
* The {@link OnvifConnection} This is a basic Netty implementation for connecting and communicating to ONVIF cameras. * The {@link OnvifConnection} This is a basic Netty implementation for connecting and communicating to ONVIF cameras.
* *
*
*
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@@ -146,7 +144,7 @@ public class OnvifConnection {
private Float tiltRangeMax = 1.0f; private Float tiltRangeMax = 1.0f;
private Float zoomMin = 0.0f; private Float zoomMin = 0.0f;
private Float zoomMax = 1.0f; private Float zoomMax = 1.0f;
// These hold the PTZ values for updating Openhabs controls in 0-100 range // These hold the PTZ values for updating openHABs controls in 0-100 range
private Float currentPanPercentage = 0.0f; private Float currentPanPercentage = 0.0f;
private Float currentTiltPercentage = 0.0f; private Float currentTiltPercentage = 0.0f;
private Float currentZoomPercentage = 0.0f; private Float currentZoomPercentage = 0.0f;
@@ -308,7 +306,7 @@ public class OnvifConnection {
} }
public void processReply(String message) { public void processReply(String message) {
logger.trace("Onvif reply is:{}", message); logger.trace("ONVIF reply is: {}", message);
if (message.contains("PullMessagesResponse")) { if (message.contains("PullMessagesResponse")) {
eventRecieved(message); eventRecieved(message);
} else if (message.contains("RenewResponse")) { } else if (message.contains("RenewResponse")) {
@@ -317,7 +315,7 @@ public class OnvifConnection {
setIsConnected(true); setIsConnected(true);
sendOnvifRequest(RequestType.GetCapabilities, deviceXAddr); sendOnvifRequest(RequestType.GetCapabilities, deviceXAddr);
parseDateAndTime(message); parseDateAndTime(message);
logger.debug("Openhabs UTC dateTime is:{}", getUTCdateTime()); logger.debug("openHAB UTC dateTime is: {}", getUTCdateTime());
} else if (message.contains("GetCapabilitiesResponse")) {// 2nd to be sent. } else if (message.contains("GetCapabilitiesResponse")) {// 2nd to be sent.
parseXAddr(message); parseXAddr(message);
sendOnvifRequest(RequestType.GetProfiles, mediaXAddr); sendOnvifRequest(RequestType.GetProfiles, mediaXAddr);
@@ -358,7 +356,7 @@ public class OnvifConnection {
logger.debug("ptzNodeToken={}", ptzNodeToken); logger.debug("ptzNodeToken={}", ptzNodeToken);
sendPTZRequest(RequestType.GetConfigurations); sendPTZRequest(RequestType.GetConfigurations);
} else if (message.contains("GetDeviceInformationResponse")) { } else if (message.contains("GetDeviceInformationResponse")) {
logger.debug("GetDeviceInformationResponse recieved"); logger.debug("GetDeviceInformationResponse received");
} else if (message.contains("GetSnapshotUriResponse")) { } else if (message.contains("GetSnapshotUriResponse")) {
snapshotUri = removeIPfromUrl(Helper.fetchXML(message, ":MediaUri", ":Uri")); snapshotUri = removeIPfromUrl(Helper.fetchXML(message, ":MediaUri", ":Uri"));
logger.debug("GetSnapshotUri:{}", snapshotUri); logger.debug("GetSnapshotUri:{}", snapshotUri);
@@ -464,7 +462,7 @@ public class OnvifConnection {
String day = Helper.fetchXML(message, "UTCDateTime", "Day>"); String day = Helper.fetchXML(message, "UTCDateTime", "Day>");
String month = Helper.fetchXML(message, "UTCDateTime", "Month>"); String month = Helper.fetchXML(message, "UTCDateTime", "Month>");
String year = Helper.fetchXML(message, "UTCDateTime", "Year>"); String year = Helper.fetchXML(message, "UTCDateTime", "Year>");
logger.debug("Cameras UTC dateTime is:{}-{}-{}T{}:{}:{}", year, month, day, hour, minute, second); logger.debug("Camera UTC dateTime is: {}-{}-{}T{}:{}:{}", year, month, day, hour, minute, second);
} }
private String getUTCdateTime() { private String getUTCdateTime() {
@@ -565,7 +563,7 @@ public class OnvifConnection {
bootstrap = localBootstap; bootstrap = localBootstap;
} }
if (!mainEventLoopGroup.isShuttingDown()) { if (!mainEventLoopGroup.isShuttingDown()) {
bootstrap.connect(new InetSocketAddress(ipAddress, onvifPort)).addListener(new ChannelFutureListener() { localBootstap.connect(new InetSocketAddress(ipAddress, onvifPort)).addListener(new ChannelFutureListener() {
@Override @Override
public void operationComplete(@Nullable ChannelFuture future) { public void operationComplete(@Nullable ChannelFuture future) {
@@ -576,15 +574,16 @@ public class OnvifConnection {
connectError = false; connectError = false;
Channel ch = future.channel(); Channel ch = future.channel();
ch.writeAndFlush(request); ch.writeAndFlush(request);
} else { // an error occured } else { // an error occurred
if (future.isDone() && !future.isCancelled()) { if (future.isDone() && !future.isCancelled()) {
Throwable cause = future.cause(); Throwable cause = future.cause();
String msg = cause.getMessage();
logger.trace("connect failed - cause {}", cause.getMessage()); logger.trace("connect failed - cause {}", cause.getMessage());
if (cause instanceof ConnectTimeoutException) { if (cause instanceof ConnectTimeoutException) {
logger.debug("Camera is not reachable on IP {}", ipAddress); logger.debug("Camera is not reachable on IP {}", ipAddress);
connectError = true; connectError = true;
} else if ((cause instanceof ConnectException) } else if ((cause instanceof ConnectException) && msg != null
&& cause.getMessage().contains("Connection refused")) { && msg.contains("Connection refused")) {
logger.debug("Camera ONVIF port {} is refused.", onvifPort); logger.debug("Camera ONVIF port {} is refused.", onvifPort);
refusedError = true; refusedError = true;
} }
@@ -616,7 +615,7 @@ public class OnvifConnection {
} else {// 192.168.1.1 } else {// 192.168.1.1
ipAddress = url; ipAddress = url;
deviceXAddr = "http://" + ipAddress + "/onvif/device_service"; deviceXAddr = "http://" + ipAddress + "/onvif/device_service";
logger.debug("No Onvif Port found when parsing:{}", url); logger.debug("No ONVIF Port found when parsing: {}", url);
return; return;
} }
deviceXAddr = "http://" + ipAddress + ":" + onvifPort + "/onvif/device_service"; deviceXAddr = "http://" + ipAddress + ":" + onvifPort + "/onvif/device_service";
@@ -644,7 +643,7 @@ public class OnvifConnection {
} }
String dataName = Helper.fetchXML(eventMessage, "tt:Data", "Name=\""); String dataName = Helper.fetchXML(eventMessage, "tt:Data", "Name=\"");
String dataValue = Helper.fetchXML(eventMessage, "tt:Data", "Value=\""); String dataValue = Helper.fetchXML(eventMessage, "tt:Data", "Value=\"");
logger.debug("Onvif Event Topic:{}, Data:{}, Value:{}", topic, dataName, dataValue); logger.debug("ONVIF Event Topic: {}, Data: {}, Value: {}", topic, dataName, dataValue);
switch (topic) { switch (topic) {
case "RuleEngine/CellMotionDetector/Motion": case "RuleEngine/CellMotionDetector/Motion":
if ("true".equals(dataValue)) { if ("true".equals(dataValue)) {

View File

@@ -61,7 +61,6 @@ import io.netty.util.concurrent.GlobalEventExecutor;
* *
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
@io.netty.channel.ChannelHandler.Sharable @io.netty.channel.ChannelHandler.Sharable
public class OnvifDiscovery { public class OnvifDiscovery {
@@ -150,7 +149,7 @@ public class OnvifDiscovery {
} catch (IOException e) { } catch (IOException e) {
brand = "onvif"; brand = "onvif";
} }
logger.info("Possible {} camera found at:{}", brand, packet.sender().getHostString()); logger.debug("Possible {} camera found at: {}", brand, packet.sender().getHostString());
if ("reolink".equals(brand)) { if ("reolink".equals(brand)) {
ipCameraDiscoveryService.newCameraFound(brand, packet.sender().getHostString(), 8000); ipCameraDiscoveryService.newCameraFound(brand, packet.sender().getHostString(), 8000);
} else { } else {

View File

@@ -22,7 +22,6 @@ import io.netty.handler.codec.http.LastHttpContent;
/** /**
* The {@link NettyRtspHandler} is used to decode RTSP traffic into message Strings. * The {@link NettyRtspHandler} is used to decode RTSP traffic into message Strings.
* *
*
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault

View File

@@ -43,7 +43,6 @@ import io.netty.handler.timeout.IdleStateHandler;
* The {@link RtspConnection} is a WIP and not currently used, but will talk directly to RTSP and collect information * The {@link RtspConnection} is a WIP and not currently used, but will talk directly to RTSP and collect information
* about the camera and streams. * about the camera and streams.
* *
*
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault

View File

@@ -109,7 +109,7 @@ public class CameraServlet extends IpCameraServlet {
Ffmpeg localFfmpeg = handler.ffmpegHLS; Ffmpeg localFfmpeg = handler.ffmpegHLS;
if (localFfmpeg == null) { if (localFfmpeg == null) {
handler.setupFfmpegFormat(FFmpegFormat.HLS); handler.setupFfmpegFormat(FFmpegFormat.HLS);
} else if (!localFfmpeg.getIsAlive()) { } else if (!localFfmpeg.isAlive()) {
localFfmpeg.startConverting(); localFfmpeg.startConverting();
} else { } else {
localFfmpeg.setKeepAlive(8); localFfmpeg.setKeepAlive(8);

View File

@@ -22,10 +22,8 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
* The {@link OpenStreams} Keeps track of all open mjpeg streams so the byte[] can be given to all FIFO buffers to allow * The {@link OpenStreams} Keeps track of all open mjpeg streams so the byte[] can be given to all FIFO buffers to allow
* 1 to many streams without needing to open more than 1 source stream. * 1 to many streams without needing to open more than 1 source stream.
* *
*
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
public class OpenStreams { public class OpenStreams {
private List<StreamOutput> openStreams = Collections.synchronizedList(new ArrayList<StreamOutput>()); private List<StreamOutput> openStreams = Collections.synchronizedList(new ArrayList<StreamOutput>());

View File

@@ -28,7 +28,6 @@ import org.slf4j.LoggerFactory;
* *
* @author Matthew Skinner - Initial contribution * @author Matthew Skinner - Initial contribution
*/ */
@NonNullByDefault @NonNullByDefault
public class StreamOutput { public class StreamOutput {
public final Logger logger = LoggerFactory.getLogger(getClass()); public final Logger logger = LoggerFactory.getLogger(getClass());