示例#1
0
void *in_serial_flush(void *in_context, int *size)
{
    char *buf;
    msgpack_sbuffer *sbuf;
    struct flb_in_serial_config *ctx = in_context;

    if (ctx->buffer_id == 0)
        return NULL;

    sbuf = &ctx->mp_sbuf;
    *size = sbuf->size;
    buf = malloc(sbuf->size);
    if (!buf) {
        return NULL;
    }

    /* set a new buffer and re-initialize our MessagePack context */
    memcpy(buf, sbuf->data, sbuf->size);
    msgpack_sbuffer_destroy(&ctx->mp_sbuf);
    msgpack_sbuffer_init(&ctx->mp_sbuf);
    msgpack_packer_init(&ctx->mp_pck, &ctx->mp_sbuf, msgpack_sbuffer_write);

    ctx->buffer_id = 0;

    return buf;
}
void ANetworkController::ReceivedSeekAndPauseReplay(msgpack_object* Data) {
	AReplayPlayer* Player = NULL;
	for (TActorIterator<AReplayPlayer> ObjIt(GetWorld()); ObjIt; ++ObjIt) {
		Player = *ObjIt;
		break;
	}
	check(Player != NULL);

	float Seconds = Unpack<double>(Data);
	Player->SeekAndPause(Seconds);

	msgpack_sbuffer sbuf;
	msgpack_sbuffer_init(&sbuf);

	msgpack_packer pk;
	msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

	msgpack_pack_array(&pk, 2);
	msgpack_pack_uint16(&pk, EPacketType::PT_SeekAndPauseReplay);

	msgpack_pack_float(&pk, Player->GetTime());

	int32 BytesSent;
	TcpSocket->Send((uint8*)sbuf.data, sbuf.size, BytesSent);

	msgpack_sbuffer_destroy(&sbuf);
}
示例#3
0
int main(void)
{
    msgpack_sbuffer sbuf;
    msgpack_packer pk;
    msgpack_zone mempool;
    msgpack_object deserialized;

    /* msgpack::sbuffer is a simple buffer implementation. */
    msgpack_sbuffer_init(&sbuf);

    /* serialize values into the buffer using msgpack_sbuffer_write callback function. */
    msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

    msgpack_pack_array(&pk, 3);
    msgpack_pack_int(&pk, 1);
    msgpack_pack_true(&pk);
    msgpack_pack_str(&pk, 7);
    msgpack_pack_str_body(&pk, "example", 7);

    /* deserialize the buffer into msgpack_object instance. */
    /* deserialized object is valid during the msgpack_zone instance alive. */
    msgpack_zone_init(&mempool, 2048);

    msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

    /* print the deserialized object. */
    msgpack_object_print(stdout, deserialized);
    puts("");

    msgpack_zone_destroy(&mempool);
    msgpack_sbuffer_destroy(&sbuf);

    return 0;
}
示例#4
0
void *in_xbee_flush(void *in_context, int *size)
{
    char *buf;
    msgpack_sbuffer *sbuf;
    struct flb_in_xbee_config *ctx = in_context;

    pthread_mutex_lock(&ctx->mtx_mp);

    if (ctx->buffer_id == 0)
        goto fail;

    sbuf = &ctx->mp_sbuf;
    *size = sbuf->size;
    buf = malloc(sbuf->size);
    if (!buf)
        goto fail;

    /* set a new buffer and re-initialize our MessagePack context */
    memcpy(buf, sbuf->data, sbuf->size);
    msgpack_sbuffer_destroy(&ctx->mp_sbuf);
    msgpack_sbuffer_init(&ctx->mp_sbuf);
    msgpack_packer_init(&ctx->mp_pck, &ctx->mp_sbuf, msgpack_sbuffer_write);

    ctx->buffer_id = 0;

    pthread_mutex_unlock(&ctx->mtx_mp);
    return buf;

fail:
    pthread_mutex_unlock(&ctx->mtx_mp);
    return NULL;
}
void test()
{
	uint64_t test_u64 = 0xFFF0000000000001LL;
	size_t size = 10000000;
	msgpack_sbuffer buf;
	msgpack_sbuffer_init(&buf);

	msgpack_packer * pk = msgpack_packer_new(&buf, msgpack_sbuffer_write);

	msgpack_pack_array(pk, size);
	{
		int idx = 0;
		for (; idx < size; ++idx)
			msgpack_pack_uint64(pk, test_u64);
	}
	msgpack_packer_free(pk);


	size_t upk_pos = 0;
	msgpack_unpacked msg;
	msgpack_unpacked_init(&msg);

	while (msgpack_unpack_next(&msg, buf.data, buf.size, &upk_pos)) {
	}

	msgpack_sbuffer_destroy(&buf);
}
示例#6
0
	virtual void encode()
	{
		mImgs = boost::shared_ptr<boost::circular_buffer<CameraImage> >(new boost::circular_buffer<CameraImage>(60));
		while(1)
		{
			if(mImgs->size() == 0)
			{
				usleep(3000);
				continue;
			}
			printf("encoding!\n");
			CameraImage i = mImgs->back();
			mImgs->pop_back();
			encodeImage(i);
			msgpack_sbuffer buffer;
			msgpack_packer pk;
			msgpack_sbuffer_init(&buffer);
			msgpack_packer_init(&pk, &buffer, msgpack_sbuffer_write);
			msgpack_pack_array(&pk, 4);
			msgpack_pack_int(&pk, 1);
			msgpack_pack_int(&pk, i.camera_timestamp);
			msgpack_pack_raw(&pk, i.encoded.size);
			msgpack_pack_raw_body(&pk, (void*)i.encoded.buffer.get(), i.encoded.size);
			write(mFile, buffer.data, buffer.size);
			msgpack_sbuffer_destroy(&buffer);
		}
	}
int main(void) {
    msgpack_sbuffer sbuf;
    msgpack_sbuffer_init(&sbuf);

    prepare(&sbuf);
    unpack(sbuf.data, sbuf.size);

    msgpack_sbuffer_destroy(&sbuf);
    return 0;
}
void unit_message_serialize_request(UNUSED(void **state))
{
  msgpack_sbuffer sbuf;
  msgpack_packer pk;
  struct message_request request;
  array params;

  params.size = 1;
  params.obj = CALLOC(1, struct message_object);
  params.obj[0].type = OBJECT_TYPE_UINT;
  params.obj[0].data.uinteger = 1234;

  msgpack_sbuffer_init(&sbuf);

  /* positiv test */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  request.msgid = 1234;
  request.method = (string) {.str = "test method",
      .length = sizeof("test method") - 1};
  request.params = params;
  assert_int_equal(0, message_serialize_request(&request, &pk));
  msgpack_sbuffer_clear(&sbuf);

  /* no valid string */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  request.msgid = 1234;
  request.method = (string) STRING_INIT;
  request.params = params;
  assert_int_not_equal(0, message_serialize_request(&request, &pk));
  msgpack_sbuffer_clear(&sbuf);

  free_params(request.params);

  params.size = 1;
  params.obj = CALLOC(1, struct message_object);
  params.obj[0].type = 1000;
  params.obj[0].data.uinteger = 1234;

  /* no valid params */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  request.msgid = 1234;
  request.method = (string) {.str = "test method",
      .length = sizeof("test method") - 1};
  request.params = params;
  assert_int_not_equal(0, message_serialize_request(&request, &pk));
  msgpack_sbuffer_clear(&sbuf);

  free_params(request.params);

  /* null check */
  assert_int_not_equal(0, message_serialize_request(NULL, NULL));

  msgpack_sbuffer_destroy(&sbuf);
}
void unit_message_is_response(UNUSED(void **state))
{
  msgpack_sbuffer sbuf;
  msgpack_packer pk;
  msgpack_zone mempool;
  msgpack_object deserialized;

  msgpack_sbuffer_init(&sbuf);
  msgpack_zone_init(&mempool, 2048);

  /* positiv test */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_pack_uint8(&pk, 0);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_true(message_is_response(&deserialized));

  msgpack_sbuffer_clear(&sbuf);

  /* wrong type test */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 0);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint8(&pk, 1);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_false(message_is_response(&deserialized));

  msgpack_sbuffer_clear(&sbuf);

  /* no array test */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_uint8(&pk, 1);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_false(message_is_response(&deserialized));

  msgpack_sbuffer_clear(&sbuf);

  /* NULL test */
  assert_false(message_is_response(NULL));

  msgpack_sbuffer_clear(&sbuf);

  msgpack_zone_destroy(&mempool);
  msgpack_sbuffer_destroy(&sbuf);
}
示例#10
0
void lib_msgpack_process(char *str)
{
	
	/* msgpack::sbuffer is a simple buffer implementation. */
	msgpack_sbuffer sbuf;
	msgpack_sbuffer_init(&sbuf);

	/* serialize values into the buffer using msgpack_sbuffer_write callback function. */	
	msgpack_packer pk;
	msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

	return 0;
}
示例#11
0
int main(int argc,char **argv) {
    msgpack_sbuffer sbuf;
    msgpack_sbuffer_init(&sbuf);

    prepare(&sbuf);
    char bf[2048]={0};
    prepare_from_file(argv[1],bf,atoi(argv[2]));

    unpack(bf, atoi(argv[2]));

    msgpack_sbuffer_destroy(&sbuf);
    return 0;
}
示例#12
0
void *in_mem_flush(void *in_context, int *size)
{
    char *buf;
    struct flb_in_mem_config *ctx = in_context;

    buf = malloc(ctx->sbuf.size);
    if (!buf) {
        return NULL;
    }
    memcpy(buf, ctx->sbuf.data, ctx->sbuf.size);
    *size = ctx->sbuf.size;
    msgpack_sbuffer_destroy(&ctx->sbuf);
    msgpack_sbuffer_init(&ctx->sbuf);
    msgpack_packer_init(&ctx->pckr, &ctx->sbuf, msgpack_sbuffer_write);
    ctx->idx = 0;
    return buf;
}
void ANetworkController::ReceivedGetGitHash() {
	msgpack_sbuffer sbuf;
	msgpack_sbuffer_init(&sbuf);

	msgpack_packer pk;
	msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

	msgpack_pack_array(&pk, 2);
	msgpack_pack_uint16(&pk, EPacketType::PT_GetGitHash);

	msgpack_pack_str(&pk, GIT_HASH_LEN);
	msgpack_pack_str_body(&pk, GIT_HASH, GIT_HASH_LEN);

	int32 BytesSent;
	TcpSocket->Send((uint8*)sbuf.data, sbuf.size, BytesSent);

	msgpack_sbuffer_destroy(&sbuf);
}
示例#14
0
void receiver_init(receiver *r) {
    msgpack_packer pk;

    msgpack_sbuffer_init(&r->sbuf);
    msgpack_packer_init(&pk, &r->sbuf, msgpack_sbuffer_write);
    /* 1st object */
    msgpack_pack_array(&pk, 3);
    msgpack_pack_int(&pk, 1);
    msgpack_pack_true(&pk);
    msgpack_pack_str(&pk, 7);
    msgpack_pack_str_body(&pk, "example", 7);
    /* 2nd object */
    msgpack_pack_str(&pk, 6);
    msgpack_pack_str_body(&pk, "second", 6);
    /* 3rd object */
    msgpack_pack_array(&pk, 2);
    msgpack_pack_int(&pk, 42);
    msgpack_pack_false(&pk);
    r->rest = r->sbuf.size;
}
示例#15
0
static char *
pack_data(int *size)
{
	msgpack_sbuffer *buffer = NULL;
	msgpack_packer *packer  = NULL;
	char *data;

	buffer = msgpack_sbuffer_new();
	msgpack_sbuffer_init(buffer);
	packer = msgpack_packer_new((void *)buffer, msgpack_sbuffer_write);

	pack_node(packer, &node);

	data = (char *)malloc(buffer->size + 1);
	memcpy(data, &buffer->data[0], buffer->size);
	data[buffer->size] = '\0';
	*size = buffer->size;

	msgpack_packer_free(packer);
	msgpack_sbuffer_free(buffer);
	return data;
}
示例#16
0
文件: helper.c 项目: nanopack/redd
void
save_data(char *filename, save_data_function pack_function)
{
	msgpack_sbuffer *buffer = NULL;
	msgpack_packer *packer  = NULL;
	char *save_file_name;
	FILE *save_file;

	if ((save_file_name = get_save_file_path(filename)) == NULL) {
		red_log(REDD_WARNING, "get_save_file_path returned NULL");
		return;
	}

	buffer = msgpack_sbuffer_new();
	msgpack_sbuffer_init(buffer);

	packer = msgpack_packer_new((void *)buffer, msgpack_sbuffer_write);

	msgpack_pack_map(packer, 1);
	pack_function(packer);

	if ((save_file = fopen(save_file_name, "w")) != NULL) {
		size_t written;
		written = fwrite((void *)&buffer->data[0], 1, buffer->size, save_file);
		fclose(save_file);
		if (written != buffer->size) {
			red_log(REDD_WARNING, "Failed to write to %s", save_file_name);
		}
	} else {
		red_log(REDD_WARNING, "Failed to open %s", save_file_name);
	}

	free(save_file_name);
	save_file_name = NULL;
	msgpack_packer_free(packer);
	packer = NULL;
	msgpack_sbuffer_free(buffer);
	buffer = NULL;
}
示例#17
0
void init_unpack_array(msgpack_object_type type)
{
  size_t off = 0;

  msgpack_sbuffer sbuf;
  msgpack_sbuffer_init(&sbuf);
  msgpack_packer pk;
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

  msgpack_pack_array(&pk, 3);
  if (type == MSGPACK_OBJECT_NIL) {
    msgpack_pack_nil(&pk);
  } else if (type == MSGPACK_OBJECT_POSITIVE_INTEGER) {
    msgpack_pack_int(&pk, 1);
  } else if (type == MSGPACK_OBJECT_BOOLEAN) {
    msgpack_pack_true(&pk);
  } else if (type == MSGPACK_OBJECT_MAP) {
    msgpack_pack_map(&pk, 1);
  } else if (type == MSGPACK_OBJECT_ARRAY) {
    msgpack_pack_array(&pk, 3);
    msgpack_pack_int(&pk, 1);
    msgpack_pack_int(&pk, 1);
    msgpack_pack_int(&pk, 1);
  } else if (type == MSGPACK_OBJECT_FLOAT) {
    msgpack_pack_double(&pk, 1.2);
  }
  msgpack_pack_true(&pk);
  msgpack_pack_str(&pk, 7);
  msgpack_pack_str_body(&pk, "example", 7);

  msgpack_unpacked result;

  msgpack_unpacked_init(&result);
  msgpack_unpack_next(&result, sbuf.data, sbuf.size, &off);
  msgpack_sbuffer_destroy(&sbuf);
  deserialized = result.data;
}
示例#18
0
static void
log_send(struct evkeyvalq *output_headers, struct evbuffer *res_buf,
         thd_data *thd, struct evkeyvalq *get_args)
{
  uint64_t millisec;
  int threshold, limit;
  const char *callback, *types, *query, *client_id, *target_name,
             *learn_target_name;

  parse_keyval(get_args, &query, &types, &client_id, &target_name,
               &learn_target_name, &callback, &millisec, &threshold, &limit);

  /* send data to learn client */
  if (thd->zmq_sock && millisec && client_id && query && learn_target_name) {
    char c;
    size_t l;
    msgpack_packer pk;
    msgpack_sbuffer sbuf;
    int cnt, submit_flag = 0;

    msgpack_sbuffer_init(&sbuf);
    msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

    cnt = 4;
    if (types && !strcmp(types, "submit")) {
      cnt++;
      types = NULL;
      submit_flag = 1;
    }
    msgpack_pack_map(&pk, cnt);

    c = 'i';
    msgpack_pack_raw(&pk, 1);
    msgpack_pack_raw_body(&pk, &c, 1);
    l = strlen(client_id);
    msgpack_pack_raw(&pk, l);
    msgpack_pack_raw_body(&pk, client_id, l);

    c = 'q';
    msgpack_pack_raw(&pk, 1);
    msgpack_pack_raw_body(&pk, &c, 1);
    l = strlen(query);
    msgpack_pack_raw(&pk, l);
    msgpack_pack_raw_body(&pk, query, l);

    c = 's';
    msgpack_pack_raw(&pk, 1);
    msgpack_pack_raw_body(&pk, &c, 1);
    msgpack_pack_uint64(&pk, millisec);

    c = 'l';
    msgpack_pack_raw(&pk, 1);
    msgpack_pack_raw_body(&pk, &c, 1);
    l = strlen(learn_target_name);
    msgpack_pack_raw(&pk, l);
    msgpack_pack_raw_body(&pk, learn_target_name, l);

    if (submit_flag) {
      c = 't';
      msgpack_pack_raw(&pk, 1);
      msgpack_pack_raw_body(&pk, &c, 1);
      msgpack_pack_true(&pk);
    }
    {
      zmq_msg_t msg;
      if (!zmq_msg_init_size(&msg, sbuf.size)) {
        memcpy((void *)zmq_msg_data(&msg), sbuf.data, sbuf.size);
        if (zmq_send(thd->zmq_sock, &msg, 0)) {
          print_error("zmq_send() error");
        }
        zmq_msg_close(&msg);
      }
    }
    msgpack_sbuffer_destroy(&sbuf);
  }
  /* make result */
  {
    int content_length;
    if (callback) {
      evhttp_add_header(output_headers,
                        "Content-Type", "text/javascript; charset=UTF-8");
      content_length = strlen(callback);
      evbuffer_add(res_buf, callback, content_length);
      evbuffer_add(res_buf, "(", 1);
      content_length += suggest_result(res_buf, types, query, target_name,
                                       threshold, limit,
                                       &(thd->cmd_buf), thd->ctx) + 3;
      evbuffer_add(res_buf, ");", 2);
    } else {
      evhttp_add_header(output_headers,
                        "Content-Type", "application/json; charset=UTF-8");
      content_length = suggest_result(res_buf, types, query, target_name,
                                      threshold, limit,
                                      &(thd->cmd_buf), thd->ctx);
    }
    if (content_length >= 0) {
      char num_buf[16];
      snprintf(num_buf, 16, "%d", content_length);
      evhttp_add_header(output_headers, "Content-Length", num_buf);
    }
  }
}
void unit_message_deserialize_response(UNUSED(void **state))
{
  struct api_error error = ERROR_INIT;
  msgpack_sbuffer sbuf;
  msgpack_packer pk;
  msgpack_zone mempool;
  msgpack_object deserialized;
  struct message_response response;

  msgpack_sbuffer_init(&sbuf);
  msgpack_zone_init(&mempool, 2048);

  /* positiv test */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint32(&pk, 1234);
  msgpack_pack_nil(&pk);
  msgpack_pack_array(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  free_params(response.params);

  /* wrong type type */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_nil(&pk);
  msgpack_pack_uint32(&pk, 1234);
  msgpack_pack_nil(&pk);
  msgpack_pack_array(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  /* wrong type */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 0);
  msgpack_pack_uint32(&pk, 1234);
  msgpack_pack_nil(&pk);
  msgpack_pack_array(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  /* wrong msgid */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_int(&pk, -1234);
  msgpack_pack_nil(&pk);
  msgpack_pack_array(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  /* wrong msgid value*/
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint32(&pk, UINT32_MAX);
  msgpack_pack_nil(&pk);
  msgpack_pack_array(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  /* wrong nil */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint32(&pk, 1234);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_array(&pk, 1);
  msgpack_pack_uint8(&pk, 0);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  /* wrong params */
  msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
  msgpack_pack_array(&pk, 4);
  msgpack_pack_uint8(&pk, 1);
  msgpack_pack_uint32(&pk, 1234);
  msgpack_pack_nil(&pk);
  msgpack_pack_nil(&pk);
  msgpack_unpack(sbuf.data, sbuf.size, NULL, &mempool, &deserialized);

  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      &error));

  msgpack_sbuffer_clear(&sbuf);

  /* null input params */
  assert_int_not_equal(0, message_deserialize_response(&response, &deserialized,
      NULL));
  assert_int_not_equal(0, message_deserialize_response(&response, NULL,
      &error));
  assert_int_not_equal(0, message_deserialize_response(NULL, &deserialized,
      &error));

  msgpack_zone_destroy(&mempool);
  msgpack_sbuffer_destroy(&sbuf);
}
示例#20
0
void msgpack_rpc_helpers_init(void)
{
  msgpack_zone_init(&zone, 0xfff);
  msgpack_sbuffer_init(&sbuffer);
}
示例#21
0
/* Init serial input */
int in_serial_init(struct flb_config *config)
{
    int fd;
    int ret;
    struct flb_in_serial_config *ctx;

    ctx = calloc(1, sizeof(struct flb_in_serial_config));
    if (!ctx) {
        perror("calloc");
        return -1;
    }

    if (!config->file) {
        flb_utils_error_c("serial input plugin needs configuration file");
        return -1;
    }

    serial_config_read(ctx, config->file);

    /* set context */
    ret = flb_input_set_context("serial", ctx, config);
    if (ret == -1) {
        flb_utils_error_c("Could not set configuration for"
                "serial input plugin");
    }

    if (ret == -1) {
        flb_utils_error_c("Could not set collector for serial input plugin");
    }

    /* initialize MessagePack buffers */
    msgpack_sbuffer_init(&ctx->mp_sbuf);
    msgpack_packer_init(&ctx->mp_pck, &ctx->mp_sbuf, msgpack_sbuffer_write);

    tcgetattr(fd, &ctx->tio_orig);
    memset(&ctx->tio, 0, sizeof(ctx->tio));
    ctx->tio.c_cflag = ctx->tio.c_ispeed = ctx->tio.c_ospeed = atoi(ctx->bitrate);
    ctx->tio.c_cflag |= CRTSCTS | CS8 | CLOCAL | CREAD;
    ctx->tio.c_iflag = IGNPAR | IGNCR;
    ctx->tio.c_oflag = 0;
    ctx->tio.c_lflag = ICANON;

    /* open device */
    fd = open(ctx->file, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd == -1) {
        perror("open");
        flb_utils_error_c("Could not open serial port device");
    }
    ctx->fd = fd;

    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &ctx->tio);

#if __linux__
    /* Set our collector based on a file descriptor event */
    ret = flb_input_set_collector_event("serial",
                                        in_serial_collect,
                                        ctx->fd,
                                        config);
#else
    /* Set our collector based on a timer event */
    ret = flb_input_set_collector_time("serial",
                                       in_serial_collect,
                                       IN_SERIAL_COLLECT_SEC,
                                       IN_SERIAL_COLLECT_NSEC,
                                       config);
#endif

    return 0;
}
示例#22
0
/* Init CPU input */
int in_cpu_init(struct flb_config *config)
{
    int i;
    int ret;
    int len;
    double total;
    struct flb_in_cpu_config *ctx;
    struct cpu_stats *cstats;
    struct cpu_snapshot *snap;

    /* Allocate space for the configuration */
    ctx = malloc(sizeof(struct flb_in_cpu_config));
    if (!ctx) {
        perror("malloc");
        return -1;
    }

    /* Gather number of processors and CPU ticks */
    ctx->n_processors = sysconf(_SC_NPROCESSORS_ONLN);
    ctx->cpu_ticks    = sysconf(_SC_CLK_TCK);

    /* Initialize buffers for CPU stats */
    cstats = &ctx->cstats;
    cstats->info = malloc(sizeof(struct cpu_snapshot) * (ctx->n_processors + 1));
    if (!cstats->info) {
        perror("malloc");
        return -1;
    }

    for (i = 1; i <= ctx->n_processors; i++) {
        snap = &cstats->info[i];

        CPU_KEY_FORMAT(snap, user, i);
        CPU_KEY_FORMAT(snap, nice, i);
        CPU_KEY_FORMAT(snap, system, i);
        CPU_KEY_FORMAT(snap, idle, i);
        CPU_KEY_FORMAT(snap, iowait, i);
        CPU_KEY_FORMAT(snap, irq, i);
        CPU_KEY_FORMAT(snap, softirq, i);
    }


    /* initialize MessagePack buffers */
    msgpack_sbuffer_init(&ctx->mp_sbuf);
    msgpack_packer_init(&ctx->mp_pck, &ctx->mp_sbuf, msgpack_sbuffer_write);

    /* Get CPU load, ready to be updated once fired the calc callback */
    total = proc_cpu_load(ctx->n_processors, &ctx->cstats);
    if (total == -1) {
        flb_utils_error_c("Could not obtain CPU data");
    }
    ctx->cstats.load_pre = total;

    /* Set the context */
    ret = flb_input_set_context("cpu", ctx, config);
    if (ret == -1) {
        flb_utils_error_c("Could not set configuration for CPU input plugin");
    }

    /* Set our collector based on time, CPU usage every 1 second */
    ret = flb_input_set_collector_time("cpu",
                                       in_cpu_collect,
                                       IN_CPU_COLLECT_SEC,
                                       IN_CPU_COLLECT_NSEC,
                                       config);
    if (ret == -1) {
        flb_utils_error_c("Could not set collector for CPU input plugin");
    }

    return 0;
}
示例#23
0
/* Init serial input */
int in_serial_init(struct flb_config *config)
{
    int fd;
    int ret;
    struct flb_in_serial_config *ctx;

    ctx = calloc(1, sizeof(struct flb_in_serial_config));
    if (!ctx) {
        perror("calloc");
        return -1;
    }

    if (!config->file) {
        flb_utils_error_c("serial input plugin needs configuration file");
        return -1;
    }

    serial_config_read(ctx, config->file);

    /* set context */
    ret = flb_input_set_context("serial", ctx, config);
    if (ret == -1) {
        flb_utils_error_c("Could not set configuration for"
                "serial input plugin");
    }

    if (ret == -1) {
        flb_utils_error_c("Could not set collector for serial input plugin");
    }

    /* initialize MessagePack buffers */
    msgpack_sbuffer_init(&ctx->mp_sbuf);
    msgpack_packer_init(&ctx->mp_pck, &ctx->mp_sbuf, msgpack_sbuffer_write);

    tcgetattr(fd, &ctx->tio_orig);
    memset(&ctx->tio, 0, sizeof(ctx->tio));
    switch (atoi(ctx->bitrate)) {
        case 1200:
            ctx->tio.c_cflag = B1200;
            break;
        case 2400:
            ctx->tio.c_cflag = B2400;
            break;
        case 4800:
            ctx->tio.c_cflag = B4800;
            break;
        case 9600:
            ctx->tio.c_cflag = B9600;
            break;
        case 19200:
            ctx->tio.c_cflag = B19200;
            break;
        case 38400:
            ctx->tio.c_cflag = B38400;
            break;

#ifdef __LINUX__
        case 576000:
            ctx->tio.c_cflag = B576000;
            break;
        case 115200:
            ctx->tio.c_cflag = B115200;
            break;
#endif

        default:
            flb_utils_error_c("Invalid bitrate for serial plugin");
    }

    ctx->tio.c_cflag |= CRTSCTS | CS8 | CLOCAL | CREAD;
    ctx->tio.c_iflag = IGNPAR | IGNCR;
    ctx->tio.c_oflag = 0;
    ctx->tio.c_lflag = ICANON;

    /* open device */
    fd = open(ctx->file, O_RDWR | O_NOCTTY);
    if (fd == -1) {
        perror("open");
        flb_utils_error_c("Could not open serial port device");
    }
    ctx->fd = fd;

    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &ctx->tio);

    /* Set our collector based on a file descriptor event */
    ret = flb_input_set_collector_event("serial",
                                        in_serial_collect,
                                        ctx->fd,
                                        config);
    return 0;
}
示例#24
0
文件: client.c 项目: tnako/DP
void* run_test(void  *threadid)
{
    long tid = (long)threadid;

    for (int cycle = 0; cycle < CYCLES; ++cycle) {

        GHashTable* sockets = g_hash_table_new(g_direct_hash, g_direct_equal);

        int epfd = epoll_create(MAX_CONNECTIONS);
        if (epfd < 1) {
            printf("can't create epoll\n");
            if (sockets) {
                g_hash_table_destroy(sockets);
                sockets = NULL;
            }
            return NULL;
        }

        struct epoll_event ev, ev_read, events[MAX_CONNECTIONS];
        memset(&ev, 0x0, sizeof(struct epoll_event));
        memset(&ev_read, 0x0, sizeof(struct epoll_event));
        memset(events, 0x0, sizeof(struct epoll_event) * MAX_CONNECTIONS);

        ev.events = EPOLLONESHOT | EPOLLOUT | EPOLLRDHUP;
        ev_read.events = EPOLLIN | EPOLLRDHUP;

        //unsigned int sends = 0;

        int sdIN[MAX_CONNECTIONS] = { 0 };
        int sdOUT[MAX_CONNECTIONS] = { 0 };
        int requester[MAX_CONNECTIONS] = { 0 };

        for (int i = 0; i < MAX_CONNECTIONS; i++) {
            requester[i] = nn_socket(AF_SP, NN_REQ);
            if(requester[i] < 0) {
                flockfile(stdout);
                printf("nn_socket() %s (%d)\n", nn_strerror(nn_errno()), nn_errno());
                funlockfile(stdout);
                exit(1);
            }
            int val = 1;
            nn_setsockopt(requester[i], NN_TCP, NN_TCP_NODELAY, &val, sizeof(val));
            int ret = nn_connect(requester[i], "tcp://10.2.142.102:12345");
            //int ret = nn_connect(requester[i], "tcp://127.0.0.1:12345");
            if (ret < 0) {
                flockfile(stdout);
                printf("nn_connect() %s (%d)\n", nn_strerror(nn_errno()), nn_errno());
                funlockfile(stdout);
            }
            size_t sd_size = sizeof(int);
            nn_getsockopt(requester[i], NN_SOL_SOCKET, NN_SNDFD, &sdOUT[i], &sd_size);
            nn_getsockopt(requester[i], NN_SOL_SOCKET, NN_RCVFD, &sdIN[i], &sd_size);
            //printf("fd = %d | %d\n", sdOUT[i], sdIN[i]);

            if (requester[i] >= 0) {
                g_hash_table_insert(sockets, GINT_TO_POINTER(i), GINT_TO_POINTER(0));
                ev.data.fd = sdOUT[i];
                if (epoll_ctl(epfd, EPOLL_CTL_ADD, sdOUT[i], &ev)) {
                    printf("can't epoll_ctl\n");
                    if (sockets) {
                        g_hash_table_destroy(sockets);
                        sockets = NULL;
                    }
                    nn_close(requester[i]);
                    return NULL;
                }
                ev_read.data.fd = sdIN[i];
                if (epoll_ctl(epfd, EPOLL_CTL_ADD, sdIN[i], &ev_read)) {
                    printf("can't epoll_ctl\n");
                    if (sockets) {
                        g_hash_table_destroy(sockets);
                        sockets = NULL;
                    }
                    nn_close(requester[i]);
                    return NULL;
                }
            }
        }

        while (1) {
            int rv = epoll_wait(epfd, events, MAX_CONNECTIONS, 5000);

            if (rv == 0) {
                break;
            } else if (rv < 0) {
                flockfile(stdout);
                printf("#%ld | can't epoll_wait: %s (%d)\n", tid, strerror(errno), errno);
                funlockfile(stdout);
                break;
            }

            int rv_ch = 0;
            for (int epoll_event = 0; epoll_event < MAX_CONNECTIONS ; epoll_event++) {
                if (rv_ch++ == rv) {
                    break;
                }
                if (events[epoll_event].events & EPOLLIN) {
                    int num = -1;
                    for (int i = 0; i < MAX_CONNECTIONS; i++) {
                        if (events[epoll_event].data.fd == sdIN[i]) {
                            num = i;
                            break;
                        }
                    }
                    if (num == -1) {
                        //nn_term();
                        flockfile(stdout);
                        printf("IN | Can`t find socket\n");
                        funlockfile(stdout);
                        exit(1);
                    }

                    char buffer[BUFFER_READ];
                    if (nn_recv(requester[num], buffer, BUFFER_READ, NN_DONTWAIT) < 0) {
                        if (nn_errno() == EAGAIN || nn_errno() == EFSM) {
                            continue;
                        }
                        flockfile(stdout);
                        printf("#%ld | can't recv on socket #%d %s (%d)\n", tid, requester[num], nn_strerror(nn_errno()), nn_errno());
                        funlockfile(stdout);
                        exit(1);
                    } else {
                        int a = GPOINTER_TO_INT(g_hash_table_lookup(sockets, GINT_TO_POINTER(num)));
                        if (a < MESSAGES) {
                            ev.data.fd = sdOUT[num];
                            if (epoll_ctl(epfd, EPOLL_CTL_MOD, sdOUT[num], &ev)) {
                                printf("can't epoll_ctl\n");
                                if (sockets) {
                                    g_hash_table_destroy(sockets);
                                    sockets = NULL;
                                }
                                nn_close(requester[num]);
                                return NULL;
                            }
                        }
                        ++reads_counter;
                        //printf("recv %d\n", events[epoll_event].data.fd);
                    }
                }
                if (events[epoll_event].events & (EPOLLERR | EPOLLHUP | EPOLLRDHUP)) {
                    ++discon_counter;
                    flockfile(stdout);
                    printf("#%ld | Debug: Close conn: %d - 0x%04x\n", tid, events[epoll_event].data.fd, events[epoll_event].events);
                    funlockfile(stdout);

                    if (epoll_ctl(epfd, EPOLL_CTL_DEL, events[epoll_event].data.fd, NULL)) {
                        flockfile(stdout);
                        printf("#%ld | Couldn't epoll_ctl2, fd=%d, error: %s (%d)\n", tid, events[epoll_event].data.fd, strerror(errno), errno);
                        funlockfile(stdout);
                    }
                    //shutdown(events[epoll_event].data.fd, SHUT_RDWR);
                    continue;
                }
                if (events[epoll_event].events & EPOLLOUT) {

                    int num = -1;
                    for (int i = 0; i < MAX_CONNECTIONS; i++) {
                        if (events[epoll_event].data.fd == sdOUT[i]) {
                            num = i;
                            break;
                        }
                    }
                    if (num == -1) {
                        //nn_term();
                        flockfile(stdout);
                        printf("OUT | Can`t find socket\n");
                        funlockfile(stdout);
                        exit(1);
                    }
                    
		    msgpack_sbuffer sbuf;
		    msgpack_sbuffer_init(&sbuf);
		    msgpack_packer pck;
		    msgpack_packer_init(&pck, &sbuf, msgpack_sbuffer_write);

		    msgpack_pack_raw(&pck, 5);
		    msgpack_pack_raw_body(&pck, "Hello", 10);

		    int size = sbuf.size;
		    char *buf = malloc(sbuf.size);
		    memcpy(buf, sbuf.data, sbuf.size);
		    msgpack_sbuffer_destroy(&sbuf);
                    
                    if (nn_send(requester[num], buf, size, NN_DONTWAIT) < 0) {
                        if (nn_errno() == EAGAIN) {
                            continue;
                        }
                        ++discon_counter;
                        flockfile(stdout);
                        printf("#%ld | can't send on socket #%d %s (%d)\n", tid, num, nn_strerror(nn_errno()), nn_errno());
                        funlockfile(stdout);

                        if (epoll_ctl(epfd, EPOLL_CTL_DEL, events[epoll_event].data.fd, NULL)) {
                            flockfile(stdout);
                            printf("#%ld | Couldn't epoll_ctl4, fd=%d, error: %s (%d)\n", tid, events[epoll_event].data.fd, strerror(errno), errno);
                            funlockfile(stdout);
                            exit(1);
                        }

                        nn_close(requester[num]);
			free(buf);

                        break;
                    } else {
                        //printf("send %d\n", events[epoll_event].data.fd);
                        int a = GPOINTER_TO_INT(g_hash_table_lookup(sockets, GINT_TO_POINTER(num)));
                        g_hash_table_insert(sockets, GINT_TO_POINTER(num), GINT_TO_POINTER(++a));

                        update(1);
                        ++sends_counter;
			free(buf);
                    }
                }
            }
            fflush(stdout);
        }

        for (int i = 0; i < MAX_CONNECTIONS; i++) {
            if (GPOINTER_TO_INT(g_hash_table_lookup(sockets, GINT_TO_POINTER(i))) == 0) {
                ++sockets_wo_send_counter;
            }
            nn_close(requester[i]);
        }

        if (sockets) {
            g_hash_table_foreach(sockets, find_min_max, NULL);
            g_hash_table_destroy(sockets);
        }
    }
    return NULL;
}
示例#25
0
static char * packStructure(char *serviceName, char *dest, char *trans_id, char *payload, char *contentType, unsigned int payload_len)
{           
    msgpack_sbuffer sbuf;
    msgpack_packer pk;  
    char* b64buffer =  NULL;
    size_t encodeSize = 0;
    char source[MAX_PARAMETERNAME_LEN/2] = {'\0'}; 
    int msg_type = 4;

    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, LMLite %s ENTER\n", __FUNCTION__ ));

    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, deviceMAC *********:%s\n",deviceMAC));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, serviceName :%s\n",serviceName));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, dest :%s\n",dest));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, transaction_id :%s\n",trans_id));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, contentType :%s\n",contentType));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, payload_len :%d\n",payload_len));

    snprintf(source, sizeof(source), "mac:%s/%s", deviceMAC, serviceName);

    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, Received DeviceMac from Atom side: %s\n",deviceMAC));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, Source derived is %s\n", source));
  
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, <======== Start of packStructure ======>\n"));
    
    // Start of msgpack encoding
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, -----------Start of msgpack encoding------------\n"));

    msgpack_sbuffer_init(&sbuf);
    msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
    msgpack_pack_map(&pk, WEBPA_MAP_SIZE);

    msgpack_pack_str(&pk, strlen(WEBPA_MSG_TYPE));
    msgpack_pack_str_body(&pk, WEBPA_MSG_TYPE,strlen(WEBPA_MSG_TYPE));
    msgpack_pack_int(&pk, msg_type);   
    
    msgpack_pack_str(&pk, strlen(WEBPA_SOURCE));
    msgpack_pack_str_body(&pk, WEBPA_SOURCE,strlen(WEBPA_SOURCE));
    msgpack_pack_str(&pk, strlen(source));
    msgpack_pack_str_body(&pk, source,strlen(source));
    
    msgpack_pack_str(&pk, strlen(WEBPA_DESTINATION));
    msgpack_pack_str_body(&pk, WEBPA_DESTINATION,strlen(WEBPA_DESTINATION));       
    msgpack_pack_str(&pk, strlen(dest));
    msgpack_pack_str_body(&pk, dest,strlen(dest));
    
    msgpack_pack_str(&pk, strlen(WEBPA_TRANSACTION_ID));
    msgpack_pack_str_body(&pk, WEBPA_TRANSACTION_ID,strlen(WEBPA_TRANSACTION_ID));
    msgpack_pack_str(&pk, strlen(trans_id));
    msgpack_pack_str_body(&pk, trans_id,strlen(trans_id));
     
    msgpack_pack_str(&pk, strlen(WEBPA_PAYLOAD));
    msgpack_pack_str_body(&pk, WEBPA_PAYLOAD,strlen(WEBPA_PAYLOAD));
       
    if(strcmp(contentType,"avro/binary") == 0)
    {
        CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, msg->payload binary\n"));
        msgpack_pack_bin(&pk, payload_len);
        msgpack_pack_bin_body(&pk, payload, payload_len);
    }
    else // string: "contentType :application/json"
    {
        CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, msg->payload string\n"));
        msgpack_pack_str(&pk, strlen(payload));
        msgpack_pack_str_body(&pk, payload,strlen(payload));
    }
  
    msgpack_pack_str(&pk, strlen(CONTENT_TYPE));
    msgpack_pack_str_body(&pk, CONTENT_TYPE,strlen(CONTENT_TYPE));
    msgpack_pack_str(&pk, strlen(contentType));
    msgpack_pack_str_body(&pk, contentType,strlen(contentType));
    
    /*if(consoleDebugEnable)
        fprintf(stderr, "RDK_LOG_DEBUG,msgpack encoded data contains %d bytes and data is : %s\n",(int)sbuf.size,sbuf.data);*/

    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,-----------End of msgpack encoding------------\n"));
    // End of msgpack encoding
    
    // Start of Base64 Encode
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,-----------Start of Base64 Encode ------------\n"));
    encodeSize = b64_get_encoded_buffer_size( sbuf.size );
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,encodeSize is %d\n", (int)encodeSize));
    b64buffer = malloc(encodeSize + 1); // one byte extra for terminating NULL byte
    b64_encode((const uint8_t *)sbuf.data, sbuf.size, (uint8_t *)b64buffer);
    b64buffer[encodeSize] = '\0' ;    
 
    
    /*if(consoleDebugEnable)
    {
    int i;
    fprintf(stderr, "RDK_LOG_DEBUG,\n\n b64 encoded data is : ");
    for(i = 0; i < encodeSize; i++)
        fprintf(stderr,"%c", b64buffer[i]);      

    fprintf(stderr,"\n\n");       
    }*/

    //CcspLMLiteTrace(("RDK_LOG_DEBUG,\nb64 encoded data length is %d\n",i));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,---------- End of Base64 Encode -------------\n"));
    // End of Base64 Encode
    
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,Destroying sbuf.....\n"));
    msgpack_sbuffer_destroy(&sbuf);
    
    //CcspLMLiteTrace(("RDK_LOG_DEBUG,Final Encoded data: %s\n",b64buffer));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,Final Encoded data length: %d\n",(int)strlen(b64buffer)));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG,<======== End of packStructure ======>\n"));
    CcspLMLiteConsoleTrace(("RDK_LOG_DEBUG, LMLite %s EXIT\n", __FUNCTION__ ));

    return b64buffer;
}
示例#26
0
/* Init serial input */
int in_serial_init(struct flb_input_instance *in,
                   struct flb_config *config, void *data)
{
    int fd;
    int ret;
    int br;
    struct flb_in_serial_config *ctx;
    (void) data;

    ctx = calloc(1, sizeof(struct flb_in_serial_config));
    if (!ctx) {
        perror("calloc");
        return -1;
    }

    if (!serial_config_read(ctx, in)) {
        return -1;
    }

    /* set context */
    flb_input_set_context(in, ctx);

    /* initialize MessagePack buffers */
    msgpack_sbuffer_init(&ctx->mp_sbuf);
    msgpack_packer_init(&ctx->mp_pck, &ctx->mp_sbuf, msgpack_sbuffer_write);

    /* open device */
    fd = open(ctx->file, O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (fd == -1) {
        perror("open");
        flb_utils_error_c("Could not open serial port device");
    }
    ctx->fd = fd;

    /* Store original settings */
    tcgetattr(fd, &ctx->tio_orig);

    /* Reset for new... */
    memset(&ctx->tio, 0, sizeof(ctx->tio));
    tcgetattr(fd, &ctx->tio);

    br = atoi(ctx->bitrate);
    cfsetospeed(&ctx->tio, (speed_t) flb_serial_speed(br));
    cfsetispeed(&ctx->tio, (speed_t) flb_serial_speed(br));

    /* Settings */
    ctx->tio.c_cflag     &=  ~PARENB;        /* 8N1 */
    ctx->tio.c_cflag     &=  ~CSTOPB;
    ctx->tio.c_cflag     &=  ~CSIZE;
    ctx->tio.c_cflag     |=  CS8;
    ctx->tio.c_cflag     &=  ~CRTSCTS;       /* No flow control */
    ctx->tio.c_cc[VMIN]   =  ctx->min_bytes; /* Min number of bytes to read  */
    ctx->tio.c_cflag     |=  CREAD | CLOCAL; /* Enable READ & ign ctrl lines */

    tcflush(fd, TCIFLUSH);
    tcsetattr(fd, TCSANOW, &ctx->tio);

#if __linux__
    /* Set our collector based on a file descriptor event */
    ret = flb_input_set_collector_event(in,
                                        in_serial_collect,
                                        ctx->fd,
                                        config);
#else
    /* Set our collector based on a timer event */
    ret = flb_input_set_collector_time(in,
                                       in_serial_collect,
                                       IN_SERIAL_COLLECT_SEC,
                                       IN_SERIAL_COLLECT_NSEC,
                                       config);
#endif

    return ret;
}
示例#27
0
文件: msgpack.c 项目: bcg/msgpack
void msgpack_sbuffer_init_wrap(msgpack_sbuffer* sbuf)
{
  msgpack_sbuffer_init(sbuf);
}
void ANetworkController::ReceivedGetBehaviors() {
	msgpack_sbuffer sbuf;
	msgpack_sbuffer_init(&sbuf);

	/* serialize values into the buffer using msgpack_sbuffer_write callback function. */
	msgpack_packer pk;
	msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);

	msgpack_pack_array(&pk, 2);
	msgpack_pack_uint16(&pk, EPacketType::PT_GetBehaviors);

	TArray<ABehaviours*> BehaviorsList;
	for (TActorIterator<ABehaviours> ObjIt(GetWorld()); ObjIt; ++ObjIt) {
		ABehaviours* Behaviors = *ObjIt;
		BehaviorsList.Add(Behaviors);
	}

	int32 BehaviorsListNum = BehaviorsList.Num();
	msgpack_pack_array(&pk, BehaviorsListNum);
	for (int i = 0; i < BehaviorsListNum; i++) {
		ABehaviours* Behaviors = BehaviorsList[i];
		msgpack_pack_map(&pk, 4);
		msgpack_pack_str(&pk, 13);
		msgpack_pack_str_body(&pk, "FlockingState", 13);
		msgpack_pack_uint8(&pk, (uint8)Behaviors->FlockingState);
		msgpack_pack_str(&pk, 13);
		msgpack_pack_str_body(&pk, "ThrottleGains", 13);
		Pack(&pk, Behaviors->ThrottleGains);
		msgpack_pack_str(&pk, 13);
		msgpack_pack_str_body(&pk, "SteeringGains", 13);
		Pack(&pk, Behaviors->SteeringGains);

		int32 BehaviorsNum = Behaviors->Behaviours.Num();
		msgpack_pack_str(&pk, 9);
		msgpack_pack_str_body(&pk, "Behaviors", 9);
		msgpack_pack_array(&pk, BehaviorsNum);
		for (int j = 0; j < BehaviorsNum; j++) {
			UBehaviour* Behavior = Behaviors->Behaviours[j];

			TArray<UProperty*> Properties;
			for (TFieldIterator<UProperty> PropIt(Behavior->GetClass()); PropIt; ++PropIt) {
				UProperty* Property = *PropIt;
				if (Cast<UNumericProperty>(Property) || Cast<UBoolProperty>(Property)) {
					Properties.Add(Property);
				}
			}

			msgpack_pack_map(&pk, Properties.Num() + 1);
			msgpack_pack_str(&pk, 4);
			msgpack_pack_str_body(&pk, "Name", 4);
			FString Name = Behavior->GetClass()->GetName();
			msgpack_pack_str(&pk, Name.Len());
			msgpack_pack_str_body(&pk, TCHAR_TO_UTF8(*Name), Name.Len());
			for (auto PropIt(Properties.CreateIterator()); PropIt; ++PropIt) {
				UProperty* Property = *PropIt;
				const void* Value = Property->ContainerPtrToValuePtr<uint8>(Behavior);
				FString Name = Property->GetName();
				msgpack_pack_str(&pk, Name.Len());
				msgpack_pack_str_body(&pk, TCHAR_TO_UTF8(*Name), Name.Len());
				if (UNumericProperty *NumericProperty = Cast<UNumericProperty>(Property)) {
					if (NumericProperty->IsFloatingPoint()) {
						msgpack_pack_double(&pk, NumericProperty->GetFloatingPointPropertyValue(Value));
					}
					else if (NumericProperty->IsInteger()) {
						msgpack_pack_int(&pk, NumericProperty->GetSignedIntPropertyValue(Value));
					}
				}
				else if (UBoolProperty *BoolProperty = Cast<UBoolProperty>(Property)) {
					if (BoolProperty->GetPropertyValue(Value)) {
						msgpack_pack_true(&pk);
					}
					else {
						msgpack_pack_false(&pk);
					}
				}
			}
		}
	}

	int32 BytesSent;
	TcpSocket->Send((uint8*)sbuf.data, sbuf.size, BytesSent);

	msgpack_sbuffer_destroy(&sbuf);
}
示例#29
0
/* Receive a tokenized JSON message and convert it to MsgPack */
static char *tokens_to_msgpack(char *js,
                               jsmntok_t *tokens, int arr_size, int *out_size)
{
    int i;
    int flen;
    char *p;
    char *buf;
    jsmntok_t *t;
    msgpack_packer pck;
    msgpack_sbuffer sbuf;

    /* initialize buffers */
    msgpack_sbuffer_init(&sbuf);
    msgpack_packer_init(&pck, &sbuf, msgpack_sbuffer_write);

    for (i = 0; i < arr_size ; i++) {
        t = &tokens[i];
        if (t->start == -1 || t->end == -1 || (t->start == 0 && t->end == 0)) {
            break;
        }
        flen = (t->end - t->start);

        switch (t->type) {
        case JSMN_OBJECT:
            msgpack_pack_map(&pck, t->size);
            break;
        case JSMN_ARRAY:
            msgpack_pack_array(&pck, t->size);
            break;
        case JSMN_STRING:
            msgpack_pack_bin(&pck, flen);
            msgpack_pack_bin_body(&pck, js + t->start, flen);
            break;
        case JSMN_PRIMITIVE:
            p = js + t->start;
            if (*p == 'f') {
                msgpack_pack_false(&pck);
            }
            else if (*p == 't') {
                msgpack_pack_true(&pck);
            }
            else if (*p == 'n') {
                msgpack_pack_nil(&pck);
            }
            else {
                if (is_float(p, flen)) {
                    msgpack_pack_double(&pck, atof(p));
                }
                else {
                    msgpack_pack_int64(&pck, atol(p));
                }
            }
            break;
        case JSMN_UNDEFINED:
            msgpack_sbuffer_destroy(&sbuf);
            return NULL;
        }
    }

    /* dump data back to a new buffer */
    *out_size = sbuf.size;
    buf = malloc(sbuf.size);
    memcpy(buf, sbuf.data, sbuf.size);
    msgpack_sbuffer_destroy(&sbuf);

    return buf;
}
示例#30
0
void cb_forward_flush(void *data, size_t bytes,
                      char *tag, int tag_len,
                      struct flb_input_instance *i_ins, void *out_context,
                      struct flb_config *config)
{
    int ret = -1;
    int entries = 0;
    size_t off = 0;
    size_t total;
    size_t bytes_sent;
    msgpack_packer   mp_pck;
    msgpack_sbuffer  mp_sbuf;
    msgpack_unpacked result;
    struct flb_out_forward_config *ctx = out_context;
    struct flb_upstream_conn *u_conn;
    (void) i_ins;
    (void) config;

    flb_debug("[out_forward] request %lu bytes to flush", bytes);

    /* Initialize packager */
    msgpack_sbuffer_init(&mp_sbuf);
    msgpack_packer_init(&mp_pck, &mp_sbuf, msgpack_sbuffer_write);

    /* Count number of entries, is there a better way to do this ? */
    msgpack_unpacked_init(&result);
    while (msgpack_unpack_next(&result, data, bytes, &off)) {
        entries++;
    }
    flb_debug("[out_fw] %i entries tag='%s' tag_len=%i",
              entries, tag, tag_len);
    msgpack_unpacked_destroy(&result);

    /* Output: root array */
    msgpack_pack_array(&mp_pck, 2);
    msgpack_pack_str(&mp_pck, tag_len);
    msgpack_pack_str_body(&mp_pck, tag, tag_len);
    msgpack_pack_array(&mp_pck, entries);

    /* Get a TCP connection instance */
    u_conn = flb_upstream_conn_get(ctx->u);
    if (!u_conn) {
        flb_error("[out_forward] no upstream connections available");
        msgpack_sbuffer_destroy(&mp_sbuf);
        FLB_OUTPUT_RETURN(FLB_RETRY);
    }

    /* Write message header */
    ret = flb_io_net_write(u_conn, mp_sbuf.data, mp_sbuf.size, &bytes_sent);
    if (ret == -1) {
        flb_error("[out_forward] could not write chunk header");
        msgpack_sbuffer_destroy(&mp_sbuf);
        flb_upstream_conn_release(u_conn);
        FLB_OUTPUT_RETURN(FLB_RETRY);
    }

    msgpack_sbuffer_destroy(&mp_sbuf);
    total = ret;

    /* Write body */
    ret = flb_io_net_write(u_conn, data, bytes, &bytes_sent);
    if (ret == -1) {
        flb_error("[out_forward] error writing content body");
        flb_upstream_conn_release(u_conn);
        FLB_OUTPUT_RETURN(FLB_RETRY);
    }

    total += bytes_sent;
    flb_upstream_conn_release(u_conn);
    flb_trace("[out_forward] ended write()=%d bytes", total);

    FLB_OUTPUT_RETURN(FLB_OK);
}