CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-arduino--arduino-iot-client

JavaScript client library for the Arduino IoT Cloud REST API enabling programmatic management of devices, things, properties, and time-series data

Overview
Eval results
Files

automation-triggers.mddocs/

Automation & Triggers

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.

Capabilities

Trigger Management

Create and manage automation triggers that monitor IoT properties and execute actions based on conditions.

class TriggersV1Api {
  /**
   * Create a new automation trigger
   * @param trigger - Trigger configuration with conditions and linked actions
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoTrigger> - Created trigger object
   */
  triggersV1Create(trigger: Trigger, opts?: any): Promise<ArduinoTrigger>;

  /**
   * List all triggers accessible to the authenticated user
   * @param opts - Optional parameters including organization ID and pagination
   * @returns Promise<ArduinoTrigger[]> - Array of trigger objects
   */
  triggersV1List(opts?: any): Promise<ArduinoTrigger[]>;

  /**
   * Get detailed information about a specific trigger
   * @param id - Trigger ID
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoTriggerWithLinkedEntities> - Trigger with linked entities
   */
  triggersV1Show(id: string, opts?: any): Promise<ArduinoTriggerWithLinkedEntities>;

  /**
   * Update trigger configuration and conditions
   * @param id - Trigger ID
   * @param trigger - Updated trigger configuration
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoTrigger> - Updated trigger object
   */
  triggersV1Update(id: string, trigger: Trigger, opts?: any): Promise<ArduinoTrigger>;

  /**
   * Partial update of trigger properties
   * @param id - Trigger ID
   * @param trigger - Partial trigger configuration updates
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoTrigger> - Updated trigger object
   */
  triggersV1Patch(id: string, trigger: Trigger, opts?: any): Promise<ArduinoTrigger>;

  /**
   * Delete a trigger permanently
   * @param id - Trigger ID
   * @param opts - Optional parameters including organization ID
   * @returns Promise<void>
   */
  triggersV1Delete(id: string, opts?: any): Promise<void>;

  /**
   * Get trigger as a template for replication
   * @param id - Trigger ID
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoTriggerTemplate> - Trigger template
   */
  triggersV1Template(id: string, opts?: any): Promise<ArduinoTriggerTemplate>;
}

Action Management

Create and manage actions that are executed when triggers are activated.

class TriggersV1Api {
  /**
   * Create a new automation action
   * @param createAction - Action configuration including type and parameters
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoAction> - Created action object
   */
  actionsV1Create(createAction: CreateAction, opts?: any): Promise<ArduinoAction>;

  /**
   * List all actions accessible to the authenticated user
   * @param opts - Optional parameters including organization ID and pagination
   * @returns Promise<ArduinoAction[]> - Array of action objects
   */
  actionsV1List(opts?: any): Promise<ArduinoAction[]>;

  /**
   * Get detailed information about a specific action
   * @param id - Action ID
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoAction> - Action object with full details
   */
  actionsV1Show(id: string, opts?: any): Promise<ArduinoAction>;

  /**
   * Update action configuration and parameters
   * @param id - Action ID
   * @param updateAction - Updated action configuration
   * @param opts - Optional parameters including organization ID
   * @returns Promise<ArduinoAction> - Updated action object
   */
  actionsV1Update(id: string, updateAction: UpdateAction, opts?: any): Promise<ArduinoAction>;

  /**
   * Delete an action permanently
   * @param id - Action ID
   * @param opts - Optional parameters including organization ID
   * @returns Promise<void>
   */
  actionsV1Delete(id: string, opts?: any): Promise<void>;
}

Data Models

interface ArduinoTrigger {
  active?: boolean;
  createdAt?: Date;
  description?: string;
  deviceStatusSource?: DeviceStatusSource;
  href?: string;
  id?: string;
  name?: string;
  organizationId?: string;
  property?: ArduinoProperty;
  updatedAt?: Date;
  userId?: string;
}

interface Trigger {
  active?: boolean;
  actions?: ArduinoAction[];
  description?: string;
  deviceStatusSource?: DeviceStatusSource;
  name: string;
  property?: ArduinoLinkedProperty;
}

interface ArduinoAction {
  createdAt?: Date;
  description?: string;
  emailAction?: EmailAction;
  href?: string;
  id?: string;
  kind?: ActionKind;
  name?: string;
  organizationId?: string;
  pushAction?: PushAction;
  updatedAt?: Date;
  userId?: string;
}

interface CreateAction {
  description?: string;
  emailAction?: EmailAction;
  kind: ActionKind;
  name: string;
  pushAction?: PushAction;
}

interface UpdateAction {
  description?: string;
  emailAction?: EmailAction;
  name?: string;
  pushAction?: PushAction;
}

interface EmailAction {
  body?: BodyExpression;
  deliveryOpts?: EmailDeliveryOpts;
  recipients?: UserRecipient[];
  subject?: TitleExpression;
}

interface PushAction {
  body?: BodyExpression;
  deliveryOpts?: PushDeliveryOpts;
  recipients?: UserRecipient[];
  title?: TitleExpression;
}

interface DeviceStatusSource {
  connectionType?: string;
  deviceId?: string;
}

interface ArduinoTriggerWithLinkedEntities {
  active?: boolean;
  createdAt?: Date;
  description?: string;
  deviceStatusSource?: DeviceStatusSource;
  href?: string;
  id?: string;
  linkedDevices?: ArduinoLinkedDevice[];
  linkedProperties?: ArduinoLinkedProperty[];
  name?: string;
  organizationId?: string;
  property?: ArduinoProperty;
  updatedAt?: Date;
  userId?: string;
}

interface ArduinoTriggerTemplate {
  actions?: ArduinoActionTemplate[];
  active?: boolean;
  description?: string;
  deviceStatusSource?: DeviceStatusSource;
  name?: string;
  property?: ArduinoLinkedPropertyTemplate;
}

interface ArduinoActionTemplate {
  description?: string;
  emailAction?: EmailAction;
  kind?: ActionKind;
  name?: string;
  pushAction?: PushAction;
}

interface ArduinoLinkedPropertyTemplate {
  name?: string;
  permission?: PropertyPermission;
  type?: PropertyType;
  variableName?: string;
}

interface ArduinoLinkedProperty {
  id?: string;
  name?: string;
  thingId?: string;
  type?: string;
  variableName?: string;
}

interface BodyExpression {
  template?: string;
}

interface TitleExpression {
  template?: string;
}

interface EmailDeliveryOpts {
  frequency?: string;
  rateLimit?: number;
}

interface PushDeliveryOpts {
  frequency?: string;
}

interface UserRecipient {
  email?: string;
  userId?: string;
}

enum ActionKind {
  EMAIL = 'EMAIL',
  PUSH_NOTIFICATION = 'PUSH_NOTIFICATION'
}

Comprehensive Automation Examples:

import ArduinoIotClient from '@arduino/arduino-iot-client';

const triggersApi = new ArduinoIotClient.TriggersV1Api();

// Create email notification system
async function createTemperatureAlert(thingId, temperaturePropertyId) {
  try {
    // Create email action for high temperature alert
    const highTempAction = await triggersApi.actionsV1Create({
      name: "High Temperature Alert",
      kind: "EMAIL",
      description: "Send email when temperature exceeds safe limits",
      emailAction: {
        subject: {
          template: "🌡️ High Temperature Alert - {{property.name}}"
        },
        body: {
          template: `
            <h2>Temperature Alert</h2>
            <p><strong>Thing:</strong> {{thing.name}}</p>
            <p><strong>Current Temperature:</strong> {{property.last_value}}°C</p>
            <p><strong>Threshold:</strong> 35°C</p>
            <p><strong>Time:</strong> {{property.updated_at}}</p>
            <p>Please check the environmental conditions immediately.</p>
          `
        },
        recipients: [
          { email: "admin@example.com", userId: "admin-user-id" },
          { email: "maintenance@example.com", userId: "maintenance-user-id" }
        ],
        deliveryOpts: {
          frequency: "RATE_LIMIT",
          rateLimit: 300 // Max one email per 5 minutes
        }
      }
    });

    // Create trigger for high temperature
    const highTempTrigger = await triggersApi.triggersV1Create({
      name: "High Temperature Trigger",
      description: "Activate when temperature exceeds 35°C",
      active: true,
      property: {
        id: temperaturePropertyId,
        thingId: thingId,
        name: "Temperature",
        type: "TEMPERATURE",
        variableName: "temperature"
      },
      actions: [highTempAction]
    });

    console.log(`Created high temperature trigger: ${highTempTrigger.id}`);
    return { trigger: highTempTrigger, action: highTempAction };

  } catch (error) {
    console.error('Failed to create temperature alert:', error);
    throw error;
  }
}

// Create device connectivity monitoring
async function createConnectivityMonitoring(deviceId) {
  try {
    // Create push notification action for device offline
    const offlineAction = await triggersApi.actionsV1Create({
      name: "Device Offline Alert",
      kind: "PUSH_NOTIFICATION",
      description: "Send push notification when device goes offline",
      pushAction: {
        title: {
          template: "📱 Device Offline - {{device.name}}"
        },
        body: {
          template: "Device {{device.name}} has been offline for more than 5 minutes. Last seen: {{device.last_activity_at}}"
        },
        recipients: [
          { userId: "admin-user-id" },
          { userId: "technician-user-id" }
        ],
        deliveryOpts: {
          frequency: "IMMEDIATE"
        }
      }
    });

    // Create trigger for device offline status
    const offlineTrigger = await triggersApi.triggersV1Create({
      name: "Device Connectivity Monitor",
      description: "Monitor device connectivity status",
      active: true,
      deviceStatusSource: {
        deviceId: deviceId,
        connectionType: "wifi"
      },
      actions: [offlineAction]
    });

    console.log(`Created connectivity monitoring trigger: ${offlineTrigger.id}`);
    return { trigger: offlineTrigger, action: offlineAction };

  } catch (error) {
    console.error('Failed to create connectivity monitoring:', error);
    throw error;
  }
}

// Create multi-condition automation system
async function createEnvironmentalControlSystem(thingId, properties) {
  try {
    const [tempProp, humidityProp, fanProp, ledProp] = properties;

    // 1. High temperature response
    const fanControlAction = await triggersApi.actionsV1Create({
      name: "Activate Cooling System",
      kind: "EMAIL",
      description: "Notify when cooling system is activated",
      emailAction: {
        subject: {
          template: "🌬️ Cooling System Activated"
        },
        body: {
          template: `
            <h3>Environmental Control Alert</h3>
            <p>Cooling system has been automatically activated.</p>
            <p><strong>Temperature:</strong> {{property.last_value}}°C</p>
            <p><strong>Action:</strong> Fan activated at maximum speed</p>
            <p><strong>Location:</strong> {{thing.name}}</p>
          `
        },
        recipients: [{ email: "facility@example.com", userId: "facility-user-id" }]
      }
    });

    const highTempTrigger = await triggersApi.triggersV1Create({
      name: "High Temperature Control",
      description: "Activate cooling when temperature > 28°C",
      active: true,
      property: {
        id: tempProp.id,
        thingId: thingId,
        name: tempProp.name,
        type: tempProp.type
      },
      actions: [fanControlAction]
    });

    // 2. Low temperature response
    const heatingAction = await triggersApi.actionsV1Create({
      name: "Heating System Alert",
      kind: "PUSH_NOTIFICATION",
      description: "Alert when heating might be needed",
      pushAction: {
        title: {
          template: "🔥 Low Temperature Detected"
        },
        body: {
          template: "Temperature dropped to {{property.last_value}}°C. Consider activating heating system."
        },
        recipients: [{ userId: "maintenance-user-id" }]
      }
    });

    const lowTempTrigger = await triggersApi.triggersV1Create({
      name: "Low Temperature Alert",
      description: "Alert when temperature < 18°C",
      active: true,
      property: {
        id: tempProp.id,
        thingId: thingId,
        name: tempProp.name,
        type: tempProp.type
      },
      actions: [heatingAction]
    });

    // 3. High humidity response
    const dehumidifyAction = await triggersApi.actionsV1Create({
      name: "High Humidity Alert",
      kind: "EMAIL",
      description: "Alert when humidity is too high",
      emailAction: {
        subject: {
          template: "💧 High Humidity Alert - {{thing.name}}"
        },
        body: {
          template: `
            <h3>Humidity Control Alert</h3>
            <p><strong>Current Humidity:</strong> {{property.last_value}}%</p>
            <p><strong>Threshold:</strong> 70%</p>
            <p><strong>Recommendation:</strong> Activate dehumidification system</p>
            <p><strong>Risk:</strong> High humidity can lead to condensation and equipment damage</p>
          `
        },
        recipients: [
          { email: "facility@example.com", userId: "facility-user-id" },
          { email: "maintenance@example.com", userId: "maintenance-user-id" }
        ],
        deliveryOpts: {
          frequency: "RATE_LIMIT",
          rateLimit: 600 // Max one email per 10 minutes
        }
      }
    });

    const highHumidityTrigger = await triggersApi.triggersV1Create({
      name: "High Humidity Control",
      description: "Alert when humidity > 70%",
      active: true,
      property: {
        id: humidityProp.id,
        thingId: thingId,
        name: humidityProp.name,
        type: humidityProp.type
      },
      actions: [dehumidifyAction]
    });

    console.log('Environmental control system created:');
    console.log(`- High temp trigger: ${highTempTrigger.id}`);
    console.log(`- Low temp trigger: ${lowTempTrigger.id}`);
    console.log(`- High humidity trigger: ${highHumidityTrigger.id}`);

    return {
      triggers: [highTempTrigger, lowTempTrigger, highHumidityTrigger],
      actions: [fanControlAction, heatingAction, dehumidifyAction]
    };

  } catch (error) {
    console.error('Failed to create environmental control system:', error);
    throw error;
  }
}

// Trigger management and monitoring
async function manageTriggers() {
  try {
    // List all triggers
    const allTriggers = await triggersApi.triggersV1List();
    console.log(`Total triggers: ${allTriggers.length}`);

    for (const trigger of allTriggers) {
      // Get detailed trigger info
      const details = await triggersApi.triggersV1Show(trigger.id);

      console.log(`\nTrigger: ${trigger.name}`);
      console.log(`- Active: ${trigger.active}`);
      console.log(`- Description: ${trigger.description}`);
      console.log(`- Created: ${trigger.createdAt}`);

      if (details.linkedDevices && details.linkedDevices.length > 0) {
        console.log(`- Linked devices: ${details.linkedDevices.length}`);
      }

      if (details.linkedProperties && details.linkedProperties.length > 0) {
        console.log(`- Linked properties: ${details.linkedProperties.length}`);
      }

      // Check if trigger needs maintenance (inactive for too long)
      if (!trigger.active) {
        console.log(`⚠️  Trigger ${trigger.name} is inactive`);
      }
    }

    // List all actions
    const allActions = await triggersApi.actionsV1List();
    console.log(`\nTotal actions: ${allActions.length}`);

    allActions.forEach(action => {
      console.log(`- ${action.name} (${action.kind}): ${action.description}`);
    });

  } catch (error) {
    console.error('Trigger management error:', error);
  }
}

// Advanced trigger patterns
async function createAdvancedTriggers() {
  try {
    // Create template-based triggers for multiple similar devices
    const sensorThingIds = ['thing-1', 'thing-2', 'thing-3'];
    const triggerTemplates = [];

    for (const thingId of sensorThingIds) {
      // Get trigger template
      const baseTriggerId = 'base-temperature-trigger-id';
      const template = await triggersApi.triggersV1Template(baseTriggerId);

      // Create new trigger from template
      const newTrigger = await triggersApi.triggersV1Create({
        name: `${template.name} - ${thingId}`,
        description: template.description,
        active: true,
        property: {
          ...template.property,
          thingId: thingId
        },
        actions: template.actions
      });

      triggerTemplates.push(newTrigger);
      console.log(`Created trigger from template for thing ${thingId}`);
    }

    return triggerTemplates;

  } catch (error) {
    console.error('Advanced trigger creation failed:', error);
    throw error;
  }
}

// Usage example with comprehensive error handling
async function automationDemo(thingId, deviceId, properties) {
  try {
    console.log('Setting up comprehensive automation system...');

    // 1. Temperature monitoring
    console.log('\n=== Temperature Alerts ===');
    await createTemperatureAlert(thingId, properties[0].id);

    // 2. Device connectivity monitoring
    console.log('\n=== Connectivity Monitoring ===');
    await createConnectivityMonitoring(deviceId);

    // 3. Environmental control system
    console.log('\n=== Environmental Control ===');
    await createEnvironmentalControlSystem(thingId, properties);

    // 4. Trigger management
    console.log('\n=== Trigger Management ===');
    await manageTriggers();

    // 5. Advanced patterns
    console.log('\n=== Advanced Patterns ===');
    await createAdvancedTriggers();

    console.log('\nAutomation system setup completed successfully!');

  } catch (error) {
    if (error.status === 400) {
      console.error('Bad request - check trigger/action configuration');
    } else if (error.status === 403) {
      console.error('Forbidden - check automation permissions');
    } else if (error.status === 409) {
      console.error('Conflict - trigger/action already exists');
    } else {
      console.error('Automation setup error:', error.detail || error.message);
    }
  }
}

Install with Tessl CLI

npx tessl i tessl/npm-arduino--arduino-iot-client

docs

automation-triggers.md

dashboard-management.md

device-management.md

index.md

lora-device-management.md

network-credentials.md

property-management.md

thing-management.md

timeseries-analytics.md

tile.json