what does it take to a business to be ready for Industry 4.0 
Tags: machinelearning, python, azure, aws
Published: 2020-09-24 22:10:46

in this article i'm going to show you the basic knowledge you'll need to deploy your first IoT device and connect it to a Cloud IoT Service provider, i'm using Microsoft Azure due to its clear, user-friendly documentation. 
i believe doing it yourself and manually will give you insights about what a business needs to make a successful shift into 4.0 industry.  

### What is Industry 4.0 : 
the first industrial revolution happened in the late 1700's, and now we are living its fourth revolution : the digitalization of the manufacturing process and making them self-aware with deep-learning models.

### Why Industry 4.0 is happening now ? 
to understand why the industrial internet is happening now while its technologies have been arround for decades we have to look at the traditional industry ineffeciencies which are mainly : 

+  the complexity of industrial systems has finally outpaced the human operator's ability to detect ineffeciencies, the outcome of this would be a large amount of machines that perform far below their capabilities, this factor alone is giving business owners a need to shift to 4.0

+  a big fall in the costs of compute, bandwidth, storage and sensors which means IT systems can now support industrial machine monitoring and analytics which is by the way the core of 4.0 industry and this fall of the costs is due to the Cloud technology offered by google, oracle and of course Amazon Web Services. The Cloud is now mature and make available powerful analytics tools.

Sensors are at the core of the 4.0 Industry due simply to the fact that they are our source of data in every industry, sensors types i know so far are not that much and very basic: 

+ Temperature
+ Humidity
+ Pressure
+ Proximity 
+ Level
+ Accelerometers
+ Gyroscope
+ Gas Sensors

### Connect a Sensor to the cloud and monitor a machine state: 

in the following i will use as a cloud Service provider Microsoft Azure because it is very well documented but the basic architecture is the same as Amazon's AWS. 
also, the main goal of this section is to show you how to get data from your sensors, if you don't have any sensors there is a way of connection your cpu's Temperature sensor instead of buying one.

you'll find here every single Azure's IoT provided service, however in this example i'm using [Azure IoT Hub](https://docs.microsoft.com/en-us/azure/iot-hub/) and [Azure Stream Analytics](https://docs.microsoft.com/en-us/azure/stream-analytics/) and maybe if you want to change your TensorFlow environement with [Azure Machine learning](https://docs.microsoft.com/en-us/azure/machine-learning/)

this application architecture looks like this : 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/8m9giq6q09xtooqwbi5z.png)

also because i don't have a raspberry or arduino processors, we will simulate one, and in order to do that we will create 2 Azure CLI sessions in the local machine one for the simulated device or even your cpu's Temperature sensor, and the other one is for monitoring the machine state and sending messages. 

launch the cloud shell in your account and add this command 

```az extension add --name azure-iot```

the az extension add command adds the Microsoft Azure IoT Extension for Azure CLI to your CLI shell. The IOT Extension adds IoT Hub, IoT Edge, and IoT Device Provisioning Service specific commands to Azure CLI.

### next step : connecting to IoT hub : 

Run the az group create command to create a resource group. The following command creates a resource group named MyResourceGroup in the eastus location.

```az group create --name MyResourceGroup --location eastus```

Run the az iot hub create command to create an IoT hub. It might take a few minutes to create an IoT hub.

YourIotHubName. Replace this placeholder below with the name you chose for your IoT hub. An IoT hub name must be globally unique in Azure. This placeholder is used in the rest of this quickstart to represent your IoT hub name.

```az iot hub create --resource-group MyResourceGroup --name {YourIoTHubName}```

Run the az iot hub device-identity create command in the first CLI session. This creates the simulated device identity. YourIotHubName. Replace this placeholder below with the name you chose for your IoT hub. simDevice. You can use this name directly for the simulated device in the rest of this quickstart. Optionally, use a different name.


```az iot hub device-identity create --device-id simDevice --hub-name {YourIoTHubName}```

```az iot device simulate -d simDevice -n {YourIoTHubName}```

Optionally, you can send cloud-to-device messages by using the Azure portal. To do this, browse to the overview page for your IoT Hub, select IoT Devices, select the simulated device, and select Message to Device.

```az iot device c2d-message send -d simDevice --data "Hello World" --props "key0=value0;key1=value1" -n {YourIoTHubName}```

you can confirm that your simulated device has received the message "hello world" thus, everything is working a connection is made.
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/rcqy7gngtav2b89f8cvs.png)

now that our (simulated) device is connected to IoT hub, we will run a python script that sends Humidity and Temperature data to IoT hub.

```python3
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

import random
import time

# Using the Python Device SDK for IoT Hub:
#   https://github.com/Azure/azure-iot-sdk-python
# The sample connects to a device-specific MQTT endpoint on your IoT Hub.
from azure.iot.device import IoTHubDeviceClient, Message

# The device connection string to authenticate the device with your IoT hub.
# Using the Azure CLI:
# az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyNodeDevice --output table
CONNECTION_STRING = "{Your IoT hub device connection string}"

# Define the JSON message to send to IoT Hub.
TEMPERATURE = 20.0
HUMIDITY = 60
MSG_TXT = '{{"temperature": {temperature},"humidity": {humidity}}}'

def iothub_client_init():
    # Create an IoT Hub client
    client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
    return client

def iothub_client_telemetry_sample_run():

    try:
        client = iothub_client_init()
        print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )

        while True:
            # Build the message with simulated telemetry values.
            temperature = TEMPERATURE + (random.random() * 15)
            humidity = HUMIDITY + (random.random() * 20)
            msg_txt_formatted = MSG_TXT.format(temperature=temperature, humidity=humidity)
            message = Message(msg_txt_formatted)

            # Add a custom application property to the message.
            # An IoT hub can filter on these properties without access to the message body.
            if temperature > 30:
              message.custom_properties["temperatureAlert"] = "true"
            else:
              message.custom_properties["temperatureAlert"] = "false"

            # Send the message.
            print( "Sending message: {}".format(message) )
            client.send_message(message)
            print ( "Message successfully sent" )
            time.sleep(1)

    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )

if __name__ == '__main__':
    print ( "IoT Hub Quickstart #1 - Simulated device" )
    print ( "Press Ctrl-C to exit" )
    iothub_client_telemetry_sample_run()
```

### now that we have Temperature Data we can do machine learning on it :
once the script is ran on the simulated device we will have the follwing output: 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pld952yj8gw9zp1uen86.png)

we can model the temperature data with python's scikit-learn for Time Series. here you find some of the fancy plots i got:

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4gsi7nteewi5lner3pgb.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/bxpi2c04vaylyeucmz66.png)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jcxsbdx2vr55r5ecf8wq.png)


![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/y5ut9lt3mlalj9mc784c.png)

###Temperature Trend

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/yojcgwaph9p77xo133r6.png)

###Temperature Seasonality

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/6a1b6n1lssnan6e4lq1b.png)


##Conclusion:

to summerize this humble work, IIoT or Industry 4.0 is a great technology that aims to improve manufacturing process and making it self-aware and smarter in order to catch up to machine speed and thus making the production process more efficient. 

However to make a successful shift to this digital Area a business owner need to improve his staff cloud skills and recruit a whole team of data anaylysts and data scientists as well as software engineers and developers.

Also, with sensors price drop, one is able to get as many as possible sensors because as we saw above more sensors means more data and more data means better precision of forcasting models.