aboutsummaryrefslogtreecommitdiff
path: root/mavlink-library/src/main/twirl/org/mavlink/Packet.scala.txt
blob: b52174687a6cf131cd004186835f49e846c490fb (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
@(__context: Context, __maxPayloadLength: Int, __extraCrcs: Seq[Byte])@_header(__context)
package org.mavlink

import scala.collection.mutable.ArrayBuilder

/**
 * Represents a MAVLink packet.
 * Note that due to performance reasons, the packet's payload contents are mutable.
 * @@param seq sequence number
 * @@param systemId system ID of sender
 * @@param componentId component ID of sender
 * @@param messageId MAVLink message identification (this depends on the dialect used)
 * @@param payload message contents
 */
case class Packet(
  seq: Byte,
  systemId: Byte,
  componentId: Byte,
  messageId: Byte,
  payload: Array[Byte]
) {

  lazy val crc = {
    var c = new Crc()
    c = c.accumulate(payload.length.toByte)
    c = c.accumulate(seq)
    c = c.accumulate(systemId)
    c = c.accumulate(componentId)
    c = c.accumulate(messageId)
    for (b <- payload) c = c.accumulate(b)
    c = c.accumulate(Packet.extraCrc(messageId))
    c
  }

  val toArray = {
    val builder = ArrayBuilder.make[Byte]
    builder += Packet.Stx
    builder += payload.length.toByte
    builder += seq
    builder += systemId
    builder += componentId
    builder += messageId
    builder ++= payload
    builder += crc.lsb
    builder += crc.msb
    builder.result
  }

}

object Packet {

  /** Start byte signaling the beginning of a packet. */
  final val Stx: Byte = (0xfe).toByte

  /** Maximum length of a payload contained in a packet. */
  final val MaxPayloadLength: Int = @__maxPayloadLength

  /** Additional CRCs indexed by message ID (see MAVLink specification). */
  final val ExtraCrcs: Seq[Byte] = Array[Byte](
  @__extraCrcs.map(_ formatted "%3d").grouped(10).map(_.mkString(",")).mkString(",\n  ")
  )
  
  /** Utility function to index ExtraCrcs with a byte. */
  def extraCrc(id: Byte) = ExtraCrcs(id & 0xff)

  /** An invalid packet with no payload. */
  def empty = Packet(0, 0, 0, -128, Array(0: Byte))

}