aboutsummaryrefslogtreecommitdiff
path: root/scala/src/main/scala/com/github/jodersky/ace/protocol/PhysicalLayer.scala
blob: 39c2d25458b7a3d681e95be26b5daf0e8dffe019 (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
package com.github.jodersky.ace.protocol

import scala.concurrent._
import scala.concurrent.ExecutionContext.Implicits.global
import jssc.SerialPort
import java.io.IOException
import jssc.SerialPortEvent
import jssc.SerialPortEventListener

class PhysicalLayer(serial: SerialPort) extends ReactiveLayer[Nothing, Array[Byte]] {

  def receive(nothing: Nothing) = throw new UnsupportedOperationException("A receive function cannot be called on the lowest layer.")

  private val listener = new SerialPortEventListener {
    override def serialEvent(event: SerialPortEvent) = {
      if (event.isRXCHAR()) {
        val bytes = serial.readBytes
        if (bytes != null) notifyHigher(bytes)
      }
    }
  }
  

  def write(data: Array[Byte]) = future {
    serial.writeBytes(data)
  } map { success =>
    if (success) data
    else throw new IOException("Could not write to serial port.")
  }
  
  def begin() = {
    val mask = SerialPort.MASK_RXCHAR + SerialPort.MASK_CTS + SerialPort.MASK_DSR
    serial.setEventsMask(mask)
    serial.addEventListener(listener)
  }

}