Overview

In the age of IoT, businesses are digitalising and moving from pen and paper to screen and keyboard. Many managers are appealing to IoT solutions to better run their companies.

 

IoT helps businesses improve their sales and marketing by collecting data about their consumers and suggesting actions that would make the business more attractive, resulting in improved sales and presence at the store.

 

The problem is that IoT is expensive and difficult to implement, and although major businesses will have such solutions implemented, your local café, restaurant and store may not have them! IoT should be accessible for all companies big and small. SmartLocale aims to bring your business to the digital world in minutes, removing the cost and expertise required to set up a system that tracks and predicts sales and presence in the store, café, restaurant or any other small business.

SmartLocale is an application that tracks the number of people that entered the locale and the number of sales carried out every business day. An edge-device is placed at the store’s POS collecting data about the sales and at the entrance of the store counting the number of people entering and leaving the locale. These two values are compared resulting in crucial business indicators.

 

SmartLocale exceeds existing solutions because of the extremely low price and ease of setup allowing the locale’s manager to implement the solution in minutes and start monitoring the locale’s sales and presence. All the data is centralised in the cloud where it is forecasted to predict the business’ sales and presence for the next period of time allowing the business to prepare in the case of a rainy day.

 

The manager can access an online, interactive dashboard presenting the historical and forecasted sales and presence in the store. This allows the manager to easily manage their business from their phone, tablet or laptop at any time. The application also allows the business to see which products were sold the most. The application groups all products into three categories defined by the manager and tracks the sale of products from each category.

 

This device is aimed at small to medium companies specialised in the sale of goods and provision of services. Your local café, store, restaurant or barbers can benefit from this solution. Bring your business in the age of IoT with SmartLocale.

Project Video

Project In-Depth

Data is crucial to businesses, studies carried out by Failory and other similar analytics companies state that over 90% of all start-ups fail within 1 year. This high percentage is due to a lack of market research and awareness of competitors. IoT is the solution to this problem as it can track the business’ sales and presence allowing the manager to visualise these indicators over the history of the business and forecast them to see if the business will be a success.

 

Data Fields

The table below displays all the values that are sent by the frontend device to the backend. This data is later processed and formatted in the backend.

                                                                                                                         

Timestamp

Date/time

Cake (category 1)

Number

Drinks (category 2)

Number

Lunch (category 3)

Number

Presence

Number

TotalSales

Number

Presence String

String

TotalSales String

String

 

Categorising Data

The application also allows the business to see which products were sold the most. This revolutionary feature allows the business to categorise all their products in 3 categories, for example in the case of a café they would be drinks, lunch and cake.

 

The managers can then see how many products were sold from each category and compare the categories allowing them to understand consumer trends. The manager of the business can define the categories to what is relevant to their business.

 

Business Indicators

The frontend device will only collect a small number of fields. These fields are enhanced in the backend - converted to datasets. The comparison of these datasets provides crucial business indicators that indicate how the business is doing.

 

The application has 3 types of groups of values;

 

Overview

The present values of sales and presence representing the previous business day. These values are then compared to form sales/customer. This is a crucial value that indicates the number of products bought in respect to the number of customers in the store in one day.

       

                                Last Sales                    A value presenting the overall sales in the store for the previous day. This value is composed of the number of sales in each category.

 

                                Last Presence              This value represents the total number of people that entered the store in the previous day.

 

                                Last Sales/Presence   This is a business indicator representing the number of sales respective to the number of people at the store the previous day.

 

                                This data is represented on the Overview tab on the dashboard.

                            

Historical

This group of values represents the sales and presence of the business for a defined time range. This data is plotted on graphs on the dashboard allowing the manager to visualise how the business is doing over time.

 

           Historical Sales          The sales carried out by the business every day for a defined interval of time.

 

                                 Historical Presence    The number of people present in the store every day for a defined interval of time.

 

This data is displayed on the History tab on the dashboard. The company’s total sales and presence up to this date are also displayed on this tab.

                               

Forecast

The final group of values are forecasted predicting the presence and sales in the locale in the future. This data is predicted using line graphs allowing the manager to easily visualise how their business will be doing in the defined interval of time predicted.

 

                                 Forecasted Sales        The number of sales that are forecasted to occur in the store in the following defined interval of time.

 

                                 Forecasted Presence  The forecasted number of people that will be present in the store over the next defined interval of time.

 

                                 This data is displayed on line graphs on the Forecast Tab.

Importance of Data

These indicators are very important to a business. The most important indicator is the Sales/Presence which indicates the number of sales per person. This indicator shows how the business is doing.

 

Some customers walk in the store for the first time to check it out while others are loyal customers. The key to success is to attract as many loyal customers as possible as they will always purchase from the locale when they enter it. First comers on the other side may not do this as they may not be attracted to the items sold in the store.

 

If the indicator is greater than 1, this indicates that people buy products from multiple categories and most people that enter the store will purchase something. This may be due to consumer loyalty together with efficient marketing, good pricing and a high quality of products.

 

If the indicator is less than 1, this indicates that people that enter the shop do not necessarily buy anything. This is a problem for the store as it indicates that there is a problem with the pricing, employees or quality of products. If the presence is also low, this indicates that there is a problem with competitors, location or target market.

 

The following factors indicate a healthy business:

  1. High presence
  2. High sales
  3. Sales from a variety of all 3 categories
  4. More sales than presence
  5. Gradual improvement or stagnation of sales and/or presence over time

 

The following factors indicate an unhealthy business:

  1. Low Presence
  2. Low Sales
  3. Sales isolated to certain categories
  4. Less sales than presence
  5. Decrease in customers and/or purchases over time

 

Taking Action in Respect to the Data

SmartLocale will rapidly inform the manager if there is a problem with the business. If the manager sees that the sales/customer indicator is lower than 1, action should be taken to improve the sales. The manager may want to survey the employees and target market to identify the source of the problem. The manager may then want to adapt the pricing of the products to match the competition and/or provide a wider variety of products. These choices powered by SmartLocale can save the business from going bankrupt.

Project Benefits

The benefits brought by using SmartLocale to the business are summarised below.

  • Visualise the number of products sold from each product category allowing the manager to see which category is most successful.
  • Illustrates the past sales and presence so that the manager can see how the business is doing over time.
  • Forecasts presence and sales in the future allowing the business to prepare for a time with less sales.
  • Easy to set up and use and cost-efficient

Data Visualisation

The data is visualised on a Power Bi dashboard. The data is visualised on graphs and other visuals to give the manager an intuitive view over their business at the glance of an eye. The table below displays the formulae used by Power Bi to calculate the sales/customer indicators.

                                         

Average Sales/Customer

Calculated number

Max Sales/Customer

Calculated number

Last Sales/Customer

Calculated number

 

Why Power Bi?

I chose to work with Power Bi because it is equipped with a lot of powerful graphs and visuals that can truly enhance a dashboard. Power Bi is also equipped with a forecasting function that makes it easy to predict the sales and presence in the store. The dashboard also automatically refreshes always displaying the most up-to-date data and is shareable so the whole management team can visualise the dashboard with ease.

 

The dashboard consists of 3 sections; the overview, history and forecast. These three sections are above. They are described in the Business Indicators section of the document.

Case Study: A Healthy Business

I will be displaying two examples of reports generated by two café and then comment on the findings. Note that 30 datapoints were sampled to report a business month. Below are the dashboards generated by the business.

This coffee shop will have a stable value of sales and presence where sales will always be greater than presence. There will be a few days when the temperature rises, and people will not visit the coffee shop as well as a protest when the street will be blocked. The coffee shop will also streak a few highs as the temperature falls.

 

  • Good marketing
  • Good point of sale (location)
  • Good market research and awareness of competition
  • Appealing to customers
  • Reasonable prices
  • Fair Trade or Forest Alliance certified
  • Good choice in products

Case Study: An Unhealthy Business

I will be displaying two examples of reports generated by two café and then comment on the findings. Note that 30 datapoints were sampled to report a business month. Below are the dashboards generated by the business.

 

This coffee shop does not appeal to people because of the poor choice in products and the bad history of employee treatment. The store also has very little space for eating. The shop will have a moderate presence but a poor sales. This is because its point of sale is good with little competition around. The store gains a higher presence due to the tourists in the area that are first-time customers at the locale. But these people do not purchase anything due to the lack of choice and unattractivity of the products.

 

  • Bad marketing
  • Good point of sale (location)
  • Not appealing to people
  • Unreasonable prices
  • Unattractive design
  • Poor choice in products

Project Architecture

This project consists of a frontend and a backend.

 

                      Frontend      This refers to the device that is positioned at the locale. This device collects the sales and presence and sends this data to the cloud at the end of the                            business day.

           Backend       Processes and displays the data on a dashboard. The data starts off in an IoT hub and is then pushed into a Power Bi report.

 

The frontend device will always be on to receive commands from the POS and entrance modules. But the device will only send the data at the end of the business day. The device will then reset and start the process again.

Above is the project’s architecture diagram. This diagram displays the steps taken by the application.

 

  1. The frontend device will check if the beam from the break beam sensor is broken and if a button is pressed. If so, the device will increment the respective variables.
  2. The device will continue running this code until it is the end of the business day. When this happens, the device will get the time from its RTC, process the variables and then send the data to the cloud.
  3. The data is received by Azure IoT and is then extracted by a Stream Analytics Job inputting the data into a Power Bi dataset.
  4. The data is finally extracted by a Power Bi Report which displays the data on graphs and other visuals.

Frontend

This section will discuss the frontend device and what it does to collect the data and send it to the backend.

 

Device Overview – Azure Sphere

I chose to build this project using the Azure Sphere development board as it offers industrial grade security that ensures that the system cannot be tampered with. IoT security is essential for companies as the data collected by the device is crucial for the analysis of the business and tampering with the data can cause losses for the business.

 

Data Collection

Data is collected from the frontend device. This device will be equipped with a break-beam module which is positioned at the entrance to the locale and a POS device that is placed on the counter.

 

Entrance Module

The break beam module is positioned at the entrance to the locale, this device will count the number of people entering and leaving the locale. This is done by counting the number of times the laser beam was broken by a person entering or leaving the store.

 

POS Module

The POS module is placed on the counter beside the cashier. This is equipped with 3 buttons that the seller can interact with. All the products in the locale are grouped into 3 categories defined by the manager, for example a café will have drinks, lunch and cake. Whenever a product from a category is sold, the seller will press the respective button, incrementing the number of products in the respective category sold.

 

Data Processing

All the data is processed by the device at the end of the business day. This is because the dashboard presents sales and presence for each day and it is easier to accumulate these values on the device and send them all in one payload than count the number of times the device pinged the cloud. The only value that has to be altered before sending the data is the presence. The beam of the sensor will break every time someone enters or leaves the store.

 

The problem is that this does not count the number of people that were present in the store. Assuming that all people that entered the store must also leave, the beam break count is divided by 2.

 

Onboard RTC

Azure IoT can potentially attach a timestamp to the data sent. I have tried this initially but found a delay of approximately 5 seconds occurred between the timestamp at which the data was sent and the timestamp that was attached in the cloud.

 

Although small, this difference builds up and can lead to the timestamp to be severely off. This can cause a lapse in data on a day as the device is supposed to send the data at 23:55 but sends it at 00:10. I then decided to get the time from the onboard RTC which synchs online and send it as part of the payload.

 

It is crucial to be aware of the fact that the data is sent to the cloud using a timer. The data is sent every 24 hours, so not at a precise time. It is important to start the device 24 hours before 23:55pm on the first day of operation to have the data sent at the end of each business day.

 

User Feedback

The device is equipped with an RGB LED and a buzzer to provide the user with feedback. The buzzer will buzz to alert the user’s attention to the RGB LED throughout the program and whenever a button is pressed by the seller. Below are the LED colours and their meanings:

 

A purple blinking LED indicates that there is a problem with the firmware of the device, preventing the program to execute successfully. The device should be reset in this case.

 

A green LED is displayed when the seller pressed one of the buttons after selling an item from the respective category. This informs the seller, together with a buzzer buzz, that the device registered their press.

 

A light blue LED indicates that the device is online and is awaiting the user to press a button indicating that a product was sold. No LEDs will change if the beam from the entrance module is broken.

 

The Backend

The backend refers to all the computing that happens in the cloud and the dashboard that displays the data collected by the device.

 

Microsoft Azure

I have used Azure cloud by Microsoft because of two reasons.

        1. The Azure Sphere device is designed to be connected to Azure IoT. I have decided to make use of this connection as it is secure and reliable.

2. Azure is my cloud of choice due to the beautiful interface and integration with Office 365 and Windows.

 

Backend Program Overview

The steps below illustrate the steps taken by the backend to process the data.

Data Received by IoT Hub

The data is sent to the cloud by the frontend device at the end of each business day. The data is inputted into an IoT Hub which is an entry point for IoT devices. The IoT hub directly connects to the Azure Sphere creating a secure connection. The data is stored in the IoT hub as events.

 

Stream Analytics Job

The data is then streamed by a streaming job from the IoT Hub into a Power Bi dataset. The analytics job runs constantly; searching for new events in the IoT Hub, exploiting them and inserting them into a Power Bi dataset stored on the Power Bi side.

 

Power Bi Dataset

The data is then inputted into a Power Bi report. This is the data source used by the report. The data is stored in a dataset similarly to a server. The data is updated live by new data sent by the device.

 

Power Bi Report

Finally, a Power Bi report extracts the data from the dataset and visualises the data on graphs. The manager can then see the data on a report. The report can then be easily shared with authorised people.

Going Further

Below is a list of features that would be added in a further developed version of the project.

 

  • Attach an OLED display to the frontend device placed on the POS that displays the current sales for each category and presence. This will allow the seller to get a view of how many sales were carried out.
  • An integration of the POS device and the cashier where the seller will not need to input the sales in the cashier and the device but only in the cashier.
  • The use of Cosmos DB instead of Power Bi datasets for increased reliability.
  • A function to set the working days of the store allowing the device to go to sleep during days in which the store is closed.

 

My Device

I wanted to confirm that my device has registered with the server for more than 30 days. I took screenshots of the server’s Power Bi app and attached them below.

 

Constructing the Project

Below are the steps required to build the project.

 

Step 1: Required Materials

To get started, we have to make sure that we have all the materials we need for the project. These are listed below.

We will be using the following apps and services in this project:

  • Azure IoT Hub
  • Azure Stream Analytics Job
  • Microsoft Power Bi
  • Visual Studio 2017/2019

 

Step 2: Prerequisites

Before we start building the project. You will need to ensure that you have access to a Windows 10 PC with Visual Studio 2017 or 2019 installed. You will also require the Azure Sphere SDK installed on your PC.

 

Note that I am working on version 19 and not the most recent version. Although there should be no problem loading project files using the new SDK, some bugs can occur.

 

You will then need to follow this well laid out guide provided by Microsoft to get started with your development board and set it up. When your device is in debug mode and connected to Wi-Fi, you can continue with the guide.

 

Step 3: Connecting the Circuit

Depending on your circumstances, you may want to solder the components together. I used a breadboard as it was easier for me to develop the application. The Fritzing schematics are below.

Step 4: Acknowledging the Code

The next step is to acknowledge the significant sections of code. There are 4 main sections to the code.

  • Get Buttons
  • Get Break Beam
  • Setup
  • Send Data to Azure IoT

 

Get Buttons

// process the buttons
void processButtons(int a, int b, int c)
{
      bool printStuff = false; // print the status?
      if (a == 1)
      {
            cat1++;
            totalSales++;
            printStuff = true;
            println("[Program] Button A Pressed");
      }

      if (b == 1)
      {
            cat2++;
            totalSales++;
            printStuff = true;
            println("[Program] Button B Pressed");
      }

      if (c == 1) 
      {
            cat3++;
            totalSales++;
            printStuff = true;
            println("[Program] Button C Pressed");
      }

      if (printStuff)
      {
            // print the current number of sales from each category
            Log_Debug("[Info] Button A %i \n", cat1);
            Log_Debug("[Info] Button B %i \n", cat2);
            Log_Debug("[Info] Button C %i \n", cat3);
            Log_Debug("[Info] Total %i \n", totalSales);

            ledGreen(); // turn the LED green
            buzz(1000); // buzz the buzzer for a second
            ledOff();
      }
}

This function checks the state of the 3 buttons to see if any of them are pressed. The function then increments the variable representing the number of sales for the category.

 

Get Break Beam

// check if the beam is broken
void processSensor()
{
      GPIO_Value_Type newButtonAState;
      int result = GPIO_GetValue(sensorOpen, &newButtonAState); // read the GPIO value

      if (result < 0) // if read was not allowed
      {
            Log_Debug("[Program] Access to Pin Denied \n");
            ledPurple();
            return -1;
      }

      if (newButtonAState == 0)
      {
            if (newVal)
            {
                  breakCount++;
                  newVal = false;
                  Log_Debug("[Program] Sensor Count %i\n", breakCount);
            }
      }
      else
      {
            newVal = true;
      }
}

This function checks to see if the beam of the break beam module is broken and increments a variable if it is.

 

Setup

// Set up SIGTERM termination handler, initialize peripherals, and set up event handlers
static int InitPeripheralsAndHandlers(void)
{
      Log_Debug("[Setup] Setting Up GPIOs \n");

      Log_Debug("[Setup] Opening Sesnor Pin \n");
      sensorOpen = GPIO_OpenAsInput(16); // open the GPIO pin of the break beam sensor as an output

      // check if the pin was opened successfully
      if (sensorOpen < 0)
      {
            Log_Debug("[Setup] GPIO Failed to Open \n");
            ledPurple();
            return -1;
      }

      struct sigaction action;
      memset(&action, 0, sizeof(struct sigaction));
      action.sa_handler = TerminationHandler;
      sigaction(SIGTERM, &action, NULL);

      epollFd = CreateEpollFd();
      if (epollFd < 0) 
      {
            ledPurple();
            return -1;
      }

      setupButtons(); // setup the buttons
      setConnections(); // setup the RGB LED
      // Tell the system about the callback function that gets called when we receive a device twin update message from Azure
      AzureIoT_SetDeviceTwinUpdateCallback(&deviceTwinChangedHandler);

      return 0;
}

This function sets up the GPIOs for the break beam module and the buttons, the RGB LED and IoT hub callbacks.

 

Send Data To Azure IoT

if (difftime(time_now.tv_sec, time_start.tv_sec) > runtime) // check if data should be sent to cloud
{
      println("[Program] Sending Data To Azure");
      char *pjsonBuffer = (char *)malloc(256);
      if (pjsonBuffer == NULL)
      {
            Log_Debug("ERROR: not enough memory to send telemetry");
            ledPurple();
      }

      setVariables(); // divide break beam count by 2 to get presence

      for (int i = 0; i < 3; i++)
      {
            ledOff();
            delay(1000);
            ledWhite();
            delay(1000);
      }

      // setup for getting time
      time_t      now;
      struct tm  ts;
      char        buf[32];

      // Get current time
      time(&now);

      // Format time, "ddd yyyy-mm-dd hh:mm:ss zzz"
      ts = *localtime(&now);
      strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.0Z", &ts); // Power Bi standard format

      // snprintf(bufferToSend, 128, JSON Payload Config (defined above), dataLable, dataValue);
      // compiles all data into a buffers
      snprintf(pjsonBuffer, 256, JSONBuffer, "presence", presence, "totalSales", totalSales, "cat1", cat1, "cat2", cat2, "cat3", cat3, "stringpresence", presence, "stringtotalSales", totalSales, "timestamp", buf);
      free(buf); // clear the JSON buffer
      Log_Debug("\n[Info] Sending telemetry %s\n", pjsonBuffer);
      AzureIoT_SendMessage(pjsonBuffer); // send the message to Azure

      // clear the timer and variables
      gettimeofday(&time_start, NULL);
      time_now = time_start;
      resetVariables();
      free(pjsonBuffer); // clear the JSON buffer
}

This is part of the main loop of the code, this section of code starts off by checking if it is the end of the business day. If it is, the device alerts the user by blinking the LED. The device then prepares the variables to be sent and compiles them into a buffer. The data is then sent to Azure IoT.

 

Step 5: Setting up Azure IoT

Now let’s move onto the backend. To get started sign in to Azure IoT and go to your home page.

  • Create a resource by selecting the option on the left of the screen and type IoT Hub. Select the option and create the resource using the following details. Create a new resource group for the project.

  • Create the IoT Hub and wait for it to create. The hub can either be an S1 or an F1.

  • After the deployment completed, go to the IoT Hub page and find the IoT Devices option from the menu on the left. Create a new IoT device by pressing the + button with the following details.

  • Save the device and return to the home screen.

 

Step 6: Changing Variables

It is very important to add your IoT hub connection to the application to allow the device to communicate with the backend. The steps below show you how to do this.

  • Download the code from GitHub and open it in Visual Studio. Wait for the solution to load.
  • From the solution explorer, open the solution.

  • Navigate to References in the Solution explorer and right click it. Next click on Add Connected Services. Select Azure IoT and select your subscription and device from the list.

  • Navigate to the app_manifest.json file from the solution explorer and copy the CmdArgs field.

  • Navigate to build_options.h from the solution explorer and paste the argument in the field provided.

Step 7: Setting up Stream Analytics Job

Next we need to set up the job that moves the messages from the IoT Hub to the Power Bi dataset.

  • Create another resource and search for Stream Analytics Job.
  • Select create and configure it with the following values:

  • Wait for the deployment to complete and return to the resource when it is. From the menu on the left, select Inputs and create a new input, select IoT Hub.

  • Select the IoT hub from your list and add it. Wait for the input to be tested.
  • After the input is tested, navigate to Outputs and select Power Bi.

  • Authenticate yourself using the button and then input the following data in the next window.

  • Click Save to add the output and then navigate to Query from the menu on the left. Click on the Edit button beside the query to edit it. Paste the code below into the query.
SELECT
                   presence as presence,
                   totalSales as totalSales,
                   stringpresence as presenceS,
                   stringtotalSales as totalSalesS,
                   cat1 as drinks,
                   cat2 as cake,
                   cat3 as lunch,
                   timestamp as timestamp
INTO
                   [OutputToPowerBi]
FROM
                   [InputFromAzureIoT]
  • Save the query and go back to the main page of the job.

  • Start the job by pressing the Start button.

Step 7: Flashing the Code

We now have to flash the application to the device to send some data to the backend. For this test, you will be needed to edit the runtime variable. This variable is located at the top of the main.c file, at line 38. This variable defines the amount of time between the device sends data to the cloud. Set it to 20 so the device sends data every 20 seconds but ensure to set it back before flashing the final code.

 

The code can be found at this GitHub Repo

 

Flash the code and press some buttons, you should see the data in the stream job by clicking on the Query option from the menu as before and waiting for the data to load.

 

Step 8: Setting up Power Bi

Now we need to set up Power Bi. If the stream analytics job ran successfully, you should find a dataset labelled SmartLocale in your Power Bi account. You must have the Power Bi app downloaded on your computer to get started.

  • Open the app and create a new report.
  • Open the dataset created by pressing Get Data at the top of the screen and then Power Bi Dataset.

  • The next step is to select the dataset from the list and click Create.
  • You should see the data populating the right of your screen.
  • You will now want to create some measures, to do this, right click on the name of the table (Table2 in our case) and select New Measure.

  • Now create 3 measures with the following code

 

Measure 1

Sales/Customer = (LASTNONBLANK(Table2[totalSales], 1) / LASTNONBLANK(Table2[presence], 1))

 

Measure 2

Max Presence/Customer = (MAX(Table2[totalSales]) / MAX(Table2[presence]))

 

Measure 3

Average Sales/Customer = (AVERAGE(Table2[totalSales]) / AVERAGE(Table2[presence]))

 

  • I split my report into 3 sections, to add a section , select the + button at the bottom of the window beside the name of the first section.
  • Now you can create your own graphs and visuals with Power Bi. If you need any help, you can always visit the Power Bi community, there is always someone there to help you. 

Step 9: Enclosure Schematics

I finally designed an enclosure for the project. The enclosure is made of acrylic. I drilled some holes for the buttons and LED in the enclosure. The image of the enclosure is below.