Skip to content

Commit

Permalink
run on all push
Browse files Browse the repository at this point in the history
  • Loading branch information
jellespijker authored and github-actions[bot] committed Feb 9, 2021
1 parent 4e661bc commit 97f4a29
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 69 deletions.
1 change: 0 additions & 1 deletion .github/workflows/validation-and-formatting.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
name: "Validation And Formatting"
on:
push:
branches: [stable]
pull_request:
schedule:
- cron: '0 0 * * *'
Expand Down
10 changes: 4 additions & 6 deletions custom_components/ultimaker/__init__.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
"""Ultimaker printer integration"""
DOMAIN = 'ultimaker'
DOMAIN = "ultimaker"


def setup(hass, config):
"""Your controller/hub specific code."""
# Data that you want to share with your platforms
hass.data[DOMAIN] = {
'x': 0
}
hass.data[DOMAIN] = {"x": 0}

hass.helpers.discovery.load_platform('sensor', DOMAIN, {}, config)
hass.helpers.discovery.load_platform("sensor", DOMAIN, {}, config)

return True
return True
157 changes: 95 additions & 62 deletions custom_components/ultimaker/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,57 +16,77 @@
- hotend_1_temperature (optional)
- hotend_N_temperature (optional, N = hotend index starting at 1)
"""
import logging
import asyncio
import logging
from datetime import datetime, timedelta
from typing import Any, Dict, Optional

import aiohttp
import async_timeout

from datetime import timedelta, datetime
from typing import Optional, Dict, Any

import voluptuous as vol

from . import DOMAIN
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.typing import HomeAssistantType, StateType
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
CONF_HOST, CONF_SCAN_INTERVAL, CONF_SENSORS, TEMP_CELSIUS, CONF_NAME
CONF_HOST,
CONF_NAME,
CONF_SCAN_INTERVAL,
CONF_SENSORS,
TEMP_CELSIUS,
)
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.typing import HomeAssistantType, StateType
from homeassistant.util import Throttle

from . import DOMAIN

_LOGGER = logging.getLogger(__name__)

SENSOR_TYPES = {
'status': ['Printer status', '', 'mdi:printer-3d'],
'state': ['Print job state', '', 'mdi:printer-3d-nozzle'],
'progress': ['Print job progress', '%', 'mdi:progress-clock'],
'bed_temperature': ['Bed temperature', TEMP_CELSIUS, 'mdi:thermometer'],
'bed_temperature_target': ['Bed temperature target', TEMP_CELSIUS, 'mdi:thermometer'],
'hotend_1_temperature': ['Hotend 1 temperature', TEMP_CELSIUS, 'mdi:thermometer'],
'hotend_1_temperature_target': ['Hotend 1 temperature target', TEMP_CELSIUS, 'mdi:thermometer'],
'hotend_2_temperature': ['Hotend 2 temperature', TEMP_CELSIUS, 'mdi:thermometer'],
'hotend_2_temperature_target': ['Hotend 2 temperature target', TEMP_CELSIUS, 'mdi:thermometer'],
"status": ["Printer status", "", "mdi:printer-3d"],
"state": ["Print job state", "", "mdi:printer-3d-nozzle"],
"progress": ["Print job progress", "%", "mdi:progress-clock"],
"bed_temperature": ["Bed temperature", TEMP_CELSIUS, "mdi:thermometer"],
"bed_temperature_target": [
"Bed temperature target",
TEMP_CELSIUS,
"mdi:thermometer",
],
"hotend_1_temperature": ["Hotend 1 temperature", TEMP_CELSIUS, "mdi:thermometer"],
"hotend_1_temperature_target": [
"Hotend 1 temperature target",
TEMP_CELSIUS,
"mdi:thermometer",
],
"hotend_2_temperature": ["Hotend 2 temperature", TEMP_CELSIUS, "mdi:thermometer"],
"hotend_2_temperature_target": [
"Hotend 2 temperature target",
TEMP_CELSIUS,
"mdi:thermometer",
],
}

CONF_DECIMAL = 'decimal'

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_DECIMAL, default=2): cv.positive_int,
vol.Required(CONF_SENSORS, default=list(SENSOR_TYPES)):
vol.All(cv.ensure_list, [vol.In(SENSOR_TYPES)]),
})
CONF_DECIMAL = "decimal"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required(CONF_HOST): cv.string,
vol.Required(CONF_NAME): cv.string,
vol.Optional(CONF_DECIMAL, default=2): cv.positive_int,
vol.Required(CONF_SENSORS, default=list(SENSOR_TYPES)): vol.All(
cv.ensure_list, [vol.In(SENSOR_TYPES)]
),
}
)


MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=10)
BASE_URL = 'http://{0}/api/v1'
BASE_URL = "http://{0}/api/v1"


async def async_setup_platform(hass: HomeAssistantType, config, async_add_entities, discovery_info=None):
async def async_setup_platform(
hass: HomeAssistantType, config, async_add_entities, discovery_info=None
):
"""Setup the Ultimaker printer sensors"""
session = async_get_clientsession(hass)
data = UltimakerStatusData(session, config.get(CONF_HOST))
Expand All @@ -80,14 +100,21 @@ async def async_setup_platform(hass: HomeAssistantType, config, async_add_entiti
unit = SENSOR_TYPES[sensor][1]
icon = SENSOR_TYPES[sensor][2]

_LOGGER.debug(f"Adding Ultimaker printer sensor: {name}, {sensor_type}, {unit}, {icon}")
entities.append(UltimakerStatusSensor(data, name, sensor_type, unit, icon, config.get(CONF_DECIMAL)))
_LOGGER.debug(
f"Adding Ultimaker printer sensor: {name}, {sensor_type}, {unit}, {icon}"
)
entities.append(
UltimakerStatusSensor(
data, name, sensor_type, unit, icon, config.get(CONF_DECIMAL)
)
)

async_add_entities(entities, True)


class UltimakerStatusData(object):
"""Handle Ultimaker object and limit updates"""

def __init__(self, session, host):
if host:
self._url_printer = BASE_URL.format(host) + "/printer"
Expand All @@ -106,8 +133,8 @@ async def async_update(self):
self._data |= await self.fetch_data(self._url_print_job)
self._data |= await self.fetch_data(self._url_system)
except aiohttp.ClientError:
self._data = {'status': 'not connected'}
self._data['sampleTime'] = datetime.now()
self._data = {"status": "not connected"}
self._data["sampleTime"] = datetime.now()

async def fetch_data(self, url):
try:
Expand All @@ -117,9 +144,13 @@ async def fetch_data(self, url):
_LOGGER.warning(f"Printer {self._host} is offline")
raise err
except asyncio.TimeoutError:
_LOGGER.error(f" Timeout error occurred while polling ultimaker printer using url {url}")
_LOGGER.error(
f" Timeout error occurred while polling ultimaker printer using url {url}"
)
except Exception as err:
_LOGGER.error(f"Unknown error occurred while polling Ultimaker printer using {url} -> error: {err}")
_LOGGER.error(
f"Unknown error occurred while polling Ultimaker printer using {url} -> error: {err}"
)
return {}

try:
Expand All @@ -137,7 +168,9 @@ def latest_data(self):
class UltimakerStatusSensor(Entity):
"""Representation of a Ultimaker status sensor"""

def __init__(self, data: UltimakerStatusData, name, sensor_type, unit, icon, decimal):
def __init__(
self, data: UltimakerStatusData, name, sensor_type, unit, icon, decimal
):
"""Initialize the sensor."""
self._data = data
self._name = name
Expand Down Expand Up @@ -172,7 +205,7 @@ def unit_of_measurement(self) -> Optional[str]:
def device_state_attributes(self) -> Optional[Dict[str, Any]]:
attr = {}
if self._last_updated is not None:
attr['Last Updated'] = self._last_updated
attr["Last Updated"] = self._last_updated
return attr

async def async_update(self):
Expand All @@ -181,42 +214,42 @@ async def async_update(self):
data = self._data.latest_data

if data:
self._last_updated = data.get('sampleTime', None)
self._last_updated = data.get("sampleTime", None)

if self._type == 'status':
self._state = data.get('status', 'not connected')
if self._type == "status":
self._state = data.get("status", "not connected")

elif self._type == 'state':
self._state = data.get('state', None)
elif self._type == "state":
self._state = data.get("state", None)
if self._state:
self._state = self._state.replace('_', ' ')
self._state = self._state.replace("_", " ")

elif self._type == 'progress':
self._state = data.get('progress', 0)
elif self._type == "progress":
self._state = data.get("progress", 0)
if self._state:
self._state *= 100
self._state = self._state

elif 'bed' in self._type:
bed = data.get('bed', None)
if 'temperature' in self._type and bed:
temperature = bed.get('temperature', None)
elif "bed" in self._type:
bed = data.get("bed", None)
if "temperature" in self._type and bed:
temperature = bed.get("temperature", None)
if temperature:
if 'target' in self._type:
self._state = temperature.get('target', None)
if "target" in self._type:
self._state = temperature.get("target", None)
else:
self._state = temperature.get('current', None)
self._state = temperature.get("current", None)

elif 'hotend' in self._type:
head = data.get('heads', [None])[0]
elif "hotend" in self._type:
head = data.get("heads", [None])[0]
if head:
idx = int(self._type.split("_")[1]) - 1
extruder = head['extruders'][idx]
hot_end = extruder['hotend']
temperature = hot_end['temperature']
if 'target' in self._type:
self._state = temperature.get('target', None)
extruder = head["extruders"][idx]
hot_end = extruder["hotend"]
temperature = hot_end["temperature"]
if "target" in self._type:
self._state = temperature.get("target", None)
else:
self._state = temperature.get('current', None)
self._state = temperature.get("current", None)

_LOGGER.debug(f"Device: {self._type} State: {self._state}")

0 comments on commit 97f4a29

Please sign in to comment.