DT Developer Docs
REST APIDT StudioStatus Page
  • Getting Started
  • Overview
  • Concepts
    • Devices
    • Events
    • Topics
      • Temperature Measurement Interval
      • Motion Sensor Activity Timer
  • Data Connectors
    • Introduction to Data Connectors
    • Creating a Data Connector
    • Configuring a Data Connector
    • Receiving Events
    • Best Practices
    • Example Integrations
      • Heroku
      • Google Cloud Functions
      • AWS Lambda
      • Azure HTTP Triggers
      • IBM Cloud Actions
    • Development Guides
      • Local Development with ngrok
  • REST API
  • Introduction to REST API
  • Explore Our Endpoints
    • with cURL
    • with Python API
    • with Postman
  • Authentication
    • OAuth2
    • Basic Auth
  • Error Codes
  • Emulator API
  • Examples
    • Pagination
    • Streaming Events
    • Touch to Identify
    • Refreshing Access Token
  • Reference
  • Status Page
  • Service Accounts
    • Introduction to Service Accounts
    • Creating a Service Account
    • Managing Access Rights
    • Permissions
    • Organizational Structures
  • Other
    • Application Notes
      • Generating a Room Temperature Heatmap
      • Modeling Fridge Content Temperatures
      • Outlier Detection on Multiple Temperature Sensors
      • Simple Temperature Forecasting for Substation Transformers
      • Sensor Data Insight with Power BI and Azure
      • Third-Party Sensor Data in DT Cloud
    • Frequently Asked Question
Powered by GitBook
On this page
  • Overview
  • Prerequisites
  • Azure Function
  • Create a Function App
  • Create an HTTP Trigger Function
  • Modify the HTTP Trigger
  • Dependency Management
  • Deploy
  • Data Connector
  • Test the Integration
  • Next steps
  • PostgreSQL Database

Was this helpful?

  1. Data Connectors
  2. Example Integrations

Azure HTTP Triggers

An example integration where a Data Connector forwards events to an Azure HTTP Trigger.

Last updated 1 year ago

Was this helpful?

Overview

This example uses a Data Connector to forward the events of all devices in a project to an . When receiving the HTTPS POST request, our trigger will verify both the origin and content of the request using a , then decode the data.

Prerequisites

The following points are assumed.

  • You have a of Project Developer or higher in your DT Studio project.

  • You are familiar with the and know how to .

  • You are familiar with the .

Azure Function

Depending on the runtime, parts of creating the HTTP Trigger must be done in a local environment on your machine. Ensure you have a working runtime environment for development using either the or .

Create a Function App

Function Apps combine several functions into a single unit for easier management and can be created in the Azure Portal by . Create a new Function App with the following configurations.

  • Runtime Stack: Python

  • Version: 3.11

  • Operating System: Linux

  • Runtime Stack: Python

  • Version: 3.11

  • Operating System: Linux

  • Runtime Stack: Node.js

  • Version: 18 LTS

  • Operating System: Linux

Click Review + create, then Create and wait for deployment. Once deployed, Go to resource.

Edit Application Settings

  • Name: DT_SIGNATURE_SECRET

  • Value: A unique password. We will use it later, so write it down.

Create an HTTP Trigger Function

Once the Function App is deployed, a new HTTP trigger function can be created. Azure has guides on creating and editing functions. Follow either.

By following one of the guides, create a new HTTP Trigger with the following configurations.

  • Authorization level: Anonymous.

Afterward, your project structure should end up looking something like this.

project
├── yourNewFunction
│   ├── function.json
│   └── __init__.py
├── getting_started.md
├── host.json
├── local.settings.json
└── requirements.txt
project
├── yourNewFunction
│   ├── function.json
│   └── __init__.py
├── getting_started.md
├── host.json
├── local.settings.json
└── requirements.txt
project
├── host.json
├── yourNewFunction
│   ├── function.json
│   └── index.js
├── local.settings.json
└── package.json

Modify the HTTP Trigger

Once the function has been created, the desired behavior can be programmed. The following code snippet implements a simple HTTP trigger that listens for POST requests, then validates the content and origin using the Signature Secret and Checksum verification.

__init__.py
import os
import hashlib

import azure.functions as func
import jwt

# Fetch environment variables.
SIGNATURE_SECRET = os.environ.get('DT_SIGNATURE_SECRET', '')


def verify_request(body, token):
    # Decode the token using signature secret.
    try:
        payload = jwt.decode(token, SIGNATURE_SECRET, algorithms=["HS256"])
    except Exception as err:
        print(err)
        return False

    # Verify the request body checksum.
    m = hashlib.sha1()
    m.update(body)
    checksum = m.digest().hex()
    if payload["checksum"] != checksum:
        print('Checksum Mismatch')
        return False

    return True


def main(req: func.HttpRequest) -> func.HttpResponse:
    # Extract necessary request information.
    body = req.get_body()
    token = req.headers['x-dt-signature']

    # Validate request origin and content integrity.
    if not verify_request(body, token):
        return func.HttpResponse('Bad request', status_code=400)

    #
    # Further processing goes here.
    #

    return func.HttpResponse("OK", status_code=200)
__init__.py
import os

import azure.functions as func
from dtintegrations import data_connector, provider


def main(req: func.HttpRequest) -> func.HttpResponse:
    # Extract necessary request information.
    payload = data_connector.HttpPush.from_provider(
        request=req,
        provider=provider.AZURE,
        secret=os.environ.get('DT_SIGNATURE_SECRET', ''),
    )

    #
    # Further processing goes here.
    #
    print(payload)

    return func.HttpResponse("OK", status_code=200)
index.js
const crypto = require('crypto')
const jwt = require('jsonwebtoken')

// Fetch environment variables.
const signatureSecret = process.env.DT_SIGNATURE_SECRET

function verifyRequest(body, token) {
    // Decode the token using signature secret.
    let decoded;
    try {
        decoded = jwt.verify(token, signatureSecret)
    } catch(err) {
        console.log(err)
        return false
    }

    // Verify the request body checksum.
    let shasum = crypto.createHash('sha1')
    let checksum = shasum.update(JSON.stringify(body)).digest('hex')
    if (checksum !== decoded.checksum) {
        console.log('Checksum Mismatch')
        return false
    }

    return true
}

module.exports = async function (context, req) {
    // Extract necessary request information.
    let body  = req.body
    let token = req.headers['x-dt-signature']

    // Validate request origin and content integrity.
    if (verifyRequest(body, token) === false) {
        context.res = { status: 400, body: 'Bad request' }
        return
    }
    //
    // Further processing here.
    //
    
    context.res = { status: 200, body: 'OK' }
}

Dependency Management

Dependencies must be specified and included for your HTTP Trigger to run in the cloud.

requirements.txt
azure-functions
pyjwt==2.7.0
requirements.txt
azure-functions
dtintegrations==0.5.1
npm install jsonwebtoken@9.0.1

Deploy

func azure functionapp publish <APP_NAME>

Once the function is deployed, the Invoke URL is displayed in the output. Copy and save it as we will need it when creating our Data Connector.

...
Deployment successful.
Remote build succeeded!
Syncing triggers...
Functions in msdocs-azurefunctions-qs:
    HttpExample - [httpTrigger]
THIS->  Invoke url: https://msdocs-azurefunctions-qs.azurewebsites.net/api/httpexample

Data Connector

  • Endpoint URL: The Invoke URL found in the previous step.

  • Signature Secret: The value of DT_SIGNATURE_SECRET environment variable set earlier.

Depending on your integration, it can also be smart to disable the event types you are not interested in. For instance, the NetworkStatusEvent is sent every Periodic Heartbeat and will by default be forwarded by the Data Connector if not explicitly unticked.

Test the Integration

If instead the Error counter increments, a response containing a non-200 status code is returned.

  • Verify that the Data Connector endpoint URL is correct.

Next steps

Your sensor data is now in the Azure environment, and you can start using it in their various services. Fortunately, Azure has some well-documented guides to get you started.

PostgreSQL Database

A database should be tailored to each specific use case. However, if you're uncertain, PostgreSQL (Postgres) is a good place to get started. The following guides will show you how to create a new Postgres database, then connect your HTTP Trigger to execute queries.

We will verify the incoming POST request by a signature secret, as explained in the Data Connector . In your new Function App, add a secret to your App environment by adding a new Application Setting, .

In your HTTP Trigger function directory, edit the file __init__.py. The implementation is explained in detail on the page.

In your HTTP Trigger function directory, edit the file __init__.py. The implementation is explained in detail on the page.

In your HTTP Trigger function directory, edit the file index.js. The implementation is explained in detail on the page.

As explained , edit requirements.txt to tell Azure which dependencies to install.

As explained , edit requirements.txt to tell Azure which dependencies to install.

As explained , in your project directory, install all requisite packages locally using npm install. This will generate a directory node_modules which is included when deploying.

Your function should now be ready for deployment. It is considered good practice to test- and experiment with your function locally, . The following command will deploy your function to the Function App created in the beginning.

To continuously forward the data to our newly created Cloud Function, a Data Connector with almost all default settings is sufficient. If you are unfamiliar with how Data Connectors can be created, refer to our guide. The following configurations should be set.

If the integration was correctly implemented, the Success counter for your Data Connector should increment for each new event forwarded. This happens each or by touching a sensor to force a new event.

Azure provides a host of tools that can be used to . Check the logs for any tracebacks that could explain why an error is returned.

.

.

command line
Visual Studio Code
here
here
here
which you can read how-to here
Creating a Data Connector
monitor Azure Functions
Create an Azure Database for PostgreSQL server
Connect and query data in Azure Database for PostgreSQL
Azure HTTP trigger
Introduction to Data Connectors
Create a Data Connector
Azure Functions documentation
command line
Visual Studio Code
following this guide
as explained in this guide
Data Connector Receiving Events
Data Connector Receiving Events
Data Connector Receiving Events
Periodic Heartbeat
Advanced Configurations
Signature Secret
Role