Production-ready code examples to kickstart your IoT projects. Copy, customize, and deploy.
Connect to KSP Cloud and fetch device data
from ksp_cloud import KSPClient
# Initialize the client with your API key
client = KSPClient(api_key="ksp_live_your_api_key_here")
# List all your devices
devices = client.devices.list()
print(f"You have {len(devices)} device(s)")
# Iterate through devices
for device in devices:
print(f"\nDevice: {device.name}")
print(f" ID: {device.id}")
print(f" Type: {device.type}")
print(f" Status: {device.status}")
# Get latest temperature reading
data = client.devices.get_data(device.id)
print(f" Temperature: {data.temperature}°C")
print(f" Humidity: {data.humidity}%")
print(f" Last Updated: {data.timestamp}")
# Check if temperature is in acceptable range
if data.temperature < 2 or data.temperature > 8:
print(f" ⚠️ WARNING: Temperature out of range!")
else:
print(f" ✓ Temperature is normal")Build a live temperature monitoring dashboard
import React from 'react';
import { useDevice, useDeviceSubscription } from '@ksp/cloud-sdk/react';
function TemperatureDashboard({ deviceId }) {
// Fetch initial device data
const { data: device, loading, error } = useDevice(deviceId);
// Subscribe to real-time updates
const liveData = useDeviceSubscription(deviceId);
// Use live data if available, otherwise fallback to initial data
const currentData = liveData || device;
if (loading) return <div>Loading device data...</div>;
if (error) return <div>Error: {error.message}</div>;
// Determine status color
const getStatusColor = (temp) => {
if (temp < 2 || temp > 8) return 'red';
if (temp < 4 || temp > 6) return 'yellow';
return 'green';
};
const statusColor = getStatusColor(currentData.temperature);
return (
<div className="dashboard-card">
<div className="device-header">
<h2>{currentData.name}</h2>
<span className={`status-badge ${statusColor}`}>
{currentData.status}
</span>
</div>
<div className="temperature-display">
<div className="temperature-value">
{currentData.temperature.toFixed(1)}°C
</div>
<div className="temperature-range">
Range: 2°C - 8°C
</div>
</div>
<div className="sensor-grid">
{currentData.sensors.map((sensor) => (
<div key={sensor.id} className="sensor-card">
<div className="sensor-location">{sensor.location}</div>
<div className="sensor-value">
{sensor.temperature.toFixed(1)}°C
</div>
</div>
))}
</div>
<div className="last-updated">
Last updated: {new Date(currentData.timestamp).toLocaleString()}
</div>
</div>
);
}
export default TemperatureDashboard;Log sensor data to KSP Cloud from ESP32/ESP8266
#include <KSPCloud.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "YourWiFiName";
const char* password = "YourWiFiPassword";
// KSP Cloud API key
const char* apiKey = "ksp_live_your_api_key_here";
// DHT sensor setup
#define DHTPIN 4 // GPIO4 (D2 on NodeMCU)
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
// KSP Cloud client
KSPCloud cloud(apiKey);
void setup() {
Serial.begin(115200);
delay(1000);
Serial.println("\nKSP Cloud Temperature Logger");
Serial.println("============================");
// Initialize DHT sensor
dht.begin();
// Connect to WiFi and KSP Cloud
Serial.println("Connecting to WiFi...");
cloud.begin(ssid, password);
if (cloud.isConnected()) {
Serial.println("✓ Connected to KSP Cloud");
// Register device (first time only)
cloud.registerDevice("my_temp_sensor", "DHT22 Logger");
} else {
Serial.println("✗ Failed to connect");
}
}
void loop() {
// Read sensor data
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
// Check if readings are valid
if (isnan(temperature) || isnan(humidity)) {
Serial.println("Failed to read from sensor");
delay(2000);
return;
}
// Display readings
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C | Humidity: ");
Serial.print(humidity);
Serial.println("%");
// Send to KSP Cloud
bool success = cloud.sendData({
{"temperature", temperature},
{"humidity", humidity},
{"sensor_type", "DHT22"}
});
if (success) {
Serial.println("✓ Data sent successfully");
} else {
Serial.println("✗ Failed to send data");
}
// Check for OTA firmware updates
cloud.checkUpdate();
// Wait 60 seconds before next reading
delay(60000);
}Get instant WhatsApp notifications for temperature changes
from ksp_cloud import KSPClient
# Initialize client
client = KSPClient(api_key="ksp_live_your_api_key_here")
# Configure alert for cold storage monitoring
alert = client.alerts.create(
device_id="deltax_001",
name="Cold Storage Temperature Alert",
enabled=True,
# Temperature thresholds
min_temperature=2.0, # Alert if below 2°C
max_temperature=8.0, # Alert if above 8°C
# Alert only if condition persists for 5 minutes
duration_seconds=300,
# Notification channels
notifications={
"whatsapp": {
"enabled": True,
"phone": "+919550421866",
"message_template": (
"🚨 *Temperature Alert*\n"
"Device: {device_name}\n"
"Current: {temperature}°C\n"
"Range: {min_temp}°C - {max_temp}°C\n"
"Time: {timestamp}"
)
},
"email": {
"enabled": True,
"address": "alerts@example.com",
"subject": "Temperature Alert - {device_name}"
},
"sms": {
"enabled": False
}
},
# Alert frequency (don't spam)
cooldown_minutes=30 # Wait 30 min before next alert
)
print(f"Alert created successfully!")
print(f"Alert ID: {alert.id}")
print(f"Status: {alert.status}")
# List all configured alerts
all_alerts = client.alerts.list()
print(f"\nYou have {len(all_alerts)} alert(s) configured")Explore our complete repository of examples, tutorials, and starter projects
Browse GitHub RepositoryGet started with our SDKs and comprehensive documentation