Methods & Events
Client methods, events, and TypeScript types
Methods & Events
Complete reference for CloudSignalClient methods and events.
Connection Methods
connect()
Establish connection to the MQTT broker.
await client.connect(): Promise<void>
Throws an error if connection fails after timeout.
disconnect()
Gracefully disconnect from the broker.
await client.disconnect(): Promise<void>
isConnected()
Check connection status.
client.isConnected(): boolean
Publish/Subscribe Methods
publish()
Publish a message to a topic.
client.publish(
topic: string,
payload: string | object,
options?: PublishOptions
): void
interface PublishOptions {
qos?: 0 | 1 | 2;
retain?: boolean;
}
Examples:
// Simple publish
client.publish('sensors/temperature', { value: 22.5 });
// With options
client.publish('alerts/critical', { message: 'Server down' }, {
qos: 2,
retain: true
});
// String payload
client.publish('logs/app', 'Application started');
subscribe()
Subscribe to a topic with a message handler.
client.subscribe(
topic: string,
handler: MessageHandler,
options?: SubscribeOptions
): void
type MessageHandler = (
payload: any,
topic: string,
packet: MqttPacket
) => void;
interface SubscribeOptions {
qos?: 0 | 1 | 2;
}
Examples:
// Basic subscription
client.subscribe('chat/messages', (message, topic) => {
console.log(`${topic}: ${message.text}`);
});
// With QoS
client.subscribe('orders/new', handleOrder, { qos: 2 });
// Wildcard subscription
client.subscribe('sensors/+/temperature', (data, topic) => {
const sensorId = topic.split('/')[1];
console.log(`Sensor ${sensorId}: ${data.value}°C`);
});
unsubscribe()
Unsubscribe from a topic.
client.unsubscribe(topic: string): void
Request/Response Pattern
For AI agent and RPC-style communication.
request()
Send a request and wait for a response.
const response = await client.request(
topic: string,
payload: object,
options?: RequestOptions
): Promise<any>
interface RequestOptions {
timeout?: number; // ms, default: 30000
responseTopic?: string;
}
Example:
// Send request to AI agent
const response = await client.request('ai/assistant', {
prompt: 'Summarize this document',
documentId: 'doc-123'
}, { timeout: 60000 });
console.log(response.summary);
onRequest()
Handle incoming requests.
client.onRequest(
topic: string,
handler: RequestHandler
): void
type RequestHandler = (
request: any,
respond: (response: any) => void
) => void | Promise<void>;
Example:
// Handle AI requests
client.onRequest('ai/assistant', async (request, respond) => {
const result = await processAIRequest(request);
respond({ summary: result });
});
Events
on()
Subscribe to client events.
client.on(event: string, handler: Function): void
Available Events
Connection Events:
client.on('connected', () => {
console.log('Connected to broker');
});
client.on('disconnected', (reason?: string) => {
console.log('Disconnected:', reason);
});
client.on('reconnecting', (attempt: number) => {
console.log(`Reconnecting... attempt ${attempt}`);
});
client.on('error', (error: Error) => {
console.error('Client error:', error);
});
Authentication Events:
client.on('token:refreshed', () => {
console.log('Token refreshed');
});
client.on('token:error', (error: Error) => {
console.error('Token error:', error);
});
client.on('auth:error', (error: AuthError) => {
console.error('Auth failed:', error.code);
});
Message Events:
client.on('message', (topic: string, payload: any) => {
// Called for all messages
});
client.on('offline:queued', (count: number) => {
console.log(`${count} messages queued offline`);
});
client.on('offline:sent', (count: number) => {
console.log(`${count} offline messages sent`);
});
off()
Remove an event handler.
client.off(event: string, handler: Function): void
once()
Subscribe to an event once.
client.once(event: string, handler: Function): void
Utility Methods
getClientId()
Get the MQTT client ID.
client.getClientId(): string
getConnectionState()
Get detailed connection state.
client.getConnectionState(): ConnectionState
interface ConnectionState {
connected: boolean;
reconnecting: boolean;
reconnectAttempts: number;
lastConnectedAt?: Date;
lastDisconnectedAt?: Date;
}
getQueuedMessages()
Get count of offline queued messages.
client.getQueuedMessages(): number