Add config flow to GPSD (#106196)

pull/109231/head
Jan Rieger 2024-01-31 18:38:14 +01:00 committed by GitHub
parent cd96fb381f
commit bbdb9b61c4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 257 additions and 46 deletions

View File

@ -481,6 +481,7 @@ omit =
homeassistant/components/google_cloud/tts.py
homeassistant/components/google_maps/device_tracker.py
homeassistant/components/google_pubsub/__init__.py
homeassistant/components/gpsd/__init__.py
homeassistant/components/gpsd/sensor.py
homeassistant/components/greenwave/light.py
homeassistant/components/growatt_server/__init__.py

View File

@ -507,7 +507,8 @@ build.json @home-assistant/supervisor
/tests/components/govee_ble/ @bdraco @PierreAronnax
/homeassistant/components/govee_light_local/ @Galorhallen
/tests/components/govee_light_local/ @Galorhallen
/homeassistant/components/gpsd/ @fabaff
/homeassistant/components/gpsd/ @fabaff @jrieger
/tests/components/gpsd/ @fabaff @jrieger
/homeassistant/components/gree/ @cmroche
/tests/components/gree/ @cmroche
/homeassistant/components/greeneye_monitor/ @jkeljo

View File

@ -1 +1,19 @@
"""The gpsd component."""
"""The GPSD integration."""
from __future__ import annotations
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
PLATFORMS: list[Platform] = [Platform.SENSOR]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up GPSD from a config entry."""
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@ -0,0 +1,57 @@
"""Config flow for GPSD integration."""
from __future__ import annotations
import socket
from typing import Any
from gps3.agps3threaded import GPSD_PORT as DEFAULT_PORT, HOST as DEFAULT_HOST
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Optional(CONF_HOST, default=DEFAULT_HOST): str,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
}
)
class GPSDConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for GPSD."""
VERSION = 1
async def async_step_import(self, import_data: dict[str, Any]) -> FlowResult:
"""Import a config entry from configuration.yaml."""
return await self.async_step_user(import_data)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
if user_input is not None:
self._async_abort_entries_match(user_input)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((user_input[CONF_HOST], user_input[CONF_PORT]))
sock.shutdown(2)
except OSError:
return self.async_abort(reason="cannot_connect")
port = ""
if user_input[CONF_PORT] != DEFAULT_PORT:
port = f":{user_input[CONF_PORT]}"
return self.async_create_entry(
title=user_input.get(CONF_NAME, f"GPS {user_input[CONF_HOST]}{port}"),
data=user_input,
)
return self.async_show_form(step_id="user", data_schema=STEP_USER_DATA_SCHEMA)

View File

@ -0,0 +1,3 @@
"""Constants for the GPSD integration."""
DOMAIN = "gpsd"

View File

@ -1,7 +1,8 @@
{
"domain": "gpsd",
"name": "GPSD",
"codeowners": ["@fabaff"],
"codeowners": ["@fabaff", "@jrieger"],
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/gpsd",
"iot_class": "local_polling",
"loggers": ["gps3"],

View File

@ -2,13 +2,17 @@
from __future__ import annotations
import logging
import socket
from typing import Any
from gps3.agps3threaded import AGPS3mechanism
from gps3.agps3threaded import (
GPSD_PORT as DEFAULT_PORT,
HOST as DEFAULT_HOST,
AGPS3mechanism,
)
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
@ -17,11 +21,15 @@ from homeassistant.const import (
CONF_NAME,
CONF_PORT,
)
from homeassistant.core import HomeAssistant
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
ATTR_CLIMB = "climb"
@ -29,9 +37,7 @@ ATTR_ELEVATION = "elevation"
ATTR_GPS_TIME = "gps_time"
ATTR_SPEED = "speed"
DEFAULT_HOST = "localhost"
DEFAULT_NAME = "GPS"
DEFAULT_PORT = 2947
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
@ -42,64 +48,74 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
)
def setup_platform(
async def async_setup_entry(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
config_entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up the GPSD component."""
name = config[CONF_NAME]
host = config[CONF_HOST]
port = config[CONF_PORT]
async_add_entities(
[
GpsdSensor(
config_entry.data[CONF_HOST],
config_entry.data[CONF_PORT],
config_entry.entry_id,
)
]
)
# Will hopefully be possible with the next gps3 update
# https://github.com/wadda/gps3/issues/11
# from gps3 import gps3
# try:
# gpsd_socket = gps3.GPSDSocket()
# gpsd_socket.connect(host=host, port=port)
# except GPSError:
# _LOGGER.warning('Not able to connect to GPSD')
# return False
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
sock.shutdown(2)
_LOGGER.debug("Connection to GPSD possible")
except OSError:
_LOGGER.error("Not able to connect to GPSD")
return
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Initialize gpsd import from config."""
async_create_issue(
hass,
HOMEASSISTANT_DOMAIN,
f"deprecated_yaml_{DOMAIN}",
is_fixable=False,
breaks_in_ha_version="2024.9.0",
severity=IssueSeverity.WARNING,
translation_key="deprecated_yaml",
translation_placeholders={
"domain": DOMAIN,
"integration_title": "GPSD",
},
)
add_entities([GpsdSensor(hass, name, host, port)])
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=config
)
)
class GpsdSensor(SensorEntity):
"""Representation of a GPS receiver available via GPSD."""
_attr_has_entity_name = True
_attr_name = None
def __init__(
self,
hass: HomeAssistant,
name: str,
host: str,
port: int,
unique_id: str,
) -> None:
"""Initialize the GPSD sensor."""
self.hass = hass
self._name = name
self._host = host
self._port = port
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, unique_id)},
entry_type=DeviceEntryType.SERVICE,
)
self._attr_unique_id = unique_id
self.agps_thread = AGPS3mechanism()
self.agps_thread.stream_data(host=self._host, port=self._port)
self.agps_thread.stream_data(host=host, port=port)
self.agps_thread.run_thread()
@property
def name(self) -> str:
"""Return the name."""
return self._name
@property
def native_value(self) -> str | None:
"""Return the state of GPSD."""

View File

@ -0,0 +1,19 @@
{
"config": {
"step": {
"user": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
"port": "[%key:common::config_flow::data::port%]"
},
"data_description": {
"host": "The hostname or IP address of GPSD."
}
}
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]",
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
}
}
}

View File

@ -203,6 +203,7 @@ FLOWS = {
"google_travel_time",
"govee_ble",
"govee_light_local",
"gpsd",
"gpslogger",
"gree",
"growatt_server",

View File

@ -2321,7 +2321,7 @@
"gpsd": {
"name": "GPSD",
"integration_type": "hub",
"config_flow": false,
"config_flow": true,
"iot_class": "local_polling"
},
"gpslogger": {

View File

@ -783,6 +783,9 @@ govee-ble==0.27.3
# homeassistant.components.govee_light_local
govee-local-api==1.4.1
# homeassistant.components.gpsd
gps3==0.33.3
# homeassistant.components.gree
greeclimate==1.4.1

View File

@ -0,0 +1 @@
"""Tests for the GPSD integration."""

View File

@ -0,0 +1,14 @@
"""Common fixtures for the GPSD tests."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock, None, None]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.gpsd.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry

View File

@ -0,0 +1,76 @@
"""Test the GPSD config flow."""
from unittest.mock import AsyncMock, patch
from gps3.agps3threaded import GPSD_PORT as DEFAULT_PORT
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.gpsd.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
HOST = "gpsd.local"
async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
with patch("socket.socket") as mock_socket:
mock_connect = mock_socket.return_value.connect
mock_connect.return_value = None
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: HOST,
},
)
await hass.async_block_till_done()
assert result2["type"] == FlowResultType.CREATE_ENTRY
assert result2["title"] == f"GPS {HOST}"
assert result2["data"] == {
CONF_HOST: HOST,
CONF_PORT: DEFAULT_PORT,
}
mock_setup_entry.assert_called_once()
async def test_connection_error(hass: HomeAssistant) -> None:
"""Test connection to host error."""
with patch("socket.socket") as mock_socket:
mock_connect = mock_socket.return_value.connect
mock_connect.side_effect = OSError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={CONF_HOST: "nonexistent.local", CONF_PORT: 1234},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "cannot_connect"
async def test_import(hass: HomeAssistant) -> None:
"""Test import step."""
with patch("homeassistant.components.gpsd.config_flow.socket") as mock_socket:
mock_connect = mock_socket.return_value.connect
mock_connect.return_value = None
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data={CONF_HOST: HOST, CONF_PORT: 1234, CONF_NAME: "MyGPS"},
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "MyGPS"
assert result["data"] == {
CONF_HOST: HOST,
CONF_NAME: "MyGPS",
CONF_PORT: 1234,
}