示例#1
0
文件: select.c 项目: GovanifY/thcrap
// Locates a repository for [sel] in [repo_list], starting from [orig_repo_id].
const char* SearchPatch(json_t *repo_list, const char *orig_repo_id, const json_t *sel)
{
	const char *repo_id = json_array_get_string(sel, 0);
	const char *patch_id = json_array_get_string(sel, 1);
	const json_t *orig_repo = json_object_get(repo_list, orig_repo_id);
	const json_t *patches = json_object_get(orig_repo, "patches");
	const json_t *remote_repo;
	const char *key;

	// Absolute dependency
	// In fact, just a check to see whether [sel] is available.
	if(repo_id) {
		remote_repo = json_object_get(repo_list, repo_id);
		patches = json_object_get(remote_repo, "patches");
		return json_object_get(patches, patch_id) ? repo_id : NULL;
	}

	// Relative dependency
	if(json_object_get(patches, patch_id)) {
		return orig_repo_id;
	}

	json_object_foreach(repo_list, key, remote_repo) {
		patches = json_object_get(remote_repo, "patches");
		if(json_object_get(patches, patch_id)) {
			return key;
		}
	}
示例#2
0
文件: tests.c 项目: lkunemail/parson
/* 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);
}
示例#3
0
/* 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"));
}
示例#4
0
json_t* patch_build(const json_t *sel)
{
	const char *repo_id = json_array_get_string(sel, 0);
	const char *patch_id = json_array_get_string(sel, 1);
	return json_pack("{ss+++}",
		"archive", repo_id, "/", patch_id, "/"
	);
}
示例#5
0
char* bud_config_encode_npn(bud_config_t* config,
                            const JSON_Array* npn,
                            size_t* len,
                            bud_error_t* err) {
  int i;
  char* npn_line;
  size_t npn_line_len;
  unsigned int offset;
  int npn_count;
  const char* npn_item;
  int npn_item_len;

  /* Try global defaults */
  if (npn == NULL)
    npn = config->frontend.npn;
  if (npn == NULL) {
    *err = bud_ok();
    *len = 0;
    return NULL;
  }

  /* Calculate storage requirements */
  npn_count = json_array_get_count(npn);
  npn_line_len = 0;
  for (i = 0; i < npn_count; i++)
    npn_line_len += 1 + strlen(json_array_get_string(npn, i));

  if (npn_line_len != 0) {
    npn_line = malloc(npn_line_len);
    if (npn_line == NULL) {
      *err = bud_error_str(kBudErrNoMem, "NPN copy");
      return NULL;
    }
  }

  /* Fill npn line */
  for (i = 0, offset = 0; i < npn_count; i++) {
    npn_item = json_array_get_string(npn, i);
    npn_item_len = strlen(npn_item);

    npn_line[offset++] = npn_item_len;
    memcpy(npn_line + offset, npn_item, npn_item_len);
    offset += npn_item_len;
  }
  ASSERT(offset == npn_line_len, "NPN Line overflow");

  *len = npn_line_len;
  *err = bud_ok();

  return npn_line;
}
示例#6
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:;
}
示例#7
0
文件: main.c 项目: 9re/LobiJniSample
static void handle_lobi_error(ANativeActivity *nativeActivity, int code, const char *response) {
    // see 
    // https://github.com/nakamap/docs/wiki/Android-SDK-Docs#wiki-nakamap-callback
    switch (code) {
    case LOBI_NETWORK_ERROR:
        // do something
        break;
    case LOBI_RESPONSE_ERROR:
        // do something
        break;
    case LOBI_FATAL_ERROR:
        {
            JSON_Value *responseValue = json_parse_string(response);
            JSON_Object *jsonObject = json_value_get_object(responseValue);
            // do something.
            // only in this case, response is not null and has
            // an array of messages with the key 'error'
            JSON_Array *errors = json_object_get_array((const JSON_Object *)jsonObject, "error");
            if (errors) {
                for (size_t i = 0, len = json_array_get_count(errors);
                     i < len; ++i) {
                    const char *error = json_array_get_string(errors, i);
                    lobi_showToast(nativeActivity, error);
                    LOGV("error #%d: %s", i, error);
                }
            }

            json_value_free(responseValue);
            break;
        }
    }
}
示例#8
0
gint jobdesc_streams_count (gchar *job, gchar *pipeline)
{
        JSON_Value *val;
        JSON_Object *obj;
        JSON_Array *array;
        gsize size, i;
        gint count, index;
        gchar *bin, *ptype;

        val = json_parse_string_with_comments (job);
        obj = json_value_get_object (val);
        if (g_str_has_prefix (pipeline, "encoder")) {
                ptype = "appsrc";
                array = json_object_dotget_array (obj, "encoders");
                sscanf (pipeline, "encoder.%d", &index);
                obj = json_array_get_object (array, index);

        } else if (g_str_has_prefix (pipeline, "source")) {
                ptype = "appsink";
                obj = json_object_get_object (obj, "source");
        }
        array = json_object_dotget_array (obj, "bins");
        size = json_array_get_count (array);
        count = 0;
        for (i = 0; i < size; i++) {
                bin = (gchar *)json_array_get_string (array, i);
                if (g_strrstr (bin, ptype) != NULL)
                        count += 1;
        }
        json_value_free (val);

        return count;
}
示例#9
0
文件: png.cpp 项目: thpatch/thcrap
bool png_image_get_IHDR(const char *fn, uint32_t *width, uint32_t *height, uint8_t *bpp)
{
	stack_chain_iterate_t sci = { 0 };
	BYTE *file_buffer = nullptr;
	file_buffer_t file = { 0 };

	json_t *chain = resolve_chain_game(fn);

	if (json_array_size(chain)) {
		log_printf("(PNG) Resolving %s...", json_array_get_string(chain, 0));
		while (file_buffer == nullptr && stack_chain_iterate(&sci, chain, SCI_BACKWARDS, nullptr) != 0) {
			file_buffer = (BYTE*)patch_file_load(sci.patch_info, sci.fn, &file.size);
		}
	}
	if (!file_buffer) {
		log_print("not found\n");
		json_decref(chain);
		return false;
	}
	patch_print_fn(sci.patch_info, sci.fn);
	log_print("\n");
	json_decref(chain);
	file.buffer = file_buffer;

	if (!png_check_sig(file.buffer, 8)) {
		log_print("Bad PNG signature!\n");
		free(file_buffer);
		return false;
	}
	file.buffer += 8;
	file.size -= 8;

	png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, png_error_callback, png_warning_callback);
	png_infop info_ptr = png_create_info_struct(png_ptr);
	if (setjmp(png_jmpbuf(png_ptr))) {
		png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
		free(file_buffer);
		return false;
	}
	png_set_read_fn(png_ptr, &file, read_bytes);
	png_set_sig_bytes(png_ptr, 8);
	png_read_info(png_ptr, info_ptr);

	int color_type;
	png_get_IHDR(png_ptr, info_ptr, width, height, NULL, &color_type, NULL, NULL, NULL);
	if (bpp) {
		*bpp = (color_type & PNG_COLOR_MASK_ALPHA) ? 32 : 24;
	}

	png_destroy_read_struct(&png_ptr, &info_ptr, NULL);
	free(file_buffer);
	return true;
}
示例#10
0
const char* run_cfg_fn_build(const size_t slot, const json_t *sel_stack)
{
	const char *ret = NULL;
	size_t i;
	json_t *sel;
	int skip = 0;

	ret = strings_strclr(slot);

	// If we have any translation patch, skip everything below that
	json_array_foreach(sel_stack, i, sel) {
		const char *patch_id = json_array_get_string(sel, 1);
		if(!strnicmp(patch_id, "lang_", 5)) {
			skip = 1;
			break;
		}
	}

	json_array_foreach(sel_stack, i, sel) {
		const char *patch_id = json_array_get_string(sel, 1);
		if(!patch_id) {
			continue;
		}

		if(ret && ret[0]) {
			ret = strings_strcat(slot, "-");
		}

		if(!strnicmp(patch_id, "lang_", 5)) {
			patch_id += 5;
			skip = 0;
		}
		if(!skip) {
			ret = strings_strcat(slot, patch_id);
		}
	}
	return ret;
}
示例#11
0
文件: utils.c 项目: androdev4u/bud
bud_error_t bud_config_load_ca_arr(X509_STORE** store,
                                   const JSON_Array* ca) {
  int i;
  int count;
  bud_error_t err;

  err = bud_config_verify_all_strings(ca, "ca");
  if (!bud_is_ok(err))
    return err;

  *store = X509_STORE_new();
  if (*store == NULL)
    return bud_error_str(kBudErrNoMem, "CA store");

  count = json_array_get_count(ca);
  for (i = 0; i < count; i++) {
    const char* cert;
    BIO* b;
    X509* x509;

    cert = json_array_get_string(ca, i);
    b = BIO_new_mem_buf((void*) cert, -1);
    if (b == NULL)
      return bud_error_str(kBudErrNoMem, "BIO_new_mem_buf:CA store bio");

    while ((x509 = PEM_read_bio_X509(b, NULL, NULL, NULL)) != NULL) {
      if (x509 == NULL) {
        err = bud_error_dstr(kBudErrParseCert, cert);
        break;
      }

      if (X509_STORE_add_cert(*store, x509) != 1) {
        err = bud_error(kBudErrAddCert);
        break;
      }
      X509_free(x509);
      x509 = NULL;
    }
    BIO_free_all(b);
    if (x509 != NULL)
      X509_free(x509);
  }

  return err;
}
示例#12
0
int __cdecl wmain(int argc, wchar_t *wargv[])
{
	int ret = 0;

	// Global URL cache to not download anything twice
	json_t *url_cache = json_object();
	// Repository ID cache to prioritize the most local repository if more
	// than one repository with the same name is discovered in the network
	json_t *id_cache = json_object();

	json_t *repo_list = NULL;

	const char *start_repo = "http://thcrap.nmlgc.net/repos/nmlgc/";

	json_t *sel_stack = NULL;
	json_t *new_cfg = json_pack("{s[]}", "patches");

	size_t cur_dir_len = GetCurrentDirectory(0, NULL) + 1;
	VLA(char, cur_dir, cur_dir_len);
	json_t *games = NULL;

	const char *run_cfg_fn = NULL;
	const char *run_cfg_fn_js = NULL;
	char *run_cfg_str = NULL;

	json_t *args = json_array_from_wchar_array(argc, wargv);

	wine_flag = GetProcAddress(
		GetModuleHandleA("kernel32.dll"), "wine_get_unix_file_name"
	) != 0;

	strings_mod_init();
	log_init(1);

	// Necessary to correctly process *any* input of non-ASCII characters
	// in the console subsystem
	w32u8_set_fallback_codepage(GetOEMCP());

	GetCurrentDirectory(cur_dir_len, cur_dir);
	PathAddBackslashA(cur_dir);
	str_slash_normalize(cur_dir);

	// Maximize the height of the console window... unless we're running under
	// Wine, where this 1) doesn't work and 2) messes up the console buffer
	if(!wine_flag) {
		CONSOLE_SCREEN_BUFFER_INFO sbi = {0};
		HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE);
		COORD largest = GetLargestConsoleWindowSize(console);
		HWND console_wnd = GetConsoleWindow();
		RECT console_rect;

		GetWindowRect(console_wnd, &console_rect);
		SetWindowPos(console_wnd, NULL, console_rect.left, 0, 0, 0, SWP_NOSIZE);
		GetConsoleScreenBufferInfo(console, &sbi);
		sbi.srWindow.Bottom = largest.Y - 4;
		SetConsoleWindowInfo(console, TRUE, &sbi.srWindow);
	}

	http_init();

	if(json_array_size(args) > 1) {
		start_repo = json_array_get_string(args, 1);
	}

	log_printf(
		"==========================================\n"
		"Touhou Community Reliant Automatic Patcher - Patch configuration tool\n"
		"==========================================\n"
		"\n"
		"\n"
		"This tool will create a new patch configuration for the\n"
		"Touhou Community Reliant Automatic Patcher.\n"
		"\n"
		"\n"
		"The configuration process has two steps:\n"
		"\n"
		"\t\t1. Selecting patches\n"
		"\t\t2. Download game-independent data\n"
		"\t\t3. Locating game installations\n"
		"\t\t4. Download game-specific data\n"
		"\n"
		"\n"
		"\n"
		"Patch repository discovery will start at\n"
		"\n"
		"\t%s\n"
		"\n"
		"You can specify a different URL as a command-line parameter.\n"
		"Additionally, all patches from previously discovered repositories, stored in\n"
		"subdirectories of the current directory, will be available for selection.\n"
		"\n"
		"\n",
		start_repo
	);
	pause();

	if(RepoDiscoverAtURL(start_repo, id_cache, url_cache)) {
		goto end;
	}
	if(RepoDiscoverFromLocal(id_cache, url_cache)) {
		goto end;
	}
	repo_list = RepoLoad();
	if(!json_object_size(repo_list)) {
		log_printf("No patch repositories available...\n");
		pause();
		goto end;
	}
	sel_stack = SelectPatchStack(repo_list);
	if(json_array_size(sel_stack)) {
		json_t *new_cfg_patches = json_object_get(new_cfg, "patches");
		size_t i;
		json_t *sel;

		log_printf("Downloading game-independent data...\n");
		stack_update(update_filter_global, NULL);

		/// Build the new run configuration
		json_array_foreach(sel_stack, i, sel) {
			json_array_append_new(new_cfg_patches, patch_build(sel));
		}
	}
示例#13
0
int parse_blueprint_json(JSON_Object *blueprint, blueprint_t *bp)
{
	bstring Name, bp_name, name, game_version;
	uint32_t resource_cost[5];

	bp->revision = json_object_get_number(blueprint, "blueprintVersion");

	bp_name = bfromcstr(json_object_get_string(blueprint, "blueprintName"));
	name = bfromcstr(json_object_get_string(blueprint, "Name"));
	game_version = bfromcstr(json_object_get_string(blueprint, "GameVersion"));

	bstring param1 = bfromcstr(json_object_get_string(blueprint, "Parameter1"));
	bstring param2 = bfromcstr(json_object_get_string(blueprint, "Parameter2"));
	bstring lpos = bfromcstr(json_object_get_string(blueprint, "LocalPosition"));
	bstring lrot = bfromcstr(json_object_get_string(blueprint, "LocalRotation"));

	bp->name = name;
	bp->blueprint_name = bp_name;
	bp->Name = Name;
	bp->game_version = game_version;

	const char* cpos = json_object_get_string(blueprint, "LocalPosition");
	bstring pos = bfromcstr(cpos);
	struct bstrList *pval = bsplit(pos, ',');
	for (int i = 0; i < 3; i++)
	{
		char *ptr;
		char *str = bstr2cstr(pval->entry[i], '0');
		uint32_t n = strtol(str, &ptr, 10);
	}

	const char* crot = json_object_get_string(blueprint, "LocalRotation");
	bstring rot = bfromcstr(crot);
	struct bstrList *rval = bsplit(rot, ',');
	for (int i = 0; i < 4; i++)
	{
		char *ptr;
		char *str = bstr2cstr(rval->entry[i], '0');
		double dbl = strtod(str, &ptr);
		free(str);
		bp->local_rotation[i] = dbl;
	}

	bp->parameter1 = param1;
	bp->parameter2 = param2;

	bp->design_changed = json_object_get_boolean(blueprint, "designChanged");

	bp->id = json_object_get_number(blueprint, "Id");
	bp->force_id = json_object_get_number(blueprint, "ForceId");
	bp->item_number = json_object_get_number(blueprint, "ItemNumber");

	JSON_Array *jresource_cost = json_object_get_array(blueprint, "ResourceCost");
	for (int i = 0; i < 5; i++)
		bp->resource_cost[i] = (uint32_t) json_array_get_number(jresource_cost, i);

	JSON_Array *min_coords = json_object_get_array(blueprint, "MinCords");
	for (int i = 0; i < 3; i++)
		bp->min_coords[i] = (int32_t) json_array_get_number(min_coords, i);

	JSON_Array *max_coords = json_object_get_array(blueprint, "MaxCords");
	for (int i = 0; i < 3; i++)
		bp->max_coords[i] = (int32_t) json_array_get_number(max_coords, i);

	JSON_Array *csi = json_object_get_array(blueprint, "CSI");
	for (int i = 0; i < 40; i++)
		bp->constructable_special_info[i] = json_array_get_number(csi, i);

	bp->last_alive_block = (uint32_t) json_object_get_number(blueprint, "LastAliveBlock");

	JSON_Array *palette = json_object_get_array(blueprint, "COL");
	for(int i = 0; i < 32; i++)
	{
		uint32_t rbga = 0;

		const char* ccolor = json_array_get_string(palette, i);
		bstring color = bfromcstr(ccolor);

		// Create array of substrings
		struct bstrList *values = bsplit(color, ',');
		for (int n = 0; n < 4; n++)
		{
			char *ptr;
			char *str = bstr2cstr(values->entry[n], '0');
			double dbl = strtod(str, &ptr);
			free(str);
			bp->color_palette[i].array[n] = round(dbl * 255.0);
		}
		bstrListDestroy(values);
		bdestroy(color);
	}

	JSON_Array *material = json_object_get_array(blueprint, "BlockIds");
	JSON_Array *position = json_object_get_array(blueprint, "BLP");
	JSON_Array *rotation = json_object_get_array(blueprint, "BLR");
	JSON_Array *color = json_object_get_array(blueprint, "BCI");

	JSON_Array *bp1 = json_object_get_array(blueprint, "BP1");
	JSON_Array *bp2 = json_object_get_array(blueprint, "BP2");
	JSON_Array *block_string_ids = json_object_get_array(blueprint, "BlockStringDataIds");
	JSON_Array *block_data = json_object_get_array(blueprint, "BlockStringData");

	bp->total_block_count = (uint32_t) json_object_get_number(blueprint, "TotalBlockCount");
	bp->main_block_count = (uint32_t) json_object_get_number(blueprint, "BlockCount");
	bp->blocks = calloc(bp->main_block_count, sizeof(block_t));

	for (int i = 0; i < bp->main_block_count; i++)
	{
		block_t *act = &bp->blocks[i];

		act->material = (uint32_t) json_array_get_number(material, i);
		act->rotation = (uint32_t) json_array_get_number(rotation, i);
		act->color = (uint32_t) json_array_get_number(color, i);

		bstring pos_string = bfromcstr(json_array_get_string(position, i));
		struct bstrList *pos_list = bsplit(pos_string, ',');
		for (int n = 0; n < 3; n++)
		{
			char *ptr;
			char *str = bstr2cstr(pos_list->entry[n], '0');
			double dbl = strtod(str, &ptr);
			uint32_t val = round(dbl);
			act->position.array[n] = val;
			free(str);
		}
		bstrListDestroy(pos_list);
		bdestroy(pos_string);

		bstring bp1_string = bfromcstr(json_array_get_string(bp1, i));
		struct bstrList *bp1_values = bsplit(bp1_string, ',');
		for (int n = 0; n < 4; n++)
		{
			char *ptr;
			char *str = bstr2cstr(bp1_values->entry[n], '0');
			double dbl = strtod(str, &ptr);
			act->bp1[n] = dbl;
		}

		bstring bp2_string = bfromcstr(json_array_get_string(bp2, i));
		struct bstrList *bp2_values = bsplit(bp2_string, ',');
		for (int n = 0; n < 4; n++)
		{
			char *ptr;
			char *str = bstr2cstr(bp2_values->entry[n], '0');
			double dbl = strtod(str, &ptr);
			uint32_t val = round(dbl);
			act->bp2[n] = val;
		}

		// Only used for lookup, not saved after that since it has no further semantic value
		const char *cb1 = json_array_get_string(bp1, i);

		if (act->bp1[3] != 0)
		{
			for (int n = 0; n < json_array_get_count(block_string_ids); n++)
			{
				uint32_t test_id = json_array_get_number(block_string_ids, n);
				if (test_id == 0)
				{
					break;
				}
				if (test_id == act->bp1[3])
				{
					// BlockStringData at index n is the one we want
					act->string_data = bfromcstr(json_array_get_string(block_data, n));
				}
			}
		}
	}

	JSON_Array *subconstructables = json_object_get_array(blueprint, "SCs");
	bp->num_sc = json_array_get_count(subconstructables);
	bp->SCs = calloc(bp->num_sc, sizeof(blueprint_t));
	for (int i = 0; i < bp->num_sc; i++)
	{
		JSON_Value *sc_json = json_array_get_value(subconstructables, i);
		JSON_Object *sc_obj = json_value_get_object(sc_json);
		int retval = parse_blueprint_json(sc_obj, &bp->SCs[i]);
		if (retval != 0)
			return retval;
	}

	return 0;
}
示例#14
0
int config_parse(const char *file, config_t *config)
{
    JSON_Value *jvroot;
    JSON_Object *joroot;
    JSON_Object *jomaccmd;
    JSON_Array *jarray;
    JSON_Value_Type jtype;
    const char *string;
    int ret;
    int i;

    if(file == NULL){
        return -1;
    }

    /** Clear all flags */
    config_free(config);

    printf("Start parsing configuration file....\n\n");

    /* parsing json and validating output */
    jvroot = json_parse_file_with_comments(file);
    jtype = json_value_get_type(jvroot);
    if (jtype != JSONObject) {
        return -1;
    }
    joroot = json_value_get_object(jvroot);

    string = json_object_get_string(joroot, "band");
    if(string == NULL){
        config->band = LW_BAND_EU868;
    }else{
        for(i=0; i<LW_BAND_MAX_NUM; i++){
            if(0 == strcmp(string, config_band_tab[i])){
                config->band = (lw_band_t)i;
                break;
            }
        }
        if(i==LW_BAND_MAX_NUM){
            config->band = LW_BAND_EU868;
        }
    }

    string = json_object_dotget_string(joroot, "key.nwkskey");
    if(string != NULL){
        if(str2hex(string, config->nwkskey, 16) == 16){
            config->flag |= CFLAG_NWKSKEY;
        }
    }

    string = json_object_dotget_string(joroot, "key.appskey");
    if(string != NULL){
        if(str2hex(string, config->appskey, 16) == 16){
            config->flag |= CFLAG_APPSKEY;
        }
    }

    string = json_object_dotget_string(joroot, "key.appkey");
    if(string != NULL){
        if(str2hex(string, config->appkey, 16) == 16){
            config->flag |= CFLAG_APPKEY;
        }
    }

    ret = json_object_dotget_boolean(joroot, "join.key");
    if(ret==0){
        //printf("Join key false\n");
        config->joinkey = false;
    }else if(ret==1){
        //printf("Join key true\n");
        config->joinkey = true;
    }else{
        //printf("Unknown join key value\n");
        config->joinkey = false;
    }

    string = json_object_dotget_string(joroot, "join.request");
    if(string != NULL){
        uint8_t tmp[255];
        int len;
        len = str2hex(string, tmp, 255);
        if(len>0){
            config->flag |= CFLAG_JOINR;
            config->joinr = malloc(len);
            if(config->joinr == NULL){
                return -2;
            }
            config->joinr_size = len;
            memcpy(config->joinr, tmp, config->joinr_size);
        }
    }

    string = json_object_dotget_string(joroot, "join.accept");
    if(string != NULL){
        uint8_t tmp[255];
        int len;
        len = str2hex(string, tmp, 255);
        if(len>0){
            config->flag |= CFLAG_JOINA;
            config->joina = malloc(len);
            if(config->joina == NULL){
                return -3;
            }
            config->joina_size = len;
            memcpy(config->joina, tmp, config->joina_size);
        }
    }

    jarray = json_object_get_array(joroot, "messages");
    if(jarray != NULL){
        uint8_t tmp[255];
        for (i = 0; i < json_array_get_count(jarray); i++) {
            string = json_array_get_string(jarray, i);
            if(string!=NULL){
                int len = str2hex(string, tmp, 255);
                if(len>0){
                    message_t *pl = malloc(sizeof(message_t));
                    memset(pl, 0, sizeof(message_t));
                    if(pl == NULL){
                        return -3;
                    }
                    pl->buf = malloc(len);
                    if(pl->buf == NULL){
                        return -3;
                    }
                    pl->len = len;
                    memcpy(pl->buf, tmp, pl->len);
                    pl_insert(&config->message, pl);
                }else{
                    printf("Messages[%d] \"%s\" is not hex string\n", i, string);

                }
            }else{
                printf("Messages item %d is not string\n", i);
            }
        }
    }else{
        printf("Can't get payload array\n");
    }

    jarray = json_object_get_array(joroot, "maccommands");
    if(jarray != NULL){
        uint8_t mhdr;
        int len;
        uint8_t tmp[255];
        for (i = 0; i < json_array_get_count(jarray); i++) {
            jomaccmd = json_array_get_object(jarray, i);
            string = json_object_get_string(jomaccmd, "MHDR");
            if(string != NULL){
                len = str2hex(string, &mhdr, 1);
                if(len != 1){
                    printf("\"maccommands\"[%d].MHDR \"%s\" must be 1 byte hex string\n", i, string);
                    continue;
                }
            }else{
                string = json_object_get_string(jomaccmd, "direction");
                if(string != NULL){
                    int j;
                    len = strlen(string);
                    if(len>200){
                        printf("\"maccommands\"[%d].direction \"%s\" too long\n", i, string);
                        continue;
                    }
                    for(j=0; j<len; j++){
                        tmp[j] = tolower(string[j]);
                    }
                    tmp[j] = '\0';
                    if(0==strcmp((char *)tmp, "up")){
                        mhdr = 0x80;
                    }else if(0==strcmp((char *)tmp, "down")){
                        mhdr = 0xA0;
                    }else{
                        printf("\"maccommands\"[%d].MHDR \"%s\" must be 1 byte hex string\n", i, string);
                        continue;
                    }
                }else{
                    printf("Can't recognize maccommand direction\n");
                    continue;
                }
            }
            string = json_object_get_string(jomaccmd, "command");
            if(string != NULL){
                len = str2hex(string, tmp, 255);
                if(len <= 0){
                    printf("\"maccommands\"[%d].command \"%s\" is not hex string\n", i, string);
                    continue;
                }
            }else{
                printf("c\"maccommands\"[%d].command is not string\n", i);
                continue;
            }
            message_t *pl = malloc(sizeof(message_t));
            memset(pl, 0, sizeof(message_t));
            if(pl == NULL){
                return -3;
            }
            pl->buf = malloc(len+1);
            if(pl->buf == NULL){
                return -3;
            }
            pl->len = len+1;
            pl->buf[0] = mhdr;
            pl->next = 0;
            memcpy(pl->buf+1, tmp, pl->len-1);
            pl_insert(&config->maccmd, pl);
        }
    }

    print_spliter();
    printf("%15s %s\n","BAND:\t", config_band_tab[LW_BAND_EU868]);
    printf("%15s","NWKSKEY:\t");
    putlen(16);
    puthbuf(config->nwkskey, 16);
    printf("\n");
    printf("%15s","APPSKEY:\t");
    putlen(16);
    puthbuf(config->appskey, 16);
    printf("\n");
    printf("%15s","APPKEY:\t");
    putlen(16);
    puthbuf(config->appkey, 16);
    printf("\n");
    printf("%15s","JOINR:\t");
    putlen(config->joinr_size);
    puthbuf(config->joinr, config->joinr_size );
    printf("\n");
    printf("%15s","JOINA:\t");
    putlen(config->joina_size);
    puthbuf(config->joina, config->joina_size );
    printf("\n");
    pl_print(config->message);
    maccmd_print(config->maccmd);

    json_value_free(jvroot);
    return 0;
}
示例#15
0
static inline char *
json_array_get_string_safe(JSON_Array *array, int index) {
  const char *val = json_array_get_string(array, index);
  if (!val) return NULL;
  return str_copy(val);
}
示例#16
0
文件: ninja.c 项目: odeke-em/pyg
pyg_error_t pyg_gen_ninja_print_rules(pyg_target_t* target,
                                      pyg_settings_t* settings) {
  JSON_Array* arr;
  size_t i;
  size_t count;
  char* cflags;
  char* ldflags;
  static const int types[] = { kPygSourceC, kPygSourceCXX };
  pyg_error_t err;

  /* Include dirs */
  CHECKED_PRINT("\n%s =", pyg_gen_ninja_cmd(target, "include_dirs"));

  arr = json_object_get_array(target->json, "include_dirs");
  count = json_array_get_count(arr);

  /* TODO(indutny): MSVC support */
  for (i = 0; i < count; i++) {
    CHECKED_PRINT(" -I%s",
                  pyg_gen_ninja_src_path(json_array_get_string(arr, i),
                                         settings));
  }

  /* Defines */
  CHECKED_PRINT("\n%s =", pyg_gen_ninja_cmd(target, "defines"));

  arr = json_object_get_array(target->json, "defines");
  count = json_array_get_count(arr);

  /* TODO(indutny): MSVC support */
  for (i = 0; i < count; i++)
    CHECKED_PRINT(" -D%s", json_array_get_string(arr, i));

  /* Libraries */
  CHECKED_PRINT("\n%s =", pyg_gen_ninja_cmd(target, "libs"));

  arr = json_object_get_array(target->json, "libraries");
  count = json_array_get_count(arr);

  /* TODO(indutny): MSVC support */
  for (i = 0; i < count; i++)
    CHECKED_PRINT(" %s", json_array_get_string(arr, i));

  CHECKED_PRINT("\n");

  /* cflags, ldflags */
  cflags = NULL;
  ldflags = NULL;
  err = pyg_stringify_json(json_object_get_value(target->json, "cflags"),
                           &cflags);
  if (pyg_is_ok(err)) {
    err = pyg_stringify_json(json_object_get_value(target->json, "ldflags"),
                             &ldflags);
  }
  if (pyg_is_ok(err)) {
    err = pyg_buf_put(settings->out,
                      "%s = %s\n",
                      pyg_gen_ninja_cmd(target, "cflags"),
                      cflags);
  }
  if (pyg_is_ok(err)) {
    err = pyg_buf_put(settings->out,
                      "%s = %s\n\n",
                      pyg_gen_ninja_cmd(target, "ldflags"),
                      ldflags);
  }
  free(cflags);
  free(ldflags);
  if (!pyg_is_ok(err))
    return err;

  for (i = 0; i < ARRAY_SIZE(types); i++) {
    int type = types[i];
    const char* cc;
    const char* ld;

    if ((target->source.types & type) == 0)
      continue;

    if (type == kPygSourceC) {
      cc = "cc";
      ld = "ld";
    } else {
      cc = "cxx";
      ld = "ldxx";
    }

    CHECKED_PRINT("rule %s\n", pyg_gen_ninja_cmd(target, cc));
    CHECKED_PRINT("  command = $%s -MMD -MF $out.d ", cc);
    CHECKED_PRINT("$%s ", pyg_gen_ninja_cmd(target, "defines"));
    CHECKED_PRINT("$%s ", pyg_gen_ninja_cmd(target, "include_dirs"));
    CHECKED_PRINT("$%s -c $in -o $out\n", pyg_gen_ninja_cmd(target, "cflags"));
    CHECKED_PRINT("  description = COMPILE $out\n"
                  "  depfile = $out.d\n"
                  "  deps = gcc\n\n");

    CHECKED_PRINT("rule %s\n", pyg_gen_ninja_cmd(target, ld));
    CHECKED_PRINT("  command = $ld $%s ", pyg_gen_ninja_cmd(target, "ldflags"));
    CHECKED_PRINT("-o $out $in $%s\n", pyg_gen_ninja_cmd(target, "libs"));
    CHECKED_PRINT("  description = LINK $out\n\n");
  }

  CHECKED_PRINT("rule %s\n", pyg_gen_ninja_cmd(target, "ar"));
  CHECKED_PRINT("  command = ar rsc $out $in\n");
  CHECKED_PRINT("  description = AR $out\n\n");

  return pyg_ok();
}