A TypeScript client library for the gpiozero-proxy server.
- Full TypeScript Support: Typed interfaces for gpiozero Device interfaces and JSON-RPC protocol.
- Auto-Reconnect: Automatically attempts to reconnect if the connection is lost.
- Event Handling: Easy subscription to device events (e.g.,
whenPressed). - Framework Agnostic: Works in Browser, Node.js, Vue, React, etc.
You can install the library directly from GitHub using npm:
npm install github:wearelucid/gpiozero-client-tsThis example assumes you have configured the server with an led with the id led1and a button with the id btn1.
import { GPIOZeroClient, LED, Button } from "gpiozero-client-ts";
async function main() {
// Connect with auto-reconnect enabled (default)
const client = new GPIOZeroClient("ws://localhost:8765", {
reconnect: true,
reconnectInterval: 2000, // Retry every 2 seconds
onConnect: () => console.log("Connected!"),
onDisconnect: () => console.log("Disconnected!"),
});
await client.connect();
const led = new LED(client, "led1");
const button = new Button(client, "btn1");
// Control LED
await led.on();
await new Promise((r) => setTimeout(r, 1000));
await led.off();
// Handle Button Events (subscriptions persist across reconnections)
await button.whenPressed(() => {
console.log("Button pressed!");
led.toggle();
});
await button.whenReleased(() => {
console.log("Button released!");
});
}
main().catch(console.error);The following device component interfaces from the gpiozero library have been implemented for this client. Technically, all available device component interfaces should be implementable directly using the Device interface.
ButtonLEDPWMLEDRGBLEDMotorServo
interface ClientOptions {
onSend?: (data: string) => void; // Callback for outgoing messages
onReceive?: (data: string) => void; // Callback for incoming messages
onConnect?: () => void; // Called when connection is established
onDisconnect?: () => void; // Called when connection is lost
reconnect?: boolean; // Enable auto-reconnect (default: true)
reconnectInterval?: number; // ms between retries (default: 2000)
maxReconnectAttempts?: number; // Max retries (default: Infinity)
}