aboutsummaryrefslogtreecommitdiff
path: root/flow/src/main/scala/com/github/jodersky/flow/SerialOperator.scala
blob: 69db4dfcc51052fbafddb842db0ce9d4205ff1c9 (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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.github.jodersky.flow

import java.io.IOException
import com.github.jodersky.flow.internal.InternalSerial
import Serial._
import akka.actor.Actor
import akka.actor.ActorLogging
import akka.actor.ActorRef
import akka.actor.Terminated
import akka.actor.actorRef2Scala
import akka.util.ByteString
import scala.collection.mutable.HashSet
import akka.actor.Props

/**
 * 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(serial: InternalSerial, client: ActorRef) extends Actor with ActorLogging {
  import SerialOperator._
  import context._

  private object Reader extends Thread {
    def readLoop() = {
      var continueReading = true
      while (continueReading) {
        try {
          val data = ByteString(serial.read())
          client ! Received(data)
        } catch {

          //port is closing, stop thread gracefully
          case ex: PortInterruptedException => {
            continueReading = false
          }

          //something else went wrong stop and tell actor
          case ex: Exception => {
            continueReading = false
            self ! ReadException(ex)
          }
        }
      }
    }

    override def run() {
      this.setName("flow-reader " + serial.port)
      readLoop()
    }
  }
  
  
  client ! Opened(serial.port)
  context.watch(client)
  Reader.start()
  

  override def postStop = {
    serial.close()
  }

  def receive: Receive = {

    case Write(data, ack) => {
      val sent = serial.write(data.toArray)
      if (ack != NoAck) sender ! ack
    }

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

    //go down with reader thread
    case ReadException(ex) => throw ex

  }

}

object SerialOperator {
  private case class ReadException(ex: Exception)
  
  def apply(serial: InternalSerial, client: ActorRef) = Props(classOf[SerialOperator], serial, client)
}