Business Central and IoT. Integration with Arduino.
Business Central and IoT. Integration with Arduino.
0
Components
Hardware componentsEthernet shield
x 1
MQ3
x 1
Alcohol
x 1
Azure IoT Central
x 1
Project description
Basically this post is a description what we showed on #NavTechDays in last demo(Link).
The idea was to get values from analog meter to cloud Business Central and use this values for some scenario. We used MQ3 gas analyzer as alcohol detector, Arduino Uno controller with Ethernet shield and bottle of wine as measurement material. Scenario was that drunk user can't post sales orders (in other scenario user must be drunk :) to post them).
Demo created just for fun. The core idea is to show you how to integrate your Business Central solution with hardware devices and get some metrics from them.
Needed hardware parts: 1.?Arduino Uno controller with USB cable (you can use analog, price is ~5-7$) 2.?Ethernet shield for Arduino Uno and ethernet cable (also 5-7$)
3.?MQ3 meter with connection wires (3-5$)
4.?Any alcohol for tests (price depends)
5.?Connect Arduino Uno with ethernet shield next way:
6.?Connect MQ3 pins to ethernet shield next way (MQ3 DOUT pin not used):
| MQ3 pin | Shield pin |
| +5V | 5V |
| AOUT | A0 |
| GND | GND |
table 50105 "Mq3 data"
{
DataClassification = ToBeClassified;
fields
{
field(1; EntryNo; Integer)
{
DataClassification = ToBeClassified;
}
field(2; "MQ3 value"; Integer)
{
DataClassification = ToBeClassified;
}
field(3; "Creation date"; Date)
{
DataClassification = ToBeClassified;
}
field(4; "Creation time"; Time)
{
DataClassification = ToBeClassified;
}
}
keys
{
key(PK; EntryNo)
{
Clustered = true;
}
}
trigger OnInsert()
var
Mq3: Record "Mq3 data";
begin
If Mq3.findlast() then
EntryNo := Mq3.EntryNo + 1
else
EntryNo := 1;
"Creation date" := DT2Date(CurrentDateTime());
"Creation time" := DT2Time(CurrentDateTime());
end;
}
page 50105 "MQ3 values"
{
PageType = List;
ApplicationArea = All;
UsageCategory = Lists;
SourceTable = "Mq3 data";
SourceTableView = order(descending);
layout
{
area(Content)
{
repeater(Group)
{
field(EntryNo; EntryNo)
{
ApplicationArea = All;
}
field("MQ3 value"; "MQ3 value")
{
ApplicationArea = All;
}
field("Creation date"; "Creation Date")
{
ApplicationArea = All;
}
field("Creation time"; "Creation Time")
{
ApplicationArea = All;
}
}
}
}
}
page 50106 "MQ3"
{
PageType = API;
Caption = 'MQvalues';
APIPublisher = 'ntd18';
APIGroup = 'MQValues';
APIVersion = 'beta';
EntityName = 'MQValue';
EntitySetName = 'MQValues';
SourceTable = "Mq3 data";
DelayedInsert = true;
ODataKeyFields = EntryNo;
layout
{
area(Content)
{
repeater(GroupName)
{
field("MQvalue"; "MQ3 value")
{
Caption = 'mq';
ApplicationArea = All;
}
}
}
}
}
table 50106 "MQ3 setup"
{
DataClassification = ToBeClassified;
fields
{
field(1; Entry; Integer)
{
DataClassification = ToBeClassified;
}
field(2; "Limit Value"; integer)
{
DataClassification = ToBeClassified;
}
field(3; Condition; Option)
{
OptionMembers = notdrunk,drunk;
OptionCaption = 'Not drunk, Drunk';
}
}
keys
{
key(PK; Entry)
{
Clustered = true;
}
}
}
page 50107 "Mq3 setup"
{
PageType = Card;
ApplicationArea = All;
UsageCategory = Administration;
Caption = 'MQ3 Setup';
SourceTable = "MQ3 setup";
layout
{
area(Content)
{
group(GroupName)
{
field(Condition; Condition)
{
ApplicationArea = All;
}
field(Name; "Limit Value")
{
ApplicationArea = All;
}
}
}
}
}
codeunit 50105 "MQ3 management"
{
trigger OnRun()
begin
end;
[EventSubscriber(ObjectType::Codeunit, Codeunit::"Sales-Post (Yes/No)", 'OnBeforeConfirmSalesPost', '', false, false)]
local procedure MyProcedure()
var
MQ3Values: Record "Mq3 data";
MQ3Setup: Record "MQ3 setup";
LastEntryNo: Integer;
begin
MQ3Setup.get();
If MQ3Values.FindLast() then
LastEntryNo := MQ3Values.EntryNo;
MQ3Values.SetRange(EntryNo, LastEntryNo - 5, LastEntryNo);
case MQ3Setup.Condition of
MQ3Setup.Condition::notdrunk:
begin
MQ3Values.Setfilter("MQ3 value", '>%1', MQ3Setup."Limit Value");
If MQ3Values.FindFirst() then
Error(Error001);
end;
MQ3Setup.Condition::drunk:
begin
MQ3Values.Setfilter("MQ3 value", '<=%1', MQ3Setup."Limit Value");
If MQ3Values.FindFirst() then
Error(Error002);
end;
end;
end;
var
Error001: Label 'You are drunk, orders posting prohibited!';
Error002: Label 'You are not drunk, orders posting prohibited!';
}
#r "Newtonsoft.Json"
using System.Net;
using System.Text;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;
public static async Task Run(HttpRequest req, ILogger log)
{
string mq3 = req.Query["mq3"];
var results = await SendArduinoMessage(mq3);
return mq3 != null
? (ActionResult)new OkObjectResult($"Result is: {mq3}")
: new BadRequestObjectResult("Please pass a mq-3 value on the query string");
}
public static async Task SendArduinoMessage(string mq3)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Basic USER-WEB-SERVICE-KEY");
Dictionary<string, string=""> dictionary = new Dictionary<string, string="">();
dictionary.Add("MQvalue", mq3);
string json = JsonConvert.SerializeObject(dictionary);
var requestData = new StringContent(json, Encoding.UTF8, "application/json");
var url = "https://api.businesscentral.dynamics.com/v1.0/YOUR-environment-ID/sandbox/api/ntd18/MQValues/beta/companies(your-company-GUID)/MQValues";
var response = await client.PostAsync(url, requestData);
var result = await response.Content.ReadAsStringAsync();
return result;
}
}</string,></string,>
#include
int mq3_analogPin = A0;
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; //any values
byte ip[] = { 192, 168, 137, 171 }; //+1 to Ethernet IP
byte sdns[] = { 8, 8, 8, 8 };
byte gw[] = { 192, 168, 137, 170 }; //IP which used in p.11
byte subnet[] = { 255, 255, 255, 0 };
char server[] = "ntd18.azurewebsites.net"; //your AZ function app address
EthernetClient client;
int failedcounter = 0;
boolean lastconnected = false;
void setup()
{
Serial.begin(9600);
StartEthernet();
delay(1000);
}
void loop()
{
int mq3_value = analogRead(mq3_analogPin);
//Serial.println(mq3_value);
delay(5000); //Slow down the output.
SendData(String(mq3_value));
String c = client.readStringUntil('>');
Serial.print(c);
if (!client.connected() && lastconnected)
{
Serial.println("...Disconnected");
Serial.println();
client.stop();
}
if (failedcounter > 3)
{
StartEthernet();
failedcounter = 0;
}
lastconnected = client.connected();
}
void StartEthernet()
{
client.stop();
Serial.println("Connecting Arduino to network...");
Serial.println();
delay(1000); //Keeps the connection from freezing
Ethernet.begin(mac, ip, sdns, gw, subnet);
Serial.println(Ethernet.localIP());
delay(1000);
}
void SendData(String data)
{
if (client.connect(server, 80))
{
client.print("GET /api/Arduino?mq3="); //your AZ function name + mq3 parameter
client.print(data);
client.println(" HTTP/1.1");
client.println("Host: ntd18.azurewebsites.net"); // your AZ function app name
client.println();
if (client.connected())
{
Serial.println("Connected");
Serial.println();
failedcounter = 0;
}
else
{
failedcounter++;
Serial.println("Connection unsuccesful");
Serial.println();
}
}
else
{
failedcounter++;
Serial.println("Connection unsuccesful");
Serial.println();
}
}


