/* Testing correctness of parsed values */
void test_suite_2(JSON_Value *root_value) {
    JSON_Object *root_object;
    JSON_Array *array;
    size_t i;
    TEST(root_value);
    TEST(json_value_get_type(root_value) == JSONObject);
    root_object = json_value_get_object(root_value);
    TEST(STREQ(json_object_get_string(root_object, "string"), "lorem ipsum"));
    TEST(STREQ(json_object_get_string(root_object, "utf string"), "lorem ipsum"));
    TEST(STREQ(json_object_get_string(root_object, "utf-8 string"), "あいうえお"));
    TEST(STREQ(json_object_get_string(root_object, "surrogate string"), "lorem𝄞ipsum𝍧lorem"));
    TEST(json_object_get_number(root_object, "positive one") == 1.0);
    TEST(json_object_get_number(root_object, "negative one") == -1.0);
    TEST(json_object_get_number(root_object, "hard to parse number") == -0.000314);
    TEST(json_object_get_boolean(root_object, "boolean true") == 1);
    TEST(json_object_get_boolean(root_object, "boolean false") == 0);
    TEST(json_value_get_type(json_object_get_value(root_object, "null")) == JSONNull);
    
    array = json_object_get_array(root_object, "string array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    
    array = json_object_get_array(root_object, "x^2 array");
    if (array != NULL) {
        for (i = 0; i < json_array_get_count(array); i++) {
            TEST(json_array_get_number(array, i) == (i * i));
        }
    } else {
        tests_failed++;
    }
    
    TEST(json_object_get_array(root_object, "non existent array") == NULL);
    TEST(STREQ(json_object_dotget_string(root_object, "object.nested string"), "str"));
    TEST(json_object_dotget_boolean(root_object, "object.nested true") == 1);
    TEST(json_object_dotget_boolean(root_object, "object.nested false") == 0);
    TEST(json_object_dotget_value(root_object, "object.nested null") != NULL);
    TEST(json_object_dotget_number(root_object, "object.nested number") == 123);
    
    TEST(json_object_dotget_value(root_object, "should.be.null") == NULL);
    TEST(json_object_dotget_value(root_object, "should.be.null.") == NULL);
    TEST(json_object_dotget_value(root_object, ".") == NULL);
    TEST(json_object_dotget_value(root_object, "") == NULL);
    
    array = json_object_dotget_array(root_object, "object.nested array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    TEST(json_object_dotget_boolean(root_object, "nested true"));
    
    TEST(STREQ(json_object_get_string(root_object, "/**/"), "comment"));
    TEST(STREQ(json_object_get_string(root_object, "//"), "comment"));
}
Example #2
0
/* Testing correctness of parsed values */
void test_suite_2(void) {
    JSON_Value *root_value;
    JSON_Object *object;
    JSON_Array *array;
    int i;
    const char *filename = "tests/test_2.txt";
    printf("Testing %s:\n", filename);
    root_value = json_parse_file(filename);
    TEST(root_value);
    TEST(json_value_get_type(root_value) == JSONObject);
    object = json_value_get_object(root_value);
    TEST(STREQ(json_object_get_string(object, "string"), "lorem ipsum"));
    TEST(STREQ(json_object_get_string(object, "utf string"), "lorem ipsum"));
    TEST(json_object_get_number(object, "positive one") == 1.0);
    TEST(json_object_get_number(object, "negative one") == -1.0);
    TEST(json_object_get_number(object, "hard to parse number") == -0.000314);
    TEST(json_object_get_boolean(object, "boolean true") == 1);
    TEST(json_object_get_boolean(object, "boolean false") == 0);
    TEST(json_value_get_type(json_object_get_value(object, "null")) == JSONNull);
    
    array = json_object_get_array(object, "string array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    
    array = json_object_get_array(object, "x^2 array");
    if (array != NULL) {
        for (i = 0; i < json_array_get_count(array); i++) {
            TEST(json_array_get_number(array, i) == (i * i));
        }
    } else {
        tests_failed++;
    }
    
    TEST(json_object_get_array(object, "non existent array") == NULL);
    TEST(STREQ(json_object_dotget_string(object, "object.nested string"), "str"));
    TEST(json_object_dotget_boolean(object, "object.nested true") == 1);
    TEST(json_object_dotget_boolean(object, "object.nested false") == 0);
    TEST(json_object_dotget_value(object, "object.nested null") != NULL);
    TEST(json_object_dotget_number(object, "object.nested number") == 123);
    
    TEST(json_object_dotget_value(object, "should.be.null") == NULL);
    TEST(json_object_dotget_value(object, "should.be.null.") == NULL);
    TEST(json_object_dotget_value(object, ".") == NULL);
    TEST(json_object_dotget_value(object, "") == NULL);
    
    array = json_object_dotget_array(object, "object.nested array");
    if (array != NULL && json_array_get_count(array) > 1) {
        TEST(STREQ(json_array_get_string(array, 0), "lorem"));
        TEST(STREQ(json_array_get_string(array, 1), "ipsum"));
    } else {
        tests_failed++;
    }
    TEST(json_object_dotget_boolean(object, "nested true"));    
    json_value_free(root_value);
}
Example #3
0
corto_int16 json_deserReference(void* p, corto_type t, JSON_Value* v)
{
    switch(json_value_get_type(v)) {
    case JSONString: {
        const char* reference = json_value_get_string(v);
        corto_object o = corto_resolve(NULL, (corto_string)reference);
        if (!o) {
            corto_error("unresolved reference \"%s\"", reference);
            goto error;
        }

        if (!corto_instanceof(t, o)) {
            corto_error("%s is not an instance of %s", reference, corto_idof(t));
        }

        corto_setref(p, o);
        corto_release(o);
        break;
    }
    case JSONObject: {
        JSON_Object* obj = json_value_get_object(v);

        JSON_Value* type = json_object_get_value(obj, "type");
        if (json_value_get_type(type) != JSONString) {
            corto_seterr("type parameter of anonymous object must be a string");
            goto error;
        }
        corto_type cortoType = corto_resolve(NULL, (char*)json_value_get_string(type));
        if (!cortoType) {
            corto_seterr("type '%s' not found for anonymous object", json_value_get_string(type));
            goto error;
        }

        corto_object cortoObj = *(corto_object*)p;
        if (!cortoObj || (corto_typeof(cortoObj) != cortoType)) {
            cortoObj = corto_create(cortoType);
            corto_setref(p, cortoObj);
            corto_release(cortoObj);
        }
        corto_release(cortoType);

        JSON_Value* value = json_object_get_value(obj, "value");
        if (json_deserType(cortoObj, cortoType, value)) {
            goto error;
        }
        break;
    }
    case JSONNull:
        corto_setref(p, NULL);
        break;
    default:
        corto_seterr("expected string, null or object (reference), got %s", json_valueTypeToString(v));
        break;
    }

    return 0;
error:
    return -1;
}
Example #4
0
char *json(UDF_INIT *initid, UDF_ARGS *args,
      char *result, unsigned long *length,
      char *is_null, char *error)
{
    JSON_Value *jv = json_parse_string(args->args[0]);
    JSON_Value_Type json_type = json_value_get_type(jv);
    if(json_type==JSONError){
        *length=0;
        *is_null=1;
        *error=1;
        json_value_free(jv);
        return NULL;
    }else{
        if(json_type == JSONObject){
            JSON_Object *o = json_value_get_object(jv);
            JSON_Value *value = json_object_dotget_value(o,args->args[1]);
            if(value==NULL){
                *length = 0;
                *is_null = 0;
                return NULL;
            }else{
                *is_null = 0;
                switch(json_value_get_type(value)){
                    case JSONArray:
                        *is_null = 1;
                        break;
                    case JSONError:
                    case JSONObject:
                        *is_null = 1;
                        *error = 1;
                        break;
                    case JSONString:
                        strcpy(initid->ptr,((char*)json_value_get_string(value)));
                        break;
                    case JSONNumber:
                        sprintf(initid->ptr,"%f",json_value_get_number(value));
                        break;
                    case JSONNull:
                        *is_null = 1;
                        break;
                    case JSONBoolean:
                        sprintf(initid->ptr,"%d",json_value_get_boolean(value));
                        break;
                }
                *length = initid->ptr == NULL ? 0 : strlen(initid->ptr); 
            }
        }else{
            *is_null = 1;
        }
        json_value_free(jv);
        return initid->ptr; 
    }
}
Example #5
0
static void web_SockJsServer_message(web_SockJsServer _this, struct mg_connection *conn) {
    web_SockJsServer_Connection c = web_SockJsServer_Connection(conn->connection_param);
    if (_this->onMessage._parent.procedure) {
        if (conn->content_len) {
            char *msg = cx_malloc(conn->content_len + 1);
            memcpy(msg, conn->content, conn->content_len);
            msg[conn->content_len] = '\0';

            /* Parse & unpack message */
            JSON_Value *root = json_parse_string(msg);
            if (!root) {
                goto error;
            }

            if (json_value_get_type(root) == JSONArray) {
                JSON_Array *messages = json_value_get_array(root);
                cx_uint32 i;
                for (i = 0; i < json_array_get_count(messages); i++) {
                    const char *message = json_array_get_string(messages, i);
                    cx_call(_this->onMessage._parent.procedure, NULL, _this->onMessage._parent.instance, c, message);
                }
            }

            json_value_free(root);
        }
    }
error:;
}
int APP_ParseCommand(char * pReadBuffer)
{
    if(pReadBuffer == NULL)
        return COMMAND_BAD_POINTER;
    JSON_Value *rootValue = json_parse_string(pReadBuffer);
    if (json_value_get_type(rootValue) != JSONObject)
            return COMMAND_BAD_JSON;
    JSON_Object * tObject = json_value_get_object(rootValue);
        
    if(json_object_dotget_string(tObject, "message.command") != NULL)
    {
        if(strcmp(json_object_dotget_string(tObject, "message.command"), "hello") == 0)
        {
            return COMMAND_HELLO;
        }
        else if (strcmp(json_object_dotget_string(tObject, "message.command"), "configuration") == 0)
        {
            return COMMAND_CONFIGURE;
        }
        else if (strcmp(json_object_dotget_string(tObject, "message.command"), "debug_set") == 0)
        {
            return COMMAND_DEBUG_SET;
        }
        else
        {
            return COMMAND_INVALID;
        }
    }
    else
    {
        return COMMAND_INVALID;
    }
    return COMMAND_INVALID;
}
Example #7
0
void AppList::add_app_from_file(std::string file_path)
{
    JSON_Value *root = json_parse_file(file_path.c_str());

    if (!root) {
        std::cout << "Couldn't parse returned JSON";
        return;
    }

    if (json_value_get_type(root) != JSONObject) {
        std::cout << "Returned JSON isn't a JSON object";
        json_value_free(root);
        return;
    }

    JSON_Object *node = json_value_get_object(root);

    if (!node) {
        std::cout << "Couldn't get node";
        json_value_free(root);
        return;
    }

    this->add_app(node);

    json_value_free(root);
}
Example #8
0
static EJSBool
json_value_to_ejsval(JSON_Value *v, ejsval *rv)
{
    switch (json_value_get_type (v)) {
    case JSONNull:
        *rv = _ejs_null;
        return EJS_TRUE;

    case JSONString:
        *rv = _ejs_string_new_utf8 (json_value_get_string(v));
        return EJS_TRUE;

    case JSONNumber:
        *rv = NUMBER_TO_EJSVAL(json_value_get_number(v));
        return EJS_TRUE;

    case JSONObject: {
        JSON_Object *obj = json_value_get_object (v);
        *rv = _ejs_object_create (_ejs_null);

        int count = json_object_get_count (obj);
        for (int i = 0; i < count; i ++) {
            const char *propkey = json_object_get_name (obj, i);
            ejsval propval;
            if (!json_value_to_ejsval (json_object_get_value (obj, propkey), &propval))
                return EJS_FALSE;
            _ejs_object_setprop_utf8 (*rv, propkey, propval);
        }

        return EJS_TRUE;
    }
        
    case JSONArray: {
        JSON_Array *arr = json_value_get_array (v);
        int count = json_array_get_count (arr);

        *rv = _ejs_array_new (count, EJS_FALSE);

        for (int i = 0; i < count; i ++) {
            ejsval propkey = _ejs_number_new (i);
            ejsval propval;
            if (!json_value_to_ejsval (json_array_get_value (arr, i), &propval))
                return EJS_FALSE;
            _ejs_object_setprop (*rv, propkey, propval);
        }

        return EJS_TRUE;
    }
    case JSONBoolean:
        *rv = BOOLEAN_TO_EJSVAL(json_value_get_boolean(v));
        return EJS_TRUE;


    case JSONError:
        EJS_NOT_IMPLEMENTED();
        return EJS_FALSE;
    }
}
MODULE_LOADER_RESULT ModuleLoader_ParseBaseConfigurationFromJson(
    MODULE_LOADER_BASE_CONFIGURATION* configuration,
    const JSON_Value* json
)
{
    // The JSON is expected to be an object that has a string
    // property called "binding.path"
    MODULE_LOADER_RESULT result;

    JSON_Value_Type value_type = json_value_get_type(json);
    if (
        configuration == NULL ||
        json == NULL ||
        value_type != JSONObject
       )
    {
        LogError(
            "Invalid input arguments. "
            "configuration = %p, json = %p, json value type = %d",
            configuration,
            json,
            (json != NULL) ? value_type : 0
        );

        /*
        Codes_SRS_MODULE_LOADER_13_049: [ ModuleLoader_ParseBaseConfigurationFromJson shall return MODULE_LOADER_ERROR if configuration is NULL. ]
        Codes_SRS_MODULE_LOADER_13_050 : [ModuleLoader_ParseBaseConfigurationFromJson shall return MODULE_LOADER_ERROR if json is NULL.]
        Codes_SRS_MODULE_LOADER_13_051 : [ModuleLoader_ParseBaseConfigurationFromJson shall return MODULE_LOADER_ERROR if json is not a JSON object.]
        */
        result = MODULE_LOADER_ERROR;
    }
    else
    {
        JSON_Object* config = json_value_get_object(json);
        if (config == NULL)
        {
            LogError("json_value_get_object failed");

            /*Codes_SRS_MODULE_LOADER_13_052: [ ModuleLoader_ParseBaseConfigurationFromJson shall return MODULE_LOADER_ERROR if an underlying platform call fails. ]*/
            result = MODULE_LOADER_ERROR;
        }
        else
        {
            // It is acceptable to have binding.path be NULL.

            /*Codes_SRS_MODULE_LOADER_13_053: [ ModuleLoader_ParseBaseConfigurationFromJson shall read the value of the string attribute binding.path from the JSON object and assign to configuration->binding_path. ]*/
            const char* binding_path = json_object_get_string(config, "binding.path");
            configuration->binding_path = STRING_construct(binding_path);

            /*Codes_SRS_MODULE_LOADER_13_054: [ ModuleLoader_ParseBaseConfigurationFromJson shall return MODULE_LOADER_SUCCESS if the parsing is successful. ]*/
            result = MODULE_LOADER_SUCCESS;
        }
    }

    return result;
}
Example #10
0
File: config.c Project: indutny/bud
bud_error_t bud_config_load_backend(bud_config_t* config,
                                    JSON_Object* obj,
                                    bud_config_backend_t* backend,
                                    bud_hashmap_t* map,
                                    unsigned int* ext_count) {
  bud_error_t err;
  JSON_Value* val;
  const char* external;
  int r;

  bud_config_load_addr(obj, (bud_config_addr_t*) backend);
  backend->config = config;
  backend->xforward = -1;

  val = json_object_get_value(obj, "proxyline");
  if (json_value_get_type(val) == JSONString) {
    const char* pline;

    pline = json_value_get_string(val);
    if (strcmp(pline, "haproxy") == 0)
      backend->proxyline = kBudProxylineHAProxy;
    else if (strcmp(pline, "json") == 0)
      backend->proxyline = kBudProxylineJSON;
    else
      return bud_error_dstr(kBudErrProxyline, pline);
  } else {
    backend->proxyline = val != NULL && json_value_get_boolean(val) ?
        kBudProxylineHAProxy :
        kBudProxylineNone;
  }

  val = json_object_get_value(obj, "x-forward");
  if (val != NULL)
    backend->xforward = json_value_get_boolean(val);

  /* Set defaults here to use them in sni.c */
  bud_config_set_backend_defaults(backend);

  r = bud_config_str_to_addr(backend->host, backend->port, &backend->addr);
  if (r != 0)
    return bud_error_num(kBudErrPton, r);

  external = json_object_get_string(obj, "external");
  if (external == NULL)
    return bud_ok();

  /* Insert backend into a hashmap */
  err = bud_hashmap_insert(map, external, strlen(external), backend);
  if (!bud_is_ok(err))
    return err;

  (*ext_count)++;

  return bud_ok();
}
Example #11
0
static char* json_valueTypeToString(JSON_Value *v)
{
    switch(json_value_get_type(v)) {
    case JSONBoolean: return "boolean";
    case JSONNumber: return "number";
    case JSONString: return "string";
    case JSONObject: return "object";
    case JSONArray: return "array";
    default: return "unknown";
    }
}
Example #12
0
void do_network(JSON_Value* json, char* msg) {
    if(json_value_get_type(json) == JSONObject) {
        JSON_Object* obj = json_value_get_object(json);
        const char* msgtype = json_object_dotget_string(obj, "type");

        if(strcmp(msgtype, msg_type_sensor) == 0 || strcmp(msgtype, msg_type_actor) == 0) {
            const char* command = json_object_dotget_string(obj, "msg.command");
            if(command != 0) execute_command(command);            
        }
    }
}
Example #13
0
void test_suite_precincts(JSON_Value *root_value) {
    JSON_Object *root_object;
    JSON_Array *array;

    TEST(root_value);
    TEST(json_value_get_type(root_value) == JSONObject);
    root_object = json_value_get_object(root_value);

    unsigned int number_of_precincts = (int) json_object_get_number(root_object, "number_of_precincts");
    printf("number_of_precincts: %d\n", number_of_precincts);

    TEST(number_of_precincts == 60);

    array = json_object_get_array(root_object, "precincts");
    if (array != NULL && json_array_get_count(array) == number_of_precincts) {
        JSON_Object *precinct_object;
        JSON_Array *layers_array;
        int id, coord_x, coord_y;
        unsigned int j;
        
        for(j = 0; j < number_of_precincts; j++) {
            
            precinct_object = json_array_get_object(array, j);
            id = (int) json_object_get_number(precinct_object, "id");
            coord_x = (int) json_object_get_number(precinct_object, "coord_x");
            coord_y = (int) json_object_get_number(precinct_object, "coord_y");

            printf("id: %d \t coord_x: %d \t coord_y: %d\n", id, coord_x, coord_y);

            layers_array = json_object_get_array(precinct_object, "layers");
            if (layers_array != NULL && json_array_get_count(layers_array) >= 1) {
                JSON_Object *layer_object;
                int ql, bytes, psnr;
                unsigned k;

                for(k = 0; k < json_array_get_count(layers_array); k++) {

                    layer_object = json_array_get_object(layers_array, k);
                    ql = (int) json_object_get_number(layer_object, "ql");
                    bytes = (int) json_object_get_number(layer_object, "bytes");
                    psnr = (int) json_object_get_number(layer_object, "psnr");

                    printf("\tql: %d \t bytes: %d \t psnr: %d\n", ql, bytes, psnr);
                }
                
            } else {

            }

        }
    } else {
        tests_failed++;
    }
}
static void GenStat(Stat* s, JSON_Value* v) {
    switch (json_value_get_type(v)) {
    case JSONObject:
        {
            JSON_Object* o = json_value_get_object(v);
            size_t count = json_object_get_count(o);

            for (size_t i = 0; i < count; i++) {
                const char* name = json_object_get_name(o, i);
                GenStat(s, json_object_get_value(o, name));
                s->stringLength += strlen(name);
            }
            s->objectCount++;
            s->memberCount += count;
            s->stringCount += count;
        }
        break;

    case JSONArray:
        {
            JSON_Array* a = json_value_get_array(v);
            size_t count = json_array_get_count(a);
            for (int i = 0; i < count; i++)
                GenStat(s, json_array_get_value(a, i));
            s->arrayCount++;
            s->elementCount += count;
        }
        break;

    case JSONString:
        s->stringCount++;
        s->stringLength += strlen(json_value_get_string(v));
        break;

    case JSONNumber:
        s->numberCount++;
        break;

    case JSONBoolean:
        if (json_value_get_boolean(v))
            s->trueCount++;
        else
            s->falseCount++;
        break;

    case JSONNull:
        s->nullCount++;
        break;
    }
}
Example #15
0
static corto_int16 json_deserBoolean(void* o, corto_primitive t, JSON_Value *v)
{
    CORTO_UNUSED(t);

    if (json_value_get_type(v) != JSONBoolean) {
        corto_seterr("expected boolean, got %s", json_valueTypeToString(v));
        goto error;
    }

    *(corto_bool *)o = json_value_get_boolean(v);

    return 0;
error:
    return -1;
}
Example #16
0
static corto_int16 json_deserText(void* p, corto_primitive t, JSON_Value *v)
{
    const char *s = json_value_get_string(v);
    CORTO_UNUSED(t);

    if (json_value_get_type(v) != JSONString) {
        corto_seterr("expected string, got %s", json_valueTypeToString(v));
        goto error;
    }

    corto_setstr(p, (corto_string)s);

    return 0;
error:
    return -1;
}
Example #17
0
bud_error_t bud_config_verify_npn(const JSON_Array* npn) {
  int i;
  int npn_count;

  if (npn == NULL)
    return bud_ok();

  npn_count = json_array_get_count(npn);
  for (i = 0; i < npn_count; i++) {
    if (json_value_get_type(json_array_get_value(npn, i)) == JSONString)
      continue;
    return bud_error(kBudErrNPNNonString);
  }

  return bud_ok();
}
Example #18
0
static mrb_value
json_value_to_mrb_value(mrb_state* mrb, JSON_Value* value) {
  ARENA_SAVE;
  switch (json_value_get_type(value)) {
  case JSONError:
  case JSONNull:
    return mrb_nil_value();
  case JSONString:
    return mrb_str_new_cstr(mrb, json_value_get_string(value));
  case JSONNumber:
    return mrb_float_value(json_value_get_number(value));
  case JSONObject:
    {
      mrb_value hash = mrb_hash_new(mrb);
      JSON_Object* object = json_value_get_object(value);
      size_t count = json_object_get_count(object);
      int n;
      for (n = 0; n < count; n++) {
        const char* name = json_object_get_name(object, n);
        mrb_hash_set(mrb, hash, mrb_str_new_cstr(mrb, name),
          json_value_to_mrb_value(mrb, json_object_get_value(object, name)));
      }
      return hash;
    }
  case JSONArray:
    {
      mrb_value ary;
      ary = mrb_ary_new(mrb);
      JSON_Array* array = json_value_get_array(value);
      size_t count = json_array_get_count(array);
      int n;
      for (n = 0; n < count; n++) {
        JSON_Value* elem = json_array_get_value(array, n);
        mrb_ary_push(mrb, ary, json_value_to_mrb_value(mrb, elem));
      }
      return ary;
    }
  case JSONBoolean:
    if (json_value_get_boolean(value)) {
      return mrb_true_value();
    }
    return mrb_false_value();
  default:
    mrb_raise(mrb, E_ARGUMENT_ERROR, "invalid argument");
  }
  return mrb_nil_value();
}
Example #19
0
void Config::parse_config_file(const std::string& config_file_path)
{
    JSON_Value *root = json_parse_file(config_file_path.c_str());

    if (!root) {
        std::cout << "Couldn't parse returned JSON\n";
        return;
    }

    if (json_value_get_type(root) != JSONObject) {
        std::cout << "Returned JSON isn't a JSON object\n";
        json_value_free(root);
        return;
    }

    JSON_Object *node = json_value_get_object(root);

    if (!node) {
        std::cout << "Couldn't get node\n";
        json_value_free(root);
        return;
    }

    std::string val;
    bool rel_path;
    const std::string rel_path_pattern = "./";

    for (auto it = this->config.begin(); it != this->config.end(); ++it) {
        val = get_json_val<std::string>(node, it->first);

        if (val.empty())
            continue;

        rel_path = val.find("./") == 0;

        if (rel_path) {
            val = config_file_path.substr(
                    0,
                    config_file_path.length() - this->conf_filename.length()
                ) + val.substr(rel_path_pattern.length());
        }

        it->second = val;
    }

    json_value_free(root);
}
Example #20
0
void do_network(JSON_Value* json, char* msg) {
    if(json_value_get_type(json) == JSONObject) {
        JSON_Object* obj = json_value_get_object(json);
        
        if(strcmp(json_object_dotget_string(obj, "type"), "act.heating.central") == 0) {
            if(json_object_dotget_value(obj, "msg.level") != 0) {
                int heatingLevel = 9 - (int)json_object_dotget_number(obj, "msg.level");
                printf("ACTING on cmd: %d\n", heatingLevel);

                if(heatingLevel > 9) heatingLevel = 9;
                if(heatingLevel < 0) heatingLevel = 0;
                printf("Set level %d\n", heatingLevel);
                serial_write("%d", heatingLevel);
            }
        }
    }
}
Example #21
0
bud_error_t bud_config_verify_all_strings(const JSON_Array* arr,
                                          const char* name) {
  int i;
  int count;

  if (arr == NULL)
    return bud_ok();

  count = json_array_get_count(arr);
  for (i = 0; i < count; i++) {
    if (json_value_get_type(json_array_get_value(arr, i)) == JSONString)
      continue;
    return bud_error_dstr(kBudErrNonString, name);
  }

  return bud_ok();
}
Example #22
0
static corto_int16 json_deserConstant(void* p, corto_primitive t, JSON_Value *v)
{
    const char *s = json_value_get_string(v);
    CORTO_UNUSED(t);

    if (json_value_get_type(v) != JSONString) {
        corto_seterr("expected string, got %s", json_valueTypeToString(v));
        goto error;
    }

    if (corto_convert(corto_string_o, (corto_string*)&s, t, p)) {
        goto error;
    }

    return 0;
error:
    return -1;
}
Example #23
0
static corto_int16 json_deserNumber(void* o, corto_primitive t, JSON_Value *v)
{

    if (json_value_get_type(v) != JSONNumber) {
        corto_seterr("expected number, got %s", json_valueTypeToString(v));
        goto error;
    }

    corto_float64 number = json_value_get_number(v);
    corto_convert(
        corto_primitive(corto_float64_o),
        &number,
        t,
        o);

    return 0;
error:
    return -1;
}
Example #24
0
gboolean jobdesc_is_valid (gchar *job)
{
        JSON_Value *val;
        JSON_Object *obj;
        GRegex *regex;
        GMatchInfo *match_info;
        gchar *name;

        val = json_parse_string_with_comments(job);
        if (val == NULL) {
                GST_ERROR ("parse job error.");
                return FALSE;

        } else if (json_value_get_type (val) != JSONObject){
                GST_ERROR ("job is not a json object.");
                json_value_free (val);
                return FALSE;
        }
        obj = json_value_get_object (val);

        name = (gchar *)json_object_get_string (obj, "name");
        if ((name == NULL) || (strlen (name) < 4)) {
                GST_ERROR ("invalid job with name property invalid");
                json_value_free (val);
                return FALSE;
        }

        regex = g_regex_new ("[`~!@#$%^&*()+=|\\{[\\]}:;\"\'<,>.?/]", G_REGEX_OPTIMIZE, 0, NULL);
        g_regex_match (regex, name, 0, &match_info);
        g_regex_unref (regex);
        if (g_match_info_matches (match_info)) {
                GST_ERROR ("invalid job name: %s", name);
                g_match_info_free (match_info);
                json_value_free (val);
                return FALSE;
        }
        json_value_free (val);

        return TRUE;
}
Example #25
0
File: tests.c Project: Kutoc/parson
void print_commits_info(const char *username, const char *repo) {
    JSON_Value *root_value;
    JSON_Array *commits;
    JSON_Object *commit;
    size_t i;
    
    char curl_command[512];
    char cleanup_command[256];
    char output_filename[] = "commits.json";
    
    /* it ain't pretty, but it's not a libcurl tutorial */
    sprintf(curl_command, 
        "curl -s \"https://api.github.com/repos/%s/%s/commits\" > %s",
        username, repo, output_filename);
    sprintf(cleanup_command, "rm -f %s", output_filename);
    system(curl_command);
    
    /* parsing json and validating output */
    root_value = json_parse_file(output_filename);
    if (json_value_get_type(root_value) != JSONArray) {
        system(cleanup_command);
        return;
    }
    
    /* getting array from root value and printing commit info */
    commits = json_value_get_array(root_value);
    printf("%-10.10s %-10.10s %s\n", "Date", "SHA", "Author");
    for (i = 0; i < json_array_get_count(commits); i++) {
        commit = json_array_get_object(commits, i);
        printf("%.10s %.10s %s\n",
               json_object_dotget_string(commit, "commit.author.date"),
               json_object_get_string(commit, "sha"),
               json_object_dotget_string(commit, "commit.author.name"));
    }
    
    /* cleanup code */
    json_value_free(root_value);
    system(cleanup_command);
}
int parse_SX1301_configuration(const char * conf_file) {
	int i;
	const char conf_obj[] = "SX1301_conf";
	char param_name[32]; /* used to generate variable parameter names */
	const char *str; /* used to store string value from JSON object */
	struct lgw_conf_board_s boardconf;
	struct lgw_conf_rxrf_s rfconf;
	struct lgw_conf_rxif_s ifconf;
	JSON_Value *root_val;
	JSON_Object *root = NULL;
	JSON_Object *conf = NULL;
	JSON_Value *val;
	uint32_t sf, bw;
	
	/* try to parse JSON */
	root_val = json_parse_file_with_comments(conf_file);
	root = json_value_get_object(root_val);
	if (root == NULL) {
		MSG("ERROR: %s id not a valid JSON file\n", conf_file);
		exit(EXIT_FAILURE);
	}
	conf = json_object_get_object(root, conf_obj);
	if (conf == NULL) {
		MSG("INFO: %s does not contain a JSON object named %s\n", conf_file, conf_obj);
		return -1;
	} else {
		MSG("INFO: %s does contain a JSON object named %s, parsing SX1301 parameters\n", conf_file, conf_obj);
	}

	/* set board configuration */
	memset(&boardconf, 0, sizeof boardconf); /* initialize configuration structure */
	val = json_object_get_value(conf, "lorawan_public"); /* fetch value (if possible) */
	if (json_value_get_type(val) == JSONBoolean) {
		boardconf.lorawan_public = (bool)json_value_get_boolean(val);
	} else {
		MSG("WARNING: Data type for lorawan_public seems wrong, please check\n");
		boardconf.lorawan_public = false;
	}
	val = json_object_get_value(conf, "clksrc"); /* fetch value (if possible) */
	if (json_value_get_type(val) == JSONNumber) {
		boardconf.clksrc = (uint8_t)json_value_get_number(val);
	} else {
		MSG("WARNING: Data type for clksrc seems wrong, please check\n");
		boardconf.clksrc = 0;
	}
	MSG("INFO: lorawan_public %d, clksrc %d\n", boardconf.lorawan_public, boardconf.clksrc);
	/* all parameters parsed, submitting configuration to the HAL */
        if (lgw_board_setconf(boardconf) != LGW_HAL_SUCCESS) {
                MSG("WARNING: Failed to configure board\n");
	}

	/* set configuration for RF chains */
	for (i = 0; i < LGW_RF_CHAIN_NB; ++i) {
		memset(&rfconf, 0, sizeof(rfconf)); /* initialize configuration structure */
		sprintf(param_name, "radio_%i", i); /* compose parameter path inside JSON structure */
		val = json_object_get_value(conf, param_name); /* fetch value (if possible) */
		if (json_value_get_type(val) != JSONObject) {
			MSG("INFO: no configuration for radio %i\n", i);
			continue;
		}
		/* there is an object to configure that radio, let's parse it */
		sprintf(param_name, "radio_%i.enable", i);
		val = json_object_dotget_value(conf, param_name);
		if (json_value_get_type(val) == JSONBoolean) {
			rfconf.enable = (bool)json_value_get_boolean(val);
		} else {
			rfconf.enable = false;
		}
		if (rfconf.enable == false) { /* radio disabled, nothing else to parse */
			MSG("INFO: radio %i disabled\n", i);
		} else  { /* radio enabled, will parse the other parameters */
			snprintf(param_name, sizeof param_name, "radio_%i.freq", i);
			rfconf.freq_hz = (uint32_t)json_object_dotget_number(conf, param_name);
			snprintf(param_name, sizeof param_name, "radio_%i.rssi_offset", i);
			rfconf.rssi_offset = (float)json_object_dotget_number(conf, param_name);
			snprintf(param_name, sizeof param_name, "radio_%i.type", i);
			str = json_object_dotget_string(conf, param_name);
			if (!strncmp(str, "SX1255", 6)) {
				rfconf.type = LGW_RADIO_TYPE_SX1255;
			} else if (!strncmp(str, "SX1257", 6)) {
				rfconf.type = LGW_RADIO_TYPE_SX1257;
			} else {
				MSG("WARNING: invalid radio type: %s (should be SX1255 or SX1257)\n", str);
			}
			snprintf(param_name, sizeof param_name, "radio_%i.tx_enable", i);
			val = json_object_dotget_value(conf, param_name);
			if (json_value_get_type(val) == JSONBoolean) {
				rfconf.tx_enable = (bool)json_value_get_boolean(val);
			} else {
				rfconf.tx_enable = false;
			}
			MSG("INFO: radio %i enabled (type %s), center frequency %u, RSSI offset %f, tx enabled %d\n", i, str, rfconf.freq_hz, rfconf.rssi_offset, rfconf.tx_enable);
		}
		/* all parameters parsed, submitting configuration to the HAL */
		if (lgw_rxrf_setconf(i, rfconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for radio %i\n", i);
		}
	}
	
	/* set configuration for LoRa multi-SF channels (bandwidth cannot be set) */
	for (i = 0; i < LGW_MULTI_NB; ++i) {
		memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
		sprintf(param_name, "chan_multiSF_%i", i); /* compose parameter path inside JSON structure */
		val = json_object_get_value(conf, param_name); /* fetch value (if possible) */
		if (json_value_get_type(val) != JSONObject) {
			MSG("INFO: no configuration for LoRa multi-SF channel %i\n", i);
			continue;
		}
		/* there is an object to configure that LoRa multi-SF channel, let's parse it */
		sprintf(param_name, "chan_multiSF_%i.enable", i);
		val = json_object_dotget_value(conf, param_name);
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) { /* LoRa multi-SF channel disabled, nothing else to parse */
			MSG("INFO: LoRa multi-SF channel %i disabled\n", i);
		} else  { /* LoRa multi-SF channel enabled, will parse the other parameters */
			sprintf(param_name, "chan_multiSF_%i.radio", i);
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, param_name);
			sprintf(param_name, "chan_multiSF_%i.if", i);
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, param_name);
			// TODO: handle individual SF enabling and disabling (spread_factor)
			MSG("INFO: LoRa multi-SF channel %i enabled, radio %i selected, IF %i Hz, 125 kHz bandwidth, SF 7 to 12\n", i, ifconf.rf_chain, ifconf.freq_hz);
		}
		/* all parameters parsed, submitting configuration to the HAL */
		if (lgw_rxif_setconf(i, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for LoRa multi-SF channel %i\n", i);
		}
	}
	
	/* set configuration for LoRa standard channel */
	memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
	val = json_object_get_value(conf, "chan_Lora_std"); /* fetch value (if possible) */
	if (json_value_get_type(val) != JSONObject) {
		MSG("INFO: no configuration for LoRa standard channel\n");
	} else {
		val = json_object_dotget_value(conf, "chan_Lora_std.enable");
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) {
			MSG("INFO: LoRa standard channel %i disabled\n", i);
		} else  {
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.radio");
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, "chan_Lora_std.if");
			bw = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.bandwidth");
			switch(bw) {
				case 500000: ifconf.bandwidth = BW_500KHZ; break;
				case 250000: ifconf.bandwidth = BW_250KHZ; break;
				case 125000: ifconf.bandwidth = BW_125KHZ; break;
				default: ifconf.bandwidth = BW_UNDEFINED;
			}
			sf = (uint32_t)json_object_dotget_number(conf, "chan_Lora_std.spread_factor");
			switch(sf) {
				case  7: ifconf.datarate = DR_LORA_SF7;  break;
				case  8: ifconf.datarate = DR_LORA_SF8;  break;
				case  9: ifconf.datarate = DR_LORA_SF9;  break;
				case 10: ifconf.datarate = DR_LORA_SF10; break;
				case 11: ifconf.datarate = DR_LORA_SF11; break;
				case 12: ifconf.datarate = DR_LORA_SF12; break;
				default: ifconf.datarate = DR_UNDEFINED;
			}
			MSG("INFO: LoRa standard channel enabled, radio %i selected, IF %i Hz, %u Hz bandwidth, SF %u\n", ifconf.rf_chain, ifconf.freq_hz, bw, sf);
		}
		if (lgw_rxif_setconf(8, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for LoRa standard channel\n");
		}
	}
	
	/* set configuration for FSK channel */
	memset(&ifconf, 0, sizeof(ifconf)); /* initialize configuration structure */
	val = json_object_get_value(conf, "chan_FSK"); /* fetch value (if possible) */
	if (json_value_get_type(val) != JSONObject) {
		MSG("INFO: no configuration for FSK channel\n");
	} else {
		val = json_object_dotget_value(conf, "chan_FSK.enable");
		if (json_value_get_type(val) == JSONBoolean) {
			ifconf.enable = (bool)json_value_get_boolean(val);
		} else {
			ifconf.enable = false;
		}
		if (ifconf.enable == false) {
			MSG("INFO: FSK channel %i disabled\n", i);
		} else  {
			ifconf.rf_chain = (uint32_t)json_object_dotget_number(conf, "chan_FSK.radio");
			ifconf.freq_hz = (int32_t)json_object_dotget_number(conf, "chan_FSK.if");
			bw = (uint32_t)json_object_dotget_number(conf, "chan_FSK.bandwidth");
			if      (bw <= 7800)   ifconf.bandwidth = BW_7K8HZ;
			else if (bw <= 15600)  ifconf.bandwidth = BW_15K6HZ;
			else if (bw <= 31200)  ifconf.bandwidth = BW_31K2HZ;
			else if (bw <= 62500)  ifconf.bandwidth = BW_62K5HZ;
			else if (bw <= 125000) ifconf.bandwidth = BW_125KHZ;
			else if (bw <= 250000) ifconf.bandwidth = BW_250KHZ;
			else if (bw <= 500000) ifconf.bandwidth = BW_500KHZ;
			else ifconf.bandwidth = BW_UNDEFINED;
			ifconf.datarate = (uint32_t)json_object_dotget_number(conf, "chan_FSK.datarate");
			MSG("INFO: FSK channel enabled, radio %i selected, IF %i Hz, %u Hz bandwidth, %u bps datarate\n", ifconf.rf_chain, ifconf.freq_hz, bw, ifconf.datarate);
		}
		if (lgw_rxif_setconf(9, ifconf) != LGW_HAL_SUCCESS) {
			MSG("WARNING: invalid configuration for FSK channel\n");
		}
	}
	json_value_free(root_val);
	return 0;
}
void APP2_Tasks ( void )
{
/* Update the application state machine based
     * on the current state */

    switch(app2Data.state)
    {
        case APP2_STATE_INIT:

            /* Open the device layer */
            app2Data.deviceHandle = USB_DEVICE_Open( USB_DEVICE_INDEX_0, DRV_IO_INTENT_READWRITE );

            if(app2Data.deviceHandle != USB_DEVICE_HANDLE_INVALID)
            {
                /* Register a callback with device layer to get event notification (for end point 0) */
                USB_DEVICE_EventHandlerSet(app2Data.deviceHandle, APP_USBDeviceEventHandler, 0);

                app2Data.state = APP2_STATE_WAIT_FOR_CONFIGURATION;
            }
            else
            {
                /* The Device Layer is not ready to be opened. We should try
                 * again later. */
            }

            break;

        case APP2_STATE_WAIT_FOR_CONFIGURATION:

            /* Check if the device was configured */
            if(app2Data.isConfigured)
            {
                app2Data.state = APP2_STATE_SCHEDULE_READ;
            }
            break;
            
        case APP2_STATE_SCHEDULE_READ:
            if(APP_StateReset())
            {
                break;
            }
            
            /* If a read is complete, then schedule a read
            * else wait for the current read to complete */
            
            app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
            if(app2Data.isReadComplete == true)
            {
                app2Data.isReadComplete = false;
                app2Data.readTransferHandle =  USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
                
                USB_DEVICE_CDC_Read (USB_DEVICE_CDC_INDEX_0,
                        &app2Data.readTransferHandle, app2Data.readBuffer,
                        APP_READ_BUFFER_SIZE);
                
                if(app2Data.readTransferHandle == USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID)
                {
                    app2Data.state = APP2_STATE_ERROR;
                    break;
                }
            }
            break;

        case APP2_STATE_WAIT_FOR_READ_COMPLETE:
            
            if(APP_StateReset())
            {
                break;
            }
            
            if(app2Data.isReadComplete == true)
            {            
                // Check for delimiter
                int res = APP_CheckForMessage(app2Data.readBuffer);
                if(res == MESSAGE_BAD_POINTER)
                {
                    // Do something
                    break;
                }
                else if(res == MESSAGE_NO_DELIMITER)
                {
                    strcat(messageBuffer, app2Data.readBuffer);
                    memset(app2Data.readBuffer, '\0', APP_READ_BUFFER_SIZE);
                    app2Data.state = APP2_STATE_SCHEDULE_READ;
                    break;
                }
 
                strcat(messageBuffer, app2Data.readBuffer);
                // Parse for the command being sent so we can handle it
                int command = APP_ParseCommand(messageBuffer);

                // Lets build our response message
                // First initialize the JSON value and object from parson library
                JSON_Value *rootValue = json_value_init_object();
                JSON_Object *rootObject = json_value_get_object(rootValue);
                char *serializedString = NULL;  
                    
                // Build response and handle the command
                switch(command)
                {
                    // If hello command, respond with discovery packet 
                    case COMMAND_HELLO:
                            json_object_dotset_string(rootObject, "message.command", "discovery");
                            json_object_dotset_string(rootObject, "message.discovery_object.title", APP_TITLE);
                            json_object_dotset_string(rootObject, "message.discovery_object.part_number", APP_PART_NUMBER);
                            json_object_dotset_string(rootObject, "message.discovery_object.mac_address", appData.macAddress);
                            json_object_dotset_string(rootObject, "message.discovery_object.firmware_version", APP_FIRMWARE_VERSION);
                            json_object_dotset_string(rootObject, "message.discovery_object.harmony_version", SYS_VERSION_STR);
                            json_object_dotset_boolean(rootObject, "message.discovery_object.is_commissioned", appData.isCommissioned);
                        break;
                        
                    // If configuration command, respond with ACK/NACK 
                    case COMMAND_CONFIGURE:
                    {
                        if(appData.isCommissioned == false)
                        {
                            JSON_Value *messageRoot = json_parse_string(messageBuffer);
                            if(json_value_get_type(messageRoot) != JSONObject)
                            {
                                BuildAckNackMessage(rootObject, "nack", "Invalid JSON Object");
                                break;
                            }
                            else
                            {
                                JSON_Object *messageObject = json_value_get_object(messageRoot);
                                if( json_object_dotget_string(messageObject, "message.configuration_object.aws_iot_endpoint_address") != NULL &&
                                    json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate") != NULL &&
                                    json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate_private_key") != NULL )
                                {
                                    json_object_dotset_string(rootObject, "message.command", "ack");
                                    json_object_dotset_string(rootObject, "message.ack_nack_message", "Writing commission parameters to flash");
                                    sprintf((char *)appData.host, json_object_dotget_string(messageObject, "message.configuration_object.aws_iot_endpoint_address"));
                                    sprintf((char *)appData.clientCert, json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate"));
                                    sprintf((char *)appData.clientKey, json_object_dotget_string(messageObject, "message.configuration_object.aws_certificate_private_key"));
                                    appData.isCommissioned = true;
                                    appData.writeToNVM = true;
                                }
                                else
                                {
                                    BuildAckNackMessage(rootObject, "nack", "Invalid commission parameters");
                                    break;
                                }
                            } 
                        }
                        else
                        {
                            BuildAckNackMessage(rootObject, "nack", "Already commissioned");
                        }                    
                        break;
                    }
                    
                    case COMMAND_DEBUG_SET:
                    {
                        JSON_Value *messageRoot = json_parse_string(messageBuffer);
                        if(json_value_get_type(messageRoot) != JSONObject)
                        {
                            BuildAckNackMessage(rootObject, "nack", "Invalid JSON Object");
                            break;
                        }
                        JSON_Object *messageObject = json_value_get_object(messageRoot);
                        if(messageObject == NULL)
                        {
                            BuildAckNackMessage(rootObject, "nack", "NULL Pointer");
                            break;
                        }
                        BuildAckNackMessage(rootObject, "ack", "Received debug set");
                        int DebugMessage = DEBUG_UPDATE;
                        xQueueSendToFront(app2Data.debugQueue, &DebugMessage, 1);
                        if(json_object_dotget_boolean(messageObject, "message.debug_set_object.set"))
                            appData.debugSet = true;
                        else
                            appData.debugSet = false;
                        break;
                    }
                    
                    case COMMAND_BAD_JSON:
                            BuildAckNackMessage(rootObject, "nack", "Bad JSON");
                        break;
                    
                    case COMMAND_INVALID:
                            BuildAckNackMessage(rootObject, "nack", "Command Invalid");
                        break;
                        
                    default:
                            BuildAckNackMessage(rootObject, "nack", "Something went wrong");
                        break;
                }
                memset(app2Data.writeBuffer, '\0', APP_WRITE_BUFFER_SIZE);
                // With our response built, serialize the response into a string
                serializedString = json_serialize_to_string(rootValue);
                strcpy(app2Data.writeBuffer, serializedString);
                // Find length of string and add delimiter to end
                app2Data.writeBuffer[strlen(app2Data.writeBuffer)] = '\r';
                
                json_free_serialized_string(serializedString);  
                // Reset string buffers
                memset(app2Data.readBuffer, '\0', APP_READ_BUFFER_SIZE);
                memset(messageBuffer, '\0', APP_MESSAGE_BUFFER_SIZE);
                app2Data.state = APP2_STATE_SCHEDULE_WRITE;
            }
            else
            {
                app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
                if( uxQueueMessagesWaiting( app2Data.debugQueue ) > 0 )
                {
                    int debugMessageNumber;
                    xQueueReceive( app2Data.debugQueue, &debugMessageNumber, 1 );
                    sprintf(app2Data.writeBuffer,                       
                    "{"                                                  
                         "\"message\":{"                                 
                            "\"command\":\"debug\","
                                "\"debug_object\":{"
                                    "\"board_ip_address\":\"%d.%d.%d.%d\","
                                    "\"aws_iot_endpoint\":\"%s\","
                                    "\"mac_address\":\"%s\","
                                    "\"socket_connected\":%s,"
                                    "\"mqtt_connected\":%s,"
                                    "\"raw_message\":\"%s\""
                    "}}}\r",
                    appData.board_ipAddr.v4Add.v[0],
                    appData.board_ipAddr.v4Add.v[1],
                    appData.board_ipAddr.v4Add.v[2],
                    appData.board_ipAddr.v4Add.v[3],
                    appData.host,
                    appData.macAddress,
                    (appData.socket_connected ? "true" : "false"),
                    (appData.mqtt_connected ? "true" : "false"),
                    APP_ReturnDebugCodeToString(debugMessageNumber));
                    app2Data.state = APP2_STATE_SCHEDULE_DEBUG_WRITE;
                }
            }
            break;
            
                        
        case APP2_STATE_SCHEDULE_WRITE:

            if(APP_StateReset())
            {
                break;
            }

            app2Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app2Data.isWriteComplete = false;
            app2Data.state = APP2_STATE_WAIT_FOR_WRITE_COMPLETE;

            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                &app2Data.writeTransferHandle, app2Data.writeBuffer, strlen(app2Data.writeBuffer),
                USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);

            break;
            
        case APP2_STATE_WAIT_FOR_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if message sent.  The isWriteComplete
             * flag gets updated in the CDC event handler */

            if(app2Data.isWriteComplete == true)
            {
                app2Data.state = APP2_STATE_SCHEDULE_READ;
            }
            break;
            
        case APP2_STATE_SCHEDULE_DEBUG_WRITE:
            if(APP_StateReset())
            {
                break;
            }

            app2Data.writeTransferHandle = USB_DEVICE_CDC_TRANSFER_HANDLE_INVALID;
            app2Data.isWriteComplete = false;
            app2Data.state = APP2_STATE_WAIT_FOR_DEBUG_WRITE_COMPLETE;

            USB_DEVICE_CDC_Write(USB_DEVICE_CDC_INDEX_0,
                &app2Data.writeTransferHandle, app2Data.writeBuffer, strlen(app2Data.writeBuffer),
                USB_DEVICE_CDC_TRANSFER_FLAGS_DATA_COMPLETE);

            break;
            
        case APP2_STATE_WAIT_FOR_DEBUG_WRITE_COMPLETE:

            if(APP_StateReset())
            {
                break;
            }

            /* Check if message sent.  The isWriteComplete
             * flag gets updated in the CDC event handler */

            if(app2Data.isWriteComplete == true)
            {
                app2Data.state = APP2_STATE_WAIT_FOR_READ_COMPLETE;
            }
            break;

        case APP2_STATE_ERROR:
            break;
        default:
            break;
    }
}
Example #28
0
bud_error_t bud_sni_from_json(bud_config_t* config,
                              struct json_value_t* json,
                              bud_context_t* ctx) {
  JSON_Object* obj;
  JSON_Value* val;
  const char* cert_str;
  const char* key_str;
  const char* pass_str;
  JSON_Array* cert_strs;
  JSON_Array* key_strs;
  JSON_Array* pass_strs;
  bud_error_t err;

  cert_str = NULL;
  key_str = NULL;
  pass_str = NULL;
  cert_strs = NULL;
  key_strs = NULL;
  pass_strs = NULL;

  obj = json_value_get_object(json);
  val = json_object_get_value(obj, "cert");
  if (json_value_get_type(val) == JSONString)
    cert_str = json_value_get_string(val);
  else
    cert_strs = json_value_get_array(val);
  val = json_object_get_value(obj, "key");
  if (json_value_get_type(val) == JSONString)
    key_str = json_value_get_string(val);
  else
    key_strs = json_value_get_array(val);
  val = json_object_get_value(obj, "passphrase");
  if (json_value_get_type(val) == JSONString)
    pass_str = json_value_get_string(val);
  else
    pass_strs = json_value_get_array(val);

  if (obj == NULL ||
      !((cert_str != NULL && key_str != NULL) ||
        (cert_strs != NULL && key_strs != NULL))) {
    err = bud_error_str(kBudErrJSONParse, "<SNI Response>");
    goto fatal;
  }

  /* Load NPN from response */
  memset(ctx, 0, sizeof(*ctx));
  ctx->cert_file = cert_str;
  ctx->key_file = key_str;
  ctx->key_pass = pass_str;
  ctx->cert_files = cert_strs;
  ctx->key_files = key_strs;
  ctx->key_passes = pass_strs;
  ctx->ciphers = json_object_get_string(obj, "ciphers");
  ctx->ecdh = json_object_get_string(obj, "ecdh");
  ctx->ticket_key = json_object_get_string(obj, "ticket_key");
  ctx->npn = json_object_get_array(obj, "npn");
  ctx->ca_array = json_object_get_array(obj, "ca");
  val = json_object_get_value(obj, "request_cert");
  if (val != NULL)
    ctx->request_cert = json_value_get_boolean(val);
  err = bud_config_load_backend_list(config, obj, &ctx->backend);
  if (!bud_is_ok(err))
    goto fatal;

  err = bud_context_init(config, ctx);

  /* Make sure that deallocated values won't be used */
  ctx->cert_file = NULL;
  ctx->key_file = NULL;
  ctx->key_pass = NULL;
  ctx->cert_files = NULL;
  ctx->key_files = NULL;
  ctx->key_passes = NULL;
  if (!bud_is_ok(err))
    goto fatal;

  return bud_ok();

fatal:
  if (!bud_is_ok(err)) {
    SSL_CTX_free(ctx->ctx);
    ctx->ctx = NULL;
  }
  free(ctx->backend.list);
  ctx->backend.list = NULL;
  return err;
}
Example #29
0
int main(int argc, char** argv) {
    printf("haltestelle built <%s %s> version %s\n", __DATE__, __TIME__, VERSION);
    if(argc < 5) {
        fprintf(stderr, "usage: %s <designation> <busfarhn_host> <busfarhn_port> <serialport>\n", argv[0]);
        exit(-1);
    }

    /*global*/ designation   = argv[1];
    /*global*/ busfarhn_host = argv[2];
    /*global*/ busfarhn_port = atoi(argv[3]);
    char*      serialport    = argv[4];

    /*global*/ sockfd = start_socket();
    if(connect_to_busfarhn(designation) != 0) {
        fprintf(stderr, "[ERROR] connecting to %s:%d failed\n", busfarhn_host, busfarhn_port);
        return -1;
    }
#ifdef USE_SERIAL
    #ifdef SERIAL_IS_A_FILE
    printf("%s is a FILE\n", serialport);
    #elif defined SERIAL_IS_A_ATH0
    printf("%s is a SERIAL PORT (ATH style)\n", serialport);
    #else
    printf("%s is a SERIAL PORT\n", serialport);
    #endif
#else
    printf("WARNING: NOT USING THE SERIAL PORT\n");
#endif
    printf("[STARTUP] connected to %s:%i with designation %s\n", busfarhn_host, busfarhn_port, designation);

#ifdef USE_SERIAL
    #ifdef SERIAL_IS_A_FILE
    /*global*/ serialfd = fopen(serialport, "rw");
    #elif defined SERIAL_IS_A_ATH0
    /*global*/ serialfd = open(serialport, O_RDWR);
    #else
    /*global*/ serialfd = open(serialport, O_RDWR | O_NOCTTY | O_SYNC);
    #endif
    
    if (serialfd < 0) {
        fprintf(stderr, "error %d opening %s: %s", errno, serialport, strerror (errno));
        return;
    }

    #if !(defined SERIAL_IS_A_FILE || defined SERIAL_IS_A_ATH0)
    set_interface_attribs (serialfd, SERIAL_BAUDRATE, 0);  // set speed to 115,200 bps, 8n1 (no parity)
    set_blocking (serialfd, 0);                // set no blocking
    #endif
#endif

    hs_startup();

    char netbuf[MAXBUFLEN];
    unsigned int netbufpos = 0;

    struct sockaddr_storage their_addr;
    socklen_t addr_len;

#ifdef USE_SERIAL
    pthread_t pth;
    pthread_create(&pth, NULL, thread_read_serial, NULL);
#endif

    while(1) {
        // network
        int numbytes;
        addr_len = sizeof their_addr;
        if ((numbytes = recvfrom(sockfd, (netbuf + netbufpos), MAXBUFLEN - (netbufpos + 1), MSG_DONTWAIT, (struct sockaddr *)&their_addr, &addr_len)) > 0) {
            printf("[NET] received %i bytes\n", numbytes);

            int i = 0;
            for(i = 0; i < numbytes; i++) if(netbuf[netbufpos + i] == '\n') break;
            netbufpos += numbytes;

            if(i < numbytes) {
                // found breakline
                netbuf[netbufpos - 1] = '\0';
                netbufpos = 0;
                
                printf("CMD <%s>\n", netbuf);
                JSON_Value* json = json_parse_string(netbuf);

                if(json_value_get_type(json) == JSONObject) {
                    JSON_Object* obj = json_value_get_object(json);
                    const char* msgtype = json_object_dotget_string(obj, "type");
                    
                    if(strcmp(msgtype, "io.tcp.ping") == 0) do_ping();
                    else                                    do_network(json, netbuf);
                }

                json_value_free(json);
            }

            if(netbufpos + 1 == MAXBUFLEN) {
                printf("[NET] ERROR: received %i bytes and still no breakline. Discarding the message.\n", MAXBUFLEN);
                netbufpos = 0;
            }
        } else if(numbytes == 0) {
            break;
        }
        
    }

    hs_shutdown();

    close(sockfd);

    return 0;
}
Example #30
0
static corto_int16 json_deserComposite(void* p, corto_type t, JSON_Value *v)
{
    corto_assert(t->kind == CORTO_COMPOSITE, "not deserializing composite");

    if (json_value_get_type(v) != JSONObject) {
        corto_seterr("expected object, got %s", json_valueTypeToString(v));
        goto error;
    }

    JSON_Object* o = json_value_get_object(v);
    size_t count = json_object_get_count(o);
    size_t i;
    corto_bool isUnion = corto_interface(t)->kind == CORTO_UNION;
    corto_int32 discriminator = 0;
    corto_member unionMember = NULL;

    for (i = 0; i < count; i++) {
        const char* memberName = json_object_get_name(o, i);
        corto_member member_o;

        if (!strcmp(memberName, "super")) {
            JSON_Value* value = json_object_get_value(o, memberName);
            if (json_deserItem(p, corto_type(corto_interface(t)->base), value)) {
                goto error;
            }
        } else if (!strcmp(memberName, "_d") && isUnion) {
            JSON_Value* value = json_object_get_value(o, memberName);
            if (json_deserPrimitive(&discriminator, corto_union(t)->discriminator, value)) {
                goto error;
            }
            unionMember = corto_union_findCase(t, discriminator);
            if (!unionMember) {
                corto_seterr("discriminator '%d' invalid for union '%s'",
                    discriminator, corto_fullpath(NULL, t));
            }
        } else {
            member_o = corto_interface_resolveMember(t, (char*)memberName);

            /* Ensure that we're not resolving members from a base type */
            if (!member_o || (corto_parentof(member_o) != t)) {
                corto_seterr(
                    "cannot find member '%s' in type '%s'",
                    memberName,
                    corto_fullpath(NULL, t));
                goto error;
            }

            if (isUnion && (unionMember != member_o)) {
                corto_seterr(
                    "member '%s' does not match discriminator '%d' (expected member '%s')",
                    memberName,
                    discriminator,
                    corto_idof(unionMember));
                goto error;
            } else if (isUnion) {
                corto_int32 prev = *(corto_int32*)p;
                if (prev != discriminator) {
                    corto_member prevMember = corto_union_findCase(t, prev);
                    corto_deinitp(CORTO_OFFSET(p, prevMember->offset), prevMember->type);
                    memset(CORTO_OFFSET(p, member_o->offset), 0, member_o->type->size);
                }
                *(corto_int32*)p = discriminator;
            }

            if (!json_deserMustSkip(member_o, p)) {
                JSON_Value* value = json_object_get_value(o, memberName);
                void *offset = CORTO_OFFSET(p, member_o->offset);
                if (member_o->modifiers & CORTO_OBSERVABLE) {
                    offset = *(void**)offset;
                    if (json_deserType(offset, member_o->type, value)) {
                        goto error;
                    }
                } else {
                    if (member_o->modifiers & CORTO_OPTIONAL) {
                        if (*(void**)offset) {
                            corto_deinitp(*(void**)offset, member_o->type);
                            memset(*(void**)offset, 0, member_o->type->size);
                        } else {
                            *(void**)offset = corto_calloc(member_o->type->size);
                        }
                        offset = *(void**)offset;
                    }
                    if (json_deserItem(offset, member_o->type, value)) {
                        goto error;
                    }
                }
            }
        }
    }

    return 0;
error:
    return -1;
}