Easy Dynamics 365/AX Blockchain Integration

This post continues to explore Blockchain integration into Microsoft Dynamics 365 for Finance and Operations (AX). I’ve seen examples where developers did integration using the MetaMask Chrome extension, however I want something that looks and feels like pure AX.

For this post I will be using Xalentis Fusion which provides seamless Blockchain integration, whereby Blockchain I refer to Ethereum. I don’t see much use for Bitcoin, and apart from hundreds of other altcoins available, I see more enterprise-level movement towards Ethereum or its variants, including JP Morgans’ Quorum or Microsoft “Project Bletchley”.

Xalentis Fusion works by detecting new transactions in an Ethereum Blockchain and allows filtering to take place across those. Once a filter detects your specific requirements, it can fire off any number of associated rules, written in simple script. Fusion also includes a growing API allowing REST-based integration with the outside world, which is what we will be using.

Fusion provides a Transact API method allowing transactions to be made via a REST call. We can do this ourselves easily as well, but since we’ll be using Fusion for more than transacting (later on in this post) I figured I’ll just stick with it.

We’ll keep it very basic, and create a simple form accepting a number of parameters that we will use to perform a transaction. Our form design is shown below.

BeforeTransact

We’ve added fields for Node, Sender, Recipient, Sender’s account Password, and the amount of Wei to send. Depending on the Ethereum network you are connecting to, adjust the Node value accordingly, or simply hardcode it and remove the field. We are using the Fusion Test Net so that is shown. I’ve created two addresses in the Test Net, also shown in the form design, and loaded the first with some Ether. Perhaps customers want to trade in Dollars, so you can add code to convert Dollars entered into Wei or whatever token is in use. We’ll stick with Wei for now.

Let’s submit this transaction.

AfterTransact

As you can see, the transaction has been submitted to the Blockchain and an Infolog displayed showing success. The X++ code is shown below, including the form class and a utility class that performs our REST calls to Fusion. I’ve added a TransactionRequest class as the POST action we are performing requires JSON being passed, and wrapped the class members with the DataContract attributes to enable easy serialization. This particular POST call accepts the full JSON as part of the POST URL, wrapped as Base64, and that is done in the utility class. The body is required, so we set the content-length to 0.

[DataContractAttribute]
class TransactRequestClass
{
    str addressFrom;
    str addressTo;
    str node;
    str password;
    str wei;

    [DataMemberAttribute]
    public str AddressFrom(str _addressFrom = addressFrom)
    {
        addressFrom = _addressFrom;
        return addressFrom;
    }

    [DataMemberAttribute]
    public str AddressTo(str _addressTo = addressTo)
    {
        addressTo = _addressTo;
        return addressTo;
    }

    [DataMemberAttribute]
    public str Node(str _node = node)
    {
        node = _node;
        return node;
    }

    [DataMemberAttribute]
    public str Password(str _password = password)
    {
        password = _password;
        return password;
    }

    [DataMemberAttribute]
    public str Wei(str _wei = wei)
    {
        wei = _wei;
        return wei;
    }
}

class FusionUtilityClass
{
    public static str Transact(str addressFrom, str addressTo, str password, str node, str wei)
    {
        System.Net.WebClient webClient;
        System.Text.UTF8Encoding encoder;
        System.Text.UnicodeEncoding decoder;
        System.IO.Stream s;
        System.IO.StreamReader sr;
        System.Net.HttpWebRequest myRequest;
       
        try
        {
            TransactRequestClass request = new TransactRequestClass();
            request.AddressFrom(addressFrom);
            request.AddressTo(addressTo);
            request.Node(node);
            request.Password(password);
            request.Wei(wei);

            encoder = new System.Text.UTF8Encoding();
            str json = FormJsonSerializer::serializeClass(request);
            System.Byte[] encodedBytes = encoder.GetBytes(json);
            str encoded64 = System.Convert::ToBase64String(encodedBytes);
 
            str url = "http://fusionapi.azurewebsites.net/api/transact?bodyJson=" + encoded64;
            myRequest = System.Net.WebRequest::Create(url);
            myRequest.Method = "POST";
            myRequest.Timeout = 30000;
            myRequest.ContentLength = 0;

            System.Net.WebHeaderCollection headers = myRequest.Headers;
            headers.Add("API_KEY", "your fusion api key");

            s = myRequest.GetResponse().GetResponseStream();
            sr = new System.IO.StreamReader(s);
            str txnHash = sr.ReadToEnd();
            s.Close();
            sr.Close();
            return txnHash;
        }
        catch (Exception::Error)
        {
        }
        return "";
    }
}

class XalentisTestFormClass
{
    
    [FormControlEventHandler(formControlStr(XalentisTestForm, FormButtonControl1), FormControlEventType::Clicked)]
    public static void FormButtonControl1_OnClicked(FormControl sender, FormControlEventArgs e)
    {
        FormStringControl nodeControl = sender.formRun().control(sender.formRun().controlId("FormStringControl1"));
        FormStringControl addressSenderControl = sender.formRun().control(sender.formRun().controlId("FormStringControl2"));
        FormStringControl addressRecipientControl = sender.formRun().control(sender.formRun().controlId("FormStringControl3"));
        FormStringControl passwordControl = sender.formRun().control(sender.formRun().controlId("FormStringControl4"));
        FormStringControl weiControl = sender.formRun().control(sender.formRun().controlId("FormStringControl5"));

        str addressFrom = addressSenderControl.Text();
        str node = nodeControl.Text();
        str addressTo = addressRecipientControl.Text();
        str password = passwordControl.Text();
        str wei = weiControl.Text();

        str txnHash = FusionUtilityClass::Transact(addressFrom, addressTo, Password, node, wei);
        //todo: store txnHash for history purposes.

        info("Transaction Posted");
    }
}

That works pretty well, but users don’t understand Blockchain addresses, and it would be painful to maintain that somewhere in notepad or Excel to copy and paste each time a transaction is made. Luckily Fusion provides an Account Mapping facility, which is a customer-specific key/value table mapping Blockchain addresses to friendly names, or account numbers the rest of us can readily understand.

So instead of entering address for Sender and Recipient, let’s modify our form as shown below. We can use drop-downs to pull up a list of known accounts, or use an API call to Fusion to return a full list of mapped accounts which we can then allow users to select. I’ll keep it simple with a text field. Here we’ve entered two known friendly account names we can read and verify. These could come from your chart of accounts as well, whatever works best in your scenario. As long as the display text maps to an address in Fusion, it can be resolved.

BeforeTransact2

I’ve modified our form class and utility class to add two additional API calls to Fusion to resolve the friendly names to Ethereum addresses as shown in the code below. We simply make a GET call to Fusion passing across the friendly name, and Fusion will perform the lookup, returning the proper Ethereum address we need to use when performing the transaction. The updated code is shown below.

class XalentisTestFormClass
{
    
    [FormControlEventHandler(formControlStr(XalentisTestForm, FormButtonControl1), FormControlEventType::Clicked)]
    public static void FormButtonControl1_OnClicked(FormControl sender, FormControlEventArgs e)
    {
        FormStringControl addressSenderControl = sender.formRun().control(sender.formRun().controlId("FormStringControl2"));
        FormStringControl addressRecipientControl = sender.formRun().control(sender.formRun().controlId("FormStringControl3"));
        FormStringControl passwordControl = sender.formRun().control(sender.formRun().controlId("FormStringControl4"));
        FormStringControl weiControl = sender.formRun().control(sender.formRun().controlId("FormStringControl5"));

        str addressFrom = addressSenderControl.Text();
        str addressTo = addressRecipientControl.Text();
        str password = passwordControl.Text();
        str wei = weiControl.Text();

        str txnHash = FusionUtilityClass::Transact(addressFrom, addressTo, Password, wei);
        //todo: store txnHash for history purposes.

        info("Transaction Posted");
    }
}

class FusionUtilityClass
{
    public static str Transact(str accountFrom, str accountTo, str password, str wei)
    {
        System.Net.WebClient webClient;
        System.Text.UTF8Encoding encoder;
        System.Text.UnicodeEncoding decoder;
        System.IO.Stream s;
        System.IO.StreamReader sr;
        System.Net.HttpWebRequest myRequest;
       
        try
        {
            str addressFrom;
            str addressTo;

            str url = "http://fusionapi.azurewebsites.net/api/address/" + strReplace(accountFrom, " ","%20");
            myRequest = System.Net.WebRequest::Create(url);
            myRequest.Method = "GET";
            myRequest.Timeout = 30000;
            System.Net.WebHeaderCollection headers = myRequest.Headers;
            headers.Add("API_KEY", your fusion api key);
            s = myRequest.GetResponse().GetResponseStream();
            sr = new System.IO.StreamReader(s);
            addressFrom = sr.ReadToEnd();
            s.Close();
            sr.Close();

            url = "http://fusionapi.azurewebsites.net/api/address/" + strReplace(accountTo, " ","%20");
            myRequest = System.Net.WebRequest::Create(url);
            myRequest.Method = "GET";
            myRequest.Timeout = 30000;
            headers = myRequest.Headers;
            headers.Add("API_KEY", "your fusion api key");
            s = myRequest.GetResponse().GetResponseStream();
            sr = new System.IO.StreamReader(s);
            addressTo = sr.ReadToEnd();
            s.Close();
            sr.Close();

            TransactRequestClass request = new TransactRequestClass();
            request.AddressFrom(strReplace(addressFrom,"\"",""));
            request.AddressTo(strReplace(addressTo,"\"",""));
            request.Node("http://xaleth4kq.eastus.cloudapp.azure.com:8545"); // hardcoded now
            request.Password(password);
            request.Wei(wei);
            encoder = new System.Text.UTF8Encoding();
            str json = FormJsonSerializer::serializeClass(request);
            System.Byte[] encodedBytes = encoder.GetBytes(json);
            str encoded64 = System.Convert::ToBase64String(encodedBytes);
            url = "http://fusionapi.azurewebsites.net/api/transact?bodyJson=" + encoded64;
            myRequest = System.Net.WebRequest::Create(url);
            myRequest.Method = "POST";
            myRequest.Timeout = 30000;
            myRequest.ContentLength = 0;
            headers = myRequest.Headers;
            headers.Add("API_KEY", "your fusion api key");
            s = myRequest.GetResponse().GetResponseStream();
            sr = new System.IO.StreamReader(s);
            str txnHash = sr.ReadToEnd();
            s.Close();
            sr.Close();
            return txnHash;
        }
        catch (Exception::Error)
        {
        }
        return "";
    }
}

We’ll submit this transaction, and as shown we’ve got success.

AfterTransact2

I hope this was helpful. One final item to note is using Wei, which is a BigInteger. I’ve used strings to remove the need for dealing with BigInteger types in X++.

 

Advertisements

GPS, IoT, Blockchain Integration to ERP

I’ve read a number of articles discussing how Blockchain could have a significant impact on Trade & Logistics, especially item tracking. Granted, Blockchain is not a requirement for shipment tracking, but it does deliver a number of benefits through being a shared, secure ledger that, depending on the network, could provide an automatic openness almost immediately. That is a vast improvement over building a custom customer and partner portal to query legacy backend systems.

Of course, there remains the problem of now having to integrate Blockchain into your legacy ERP system, a whole different level of headache. So, in this post I’m going to do a simple POC to simulate how easy, or hard, it would be to build an item tracking service using Ethereum Blockchain, add to that GPS tracking with temperature and humidity monitoring, and get that to your ERP system, in this case Microsoft Dynamics 365. I want to achieve that without modifying the ERP system in any way, by using Microsoft Flow, a PowerApp and Microsoft Common Data Service. The idea is that end users, customers or partners can use the PowerApp to monitor shipments and climate conditions in real-time. Supply-chain visibility every step of the way, basically.

To start, I built a simple IoT monitoring device around the Adafruit Huzzah. I’ll be using WiFi here, making a wild assumption that WiFi is available wherever this device goes. In the real world, GPRS or Loran might be more suitable, but I don’t have that available in my toolkit just yet and besides, this is an experiment only. I’ve added a low-cost GPS, DHT11 temperature and humidity sensor, and an LCD screen to show me what is happening without requiring connecting to my laptop via the serial interface. The basic IoT device is shown below, with GPS and DHT-11 working and transmitting data.

Circuit

The C code for the IoT device is shown below. I do a POST to my Ethereum network of choice with hardcoded addresses, and embed the GPS coordinates and DHT11 state into the data portion of the Ethereum transaction. Addressing and data is entirely up to you; perhaps instead of hardcoding, this can all be read off an SD card.

#include <DHT.h>
#include "TinyGPS++.h"
#include <SoftwareSerial.h>
#include <Adafruit_SSD1306.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include "Adafruit_GFX.h"
#include "Adafruit_SSD1306.h"

#define SSID "WiFiSSID" 
#define PASS "mypassword" 
#define OLED_RESET LED_BUILTIN
#define DHTPIN 12
#define DHTTYPE DHT11

TinyGPSPlus gps;
DHT dht(DHTPIN, DHTTYPE);
Adafruit_SSD1306 display(OLED_RESET);
SoftwareSerial mySerial(13, 15);

const char *gpsStream =
  "$GPRMC,045103.000,A,3014.1984,N,09749.2872,W,0.67,161.46,030913,,,A*7C\r\n"
  "$GPGGA,045104.000,3014.1985,N,09749.2873,W,1,09,1.2,211.6,M,-22.5,M,,0000*62\r\n"
  "$GPRMC,045200.000,A,3014.3820,N,09748.9514,W,36.88,65.02,030913,,,A*77\r\n"
  "$GPGGA,045201.000,3014.3864,N,09748.9411,W,1,10,1.2,200.8,M,-22.5,M,,0000*6C\r\n"
  "$GPRMC,045251.000,A,3014.4275,N,09749.0626,W,0.51,217.94,030913,,,A*7D\r\n"
  "$GPGGA,045252.000,3014.4273,N,09749.0628,W,1,09,1.3,206.9,M,-22.5,M,,0000*6F\r\n";

void setup() {
  Serial.begin(9600);
  dht.begin();
  display.setCursor(0,0);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  display.clearDisplay();
  display.display();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.println("Connecting");
  display.println("to");
  display.println("WiFi...");
  display.display();

  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  } 
  display.clearDisplay();
  display.display();
  display.setCursor(0,0);
  display.println("EtherGPS");
  display.println("www.xalentis.com");
  display.display();
  mySerial.begin(38400); // GPS
  delay(5000); // warm up GPS 
  display.clearDisplay();
  display.display();
  display.setCursor(0,0);
  display.println("Scanning...");
  display.display();
}

void loop() 
{
  while (*gpsStream)
    if (gps.encode(*gpsStream++))
      updateInfo();
}

void updateInfo()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (gps.location.isValid())
  {
    display.clearDisplay();
    display.display();
    display.setCursor(0,0);
    display.println("Temp:" + String(t));
    display.println("Hum:" + String(h));
    display.println("Lat:" + String(gps.location.lat()));
    display.println("Lon:" + String(gps.location.lng()));
    display.display();

    String data = "0x";
    String deviceSerial = "3132333435"; // 12345 in HEX
    data = data + deviceSerial + "2c"; // comma
    
    String temp = String(t);
    String hum = String(h);
    String lat = String(gps.location.lat());
    String lon = String(gps.location.lng());
    byte buffer[255]={0};
    
    //temp
    temp.getBytes(buffer, 255, 0);
    for (int i=0;i<=temp.length()-1;i++)
    {
      data = data + String((int)buffer[i], HEX);
    }
    data = data + deviceSerial + "2c"; // comma

    //hum
    hum.getBytes(buffer, 255, 0);
    for (int i=0;i<=hum.length()-1;i++)
    {
      data = data + String((int)buffer[i], HEX);
    }
    data = data + deviceSerial + "2c"; // comma

    //latitude
    lat.getBytes(buffer, 255, 0);
    for (int i=0;i<=lat.length()-1;i++)
    {
      data = data + String((int)buffer[i], HEX);
    }
    data = data + deviceSerial + "2c"; // comma

    //longitude
    lon.getBytes(buffer, 255, 0);
    for (int i=0;i<=lon.length()-1;i++)
    {
      data = data + String((int)buffer[i], HEX);
    }

    // build up our Ethereum transaction
    StaticJsonBuffer<1000> JSONbufferTwo;  
    JsonObject& uploadJSON = JSONbufferTwo.createObject(); 
    uploadJSON["jsonrpc"] = "2.0";
    uploadJSON["method"] = "personal_sendTransaction";      
    JsonArray&  uploadQueryParams = uploadJSON.createNestedArray("params");
    JsonObject& callTxParams = JSONbufferTwo.createObject();
    callTxParams["from"] = "0x27f6f763ae5c52721db57c4423c298a78de1f22a";
    callTxParams["to"] = "0xcaade3aa018d57d808fceb16824c47dfd206484c";
    callTxParams["value"] = "0x6FC23AC00"; //hex value 30 Gwei 
    callTxParams["gas"] = "0x30D40"; //hex value for 200000 -high gas limit for good measure          
    callTxParams["gasPrice"] = "0x6FC23AC00"; //hex value 30 Gwei gasprice 21gwei is typical
    callTxParams["data"] = data; // device,tem,hum,lat,long
    uploadQueryParams.add(callTxParams);
    uploadQueryParams.add("myetherpassword");
    uploadJSON["id"] = 1;
    String uploadString;
    uploadJSON.printTo(uploadString);
    callGeth(uploadString); // send for mining
  }
}

String callGeth(String inputJSON) 
{
  HTTPClient http;
  http.begin("http://13.72.73.21:8545/");
  http.addHeader("Content-Type", "application/json");
  int httpCode = http.POST(inputJSON);
  String JSONResult = http.getString(); // contains Txn
  http.end();
  return JSONResult;
}

At this point the transactions are flowing to the Blockchain network and that is great, but we need to be able to monitor the Blockchain for transactions we are interested in, so we can pull that off the Blockchain and into an ERP system, right?

The easiest way to do that is to use Xalentis Fusion. Sign up for a trial account at www.xalentis.com or grab it via Microsoft AppSource. Once signed-up, and logged-in, you’ll end up at the main dashboard as shown below.

xalgps1

Follow the Getting Started tutorial which takes about 10 minutes to create a pair of accounts and top them up with credit as required. The Ethereum network being used is a canned version of Microsoft’s Project Bletchley, so it’s not on the main or test Ethereum networks and can be used without spending any real Ether. You can deploy your own network and use that within the Fusion platform as well, by creating transaction filters pointing to your own deployed RPC node. Make sure your RPC node is visibly outside your firewall, obviously.

The following image shows us having created a transaction filter to monitor the default RPC node at http://xaleth4kq.eastus.cloudapp.azure.com, for any transactions made from the address 0x27f6f763ae5c52721db57c4423c298a78de1f22a. Filters can be created to match any transaction, from any address, or even containing a specific string value in the data portion. This is useful when the address(es) constantly change, while a specific identifier is passed within the data portion, perhaps a Device ID, Company ID or Serial Number of sorts – anything static.

xalgps2

Filters execute rules containing a simple compiled script, and this is where actions are performed on matching transactions. The script below has been added as a rule for our filter.

xalgps3

The rule simply extracts whatever is in the transaction data field, parses that and constructs a JSON packet. This packet will be passed to a Microsoft Flow we will be creating.

We’ll need a place to store our data. Using Flow, we could push directly into Dynamics 365, but since we don’t want to directly modify our ERP by adding a new table, I’ve chosen to use Microsoft Common Data Service as a temporary store instead. The image below shows the new Entity we’ve created with fields for Device, Temperature, Humidity, Longitude and Latitude.

GPS_CDS

Using Microsoft Flow, we’ll first use the Request action to accept an incoming POST request (from our Rule). Next, we’ll take the body of the POST request, parse it, and store the fields into our new CDS Entity. The Flow design is shown below.

GPS_Flow

Use the generated URL from the Flow to update the Rule – the final line calling Flow requires that URL.

Run the Flow, and then power up the IoT device to start submitting GPS and climate information into the Blockchain network. As transactions are mined into new blocks, Fusion will detect the transaction matching our Filter, and execute the associated Rule. The Rule in turn will parse the transaction data field, parse the content, construct it as JSON, and call our Flow with that body content. When the Flow executes, the JSON will be parsed and the data elements inserted as a new record into the CDS, as shown below.

GPS_DataCDS

We can use the data now stored in the CDS to create a PowerApp that displays that information on a Google Map. The PowerApp shown is fairly basic, but with enough time, patience and data this can be turned into something much more interactive, and it is real-time, a vast improvement over building a customer tracking portal from scratch, getting updates only when items are scanned with a barcode or RFID reader.

GPS_Map

Apart from our Rule script, we’ve used virtually no coding, and we’ve not modified our production ERP system in any way. As a bonus, we also have a mobile app that customers and partners can use!

RFID + IoT + Ethereum Blockchain

This is a very quick post, mostly code-only, showing how to read RFID tags on say an assembly line, process those using a WiFi IoT device (Adafruit Huzzah), extract the product serial number from the RFID tag and send that as part of a transaction to an Ethereum Blockchain.

I am using a MiFare RFID card reader, but you would want to use a long-range reader that supports low-cost sticker tags. POSTing the transaction to the blockchain takes a second or two, so don’t expect to scan 100 products/second flying past the reader and manage to submit those as transactions.

URL’s and codes are hard-baked, so consider how you want to post the transaction. I use static Ethereum addresses and stick the product ID in the data portion, you might want to read that from the RFID tags as well.

Once your product ID is in the blockchain, you might want to move that to your ERP system, or even a cool PowerApp or something. Unless you want to code X++ and mess around with your production systems, I suggest using Xalentis Fusion instead, to enable code-free integration between Ethereum and Microsoft Dynamics 365 for Finance and Operations. It also supports SMS, Email messaging, Service Bus messaging, Flow, PowerApps and Common Data Service.

Enjoy.

#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
 
#define RST_PIN         15
#define SS_PIN          2
#define SSID            "mywifiSSID" 
#define PASS            "password" 
 
MFRC522 mfrc522(SS_PIN, RST_PIN);
 
void setup() {
  Serial1.begin(115200);
  while(!Serial1){}
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
}
 
void loop()
{
  // Using MiFare card reader here, for production use sticker tags and high-speed reader instead
  MFRC522::MIFARE_Key key; // default to FFFFFFFFFFFF
  key.keyByte[0] = 0xFF;
  key.keyByte[1] = 0xFF;
  key.keyByte[2] = 0xFF;
  key.keyByte[3] = 0xFF;
  key.keyByte[4] = 0xFF;
  key.keyByte[5] = 0xFF;
 
  // Loop until RFID tag is presented 
  if (!mfrc522.PICC_IsNewCardPresent()) return;
  if (!mfrc522.PICC_ReadCardSerial()) return;

  byte readbuffer1[18];
  byte readbuffer2[18];
  byte block;
  MFRC522::StatusCode status;
  byte len;
  byte sizeread = sizeof(readbuffer1);
  block = 0;
  
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    return;
  }
  else
  {
    for (int i = 0; i < 18; i++)
    {
      readbuffer1[i] = 0x00;
      readbuffer2[i] = 0x00;
    }
    // read product ID from RFID tag
    status = mfrc522.MIFARE_Read(1, readbuffer1, &sizeread);
    if (status != MFRC522::STATUS_OK)
    {
      return;
    }
    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();
  }
 
  // convert product ID from RFID tag to hex string
  String data = "0x";
  for (int j=0; j<18;j++)
  {
    if (readbuffer1[j]=='\0') break;
    data = data + String(readbuffer1[j], HEX);
  }

  // build up our Ethereum transaction
  StaticJsonBuffer<1000> JSONbufferTwo;  
  JsonObject& uploadJSON = JSONbufferTwo.createObject(); 
  uploadJSON["jsonrpc"] = "2.0";
  uploadJSON["method"] = "personal_sendTransaction";      
  JsonArray&  uploadQueryParams = uploadJSON.createNestedArray("params");
  JsonObject& callTxParams = JSONbufferTwo.createObject();
  callTxParams["from"] = "0x27f6f763ae5c52721db57c4423c298a78de1f22a";
  callTxParams["to"] = "0xcaade3aa018d57d808fceb16824c47dfd206484c";
  callTxParams["value"] = "0x6FC23AC00"; //hex value 30 Gwei 
  callTxParams["gas"] = "0x30D40"; //hex value for 200000 -high gas limit for good measure          
  callTxParams["gasPrice"] = "0x6FC23AC00"; //hex value 30 Gwei gasprice 21gwei is typical
  callTxParams["data"] = data;
  uploadQueryParams.add(callTxParams);
  uploadQueryParams.add("bigsecretaccountpassword");
  uploadJSON["id"] = 1;
  String uploadString;
  uploadJSON.printTo(uploadString);
  callGeth(uploadString); // send for mining
}

String callGeth(String inputJSON) // thanks to https://github.com/gusgorman402
{
  HTTPClient http;
  http.begin("http://your RPC address here:8545/");
  http.addHeader("Content-Type", "application/json");
  int httpCode = http.POST(inputJSON);
  String JSONResult = http.getString(); // contains Txn
  http.end();
  return JSONResult;
}

 

JSON to X++ Classes the easy way

Calling API’s that expect and return JSON from within X++ has become fairly routine and simple with the release of Dynamics 365 for Operations. Recently we moved a module written in C# that resided as external DLL’s within AX, to an Azure-based API that talks JSON via REST. Calling the API was fairly straightforward but manipulating the JSON between X++ and the API seemed like a lot of manual work requiring get/set operations for each property.

Assume you have a class in X++ containing a number of properties, similar to this one below.

class PFLPayrollResultsRequest
{
    str customerID;
    str appKey;
    str legalEntity;
    str payRunNumber;
 
    public str CustomerID(str _customerID = customerID)
    {
        customerID = _customerID;
        return customerID;
    }
 
    public str AppKey(str _appKey = appKey)
    {
        appKey = _appKey;
        return appKey;
    }
 
    public str LegalEntity(str _legalEntity = legalEntity)
    {
        legalEntity = _legalEntity;
        return legalEntity;
    }
 
    public str PayRunNumber(str _payRunNumber = payRunNumber)
    {
        payRunNumber = _payRunNumber;
        return payRunNumber;
    }
}

 

This class might be used for data retrieval and storage within X++, and let’s assume at some point we want to send the state to an external API using JSON. At first glance it seems that we would have to access each individual property and retrieve it from the class, build the JSON string up from that, and then submit that across the wire. The NewtonSoft library gives us a fair bit of methods to work with, however that is external to X++, and NewtonSoft does not understand X++ classes. When the API call returns, it might contain thousands of records which then have to be loaded into X++ classes, property by property.

The solution lies in using the FormJsonSerializer class. Simply decorate your X++ class with a number of attributes (DataContractAttribute, DataMemberAttribute) as shown below:

[DataContractAttribute]
class PFLPayrollResultsRequest
{
    str customerID;
    str appKey;
    str legalEntity;
    str payRunNumber;
 
    [DataMemberAttribute]
    public str CustomerID(str _customerID = customerID)
    {
        customerID = _customerID;
        return customerID;
    }
 
    [DataMemberAttribute]
    public str AppKey(str _appKey = appKey)
    {
        appKey = _appKey;
        return appKey;
    }
 
    [DataMemberAttribute]
    public str LegalEntity(str _legalEntity = legalEntity)
    {
        legalEntity = _legalEntity;
        return legalEntity;
    }
 
    [DataMemberAttribute]
    public str PayRunNumber(str _payRunNumber = payRunNumber)
    {
        payRunNumber = _payRunNumber;
        return payRunNumber;
    }
}

 

Now we can serialize this class to a JSON string for transfer, and also load an X++ class with the JSON result set returned. A quick example is shown below, in X++.

    public static void GetTempTrans()
    {
        System.Net.WebClient webClient;
        System.Text.UTF8Encoding encoder;
       
        try
        {
            PFLPayrollResultsRequest request = new PFLPayrollResultsRequest(); - this is the request class we convert to JSON and send to the API
            request.AppKey("232B8D90-7C3BF92DEA9F");
            request.CustomerID("27C2C06F8C2737");
            request.LegalEntity("AUP");
            request.PayRunNumber("12345");
 
            webClient = new System.Net.WebClient();
            System.Net.WebHeaderCollection headers = webClient.Headers;
            headers.Add("Content-Type", "application/json");
            encoder = new System.Text.UTF8Encoding();
            str json = FormJsonSerializer::serializeClass(request);// use this AX helper class (FormJsonSerializer) to convert to JSON here
            System.Byte[] encodedBytes = encoder.GetBytes(json);
            System.Byte[] response = webClient.UploadData("https://www.myapi.com/api/Engine/Post/TemporaryResults", encodedBytes);
            str jsonResponse = webClient.Encoding.GetString(response); 
            // deserialize result returned from API here using FormJsonSerializer::deserializeClass();
        }
        catch
        {
        } 
    }

API to CDM using Flow in a PowerApp

There have been some interesting developments since late last year around Microsoft Dynamics with the addition of Flow, PowerApps and the Common Data Model. It has been hard for ISV’s to keep up to date, considering we’ve gone from “AX 7” to Microsoft Dynamics 365 for Operations and in the future the introduction of the Common Data Model, bound to shake things up even more, all in the space of less than twelve months.

As an ISV with a payroll module that has been tightly embedded into AX since 2009 we’ve not been immune to these changes and considerable thought and preparation has gone into future-proofing our product. As our payroll engine have always been .NET based, this has allowed us some flexibility in terms of portability. Dynamics, or AX, has always been just a UI for us, something that facilitates interaction between the user and our payroll engine, while utilizing the storage of AX in the same vein.

This all changed over December last year when we decoupled our engine from AX and moved it to Azure as a proper App Service with an API, moving storage from AX to Azure Table Storage at the same time, delivering flexibility, scalability and a fourfold performance increase over our standard “fully embedded” AX version. In the future, Dynamics properly becomes no more than a UI for us, and our interaction with Dynamics will be via the Common Data Model to retrieve and store key data elements (mostly HCM fields) as we need it during processing.

To that end, it is important to ensure our API-based product is architected well enough to take advantage of, and provide services via PowerApps, Power BI and is able to be used in Microsoft Flow. The steps below is very much exploratory, as this is my first experience in building a PowerApp and using Flow, so don’t expect miracles in this post.

So the aim here is to utilize our payroll engine via its API hosted in Azure to fetch the results of a pay run, and then populate that into a custom entity in CDM, potentially then being used in Dynamics in the future. First things first, let’s get the call to the API worked out.

We’ll start with a basic Flow which calls the API via HTTP, retrieves the pay run results, parses the resulting JSON and then save that into a CSV somewhere in OneDrive for Business. All of this is possible using Flow using the fairly simple (if somewhat buggy) web-based UI.

The overall result is shown below and we’ll go into each step in more detail this post.

FlowDesign

So here we have an HTTP service, posting its results to a JSON parser, which in turn transfers the results to a CSV generator, ultimately ending up as a file in the OneDrive for Business service right at the end.

FlowDesign1

The HTTP service requires a number of parameters. First we are doing a POST call, and we’ll enter the URL and method for that call. No headers are required, but our API expects a number of parameters to be supplied via the body, which we’ll hardcode for now and paste as JSON. These include the CustomerID, APP Key, Legal Entity and Pay Run.

FlowDesign1_1

For the JSON parser we need to specify where the JSON is coming from, which is of course the body of the result from our HTTP call, so we will select that.  Now things unfortunately get a lot more painful. We need to supply the JSON schema for the result being returned so that the JSON parser can parse it all properly. So if you are building an API, make sure you have all your specifications ready and sorted.

At this point I’ll go back to the API drawing board and fiddle around to extract the schema by pasting an example result. Flow is smart enough to figure out the schema for us from that. Nice. To create a CSV file from that we simply select that output in the CSV service as shown.

FlowDesign2

The rest is easy, just select the OneDrive for Business service as the next connection, sign-in to supply credentials and specific the folder, file name and the input, which is of course the CSV we created in the previous step.

FlowDesignRun

Let’s go ahead and save our changes, then run this Flow as shown.

FileCreated

Our OneDrive for Business folder shows the file created, and we can open that in Excel to view the results which is spot-on. So that works.

ExcelView

This is all fine, but we really need this data in a CDM entity not a CSV file. So let’s remove the CSV and OneDrive for Business services. Next, create a new custom entity in CDM as shown below.

FlowEntity

Unfortunately, we have to enter each field manually, there is no easy way to import a schema that I can see. It’s simple enough though, we can use the Excel we generated previously and just copy the headers in as field names. We’ll save this new entity as “XalariTrans” and return to fixing up our Flow.

FlowCreateRecordDesign

Drop in a Create Record Service as shown, and supply the database and entity. Each field in the entity needs to be mapped to an element extracted from the JSON in the previous step, and this is made easy with Flow.

Let’s run this. Notice that Flow automatically added a loop around the Create Record service to ensure that all records are inserted automatically.

ParamFinalOutput

The run was successful and we can go back to our custom entity and verify that the data was transferred from the API to CDM as shown below.

FlowDataView

This approach while working, is rather lame. What we really want is to build a set of API calls that can be reused as connections, and for that we need to create a Custom Connection. So under Connections click Custom, and then click Add. We’ll enter a name, description and upload an icon. We also need to provide a Swagger file which is essentially an API specification that details the inputs, outputs, schema, URL, and much more.

Creating a Swagger file from scratch is a study in frustration for first-timers. I ended up using several tools to generate and edit the proper Swagger JSON file and even then, had complaints when loading it into Flow.

So, with the Swagger specification created and selected, we can add this new Connection Service.

Connections

We can now update our Flow by removing the HTTP service and replacing that with our new Connection service as shown below.

ConnectionExecute

This runs fine, however recall that our API calls require parameters in the body of the POST call, including Customer ID and App Key. For now we’ve pasted the body JSON into the Connection as a parameter but that is rather useless, as these are customer-specific. So we need to retrieve these as settings from our PowerApp somehow, pass that to Flow during execution, which in turn will stick that in the body of the POST call. The way to achieve this is to modify our Swagger file for our Custom Connection as shown below:

Swagger

With that done we can update the Custom Connection. When we edit our Flow, notice how those parameters are now available in the Connection as shown below.

AppParamsFlow

As these will come from our PowerApp, we can specify that for each required input parameter. Notice it is in purple, matching the PowerApp at the top to indicate that expectation. So it knows those values need to be provided by the PowerApp. Nice.

So let’s use the PowerApp designer to build a PowerApp that will use our Flow. You’ll need to download the desktop version if you want to call a Flow from within your PowerApp, which is not supported in the online version.

We’ll build a simple app by dropping two text boxes on the form with a single button we rename to “Transfer”. We’ll set the text for the boxes to “DME” and “1” to correspond to the LegalEntity and PayRun parameters we require. This can of course be left blank and edited by end users.

AppParameters

Select our Flow under the Actions tab. This links the Flow with our button’s OnSelect event, the result being when the button is clicked, the Flow will be called. Notice at the top we are passing our parameters to the Flow, being the Customer ID, APP Key, and the contents of the two text boxes, allowing users to change the Legal Entity and Pay Run by editing the values in the text boxes.

AppFinal

That’s it, we can run the PowerApp and hit the Transfer button. After a second or two we can return to our Entity in CDM and view the Data tab, showing that the records was transferred successfully.

A simple exercise indeed, we are still miles from having a professional PowerApp but we’ve managed to figure out a number of things including API calls, using Swagger, building Custom Connections and Flow’s, and passing parameters from a PowerApp to Flow, then to a backend API and storing the results as records in CDM.

 

 

 

 

Dynamics AX RFID using IoT

Don’t you hate it when you need to track someone down in an office building for an urgent message, or to sign some paperwork and you have no idea where they are? In a meeting perhaps, phone switched on silent? In the kitchen taking a break?

So here is a quick and easy worker locator using RFID swipe cards with an IoT board that displays your office layout in Dynamics AX, and pin-points where you can find Waldo right now.

For this project we’ll use a $20 Adafruit HUZZAH ESP8266/WiFi board with an MFC522 RFID reader. Mount the reader in a small plastic casing as shown below. The signal is strong enough to read access cards through the plastic wall.

We’ll add a LiPo rechargeable battery to make this portable as well. Just in case you need to mount one of these as and when required.

IMG_0182

Next we’ll solder the Adafruit board onto some PCB and add a red and green LED to signal “success” or “failure” when a card is touched to the box. The PCB is really just required to add resistors between VCC and the LED’s.

I like reusing stuff between projects so again, mounting the IoT board with headers onto the PCB makes sense. The completed PCB setup is shown below. The edges of the PCB have been trimmed to fit into the box with the rest, and that measures 8cm x 5cm so perfect to mount on a wall.

IMG_0184

Once the RFID reader has been connected and soldered onto the PCB we can stack all of it safely into the box as seen below. The LiPo battery can be recharged via USB and we can get a lot of usage out of it between charges, by putting the ESP8266 WiFi chip into deep sleep mode as often as possible.

IMG_0186

We’ll drill two small holes for the LED’s at the top, connect the battery and make another hole for a USB charger connection. All sorted the finished product is seen below ready for mounting.

IMG_0189

Coding-wise, I’ve used C through the Arduino IDE to make the whole project work. The code for this is below.

#include <SPI.h>
#include <MFRC522.h>
#include <ESP8266WiFi.h>
 
#define RST_PIN         15
#define SS_PIN          2
#define LED_GREEN       4
#define LED_RED         5
 
const char* tempssid = "TempAP"; // use a mobile phone to setup AP using IoTLink.net
const char* temppass = "TempPass";
const char* iotlink = "www.iotlink.net";
bool routed = false;
 
MFRC522 mfrc522(SS_PIN, RST_PIN);
 
void setup() {
  Serial1.begin(115200);
  while(!Serial1){}
 
  Serial.begin(9600);
  SPI.begin();
  mfrc522.PCD_Init();
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_RED, OUTPUT);
  digitalWrite(LED_GREEN, LOW);
  digitalWrite(LED_RED, LOW);
 
  WiFi.begin(tempssid, temppass);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
}
 
void loop()
{
  if (!routed)
  {
    route();
  }
 
  MFRC522::MIFARE_Key key; // default to FFFFFFFFFFFF
  key.keyByte[0] = 0xFF;
  key.keyByte[1] = 0xFF;
  key.keyByte[2] = 0xFF;
  key.keyByte[3] = 0xFF;
  key.keyByte[4] = 0xFF;
  key.keyByte[5] = 0xFF;
 
  // Loop until card is presented
  if (!mfrc522.PICC_IsNewCardPresent()) {
    return;
  }
 
  if (!mfrc522.PICC_ReadCardSerial())   
  {
    digitalWrite(LED_RED, HIGH);
    delay(1000);
    return;
  }
 
  byte readbuffer1[18];
  byte readbuffer2[18];
  byte block;
  MFRC522::StatusCode status;
  byte len;
  byte sizeread = sizeof(readbuffer1);
 
  block = 0;
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    // failed
    digitalWrite(LED_RED, HIGH);
    delay(1000);
    digitalWrite(LED_RED, LOW);
    return;
  }
  else
  {
    for (int i = 0; i < 18; i++)
    {
      readbuffer1[i] = 0x00;
      readbuffer2[i] = 0x00;
    }
 
    // read worker name or ID from card
    status = mfrc522.MIFARE_Read(1, readbuffer1, &sizeread);
    if (status != MFRC522::STATUS_OK)
    {
      // read failed
      digitalWrite(LED_RED, HIGH);
      delay(1000);
      digitalWrite(LED_RED, LOW);
      return;
    }
    mfrc522.PICC_HaltA();
    mfrc522.PCD_StopCrypto1();
  }
 
  // success
  String workername = String((char *)readbuffer1);
  digitalWrite(LED_GREEN, HIGH);
  delay(1000);
  digitalWrite(LED_GREEN, LOW);
 
  // send to ThingSpeak
  const char* host = "api.thingspeak.com";
  const char* thingspeak_key = "your api key";
 
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort))
  {
    return;
  }
 
  String url = "/update?key=";
  url += thingspeak_key;
  url += "&field1=";
  url += workername;
 
  client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  delay(10);
  while(client.available()){
    String line = client.readStringUntil('\r');
  }
}
 
void route()
{
  WiFiClient client;
 
  if (!client.connect(iotlink, 80))
  {
    Serial.println("IoTLink connection failed");
    return;
  }
 
  // uniquely identify our device using the chip id.
  // this id needs to be loaded into IoTLink and mapped to an AP by the customer
  String url = "/route?deviceid=" + String(ESP.getChipId());
  client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + iotlink + "\r\n" + "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println("IoTLink Timeout !");
      client.stop();
      return;
    }
  }
  String response = "";
  while(client.available()){
    response = client.readStringUntil('\r'); 
  }
  response.remove(0,1); // gobble NL
  String ssidx = getValue(response,',',0);
  String passx = getValue(response,',',1);
  char ssidnew[32] = {0};
  char passnew[32] = {0};
  ssidx.toCharArray(ssidnew, 32);
  passx.toCharArray(passnew, 32);
 
  WiFi.disconnect();
  delay(4000);
  WiFi.begin((char *)ssidnew, (char *)passnew);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  routed = true;
  // optionally store retrieved AP information into EEPROM in case of device reset
  // this avoids having to use a temporary AP again to route to IoTLink
}
 
// Helper
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;
 
  for(int i=0; i<=maxIndex && found<=index; i++)
  {
    if(data.charAt(i)==separator || i==maxIndex)
    {
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
 

 

First, we use a temporary AP and IoTLink (www.iotlink.net) to connect to the assigned AP for internet access. Once that is routed and connected, we wait for a card swipe. We read the worker details off the card, and send this to ThingSpeak via our WiFi connection.

ThingSpeak supports multiple channels with up to 8 fields per channel. For this example, I used a single channel and assumed each field will correspond to an office or room. Since that is limited, you might want to create a channel per location where you want to mount an RFID reader and just use one single field per channel. This is a prototype project so I took the easy way out.

Once we are satisfied that the electronics work, and swiping a card generates data in ThingSpeak, we can switch to AX 7.

For AX, I created a simple form and an extended control. In the HTML of the control, I load the office layout graphic (directly from my friends at EDrawSoft who kindly gave me permission to use it) and then get the latest data from my ThingSpeak channel using JavaScript.

I can go through each channel and field to determine who has swiped where in the building, and in this example we’ll just look for worker ‘VOS’. Once found, we can highlight where they last swiped in red around that office or room, and display their name at the top. The HTML/JavaScript for AX is shown below.

src="/resources/scripts/FBXRFIDControl.js">
id="FBXRFIDControl">
/>
style="border-width: 1px; border-style: solid; width: 100%; height: 100%; float: left;"> id="thecanvas">
<br /><br /> type="text/javascript"> var clickX = new Array(); var clickY = new Array(); var clickDrag = new Array(); var paint; function InitForm() { var thecanvas = document.getElementById('thecanvas'); thecanvas.width = 700; thecanvas.height = 600; var thecontext = thecanvas.getContext("2d"); var theImage = new Image(); theImage.onload = function () { thecontext.drawImage(this, 0, 0); } theImage.src = "https://www.edrawsoft.com/images/examples/office%20layout%20sample.png"; $.getJSON('https://www.thingspeak.com/channels/yourchannel/feed/last.json?callback=?&offset=0&location=true;key=yourkey', function (data) { var worker = data.field1; if (worker != '') { // someone in office 1, display who it is and highlight this office as 'occupied' var thecanvas = document.getElementById('thecanvas'); var thecontext = thecanvas.getContext("2d"); thecontext.fillStyle = "red"; thecontext.font = "bold 10px Arial"; thecontext.fillText(worker, 30, 30); thecontext.strokeStyle = "Red"; thecontext.lineWidth = 6; thecontext.rect(10, 15, 235, 175); thecontext.stroke(); } }); } </div>

 

Running in AX produces the results shown below. The code needs some work to add drop-downs for selecting worker, or perhaps clicking on a room will display the names of everyone currently swiped into that room. There are many ways to improve on this.

AX7

A nice simple project to combine RFID, IoT and Dynamics AX into an easy to use little project.

IoT Health & Safety in Dynamics AX 7

This is a quick project I put together to explore using small-size IoT modules for practical work, say Health & Safety or Equipment monitoring and reporting. For this post I’ll use the super-compact Cactus Rev 2 which gives me multiple I/O ports with WiFi built-in via an ESP8266 and I will use that to transmit three sensor values to Dynamics AX 7 via ThingSpeak.

The Cactus Rev 2 module is an amazing little device that measures less than 4cm by 2cm and is half a centimeter thick. It can be powered via USB or RAW and runs off <4v which is important as I want to power this using a LiPo battery to make it portable. The Cactus is pretty close to being the best possible module to use for building “wearable” IoT and can be powered using two coin batteries, with the ESP8266 being disabled and enabled as required to conserve power.

To make things a bit more practical, I’ll add a DHT11 temperature and humidity sensor, as well as a light sensor. I can also add an MQ9 sensor to detect various dangerous gasses but since that requires 5v it will need a booster added to the circuit so I’ll pass. It’s the idea that counts, right?

The completed circuit is shown below after soldering everything to a PCB and doing the required wiring, using 1 x Analog and 1 x Digital port all up, so leaving plenty of room for other sensors if required. I tried to keep things small and this measures 5cm x 4cm and about 1cm thick when completed. Keep in mind that sending this to production will drastically reduce the size, but this is only a prototype.

IMG_0173

I’m running this off USB to test, but ran the wiring (top-left) from RAW and GND to the back of the circuit where I can mound a rechargeable LiPo battery, and this will recharge  automatically every time I connect the USB cable. So it’s portable, virtually wearable and can be recharged at your desk.

We’ll use WiFi via the onboard ESP8266 and for that we’ll need an Access Point (AP) and obviously SSID and PASS. I could have opted to use an Arduino Nano with NRF905 instead as well. While it’s a prototype, we want to be production-ready so the sketch includes WiFi routing via a vendor/customer IoT Directory available at www.iotlink.net and I have coded this into the sketch. This means we’ll just need a temporary hardcoded AP during installation (or search for open AP) and IoTLink will take care of the rest.

The sketch code (in C) is shown below, pretty straightforward. We connect to a temporary AP, then using that and IoTLink find the correct customer AP settings in the device directory and re-route. Once connected we can start measuring sensor values and send  that to ThingSpeak to display in a dashboard.

#include <espduino.h>
#include <rest.h>
#include "DHT.h"
 
#define DHTPIN 15
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

#define PIN_ENABLE_ESP 13

ESP esp(&Serial1, &Serial, PIN_ENABLE_ESP);
REST rest(&esp);
boolean wifiConnected = false;

//IoTLink
boolean routed = false;
#define DEVICE_ID "DEV001" // This unique device ID
#define SSID  "TempSSID" // Default AP used for configuation
#define PASS  "TempPASS" 

void wifiCb(void* response)
{
  uint32_t status;
  RESPONSE res(response);

  if(res.getArgc() == 1) 
  {
    res.popArgs((uint8_t*)&status, 4);
    if(status == STATION_GOT_IP) 
    {
      wifiConnected = true;
    } else {
      wifiConnected = false;
    }  
  }
}

void setup() {
  Serial1.begin(19200);
  Serial.begin(19200);
  delay(1000);
  dht.begin();
  esp.enable();
  delay(500);
  esp.reset();
  delay(500);
  while(!esp.ready());
  if(!rest.begin("www.iotlink.net", 443, true)) // use SSL secure connection
  {
    while(1);
  } 
  esp.wifiCb.attach(&wifiCb);
  esp.wifiConnect(SSID, PASS); 
}

void loop() 
{
  esp.process();
  if(wifiConnected) 
  {
    if (!routed)
    {
      delay(1000);
      Route();
    }
    else
    {
      float h = dht.readHumidity();
      float t = dht.readTemperature();
      int l = analogRead(2);
      char response[266];
      char buff[64];
      char str_hum[6], str_temp[6], str_light[6];
      dtostrf(h, 4, 2, str_hum);
      dtostrf(t, 4, 2, str_temp);
      dtostrf(l, 6, 0, str_light);
      sprintf(buff, "/update?api_key=<your key here>&field1=%s&field2=%s&field3=%s", str_temp, str_hum, str_light);
      rest.get((const char*)buff);

      if(rest.getResponse(response, 266) == HTTP_STATUS_OK)
      {
      }
      delay(5000);
    }
  }
}

bool Route()
{
  char response[60]={','};
  char buff[50]={0};
  char ssid_new[20]={0};
  char pass_new[20]={0};

  sprintf(buff, "/route?deviceid=%s", DEVICE_ID);
  rest.get((const char*)buff);
  if(rest.getResponse(response, 60) == HTTP_STATUS_OK)
  {  
    String sr(response);
    String ssidx = getValue(sr,',',0);
    String passx = getValue(sr,',',1);
    ssidx.toCharArray(ssid_new,20);
    passx.toCharArray(pass_new,20);
    wifiConnected = false;
    routed = true;
    delay(500);
    esp.reset();
    delay(500);
    while(!esp.ready());
    if(!rest.begin("api.thingspeak.com"))
    {
      while(1);
    } 
    esp.wifiCb.attach(&wifiCb);
    esp.wifiConnect(ssid_new, pass_new);
    return true;
  }
  return false;
}

// Helper
String getValue(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length()-1;

  for(int i=0; i<=maxIndex && found<=index; i++){
    if(data.charAt(i)==separator || i==maxIndex){
        found++;
        strIndex[0] = strIndex[1]+1;
        strIndex[1] = (i == maxIndex) ? i+1 : i;
    }
  }
  return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}

 

I could have used Azure IoT Hubs and Power BI instead of ThingSpeak, but getting that working is time-consuming (compared to ThingSpeak), requires TSL from what I can gather and the Cactus just does not have the power nor storage capacity (it does support SSL though).

Running our circuit via the Arduino IDE in debug mode shows us it is all working nicely, as can be seen below:

IoTArduino

Dashboards are getting populated too, so the data is streaming in and we can move  this into Dynamics AX 7.

IoTThingSpeak

Say instead of wearable Health & Safety we wanted to use this to monitor a vital piece of equipment on the shop floor instead. For that we’ll create a simple dialog in AX, and add an extended control which will do the data fetching from ThingSpeak and display it on a factory layout diagram.

We start with a basic control, and then modify the HTML to include some JavaScript as shown below. All we are effectively doing is fetching the latest sensor readers from ThingSpeak, as reported by the IoT device. We request the latest sample, essentially.

One thing I am yet to find a workaround for in AX is the ability to utilise a JavaScript timer. This seems to be disabled somehow in AX. A timer would be useful to refresh all samples, say every 15 seconds or so. If someone has figured this out, please let me know.

src="/resources/scripts/FBXRFIDControl.js">
id="FBXRFIDControl">
/>
style="border-width: 1px; border-style: solid; width: 100%; height: 100%; float: left;"> id="thecanvas">
<br /><br /> type="text/javascript"> var clickX = new Array(); var clickY = new Array(); var clickDrag = new Array(); var paint; function InitForm() { var thecanvas = document.getElementById('thecanvas'); thecanvas.width = 700; thecanvas.height = 400; var thecontext = thecanvas.getContext("2d"); var theImage = new Image(); theImage.onload = function () { thecontext.drawImage(this, 0, 0); } theImage.src = "https://www.edrawsoft.com/templates/images/production-pfd.png"; $.getJSON('https://www.thingspeak.com/channels/yourchannel/feed/last.json?callback=?&offset=0&location=true;key=yourkey', function (data) { var temp = data.field1; var hum = data.field2; var light = data.field3; // can change font of text depending on whether light levels are sufficient // in turn, IoT device can adjust office lighting if levels are too high or too low var thecanvas = document.getElementById('thecanvas'); var thecontext = thecanvas.getContext("2d"); thecontext.fillStyle = "blue"; thecontext.font = "bold 10px Arial"; thecontext.fillText(temp + 'C ' + hum + '%', 490, 250); }); } </div>

 

Running this in AX produces the result shown below, with the sensor readings being displayed in blue next to the vital piece of equipment we are monitoring, in this case a motor.

IoTOHS

In terms of practicality it covers a number of potential use-cases:

  • Office environment monitoring
  • Health & Safety monitoring (toxic gasses, working temperature, low-light conditions, high humidity)
  • Add a vibration sensor to monitor potential equipment malfunction