From dd30c438a56f496d5c6ad4bbb26e3c1c29a0c557 Mon Sep 17 00:00:00 2001 From: Scott Hanson Date: Fri, 4 Mar 2022 00:49:15 -0500 Subject: [PATCH] cleanup some code --- .../frigate/internal/dto/EventDTO.java | 32 ++--- .../internal/events/IEventsHandler.java | 8 +- .../handler/FrigateCameraHandler.java | 47 ++++---- .../handler/FrigateServerHandler.java | 112 ++++++++---------- .../main/resources/OH-INF/thing/bridge.xml | 6 +- .../resources/OH-INF/thing/thing-types.xml | 12 +- 6 files changed, 95 insertions(+), 122 deletions(-) diff --git a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/dto/EventDTO.java b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/dto/EventDTO.java index d036d6e838cd9..de24fc59fae87 100644 --- a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/dto/EventDTO.java +++ b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/dto/EventDTO.java @@ -20,22 +20,22 @@ public class EventDTO { public String id; public String camera; - public double frame_time; - public double snapshot_time; + //public double frame_time; + //public double snapshot_time; public String label; public float top_score; - public boolean false_positive; - public double start_time; - public double end_time; - public float score; - //public int[] box; // : [424, 500, 536, 712], - public float area; - //public int[] region; // : [264, 450, 667, 853], - //public String[] current_zones; - //public String[] entered_zones; - public boolean has_snapshot; - public boolean has_clip; - public boolean stationary; - public int motionless_count; - public int position_changes; + //public boolean false_positive; + //public double start_time; + //public double end_time; + //public float score; + // public int[] box; // : [424, 500, 536, 712], + //public float area; + // public int[] region; // : [264, 450, 667, 853], + // public String[] current_zones; + // public String[] entered_zones; + //public boolean has_snapshot; + //public boolean has_clip; + //public boolean stationary; + //public int motionless_count; + //public int position_changes; } diff --git a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/events/IEventsHandler.java b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/events/IEventsHandler.java index 61ade92a793d6..f9fcd3436ebbd 100644 --- a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/events/IEventsHandler.java +++ b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/events/IEventsHandler.java @@ -14,9 +14,6 @@ import static java.nio.charset.StandardCharsets.UTF_8; -import java.io.IOException; -import java.net.InetAddress; -import java.net.UnknownHostException; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; @@ -100,7 +97,7 @@ public void connectionStateChanged(MqttConnectionState state, @Nullable Throwabl if (connection != null) { reconnect = null; - connection.subscribe("frigate/#", this).exceptionally(exception -> { + connection.subscribe("frigate/#", this).exceptionally(exception -> { logger.warn("MQTT subscription failed: {}", exception.getMessage()); return false; }).thenAccept(successful -> { @@ -121,9 +118,6 @@ public void connectionStateChanged(MqttConnectionState state, @Nullable Throwabl @Override public void processMessage(String topic, byte[] payload) { - // Report raw JSON reply - final String json = new String(payload, UTF_8); - receive(topic, payload); } diff --git a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateCameraHandler.java b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateCameraHandler.java index e463fb47b5e7a..f2ff396ee513d 100644 --- a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateCameraHandler.java +++ b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateCameraHandler.java @@ -14,22 +14,16 @@ import static org.openhab.binding.frigate.internal.FrigateBindingConstants.*; -import java.time.ZonedDateTime; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import org.openhab.binding.frigate.internal.FrigateCameraConfiguration; import org.openhab.binding.frigate.internal.dto.EventDTO; +import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.RawType; import org.openhab.core.library.types.StringType; -import org.openhab.core.library.types.DateTimeType; -import org.openhab.core.library.types.DecimalType; -import org.openhab.core.library.types.OpenClosedType; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; @@ -41,10 +35,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; - /** * The {@link FrigateCameraHandler} is responsible for handling commands, which are * sent to one of the channels. @@ -57,7 +47,7 @@ public class FrigateCameraHandler extends BaseThingHandler { private @Nullable FrigateCameraConfiguration config; private @Nullable Future normalPollFuture; - //private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); + // private static final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); private String cameraName = ""; private int refreshInterval = 60; @@ -89,13 +79,15 @@ public void handleCommand(ChannelUID channelUID, Command command) { @Override public void initialize() { config = getConfigAs(FrigateCameraConfiguration.class); - cameraName = config.name; - refreshInterval = config.imagerefresh; + if (config != null) { + cameraName = config.name; + refreshInterval = config.imagerefresh; + } logger.debug("Thing Name: {}", cameraName); updateStatus(ThingStatus.UNKNOWN); scheduler.execute(() -> { - boolean thingReachable = updateImage(true); + boolean thingReachable = updateImage(true); if (thingReachable) { updateStatus(ThingStatus.ONLINE); restartPolls(); @@ -123,7 +115,7 @@ private boolean updateImage(boolean updateAll) { RawType image = localHandler.getImage(imgurl); if (image != null) { updateState(CHANNEL_IMAGE, image); - if(updateAll) { + if (updateAll) { updateState(CHANNEL_IMAGE_URL, new StringType(localHandler.buildBaseUrl(imgurl))); String streamurl = String.format("/api/%s", cameraName); updateState(CHANNEL_VIDEO_URL, new StringType(localHandler.buildBaseUrl(streamurl))); @@ -132,21 +124,21 @@ private boolean updateImage(boolean updateAll) { } } updateState(CHANNEL_IMAGE, UnDefType.UNDEF); - if(updateAll) { + if (updateAll) { updateState(CHANNEL_IMAGE_URL, UnDefType.UNDEF); updateState(CHANNEL_VIDEO_URL, UnDefType.UNDEF); } return false; } - private void pollImage() - { + + private void pollImage() { updateImage(false); } private synchronized void restartPolls() { stopPolls(); normalPollFuture = scheduler.scheduleWithFixedDelay(this::pollImage, refreshInterval, refreshInterval, - TimeUnit.SECONDS); + TimeUnit.SECONDS); } private synchronized void stopPolls() { @@ -166,14 +158,15 @@ public String GetCameraName() { public void SetLastObject(byte[] data) { RawType image = new RawType(data, "image/jpeg"); - updateState(CHANNEL_LASTOBJECT, image); + updateState(CHANNEL_LASTOBJECT, image); } - public void UpdateEvent (EventDTO event){ - updateState(CHANNEL_EVENT_ID, new StringType(event.id)); - updateState( CHANNEL_EVENT_TYPE, new StringType(event.label)); - updateState( CHANNEL_EVENT_SCORE , new DecimalType(event.top_score)); - //updateState( CHANNEL_EVENT_START ,new DateTimeType(ZonedDateTime.ofInstant(event.getEnd().toInstant(), timeZoneProvider.getTimeZone()))); - //updateState( CHANNEL_EVENT_END , new DateTimeType(event.end_time)); + public void UpdateEvent(EventDTO event) { + updateState(CHANNEL_EVENT_ID, new StringType(event.id)); + updateState(CHANNEL_EVENT_TYPE, new StringType(event.label)); + updateState(CHANNEL_EVENT_SCORE, new DecimalType(event.top_score)); + // updateState( CHANNEL_EVENT_START ,new DateTimeType(ZonedDateTime.ofInstant(event.getEnd().toInstant(), + // timeZoneProvider.getTimeZone()))); + // updateState( CHANNEL_EVENT_END , new DateTimeType(event.end_time)); } } diff --git a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateServerHandler.java b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateServerHandler.java index 98c540aa4ad91..596140a5868d5 100644 --- a/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateServerHandler.java +++ b/bundles/org.openhab.binding.frigate/src/main/java/org/openhab/binding/frigate/internal/handler/FrigateServerHandler.java @@ -13,21 +13,16 @@ package org.openhab.binding.frigate.internal.handler; -import static org.openhab.binding.frigate.internal.FrigateBindingConstants.*; - import static java.nio.charset.StandardCharsets.UTF_8; +import static org.openhab.binding.frigate.internal.FrigateBindingConstants.*; import java.io.ByteArrayInputStream; import java.io.IOException; -import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.List; -import java.util.Map; import java.util.Random; import java.util.Set; - import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -41,11 +36,12 @@ import org.eclipse.jetty.http.HttpStatus; import org.openhab.binding.frigate.internal.FrigateServerConfiguration; import org.openhab.binding.frigate.internal.dto.EventDTO; -import org.openhab.binding.frigate.internal.dto.EventsDTO; import org.openhab.binding.frigate.internal.dto.ServiceDTO; import org.openhab.binding.frigate.internal.events.IEventsHandler; import org.openhab.core.io.net.http.HttpUtil; import org.openhab.core.io.transport.mqtt.MqttConnectionState; +import org.openhab.core.library.types.RawType; +import org.openhab.core.library.types.StringType; import org.openhab.core.thing.Bridge; import org.openhab.core.thing.ChannelUID; import org.openhab.core.thing.Thing; @@ -53,8 +49,6 @@ import org.openhab.core.thing.binding.BaseBridgeHandler; import org.openhab.core.types.Command; import org.openhab.core.types.RefreshType; -import org.openhab.core.library.types.StringType; -import org.openhab.core.library.types.RawType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -62,7 +56,6 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; -import com.google.gson.reflect.TypeToken; /** * The {@link FrigateServerHandler} is responsible for communicating with the Frigate Server @@ -70,7 +63,7 @@ * @author Scott Hanson - Initial contribution */ @NonNullByDefault -public class FrigateServerHandler extends BaseBridgeHandler { +public class FrigateServerHandler extends BaseBridgeHandler { private @Nullable FrigateServerConfiguration config; private HttpClient httpClient; private final Logger logger = LoggerFactory.getLogger(FrigateServerHandler.class); @@ -109,58 +102,53 @@ public void handleCommand(ChannelUID channelUID, Command command) { if (command instanceof RefreshType) { getStats(); return; - } + } } @Override public void initialize() { config = getConfigAs(FrigateServerConfiguration.class); updateStatus(ThingStatus.UNKNOWN); - - host = config.ipaddress; - portNumber = config.port; - - mqttHost = config.mqttipaddress; - mqttPort = config.mqttport; - + if (config != null) { + host = config.ipaddress; + portNumber = config.port; + mqttHost = config.mqttipaddress; + mqttPort = config.mqttport; + } scheduler.execute(() -> { boolean worked = getStats(); - if(worked) { - updateStatus(ThingStatus.ONLINE); - if(!mqttHost.isEmpty()){ - connect(mqttHost,mqttPort); + if (worked) { + updateStatus(ThingStatus.ONLINE); + if (!mqttHost.isEmpty()) { + connect(mqttHost, mqttPort); } - } - else{ + } else { updateStatus(ThingStatus.OFFLINE); } }); } - private boolean getStats(){ + private boolean getStats() { String response = executeGet(buildBaseUrl("/api/stats")); - if(response != null) { + if (response != null) { updateStatus(ThingStatus.ONLINE); JsonObject jsonObject = JsonParser.parseString(response).getAsJsonObject(); - Set keys = jsonObject.keySet(); - for (String key : keys){ - if(key.equals( "detection_fps")){ - //Float fps = jsonObject.get(key).getAsFloat(); - //updateState(CHANNEL_DETECTION_FPS, new DecimalType(fps)); - } - else if(key.equals( "detectors")){ + Set keys = jsonObject.keySet(); + for (String key : keys) { + if (key.equals("detection_fps")) { + // Float fps = jsonObject.get(key).getAsFloat(); + // updateState(CHANNEL_DETECTION_FPS, new DecimalType(fps)); + } else if (key.equals("detectors")) { - } - else if(key.equals( "service")){ + } else if (key.equals("service")) { ServiceDTO ser = GSON.fromJson(jsonObject.get(key), ServiceDTO.class); updateState(CHANNEL_VERSION, new StringType(ser.version)); - } - else{ + } else { } } return true; - } + } return false; } @@ -232,8 +220,8 @@ public String buildBaseUrl(String path) { private void connect(String mqttIP, int port) { logger.debug("Connecting MQTT to {}", mqttIP); - String userID = "openHabFrigate_" + randomString(5); - connection.connect(mqttIP, port, userID); + String userID = "openHabFrigate_" + randomString(5); + connection.connect(mqttIP, port, userID); } private static String randomString(int length) { @@ -249,44 +237,44 @@ private static String randomString(int length) { public void receive(final String topic, final byte[] message) { logger.trace("Got topic {}", topic); - //String json = new String(message, UTF_8); + // String json = new String(message, UTF_8); - if(topic.startsWith("frigate/") && topic.endsWith("/snapshot")){ + if (topic.startsWith("frigate/") && topic.endsWith("/snapshot")) { Bridge bridge = getThing(); List things = bridge.getThings(); for (Thing thing : things) { FrigateCameraHandler cam = (FrigateCameraHandler) thing.getHandler(); if (cam != null) { - String detect_topic = String.format("frigate/%s/",cam.GetCameraName()); - //frigate///snapshot - if(topic.contains(detect_topic)) { - logger.trace("updating snapshot for {}",cam.GetCameraName()); + String detect_topic = String.format("frigate/%s/", cam.GetCameraName()); + // frigate///snapshot + if (topic.contains(detect_topic)) { + logger.trace("updating snapshot for {}", cam.GetCameraName()); cam.SetLastObject(message); } } } } - if(topic.startsWith("frigate/events") ){ + if (topic.startsWith("frigate/events")) { String json = new String(message, UTF_8); - //EventsDTO event = GSON.fromJson(json, EventsDTO.class); + // EventsDTO event = GSON.fromJson(json, EventsDTO.class); JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject(); - String type = jsonObject.get("type").toString(); + String type = jsonObject.get("type").toString(); EventDTO event = GSON.fromJson(jsonObject.get("after"), EventDTO.class); - //EventsDTO - //if(type.equals("end")){ - Bridge bridge = getThing(); - List things = bridge.getThings(); - for (Thing thing : things) { - FrigateCameraHandler cam = (FrigateCameraHandler) thing.getHandler(); - if (cam != null) { - if(event.camera.equals(cam.GetCameraName())) { - logger.trace("updating event for {}",cam.GetCameraName()); - cam.UpdateEvent(event); - } + // EventsDTO + // if(type.equals("end")){ + Bridge bridge = getThing(); + List things = bridge.getThings(); + for (Thing thing : things) { + FrigateCameraHandler cam = (FrigateCameraHandler) thing.getHandler(); + if (cam != null) { + if (event.camera.equals(cam.GetCameraName())) { + logger.trace("updating event for {}", cam.GetCameraName()); + cam.UpdateEvent(event); } } - //} + } + // } } } } diff --git a/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/bridge.xml b/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/bridge.xml index 29a0793427cad..b378bc852e17f 100644 --- a/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/bridge.xml +++ b/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/bridge.xml @@ -8,20 +8,18 @@ Local Frigate NVR Server - - Frigate version - + diff --git a/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/thing-types.xml b/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/thing-types.xml index b994038d09ff4..bfad8e709fbfb 100644 --- a/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/thing-types.xml +++ b/bundles/org.openhab.binding.frigate/src/main/resources/OH-INF/thing/thing-types.xml @@ -13,7 +13,7 @@ Represents a Frigate camera - + @@ -25,7 +25,7 @@ + --> @@ -53,7 +53,7 @@ Current monitor state - --> + --> String @@ -83,11 +83,11 @@ Start date/time of the event - - + + DateTime End date/time of the event - --> + -->