Overview
The Growatt SDK supports initialization from environment variables using the from_env() method. This is convenient for production deployments, containerized applications, and keeping credentials out of source code.
Supported Environment Variables
The SDK recognizes the following environment variables:
Your Growatt account username
Your Growatt account password
Alternative base URL for the Growatt API. Defaults to https://server.growatt.com if not set.
Session duration in minutes. Defaults to 30 minutes if not set.
from_env() Method
Signature
pub fn from_env() -> Self
Creates a new Growatt client with configuration loaded from environment variables.
Returns
Returns a configured Growatt client instance with settings from environment variables
Behavior
- Automatically loads
.env file if present in the project directory
- Falls back to system environment variables if
.env doesn’t exist
- Sets username and password if
GROWATT_USERNAME and GROWATT_PASSWORD are available
- Uses default values for optional variables if not set
- Does not perform authentication automatically (call
login() separately)
Using .env Files
Create a .env file in your project root:
# .env
GROWATT_USERNAME=your_username
GROWATT_PASSWORD=your_password
GROWATT_BASE_URL=https://server.growatt.com
GROWATT_SESSION_DURATION=30
Never commit .env files containing credentials to version control. Add .env to your .gitignore file.
Example with .env File
use growatt::Growatt;
use dotenv::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load from .env file
dotenv().ok();
// Create client with environment configuration
let mut client = Growatt::from_env();
// Credentials are stored but not authenticated yet
// Call login without parameters (uses stored credentials)
if let (Some(username), Some(password)) = (
std::env::var("GROWATT_USERNAME").ok(),
std::env::var("GROWATT_PASSWORD").ok(),
) {
client.login(&username, &password).await?;
// Your API calls here
let plants = client.get_plants().await?;
println!("Plants: {:?}", plants);
}
Ok(())
}
Using System Environment Variables
Set environment variables in your shell or deployment platform:
# Linux/macOS
export GROWATT_USERNAME="your_username"
export GROWATT_PASSWORD="your_password"
export GROWATT_SESSION_DURATION="45"
# Windows (PowerShell)
$env:GROWATT_USERNAME="your_username"
$env:GROWATT_PASSWORD="your_password"
$env:GROWATT_SESSION_DURATION="45"
Example with System Environment
use growatt::Growatt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load from system environment
let mut client = Growatt::from_env();
// Authenticate using stored credentials
if let (Ok(username), Ok(password)) = (
std::env::var("GROWATT_USERNAME"),
std::env::var("GROWATT_PASSWORD"),
) {
client.login(&username, &password).await?;
println!("Logged in successfully");
} else {
eprintln!("GROWATT_USERNAME and GROWATT_PASSWORD must be set");
}
Ok(())
}
Docker Integration
Pass environment variables to Docker containers:
# Dockerfile
FROM rust:latest
WORKDIR /app
COPY . .
RUN cargo build --release
CMD ["./target/release/your-app"]
# Run with environment variables
docker run -e GROWATT_USERNAME="your_username" \
-e GROWATT_PASSWORD="your_password" \
-e GROWATT_SESSION_DURATION="45" \
your-image
# Or use .env file
docker run --env-file .env your-image
Kubernetes ConfigMaps and Secrets
# secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: growatt-credentials
type: Opaque
stringData:
GROWATT_USERNAME: your_username
GROWATT_PASSWORD: your_password
---
# configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
name: growatt-config
data:
GROWATT_SESSION_DURATION: "45"
GROWATT_BASE_URL: "https://server.growatt.com"
---
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: growatt-app
spec:
template:
spec:
containers:
- name: app
image: your-image
envFrom:
- secretRef:
name: growatt-credentials
- configMapRef:
name: growatt-config
Configuration Priority
When using from_env(), settings are applied in this order:
- Default values (e.g., 30 minutes for session duration)
.env file values (if dotenv is used)
- System environment variables (override
.env)
// Example showing configuration priority
use growatt::Growatt;
use dotenv::dotenv;
#[tokio::main]
async fn main() {
// Load .env file
dotenv().ok();
// Create client - system env vars take precedence over .env
let client = Growatt::from_env();
// If both .env and system have GROWATT_USERNAME,
// the system environment variable wins
}
Validation and Error Handling
use growatt::Growatt;
use std::env;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Validate required environment variables
let username = env::var("GROWATT_USERNAME")
.expect("GROWATT_USERNAME must be set");
let password = env::var("GROWATT_PASSWORD")
.expect("GROWATT_PASSWORD must be set");
// Create client
let mut client = Growatt::from_env();
// Login with validated credentials
match client.login(&username, &password).await {
Ok(true) => println!("Successfully authenticated"),
Ok(false) => eprintln!("Login returned false"),
Err(e) => eprintln!("Login failed: {}", e),
}
Ok(())
}
Complete Example
use growatt::Growatt;
use dotenv::dotenv;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load .env file and environment
dotenv().ok();
// Create client with environment configuration
let mut client = Growatt::from_env();
// Get credentials from environment
let username = std::env::var("GROWATT_USERNAME")
.expect("GROWATT_USERNAME environment variable not set");
let password = std::env::var("GROWATT_PASSWORD")
.expect("GROWATT_PASSWORD environment variable not set");
// Login
if client.login(&username, &password).await? {
println!("Login successful!");
// Get plants
let plants = client.get_plants().await?;
for plant in plants.0 {
println!("Plant: {} (ID: {})", plant.plant_name, plant.plant_id);
}
// Logout
client.logout().await?;
}
Ok(())
}
Best Practices
Security: Use environment variables for credentials in production. Never hardcode credentials in source code.
Version Control: Add .env to .gitignore to prevent accidentally committing credentials.
Validation: Always validate that required environment variables are set before using the client to provide clear error messages.
# .gitignore
.env
.env.local
.env.*.local
Source Reference
from_env() implementation: src/lib.rs:111
- Environment variable loading: src/lib.rs:113-138
- Username/password storage: src/lib.rs:118-124
- Base URL configuration: src/lib.rs:127-129
- Session duration configuration: src/lib.rs:132-136