Sales Effectiveness in Dynamics CRM with Azure IoT and Machine Learning
How can an organisation optimise its sales channels and product targeting by building a 365-degree view of its customers in Dynamics CRM? The answer, and topic of this article, is with the help of Azure IoT and Machine Learning services!
The use case described in this article is the identification of common patterns of actions by consumers, classification based on criteria like age, gender, location, etc., and promotion of best-fit products. To achieve this objective, wearable and mobile devices are used and connected to the Azure IoT Hub for collecting information about location, commuting patterns and weather condition. All this information is then scored and evaluated in Azure Machine Learning to predict the best matching products. Data about sales conversion and customer loyalty is also captured and analysed with Power BI.
CRM Integration Flow with Azure IoT and Machine Learning
The products on sales are active cosmetics. The objective is to optimise stock availability in street distributors according to predicted demand. This is done by creating a full profile of customer’s actions and classifying them according to different criteria, or features:
· Age
· Gender
· Skin Type
· Season
· Weather Condition
This information, collected by the Azure IoT platform and stored in the CRM system, provides the analysis dataset for applying a “demand prediction” Machine Learning algorithm that determines:
· Churn Rate, or measure of customer attrition, defined as the number of customers who discontinue a product during a specified time period, divided by the total number of customers over the same time period.
· Appetency, a word with the same root as “appetite”, which indeed defines the appetite, or desire of a customer to buy a specific product.
· Upselling, the likelihood to sell a similar product to others that have been bought in the past, in response to determined conditions.
Let’s start digging into the implementation details of the technology components of this solution, based on the Microsoft’s Azure stack. Microsoft’s offering for Internet-of-Thing solutions consists of several resources, of which the Azure IoT Suite represents the most comprehensive, as it aggregates multiple components into a single package ready for use. At time of writing, the Azure IoT Suite offers the possibility to create two types of solutions:
· Predictive Maintenance: Anticipate maintenance needs and avoid unscheduled downtime by connecting and monitoring devices for predictive maintenance.
· Remote Monitoring: Connect and monitor devices to analyse untapped data and improve business outcomes by automating processes.
This solution is based on the “Remote Monitoring” type for streaming data from connected devices in use by customers. A typical dashboard of the Azure IoT Suite contains elements of:
· Visualisation of devices over a geography (Bing Map).
· Telemetry History (line diagram showing real-time data streams).
· Gauges for reporting average measures.
· Alarm History for reporting violations of defines rules (exceeding of set metrics as measured by the connected devices).
Azure IoT Suite Dashboard
Several technology components work together in the Azure IoT Suite and are brought together in Azure under the same Resource Group, namely aptly after the Azure IoT Suite solution itself. Components include:
· IoT Hub: The pulsing heart of the IoT Suite, providing a device registry and bi-directional communication.
· Storage: Typically, in the form of a NoSQL database like DocumentDB, for storing data and alert history.
· Event Hub: A highly scalable data streaming platform capable of ingesting millions of events per second.
· App Service: Works in combination with Power BI to display data in the dashboard.
· Stream Analytics: Provides in-motion data analysis, processes incoming telemetry, and detects events.
A full description of the components of the Azure IoT Suite preconfigured solutions is available on Microsoft Web Site.
Azure resources for the IoT Suite
The Azure IoT Hub is an Azure service that enables secure and reliable bi-directional communications between your application back end and millions of devices. It allows the application back end to receive telemetry at scale from your devices, route that data to a stream event processor, receive file uploads from devices, and also to send cloud-to-device commands to specific devices. In addition, IoT Hub includes a device identity registry used to provision devices, their security credentials, and their rights to connect to the hub. The device identity registry, thus enforces:
· Block of unsolicited network information: Only registered devices can communicate with the IoT Hub.
· Bi-directional secured communication: Device specific queues are maintained for all commands, to guarantee delivery, especially in conditions of low-power usage. When a device enters into stand-by mode to reduce power consumption and preserve battery life, an “awake” signal is sent by the IoT Hub to alert the device that a new measure is required, at specified intervals of time.
Connecting a device to the IoT Hub, programmatically, is relatively simple when using the .NET framework and the device runs Windows 10 IoT Core operating system. The solution in Visual Studio requires the following packages to enable the communication between the device and the IoT Hub. These packages have a lot of dependencies, though, so expect to see a longer list of packages installed automatically by NuGet Package Manager.
NuGet Packages for connecting a device to the Azure IoT Hub
The ThermostatManager class in the code sample below connects a pseudo-thermostat device to the Azure IoT Hub via the RegistryManager factory, and adds the device identified by its unique ID. Access to the IoT Hub is identified by a connection string in the form of:
HostName={AzureIoTHub-Hostname}; SharedAccessKeyName={AccessPolicyName}; SharedAccessKey={AccessPrimaryKey}
These three elements can be conveniently stored in the application configuration file, and be used for building the connection string in the expected format.
<appSettings>
<add key="AzureIoTHub-HostName" value="{hostname}.azure-devices.net"/>
<add key="AzureIoTHub-AccessPolicyName" value="iothubowner"/>
<add key="AzureIoTHub-AccessPrimaryKey" value="{primary-key}"/>
</appSettings>
Connection String elements to Azure IoT Hub
The access policy defines the level of permissions granted to an application / device that connects to the hub. “iothubowner” is the most privileged access, able to maintain the device registry and establish communication from and to the connected devices. Other policies have less permissions and are more suitable for cloud-to-device communication only (service) or device-to-cloud direction (device). Choose your access policy depending on the activities your application is expected to perform. Each access policy has a primary and secondary key for authentication in Azure IoT Hub.
Access Policy to Azure IoT Hub
Once added to the IoT Hub, a key is assigned to the device in the hub’s registry. Each registered device is identified by an instance of the Device class in the Microsoft.Azure.Devices namespace. Given the device ID and access key, a client instance (DeviceClient class) should be used for further communication between the device and the hub.
using Microsoft.Azure.Devices;
using Microsoft.Azure.Devices.Common.Exceptions;
public class ThermostatManager
{
public ThermostatManager(string hostName, string accessPolicyName, string accessPrimaryKey)
{
this.hostName = hostName;
string connectionString = $"HostName={hostName};SharedAccessKeyName={accessPolicyName};SharedAccessKey={accessPrimaryKey}";
registry = RegistryManager.CreateFromConnectionString(connectionString);
}
public async Task AddDeviceAsync(Thermostat thermostat)
{
// Add the device to the IoT Hub
Device device;
try
{
device = await registry.AddDeviceAsync(new Device(thermostat.Id));
}
catch (DeviceAlreadyExistsException)
{
device = await registry.GetDeviceAsync(thermostat.Id);
}
// Creates a device client for communication with the IoT Hub
DeviceClient client = DeviceClient.Create(this.hostName,
new DeviceAuthenticationWithRegistrySymmetricKey(
device.Id,
device.Authentication.SymmetricKey.PrimaryKey));
[..]
}
Registering a device into the Azure IoT Hub
Once the device is registered in the hub, it can start streaming data using the client object.
private async void SendMessagesAsync(Thermostat sender, EventArgs e)
{
var telemetryDataPoint = new
{
deviceId = sender.Id,
temperature = e.Measure
};
var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
var message = new Message(Encoding.ASCII.GetBytes(messageString));
await deviceClient.SendEventAsync(message);
}
Sending a message to the IoT Hub
The full code is available on CodePlex for free download. It also provides a simulation of two thermostat devices connected to the Azure IoT Hub and streaming data every second in parallel. The first device runs for 10 seconds, and the second one for 15 seconds. Communication is interrupted with a cancellation token. When the execution of a data reading from the device is cancelled, an ReadCanceled event is raised.
public void Run()
{
Parallel.ForEach(deviceList, async (item) =>
{
CancellationTokenSource cts = item.RunForMilliseconds < 0 ? null : new CancellationTokenSource(item.RunForMilliseconds);
await RunThermostatAsync(item.Thermostat, cts);
});
}
private async Task RunThermostatAsync(Thermostat thermostat, CancellationTokenSource cts)
{
try
{
while (true)
{
await thermostat.ReadTemperatureAsync(cts != null ? cts.Token : CancellationToken.None);
}
}
catch (OperationCanceledException)
{
OnReadCanceled(thermostat);
}
}
public delegate void ReadCanceledEventHandler(Thermostat sender, EventArgs e);
public event ReadCanceledEventHandler ReadCanceled;
protected virtual void OnReadCanceled(Thermostat sender)
{
ReadCanceled?.Invoke(sender, EventArgs.Empty);
}
Parallel running and cancellation handling of device readings
The simulation runs as a Windows Console application, with the following output. Temperatures are simulated and generated randomly, and sent to the IoT Hub every second until the cancellation period occurs.
Messages sent to the IoT Hub from the connected devices
In the Azure Portal, it is possible to see metrics about the number of connected devices and messages exchanged.
IoT Hub Metrics
This part 1 of the article introduced the use case for generating more effective sales in Dynamics CRM, as a result of optimisation of stock availability of products. This is obtained by identifying customer usage patterns, combining the technology of mobile and wearable devices connected to Azure IoT Hub for collecting information.
In the second part of the article, focus is on the implementation of a demand estimation experiment in Azure Machine Learning, which analyses the data collected in the IoT Hub and scores, i.e. predicts, future demand. Based on the estimated demand, according to a number of conditions identified in the input dataset, churn rate, appetency and upselling are optimised for the products in stock.
Project Name: AzureIoT