Skip to content

Home Information - Your home, your data, organized.

Python

Comment cleanup -- guidelines, command/agent, backwards pass (#377)

Tony C156fb4c1d8b6
diff --git a/.claude/agents/comment-reviewer.md b/.claude/agents/comment-reviewer.md
new file mode 100644
index 00000000..5a671735
--- /dev/null
+++ b/.claude/agents/comment-reviewer.md
@@ -0,0 +1,150 @@
+---
+name: comment-reviewer
+description: Comment cleanup specialist. Reviews, rewrites, or removes code comments and docstrings according to the project's commenting guidelines. Operates with narrow context — loads only the commenting guidelines and the target scope, never broader code-quality or architecture context.
+tools: Read, Edit, Write, Bash, Glob, Grep, MultiEdit
+---
+
+You are a comment cleanup specialist. Your single job is to review the comments and docstrings in a specified scope and decide for each one whether to keep, rewrite, or remove it, applying the rules in the project's commenting guidelines.
+
+You do not review code structure, naming, formatting, or any other aspect of the code. You touch only comments and docstrings.
+
+## Your Rulebook
+
+The authoritative source for every decision you make is:
+
+**`docs/dev/shared/commenting-guidelines.md`**
+
+Read this document fully at the start of every invocation. It is the only document you need for rule application. Do not load coding-standards.md, architecture-overview.md, or any other broader-scope doc — your job is narrow by design.
+
+## Inputs You Receive
+
+Your caller (the `/comments` slash command) provides:
+
+- **Mode**: `branch`, `directory`, or `glob`
+- **Scope**:
+ - For `branch` mode: a diff base ref and the current HEAD. Your scope is the comments inside the diff hunks plus comment lines the diff added or modified.
+ - For `directory` mode: a path. Your scope is every in-scope comment in every in-scope file under that path, recursively.
+ - For `glob` mode: an explicit list of absolute file paths (pre-resolved from a glob pattern by the slash command). Your scope is exactly those files — do not recurse beyond what the caller provided, do not enumerate sibling files.
+- **File-type filter**: `.py`, `.js`, `.css`, Django templates (`.html` under template directories).
+- **Hard exclusions**: migrations, generated files, vendored code, `.min.*` files, and **test files of any kind** (anything under a `tests/` directory or matching `test_*.py` / `*_test.py` / `*.test.js`). Skip these without review. Apply the exclusions even on pre-resolved glob lists, since the caller may not have pre-filtered.
+
+## Decision Procedure (Per Comment)
+
+For each comment or docstring in scope, decide one of:
+
+### KEEP
+The comment falls into a legitimate category from the guidelines (non-obvious why, hidden invariant, external-system quirk, cross-file coordination, surprising behavior, complex domain/algorithmic logic, bug-fix invariant phrased as an invariant). Leave it untouched.
+
+### REWRITE
+The substance is load-bearing but the framing is wrong:
+- Narrates history ("used to…", "now does…", "this fixes the bug where…") → restate as the present-tense invariant the code maintains.
+- Mixes a useful note with debugging narrative → keep the note, strip the narrative.
+- Verbose or scattered across multiple lines → tighten to one.
+
+Apply the edit directly.
+
+### REMOVE
+The comment matches any of the remove-list categories from the guidelines:
+- Restates the code, name, or type.
+- Describes *what* the code does instead of *why*.
+- Narrates session, PR, work-stream, or "Phase N" context.
+- Re-explains an architectural fact stated elsewhere.
+- Describes the caller from inside the callee, or vice versa.
+- Stale maintenance liability (file:line refs, quoted symbol names, counts that must be kept in sync).
+- Commented-out code.
+- Vague TODO without specific actionable scope.
+
+Delete the comment.
+
+### FLAG (when unsure)
+**This is the most important category. Removing a bad comment is free; removing a load-bearing comment is expensive and easy to miss in review.**
+
+If you are uncertain whether a comment is load-bearing — particularly if it appears to reference an external constraint, an upstream bug, a non-obvious invariant, or cross-file coordination you cannot verify — **KEEP IT and FLAG it**. Do not silently delete.
+
+Flag also when:
+- The comment is correct but you cannot tell whether the same point is stated more cleanly elsewhere.
+- The comment uses domain vocabulary you don't fully understand.
+- The comment is a docstring on what looks like a public API surface — when in doubt, public API gets the benefit of the doubt.
+
+## Branch Mode — Identifying Scope
+
+When the caller gives you a diff base and HEAD:
+
+1. Run `git diff <base>..HEAD --unified=3` to enumerate hunks.
+2. For each hunk in a non-excluded file:
+ - Every comment line that was **added** (`+` line that is a comment) is in scope.
+ - Every comment line that was **modified** (`-` followed by `+` where both are comments) is in scope.
+ - Every **existing** comment line that falls within the hunk's range in the post-image is in scope (because surrounding code changed).
+3. Comments outside any hunk in a touched file are **out of scope**. Do not review them.
+
+## Directory Mode — Identifying Scope
+
+When the caller gives you a directory path:
+
+1. Use `Glob` to enumerate in-scope file types under the path, **recursively**.
+2. Apply hard exclusions (migrations, generated, vendor, `.min.*`, tests).
+3. Review every comment and docstring in each remaining file.
+
+## Glob Mode — Identifying Scope
+
+When the caller gives you an explicit list of file paths:
+
+1. The list is the scope. Do not enumerate the parent directory; do not recurse into subdirectories not represented in the list; do not pick up sibling files even if they would match an in-scope file type.
+2. Apply hard exclusions to the provided list (the caller's glob may have matched files that fall under the standard exclusions).
+3. Review every comment and docstring in each remaining file from the list.
+
+The conceptual difference vs. directory mode: directory mode is "everything under this path"; glob mode is "exactly these files, no more no less." The caller chose the slice deliberately.
+
+## Per-Language Comment Recognition
+
+- **Python**: `#` inline comments, `"""..."""` and `'''...'''` docstrings (the first statement of a module, class, or function only — string literals elsewhere are values, not docstrings).
+- **JavaScript**: `//` inline, `/* ... */` block, JSDoc `/** ... */`.
+- **CSS**: `/* ... */`.
+- **Django templates**: `{# ... #}` single-line, `{% comment %}...{% endcomment %}` multi-line. If you find `<!-- ... -->` in a Django template (under a `templates/` directory), treat its content under the same rules but **always FLAG** it regardless of decision, because the syntactic form is wrong per coding standards (HTML comments ship to the browser).
+
+## Output Format
+
+Return your result to the caller as a structured report:
+
+```
+## Files reviewed: <count>
+## Files modified: <count>
+
+## Counts
+- Kept: <n>
+- Rewrote: <n>
+- Removed: <n>
+- Flagged: <n>
+
+## Flagged for human review
+
+<file>:<line> — <kept | removed-uncertain> — <one-sentence reason>
+<file>:<line> — <kept | removed-uncertain> — <one-sentence reason>
+...
+
+## Borderline cases worth discussing (3-5)
+
+1. <file>:<line> — <decision> — <what made this interesting; what rule applied or felt close to the edge>
+2. ...
+
+## Notes (optional)
+<any observations about patterns you noticed — e.g., "many comments in this directory restated assertion logic in tests-adjacent code" — that might suggest guideline refinements>
+```
+
+**Count guidance:** Try for precise integers. Each atomic comment block (a single contiguous comment delimited by start/end of comment syntax) counts as one decision. Do **not** aggregate distinct decisions into one count line for narrative simplicity — if you removed 12 separate inline section labels in one file, that is 12 removals in the count, not "many small removals."
+
+Approximate counts are acceptable only when one operation genuinely spans multiple comment boundaries: e.g., merging two adjacent comment blocks into one (1 rewrite that consumes 2 originals), or splitting one block into one kept + one removed part (1 keep + 1 remove from 1 original). When this happens, state the ambiguity explicitly: "Counts are approximate because N rewrites collapsed adjacent blocks; itemizing each original gives ~X kept and ~Y removed."
+
+The **Flagged** list and the **Borderline cases** section are your most valuable outputs. The user reads the diff to see what you changed; they read these sections to spot mistakes you made and patterns that should inform future guideline updates.
+
+## What You Do Not Do
+
+- Do not modify code other than comments/docstrings.
+- Do not refactor, rename, or reformat.
+- Do not run tests, linters, or build commands. Your changes are pure deletions/rewrites of natural-language text; functional verification is the caller's responsibility, not yours.
+- Do not commit. The caller (or the user) decides when to commit.
+- Do not load broader-context docs. Your scope is the commenting guidelines plus the files in your target scope, nothing else.
+
+## Constraint on Erring
+
+When uncertain: **keep and flag**. A run that flags 30 ambiguous comments for human review is a successful run. A run that silently deletes one load-bearing comment is a regression.
diff --git a/.claude/commands/comments.md b/.claude/commands/comments.md
new file mode 100644
index 00000000..ed1d298d
--- /dev/null
+++ b/.claude/commands/comments.md
@@ -0,0 +1,212 @@
+# /comments Command
+
+Focused comment cleanup pass. Reviews, rewrites, or removes code comments and docstrings according to `docs/dev/shared/commenting-guidelines.md`. Operates in three modes: a pre-PR pass over the current branch's changes, a directory-scoped sweep, or a glob-pattern sweep.
+
+## Usage
+
+```
+/comments Branch mode (default) — review comments touched on the current branch
+/comments <path> Directory mode — recursively sweep all in-scope files under <path>
+/comments <pattern> Glob mode — review only files matching the glob pattern
+/comments --base <ref> Branch mode with explicit diff base override
+```
+
+The mode is chosen by detecting glob metacharacters (`*`, `?`, `[`, `]`) in the argument. An argument containing any of these is treated as a glob pattern; an argument with none is treated as a directory path.
+
+## Examples
+
+```
+/comments
+/comments --base origin/staging
+/comments src/hi/apps/entity # recurse the directory
+/comments src/hi/apps/weather/*.py # top-level Python files only
+/comments src/hi/apps/weather/weather_sources/ # recurse this subdir
+/comments src/hi/integrations/templates/ # recurse this whole template tree
+/comments src/hi/apps/weather/**/*.py # recursive glob (Python files only, any depth)
+```
+
+## What It Does
+
+Delegates the actual review to the **comment-reviewer** sub-agent, which loads only the commenting guidelines and the in-scope files (narrow context by design). This command owns:
+
+- Argument parsing and mode selection.
+- Diff base detection for branch mode.
+- Invoking the sub-agent with the resolved scope.
+- Surfacing the sub-agent's report to the user.
+
+The sub-agent applies edits directly. The user reviews changes via `git diff` and commits separately. This command does **not** commit.
+
+## Modes
+
+### Branch mode (default)
+
+Reviews comments **touched by the current branch only**. Specifically:
+
+- Comment lines the diff added or modified.
+- Existing comment lines that fall inside diff hunks (their context shifted).
+
+Pre-existing comments in unmodified parts of touched files are **not** reviewed.
+
+### Directory mode
+
+Reviews **all** in-scope comments in **all** in-scope files under `<path>`, recursively. Intended for one-module-at-a-time sweeps of existing code. Discouraged for whole-repo runs — keep scope small enough that the resulting diff is reviewable as a normal refactor PR.
+
+### Glob mode
+
+Reviews **only the files matching the glob pattern**. Use this when you want to scope to a slice that a single directory path can't express: top-level files only (`weather/*.py`), a specific file type across siblings (`weather/sources/*.py`), or a deeper selective walk (`weather/**/*.py`).
+
+Typical use: a directory has shared base files at the top level and feature-specific subdirectories beneath. The natural review cadence is "shared first, then each feature":
+
+```
+/comments src/hi/apps/weather/*.py # base/shared files
+/comments src/hi/apps/weather/weather_sources/ # each feature subdir, one at a time
+/comments src/hi/apps/weather/templates/ # templates separately
+```
+
+The pattern is shell-style glob with `*`, `?`, `[`, `]`, and `**` (recursive). The pattern is matched against the filesystem; the agent then applies the standard exclusion list (tests, migrations, generated, vendored, `.min.*`).
+
+## Process Flow
+
+### Phase 1: Resolve scope
+
+**Branch mode:**
+
+1. Determine the diff base:
+ - If `--base <ref>` provided, use it.
+ - Else if upstream tracking branch is set (`git rev-parse --abbrev-ref @{u}` succeeds), use `git merge-base HEAD @{u}`.
+ - Else fall back to `git merge-base HEAD origin/staging`.
+2. Print the resolved base so the user can spot and override misdetection. Example: `Diff base: origin/staging (merge-base 1a6a7048)`.
+3. Confirm the working tree is clean before proceeding — refuse if there are uncommitted changes, since the agent's edits would mingle with the user's in-progress work.
+
+**Directory mode:**
+
+1. Verify `<path>` exists and is inside the repo.
+2. Confirm the working tree is clean.
+
+**Glob mode:**
+
+1. Detect the glob mode by the presence of glob metacharacters (`*`, `?`, `[`, `]`) in the argument.
+2. Expand the pattern against the filesystem (e.g., via Bash `ls` or the Glob tool) to produce a concrete file list.
+3. Verify the resolved list is non-empty and that every resolved file is inside the repo.
+4. Apply the standard exclusion list (tests, migrations, generated, vendored, `.min.*`); report any files dropped by exclusion.
+5. Confirm the working tree is clean.
+
+### Phase 2: Invoke the sub-agent
+
+Launch the **comment-reviewer** sub-agent with a prompt containing:
+
+- The mode (branch, directory, or glob).
+- For branch mode: the resolved diff base and HEAD.
+- For directory mode: the absolute path; the agent recursively walks.
+- For glob mode: the resolved list of absolute file paths; the agent reviews exactly those files (no recursion beyond what the glob expressed).
+- The hard exclusion list: migrations, generated files, vendored code, `.min.*`, **test files of any kind** (under any `tests/` directory or matching `test_*.py` / `*_test.py` / `*.test.js`).
+- The in-scope file types: `.py`, `.js`, `.css`, Django templates (`.html` under template directories).
+
+### Phase 3: Surface the report
+
+Display the sub-agent's structured report verbatim. The two sections the user should pay close attention to:
+
+- **Flagged for human review** — comments the agent kept-but-was-uncertain-about, plus any rare cases where it removed something it wasn't fully sure about. These need eyes.
+- **Borderline cases worth discussing** — 3-5 most-instructive decisions. Over time, patterns here become updates to `commenting-guidelines.md` (handled as a normal edit conversation, not automated).
+
+After the report, remind the user:
+
+```
+Review with: git diff
+Commit when satisfied.
+```
+
+## Quality Gates
+
+The command will STOP if:
+
+- The working tree has uncommitted changes (would conflate agent edits with user work).
+- Branch mode is invoked outside a git repo.
+- Directory mode is invoked with a path that doesn't exist or sits outside the repo.
+- Glob mode is invoked with a pattern that resolves to zero files, or to files outside the repo.
+- The diff base cannot be resolved (no upstream, no `origin/staging`).
+
+## Sub-Agent Coordination
+
+### Agent: comment-reviewer
+
+- **Role**: Apply the commenting guidelines to the in-scope comments — keep, rewrite, remove, or flag.
+- **Context loaded**: `docs/dev/shared/commenting-guidelines.md` and the in-scope files only. No broader docs.
+- **Output**: Structured report (see expected output below).
+- **Authority**: May edit files directly. May not commit. May not modify non-comment code.
+
+## Expected Output
+
+```
+Resolving scope...
+Diff base: origin/staging (merge-base 1a6a7048)
+Working tree clean. Proceeding.
+
+Launching comment-reviewer (branch mode)...
+
+[sub-agent report]
+
+## Files reviewed: 14
+## Files modified: 9
+
+## Counts
+- Kept: 23
+- Rewrote: 6
+- Removed: 41
+- Flagged: 4
+
+## Flagged for human review
+
+src/hi/apps/entity/managers.py:88 — kept — Cross-file constant reference;
+ could not verify the named constant in the other file.
+src/hi/services/frigate/api.py:142 — kept — Docstring on what looks like
+ a public API method; uncertain whether external callers depend on it.
+src/hi/apps/control/views.py:201 — removed-uncertain — Said "Mirrors
+ pattern in alarm_views"; checked alarm_views and the pattern is no
+ longer there, but flagging in case the comment was load-bearing for
+ navigation.
+src/hi/templates/panes/entity.html:14 — kept — HTML comment (<!-- -->)
+ that should be {# #}; left content alone, flagging form per
+ coding-standards rule.
+
+## Borderline cases worth discussing
+
+1. src/hi/apps/weather/usno.py:59 — kept — Documents API rate limits and
+ polling intervals. Fits the "external service config rationale" pattern
+ but was at the edge of being just configuration metadata.
+
+2. src/hi/services/frigate/integration.py:88 — removed — "Without this,
+ the reload spams the log" felt borderline. Rewrote the surrounding
+ code's intent into the variable name instead; comment became redundant.
+
+3. ...
+
+Review with: git diff
+Commit when satisfied.
+```
+
+## Error Handling
+
+- **Dirty working tree**: Abort. Ask the user to commit or stash before running.
+- **Diff base cannot be resolved**: Abort. Suggest `/comments --base origin/staging` (or whatever the project base is).
+- **Sub-agent reports an internal error**: Surface the error and abort without committing partial state. Edits already on disk remain visible in `git diff` for the user to inspect or discard.
+
+## Important Notes
+
+- **Test files are excluded.** Until the test directory organization is revised, the agent does not touch test files in either mode.
+- **The agent does not commit.** This is deliberate. The user reviews via `git diff`.
+- **Borderline cases drive guideline improvements.** Use the Borderline section to spot patterns and refine `docs/dev/shared/commenting-guidelines.md` over time.
+- **Flagged items are the safety mechanism.** Treat the Flagged section as a small to-do list before opening the PR.
+
+## Limitations
+
+- Reviews comments and docstrings only — does not touch code structure, naming, or formatting.
+- Branch mode only reviews comments inside changed hunks; legacy comments in untouched parts of touched files are left alone (by design).
+- Directory mode performs better on smaller scopes. Avoid running it on whole apps or the repo root in a single invocation.
+- The agent cannot verify cross-file claims (e.g., "matches constant X in file Y") — these consistently end up in the Flagged section.
+
+## Related
+
+- Guidelines (the rulebook): `docs/dev/shared/commenting-guidelines.md`
+- Coding standards (syntactic): `docs/dev/shared/coding-standards.md`
+- Sub-agent definition: `.claude/agents/comment-reviewer.md`
diff --git a/.claude/commands/conform.md b/.claude/commands/conform.md
deleted file mode 100644
index 99f645c4..00000000
--- a/.claude/commands/conform.md
+++ /dev/null
@@ -1,171 +0,0 @@
-# /conform Command
-
-Automated code quality conformance - reviews and fixes Python files to match project coding standards with test safety verification.
-
-## Usage
-```
-/conform <target>
-```
-
-Where `<target>` can be:
-- A Python filename (e.g., `history_table_manager.py`)
-- A class name (e.g., `HistoryTableManager`)
-- A relative path (e.g., `hi/apps/common/history_table_manager.py`)
-- A module path (e.g., `hi.apps.common.history_table_manager`)
-
-## Examples
-```
-/conform HistoryTableManager
-/conform history_table_manager.py
-/conform hi/apps/entity/managers.py
-/conform hi.apps.entity.managers
-```
-
-## What It Does
-
-This command automates the process of bringing Python code into conformance with project coding standards while ensuring test coverage and safety:
-
-1. **Verifies test coverage** - Ensures tests exist or creates them
-2. **Runs initial tests** - Establishes baseline that tests pass
-3. **Applies automated fixes** - Corrects coding standard violations
-4. **Validates changes** - Ensures tests still pass after modifications
-5. **Runs final linting** - Confirms no new issues introduced
-
-## Process Flow
-
-### Phase 1: Test Verification
-- Locate the target Python file
-- Search for associated test file(s)
-- If no tests exist:
- - Launch test-engineer agent to create comprehensive tests
- - Verify new tests pass
-- If tests exist:
- - Run tests to ensure they pass before changes
-
-### Phase 2: Analysis
-- Launch code-quality agent for comprehensive review
-- Identify all coding standard violations
-- Categorize issues by severity and type
-- Create fix plan
-
-### Phase 3: Automated Fixes
-- Apply fixes for clear violations:
- - Remove obvious comments and docstrings
- - Fix alignment in method parameters, dataclasses, enums
- - Add missing explicit control flow statements
- - Organize imports properly
- - Preserve deliberate style choices (e.g., spaces in parentheses)
-
-### Phase 4: Validation
-- Run tests again to ensure no functional changes
-- Run `make lint` to verify no new issues
-- Provide summary of changes made
-- Flag any issues that require manual review
-
-## Quality Gates
-
-The command will STOP if:
-- No test file exists AND test creation fails
-- Initial tests fail (won't modify code with failing tests)
-- Tests fail after modifications (will revert changes)
-- Linting introduces new errors (will attempt to fix or revert)
-
-## Sub-Agent Coordination
-
-### Phase 1 Agent: test-engineer (if needed)
-- **Role**: Create comprehensive test coverage
-- **Input**: Target file and class/module structure
-- **Output**: Test file with appropriate coverage
-- **Validation**: Tests must pass before proceeding
-
-### Phase 2 Agent: code-quality
-- **Role**: Analyze file and identify all violations
-- **Input**: Full file path and content
-- **Output**: Detailed list of violations with line numbers
-
-### Supporting Operations:
-- **Bash tool**: Run tests and linting
-- **MultiEdit tool**: Apply batched fixes efficiently
-- **Read tool**: Verify changes
-
-## Expected Output
-
-```
-Conforming history_table_manager.py to project standards...
-
-Step 1: Verifying test coverage
-✓ Found test file: tests/test_history_table_manager.py
-✓ Running tests... All 15 tests pass
-
-Step 2: Analyzing code quality
-Found 12 violations:
-- 5 alignment issues
-- 4 obvious comments
-- 2 missing explicit returns
-- 1 import organization issue
-
-Step 3: Applying automated fixes
-✓ Fixed method parameter alignment (lines 81-86)
-✓ Fixed dataclass alignment (lines 54-58)
-✓ Fixed enum alignment (lines 39-50)
-✓ Removed obvious docstrings (lines 37, 188-190, 194-196)
-✓ Removed redundant comments (lines 56, 117, 132, 139, 152)
-✓ Added explicit returns (lines 93, 186)
-✓ Reorganized imports
-
-Step 4: Validation
-✓ Tests still pass (15/15)
-✓ make lint: No violations
-
-Successfully conformed history_table_manager.py to project standards.
-12 issues fixed automatically, all tests still passing.
-```
-
-## Error Handling
-
-- **No test file found**:
- - Automatically creates tests via test-engineer agent
- - If test creation fails, aborts the cleanup
-
-- **Tests fail before changes**:
- - Aborts with message to fix tests first
- - Suggests using `/fixtests` command
-
-- **Tests fail after changes**:
- - Automatically reverts all changes
- - Reports which changes caused test failures
- - Suggests manual review
-
-- **Lint failures after fixes**:
- - Attempts secondary fixes
- - If still failing, reverts and reports
-
-## Safety Features
-
-1. **Test-First Approach**: Won't modify code without passing tests
-2. **Incremental Changes**: Applies fixes in logical batches
-3. **Automatic Rollback**: Reverts if tests fail after changes
-4. **Change Validation**: Each change verified against tests
-5. **Audit Trail**: Lists every change made with line numbers
-
-## Important Notes
-
-- **Preserves functionality** - Changes only syntax/style, never logic
-- **Respects project preferences** - Maintains deliberate PEP8 deviations
-- **Comments philosophy** - Removes only obviously redundant comments
-- **Variable assignments** - Maintains named variables over inlining
-- **Test coverage** - Ensures or creates tests before any modifications
-
-## Limitations
-
-- Works only with Python files in the project
-- Cannot fix complex architectural issues
-- Requires ability to run tests (proper environment setup)
-- May not handle all edge cases in test discovery
-- Does not modify third-party or system files
-
-## Related Commands
-- `/fixtests` - Fix failing tests before running conform
-- `/review` - Code review without automatic fixes
-- `/commit` - Commit changes after conformance
-- `/test` - Run tests for a specific module
diff --git a/.gitignore b/.gitignore
index f2ac85b6..5070009d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -29,4 +29,12 @@ __pycache__/
/docs/**/*.html
!.github/
+
+# .claude/ -- include agents/ and commands/, ignore runtime state
+# (settings.local.json, scheduled_tasks.lock, state/, etc.)
+!.claude/
+.claude/*
+!.claude/agents/
+!.claude/commands/
+
/CLAUDE.md
diff --git a/docs/dev/shared/commenting-guidelines.md b/docs/dev/shared/commenting-guidelines.md
index c0799d2e..9a33f116 100644
--- a/docs/dev/shared/commenting-guidelines.md
+++ b/docs/dev/shared/commenting-guidelines.md
@@ -42,6 +42,45 @@ A useful comment in any of these categories is short, points at the non-obvious
Earning a place is the first bar; earning the current *length* is the second. Many genuinely useful comments are wordier than the substance warrants — extra qualifications, restated context, parenthetical examples that no longer pull their weight. When keeping a comment, ask whether the same substance reads cleaner in half the words. Bias toward shorter even when keeping.
+### WHY vs WHAT — The One-Liner Override Test
+
+When a method overrides a public contract (a base-class method, a `requires_X() -> bool`-style configuration hook), a one-line docstring is keep-worthy when it explains *why* the method returns the specific value it does — domain knowledge the signature cannot carry. Example:
+
+```python
+def requires_api_key(self) -> bool:
+ """NWS does not require an API key."""
+ return False
+```
+
+The docstring tells the reader *why* (the NWS API's actual policy), not just *what* (returns False). Without it, the reader infers the policy by absence — workable but worse than knowing.
+
+The keep applies when:
+- The override implements a public contract where the choice of return value carries domain meaning.
+- The docstring names that meaning in terms the signature cannot.
+
+The keep does **not** apply when:
+- A higher-level docstring (class, module) already establishes the WHY. For example, a `ProfileManager` class that documents its robust-loading strategy makes per-method `"""Create X with error tracking..."""` docstrings redundant — the WHY lives once at the class level.
+- The docstring restates only the WHAT (`"""Return False."""`, `"""Returns the integration's id."""`).
+- The override is mechanical, with no domain knowledge to convey.
+
+### Disambiguating Adjacent Similar Patterns
+
+When two visually similar code patterns appear in the same file but serve different purposes, comments that disambiguate which case each instance is are keep-worthy — even when each individual comment looks like a section label. Example:
+
+```python
+if entity_id not in lookup:
+ continue # Skip comment-only entries
+
+# ... different method ...
+
+if entity_id not in lookup:
+ continue # Skip if entity creation failed upstream
+```
+
+Both comments label an `if X not in lookup: continue` line, which alone reads as the "section labels restating well-named code" anti-pattern. But each comment names a *different reason* for the same code shape (skip-by-design vs skip-due-to-error), and that disambiguation is the load-bearing information.
+
+The keep applies when removing the comment would leave a reader uncertain which of two valid behaviors the code is implementing.
+
## When a Comment Does Not Belong
Remove comments that fall into any of these categories. These are the patterns observed most often.
@@ -116,6 +155,10 @@ When the backend genuinely needs to mention UI behavior, describe it functionall
If a cross-reference is genuinely load-bearing, prefer a stable signal: a shared constant, an explicit import, or a name match enforced by the code itself.
+**Carve-out: external API documentation URLs are keep-worthy.** A URL to the definitive contract documentation for an external system the code depends on (e.g., `https://api.weather.gov/openapi`, `https://open-meteo.com/en/docs`, an RFC, WMO/METAR specs) is a bookmark to the source of truth — not a maintenance liability. If the URL rots, the implementation that depends on the underlying API has a bigger problem than the comment.
+
+The distinction from the bullets above: internal code references (file paths, method names) rot when *internal* code is renamed; external API URLs rot only when the external system itself changes, which is precisely the event the URL is helping the reader trace.
+
### Commented-out code
Delete it. Version control retains the history. Commented blocks create ambiguity about whether the code should be active and tend to drift out of compilability.
@@ -176,6 +219,23 @@ When reviewing comments on a branch or in a directory, decide per comment:
- Is commented-out code or a vague TODO.
- **Flatten module-vs-class docstring duplication.** When a module docstring and a class docstring in the same file repeat the same content, keep what's unique at each level. The module docstring is the right home for cross-class wire formats and inter-class contracts; the class docstring is the right home for the class's own scope and invariants.
+### Partial Removal — Strip and Salvage
+
+The remove-on-sight patterns in "When a Comment Does Not Belong" are shortcuts. The fuller rule for any comment that *contains* an offending element (issue number, "Phase N" prefix, "(as of yet)" hedge, caller-name parenthetical, "Mirrors X" framing, UI label outside the per-language carve-outs, etc.):
+
+1. **Strip the offending substring** — prefix, parenthetical, sentence, or fragment.
+2. **Examine the residue.** Is it load-bearing on its own? Does it state a contract, invariant, design rationale, or non-obvious WHY?
+3. **Act on what remains:**
+ - Substantive residue → **REWRITE** to a tight standalone form.
+ - Trivial residue (the offending part was carrying most of the weight) → **REMOVE** the whole comment.
+
+Examples:
+- `"Phase 5: CONFIRM IMPORT on the preview modal posts to the run view."` → strip `"Phase 5: "`, residue describes a real workflow → REWRITE (keep the workflow description).
+- `"Issue #283 sync-check probe rides on the connector."` → strip `"Issue #283 "`, residue is informational about the connector → REWRITE.
+- `"Per the discussion in #281, we removed this branch."` → strip the work-stream reference, residue (`"we removed this branch"`) is itself archeology → REMOVE the whole comment.
+
+The "if it has X, remove" shortcut is fine when the X-bearing comments are almost always entirely noise. Use the strip-and-salvage check whenever the comment shows any sign of independent substance — better to keep a substantive sentence with the work-stream prefix shaved off than to drop both.
+
### When Unsure — Keep and Flag
Removing a *bad* comment is free. Removing a *load-bearing* comment is expensive and easy to miss in review. When in doubt:
@@ -185,12 +245,32 @@ Removing a *bad* comment is free. Removing a *load-bearing* comment is expensive
A cleanup pass that errs toward keeping ambiguous comments is correct. A cleanup pass that silently deletes load-bearing context is a regression.
-### Authoring Boundary — Edit, Don't Author
+**Multi-rule conflict counts as uncertainty.** When a single comment hits two rules that point in opposite directions — for example, Comment-vs-Code Drift says "fix it" while a remove-on-sight pattern says "remove it" — that is, by definition, uncertainty about the right action. KEEP and FLAG. Don't pick a side silently.
+
+### Typo Fixes — Comments and Docstrings Only
+
+Obvious typos in comments and docstrings are fixable by the cleanup pass. Treat them like ASCII normalization: a syntactic concern applied during cleanup as a courtesy when the agent is already touching the file.
+
+In scope:
+- Misspellings (`Attrribute` → `Attribute`, `recieve` → `receive`).
+- Duplicate words (`the the`, `placement placement`, `is is`).
+- Obvious transpositions (`teh` → `the`).
+- Missing capitalization on sentence starts.
+
+Out of scope:
+- **Typos in code identifiers** (variable, method, class, attribute names) — those are renaming refactors with much broader implications. Even if a typo appears in a public class name, the cleanup pass does not rename it.
+- **Typos in user-facing strings** (HTML body text, button labels, `help_text`, error messages, log messages) — those follow the user-facing-strings hard constraint and have their own review process.
+
+If the typo's intent is ambiguous — the misspelling might be a deliberate word choice, or the apparent "typo" might be a domain-specific term — KEEP and FLAG rather than fix.
+
+### Authoring Boundary — Don't Insert Missing Comments
-The cleanup pass reviews and edits *existing* comments. It does not author new ones — even when a file would clearly benefit from a comment that isn't there (a missing Context block in a template, a missing docstring on a public method, a missing invariant note next to a non-obvious guard).
+The cleanup pass operates on *existing* comments. It does not insert comments where there are none — even when a file would clearly benefit from one (a missing Context block in a template, a missing docstring on a public method, a missing invariant note next to a non-obvious guard).
Identifying these gaps is valuable but is a separate authoring task with different inputs (design intent, contract knowledge) than what the cleanup pass operates on. Surface the gap as a flagged observation if useful; do not silently fill it.
+**Rewriting is editing, not authoring.** When an existing comment has substance worth preserving but framing or structure that needs to change, rewriting it — including significant restructuring, stripping offending prefixes or parentheticals, reshaping a multi-paragraph block into a single sentence, or salvaging the substance and discarding everything around it — is part of normal cleanup work. The boundary is about *inserting* where there was nothing, not about how aggressively to *reshape* what was there.
+
### Substance-at-Wrong-Location — Stay Myopic
A comment may describe semantics owned by another module — for example, an enum docstring that explains the implementation's behavior rather than just naming the choice. The cleanup pass is myopic by design: it does **not** cross files to verify whether the substance exists at its canonical location.
@@ -235,6 +315,10 @@ Context:
**UI labels that the template itself renders are not pattern #4 violations.** The "UI element name-dropping in backend code" rule targets backend comments that quote UI labels living elsewhere — those references rot when the UI changes. A template that *renders* a button labeled `UPDATE` and refers to "UPDATE" in its top comment is a different case: the label and the comment about it live in the same file and change together. The cleanup pass can leave these in place. Backend code that references the same `UPDATE` button by name is still pattern #4 — the rule applies to cross-file references, not local self-reference.
+**Section labels are keep-worthy for navigation.** Templates have nominal grouping constructs (`{% block %}`, `{% if %}`, `{% for %}`, etc.) but they are not visually distinct without IDE-level Django template syntax awareness. Banner-style and short single-line section labels (`{# ----- Search form ----- #}`, `{# Cancel + Add row #}`, `{# Sticky header #}`) earn their place as navigation aids in dense templates. The bar for removing a template section label is high: only remove when the label adds *zero* information and the next block's content is completely self-explanatory.
+
+**`<!-- -->` HTML comments in templates — flag, don't convert.** Django templates should use `{# ... #}` (single-line) or `{% comment %} ... {% endcomment %}` (multi-line) for developer comments, because `<!-- -->` comments render in the browser. When the cleanup pass encounters an `<!-- -->` comment inside a Django template, it should **FLAG** the syntactic mismatch but **not convert** it. A future intentional use — for example, a comment deliberately rendered in the browser HTML as documentation for downstream consumers — would be silently broken by automatic conversion. The conversion is a coding-standards decision that requires human verification of intent.
+
### CSS
CSS has no nesting, no module system, and no function/class structure. Section labels are the only grouping construct the language offers.
@@ -245,6 +329,20 @@ CSS has no nesting, no module system, and no function/class structure. Section l
**Inline trailing comments on property values are useful and should be kept** when they explain a magic value (`min-height: 44px; /* Touch-friendly minimum */`), a behavioral choice (`flex-shrink: 0; /* Don't shrink button */`), or a browser-compat reason (`border-width: 0.5px; /* Sharper on retina */`). They are pure WHY at the most precise location.
+### Django Views
+
+Django view classes (`HiModalView`, `View`, `ConfigPageView` subclasses, etc.) sit at the boundary between backend logic and rendered UI. The same UI-label exception that applies to templates and CSS applies here: the view is the file that *defines* the rendering for the UI surface it owns.
+
+**UI labels that the view directly renders, dispatches on, or names in its modal/page contract are keep-worthy.** Examples that earned their place across the codebase:
+
+- Button labels rendered by the view's template: `UPDATE`, `CONNECT`, `Sync / Not now`, `Refresh and Retain` / `Refresh and Remove`.
+- Mode names dispatched by the view's POST: `DELETE`, `DELETE SAFE`, `DELETE ALL`, `SAFE` / `ALL`.
+- CTAs and modal flows the view assembles: `'Place N new items' CTA`, "the manage page", "the sync result modal".
+
+The reasoning matches templates and CSS: the label and the comment about it live in the same file (or in the view's own contract with its template) and change together. Stripping these labels in favor of generic phrasing ("preserve/hard-delete pair", "confirm/cancel actions") loses precision without gaining stability — when the button label changes, the view's logic has to change too, and the comment will surface as part of that change.
+
+Pattern #4 still applies when a backend non-view file references UI labels owned elsewhere (e.g., a manager class mentioning the "Detached" tile). The view-layer carve-out is for the view itself.
+
## What Is Out of Scope for the Cleanup Pass
The cleanup pass is about **content and semantics**. The following are syntactic concerns that belong to general code review and to [Coding Standards](coding-standards.md):
diff --git a/src/hi/apps/profiles/constants.py b/src/hi/apps/profiles/constants.py
index 1aafc44e..309bb901 100644
--- a/src/hi/apps/profiles/constants.py
+++ b/src/hi/apps/profiles/constants.py
@@ -8,37 +8,30 @@ EDIT_MODE_ENTRY_COUNT_KEY = 'edit_mode_entry_count'
# Profile JSON specification comment constants for self-documenting files
# These comments document the different structural patterns possible in the JSON format
-# Entity structural pattern comments - based on JSON structure patterns
ENTITY_COMMENT_ICON_POSITIONED = "Icon-positioned entities (EntityPosition) - most common case"
ENTITY_COMMENT_PATH_ENTITY = "Path entity (EntityPath) - represented by SVG paths"
ENTITY_COMMENT_COLLECTION_MEMBER = "Entities that are part of collections"
-# Collection structural pattern comments - based on JSON structure patterns
COLLECTION_COMMENT_WITH_POSITIONING = "Collection with spatial positioning on location views"
COLLECTION_COMMENT_PATH_BASED = "Collection with path representation"
-# Profile JSON field name constants to avoid magic strings
-# Top-level fields
PROFILE_FIELD_NAME = 'profile_name'
PROFILE_FIELD_DESCRIPTION = 'description'
PROFILE_FIELD_LOCATIONS = 'locations'
PROFILE_FIELD_COLLECTIONS = 'collections'
PROFILE_FIELD_ENTITIES = 'entities'
-# Location fields
LOCATION_FIELD_NAME = 'name'
LOCATION_FIELD_SVG_TEMPLATE_NAME = 'svg_template_name'
LOCATION_FIELD_ORDER_ID = 'order_id'
LOCATION_FIELD_VIEWS = 'views'
-# LocationView fields
LOCATION_VIEW_FIELD_NAME = 'name'
LOCATION_VIEW_FIELD_TYPE_STR = 'location_view_type_str'
LOCATION_VIEW_FIELD_SVG_VIEW_BOX_STR = 'svg_view_box_str'
LOCATION_VIEW_FIELD_SVG_STYLE_NAME_STR = 'svg_style_name_str'
LOCATION_VIEW_FIELD_ORDER_ID = 'order_id'
-# Collection fields
COLLECTION_FIELD_NAME = 'name'
COLLECTION_FIELD_TYPE_STR = 'collection_type_str'
COLLECTION_FIELD_VIEW_TYPE_STR = 'collection_view_type_str'
@@ -48,14 +41,12 @@ COLLECTION_FIELD_POSITIONS = 'positions'
COLLECTION_FIELD_PATHS = 'paths'
COLLECTION_FIELD_VISIBLE_IN_VIEWS = 'visible_in_views'
-# Entity fields
ENTITY_FIELD_NAME = 'name'
ENTITY_FIELD_TYPE_STR = 'entity_type_str'
ENTITY_FIELD_POSITIONS = 'positions'
ENTITY_FIELD_PATHS = 'paths'
ENTITY_FIELD_VISIBLE_IN_VIEWS = 'visible_in_views'
-# Common fields
COMMON_FIELD_COMMENT = 'comment'
COMMON_FIELD_LOCATION_NAME = 'location_name'
COMMON_FIELD_SVG_X = 'svg_x'
diff --git a/src/hi/apps/profiles/context_processors.py b/src/hi/apps/profiles/context_processors.py
index 52ea7a3a..4f7be90a 100644
--- a/src/hi/apps/profiles/context_processors.py
+++ b/src/hi/apps/profiles/context_processors.py
@@ -5,7 +5,6 @@ from .session_helpers import (
def profiles_context(request):
- """Provide profile-related context variables for templates."""
return {
'show_view_intro_help': should_show_view_intro_help(request),
'show_edit_intro_help': should_show_edit_intro_help(request),
diff --git a/src/hi/apps/profiles/profile_manager.py b/src/hi/apps/profiles/profile_manager.py
index 4a47d8a2..e65237ad 100644
--- a/src/hi/apps/profiles/profile_manager.py
+++ b/src/hi/apps/profiles/profile_manager.py
@@ -28,7 +28,6 @@ logger = logging.getLogger(__name__)
@dataclass
class ProfileLoadingStats:
- """Track success/failure counts during profile loading."""
locations_attempted: int = 0
locations_succeeded: int = 0
locations_failed: int = 0
@@ -74,7 +73,6 @@ class ProfileLoadingStats:
collection_views_failed: int = 0
def log_summary(self, profile_label: str):
- """Log a comprehensive summary of loading results."""
logger.info(f'Profile loading summary for {profile_label}:')
logger.info(f' Locations: {self.locations_succeeded}/{self.locations_attempted} succeeded')
logger.info(f' Entities: {self.entities_succeeded}/{self.entities_attempted} succeeded')
@@ -131,23 +129,18 @@ class ProfileManager:
json.JSONDecodeError: If profile JSON is invalid
Exception: For other fundamental errors during profile loading
"""
- # Validate database is empty before starting
self._validate_empty_database()
-
+
json_file_path = self._get_profile_json_path(profile_type)
profile_data = self._load_json_file( json_file_path )
-
- # Validate fundamental requirements before starting
+
self._validate_fundamental_requirements(profile_data)
-
- # Copy SVG fragment files from assets to MEDIA_ROOT before validation
+
self._render_svg_templates(profile_data)
-
- # Initialize tracking
+
stats = ProfileLoadingStats()
-
+
with transaction.atomic():
- # Create core models with error tracking
locations, location_lookup = self._create_locations_robust(
profile_data.get(PC.PROFILE_FIELD_LOCATIONS, []), stats)
@@ -156,8 +149,7 @@ class ProfileManager:
collections, collection_lookup = self._create_collections_robust(
profile_data.get(PC.PROFILE_FIELD_COLLECTIONS, []), stats)
-
- # Create relationships with error tracking
+
self._create_entity_positions_and_paths_robust(
profile_data.get(PC.PROFILE_FIELD_ENTITIES, []),
entity_lookup, location_lookup, stats)
@@ -181,16 +173,14 @@ class ProfileManager:
self._create_collection_views_robust(
profile_data.get(PC.PROFILE_FIELD_COLLECTIONS, []),
collection_lookup, location_lookup, stats)
-
- # Validate minimum requirements were met
+
if not stats.meets_minimum_requirements():
raise ValueError(
f'Profile loading failed: Minimum requirements not met. '
f'Successfully loaded {stats.locations_succeeded} locations '
f'and {stats.entities_succeeded} entities. '
f'At least 1 location and 1 entity are required.')
-
- # Log comprehensive results
+
stats.log_summary(profile_type.label)
return stats
@@ -201,7 +191,6 @@ class ProfileManager:
Raises:
ValueError: If fundamental requirements are not met
"""
- # Ensure there are locations defined
locations_data = profile_data.get(PC.PROFILE_FIELD_LOCATIONS, [])
if not locations_data:
raise ValueError('Profile must contain at least one location definition')
@@ -354,7 +343,6 @@ class ProfileManager:
return
def _create_entities( self, entity_data_list: List[dict] ) -> List[Entity]:
- """Create Entity instances from profile data"""
entities = []
for entity_data in entity_data_list:
@@ -549,8 +537,7 @@ class ProfileManager:
)
position_count += 1
continue
-
- # Create CollectionPath instances
+
for path_data in collection_data.get(PC.COLLECTION_FIELD_PATHS, []):
location = location_lookup[path_data[PC.COMMON_FIELD_LOCATION_NAME]]
@@ -604,10 +591,7 @@ class ProfileManager:
logger.debug(f'Created {view_count} collection views')
return
- # Robust error handling versions of creation methods
-
def _create_locations_robust(self, location_data_list: List[dict], stats: ProfileLoadingStats) -> tuple[List[Location], Dict[str, Location]]:
- """Create locations with error tracking and graceful failure handling."""
locations = []
for location_data in location_data_list:
@@ -636,7 +620,6 @@ class ProfileManager:
return locations, location_lookup
def _create_entities_robust(self, entity_data_list: List[dict], stats: ProfileLoadingStats) -> tuple[List[Entity], Dict[str, Entity]]:
- """Create entities with error tracking and graceful failure handling."""
entities = []
for entity_data in entity_data_list:
@@ -667,7 +650,6 @@ class ProfileManager:
return entities, entity_lookup
def _create_collections_robust(self, collection_data_list: List[dict], stats: ProfileLoadingStats) -> tuple[List[Collection], Dict[str, Collection]]:
- """Create collections with error tracking and graceful failure handling."""
collections = []
for collection_data in collection_data_list:
@@ -706,18 +688,16 @@ class ProfileManager:
entity_lookup: Dict[str, Entity],
location_lookup: Dict[str, Location],
stats: ProfileLoadingStats):
- """Create entity positions and paths with error tracking and graceful failure handling."""
for entity_data in entity_data_list:
if PC.ENTITY_FIELD_NAME not in entity_data:
continue
-
+
entity_name = entity_data[PC.ENTITY_FIELD_NAME]
if entity_name not in entity_lookup:
continue # Skip if entity creation failed
-
+
entity = entity_lookup[entity_name]
-
- # Handle positions
+
for position_data in entity_data.get(PC.ENTITY_FIELD_POSITIONS, []):
stats.entity_positions_attempted += 1
try:
@@ -741,8 +721,7 @@ class ProfileManager:
stats.entity_positions_failed += 1
logger.error(f'Failed to create position for entity "{entity_name}": {e}')
continue
-
- # Handle paths
+
for path_data in entity_data.get(PC.ENTITY_FIELD_PATHS, []):
stats.entity_paths_attempted += 1
try:
@@ -770,7 +749,6 @@ class ProfileManager:
def _create_location_views_robust(self, location_data_list: List[dict],
location_lookup: Dict[str, Location],
stats: ProfileLoadingStats):
- """Create location views with error tracking and graceful failure handling."""
for location_data in location_data_list:
location_name = location_data[PC.LOCATION_FIELD_NAME]
if location_name not in location_lookup:
@@ -813,21 +791,19 @@ class ProfileManager:
entity_lookup: Dict[str, Entity],
location_lookup: Dict[str, Location],
stats: ProfileLoadingStats):
- """Create entity views with error tracking and graceful failure handling."""
for entity_data in entity_data_list:
if PC.ENTITY_FIELD_NAME not in entity_data:
continue
-
+
entity_name = entity_data[PC.ENTITY_FIELD_NAME]
if entity_name not in entity_lookup:
continue # Skip if entity creation failed
-
+
entity = entity_lookup[entity_name]
-
+
for view_name in entity_data.get(PC.ENTITY_FIELD_VISIBLE_IN_VIEWS, []):
stats.entity_views_attempted += 1
try:
- # Find the LocationView by searching all locations
location_view = None
for location in location_lookup.values():
try:
@@ -860,7 +836,6 @@ class ProfileManager:
collection_lookup: Dict[str, Collection],
entity_lookup: Dict[str, Entity],
stats: ProfileLoadingStats):
- """Create collection-entity relationships with error tracking and graceful failure handling."""
for collection_data in collection_data_list:
if PC.COLLECTION_FIELD_NAME not in collection_data:
continue
@@ -898,18 +873,16 @@ class ProfileManager:
collection_lookup: Dict[str, Collection],
location_lookup: Dict[str, Location],
stats: ProfileLoadingStats):
- """Create collection positions and paths with error tracking and graceful failure handling."""
for collection_data in collection_data_list:
if PC.COLLECTION_FIELD_NAME not in collection_data:
continue
-
+
collection_name = collection_data[PC.COLLECTION_FIELD_NAME]
if collection_name not in collection_lookup:
continue # Skip if collection creation failed
-
+
collection = collection_lookup[collection_name]
-
- # Handle positions
+
for position_data in collection_data.get(PC.COLLECTION_FIELD_POSITIONS, []):
stats.collection_positions_attempted += 1
try:
@@ -933,8 +906,7 @@ class ProfileManager:
stats.collection_positions_failed += 1
logger.error(f'Failed to create position for collection "{collection_name}": {e}')
continue
-
- # Handle paths
+
for path_data in collection_data.get(PC.COLLECTION_FIELD_PATHS, []):
stats.collection_paths_attempted += 1
try:
@@ -963,21 +935,19 @@ class ProfileManager:
collection_lookup: Dict[str, Collection],
location_lookup: Dict[str, Location],
stats: ProfileLoadingStats):
- """Create collection views with error tracking and graceful failure handling."""
for collection_data in collection_data_list:
if PC.COLLECTION_FIELD_NAME not in collection_data:
continue
-
+
collection_name = collection_data[PC.COLLECTION_FIELD_NAME]
if collection_name not in collection_lookup:
continue # Skip if collection creation failed
-
+
collection = collection_lookup[collection_name]
-
+
for view_name in collection_data.get(PC.COLLECTION_FIELD_VISIBLE_IN_VIEWS, []):
stats.collection_views_attempted += 1
try:
- # Find the LocationView by searching all locations
location_view = None
for location in location_lookup.values():
try:
diff --git a/src/hi/apps/profiles/session_helpers.py b/src/hi/apps/profiles/session_helpers.py
index 9c47c177..e291685a 100644
--- a/src/hi/apps/profiles/session_helpers.py
+++ b/src/hi/apps/profiles/session_helpers.py
@@ -22,20 +22,17 @@ def mark_first_location_created(request):
def mark_edit_mode_entry(request):
"""
- Called when entering edit mode.
+ Called when entering edit mode.
Only tracks if this is the same session that initialized the profile.
"""
- # Only track edit mode in the initialization session
if VIEW_INTRO_HELP_SESSION_KEY not in request.session:
return
-
- # Increment entry count
+
count = request.session.get(EDIT_MODE_ENTRY_COUNT_KEY, 0)
-
- # On first entry, start the help timer
+
if count == 0:
request.session[EDIT_INTRO_HELP_SESSION_KEY] = time.time()
-
+
request.session[EDIT_MODE_ENTRY_COUNT_KEY] = count + 1
@@ -45,7 +42,6 @@ def dismiss_view_intro_help(request):
def should_show_view_intro_help(request):
- """Check if view mode help should be shown based on session timing."""
timestamp = request.session.get(VIEW_INTRO_HELP_SESSION_KEY)
if not timestamp:
return False
@@ -61,14 +57,11 @@ def should_show_edit_intro_help(request):
2. This is the first edit mode entry
3. We're still within the time window
"""
- # Must be in initialization session
if VIEW_INTRO_HELP_SESSION_KEY not in request.session:
return False
-
- # Must have entered edit mode at least once
+
timestamp = request.session.get(EDIT_INTRO_HELP_SESSION_KEY)
if not timestamp:
return False
-
- # Must be within time window
+
return (time.time() - timestamp) < EDIT_INTRO_HELP_DURATION_SECONDS
diff --git a/src/hi/apps/profiles/views.py b/src/hi/apps/profiles/views.py
index fe21b186..267aa3be 100644
--- a/src/hi/apps/profiles/views.py
+++ b/src/hi/apps/profiles/views.py
@@ -41,7 +41,6 @@ class InitializePredefinedView(View):
This view should only be accessible when the database is empty
(no LocationView objects exist).
"""
- # Validate profile_type parameter - raise 404 for invalid URLs
try:
profile_enum = ProfileType.from_name(profile_type)
except ValueError:
@@ -51,8 +50,7 @@ class InitializePredefinedView(View):
try:
profile_manager.load_profile( profile_enum )
logger.info( f'Successfully loaded profile: {profile_enum}' )
-
- # Mark profile as initialized for help system
+
mark_profile_initialized(request)
request.view_parameters.view_mode = ViewMode.MONITOR
diff --git a/src/hi/apps/weather/aggregated_weather_data.py b/src/hi/apps/weather/aggregated_weather_data.py
index f4aa5598..3e3904e5 100644
--- a/src/hi/apps/weather/aggregated_weather_data.py
+++ b/src/hi/apps/weather/aggregated_weather_data.py
@@ -23,14 +23,7 @@ logger = logging.getLogger(__name__)
@dataclass
class AggregatedWeatherData:
- """
- Represents aggregated weather data for a single time interval from multiple sources.
-
- This class handles the aggregation of weather data points from different sources
- that overlap with a target time interval. It provides sophisticated merging logic
- that considers source priority, data freshness, and time-weighted averaging.
- """
-
+
# How old source data has to be for lower priority sources to
# override higher priority sources (in seconds)
DATA_AGE_STALE_SECS = 2 * 60 * 60 # 2 hours
@@ -42,46 +35,31 @@ class AggregatedWeatherData:
def add_source_data( self,
data_point_source : DataPointSource,
source_interval_data : IntervalEnvironmentalData ):
- """
- Add source data that overlaps with this aggregated interval.
-
- Args:
- data_point_source: The data source providing the data
- source_interval_data: Interval data from the source that overlaps
- """
assert isinstance( source_interval_data.data, self.data_class )
assert self.interval_data.interval.overlaps( source_interval_data.interval )
-
+
# Collate by the individual data point fields so we can more easily
# aggregate source and interval data on a per-field basis.
-
+
source_interval = source_interval_data.interval
source_data = source_interval_data.data
-
+
from .model_helpers import is_datapoint_field
for a_field in fields( source_data ):
field_name = a_field.name
-
+
if not is_datapoint_field(a_field.type):
continue
source_data_point = getattr( source_data, field_name )
- # Skip None values to avoid type confusion during aggregation
if source_data_point is not None:
self.source_data[field_name][data_point_source][source_interval] = source_data_point
continue
return
def reaggregate_source_data( self ):
- """
- Re-aggregate all source data into the target interval.
-
- This method processes all source data that has been added and creates
- aggregated data points using appropriate aggregation strategies for
- different data point types.
- """
if not self.source_data:
return
@@ -93,10 +71,9 @@ class AggregatedWeatherData:
continue
interval_data_point_map = source_map[data_point_source]
-
- # Filter out any None values that might have been added
+
interval_data_point_map = {k: v for k, v in interval_data_point_map.items() if v is not None}
-
+
if not interval_data_point_map:
setattr( self.interval_data.data, field_name, None )
continue
@@ -105,8 +82,7 @@ class AggregatedWeatherData:
new_data_point = next( iter( interval_data_point_map.values() ))
setattr( self.interval_data.data, field_name, new_data_point )
continue
-
- # Determine the expected DataPoint type from the first source data point
+
sample_data_point = next(iter(interval_data_point_map.values()))
if isinstance( sample_data_point, NumericDataPoint ):
@@ -126,7 +102,6 @@ class AggregatedWeatherData:
interval_data_point_map = interval_data_point_map,
)
else:
- # Unknown DataPoint type - skip this field
logger.warning(f"Unknown DataPoint type for field '{field_name}': {type(sample_data_point)}")
continue
@@ -137,18 +112,9 @@ class AggregatedWeatherData:
def get_best_data_point_source(
self,
source_map : Dict[ DataPointSource, Dict[ TimeInterval, DataPoint ]] ) -> DataPointSource | None:
- """
- Select the best data source based on priority and freshness.
-
- Args:
- source_map: Map of data sources to their interval data
-
- Returns:
- The data source that should be used for aggregation, or None if no valid sources
- """
if not source_map:
return None
-
+
data_point_source_list = list( source_map.keys() )
data_point_source_list.sort( key = lambda item: item.priority )
@@ -157,17 +123,14 @@ class AggregatedWeatherData:
stale_data_tuple_list = list()
for data_point_source in data_point_source_list:
interval_map = source_map[data_point_source]
-
- # Skip sources with no intervals or no data points
+
if not interval_map:
continue
-
- # Get valid data points (non-None)
+
valid_data_points = [dp for dp in interval_map.values() if dp is not None]
if not valid_data_points:
continue
-
- # Find the most recent data point
+
max_source_datetime = max(dp.source_datetime for dp in valid_data_points)
source_data_age = now - max_source_datetime
if source_data_age.total_seconds() < self.DATA_AGE_STALE_SECS:
@@ -179,22 +142,13 @@ class AggregatedWeatherData:
if stale_data_tuple_list:
stale_data_tuple_list.sort( key = lambda item: item[1], reverse = True )
return stale_data_tuple_list[0][0]
-
- # No valid data sources found
+
return None
def aggregate_boolean_data_points(
self,
interval_data_point_map : Dict[ TimeInterval, DataPoint ] ) -> BooleanDataPoint:
- """
- Aggregate boolean data points using duration-weighted majority voting.
-
- Args:
- interval_data_point_map: Map of intervals to boolean data points
-
- Returns:
- Aggregated boolean data point with majority value
- """
+ """ Aggregate boolean data points using duration-weighted majority voting. """
assert bool( interval_data_point_map )
total_true_duration = 0.0
@@ -223,15 +177,7 @@ class AggregatedWeatherData:
def aggregate_time_data_points(
self,
interval_data_point_map : Dict[ TimeInterval, DataPoint ] ) -> TimeDataPoint:
- """
- Aggregate time data points using longest duration selection.
-
- Args:
- interval_data_point_map: Map of intervals to time data points
-
- Returns:
- Time data point from the interval with longest overlap
- """
+ """ Aggregate time data points using longest duration selection. """
assert bool( interval_data_point_map )
max_value = None
@@ -255,15 +201,7 @@ class AggregatedWeatherData:
def aggregate_string_data_points(
self,
interval_data_point_map : Dict[ TimeInterval, DataPoint ] ) -> StringDataPoint:
- """
- Aggregate string data points using longest duration selection.
-
- Args:
- interval_data_point_map: Map of intervals to string data points
-
- Returns:
- String data point from the interval with longest overlap
- """
+ """ Aggregate string data points using longest duration selection. """
assert bool( interval_data_point_map )
max_value = None
@@ -287,15 +225,7 @@ class AggregatedWeatherData:
def aggregate_numeric_data_points(
self,
interval_data_point_map : Dict[ TimeInterval, DataPoint ] ) -> NumericDataPoint:
- """
- Aggregate numeric data points using time-weighted averaging.
-
- Args:
- interval_data_point_map: Map of intervals to numeric data points
-
- Returns:
- Aggregated numeric data point with time-weighted average and min/max
- """
+ """ Aggregate numeric data points using time-weighted averaging. """
assert bool( interval_data_point_map )
min_quantity = None
@@ -340,22 +270,11 @@ class AggregatedWeatherData:
@classmethod
def from_time_interval( cls, time_interval : TimeInterval, data_class : Type[ EnvironmentalData ] ):
- """
- Create an AggregatedWeatherData instance for a given time interval.
-
- Args:
- time_interval: The target time interval for aggregation
- data_class: The data class type for this aggregated data
-
- Returns:
- New AggregatedWeatherData instance ready for source data
- """
from .interval_models import SourceFieldData
from dataclasses import fields
-
- # Initialize source_data with SourceFieldData for each DataPoint field
+
from .model_helpers import is_datapoint_field
-
+
source_data = {}
data_instance = data_class()
for field in fields(data_instance):
diff --git a/src/hi/apps/weather/daily_weather_tracker.py b/src/hi/apps/weather/daily_weather_tracker.py
index bf705fe5..a9cffe9c 100644
--- a/src/hi/apps/weather/daily_weather_tracker.py
+++ b/src/hi/apps/weather/daily_weather_tracker.py
@@ -1,18 +1,6 @@
"""
-Daily Weather Data Tracking
-
Generalized tracking of daily weather statistics using calendar days in local timezone.
Provides fallback values when weather APIs don't provide daily extremes or aggregations.
-
-Currently implements:
-- Temperature min/max tracking
-
-Designed for easy extension to track other weather fields like:
-- Humidity min/max
-- Wind speed max
-- Pressure min/max
-- Precipitation totals
-- etc.
"""
import json
import logging
@@ -38,29 +26,25 @@ logger = logging.getLogger(__name__)
class DailyWeatherTracker(Singleton):
"""
Tracks daily weather statistics for fallback values.
-
+
Uses calendar days in local timezone and stores daily min/max/sum/count
statistics for various weather fields.
"""
-
- # Redis cache key prefix
+
CACHE_KEY_PREFIX = "weather:daily_stats"
-
- # Cache timeout (7 days)
- CACHE_TIMEOUT_SECONDS = 7 * 24 * 60 * 60
-
- # Supported statistic types
+
+ CACHE_TIMEOUT_SECONDS = 7 * 24 * 60 * 60 # 7 days
+
STAT_MIN = 'min'
STAT_MAX = 'max'
STAT_SUM = 'sum'
STAT_COUNT = 'count'
STAT_AVG = 'avg' # Computed from sum/count
-
- # Field names
+
FIELD_TEMPERATURE = 'temperature'
TRACE = False # For debugging
-
+
def __init_singleton__(self):
self._fallback_source = DataPointSource(
id="daily_weather_tracker",
@@ -72,18 +56,7 @@ class DailyWeatherTracker(Singleton):
def record_weather_conditions( self,
weather_conditions_data : WeatherConditionsData,
location_key : str = "default") -> None:
- """
- Record weather conditions and update daily statistics.
-
- Currently tracks:
- - Temperature min/max
-
- Args:
- weather_conditions_data: Complete weather conditions data
- location_key: Unique identifier for the location
- """
- # Record temperature if available
- if ( weather_conditions_data.temperature
+ if ( weather_conditions_data.temperature
and weather_conditions_data.temperature.quantity_ave is not None ):
temp_celsius = weather_conditions_data.temperature.quantity_ave.to('degree_Celsius').magnitude
temp_timestamp = weather_conditions_data.temperature.source_datetime or datetimeproxy.now()
@@ -98,27 +71,11 @@ class DailyWeatherTracker(Singleton):
)
else:
logger.warning(f"record_weather_conditions called for {location_key} but no temperature data available")
-
- # Future: Add other weather field tracking here
- # if weather_conditions_data.relative_humidity:
- # self._record_humidity(weather_conditions_data.relative_humidity, location_key)
- # if weather_conditions_data.windspeed:
- # self._record_wind_speed(weather_conditions_data.windspeed, location_key)
-
+
def get_temperature_min_max_today(
self,
location_key: str = "default"
) -> Tuple[Optional[NumericDataPoint], Optional[NumericDataPoint]]:
- """
- Get today's minimum and maximum temperatures.
-
- Args:
- location_key: Unique identifier for the location
-
- Returns:
- Tuple of (min_temperature, max_temperature) as NumericDataPoint objects,
- or (None, None) if no data available
- """
try:
field_stats = self._get_field_stats_today(location_key, self.FIELD_TEMPERATURE)
if self.TRACE:
@@ -126,18 +83,16 @@ class DailyWeatherTracker(Singleton):
min_data = field_stats.get(self.STAT_MIN)
max_data = field_stats.get(self.STAT_MAX)
-
+
if not min_data or not max_data:
return None, None
-
- # Create fallback station
+
fallback_station = Station(
source=self._fallback_source,
station_id="daily_tracker",
name="Daily Weather Tracker"
)
-
- # Create NumericDataPoint objects
+
min_datapoint = NumericDataPoint(
station=fallback_station,
source_datetime=datetime.fromisoformat(min_data['timestamp']),
@@ -180,28 +135,14 @@ class DailyWeatherTracker(Singleton):
units : str,
timestamp : datetime,
track_stats : list ) -> None:
- """
- Record a value for a weather field and update specified statistics.
-
- Args:
- location_key: Unique identifier for the location
- field_name: Name of the weather field (e.g., 'temperature')
- value: Numeric value to record
- units: Units of the value
- timestamp: When the value was observed
- track_stats: List of statistics to track (STAT_MIN, STAT_MAX, etc.)
- """
try:
- # Get current date in local timezone
date_key = self._get_date_key_today()
-
- # Get current field statistics
+
field_stats = self._get_field_stats(location_key, date_key, field_name)
logger.debug( f'Start field stats [value={value}] = {field_stats}' )
-
- # Update statistics
+
updated = False
-
+
if self.STAT_MIN in track_stats:
min_data = field_stats.get(self.STAT_MIN)
if not min_data or value < min_data['value']:
@@ -240,8 +181,7 @@ class DailyWeatherTracker(Singleton):
updated = True
logger.debug( f'End field stats [updated={updated}] = {field_stats}' )
-
- # Store updated statistics if changed
+
if updated:
self._store_field_stats(location_key, date_key, field_name, field_stats)
logger.debug( f"Updated daily {field_name} stats for {date_key} at location {location_key}: "
@@ -256,7 +196,6 @@ class DailyWeatherTracker(Singleton):
logger.exception(f"Error recording {field_name} value: {e}")
def _get_field_stats(self, location_key: str, date_key: str, field_name: str) -> Dict[str, Any]:
- """Get field statistics from cache."""
cache_key = self._get_cache_key(location_key, date_key, field_name)
stats_json = cache.get(cache_key)
@@ -272,16 +211,14 @@ class DailyWeatherTracker(Singleton):
return {}
def _get_field_stats_today(self, location_key: str, field_name: str) -> Dict[str, Any]:
- """Get today's field statistics."""
date_key = self._get_date_key_today()
return self._get_field_stats(location_key, date_key, field_name)
-
+
def _store_field_stats( self,
location_key : str,
date_key : str,
field_name : str,
stats : Dict[str, Any]) -> None:
- """Store field statistics to cache."""
cache_key = self._get_cache_key(location_key, date_key, field_name)
stats_json = json.dumps(stats)
logger.debug( f'Store field stats [key={cache_key}] - {stats_json}' )
@@ -289,48 +226,32 @@ class DailyWeatherTracker(Singleton):
return
def clear_today(self, location_key: str = "default", field_name: Optional[str] = None) -> None:
- """
- Clear today's data for a specific field or all fields.
-
- Args:
- location_key: Unique identifier for the location
- field_name: Specific field to clear, or None to clear all
- """
if field_name:
date_key = self._get_date_key_today()
cache_key = self._get_cache_key(location_key, date_key, field_name)
cache.delete(cache_key)
logger.debug(f"Cleared today's {field_name} data for {location_key}")
else:
- # Clear all fields - would need to iterate through known fields
- # For now, just clear temperature since that's what we implement
self.clear_today(location_key, self.FIELD_TEMPERATURE)
-
+
def get_daily_summary(self, location_key: str = "default") -> Dict[str, Any]:
- """
- Get today's weather summary for debugging.
-
- Returns:
- Dict with field statistics or empty dict if no data
- """
+ """ Today's weather summary for debugging. """
tz_name = ConsoleSettingsHelper().get_tz_name()
date_key = self._get_date_key_today(tz_name)
-
+
summary = {
'date': date_key,
'timezone': tz_name,
'fields': {}
}
-
- # Add temperature stats if available
+
temp_stats = self._get_field_stats(location_key, date_key, self.FIELD_TEMPERATURE)
if temp_stats:
summary['fields'][self.FIELD_TEMPERATURE] = temp_stats
-
- # Return None if no fields have data
+
if not summary['fields']:
return None
-
+
return summary
def _get_date_key_today(self, tz_name: str = None) -> str:
@@ -340,9 +261,5 @@ class DailyWeatherTracker(Singleton):
return now_local.strftime('%Y-%m-%d')
def _get_cache_key(self, location_key: str, date_key: str, field_name: str) -> str:
- """Generate cache key for field statistics.
-
- Single source of truth for cache key format to ensure consistency
- between storage and retrieval operations.
- """
+ """Single source of truth for cache key format, shared between storage and retrieval."""
return f"{self.CACHE_KEY_PREFIX}:{location_key}:{date_key}:{field_name}"
diff --git a/src/hi/apps/weather/enums.py b/src/hi/apps/weather/enums.py
index 020d8800..35730768 100644
--- a/src/hi/apps/weather/enums.py
+++ b/src/hi/apps/weather/enums.py
@@ -53,7 +53,7 @@ class MoonPhase( LabeledEnum ):
@classmethod
def from_illumination( cls, illumination_percent : float, is_waxing : bool ):
- """ Thresholds are balanced for people's perceptions, not technicla deifnitions. """
+ """ Thresholds are balanced for people's perceptions, not technical definitions. """
if is_waxing:
if illumination_percent <= 3:
return cls.NEW_MOON
@@ -106,7 +106,6 @@ class AlertSeverity( LabeledEnum ):
UNKNOWN = ( 'Unknown' , '' )
def css_class(self):
- """Return Bootstrap alert CSS class for this severity level."""
severity_css_map = {
'EXTREME': 'danger',
'SEVERE': 'warning',
@@ -141,10 +140,7 @@ class AlertStatus( LabeledEnum ):
class WeatherEventType( LabeledEnum ):
- """
- Canonical weather event types that can come from multiple data sources.
- This provides a standardized classification system for weather alerts.
- """
+ """ Canonical weather event types unified across data sources. """
# Severe Weather Events
TORNADO = ( 'Tornado' , 'Rotating column of air extending from thunderstorm to ground' )
diff --git a/src/hi/apps/weather/interval_data_manager.py b/src/hi/apps/weather/interval_data_manager.py
index ded14b37..ae465ad9 100644
--- a/src/hi/apps/weather/interval_data_manager.py
+++ b/src/hi/apps/weather/interval_data_manager.py
@@ -34,9 +34,9 @@ class IntervalDataManager:
self._data_class = data_class
self._aggregated_interval_data_list = list()
self._was_initialized = False
-
- # For daily intervals (24-hour), use local timezone boundaries
- # For hourly intervals (1-hour), continue using UTC boundaries
+
+ # Daily intervals (24h) use local-timezone day boundaries;
+ # hourly intervals use UTC boundaries.
self._use_local_timezone = (interval_hours == 24)
if self._use_local_timezone:
self._console_helper = ConsoleSettingsHelper()
@@ -62,7 +62,7 @@ class IntervalDataManager:
# Update intervals first to handle time passage (remove old, add new intervals)
self._update_intervals()
-
+
self._add_source_data_to_interval_data(
data_point_source = data_point_source,
source_interval_data_list = new_interval_data_list,
@@ -122,17 +122,15 @@ class IntervalDataManager:
def _get_calculated_intervals( self ):
""" Create the intervals needed for the current time. """
-
+
if self._use_local_timezone:
- # For daily intervals, use local timezone boundaries
return self._get_calculated_intervals_local_timezone()
else:
- # For hourly intervals, use UTC boundaries
return self._get_calculated_intervals_utc()
-
+
def _get_calculated_intervals_utc( self ):
""" Create UTC-based intervals (for hourly forecasts). """
-
+
now = datetimeproxy.now()
rounded_start = now.replace(
@@ -163,35 +161,30 @@ class IntervalDataManager:
def _get_calculated_intervals_local_timezone( self ):
""" Create local timezone-based intervals (for daily forecasts). """
-
- # Get current time in local timezone
+
user_timezone = self._console_helper.get_tz_name()
local_tz = pytz.timezone(user_timezone)
utc_now = datetimeproxy.now()
local_now = utc_now.astimezone(local_tz)
-
+
if self.TRACE:
logger.debug(f'Creating daily intervals for timezone: {user_timezone}')
logger.debug(f'UTC now: {utc_now}')
logger.debug(f'Local now: {local_now}')
-
- # For daily intervals, start from the beginning of the current day in local timezone
+
local_day_start = local_now.replace(hour=0, minute=0, second=0, microsecond=0)
-
- # For historical data (descending), start from yesterday
+
if not self._is_order_ascending:
local_day_start = local_day_start # Keep today's start for calculation reference
-
+
time_interval_list = list()
for idx in range( self._max_interval_count ):
if self._is_order_ascending:
- # Future dates: today, tomorrow, etc.
local_interval_start = local_day_start + timedelta(days=idx)
local_interval_end = local_day_start + timedelta(days=idx + 1)
else:
- # Past dates: yesterday, day before yesterday, etc.
- # idx=0 should be yesterday, idx=1 should be day before yesterday, etc.
+ # idx=0 is yesterday, idx=1 is day before yesterday, etc.
local_interval_start = local_day_start - timedelta(days=idx + 1)
local_interval_end = local_day_start - timedelta(days=idx)
diff --git a/src/hi/apps/weather/model_helpers.py b/src/hi/apps/weather/model_helpers.py
index 3cefb297..6a96d874 100644
--- a/src/hi/apps/weather/model_helpers.py
+++ b/src/hi/apps/weather/model_helpers.py
@@ -1,9 +1,6 @@
"""
-Helper utilities for working with weather model types and DataPoint field detection.
-
-This module provides robust utilities for detecting and working with DataPoint fields
-in dataclass-based weather models, handling various type annotation patterns including
-direct types, Union types, and Optional types.
+Helper utilities for detecting DataPoint fields in dataclass-based weather models,
+handling direct types, Union types, and Optional types.
"""
from typing import get_origin, get_args, Union
@@ -14,47 +11,25 @@ from .transient_models import DataPoint
def extract_datapoint_type(field_type) -> tuple[type | None, bool]:
"""
- Extract the DataPoint type from a field type annotation, handling various type patterns.
-
- This function robustly handles:
- - Direct DataPoint types: NumericDataPoint
- - Union types (Python 3.10+): NumericDataPoint | None
- - Optional types: Optional[NumericDataPoint]
- - Complex unions with multiple types
-
- Args:
- field_type: The type annotation from a dataclass field
-
- Returns:
- Tuple of (datapoint_class, is_optional) where:
- - datapoint_class: The DataPoint subclass, or None if not a DataPoint field
- - is_optional: True if the field can be None
-
- Examples:
- >>> extract_datapoint_type(NumericDataPoint)
- (NumericDataPoint, False)
- >>> extract_datapoint_type(NumericDataPoint | None)
- (NumericDataPoint, True)
- >>> extract_datapoint_type(Optional[StringDataPoint])
- (StringDataPoint, True)
- >>> extract_datapoint_type(str)
- (None, False)
+ Extract the DataPoint subclass (if any) and optionality from a dataclass field's
+ type annotation. Handles direct types, ``T | None``, ``Optional[T]``, and unions
+ with multiple non-None members (first DataPoint subclass wins).
+
+ Returns ``(datapoint_class, is_optional)``; ``datapoint_class`` is ``None`` when
+ the field does not carry a DataPoint subclass.
"""
- # Handle direct DataPoint types
try:
if isinstance(field_type, type) and issubclass(field_type, DataPoint):
return (field_type, False)
except TypeError:
- # field_type is not a class, continue to union handling
pass
-
- # Handle Union/Optional types
+
origin = get_origin(field_type)
if origin is Union or origin is types.UnionType:
args = get_args(field_type)
datapoint_type = None
is_optional = False
-
+
for arg in args:
if arg is type(None):
is_optional = True
@@ -67,111 +42,31 @@ def extract_datapoint_type(field_type) -> tuple[type | None, bool]:
else:
datapoint_type = arg
except TypeError:
- # arg is not a class, skip
continue
-
+
return (datapoint_type, is_optional)
-
- # Not a DataPoint field
+
return (None, False)
def is_datapoint_field(field_type) -> bool:
- """
- Check if a field type represents a DataPoint field (directly or optionally).
-
- Args:
- field_type: The type annotation from a dataclass field
-
- Returns:
- True if the field can contain a DataPoint, False otherwise
-
- Examples:
- >>> is_datapoint_field(NumericDataPoint)
- True
- >>> is_datapoint_field(NumericDataPoint | None)
- True
- >>> is_datapoint_field(Optional[StringDataPoint])
- True
- >>> is_datapoint_field(str)
- False
- >>> is_datapoint_field(int | None)
- False
- """
datapoint_class, _ = extract_datapoint_type(field_type)
return datapoint_class is not None
def get_datapoint_class(field_type) -> type | None:
- """
- Get the DataPoint class from a field type, ignoring optionality.
-
- Args:
- field_type: The type annotation from a dataclass field
-
- Returns:
- The DataPoint subclass, or None if not a DataPoint field
-
- Examples:
- >>> get_datapoint_class(NumericDataPoint | None)
- <class 'NumericDataPoint'>
- >>> get_datapoint_class(Optional[StringDataPoint])
- <class 'StringDataPoint'>
- >>> get_datapoint_class(str)
- None
- """
datapoint_class, _ = extract_datapoint_type(field_type)
return datapoint_class
def create_datapoint_instance(field_type, **kwargs):
- """
- Create an instance of the appropriate DataPoint type for a field.
-
- Args:
- field_type: The type annotation from a dataclass field
- **kwargs: Arguments to pass to the DataPoint constructor
-
- Returns:
- Instance of the DataPoint subclass
-
- Raises:
- ValueError: If field_type is not a DataPoint field
- TypeError: If constructor arguments are invalid
-
- Example:
- >>> # For a field annotated as NumericDataPoint | None
- >>> dp = create_datapoint_instance(
- ... field.type,
- ... station=station,
- ... source_datetime=now,
- ... quantity_ave=UnitQuantity(25.0, 'degC')
- ... )
- """
datapoint_class = get_datapoint_class(field_type)
if datapoint_class is None:
raise ValueError(f"Field type {field_type} is not a DataPoint field")
-
+
return datapoint_class(**kwargs)
def is_field_optional(field_type) -> bool:
- """
- Check if a field type is optional (can be None).
-
- Args:
- field_type: The type annotation from a dataclass field
-
- Returns:
- True if the field can be None, False otherwise
-
- Examples:
- >>> is_field_optional(NumericDataPoint | None)
- True
- >>> is_field_optional(Optional[StringDataPoint])
- True
- >>> is_field_optional(NumericDataPoint)
- False
- """
_, is_optional = extract_datapoint_type(field_type)
return is_optional
diff --git a/src/hi/apps/weather/monitors.py b/src/hi/apps/weather/monitors.py
index c3b88eb5..9b08f189 100644
--- a/src/hi/apps/weather/monitors.py
+++ b/src/hi/apps/weather/monitors.py
@@ -44,7 +44,6 @@ class WeatherMonitor( PeriodicMonitor, SettingsMixin ):
api_health_status_provider_sequence = discovered_sources,
)
- # During startup safety/warmup, consider everything healthy.
for weather_data_source in self._weather_data_source_instance_list:
is_enabled = await self._settings_helper.is_weather_source_enabled_async(
weather_data_source.id
diff --git a/src/hi/apps/weather/settings.py b/src/hi/apps/weather/settings.py
index c66afe9f..1218dd90 100644
--- a/src/hi/apps/weather/settings.py
+++ b/src/hi/apps/weather/settings.py
@@ -9,14 +9,13 @@ Label = 'Weather'
def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
"""Dynamically create settings based on discovered weather sources."""
from .weather_source_discovery import WeatherSourceDiscovery
-
+
settings_dict = {}
discovered_sources = WeatherSourceDiscovery.discover_weather_data_source_instances()
-
+
for source in discovered_sources:
source_key_prefix = source.id.upper().replace( '-', '_' )
- # Create enabled/disabled setting for each source
enabled_key = f"{source_key_prefix}_ENABLED"
settings_dict[enabled_key] = SettingDefinition(
label=f'Enable {source.label}',
@@ -46,7 +45,6 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
initial_value=canonical_base_url,
)
- # Create API key setting if source requires it
if source.requires_api_key():
api_key_key = f"{source_key_prefix}_API_KEY"
settings_dict[api_key_key] = SettingDefinition(
@@ -59,7 +57,6 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
initial_value='',
)
- # Add general weather settings
settings_dict['DEFAULT_POLLING_INTERVAL_SECONDS'] = SettingDefinition(
label='Default Polling Interval (Seconds)',
description='Default interval in seconds for polling weather data from enabled sources.',
@@ -107,6 +104,5 @@ def _create_dynamic_weather_settings() -> Dict[str, SettingDefinition]:
return settings_dict
-# Dynamically create the WeatherSetting enum
_dynamic_settings = _create_dynamic_weather_settings()
WeatherSetting = SettingEnum('WeatherSetting', _dynamic_settings)
diff --git a/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html b/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html
index 992eb7e4..9c8a5ec3 100644
--- a/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html
+++ b/src/hi/apps/weather/templates/weather/panes/astronomical_brief.html
@@ -20,7 +20,7 @@
</div>
<div>
Moon:
- {% if astronomical_data.moon_illumnination %}
+ {% if astronomical_data.moon_illumination %}
{% with astronomical_data.moon_phase as moon_phase %}
<img height="32" src="{% static moon_phase.icon_filename %}"
alt="{{ moon_phase.label }}" />
diff --git a/src/hi/apps/weather/templates/weather/panes/astronomical_daily.html b/src/hi/apps/weather/templates/weather/panes/astronomical_daily.html
index 57e5e00a..1e4e4241 100644
--- a/src/hi/apps/weather/templates/weather/panes/astronomical_daily.html
+++ b/src/hi/apps/weather/templates/weather/panes/astronomical_daily.html
@@ -12,31 +12,31 @@
<th>Moon</th>
</thead>
<tbody>
- {% for interval_astronommical in daily_astronomical_data.data_list %}
+ {% for interval_astronomical in daily_astronomical_data.data_list %}
<tr>
- <td>{{ interval_astronommical.interval.start |localtime|date:"n/j" }}
+ <td>{{ interval_astronomical.interval.start |localtime|date:"n/j" }}
</td>
<td>
- {% if interval_astronommical.data.sunrise %}
- {{ interval_astronommical.data.sunrise.value }}
+ {% if interval_astronomical.data.sunrise %}
+ {{ interval_astronomical.data.sunrise.value }}
{% else %}
--
{% endif %}
</td>
<td>
- {% if interval_astronommical.data.sunset %}
- {{ interval_astronommical.data.sunset.value }}
+ {% if interval_astronomical.data.sunset %}
+ {{ interval_astronomical.data.sunset.value }}
{% else %}
--
{% endif %}
</td>
<td>
- {% if interval_astronommical.data.moon_illumnination %}
- {% with interval_astronommical.data.moon_phase as moon_phase %}
+ {% if interval_astronomical.data.moon_illumination %}
+ {% with interval_astronomical.data.moon_phase as moon_phase %}
<img height="32" src="{% static moon_phase.icon_filename %}"
alt="{{ moon_phase.label }}" />
{% endwith %}
- {{ interval_astronommical.data.moon_illumnination.quantity }}
+ {{ interval_astronomical.data.moon_illumination.quantity }}
{% else %}
--
{% endif %}
diff --git a/src/hi/apps/weather/templates/weather/panes/astronomical_extended.html b/src/hi/apps/weather/templates/weather/panes/astronomical_extended.html
index bd43c506..3b5af97c 100644
--- a/src/hi/apps/weather/templates/weather/panes/astronomical_extended.html
+++ b/src/hi/apps/weather/templates/weather/panes/astronomical_extended.html
@@ -20,7 +20,7 @@
</div>
<div>
Moon:
- {% if astronomical_data.moon_illumnination %}
+ {% if astronomical_data.moon_illumination %}
{% if astronomical_data.moon_is_waxing.value %}Waxing{% else %}Waning{% endif %}
{% else %}
--
@@ -31,16 +31,16 @@
<div class="d-flex justify-content-around">
<div>
Moon Illumination:
- {% if astronomical_data.moon_illumnination %}
- {{ astronomical_data.moon_illumnination.quantity|format_magnitude:1 }}
- <small>{{ astronomical_data.moon_illumnination.quantity|format_units }}</small>
+ {% if astronomical_data.moon_illumination %}
+ {{ astronomical_data.moon_illumination.quantity|format_magnitude:1 }}
+ <small>{{ astronomical_data.moon_illumination.quantity|format_units }}</small>
{% else %}
--
{% endif %}
</div>
<div>
Moon Phase:
- {% if astronomical_data.moon_illumnination %}
+ {% if astronomical_data.moon_illumination %}
{{ moon_phase.label }}
{% else %}
--
diff --git a/src/hi/apps/weather/tests/synthetic_data.py b/src/hi/apps/weather/tests/synthetic_data.py
index f3d0acb1..4e0f6497 100644
--- a/src/hi/apps/weather/tests/synthetic_data.py
+++ b/src/hi/apps/weather/tests/synthetic_data.py
@@ -211,7 +211,7 @@ class WeatherSyntheticData:
second=random.randint(0, 59)
),
),
- moon_illumnination=NumericDataPoint(
+ moon_illumination=NumericDataPoint(
station=station,
source_datetime=now,
quantity_ave=UnitQuantity(random.randint(0, 100), 'percent'),
diff --git a/src/hi/apps/weather/tests/test_transient_models.py b/src/hi/apps/weather/tests/test_transient_models.py
index 052af583..b453c6d7 100644
--- a/src/hi/apps/weather/tests/test_transient_models.py
+++ b/src/hi/apps/weather/tests/test_transient_models.py
@@ -393,7 +393,7 @@ class TestWeatherTransientModels(BaseTestCase):
for illumination, is_waxing, expected_phase in test_cases:
with self.subTest(illumination=illumination, waxing=is_waxing):
astro_data = AstronomicalData(
- moon_illumnination=NumericDataPoint(
+ moon_illumination=NumericDataPoint(
station=self.test_station,
source_datetime=self.test_datetime,
quantity_ave=UnitQuantity(illumination, 'percent')
@@ -421,7 +421,7 @@ class TestWeatherTransientModels(BaseTestCase):
# Missing waxing status
astro_data = AstronomicalData(
- moon_illumnination=NumericDataPoint(
+ moon_illumination=NumericDataPoint(
station=self.test_station,
source_datetime=self.test_datetime,
quantity_ave=UnitQuantity(50, 'percent')
@@ -447,7 +447,7 @@ class TestWeatherTransientModels(BaseTestCase):
for test_data in test_data_list:
with self.subTest(test_data=test_data):
astro_data = AstronomicalData(
- moon_illumnination=NumericDataPoint(
+ moon_illumination=NumericDataPoint(
station=self.test_station,
source_datetime=self.test_datetime,
quantity_ave=UnitQuantity(test_data['percent'], 'percent')
@@ -483,7 +483,7 @@ class TestWeatherTransientModels(BaseTestCase):
for test_data in test_data_list:
with self.subTest(test_data=test_data):
astro_data = AstronomicalData(
- moon_illumnination=NumericDataPoint(
+ moon_illumination=NumericDataPoint(
station=self.test_station,
source_datetime=self.test_datetime,
quantity_ave=UnitQuantity(test_data['percent'], 'percent')
@@ -653,7 +653,7 @@ class TestWeatherTransientModels(BaseTestCase):
"""Test the bug fix for moon_phase null safety"""
# Test with missing moon_is_waxing
astro_data = AstronomicalData(
- moon_illumnination=NumericDataPoint(
+ moon_illumination=NumericDataPoint(
station=self.test_station,
source_datetime=self.test_datetime,
quantity_ave=UnitQuantity(50, 'percent')
@@ -664,9 +664,9 @@ class TestWeatherTransientModels(BaseTestCase):
# Should return None safely, not crash
self.assertIsNone(astro_data.moon_phase)
- # Test with missing moon_illumnination
+ # Test with missing moon_illumination
astro_data2 = AstronomicalData(
- moon_illumnination=None,
+ moon_illumination=None,
moon_is_waxing=BooleanDataPoint(
station=self.test_station,
source_datetime=self.test_datetime,
diff --git a/src/hi/apps/weather/tests/test_usno.py b/src/hi/apps/weather/tests/test_usno.py
index f50186f1..ad5bcffe 100644
--- a/src/hi/apps/weather/tests/test_usno.py
+++ b/src/hi/apps/weather/tests/test_usno.py
@@ -119,9 +119,9 @@ class TestUSNO(BaseTestCase):
self.assertEqual(result.moonset.value, time(0, 52))
# Verify moon phase data
- self.assertIsNotNone(result.moon_illumnination)
- self.assertIsInstance(result.moon_illumnination, NumericDataPoint)
- self.assertEqual(result.moon_illumnination.quantity_ave.magnitude, 35.0)
+ self.assertIsNotNone(result.moon_illumination)
+ self.assertIsInstance(result.moon_illumination, NumericDataPoint)
+ self.assertEqual(result.moon_illumination.quantity_ave.magnitude, 35.0)
self.assertIsNotNone(result.moon_is_waxing)
self.assertIsInstance(result.moon_is_waxing, BooleanDataPoint)
@@ -399,7 +399,7 @@ class TestUSNO(BaseTestCase):
self.assertIsInstance(result, AstronomicalData)
self.assertIsNone(result.sunrise)
self.assertIsNone(result.sunset)
- self.assertIsNone(result.moon_illumnination)
+ self.assertIsNone(result.moon_illumination)
return
@patch('hi.apps.common.datetimeproxy.now')
@@ -455,9 +455,9 @@ class TestUSNO(BaseTestCase):
self.assertEqual(result.moonset.value, time(0, 52))
# Verify moon phase data - this is the key new feature
- self.assertIsInstance(result.moon_illumnination, NumericDataPoint)
- self.assertEqual(result.moon_illumnination.quantity.magnitude, 35.0)
- self.assertEqual(result.moon_illumnination.quantity.units, UnitQuantity(1, 'percent').units)
+ self.assertIsInstance(result.moon_illumination, NumericDataPoint)
+ self.assertEqual(result.moon_illumination.quantity.magnitude, 35.0)
+ self.assertEqual(result.moon_illumination.quantity.units, UnitQuantity(1, 'percent').units)
self.assertIsInstance(result.moon_is_waxing, BooleanDataPoint)
self.assertTrue(result.moon_is_waxing.value)
@@ -555,7 +555,7 @@ class TestUSNO(BaseTestCase):
self.assertIsNone(result.sunset)
# Should not have moon phase data without fracillum
- self.assertIsNone(result.moon_illumnination)
+ self.assertIsNone(result.moon_illumination)
self.assertIsNone(result.moon_is_waxing)
return
@@ -620,7 +620,7 @@ class TestUSNO(BaseTestCase):
source_datetime = mock_today,
value = time(7, 40),
),
- moon_illumnination = NumericDataPoint(
+ moon_illumination = NumericDataPoint(
station = Station(
source = self.usno.data_point_source,
station_id = 'test-station',
@@ -724,7 +724,7 @@ class TestUSNO(BaseTestCase):
source_datetime = source_datetime,
value = time(7, 40),
),
- moon_illumnination = NumericDataPoint(
+ moon_illumination = NumericDataPoint(
station = station,
source_datetime = source_datetime,
quantity_ave = UnitQuantity(35.0, 'percent'),
@@ -740,7 +740,7 @@ class TestUSNO(BaseTestCase):
# Test data_source_counts property
source_counts = astronomical_data.data_source_counts
self.assertEqual(len(source_counts), 1)
- self.assertEqual(source_counts[source], 2) # sunrise + moon_illumnination
+ self.assertEqual(source_counts[source], 2) # sunrise + moon_illumination
return
def test_moon_phase_integration(self):
@@ -770,7 +770,7 @@ class TestUSNO(BaseTestCase):
for illumination, is_waxing, expected_phase_name in test_cases:
astronomical_data = AstronomicalData(
- moon_illumnination = NumericDataPoint(
+ moon_illumination = NumericDataPoint(
station = station,
source_datetime = source_datetime,
quantity_ave = UnitQuantity(illumination, 'percent'),
diff --git a/src/hi/apps/weather/transient_models.py b/src/hi/apps/weather/transient_models.py
index 9245b0a7..f7cdd283 100644
--- a/src/hi/apps/weather/transient_models.py
+++ b/src/hi/apps/weather/transient_models.py
@@ -79,7 +79,7 @@ class DataPoint:
@property
def value_str(self):
- # Use the default dataclass representation to avoid recursion
+ # Use the default dataclass representation to avoid recursion via __str__
return super().__str__()
@property
@@ -95,7 +95,7 @@ class DataPoint:
return self.station.source
-T = TypeVar("T") # Define a generic type placeholder
+T = TypeVar("T")
@dataclass( kw_only = True )
@@ -148,12 +148,11 @@ class NumericDataPoint( DataPoint ):
self.quantity_max = self.quantity_ave
elif self.quantity_min is not None and self.quantity_max is not None:
if self.quantity_ave is None:
- # For offset units (like Celsius), convert to absolute units for arithmetic
try:
self.quantity_ave = ( self.quantity_min + self.quantity_max ) / 2.0
except OffsetUnitCalculusError:
- # Handle offset unit arithmetic by converting to absolute units
- # Convert to absolute units (e.g., Celsius -> Kelvin), average, then convert back
+ # Offset units (e.g. Celsius) cannot be averaged directly;
+ # convert to base (Kelvin), average, then convert back.
min_abs = self.quantity_min.to_base_units()
max_abs = self.quantity_max.to_base_units()
ave_abs = (min_abs + max_abs) / 2.0
@@ -193,8 +192,7 @@ class EnvironmentalData:
for a_field in fields( self ):
field_name = a_field.name
datapoint = getattr( self, field_name )
-
- # Check if the actual value is a DataPoint instance (not the type annotation)
+
if not isinstance( datapoint, DataPoint ):
continue
if not datapoint.station:
@@ -203,15 +201,13 @@ class EnvironmentalData:
continue
return list( station_map.values() )
- @property
+ @property
def data_source_counts(self) -> Dict[DataPointSource, int]:
- """Get counts of DataPoint fields by data source."""
source_counts = dict()
for a_field in fields( self ):
field_name = a_field.name
datapoint = getattr( self, field_name )
-
- # Check if the actual value is a DataPoint instance (not the type annotation)
+
if not isinstance( datapoint, DataPoint ):
continue
if not datapoint.source:
@@ -224,8 +220,7 @@ class EnvironmentalData:
@property
def data_sources(self) -> Set[DataPointSource]:
- """Get all data sources that have at least one DataPoint field."""
- return set(self.data_source_counts.keys())
+ return set(self.data_source_counts.keys())
@dataclass( kw_only = True )
@@ -314,7 +309,7 @@ class AstronomicalData( EnvironmentalData ):
solar_noon : TimeDataPoint | None = None
moonrise : TimeDataPoint | None = None
moonset : TimeDataPoint | None = None
- moon_illumnination : NumericDataPoint | None = None # Percent
+ moon_illumination : NumericDataPoint | None = None # Percent
moon_is_waxing : BooleanDataPoint | None = None
civil_twilight_begin : TimeDataPoint | None = None
civil_twilight_end : TimeDataPoint | None = None
@@ -325,10 +320,10 @@ class AstronomicalData( EnvironmentalData ):
@property
def moon_phase(self) -> MoonPhase:
- if self.moon_illumnination is None or self.moon_is_waxing is None:
+ if self.moon_illumination is None or self.moon_is_waxing is None:
return None
return MoonPhase.from_illumination(
- illumination_percent = self.moon_illumnination.quantity.magnitude,
+ illumination_percent = self.moon_illumination.quantity.magnitude,
is_waxing = self.moon_is_waxing.value,
)
@@ -338,7 +333,7 @@ class AstronomicalData( EnvironmentalData ):
return 0
if not self.moon_is_waxing.value:
return round( 14.77 + self.days_until_new_moon )
- return round( 14.77 * (( 100.0 - self.moon_illumnination.quantity.magnitude ) / 100.0 ))
+ return round( 14.77 * (( 100.0 - self.moon_illumination.quantity.magnitude ) / 100.0 ))
@property
def days_until_new_moon(self):
@@ -346,7 +341,7 @@ class AstronomicalData( EnvironmentalData ):
return 0
if self.moon_is_waxing.value:
return round( 14.77 + self.days_until_full_moon )
- return round( 14.77 * ( self.moon_illumnination.quantity.magnitude / 100.0 ))
+ return round( 14.77 * ( self.moon_illumination.quantity.magnitude / 100.0 ))
@dataclass( kw_only = True, frozen = True )
@@ -356,7 +351,7 @@ class TimeInterval:
name : StringDataPoint | None = None
def __post_init__(self):
- # Invariant is start time always less that end time.
+ # Invariant: start time always less than end time.
assert self.start < self.end
return
diff --git a/src/hi/apps/weather/views.py b/src/hi/apps/weather/views.py
index d0734d28..e3e5d95e 100644
--- a/src/hi/apps/weather/views.py
+++ b/src/hi/apps/weather/views.py
@@ -32,14 +32,12 @@ class TodaysAstronomicalDetailsView( HiModalView, WeatherMixin ):
def get(self, request, *args, **kwargs):
todays_astronomical_data = self.weather_manager().get_todays_astronomical_data()
daily_astronomical_data = self.weather_manager().get_daily_astronomical_data()
-
- # Check if any astronomical data comes from sunrise-sunset-org source
+
has_sunrise_sunset_data = bool(
todays_astronomical_data
and SunriseSunsetOrg.SOURCE_ID in {x.id for x in todays_astronomical_data.data_sources}
)
-
- # Check if any astronomical data comes from USNO source
+
has_usno_data = bool(
todays_astronomical_data
and USNO.SOURCE_ID in {x.id for x in todays_astronomical_data.data_sources}
diff --git a/src/hi/apps/weather/weather_alert_alarm_mapper.py b/src/hi/apps/weather/weather_alert_alarm_mapper.py
index e61eafa9..b804af5c 100644
--- a/src/hi/apps/weather/weather_alert_alarm_mapper.py
+++ b/src/hi/apps/weather/weather_alert_alarm_mapper.py
@@ -1,14 +1,8 @@
"""
-Weather Alert to System Alarm Mapping
+Convert weather alerts (using canonical WeatherEventType) into system alarms.
-This module handles the conversion of weather alerts (using canonical WeatherEventType)
-into system alarms that can trigger notifications and user alerts.
-
-The mapping strategy is based on:
-1. Event type significance (life-threatening vs informational)
-2. Alert severity level
-3. Alert status (actual vs test/exercise)
-4. Alert urgency and certainty
+Mapping inputs: event type significance (life-threatening vs informational),
+alert severity, alert status (actual vs test/exercise), urgency, and certainty.
"""
import logging
from typing import List, Optional
@@ -182,73 +176,47 @@ class WeatherAlertAlarmMapper:
DEFAULT_LIFETIME_SECS = 4 * 60 * 60 # 4 hours
def should_create_alarm(self, weather_alert: WeatherAlert) -> bool:
- """
- Determine if a weather alert should create a system alarm.
-
- Args:
- weather_alert: The weather alert to evaluate
-
- Returns:
- True if this alert should create a system alarm
- """
- # Never create alarms for test messages or exercises
if weather_alert.status in [AlertStatus.TEST, AlertStatus.EXERCISE, AlertStatus.DRAFT]:
return False
-
- # Always create alarms for critical event types
+
if weather_alert.event_type in self.CRITICAL_EVENT_TYPES:
return True
-
- # For severity-dependent events, check severity level
+
if weather_alert.event_type in self.SEVERITY_DEPENDENT_EVENT_TYPES:
- # Create alarms for EXTREME and SEVERE, optionally for MODERATE based on urgency
if weather_alert.severity in [AlertSeverity.EXTREME, AlertSeverity.SEVERE]:
return True
if ( weather_alert.severity == AlertSeverity.MODERATE
and weather_alert.urgency == AlertUrgency.IMMEDIATE ):
return True
-
- # Don't create alarms for informational events
+
if weather_alert.event_type in self.INFORMATIONAL_EVENT_TYPES:
return False
-
- # For other event types, be conservative - only create for EXTREME severity
+
+ # Conservative fallback for unclassified event types: alarm only on EXTREME.
if weather_alert.severity == AlertSeverity.EXTREME:
return True
-
+
return False
def get_alarm_level(self, weather_alert: WeatherAlert) -> Optional[AlarmLevel]:
- """
- Determine the appropriate alarm level for a weather alert.
-
- Args:
- weather_alert: The weather alert to map
-
- Returns:
- The appropriate AlarmLevel or None if no alarm should be created
- """
if not self.should_create_alarm(weather_alert):
return None
-
- # Get base alarm level from event type
+
base_level = self.EVENT_TYPE_TO_BASE_ALARM_LEVEL.get(
- weather_alert.event_type,
+ weather_alert.event_type,
AlarmLevel.INFO
)
-
- # Adjust based on severity
+
+ # Severity adjustment: EXTREME always CRITICAL; SEVERE at least WARNING (CRITICAL
+ # only if base is CRITICAL); MODERATE caps at WARNING; MINOR caps at INFO.
if weather_alert.severity == AlertSeverity.EXTREME:
- # Extreme severity always gets CRITICAL
return AlarmLevel.CRITICAL
elif weather_alert.severity == AlertSeverity.SEVERE:
- # Severe gets at least WARNING, could be CRITICAL for critical event types
if base_level == AlarmLevel.CRITICAL:
return AlarmLevel.CRITICAL
else:
return AlarmLevel.WARNING
elif weather_alert.severity == AlertSeverity.MODERATE:
- # Moderate gets at most WARNING
if base_level == AlarmLevel.CRITICAL:
return AlarmLevel.WARNING
elif base_level == AlarmLevel.WARNING:
@@ -256,60 +224,28 @@ class WeatherAlertAlarmMapper:
else:
return AlarmLevel.INFO
else: # MINOR
- # Minor severity gets at most INFO
return AlarmLevel.INFO
def get_alarm_lifetime(self, weather_alert: WeatherAlert) -> int:
- """
- Calculate appropriate alarm lifetime for the weather alert.
-
- Args:
- weather_alert: The weather alert to calculate lifetime for
-
- Returns:
- Alarm lifetime in seconds
- """
- # If the weather alert has an expiration time, use that
+ """ Alarm lifetime in seconds. """
if weather_alert.expires:
now = datetimeproxy.now()
if weather_alert.expires > now:
lifetime_seconds = int((weather_alert.expires - now).total_seconds())
# Cap at reasonable maximum (48 hours) and minimum (15 minutes)
return max(15 * 60, min(lifetime_seconds, 48 * 60 * 60))
-
- # Use event type-based lifetime
+
return self.EVENT_TYPE_TO_LIFETIME.get(
- weather_alert.event_type,
+ weather_alert.event_type,
self.DEFAULT_LIFETIME_SECS
)
def get_alarm_type(self, weather_alert: WeatherAlert) -> str:
- """
- Generate alarm type string for the weather alert.
-
- This creates a consistent alarm type based on the canonical event type,
- which will be used in the alarm signature for grouping similar alerts.
-
- Args:
- weather_alert: The weather alert to generate type for
-
- Returns:
- A string representing the alarm type
- """
- # Use the canonical event type name as the alarm type
- # This ensures consistent grouping across different weather sources
+ """ Alarm-type string; canonical event-type name groups equivalent alerts
+ across different weather sources in the alarm signature. """
return weather_alert.event_type.name
def create_sensor_responses(self, weather_alert: WeatherAlert) -> List[SensorResponse]:
- """
- Create sensor responses from weather alert information.
-
- Args:
- weather_alert: The weather alert to create sensor responses for
-
- Returns:
- List of SensorResponse for this weather alert
- """
detail_attrs = {
'Event Type': weather_alert.event_type.label,
'Source Event': weather_alert.event,
@@ -322,71 +258,54 @@ class WeatherAlertAlarmMapper:
'Effective': weather_alert.effective.strftime('%Y-%m-%d %H:%M:%S') if weather_alert.effective else 'Unknown',
}
- # Add optional fields if available
if weather_alert.expires:
detail_attrs['Expires'] = weather_alert.expires.strftime('%Y-%m-%d %H:%M:%S')
-
+
if weather_alert.instruction:
- # Truncate instructions for alarm details
instruction = weather_alert.instruction
if len(instruction) > 200:
instruction = instruction[:200] + '...'
detail_attrs['Instructions'] = instruction
-
- # Add brief description
+
if weather_alert.description:
description = weather_alert.description
if len(description) > 300:
description = description[:300] + '...'
detail_attrs['Description'] = description
-
- # Create a SensorResponse for weather alerts
- # Weather alerts don't have sensors, so we use a synthetic integration key
- # Use event type and timestamp to create a unique identifier
+
+ # Weather alerts have no associated sensor; build a synthetic integration key
+ # from event type and timestamp.
alert_id = f'{weather_alert.event_type.name}.{weather_alert.effective.timestamp() if weather_alert.effective else "unknown"}'
integration_key = IntegrationKey(
integration_id='weather',
integration_name=f'alert.{alert_id}'
)
-
+
return [SensorResponse(
integration_key=integration_key,
- value='active', # Weather alerts are active when they exist
+ value='active',
timestamp=weather_alert.effective or datetimeproxy.now(),
- sensor=None, # No sensor for weather alerts
+ sensor=None,
detail_attrs=detail_attrs,
- has_event_video_clip=False, # Weather alerts have no video
+ has_event_video_clip=False,
)]
def create_alarm(self, weather_alert: WeatherAlert) -> Optional[Alarm]:
- """
- Create a system alarm from a weather alert.
-
- Args:
- weather_alert: The weather alert to convert
-
- Returns:
- An Alarm object or None if no alarm should be created
- """
- # Check if this alert should create an alarm
if not self.should_create_alarm(weather_alert):
logger.debug(f'Weather alert does not warrant system alarm: {weather_alert.event_type.label}')
return None
-
- # Get alarm level
+
alarm_level = self.get_alarm_level(weather_alert)
if not alarm_level:
logger.debug(f'Weather alert does not map to alarm level: {weather_alert.event_type.label}')
return None
-
- # Create alarm title from headline or event type
+
title = weather_alert.headline
if not title or len(title.strip()) == 0:
title = f"{weather_alert.event_type.label} - {weather_alert.severity.label}"
-
- # Create the alarm. source_alarm_id ties this Alarm record
- # back to the specific upstream alert, so repeated polls of
- # the same active alert refresh expiry without incrementing
+
+ # source_alarm_id ties this Alarm record back to the specific upstream alert,
+ # so repeated polls of the same active alert refresh expiry without incrementing
# alarm_count.
alarm = Alarm(
alarm_source=AlarmSource.WEATHER,
@@ -404,15 +323,6 @@ class WeatherAlertAlarmMapper:
return alarm
def create_alarms_from_weather_alerts(self, weather_alerts: List[WeatherAlert]) -> List[Alarm]:
- """
- Process a list of weather alerts and create system alarms for qualifying ones.
-
- Args:
- weather_alerts: List of weather alerts to process
-
- Returns:
- List of created Alarm objects
- """
alarms = []
for weather_alert in weather_alerts:
diff --git a/src/hi/apps/weather/weather_data_source.py b/src/hi/apps/weather/weather_data_source.py
index 57293769..7630a02b 100644
--- a/src/hi/apps/weather/weather_data_source.py
+++ b/src/hi/apps/weather/weather_data_source.py
@@ -88,11 +88,11 @@ class WeatherDataSource( ApiHealthStatusProvider ):
async def get_data(self):
""" Main method periodically called to fetch data """
pass
-
+
def requires_api_key(self) -> bool:
"""Override in subclasses that require an API key."""
return False
-
+
def get_default_enabled_state(self) -> bool:
"""Override in subclasses to set default enabled/disabled state."""
return True
@@ -202,20 +202,17 @@ class WeatherDataSource( ApiHealthStatusProvider ):
from hi.apps.weather.weather_settings_helper import WeatherSettingsHelper
self._weather_settings_helper = WeatherSettingsHelper()
return self._weather_settings_helper
-
- @property
+
+ @property
def is_enabled(self) -> bool:
- """Check if this weather source is enabled in settings."""
return self._get_weather_settings_helper().is_weather_source_enabled(self._id)
-
+
@property
def api_key(self) -> str:
- """Get the API key for this weather source from settings."""
return self._get_weather_settings_helper().get_weather_source_api_key(self._id)
-
+
@property
def is_cache_enabled(self) -> bool:
- """Check if weather data caching is enabled."""
return self._get_weather_settings_helper().is_weather_cache_enabled()
@classmethod
diff --git a/src/hi/apps/weather/weather_manager.py b/src/hi/apps/weather/weather_manager.py
index cab93b1f..495ea644 100644
--- a/src/hi/apps/weather/weather_manager.py
+++ b/src/hi/apps/weather/weather_manager.py
@@ -62,30 +62,29 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
self._daily_history = DailyHistory()
self._daily_astronomical_data = DailyAstronomicalData()
self._weather_alerts = [] # List[WeatherAlert]
-
- # IntervalDataManager instances for handling API data reconciliation
+
self._hourly_forecast_manager = IntervalDataManager(
- interval_hours=1, # 1-hour intervals
- max_interval_count=48, # 48 hours of forecast
- is_order_ascending=True, # Future forecasts
+ interval_hours=1,
+ max_interval_count=48,
+ is_order_ascending=True,
data_class=WeatherForecastData
)
self._daily_forecast_manager = IntervalDataManager(
- interval_hours=24, # 24-hour intervals
- max_interval_count=10, # 10 days of forecast
- is_order_ascending=True, # Future forecasts
+ interval_hours=24,
+ max_interval_count=10,
+ is_order_ascending=True,
data_class=WeatherForecastData
)
self._daily_history_manager = IntervalDataManager(
- interval_hours=24, # 24-hour intervals
- max_interval_count=30, # 30 days of history
- is_order_ascending=False, # Past history
+ interval_hours=24,
+ max_interval_count=30,
+ is_order_ascending=False,
data_class=WeatherHistoryData
)
self._daily_astronomical_manager = IntervalDataManager(
- interval_hours=24, # 24-hour intervals
- max_interval_count=10, # 10 days of astronomical data
- is_order_ascending=True, # Future astronomical data
+ interval_hours=24,
+ max_interval_count=10,
+ is_order_ascending=True,
data_class=AstronomicalData
)
@@ -107,7 +106,6 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
return
def _initialize( self ):
- # Initialize all interval data managers
self._hourly_forecast_manager.ensure_initialized()
self._daily_forecast_manager.ensure_initialized()
self._daily_history_manager.ensure_initialized()
@@ -131,12 +129,11 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
def get_weather_pane_status(self) -> WeatherPaneStatus:
"""Status line content for the current-conditions pane,
- computed from (data freshness × weather monitor health). See
- the design discussion in the commit that introduced this for
- the cross-product rules. The pane always renders something at
- the bottom: in the healthy path, the existing
- ``At HH:MM from <SOURCE>`` timestamp; otherwise this method's
- result drives the swap to a captioned/iconified line."""
+ computed from (data freshness x weather monitor health). The
+ pane always renders something at the bottom: in the healthy
+ path, the existing ``At HH:MM from <SOURCE>`` timestamp;
+ otherwise this method's result drives the swap to a
+ captioned/iconified line."""
# Lazy imports keep the transient-models import graph quiet
# (these modules also import from weather indirectly).
from hi.apps.monitor.monitor_manager import AppMonitorManager
@@ -162,7 +159,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
health_status = provider.health_status
except KeyError:
# Monitor isn't registered. Treat the same as the defensive
- # "none × healthy" cell below — caller will surface the
+ # "none x healthy" cell below -- caller will surface the
# fallback caption.
pass
@@ -177,12 +174,11 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
return WeatherPaneStatus( is_timestamp_stale = True )
if data_state == 'none' and is_healthy:
- # Reachable in practice — the weather monitor reports
+ # Reachable in practice: the weather monitor reports
# aggregate health across multiple endpoints, so it can
# land HEALTHY when only some of the underlying endpoints
- # succeed. Operators can drill into System Info for the
- # per-endpoint detail; the pane just shows a neutral
- # fallback instead of going blank.
+ # succeed. The pane shows a neutral fallback instead of
+ # going blank.
return WeatherPaneStatus( caption_text = 'Waiting for data' )
# Non-healthy: surface the monitor's own message.
@@ -242,8 +238,8 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
new_data = weather_conditions_data,
data_point_source = data_point_source,
)
-
- # Record weather conditions for daily tracking (defensive - don't let this break main processing)
+
+ # Defensive: daily tracking failures must not break main processing
try:
location_key = self._get_location_key()
self._daily_weather_tracker.record_weather_conditions(
@@ -268,52 +264,45 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
async def update_hourly_forecast( self,
data_point_source : DataPointSource,
forecast_data_list : List[IntervalWeatherForecast] ):
- """Update hourly forecast data using IntervalDataManager for interval reconciliation."""
async with self._data_async_lock:
logger.debug( f'Adding hourly forecast : {data_point_source.id} [{len(forecast_data_list)}]' )
self._hourly_forecast_manager.add_data(
data_point_source = data_point_source,
new_interval_data_list = forecast_data_list
)
-
- # Update canonical forecast data from aggregated intervals
+
self._update_hourly_forecast_from_manager()
return
async def update_daily_forecast( self,
data_point_source : DataPointSource,
forecast_data_list : List[IntervalWeatherForecast] ):
- """Update daily forecast data using IntervalDataManager for interval reconciliation."""
async with self._data_async_lock:
logger.debug( f'Adding daily forecast: {data_point_source.id} [{len(forecast_data_list)}]' )
self._daily_forecast_manager.add_data(
data_point_source = data_point_source,
new_interval_data_list = forecast_data_list
)
-
- # Update canonical forecast data from aggregated intervals
+
self._update_daily_forecast_from_manager()
return
async def update_daily_history( self,
data_point_source : DataPointSource,
history_data_list : List[IntervalWeatherHistory] ):
- """Update daily history data using IntervalDataManager for interval reconciliation."""
async with self._data_async_lock:
logger.debug( f'Adding daily history: {data_point_source.id} [{len(history_data_list)}]' )
self._daily_history_manager.add_data(
data_point_source = data_point_source,
new_interval_data_list = history_data_list
)
-
- # Update canonical history data from aggregated intervals
+
self._update_daily_history_from_manager()
return
async def update_astronomical_data( self,
data_point_source : DataPointSource,
astronomical_data_list : List[IntervalAstronomical] ):
- """Update astronomical data using IntervalDataManager for interval reconciliation."""
async with self._data_async_lock:
logger.debug( f'Adding astronomical: {data_point_source.id}'
f' [{len(astronomical_data_list)} items]' )
@@ -321,39 +310,33 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
data_point_source = data_point_source,
new_interval_data_list = astronomical_data_list
)
- # Update canonical astronomical data from aggregated intervals
self._update_daily_astronomical_from_manager()
return
async def update_weather_alerts( self,
data_point_source : DataPointSource,
weather_alerts : List[WeatherAlert] ):
- """Update weather alerts from data sources and create system alarms for qualifying alerts."""
- # Check if weather alerts processing is enabled
weather_settings_helper = WeatherSettingsHelper()
if not await weather_settings_helper.is_weather_alerts_enabled_async():
logger.debug(f'Weather alerts processing disabled, ignoring'
f' {len(weather_alerts)} alerts from {data_point_source.id}')
return
-
+
async with self._data_async_lock:
logger.debug( f'Received weather alerts from {data_point_source.id}:'
f' {len(weather_alerts)} alerts' )
-
- # For now, simply replace all alerts with the new ones from this source
- # TODO: Future enhancement could merge alerts from multiple sources
+
+ # Replace all alerts with the new set from this source.
+ # TODO: merge alerts when multiple sources are in play.
self._weather_alerts = weather_alerts
-
- # Log alerts for development visibility
+
for alert in weather_alerts:
logger.info( f'Weather Alert: {alert.event_type.label}'
f' ({alert.event}) - {alert.severity.label} - {alert.headline}' )
-
- # Create system alarms from weather alerts
+
try:
alarms = self._weather_alert_alarm_mapper.create_alarms_from_weather_alerts(weather_alerts)
-
- # Add each alarm to the alert manager
+
alert_manager = await self.alert_manager_async()
if alert_manager:
for alarm in alarms:
@@ -361,7 +344,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
logger.info(f'Added weather alarm to system: {alarm.signature}')
else:
logger.warning('Alert manager not available, weather alarms not created')
-
+
except Exception as e:
logger.exception(f'Error creating system alarms from weather alerts: {e}')
return
@@ -377,26 +360,24 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
for field in fields( current_data ):
field_name = field.name
-
+
current_datapoint = getattr( current_data, field_name )
new_datapoint = getattr( new_data, field_name )
- # Skip fields that are not DataPoint fields (but allow None datapoints to be processed)
+ # Skip non-DataPoint fields (None is allowed and falls through below)
if current_datapoint is not None and not isinstance( current_datapoint, DataPoint ):
continue
- # Skip data not present in source's data
if new_datapoint is None:
continue
- # Always fill in blank data
if current_datapoint is None:
if self.TRACE:
logger.debug( f'Setting first data: {field_name} = {new_datapoint}' )
setattr( current_data, field_name, new_datapoint )
continue
-
- # Same and higher priority sources can overwrite as long as data is fresher.
+
+ # Same or higher priority sources can overwrite as long as data is fresher.
# (N.B. lower priority sources have larger integer values)
current_priority = current_datapoint.source.priority
new_priority = new_datapoint.source.priority
@@ -409,7 +390,7 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
if self.TRACE:
logger.debug( f'Skipping older data: {field_name} = {new_datapoint}' )
continue
-
+
# Lower priority sources can only overwrite if current data is stale and new data is newer.
if new_datapoint.source_datetime <= current_datapoint.source_datetime:
if self.TRACE:
@@ -430,61 +411,50 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
continue
return
- # Removed useless conversion methods - interval types already extend IntervalEnvironmentalData
-
- # Helper methods for updating canonical data from IntervalDataManager
-
def _update_hourly_forecast_from_manager(self):
- """Update canonical hourly forecast from aggregated interval data."""
forecast_data_list = []
for aggregated_data in self._hourly_forecast_manager._aggregated_interval_data_list:
if aggregated_data.interval_data.data:
- # Create IntervalWeatherForecast with both interval and data
interval_forecast = IntervalWeatherForecast(
interval=aggregated_data.interval_data.interval,
data=aggregated_data.interval_data.data
)
forecast_data_list.append(interval_forecast)
continue
-
+
self._hourly_forecast.data_list = forecast_data_list
return
def _update_daily_forecast_from_manager(self):
- """Update canonical daily forecast from aggregated interval data."""
forecast_data_list = []
for aggregated_data in self._daily_forecast_manager._aggregated_interval_data_list:
if aggregated_data.interval_data.data:
- # Create IntervalWeatherForecast with both interval and data
interval_forecast = IntervalWeatherForecast(
interval=aggregated_data.interval_data.interval,
data=aggregated_data.interval_data.data
)
forecast_data_list.append(interval_forecast)
continue
-
+
self._daily_forecast.data_list = forecast_data_list
return
def _update_daily_history_from_manager(self):
- """Update canonical daily history from aggregated interval data."""
history_data_list = []
for aggregated_data in self._daily_history_manager._aggregated_interval_data_list:
if aggregated_data.interval_data.data:
- # Create IntervalWeatherHistory with both interval and data
interval_history = IntervalWeatherHistory(
interval=aggregated_data.interval_data.interval,
data=aggregated_data.interval_data.data
)
history_data_list.append(interval_history)
continue
-
+
self._daily_history.data_list = history_data_list
logger.debug(f'Updated daily history: {len(history_data_list)} items in data_list')
return
def _update_daily_astronomical_from_manager(self):
- """Update canonical daily astronomical data from aggregated interval data."""
astronomical_data_list = []
for aggregated_data in self._daily_astronomical_manager._aggregated_interval_data_list:
if aggregated_data.interval_data.data:
@@ -514,20 +484,13 @@ class WeatherManager( Singleton, SettingsMixin, AlertMixin ):
}
def _get_location_key(self):
- """
- Generate a location key for the daily weather tracker.
-
- Returns:
- String key representing the geographic location
- """
console_helper = ConsoleSettingsHelper()
geo_location = console_helper.get_geographic_location()
-
+
if geo_location:
- # Create location key from lat/lon rounded to 3 decimal places
+ # Lat/lon rounded to 3 decimal places (~110m precision).
return f"{geo_location.latitude:.3f},{geo_location.longitude:.3f}"
-
- # Ultimate fallback
+
return "default"
diff --git a/src/hi/apps/weather/weather_settings_helper.py b/src/hi/apps/weather/weather_settings_helper.py
index 173a211b..1d996d04 100644
--- a/src/hi/apps/weather/weather_settings_helper.py
+++ b/src/hi/apps/weather/weather_settings_helper.py
@@ -8,23 +8,20 @@ logger = logging.getLogger(__name__)
class WeatherSettingsHelper( SettingsMixin ):
- """Helper class to access weather-related settings."""
@staticmethod
def _source_setting_prefix( source_id: str ) -> str:
return source_id.upper().replace( '-', '_' )
def _get_weather_source_enabled_value(self, source_id: str, settings_manager):
- """Private helper to get weather source enabled value with any settings manager."""
- # Dynamically find the setting enum for this source
enabled_setting_name = f"{self._source_setting_prefix(source_id)}_ENABLED"
-
+
try:
setting_enum = getattr(WeatherSetting, enabled_setting_name)
except AttributeError:
logger.warning(f'No enabled setting found for weather source: {source_id}')
return False
-
+
value = settings_manager.get_setting_value(setting_enum)
if value is None:
return False
@@ -32,9 +29,8 @@ class WeatherSettingsHelper( SettingsMixin ):
if isinstance(value, str):
return value.lower() in ('true', '1', 'yes', 'on')
return bool(value)
-
+
def is_weather_source_enabled(self, source_id: str) -> bool:
- """Check if a specific weather source is enabled."""
return self._get_weather_source_enabled_value(source_id, self.settings_manager())
async def is_weather_source_enabled_async(self, source_id: str) -> bool:
@@ -70,17 +66,15 @@ class WeatherSettingsHelper( SettingsMixin ):
return str(value) if value is not None else ''
def get_enabled_weather_sources(self) -> List[str]:
- """Get list of enabled weather source IDs."""
enabled_sources = []
-
- # Dynamically discover all weather sources and check if they're enabled
+
from .weather_source_discovery import WeatherSourceDiscovery
discovered_sources = WeatherSourceDiscovery.discover_weather_data_source_instances()
-
+
for source in discovered_sources:
if self.is_weather_source_enabled(source.id):
enabled_sources.append(source.id)
-
+
return enabled_sources
DEFAULT_POLLING_INTERVAL_SECONDS = 600
@@ -96,7 +90,6 @@ class WeatherSettingsHelper( SettingsMixin ):
return default
def get_default_polling_interval_secs(self) -> int:
- """Get the default polling interval in seconds."""
value = self.settings_manager().get_setting_value(
WeatherSetting.DEFAULT_POLLING_INTERVAL_SECONDS )
return self._coerce_int_setting(
@@ -112,7 +105,6 @@ class WeatherSettingsHelper( SettingsMixin ):
value, self.DEFAULT_POLLING_INTERVAL_SECONDS, 'polling interval' )
def get_startup_warmup_secs(self) -> int:
- """Get the startup warmup delay in seconds."""
value = self.settings_manager().get_setting_value(
WeatherSetting.STARTUP_WARMUP_SECONDS )
return self._coerce_int_setting(
@@ -128,7 +120,6 @@ class WeatherSettingsHelper( SettingsMixin ):
value, self.DEFAULT_STARTUP_WARMUP_SECONDS, 'startup warmup' )
def is_weather_cache_enabled(self) -> bool:
- """Check if weather data caching is enabled."""
return self._get_weather_cache_enabled_value(self.settings_manager())
def _get_weather_cache_enabled_value(self, settings_manager):
@@ -146,7 +137,6 @@ class WeatherSettingsHelper( SettingsMixin ):
return self._get_weather_cache_enabled_value(settings_manager)
def _get_weather_alerts_enabled_value(self, settings_manager):
- """Private helper to get weather alerts enabled value with any settings manager."""
value = settings_manager.get_setting_value(WeatherSetting.WEATHER_ALERTS_ENABLED)
if value is None:
return True
@@ -156,18 +146,15 @@ class WeatherSettingsHelper( SettingsMixin ):
return bool(value)
def is_weather_alerts_enabled(self) -> bool:
- """Check if weather alerts processing is enabled."""
return self._get_weather_alerts_enabled_value(self.settings_manager())
async def is_weather_alerts_enabled_async(self) -> bool:
- """Check if weather alerts processing is enabled (async version)."""
settings_manager = await self.settings_manager_async()
if not settings_manager:
return True
return self._get_weather_alerts_enabled_value(settings_manager)
-
+
def get_weather_source_config(self, source_id: str) -> Dict[str, any]:
- """Get complete configuration for a weather source."""
return {
'enabled': self.is_weather_source_enabled(source_id),
'api_key': self.get_weather_source_api_key(source_id),
diff --git a/src/hi/apps/weather/weather_source_discovery.py b/src/hi/apps/weather/weather_source_discovery.py
index eed99462..f54d293e 100644
--- a/src/hi/apps/weather/weather_source_discovery.py
+++ b/src/hi/apps/weather/weather_source_discovery.py
@@ -11,15 +11,12 @@ logger = logging.getLogger(__name__)
class WeatherSourceDiscovery:
- """Centralized weather data source discovery utility."""
-
+
@classmethod
def discover_weather_data_source_instances(cls) -> List[WeatherDataSource]:
"""
- Discover all WeatherDataSource instances from the weather_sources directory.
-
- This is the single source of truth for weather source discovery,
- used by both the settings system and the monitoring system.
+ Single source of truth for WeatherDataSource discovery from the
+ weather_sources directory; shared by settings and monitoring systems.
"""
from .weather_data_source import WeatherDataSource
@@ -53,7 +50,7 @@ class WeatherSourceDiscovery:
continue
except Exception as e:
logger.warning(f'Error accessing weather sources directory {sources_dir}: {e}')
-
+
# Sort by priority (lower numbers = higher priority)
discovered_sources.sort(key=lambda item: item.priority)
return discovered_sources
diff --git a/src/hi/apps/weather/weather_sources/nws.py b/src/hi/apps/weather/weather_sources/nws.py
index 4896da48..1f1f0c46 100644
--- a/src/hi/apps/weather/weather_sources/nws.py
+++ b/src/hi/apps/weather/weather_sources/nws.py
@@ -48,7 +48,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
STATIONS_DATA_CACHE_EXPIRY_SECS = 12 * 60 * 60 # Data can change, but not often
OBSERVATIONS_DATA_CACHE_EXPIRY_SECS = 5 * 60 # Cache for rate-limit risk reduction
FORECAST_DATA_CACHE_EXPIRY_SECS = 60 * 60
- ALERTS_DATA_CACHE_EXPIRY_SECS = 10 * 60 # Alerts can change frequently, short cache
+ ALERTS_DATA_CACHE_EXPIRY_SECS = 10 * 60
@classmethod
def weather_source_id(cls):
@@ -67,7 +67,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
priority = 1,
requests_per_day_limit = 432,
requests_per_polling_interval = 3,
- min_polling_interval_secs = 10 * 60, # NWS station's data seem to update only hourly
+ min_polling_interval_secs = 10 * 60, # NWS station data updates only hourly
)
self._headers = {
@@ -77,11 +77,9 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return
def requires_api_key(self) -> bool:
- """NWS does not require an API key."""
return False
-
+
def get_default_enabled_state(self) -> bool:
- """NWS is enabled by default."""
return True
async def get_data(self):
@@ -96,7 +94,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
logger.warning( 'Weather manager not available. Skipping NWS weather fetch.' )
return
- # Fetch current conditions
try:
current_conditions_data = self.get_current_conditions(
geographic_location = geographic_location,
@@ -109,7 +106,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
except Exception as e:
self._log_fetch_error( 'current conditions', e )
- # Fetch hourly forecast data
try:
interval_hourly_forecast_list = self.get_forecast_hourly(
geographic_location = geographic_location,
@@ -122,7 +118,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
except Exception as e:
self._log_fetch_error( 'hourly forecast', e )
- # Fetch 12-hour forecast data (used for daily forecast)
+ # NWS 12h forecast feeds the daily forecast slot.
try:
interval_daily_forecast_list = self.get_forecast_12h(
geographic_location = geographic_location,
@@ -135,10 +131,10 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
except Exception as e:
self._log_fetch_error( 'daily forecast', e )
- # Fetch weather alerts. Always push the result — even an empty
- # list — so removed-upstream alerts clear from our stored list.
- # NWS /alerts/active is contractually the full set of active
- # alerts, so wholesale replacement is correct.
+ # Always push the result -- even an empty list -- so
+ # removed-upstream alerts clear from our stored list. NWS
+ # /alerts/active is contractually the full set of active alerts,
+ # so wholesale replacement is correct.
try:
weather_alerts = self.get_weather_alerts(
geographic_location = geographic_location,
@@ -150,9 +146,8 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
except Exception as e:
self._log_fetch_error( 'weather alerts', e )
- # Note: NWS does not provide historical weather data or astronomical data
- # These would need to be fetched from other sources if needed
-
+ # NWS does not provide historical or astronomical data; other
+ # sources cover those.
return
def get_current_conditions( self, geographic_location : GeographicLocation ) -> WeatherConditionsData:
@@ -239,7 +234,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
timestamp_str = properties_data.get( 'timestamp' )
source_datetime = datetime.fromisoformat( timestamp_str )
except Exception as e:
- # Use current time if problem.
logger.warning( f'Missing or bad timestamp in NWS observation payload: {e}' )
source_datetime = datetimeproxy.now()
@@ -367,7 +361,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
timestamp_str = properties_data.get( 'generatedAt' )
source_datetime = datetime.fromisoformat( timestamp_str )
except Exception as e:
- # Use current time if problem.
logger.warning( f'Missing or bad timestamp in NWS hourly forecast payload: {e}' )
source_datetime = datetimeproxy.now()
@@ -384,7 +377,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
interval_weather_forecast_list = list()
for period_data in period_data_list:
- # Parse time interval
try:
interval_start_str = period_data.get( 'startTime' )
interval_start = datetime.fromisoformat( interval_start_str )
@@ -397,8 +389,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
except Exception as e:
logger.warning( f'Missing or bad endTime in NWS forecast payload: {e}' )
continue
-
- # Create name for time interval
+
interval_name = period_data.get('name')
name_data_point = None
if interval_name:
@@ -407,15 +398,13 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
source_datetime = source_datetime,
value = interval_name,
)
-
- # Create time interval
+
time_interval = TimeInterval(
start=interval_start,
end=interval_end,
name=name_data_point
)
-
- # Create weather forecast data
+
forecast_data = WeatherForecastData()
description_short = period_data.get('shortForecast')
if description_short:
@@ -474,8 +463,7 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
)
except ValueError:
logger.warning( f'Unknown NWS wind direction "{wind_direction_str}"' )
-
- # Create interval weather forecast
+
interval_weather_forecast = IntervalWeatherForecast(
interval=time_interval,
data=forecast_data
@@ -598,7 +586,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return stations_data
def _get_stations_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[ str, Any ]:
- # Can cache this data, expires 12 hours-ish (they do not change often)
points_data = self._get_points_data( geographic_location = geographic_location )
stations_url = points_data['properties']['observationStations']
@@ -630,7 +617,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return points_data
def _get_points_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[ str, Any ]:
- # Can cache this data, expires 12 hours-ish (they do not change often)
points_url = f'{self._get_base_url()}points/{geographic_location.latitude},{geographic_location.longitude}'
return self._api_get_json(
@@ -667,11 +653,10 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
if closest_station:
return closest_station
-
- # Backup if all parsing fails
+
if (( 'observationStations' in stations_data )
and len( stations_data['observationStations']) > 0 ):
- station_url = stations_data['observationStations'][0] # Choose from list????
+ station_url = stations_data['observationStations'][0]
observations_url = f'{station_url}/observations/latest'
return Station(
@@ -1017,7 +1002,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return
def get_weather_alerts( self, geographic_location : GeographicLocation ) -> List[WeatherAlert]:
- """Get active weather alerts for the given location."""
alerts_data = self._get_alerts_data( geographic_location = geographic_location )
return self._parse_alerts_data(
alerts_data = alerts_data,
@@ -1025,7 +1009,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
)
def _get_alerts_data( self, geographic_location : GeographicLocation ) -> Dict[str, Any]:
- """Get alerts data from cache or API."""
cache_key = f'ws:{self.id}:alerts:{geographic_location.latitude:.3f}:{geographic_location.longitude:.3f}'
alerts_data_str = self.redis_client.get(cache_key)
@@ -1049,7 +1032,6 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return alerts_data
def _get_alerts_data_from_api( self, geographic_location : GeographicLocation ) -> Dict[str, Any]:
- """Make API call to NWS for alerts data."""
alerts_url = f'{self._get_base_url()}alerts/active?point={geographic_location.latitude},{geographic_location.longitude}'
logger.debug(f'NWS alerts API request: {alerts_url}')
@@ -1059,10 +1041,9 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
headers = self._headers,
)
- def _parse_alerts_data( self,
+ def _parse_alerts_data( self,
alerts_data : Dict[str, Any],
geographic_location : GeographicLocation ) -> List[WeatherAlert]:
- """Parse NWS alerts API response into WeatherAlert objects."""
weather_alerts = []
features = alerts_data.get('features', [])
@@ -1077,69 +1058,60 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
continue
# NWS publishes a stable per-alert id at the feature
- # level (typically a URI). Threading it onto the
- # parsed WeatherAlert lets the alarm mapper use it as
+ # level (typically a URI). Threading it onto the parsed
+ # WeatherAlert lets the alarm mapper use it as
# source_alarm_id to dedup repeat polls of the same
# active alert.
alert_id = feature.get('id')
- # Extract basic alert information
event = properties.get('event', 'Unknown Event')
headline = properties.get('headline', '')
description = properties.get('description', '')
instruction = properties.get('instruction', '')
area_desc = properties.get('areaDesc', '')
-
- # Parse status using NwsConverters
+
status_str = properties.get('status', 'Actual')
status = NwsConverters.to_alert_status(status_str)
if status is None:
logger.warning(f'Unknown alert status: {status_str}')
status = AlertStatus.ACTUAL
-
- # Parse severity using NwsConverters
+
severity_str = properties.get('severity', 'Minor')
- severity = NwsConverters.to_alerts_severity(severity_str) # Note: using existing typo
+ severity = NwsConverters.to_alert_severity(severity_str)
if severity is None:
logger.warning(f'Unknown alert severity: {severity_str}')
severity = AlertSeverity.MINOR
-
- # Parse urgency using NwsConverters
+
urgency_str = properties.get('urgency', 'Unknown')
urgency = NwsConverters.to_alert_urgency(urgency_str)
if urgency is None:
logger.warning(f'Unknown alert urgency: {urgency_str}')
urgency = AlertUrgency.UNKNOWN
-
- # Parse certainty using NwsConverters
+
certainty_str = properties.get('certainty', 'Possible')
certainty = NwsConverters.to_alert_certainty(certainty_str)
if certainty is None:
logger.warning(f'Unknown alert certainty: {certainty_str}')
certainty = AlertCertainty.POSSIBLE
-
- # Parse category using NwsConverters (check for category field, default to meteorological)
+
category_str = properties.get('category', 'met')
category = NwsConverters.to_alert_category(category_str)
if category is None:
category = AlertCategory.METEOROLOGICAL
-
- # Extract NWS event code and convert to canonical event type
+
event_code = None
event_code_data = properties.get('eventCode', {})
if event_code_data and 'NationalWeatherService' in event_code_data:
nws_codes = event_code_data['NationalWeatherService']
if nws_codes and len(nws_codes) > 0:
- event_code = nws_codes[0] # Take the first code
-
- # Convert to canonical event type (with fallback to event name)
+ event_code = nws_codes[0]
+
if event_code:
event_type = NwsConverters.to_weather_event_type(event_code)
else:
event_type = NwsConverters.to_weather_event_type_from_event_name(event)
logger.debug(f'No event code found for {event}, using fallback mapping to {event_type}')
-
- # Parse timestamps
+
try:
effective = self._parse_iso_datetime(properties.get('effective'))
expires = self._parse_iso_datetime(properties.get('expires'))
@@ -1181,12 +1153,9 @@ class NationalWeatherService( WeatherDataSource, WeatherMixin ):
return weather_alerts
def _parse_iso_datetime(self, iso_string: str) -> datetime:
- """Parse ISO datetime string to datetime object."""
if not iso_string:
return None
try:
- # Handle ISO format with timezone info
return datetime.fromisoformat(iso_string.replace('Z', '+00:00'))
except ValueError:
- # Fallback for other formats
return datetimeproxy.iso_to_datetime_utc(iso_string)
diff --git a/src/hi/apps/weather/weather_sources/nws_converters.py b/src/hi/apps/weather/weather_sources/nws_converters.py
index d9c54e47..b15e49da 100644
--- a/src/hi/apps/weather/weather_sources/nws_converters.py
+++ b/src/hi/apps/weather/weather_sources/nws_converters.py
@@ -115,7 +115,6 @@ class NwsConverters:
"WSW": "Winter Storm Warning",
}
- # NWS alert codes to canonical weather event types
NwsCodeToWeatherEventTypeMap = {
# Severe Weather
'TOR': WeatherEventType.TORNADO,
@@ -282,7 +281,7 @@ class NwsConverters:
return cls.NwsAlertCategoryMap.get( nws_string.strip().lower() )
@classmethod
- def to_alerts_severity( cls, nws_string : str ) -> AlertSeverity:
+ def to_alert_severity( cls, nws_string : str ) -> AlertSeverity:
return cls.NwsAlertSeverityMap.get( nws_string.strip().lower() )
@classmethod
@@ -299,42 +298,19 @@ class NwsConverters:
@classmethod
def to_weather_event_type( cls, nws_code : str ) -> WeatherEventType:
- """
- Convert NWS alert code to canonical weather event type.
-
- Args:
- nws_code: NWS alert code (e.g., 'TOR', 'FFW', 'SVR', 'LWY')
-
- Returns:
- Corresponding WeatherEventType or WeatherEventType.OTHER if not found
- """
if not nws_code:
return WeatherEventType.OTHER
-
- # NWS codes are typically 3 characters, case-insensitive
code_upper = nws_code.strip().upper()
return cls.NwsCodeToWeatherEventTypeMap.get(code_upper, WeatherEventType.OTHER)
@classmethod
def to_weather_event_type_from_event_name( cls, event_name : str ) -> WeatherEventType:
- """
- Convert NWS event name to canonical weather event type (fallback method).
-
- This is used when the eventCode field is not available in the API response.
-
- Args:
- event_name: NWS event name (e.g., 'Tornado Warning', 'Lake Wind Advisory')
-
- Returns:
- Corresponding WeatherEventType or WeatherEventType.OTHER if not found
- """
+ """Fallback used when the eventCode field is absent from the API response."""
if not event_name:
return WeatherEventType.OTHER
-
- # Normalize the event name for comparison
+
event_upper = event_name.strip().upper()
-
- # Map common NWS event names to canonical types (key patterns)
+
if 'TORNADO' in event_upper:
return WeatherEventType.TORNADO
elif 'SEVERE THUNDERSTORM' in event_upper:
diff --git a/src/hi/apps/weather/weather_sources/openmeteo.py b/src/hi/apps/weather/weather_sources/openmeteo.py
index e8f8af7a..f2c7c886 100644
--- a/src/hi/apps/weather/weather_sources/openmeteo.py
+++ b/src/hi/apps/weather/weather_sources/openmeteo.py
@@ -33,9 +33,9 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
BASE_URL = "https://api.open-meteo.com/v1/"
ARCHIVE_BASE_URL = "https://archive-api.open-meteo.com/v1/archive"
- CURRENT_DATA_CACHE_EXPIRY_SECS = 10 * 60 # Cache for 10 minutes
- FORECAST_DATA_CACHE_EXPIRY_SECS = 60 * 60 # Cache for 1 hour
- HISTORICAL_DATA_CACHE_EXPIRY_SECS = 30 * 24 * 60 * 60 # 30 days - historical data rarely changes
+ CURRENT_DATA_CACHE_EXPIRY_SECS = 10 * 60
+ FORECAST_DATA_CACHE_EXPIRY_SECS = 60 * 60
+ HISTORICAL_DATA_CACHE_EXPIRY_SECS = 30 * 24 * 60 * 60 # Long TTL: historical data rarely changes
@classmethod
@@ -55,7 +55,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
priority = 2, # Lower priority than NWS
requests_per_day_limit = 10000, # Open-Meteo is very generous
requests_per_polling_interval = 5,
- min_polling_interval_secs = 5 * 60, # 5 minutes minimum
+ min_polling_interval_secs = 5 * 60,
)
self._headers = {
@@ -64,11 +64,9 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
return
def requires_api_key(self) -> bool:
- """Open-Meteo does not require an API key."""
return False
-
+
def get_default_enabled_state(self) -> bool:
- """Open-Meteo is enabled by default."""
return True
async def get_data(self):
@@ -85,7 +83,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
logger.warning('Weather manager not available. Skipping OpenMeteo weather fetch.')
return
- # Fetch current conditions
try:
current_conditions_data = self.get_current_conditions(
geographic_location = geographic_location,
@@ -99,7 +96,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
self.record_error( 'Current conditions fetch error: {e}' )
self._log_fetch_error( 'current conditions', e )
- # Fetch hourly forecast data
try:
interval_hourly_forecast_list = self.get_forecast_hourly(
geographic_location = geographic_location,
@@ -113,7 +109,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
self.record_error( 'Hourly forecast fetch error: {e}' )
self._log_fetch_error( 'hourly forecast', e )
- # Fetch daily forecast data
try:
interval_daily_forecast_list = self.get_forecast_daily(
geographic_location = geographic_location,
@@ -127,7 +122,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
self.record_error( 'Daily forecast fetch error: {e}' )
self._log_fetch_error( 'daily forecast', e )
- # Fetch historical weather data (last 7 days)
try:
logger.debug('Fetching OpenMeteo historical weather data for 7 days')
interval_daily_history_list = self.get_historical_weather(
@@ -145,9 +139,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
self.record_error( 'Historical data fetch error: {e}' )
self._log_fetch_error( 'historical data', e )
- # Note: OpenMeteo does not provide astronomical data
- # This would need to be fetched from other sources if needed
-
+ # OpenMeteo does not provide astronomical data; other sources cover that.
return
def get_current_conditions(self, geographic_location: GeographicLocation) -> WeatherConditionsData:
@@ -222,7 +214,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
weather_conditions_data = WeatherConditionsData()
- # Temperature from current weather
temperature = current_weather_data.get('temperature')
if temperature is not None:
temp_unit = current_weather_units.get('temperature', '°C')
@@ -233,7 +224,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
OpenMeteoConverters.normalize_temperature_unit(temp_unit)),
)
- # Wind speed from current weather
windspeed = current_weather_data.get('windspeed')
if windspeed is not None:
wind_unit = current_weather_units.get('windspeed', 'km/h')
@@ -243,7 +233,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
quantity_ave = UnitQuantity(windspeed, OpenMeteoConverters.normalize_wind_unit(wind_unit)),
)
- # Wind direction from current weather
wind_direction = current_weather_data.get('winddirection')
if wind_direction is not None:
weather_conditions_data.wind_direction = NumericDataPoint(
@@ -252,7 +241,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
quantity_ave = UnitQuantity(wind_direction, 'degrees'),
)
- # Weather code description
weather_code = current_weather_data.get('weathercode')
if weather_code is not None:
try:
@@ -265,7 +253,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
except ValueError:
logger.warning(f'Unknown OpenMeteo weather code: {weather_code}')
- # Is daytime
is_day = current_weather_data.get('is_day')
if is_day is not None:
weather_conditions_data.is_daytime = BooleanDataPoint(
@@ -274,13 +261,13 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
value = bool(is_day),
)
- # Additional data from hourly arrays (get current hour data)
+ # Pull current-hour values from the hourly arrays for fields the
+ # current_weather payload does not expose directly.
if hourly_data and hourly_data.get('time'):
current_hour_str = source_datetime.strftime('%Y-%m-%dT%H:00')
try:
current_hour_index = hourly_data['time'].index(current_hour_str)
-
- # Relative humidity
+
if 'relativehumidity_2m' in hourly_data:
humidity = hourly_data['relativehumidity_2m'][current_hour_index]
if humidity is not None:
@@ -290,7 +277,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
quantity_ave = UnitQuantity(humidity, 'percent'),
)
- # Dew point
if 'dewpoint_2m' in hourly_data:
dewpoint = hourly_data['dewpoint_2m'][current_hour_index]
if dewpoint is not None:
@@ -304,7 +290,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Precipitation
if 'precipitation' in hourly_data:
precipitation = hourly_data['precipitation'][current_hour_index]
if precipitation is not None:
@@ -318,7 +303,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Pressure (sea level)
if 'pressure_msl' in hourly_data:
pressure = hourly_data['pressure_msl'][current_hour_index]
if pressure is not None:
@@ -369,25 +353,21 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
interval_weather_forecast_list = list()
for i, time_str in enumerate(time_list):
-
- # Parse time interval
+
try:
interval_start = datetimeproxy.iso_naive_to_datetime_utc(time_str)
interval_end = interval_start + timedelta(hours = 1)
except Exception as e:
logger.warning(f'Missing or bad time in OpenMeteo hourly forecast payload: {e}')
continue
-
- # Create time interval
+
time_interval = TimeInterval(
start=interval_start,
end=interval_end
)
-
- # Create weather forecast data
+
forecast_data = WeatherForecastData()
-
- # Temperature
+
if 'temperature_2m' in hourly_data and i < len(hourly_data['temperature_2m']):
temperature = hourly_data['temperature_2m'][i]
if temperature is not None:
@@ -401,7 +381,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Relative humidity
if 'relativehumidity_2m' in hourly_data and i < len(hourly_data['relativehumidity_2m']):
humidity = hourly_data['relativehumidity_2m'][i]
if humidity is not None:
@@ -411,7 +390,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
quantity_ave = UnitQuantity(humidity, 'percent'),
)
- # Wind speed
if 'windspeed_10m' in hourly_data and i < len(hourly_data['windspeed_10m']):
windspeed = hourly_data['windspeed_10m'][i]
if windspeed is not None:
@@ -425,7 +403,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Wind direction
if 'winddirection_10m' in hourly_data and i < len(hourly_data['winddirection_10m']):
wind_direction = hourly_data['winddirection_10m'][i]
if wind_direction is not None:
@@ -435,7 +412,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
quantity_ave = UnitQuantity(wind_direction, 'degrees'),
)
- # Precipitation
if 'precipitation' in hourly_data and i < len(hourly_data['precipitation']):
precipitation = hourly_data['precipitation'][i]
if precipitation is not None:
@@ -449,7 +425,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Weather code
if 'weathercode' in hourly_data and i < len(hourly_data['weathercode']):
weather_code = hourly_data['weathercode'][i]
if weather_code is not None:
@@ -463,7 +438,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
except ValueError:
logger.warning(f'Unknown OpenMeteo weather code: {weather_code}')
- # Create interval weather forecast
interval_weather_forecast = IntervalWeatherForecast(
interval=time_interval,
data=forecast_data
@@ -473,7 +447,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
return interval_weather_forecast_list
- def _parse_daily_forecast_data(self,
+ def _parse_daily_forecast_data(self,
forecast_data: Dict,
geographic_location: GeographicLocation) -> List[IntervalWeatherForecast]:
@@ -510,8 +484,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
interval_weather_forecast_list = list()
for i, date_str in enumerate(time_list):
-
- # Parse time interval
+
try:
date_obj = datetime.fromisoformat(date_str).date()
datetime_obj = datetime.combine( date_obj, datetime.min.time() ).isoformat()
@@ -520,16 +493,14 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
except Exception as e:
logger.warning(f'Missing or bad date in OpenMeteo daily forecast payload: {e}')
continue
-
+
time_interval = TimeInterval(
start=interval_start,
end=interval_end
)
-
- # Create weather forecast data
+
forecast_data = WeatherForecastData()
-
- # Temperature max
+
if 'temperature_2m_max' in daily_data and i < len(daily_data['temperature_2m_max']):
temp_max = daily_data['temperature_2m_max'][i]
if temp_max is not None:
@@ -543,7 +514,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Temperature min
if 'temperature_2m_min' in daily_data and i < len(daily_data['temperature_2m_min']):
temp_min = daily_data['temperature_2m_min'][i]
if temp_min is not None:
@@ -561,7 +531,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
else:
forecast_data.temperature.quantity_min = quantity_min
- # Precipitation sum
if 'precipitation_sum' in daily_data and i < len(daily_data['precipitation_sum']):
precipitation = daily_data['precipitation_sum'][i]
if precipitation is not None:
@@ -575,7 +544,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Weather code
if 'weathercode' in daily_data and i < len(daily_data['weathercode']):
weather_code = daily_data['weathercode'][i]
if weather_code is not None:
@@ -589,7 +557,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
except ValueError:
logger.warning(f'Unknown OpenMeteo weather code: {weather_code}')
- # Create interval weather forecast
interval_weather_forecast = IntervalWeatherForecast(
interval=time_interval,
data=forecast_data
@@ -649,8 +616,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
)
history_data = WeatherHistoryData()
-
- # Temperature max
+
if 'temperature_2m_max' in daily_data and i < len(daily_data['temperature_2m_max']):
temp_max = daily_data['temperature_2m_max'][i]
if temp_max is not None:
@@ -664,7 +630,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Temperature min
if 'temperature_2m_min' in daily_data and i < len(daily_data['temperature_2m_min']):
temp_min = daily_data['temperature_2m_min'][i]
if temp_min is not None:
@@ -681,8 +646,7 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
)
else:
history_data.temperature.quantity_min = quantity_min
-
- # Precipitation sum
+
if 'precipitation_sum' in daily_data and i < len(daily_data['precipitation_sum']):
precipitation = daily_data['precipitation_sum'][i]
if precipitation is not None:
@@ -696,7 +660,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
),
)
- # Weather code
if 'weathercode' in daily_data and i < len(daily_data['weathercode']):
weather_code = daily_data['weathercode'][i]
if weather_code is not None:
@@ -741,7 +704,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
return current_data
def _get_current_weather_data_from_api(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
- # Request current weather plus additional hourly data for current hour
url = (f"{self._get_base_url()}forecast?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
@@ -777,7 +739,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
return forecast_data
def _get_hourly_forecast_data_from_api(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
- # Request 7 days of hourly forecast data
url = (f"{self._get_base_url()}forecast?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
@@ -813,7 +774,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
return forecast_data
def _get_daily_forecast_data_from_api(self, geographic_location: GeographicLocation) -> Dict[str, Any]:
- # Request 14 days of daily forecast data
url = (f"{self._get_base_url()}forecast?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
@@ -859,7 +819,6 @@ class OpenMeteo(WeatherDataSource, WeatherMixin):
geographic_location : GeographicLocation,
start_date : date,
end_date : date ) -> Dict[str, Any]:
- # Request historical weather data from archive API
url = (f"{self.ARCHIVE_BASE_URL}?"
f"latitude={geographic_location.latitude}&"
f"longitude={geographic_location.longitude}&"
diff --git a/src/hi/apps/weather/weather_sources/openmeteo_converters.py b/src/hi/apps/weather/weather_sources/openmeteo_converters.py
index a54669bf..2f11432e 100644
--- a/src/hi/apps/weather/weather_sources/openmeteo_converters.py
+++ b/src/hi/apps/weather/weather_sources/openmeteo_converters.py
@@ -9,11 +9,8 @@ logger = logging.getLogger(__name__)
class OpenMeteoConverters:
- """Converts OpenMeteo API data formats to canonical weather data model."""
- # OpenMeteo weather codes mapping to descriptive text
- # Based on WMO weather interpretation codes (WW)
- # See: https://open-meteo.com/en/docs
+ # WMO weather interpretation codes (WW). See https://open-meteo.com/en/docs
WEATHER_CODE_DESCRIPTIONS = {
0: "Clear sky",
1: "Mainly clear",
@@ -47,34 +44,13 @@ class OpenMeteoConverters:
@staticmethod
def weather_code_to_description(weather_code: int) -> str:
- """
- Convert OpenMeteo weather code to descriptive text.
-
- Args:
- weather_code: OpenMeteo weather code (WMO code)
-
- Returns:
- Descriptive text for the weather condition
-
- Raises:
- ValueError: If weather code is not recognized
- """
if weather_code in OpenMeteoConverters.WEATHER_CODE_DESCRIPTIONS:
return OpenMeteoConverters.WEATHER_CODE_DESCRIPTIONS[weather_code]
-
+
raise ValueError(f'Unknown OpenMeteo weather code: {weather_code}')
@staticmethod
def normalize_temperature_unit(unit_str: str) -> str:
- """
- Normalize OpenMeteo temperature unit to Pint-compatible format.
-
- Args:
- unit_str: OpenMeteo temperature unit string
-
- Returns:
- Pint-compatible unit string
- """
if unit_str == '°C':
return 'degC'
elif unit_str == '°F':
@@ -87,15 +63,6 @@ class OpenMeteoConverters:
@staticmethod
def normalize_wind_unit(unit_str: str) -> str:
- """
- Normalize OpenMeteo wind speed unit to Pint-compatible format.
-
- Args:
- unit_str: OpenMeteo wind speed unit string
-
- Returns:
- Pint-compatible unit string
- """
if unit_str == 'km/h':
return 'km/h'
elif unit_str == 'm/s':
@@ -110,15 +77,6 @@ class OpenMeteoConverters:
@staticmethod
def normalize_precipitation_unit(unit_str: str) -> str:
- """
- Normalize OpenMeteo precipitation unit to Pint-compatible format.
-
- Args:
- unit_str: OpenMeteo precipitation unit string
-
- Returns:
- Pint-compatible unit string
- """
if unit_str == 'mm':
return 'mm'
elif unit_str == 'inch':
@@ -129,15 +87,6 @@ class OpenMeteoConverters:
@staticmethod
def normalize_pressure_unit(unit_str: str) -> str:
- """
- Normalize OpenMeteo pressure unit to Pint-compatible format.
-
- Args:
- unit_str: OpenMeteo pressure unit string
-
- Returns:
- Pint-compatible unit string
- """
if unit_str == 'hPa':
return 'hPa'
elif unit_str == 'Pa':
@@ -152,15 +101,6 @@ class OpenMeteoConverters:
@staticmethod
def is_weather_code_precipitation(weather_code: int) -> bool:
- """
- Check if a weather code indicates precipitation.
-
- Args:
- weather_code: OpenMeteo weather code
-
- Returns:
- True if the weather code indicates precipitation
- """
precipitation_codes = {
51, 53, 55, 56, 57, # Drizzle
61, 63, 65, 66, 67, # Rain
@@ -172,29 +112,12 @@ class OpenMeteoConverters:
@staticmethod
def is_weather_code_clear(weather_code: int) -> bool:
- """
- Check if a weather code indicates clear/sunny conditions.
-
- Args:
- weather_code: OpenMeteo weather code
-
- Returns:
- True if the weather code indicates clear conditions
- """
clear_codes = {0, 1} # Clear sky, mainly clear
return weather_code in clear_codes
@staticmethod
def get_weather_code_severity(weather_code: int) -> str:
- """
- Get the severity level of a weather condition.
-
- Args:
- weather_code: OpenMeteo weather code
-
- Returns:
- Severity level: 'clear', 'light', 'moderate', 'heavy', 'severe'
- """
+ """Return one of: 'clear', 'light', 'moderate', 'heavy', 'severe'."""
if weather_code in {0, 1}:
return 'clear'
elif weather_code in {2, 3}:
diff --git a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py
index 3bed2800..0ecb2346 100644
--- a/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py
+++ b/src/hi/apps/weather/weather_sources/sunrise_sunset_org.py
@@ -56,20 +56,18 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
priority = 3, # Lower priority than NWS and OpenMeteo
requests_per_day_limit = 1000, # Conservative estimate for "reasonable" usage
requests_per_polling_interval = 1, # Only need one request per day per location
- min_polling_interval_secs = 24 * 60 * 60, # Daily data - minimum 24 hours
+ min_polling_interval_secs = 24 * 60 * 60, # Daily data only updates once per day
)
self._headers = {
'User-Agent': 'HomeInformation ([email protected])',
}
return
-
+
def requires_api_key(self) -> bool:
- """Sunrise-Sunset API does not require an API key."""
return False
-
+
def get_default_enabled_state(self) -> bool:
- """Sunrise-Sunset is enabled by default."""
return True
async def get_data(self):
@@ -86,7 +84,6 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
logger.warning('Weather manager not available. Skipping Sunrise-Sunset.org fetch.')
return
- # Fetch 10 days of astronomical data using the new multi-day method
try:
astronomical_data_list = self.get_astronomical_data_list(
geographic_location = geographic_location,
@@ -120,10 +117,9 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
def get_astronomical_data( self,
geographic_location : GeographicLocation,
target_date : date = None) -> AstronomicalData:
- """Get astronomical data for a specific date and location."""
if target_date is None:
target_date = datetimeproxy.now().date()
-
+
api_data = self._get_astronomical_api_data(
geographic_location = geographic_location,
target_date = target_date,
@@ -134,12 +130,11 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
target_date = target_date,
)
- def _parse_astronomical_data(self,
+ def _parse_astronomical_data(self,
api_data: Dict,
geographic_location: GeographicLocation,
target_date: date) -> AstronomicalData:
-
- # Check API status
+
status = api_data.get('status')
if status != SunriseSunsetStatus.OK.value:
raise ValueError(f'Sunrise-Sunset API error: {status}')
@@ -161,8 +156,7 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
)
astronomical_data = AstronomicalData()
-
- # Parse time fields from UTC ISO format
+
time_fields = [
('sunrise', 'sunrise'),
('sunset', 'sunset'),
@@ -203,26 +197,24 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
astronomical_data_list = []
today = datetimeproxy.now().date()
-
- # Get local timezone from superclass
+
local_tz = pytz.timezone(self.tz_name)
-
+
for day_offset in range(days_count):
target_date = today + timedelta(days=day_offset)
-
+
try:
- # Get astronomical data for this date
astronomical_data = self.get_astronomical_data(
geographic_location=geographic_location,
target_date=target_date
)
-
+
if astronomical_data:
- # Create local day boundaries (midnight to midnight in local time)
+ # Day boundaries are midnight-to-midnight in local time,
+ # then converted to UTC for internal storage.
local_start = local_tz.localize(datetime.combine(target_date, datetime.min.time()))
local_end = local_tz.localize(datetime.combine(target_date, datetime.max.time()))
-
- # Convert to UTC for internal storage (following IntervalDataManager pattern)
+
interval_start = local_start.astimezone(pytz.UTC)
interval_end = local_end.astimezone(pytz.UTC)
@@ -273,7 +265,6 @@ class SunriseSunsetOrg(WeatherDataSource, WeatherMixin):
def _get_astronomical_api_data_from_api( self,
geographic_location : GeographicLocation,
target_date : date) -> Dict[str, Any]:
- # Build API URL with parameters
url = (f"{self._get_base_url()}?"
f"lat={geographic_location.latitude}&"
f"lng={geographic_location.longitude}&"
diff --git a/src/hi/apps/weather/weather_sources/usno.py b/src/hi/apps/weather/weather_sources/usno.py
index 42f80c9e..edac31ca 100644
--- a/src/hi/apps/weather/weather_sources/usno.py
+++ b/src/hi/apps/weather/weather_sources/usno.py
@@ -65,20 +65,18 @@ class USNO( WeatherDataSource, WeatherMixin ):
priority = 2, # Higher priority than sunrise-sunset.org due to moon phase data
requests_per_day_limit = 1000, # Conservative estimate
requests_per_polling_interval = 1, # Only need one request per day per location
- min_polling_interval_secs = 24 * 60 * 60, # Daily data - minimum 24 hours
+ min_polling_interval_secs = 24 * 60 * 60, # Daily data only updates once per day
)
self._headers = {
'User-Agent': 'HomeInformation ([email protected])',
}
return
-
+
def requires_api_key(self) -> bool:
- """USNO API does not require an API key."""
return False
-
+
def get_default_enabled_state(self) -> bool:
- """USNO is enabled by default."""
return True
async def get_data(self):
@@ -95,7 +93,6 @@ class USNO( WeatherDataSource, WeatherMixin ):
logger.warning('Weather manager not available. Skipping USNO fetch.')
return
- # Fetch 10 days of astronomical data
try:
astronomical_data_list = self.get_astronomical_data_list(
geographic_location = geographic_location,
@@ -129,7 +126,6 @@ class USNO( WeatherDataSource, WeatherMixin ):
def get_astronomical_data( self,
geographic_location : GeographicLocation,
target_date : date = None) -> AstronomicalData:
- """Get astronomical data for a specific date and location."""
if target_date is None:
target_date = datetimeproxy.now().date()
@@ -162,7 +158,8 @@ class USNO( WeatherDataSource, WeatherMixin ):
)
if astronomical_data:
- # Create local day boundaries (midnight to midnight in local time)
+ # Day boundaries are midnight-to-midnight in local time,
+ # then converted to UTC for internal storage.
local_start = local_tz.localize(datetime.combine( target_date,
datetime.min.time()) )
local_end = local_tz.localize(datetime.combine( target_date,
@@ -189,22 +186,20 @@ class USNO( WeatherDataSource, WeatherMixin ):
return astronomical_data_list
- def _parse_astronomical_data(self,
+ def _parse_astronomical_data(self,
api_data: Dict,
geographic_location: GeographicLocation,
target_date: date) -> AstronomicalData:
- """Parse USNO API response into AstronomicalData object."""
-
- # Check for API errors
+
if 'error' in api_data:
raise ValueError(f'USNO API error: {api_data["error"]}')
-
+
properties = api_data.get('properties', {})
if not properties:
raise ValueError('Missing "properties" in USNO API response')
-
+
+ # Empty data is allowed: USNO returns empty data for some dates.
data = properties.get('data', {})
- # Note: Empty data is allowed - API might return empty data for some dates
source_datetime = datetimeproxy.now()
@@ -219,16 +214,15 @@ class USNO( WeatherDataSource, WeatherMixin ):
)
astronomical_data = AstronomicalData()
-
- # Parse solar phenomena (sundata)
+
sundata = data.get('sundata', [])
for event in sundata:
phen = event.get('phen', '').lower()
time_str = event.get('time')
-
+
if time_str and phen in ['rise', 'set', 'upper transit']:
try:
- # Parse time - it's already in local time from the API
+ # Time is already in local time from the API.
time_obj = self._parse_usno_time(time_str)
if time_obj:
time_data_point = TimeDataPoint(
@@ -246,16 +240,15 @@ class USNO( WeatherDataSource, WeatherMixin ):
except Exception as e:
logger.warning(f'Problem parsing USNO solar {phen} time "{time_str}": {e}')
-
- # Parse lunar phenomena (moondata)
+
moondata = data.get('moondata', [])
for event in moondata:
phen = event.get('phen', '').lower()
time_str = event.get('time')
-
+
if time_str and phen in ['rise', 'set']:
try:
- # Parse time - it's already in local time from the API
+ # Time is already in local time from the API.
time_obj = self._parse_usno_time(time_str)
if time_obj:
time_data_point = TimeDataPoint(
@@ -271,26 +264,23 @@ class USNO( WeatherDataSource, WeatherMixin ):
except Exception as e:
logger.warning(f'Problem parsing USNO lunar {phen} time "{time_str}": {e}')
-
- # Parse moon phase data
+
try:
- # Get current moon phase information
curphase = data.get('curphase', '')
fracillum = data.get('fracillum', '')
-
+
if fracillum:
- # Parse fractional illumination (format like "35%" -> 35.0)
+ # Fractional illumination format like "35%" -> 35.0.
illum_str = fracillum.replace('%', '').strip()
if illum_str:
illumination_percent = float(illum_str)
-
- astronomical_data.moon_illumnination = NumericDataPoint(
+
+ astronomical_data.moon_illumination = NumericDataPoint(
station = station,
source_datetime = source_datetime,
quantity_ave = UnitQuantity(illumination_percent, 'percent'),
)
-
- # Determine if moon is waxing based on phase name
+
is_waxing = self._determine_moon_waxing_status(curphase)
if is_waxing is not None:
astronomical_data.moon_is_waxing = BooleanDataPoint(
@@ -306,21 +296,19 @@ class USNO( WeatherDataSource, WeatherMixin ):
def _parse_usno_time(self, time_str: str) -> time:
"""
- Parse USNO time string. Since we request data with our local timezone offset,
- the returned times are already in local time.
+ USNO returns times already in local time because we send a tz
+ offset on the request. Input format is "HH:MM".
"""
try:
- # Parse the time string (format: "HH:MM")
time_parts = time_str.split(':')
if len(time_parts) != 2:
return None
-
+
hour = int(time_parts[0])
minute = int(time_parts[1])
-
- # Return the time object - it's already in local time
+
return time(hour, minute)
-
+
except Exception:
return None
@@ -345,13 +333,11 @@ class USNO( WeatherDataSource, WeatherMixin ):
elif 'last quarter' in phase_lower or 'last' in phase_lower or 'third quarter' in phase_lower:
return False
else:
- # For indeterminate phases, return None
return None
def _get_astronomical_api_data( self,
geographic_location : GeographicLocation,
target_date : date) -> Dict[str, Any]:
- """Get astronomical data from cache or API."""
cache_key = f'ws:{self.id}:astronomical:{geographic_location.latitude:.3f}:{geographic_location.longitude:.3f}:{target_date}'
api_data_str = self.redis_client.get(cache_key)
@@ -378,15 +364,12 @@ class USNO( WeatherDataSource, WeatherMixin ):
def _get_astronomical_api_data_from_api( self,
geographic_location : GeographicLocation,
target_date : date) -> Dict[str, Any]:
- """Make API call to USNO for astronomical data."""
-
- # Calculate timezone offset for the request
+
local_tz = pytz.timezone(self.tz_name)
local_dt = local_tz.localize(datetime.combine(target_date, datetime.min.time()))
offset_seconds = local_dt.utcoffset().total_seconds()
- tz_offset = offset_seconds / 3600 # Convert to hours
-
- # Build API URL with parameters
+ tz_offset = offset_seconds / 3600
+
url = (f"{self._get_base_url()}?"
f"date={target_date.isoformat()}&"
f"coords={geographic_location.latitude},{geographic_location.longitude}&"
diff --git a/src/hi/apps/weather/wmo_units.py b/src/hi/apps/weather/wmo_units.py
index 393931aa..9ef2e7ce 100644
--- a/src/hi/apps/weather/wmo_units.py
+++ b/src/hi/apps/weather/wmo_units.py
@@ -887,7 +887,7 @@ class WmoUnits:
if unit_str.startswith( 'wmoUnit:' ):
unit_str = unit_str[8:].strip()
elif unit_str.startswith( 'wmo:' ):
- unit_str = unit_str[4:].strip() # Fixed: was 5, should be 4
+ unit_str = unit_str[4:].strip()
elif unit_str.startswith( 'unit:' ):
unit_str = unit_str[5:].strip()
diff --git a/src/hi/integrations/connector/integration_connector.py b/src/hi/integrations/connector/integration_connector.py
index 9c6c7673..3c9d6e55 100644
--- a/src/hi/integrations/connector/integration_connector.py
+++ b/src/hi/integrations/connector/integration_connector.py
@@ -49,15 +49,11 @@ class IntegrationConnector( CapabilityGateway ):
Synchronization is process-wide rather than per-integration: at
most one integration sync runs at a time. Concurrent syncs across
integrations could race over shared infrastructure (entity tables,
- location-view bookkeeping in later phases) and the user is unlikely
- to need parallelism here. Override at a subclass level if a future
- integration genuinely needs concurrent sync.
+ location-view bookkeeping).
"""
capability = IntegrationCapability.CONNECT
- # Single shared lock name across all integration syncs. See class
- # docstring above for the rationale.
SYNCHRONIZATION_LOCK_NAME = 'integrations_sync'
def get_sync_description(self, is_initial_connect: bool) -> Optional[str]:
@@ -80,10 +76,8 @@ class IntegrationConnector( CapabilityGateway ):
Short, generic header for the sync result modal: 'Connect
Result' for the first-time path, 'Update Check Result'
otherwise. The integration's identity is surfaced in the
- modal body (logo + label) rather than the title bar — keeps
- the title bar contrast predictable regardless of integration.
- Override only if a specific integration genuinely needs custom
- copy.
+ modal body rather than the title bar so title-bar contrast
+ stays predictable regardless of integration.
"""
if is_initial_connect:
return 'Connect Result'
@@ -93,13 +87,13 @@ class IntegrationConnector( CapabilityGateway ):
"""Return the integration's periodic monitor when it has one;
None otherwise. The monitor polls upstream state for live
sensor responses and surfaces health status. Connect-only
- by nature — Import has no ongoing connection to monitor."""
+ by nature -- Import has no ongoing connection to monitor."""
return None
def get_controller(self) -> Optional[IntegrationController]:
"""Return the integration's controller when it accepts control
actions; None otherwise. The controller routes a control value
- from HI to the upstream system. Connect-only — Import-mode
+ from HI to the upstream system. Connect-only -- Import-mode
entities are HI-owned and their controllers are HI-native."""
return None
@@ -120,14 +114,13 @@ class IntegrationConnector( CapabilityGateway ):
def get_entity_video_stream(self, entity: Entity) -> Optional[VideoStream]:
"""Return the live video stream for ``entity``, or ``None`` when
- the integration cannot produce one. Opt-in capability — most
- integrations leave this as the default."""
+ the integration cannot produce one. Opt-in capability."""
return None
def get_entity_video_snapshot(self, entity: Entity) -> Optional[VideoSnapshot]:
"""Return a fresh still-image snapshot for ``entity``, or
``None`` when the integration cannot produce one. Opt-in
- capability — most integrations leave this as the default."""
+ capability."""
return None
def get_sensor_response_video_stream(
@@ -147,14 +140,14 @@ class IntegrationConnector( CapabilityGateway ):
URL always reflects current integration configuration (e.g.,
an operator who moves the upstream host doesn't get stale
URLs on historical rows). Pair with
- ``SensorResponse.has_event_video_snapshot`` — only call when
+ ``SensorResponse.has_event_video_snapshot`` -- only call when
the flag is True."""
return None
def get_external_view_data(self, entity: Entity) -> Optional[ExternalViewData]:
"""Return the external-data view payload for the entity-detail
modal. Return ``None`` if this integration has no external view
- for ``entity`` — the external-data region is then suppressed.
+ for ``entity`` -- the external-data region is then suppressed.
Defaults to ``None``; integrations whose data lives upstream
override this hook to return a populated ``ExternalViewData``
@@ -177,10 +170,8 @@ class IntegrationConnector( CapabilityGateway ):
``preserve_user_data`` controls how user-data entities are
handled when the sync drops them as no-longer-present
- upstream — symmetric to the integration-disable flow's SAFE
- / ALL choice. True (default, "Refresh and Retain") detaches
- them; False ("Refresh and Remove") hard-deletes them. Stored
- on the instance for the duration so
+ upstream: True (default) detaches them; False hard-deletes
+ them. Stored on the instance for the duration so
``_remove_entity_intelligently`` can read it without
threading the flag through every subclass's ``_sync_impl``;
the process-wide ``SYNCHRONIZATION_LOCK_NAME`` precludes
@@ -213,11 +204,11 @@ class IntegrationConnector( CapabilityGateway ):
def _record_sync_check_complete_if_successful(
self, result : IntegrationSyncResult ) -> None:
- """Issue #283: a successful sync brings HI in line with upstream
- as of right now. Write a zero-delta sync-check result with the
- current timestamp so UI surfaces clear immediately and the next
+ """A successful sync brings HI in line with upstream as of right
+ now. Write a zero-delta sync-check result with the current
+ timestamp so UI surfaces clear immediately and the next
background probe has a fresh baseline. Cache write failures must
- not propagate — the sync itself succeeded and the caller's
+ not propagate -- the sync itself succeeded and the caller's
flow should continue regardless."""
if result.error_list:
return
@@ -244,7 +235,7 @@ class IntegrationConnector( CapabilityGateway ):
process-level state derives from those records should refresh
here. Default is no-op.
- Runs regardless of result.error_list — partial syncs may have
+ Runs regardless of result.error_list -- partial syncs may have
committed enough changes to invalidate process-level state."""
return
@@ -256,60 +247,49 @@ class IntegrationConnector( CapabilityGateway ):
raise NotImplementedError('Subclasses must override this method')
async def check_needs_sync(self) -> Optional[SyncDelta]:
- """Issue #283 — periodic sync-check probe. Return a
- ``SyncDelta`` describing how upstream has drifted from HI's
- current state, or ``None`` to opt out.
-
- The framework monitor in ``hi.integrations.monitors`` invokes
- this on each enabled+unpaused integration's synchronizer once
- per cycle (default 4 hours). Implementations should do a
- *cheap* upstream fetch — the probe is purely informational and
- runs even when no user action is in progress — and delegate
- the comparison to ``IntegrationSyncCheck.compute_delta``. The
- framework wraps the returned delta into a
- ``SyncCheckResult`` (with timestamp and summary) and caches
- it; subclasses do not touch the cache directly.
+ """Periodic sync-check probe. Return a ``SyncDelta`` describing
+ how upstream has drifted from HI's current state, or ``None``
+ to opt out.
+
+ The framework monitor invokes this on each enabled+unpaused
+ integration's synchronizer once per cycle. Implementations
+ should do a *cheap* upstream fetch -- the probe is purely
+ informational and runs even when no user action is in
+ progress -- and delegate the comparison to
+ ``IntegrationSyncCheck.compute_delta``. The framework wraps
+ the returned delta into a ``SyncCheckResult`` and caches it;
+ subclasses do not touch the cache directly.
Failures (client unavailable, upstream unreachable) should
propagate; the framework monitor's per-call try/except
classifies the cycle as ERROR for that integration and
continues with the others.
- Default returns ``None`` — opt-out. Sync-check is opt-in even
+ Default returns ``None`` -- opt-out. Sync-check is opt-in even
among integrations that support full sync.
"""
return None
- # ``get_metadata`` is inherited from CapabilityGateway. CONNECT
- # subclasses must implement it; the base raises NotImplementedError
- # via the inherited abstract.
-
def reconnect_disconnected_items(
self,
integration_key_to_upstream : Dict[ IntegrationKey, Any ],
integration_key_to_entity : Dict[ IntegrationKey, Entity ],
result : IntegrationSyncResult ):
"""
- Framework-level auto-reconnect (Issue #281). Symmetric to
- the framework-level disconnect path
- (``EntityIntegrationOperations.preserve_with_user_data``):
- both directions of the cycle live in shared code, with each
- integration contributing only the minimal piece that's
- genuinely integration-specific — the converter dispatch via
+ Framework-level auto-reconnect. Each integration contributes
+ only the minimal piece that's genuinely integration-specific:
+ the converter dispatch via
``_rebuild_integration_components()``.
For each unmatched upstream key with a unique secondary
match, this method:
- * clears the previous-identity columns (which removes the
- "From <integration>" badge in the UI),
+ * clears the previous-identity columns,
* dispatches to ``_rebuild_integration_components()`` so the
integration's converter repopulates the integration-owned
components on the existing entity,
* appends the entity name to ``result.reconnected_list``
- (which drives the "Reconnected" tile + per-category list
- in the sync result modal) and to ``result.info_list``
- (the diagnostic Details section),
+ and to ``result.info_list``,
* inserts the reconnected entity into
``integration_key_to_entity`` so the synchronizer's main
loop sees it as primary-matched and gives it the standard
@@ -325,7 +305,7 @@ class IntegrationConnector( CapabilityGateway ):
Ambiguous secondary matches are handled inside
``find_reconnect_candidates``: dropped silently, with a
WARNING log + ``info_list`` breadcrumb so the operator can
- find them and resolve via merge (#263).
+ find them and resolve via merge.
"""
unmatched_upstream_keys = [
integration_key for integration_key in integration_key_to_upstream
@@ -360,11 +340,11 @@ class IntegrationConnector( CapabilityGateway ):
)
# The disconnect path set is_disabled=True (the
# capability gate that hides detached entities from
- # listings like the Cameras sidebar). Reconnect is
- # the symmetric clear: the entity is integration-
- # attached again and should participate in those
- # listings. Capability flags like has_video_stream
- # are converter-owned and should already have been
+ # capability-filtered listings). Reconnect is the
+ # symmetric clear: the entity is integration-attached
+ # again and should participate in those listings.
+ # Capability flags like has_video_stream are
+ # converter-owned and should already have been
# re-established by _rebuild_integration_components.
entity.is_disabled = False
# Defensive save: subclasses' converters typically
@@ -380,11 +360,6 @@ class IntegrationConnector( CapabilityGateway ):
'is_disabled',
],
)
- # reconnected_list drives the operator-visible
- # "Reconnected" tile + per-category list in the
- # sync result modal; info_list keeps the same name
- # in the diagnostic Details section so the operator
- # sees a consistent record across both surfaces.
result.reconnected_list.append( entity.name )
result.info_list.append(
f'Auto-reconnected {metadata.label} item "{entity.name}"'
@@ -397,16 +372,14 @@ class IntegrationConnector( CapabilityGateway ):
upstream : Any,
result : IntegrationSyncResult ):
"""
- Subclass hook for the auto-reconnect (Issue #281) path. Given
- an existing Entity (the previously-disconnected one) and the
- upstream payload for it, repopulate the entity's
- integration-owned components by dispatching to the
- integration's converter with the existing-entity parameter set.
+ Subclass hook for the auto-reconnect path. Given an existing
+ Entity (the previously-disconnected one) and the upstream
+ payload for it, repopulate the entity's integration-owned
+ components by dispatching to the integration's converter with
+ the existing-entity parameter set.
The base class raises NotImplementedError; subclasses must
- override to participate in auto-reconnect. (Reconnect is
- framework-driven; the only piece each integration owns is
- this thin converter-dispatch override.)
+ override to participate in auto-reconnect.
"""
raise NotImplementedError(
f'{self.__class__.__name__} must override '
@@ -420,15 +393,14 @@ class IntegrationConnector( CapabilityGateway ):
"""
Remove an entity that no longer exists in the integration.
- Delegates to ``EntityIntegrationOperations.remove_entities_with_closure``
- — the same path the integration-disable flow uses. The
- closure walk picks up delegate entities (e.g., the Area
+ Delegates to ``EntityIntegrationOperations.remove_entities_with_closure``.
+ The closure walk picks up delegate entities (e.g., the Area
auto-created when a camera was placed in a view) when their
only remaining principal is being removed. Whether
operator-added attributes trigger the detach-and-preserve
branch is controlled by ``self._preserve_user_data`` (set on
- ``sync()`` entry from the operator's pre-sync choice;
- defaults to True / preserve when not explicitly set).
+ ``sync()`` entry; defaults to True / preserve when not
+ explicitly set).
"""
EntityIntegrationOperations.remove_entities_with_closure(
seed_entity_ids = { entity.id },
diff --git a/src/hi/integrations/connector/monitors.py b/src/hi/integrations/connector/monitors.py
index 558b42ae..2ba65c82 100644
--- a/src/hi/integrations/connector/monitors.py
+++ b/src/hi/integrations/connector/monitors.py
@@ -1,28 +1,26 @@
"""
-Framework-level periodic monitor for the Issue #283 sync-check
-feature.
+Framework-level periodic monitor for the sync-check feature.
A single ``IntegrationSyncCheckMonitor`` runs at a long cadence
-(``IntegrationSyncCheck.INTERVAL_SECS``, currently 4 hours), iterates
-the enabled and unpaused integrations, gets each integration's
-connector via ``gateway.get_connector()``, and dispatches to
-its ``check_needs_sync()``. Sync-check rides on the same opt-in
-surface as full sync — an integration without a connector
-naturally opts out of the periodic drift check too. Per-integration
-calls are wrapped in try/except so one integration's transient
-failure does not abort the cycle for the others. Sequential (not
-parallel) iteration is deliberate: we hit one upstream at a time
-across all integrations, which avoids lock-step CPU bursts when
-monitors of multiple integrations would otherwise align at the long
-boundary.
+(``IntegrationSyncCheck.INTERVAL_SECS``), iterates the enabled and
+unpaused integrations, gets each integration's connector via
+``gateway.get_connector()``, and dispatches to its
+``check_needs_sync()``. Sync-check rides on the same opt-in surface
+as full sync -- an integration without a connector naturally opts
+out of the periodic drift check too. Per-integration calls are
+wrapped in try/except so one integration's transient failure does
+not abort the cycle for the others. Sequential (not parallel)
+iteration is deliberate: we hit one upstream at a time across all
+integrations, which avoids lock-step CPU bursts when monitors of
+multiple integrations would otherwise align at the long boundary.
Lifecycle: started from ``IntegrationManager`` after the
-per-integration health monitors have been launched. Stopped from the
-same lifecycle. The first cycle runs immediately on start (the base
-``PeriodicMonitor`` semantics) — that gives best-effort cache
-population at server boot. Per-integration calls that fail because
-their underlying manager / client is not yet ready are reported as
-errors for this cycle only and the next cycle catches them.
+per-integration health monitors have been launched. The first cycle
+runs immediately on start (the base ``PeriodicMonitor`` semantics)
+-- that gives best-effort cache population at server boot.
+Per-integration calls that fail because their underlying manager /
+client is not yet ready are reported as errors for this cycle only
+and the next cycle catches them.
"""
import logging
@@ -50,7 +48,7 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):
return
def alarm_ceiling(self):
- # Drift detection is informational by design — the user always
+ # Drift detection is informational by design -- the user always
# confirms the actual sync. Cap at INFO so probe failures
# never escalate beyond a notice.
return AlarmLevel.INFO
@@ -103,7 +101,7 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):
connector = gateway.get_connector()
if connector is None:
- # No connector means no sync support — and therefore
+ # No connector means no sync support -- and therefore
# no sync-check. Cache state is not touched.
return SyncCheckOutcome.OPTED_OUT
@@ -141,7 +139,7 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):
) -> None:
"""Summarize the cycle into the monitor's own health-status
surface. The framework monitor's job is "did I iterate and
- dispatch every enabled integration?" — that always succeeds
+ dispatch every enabled integration?" -- that always succeeds
when we reach this method (per-integration call failures are
absorbed by ``_check_one_integration``'s try/except). So
cycle outcome is reported as HEALTHY regardless of how many
@@ -157,7 +155,7 @@ class IntegrationSyncCheckMonitor( PeriodicMonitor ):
True framework / process failures (cache layer unavailable,
``IntegrationManager`` not initialized, etc.) raise out of
``do_work`` and are caught by the base class's
- ``run_query``, which records them as ERROR — that is the
+ ``run_query``, which records them as ERROR -- that is the
only path that should alert from this monitor.
"""
checked = (
diff --git a/src/hi/integrations/connector/sync_check.py b/src/hi/integrations/connector/sync_check.py
index 7691e8cc..8605fbec 100644
--- a/src/hi/integrations/connector/sync_check.py
+++ b/src/hi/integrations/connector/sync_check.py
@@ -2,17 +2,17 @@
Per-integration sync-check state, and the integration-agnostic delta
primitive used to compute it.
-Issue #283: a periodic background probe surfaces a "needs-sync"
-signal when an integration's HI representation has drifted from
-upstream. The probe never modifies entities — the user always
-chooses when to invoke Refresh. Per-integration probe logic lives in
-each ``IntegrationConnector.check_needs_sync()`` override, which
-returns a ``SyncDelta``; sync-check rides on the same opt-in surface
-as full sync (an integration without a synchronizer naturally opts
-out of the periodic drift check too). The framework monitor wraps
-the returned delta into a ``SyncCheckResult`` (delta + timestamp +
+A periodic background probe surfaces a "needs-sync" signal when an
+integration's HI representation has drifted from upstream. The probe
+never modifies entities -- the user always chooses when to invoke
+Refresh. Per-integration probe logic lives in each
+``IntegrationConnector.check_needs_sync()`` override, which returns
+a ``SyncDelta``; sync-check rides on the same opt-in surface as full
+sync (an integration without a synchronizer naturally opts out of
+the periodic drift check too). The framework monitor wraps the
+returned delta into a ``SyncCheckResult`` (delta + timestamp +
summary) and caches it. The cache entry is the *last known state of
-the check*, not a "warning flag" — a successful Refresh records a
+the check*, not a "warning flag" -- a successful Refresh records a
zero-delta result with a current timestamp so the UI can show
"verified up to date at HH:MM".
@@ -40,8 +40,8 @@ logger = logging.getLogger(__name__)
class SyncCheckOutcome( LabeledEnum ):
"""
Per-integration result classification used by the framework
- monitor's bookkeeping. Not user-facing — this drives the cycle's
- summary log line and tests, not the UI banner.
+ monitor's bookkeeping. Not user-facing -- this drives the cycle's
+ summary log line, not the UI banner.
"""
OPTED_OUT = ( 'Opted Out' , 'Integration does not implement sync-check.' )
IN_SYNC = ( 'In Sync' , 'Upstream and HI match as of this check.' )
@@ -52,16 +52,16 @@ class SyncCheckOutcome( LabeledEnum ):
@dataclass(frozen=True)
class SyncDelta:
"""
- Result of comparing two integration-key sets — what the
+ Result of comparing two integration-key sets -- what the
synchronizer's ``check_needs_sync()`` returns. Integration-
agnostic; the convention is that ``added`` contains keys upstream
but not in HI, and ``removed`` contains keys in HI but not
upstream. Update detection (key-present-on-both-sides but content
- changed) is out of scope for v1.
+ changed) is not modeled.
Both sets contain ``IntegrationKey`` instances so comparison and
hashing automatically apply the canonical normalization
- (``IntegrationKey.__post_init__``) — the same canonicalization
+ (``IntegrationKey.__post_init__``) -- the same canonicalization
that produced the stored ``entity.integration_key`` values. The
probe never has to know about the normalization rule.
"""
@@ -87,7 +87,7 @@ class SyncCheckResult:
Cached state for one integration: the most recent ``SyncDelta``
plus when the check ran and a short human-readable summary for
the UI. Always present after the first cycle (or after a
- successful Refresh) — even when nothing has drifted, the
+ successful Refresh) -- even when nothing has drifted, the
zero-delta result records "verified up to date at HH:MM".
"""
delta : SyncDelta
@@ -149,7 +149,7 @@ class IntegrationSyncCheck:
in-place. Without a guard, every read of a stale entry would
propagate the unpickle exception out through the manage page.
Catch broadly, evict the bad key so the next request runs
- clean, and degrade to a cache miss — the next probe cycle (or
+ clean, and degrade to a cache miss -- the next probe cycle (or
a successful Refresh) writes fresh state."""
if not integration_id:
return None
@@ -178,19 +178,18 @@ class IntegrationSyncCheck:
in-progress drift does not re-alarm cycle after cycle.
Concurrency: this is a read-modify-write on the cache without
- a lock. The two callers — the framework monitor's probe cycle
+ a lock. The two writers (the framework monitor's probe cycle
and ``record_sync_complete`` via the synchronizer's post-sync
- hook — can theoretically run concurrently if a user-triggered
- Refresh overlaps a probe cycle. By inspection the
- interleavings are benign: duplicate-direction races (both
- writers see prior=clean and call ``_fire_needs_sync_alarm``)
- collapse to a single alert via ``AlertManager``'s
- signature-based dedup, and opposite-direction races worst
- case fire a stale alarm for drift that was just cleared
- — dismissable, rare, no correctness impact. A Redis lock
- would prevent it but trades real cache-backend portability
- risk (LocMemCache in tests) for a marginal UX win, so we
- intentionally do not lock here."""
+ hook) can run concurrently if a user-triggered Refresh
+ overlaps a probe cycle. By inspection the interleavings are
+ benign: duplicate-direction races (both writers see
+ prior=clean and call ``_fire_needs_sync_alarm``) collapse to
+ a single alert via ``AlertManager``'s signature-based dedup,
+ and opposite-direction races worst case fire a stale alarm
+ for drift that was just cleared -- dismissable, rare, no
+ correctness impact. A Redis lock would prevent it but trades
+ real cache-backend portability risk (LocMemCache in tests)
+ for a marginal UX win, so we intentionally do not lock here."""
if not integration_id:
return
prior = cls.get_state( integration_id )
@@ -207,8 +206,8 @@ class IntegrationSyncCheck:
)
if cls._should_alarm( prior = prior, current = result ):
# Alarm delivery failures must not break the cache write
- # — the probe state is already persisted; the next
- # clear→set transition will re-attempt notification.
+ # -- the probe state is already persisted; the next
+ # clear->set transition will re-attempt notification.
try:
cls._fire_needs_sync_alarm(
integration_id = integration_id,
@@ -223,12 +222,12 @@ class IntegrationSyncCheck:
@staticmethod
def _should_alarm( prior : Optional[ SyncCheckResult ],
current : SyncCheckResult ) -> bool:
- """Notification gate. Fires only on the clear → needs-sync
+ """Notification gate. Fires only on the clear -> needs-sync
transition: prior was None (first probe / cache expired) or
in-sync, AND current reports needs-sync. Drift that persists
- across cycles (needs-sync → needs-sync) does not re-alarm —
+ across cycles (needs-sync -> needs-sync) does not re-alarm --
the user has already been told. Refresh-induced
- needs-sync → in-sync transitions are not a notification
+ needs-sync -> in-sync transitions are not a notification
direction."""
if not current.needs_sync:
return False
@@ -243,9 +242,8 @@ class IntegrationSyncCheck:
into the needs-sync state. Per-integration unique signature
(``integrations.needs_sync.<integration_id>``) so two
integrations both reporting drift surface as two distinct
- alerts. Lifetime is ``Alarm.MAX_LIFETIME_SECS`` — the
- canonical "until acknowledged" value (see
- ``hi/apps/alert/alarm.py``)."""
+ alerts. Lifetime is ``Alarm.MAX_LIFETIME_SECS`` -- the
+ canonical "until acknowledged" value."""
from hi.apps.alert.alarm import Alarm
from hi.apps.alert.alert_manager import AlertManager
from hi.apps.alert.enums import AlarmLevel, AlarmSource
diff --git a/src/hi/integrations/connector/sync_result.py b/src/hi/integrations/connector/sync_result.py
index 913ebe60..d1b9f507 100644
--- a/src/hi/integrations/connector/sync_result.py
+++ b/src/hi/integrations/connector/sync_result.py
@@ -4,22 +4,17 @@ Transient data shapes returned by integration sync operations.
The framework owns the sync workflow (pre-sync modal, sync view,
post-sync placement modal). Each integration's
``IntegrationConnector.sync()`` returns an
-``IntegrationSyncResult`` describing what happened during sync —
-title, structured change counts, info/error notes — plus an
+``IntegrationSyncResult`` describing what happened during sync --
+title, structured change counts, info/error notes -- plus an
optional ``EntityPlacementInput`` that drives the placement modal
when the sync produced new entities to place.
The placement input shape lives in ``hi.apps.entity.entity_placement``
-because it isn't sync-specific: any future flow that bulk-places
-entities (e.g., a "place unplaced items" recovery feature) builds
-the same shape from a different source. Sync is one supplier among
-several.
+because it isn't sync-specific: sync is one supplier among
+several. The shape is built from entities, not from sync-time
+context.
-The result modal renders a counts-driven lead summary
-("N created, M updated, R removed") with per-category disclosures
-that enumerate the affected items by name, plus collapsible
-Details (``info_list``) and Errors (``error_list``) sections.
-Counts are derived from list lengths — the lists are the source
+Counts are derived from list lengths -- the lists are the source
of truth. ``info_list`` carries diagnostic context the per-item
lists can't express ("Found N upstream items", "Filtered N by
allowlist", etc.).
@@ -36,41 +31,33 @@ class IntegrationSyncResult:
"""Outcome of a single integration sync run.
``placement_input`` is None when the sync produced no new
- entities to place (the typical refresh-with-no-new-items case);
- populated when there's something for the placement modal to
- show. The framework uses presence/absence of placement_input —
- not emptiness checks against groups/ungrouped_items — to decide
- whether to show the placement.
+ entities to place; populated when there's something for the
+ placement modal to show. The framework uses presence/absence of
+ placement_input -- not emptiness checks against
+ groups/ungrouped_items -- to decide whether to show the
+ placement.
``created_list`` / ``updated_list`` / ``reconnected_list`` /
``detached_list`` / ``removed_list`` hold the *names* of entities
affected by this sync run, populated by the per-integration
- synchronizer as it walks upstream items. The result modal uses
- list length for the count badges and the list contents for
- per-category "Show items" disclosures so the operator can see
- which entities were touched. Names only — per-attribute change
- detail is intentionally not surfaced.
+ synchronizer as it walks upstream items. Names only --
+ per-attribute change detail is intentionally not surfaced.
The five categories are mutually exclusive for any given entity
in a single sync run:
- * ``created_list`` — brand new entities this sync.
- * ``updated_list`` — existing primary-matched entities
- whose payload changed.
- * ``reconnected_list`` — previously-detached entities that
- were re-attached this sync (Issue
- #281 auto-reconnect).
- * ``detached_list`` — entities preserved with user data on
- this sync (sync-time preservation
- or Disable-SAFE). They retain their
- custom attributes / layout / etc.
- and surface in the UI as "Detached
- from <integration>".
- * ``removed_list`` — entities hard-deleted this sync.
+ * ``created_list`` -- brand new entities this sync.
+ * ``updated_list`` -- existing primary-matched entities
+ whose payload changed.
+ * ``reconnected_list`` -- previously-detached entities that
+ were re-attached this sync.
+ * ``detached_list`` -- entities preserved with user data on
+ this sync. They retain their
+ custom attributes / layout / etc.
+ * ``removed_list`` -- entities hard-deleted this sync.
- ``info_list`` carries diagnostic notes — "Found N upstream
+ ``info_list`` carries diagnostic notes -- "Found N upstream
items", "Filtered N by allowlist", ambiguous-reconnect
- breadcrumbs — that the per-item lists can't express. Rendered
- as a collapsible Details section in the result modal.
+ breadcrumbs -- that the per-item lists can't express.
``error_list`` is the parallel for failures.
``created_entities`` carries the just-created ``Entity``
@@ -95,8 +82,7 @@ class IntegrationSyncResult:
@property
def has_changes(self) -> bool:
- """True if the sync produced any operator-relevant change.
- Drives the 'Nothing new' lead line when False."""
+ """True if the sync produced any operator-relevant change."""
return bool(
self.created_list
or self.updated_list
diff --git a/src/hi/integrations/connector/user_data_detector.py b/src/hi/integrations/connector/user_data_detector.py
index 587447e4..9829c4b8 100644
--- a/src/hi/integrations/connector/user_data_detector.py
+++ b/src/hi/integrations/connector/user_data_detector.py
@@ -19,33 +19,25 @@ class EntityUserDataDetector:
"""
Detects user-created data associated with entities to determine
whether an entity should be preserved during integration deletion.
-
- This class provides analysis methods only - no database operations
- are performed. The calling code is responsible for acting on the
- information provided by these methods.
+ Analytical only -- the caller acts on the returned information.
"""
@staticmethod
def has_user_created_attributes(entity: Entity) -> bool:
"""
- Check if an entity has user-created attributes that justify preservation.
+ Check if an entity has user-created attributes that justify
+ preservation.
Provenance is determined by ``attribute_type_str``:
- - ``AttributeType.CUSTOM`` → user-added via the UI.
- - ``AttributeType.PREDEFINED`` → defined by the system or by an
+ - ``AttributeType.CUSTOM`` -> user-added via the UI.
+ - ``AttributeType.PREDEFINED`` -> defined by the system or by an
integration's converter.
- ``integration_key_str`` is *not* a provenance signal — it is an
+ ``integration_key_str`` is *not* a provenance signal -- it is an
optional per-attribute upstream backreference some integrations
(e.g., HomeBox) use for fine-grained sync, and is absent for
integration-created attributes that have no per-field upstream id
(e.g., HA's synthesized Insteon-address attribute).
-
- Args:
- entity: The Entity to check for user-created attributes
-
- Returns:
- True if the entity has user-created attributes, False otherwise
"""
user_attributes = entity.attributes.filter(
attribute_type_str=str(AttributeType.CUSTOM),
@@ -115,17 +107,14 @@ class EntityUserDataDetector:
orphaned_state_ids = set()
for state in entity.states.all():
- # Check if state will have any remaining sensors
remaining_sensors = state.sensors.exclude(
id__in=removed_sensor_ids
).exists()
-
- # Check if state will have any remaining controllers
+
remaining_controllers = state.controllers.exclude(
id__in=removed_controller_ids
).exists()
-
- # If no remaining sensors or controllers, this state can be deleted
+
if not remaining_sensors and not remaining_controllers:
orphaned_state_ids.add(state.id)
logger.debug(f'EntityState {state} will be orphaned and should be removed')
diff --git a/src/hi/integrations/connector/view_mixins.py b/src/hi/integrations/connector/view_mixins.py
index a4e292fe..8a39bfd5 100644
--- a/src/hi/integrations/connector/view_mixins.py
+++ b/src/hi/integrations/connector/view_mixins.py
@@ -11,7 +11,7 @@ from hi.integrations.placement_request import PlacementUrlParams
class ConnectorViewMixin:
"""Connect-mode-specific view helpers. Lives in the connector
sub-package because every method here is meaningful only to the
- Connect capability — sync runs, sync-result modals, and the
+ Connect capability -- sync runs, sync-result modals, and the
placement CTA off a sync result."""
def render_sync_result( self,
@@ -19,14 +19,11 @@ class ConnectorViewMixin:
integration_data,
preserve_user_data : bool = True ):
"""Run the integration's connector and render the
- sync-result modal. Shared by the initial-connect flow
- (ConnectorConfigureView.post after enable) and the update-check
- flow (IntegrationSyncView.post after pre-sync confirm).
-
- Returns the modal response directly, including the placement
- URL for the 'Place new items' CTA when sync produced new
- entities. Cache invalidations run in a ``finally`` so a
- partial-commit failure during sync also flushes."""
+ sync-result modal. Returns the modal response directly,
+ including the placement URL for the placement CTA when sync
+ produced new entities. Cache invalidations run in a
+ ``finally`` so a partial-commit failure during sync also
+ flushes."""
gateway = integration_data.integration_gateway
connector = gateway.get_connector()
if connector is None:
diff --git a/src/hi/integrations/connector/views.py b/src/hi/integrations/connector/views.py
index ed1d4845..4fb73737 100644
--- a/src/hi/integrations/connector/views.py
+++ b/src/hi/integrations/connector/views.py
@@ -83,19 +83,17 @@ class IntegrationHealthStatusView( HiModalView, IntegrationViewMixin ):
class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
"""
- Pre-sync confirmation modal for the manage-page UPDATE
- button. Surfaces the synchronizer's description and offers
- Sync / Not now actions. Not used in the first-time sync
- enable flow.
-
- On the update-check path the modal additionally surfaces the
- same SAFE / ALL policy choice the disable modal does when the
- integration has any user-data entities — the operator's choice
- expresses the policy applied at sync execution if any drops
- carry user data.
-
- 404s when the integration does not provide a connector (sync
- is opt-in capability — not every integration supports it).
+ Pre-sync confirmation modal for the manage-page UPDATE button.
+ Surfaces the synchronizer's description and offers Sync / Not now
+ actions. Not used in the first-time sync enable flow.
+
+ On the update-check path the modal additionally surfaces the same
+ SAFE / ALL policy choice the disable modal does when the integration
+ has any user-data entities -- the operator's choice expresses the
+ policy applied at sync execution if any drops carry user data.
+
+ 404s when the integration does not provide a connector (sync is
+ opt-in capability -- not every integration supports it).
"""
def get_template_name( self ) -> str:
@@ -135,20 +133,19 @@ class IntegrationPreSyncView( HiModalView, IntegrationViewMixin ):
class IntegrationSyncView( HiModalView, IntegrationViewMixin, ConnectorViewMixin ):
"""
- Framework sync execution view. Invokes the integration's
- connector and always renders the sync result modal — the
- operator's single end-of-sync surface. When the sync produced
- new entities to place, the result modal exposes a primary
- 'Place N new items' CTA that navigates (via antinode modal-to-
- modal) to the placement GET endpoint where the operator picks
+ Framework sync execution view. Invokes the integration's connector
+ and always renders the sync result modal -- the operator's single
+ end-of-sync surface. When the sync produced new entities to place,
+ the result modal exposes a primary 'Place N new items' CTA that
+ navigates to the placement GET endpoint where the operator picks
targets. When there are no new entities (refresh-with-updates,
refresh-with-removes, errors, or nothing-new), the result modal
shows just a dismissal action.
This shape was chosen so updates and removes are never silently
- swallowed by an automatic transition to the placement: the
- operator always sees what changed, and only opts into placement
- when there's actually something to place.
+ swallowed by an automatic transition to placement: the operator
+ always sees what changed, and only opts into placement when
+ there's actually something to place.
"""
def get_template_name( self ) -> str:
@@ -159,7 +156,7 @@ class IntegrationSyncView( HiModalView, IntegrationViewMixin, ConnectorViewMixin
# Operator's per-Refresh policy for items that would be
# dropped. True ("Refresh and Retain") preserves user-data
# entities by detaching them; False ("Refresh and Remove")
- # hard-deletes everything dropped. Defaults to True — the
+ # hard-deletes everything dropped. Defaults to True -- the
# safe value when the choice was not surfaced (no user-data
# entities) or the field was absent for any reason.
preserve_user_data = str_to_bool(
@@ -187,9 +184,9 @@ class ConnectorConfigureView( CapabilityConfigureView, ConnectorViewMixin ):
integration_data = integration_data,
)
- # Connect-side managers (Frigate/Hass/ZM) gate client (re)build
- # on integration.is_enabled, so the notify MUST fire after
- # enable_integration — otherwise the manager reloads with
+ # Connect-side managers gate client (re)build on
+ # integration.is_enabled, so the notify MUST fire after
+ # enable_integration -- otherwise the manager reloads with
# is_enabled=False, nulls its client, and the immediately-
# following sync sees no client. Calling unconditionally also
# covers the re-Configure path (already enabled), where
@@ -222,9 +219,9 @@ class ConnectorConfigureView( CapabilityConfigureView, ConnectorViewMixin ):
class IntegrationDisableView( HiModalView, IntegrationViewMixin ):
"""
Remove confirmation dialog. Classifies attached entities on GET to
- decide between a single DELETE action (no user-data entities exist) or
- DELETE SAFE / DELETE ALL variants (some entities have user-added data).
- POST dispatches to disable_integration with the chosen mode.
+ decide between a single DELETE action (no user-data entities exist)
+ or DELETE SAFE / DELETE ALL variants (some entities have user-added
+ data). POST dispatches to disable_integration with the chosen mode.
"""
def get_template_name( self ) -> str:
@@ -330,7 +327,6 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
if not integration_data.integration.is_enabled:
raise BadRequest( f'{integration_data.label} integration is not configured' )
- # Get health status from the integration gateway
health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()
attr_item_context = IntegrationAttributeItemEditContext(
@@ -350,10 +346,9 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
integration_id = integration_data.integration_id,
).exists()
- # Issue #283 sync-check state.
+ # Sync-check state for the manage page:
# * sync_check_result drives the banner and the Refresh
- # button emphasis on the active integration's manage
- # page.
+ # button emphasis on the active integration's manage page.
# * sidebar_items pairs each integration with its current
# sync-check result so the sidebar template iterates one
# pre-resolved list instead of looking up per-integration
@@ -402,7 +397,6 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
if not integration_data.integration.is_enabled:
raise BadRequest( f'{integration_data.label} integration is not configured' )
- # Get health status from the integration gateway
health_status_provider = integration_data.integration_gateway.get_connector().get_health_status_provider()
attr_item_context = IntegrationAttributeItemEditContext(
@@ -420,7 +414,6 @@ class ConnectorManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
attr_item_context,
regular_attributes_formset,
request ):
- """ Override for AttributeEditViewMixin """
self.validate_attributes_extra_helper(
attr_item_context,
regular_attributes_formset,
diff --git a/src/hi/integrations/importer/integration_importer.py b/src/hi/integrations/importer/integration_importer.py
index 27953037..24c5d5bd 100644
--- a/src/hi/integrations/importer/integration_importer.py
+++ b/src/hi/integrations/importer/integration_importer.py
@@ -1,11 +1,10 @@
"""
Per-integration importer base class.
-Parallel to IntegrationConnector (Connect-capability). Each
-IMPORT-capable integration provides a concrete subclass and returns
-an instance from IntegrationGateway.get_importer(). The framework
-owns the import workflow (Data Import page, configure modal,
-preview, confirm, result modal, post-import placement); the
+Each IMPORT-capable integration provides a concrete subclass and
+returns an instance from IntegrationGateway.get_importer(). The
+framework owns the import workflow (Data Import page, configure
+modal, preview, confirm, result modal, post-import placement); the
importer participates by supplying the integration-specific
candidate-listing, item ingest, and discard operations.
"""
@@ -32,15 +31,13 @@ class IntegrationImporter( CapabilityGateway ):
integration_attributes: List[IntegrationAttribute],
) -> IntegrationValidationResult:
"""Schema-only validation of the proposed configuration. Must
- NOT perform network operations. Mirrors IntegrationGateway's
- contract for the same operation on the Connect side."""
+ NOT perform network operations."""
raise NotImplementedError('Subclasses must override this method')
def get_candidate_items(self) -> List[CandidateItem]:
"""Synchronously fetch the upstream items that would be
- candidates for import. Used for the preview-step count
- ("would import N, would skip M"). Implementations filter out
- items already present in HI (by integration_name match)."""
+ candidates for import. Implementations filter out items
+ already present in HI (by integration_name match)."""
raise NotImplementedError('Subclasses must override this method')
def run_import(self) -> IntegrationImportResult:
diff --git a/src/hi/integrations/importer/transient_models.py b/src/hi/integrations/importer/transient_models.py
index c6185390..398d70ef 100644
--- a/src/hi/integrations/importer/transient_models.py
+++ b/src/hi/integrations/importer/transient_models.py
@@ -11,7 +11,7 @@ class CandidateItem:
``integration_name`` is the per-integration unique identifier for
the upstream item; matched against existing entities'
- ``integration_name`` to detect already-imported items.
+ ``previous_integration_name`` to detect already-imported items.
"""
name: str
integration_name: str
@@ -21,7 +21,6 @@ class CandidateItem:
class IntegrationImportResult:
"""Outcome of a single IntegrationImporter.run_import() invocation.
- Parallel to IntegrationSyncResult but with import-specific fields.
Imports are add-only: items not already in HI are created;
pre-existing matches are reported as skipped. There is no
update/remove path.
@@ -29,11 +28,6 @@ class IntegrationImportResult:
``placement_input`` is None when the import produced no new
entities to place; populated when the result modal should expose
the post-import placement flow.
-
- ``created_entities`` carries the just-created ``Entity``
- instances back to the framework caller, which passes them
- through ``gateway.group_entities_for_placement`` to build the
- ``placement_input`` — same shape as the Connect-sync flow.
"""
title: str
placement_input: Optional[EntityPlacementInput] = None
@@ -55,9 +49,7 @@ class IntegrationImportResult:
class IntegrationDiscardResult:
"""Outcome of an IntegrationImporter.discard_imported_data() invocation.
- ``count`` is the number of imported entities removed. ``errors``
- carries per-entity failure messages; an empty list means clean
- removal.
+ ``errors`` carries per-entity failure messages.
"""
count: int = 0
errors: List[str] = field(default_factory=list)
diff --git a/src/hi/integrations/importer/views.py b/src/hi/integrations/importer/views.py
index d4a21706..6725d61e 100644
--- a/src/hi/integrations/importer/views.py
+++ b/src/hi/integrations/importer/views.py
@@ -1,12 +1,11 @@
"""
Data Import page + Configure form views.
-CONFIGURE on the page row opens the credentials form modal (reuses
-``IntegrationAttributeItemEditContext`` with ``capability=IMPORT``).
-The form's IMPORT submit validates credentials, fetches upstream
-candidates via ``IntegrationImporter.get_candidate_items()``, computes a
-new-vs-skipped split against existing HI entities, and renders the
-preview modal. Phase 5 wires CONFIRM IMPORT → run.
+CONFIGURE on the page row opens the credentials form modal. The
+form's IMPORT submit validates credentials, fetches upstream
+candidates via ``IntegrationImporter.get_candidate_items()``,
+computes a new-vs-skipped split against existing HI entities, and
+renders the preview modal.
"""
import logging
from typing import Any, Dict
@@ -68,7 +67,7 @@ class ImporterConfigureView( CapabilityConfigureView ):
"""Credentials form for IMPORT. The form's submit (IMPORT) runs
validate_configuration + validate_access, fetches candidates, and
renders the preview modal with new/skipped counts. No DB writes
- to entities yet — that happens in the confirm step."""
+ to entities -- those happen in the confirm step."""
capability = IntegrationCapability.IMPORT
button_label = 'IMPORT'
@@ -134,7 +133,6 @@ class ImporterConfigureView( CapabilityConfigureView ):
class DataImportInfoView( HiModalView ):
- """Static info modal explaining Data Import vs. Integration."""
def get_template_name(self) -> str:
return 'integrations/importer/modals/data_import_info.html'
@@ -154,9 +152,8 @@ class ImporterRunView( HiModalView, IntegrationViewMixin ):
try:
result = importer.run_import()
finally:
- # Mirror the post-sync invalidations so any cached
- # metadata or sensor-response state pinned by polls that
- # raced the import gets dropped.
+ # Drop cached metadata / sensor-response state that may
+ # have been pinned by polls racing the import.
IntegrationMetadataCache().invalidate()
SensorResponseManager().invalidate_local_sensor_cache()
@@ -191,7 +188,7 @@ class ImporterRunView( HiModalView, IntegrationViewMixin ):
class ImporterDiscardView( HiModalView, IntegrationViewMixin ):
"""DISCARD handler. GET renders the confirmation modal with the
count of imported entities; POST runs discard_imported_data and
- redirects back to the Data Import page. Single-action confirm —
+ redirects back to the Data Import page. Single-action confirm --
imported items ARE the user data, so the Connect-side SAFE/ALL
split doesn't apply."""
@@ -222,9 +219,8 @@ class ImporterDiscardView( HiModalView, IntegrationViewMixin ):
integration_id = integration_data.integration_id,
)
finally:
- # Mirror the Connect-side Disable cleanup: any cached
- # metadata / sensor-response state for the just-deleted
- # entities must drop too.
+ # Drop cached metadata / sensor-response state for the
+ # just-deleted entities.
IntegrationMetadataCache().invalidate()
SensorResponseManager().invalidate_local_sensor_cache()
diff --git a/src/hi/integrations/referencer/integration_referencer.py b/src/hi/integrations/referencer/integration_referencer.py
index 180c4e51..ac440db1 100644
--- a/src/hi/integrations/referencer/integration_referencer.py
+++ b/src/hi/integrations/referencer/integration_referencer.py
@@ -1,10 +1,9 @@
"""
Per-integration ATTRIBUTE_REFERENCE base class.
-Parallel to ``IntegrationConnector`` (CONNECT capability) and
-``IntegrationImporter`` (IMPORT capability). Each integration that
-advertises ``IntegrationCapability.ATTRIBUTE_REFERENCE`` provides a
-concrete subclass and returns an instance from
+Each integration that advertises
+``IntegrationCapability.ATTRIBUTE_REFERENCE`` provides a concrete
+subclass and returns an instance from
``IntegrationGateway.get_attribute_referencer()``. The framework
owns the picker UI, attach lifecycle, and TEXT-attribute creation;
the integration participates by translating a search query into a
@@ -36,8 +35,7 @@ class IntegrationAttributeReferencer( CapabilityGateway ):
integration_attributes: List[IntegrationAttribute],
) -> IntegrationValidationResult:
"""Schema-only validation of the proposed configuration.
- Must NOT perform network operations. Mirrors the contract
- for the same operation on the Connect / Import sides."""
+ Must NOT perform network operations."""
raise NotImplementedError('Subclasses must override this method')
def search_references(
diff --git a/src/hi/integrations/referencer/transient_models.py b/src/hi/integrations/referencer/transient_models.py
index f5165cb5..d2ff3935 100644
--- a/src/hi/integrations/referencer/transient_models.py
+++ b/src/hi/integrations/referencer/transient_models.py
@@ -24,7 +24,7 @@ class AttributeReferenceResult:
"""One row in the picker's result list.
``title`` and ``source_url`` are the only fields that survive
- the attach step — they become the attribute's ``name`` and
+ the attach step -- they become the attribute's ``name`` and
``value`` respectively. Everything else is picker chrome.
"""
title: str
diff --git a/src/hi/integrations/referencer/views.py b/src/hi/integrations/referencer/views.py
index 3c753873..7cd17a4d 100644
--- a/src/hi/integrations/referencer/views.py
+++ b/src/hi/integrations/referencer/views.py
@@ -1,16 +1,14 @@
"""
-ATTRIBUTE_REFERENCE picker — one HiModal view backed by antinode
+ATTRIBUTE_REFERENCE picker -- one HiModal view backed by antinode
partial swaps.
Workflow:
- GET ``/integrations/referencer/picker/`` with ``item_type`` +
``item_id`` query params renders the full picker modal. The
- action-bar "LINK" button in EntityEdit / LocationEdit opens
- the modal via ``data-async="modal"``. The view discovers all
- currently-enabled ATTRIBUTE_REFERENCE integrations and lets
- the operator choose between them via an in-modal selector
- when more than one is configured.
+ view discovers all currently-enabled ATTRIBUTE_REFERENCE
+ integrations and lets the operator choose between them via an
+ in-modal selector when more than one is configured.
- POST to the same URL re-renders the picker body. The form
carries ``integration_id`` as a hidden field so the view knows
@@ -28,8 +26,8 @@ Multi-select state is server-driven via three form fields:
(hidden per result; identifies what was rendered), and ``result_url``
(checkbox value per result; only submitted when checked). The view
computes the new selection list each POST: existing + newly checked
-- unchecked visibles ± an explicit ``remove_url`` if the operator
-clicked a chip's × button.
+- unchecked visibles +/- an explicit ``remove_url`` if the operator
+clicked a chip's remove button.
"""
import json
@@ -76,7 +74,7 @@ _PAGE_SIZE_CHOICES = (20, 50, 100)
_DEFAULT_LIMIT = 20
_MAX_LIMIT = 100
-# ItemType → (owner model, attribute model, owner FK field name).
+# ItemType -> (owner model, attribute model, owner FK field name).
_ATTRIBUTE_OWNER_MODELS = {
ItemType.ENTITY: (Entity, EntityAttribute, 'entity'),
ItemType.LOCATION: (Location, LocationAttribute, 'location'),
@@ -231,12 +229,11 @@ def _create_attributes(
class AttributeReferencePickerView( HiModalView ):
- """GET the picker modal. Initial render is empty — no results,
- no selections. Selection state lives in JS (see
- ``static/js/attr-picker.js``); subsequent search results arrive
- via async POST to ``integrations_attribute_reference_search``,
- and the final commit posts to
- ``integrations_attribute_reference_attach``."""
+ """GET the picker modal. Initial render seeds the result list
+ by searching on the owner's name; selection state then lives in
+ JS. Subsequent search results arrive via async POST to
+ ``integrations_attribute_reference_search``, and the final
+ commit posts to ``integrations_attribute_reference_attach``."""
MODAL_TEMPLATE_NAME = 'integrations/referencer/modals/attr_picker.html'
@@ -263,11 +260,7 @@ class AttributeReferencePickerView( HiModalView ):
# Seed the picker with a query based on the owner's name so
# the operator opens to relevant results without retyping
- # what they're already configuring. Goes through the same
- # ``_search_upstream`` the search endpoint uses; the body
- # template's results container renders the same
- # ``attr_picker_results.html`` partial the search response
- # returns.
+ # what they're already configuring.
query = owner.name
referencer = integration_data.integration_gateway.get_attribute_referencer()
results = _search_upstream(
@@ -357,22 +350,16 @@ class AttributeReferenceAttachView( View ):
return antinode.refresh_response()
-# ----------------------------------------------------------------------
-# Reference-capability management page
-# ----------------------------------------------------------------------
-#
-# Parallel to the Connectors page (CONNECT capability) and the Data
-# Import page (IMPORT capability). The operator-facing tab label is
-# "Content Sources"; code-side naming uses ``reference`` to align
-# with the capability and the surrounding referencer/ directory.
+# The operator-facing tab label is "Content Sources"; code-side
+# naming uses ``reference`` to align with the capability and the
+# surrounding referencer/ directory.
class ReferenceHomeView( ConfigPageView, IntegrationViewMixin ):
"""Landing route for the reference-management page. Picks the
first ATTRIBUTE_REFERENCE integration (enabled or not) and
redirects to its manage URL. Returns the empty-state template
- when none are discovered (defensive — currently can't happen
- at runtime as long as the paperless app is installed)."""
+ when none are discovered."""
def config_page_type(self) -> ConfigPageType:
return ConfigPageType.INTEGRATIONS_REFERENCE
@@ -397,17 +384,12 @@ class ReferenceManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
"""Per-integration attribute-form page for ATTRIBUTE_REFERENCE
integrations.
- Differences from ``ConnectorManageView``:
- - Filters by ATTRIBUTE_REFERENCE (not CONNECT).
- - Does not read health status / sync-check state /
- has_entities; ATTRIBUTE_REFERENCE has no monitors and no
- sync cycle.
- - Passes ``capability = ATTRIBUTE_REFERENCE`` to the attribute
- edit context so the attribute queryset is filtered to the
- attributes the capability declares.
- - Tolerates ``is_enabled = False`` integrations — the operator
- configures credentials here before the integration is
- enabled.
+ ATTRIBUTE_REFERENCE has no monitors and no sync cycle, so the
+ page does not surface health status, sync-check state, or
+ has_entities. The attribute queryset is filtered to attributes
+ the ATTRIBUTE_REFERENCE capability declares. ``is_enabled =
+ False`` integrations are tolerated so the operator can configure
+ credentials here before the integration is enabled.
"""
def config_page_type(self) -> ConfigPageType:
@@ -518,12 +500,9 @@ class ReferenceManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
def validate_attributes_extra( self, attr_item_context,
regular_attributes_formset, request ):
- # The shared helper runs both gateway.validate_configuration
- # (schema) and gateway.validate_access (live probe) and
- # decorates the formset with the failure message on either
- # failure. We deliberately want the access probe on every
- # save so a credential typo on UPDATE-while-enabled is
- # rejected (atomic semantics — nothing changes on failure).
+ # We deliberately want the access probe on every save so a
+ # credential typo on UPDATE-while-enabled is rejected
+ # (atomic semantics -- nothing changes on failure).
self.validate_attributes_extra_helper(
attr_item_context,
regular_attributes_formset,
@@ -552,7 +531,7 @@ class ReferenceManageView( ConfigPageView, IntegrationViewMixin, AttributeEditVi
# first-time activation path; ``UPDATE`` is the
# already-enabled re-validate-and-save path. Both share the
# same form-submission endpoint and the same validation
- # gates — only the label and the post-save bookkeeping
+ # gates -- only the label and the post-save bookkeeping
# differ.
update_label = (
'UPDATE' if integration_data.integration.is_enabled else 'ENABLE'
diff --git a/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html b/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html
index c0277f42..b14b4cbd 100644
--- a/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/pre_sync_confirm.html
@@ -2,37 +2,32 @@
{% load icons %}
{% comment %}
-Pre-sync confirmation modal for the manage-page UPDATE
-button. Not used for the first-time enable sync flow. The modal confirms
-intent and explains what the operation will do; it does NOT surface
-integration health.
+Pre-sync confirmation modal. Confirms intent and explains what the
+operation will do; does NOT surface integration health.
-`is_initial_connect` is still threaded because the manage page can
-expose a CONNECT variant when the integration is enabled but has no
-attached entities (e.g., entities deleted post-enable). That path
-shares this template.
+The CONNECT variant renders when the integration is enabled but has
+no attached entities (e.g., entities deleted post-enable).
When `removal_summary.has_mixed_state` (update-check path with at
-least one user-data entity present), the modal mirrors the disable
-modal's policy choice: RETAIN MISSING preserves dropped user-data
-items by detaching, REMOVE MISSING hard-deletes them. The summary is
-the integration's full footprint; the operator's choice expresses
-policy that applies at sync execution if any drops carry user data.
+least one user-data entity present), the modal offers a policy
+choice: RETAIN MISSING preserves dropped user-data items by
+detaching, REMOVE MISSING hard-deletes them. The summary is the
+integration's full footprint; the operator's choice expresses policy
+that applies at sync execution if any drops carry user data.
The form is opened in `preamble` and closed in `postamble` so each
-action button is a plain `<button name="preserve_user_data" value=…>`
-on the same form (mirrors the integration_disable.html pattern).
+action button is a plain `<button name="preserve_user_data" value=...>`
+on the same form.
Context:
- integration_data : IntegrationData (required) — for label, id.
- is_initial_connect : bool (required) — True when no entities for
+ integration_data : IntegrationData (required) -- for label, id.
+ is_initial_connect : bool (required) -- True when no entities for
this integration have been imported yet
(initial CONNECT); False for subsequent
update-check operations.
- sync_description : Optional[str] — per-integration text from
- IntegrationConnector.get_sync_description.
- sync_url : str (required) — URL the form posts to.
- removal_summary : Optional[IntegrationRemovalSummary] —
+ sync_description : Optional[str]
+ sync_url : str (required) -- URL the form posts to.
+ removal_summary : Optional[IntegrationRemovalSummary] --
integration's user-data classification.
None when no entities are attached. Drives
the Retain / Remove choice on the
diff --git a/src/hi/integrations/templates/integrations/connector/modals/sync_result.html b/src/hi/integrations/templates/integrations/connector/modals/sync_result.html
index eb967e67..0e4ac9f0 100644
--- a/src/hi/integrations/templates/integrations/connector/modals/sync_result.html
+++ b/src/hi/integrations/templates/integrations/connector/modals/sync_result.html
@@ -3,30 +3,26 @@
{% load static %}
{% comment %}
- Integration sync result modal.
-
- The single end-of-sync surface: always rendered after sync
- completes, regardless of what changed. Updates and removes are
- surfaced here in their own right rather than being silently
- swallowed by an automatic transition to the placement.
+ Integration sync result modal. Always rendered after sync
+ completes, regardless of what changed -- updates and removes are
+ surfaced rather than silently swallowed by an automatic transition
+ to placement.
Renders a hero headline, a stat-card row of change counts,
color-coded per-category enumerations of affected entities, and
collapsible Errors / Details sections. When the sync produced
- newly-created entities, the footer's primary CTA navigates to
- the placement modal (via antinode modal-to-modal); otherwise
- the footer is a single dismissal button.
+ newly-created entities, the footer's primary CTA navigates to the
+ placement modal; otherwise the footer is a single dismissal button.
- The modal title bar keeps the generic HI logo + short generic
- title ('Connect Result' / 'Update Check Result'); the integration's
- identity is surfaced as a body subtitle row (logo + label) where
- the white background gives the transparent integration logos
- predictable contrast.
+ The modal title bar uses the generic HI logo + short generic title;
+ the integration's identity is surfaced as a body subtitle row
+ (logo + label) where the white background gives the transparent
+ integration logos predictable contrast.
Context:
sync_result : IntegrationSyncResult (required)
integration_data : IntegrationData (required)
- placement_url : str (optional) — target of the 'Place N items'
+ placement_url : str (optional) -- target of the 'Place N items'
CTA. Required when sync_result.created_list is
non-empty; ignored otherwise.
{% endcomment %}
@@ -41,10 +37,8 @@
{% include "integrations/panes/integration_modal_header.html" %}
{% comment %}
- Hero headline — the operator's first read of the modal. Errors
- take precedence; otherwise the change-count summary speaks.
- Centered, with a leading status icon at display weight so this
- zone clearly outranks the detail sections below.
+ Hero headline -- errors take precedence; otherwise the
+ change-count summary speaks.
{% endcomment %}
{% if sync_result.error_list and not sync_result.has_changes %}
<div class="text-center mb-4">
@@ -89,11 +83,8 @@
</div>
{% comment %}
- Stat-card row: big number + label per non-zero category.
- Visually anchors the result so the operator's eye lands on
- 'what changed and how much' before scanning the per-category
- item lists. Only non-zero categories render — symmetry is less
- important than not implying a third stat that doesn't exist.
+ Only non-zero categories render -- symmetry is less important
+ than not implying a stat that doesn't exist.
{% endcomment %}
<div class="d-flex justify-content-around flex-wrap text-center mb-4 pb-3 border-bottom">
{% if sync_result.created_list %}
@@ -138,12 +129,6 @@
{% endif %}
</div>
- {% comment %}
- Per-category item enumeration — color-coded left border bars
- matching the stat colors so the eye links each list back to
- its stat card. Section header is small/uppercase to subordinate
- the affordance to the entity names themselves.
- {% endcomment %}
{% if sync_result.removed_list %}
<div class="mb-3 pl-3 hi-category-section hi-category-section--danger">
<div class="small text-danger text-uppercase mb-1 hi-uppercase-label">
@@ -210,17 +195,12 @@
{% endif %}
{% endif %}
-{% comment %}
- Actionable hint (e.g., HASS allowlist) — promoted from muted
- footer text to a real callout.
-{% endcomment %}
{% if sync_result.footer_message %}
<div class="alert alert-info small mb-3">
{{ sync_result.footer_message }}
</div>
{% endif %}
-{% comment %}Errors detail — expanded by default when present.{% endcomment %}
{% if sync_result.error_list %}
<div class="mb-2 pl-3 hi-category-section hi-category-section--danger">
<a class="small text-danger text-uppercase hi-uppercase-label" data-toggle="collapse"
@@ -238,7 +218,6 @@
</div>
{% endif %}
-{% comment %}Diagnostic notes — collapsed by default.{% endcomment %}
{% if sync_result.info_list %}
<div class="mt-2">
<a class="text-muted small" data-toggle="collapse"
@@ -259,13 +238,13 @@
{% comment %}
Each footer block is declared unconditionally; the {% if %} is
- inside the block content, not around the {% block %} tag.
- Django parses block declarations regardless of enclosing if-
- conditions, so wrapping the declarations would render both
- branches simultaneously.
+ inside the block content, not around the {% block %} tag. Django
+ parses block declarations regardless of enclosing if-conditions,
+ so wrapping the declarations would render both branches
+ simultaneously.
Page-reload onclick on the dismiss buttons: the modal-to-modal
- flow that lands here never refreshed the underlying integrations
+ flow that lands here never refreshes the underlying integrations
page, so a plain dismiss leaves a stale background. Reload makes
the background page consistent with anything the sync changed.
{% endcomment %}
diff --git a/src/hi/integrations/templates/integrations/modals/placement.html b/src/hi/integrations/templates/integrations/modals/placement.html
index e67066c6..930dc578 100644
--- a/src/hi/integrations/templates/integrations/modals/placement.html
+++ b/src/hi/integrations/templates/integrations/modals/placement.html
@@ -2,7 +2,7 @@
{% load icons %}
{% comment %}
-Post-sync entity placement placement.
+Post-sync entity placement.
Progressive disclosure: by default only the top-level decision is
visible ("Place all new items in [target]") with an inventory
@@ -11,8 +11,8 @@ and per-item rows are hidden behind a "Place differently"
disclosure. Inside the disclosure, group rows are single-line and
each carries its own per-item drill-down disclosure.
-Three-level inheritance under the hood is unchanged: top default →
-group default → per-item. Empty selections at any level inherit
+Three-level inheritance under the hood is unchanged: top default ->
+group default -> per-item. Empty selections at any level inherit
from the level above; explicit "Don't place" at any level prevents
placement for that branch.
@@ -29,29 +29,29 @@ multi-Location deployments can disambiguate views with shared names
Context:
integration_data : IntegrationData (required)
placement_input : EntityPlacementInput (required)
- grouping_heading : Optional[str] — column-header text shown
+ grouping_heading : Optional[str] -- column-header text shown
above the group list inside the override
panel. None when the heading is the
implicit default ("Item Type"); the
column header is suppressed in that case.
location_view_groups : List[(Location, List[LocationView])] (required)
collection_list : List[Collection] (required)
- top_default_value : str (required) — pre-selected value for
+ top_default_value : str (required) -- pre-selected value for
the top dropdown ('__new_view__',
'view:<id>', 'collection:<id>', or '')
- new_view_name : str (required) — pre-disambiguated name
+ new_view_name : str (required) -- pre-disambiguated name
shown in the '+ New view: "X"' option
label; matches what the apply path will
actually create.
- new_collection_name : str (required) — pre-disambiguated name
+ new_collection_name : str (required) -- pre-disambiguated name
shown in the '+ New collection: "X"'
option label; matches what the apply
path will actually create.
- inventory_preview : List[{'label', 'count'}] (required) —
+ inventory_preview : List[{'label', 'count'}] (required) --
group label + count tuples for the
summary line; empty for all-ungrouped
inputs (preview hidden in that case)
- placement_url : str (required) — same URL that rendered
+ placement_url : str (required) -- same URL that rendered
this modal; the form POSTs back to it
and the view branches on the submitted
``action`` value.
diff --git a/src/hi/integrations/templates/integrations/modals/placement_dismiss.html b/src/hi/integrations/templates/integrations/modals/placement_dismiss.html
index 378ed015..14abb4e0 100644
--- a/src/hi/integrations/templates/integrations/modals/placement_dismiss.html
+++ b/src/hi/integrations/templates/integrations/modals/placement_dismiss.html
@@ -19,7 +19,7 @@ Two paths forward:
Context:
integration_data : IntegrationData (required)
- placement_url : str (required) — GO BACK target
+ placement_url : str (required) -- GO BACK target
{% endcomment %}
{% block header_class %}bg-secondary{% endblock %}
diff --git a/src/hi/integrations/templates/integrations/modals/post_placement.html b/src/hi/integrations/templates/integrations/modals/post_placement.html
index 7ec6ed57..c71728cc 100644
--- a/src/hi/integrations/templates/integrations/modals/post_placement.html
+++ b/src/hi/integrations/templates/integrations/modals/post_placement.html
@@ -81,16 +81,16 @@ Update check complete
refinement is optional polish). Right = REFINE/REVIEW on
the highest-occupied target.
* Single centered OK button when nothing was placed (operator
- chose 'Don't place' everywhere) — no real action was
+ chose 'Don't place' everywhere) -- no real action was
completed, so OK ('acknowledge info, dismiss') is more
accurate than DONE ('action completed'). Centered via the
- action_3 layout's action_center slot — using a side slot
+ action_3 layout's action_center slot -- using a side slot
would look skewed compared to other single-button modals
across the app.
Either button reloads the page on dismiss. The modal-to-modal
- flow that brought the operator here (Configure → pre-sync →
- result → placement → post-dispatch) never refreshed the
+ flow that brought the operator here (Configure -> pre-sync ->
+ result -> placement -> post-dispatch) never refreshed the
underlying integrations page; the entities just imported and
placed need to surface there.
{% endcomment %}
diff --git a/src/hi/integrations/templates/integrations/panes/placement_target_options.html b/src/hi/integrations/templates/integrations/panes/placement_target_options.html
index f6c3127e..673214bf 100644
--- a/src/hi/integrations/templates/integrations/panes/placement_target_options.html
+++ b/src/hi/integrations/templates/integrations/panes/placement_target_options.html
@@ -4,15 +4,12 @@ Reusable dropdown options for placement target-selects (LocationViews
Renders LocationViews first as one <optgroup> per Location (ordered
by Location.order_id, views within by LocationView.order_id), then
-a single 'Collections' <optgroup>. Option values are *tagged* —
-``view:<id>`` or ``collection:<id>`` — so views and collections can
+a single 'Collections' <optgroup>. Option values are *tagged* --
+``view:<id>`` or ``collection:<id>`` -- so views and collections can
share the same select element without colliding on numeric ids.
-Optionally honors ``selected_view_id`` / ``selected_collection_id``
-(passed via ``include … with …``) by adding the ``selected``
-attribute to the matching option. Used by the placement's top
-dropdown so the smart-default sticks; group/entity dropdowns don't
-pass them.
+When ``selected_view_id`` / ``selected_collection_id`` are provided,
+the matching option gets the ``selected`` attribute.
Context:
location_view_groups : List[(Location, List[LocationView])]
diff --git a/src/hi/integrations/templates/integrations/referencer/modals/attr_picker.html b/src/hi/integrations/templates/integrations/referencer/modals/attr_picker.html
index 2c3a0e5c..42097f49 100644
--- a/src/hi/integrations/templates/integrations/referencer/modals/attr_picker.html
+++ b/src/hi/integrations/templates/integrations/referencer/modals/attr_picker.html
@@ -5,10 +5,10 @@
ATTRIBUTE_REFERENCE picker modal.
Selection state lives in attr-picker.js (one selection set per open
-modal instance, keyed by the picker-root DOM node — i.e., this
+modal instance, keyed by the picker-root DOM node -- i.e., this
modal-dialog). attr-picker.js attaches its handlers as delegated
listeners at document level, so antinode-injected modal content
-wires up automatically — no init step in this template.
+wires up automatically -- no init step in this template.
Layout:
@@ -66,7 +66,7 @@ Link Content
No ``data-async`` here: attr-picker.js owns the submit so it can
populate ``selections_json`` and POST through antinode's public
API (``AN.hideModalIfNeeded`` + ``AN.post``). Letting antinode
- also bind via ``data-async`` would race the field-population —
+ also bind via ``data-async`` would race the field-population --
antinode reads the form at the <body> level before attr-picker's
document-level submit handler fires.
{% endcomment %}
diff --git a/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html b/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html
index 17bb94ae..bfc6407b 100644
--- a/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html
+++ b/src/hi/integrations/templates/integrations/referencer/panes/attribute_actions.html
@@ -17,7 +17,7 @@ Context (inherited from the surrounding edit body):
DISABLE shares the surrounding attribute form (HTML forbids nested
forms; the attr.js wiring reads the outer form's ``action`` and
ignores ``formaction``). Dispatch is via the ``action`` POST field
-— the manage view's POST handler branches on it.
+-- the manage view's POST handler branches on it.
{% endcomment %}
<button type="submit"
name="action"
diff --git a/src/hi/static/css/attribute.css b/src/hi/static/css/attribute.css
index f4665da4..8a774c5f 100644
--- a/src/hi/static/css/attribute.css
+++ b/src/hi/static/css/attribute.css
@@ -1002,7 +1002,7 @@
.attr-v2-action-buttons a.btn .hi-icon-left {
margin-right: 0.5rem;
}
-}
+
/* ====================================================================== */
/* SECRET FIELD STYLING */
/* ====================================================================== */
diff --git a/src/hi/static/js/attr-dirty-tracking.js b/src/hi/static/js/attr-dirty-tracking.js
index a5283279..8368d2a9 100644
--- a/src/hi/static/js/attr-dirty-tracking.js
+++ b/src/hi/static/js/attr-dirty-tracking.js
@@ -248,11 +248,7 @@
},
insertDirtyIndicator: function(container, indicator) {
- if (container.classList.contains(Hi.ATTR_V2_ATTRIBUTE_NAME_CLASS)) {
- container.appendChild(indicator);
- } else {
- container.appendChild(indicator);
- }
+ container.appendChild(indicator);
},
// Add fallback CSS classes for browsers without :has() support