Skip to main content

SolarCost bridge para capturar Totales de Solar Assistant y publicarlos por HTTP.

Project description

SolarCost Bridge

Bridge en Python para:

  • autenticarse contra SolarAssistant,
  • conectarse al websocket de Phoenix LiveView de la solapa Totales,
  • mantener un estado actualizado y persistido,
  • publicar ese estado por HTTP para que otra aplicacion lo consulte.

Estructura

  • src/sa_totals_bridge: codigo fuente
  • requirements.txt: dependencias
  • data/: base SQLite local generada en ejecucion

Instalacion

sudo apt update
sudo apt install -y python3-full python3-venv
mkdir -p /opt/solarcost/bridge
cd /opt/solarcost/bridge
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install solarcost-bridge
sudo "$(command -v sa_bridge)" init

El comando recomendado es sa_bridge. Los comandos anteriores sa-bridge y sa-totals-bridge siguen funcionando por compatibilidad.

Si prefieres mantener el comando anterior, tambien funciona:

sudo "$(command -v sa-totals-bridge)" init

Si Solar Assistant corre en la misma maquina que el bridge, el asistente propone por defecto http://127.0.0.1.

Desinstalacion

pip uninstall solo elimina el paquete instalado dentro del entorno virtual. No borra automaticamente:

  • el archivo solarcost-bridge.env,
  • la base SQLite,
  • el directorio de trabajo,
  • los unit files de systemd,
  • ni los servicios habilitados.

Eso es intencional para no perder configuracion o datos sin querer.

Si quieres una desinstalacion conservando configuracion:

source .venv/bin/activate
pip uninstall solarcost-bridge

O con el asistente interactivo:

sa_bridge uninstall

Si quieres tocar un servicio system, usa:

sudo "$(command -v sa_bridge)" uninstall

Si instalaste desde el repo, tambien puedes usar:

./uninstall.sh

Si quieres una desinstalacion limpia completa:

sudo systemctl stop solarcost-bridge.service
sudo systemctl disable solarcost-bridge.service
sudo rm -f /etc/systemd/system/solarcost-bridge.service
sudo systemctl daemon-reload

rm -f /ruta/a/solarcost-bridge.env
rm -f /ruta/a/data/solar_assistant_totals.sqlite3
rm -rf /ruta/al/directorio/de/trabajo

Despliegue rapido en Raspberry Pi

  1. Clona el repo en la Pi.
  2. Entra a la carpeta del proyecto.
  3. Ejecuta ./init.sh.
  4. Responde el asistente interactivo.
  5. Si elegiste system o user, el script deja generado el service y puede habilitarlo automaticamente.

Ejemplo:

git clone https://github.com/gteijeiro/solarcost-bridge.git
cd solarcost-bridge
./init.sh

Para ver logs del servicio:

sudo journalctl -u solarcost-bridge.service -f

Ejecucion

export SA_BASE_URL="http://SOLAR_ASSISTANT_HOST_O_IP"
export SA_PASSWORD="TU_PASSWORD_DE_SOLAR_ASSISTANT"
sa_bridge

Tambien puedes usar el subcomando explicito:

sa_bridge run

La API queda por defecto en:

  • http://127.0.0.1:8765
  • http://<tu-ip-local>:8765

Como funciona la actualizacion

  • El bridge abre una sesion autenticada contra Solar Assistant.
  • Luego abre un websocket de Phoenix LiveView hacia la solapa Totales.
  • La API HTTP del bridge no abre un websocket por cada request.
  • Cada request a la API solo devuelve el ultimo snapshot guardado en memoria y SQLite.
  • SA_HEARTBEAT_INTERVAL mantiene viva la conexion websocket.
  • SA_REFRESH_INTERVAL fuerza una resincronizacion periodica del periodo actual porque la vista Totales no siempre emite cambios nuevos por si sola.

En otras palabras:

  • heartbeat no trae datos nuevos, solo evita que la conexion muera.
  • refresh vuelve a abrir la sesion del collector y refresca los valores actuales.

Por defecto el bridge:

  • manda heartbeat cada 30 segundos,
  • fuerza resincronizacion cada 10 segundos,
  • hace backfill historico una vez al arrancar el collector,
  • despues mantiene el historial ya guardado y solo refresca el periodo actual.

Si quieres menos carga en la Pi o en Solar Assistant:

export SA_DAILY_HISTORY_PERIODS="6"
export SA_MONTHLY_HISTORY_PERIODS="3"
export SA_REFRESH_INTERVAL="20"

Si quieres desactivar la resincronizacion forzada y dejar solo el websocket:

export SA_REFRESH_INTERVAL="0"

Endpoints

  • GET /health
  • GET /state
  • GET /totals/daily
  • GET /totals/daily/points
  • GET /totals/monthly
  • GET /totals/monthly/points
  • GET /openapi.json
  • GET /docs

Los endpoints de points devuelven una sola lista concatenada de todos los periodos cargados. Si necesitas un periodo puntual, puedes usar ?period_key=....

Variables disponibles

  • SA_BASE_URL
  • SA_PASSWORD
  • SA_BIND_HOST
  • SA_BIND_PORT
  • SA_DB_PATH
  • SA_LOG_LEVEL
  • SA_RECONNECT_DELAY
  • SA_HEARTBEAT_INTERVAL
  • SA_REFRESH_INTERVAL
  • SA_CONNECT_TIMEOUT
  • SA_DAILY_HISTORY_PERIODS
  • SA_MONTHLY_HISTORY_PERIODS

Diagnostico rapido

Para saber si el bridge esta trayendo datos recientes, revisa:

  • GET /health
  • GET /state

Campos utiles:

  • service.connected
  • service.last_login_at
  • service.last_join_at
  • service.last_message_at
  • service.last_error
  • daily.updated_at
  • monthly.updated_at

Si connected=true pero last_message_at o daily.updated_at quedan viejos durante mucho tiempo, normalmente significa que Solar Assistant no esta empujando diffs nuevos y dependes del SA_REFRESH_INTERVAL.

Recomendacion de seguridad

  • No guardes SA_PASSWORD en archivos versionados.
  • No subas la base data/solar_assistant_totals.sqlite3 a GitHub.
  • Si usas .env, mantenlo fuera del repositorio.

Notas

  • El collector hace una busqueda hacia atras con prev-daily y prev-monthly, y luego vuelve al periodo actual con next-daily y next-monthly.
  • Por defecto intenta traer 12 periodos diarios anteriores y 5 periodos mensuales anteriores.
  • Swagger UI esta en /docs y carga assets desde CDN.

Build y publicacion

Build local:

python -m pip install --upgrade build
python -m build

El repo incluye workflows de GitHub Actions para:

  • CI en push y pull_request,
  • publicacion manual a TestPyPI con workflow_dispatch,
  • publicacion a PyPI al crear un tag v*.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

solarcost_bridge-0.1.1.tar.gz (26.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

solarcost_bridge-0.1.1-py3-none-any.whl (27.2 kB view details)

Uploaded Python 3

File details

Details for the file solarcost_bridge-0.1.1.tar.gz.

File metadata

  • Download URL: solarcost_bridge-0.1.1.tar.gz
  • Upload date:
  • Size: 26.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for solarcost_bridge-0.1.1.tar.gz
Algorithm Hash digest
SHA256 c3d92bf97f8420c112b9f30c479416018468a74c9b60e615971ba6e1f7a9439f
MD5 19a72664a814f1f7809c481de8dd40bc
BLAKE2b-256 aece0723a9382ab862cb942c1ee3168e1012e3a32e9cdd0623ca8e94077b1453

See more details on using hashes here.

Provenance

The following attestation bundles were made for solarcost_bridge-0.1.1.tar.gz:

Publisher: publish.yml on gteijeiro/solarcost-bridge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file solarcost_bridge-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for solarcost_bridge-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d527868ac37f1b0d7a1f40b6e0990fe34c80e5b9d86212d398edfea39405402a
MD5 89623c451fe49bc7ac717f5eb4bc751b
BLAKE2b-256 9a6dd7ccc2ac0fb0477ed917289196c319bc80c24fa507e631012f79b3fce49c

See more details on using hashes here.

Provenance

The following attestation bundles were made for solarcost_bridge-0.1.1-py3-none-any.whl:

Publisher: publish.yml on gteijeiro/solarcost-bridge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page