or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

auth.mdconfiguration.mdcore-system.mdentity-framework.mdhelpers.mdindex.mdintegration-framework.mdregistries.md

helpers.mddocs/

0

# Helper Utilities

1

2

Comprehensive collection of utility functions and classes for common Home Assistant development tasks including validation, templating, event handling, service management, and async operations.

3

4

## Capabilities

5

6

### Configuration Validation

7

8

Voluptuous schema helpers and validation functions for validating configuration data, user input, and service parameters.

9

10

```python { .api }

11

import homeassistant.helpers.config_validation as cv

12

13

def entity_id(value: Any) -> str:

14

"""Validate entity ID format.

15

16

Args:

17

value: Value to validate

18

19

Returns:

20

Validated entity ID

21

22

Raises:

23

vol.Invalid: If invalid entity ID

24

"""

25

26

def entity_ids(value: Any) -> list[str]:

27

"""Validate list of entity IDs.

28

29

Args:

30

value: Value to validate

31

32

Returns:

33

List of validated entity IDs

34

"""

35

36

def time(value: Any) -> datetime.time:

37

"""Validate time format.

38

39

Args:

40

value: Value to validate

41

42

Returns:

43

Validated time object

44

"""

45

46

def coordinates(value: Any) -> tuple[float, float]:

47

"""Validate GPS coordinates.

48

49

Args:

50

value: Value to validate

51

52

Returns:

53

Tuple of (latitude, longitude)

54

"""

55

56

def url(value: Any) -> str:

57

"""Validate URL format.

58

59

Args:

60

value: Value to validate

61

62

Returns:

63

Validated URL

64

"""

65

66

def port(value: Any) -> int:

67

"""Validate port number.

68

69

Args:

70

value: Value to validate

71

72

Returns:

73

Validated port number (1-65535)

74

"""

75

76

def positive_int(value: Any) -> int:

77

"""Validate positive integer.

78

79

Args:

80

value: Value to validate

81

82

Returns:

83

Validated positive integer

84

"""

85

86

def boolean(value: Any) -> bool:

87

"""Validate boolean value.

88

89

Args:

90

value: Value to validate

91

92

Returns:

93

Boolean value

94

"""

95

96

def string(value: Any) -> str:

97

"""Validate string value.

98

99

Args:

100

value: Value to validate

101

102

Returns:

103

String value

104

"""

105

106

def icon(value: Any) -> str:

107

"""Validate icon name.

108

109

Args:

110

value: Value to validate

111

112

Returns:

113

Validated icon name (mdi:*)

114

"""

115

116

def temperature_unit(value: Any) -> str:

117

"""Validate temperature unit.

118

119

Args:

120

value: Value to validate

121

122

Returns:

123

Validated temperature unit

124

"""

125

126

# Schema building helpers

127

PLATFORM_SCHEMA = vol.Schema({

128

vol.Required(CONF_PLATFORM): string,

129

}, extra=vol.ALLOW_EXTRA)

130

131

PLATFORM_SCHEMA_BASE = vol.Schema({})

132

133

SERVICE_SCHEMA = vol.Schema({}, extra=vol.ALLOW_EXTRA)

134

```

135

136

### Service Management

137

138

Utilities for registering services, handling service calls, and managing service-related functionality.

139

140

```python { .api }

141

async def async_register_admin_service(hass: HomeAssistant, domain: str,

142

service: str, service_func: Callable,

143

schema: dict = None) -> None:

144

"""Register admin service.

145

146

Args:

147

hass: Home Assistant instance

148

domain: Service domain

149

service: Service name

150

service_func: Service handler function

151

schema: Service schema

152

"""

153

154

async def async_extract_entity_ids(hass: HomeAssistant, service_call: ServiceCall,

155

expand_group: bool = True) -> list[str]:

156

"""Extract entity IDs from service call.

157

158

Args:

159

hass: Home Assistant instance

160

service_call: Service call

161

expand_group: Expand groups to individual entities

162

163

Returns:

164

List of entity IDs

165

"""

166

167

async def async_extract_entities(hass: HomeAssistant, service_call: ServiceCall,

168

expand_group: bool = True) -> list[Entity]:

169

"""Extract entities from service call.

170

171

Args:

172

hass: Home Assistant instance

173

service_call: Service call

174

expand_group: Expand groups to individual entities

175

176

Returns:

177

List of entity objects

178

"""

179

180

def verify_domain_control(hass: HomeAssistant, domain: str) -> None:

181

"""Verify domain control permissions.

182

183

Args:

184

hass: Home Assistant instance

185

domain: Domain to verify

186

187

Raises:

188

Unauthorized: If domain control not allowed

189

"""

190

191

async def entity_service_call(hass: HomeAssistant, platforms: list,

192

service_name: str, service_call: ServiceCall) -> None:

193

"""Call service on entity platforms.

194

195

Args:

196

hass: Home Assistant instance

197

platforms: List of entity platforms

198

service_name: Service to call

199

service_call: Service call data

200

"""

201

```

202

203

### Event Handling

204

205

Event tracking, state change monitoring, and time-based event scheduling utilities.

206

207

```python { .api }

208

async def async_track_state_change(hass: HomeAssistant, entity_ids: Union[str, list[str]],

209

action: Callable, from_state: str = None,

210

to_state: str = None) -> Callable:

211

"""Track state changes for entities.

212

213

Args:

214

hass: Home Assistant instance

215

entity_ids: Entity ID(s) to track

216

action: Function to call on state change

217

from_state: Previous state to match

218

to_state: New state to match

219

220

Returns:

221

Function to stop tracking

222

"""

223

224

async def async_track_time_interval(hass: HomeAssistant, action: Callable,

225

interval: timedelta) -> Callable:

226

"""Track time intervals.

227

228

Args:

229

hass: Home Assistant instance

230

action: Function to call at intervals

231

interval: Time interval

232

233

Returns:

234

Function to stop tracking

235

"""

236

237

async def async_track_utc_time_change(hass: HomeAssistant, action: Callable,

238

hour: int = None, minute: int = None,

239

second: int = None) -> Callable:

240

"""Track UTC time changes.

241

242

Args:

243

hass: Home Assistant instance

244

action: Function to call on time change

245

hour: Hour to trigger on

246

minute: Minute to trigger on

247

second: Second to trigger on

248

249

Returns:

250

Function to stop tracking

251

"""

252

253

async def async_call_later(hass: HomeAssistant, delay: float, action: Callable) -> Callable:

254

"""Call function after delay.

255

256

Args:

257

hass: Home Assistant instance

258

delay: Delay in seconds

259

action: Function to call

260

261

Returns:

262

Function to cancel call

263

"""

264

265

async def async_track_sunrise(hass: HomeAssistant, action: Callable,

266

offset: timedelta = None) -> Callable:

267

"""Track sunrise events.

268

269

Args:

270

hass: Home Assistant instance

271

action: Function to call at sunrise

272

offset: Time offset from sunrise

273

274

Returns:

275

Function to stop tracking

276

"""

277

278

async def async_track_sunset(hass: HomeAssistant, action: Callable,

279

offset: timedelta = None) -> Callable:

280

"""Track sunset events.

281

282

Args:

283

hass: Home Assistant instance

284

action: Function to call at sunset

285

offset: Time offset from sunset

286

287

Returns:

288

Function to stop tracking

289

"""

290

291

async def async_track_template(hass: HomeAssistant, template: Template,

292

action: Callable, variables: dict = None) -> Callable:

293

"""Track template value changes.

294

295

Args:

296

hass: Home Assistant instance

297

template: Template to track

298

action: Function to call on template change

299

variables: Template variables

300

301

Returns:

302

Function to stop tracking

303

"""

304

```

305

306

### Template System

307

308

Jinja2 template engine integration for dynamic content generation and evaluation.

309

310

```python { .api }

311

class Template:

312

"""Template wrapper for Jinja2 templates."""

313

314

def __init__(self, template: str, hass: HomeAssistant = None):

315

"""Initialize template.

316

317

Args:

318

template: Template string

319

hass: Home Assistant instance

320

"""

321

322

def render(self, variables: dict = None, **kwargs) -> str:

323

"""Render template.

324

325

Args:

326

variables: Template variables

327

**kwargs: Additional variables

328

329

Returns:

330

Rendered template string

331

"""

332

333

async def async_render(self, variables: dict = None, **kwargs) -> str:

334

"""Render template asynchronously.

335

336

Args:

337

variables: Template variables

338

**kwargs: Additional variables

339

340

Returns:

341

Rendered template string

342

"""

343

344

def ensure_valid(self) -> None:

345

"""Ensure template is valid.

346

347

Raises:

348

TemplateError: If template is invalid

349

"""

350

351

@property

352

def is_static(self) -> bool:

353

"""Return True if template is static."""

354

355

def render_complex(value: Any, variables: dict = None,

356

limited: bool = False) -> Any:

357

"""Render complex template data.

358

359

Args:

360

value: Value to render (may contain templates)

361

variables: Template variables

362

limited: Use limited template environment

363

364

Returns:

365

Rendered value

366

"""

367

368

def is_template_string(maybe_template: str) -> bool:

369

"""Check if string contains template syntax.

370

371

Args:

372

maybe_template: String to check

373

374

Returns:

375

True if string contains templates

376

"""

377

378

def extract_entities(template: str) -> set[str]:

379

"""Extract entity IDs from template.

380

381

Args:

382

template: Template string

383

384

Returns:

385

Set of entity IDs referenced in template

386

"""

387

388

# Template functions available in templates

389

def now() -> datetime:

390

"""Get current datetime in template."""

391

392

def utcnow() -> datetime:

393

"""Get current UTC datetime in template."""

394

395

def states(entity_id: str = None) -> Union[State, list[State]]:

396

"""Get entity state(s) in template."""

397

398

def is_state(entity_id: str, state: str) -> bool:

399

"""Check entity state in template."""

400

401

def is_state_attr(entity_id: str, attribute: str, value: Any) -> bool:

402

"""Check entity attribute in template."""

403

404

def state_attr(entity_id: str, attribute: str) -> Any:

405

"""Get entity attribute in template."""

406

407

def distance(lat1: float, lon1: float, lat2: float, lon2: float) -> float:

408

"""Calculate distance between coordinates in template."""

409

```

410

411

### Storage

412

413

Persistent storage utilities for integrations to store and retrieve configuration and state data.

414

415

```python { .api }

416

class Store:

417

"""Storage helper for integrations."""

418

419

def __init__(self, hass: HomeAssistant, version: int, key: str,

420

encoder: Callable = None, decoder: Callable = None):

421

"""Initialize store.

422

423

Args:

424

hass: Home Assistant instance

425

version: Storage version

426

key: Storage key

427

encoder: Custom encoder

428

decoder: Custom decoder

429

"""

430

431

async def async_load(self) -> dict:

432

"""Load data from storage.

433

434

Returns:

435

Stored data or None if not found

436

"""

437

438

async def async_save(self, data: dict) -> None:

439

"""Save data to storage.

440

441

Args:

442

data: Data to save

443

"""

444

445

async def async_remove(self) -> None:

446

"""Remove data from storage."""

447

```

448

449

### Typing Utilities

450

451

Type checking and validation utilities for Home Assistant development.

452

453

```python { .api }

454

def is_callback(func: Callable) -> bool:

455

"""Check if function is marked as callback.

456

457

Args:

458

func: Function to check

459

460

Returns:

461

True if function is callback

462

"""

463

464

def is_coroutine_function(func: Callable) -> bool:

465

"""Check if function is a coroutine.

466

467

Args:

468

func: Function to check

469

470

Returns:

471

True if function is coroutine

472

"""

473

474

def callback_wrapper(func: Callable) -> Callable:

475

"""Wrap function as callback.

476

477

Args:

478

func: Function to wrap

479

480

Returns:

481

Wrapped function

482

"""

483

```

484

485

### Network Utilities

486

487

Network-related utility functions for IP address validation, network discovery, and connectivity checking.

488

489

```python { .api }

490

def is_private(ip: str) -> bool:

491

"""Check if IP address is private.

492

493

Args:

494

ip: IP address to check

495

496

Returns:

497

True if IP is private

498

"""

499

500

def is_loopback(ip: str) -> bool:

501

"""Check if IP address is loopback.

502

503

Args:

504

ip: IP address to check

505

506

Returns:

507

True if IP is loopback

508

"""

509

510

def is_local(ip: str) -> bool:

511

"""Check if IP address is local.

512

513

Args:

514

ip: IP address to check

515

516

Returns:

517

True if IP is local

518

"""

519

520

def get_source_ip(target_ip: str) -> str:

521

"""Get source IP for connecting to target.

522

523

Args:

524

target_ip: Target IP address

525

526

Returns:

527

Source IP address

528

"""

529

530

async def async_get_source_ip(target_ip: str) -> str:

531

"""Get source IP asynchronously.

532

533

Args:

534

target_ip: Target IP address

535

536

Returns:

537

Source IP address

538

"""

539

```

540

541

## Types

542

543

```python { .api }

544

from typing import Any, Callable, Dict, List, Optional, Union

545

import voluptuous as vol

546

from datetime import datetime, timedelta

547

548

# Validation types

549

ValidatorType = Callable[[Any], Any]

550

SchemaType = vol.Schema

551

552

# Template types

553

TemplateType = Union[str, Template, None]

554

TemplateRenderType = Union[str, int, float, bool, None]

555

556

# Event tracking types

557

EntityIdType = Union[str, List[str]]

558

ActionType = Callable[[str, State, State], None]

559

TimeActionType = Callable[[datetime], None]

560

561

# Storage types

562

StorageDataType = Dict[str, Any]

563

StorageKeyType = str

564

565

# Network types

566

IPAddressType = str

567

PortType = int

568

```