first
This commit is contained in:
commit
b4a6d1165a
32 files changed
+534
No files matched your search
@@ -0,0 +1 @@
|
||||
.pytest_cache
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"mikestead.dotenv",
|
||||
"ms-python.python",
|
||||
"charliermarsh.ruff"
|
||||
]
|
||||
}
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"python.testing.pytestArgs": [
|
||||
"tests"
|
||||
],
|
||||
"python.testing.unittestEnabled": false,
|
||||
"python.testing.pytestEnabled": true
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
|
||||
services:
|
||||
homeassistant:
|
||||
image: ghcr.io/home-assistant/home-assistant:stable
|
||||
restart: unless-stopped
|
||||
privileged: true
|
||||
# environment:
|
||||
# TZ: MY_TIME_ZONE
|
||||
volumes:
|
||||
- ./custom_components:/config/custom_components
|
||||
# network_mode: host
|
||||
ports:
|
||||
- 8123:8123
|
||||
|
||||
# docker run -d \
|
||||
# --name homeassistant \
|
||||
# --privileged \
|
||||
# --restart=unless-stopped \
|
||||
# -e TZ=MY_TIME_ZONE \
|
||||
# -v /PATH_TO_YOUR_CONFIG:/config \
|
||||
# -v /run/dbus:/run/dbus:ro \
|
||||
# --network=host \
|
||||
# ghcr.io/home-assistant/home-assistant:stable
|
||||
Whitespace-only changes.
Binary file not shown.
@@ -0,0 +1,86 @@
|
||||
"""Example of a custom component exposing a service."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from functools import partial
|
||||
from homeassistant.const import CONF_API_KEY, CONF_URL, Platform, CONF_ENTITY_ID
|
||||
from homeassistant.core import (
|
||||
HomeAssistant,
|
||||
SupportsResponse,
|
||||
ServiceCall,
|
||||
ServiceResponse,
|
||||
HassJobType,
|
||||
)
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.helpers.entity_component import EntityComponent
|
||||
|
||||
from .const import DOMAIN, SERVICES_SEND_TEXT, PHONE_ENTRY, MESSAGE_ENTRY
|
||||
from .textbelt_api import TextbeltAPI
|
||||
from .schemas import SEND_TEXT_SCHEMA
|
||||
from .types import TextbeltConfigEntry, TextbeltData
|
||||
from .sensor import CreditBalanceSensor
|
||||
|
||||
log = logging.getLogger(DOMAIN)
|
||||
PLATFORMS = [Platform.SENSOR, Platform.NOTIFY]
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: TextbeltConfigEntry):
|
||||
hass.data[DOMAIN] = EntityComponent[CreditBalanceSensor](log, DOMAIN, hass)
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICES_SEND_TEXT,
|
||||
partial(send_text, hass=hass),
|
||||
schema=SEND_TEXT_SCHEMA,
|
||||
supports_response=SupportsResponse.OPTIONAL,
|
||||
job_type=HassJobType.Coroutinefunction,
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, config: TextbeltConfigEntry) -> bool:
|
||||
textbelt = TextbeltAPI(config.data[CONF_API_KEY], config.data[CONF_URL])
|
||||
config.runtime_data = TextbeltData(textbelt, config.data[PHONE_ENTRY])
|
||||
await hass.config_entries.async_forward_entry_setups(config, PLATFORMS)
|
||||
return True
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: TextbeltConfigEntry) -> bool:
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
loaded_entries = [
|
||||
entry
|
||||
for entry in hass.config_entries.async_entries(DOMAIN)
|
||||
if entry.state == ConfigEntryState.LOADED
|
||||
]
|
||||
if len(loaded_entries) == 1:
|
||||
hass.services.async_remove(DOMAIN, SERVICES_SEND_TEXT)
|
||||
|
||||
return unload_ok
|
||||
|
||||
|
||||
async def send_text(call: ServiceCall, hass: HomeAssistant) -> ServiceResponse:
|
||||
entity_ids = call.data[CONF_ENTITY_ID]
|
||||
message = call.data[MESSAGE_ENTRY]
|
||||
phone = call.data[PHONE_ENTRY]
|
||||
p: EntityComponent[CreditBalanceSensor] = hass.data[Platform.SENSOR]
|
||||
resp = {}
|
||||
success = 0
|
||||
for entity_id in entity_ids:
|
||||
e = p.get_entity(entity_id)
|
||||
if isinstance(e, CreditBalanceSensor):
|
||||
err, r = await e.textbelt.send_text(msg=message, phone=phone)
|
||||
if err is not None:
|
||||
log.warning(f"Failed to send text to {entity_id} due to {err}")
|
||||
resp[entity_id] = {"success": False, "error": err}
|
||||
else:
|
||||
success += 1
|
||||
resp[entity_id] = r
|
||||
else:
|
||||
log.warning(f"invalid entity {entity_id} cannot be used for text messages")
|
||||
if success == 0:
|
||||
raise HomeAssistantError(
|
||||
f"Failed to send text due to {resp}",
|
||||
translation_domain=DOMAIN,
|
||||
)
|
||||
return resp
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,30 @@
|
||||
from typing import Any
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.data_entry_flow import FlowResult
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
|
||||
from .const import DOMAIN
|
||||
from .schemas import USER_INPUT_SCHEMA
|
||||
|
||||
|
||||
class TextbeltFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
VERSION = 1
|
||||
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
|
||||
|
||||
async def async_step_user(
|
||||
self,
|
||||
user_input: dict[str, Any] | None = None,
|
||||
) -> FlowResult:
|
||||
errors = {}
|
||||
if user_input is not None:
|
||||
self.context["title_placeholders"] = {"name": user_input[CONF_API_KEY]}
|
||||
return self.async_create_entry(title=DOMAIN, data=user_input)
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=USER_INPUT_SCHEMA,
|
||||
errors=errors,
|
||||
description_placeholders={
|
||||
k.schema: k.description for k in USER_INPUT_SCHEMA.schema.keys()
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,4 @@
|
||||
DOMAIN = "ha_textbelt"
|
||||
SERVICES_SEND_TEXT = "send_text"
|
||||
PHONE_ENTRY = "phone"
|
||||
MESSAGE_ENTRY = "message"
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"domain": "ha_textbelt",
|
||||
"name": "Textbelt SMS",
|
||||
"codeowners": [],
|
||||
"config_flow": true,
|
||||
"dependencies": [],
|
||||
"documentation": "",
|
||||
"integration_type": "service",
|
||||
"iot_class": "local_polling",
|
||||
"loggers": [
|
||||
"textbelt"
|
||||
],
|
||||
"requirements": [],
|
||||
"version": "0.1.0"
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import logging
|
||||
|
||||
from homeassistant.components.notify import NotifyEntity, NotifyEntityFeature
|
||||
from homeassistant.core import (
|
||||
HomeAssistant,
|
||||
)
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from .const import DOMAIN
|
||||
from .textbelt_api import TextbeltAPI
|
||||
from .types import TextbeltConfigEntry
|
||||
|
||||
log = logging.getLogger(DOMAIN)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: TextbeltConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
notifier = SendTextMessage(
|
||||
name=entry.runtime_data.phone,
|
||||
phone_number=entry.runtime_data.phone,
|
||||
textbelt=entry.runtime_data.client,
|
||||
)
|
||||
async_add_entities([notifier])
|
||||
|
||||
|
||||
class SendTextMessage(NotifyEntity):
|
||||
_attr_supported_features = NotifyEntityFeature.TITLE
|
||||
_attr_name = "Send Text via Textbelt"
|
||||
_attr_has_entity_name = True
|
||||
_attr_icon = "mdi:cellphone-charging"
|
||||
|
||||
def __init__(self, name: str, phone_number: str, textbelt: TextbeltAPI) -> None:
|
||||
super().__init__()
|
||||
self.phone_number = phone_number
|
||||
self.textbelt = textbelt
|
||||
self._attr_name += f" ({name})"
|
||||
self._attr_unique_id = "_".join(
|
||||
[
|
||||
DOMAIN,
|
||||
"notify",
|
||||
name,
|
||||
]
|
||||
)
|
||||
|
||||
async def async_send_message(self, message: str, **kwargs) -> None:
|
||||
"""Send a message."""
|
||||
resp = await self._send_text(self.phone_number, message=message)
|
||||
self._attr_state = resp["textId"]
|
||||
return resp
|
||||
|
||||
async def _send_text(self, phone: str, message: str):
|
||||
err, resp = await self.textbelt.send_text(
|
||||
msg=message,
|
||||
phone=phone,
|
||||
)
|
||||
if err is None:
|
||||
return resp
|
||||
else:
|
||||
raise HomeAssistantError(err, translation_domain=DOMAIN)
|
||||
@@ -0,0 +1,32 @@
|
||||
import voluptuous as vol
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_ENTITY_ID
|
||||
from .const import PHONE_ENTRY, MESSAGE_ENTRY
|
||||
|
||||
USER_INPUT_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Optional(
|
||||
PHONE_ENTRY,
|
||||
): cv.string,
|
||||
vol.Required(
|
||||
CONF_API_KEY,
|
||||
): cv.string,
|
||||
vol.Optional(
|
||||
CONF_URL,
|
||||
default="https://textbelt.com/",
|
||||
): cv.string,
|
||||
}
|
||||
)
|
||||
|
||||
SEND_TEXT_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(
|
||||
MESSAGE_ENTRY,
|
||||
): cv.string,
|
||||
vol.Required(
|
||||
PHONE_ENTRY,
|
||||
): cv.string,
|
||||
},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Platform for sensor integration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorDeviceClass,
|
||||
SensorEntity,
|
||||
SensorStateClass,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
|
||||
from .textbelt_api import TextbeltAPI
|
||||
from .types import TextbeltConfigEntry
|
||||
from .const import DOMAIN
|
||||
|
||||
log = logging.getLogger(DOMAIN)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: TextbeltConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
sensor = CreditBalanceSensor(
|
||||
name=entry.runtime_data.phone,
|
||||
phone_number=entry.runtime_data.phone,
|
||||
textbelt=entry.runtime_data.client,
|
||||
)
|
||||
async_add_entities([sensor], True)
|
||||
|
||||
|
||||
class CreditBalanceSensor(SensorEntity):
|
||||
_attr_name = "Credit Balance for API KEY"
|
||||
_attr_icon = "mdi:credit-card-multiple"
|
||||
_attr_device_class = SensorDeviceClass.MONETARY
|
||||
_attr_state_class = SensorStateClass.TOTAL
|
||||
_attr_unit_of_measurement = "msgs"
|
||||
_attr_should_poll = True
|
||||
|
||||
def __init__(self, name: str, phone_number: str, textbelt: TextbeltAPI) -> None:
|
||||
super().__init__()
|
||||
self.textbelt = textbelt
|
||||
self.phone_number = phone_number
|
||||
self._attr_name += f" ({name})"
|
||||
self._attr_unique_id = "_".join(
|
||||
[
|
||||
DOMAIN,
|
||||
"credit_balance",
|
||||
name,
|
||||
]
|
||||
)
|
||||
|
||||
async def async_update(self) -> None:
|
||||
err, resp = await self.textbelt.get_balance()
|
||||
if err is None:
|
||||
self._attr_available = True
|
||||
self._attr_native_value = resp
|
||||
else:
|
||||
self._attr_available = False
|
||||
self._attr_native_value = 0
|
||||
raise HomeAssistantError(f"Textbelt ERROR {err}", translation_domain=DOMAIN)
|
||||
@@ -0,0 +1,16 @@
|
||||
send_text:
|
||||
target:
|
||||
entity:
|
||||
domain: sensor
|
||||
integration: ha_textbelt
|
||||
fields:
|
||||
phone:
|
||||
required: true
|
||||
example: "18888888"
|
||||
selector:
|
||||
text:
|
||||
message:
|
||||
required: true
|
||||
example: "Hello World"
|
||||
selector:
|
||||
text:
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"description": "Setup intergration with textbelt!",
|
||||
"data": {
|
||||
"name": "Name",
|
||||
"api_key": "[%key:common::config_flow::data::api_key%]",
|
||||
"url": "[%key:common::config_flow::data::url%]"
|
||||
},
|
||||
"data_description": {
|
||||
"api_key": "The textbelt api key (can be found here https://textbelt.com/)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {},
|
||||
"abort": {}
|
||||
},
|
||||
"services": {
|
||||
"send_text": {
|
||||
"name": "Send Text",
|
||||
"description": "Send text message with textbelt",
|
||||
"fields": {
|
||||
"phone": {
|
||||
"name": "Phone Number",
|
||||
"description": "Phone to where we send the text message."
|
||||
},
|
||||
"message": {
|
||||
"name": "[%key:common::config_flow::data::message%]",
|
||||
"description": "Text message we want to send."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import httpx
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
from typing import NamedTuple
|
||||
|
||||
ErrorStr = str
|
||||
ApiKey = str
|
||||
|
||||
|
||||
class QuotaState(NamedTuple):
|
||||
quota: int | None
|
||||
last_update: datetime
|
||||
last_error: ErrorStr | None
|
||||
|
||||
|
||||
_quotas: dict[ApiKey, QuotaState | None] = {}
|
||||
|
||||
|
||||
class TextbeltAPI:
|
||||
def __init__(self, key: ApiKey, base_url: str = "https://textbelt.com/") -> None:
|
||||
self.key = key
|
||||
self.client = httpx.AsyncClient(base_url=base_url)
|
||||
_quotas[key] = _quotas.get(key, None)
|
||||
|
||||
@property
|
||||
def quota(self):
|
||||
return _quotas.get(self.key, None)
|
||||
|
||||
@quota.setter
|
||||
def quota(self, value: QuotaState):
|
||||
_quotas[self.key] = value
|
||||
|
||||
async def get_balance(self) -> tuple[ErrorStr, None] | tuple[None, int]:
|
||||
if self.quota is not None:
|
||||
if self.quota.quota is not None:
|
||||
if datetime.now() - self.quota.last_update < timedelta(minutes=30):
|
||||
return self.quota.last_error, self.quota.quota
|
||||
elif datetime.now() - self.quota.last_update < timedelta(minutes=10):
|
||||
return self.quota.last_error, self.quota.quota
|
||||
err, resp = await self._get_balance()
|
||||
if err is None:
|
||||
self.quota = QuotaState(resp, datetime.now(), None)
|
||||
else:
|
||||
self.quota = QuotaState(None, datetime.now(), err)
|
||||
return self.quota.last_error, self.quota.quota
|
||||
|
||||
async def _get_balance(self) -> tuple[ErrorStr, None] | tuple[None, int]:
|
||||
resp = await self.client.get(f"/quota/{self.key}")
|
||||
if resp.status_code == HTTPStatus.OK:
|
||||
data = resp.json()
|
||||
if data["success"]:
|
||||
return None, data["quotaRemaining"]
|
||||
return resp.text, None
|
||||
return f"Unexpected status code = {resp.status_code} data = {resp.text}", None
|
||||
|
||||
async def send_text(
|
||||
self,
|
||||
msg: str,
|
||||
phone: str,
|
||||
) -> tuple[ErrorStr, None] | tuple[None, dict]:
|
||||
resp = await self.client.post(
|
||||
"/text",
|
||||
json={
|
||||
"phone": phone,
|
||||
"message": msg,
|
||||
"key": self.key,
|
||||
},
|
||||
)
|
||||
if resp.status_code == HTTPStatus.OK:
|
||||
data = resp.json()
|
||||
if data["success"]:
|
||||
if data.get("quotaRemaining", None) is not None:
|
||||
self.quota = QuotaState(
|
||||
data["quotaRemaining"], datetime.now(), None
|
||||
)
|
||||
return None, data
|
||||
return data["error"], None
|
||||
return f"Unexpected status code = {resp.status_code} data = {resp.text}", None
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Enter you textbelt information",
|
||||
"data": {
|
||||
"name": "Name",
|
||||
"api_key": "API Key",
|
||||
"url": "URL for Textbelt"
|
||||
},
|
||||
"data_description": {
|
||||
"name": "Name to remember the API KEY by (defaults to a random string).",
|
||||
"api_key": "The textbelt api key (can be found here https://textbelt.com/)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"send_text": {
|
||||
"name": "Send Text",
|
||||
"description": "Send text message with textbelt",
|
||||
"fields": {
|
||||
"phone": {
|
||||
"name": "Phone Number",
|
||||
"description": "Phone to where we send the text message."
|
||||
},
|
||||
"message": {
|
||||
"name": "Text Message",
|
||||
"description": "Text message we want to send."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
|
||||
from .textbelt_api import TextbeltAPI
|
||||
|
||||
|
||||
@dataclass
|
||||
class TextbeltData:
|
||||
"""Adguard data type."""
|
||||
|
||||
client: TextbeltAPI
|
||||
phone: str
|
||||
|
||||
|
||||
type TextbeltConfigEntry = ConfigEntry[TextbeltData]
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"name": "Textbelt SMS API",
|
||||
"homeassistant": "2024.6.4",
|
||||
"render_readme": true
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pytest
|
||||
pytest-cov
|
||||
pytest-homeassistant-custom-component
|
||||
Binary file not shown.
@@ -0,0 +1,10 @@
|
||||
"""Test component setup."""
|
||||
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from custom_components.ha_textbelt.const import DOMAIN
|
||||
|
||||
|
||||
async def test_async_setup(hass):
|
||||
"""Test the component gets setup."""
|
||||
assert await async_setup_component(hass, DOMAIN, {}) is True
|
||||
Reference in new issue
Block a user