0

I am completely new to Redis. I have a C application running on an Embedded Linux device which should connect to a Redis exposed locally. I am using Hiredis.

I can successfully connect to the Redis using redisConnect().

Now I need to write datapoints to the Redis in an attribute : value JSON format, for example as follows :

{
  "value" : 1000.1,
  "unit"  : "mA",
  "name"  : "Current"
}

I have been looking at example code, but don't see anything showing exactly what I am trying to achieve.

Is it ok to use the redisCommand() for this as follows? :

redisCommand(redisContext,"value %f unit %s name %s", 1000.1, "mA", "Current");
Engineer999
  • 3,683
  • 6
  • 33
  • 71

1 Answers1

0

Here is what have worked for me:

#include <stdio.h>
#include <stdlib.h>

#include <hiredis.h>

int main(void) {
    redisContext *redis_ctx = NULL;
    redisReply *reply = NULL;
    struct timeval redis_timeout = { 1, 500000 }; // 1.5 seconds
    redis_ctx = redisConnectWithTimeout("127.0.0.1", 6379, redis_timeout);
    if (redis_ctx == NULL || redis_ctx->err) {
        if (redis_ctx) {
            printf("Redis Connection error: %s\n", redis_ctx->errstr);
            redisFree(redis_ctx);
        } else {
            printf("Connection error: can't allocate redis context\n");
        }
    }
    if (redis_ctx) {
        reply = redisCommand(redis_ctx, "PUBLISH test_channel {\"attrb1\":%d,\"attrb2\":%d,\"attrb3\":%s}", 1, 2, "11");
        printf("EXTRA EXTRA: %s", reply->str);
        freeReplyObject(reply);
        redisFree(redis_ctx);
    }

    return EXIT_SUCCESS;
}

Note that the JSON part of the string, being passed to redisCommand, does not have any spaces between the fields and values.

luke_16
  • 187
  • 1
  • 1
  • 11