/* Message related functions.
 *
 * Author: Steffen Vogel <post@steffenvogel.de>
 * SPDX-FileCopyrightText: 2014-2023 Institute for Automation of Complex Power Systems, RWTH Aachen University
 * SPDX-License-Identifier: Apache-2.0
 */

#include <arpa/inet.h>

#include "msg.h"
#include "msg_format.h"

void msg_ntoh(struct msg *m) {
  msg_hdr_ntoh(m);

  for (int i = 0; i < m->length; i++)
    m->data[i].i = ntohl(m->data[i].i);
}

void msg_hton(struct msg *m) {
  for (int i = 0; i < m->length; i++)
    m->data[i].i = htonl(m->data[i].i);

  msg_hdr_hton(m);
}

void msg_hdr_hton(struct msg *m) {
  m->length = htons(m->length);
  m->sequence = htonl(m->sequence);
  m->ts.sec = htonl(m->ts.sec);
  m->ts.nsec = htonl(m->ts.nsec);
}

void msg_hdr_ntoh(struct msg *m) {
  m->length = ntohs(m->length);
  m->sequence = ntohl(m->sequence);
  m->ts.sec = ntohl(m->ts.sec);
  m->ts.nsec = ntohl(m->ts.nsec);
}

int msg_verify(struct msg *m) {
  if (m->version != MSG_VERSION)
    return -1;
  else if (m->type != MSG_TYPE_DATA)
    return -2;
  else if (m->reserved1 != 0)
    return -3;
  else
    return 0;
}
