aboutsummaryrefslogtreecommitdiff
path: root/mavigator-cockpit/src/main/scala/mavigator/cockpit/MavlinkWebSockets.scala
blob: b2ecf48fcdd1edf6ef45083f317351f7aea2a640 (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
package mavigator
package cockpit

import org.mavlink._
import org.mavlink.Parser.Errors._
import org.mavlink.messages._

import org.scalajs.dom
import scalajs.js

trait MavlinkWebSockets { self: Instruments =>

  private class MavlinkWebSocket(url: String, remoteSystemId: Int) {

    private var _open = false
    def open: Boolean = _open

    private val parser = new Parser(
      {
        case pckt@Packet(seq, `remoteSystemId`, compId, msgId, payload) =>
          val msg = Message.unpack(pckt.messageId, pckt.payload)
          onMessage(msg)
            //_packets() = _packets.now + 1
        case _ =>
          //_wrongIds() = _wrongIds.now + 1
      },
      {
        case CrcError => //_crcErrors() = _crcErrors.now + 1
        case OverflowError => //_overflows() = _overflows.now + 1
      }
    )

    private val connection = new dom.WebSocket(url)

    connection.binaryType = "arraybuffer"

    connection.onopen = (e: dom.Event) => {
      _open = true
    }
    connection.onmessage = (e: dom.MessageEvent) => {
      val buffer = e.data.asInstanceOf[js.typedarray.ArrayBuffer]
      val view = new js.typedarray.DataView(buffer)

      for (i <- 0 until view.byteLength) {
        parser.push(view.getInt8(i))
      }
    }
    connection.onclose = (e: dom.CloseEvent) => {
      _open = false
    }

  }

  private def onMessage(msg: Message): Unit = msg match {
    case a: Attitude =>
      attitudeOverlay.update((a.pitch, a.roll))
      horizonOverlay.update((a.pitch, a.roll))

    case _ => ()
  }

  def connect(url: String, remoteSystemId: Int): Unit = new MavlinkWebSocket(url, remoteSystemId)
}