1 """Sensor for SigFox devices."""
3 from __future__
import annotations
6 from http
import HTTPStatus
9 from urllib.parse
import urljoin
12 import voluptuous
as vol
15 PLATFORM_SCHEMA
as SENSOR_PLATFORM_SCHEMA,
24 _LOGGER = logging.getLogger(__name__)
26 SCAN_INTERVAL = datetime.timedelta(seconds=30)
27 API_URL =
"https://backend.sigfox.com/api/"
28 CONF_API_LOGIN =
"api_login"
29 CONF_API_PASSWORD =
"api_password"
30 DEFAULT_NAME =
"sigfox"
32 PLATFORM_SCHEMA = SENSOR_PLATFORM_SCHEMA.extend(
34 vol.Required(CONF_API_LOGIN): cv.string,
35 vol.Required(CONF_API_PASSWORD): cv.string,
36 vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
44 add_entities: AddEntitiesCallback,
45 discovery_info: DiscoveryInfoType |
None =
None,
47 """Set up the sigfox sensor."""
48 api_login = config[CONF_API_LOGIN]
49 api_password = config[CONF_API_PASSWORD]
50 name = config[CONF_NAME]
52 sigfox =
SigfoxAPI(api_login, api_password)
56 devices = sigfox.devices
62 """Take an ms since epoch and return datetime string."""
63 return datetime.datetime.fromtimestamp(epoch_time).isoformat()
67 """Class for interacting with the SigFox API."""
70 """Initialise the API object."""
71 self.
_auth_auth = requests.auth.HTTPBasicAuth(api_login, api_password)
77 """Check API credentials are valid."""
78 url = urljoin(API_URL,
"devicetypes")
79 response = requests.get(url, auth=self.
_auth_auth, timeout=10)
80 if response.status_code != HTTPStatus.OK:
81 if response.status_code == HTTPStatus.UNAUTHORIZED:
82 _LOGGER.error(
"Invalid credentials for Sigfox API")
85 "Unable to login to Sigfox API, error code %s",
86 str(response.status_code),
88 raise ValueError(
"Sigfox integration not set up")
92 """Get a list of device types."""
93 url = urljoin(API_URL,
"devicetypes")
94 response = requests.get(url, auth=self.
_auth_auth, timeout=10)
95 return [device[
"id"]
for device
in json.loads(response.text)[
"data"]]
98 """Get the device_id of each device registered."""
100 for unique_type
in device_types:
101 location_url = f
"devicetypes/{unique_type}/devices"
102 url = urljoin(API_URL, location_url)
103 response = requests.get(url, auth=self.
_auth_auth, timeout=10)
104 devices_data = json.loads(response.text)[
"data"]
105 devices.extend(device[
"id"]
for device
in devices_data)
110 """Return the API authentication."""
111 return self.
_auth_auth
115 """Return the list of device_id."""
120 """Class for single sigfox device."""
123 """Initialise the device object."""
127 self.
_name_name = f
"{name}_{device_id}"
131 """Return the last message from a device."""
132 device_url = f
"devices/{self._device_id}/messages?limit=1"
133 url = urljoin(API_URL, device_url)
134 response = requests.get(url, auth=self.
_auth_auth, timeout=10)
135 data = json.loads(response.text)[
"data"][0]
136 payload = bytes.fromhex(data[
"data"]).decode(
"utf-8")
137 lat = data[
"rinfos"][0][
"lat"]
138 lng = data[
"rinfos"][0][
"lng"]
140 epoch_time = data[
"time"]
150 """Fetch the latest device message."""
156 """Return the HA name of the sensor."""
157 return self.
_name_name
161 """Return the payload of the last message."""
166 """Return other details about the last message."""
def check_credentials(self)
def get_device_types(self)
def __init__(self, api_login, api_password)
def get_devices(self, device_types)
def extra_state_attributes(self)
def get_last_message(self)
def __init__(self, device_id, auth, name)
def add_entities(account, async_add_entities, tracked)
def epoch_to_datetime(epoch_time)
None setup_platform(HomeAssistant hass, ConfigType config, AddEntitiesCallback add_entities, DiscoveryInfoType|None discovery_info=None)