Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Your First IoT Application Using Scala on RaspberryPi

DZone's Guide to

Your First IoT Application Using Scala on RaspberryPi

Here you can learn how to make your first basic IoT application using Scala that can send the temperature of the RaspberryPi to the broker.

· IoT Zone
Free Resource

Build an open IoT platform with Red Hat—keep it flexible with open source software.

Let’s start our journey for making the first IoT application to make the world a better place (I would never miss a chance to mock Hooli!).

In this blog, the two technologies SCALA and IoT will finally meet and we will be doing many other things such as:

  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:

IMG_20160827_203534_HDR

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

  1. Scala-IoT: Introduction to Internet Of Things.
  2. Scala-IoT: What is MQTT? How is it lightweight ?
  3. Scala-IoT: Getting started with RaspberryPi without Monitor or Screen.

Until now, we have a 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 pi@192.168.0.1
  2. Download Scala on the raspberryPi.
    wget https://downloads.lightbend.com/scala/2.11.8/scala-2.11.8.deb
  3.  Install Scala by using the dpkg command.
    sudo dpkg -i scala-2.11.8.deb
  4. Check if Scala is correctly installed by using scala-repl.
    scala
  5. 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 and 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 sending the temperature of the CPU of RaspberryPi to an 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 theMosquitto server that is running on the laptop or raspi (wherever you want to), in my case, I am runningMosquitto 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:

mosquitto

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 gGitHubrepo :shiv4nsh/scala-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. mosquitto
  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
  5. Copy the jar to RaspberryPi using the scp command.
    scp raspi-mqtt-client.jar pi@:/home/pi/Projects/scala
  6. 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.
  7. 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; it's totally up to  your architecture.

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

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

Download Red Hat’s blueprint for building an open IoT platform—open source from cloud to gateways to devices.

Topics:
scala ,project ,raspberry pi ,iot

Published at DZone with permission of Shivansh Srivastava, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}