IoT with Particle: Functions and Variables using the Build IDE

In yesterday’s post, I talked a bit about the setup process and initial configuration of a Particle Photon. To start quickly, we used the Tinker firmware and the Particle iOS app to light up a LED using digitalWrite to light it up with full brightness (full 3.3V) but also with analogWrite to vary the brightness depending on the value you write (between 0-255 using the PWM port D0).

Today, we’ll add a photoresistor and a LED with the LED positioned above the photoresistor. We’ll turn on the LED from the Particle Cloud using a Particle Function and we’ll read out the photoresistor value using a Particle Variable.

For the photoresistor, I only had a Grove Light Sensor lying around. If you don’t know the Grove system, it’s a a collection of sensors with simple four-wire connectors that typically work with an add-on board for these connectors. For the Photon, there is such a solution as well. To get started easily you could go for the starter kit: https://www.seeedstudio.com/Grove-Starter-Kit-for-Photon-p-2179.html. Since I do not have the Grove add-on board for the Photon, I connected the sensor using three male-to-female (two for power and ground and one for the signal) wires and connected the signal pin to port A0 on the Photon. Indeed, the photoresistor will output a value to read using analogRead. The value rises with increasing brightness.

So how do we turn on the LED from the Particle Cloud? That’s where Particle Functions come in. Particle Functions make it extremely easy to control your device from anywhere. In fact, it’s one of the easiest solutions I have found to date. But first, you have to know something about the integrated development environment called Build.

Particle’s web-based IDE: Build

You access the IDE from https://build.particle.io. The screenshot below shows the IDE with a new app ready to be coded:

image

If you are used to Arduino, it all looks pretty similar here but beware there are many subtle differences. The cool thing is that you can code your app here and flash the device from the Web using the flash icon in the top left. Let’s write a simple app to flash a led at port D1:

image

Okay, cool but not very interesting. Let’s put this LED under cloud control with a function.

Particle Functions

Let’s write a Particle Function that can turn the LED on or off remotely.

image

With the simple code above you have registered a Particle Function, led, that you can call remotely (with proper credentials of course). When you call the led function and you pass a parameter (always a string) the function ledToggler is executed on the device. Great, but how do you call the led function? There are several options:

  • use the Particle CLI
  • send an HTTP POST to a Particle API endpoint

The CLI is easy. After installing it (see https://docs.particle.io/guide/tools-and-features/cli/photon/), just execute the following command to see your devices and their functions: particle list (note: use particle login first to login with your Particle account)

image

Now call the function using particle call

image

Above you see two calls to turn the LED on and off. After each call, you also see the return value of the function.

To use the HTTP POST method, there’s a myriad of tools and frameworks to do so. From the command line, you can use cURL but you could also use Postman. I use cURL on Windows, which is part of Git Bash. You can also try https://curl.haxx.se/download.html. With cURLyou need to supply your device ID + an access token you can get from the IDE:

image

Above you see the same two calls to turn the LED on or off. The HTTP POST returns some JSON with the return_value from the function.

Particle Variables

Functions are great to trigger actions on your devices, but how do we read data from a sensor like the photoresistor in our case? That’s surprisingly easy again: just use a Particle Variable. Modify the code as follows:

image

Above, the A0 pin (called PR) is setup for reading values. In the loop, we keep reading the brightness from the photoresistor using analogRead followed by a delay of 1 second. A Particle Variable is defined that you can read from the cloud using the CLI or HTTP GET. With the CLI:

image

Without the LED above the photo resistor, inside the house, we get 1485 as a brightness value. With the LED turned on right above it, the value is 2303. Great!!! By the way, the LED is not too bright because I used a 1000 Ohm resistor.

Using cURL:

image

Wrap Up

You have now seen how easy it is to trigger actions with Particle Functions and read sensor data using Particle Variables. This functionality automatically comes with your Particle device at no extra cost and is completely driven from code. There is no need to use other services to post sensor data which keeps things simple. And I like simple, don’t you?

In a subsequent post, we’ll take a look at publishing event data using Particle Publish! Stay tuned!

IoT with Particle: a smooth experience

At ThingTank, the IoT brand of Xylos, we make our own IoT hardware which can be quite complex if you need to connect multiple sensors efficiently, or even multiple MCUs where each MCU has its own set of sensors. Most people that want to start with IoT (typically at home or for a small company proof of concept) use either Arduino or Raspberry Pi with one or two sensors connected. Both solutions are great in their own right but there are others! One such solution is Particle, a combination of both hardware, software and cloud. Let’s take a look at what they offer from a hardware and configuration perspective. Future posts will discuss their cloud offering and how to connect to other systems such as Azure IoT Hub.

Hardware

Particle sell their own hardware (like the Photon and Electron) but they also work with other hardware such as a Raspberry Pi. I bought a Photon from https://www.antratek.be/photon. It costs around 25€ which is not as cheap as some alternatives but still well worth the money.

image

After unpacking, I mounted it on a breadboard and gave it power from a wall socket using an adapter I had lying around that I used in the past to power a Raspberry Pi. Although you can, you do not have to connect the Photon to a computer to configure it. Yes, you heard that right! You can configure the Photon using a mobile app and you can flash new firmware OTA (over the air) right from a web-based IDE called Build. Let’s see how initial configuration works…

Configuration

The Photon only comes with WiFi, compared to the Electron which comes with 2G/3G and a global SIM card. To connect the Photon to WiFi (one of five connections the device can remember), use the Particle app for iOS or Android (the easiest method):

file9

To configure a new device, the app guides you through the whole process. The Photon will create its own WiFi network. After connecting your phone to that network, you can configure the network you want the Photon to connect to:

file10

When the process is finished, the device can be seen in the Particle Console:

image

As part of the configuration process, you can give the device a name. The device name (or device id) can later be used in HTTP calls or from the Particle CLI.

Tinker

This post will not discuss how to flash the device with a custom firmware (that’s for a later post). But even without a custom firmware, you can still start exploring the device and do useful things with the digital and analog ports using the mobile app and the out-of-the-box Tinker firmware. The Tinker firmware can always be flashed back to the device if needed.

In the mobile app, after selecting the device, you will see the port layout of the device:

file-4

 

Without going into details here, know that there is an onboard LED connected to digital port D7. When you select D7, you will be asked what you want to do:

file-5

In this case, we want to turn on the onboard LED so we obviously want to write to the port. After selecting digitalWrite, you can select D7 to set the port HIGH (3.3V) or LOW (GND). When the port is set to HIGH, the on-board LED will light up in blue. Cool no? Although not very useful, you have now configured the Photon to connect to the Particle back-end in the cloud and you can use their app to control the ports from the cloud as well.

Tinker works just a well with analogWrite. If you have an LED connected to D0, and a resistor from the other side of the LED to GND, you can send a value between 0 and 255 to the port which will light up the LED with varying brightness:

file-6

image

Note: D0-D7 are digital ports but D0~D3 may also be used as a PWM output (PWM = pulse width modulaton); that’s why you can send values ranging from 0 to 255 to those ports as well (analogWrite)

Summary

Particle has gone out of its way to make it as easy as possible to get started. Setting up the device is super simple and getting started with the built-in Tinker firmware makes it easier for beginners to understand how to use the ports without having to start coding. In follow-up posts, we’ll have a look at some of the cloud functionality and we’ll connect some more useful sensors like a photoresistor and a PIR sensor… Stay tuned!!!

Have some fun with Slash Webtasks and Slack

At ThingTank we really love a tool like Slack because of its simplicity and extensibility. Like so many, we use it to get notifications from all sorts of systems. A lot of websites and tools integrate with Slack such as Azure Logic Apps or CI systems like Shippable. Those types of integrations are very easy to configure.

But what if you want to send commands from Slack? You would typically use a slash command for that. Some common commands are /giphy to insert an animated GIF or /hangouts to start a Google Hangouts session.

In this case, we wanted to create a slash command to tell our CI system (Shippable) to run a build for a project. We found that one of the simplest ways to do that, is to use Slash Webtasks from those clever guys at Auth0. We already use Auth0 for securing our back-end APIs and we really love the way they think about developer productivity. You will first have to install the Webtasks app from https://webtask.io/slack. After that, you will have a new slash command in Slack: /wt.

After installation, you use the /wt command to start creating Slash Webtasks. First, create a new Slash Webtask like so (we’ll call it builder):

image

Just click Edit it in Webtask Editor to start editing the task. The tasks are programmed in Node.js and lots of packages are available to you. No need for package.json or manual npm install commands. The sample code will look like this:

image

This is just a Hello World example that says hello to you in Slack. You can invoke it with /wt builder and you will get a response like Hello @geba. The context object provides access to all sorts of goodies like in this case your user name in Slack.

Some sample code to run a build in Shippable can be found in this gist: https://gist.github.com/gbaeke/9e92b4a33e41793f1d6c454cfc496bd6. Open it up and take a look at the code. In short, this is what happens:

  • Require the request package (https://www.npmjs.com/package/request) to be used later to send the POST to the Shippable API that performs the build
  • Retrieve the Shippable API key from the secrets you can store in Slash Webtasks.
  • Retrieve the text after your command /wt builder. So if I use /wt builder realtime, the variable “project” will contain the string “realtime”
  • Internally, we keep a small dictionary of project names and their corresponding id that we require in the API; we could have done other API requests to retrieve the id but this is simpler and meets our needs
  • Use request, to perform a POST request to https://api.shippable.com/projects/projectid/newBuild and specify the API token in the authorization header
  • Give some feedback to the user; the CI process in Shippable is configured to report back to Slack in its shippable.yml configuration file

A note about those secrets, these are configured right in the editor:

image

We’ve only touched on the basics here but there is not much more to it. If you are looking for a simple way to create custom slash commands in Slack, give Slash Webtasks a try. It’s really fun to work with and it’s very elegant. And by the way, Webtasks on its own can do much more. It’s one of those serverless solutions but it has some nifty features such as Express integration etc… Maybe I’ll cover that in another post!

IoT Hub Scaling

When you work with Azure IoT Hub, it is not always easy to tell what will happen when you reach the limits of IoT Hub and what to do when you reach those limits. As a reminder, recall that the scale of IoT Hub is defined by its tier and the number of units in the tier. There are three paying tiers, besides the free tier:

image

Although these tiers make it clear how many messages you can send, other limits such as the amount of messages per second cannot be seen here. To have an idea about the amount of messages you can send and the sustained throughput see https://azure.microsoft.com/en-us/documentation/articles/iot-hub-scaling/#device-to-cloud-and-cloud-to-device-message-throughput

The specific burst performance numbers can be found here: https://azure.microsoft.com/en-us/documentation/articles/iot-hub-devguide-quotas-throttling/. Typically, the limit you are concerned with is the amount of device-to-cloud sends which are as follows:

  • S1: 12/sec/unit (but you get at least 100/sec in total; not per unit obviously); 10 units give you 120/sec and not 100+120/sec
  • S2: 120/sec/unit
  • S3: 6000/sec/unit

Now suppose you think about deploying 300 devices which send data every half a second. What tier should you use and how many units? It is clear that you need to send 600 messages per second so 5 units of S2 will suffice. You could also take 50 units of S1 for the same performance and price. With 5 units of S2 though, you can send more messages.

Now it would be nice to test the above in advance. At ThingTank we use Docker containers for this and we schedule them with Rancher, a great and easy to use Docker orchestration tool. If you want to try it, just use the container you can find on Docker Hub or the new Docker Store (still in beta). Just search for gbaeke and you will find the following container:

image

If you want to check out the code (warning: written hastily!), you can find it on GitHub here: https://github.com/xyloscloudservices/docker-itproceed. It is a simple NodeJs script that uses the Azure IoT Hub libraries to create a new device in the registry with a GUID for the name. Afterwards, the code sends a simple JSON payload to IoT Hub every half a second.

To use the script, start it as follows with three parameters:

app.js IoT_Hub_Short_Name IoT_Hub_Connection_String millis

Note: the millis parameter is the amount of milliseconds to wait between each send

Now you can run the containers in Rancher (for instance). I won’t go into the details how to add Docker Hosts to Rancher and how to create a new Stack (as they call it). Alternatively, you can run the containers on Azure Container Service or similar solutions.

In the PowerBI chart below, you see the eventcount every five seconds which is around 420-440 events which is a bit lower than expected for one S1 unit:

image

Note: the spike you see happens after the launch of 300 containers; throttling quickly kicks in

When switched to 5 S2 units, the graph looks as follows:

image

You see the eventcount jump to 3000 (near the end) which is what you would expect (300 containers send 600 messages per second = 3000 messages per 5 seconds which is possible with 5 S2 units that deliver 120 messages/sec/unit)

You really need to think if you want to send data every half a second or second. For our ThingTank Air Quality solution, we take measurements every second but aggregate them over a minute at the edge. Sending every minute with 5 S2 units would amount to thousands of devices before you reach the limits of IoT Hub!

Adding natural language to your Bot

In the last post, Bots in an IoT context, I created a very simple bot to request the air quality in a room. To change the room, you had to type change room and then type the room name when requested. It would be much nicer to be able to give commands like change room to <roomname> or set the room to <roomname> or switch room to <roomname>. Instead of using regular expressions, you should use the Language Understanding Intelligent Service or LUIS in short.

In LUIS, you first create an app. In the app, you define things like intents and entities. In this case, I only need one intent which I called ChangeRoom. Because I am going to specify the name of the room in phrases I type, I also defined an entity called room.

image

Next, you need to specify utterances and tell LUIS what the intent of the utterance is (if LUIS does not match your intent to the utterance automatically). The example below shows an example utterance:

image

When you type the utterance and click the orange arrow, LUIS will analyze the utterance. In the case above, LUIS automatically matched the utterance to the ChangeRoom intent and also marked the word asterix as an entity. If you hover over the entity, you will see the entity name, in this case room.

You should enter several utterances that make sense for your scenario and fix the intent and entity if needed. After adding several utterances, it is time to train the model with the tiny link in the bottom left of the browser.

After training, it is time to publish the application. You will get a URL that you need to supply in your bot. You can also test some queries from the publish dialog. For instance:

image

If you click the link for the query above, you get a JSON response like below:

image

What you see in the response above, is that LUIS matched the query to intent ChangeRoom and that the room entity is set to Asterix with a score of 0.948. Great!!

Now it is time to use this in your bot. You will need the following code to be able to use the LUIS app from your code and use the LUIS recognizer in the intents:

image

Obviously, you set the URL of the recognizer to the URL you received after publishing the LUIS app. Next, use the LUIS intent (ChangeRoom remember), in your code as follows:

image

In the above code, the important part is extracting the room entity. We make sure that, when a room entity is not found, we give the user a message. Otherwise, we set the room in userData.roomName.

Now it is time to test the code in Slack or another service. Everything was set up in the previous post, so we just need to push the code changes to Azure App Services (git push azure commit). Just for fun, I will show the results in Skype:

image

As you can see, many different phrases can be used. Not all of them were entered in LUIS. Of course, not all phrases will work. It’s clear that new place is Obelix does not work. However, it’s very simple to go back to the LUIS app and add extra utterances, train the model and publish it again.

To sum things up:

  • Regular expressions are great to get started
  • Use LUIS to add natural language processing to your bot in a simple and intuitive way

Bots in an IoT context

At ThingTank (@thingtankBE), we are constantly looking to expose IoT data in different ways. A chat bot can be a great way to ask for device measurements or even instruct devices to perform actions. In this post, I will describe a bot that gets air quality data for a meeting room with Slack.

I chose to write the bot in Node.js for simplicity reasons and publish it to Azure’s App Service. The basics about writing a bot with Node.js can be found in the documentation of Microsoft’s Bot Framework here: https://docs.botframework.com/en-us/node/builder/overview.

Our bot is really simple for now. After getting the basics up and running, the bot can be enhanced with a natural language interface. What we want to do now:

  • Set the room name and save it in the session (UserData)
  • Change the room name and save it in the session
  • Simple help: list the commands you can use
  • Get air quality measurements (a subset)

To achieve the above, you use dialogs, intents and some simple regular expressions. Check out the source code to see how it is done (remember, this is a basic script to get it working at a minimum). The basic logic is as follows:

  • If the intent is unknown, check if the room name is set. If not, switch to the /roomName dialog that asks for the room name and stores it in session.UserData
  • if the intent matches commands, repond with a list of commands
  • if the intent matches change room, switch to the /roomName dialog that asks for the room name
  • if the intent matches air quality, get the measurements for the selected room using the getRoom function in an external module airq.js. Our real-time air quality data comes from a pubsub channel and the getRoom function just retrieves it from there

Writing an intent is very simple. The change room intent for instance:

intents.matches(/^change room/i, [
function (session) {
session.send(“Ok, let’s change the room name…”);
session.beginDialog(‘/roomName’);
},
function(session, results) {
session.send(‘Changed room to %s’, session.userData.roomName);
}
]);

If you look at the source code, you will see we use the Chat Connector. When you are writing your bot in the beginning, I recommend you use the ConsoleConnector instead. You can then simply run your bot with node .js and interact with it from the command line. In our case, we use the ChatConnector so you should use the Bot Framework Channel Emulator from here to interact with and test your bot.

image

To get the emulator working, you need to obtain an App Id and App Password from Microsoft and make sure you use those in both your bot source code and the emulator. In the source code, these two values come from environment variables.Note that for local testing, you can leave these values blank.

Now it’s time to publish the bot on the web so we can register it with Microsoft and then enable it on Slack. To publish the bot, use the instructions here. You will use the Azure CLI and git to make this work so be sure to install both on your machine. After the bot is installed and running on App Service, set the environment variables for App Id and App Password in the website properties. Next, you can test your bot using the Channel Emulator.

Important: when you test your bot in the cloud using the Channel Emulator, be sure to use ngrok as specified here: https://docs.botframework.com/en-us/tools/bot-framework-emulator/#using-the-emulator-with-ngrok-to-interact-with-your-bot-in-the-cloud.

Now we have the bot running, it’s time to register it with Microsoft at https://dev.botframework.com/bots/new. As part of the registration process, you need to supply the URL to your bot in the cloud and obtain a new App Id and App Password. Update the website settings with these new values. After registration, you get:

image

From the above page, you can test your bot and add other channels. One of those channels is Slack. When you add Slack as a channel, you will be guided to create an app in Slack, authenticate, and of course, create a Slack bot. In Slack, you will get something like:

image

To summarize:

  • Creating a simple bot with the Bot Framework is easy; the fun starts when you want to enable things like natural language processing
  • When you deploy you bot to the cloud and want to test it with the Channel Emulator, use ngrok
  • When you want to deploy the bot to Slack, register the bot with Microsoft and simply add Slack as a channel

Azure Automation and PowerApps

One of our applications in our “test playground” is running some code in an Azure WebApp that needs to be restarted once in a while. Rather than trying to fix the underlying problem (no fun in that right?), I decided to create a small mobile app to restart the WebApp when needed. To make it a bit more fun, I used the following “code-less” solutions to make it work:

  • Azure Automation: Graphical Runbook to restart the WebApp; use a Webhook to call the Runbook using a simple HTTP POST
  • Microsoft Flow: calls the Azure Automation Webhook when a control is selected in a PowerApp
  • PowerApp: simple app with a button that calls the above Flow

Azure Automation

I created an Azure Automation account with the option to create a service principal. This results in an account that is added as Contributor for the subscription in which the Azure Automation account was created. This also means that a runbook that uses this account is allowed to restart a WebApp in the same subscription. In my case, the Automation Account and the WebApp are in the same subscription.

Now, before you can use the Restart-AzureRMWebApp cmdlet, you need to add the AzureRM.Websites module to the Automation Account. To do so, navigate to https://www.powershellgallery.com/packages/AzureRM.Websites/1.1.2 and use the Deploy to Azure Automation button. Follow the instructions to add the module to an existing Azure Automation account. When you are finished, click Assets in the Automation Account’s main pane and then click Modules. You should see the following:

 image

Now you can duplicate the AzureAutomationTutorial graphical runbook. In Runbooks, click that Runbook and use the Export option to export the definition to a local file on your computer. Now add a new Runbook and use the Import an existing runbook option together with the export file you just created. Your copied Runbook will look like below:

image

You can remove everything after Login to Azure (that’s the login with the Service Principal that has Contributor rights). Just add the Restart-AzureRMWebApp cmdlet like so:

image

The Restart-AzureRmWebApp only needs two parameters: the name of the WebApp and the resource group of the WebApp. To be able to call the Runbook using HTTP POST, create a Webhook for it. In the properties of the Runbook, click Webhooks and then add a Webhook. Note that there is no authentication for these Webhooks. It’s just a long, unique URL with an expiration date that you set. Make sure you copy the URL before you save the Webhook because it will not be shown later. I created a RunFromPowerApps webhook like so:

image

You can try the Webhook with Postman (https://www.getpostman.com/) or curl and see if a job gets started.

Microsoft Flow

Well, this could not be simpler. Go to https://flow.microsoft.com and login with your credentials (the same credentials for PowerApps, in my case they are Azure AD organization credentials). From My flows create a new flow that looks like this:

image

In the URI, enter the Webhook address from Azure Automation. Save the flow. We will now use this flow in PowerApps.

PowerApps

To create a PowerApp, install the Windows PowerApp application (a Windows Store app) and logon with the same credentials you used with Flow. I created a blank app with a simple button, nothing fancy. With the button selected, click Flows from the Action menu. You should see the flow you created. Just select it to link it to the button selection. You should see something like:

image

Note that it is possible to pass data to the flow as parameters to the Run() command. You could for instance create a list of WebApps to restart and pass the WebApp to be restarted to the Flow and the Webhook.

Test the PowerApp with the play button in the menu bar. When you click Restart, check that the Automation Job fired properly:

image

Now you can run the PowerApp on your iOS or Android device with the PowerApp app for those platforms. Enjoy!

This simple example shows that a lot can be accomplished with tools like Azure Automation, Flow and PowerApps for prototyping or even actual applications with a quick time to value.

Using Azure Cognitive Services from Logic Apps

Azure’s Cognitive Services are very easy to use from within your own applications or more “code-less” solutions such as Azure Logic Apps. In this post, I will show a simple example of a Logic App that does sentiment analysis on incoming tweets. When the sentiment score is very high, an SMS is sent.

To perform sentiment analysis, use the Text Analytics API from Cognitive Services. First, in the Azure Portal, create a Cognitive Services account of type Text Analytics. After that account has been created, you will need the following information to be used in Logic Apps:

  • Endpoint: https://westus.api.cognitive.microsoft.com/text/analytics/v2.0
  • Key: use one of the two secret keys to access the API

If you create a Cognitive Services account in the free tier, you can make 5000 calls per 30 days.

Now create a Logic App in the Azure Portal and go to Triggers and Actions to enter the designer. I will not provide step-by-step details as working with triggers and actions in the graphical designer is very easy. To obtain the results we want, we will have to switch to Code View though.

First, from the Microsoft Managed APIs, add a Twitter trigger. Provide your credentials to Twitter and provide a search term.

Now click the + icon to add an action. To call the Sentiment Analysis API, use the HTTP action and provide the following information (Note: forgetting to specify the specific API to call is a common error; for the URI below also add /sentiment to perform sentiment analysis!!!):

2016-04-22 15_48_34-Logic Apps Designer - Microsoft Azure

Naturally, replace your key with one of the keys obtained from your Cognitive Services account. The body of your HTTP POST can be an array of documents, with each document having an id and the text you want to analyze. In our case, we want to analyze the Tweet text so we use the graphical designer to insert it. In Code View, this will be:

2016-04-22 15_52_59-Logic Apps Designer - Microsoft Azure

Now we want to send an SMS when the sentiment of the Tweet is very positive. The sentiment is expressed as a value between 0 and 1 where 1 is a really, really, really positive tweet.

To send an SMS when the sentiment is above 0.95, first click the + icon and add a condition. The value to evaluate is part of the HTTP body of the previous action. So add that and select greater than or equals and enter 0.95 in the value. Then switch to advanced view to see the expression you built. It will look like:

@greaterOrEquals(body(‘Http’), 0.95)

The above is not going to cut it though since the response body is JSON and the sentiment score needs to be extracted from it. Change the expression to the following:

@greaterOrEquals(float(json(string(body(‘Http’))).documents[0].score), 0.95)

Since the response body is an array of documents and we only have one document, just obtain the score from the first document.

2016-04-22 16_03_05-Logic Apps Designer - Microsoft Azure

Now we can click Add an action in the If yes section to send an SMS. You can use the Twilio Send Message Managed API to do so but you will need an account at Twilio for this to work. Alternatively, you can send an e-mail or just post a result to http://requestb.in. For Twilio, you will end up with something like below. Phone numbers have been blurred to protect the innocent.

2016-04-22 16_08_08-Logic Apps Designer - Microsoft Azure

In the above, we only want to show the score for the Tweet and not the whole body. This can be done in Code View:

In the Send_Message action, change the following:

@{body(‘Http’)} for @{triggerBody()[‘TweetText’]}

to:

@{json(string(body(‘Http’))).documents[0].score} for @{triggerBody()[‘TweetText’]}

Note that changes like the above can make the UI designer unavailable.

When you save this Logic App, incoming tweets containing Azure should be analyzed and you should get SMSs when tweets are very positive. Hey, it’s Azure, why shouldn’t they be? 🙂

You can check if the Logic App is executing correctly from the Operations tile:

2016-04-22 16_23_11-Logic Apps Designer - Microsoft Azure

For a search term like Azure, I recommend to turn off the Logic App if you don’t want to exhaust your 5000 free tier API calls.

Azure Resource Manager REST API from Node

In our video about Fault Domains in Azure IaaSv2, we mentioned Azure Resource Manager and the use of templates to deploy IaaSv2 resources such as virtual machines in a fault domain, a load balancer, a public IP address and more. Azure Resource Manager also has a REST API that can be used from any language. This post discusses the use of the REST API from node.js, including obtaining a token from Azure Active Directory using adal-node.

Before obtaining the token, you need to decide which account to use. In this case I created a service principal in Azure AD to be used as a service account. The process to create a service principal is well documented here and here. I created the service principal using the procedure in the first link, by creating a dummy application in Azure Active Directory. When you create such a dummy application you will obtain two of several things you need to obtain the token:

  • The client ID (a GUID) which basically serves as the user name
  • A generated key with a validity of 1 or 2 years that servers as the password

Other information you will need is the tenant ID (also a GUID) which is used to construct the authorization URL. To actually obtain the token using ADAL (Active Directory Authentication Library) for node.js with adal-node, take a look at adal-node on npm, in the server to server with client credentials sample. There are some issues with that sample code, so I modified it as follows:

var adal=require('adal-node');
var AuthenticationContext= adal.AuthenticationContext;
var tenantID="TenantIDGUID";
var clientID="ClientIDGUID";
var resource="https://management.azure.com/";
var authURL="https://login.windows.net/" + tenantID;
var secret="ClientSecret";
var context=new AuthenticationContext(authURL);
context.acquireTokenWithClientCredentials(resource, clientID, secret, function(err,tokenResponse) { }

Some things to note:

Once you obtain the token, you will get a tokenResponse in the callback function. The tokenResponse contains:

{ tokenType: 'Bearer',
expiresIn: 3600,
expiresOn: Fri Jun 05 2015 10:46:48 GMT+0200 (Romance Daylight Time),
resource: 'https://management.azure.com/',
accessToken: 'long, long token',
isMRRT: true,
_clientId: 'clientID',
_authority: 'https://login.windows.net/tenantID' }

So basically, you are getting an OAuth bearer token you can use in a call to a Web API that expects such a token. The Azure Resource Manager REST APIs will be called with this token.

To actually make the API request, I do the following:

  • Use the restler module: see https://www.npmjs.com/package/restler
  • Get the access token from the token response above: the token is obtained with tokenResponse[‘accessToken’]
  • Build the request URL, in this case to list all resources in my subscription. To interactively find out the kind of requests you can make, use Resource Explorer
  • Make the REST call with restler, passing the accessToken

The code looks like this where you replace {yourSubID} with your Azure subscription ID:

var rest=require('restler');
authHeader = tokenResponse['accessToken'];
requestURL="https://management.azure.com/subscriptions/{yourSubID}/resources?api-version=2015-01-01";
rest.get(requestURL, {accessToken:authHeader}).on('complete',function(result) {
console.log(result); });

If you go to https://github.com/gbaeke/armnode you will find the full samples to get you started. Hope this is helpful. Leave a comment if you have further questions.

%d bloggers like this: