IoT with MuleSoft | Mule 4.2.2 |Real time use case | Live Demo | Temperature Sensor | LED light Blinking | Twilio
Sravan Lingam
MuleSoft Ambassador ???? Solution Architect ?? Mulesoft Meetup Leader ??All Certified MuleSoft Dev & Architect | 3 times MuleSoft All Star ??Award winner ???Owner of MuleSoft TechZone
Hey Muleys,
I have already shared a video on how to implement IoT with MuleSoft use case.
Here is detailed version of it! I would like you to try out some new use cases and publish them. Hope this article helps you to implement
First of all. Why only MuleSoft with IoT ? Why not other Integration platforms?
One quick answer to it in 2 words.
Ease of Integration & Speed of Delivery.
Let's Dive in.
Make sure you watch the videos posted at the end of the article ! You will get full idea on how easy is to implement it.
The Internet of Things (IoT) is the network of physical devices, vehicles, and other items embedded with electronics, software, sensors, actuators, and network connectivity which enable these objects to collect and exchange data. The Scope of IoT is not limited to just connecting things (device, appliances,machines) to the Internet. IoT allows these things to communicate and exchange data (control&information).
Simply , we can see its about connecting Software with Hardware!
MuleSoft + IoT :
? Mule engine can be embedded directly into IoT devices, which enables data exchange for the devices by connecting to IoT cloud services and backend apps in the cloud.
? The Mule Runtime engine can be used to expose APIs on any IoT device. Mule APIs can be deployed on IoT devices and turn them on and off.
? In this Article we will discuss about IOT and how it can be used with Mulesoft and how Mule APIs can be deployed on IoT devices.
Use Case :
When a user passes receiver’s number in the url , the receiver should receive the current local temperature details to his mobile and on successful receiving of details on his mobile, a green LED light should be blinked. In case of any issue in receiving details, the Red LED light should be blinked .
How does it work internally?
When you hit the below end point:
https://localhost:8081/test?toNumber=919999999999
The request comes to Mule application. The receiver number is stored in a variable .Then the Mule App connects to Raspberry PI (IoT device) and sense the Temperature using temperature sensor . Then the temperature is stored in a variable and then send the details to receiver mobile number using Twilio Connector. On successful receiving of details, a Green RED Light is blinked else RED Led .
Let’s cook the recipe :
Software’s Required:
– Rasbian OS - https://www.raspberrypi.org/downloads/raspbian/
– SD formatter - https://www.sdcard.org/downloads/formatter/
– Xming Display Server -https://xming.en.softonic.com/
– Win32 Disk imager - https://win32diskimager.download/
– PuTTY - https://www.putty.org/
– WinSCP - https://winscp.net/eng/download.php
– Mule Standalone Server (4.2.2) - https://www.mulesoft.com/lp/dl/mule-esb-enterprise
Hardware Required:
- Raspberry Pi 3 + Micro SD Card of 16GB + Ethernet Cable or HDMI cable (in this use case we are using ethernet cable) + Adapter Charger for Raspberry Pi 3 : Available in electronic stores or any e-commerce websites as a combo.
- I bought it at : https://www.amazon.in/gp/product/B07C6SN8PL/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1
- Resistors :
- 4k7 ohms (4.7k) - 1 (used for temp sensor)
- 22k ohms : 2 in numbers (used for RED and GREEN LED light each )
- Jumper wires : Male – Female (10 for safe side)
- Bread Board : 1
- Temperature Sensor : DS18B20 model
- Red and Green LED lights : One each
Let’s cook the recipe :
Part 1 - Setting up Raspberry PI:
Things to be completed before starting these steps :
Download and Install SD Card formatter , Win32 Disk imager ,WinSCP, Putty, Xming and keep it ready handy. Also have some basic touch with linux commands.
Step 1: Download and install Raspbian
Download Raspbian OS (url mentioned in software requirements). Download “Rasbian Buster with Desktop and recommended software” . It’s almost 2.5 GB .
While it is downloading Parallelly insert your micro SD card into your system and format it using SD Card formatter.
Now extract the downloaded Raspbian OS in your local. You can see only one file of type Disk image.
We can’t unzip them normally. That’s the reason we use Win32 disk Imager to extract and copy them to Micro SD card.
Open win32 disk imager and you can see that the destination folder will be automatically detected (here is SD card) and just select the file where you have extracted Raspbian and click on write. It takes a while usually 9 mins . Once done it says write succefull .
Now your OS is copied successfully in your SD card.
Step 2: To enable ssh
The ssh command provides a secure encrypted connection between two hosts over an insecure network. This connection can also be used for terminal access, file transfers, and for tunneling other applications.
As we need to see what’s happening in Raspberry PI , we need an UI to see it. So to get things setup for UI, we need ssh enabled.
Simple thing. Go to SD card folder you can see the extracted files which are extracted using win32 disk imager. Now Just create a text file and name it as ssh.
After creating , remove the SD Card from your PC
Step 3: Network and Sharing:
Now we need to connect our Raspberry device to our system. As I said before we have 2 ways. One using HDMI cable which required wifi sharing , a monitor , keyboard and mouse to perform operations. To go for alternative better use Ethernet cable which helps us to get connected with our PC itself.
In this usecase, we are using Ethernet connectivity.
After ejecting the SD card. Mount you SD card to your Raspberry PI. See the slot where it needs to be inserted(usually it will be downside of the pi ). And plug the adaptor and switch on.
Now connect the ethernet cable , on side connected to Raspberry PI and other to your PC.
Make sure you PC is already connected to wifi or internet before plugging ethernet cable.
Once ethernet cable is plugged to your PC. Go to Network and Sharing center . You will see un identified network.
See below screenshot:
Now click on the connections of internet which you have already connected to . Click on Wifi – properties.
Goto sharing and see that 2 options in Internet Connection Sharing are checked. Also See that Home networking connection is automatically generated with name “Ethernet” (you can go through the video I shared at the end)
Now click on unidentified network (ethernet) . Goto Properties and double click on “Internet Protocol Version 4 (TCP/IPv4). Under “Use the following IP address” see that a IP addressed is automatically shown . Copy that IP address as we will be using the same IP to connect to Raspberry PI.
Step 4 : Connecting to Raspberry using Putty:
Before connecting using Putty , make sure you have open Xming (assuming its downloaded and installed already ).
Now goto Putty :
Make below config:
Hostname : raspberrypi.mshome.net (this is default hostname for raspberry pi. You can also use IP address generated above but better use the hostname mentioned)
Port: 22
Go to SSH and make config as below
Save with some name. Now all ready to connect to our device.
Now click on Open. You will get a security alert warning. Click on yes to proceed.
A cmd prompt is popped out asking to login as
Default login details are :
Login as : pi
Password: raspberry
Now you are connected to “pi” user of your Raspberry device.
To see a Graphical view of your device(genrally another system which runs on Raspbian OS).
Use below command in putty command :
pi@raspberrypi : $ startlxde
Now your Xming opens !
Now Have your LXTerminal pinned on your desktop .
Open Terminal and type below command:
pi@raspberrypi : $ sudo raspi-config
A blue prompt appears. It has option1 to change password. Make sure you change password and finish off.
Now we are all set. Lets go to further steps
Step 5: Installing Java
After changing password successfully . We need to install Java version 8 .
By default there’s java,python already installed when we have download Raspbian OS.
If you check the version(use java -version command), we see Java 11.x version is already installed. We have some permission issues with 11 version. That’s the reason we are going to install Java 8 version for this use case. Before installing , uninstall Java 11 version. Use below commands for uninstalling java 11 and then installing java 8 accordingly.
To uninstall Java 11:
pi@raspberrypi : $ sudo apt-get purge openjdk*
To install Java 8:
pi@raspberrypi : $ sudo apt-get install openjdk-8-jdk
Between installation it ask you to continue or not. Type y and enter (see installation in the video link shared at the end of article)
Now check Java version again. It will show Java 8
Now we have setup our Raspberry OS. All 5 steps are related to Raspberry and has nothing to do with Mule installation. This are common steps for setting up Raspberry PI device
Part 2 - Setting up Raspberry PI
Step 1: Installing Mule Stand Alone server
Open browser in Xming (in raspberry pi). And go to link I shared in software requirements to download mule standalone server. Download the server.
While it is getting downloaded , we shall create a new user with name “mule”. All MuleSoft operations are carried out by this user(not mandatory but good to create one).
Creating Mule user:
Type below command:
pi@raspberrypi : $ sudo su – root@raspberrypi : # useradd -s /bin/bash -d /home/mule -U -G sudo mule root@raspberrypi : # passwd mule New Password: Retype New Password:
Your “mule” user is now created successfully .
Now create a director and give all necessary permissions Use below commands:
root@raspberrypi : # mkdir /home/mule /opt/mule root@raspberrypi : # chown mule:mule /opt/mule root@raspberrypi : # exit logout
Now its time to look at mule-standalone server.
Your Mule standalone is downloaded and will be Downloads folder of pi user.
Follow below commands next:
pi@raspberrypi : $ cd /home/pi/Downloads pi@raspberrypi :~/ Downloads$ chmod 777 * pi@raspberrypi :~/ Downloads$ su -mule Password: <enter your password and click enter> mule@raspberrypi :~$ cd /home/pi/Downloads mule@raspberrypi : /home/pi/Downloads$ cp mule-ee-distribution-standalone-4.2.2.zip /opt/mule mule@raspberrypi : /home/pi/Downloads$ cd /opt/mule mule@raspberrypi : /opt/mule$ unzip mule-ee-distribution-standalone-4.2.2.zip mule@raspberrypi : /opt/mule$ cd mule-ee-distribution-standalone-4.2.2 mule@raspberrypi : /opt/mule/mule-ee-distribution-standalone-4.2.2$ cd /opt/mule
Mule runtime uses the Tanuki Service Wrapper, which allows a Java-based application (that’s right, such as Mule runtime) to be started as a Windows Service or UNIX daemon. However, out-of-the-box, the bundled Service Wrapper is not optimized for Raspberry Pi’s ARM architecture. Therefore, the next step is to download the Armhf port of the Java Service Wrapper and patch the bundled Service Wrapper by copying a few required files to the Mule runtime directory.
Additional config files needed:
mule@raspberrypi:/opt/mule $ wget https://download.tanukisoftware.com/wrapper/3.5.34/wrapper-linux-armhf-32-3.5.34.tar.gz tar zxf wrapper-linux-armhf-32-3.5.34.tar.gz mule@raspberrypi:/opt/mule $ cp ./wrapper-linux-armhf-32-3.5.34/lib/libwrapper.so ./mule-standalone-4.2.2/lib/boot/libwrapper-linux-armhf-32.so mule@raspberrypi:/opt/mule $ cp ./wrapper-linux-armhf-32-3.5.34/lib/wrapper.jar ./mule-standalone-4.2.2/lib/boot/wrapper-3.2.3.jar mule@raspberrypi:/opt/mule $ cp ./wrapper-linux-armhf-32-3.5.34/bin/wrapper ./mule-standalone-4.2.2/lib/boot/exec/wrapper-linux-armhf-32
Next Steps:
Exit current terminal and re-open it. It comes with pi user
mule@raspberrypi:/opt/mule $ cd mule-enterprise-standalone-4.2.2 mule@raspberrypi:/opt/mule/mule-enterprise-standalone-4.2.2$ cd conf mule@raspberrypi:/opt/mule/mule-enterprise-standalone-4.2.2/conf $ vi wrapper.conf
The mule file comes in edited format
Change below lines as mentioned and save it:
# Initial Java Heap Size (in MB) wrapper.java.initmemory=256 # Maximum Java Heap Size (in MB) wrapper.java.maxmemory=512
Now Final Step:
mule@raspberrypi:/opt/mule/mule-enterprise-standalone-4.2.2 $ cd bin mule@raspberrypi:/opt/mule/mule-enterprise-standalone-4.2.2/bin $ ./mule
The server is up and running Now:
Step 2:Developing Mule Application:
Now we shall develop a RestFul application in your local (Windows) syatem. And then run the application which generates snapshot jar file.
Connectors used :
· Groovy script :
o This component is used to run python scripts. Use operation groovy.
· Twilio:
o This component is used to send message to user
· Transform Message :
o Setting variables , also structuring message before sending to twilio.
Note: You are not writing any python scripts in mule application. The python scripts to light LED’s and sense temperature are already written and placed in a specified location. The location path is given in groovy scripts
See that you have given proper message structure before sending to twilio . as twlio expectes a specified format which has body, to ,from and message
Also Make sure you have a developer account with Twilio and make sure whatever number you are passing must be registered with Twilio before itself. Messages are sent Only to registered numbers .
If you are not okay of using Twilio , it’s fine. You can build your own use case. Like printing the temperature etc.
Code for the developed app is pasted at the end of article.
Run your application. Once deployed copy the jar file generated in target folder to your Raspberry device folder using WinSCP
Open WinSCP . Use same host,port details as we connected in putty.It will ask for username and password. Enter username as “pi” and password.
Copy the file form windows PC to /home/pi/Downloads folder of your Raspberry PI
Step 3:
Connections in Raspberry PI:
Remember – Physical numbering is different from GIPO pin number. Watch the video on how to make connections.
Make connections referring to below picture
Connection with Jumper wires:
Note physical numbering is normal 1,2,3…42
GIPO is different. Connections please go with physical numbering. In python script you can see GIP pin numbers. Do not get confused
Green LED light :
GIPO Numbering:
Voltage : GIPO17
Ground : Any nearest ground pin
Physical Number:
Voltage : 11th pin
Ground : 14th pin
Red LED light:
GIPO Numbering:
Voltage : GIPO26
Ground : Any nearest ground pin
Physical Number:
Voltage : 37th pin
Ground : 39th pin
Temperature sensor:
GIPO Numbering:
Voltage : 3V3
Ground : Any nearest ground pin
Data : GIPO 4
Physical Number:
Voltage : 1st pin
Ground : 6th pin
Data : 7th Pin
See the below video on how to make connections
*Important *:
Before executing python scripts via mule app, make sure you run python scripts independently (as python is installed already by default when Raspbian OS is installed).
$ python /home/pi/Downloads workingTemp.py
Before running python scripts via mule app give the necessary permissions : like chmod 777 & chmod a+x
This is very important. Orelse you cant run scripts using mule app
Step 4:
Use following commands to deploy your application suing mule server
Open LxTerminal:
pi@raspberrypi: ~ $ cd /home/pi/Downloads pi@raspberrypi: ~/Downloads $ chmod 777 raspberry-temperature-new-1.0.0-SNAPSHOT-mule-application.jar pi@raspberrypi: ~/Downloads $ chmod a+x raspberry-temperature-new-1.0.0-SNAPSHOT-mule-application.jar
Write Python Scripts:
greenLight.py:
redLight.py:
temperature.py
?
Giving permissions to python scripts:
pi@raspberrypi: ~/Downloads $ chmod 777 greenLight.py pi@raspberrypi: ~/Downloads $ chmod a+x greenLight.py pi@raspberrypi: ~/Downloads $ chmod 777 redLight.py pi@raspberrypi: ~/Downloads $ chmod a+x redLight.py pi@raspberrypi: ~/Downloads $ chmod 777 temp.py pi@raspberrypi: ~/Downloads $ chmod a+x temp.py
Final Step:
pi@raspberrypi: ~/Downloads $ su -mule Password: <enter password> mule@raspberrypi: ~ $ cd /home/pi/Downloads mule@raspberrypi:cd /home/pi/Downloads$ cp raspberry-temperature-new-1.0.0-SNAPSHOT-mule-application.jar /opt/mule/mule-enterprise-standalone-4.2.2/apps
As server is already up and running, the app is successfully deployed.
Checkout below videos to test success and failure scenarios:
For success :
For Failure:
For connections on breadboard:
For full setup :
Hardware pics:
Raspberry PI:
Jumper wires(Male to Female):
Temperature sensor:
4k7 resistor:
22k resistor:
Raspberry Pins:
Mule App Code:
<?xml version="1.0" encoding="UTF-8"?> <mule xmlns:db="https://www.mulesoft.org/schema/mule/db" xmlns:twilio-connector="https://www.mulesoft.org/schema/mule/twilio-connector" xmlns:scripting="https://www.mulesoft.org/schema/mule/scripting" xmlns:ee="https://www.mulesoft.org/schema/mule/ee/core" xmlns:http="https://www.mulesoft.org/schema/mule/http" xmlns="https://www.mulesoft.org/schema/mule/core" xmlns:doc="https://www.mulesoft.org/schema/mule/documentation" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://www.mulesoft.org/schema/mule/core https://www.mulesoft.org/schema/mule/core/current/mule.xsd https://www.mulesoft.org/schema/mule/http https://www.mulesoft.org/schema/mule/http/current/mule-http.xsd https://www.mulesoft.org/schema/mule/ee/core https://www.mulesoft.org/schema/mule/ee/core/current/mule-ee.xsd https://www.mulesoft.org/schema/mule/scripting https://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd https://www.mulesoft.org/schema/mule/twilio-connector https://www.mulesoft.org/schema/mule/twilio-connector/current/mule-twilio-connector.xsd https://www.mulesoft.org/schema/mule/db https://www.mulesoft.org/schema/mule/db/current/mule-db.xsd"> <http:listener-config name="HTTP_Listener_config" doc:name="HTTP Listener config" doc:id="1f79f7af-0874-4818-9b31-9a77b3c14240" > <http:listener-connection host="0.0.0.0" port="8081" /> </http:listener-config> <scripting:config name="Scripting_Config" doc:name="Scripting Config" doc:id="2c707185-8159-47fe-b8f1-8d191a236a00" /> <twilio-connector:config name="Twilio_Connector_Config" doc:name="Twilio Connector Config" doc:id="d345e33c-10c6-44cf-b6fe-6808702e6f12" property_username="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" property_password="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" > <twilio-connector:connection /> </twilio-connector:config> <flow name="nbuw-testFlow" doc:id="85f9e606-ef49-4298-8781-ee3eca55a48f" > <http:listener doc:name="Listener" doc:id="2f4ac9e4-1891-4a2d-9956-b5f1be11e757" path="/test" config-ref="HTTP_Listener_config"/> <ee:transform doc:name="set toNum" doc:id="66813c22-07ad-4498-b485-306971767031" > <ee:message > </ee:message> <ee:variables > <ee:set-variable variableName="toNum" ><![CDATA[attributes.queryParams.toNum]]></ee:set-variable> </ee:variables> </ee:transform> <scripting:execute doc:name="exTemp" doc:id="07be3954-f861-4c04-8949-cb56d5c5a669" engine="groovy"> <scripting:code >def command = "python /home/pi/Downloads/workingTemp.py" println "$command" def cmd=command.execute()</scripting:code> </scripting:execute> <ee:transform doc:name="set temp" doc:id="39b19cc4-84a9-45ff-b649-43e4c0e4f257" > <ee:message > </ee:message> <ee:variables > <ee:set-variable variableName="temp" ><![CDATA[%dw 2.0 output text/plain --- payload.inputStream default '10']]></ee:set-variable> </ee:variables> </ee:transform> <try doc:name="Try" doc:id="8a673a17-2459-4b9b-b9b1-343d65111442" > <ee:transform doc:name="twPayload" doc:id="f120c417-895e-4e29-a28d-61c17f5b2804" > <ee:message > <ee:set-payload ><![CDATA[%dw 2.0 output application/json --- { Body: "Hi,Temperature is :" ++ vars.temp as String ++ ".Mule is on Fire", From: "+16156714137", To: "+" ++ vars.toNum } as Object { class : "org.mule.modules.twilio.pojo.sendmessagerequest.MessageInput" } ]]></ee:set-payload> </ee:message> </ee:transform> <twilio-connector:send-message doc:name="Send message" doc:id="ae911091-1cf9-4ed8-9bbd-4cbb2d40bb39" config-ref="Twilio_Connector_Config" account-sid="AC458d2ec378410589ff55a3ebabb355c7" /> <scripting:execute doc:name="exGLight" doc:id="232b2300-360e-47b7-9acc-6795f8026d63" engine="groovy"> <scripting:code >def command = "python /home/pi/Downloads/greenLight.py" println "$command" def cmd=command.execute()</scripting:code> </scripting:execute> <ee:transform doc:name="success" doc:id="2b15cf27-8ba6-41e5-a2de-7ac190ff7476" > <ee:message > <ee:set-payload ><![CDATA['Temperature Recorded and sent message']]></ee:set-payload> </ee:message> </ee:transform> <error-handler > <on-error-continue enableNotifications="true" logException="true" doc:name="On Error Continue" doc:id="ee3458e6-a18b-4da7-a0a8-260bb82f1b4b" > <scripting:execute doc:name="Execute RedLigt Script" doc:id="d4d9f4b6-3da9-44a6-a23f-6e90204b0d60" engine="groovy"> <scripting:code >def command = "python /home/pi/Downloads/redLight.py" println "$command" def cmd=command.execute()</scripting:code> </scripting:execute> <ee:transform doc:name="sucsess" doc:id="cd71422c-a826-49f4-afe6-2fbe53d60ca7" > <ee:message > <ee:set-payload ><![CDATA['Temperature Recorded but Message sending failed message']]></ee:set-payload> </ee:message> </ee:transform> </on-error-continue> </error-handler> </try> <logger level="INFO" doc:name="Logger" doc:id="cec8bb89-d4a9-4660-9c65-8b862395eb39" message="#[payload]"/> </flow> </mule>
Hope this article helps you to do some real time use cases!
Happy Learning!!
Yours Sravan Lingam :)
Manager - Technology Consulting at Accenture UK
4 年Thank you Sravan - it's really great.
Loading........
4 年Sravan, thank you for sharing this great article.
MuleSoft Ambassador | Salesforce MuleSoft Partner Advisory Board Member | Solutions Architect at DXC Technology
4 年Suresh Dhaka
Full-Stack Lead, Liferay 7.x, Liferay DXP, Angular JS, Spring Boot, Microservices, Java, Docker, Mule ESB, Liferay Certified, AWS
4 年That's really great demo and more to it its explained well!
Senior Technical consultant at Salesforce
4 年Nice Article. Sravan Lingam??