0
# Connection Management
1
2
Core connection functionality for establishing and managing MQTT connections to Arduino IoT Cloud with support for multiple authentication methods.
3
4
## Capabilities
5
6
### ArduinoIoTCloud Factory
7
8
The main factory object for creating cloud connections based on provided options.
9
10
```typescript { .api }
11
/**
12
* Factory object for creating Arduino IoT Cloud connections
13
*/
14
const ArduinoIoTCloud: IArduinoIoTCloudFactory;
15
16
interface IArduinoIoTCloudFactory {
17
connect(options: APIOptions & Partial<CloudOptions>): Promise<IMultiPropertiesCloudClient>;
18
connect(options: BrowserOptions & Partial<CloudOptions>): Promise<IMultiPropertiesCloudClient>;
19
connect(options: CredentialsOptions & Partial<CloudOptions>): Promise<ISinglePropertyCloudClient>;
20
}
21
```
22
23
**Usage Examples:**
24
25
```typescript
26
import { ArduinoIoTCloud } from "arduino-iot-js";
27
28
// API credentials (returns IMultiPropertiesCloudClient)
29
const apiClient = await ArduinoIoTCloud.connect({
30
clientId: "your-client-id",
31
clientSecret: "your-client-secret",
32
host: "iot.arduino.cc", // optional
33
onConnected: () => console.log("Connected!")
34
});
35
36
// Browser token (returns IMultiPropertiesCloudClient)
37
const tokenClient = await ArduinoIoTCloud.connect({
38
token: "your-jwt-token",
39
useCloudProtocolV2: true // optional
40
});
41
42
// Device credentials (returns ISinglePropertyCloudClient)
43
const deviceClient = await ArduinoIoTCloud.connect({
44
deviceId: "your-device-id",
45
secretKey: "your-secret-key",
46
port: 8884 // optional
47
});
48
```
49
50
### Base Client Interface
51
52
Common interface shared by all cloud client types.
53
54
```typescript { .api }
55
interface ICloudClient {
56
/** Reconnect to the MQTT broker */
57
reconnect(): Promise<void>;
58
/** Disconnect from the MQTT broker */
59
disconnect(): Promise<void>;
60
/** Send a raw message to a specific MQTT topic */
61
sendMessage(topic: string, message: string | ArrayBuffer): Promise<void>;
62
}
63
```
64
65
### Multi-Properties Client
66
67
Client interface for user credentials that can access multiple things and properties.
68
69
```typescript { .api }
70
interface IMultiPropertiesCloudClient extends ICloudClient {
71
/** Send a property value to a specific thing */
72
sendProperty<T extends CloudMessageValue>(
73
thingId: string,
74
name: string,
75
value: T,
76
tmp?: number
77
): Promise<void>;
78
79
/** Listen to property value changes from a specific thing */
80
onPropertyValue<T extends CloudMessageValue>(
81
thingId: string,
82
name: string,
83
cb: OnMessageCallback<T>
84
): void;
85
}
86
```
87
88
### Single Property Client
89
90
Client interface for device credentials that behaves as a single device.
91
92
```typescript { .api }
93
interface ISinglePropertyCloudClient extends ICloudClient {
94
/** Send a property value from this device */
95
sendProperty<T extends CloudMessageValue>(
96
name: string,
97
value: T,
98
tmp?: number
99
): Promise<void>;
100
101
/** Listen to property value changes for this device */
102
onPropertyValue<T extends CloudMessageValue>(
103
name: string,
104
cb: OnMessageCallback<T>
105
): void;
106
107
/** Get the thing ID associated with this device */
108
getThing(): Promise<string>;
109
}
110
```
111
112
### Token Client Interface
113
114
Additional interface for clients that use JWT token authentication.
115
116
```typescript { .api }
117
interface ITokenCloudClient {
118
/** Get the current JWT token */
119
getToken(): string;
120
/** Update the JWT token and reconnect */
121
updateToken(newToken: string): Promise<void>;
122
}
123
```
124
125
### Connection Options
126
127
Configuration options for cloud connections.
128
129
```typescript { .api }
130
interface CloudOptions {
131
/** MQTT broker host (default: 'iot.arduino.cc') */
132
host?: string;
133
/** MQTT broker port */
134
port?: string | number;
135
/** Use cloud protocol v2 (default: true) */
136
useCloudProtocolV2?: boolean;
137
/** Use SSL connection */
138
ssl?: boolean;
139
/** Callback when connection goes offline */
140
onOffline?: () => void;
141
/** Callback when connection is established */
142
onConnected?: () => void;
143
/** Callback when connection is lost */
144
onDisconnect?: (message?: any) => void;
145
}
146
147
namespace CloudOptions {
148
/** Default connection options */
149
export const DEFAULT: CloudOptions;
150
}
151
```
152
153
### Authentication Options
154
155
Different authentication option types for various connection modes.
156
157
```typescript { .api }
158
/** API credentials for user access */
159
interface APIOptions {
160
/** API endpoint URL (optional) */
161
apiUrl?: string;
162
/** OAuth client ID */
163
clientId: string;
164
/** JWT audience (optional) */
165
audience?: string;
166
/** OAuth client secret */
167
clientSecret: string;
168
}
169
170
/** Browser JWT token authentication */
171
interface BrowserOptions {
172
/** JWT token for authentication */
173
token: string;
174
}
175
176
/** Device credentials for single device behavior */
177
interface CredentialsOptions {
178
/** Device identifier */
179
deviceId: string;
180
/** Device secret key */
181
secretKey: string;
182
}
183
```
184
185
186
## Connection Examples
187
188
### Error Handling
189
190
```typescript
191
import { ArduinoIoTCloud } from "arduino-iot-js";
192
193
try {
194
const client = await ArduinoIoTCloud.connect({
195
clientId: "invalid-id",
196
clientSecret: "invalid-secret",
197
onDisconnect: (error) => {
198
console.error("Connection lost:", error);
199
// Implement reconnection logic
200
}
201
});
202
} catch (error) {
203
console.error("Connection failed:", error.message);
204
}
205
```
206
207
### Reconnection
208
209
```typescript
210
import { ArduinoIoTCloud } from "arduino-iot-js";
211
212
const client = await ArduinoIoTCloud.connect({
213
deviceId: "your-device-id",
214
secretKey: "your-secret-key",
215
onDisconnect: async (message) => {
216
console.log("Disconnected, attempting to reconnect...");
217
try {
218
await client.reconnect();
219
console.log("Reconnected successfully");
220
} catch (error) {
221
console.error("Reconnection failed:", error);
222
}
223
}
224
});
225
```
226
227
### Graceful Disconnection
228
229
```typescript
230
import { ArduinoIoTCloud } from "arduino-iot-js";
231
232
const client = await ArduinoIoTCloud.connect({
233
token: "your-jwt-token"
234
});
235
236
// Use the client...
237
238
// Clean disconnection
239
process.on('SIGINT', async () => {
240
console.log('Shutting down...');
241
await client.disconnect();
242
process.exit(0);
243
});
244
```