aboutsummaryrefslogtreecommitdiff
path: root/flow-core/src/main/scala/com/github/jodersky/flow/SerialOperator.scala
blob: ec0ee278023c4f5a26bb2b528255a14dd9ff9aed (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
package com.github.jodersky.flow

import akka.actor.{ Actor, ActorLogging, ActorRef, Props, Terminated, actorRef2Scala }
import internal.{ Reader, SerialConnection, ThreadDied }
import java.nio.ByteBuffer

/**
 * Operator associated to an open serial port. All communication with a port is done via an operator. Operators are created though the serial manager.
 * @see SerialManager
 */
class SerialOperator(connection: SerialConnection, bufferSize: Int, client: ActorRef) extends Actor with ActorLogging {
  import SerialOperator._
  import context._

  val readBuffer = ByteBuffer.allocateDirect(bufferSize)
  val reader = new Reader(connection, readBuffer, self, client)
  val writeBuffer = ByteBuffer.allocateDirect(bufferSize)

  context.watch(client)
  client ! Serial.Opened(connection.port)
  reader.start()

  override def postStop = {
    connection.close()
  }

  def receive: Receive = {

    case Serial.Write(data, ack) => {
      writeBuffer.clear()
      data.copyToBuffer(writeBuffer)
      val sent = connection.write(writeBuffer)
      if (ack != Serial.NoAck) sender ! ack(sent)
    }

    case Serial.Close => {
      client ! Serial.Closed
      context stop self
    }

    case Terminated(`client`) => {
      context stop self
    }

    //go down with reader thread
    case ThreadDied(`reader`, ex) => throw ex

  }

}

object SerialOperator {
  def apply(connection: SerialConnection, bufferSize: Int, client: ActorRef) = Props(classOf[SerialOperator], connection, bufferSize, client)
}