Initial release

This commit is contained in:
Martino Ferrari
2026-05-29 13:29:59 +02:00
commit 617b5bd712
110 changed files with 29234 additions and 0 deletions
+7
View File
@@ -0,0 +1,7 @@
module marte2/common
go 1.21
require github.com/gorilla/websocket v1.5.1
require golang.org/x/net v0.17.0 // indirect
+4
View File
@@ -0,0 +1,4 @@
github.com/gorilla/websocket v1.5.1 h1:gmztn0JnHVt9JZquRuzLw3g4wouNVzKL15iLr/zn/QY=
github.com/gorilla/websocket v1.5.1/go.mod h1:x3kM2JMyaluk02fnUJpQuwD2dCS5NDG2ZHL0uE0tcaY=
golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM=
golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=
+383
View File
@@ -0,0 +1,383 @@
package udpsprotocol
import (
"bytes"
"encoding/binary"
"fmt"
"math"
"time"
)
// ─── Constants ───────────────────────────────────────────────────────────────
const (
MagicUDPS uint32 = 0x53504455 // 'UDPS' little-endian
PktData uint8 = 0
PktConfig uint8 = 1
PktACK uint8 = 2
PktConnect uint8 = 3
PktDisconnect uint8 = 4
HeaderSize = 17
SigDescSize = 136
NoTimeSignal = uint32(0xFFFFFFFF)
QuantNone uint8 = 0
QuantUint8 uint8 = 1
QuantInt8 uint8 = 2
QuantUint16 uint8 = 3
QuantInt16 uint8 = 4
// TimeMode values must match UDPStreamerTimeMode enum in UDPStreamer.h
TimeModePacket uint8 = 0 // use wall-clock packet arrival time
TimeModeFullArray uint8 = 1 // TimeSignal has same N elements; not expanded here
TimeModeFirstSample uint8 = 2 // TimeSignal scalar = time of element [0]
TimeModeLastSample uint8 = 3 // TimeSignal scalar = time of element [N-1]
// PublishMode values must match UDPStreamerPublishMode enum in UDPStreamer.h
PublishModeStrict uint8 = 0 // one packet per Synchronise() call
PublishModeAccumulate uint8 = 1 // variable batch; DATA has [8 HRT][4 numSamples][signals...]
PublishModeDecimate uint8 = 2 // one packet every Ratio calls
)
// ─── Packet header (17 bytes, little-endian, packed) ─────────────────────────
type PacketHeader struct {
Magic uint32
Type uint8
Counter uint32
FragmentIdx uint16
TotalFragments uint16
PayloadBytes uint32
}
// ParseHeader decodes exactly HeaderSize bytes into a PacketHeader.
func ParseHeader(b []byte) (PacketHeader, error) {
if len(b) < HeaderSize {
return PacketHeader{}, fmt.Errorf("header too short: %d bytes", len(b))
}
var h PacketHeader
r := bytes.NewReader(b[:HeaderSize])
if err := binary.Read(r, binary.LittleEndian, &h); err != nil {
return PacketHeader{}, err
}
if h.Magic != MagicUDPS {
return PacketHeader{}, fmt.Errorf("bad magic: 0x%08X", h.Magic)
}
return h, nil
}
// buildHeader serialises a PacketHeader to a 17-byte slice.
func buildHeader(h PacketHeader) []byte {
buf := new(bytes.Buffer)
_ = binary.Write(buf, binary.LittleEndian, h)
return buf.Bytes()
}
// BuildConnectPacket returns a 17-byte CONNECT datagram.
func BuildConnectPacket() []byte {
return buildHeader(PacketHeader{
Magic: MagicUDPS,
Type: PktConnect,
Counter: 0,
FragmentIdx: 0,
TotalFragments: 1,
PayloadBytes: 0,
})
}
// BuildDisconnectPacket returns a 17-byte DISCONNECT datagram.
func BuildDisconnectPacket() []byte {
return buildHeader(PacketHeader{
Magic: MagicUDPS,
Type: PktDisconnect,
Counter: 0,
FragmentIdx: 0,
TotalFragments: 1,
PayloadBytes: 0,
})
}
// ─── Signal descriptor (136 bytes) ───────────────────────────────────────────
// SignalInfo holds the parsed metadata for one signal.
type SignalInfo struct {
Name string `json:"name"`
TypeCode uint8 `json:"typeCode"`
QuantType uint8 `json:"quantType"`
NumDimensions uint8 `json:"numDimensions"`
NumRows uint32 `json:"numRows"`
NumCols uint32 `json:"numCols"`
RangeMin float64 `json:"rangeMin"`
RangeMax float64 `json:"rangeMax"`
TimeMode uint8 `json:"timeMode"`
SamplingRate float64 `json:"samplingRate"`
TimeSignalIdx uint32 `json:"timeSignalIdx"`
Unit string `json:"unit"`
}
// NumElements returns the total number of scalar values in one sample of this signal.
func (s SignalInfo) NumElements() int {
r := int(s.NumRows)
c := int(s.NumCols)
if r == 0 {
r = 1
}
if c == 0 {
c = 1
}
return r * c
}
// rawTypeSize returns the byte size for one element of the raw (unquantised) type.
func rawTypeSize(typeCode uint8) int {
switch typeCode {
case 0, 1: // uint8, int8
return 1
case 2, 3: // uint16, int16
return 2
case 4, 5: // uint32, int32
return 4
case 6, 7: // uint64, int64
return 8
case 8: // float32
return 4
case 9: // float64
return 8
default:
return 1
}
}
// quantSize returns the byte size of one quantised element.
func quantSize(qt uint8) int {
switch qt {
case QuantUint8, QuantInt8:
return 1
case QuantUint16, QuantInt16:
return 2
default:
return 0
}
}
// readRawElement reads one element at offset and converts it to float64.
func readRawElement(b []byte, offset int, typeCode uint8) float64 {
switch typeCode {
case 0:
return float64(b[offset])
case 1:
return float64(int8(b[offset]))
case 2:
return float64(binary.LittleEndian.Uint16(b[offset:]))
case 3:
return float64(int16(binary.LittleEndian.Uint16(b[offset:])))
case 4:
return float64(binary.LittleEndian.Uint32(b[offset:]))
case 5:
return float64(int32(binary.LittleEndian.Uint32(b[offset:])))
case 6:
return float64(binary.LittleEndian.Uint64(b[offset:]))
case 7:
return float64(int64(binary.LittleEndian.Uint64(b[offset:])))
case 8:
bits := binary.LittleEndian.Uint32(b[offset:])
return float64(math.Float32frombits(bits))
case 9:
bits := binary.LittleEndian.Uint64(b[offset:])
return math.Float64frombits(bits)
default:
return 0
}
}
// dequantise converts a raw quantised integer to a physical float64.
func dequantise(qt uint8, raw uint16, rangeMin, rangeMax float64) float64 {
span := rangeMax - rangeMin
switch qt {
case QuantUint8:
return rangeMin + (float64(uint8(raw))/255.0)*span
case QuantInt8:
return rangeMin + (float64(int8(raw)+127)/254.0)*span
case QuantUint16:
return rangeMin + (float64(raw)/65535.0)*span
case QuantInt16:
return rangeMin + (float64(int16(raw)+32767)/65534.0)*span
default:
return 0
}
}
// nullTermString converts a zero-padded byte slice to a Go string.
func nullTermString(b []byte) string {
n := bytes.IndexByte(b, 0)
if n < 0 {
return string(b)
}
return string(b[:n])
}
// ─── CONFIG payload parser ────────────────────────────────────────────────────
// ParseConfig decodes a fully-reassembled CONFIG payload.
// Returns the signal list, the publishing mode byte (PublishMode*), and any error.
func ParseConfig(payload []byte) ([]SignalInfo, uint8, error) {
if len(payload) < 4 {
return nil, 0, fmt.Errorf("config payload too short")
}
numSigs := binary.LittleEndian.Uint32(payload[0:4])
offset := 4
sigs := make([]SignalInfo, 0, numSigs)
for i := uint32(0); i < numSigs; i++ {
if offset+SigDescSize > len(payload) {
return nil, 0, fmt.Errorf("config payload truncated at signal %d", i)
}
raw := payload[offset : offset+SigDescSize]
si := SignalInfo{
Name: nullTermString(raw[0:64]),
TypeCode: raw[64],
QuantType: raw[65],
NumDimensions: raw[66],
NumRows: binary.LittleEndian.Uint32(raw[67:71]),
NumCols: binary.LittleEndian.Uint32(raw[71:75]),
RangeMin: math.Float64frombits(binary.LittleEndian.Uint64(raw[75:83])),
RangeMax: math.Float64frombits(binary.LittleEndian.Uint64(raw[83:91])),
TimeMode: raw[91],
SamplingRate: math.Float64frombits(binary.LittleEndian.Uint64(raw[92:100])),
TimeSignalIdx: binary.LittleEndian.Uint32(raw[100:104]),
Unit: nullTermString(raw[104:136]),
}
sigs = append(sigs, si)
offset += SigDescSize
}
// Trailing publish-mode byte (added after signal descriptors).
publishMode := PublishModeStrict
if offset < len(payload) {
publishMode = payload[offset]
}
return sigs, publishMode, nil
}
// ─── DATA payload parser ──────────────────────────────────────────────────────
// DataSample holds the decoded values from one DATA packet.
type DataSample struct {
HRTTimestamp uint64
WallTime time.Time // wall-clock time at UDP arrival; used as x-axis
Values map[string][]float64 // key = signal name, value = []float64 with NumElements entries
}
// parseElems reads n elements for sig from payload at offset, advancing offset.
// Returns the slice of float64 values and the new offset.
func parseElems(payload []byte, offset, n int, sig SignalInfo) ([]float64, int, error) {
elems := make([]float64, n)
if sig.QuantType == QuantNone {
sz := rawTypeSize(sig.TypeCode)
needed := n * sz
if offset+needed > len(payload) {
return nil, offset, fmt.Errorf("data payload truncated for signal %q", sig.Name)
}
for i := 0; i < n; i++ {
elems[i] = readRawElement(payload, offset+i*sz, sig.TypeCode)
}
offset += needed
} else {
sz := quantSize(sig.QuantType)
needed := n * sz
if offset+needed > len(payload) {
return nil, offset, fmt.Errorf("data payload truncated (quant) for signal %q", sig.Name)
}
for i := 0; i < n; i++ {
var raw uint16
if sz == 1 {
raw = uint16(payload[offset+i])
} else {
raw = binary.LittleEndian.Uint16(payload[offset+i*2:])
}
elems[i] = dequantise(sig.QuantType, raw, sig.RangeMin, sig.RangeMax)
}
offset += needed
}
return elems, offset, nil
}
// ParseData decodes a fully-reassembled DATA payload using the provided signal config
// and publishing mode. arrivalTime is the wall-clock time at which the packet arrived.
//
// For PublishModeAccumulate the payload format is:
//
// [8 HRT][4 numSamples][for each signal: accumulated scalars → numSamples elems; arrays → NumElements elems]
//
// The function returns one DataSample per accumulated snapshot so the hub can
// process each slot independently with its own timestamp.
func ParseData(payload []byte, sigs []SignalInfo, publishMode uint8, arrivalTime time.Time) ([]DataSample, error) {
if len(payload) < 8 {
return nil, fmt.Errorf("data payload too short")
}
hrt := binary.LittleEndian.Uint64(payload[0:8])
offset := 8
if publishMode == PublishModeAccumulate {
if len(payload) < 12 {
return nil, fmt.Errorf("accumulate data payload too short (missing numSamples)")
}
numSamples := int(binary.LittleEndian.Uint32(payload[8:12]))
offset = 12
if numSamples == 0 {
return []DataSample{}, nil
}
// Parse per-signal data blocks (all slots for a signal are contiguous).
accumVals := make(map[string][]float64, len(sigs)) // scalars: numSamples values
fixedVals := make(map[string][]float64, len(sigs)) // arrays: NumElements values
for _, sig := range sigs {
n := sig.NumElements()
if n == 1 {
// Accumulated scalar: read numSamples back-to-back elements.
elems, newOff, err := parseElems(payload, offset, numSamples, sig)
if err != nil {
return nil, err
}
offset = newOff
accumVals[sig.Name] = elems
} else {
// Fixed array (non-accumulated): one set of NumElements values.
elems, newOff, err := parseElems(payload, offset, n, sig)
if err != nil {
return nil, err
}
offset = newOff
fixedVals[sig.Name] = elems
}
}
// Build one DataSample per slot.
samples := make([]DataSample, numSamples)
for k := 0; k < numSamples; k++ {
vals := make(map[string][]float64, len(sigs))
for sigName, av := range accumVals {
vals[sigName] = []float64{av[k]}
}
for sigName, fv := range fixedVals {
vals[sigName] = fv // shared read-only reference; hub does not modify
}
samples[k] = DataSample{HRTTimestamp: hrt, WallTime: arrivalTime, Values: vals}
}
return samples, nil
}
// Strict / Decimate: single snapshot, one element set per signal.
vals := make(map[string][]float64, len(sigs))
for _, sig := range sigs {
n := sig.NumElements()
elems, newOff, err := parseElems(payload, offset, n, sig)
if err != nil {
return nil, err
}
offset = newOff
vals[sig.Name] = elems
}
return []DataSample{{HRTTimestamp: hrt, WallTime: arrivalTime, Values: vals}}, nil
}
@@ -0,0 +1,105 @@
package udpsprotocol
import (
"sync"
"time"
)
// fragmentSet holds the received fragments for one (counter, type) pair.
type fragmentSet struct {
total int
received int
fragments [][]byte // indexed by fragmentIdx
lastSeen time.Time
}
// Reassembler reassembles fragmented UDP payloads.
// Key: uint64(counter)<<8 | uint64(pktType)
type Reassembler struct {
mu sync.Mutex
sets map[uint64]*fragmentSet
expiry time.Duration // how long to keep incomplete sets
}
// NewReassembler creates a Reassembler that expires stale fragment sets after ttl.
func NewReassembler(ttl time.Duration) *Reassembler {
r := &Reassembler{
sets: make(map[uint64]*fragmentSet),
expiry: ttl,
}
go r.gcLoop()
return r
}
func reassemblyKey(counter uint32, pktType uint8) uint64 {
return uint64(counter)<<8 | uint64(pktType)
}
// AddFragment registers one fragment. Returns the reassembled payload and true
// when all fragments for this (counter, type) have been received, otherwise
// returns nil, false.
func (r *Reassembler) AddFragment(h PacketHeader, payload []byte) ([]byte, bool) {
key := reassemblyKey(h.Counter, h.Type)
total := int(h.TotalFragments)
idx := int(h.FragmentIdx)
// Fast path: single-fragment packet.
if total == 1 && idx == 0 {
return payload, true
}
r.mu.Lock()
defer r.mu.Unlock()
fs, ok := r.sets[key]
if !ok {
fs = &fragmentSet{
total: total,
fragments: make([][]byte, total),
}
r.sets[key] = fs
}
if idx >= len(fs.fragments) {
// Stale or corrupt discard.
return nil, false
}
if fs.fragments[idx] == nil {
fs.fragments[idx] = payload
fs.received++
}
fs.lastSeen = time.Now()
if fs.received < fs.total {
return nil, false
}
// All fragments received concatenate in order.
delete(r.sets, key)
total_len := 0
for _, f := range fs.fragments {
total_len += len(f)
}
out := make([]byte, 0, total_len)
for _, f := range fs.fragments {
out = append(out, f...)
}
return out, true
}
// gcLoop periodically removes fragment sets that have been incomplete for too long.
func (r *Reassembler) gcLoop() {
ticker := time.NewTicker(r.expiry / 2)
defer ticker.Stop()
for range ticker.C {
r.mu.Lock()
now := time.Now()
for k, fs := range r.sets {
if now.Sub(fs.lastSeen) > r.expiry {
delete(r.sets, k)
}
}
r.mu.Unlock()
}
}
+903
View File
@@ -0,0 +1,903 @@
package wshub
import (
"encoding/binary"
"encoding/json"
"log"
"math"
"net/http"
"strconv"
"strings"
"sync"
"time"
"unsafe"
"github.com/gorilla/websocket"
"marte2/common/udpsprotocol"
)
// ─── WebSocket client ─────────────────────────────────────────────────────────
type wsMessage struct {
msgType int
data []byte
}
type wsClient struct {
hub *Hub
conn *websocket.Conn
send chan wsMessage
}
func (c *wsClient) writePump() {
pingTicker := time.NewTicker(30 * time.Second)
defer func() {
pingTicker.Stop()
c.conn.Close()
}()
for {
select {
case msg, ok := <-c.send:
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
if err := c.conn.WriteMessage(msg.msgType, msg.data); err != nil {
return
}
case <-pingTicker.C:
if err := c.conn.WriteControl(websocket.PingMessage, []byte{},
time.Now().Add(10*time.Second)); err != nil {
return
}
}
}
}
func (c *wsClient) readPump() {
defer func() {
c.hub.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(64 * 1024)
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
c.conn.SetPongHandler(func(string) error {
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
return nil
})
for {
_, msg, err := c.conn.ReadMessage()
if err != nil {
break
}
var env map[string]interface{}
if json.Unmarshal(msg, &env) == nil {
if t, ok := env["type"].(string); ok {
switch t {
case "ping":
resp, _ := json.Marshal(map[string]string{"type": "pong"})
select {
case c.send <- wsMessage{websocket.TextMessage, resp}:
default:
}
case "addSource":
label, _ := env["label"].(string)
addr, _ := env["addr"].(string)
mcastGroup, _ := env["multicastGroup"].(string)
dataPortF, _ := env["dataPort"].(float64)
if addr != "" {
select {
case c.hub.commandCh <- hubCmd{
op: "wsAddSource", label: label, addr: addr,
multicastGroup: mcastGroup, dataPort: int(dataPortF),
}:
default:
}
}
case "removeSource":
id, _ := env["id"].(string)
if id != "" {
select {
case c.hub.commandCh <- hubCmd{op: "wsRemoveSource", sourceID: id}:
default:
}
}
case "saveSources":
select {
case c.hub.commandCh <- hubCmd{op: "wsSaveSources"}:
default:
}
default:
// Unrecognized message type — forward to DebugCh
select {
case c.hub.DebugCh <- msg:
default:
}
}
}
}
c.conn.SetReadDeadline(time.Now().Add(60 * time.Second))
}
}
// ─── Hub ─────────────────────────────────────────────────────────────────────
var upgrader = websocket.Upgrader{
ReadBufferSize: 4096,
WriteBufferSize: 64 * 1024,
CheckOrigin: func(r *http.Request) bool { return true },
}
// sourceHubState holds all data for one active data source.
// Only accessed from the Run() goroutine.
type sourceHubState struct {
id, label, addr, connState string
signals []udpsprotocol.SignalInfo
configJS []byte
// Time-signal calibration — only accessed from Run() goroutine.
timeSigCalib map[string]float64
configSeq uint64
configSeqAtCalib uint64
}
// taggedSample is a DataSample annotated with its source ID.
type taggedSample struct {
sourceID string
sample udpsprotocol.DataSample
}
// hubCmd carries a command to the Run() goroutine.
type hubCmd struct {
op string // "addSource","removeSource","setSourceState","updateConfig",
// "wsAddSource","wsRemoveSource","wsSaveSources"
sourceID string
label string
addr string
state string
sigs []udpsprotocol.SignalInfo
multicastGroup string
dataPort int
}
// Hub is the central broker between UDP clients and WebSocket clients.
// All map state is accessed exclusively from the Run() goroutine, except
// ringsMu/rings which are also read by HTTP handler goroutines.
type Hub struct {
clients map[*wsClient]bool
register chan *wsClient
unregister chan *wsClient
broadcastCh chan []byte
dataCh chan taggedSample
commandCh chan hubCmd
// DebugCh receives raw browser messages whose type is not handled by the hub.
DebugCh chan []byte
sm *SourceManager // set after construction; used for WS-initiated source changes
// Ring buffers for hi-res zoom data.
// ringsMu protects the map structure; each sigRing has its own RWMutex for data.
ringsMu sync.RWMutex
rings map[string]*sigRing // "sourceId:signalKey" → ring
// lastZoomAt tracks the last time a zoom request was served.
// Ring buffer writes are skipped when no zoom has been requested
// in the last 10 s, saving substantial CPU on LTTB + ring writes.
lastZoomAt time.Time
zoomAtMu sync.Mutex
statsMu sync.RWMutex
statsMap map[string]*SourceStat
// onClientConnect, if set, is called each time a new WebSocket client
// registers. The callback receives a send function that delivers a message
// directly to that client. It is invoked synchronously from Run(), so it
// must not block.
onClientConnectMu sync.RWMutex
onClientConnect func(send func([]byte))
}
// NewHub creates an initialised Hub.
func NewHub() *Hub {
return &Hub{
clients: make(map[*wsClient]bool),
register: make(chan *wsClient, 8),
unregister: make(chan *wsClient, 8),
broadcastCh: make(chan []byte, 256),
dataCh: make(chan taggedSample, 65536), // large buffer: absorbs bursts at high sample rates
commandCh: make(chan hubCmd, 64),
DebugCh: make(chan []byte, 256),
rings: make(map[string]*sigRing),
statsMap: make(map[string]*SourceStat),
}
}
// SetOnClientConnect registers a callback invoked synchronously (from Run())
// each time a new WebSocket client connects. The callback receives a send
// function that enqueues one message to that specific client.
func (h *Hub) SetOnClientConnect(fn func(send func([]byte))) {
h.onClientConnectMu.Lock()
h.onClientConnect = fn
h.onClientConnectMu.Unlock()
}
// SetSourceManager sets the SourceManager associated with the Hub.
func (h *Hub) SetSourceManager(sm *SourceManager) {
h.sm = sm
}
// getRing returns the ring buffer for a fully-prefixed signal key, or nil.
func (h *Hub) getRing(key string) *sigRing {
h.ringsMu.RLock()
rb := h.rings[key]
h.ringsMu.RUnlock()
return rb
}
// shouldWriteRing returns true if zoom was requested within the last 10 seconds.
func (h *Hub) shouldWriteRing() bool {
h.zoomAtMu.Lock()
ok := time.Since(h.lastZoomAt) < 10*time.Second
h.zoomAtMu.Unlock()
return ok
}
// HandleZoom serves GET /api/zoom?... It also records the access time
// so the ring buffer knows zoom is active and worth populating.
func (h *Hub) HandleZoom(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query()
t0, err0 := strconv.ParseFloat(q.Get("t0"), 64)
t1, err1 := strconv.ParseFloat(q.Get("t1"), 64)
if err0 != nil || err1 != nil || t1 <= t0 {
http.Error(w, "invalid t0/t1", http.StatusBadRequest)
return
}
var n int
if nStr := q.Get("n"); nStr == "" {
n = 2400
} else {
n, _ = strconv.Atoi(nStr)
if n <= 0 {
n = 1 << 30 // no decimation
} else if n < 10 {
n = 2400
}
}
if n > 0 {
h.zoomAtMu.Lock()
h.lastZoomAt = time.Now()
h.zoomAtMu.Unlock()
}
keys := strings.Split(q.Get("signals"), ",")
h.ringsMu.RLock()
refs := make(map[string]*sigRing, len(keys))
for _, k := range keys {
k = strings.TrimSpace(k)
if k == "" {
continue
}
if rb, ok := h.rings[k]; ok {
refs[k] = rb
}
}
h.ringsMu.RUnlock()
result := make(map[string]sigData, len(refs))
for k, rb := range refs {
rt, rv := rb.slice(t0, t1)
if len(rt) == 0 {
continue
}
dt, dv := lttbDecimate(rt, rv, n)
result[k] = sigData{T: dt, V: dv}
}
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(map[string]any{
"type": "zoom",
"signals": result,
}); err != nil {
log.Printf("hub: zoom encode: %v", err)
}
}
// AddSource notifies the Hub that a new source has been registered.
func (h *Hub) AddSource(id, label, addr string) {
select {
case h.commandCh <- hubCmd{op: "addSource", sourceID: id, label: label, addr: addr}:
default:
}
}
// RemoveSource notifies the Hub that a source has been removed.
func (h *Hub) RemoveSource(id string) {
select {
case h.commandCh <- hubCmd{op: "removeSource", sourceID: id}:
default:
}
}
// SetSourceState updates the connection state of a source.
func (h *Hub) SetSourceState(id, state string) {
select {
case h.commandCh <- hubCmd{op: "setSourceState", sourceID: id, state: state}:
default:
}
}
// UpdateConfigForSource stores a new signal config for a source and broadcasts it.
func (h *Hub) UpdateConfigForSource(sourceID string, sigs []udpsprotocol.SignalInfo) {
select {
case h.commandCh <- hubCmd{op: "updateConfig", sourceID: sourceID, sigs: sigs}:
default:
}
}
// PushDataForSource enqueues a data sample from a specific source.
func (h *Hub) PushDataForSource(sourceID string, s udpsprotocol.DataSample) {
select {
case h.dataCh <- taggedSample{sourceID: sourceID, sample: s}:
default:
}
}
// broadcast enqueues a message for delivery to all WebSocket clients.
func (h *Hub) broadcast(msg []byte) {
select {
case h.broadcastCh <- msg:
default:
}
}
// Broadcast is the exported wrapper for broadcast.
func (h *Hub) Broadcast(msg []byte) {
h.broadcast(msg)
}
// HandleWebSocket upgrades an HTTP request to a WebSocket connection.
func (h *Hub) HandleWebSocket(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("ws upgrade: %v", err)
return
}
c := &wsClient{hub: h, conn: conn, send: make(chan wsMessage, 64)}
h.register <- c
go c.writePump()
go c.readPump()
}
// buildSourcesMsg serialises the current source list as a JSON "sources" message.
func buildSourcesMsg(sm map[string]*sourceHubState) []byte {
type srcInfo struct {
ID string `json:"id"`
Label string `json:"label"`
Addr string `json:"addr"`
State string `json:"state"`
}
list := make([]srcInfo, 0, len(sm))
for _, src := range sm {
list = append(list, srcInfo{ID: src.id, Label: src.label, Addr: src.addr, State: src.connState})
}
msg, _ := json.Marshal(map[string]interface{}{"type": "sources", "sources": list})
return msg
}
// Run is the hub's main goroutine. Must be started with go hub.Run().
func (h *Hub) Run() {
ticker := time.NewTicker(time.Second / 30)
defer ticker.Stop()
statsTicker := time.NewTicker(time.Second)
defer statsTicker.Stop()
sourcesMap := make(map[string]*sourceHubState)
var sourcesMsg []byte
// pending[sourceID] accumulates samples between 30 Hz ticks.
pending := make(map[string][]udpsprotocol.DataSample)
rebuildSources := func() {
sourcesMsg = buildSourcesMsg(sourcesMap)
h.broadcast(sourcesMsg)
}
for {
select {
case c := <-h.register:
h.clients[c] = true
// Send current state to the new client.
if sourcesMsg != nil {
select { case c.send <- wsMessage{websocket.TextMessage, sourcesMsg}: default: }
}
for _, src := range sourcesMap {
if src.configJS != nil {
select { case c.send <- wsMessage{websocket.TextMessage, src.configJS}: default: }
}
}
// Notify the application layer so it can replay any persistent state
// (e.g., MARTe2 connection status, forced/traced signals).
h.onClientConnectMu.RLock()
fn := h.onClientConnect
h.onClientConnectMu.RUnlock()
if fn != nil {
fn(func(msg []byte) {
select { case c.send <- wsMessage{websocket.TextMessage, msg}: default: }
})
}
case c := <-h.unregister:
if _, ok := h.clients[c]; ok {
delete(h.clients, c)
close(c.send)
}
case msg := <-h.broadcastCh:
for c := range h.clients {
select { case c.send <- wsMessage{websocket.TextMessage, msg}: default: }
}
case cmd := <-h.commandCh:
switch cmd.op {
case "addSource":
sourcesMap[cmd.sourceID] = &sourceHubState{
id: cmd.sourceID,
label: cmd.label,
addr: cmd.addr,
connState: "connecting",
timeSigCalib: make(map[string]float64),
}
h.statsMu.Lock()
h.statsMap[cmd.sourceID] = &SourceStat{}
h.statsMu.Unlock()
rebuildSources()
case "removeSource":
delete(sourcesMap, cmd.sourceID)
delete(pending, cmd.sourceID)
pfxDel := cmd.sourceID + ":"
h.ringsMu.Lock()
for k := range h.rings {
if strings.HasPrefix(k, pfxDel) {
delete(h.rings, k)
}
}
h.ringsMu.Unlock()
h.statsMu.Lock()
delete(h.statsMap, cmd.sourceID)
h.statsMu.Unlock()
rebuildSources()
case "setSourceState":
if src, ok := sourcesMap[cmd.sourceID]; ok {
src.connState = cmd.state
rebuildSources()
}
case "updateConfig":
src, ok := sourcesMap[cmd.sourceID]
if !ok {
continue
}
src.signals = cmd.sigs
src.configSeq++
cfgMsg, err := json.Marshal(map[string]any{
"type": "config",
"sourceId": cmd.sourceID,
"signals": cmd.sigs,
})
if err != nil {
log.Printf("hub: marshal config: %v", err)
continue
}
src.configJS = cfgMsg
h.broadcast(cfgMsg)
// Rebuild ring buffers for this source.
pfxUpd := cmd.sourceID + ":"
h.ringsMu.Lock()
for k := range h.rings {
if strings.HasPrefix(k, pfxUpd) {
delete(h.rings, k)
}
}
for _, sig := range cmd.sigs {
ne := sig.NumElements()
isTemporal := ne > 1 && sig.TimeMode != udpsprotocol.TimeModePacket
if isTemporal {
h.rings[pfxUpd+sig.Name] = newSigRing(ringCapTemporal)
} else {
// Both scalar (ne==1) and snapshot-waveform (ne>1, TimeModePacket)
// are stored under the base signal name.
h.rings[pfxUpd+sig.Name] = newSigRing(ringCapScalar)
}
}
h.ringsMu.Unlock()
case "wsAddSource":
if h.sm != nil {
go func(label, addr, mcastGroup string, dataPort int) {
h.sm.Add(label, addr, mcastGroup, dataPort)
}(cmd.label, cmd.addr, cmd.multicastGroup, cmd.dataPort)
}
case "wsRemoveSource":
if h.sm != nil {
go func(id string) { h.sm.Remove(id) }(cmd.sourceID)
}
case "wsSaveSources":
if h.sm != nil {
if err := h.sm.Save(); err != nil {
log.Printf("hub: save sources: %v", err)
}
}
}
case ts := <-h.dataCh:
pending[ts.sourceID] = append(pending[ts.sourceID], ts.sample)
case <-ticker.C:
for srcID, samples := range pending {
if len(samples) == 0 {
continue
}
src, ok := sourcesMap[srcID]
if !ok || len(src.signals) == 0 || len(h.clients) == 0 {
pending[srcID] = pending[srcID][:0]
continue
}
msg := h.buildBinaryDataMessageForSource(src, samples)
pending[srcID] = pending[srcID][:0]
if msg != nil {
for c := range h.clients {
select {
case c.send <- wsMessage{websocket.BinaryMessage, msg}:
default:
}
}
}
}
case <-statsTicker.C:
h.statsMu.RLock()
snap := make(map[string]StatInfo, len(h.statsMap))
for id, st := range h.statsMap {
snap[id] = st.Snapshot()
}
h.statsMu.RUnlock()
if len(snap) > 0 {
msg, _ := json.Marshal(map[string]any{"type": "stats", "sources": snap})
h.broadcast(msg)
}
}
}
}
// float64ToBytes reinterprets a []float64 as []byte without copying.
func float64ToBytes(f []float64) []byte {
if len(f) == 0 {
return nil
}
return unsafe.Slice((*byte)(unsafe.Pointer(&f[0])), len(f)*8)
}
// writeFloat64s encodes a []float64 as little-endian bytes into buf at offset
// and returns the new offset.
func writeFloat64s(buf []byte, off int, f []float64) int {
copy(buf[off:], float64ToBytes(f))
return off + len(f)*8
}
// ─── Data serialisation ───────────────────────────────────────────────────────
const maxPushPoints = 50
const maxRingPoints = 20_000
const ringCapTemporal = 6_000_000
const ringCapScalar = 100_000
// lttbDecimate reduces (tIn, vIn) to at most threshold representative points
// using the Largest-Triangle-Three-Buckets algorithm.
func lttbDecimate(tIn, vIn []float64, threshold int) ([]float64, []float64) {
n := len(tIn)
if n <= threshold || threshold < 3 {
return tIn, vIn
}
outT := make([]float64, threshold)
outV := make([]float64, threshold)
outT[0], outV[0] = tIn[0], vIn[0]
outT[threshold-1], outV[threshold-1] = tIn[n-1], vIn[n-1]
every := float64(n-2) / float64(threshold-2)
a := 0
for i := 0; i < threshold-2; i++ {
avgS := int(float64(i+1)*every) + 1
avgE := int(float64(i+2)*every) + 1
if avgE > n {
avgE = n
}
avgT, avgV, cnt := 0.0, 0.0, 0
for j := avgS; j < avgE; j++ {
avgT += tIn[j]; avgV += vIn[j]; cnt++
}
if cnt > 0 {
avgT /= float64(cnt); avgV /= float64(cnt)
}
rS := int(float64(i)*every) + 1
rE := int(float64(i+1)*every) + 1
if rE > n {
rE = n
}
maxArea, next := -1.0, rS
aT, aV := tIn[a], vIn[a]
for j := rS; j < rE; j++ {
area := math.Abs((aT-avgT)*(vIn[j]-aV) - (aT-tIn[j])*(avgV-aV))
if area > maxArea {
maxArea = area; next = j
}
}
outT[i+1], outV[i+1] = tIn[next], vIn[next]
a = next
}
return outT, outV
}
type sigData struct {
T []float64 `json:"t"`
V []float64 `json:"v"`
}
type dataMsg struct {
Type string `json:"type"`
SourceID string `json:"sourceId"`
Signals map[string]sigData `json:"signals"`
}
// buildBinaryDataMessageForSource encodes a batch of samples as a compact binary frame.
func (h *Hub) buildBinaryDataMessageForSource(src *sourceHubState, batch []udpsprotocol.DataSample) []byte {
if len(batch) == 0 {
return nil
}
if src.configSeq != src.configSeqAtCalib {
src.configSeqAtCalib = src.configSeq
src.timeSigCalib = make(map[string]float64)
}
sigs := src.signals
pfx := src.id + ":"
writeRing := h.shouldWriteRing()
type pairBuf struct {
t, v []float64
}
pairs := make(map[string]pairBuf, len(sigs)*2)
for _, sig := range sigs {
n := sig.NumElements()
switch {
case n > 1 && (sig.TimeMode == udpsprotocol.TimeModeFirstSample || sig.TimeMode == udpsprotocol.TimeModeLastSample):
hasTimeSig := sig.TimeSignalIdx != udpsprotocol.NoTimeSignal && int(sig.TimeSignalIdx) < len(sigs)
var timeSigName string
timerToSec := 1e-6
if hasTimeSig {
ts := sigs[sig.TimeSignalIdx]
timeSigName = ts.Name
if ts.TypeCode == 6 {
timerToSec = 1e-9
}
}
dt := 0.0
if sig.SamplingRate > 0 {
dt = 1.0 / sig.SamplingRate
}
allT := make([]float64, 0, len(batch)*n)
allV := make([]float64, 0, len(batch)*n)
for _, s := range batch {
vals, ok := s.Values[sig.Name]
if !ok || len(vals) < n {
continue
}
var anchorTime float64
anchorIsFirstSample := sig.TimeMode == udpsprotocol.TimeModeFirstSample
if hasTimeSig {
tVals, tOk := s.Values[timeSigName]
if tOk && len(tVals) >= 1 {
timerS := tVals[0] * timerToSec
wallT := float64(s.WallTime.UnixNano()) / 1e9
if _, exists := src.timeSigCalib[timeSigName]; !exists {
src.timeSigCalib[timeSigName] = wallT - timerS
}
anchorTime = src.timeSigCalib[timeSigName] + timerS
} else {
anchorTime = float64(s.WallTime.UnixNano()) / 1e9
anchorIsFirstSample = false
}
} else {
anchorTime = float64(s.WallTime.UnixNano()) / 1e9
anchorIsFirstSample = false
}
for k := 0; k < n; k++ {
var t float64
if anchorIsFirstSample {
t = anchorTime + float64(k)*dt
} else {
t = anchorTime - float64(n-1-k)*dt
}
allT = append(allT, t)
allV = append(allV, vals[k])
}
}
if writeRing {
ringT, ringV := lttbDecimate(allT, allV, maxRingPoints)
if rb := h.getRing(pfx + sig.Name); rb != nil {
rb.write(ringT, ringV)
}
}
decimT, decimV := lttbDecimate(allT, allV, maxPushPoints)
pairs[sig.Name] = pairBuf{t: decimT, v: decimV}
case sig.TimeMode == udpsprotocol.TimeModeFullArray:
hasTimeSig := sig.TimeSignalIdx != udpsprotocol.NoTimeSignal && int(sig.TimeSignalIdx) < len(sigs)
var timeSigName string
timerToSec := 1e-6
if hasTimeSig {
ts := sigs[sig.TimeSignalIdx]
timeSigName = ts.Name
if ts.TypeCode == 6 {
timerToSec = 1e-9
}
}
allT := make([]float64, 0, len(batch)*n)
allV := make([]float64, 0, len(batch)*n)
for _, s := range batch {
vals, ok := s.Values[sig.Name]
if !ok || len(vals) < n {
continue
}
if hasTimeSig {
tVals, tOk := s.Values[timeSigName]
if tOk && len(tVals) >= n {
if _, exists := src.timeSigCalib[timeSigName]; !exists {
wallT := float64(s.WallTime.UnixNano()) / 1e9
src.timeSigCalib[timeSigName] = wallT - tVals[0]*timerToSec
}
calib := src.timeSigCalib[timeSigName]
for k := 0; k < n; k++ {
allT = append(allT, calib+tVals[k]*timerToSec)
allV = append(allV, vals[k])
}
continue
}
}
wallT := float64(s.WallTime.UnixNano()) / 1e9
for k := 0; k < n; k++ {
allT = append(allT, wallT)
allV = append(allV, vals[k])
}
}
if writeRing {
ringT, ringV := lttbDecimate(allT, allV, maxRingPoints)
if rb := h.getRing(pfx + sig.Name); rb != nil {
rb.write(ringT, ringV)
}
}
decimT, decimV := lttbDecimate(allT, allV, maxPushPoints)
pairs[sig.Name] = pairBuf{t: decimT, v: decimV}
case n == 1:
ts := make([]float64, 0, len(batch))
vs := make([]float64, 0, len(batch))
for _, s := range batch {
vals, ok := s.Values[sig.Name]
if !ok || len(vals) < 1 {
continue
}
ts = append(ts, float64(s.WallTime.UnixNano())/1e9)
vs = append(vs, vals[0])
}
if writeRing {
if rb := h.getRing(pfx + sig.Name); rb != nil {
rb.write(ts, vs)
}
}
pairs[sig.Name] = pairBuf{t: ts, v: vs}
default:
// n > 1, TimeModePacket: no samplingRate from C++, so we interpolate
// timestamps from wall-clock differences between consecutive packets.
// Each packet covers n elements; dt per element ≈ (T_{i+1}-T_i)/n.
allT := make([]float64, 0, len(batch)*n)
allV := make([]float64, 0, len(batch)*n)
for bi, s := range batch {
vals, ok := s.Values[sig.Name]
if !ok || len(vals) < n {
continue
}
wallSec := float64(s.WallTime.UnixNano()) / 1e9
var dtSec float64
if bi+1 < len(batch) {
dtSec = (float64(batch[bi+1].WallTime.UnixNano())-float64(s.WallTime.UnixNano()))/1e9/float64(n)
} else if bi > 0 {
dtSec = (float64(s.WallTime.UnixNano())-float64(batch[bi-1].WallTime.UnixNano()))/1e9/float64(n)
} else {
dtSec = 1.0 / float64(n) // single-sample fallback
}
for j := 0; j < n; j++ {
allT = append(allT, wallSec+float64(j)*dtSec)
allV = append(allV, vals[j])
}
}
if len(allT) > 0 {
if writeRing {
ringT, ringV := lttbDecimate(allT, allV, maxRingPoints)
if rb := h.getRing(pfx + sig.Name); rb != nil {
rb.write(ringT, ringV)
}
}
decimT, decimV := lttbDecimate(allT, allV, maxPushPoints)
pairs[sig.Name] = pairBuf{t: decimT, v: decimV}
}
}
}
// Compute total size and serialize
totalSize := 1 + 1 + len(src.id) + 4
for key, p := range pairs {
totalSize += 2 + len(key) + 4
totalSize += len(p.t)*8 + len(p.v)*8
}
buf := make([]byte, totalSize)
buf[0] = 1 // version
buf[1] = byte(len(src.id))
copy(buf[2:], src.id)
off := 2 + len(src.id)
binary.LittleEndian.PutUint32(buf[off:], uint32(len(pairs)))
off += 4
for key, p := range pairs {
binary.LittleEndian.PutUint16(buf[off:], uint16(len(key)))
off += 2
copy(buf[off:], key)
off += len(key)
binary.LittleEndian.PutUint32(buf[off:], uint32(len(p.t)))
off += 4
off = writeFloat64s(buf, off, p.t)
off = writeFloat64s(buf, off, p.v)
}
return buf
}
// RecordDataFragment is called by UDPClient for every incoming DATA datagram.
func (h *Hub) RecordDataFragment(sourceID string, counter uint32, nBytes int, arrivalNs int64, complete bool) {
h.statsMu.RLock()
st := h.statsMap[sourceID]
h.statsMu.RUnlock()
if st != nil {
st.RecordFragment(counter, nBytes, arrivalNs, complete)
}
}
// arrayKey returns the buffer key for element i of an array signal.
func arrayKey(name string, i int) string {
return name + "[" + itoa(i) + "]"
}
func itoa(n int) string {
if n == 0 {
return "0"
}
buf := [20]byte{}
pos := len(buf)
for n > 0 {
pos--
buf[pos] = byte('0' + n%10)
n /= 10
}
return string(buf[pos:])
}
+88
View File
@@ -0,0 +1,88 @@
package wshub
import "sync"
// sigRing is a fixed-capacity circular buffer storing (time, value) pairs.
// Writes come from the Hub.Run() goroutine; reads come from HTTP handler goroutines.
// The embedded RWMutex protects concurrent access.
type sigRing struct {
mu sync.RWMutex
t, v []float64
cap int
head, size int // next write position; current fill
}
func newSigRing(capacity int) *sigRing {
return &sigRing{
t: make([]float64, capacity),
v: make([]float64, capacity),
cap: capacity,
}
}
// write appends (tArr[i], vArr[i]) pairs, overwriting oldest entries when full.
func (rb *sigRing) write(tArr, vArr []float64) {
rb.mu.Lock()
defer rb.mu.Unlock()
for i := 0; i < len(tArr); i++ {
rb.t[rb.head] = tArr[i]
rb.v[rb.head] = vArr[i]
rb.head = (rb.head + 1) % rb.cap
if rb.size < rb.cap {
rb.size++
}
}
}
// slice returns copies of all (t, v) pairs whose timestamp falls in [t0, t1].
// The returned slices are safe to use after the call without holding any lock.
func (rb *sigRing) slice(t0, t1 float64) ([]float64, []float64) {
rb.mu.RLock()
defer rb.mu.RUnlock()
if rb.size == 0 {
return nil, nil
}
start := 0
if rb.size == rb.cap {
start = rb.head
}
physAt := func(k int) int { return (start + k) % rb.cap }
// Binary search for t0
lo, hi := 0, rb.size
for lo < hi {
m := (lo + hi) >> 1
if rb.t[physAt(m)] < t0 {
lo = m + 1
} else {
hi = m
}
}
kStart := lo
// Binary search for t1
lo, hi = kStart, rb.size
for lo < hi {
m := (lo + hi) >> 1
if rb.t[physAt(m)] <= t1 {
lo = m + 1
} else {
hi = m
}
}
kEnd := lo
n := kEnd - kStart
if n <= 0 {
return nil, nil
}
outT := make([]float64, n)
outV := make([]float64, n)
for i := 0; i < n; i++ {
p := physAt(kStart + i)
outT[i] = rb.t[p]
outV[i] = rb.v[p]
}
return outT, outV
}
+483
View File
@@ -0,0 +1,483 @@
package wshub
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"marte2/common/udpsprotocol"
)
// ─── Source configuration ─────────────────────────────────────────────────────
// SourceConfig is the serialisable description of one data source (for file save/load).
type SourceConfig struct {
Label string `json:"label"`
Addr string `json:"addr"`
MulticastGroup string `json:"multicastGroup,omitempty"`
DataPort int `json:"dataPort,omitempty"`
}
// managedSource is the SourceManager's view of one running source.
type managedSource struct {
id string
label string
addr string
multicastGroup string
dataPort int
client *UDPClient
}
// SourceManager owns the lifecycle of all active data sources.
type SourceManager struct {
mu sync.RWMutex
sources map[string]*managedSource
hub *Hub
filePath string
nextID atomic.Int32
}
// NewSourceManager creates a SourceManager bound to the given hub.
func NewSourceManager(hub *Hub, filePath string) *SourceManager {
return &SourceManager{
sources: make(map[string]*managedSource),
hub: hub,
filePath: filePath,
}
}
func (sm *SourceManager) genID() string {
return fmt.Sprintf("s%d", sm.nextID.Add(1))
}
// Add creates a new source and starts connecting.
func (sm *SourceManager) Add(label, addr, multicastGroup string, dataPort int) string {
if label == "" {
label = addr
}
id := sm.genID()
c := NewUDPClient(addr, id, sm.hub, multicastGroup, dataPort)
ms := &managedSource{
id: id, label: label, addr: addr,
multicastGroup: multicastGroup, dataPort: dataPort,
client: c,
}
sm.mu.Lock()
sm.sources[id] = ms
sm.mu.Unlock()
sm.hub.AddSource(id, label, addr)
go c.Run()
return id
}
// Remove stops the source and removes it from the hub.
func (sm *SourceManager) Remove(id string) {
sm.mu.Lock()
ms, ok := sm.sources[id]
if ok {
delete(sm.sources, id)
}
sm.mu.Unlock()
if ok {
ms.client.Stop()
sm.hub.RemoveSource(id)
}
}
// Save writes the current source list to filePath.
func (sm *SourceManager) Save() error {
if sm.filePath == "" {
return fmt.Errorf("no sources-file configured")
}
sm.mu.RLock()
cfgs := make([]SourceConfig, 0, len(sm.sources))
for _, ms := range sm.sources {
cfgs = append(cfgs, SourceConfig{
Label: ms.label,
Addr: ms.addr,
MulticastGroup: ms.multicastGroup,
DataPort: ms.dataPort,
})
}
sm.mu.RUnlock()
data, err := json.MarshalIndent(cfgs, "", " ")
if err != nil {
return err
}
return os.WriteFile(sm.filePath, data, 0644)
}
// Load reads sources from path and adds them.
func (sm *SourceManager) Load(path string) error {
data, err := os.ReadFile(path)
if err != nil {
return err
}
var cfgs []SourceConfig
if err := json.Unmarshal(data, &cfgs); err != nil {
return err
}
sm.filePath = path
for _, cfg := range cfgs {
sm.Add(cfg.Label, cfg.Addr, cfg.MulticastGroup, cfg.DataPort)
}
return nil
}
// ParseSourceArg parses "label@host:port" or "host:port".
func ParseSourceArg(s string) (label, addr string) {
label, addr, _, _ = ParseSourceArgFull(s)
return
}
// ParseSourceArgFull parses "[label@]host:port[/multicastGroup:dataPort]".
func ParseSourceArgFull(s string) (label, addr, multicastGroup string, dataPort int) {
s = strings.TrimSpace(s)
rest := s
if idx := strings.Index(s, "@"); idx >= 0 {
label = strings.TrimSpace(s[:idx])
rest = strings.TrimSpace(s[idx+1:])
}
if idx := strings.Index(rest, "/"); idx >= 0 {
addr = strings.TrimSpace(rest[:idx])
mcastPart := strings.TrimSpace(rest[idx+1:])
if lastColon := strings.LastIndex(mcastPart, ":"); lastColon >= 0 {
multicastGroup = strings.TrimSpace(mcastPart[:lastColon])
dataPort, _ = strconv.Atoi(strings.TrimSpace(mcastPart[lastColon+1:]))
} else {
multicastGroup = mcastPart
}
} else {
addr = rest
}
return
}
// ─── UDPClient ────────────────────────────────────────────────────────────────
const (
silenceTimeout = 5 * time.Second
reconnectDelay = 2 * time.Second
readBufSize = 65536
udpRcvBufSize = 8 * 1024 * 1024
)
// UDPClient manages the connection to one MARTe2 streamer source.
type UDPClient struct {
serverAddr string
sourceID string
hub *Hub
multicastGroup string
dataPort int
stopCh chan struct{}
}
// NewUDPClient creates a UDPClient bound to a specific source ID.
func NewUDPClient(serverAddr, sourceID string, hub *Hub, multicastGroup string, dataPort int) *UDPClient {
return &UDPClient{
serverAddr: serverAddr,
sourceID: sourceID,
hub: hub,
multicastGroup: multicastGroup,
dataPort: dataPort,
stopCh: make(chan struct{}),
}
}
// Stop asks the client to disconnect and exit.
func (u *UDPClient) Stop() {
close(u.stopCh)
}
// Run is the main loop; it reconnects automatically if the server goes silent.
func (u *UDPClient) Run() {
for {
select {
case <-u.stopCh:
return
default:
}
u.hub.SetSourceState(u.sourceID, "connecting")
log.Printf("[%s] connecting to %s", u.sourceID, u.serverAddr)
var err error
if u.multicastGroup != "" {
err = u.runMulticastSession()
} else {
err = u.runSession()
}
if err != nil {
log.Printf("[%s] session ended: %v", u.sourceID, err)
}
u.hub.SetSourceState(u.sourceID, "disconnected")
select {
case <-u.stopCh:
return
case <-time.After(reconnectDelay):
}
}
}
// runSession opens a UDP socket, sends CONNECT, reads data until silent or error.
func (u *UDPClient) runSession() error {
conn, err := net.ListenUDP("udp4", &net.UDPAddr{})
if err != nil {
return err
}
defer conn.Close()
if err := conn.SetReadBuffer(udpRcvBufSize); err != nil {
log.Printf("[%s] udp: SetReadBuffer: %v", u.sourceID, err)
}
serverAddr, err := net.ResolveUDPAddr("udp4", u.serverAddr)
if err != nil {
return err
}
if _, err := conn.WriteToUDP(udpsprotocol.BuildConnectPacket(), serverAddr); err != nil {
return err
}
log.Printf("[%s] udp: sent CONNECT", u.sourceID)
reassembler := udpsprotocol.NewReassembler(2 * time.Second)
buf := make([]byte, readBufSize)
var currentSigs []udpsprotocol.SignalInfo
var currentPublishMode uint8
for {
conn.SetReadDeadline(time.Now().Add(silenceTimeout))
n, _, err := conn.ReadFromUDP(buf)
arrivalTime := time.Now()
if err != nil {
conn.WriteToUDP(udpsprotocol.BuildDisconnectPacket(), serverAddr)
return err
}
if n < udpsprotocol.HeaderSize {
log.Printf("[%s] udp: short datagram (%d bytes), skipping", u.sourceID, n)
continue
}
hdr, err := udpsprotocol.ParseHeader(buf[:n])
if err != nil {
log.Printf("[%s] udp: parse header: %v", u.sourceID, err)
continue
}
payload := make([]byte, n-udpsprotocol.HeaderSize)
copy(payload, buf[udpsprotocol.HeaderSize:n])
complete, ok := reassembler.AddFragment(hdr, payload)
if hdr.Type == udpsprotocol.PktData {
u.hub.RecordDataFragment(u.sourceID, hdr.Counter, n, arrivalTime.UnixNano(), ok)
}
if !ok {
continue
}
switch hdr.Type {
case udpsprotocol.PktConfig:
sigs, pm, err := udpsprotocol.ParseConfig(complete)
if err != nil {
log.Printf("[%s] udp: parse config: %v", u.sourceID, err)
continue
}
currentSigs = sigs
currentPublishMode = pm
log.Printf("[%s] udp: received CONFIG (%d signals, publishMode=%d)", u.sourceID, len(sigs), pm)
u.hub.SetSourceState(u.sourceID, "connected")
u.hub.UpdateConfigForSource(u.sourceID, sigs)
case udpsprotocol.PktData:
if len(currentSigs) == 0 {
continue
}
samples, err := udpsprotocol.ParseData(complete, currentSigs, currentPublishMode, arrivalTime)
if err != nil {
log.Printf("[%s] udp: parse data: %v", u.sourceID, err)
continue
}
for _, s := range samples {
u.hub.PushDataForSource(u.sourceID, s)
}
case udpsprotocol.PktACK:
log.Printf("[%s] udp: received ACK (counter=%d)", u.sourceID, hdr.Counter)
case udpsprotocol.PktDisconnect:
log.Printf("[%s] udp: server sent DISCONNECT", u.sourceID)
return nil
default:
log.Printf("[%s] udp: unknown packet type %d", u.sourceID, hdr.Type)
}
select {
case <-u.stopCh:
conn.WriteToUDP(udpsprotocol.BuildDisconnectPacket(), serverAddr)
return nil
default:
}
}
}
// runMulticastSession handles the multicast mode session.
func (u *UDPClient) runMulticastSession() error {
tcpAddr, err := net.ResolveTCPAddr("tcp4", u.serverAddr)
if err != nil {
return err
}
tcpConn, err := net.DialTCP("tcp4", nil, tcpAddr)
if err != nil {
return err
}
defer tcpConn.Close()
if _, err := tcpConn.Write(udpsprotocol.BuildConnectPacket()); err != nil {
return err
}
log.Printf("[%s] tcp: sent CONNECT to %s", u.sourceID, u.serverAddr)
hdrBuf := make([]byte, udpsprotocol.HeaderSize)
if _, err := io.ReadFull(tcpConn, hdrBuf); err != nil {
return err
}
cfgHdr, err := udpsprotocol.ParseHeader(hdrBuf)
if err != nil {
return err
}
if cfgHdr.Type != udpsprotocol.PktConfig {
return net.ErrClosed
}
cfgPayload := make([]byte, cfgHdr.PayloadBytes)
if cfgHdr.PayloadBytes > 0 {
if _, err := io.ReadFull(tcpConn, cfgPayload); err != nil {
return err
}
}
currentSigs, currentPublishMode, err := udpsprotocol.ParseConfig(cfgPayload)
if err != nil {
return err
}
log.Printf("[%s] tcp: received CONFIG (%d signals, publishMode=%d)", u.sourceID, len(currentSigs), currentPublishMode)
u.hub.SetSourceState(u.sourceID, "connected")
u.hub.UpdateConfigForSource(u.sourceID, currentSigs)
mcastPort := u.dataPort
if mcastPort == 0 {
mcastPort = tcpAddr.Port + 1
}
mcastIP := net.ParseIP(u.multicastGroup)
if mcastIP == nil {
return &net.AddrError{Err: "invalid multicast group IP", Addr: u.multicastGroup}
}
mcastAddr := &net.UDPAddr{IP: mcastIP, Port: mcastPort}
mcastConn, err := net.ListenMulticastUDP("udp4", nil, mcastAddr)
if err != nil {
return err
}
defer mcastConn.Close()
if err := mcastConn.SetReadBuffer(udpRcvBufSize); err != nil {
log.Printf("[%s] multicast SetReadBuffer: %v", u.sourceID, err)
}
log.Printf("[%s] joined multicast %s:%s", u.sourceID, u.multicastGroup, strconv.Itoa(mcastPort))
tcpDone := make(chan error, 1)
go func() {
buf := make([]byte, udpsprotocol.HeaderSize+64)
for {
n, readErr := tcpConn.Read(buf)
if readErr != nil {
tcpDone <- readErr
return
}
if n >= udpsprotocol.HeaderSize {
hdr, parseErr := udpsprotocol.ParseHeader(buf[:n])
if parseErr == nil && hdr.Type == udpsprotocol.PktDisconnect {
tcpDone <- nil
return
}
}
}
}()
reassembler := udpsprotocol.NewReassembler(2 * time.Second)
buf := make([]byte, readBufSize)
for {
mcastConn.SetReadDeadline(time.Now().Add(silenceTimeout))
n, _, readErr := mcastConn.ReadFromUDP(buf)
arrivalTime := time.Now()
if readErr != nil {
select {
case <-tcpDone:
return nil
default:
}
tcpConn.Write(udpsprotocol.BuildDisconnectPacket())
return readErr
}
if n < udpsprotocol.HeaderSize {
continue
}
hdr, parseErr := udpsprotocol.ParseHeader(buf[:n])
if parseErr != nil {
log.Printf("[%s] multicast: parse header: %v", u.sourceID, parseErr)
continue
}
payload := make([]byte, n-udpsprotocol.HeaderSize)
copy(payload, buf[udpsprotocol.HeaderSize:n])
complete, ok := reassembler.AddFragment(hdr, payload)
if hdr.Type == udpsprotocol.PktData {
u.hub.RecordDataFragment(u.sourceID, hdr.Counter, n, arrivalTime.UnixNano(), ok)
}
if !ok {
continue
}
if hdr.Type == udpsprotocol.PktData {
if len(currentSigs) == 0 {
continue
}
samples, parseErr := udpsprotocol.ParseData(complete, currentSigs, currentPublishMode, arrivalTime)
if parseErr != nil {
log.Printf("[%s] multicast: parse data: %v", u.sourceID, parseErr)
continue
}
for _, s := range samples {
u.hub.PushDataForSource(u.sourceID, s)
}
}
select {
case <-u.stopCh:
tcpConn.Write(udpsprotocol.BuildDisconnectPacket())
return nil
case tcpErr := <-tcpDone:
log.Printf("[%s] tcp control closed: %v", u.sourceID, tcpErr)
return nil
default:
}
}
}
+155
View File
@@ -0,0 +1,155 @@
package wshub
import (
"math"
"sync"
)
const statRingSize = 512
// SourceStat accumulates per-source UDP performance metrics.
// Thread-safe; RecordFragment is called from the UDPClient goroutine.
type SourceStat struct {
mu sync.Mutex
seenFirst bool
lastCounter uint32
TotalRx uint64
TotalLost uint64
// Cycle-time ring (seconds between consecutive DATA completions)
ctRing [statRingSize]float64
ctHead int
ctFull bool
lastRxNs int64
// Per-cycle accumulators (reset after each DATA completion)
fragCount int
byteCount int
fragRing [statRingSize]int
byteRing [statRingSize]int
}
// RecordFragment is called for every UDP datagram of a DATA packet.
// complete: this fragment completed the DATA reassembly.
// nBytes: raw datagram size (header+payload).
func (s *SourceStat) RecordFragment(counter uint32, nBytes int, arrivalNs int64, complete bool) {
s.mu.Lock()
defer s.mu.Unlock()
s.fragCount++
s.byteCount += nBytes
if !complete {
return
}
s.TotalRx++
if s.seenFirst {
if delta := counter - s.lastCounter; delta > 1 {
s.TotalLost += uint64(delta - 1)
}
} else {
s.seenFirst = true
}
s.lastCounter = counter
if s.lastRxNs != 0 {
idx := s.ctHead
s.ctRing[idx] = float64(arrivalNs-s.lastRxNs) * 1e-9
s.fragRing[idx] = s.fragCount
s.byteRing[idx] = s.byteCount
s.ctHead = (s.ctHead + 1) % statRingSize
if s.ctHead == 0 {
s.ctFull = true
}
}
s.lastRxNs = arrivalNs
s.fragCount = 0
s.byteCount = 0
}
// Snapshot computes and returns a StatInfo for broadcast.
func (s *SourceStat) Snapshot() StatInfo {
s.mu.Lock()
defer s.mu.Unlock()
n := s.ctHead
if s.ctFull {
n = statRingSize
}
si := StatInfo{TotalReceived: s.TotalRx, TotalLost: s.TotalLost}
if n == 0 {
return si
}
sum, sumSq := 0.0, 0.0
minV, maxV := math.MaxFloat64, 0.0
fragSum, byteSum := 0, 0
for i := 0; i < n; i++ {
v := s.ctRing[i]
sum += v
sumSq += v * v
if v < minV {
minV = v
}
if v > maxV {
maxV = v
}
fragSum += s.fragRing[i]
byteSum += s.byteRing[i]
}
avg := sum / float64(n)
variance := sumSq/float64(n) - avg*avg
if variance < 0 {
variance = 0
}
stdv := math.Sqrt(variance)
si.CycleAvgMs = avg * 1e3
si.CycleStdMs = stdv * 1e3
si.CycleMinMs = minV * 1e3
si.CycleMaxMs = maxV * 1e3
si.RateHz = 1.0 / avg
si.RateStdHz = stdv / (avg * avg)
si.FragsPerCycle = float64(fragSum) / float64(n)
si.BytesPerCycle = float64(byteSum) / float64(n)
const nBins = 20
si.CycleHistMin = minV * 1e3
si.CycleHistMax = maxV * 1e3
si.CycleHist = make([]int, nBins)
span := maxV - minV
for i := 0; i < n; i++ {
var bin int
if span > 0 {
bin = int((s.ctRing[i] - minV) / span * float64(nBins))
if bin >= nBins {
bin = nBins - 1
}
} else {
bin = nBins / 2
}
si.CycleHist[bin]++
}
return si
}
// StatInfo is the JSON snapshot for one source sent to the frontend.
type StatInfo struct {
TotalReceived uint64 `json:"totalReceived"`
TotalLost uint64 `json:"totalLost"`
RateHz float64 `json:"rateHz"`
RateStdHz float64 `json:"rateStdHz"`
FragsPerCycle float64 `json:"fragsPerCycle"`
BytesPerCycle float64 `json:"bytesPerCycle"`
CycleAvgMs float64 `json:"cycleAvgMs"`
CycleStdMs float64 `json:"cycleStdMs"`
CycleMinMs float64 `json:"cycleMinMs"`
CycleMaxMs float64 `json:"cycleMaxMs"`
CycleHist []int `json:"cycleHist"`
CycleHistMin float64 `json:"cycleHistMin"`
CycleHistMax float64 `json:"cycleHistMax"`
}
+234
View File
@@ -0,0 +1,234 @@
/**
* @file UDPSProtocol.h
* @brief Shared UDPS binary streaming protocol definitions.
*
* This header is free of MARTe2-specific types (other than CompilerTypes.h)
* so it can be included by both UDPStreamer (DataSource) and DebugService
* (Interface), as well as any future component that needs to produce or
* consume UDPS packets.
*
* Protocol overview
* -----------------
* Every packet starts with a 17-byte packed header (UDPSPacketHeader).
* Large payloads are split into multiple fragments sharing the same counter.
*
* Packet types:
* DATA (0) - signal sample values, Server → Client
* CONFIG (1) - signal metadata, Server → Client (sent when set changes)
* ACK (2) - counter acknowledgment, Client → Server (optional)
* CONNECT (3) - session initiation, Client → Server
* DISCONNECT (4) - session teardown, Client → Server or Server → Client
*
* CONFIG payload:
* [uint32 numSigs]
* numSigs × UDPSSignalDescriptor (136 bytes each, packed)
* [uint8 publishMode] (PublishModeStrict / Accumulate / Decimate)
*
* DATA payload (Strict / Decimate):
* [uint64 HRT timestamp]
* per-signal data in CONFIG order (quantised or raw, no padding)
*
* DATA payload (Accumulate):
* [uint64 HRT timestamp]
* [uint32 numSamples]
* for each signal: if scalar → numSamples elements; else → NumElements once
*/
#ifndef UDPS_PROTOCOL_H_
#define UDPS_PROTOCOL_H_
#include "CompilerTypes.h"
namespace MARTe {
/*---------------------------------------------------------------------------*/
/* Magic and packet types */
/*---------------------------------------------------------------------------*/
/** Magic number: ASCII 'UDPS' stored little-endian (0x53504455). */
static const uint32 UDPS_MAGIC = 0x53504455u;
/** Packet type constants — must match the Go-side PktXxx constants. */
static const uint8 UDPS_TYPE_DATA = 0u; ///< Server → Client: signal data
static const uint8 UDPS_TYPE_CONFIG = 1u; ///< Server → Client: signal config
static const uint8 UDPS_TYPE_ACK = 2u; ///< Client → Server: ack counter
static const uint8 UDPS_TYPE_CONNECT = 3u; ///< Client → Server: connect request
static const uint8 UDPS_TYPE_DISCONNECT = 4u; ///< Client → Server: disconnect
/*---------------------------------------------------------------------------*/
/* Wire packet header (17 bytes) */
/*---------------------------------------------------------------------------*/
/**
* @brief 17-byte packed UDP packet header, little-endian.
*
* All fields use unsigned integer types; no padding. Placed at offset 0
* of every UDPS datagram.
*/
#pragma pack(push, 1)
struct UDPSPacketHeader {
uint32 magic; ///< Must equal UDPS_MAGIC
uint8 type; ///< One of UDPS_TYPE_*
uint32 counter; ///< Per-update sequence counter (same for all fragments)
uint16 fragmentIdx; ///< 0-based index of this fragment
uint16 totalFragments; ///< Total fragments for this update (1 = no fragmentation)
uint32 payloadBytes; ///< Payload bytes immediately following this header
};
#pragma pack(pop)
static const uint32 UDPS_HEADER_SIZE = 17u; ///< sizeof(UDPSPacketHeader)
/*---------------------------------------------------------------------------*/
/* Signal type codes (CONFIG wire format) */
/*---------------------------------------------------------------------------*/
/** Compact type codes stored in UDPSSignalDescriptor::typeCode. */
static const uint8 UDPS_TYPECODE_UINT8 = 0u;
static const uint8 UDPS_TYPECODE_INT8 = 1u;
static const uint8 UDPS_TYPECODE_UINT16 = 2u;
static const uint8 UDPS_TYPECODE_INT16 = 3u;
static const uint8 UDPS_TYPECODE_UINT32 = 4u;
static const uint8 UDPS_TYPECODE_INT32 = 5u;
static const uint8 UDPS_TYPECODE_UINT64 = 6u;
static const uint8 UDPS_TYPECODE_INT64 = 7u;
static const uint8 UDPS_TYPECODE_FLOAT32 = 8u;
static const uint8 UDPS_TYPECODE_FLOAT64 = 9u;
static const uint8 UDPS_TYPECODE_UNKNOWN = 255u;
/*---------------------------------------------------------------------------*/
/* Quantisation and time-mode codes */
/*---------------------------------------------------------------------------*/
/** Quantisation codes stored in UDPSSignalDescriptor::quantType. */
static const uint8 UDPS_QUANT_NONE = 0u; ///< No quantisation; raw wire format
static const uint8 UDPS_QUANT_UINT8 = 1u; ///< Map to uint8 [0, 255]
static const uint8 UDPS_QUANT_INT8 = 2u; ///< Map to int8 [-127, 127]
static const uint8 UDPS_QUANT_UINT16 = 3u; ///< Map to uint16 [0, 65535]
static const uint8 UDPS_QUANT_INT16 = 4u; ///< Map to int16 [-32767, 32767]
/** Time-mode codes stored in UDPSSignalDescriptor::timeMode. */
static const uint8 UDPS_TIMEMODE_PACKET = 0u; ///< Use packet-level HRT timestamp
static const uint8 UDPS_TIMEMODE_FULL_ARRAY = 1u; ///< TimeSignal has NumElements timestamps
static const uint8 UDPS_TIMEMODE_FIRST_SAMPLE = 2u; ///< TimeSignal scalar = timestamp of element [0]
static const uint8 UDPS_TIMEMODE_LAST_SAMPLE = 3u; ///< TimeSignal scalar = timestamp of element [N-1]
/** Sentinel value for UDPSSignalDescriptor::timeSignalIdx when no time signal. */
static const uint32 UDPS_NO_TIME_SIGNAL = 0xFFFFFFFFu;
/*---------------------------------------------------------------------------*/
/* Publish mode codes (CONFIG trailing byte) */
/*---------------------------------------------------------------------------*/
static const uint8 UDPS_PUBLISH_STRICT = 0u; ///< One packet per Synchronise() call
static const uint8 UDPS_PUBLISH_ACCUMULATE = 1u; ///< Variable batch; flush on size or time
static const uint8 UDPS_PUBLISH_DECIMATE = 2u; ///< One packet per Ratio calls
/*---------------------------------------------------------------------------*/
/* CONFIG payload — per-signal descriptor */
/*---------------------------------------------------------------------------*/
/** Maximum length of signal name and unit strings in the CONFIG payload. */
static const uint32 UDPS_MAX_SIGNAL_NAME = 64u;
static const uint32 UDPS_MAX_UNIT_LEN = 32u;
/** Byte size of one serialised UDPSSignalDescriptor on the wire. */
static const uint32 UDPS_SIGNAL_DESC_SIZE = 136u;
/**
* @brief Wire-format per-signal descriptor embedded in the CONFIG payload.
*
* Contains only plain C types so it can be memcpy'd directly to/from
* the network buffer (little-endian on all supported platforms).
*
* Size: 64 + 1 + 1 + 1 + 4 + 4 + 8 + 8 + 1 + 8 + 4 + 32 = 136 bytes.
*/
#pragma pack(push, 1)
struct UDPSSignalDescriptor {
char8 name[UDPS_MAX_SIGNAL_NAME]; ///< Null-terminated signal name
uint8 typeCode; ///< UDPS_TYPECODE_*
uint8 quantType; ///< UDPS_QUANT_*
uint8 numDimensions; ///< 0=scalar, 1=array, 2=matrix
uint32 numRows; ///< Number of rows (or elements for 1D)
uint32 numCols; ///< Number of columns (1 for 1D/scalar)
float64 rangeMin; ///< Physical range minimum (for quantisation)
float64 rangeMax; ///< Physical range maximum (for quantisation)
uint8 timeMode; ///< UDPS_TIMEMODE_*
float64 samplingRate; ///< Hz; used for FirstSample/LastSample modes
uint32 timeSignalIdx; ///< Index of time-ref signal; UDPS_NO_TIME_SIGNAL if none
char8 unit[UDPS_MAX_UNIT_LEN]; ///< Null-terminated physical unit string
};
#pragma pack(pop)
/*---------------------------------------------------------------------------*/
/* TypeDescriptor → UDPS type-code mapping */
/*---------------------------------------------------------------------------*/
/**
* @brief Maps a MARTe2 TypeDescriptor to the compact UDPS_TYPECODE_* value.
*
* Returns UDPS_TYPECODE_UNKNOWN for types that have no UDPS equivalent.
* Defined inline to avoid a separate translation unit for this trivial table.
*/
inline uint8 UDPSTypeDescriptorToCode(TypeDescriptor td) {
if (td == UnsignedInteger8Bit) return UDPS_TYPECODE_UINT8;
if (td == SignedInteger8Bit) return UDPS_TYPECODE_INT8;
if (td == UnsignedInteger16Bit) return UDPS_TYPECODE_UINT16;
if (td == SignedInteger16Bit) return UDPS_TYPECODE_INT16;
if (td == UnsignedInteger32Bit) return UDPS_TYPECODE_UINT32;
if (td == SignedInteger32Bit) return UDPS_TYPECODE_INT32;
if (td == UnsignedInteger64Bit) return UDPS_TYPECODE_UINT64;
if (td == SignedInteger64Bit) return UDPS_TYPECODE_INT64;
if (td == Float32Bit) return UDPS_TYPECODE_FLOAT32;
if (td == Float64Bit) return UDPS_TYPECODE_FLOAT64;
return UDPS_TYPECODE_UNKNOWN;
}
/**
* @brief Returns the wire byte size of one element for the given type code.
* Returns 0 for UDPS_TYPECODE_UNKNOWN.
*/
inline uint32 UDPSTypeCodeByteSize(uint8 typeCode) {
switch (typeCode) {
case UDPS_TYPECODE_UINT8: case UDPS_TYPECODE_INT8: return 1u;
case UDPS_TYPECODE_UINT16: case UDPS_TYPECODE_INT16: return 2u;
case UDPS_TYPECODE_UINT32: case UDPS_TYPECODE_INT32:
case UDPS_TYPECODE_FLOAT32: return 4u;
case UDPS_TYPECODE_UINT64: case UDPS_TYPECODE_INT64:
case UDPS_TYPECODE_FLOAT64: return 8u;
default: return 0u;
}
}
/*---------------------------------------------------------------------------*/
/* Inline packet-building helpers */
/*---------------------------------------------------------------------------*/
/**
* @brief Serialise a UDPSPacketHeader into the first 17 bytes of @p buf.
* @param buf Must have room for at least UDPS_HEADER_SIZE bytes.
* @param type Packet type (UDPS_TYPE_*).
* @param counter Per-update sequence counter.
* @param fragIdx 0-based fragment index.
* @param totalFrags Total fragments for this update.
* @param payloadBytes Bytes of payload that follow this header.
*/
inline void UDPSBuildHeader(uint8 *buf,
uint8 type,
uint32 counter,
uint16 fragIdx,
uint16 totalFrags,
uint32 payloadBytes)
{
UDPSPacketHeader hdr;
hdr.magic = UDPS_MAGIC;
hdr.type = type;
hdr.counter = counter;
hdr.fragmentIdx = fragIdx;
hdr.totalFragments = totalFrags;
hdr.payloadBytes = payloadBytes;
memcpy(buf, &hdr, UDPS_HEADER_SIZE);
}
} /* namespace MARTe */
#endif /* UDPS_PROTOCOL_H_ */