#include <stdlib.h>
#include <assert.h>
#include <signal.h>
#include <zmq.h>

#include "processvalue.pb-c.h"


#define BUFSIZE 1024

int running = 1;
static void stopHandler(int sign) {
  printf("received ctrl-c\n");
  running = 0;
}



int main(int argc, char** argv) {
  signal(SIGINT, stopHandler); /* catches ctrl-c */

  /* prepare zmq context, connect to server and subscribe with empty filter */
  void *zmqContext = zmq_ctx_new();
  void *zmqSubscriber = zmq_socket(zmqContext, ZMQ_SUB);
  int rc = zmq_connect(zmqSubscriber, "tcp://127.0.0.1:12346");
  assert(rc == 0);
  rc = zmq_setsockopt(zmqSubscriber, ZMQ_SUBSCRIBE, 0, 0);
  assert(rc == 0);

  while (running) {
    char buf[BUFSIZE];
    int rcLen = zmq_recv(zmqSubscriber, buf, BUFSIZE, 0);
    assert(rcLen != -1);

    Krohne__ProcessValue *processValue = krohne__process_value__unpack(NULL, rcLen, buf);
    assert(processValue != NULL);
    printf("value:  %d\n", processValue->value);
    printf("unit:   %i\n", processValue->unit);
    printf("status: %i\n", processValue->status);
    krohne__process_value__free_unpacked(processValue, NULL);
  }

  printf("Terminating ...\n");
  zmq_close(zmqSubscriber);
  zmq_ctx_destroy(zmqContext);
}
