Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions _pr_body.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
Merges `develop` into `main` for release v1.4.3.

## Changes

- Fixed: Flow meter sensor now correctly reports "Unexpected flow" instead of "Wet soil" in irrigation history (issue #36)
- Fixed: Safety sweep — all zone valves are explicitly closed when the last active zone finishes
- Fixed: Manual start now supports a "Force start" option to bypass active sensor blocks
- New: Pump control — configure a pump entity (e.g. well pump) that starts/stops with irrigation
- New: Settings page — language selector (EN/PL/DE) and 6 customisable interface colours, persisted to DB

See [CHANGELOG](addon/CHANGELOG.md) for full details.
8 changes: 8 additions & 0 deletions addon/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## 1.4.3

- Fixed: Flow meter sensor now correctly reports "Unexpected flow" (instead of "Wet soil") in irrigation history.
- Fixed: Safety sweep — all zone valves are explicitly closed when the last active zone finishes (prevents stuck-open valves).
- Fixed: Manual start now supports a "Force start" option to bypass active sensor blocks (soil, rain, frost, flow).
- New: Pump control — configure a pump entity (e.g. well pump) that starts automatically with the first section and stops after the last, mirroring main valve behaviour.
- New: Settings page — language selector (EN/PL/DE) and 6 customisable interface colours (hex input + colour picker), all persisted to the database.

## 1.4.2

- Fixed: HA WebSocket "Cannot write to closing transport" error after Home Assistant restart — sends are now guarded by a connection-state flag that is only set after successful `auth_ok`.
Expand Down
14 changes: 13 additions & 1 deletion addon/backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,19 @@ def health():

@app.get("/api/config")
def get_config():
return {"language": settings.default_language}
# DB language override takes precedence over addon env var
lang = settings.default_language
try:
from sqlmodel import Session, select
from backend.models import AppSetting
from backend.database.db import engine
with Session(engine) as session:
row = session.get(AppSetting, "app_language")
if row and row.value:
lang = row.value
except Exception:
pass
return {"language": lang}


static_dir = settings.static_dir
Expand Down
1 change: 1 addition & 0 deletions addon/backend/models/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ class SkipReason(str, Enum):
rain = "rain"
soil_wet = "soil_wet"
frost = "frost"
flow_detected = "flow_detected"
manual_stop = "manual_stop"
ha_unavailable = "ha_unavailable"

Expand Down
2 changes: 2 additions & 0 deletions addon/backend/routers/irrigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

class StartRequest(BaseModel):
duration_min: Optional[int] = None
force: bool = False # bypass sensor checks when True


@router.get("/status")
Expand All @@ -27,6 +28,7 @@ async def start_zone(zone_id: int, body: StartRequest = StartRequest()):
zone_id=zone_id,
duration_min=body.duration_min,
triggered_by=TriggerSource.manual,
skip_sensor_check=body.force,
)
if not result.get("ok") and not result.get("skipped"):
raise HTTPException(400, result.get("error", "Cannot start zone"))
Expand Down
50 changes: 49 additions & 1 deletion addon/backend/services/irrigation.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ def _get_main_valve_entity() -> Optional[str]:
return None


def _get_pump_entity() -> Optional[str]:
try:
with Session(engine) as session:
row = session.get(AppSetting, "pump_entity_id")
return row.value if row and row.value else None
except Exception as e:
logger.warning(f"Cannot read pump setting: {e}")
return None


def _persist_active_state(zone_id: int, zone_name: str, valve_entities: List[str],
started_at: datetime, duration_min: int, log_id: Optional[int]) -> None:
planned_end_at = started_at + timedelta(minutes=duration_min)
Expand Down Expand Up @@ -187,6 +197,15 @@ async def recover_active_watering() -> dict:
except Exception as e:
logger.warning(f"Main valve reopen failed ({main_valve}): {e}")

pump_valve = _get_pump_entity()
if pump_valve:
try:
if not await _is_entity_on(pump_valve):
await ha_client.turn_on(pump_valve)
logger.info(f"Pump {pump_valve} restarted during recovery")
except Exception as e:
logger.warning(f"Pump restart failed ({pump_valve}): {e}")

for idx, entity_id in enumerate(valve_entities):
if on_states[idx]:
continue
Expand Down Expand Up @@ -317,7 +336,7 @@ async def check_sensors_blocking(
f"Sensor block: flow meter {sensor.entity_id} = {val} L/min "
f"(unexpected flow while idle, threshold={threshold})"
)
return SkipReason.soil_wet # reuse closest reason; frontend shows it
return SkipReason.flow_detected
except (ValueError, TypeError):
pass

Expand Down Expand Up @@ -377,6 +396,14 @@ async def start_zone(zone_id: int, duration_min: Optional[int] = None,
except Exception as e:
logger.warning(f"Main valve open failed ({main_valve}): {e}")

pump_valve = _get_pump_entity()
if pump_valve:
try:
await ha_client.turn_on(pump_valve)
logger.info(f"Pump {pump_valve} started")
except Exception as e:
logger.warning(f"Pump start failed ({pump_valve}): {e}")

for entity_id in valve_entities:
try:
await ha_client.turn_on(entity_id)
Expand Down Expand Up @@ -481,6 +508,27 @@ async def _finish_zone(zone_id: int, info: dict, reason: str,
except Exception as e:
logger.warning(f"Main valve close failed ({main_valve}): {e}")

pump_valve = _get_pump_entity()
if pump_valve:
try:
await ha_client.turn_off(pump_valve)
logger.info(f"Pump {pump_valve} closed")
except Exception as e:
logger.warning(f"Pump close failed ({pump_valve}): {e}")

# Safety sweep: close all zone valves in DB to guard against any stuck valve
try:
with Session(engine) as session:
all_valves = session.exec(select(Valve).where(Valve.enabled == True)).all()
for v in all_valves:
try:
await ha_client.turn_off(v.entity_id)
except Exception:
pass
logger.info("Safety sweep: all zone valves closed")
except Exception as e:
logger.warning(f"Safety sweep failed: {e}")

_update_log(info.get("log_id"), info.get("started_at"), skipped=skipped, skip_reason=skip_reason)
await _broadcast("zone_stopped", {"zone_id": zone_id, "reason": reason, "active_zones": get_active_zones()})

Expand Down
2 changes: 1 addition & 1 deletion addon/config.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: "Irrigation BSS"
version: "1.4.2"
version: "1.4.3"
slug: "irrigation_bss"
description: "Advanced irrigation management — zones, valves, sensors, scheduler"
url: "https://github.com/BSS-Baumgart/bss_ha_irrigation"
Expand Down
19 changes: 18 additions & 1 deletion addon/frontend/public/locales/de/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"manualStart": "Manueller Start",
"quickStart": "Schnellstart",
"wateringBlocked": "Bewässerung durch Sensoren blockiert:",
"forceStart": "Erzwungener Start (Sensorblockaden ignorieren)",
"remaining": "verbleibend",
"noZones": "Keine Sektionen konfiguriert."
},
Expand Down Expand Up @@ -89,7 +90,9 @@
"turnOn": "Einschalten",
"turnOff": "Ausschalten",
"mainValve": "Hauptventil",
"mainValveDesc": "Öffnet automatisch vor der ersten Sektion und schließt nach der letzten."
"mainValveDesc": "Öffnet automatisch vor der ersten Sektion und schließt nach der letzten.",
"pump": "Pumpe",
"pumpDesc": "Brunnenpumpe oder Förderpumpe — startet automatisch mit der ersten Sektion und stoppt nach der letzten."
},
"sensors": {
"title": "Sensoren",
Expand Down Expand Up @@ -194,11 +197,25 @@
"rain": "Regen",
"soil_wet": "Feuchter Boden",
"frost": "Frost",
"flow_detected": "Unerwarteter Durchfluss",
"manual_stop": "Manueller Stopp",
"ha_unavailable": "HA nicht verfügbar"
},
"waterUsed": "Wasserverbrauch",
"clearHistory": "Verlauf löschen",
"clearConfirm": "Möchten Sie den Bewässerungsverlauf wirklich löschen?"
},
"settings": {
"title": "Einstellungen",
"language": "Sprache",
"colorTheme": "Farbschema",
"colorThemeDesc": "Passen Sie die 6 Hauptfarben der Oberfläche an. Geben Sie einen Hex-Wert (#rrggbb) ein oder verwenden Sie den Farbwähler.",
"colorPrimary": "Primär (Akzent, Schaltflächen)",
"colorPrimaryDark": "Primär dunkel (Hover)",
"colorBg": "Hintergrund",
"colorSurface": "Oberfläche (Karten)",
"colorBorder": "Rahmen",
"colorTextSecondary": "Sekundärer Text",
"resetColors": "Auf Standard zurücksetzen"
}
}
19 changes: 18 additions & 1 deletion addon/frontend/public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"manualStart": "Manual start",
"quickStart": "Quick start",
"wateringBlocked": "Watering blocked by sensors:",
"forceStart": "Force start (ignore sensor blocks)",
"remaining": "remaining",
"noZones": "No sections configured yet."
},
Expand Down Expand Up @@ -89,7 +90,9 @@
"turnOn": "Turn on",
"turnOff": "Turn off",
"mainValve": "Main valve",
"mainValveDesc": "Opens automatically before the first section starts and closes after the last section stops."
"mainValveDesc": "Opens automatically before the first section starts and closes after the last section stops.",
"pump": "Pump",
"pumpDesc": "Well pump or booster pump — starts automatically when first section starts and stops after the last stops."
},
"sensors": {
"title": "Sensors",
Expand Down Expand Up @@ -194,11 +197,25 @@
"rain": "Rain",
"soil_wet": "Wet soil",
"frost": "Frost",
"flow_detected": "Unexpected flow",
"manual_stop": "Manual stop",
"ha_unavailable": "HA unavailable"
},
"waterUsed": "Water used",
"clearHistory": "Clear history",
"clearConfirm": "Are you sure you want to clear watering history?"
},
"settings": {
"title": "Settings",
"language": "Language",
"colorTheme": "Color theme",
"colorThemeDesc": "Customize the 6 main colors of the interface. Enter a hex value (#rrggbb) or use the color picker.",
"colorPrimary": "Primary (accent, buttons)",
"colorPrimaryDark": "Primary dark (hover)",
"colorBg": "Background",
"colorSurface": "Surface (cards)",
"colorBorder": "Border",
"colorTextSecondary": "Secondary text",
"resetColors": "Reset to defaults"
}
}
19 changes: 18 additions & 1 deletion addon/frontend/public/locales/pl/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@
"manualStart": "Ręczny start",
"quickStart": "Szybki start",
"wateringBlocked": "Podlewanie zablokowane przez czujniki:",
"forceStart": "Wymuś start (ignoruj blokady czujników)",
"remaining": "pozostało",
"noZones": "Brak skonfigurowanych sekcji."
},
Expand Down Expand Up @@ -89,7 +90,9 @@
"turnOn": "Włącz",
"turnOff": "Wyłącz",
"mainValve": "Zawór główny",
"mainValveDesc": "Otwiera się automatycznie przed uruchomieniem pierwszej sekcji i zamyka po zatrzymaniu ostatniej."
"mainValveDesc": "Otwiera się automatycznie przed uruchomieniem pierwszej sekcji i zamyka po zatrzymaniu ostatniej.",
"pump": "Pompa",
"pumpDesc": "Pompa ze studni lub pompa wspomagająca — uruchamia się automatycznie przed pierwszą sekcją i zatrzymuje po ostatniej."
},
"sensors": {
"title": "Czujniki",
Expand Down Expand Up @@ -194,11 +197,25 @@
"rain": "Deszcz",
"soil_wet": "Mokra gleba",
"frost": "Mróz",
"flow_detected": "Nieoczekiwany przepływ",
"manual_stop": "Ręczne zatrzymanie",
"ha_unavailable": "HA niedostępne"
},
"waterUsed": "Zużycie wody",
"clearHistory": "Wyczyść historię",
"clearConfirm": "Czy na pewno chcesz wyczyścić historię podlewania?"
},
"settings": {
"title": "Ustawienia",
"language": "Język",
"colorTheme": "Motyw kolorystyczny",
"colorThemeDesc": "Dostosuj 6 głównych kolorów interfejsu. Wpisz wartość hex (#rrggbb) lub użyj próbnika kolorów.",
"colorPrimary": "Główny (akcent, przyciski)",
"colorPrimaryDark": "Główny ciemny (hover)",
"colorBg": "Tło",
"colorSurface": "Powierzchnia (karty)",
"colorBorder": "Obramowanie",
"colorTextSecondary": "Tekst drugorzędny",
"resetColors": "Przywróć domyślne"
}
}
2 changes: 2 additions & 0 deletions addon/frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import SensorsPage from './pages/SensorsPage'
import SchedulePage from './pages/SchedulePage'
import WeatherPage from './pages/WeatherPage'
import HistoryPage from './pages/HistoryPage'
import SettingsPage from './pages/SettingsPage'
import { useWebSocket } from './hooks/useWebSocket'

function App() {
Expand All @@ -25,6 +26,7 @@ function App() {
<Route path="/schedule" element={<SchedulePage />} />
<Route path="/weather" element={<WeatherPage />} />
<Route path="/history" element={<HistoryPage />} />
<Route path="/settings" element={<SettingsPage />} />
<Route path="*" element={<Navigate to="/dashboard" replace />} />
</Routes>
</AppLayout>
Expand Down
4 changes: 2 additions & 2 deletions addon/frontend/src/api/irrigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import type { IrrigationStatus } from '../types'

export const irrigationApi = {
status: () => client.get<IrrigationStatus>('/api/irrigation/status').then(r => r.data),
start: (zoneId: number, durationMin?: number) =>
client.post(`/api/irrigation/start/${zoneId}`, { duration_min: durationMin }).then(r => r.data),
start: (zoneId: number, durationMin?: number, force?: boolean) =>
client.post(`/api/irrigation/start/${zoneId}`, { duration_min: durationMin, force: force ?? false }).then(r => r.data),
stop: (zoneId: number) =>
client.post(`/api/irrigation/stop/${zoneId}`).then(r => r.data),
stopAll: () => client.post('/api/irrigation/stop-all').then(r => r.data),
Expand Down
27 changes: 22 additions & 5 deletions addon/frontend/src/components/Layout/AppLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,48 @@ import { useEffect, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import Sidebar from './Sidebar'
import HeaderBar from './HeaderBar'
import { useIrrigationStore } from '../../store/irrigationStore'
import { useIrrigationStore, applyThemeColors, DEFAULT_COLORS, type ThemeColors } from '../../store/irrigationStore'
import { INGRESS_BASE } from '../../lib/ingressBase'
import { settingsApi } from '../../api/settings'

const COLOR_KEYS: (keyof ThemeColors)[] = ['primary', 'primaryDark', 'bg', 'surface', 'border', 'textSecondary']
const SETTING_KEYS = ['theme_color_primary', 'theme_color_primary_dark', 'theme_color_bg', 'theme_color_surface', 'theme_color_border', 'theme_color_text_secondary']

export default function AppLayout({ children }: { children: ReactNode }) {
const theme = useIrrigationStore(s => s.theme)
const sidebarOpen = useIrrigationStore(s => s.sidebarOpen)
const closeSidebar = useIrrigationStore(s => s.closeSidebar)
const setThemeColors = useIrrigationStore(s => s.setThemeColors)
const { i18n } = useTranslation()

useEffect(() => {
document.documentElement.classList.toggle('dark', theme === 'dark')
}, [theme])

useEffect(() => {
localStorage.removeItem('irrigation-lang-override')
fetch(`${INGRESS_BASE}/api/config`)
.then(r => r.json())
.then(cfg => {
if (cfg.language) {
i18n.changeLanguage(cfg.language)
}
if (cfg.language) i18n.changeLanguage(cfg.language)
})
.catch(() => {})
}, [i18n])

useEffect(() => {
settingsApi.getAll().then(cfg => {
const colors: Partial<ThemeColors> = {}
COLOR_KEYS.forEach((key, i) => {
const val = cfg[SETTING_KEYS[i]]
if (val) colors[key] = val
})
if (Object.keys(colors).length > 0) {
setThemeColors(colors)
} else {
applyThemeColors(DEFAULT_COLORS)
}
}).catch(() => { applyThemeColors(DEFAULT_COLORS) })
}, [setThemeColors])

return (
<div className="flex h-screen overflow-hidden bg-gray-100 dark:bg-gray-950">
{/* Mobile overlay */}
Expand Down
3 changes: 2 additions & 1 deletion addon/frontend/src/components/Layout/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { NavLink } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import {
LayoutDashboard, Layers, Zap, Radio, CalendarDays,
Cloud, History, Sun, Moon, X,
Cloud, History, Sun, Moon, X, Settings,
} from 'lucide-react'
import clsx from 'clsx'
import { useIrrigationStore } from '../../store/irrigationStore'
Expand All @@ -15,6 +15,7 @@ const navItems = [
{ to: '/schedule', icon: CalendarDays, label: 'nav.schedule' },
{ to: '/weather', icon: Cloud, label: 'nav.weather' },
{ to: '/history', icon: History, label: 'nav.history' },
{ to: '/settings', icon: Settings, label: 'nav.settings' },
]

export default function Sidebar() {
Expand Down
Loading
Loading