0
# Automation & Triggers
1
2
Event-driven automation with triggers, actions, and conditional logic for IoT workflows. The TriggersV1Api enables creating sophisticated automation rules that respond to property changes, thresholds, and time-based conditions.
3
4
## Capabilities
5
6
### Trigger Management
7
8
Create and manage automation triggers that monitor IoT properties and execute actions based on conditions.
9
10
```javascript { .api }
11
class TriggersV1Api {
12
/**
13
* Create a new automation trigger
14
* @param trigger - Trigger configuration with conditions and linked actions
15
* @param opts - Optional parameters including organization ID
16
* @returns Promise<ArduinoTrigger> - Created trigger object
17
*/
18
triggersV1Create(trigger: Trigger, opts?: any): Promise<ArduinoTrigger>;
19
20
/**
21
* List all triggers accessible to the authenticated user
22
* @param opts - Optional parameters including organization ID and pagination
23
* @returns Promise<ArduinoTrigger[]> - Array of trigger objects
24
*/
25
triggersV1List(opts?: any): Promise<ArduinoTrigger[]>;
26
27
/**
28
* Get detailed information about a specific trigger
29
* @param id - Trigger ID
30
* @param opts - Optional parameters including organization ID
31
* @returns Promise<ArduinoTriggerWithLinkedEntities> - Trigger with linked entities
32
*/
33
triggersV1Show(id: string, opts?: any): Promise<ArduinoTriggerWithLinkedEntities>;
34
35
/**
36
* Update trigger configuration and conditions
37
* @param id - Trigger ID
38
* @param trigger - Updated trigger configuration
39
* @param opts - Optional parameters including organization ID
40
* @returns Promise<ArduinoTrigger> - Updated trigger object
41
*/
42
triggersV1Update(id: string, trigger: Trigger, opts?: any): Promise<ArduinoTrigger>;
43
44
/**
45
* Partial update of trigger properties
46
* @param id - Trigger ID
47
* @param trigger - Partial trigger configuration updates
48
* @param opts - Optional parameters including organization ID
49
* @returns Promise<ArduinoTrigger> - Updated trigger object
50
*/
51
triggersV1Patch(id: string, trigger: Trigger, opts?: any): Promise<ArduinoTrigger>;
52
53
/**
54
* Delete a trigger permanently
55
* @param id - Trigger ID
56
* @param opts - Optional parameters including organization ID
57
* @returns Promise<void>
58
*/
59
triggersV1Delete(id: string, opts?: any): Promise<void>;
60
61
/**
62
* Get trigger as a template for replication
63
* @param id - Trigger ID
64
* @param opts - Optional parameters including organization ID
65
* @returns Promise<ArduinoTriggerTemplate> - Trigger template
66
*/
67
triggersV1Template(id: string, opts?: any): Promise<ArduinoTriggerTemplate>;
68
}
69
```
70
71
### Action Management
72
73
Create and manage actions that are executed when triggers are activated.
74
75
```javascript { .api }
76
class TriggersV1Api {
77
/**
78
* Create a new automation action
79
* @param createAction - Action configuration including type and parameters
80
* @param opts - Optional parameters including organization ID
81
* @returns Promise<ArduinoAction> - Created action object
82
*/
83
actionsV1Create(createAction: CreateAction, opts?: any): Promise<ArduinoAction>;
84
85
/**
86
* List all actions accessible to the authenticated user
87
* @param opts - Optional parameters including organization ID and pagination
88
* @returns Promise<ArduinoAction[]> - Array of action objects
89
*/
90
actionsV1List(opts?: any): Promise<ArduinoAction[]>;
91
92
/**
93
* Get detailed information about a specific action
94
* @param id - Action ID
95
* @param opts - Optional parameters including organization ID
96
* @returns Promise<ArduinoAction> - Action object with full details
97
*/
98
actionsV1Show(id: string, opts?: any): Promise<ArduinoAction>;
99
100
/**
101
* Update action configuration and parameters
102
* @param id - Action ID
103
* @param updateAction - Updated action configuration
104
* @param opts - Optional parameters including organization ID
105
* @returns Promise<ArduinoAction> - Updated action object
106
*/
107
actionsV1Update(id: string, updateAction: UpdateAction, opts?: any): Promise<ArduinoAction>;
108
109
/**
110
* Delete an action permanently
111
* @param id - Action ID
112
* @param opts - Optional parameters including organization ID
113
* @returns Promise<void>
114
*/
115
actionsV1Delete(id: string, opts?: any): Promise<void>;
116
}
117
```
118
119
## Data Models
120
121
```javascript { .api }
122
interface ArduinoTrigger {
123
active?: boolean;
124
createdAt?: Date;
125
description?: string;
126
deviceStatusSource?: DeviceStatusSource;
127
href?: string;
128
id?: string;
129
name?: string;
130
organizationId?: string;
131
property?: ArduinoProperty;
132
updatedAt?: Date;
133
userId?: string;
134
}
135
136
interface Trigger {
137
active?: boolean;
138
actions?: ArduinoAction[];
139
description?: string;
140
deviceStatusSource?: DeviceStatusSource;
141
name: string;
142
property?: ArduinoLinkedProperty;
143
}
144
145
interface ArduinoAction {
146
createdAt?: Date;
147
description?: string;
148
emailAction?: EmailAction;
149
href?: string;
150
id?: string;
151
kind?: ActionKind;
152
name?: string;
153
organizationId?: string;
154
pushAction?: PushAction;
155
updatedAt?: Date;
156
userId?: string;
157
}
158
159
interface CreateAction {
160
description?: string;
161
emailAction?: EmailAction;
162
kind: ActionKind;
163
name: string;
164
pushAction?: PushAction;
165
}
166
167
interface UpdateAction {
168
description?: string;
169
emailAction?: EmailAction;
170
name?: string;
171
pushAction?: PushAction;
172
}
173
174
interface EmailAction {
175
body?: BodyExpression;
176
deliveryOpts?: EmailDeliveryOpts;
177
recipients?: UserRecipient[];
178
subject?: TitleExpression;
179
}
180
181
interface PushAction {
182
body?: BodyExpression;
183
deliveryOpts?: PushDeliveryOpts;
184
recipients?: UserRecipient[];
185
title?: TitleExpression;
186
}
187
188
interface DeviceStatusSource {
189
connectionType?: string;
190
deviceId?: string;
191
}
192
193
interface ArduinoTriggerWithLinkedEntities {
194
active?: boolean;
195
createdAt?: Date;
196
description?: string;
197
deviceStatusSource?: DeviceStatusSource;
198
href?: string;
199
id?: string;
200
linkedDevices?: ArduinoLinkedDevice[];
201
linkedProperties?: ArduinoLinkedProperty[];
202
name?: string;
203
organizationId?: string;
204
property?: ArduinoProperty;
205
updatedAt?: Date;
206
userId?: string;
207
}
208
209
interface ArduinoTriggerTemplate {
210
actions?: ArduinoActionTemplate[];
211
active?: boolean;
212
description?: string;
213
deviceStatusSource?: DeviceStatusSource;
214
name?: string;
215
property?: ArduinoLinkedPropertyTemplate;
216
}
217
218
interface ArduinoActionTemplate {
219
description?: string;
220
emailAction?: EmailAction;
221
kind?: ActionKind;
222
name?: string;
223
pushAction?: PushAction;
224
}
225
226
interface ArduinoLinkedPropertyTemplate {
227
name?: string;
228
permission?: PropertyPermission;
229
type?: PropertyType;
230
variableName?: string;
231
}
232
233
interface ArduinoLinkedProperty {
234
id?: string;
235
name?: string;
236
thingId?: string;
237
type?: string;
238
variableName?: string;
239
}
240
241
interface BodyExpression {
242
template?: string;
243
}
244
245
interface TitleExpression {
246
template?: string;
247
}
248
249
interface EmailDeliveryOpts {
250
frequency?: string;
251
rateLimit?: number;
252
}
253
254
interface PushDeliveryOpts {
255
frequency?: string;
256
}
257
258
interface UserRecipient {
259
email?: string;
260
userId?: string;
261
}
262
263
enum ActionKind {
264
EMAIL = 'EMAIL',
265
PUSH_NOTIFICATION = 'PUSH_NOTIFICATION'
266
}
267
```
268
269
**Comprehensive Automation Examples:**
270
271
```javascript
272
import ArduinoIotClient from '@arduino/arduino-iot-client';
273
274
const triggersApi = new ArduinoIotClient.TriggersV1Api();
275
276
// Create email notification system
277
async function createTemperatureAlert(thingId, temperaturePropertyId) {
278
try {
279
// Create email action for high temperature alert
280
const highTempAction = await triggersApi.actionsV1Create({
281
name: "High Temperature Alert",
282
kind: "EMAIL",
283
description: "Send email when temperature exceeds safe limits",
284
emailAction: {
285
subject: {
286
template: "🌡️ High Temperature Alert - {{property.name}}"
287
},
288
body: {
289
template: `
290
<h2>Temperature Alert</h2>
291
<p><strong>Thing:</strong> {{thing.name}}</p>
292
<p><strong>Current Temperature:</strong> {{property.last_value}}°C</p>
293
<p><strong>Threshold:</strong> 35°C</p>
294
<p><strong>Time:</strong> {{property.updated_at}}</p>
295
<p>Please check the environmental conditions immediately.</p>
296
`
297
},
298
recipients: [
299
{ email: "admin@example.com", userId: "admin-user-id" },
300
{ email: "maintenance@example.com", userId: "maintenance-user-id" }
301
],
302
deliveryOpts: {
303
frequency: "RATE_LIMIT",
304
rateLimit: 300 // Max one email per 5 minutes
305
}
306
}
307
});
308
309
// Create trigger for high temperature
310
const highTempTrigger = await triggersApi.triggersV1Create({
311
name: "High Temperature Trigger",
312
description: "Activate when temperature exceeds 35°C",
313
active: true,
314
property: {
315
id: temperaturePropertyId,
316
thingId: thingId,
317
name: "Temperature",
318
type: "TEMPERATURE",
319
variableName: "temperature"
320
},
321
actions: [highTempAction]
322
});
323
324
console.log(`Created high temperature trigger: ${highTempTrigger.id}`);
325
return { trigger: highTempTrigger, action: highTempAction };
326
327
} catch (error) {
328
console.error('Failed to create temperature alert:', error);
329
throw error;
330
}
331
}
332
333
// Create device connectivity monitoring
334
async function createConnectivityMonitoring(deviceId) {
335
try {
336
// Create push notification action for device offline
337
const offlineAction = await triggersApi.actionsV1Create({
338
name: "Device Offline Alert",
339
kind: "PUSH_NOTIFICATION",
340
description: "Send push notification when device goes offline",
341
pushAction: {
342
title: {
343
template: "📱 Device Offline - {{device.name}}"
344
},
345
body: {
346
template: "Device {{device.name}} has been offline for more than 5 minutes. Last seen: {{device.last_activity_at}}"
347
},
348
recipients: [
349
{ userId: "admin-user-id" },
350
{ userId: "technician-user-id" }
351
],
352
deliveryOpts: {
353
frequency: "IMMEDIATE"
354
}
355
}
356
});
357
358
// Create trigger for device offline status
359
const offlineTrigger = await triggersApi.triggersV1Create({
360
name: "Device Connectivity Monitor",
361
description: "Monitor device connectivity status",
362
active: true,
363
deviceStatusSource: {
364
deviceId: deviceId,
365
connectionType: "wifi"
366
},
367
actions: [offlineAction]
368
});
369
370
console.log(`Created connectivity monitoring trigger: ${offlineTrigger.id}`);
371
return { trigger: offlineTrigger, action: offlineAction };
372
373
} catch (error) {
374
console.error('Failed to create connectivity monitoring:', error);
375
throw error;
376
}
377
}
378
379
// Create multi-condition automation system
380
async function createEnvironmentalControlSystem(thingId, properties) {
381
try {
382
const [tempProp, humidityProp, fanProp, ledProp] = properties;
383
384
// 1. High temperature response
385
const fanControlAction = await triggersApi.actionsV1Create({
386
name: "Activate Cooling System",
387
kind: "EMAIL",
388
description: "Notify when cooling system is activated",
389
emailAction: {
390
subject: {
391
template: "🌬️ Cooling System Activated"
392
},
393
body: {
394
template: `
395
<h3>Environmental Control Alert</h3>
396
<p>Cooling system has been automatically activated.</p>
397
<p><strong>Temperature:</strong> {{property.last_value}}°C</p>
398
<p><strong>Action:</strong> Fan activated at maximum speed</p>
399
<p><strong>Location:</strong> {{thing.name}}</p>
400
`
401
},
402
recipients: [{ email: "facility@example.com", userId: "facility-user-id" }]
403
}
404
});
405
406
const highTempTrigger = await triggersApi.triggersV1Create({
407
name: "High Temperature Control",
408
description: "Activate cooling when temperature > 28°C",
409
active: true,
410
property: {
411
id: tempProp.id,
412
thingId: thingId,
413
name: tempProp.name,
414
type: tempProp.type
415
},
416
actions: [fanControlAction]
417
});
418
419
// 2. Low temperature response
420
const heatingAction = await triggersApi.actionsV1Create({
421
name: "Heating System Alert",
422
kind: "PUSH_NOTIFICATION",
423
description: "Alert when heating might be needed",
424
pushAction: {
425
title: {
426
template: "🔥 Low Temperature Detected"
427
},
428
body: {
429
template: "Temperature dropped to {{property.last_value}}°C. Consider activating heating system."
430
},
431
recipients: [{ userId: "maintenance-user-id" }]
432
}
433
});
434
435
const lowTempTrigger = await triggersApi.triggersV1Create({
436
name: "Low Temperature Alert",
437
description: "Alert when temperature < 18°C",
438
active: true,
439
property: {
440
id: tempProp.id,
441
thingId: thingId,
442
name: tempProp.name,
443
type: tempProp.type
444
},
445
actions: [heatingAction]
446
});
447
448
// 3. High humidity response
449
const dehumidifyAction = await triggersApi.actionsV1Create({
450
name: "High Humidity Alert",
451
kind: "EMAIL",
452
description: "Alert when humidity is too high",
453
emailAction: {
454
subject: {
455
template: "💧 High Humidity Alert - {{thing.name}}"
456
},
457
body: {
458
template: `
459
<h3>Humidity Control Alert</h3>
460
<p><strong>Current Humidity:</strong> {{property.last_value}}%</p>
461
<p><strong>Threshold:</strong> 70%</p>
462
<p><strong>Recommendation:</strong> Activate dehumidification system</p>
463
<p><strong>Risk:</strong> High humidity can lead to condensation and equipment damage</p>
464
`
465
},
466
recipients: [
467
{ email: "facility@example.com", userId: "facility-user-id" },
468
{ email: "maintenance@example.com", userId: "maintenance-user-id" }
469
],
470
deliveryOpts: {
471
frequency: "RATE_LIMIT",
472
rateLimit: 600 // Max one email per 10 minutes
473
}
474
}
475
});
476
477
const highHumidityTrigger = await triggersApi.triggersV1Create({
478
name: "High Humidity Control",
479
description: "Alert when humidity > 70%",
480
active: true,
481
property: {
482
id: humidityProp.id,
483
thingId: thingId,
484
name: humidityProp.name,
485
type: humidityProp.type
486
},
487
actions: [dehumidifyAction]
488
});
489
490
console.log('Environmental control system created:');
491
console.log(`- High temp trigger: ${highTempTrigger.id}`);
492
console.log(`- Low temp trigger: ${lowTempTrigger.id}`);
493
console.log(`- High humidity trigger: ${highHumidityTrigger.id}`);
494
495
return {
496
triggers: [highTempTrigger, lowTempTrigger, highHumidityTrigger],
497
actions: [fanControlAction, heatingAction, dehumidifyAction]
498
};
499
500
} catch (error) {
501
console.error('Failed to create environmental control system:', error);
502
throw error;
503
}
504
}
505
506
// Trigger management and monitoring
507
async function manageTriggers() {
508
try {
509
// List all triggers
510
const allTriggers = await triggersApi.triggersV1List();
511
console.log(`Total triggers: ${allTriggers.length}`);
512
513
for (const trigger of allTriggers) {
514
// Get detailed trigger info
515
const details = await triggersApi.triggersV1Show(trigger.id);
516
517
console.log(`\nTrigger: ${trigger.name}`);
518
console.log(`- Active: ${trigger.active}`);
519
console.log(`- Description: ${trigger.description}`);
520
console.log(`- Created: ${trigger.createdAt}`);
521
522
if (details.linkedDevices && details.linkedDevices.length > 0) {
523
console.log(`- Linked devices: ${details.linkedDevices.length}`);
524
}
525
526
if (details.linkedProperties && details.linkedProperties.length > 0) {
527
console.log(`- Linked properties: ${details.linkedProperties.length}`);
528
}
529
530
// Check if trigger needs maintenance (inactive for too long)
531
if (!trigger.active) {
532
console.log(`⚠️ Trigger ${trigger.name} is inactive`);
533
}
534
}
535
536
// List all actions
537
const allActions = await triggersApi.actionsV1List();
538
console.log(`\nTotal actions: ${allActions.length}`);
539
540
allActions.forEach(action => {
541
console.log(`- ${action.name} (${action.kind}): ${action.description}`);
542
});
543
544
} catch (error) {
545
console.error('Trigger management error:', error);
546
}
547
}
548
549
// Advanced trigger patterns
550
async function createAdvancedTriggers() {
551
try {
552
// Create template-based triggers for multiple similar devices
553
const sensorThingIds = ['thing-1', 'thing-2', 'thing-3'];
554
const triggerTemplates = [];
555
556
for (const thingId of sensorThingIds) {
557
// Get trigger template
558
const baseTriggerId = 'base-temperature-trigger-id';
559
const template = await triggersApi.triggersV1Template(baseTriggerId);
560
561
// Create new trigger from template
562
const newTrigger = await triggersApi.triggersV1Create({
563
name: `${template.name} - ${thingId}`,
564
description: template.description,
565
active: true,
566
property: {
567
...template.property,
568
thingId: thingId
569
},
570
actions: template.actions
571
});
572
573
triggerTemplates.push(newTrigger);
574
console.log(`Created trigger from template for thing ${thingId}`);
575
}
576
577
return triggerTemplates;
578
579
} catch (error) {
580
console.error('Advanced trigger creation failed:', error);
581
throw error;
582
}
583
}
584
585
// Usage example with comprehensive error handling
586
async function automationDemo(thingId, deviceId, properties) {
587
try {
588
console.log('Setting up comprehensive automation system...');
589
590
// 1. Temperature monitoring
591
console.log('\n=== Temperature Alerts ===');
592
await createTemperatureAlert(thingId, properties[0].id);
593
594
// 2. Device connectivity monitoring
595
console.log('\n=== Connectivity Monitoring ===');
596
await createConnectivityMonitoring(deviceId);
597
598
// 3. Environmental control system
599
console.log('\n=== Environmental Control ===');
600
await createEnvironmentalControlSystem(thingId, properties);
601
602
// 4. Trigger management
603
console.log('\n=== Trigger Management ===');
604
await manageTriggers();
605
606
// 5. Advanced patterns
607
console.log('\n=== Advanced Patterns ===');
608
await createAdvancedTriggers();
609
610
console.log('\nAutomation system setup completed successfully!');
611
612
} catch (error) {
613
if (error.status === 400) {
614
console.error('Bad request - check trigger/action configuration');
615
} else if (error.status === 403) {
616
console.error('Forbidden - check automation permissions');
617
} else if (error.status === 409) {
618
console.error('Conflict - trigger/action already exists');
619
} else {
620
console.error('Automation setup error:', error.detail || error.message);
621
}
622
}
623
}
624
```