aboutsummaryrefslogtreecommitdiff
path: root/scala/ace/src/main/scala/com/github/jodersky/ace/Framer.scala
blob: 8546c48098fae1b2ffea8df196f5be3b3701d45f (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
package com.github.jodersky.ace

import scala.collection.mutable.ArrayBuffer
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

/** A framer takes bytes (as unsigned integers) and creates frames.
 *  Note that the input type of this reactive layer is also a sequence of
 *  integers for performance reasons (i.e. a future will not be created for every byte sent).
 */
class Framer extends ReactiveLayer[Seq[Int], Seq[Int]] {
  import Framer._

  private var state: State = Waiting
  private val buffer = new ArrayBuffer[Int]

  protected def receive(bytes: Seq[Int]) = bytes foreach receive
  
  protected def receive(byte: Int): Unit = {

    state match {
      case Escaping => {
        buffer += byte
        state = Receiving
      }
      case Waiting => if (byte == Start) {
        buffer.clear()
        state = Receiving
      }
      case Receiving => byte match {
        case Escape => state = Escaping
        case Start => buffer.clear()
        case Stop => {
          state = Waiting
          if (checksum(buffer.init) == buffer.last)
            notifyHigher(buffer.init)
        }
        case datum => buffer += datum
      }
    }
  }

  def send(data: Seq[Int]): Future[Seq[Int]] = {
    val buffer = new ArrayBuffer[Int]
    
    buffer += Start    
    data foreach { byte =>
      byte match {
        case Start | Stop | Escape => {
          buffer += Escape
          buffer += byte
        }
        case _ => buffer += byte
      }
    }
    val c = checksum(data)
    c match {
        case Start | Stop | Escape => {
          buffer += Escape
          buffer += c
        }
        case _ => buffer += c
      }
    buffer += Stop
    sendToLower(buffer) map (_ => data)
  }
}

object Framer {
  sealed trait State
  case object Waiting extends State
  case object Receiving extends State
  case object Escaping extends State

  final val Escape = 0x10
  final val Start = 0x02
  final val Stop = 0x03

  def checksum(unsignedData: Seq[Int]) = {
    unsignedData.fold(0)(_ ^ _)
  }

}