static void clubby_proto_parse_req(struct json_token *frame, struct json_token *cmds_arr, void *context) { if (cmds_arr->type != JSON_TYPE_ARRAY || cmds_arr->num_desc == 0) { /* Just for debugging - there _is_ cmds field but it is empty */ LOG(LL_ERROR, ("No cmd in cmds")); return; } struct json_token *cmd = NULL; struct clubby_event evt; evt.ev = CLUBBY_REQUEST; evt.context = context; evt.request.src = find_json_token(frame, "src"); if (evt.request.src == NULL || evt.request.src->type != JSON_TYPE_STRING) { LOG(LL_ERROR, ("Invalid src |%.*s|", frame->len, frame->ptr)); return; } /* * If any required field is missing we stop processing of the whole package * It looks simpler & safer */ const char *cmds_arr_end = cmds_arr->ptr + cmds_arr->len; for (cmd = cmds_arr + 1; cmd->type != JSON_TYPE_EOF && cmd->ptr < cmds_arr_end;) { if (cmd->type != JSON_TYPE_OBJECT) { LOG(LL_ERROR, ("Commands array contains %d instead of object: |%.*s|", cmd->type, cmd->len, cmd->ptr)); break; } evt.request.cmd_body = cmd; evt.request.cmd = find_json_token(cmd, "cmd"); if (evt.request.cmd == NULL || evt.request.cmd->type != JSON_TYPE_STRING) { LOG(LL_ERROR, ("Invalid command |%.*s|", cmd->len, cmd->ptr)); break; } struct json_token *id_tok = find_json_token(cmd, "id"); if (id_tok == NULL || id_tok->type != JSON_TYPE_NUMBER) { LOG(LL_ERROR, ("No id command |%.*s|", cmd->len, cmd->ptr)); break; } evt.request.id = to64(id_tok->ptr); s_clubby_cb(&evt); const char *cmd_end = cmd->ptr + cmd->len; struct json_token *next = cmd + 1; while (next->type != JSON_TYPE_EOF && next->ptr < cmd_end) { next++; } cmd = next; } }
static int fill_part_info(struct update_context *ctx, struct json_token *parts_tok, const char *part_name, struct part_info *pi) { struct json_token *part_tok = find_json_token(parts_tok, part_name); if (part_tok == NULL) { LOG(LL_ERROR, ("Part %s not found", part_name)); return -1; } struct json_token *addr_tok = find_json_token(part_tok, "addr"); if (addr_tok == NULL) { LOG(LL_ERROR, ("Addr token not found in manifest")); return -1; } /* * we can use strtol for non-null terminated string here, we have * symbols immediately after address which will stop number parsing */ pi->addr = strtol(addr_tok->ptr, NULL, 16); if (pi->addr == 0) { /* Only rboot can has addr = 0, but we do not update rboot now */ LOG(LL_ERROR, ("Invalid address in manifest")); return -1; } LOG(LL_DEBUG, ("Addr to write from manifest: %X", pi->addr)); /* * manifest always contain relative addresses, we have to * convert them to absolute (+0x100000 for slot #1) */ pi->addr += ctx->slot_to_write * FW_SLOT_SIZE; LOG(LL_DEBUG, ("Addr to write to use: %X", pi->addr)); struct json_token *sha1sum_tok = find_json_token(part_tok, "cs_sha1"); if (sha1sum_tok == NULL || sha1sum_tok->type != JSON_TYPE_STRING || sha1sum_tok->len != sizeof(pi->sha1sum)) { LOG(LL_ERROR, ("cs_sha1 token not found in manifest")); return -1; } memcpy(pi->sha1sum, sha1sum_tok->ptr, sizeof(pi->sha1sum)); struct json_token *file_name_tok = find_json_token(part_tok, "src"); if (file_name_tok == NULL || file_name_tok->type != JSON_TYPE_STRING || (size_t) file_name_tok->len > sizeof(pi->file_name) - 1) { LOG(LL_ERROR, ("cs_sha1 token not found in manifest")); return -1; } memcpy(pi->file_name, file_name_tok->ptr, file_name_tok->len); LOG(LL_DEBUG, ("Part %s : addr: %X sha1: %.*s src: %s", part_name, (int) pi->addr, sizeof(pi->sha1sum), pi->sha1sum, pi->file_name)); return 1; }
static void clubby_proto_parse_resp(struct json_token *resp_arr) { struct clubby_event evt; evt.ev = CLUBBY_RESPONSE; if (resp_arr->type != JSON_TYPE_ARRAY || resp_arr->num_desc == 0) { LOG(LL_ERROR, ("No resp in resp")); return; } /* Frozen's API for working with arrays is nonexistent, so what we do here * looks kinda funny. * Things to note: resp_arr->len is length of the array in characters, not * elements. * tok->num_desc includes all the tokens inside array, not just elements. * There is basically no way to tell number of elements upfront. */ struct json_token *resp = NULL; const char *resp_arr_end = resp_arr->ptr + resp_arr->len; for (resp = resp_arr + 1; resp->type != JSON_TYPE_EOF && resp->ptr < resp_arr_end;) { if (resp->type != JSON_TYPE_OBJECT) { LOG(LL_ERROR, ("Response array contains %d instead of object: |%.*s|", resp->type, resp->len, resp->ptr)); break; } evt.response.resp_body = resp; struct json_token *id_tok = find_json_token(resp, "id"); if (id_tok == NULL || id_tok->type != JSON_TYPE_NUMBER) { LOG(LL_ERROR, ("No id in response |%.*s|", resp->len, resp->ptr)); break; } /* Any number inside a JSON message will have non-number character. * Hence, no need to have it explicitly nul-terminated. */ evt.response.id = strtoul(id_tok->ptr, NULL, 10); struct json_token *status_tok = find_json_token(resp, "status"); if (status_tok == NULL || status_tok->type != JSON_TYPE_NUMBER) { LOG(LL_ERROR, ("No status in response |%.*s|", resp->len, resp->ptr)); break; } evt.response.status = strtol(status_tok->ptr, NULL, 10); evt.response.status_msg = find_json_token(resp, "status_msg"); evt.response.resp = find_json_token(resp, "resp"); s_clubby_cb(&evt); const char *resp_end = resp->ptr + resp->len; struct json_token *next = resp + 1; while (next->type != JSON_TYPE_EOF && next->ptr < resp_end) { next++; } resp = next; } }
int sj_conf_get_str(struct json_token *toks, const char *key, const char *acl, char **val) { struct json_token *tok = find_json_token(toks, key); int result = 0; if (tok == NULL) { LOG(LL_VERBOSE_DEBUG, ("key [%s] not found", key)); } else if (!sj_conf_check_access(key, acl)) { LOG(LL_ERROR, ("Setting key [%s] is not allowed", key)); } else { if (*val != NULL) { free(*val); } *val = NULL; if (tok->len == 0) { /* Empty string token - keep value as NULL */ result = 1; LOG(LL_DEBUG, ("Loaded: %s=NULL", key)); } else if ((*val = (char *) malloc(tok->len + 1)) != NULL) { memcpy(*val, tok->ptr, tok->len); (*val)[tok->len] = '\0'; result = 1; LOG(LL_DEBUG, ("Loaded: %s=[%s]", key, *val)); } else { LOG(LL_ERROR, ("malloc(%d) fails for key [%s]", tok->len + 1, key)); } } return result; }
static void clubby_proto_parse_req(struct json_token *method, struct json_token *frame, struct clubby_event *evt) { evt->ev = CLUBBY_REQUEST; evt->request.method = method; evt->request.args = find_json_token(frame, "args"); }
static void clubby_proto_parse_resp(struct json_token *result_tok, struct json_token *error_tok, struct clubby_event *evt) { evt->ev = CLUBBY_RESPONSE; evt->response.result = result_tok; if (error_tok != NULL) { evt->response.error.error_obj = error_tok; struct json_token *error_code_tok = find_json_token(error_tok, "code"); if (error_code_tok == NULL) { LOG(LL_ERROR, ("No error code in error object")); return; } evt->response.error.error_code = to64(error_code_tok->ptr); evt->response.error.error_message = find_json_token(error_tok, "message"); } }
int Eiger::parseSequenceId (const response_t *response, int *sequenceId) { const char *functionName = "parseParamList"; if(!response->contentLength) { ERR("no content to parse"); return EXIT_FAILURE; } struct json_token tokens[MAX_JSON_TOKENS]; int err = parse_json(response->content, response->contentLength, tokens, MAX_JSON_TOKENS); if(err < 0) { ERR("unable to parse response json"); return EXIT_FAILURE; } if(tokens[0].type != JSON_TYPE_OBJECT) { ERR("unexpected token type"); return EXIT_FAILURE; } struct json_token *seqIdToken = find_json_token(tokens, "sequence id"); if(!seqIdToken) { seqIdToken = find_json_token(tokens, "series id"); if(!seqIdToken) { ERR("unable to find 'series id' or 'sequence id' token"); return EXIT_FAILURE; } } if(sscanf(seqIdToken->ptr, "%d", sequenceId) != 1) { ERR("unable to parse 'sequence_id' token"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
static void load_long(struct json_token* tokens, const char* path, long* into) { const struct json_token* token; token = find_json_token(tokens, path); if (token) { *into = strntol(token->ptr, token->len, 10); } }
static const char *test_config(void) { static const char *config_str = "{ ports: [ 80, 443 ] } "; struct json_token tokens[100]; int tokens_size = sizeof(tokens) / sizeof(tokens[0]); ASSERT(parse_json(config_str, strlen(config_str), tokens, tokens_size) > 0); ASSERT(tokens[0].type == JSON_TYPE_OBJECT); ASSERT(tokens[1].type == JSON_TYPE_STRING); ASSERT(tokens[2].type == JSON_TYPE_ARRAY); ASSERT(tokens[3].type == JSON_TYPE_NUMBER); ASSERT(tokens[4].type == JSON_TYPE_NUMBER); ASSERT(tokens[5].type == JSON_TYPE_EOF); ASSERT(find_json_token(tokens, "ports") == &tokens[2]); ASSERT(find_json_token(tokens, "ports[0]") == &tokens[3]); ASSERT(find_json_token(tokens, "ports[1]") == &tokens[4]); ASSERT(find_json_token(tokens, "ports[3]") == NULL); ASSERT(find_json_token(tokens, "foo.bar") == NULL); return NULL; }
static const char *test_nested(void) { struct json_token ar[100]; const char *s = "{ a : [ [1, 2, { b : 2 } ] ] }"; enum json_type types[] = { JSON_TYPE_OBJECT, JSON_TYPE_STRING, JSON_TYPE_ARRAY, JSON_TYPE_ARRAY, JSON_TYPE_NUMBER, JSON_TYPE_NUMBER, JSON_TYPE_OBJECT, JSON_TYPE_STRING, JSON_TYPE_NUMBER, JSON_TYPE_EOF }; int i, ar_size = ARRAY_SIZE(ar), types_size = ARRAY_SIZE(types); ASSERT(parse_json(s, strlen(s), ar, ar_size) == (int) strlen(s)); for (i = 0; i < types_size; i++) { ASSERT(ar[i].type == types[i]); } ASSERT(find_json_token(ar, "a[0]") == &ar[3]); ASSERT(find_json_token(ar, "a[0][0]") == &ar[4]); ASSERT(find_json_token(ar, "a[0][1]") == &ar[5]); ASSERT(find_json_token(ar, "a[0][2]") == &ar[6]); ASSERT(find_json_token(ar, "a[0][2].b") == &ar[8]); return NULL; }
static void clubby_proto_handle_frame(char *data, size_t len, void *context) { struct json_token *frame = parse_json2(data, len); if (frame == NULL) { LOG(LL_DEBUG, ("Error parsing clubby frame")); return; } struct json_token *tmp; tmp = find_json_token(frame, "resp"); if (tmp != NULL) { clubby_proto_parse_resp(tmp, context); } tmp = find_json_token(frame, "cmds"); if (tmp != NULL) { clubby_proto_parse_req(frame, tmp, context); } free(frame); }
static void clubby_proto_handle_frame(struct mg_str data) { struct json_token *frame = parse_json2(data.p, data.len); if (frame == NULL) { LOG(LL_DEBUG, ("Error parsing clubby frame")); return; } struct json_token *tmp; tmp = find_json_token(frame, "resp"); if (tmp != NULL) { clubby_proto_parse_resp(tmp); } tmp = find_json_token(frame, "cmds"); if (tmp != NULL) { clubby_proto_parse_req(frame, tmp); } free(frame); }
/* * Dispatches a JSON-RPC request. * * Parses JSON-RPC request contained in `buf`, `len`. Then, dispatches the *request * to the correct handler method. Valid method names should be specified in NULL * terminated array `methods`, and corresponding handlers in `handlers`. * Result is put in `dst`, `dst_len`. Return: length of the result, which * can be larger then `dst_len` that indicates an overflow. */ int ns_rpc_dispatch(const char *buf, int len, char *dst, int dst_len, const char **methods, ns_rpc_handler_t *handlers) { struct json_token tokens[200]; struct ns_rpc_request req; int i, n; memset(&req, 0, sizeof(req)); n = parse_json(buf, len, tokens, sizeof(tokens) / sizeof(tokens[0])); if (n <= 0) { int err_code = (n == JSON_STRING_INVALID) ? JSON_RPC_PARSE_ERROR : JSON_RPC_SERVER_ERROR; return ns_rpc_create_std_error(dst, dst_len, &req, err_code); } req.message = tokens; req.id = find_json_token(tokens, "id"); req.method = find_json_token(tokens, "method"); req.params = find_json_token(tokens, "params"); if (req.id == NULL || req.method == NULL) { return ns_rpc_create_std_error(dst, dst_len, &req, JSON_RPC_INVALID_REQUEST_ERROR); } for (i = 0; methods[i] != NULL; i++) { int mlen = strlen(methods[i]); if (mlen == req.method->len && memcmp(methods[i], req.method->ptr, mlen) == 0) break; } if (methods[i] == NULL) { return ns_rpc_create_std_error(dst, dst_len, &req, JSON_RPC_METHOD_NOT_FOUND_ERROR); } return handlers[i](dst, dst_len, &req); }
static int fill_manifest(struct update_context *ctx) { struct json_token *toks = parse_json2((char *) ctx->data, ctx->file_info.file_size); if (toks == NULL) { LOG(LL_ERROR, ("Failed to parse manifest")); goto error; } struct json_token *parts_tok = find_json_token(toks, "parts"); if (parts_tok == NULL) { LOG(LL_ERROR, ("parts token not found in manifest")); goto error; } if (fill_part_info(ctx, parts_tok, "fw", &ctx->fw_part) < 0 || fill_part_info(ctx, parts_tok, "fs", &ctx->fs_part) < 0) { goto error; } struct json_token *version_tok = find_json_token(toks, "version"); if (version_tok == NULL || version_tok->type != JSON_TYPE_STRING || version_tok->len != sizeof(ctx->version)) { LOG(LL_ERROR, ("version token not found in manifest")); goto error; } memcpy(ctx->version, version_tok->ptr, sizeof(ctx->version)); LOG(LL_DEBUG, ("Version: %.*s", sizeof(ctx->version), ctx->version)); context_remove_data(ctx, ctx->file_info.file_size); return 1; error: ctx->status_msg = "Invalid manifest"; return -1; }
WSObj & WSObjDict_JSON::at(string const &key) { try { return *data.at(key); } catch (std::out_of_range) { struct json_token * tok = find_json_token(token, key.c_str()); if (tok == NULL) throw WSOutOfIndexException(); auto p = WSObj_JSON::factory(tok); auto rawp = p.get(); data[key] = move(p); return *rawp; } }
int sj_conf_get_bool(struct json_token *toks, const char *key, const char *acl, int *val) { struct json_token *tok = find_json_token(toks, key); int result = 0; if (tok == NULL) { LOG(LL_VERBOSE_DEBUG, ("key [%s] not found", key)); } else if (!sj_conf_check_access(key, acl)) { LOG(LL_ERROR, ("Setting key [%s] is not allowed", key)); } else if (tok->type != JSON_TYPE_TRUE && tok->type != JSON_TYPE_FALSE) { LOG(LL_ERROR, ("key [%s] is not boolean", key)); } else { *val = tok->type == JSON_TYPE_TRUE ? 1 : 0; LOG(LL_DEBUG, ("Loaded: %s=%s", key, (*val ? "true" : "false"))); result = 1; } return result; }
int sj_conf_get_int(struct json_token *toks, const char *key, const char *acl, int *val) { struct json_token *tok = find_json_token(toks, key); int result = 0; if (tok == NULL) { LOG(LL_VERBOSE_DEBUG, ("key [%s] not found", key)); } else if (!sj_conf_check_access(key, acl)) { LOG(LL_ERROR, ("Setting key [%s] is not allowed", key)); } else if (tok->type != JSON_TYPE_NUMBER) { LOG(LL_ERROR, ("key [%s] is not numeric", key)); } else { *val = strtod(tok->ptr, NULL); LOG(LL_DEBUG, ("Loaded: %s=%d", key, *val)); result = 1; } return result; }
int main(void) { // static const char *str = " { foo: 1, bar: 2 } "; static const char *str = "{\"array\": [1,2,3],\"boolean\": true,\"null\": null,\"number\": 123,\"object\": {\"a\": \"b\",\"c\": \"d\",\"e\": \"f\"},\"string\": \"Hello World\"}"; struct json_token *arr, *tok; // Tokenize json string, fill in tokens array arr = json_parse(str, strlen(str)); printf("status - %s\n", arr ? "PASS" : "FAIL"); #if 0 // Search for parameter "bar" and print it's value tok = find_json_token(arr, "object[0]"); printf("Value - [%.*s]\n", tok->len, tok->ptr); #endif // Do not forget to free allocated tokens array free(arr); return 0; }
WSObj& WSObjArray_JSON::at(int const &index) { try { return *data.at(index); } catch (std::out_of_range) { ostringstream indxString; indxString << "[" << index << "]"; struct json_token *tok = find_json_token(token, indxString.str().c_str()); if (tok == NULL) throw WSOutOfIndexException(); auto p = WSObj_JSON::factory(tok); auto rawp = p.get(); data[index] = move(p); return *rawp; } }
static void channel_load(struct json_token* tokens, const char* kind, struct channel* channel) { char path[256]; long active = 0; const struct json_token* token; // LOG(("channel_load> %s\n", kind)); snprintf(path, sizeof(path), EFFECTS ".%s." ALL, kind); token = find_json_token(tokens, path); if (token) { int i; for (i = 0; i < channel->num_effects && i < token->num_desc; i++) { snprintf(path, sizeof(path), EFFECTS ".%s." ALL "[%d]" ARGUMENT, kind, i); load_long(tokens, path, &channel->effects[i]->argument); snprintf(path, sizeof(path), EFFECTS ".%s." ALL "[%d]" IS_SSAVER, kind, i); load_long(tokens, path, &channel->effects[i]->screen_saver); if (channel == &channel_panels) { int j; for (j = 0; j < NUM_PANELS/3; j++) { snprintf(path, sizeof(path), EFFECTS ".%s." ALL "[%d]" COLOR "[%d]", kind, i, j); load_long(tokens, path, &channel->effects[i]->color_arg.colors[j].value); } } else { snprintf(path, sizeof(path), EFFECTS ".%s." ALL "[%d]" COLOR, kind, i); load_long(tokens, path, &channel->effects[i]->color_arg.color.value); } } } snprintf(path, sizeof(path), EFFECTS ".%s." ACTIVE, kind); load_long(tokens, path, &active); if (active < channel->num_effects && channel->effects[active]->name) { channel->active = active; } }
/* * Parse JSON-RPC reply contained in `buf`, `len` into JSON tokens array * `toks`, `max_toks`. If buffer contains valid reply, `reply` structure is * populated. The result of RPC call is located in `reply.result`. On error, * `error` structure is populated. Returns: the result of calling * `parse_json(buf, len, toks, max_toks)`. */ int ns_rpc_parse_reply(const char *buf, int len, struct json_token *toks, int max_toks, struct ns_rpc_reply *rep, struct ns_rpc_error *er) { int n = parse_json(buf, len, toks, max_toks); memset(rep, 0, sizeof(*rep)); memset(er, 0, sizeof(*er)); if (n > 0) { if ((rep->result = find_json_token(toks, "result")) != NULL) { rep->message = toks; rep->id = find_json_token(toks, "id"); } else { er->message = toks; er->id = find_json_token(toks, "id"); er->error_code = find_json_token(toks, "error.code"); er->error_message = find_json_token(toks, "error.message"); er->error_data = find_json_token(toks, "error.data"); } } return n; }
int main() { m2x_context ctx; struct json_token *arr = NULL, *tok = NULL, *tok2 = NULL; int i, len; m2x_response response; char buf[40]; m2x_open(M2X_KEY, &ctx); response = m2x_device_list(&ctx, ""); printf("Response Status Code: %d\n", response.status); if (m2x_is_success(&response)) { arr = (struct json_token *) response.data; printf("Total: %d\n", parse_integer(find_json_token(arr, "body.total"))); printf("Pages: %d\n", parse_integer(find_json_token(arr, "body.pages"))); printf("Limit: %d\n\n", parse_integer(find_json_token(arr, "body.limit"))); tok = find_json_token(arr, "body.devices"); if (tok) { i = 0; while (1) { sprintf(buf, "[%d].id", i); tok2 = find_json_token(tok, buf); if (!tok2) { break; } print_token_as_string("Device ID: ", tok2); sprintf(buf, "[%d].name", i); tok2 = find_json_token(tok, buf); print_token_as_string("Device Name: ", tok2); printf("\n"); i++; } } } m2x_release_response(&ctx, &response); m2x_close(&ctx); return 0; }
int WebController::HandleJsonRequest(struct mg_connection *conn, const char *object, const char *func) { json_token *data = NULL; json_token *paramtoken; char *content; int params; int ret; content = strndup(conn->content, conn->content_len); debug("%s",content); free(content); data = parse_json2(conn->content, conn->content_len); if (data == NULL) { debug("parsing api request failed"); return MG_FALSE; } params = 0; paramtoken = find_json_token(data, "params"); if (paramtoken != NULL) { if (paramtoken->type == JSON_TYPE_OBJECT) { params = 1; } else if (paramtoken->type == JSON_TYPE_ARRAY) { params = paramtoken->num_desc; } else { params = 1; } } //Reset global response string gp_response[0] = '\0'; //gp_response = (char*) malloc(sizeof(char) * ( MAX_LINE)); ret = 0; if (!strcmp("kmx", object)) { if (FUNC_SIGP("loadGlobalFile", 2)) { int fileType = -1; char * file = NULL; toki(paramtoken + 1, &fileType); toks(paramtoken + 2, &file, 0); if (file != NULL) { if(strlen(file) > 0){ if(fileType == 1){ this->LoadGcode(file); } else if(fileType == 2){ this->LoadMachineConfiguration(file); } } free(file); } } else if(FUNC_SIGP("listDir", 1)){ ListDir(paramtoken); } else if (FUNC_SIGP("jog", 2)) { int axis; int speed; toki(paramtoken + 1, &axis); toki(paramtoken + 2, &speed); this->Jog(axis, speed); } else if (FUNC_SIGP("onFeedhold", 0)) { this->Feedhold(); } else if (FUNC_SIGP("onSimulate", 0)) { this->Simulate(); } else if (FUNC_SIGP("onEmergencyStop", 0)) { this->EmergencyStop(); } else if (FUNC_SIGP("onHalt", 0)) { this->Halt(); } else if (FUNC_SIGP("onStep", 0)) { this->Step(); } else if (FUNC_SIGP("onReset", 0)) { this->Reset(); } else if (FUNC_SIGP("onCycleStart", 0)) { this->CycleStart(); } else if(FUNC_SIGP("onUpdateMotionParams", 0)) { this->UpdateMotionParams(); } else if (FUNC_SIGP("onInvokeAction", 1)) { BOOL FlushBeforeUnbufferedOperation = FALSE; int action; toki(paramtoken + 1, &action); ret = this->InvokeAction(action,FlushBeforeUnbufferedOperation); } else if (FUNC_SIGP("onDoErrorMessage", 1)) { char *p1 = NULL; toks(paramtoken, &p1, 0); this->DoErrorMessage(p1); EMIT_RESPONSE("[S]", p1); free(p1); } else { log_info("Function request is not part of API %s",func); } } else { log_info("API not implemented %s",object); } mg_send_header(conn, "Content-Type", "application/json"); //Need to send some data or connection will not be closed if (gp_response[0] == '\0') { EMIT_RESPONSE("N"); } mg_printf_data(conn, "%s", gp_response); //free(gp_response); free(data); return MG_TRUE; }
static const char *test_errors(void) { struct json_token ar[100]; int size = ARRAY_SIZE(ar); static const char *invalid_tests[] = { "1", "a:3", "\x01", "{:", " { 1", "{a:\"\n\"}", "{a:1x}", "{a:1e}", "{a:.1}", "{a:0.}", "{a:0.e}", "{a:0.e1}", "{a:0.1e}", "{a:\"\\u\" } ", "{a:\"\\yx\"}", "{a:\"\\u111r\"}", NULL }; static const char *incomplete_tests[] = { "", " \r\n\t", "{", " { a", "{a:", "{a:\"", " { a : \"xx", "{a:12", "{a:\"\\uf", "{a:\"\\uff", "{a:\"\\ufff", "{a:\"\\uffff", "{a:\"\\uffff\"", "{a:\"\\uffff\" ,", NULL }; static const struct { const char *str; int expected_len; } success_tests[] = { { "{}", 2 }, // 2, 3, 4 byte utf-8 chars { "{a:\"\xd0\xb1\xe3\x81\xaf\xf0\xa2\xb3\x82\"}", 15 }, { "{a:\"\\u0006\"}", 12 }, { " { } ", 4 }, { "{a:1}", 5 }, { "{a:1.23}", 8 }, { "{a:1e23}", 8 }, { "{a:1.23e2}", 10 }, { "{a:-123}", 8 }, { "{a:-1.3}", 8 }, { "{a:-1.3e-2}", 11}, { "{a:\"\"}", 6 }, { "{a:\" \\n\\t\\r\"}", 13 }, { " {a:[1]} 123456", 8 }, { " {a:[]} 123456", 7 }, { " {a:[1,2]} 123456", 10 }, { "{a:1,b:2} xxxx", 9 }, { "{a:1,b:{},c:[{}]} xxxx", 17 }, { "{a:true,b:[false,null]} xxxx", 23 }, { NULL, 0 } }; const char *s1 = " { a: 1, b: \"hi there\", c: true, d: false, " " e : null, f: [ 1, -2, 3], g: { \"1\": [], h: [ 7 ] } } "; const char *s2 = "{ a: 1, b: \"hi there\", c: true, d: false, " " e : null, f: [ 1, -2, 3], g: { \"1\": [], h: [ 7 ] } }"; const char *s3 = "{ \"1\": [], h: [ 7 ] }"; int i; ASSERT(parse_json(NULL, 0, NULL, 0) == JSON_STRING_INVALID); for (i = 0; invalid_tests[i] != NULL; i++) { ASSERT(parse_json(invalid_tests[i], strlen(invalid_tests[i]), ar, size) == JSON_STRING_INVALID); } for (i = 0; incomplete_tests[i] != NULL; i++) { ASSERT(parse_json(incomplete_tests[i], strlen(incomplete_tests[i]), ar, size) == JSON_STRING_INCOMPLETE); } for (i = 0; success_tests[i].str != NULL; i++) { ASSERT(parse_json(success_tests[i].str, strlen(success_tests[i].str), ar, size) == success_tests[i].expected_len); } ASSERT(parse_json("{}", 2, ar, 1) == JSON_TOKEN_ARRAY_TOO_SMALL); ASSERT(parse_json("{}", 2, ar, 2) == 2); ASSERT(cmp_token(&ar[0], "{}", JSON_TYPE_OBJECT)); ASSERT(ar[1].type == JSON_TYPE_EOF); ASSERT(parse_json(s1, strlen(s1), NULL, 0) > 0); ASSERT(parse_json(s1, strlen(s1), ar, 10) == JSON_TOKEN_ARRAY_TOO_SMALL); ASSERT(parse_json(s1, strlen(s1), ar, size) > 0); ASSERT(cmp_token(&ar[0], s2, JSON_TYPE_OBJECT)); ASSERT(cmp_token(&ar[1], "a", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[2], "1", JSON_TYPE_NUMBER)); ASSERT(cmp_token(&ar[3], "b", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[4], "hi there", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[5], "c", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[6], "true", JSON_TYPE_TRUE)); ASSERT(cmp_token(&ar[7], "d", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[8], "false", JSON_TYPE_FALSE)); ASSERT(cmp_token(&ar[9], "e", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[10], "null", JSON_TYPE_NULL)); ASSERT(cmp_token(&ar[11], "f", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[12], "[ 1, -2, 3]", JSON_TYPE_ARRAY)); ASSERT(cmp_token(&ar[13], "1", JSON_TYPE_NUMBER)); ASSERT(cmp_token(&ar[14], "-2", JSON_TYPE_NUMBER)); ASSERT(cmp_token(&ar[15], "3", JSON_TYPE_NUMBER)); ASSERT(cmp_token(&ar[16], "g", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[17], s3, JSON_TYPE_OBJECT)); ASSERT(cmp_token(&ar[18], "1", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[19], "[]", JSON_TYPE_ARRAY)); ASSERT(cmp_token(&ar[20], "h", JSON_TYPE_STRING)); ASSERT(cmp_token(&ar[21], "[ 7 ]", JSON_TYPE_ARRAY)); ASSERT(cmp_token(&ar[22], "7", JSON_TYPE_NUMBER)); ASSERT(ar[23].type == JSON_TYPE_EOF); ASSERT(find_json_token(ar, "a") == &ar[2]); ASSERT(find_json_token(ar, "f") == &ar[12]); ASSERT(find_json_token(ar, "g.h") == &ar[21]); ASSERT(find_json_token(ar, "g.h[0]") == &ar[22]); ASSERT(find_json_token(ar, "g.h[1]") == NULL); ASSERT(find_json_token(ar, "g.h1") == NULL); ASSERT(find_json_token(ar, "") == NULL); ASSERT(find_json_token(ar, NULL) == NULL); return NULL; }
void WebController::SetMotionParams(const char *buf, size_t len) { log_info("SetMotionParams"); json_token *jsontoken = NULL; jsontoken = parse_json2(buf, len); char * name = NULL; json_token *token; MOTION_PARAMS *p=Interpreter->GetMotionParams(); double maxAccel,maxVel,countsPerUnit; double breakAngle,collinearTol,cornerTol,facetAngle,tpLookahead; breakAngle = collinearTol = cornerTol = facetAngle = tpLookahead = 0; json_double(jsontoken,"tplanner.breakangle",&breakAngle); json_double(jsontoken,"tplanner.cornertolerance",&cornerTol); json_double(jsontoken,"tplanner.lookahead",&tpLookahead); json_double(jsontoken,"tplanner.collineartolerance",&collinearTol); json_double(jsontoken,"tplanner.facetangle",&facetAngle); p->BreakAngle = breakAngle; p->CollinearTol = collinearTol; p->CornerTol = cornerTol; p->FacetAngle = facetAngle; p->TPLookahead = tpLookahead; //TODO //p->RadiusA = m_RadiusA; //p->RadiusB = m_RadiusB; //p->RadiusC = m_RadiusC; char path[64]; for(int i= 0;i<6;i++){ sprintf(path,"axes[%i]",i); token = find_json_token(jsontoken, path); if(token){ maxAccel = maxVel = countsPerUnit = 0.0; json_str(token,"name",&name,1); json_double(token,"countsPerUnit",&countsPerUnit); json_double(token,"maxAccel",&maxAccel); json_double(token,"maxVel",&maxVel); // default values form KMotionCNCDlg.c maxAccel = maxAccel == 0.0?0.01:maxAccel; maxVel = maxVel == 0.0?0.1:maxVel; //Zero on countPerUnit will abort GCode countsPerUnit = countsPerUnit == 0.0?100.0:countsPerUnit; switch (name[0]) { case 'X': p->CountsPerInchX = countsPerUnit; p->MaxAccelX = maxAccel; p->MaxVelX = maxVel; break; case 'Y': p->CountsPerInchY = countsPerUnit; p->MaxAccelY = maxAccel; p->MaxVelY = maxVel; break; case 'Z': p->CountsPerInchZ = countsPerUnit; p->MaxAccelZ = maxAccel; p->MaxVelZ = maxVel; break; case 'A': p->CountsPerInchA = countsPerUnit; p->MaxAccelA = maxAccel; p->MaxVelA = maxVel; break; case 'B': p->CountsPerInchB = countsPerUnit; p->MaxAccelB = maxAccel; p->MaxVelB = maxVel; break; case 'C': p->CountsPerInchC = countsPerUnit; p->MaxAccelC = maxAccel; p->MaxVelC = maxVel; break; } } else { printf("Failed %s\n",path); } } free(name); //M2-M9,S index 2-9 //userButtons index 11-20 //M100-M119 index 21 -39 //Special actions index 41 -48 setInterpreterActionParams(jsontoken, 0,MAX_MCODE_ACTIONS_M1,"actions[%i]"); setInterpreterActionParams(jsontoken, MCODE_ACTIONS_SPECIAL_OFFSET,MAX_MCODE_ACTIONS_SPECIAL,"specialActions[%i]"); setInterpreterActionParams(jsontoken, MAX_MCODE_ACTIONS_M1,MAX_MCODE_ACTIONS_BUTTONS,"userActions[%i]"); setInterpreterActionParams(jsontoken, MCODE_ACTIONS_M100_OFFSET,MAX_MCODE_ACTIONS_M100,"extendedActions[%i]"); //printf("X %lf, %lf, %lf \n",p->CountsPerInchX,p->MaxAccelX, p->MaxVelX ); //printf("Y %lf, %lf, %lf \n",p->CountsPerInchY,p->MaxAccelY, p->MaxVelY ); //printf("Z %lf, %lf, %lf \n",p->CountsPerInchZ,p->MaxAccelZ, p->MaxVelZ ); //printf("A %lf, %lf, %lf \n",p->CountsPerInchA,p->MaxAccelA, p->MaxVelA ); //printf("B %lf, %lf, %lf \n",p->CountsPerInchB,p->MaxAccelB, p->MaxVelB ); //printf("C %lf, %lf, %lf \n",p->CountsPerInchC,p->MaxAccelC, p->MaxVelC ); //TODO //strcpy(Interpreter->ToolFile,m_ToolFile); //strcpy(Interpreter->SetupFile,m_SetupFile); //strcpy(Interpreter->GeoFile,m_GeoFile); //strcpy(Interpreter->VarsFile,m_VarsFile); //p->DegreesA = m_DegreesA!=0; //p->DegreesB = m_DegreesB!=0; //p->DegreesC = m_DegreesC!=0; p->ArcsToSegs = true;; Interpreter->CoordMotion->SetTPParams(); free(jsontoken); }
/* * Parse control JSON and perform command: * for now only LED on/off is supported. */ static void perform_control_command(const char *data, size_t len) { struct json_token toks[200], *onoff; parse_json(data, len, toks, sizeof(toks)); onoff = find_json_token(toks, "onoff"); set_led(strncmp("[\"on\"]", onoff->ptr, onoff->len) == 0); }
int Eiger::get (sys_t sys, const char *param, char *value, size_t len, int timeout) { const char *functionName = "get"; request_t request; char requestBuf[MAX_MESSAGE_SIZE]; request.data = requestBuf; request.dataLen = sizeof(requestBuf); request.actualLen = epicsSnprintf(request.data, request.dataLen, REQUEST_GET, sysStr[sys], param); response_t response; char responseBuf[MAX_MESSAGE_SIZE]; response.data = responseBuf; response.dataLen = sizeof(responseBuf); if(doRequest(&request, &response, timeout)) { ERR_ARGS("[param=%s] request failed", param); return EXIT_FAILURE; } if(response.code != 200) { ERR_ARGS("[param=%s] server returned error code %d", param, response.code); return EXIT_FAILURE; } if(!value) return EXIT_SUCCESS; struct json_token tokens[MAX_JSON_TOKENS]; struct json_token *valueToken; int err = parse_json(response.content, response.contentLength, tokens, MAX_JSON_TOKENS); if(err < 0) { ERR_ARGS("[param=%s] unable to parse json response\n[%.*s]", param, (int)response.contentLength, response.content); return EXIT_FAILURE; } valueToken = find_json_token(tokens, "value"); if(valueToken == NULL) { ERR_ARGS("[param=%s] unable to find 'value' json field", param); return EXIT_FAILURE; } if((size_t)valueToken->len > ((size_t)(len + 1))) { ERR_ARGS("[param=%s] destination buffer is too short", param); return EXIT_FAILURE; } memcpy((void*)value, (void*)valueToken->ptr, valueToken->len); value[valueToken->len] = '\0'; return EXIT_SUCCESS; }
void http() { CURL *curl; CURLcode res; curl = curl_easy_init(); if(curl) { struct string s; init_string(&s); curl_easy_setopt(curl, CURLOPT_URL, "http://iotser.iots.com.tw:3000/channels/51/feeds/last.json"); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &s); #ifdef SKIP_PEER_VERIFICATION /* * If you want to connect to a site who isn't using a certificate that is * signed by one of the certs in the CA bundle you have, you can skip the * verification of the server's certificate. This makes the connection * A LOT LESS SECURE. * * If you have a CA cert for the server stored someplace else than in the * default bundle, then the CURLOPT_CAPATH option might come handy for * you. */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); #endif #ifdef SKIP_HOSTNAME_VERIFICATION /* * If the site you're connecting to uses a different host name that what * they have mentioned in their server certificate's commonName (or * subjectAltName) fields, libcurl will refuse to connect. You can skip * this check, but this will make the connection less secure. */ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); #endif //curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, function_pt); /* Perform the request, res will get the return code */ res = curl_easy_perform(curl); /* Check for errors */ if(res != CURLE_OK) fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)); // printf("%s\n", s.ptr); struct json_token *arr, *tok; arr = parse_json2(s.ptr, strlen(s.ptr)); tok = find_json_token(arr, "field1"); if(tok!=NULL) sprintf(data,"%.*s",tok->len,tok->ptr); //printf("Value of field1 is: %.*s\n", tok->len, tok->ptr); free(arr); free(s.ptr); /* always cleanup */ curl_easy_cleanup(curl); } curl_global_cleanup(); return 0; }
void WebController::setInterpreterActionParams(struct json_token *jsontoken, int indexOffset, int count, const char* pathTemplate) { double dParam0, dParam1, dParam2, dParam3, dParam4; int action; char path[64]; char *file = NULL; char *name = NULL; json_token *token; for(int i= 0;i<count;i++){ sprintf(path,pathTemplate,i); token = find_json_token(jsontoken, path); if(token){ action = dParam0 = dParam1 = dParam2 = dParam3 = dParam4 = 0; json_int(token,"action",&action); if(action > 0){ json_str(token,"name",&name,64); json_str(token,"file",&file,256); json_double(token,"dParam0",&dParam0); json_double(token,"dParam1",&dParam1); json_double(token,"dParam2",&dParam2); json_double(token,"dParam3",&dParam3); json_double(token,"dParam4",&dParam4); } //M2-M9,S index 2-9 //userButtons index 11-20 //M100-M119 index 21 -39 //Special actions index 41 -48 int actionIndex = indexOffset + i; int actionNameIndex = action > 0 && action < 10?action:10; if(actionNameIndex != 10){ //printf("Set action index %d to %s\n",actionIndex, ACTION_NAMES[actionNameIndex]); } Interpreter->McodeActions[actionIndex].Action = action; Interpreter->McodeActions[actionIndex].dParams[0] = dParam0; Interpreter->McodeActions[actionIndex].dParams[1] = dParam1; Interpreter->McodeActions[actionIndex].dParams[2] = dParam2; Interpreter->McodeActions[actionIndex].dParams[3] = dParam3; Interpreter->McodeActions[actionIndex].dParams[4] = dParam4; //file should be nulled if not set. if(file == NULL || action == 0){ Interpreter->McodeActions[actionIndex].String[0] = 0; } else { if(file[0]=='/'){ //path is absolute strcpy(Interpreter->McodeActions[actionIndex].String, file); } else { //path is relative. make it absolute char absoluteFile[256]; absolutePath(file, absoluteFile); strcpy(Interpreter->McodeActions[actionIndex].String, absoluteFile); } } } else { printf("Failed %s\n", pathTemplate); } } free(file); free(name); }
/**************************************************************************************** Function Name : main Description : Initalize UART, Thread and publish if any status change in the current sensors Parameters : void Return : int, if error in the function returns -1 else 0 ****************************************************************************************/ int main(int argc,char *argv[]) { struct json_token *l_arr, *l_tok; if((uartInit(argv[1])) == 0) { while(1) { if (g_uart0_filestream != -1) { char l_rxBuffer[150]; int l_rxLength = read(g_uart0_filestream,(void*)l_rxBuffer, 150); if (l_rxLength > 0) { l_rxBuffer[l_rxLength] = '\0'; } printf("%c\n",l_rxLength[122]); /* Data Format: {"LOAD_1":value,"LOAD_2":value,"current_1":value "energy_1:value,"current_2":value,"current_3":value, "energy_2":value"} */ //wait for complete data to be recived and process only that if((l_rxLength > 32) && (l_rxBuffer[l_rxLength-1] == '}') && (l_rxBuffer[0] == '{')){ int l_load_1,l_load_2; char l_current_1_str[5]; char l_energy_1_str[5]; char l_current_2_str[5]; char l_energy_2_str[5]; char l_current_3_str[5]; char l_energy_3_str[5]; char l_load_1_str[2]; char l_load_2_str[2]; float l_sensor1_value,l_sensor2_value,l_sensor3_value,l_sensor4_value,l_sensor5_value,l_sensor6_value; l_arr = parse_json2(l_rxBuffer, strlen(l_rxBuffer)); l_tok = find_json_token(l_arr, "LOAD_1"); sprintf(l_load_1_str,"%.*s",l_tok->len,l_tok->ptr); l_load_1 = atof(l_load_1_str); l_tok = find_json_token(l_arr, "LOAD_2"); sprintf(l_load_2_str,"%.*s",l_tok->len,l_tok->ptr); l_load_2 = atof(l_load_2_str); l_tok = find_json_token(l_arr, "current_1"); sprintf(l_current_1_str,"%.*s",l_tok->len,l_tok->ptr); l_sensor1_value = atof(l_current_1_str); l_tok = find_json_token(l_arr, "energy_1"); sprintf(l_energy_1_str,"%.*s",l_tok->len,l_tok->ptr); l_sensor2_value = atof(l_energy_1_str); l_tok = find_json_token(l_arr, "current_2"); sprintf(l_current_2_str,"%.*s",l_tok->len,l_tok->ptr); l_sensor3_value = atof(l_current_2_str); l_tok = find_json_token(l_arr, "energy_2"); sprintf(l_energy_2_str,"%.*s",l_tok->len,l_tok->ptr); l_sensor4_value = atof(l_energy_2_str); l_tok = find_json_token(l_arr, "current_2"); sprintf(l_current_3_str,"%.*s",l_tok->len,l_tok->ptr); l_sensor5_value = atof(l_current_3_str); l_tok = find_json_token(l_arr, "energy_2"); sprintf(l_energy_3_str,"%.*s",l_tok->len,l_tok->ptr); l_sensor6_value = atof(l_energy_3_str); prepare_json_data(l_load_1,l_load_2,l_sensor1_value,l_sensor2_value,l_sensor3_value,l_sensor4_value,l_sensor5_value,l_sensor6_value); pubnub_publishStatus(g_jsonResponse); memset(g_jsonResponse, 0, sizeof(g_jsonResponse)); free(l_arr); } } usleep(500000); } //Close the UART Connection close(g_uart0_filestream); } else { printf("UART Initialization Failed, Aborting"); return -1; } return 0; }