aboutsummaryrefslogtreecommitdiff
path: root/mavigator-uav/src/main/scala/mavigator/uav/serial/SerialBackend.scala
blob: 878e8914e1f54fce6f5046613cc03835e61c3336 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package mavigator
package uav
package serial

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.{Failure, Success}

import akka.NotUsed
import akka.serial.{Parity, SerialSettings}
import akka.serial.stream.Serial
import akka.serial.stream.Serial.Connection
import akka.stream.scaladsl.{Flow, Keep}
import akka.util.ByteString

object SerialBackend extends Backend {

  override def init(core: Core): Unit = {
    import core.materializer
    import core.system
    import core.system.dispatcher

    system.log.info("Initializing serial backend...")

    val conf = system.settings.config.getConfig("mavigator.uav.serial")
    val port = conf.getString("port")
    val serialSettings = SerialSettings(
      baud = conf.getInt("baud"),
      twoStopBits = conf.getBoolean("two_stop_bits"),
      parity = Parity(conf.getInt("parity"))
    )

    val connectionDelay = conf.getInt("connection_delay").millis

    system.log.info("Waiting for serial device on " + port + "...")
    Serial().watch(Set(port)).map{ port =>
      system.log.info("Serial device connected on port " + port)
      port
    }.delay(connectionDelay).runForeach{ port =>
      system.log.info("Opening serial port " + port)

      val backend: Flow[ByteString, ByteString, NotUsed] = core.setBackend()

      val uav: Flow[ByteString, ByteString, Future[Connection]] = Serial().open(port, serialSettings)

      val connection = uav.joinMat(backend)(Keep.left).run().onComplete{
        case Success(connection) =>
          system.log.info("Successfully opened serial port " + connection.port)
        case Failure(ex) =>
          system.log.error(ex, "Error occurred while trying to open " + port)
      }

    }


  }

}