aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/scala/akka/serial/SerialManager.scala
blob: 4833165859e8090a3ebebcba14036a87fcd49425 (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
package akka.serial

import akka.actor.{ Actor, ActorLogging, OneForOneStrategy }
import akka.actor.SupervisorStrategy.{ Escalate, Stop }
import scala.util.{ Failure, Success, Try }
import sync.SerialConnection

/**
 * Entry point to the serial API. Actor that manages serial port creation. Once opened, a serial port is handed over to
 * a dedicated operator actor that acts as an intermediate between client code and the native system serial port.
 * @see SerialOperator
 */
private[serial] class SerialManager extends Actor {
  import SerialManager._
  import context._

  override val supervisorStrategy = OneForOneStrategy() {
    case _: Exception if sender == watcher => Escalate
    case _: Exception => Stop
  }

  private val watcher = actorOf(Watcher(self), "watcher")

  def receive = {

    case open @ Serial.Open(port, settings, bufferSize) => Try {
      SerialConnection.open(port, settings)
    } match {
      case Success(connection) => context.actorOf(SerialOperator(connection, bufferSize, sender), name = escapePortString(connection.port))
      case Failure(err) => sender ! Serial.CommandFailed(open, err)
    }

    case w: Serial.Watch => watcher.forward(w)

    case u: Serial.Unwatch => watcher.forward(u)

  }

}

private[serial] object SerialManager {

  private def escapePortString(port: String) = port map {
    case '/' => '-'
    case c => c
  }

}