Skip to content

Commit

Permalink
Fix camera
Browse files Browse the repository at this point in the history
Camera was not working properly, trying new method to save temporary file.
  • Loading branch information
tmjo committed Jan 16, 2022
1 parent a42bdcb commit 09115ff
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 17 deletions.
17 changes: 15 additions & 2 deletions custom_components/norwegiantide/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,12 @@

class NorwegianTideApiClient:
def __init__(
self, place, latitude, longitude, session: aiohttp.ClientSession
self,
place,
latitude,
longitude,
session: aiohttp.ClientSession,
output_dir=CONST_DIR_DEFAULT,
) -> None:

"""Sample API Client."""
Expand All @@ -60,6 +65,8 @@ def __init__(
self.tidedata = {}
self.tidedatatime = {}
self.next_tide = {}
self.output_dir = output_dir
self.file_image = API_NAME + "_" + self.place + "_img.png"

def get_url(
self,
Expand Down Expand Up @@ -137,6 +144,11 @@ def process_data(self):
self.current_observation = self.getCurrentDataObservation()
self.data = self.getDataAll()

try:
self.plot_tidedata()
except Exception as e: # pylint: disable=broad-except
_LOGGER.warning(f"Error processing tide plot: {e}")

return {
API_PLACE: self.getLocationPlace(),
API_LAT: self.getLocation(API_LAT),
Expand Down Expand Up @@ -539,14 +551,15 @@ def plot_tidedata(

# Save image
if filename is None:
filename = os.path.join(CONST_DIR_DEFAULT, API_NAME + ".png")
filename = os.path.join(self.output_dir, self.file_image)

_LOGGER.debug(f"Saving image {filename}.")
plt.savefig(filename)

# Show
if show:
plt.show()
plt.close()

def plot_add_highlow(self, plt, highlow=None, color="darkorange", fontsize=8):
if highlow is None:
Expand Down
79 changes: 64 additions & 15 deletions custom_components/norwegiantide/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
from datetime import timedelta
import io
from typing import Callable, List
import mimetypes
import os

import voluptuous as vol

Expand All @@ -25,6 +27,7 @@
NAME,
VERSION,
ATTRIBUTION,
CONST_DIR_DEFAULT,
)


Expand Down Expand Up @@ -73,6 +76,30 @@ def __init__(
)
Camera.__init__(self)

# Directories
# CONST_DIR_THIS = os.path.split(__file__)[0]
# CONST_DIR_DEFAULT = os.path.join(CONST_DIR_THIS, "tmp")
# file_path = os.path.join(CONST_DIR_DEFAULT, "norwegianweather.png")
file_path = os.path.join(CONST_DIR_DEFAULT, self.coordinator.api.file_image)

self._name = name
self.check_file_path_access(file_path)
self._file_path = file_path
# Set content type of local file
content, _ = mimetypes.guess_type(file_path)
if content is not None:
self.content_type = content

@property
def brand(self):
"""Return the camera brand."""
return self.device_info.get("manufacturer", None)

@property
def model(self):
"""Return the camera model."""
return self.device_info.get("model", None)

@property
def frame_interval(self):
# this is how often the image will update in the background.
Expand All @@ -84,20 +111,42 @@ def frame_interval(self):
async def async_camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
# def camera_image(self):
"""Load image bytes in memory"""
# # don't use throttle because extra calls return Nones
# if not self._loaded:
# _LOGGER.debug("Loading image data")
# self.sky.load(self._tmpdir)
# self._loaded = True
# def camera_image(self) -> bytes | None:

"""Return image response."""

_LOGGER.debug("Updating camera image")
try:
buf = io.BytesIO()
# self.sky.plot_sky(buf)
self.coordinator.api.plot_tidedata(buf)
buf.seek(0)
return buf.getvalue()
except:
_LOGGER.warning("Could not read camera!")
return None
with open(self._file_path, "rb") as file:
return file.read()
except FileNotFoundError:
_LOGGER.warning(
"Could not read camera %s image from file: %s",
self._name,
self._file_path,
)
return None

def check_file_path_access(self, file_path):
"""Check that filepath given is readable."""
if not os.access(file_path, os.R_OK):
_LOGGER.warning(
"Could not read camera %s image from file: %s", self._name, file_path
)

def update_file_path(self, file_path):
"""Update the file_path."""
self.check_file_path_access(file_path)
self._file_path = file_path
self.schedule_update_ha_state()

# @property
# def name(self):
# """Return the name of this camera."""
# # return self._name
# return f"{self._place}_{self._entity_name}".replace("_", " ")

@property
def extra_state_attributes(self):
"""Return the camera state attributes."""
return {"file_path": self._file_path}
2 changes: 2 additions & 0 deletions custom_components/norwegiantide/const.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""Constants for NorwegianTide."""
from homeassistant.const import DEVICE_CLASS_TIMESTAMP, LENGTH_CENTIMETERS, TIME_HOURS

from .api import CONST_DIR_DEFAULT

# Base component constants
NAME = "Norwegian Tide"
DOMAIN = "norwegiantide"
Expand Down
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 09115ff

Please sign in to comment.