Reading Time: 5 minutes

Let’s start our journey for making the first IoT application to make world a better place 😉

(I would never miss a chance to mock Hooli ! 😉 )

In this blog finally the two technologies SCALA and IOT will meet and we will be doing these many things in this blog:

Setting up the scala sbt environment on RaspberryPi Developing your first IOT application using Scala Deploying the developed application on RaspberryPi.

And finally we are going to achieve this:

To those who have not been following this series, this is what has happened till now :

Till now we have basic understanding of IOT and MQTT and we have setup our RaspberryPi so that we can access the RaspberryPi’s desktop on our laptop screen !

Setting up the Scala environment : Installing Scala

We are going to install scala and sbt environment simply:

ssh into the RaspberryPi. ssh pi@192.168.0.1 Download the scala on the raspberryPi. wget https://downloads.lightbend.com/scala/2.11.8/scala-2.11.8.deb Install scala by using the dpkg command. sudo dpkg -i scala-2.11.8.deb Check if scala is correctly installed by using scala-repl. scala You have successfully installed scala.

Now we have a basic setup of scala but we want to make project hence we need sbt now !

Setting up the sbt environment: Installing sbt

For installing sbt we have to run the following commands on the shell

echo "deb https://dl.bintray.com/sbt/debian /" | sudo tee -a /etc/apt/sources.list.d/sbt.list sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 2EE0EA64E40A89B84B2DF73499E82A75642AC823 sudo apt-get update sudo apt-get install sbt

Now we have set up the environment and now we have to develop the application

Developing your first basic IoT application using Scala

General Idea: So what this application would be doing is that , it would be sending the temperature of the CPU of RaspberryPi to a MQTT server with the Temperature as a topic and a client will be deployed on your laptop

So here we are using mosquitto as the MQTT server because akka-mqtt server that I have been working on is still WIP .

Sending the Temperature Event:

So here is the code for sending the temperature that we would be deploying on RaspberryPi.

package com.knoldus import com.typesafe.config.ConfigFactory import org.eclipse.paho.client.mqttv3.{MqttClient, MqttException, MqttMessage} import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence import scala.sys.process._ /** * * MQTT publisher * * @author Shivansh * @mail shiv4nsh@gmail.com * */ object MQTTPublisher extends App { val config = ConfigFactory.load() val url = "192.168.0.8" val port = config.getInt("mosquitto-server.port") def publishToserver() = { println("Hey I am publishing") val brokerUrl = s"tcp://$url:$port" val topic = "TemperatureEvent" val tempCommand = "/opt/vc/bin/vcgencmd measure_temp" def getMessage = s"Temperature of CPU at ${System.currentTimeMillis()} is ${tempCommand.!!.split("=")(1)} " var client: MqttClient = null val persistence = new MemoryPersistence try { client = new MqttClient(brokerUrl, MqttClient.generateClientId, persistence) client.connect() val msgTopic = client.getTopic(topic) val message = new MqttMessage(getMessage.getBytes("utf-8")) while (true) { val msgPublished=msgTopic.publish(message) msgPublished println(s"Publishing the data topic ${msgTopic.getName} message: ${message.toString}") Thread.sleep(1000) } } catch { case exception: MqttException => println(s"ExceptionOccured:$exception ") } finally { client.disconnect() } } publishToserver }

So here , what we are doing is we are running a command that fetches the temperature and we are making a topic “Temperature Event” and we are publishing the Message with the Current temperature of RaspberryPi.

This application will be running on the Raspberry Pi.

Setting up the Mosquitto server

Now this application is sending data to the mosquitto server that is running on the Laptop or raspi (wherever you want to) , in my case I am running mosquitto server on My laptop

You can download the mosquitto server from here.

It is a simple tar file just us the following command to uncompress it and then run the mosquitto server

tar -xvzf mosquitto-1.4.10.tar.gz

For further assistance you can take a look here for configuring Mosquitto server

This is how it looks like if it has started correctly:

Receiving the Temperature Events :

This code will be deployed on your laptop and we will be getting the messages from the mosquitto server for the topic “Temperature Events”

So here is the code for receiving the temperature event:

package com.knoldus import com.typesafe.config.ConfigFactory import org.eclipse.paho.client.mqttv3._ import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence /** * * MQTT subcriber * * @author Shivansh * @mail shiv4nsh@gmail.com * */ object MQTTSubscriber extends App { val config = ConfigFactory.load() val url = config.getString("mosquitto-server.url") val port = config.getInt("mosquitto-server.port") def subscribeToCommands() { val brokerUrl = s"tcp://$url:$port" val topic = "TemperatureEvent" val persistence = new MemoryPersistence val client = new MqttClient(brokerUrl, MqttClient.generateClientId, persistence) client.connect client.subscribe(topic) val callback = new MqttCallBackImpl client.setCallback(callback) } subscribeToCommands } class MqttCallBackImpl extends MqttCallback { override def messageArrived(topic: String, message: MqttMessage): Unit = { println(s"Receiving Data | Topic : $topic | Message : $message") } override def connectionLost(cause: Throwable): Unit = { println(cause.toString) } override def deliveryComplete(token: IMqttDeliveryToken): Unit = { println(s"Delivered Message :${token.getMessage}") } }

Here we are just receiving the data

For the Subscriber and Publisher we are using the Eclipse Paho library here.

You can easily find the whole code here on my github repo :shiv4nsh/scala-mqtt-client-rasberrypi-starter-kit

Deploying the Application:

Steps for deploying the application are:

We are considering here two device solution : Dev_Laptop (Subscriber) and Dev_RasberryPi (Publisher) So start your Mosquitto on Dev_Laptop. Configure the application.conf with the port and the url of the mosquitto server. Make a assembly jar of this project using the following command. sbt assembly Copy the jar to RaspberryPi using the scp command. scp raspi-mqtt-client.jar pi@:/home/pi/Projects/scala Run the Publisher on Dev_RaspberryPi using the following command java -cp raspi-mqtt-client.jar com.knoldus.MQTTPublisher This will start the publisher to sending the temperature events to broker. Run the Subscriber on Dev_Laptop using the following command java -cp raspi-mqtt-client.jar com.knoldus.MQTTSubscriber

Hurray !

Now you have made your first basic IOT application using Scala that can send the temperature of the RaspberryPi to the broker and the subscriber can subscribe to those events.

Note: Remember here the subscriber can be RaspberryPi as well its totally upto your architecture.

You can also find the get the code using the Lightbend activator from here.

So in the further blogs we will be deploying the same application on RaspberryPi and will try to get the Stream using the Apache Spark.

If you do not have RaspberryPi and still wanted to get started with IoT easily , then comment here , and let me know, maybe we can have the next blog on Developing your IoT application using NODE-RED and deploying it on IBM Bluemix for free.

If you found it interesting, do let me know here or on twitter : @shiv4nsh

You can also follow me if you wanna stay tuned to this Scala – IOT series and other IOT , Deep Learning related news ! 😉

So stay Tuned !

Till then Happy hAKKAing !

References:



