IOT application using Scala on RaspberryPi

IOT application using Scala on RaspberryPi

  • 2016-09-06
  • 1702

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

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

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

And finally we are going to achieve this:

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:

  1. ssh into the RaspberryPi.
ssh [email protected]
  1. Download the scala on the raspberryPi.

  1. Install scala by using the dpkg command.
sudo dpkg -i scala-2.11.8.deb
  1. Check if scala is correctly installed by using scala-repl.
  1. 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 /" | sudo tee -a /etc/apt/sources.list.d/sbt.list
sudo apt-key adv --keyserver hkp:// --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 [email protected]

object MQTTPublisher extends App {

  val config = ConfigFactory.load()
  val url = ""
  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)
      val msgTopic = client.getTopic(topic)
      val message = new MqttMessage(getMessage.getBytes("utf-8"))
      while (true) {
        val msgPublished=msgTopic.publish(message)
        println(s"Publishing the data topic ${msgTopic.getName} message: ${message.toString}")
    catch {
      case exception: MqttException => println(s"ExceptionOccured:$exception ")
    finally {

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 [email protected]

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)
    val callback = new MqttCallBackImpl



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 = {

  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 :shiv4nshscala-mqtt-client-rasberrypi-starter-kit

Deploying the Application:

Steps for deploying the application are:

  1. We are considering here two device solution : Dev_Laptop (Subscriber) and Dev_RasberryPi (Publisher)

  2. So start your Mosquitto on Dev_Laptop.


  3. Configure the application.conf with the port and the url of the mosquitto server.

  4. Make a assembly jar of this project using the following command.

 sbt assembly
  1. Copy the jar to RaspberryPi using the scp command.
  scp raspi-mqtt-client.jar pi@:/home/pi/Projects/scala
  1. 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.
  1. 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.


Advanced Home Automation using Raspberry Pi 3

Complete Guide to Build IOT Things from Scratch to Market

Fundamentals of IoT Development with ThingWorx

IoT enabled Aeroponics using Raspberry Pi 3

Hands on Internet of Things: Get started with a Raspberry Pi

Microcontrollers for the Internet of Things