コード例 #1
0
ファイル: events.c プロジェクト: Johan-M/pilight
void *events_clientize(void *param) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	unsigned int failures = 0;
	while(loop && failures <= 5) {
		struct ssdp_list_t *ssdp_list = NULL;
		int standalone = 0;
		settings_find_number("standalone", &standalone);
		if(ssdp_seek(&ssdp_list) == -1 || standalone == 1) {
			logprintf(LOG_DEBUG, "no pilight ssdp connections found");
			char server[16] = "127.0.0.1";
			if((sockfd = socket_connect(server, (unsigned short)socket_get_port())) == -1) {
				logprintf(LOG_DEBUG, "could not connect to pilight-daemon");
				failures++;
				continue;
			}
		} else {
			if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
				logprintf(LOG_DEBUG, "could not connect to pilight-daemon");
				failures++;
				continue;
			}
		}
		if(ssdp_list) {
			ssdp_free(ssdp_list);
		}

		struct JsonNode *jclient = json_mkobject();
		struct JsonNode *joptions = json_mkobject();
		json_append_member(jclient, "action", json_mkstring("identify"));
		json_append_member(joptions, "config", json_mknumber(1, 0));
		json_append_member(jclient, "options", joptions);
		json_append_member(jclient, "media", json_mkstring("all"));
		char *out = json_stringify(jclient, NULL);
		socket_write(sockfd, out);
		json_free(out);
		json_delete(jclient);

		if(socket_read(sockfd, &recvBuff, 0) != 0
			 || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
				failures++;
			continue;
		}
		failures = 0;
		while(loop) {
			if(socket_read(sockfd, &recvBuff, 0) != 0) {
				break;
			} else {
				events_queue(recvBuff);
			}
		}
	}

	if(recvBuff) {
		FREE(recvBuff);
		recvBuff = NULL;
	}
	socket_close(sockfd);
	return 0;
}
コード例 #2
0
ファイル: config.c プロジェクト: git-developer/pilight
int config_write(int level, const char *media) {
    logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

    struct JsonNode *root = json_mkobject();
    FILE *fp;

    sort_list(0);
    struct config_t *listeners = config;
    while(listeners) {
        if(listeners->sync) {
            struct JsonNode *child = listeners->sync(level, media);
            if(child != NULL) {
                json_append_member(root, listeners->name, child);
            }
        }
        listeners = listeners->next;
    }

    /* Overwrite config file with proper format */
    if(!(fp = fopen(configfile, "w+"))) {
        logprintf(LOG_ERR, "cannot write config file: %s", configfile);
        return EXIT_FAILURE;
    }
    fseek(fp, 0L, SEEK_SET);
    char *content = json_stringify(root, "\t");
    fwrite(content, sizeof(char), strlen(content), fp);
    fclose(fp);
    json_free(content);
    json_delete(root);
    return EXIT_SUCCESS;
}
コード例 #3
0
ファイル: gpio_switch.c プロジェクト: pilight/pilight
static struct threadqueue_t *initDev(JsonNode *jdevice) {
	char *platform = GPIO_PLATFORM;

	if(config_setting_get_string("gpio-platform", 0, &platform) != 0) {
		logprintf(LOG_ERR, "no gpio-platform configured");
		return NULL;
	}
	if(strcmp(platform, "none") == 0) {
		FREE(platform);
		logprintf(LOG_ERR, "no gpio-platform configured");
		return NULL;
	}
	if(wiringXSetup(platform, logprintf1) < 0) {
		FREE(platform);
		return NULL;
	}
	FREE(platform);

	loop = 1;
	char *output = json_stringify(jdevice, NULL);
	JsonNode *json = json_decode(output);
	json_free(output);

	struct protocol_threads_t *node = protocol_thread_init(gpio_switch, json);
	return threads_register("gpio_switch", &thread, (void *)node, 0);
}
コード例 #4
0
ファイル: ds18b20.c プロジェクト: knudje/pilight
struct threadqueue_t *ds18b20InitDev(JsonNode *jdevice) {
	ds18b20_loop = 1;
	char *output = json_stringify(jdevice, NULL);
	JsonNode *json = json_decode(output);
	sfree((void *)&output);

	struct protocol_threads_t *node = protocol_thread_init(ds18b20, json);
	return threads_register("ds18b20", &ds18b20Parse, (void *)node, 0);
}
コード例 #5
0
ファイル: xbmc.c プロジェクト: knudje/pilight
struct threadqueue_t *xbmcInitDev(JsonNode *jdevice) {
	xbmc_loop = 1;
	char *output = json_stringify(jdevice, NULL);
	JsonNode *json = json_decode(output);
	sfree((void *)&output);

	struct protocol_threads_t *node = protocol_thread_init(xbmc, json);	
	return threads_register("xbmc", &xbmcParse, (void *)node, 0);
}
コード例 #6
0
ファイル: ds18s20.c プロジェクト: Lyve1981/pilight
static struct threadqueue_t *initDev(JsonNode *jdevice) {
	loop = 1;
	char *output = json_stringify(jdevice, NULL);
	JsonNode *json = json_decode(output);
	json_free(output);

	struct protocol_threads_t *node = protocol_thread_init(ds18s20, json);
	return threads_register("ds18s20", &thread, (void *)node, 0);
}
コード例 #7
0
ファイル: program.c プロジェクト: knudje/pilight
struct threadqueue_t *programInitDev(JsonNode *jdevice) {
	program_loop = 1;
	char *output = json_stringify(jdevice, NULL);
	JsonNode *json = json_decode(output);
	sfree((void *)&output);

	struct protocol_threads_t *node = protocol_thread_init(program, json);	
	return threads_register("program", &programParse, (void *)node, 0);
}
コード例 #8
0
ファイル: geojson-loop.cpp プロジェクト: mapbox/tippecanoe
// XXX duplicated
static void json_context(json_object *j) {
	char *s = json_stringify(j);

	if (strlen(s) >= 500) {
		sprintf(s + 497, "...");
	}

	fprintf(stderr, "In JSON object %s\n", s);
	free(s);  // stringify
}
コード例 #9
0
ファイル: dht22.c プロジェクト: Johan-M/pilight
static struct threadqueue_t *dht22InitDev(JsonNode *jdevice) {
	dht22_loop = 1;
	wiringXSetup();
	char *output = json_stringify(jdevice, NULL);
	JsonNode *json = json_decode(output);
	json_free(output);

	struct protocol_threads_t *node = protocol_thread_init(dht22, json);
	return threads_register("dht22", &dht22Parse, (void *)node, 0);
}
コード例 #10
0
ファイル: registry.c プロジェクト: Lyve1981/pilight
static JsonNode *registry_sync(int level, const char *display) {
	if(registry != NULL) {
		char *content = json_stringify(registry, NULL);
		struct JsonNode *jret = json_decode(content);
		json_free(content);
		return jret;
	} else {
		return NULL;
	}
}
コード例 #11
0
  std::string SourceMap::generate_source_map(Context &ctx) {

    const bool include_sources = ctx.source_map_contents;
    const std::vector<std::string> includes = ctx.include_links;
    const std::vector<char*> sources = ctx.sources;

    JsonNode* json_srcmap = json_mkobject();

    json_append_member(json_srcmap, "version", json_mknumber(3));

    // pass-through sourceRoot option
    if (!ctx.source_map_root.empty()) {
      JsonNode* root = json_mkstring(ctx.source_map_root.c_str());
      json_append_member(json_srcmap, "sourceRoot", root);
    }

    const char *include = file.c_str();
    JsonNode *json_include = json_mkstring(include);
    json_append_member(json_srcmap, "file", json_include);

    JsonNode *json_includes = json_mkarray();
    for (size_t i = 0; i < source_index.size(); ++i) {
      const char *include = includes[source_index[i]].c_str();
      JsonNode *json_include = json_mkstring(include);
      json_append_element(json_includes, json_include);
    }
    json_append_member(json_srcmap, "sources", json_includes);

    if (include_sources) {
      JsonNode *json_contents = json_mkarray();
      for (size_t i = 0; i < source_index.size(); ++i) {
        const char *content = sources[source_index[i]];
        JsonNode *json_content = json_mkstring(content);
        json_append_element(json_contents, json_content);
      }
      if (json_contents->children.head)
        json_append_member(json_srcmap, "sourcesContent", json_contents);
    }

    std::string mappings = serialize_mappings();
    JsonNode *json_mappings = json_mkstring(mappings.c_str());
    json_append_member(json_srcmap, "mappings", json_mappings);

    JsonNode *json_names = json_mkarray();
    // so far we have no implementation for names
    // no problem as we do not alter any identifiers
    json_append_member(json_srcmap, "names", json_names);

    char *str = json_stringify(json_srcmap, "\t");
    std::string result = std::string(str);
    free(str);
    json_delete(json_srcmap);
    return result;
  }
コード例 #12
0
ファイル: registry.c プロジェクト: Lyve1981/pilight
static int registry_parse(JsonNode *root) {
	if(root->tag == JSON_OBJECT) {
		char *content = json_stringify(root, NULL);
		registry = json_decode(content);
		json_free(content);
	} else {
		logprintf(LOG_ERR, "config registry should be of an object type");
		return -1;
	}
	return 0;
}
コード例 #13
0
ファイル: ui.c プロジェクト: imgflo/imgflo
gchar *
form_response(const gchar *protocol, const gchar *command, JsonObject *payload)
{
    JsonObject *response = json_object_new();

    json_object_set_string_member(response, "protocol", protocol);
    json_object_set_string_member(response, "command", command);
    json_object_set_object_member(response, "payload", payload);

    gsize len = 0;
    gchar *data = json_stringify(response, &len);
    return data;
}
コード例 #14
0
ファイル: settings.c プロジェクト: knudje/pilight
int settings_read(void) {
    FILE *fp;
    char *content;
    size_t bytes;
    JsonNode *root;
    struct stat st;

    /* Read JSON config file */
    if(!(fp = fopen(settingsfile, "rb"))) {
        logprintf(LOG_ERR, "cannot read settings file: %s", settingsfile);
        return EXIT_FAILURE;
    }

    fstat(fileno(fp), &st);
    bytes = (size_t)st.st_size;

    if(!(content = calloc(bytes+1, sizeof(char)))) {
        logprintf(LOG_ERR, "out of memory");
        fclose(fp);
        return EXIT_FAILURE;
    }

    if(fread(content, sizeof(char), bytes, fp) == -1) {
        logprintf(LOG_ERR, "cannot read settings file: %s", settingsfile);
    }
    fclose(fp);

    /* Validate JSON and turn into JSON object */
    if(json_validate(content) == false) {
        logprintf(LOG_ERR, "settings are not in a valid json format", content);
        sfree((void *)&content);
        return EXIT_FAILURE;
    }

    root = json_decode(content);

    if(settings_parse(root) != 0) {
        sfree((void *)&content);
        return EXIT_FAILURE;
    }
    char *output = json_stringify(root, "\t");
    settings_write(output);
    json_delete(root);
    sfree((void *)&output);
    sfree((void *)&content);
    return EXIT_SUCCESS;
}
コード例 #15
0
ファイル: gcache.c プロジェクト: Miradorn/recorder
int gcache_json_put(struct gcache *gc, char *keystr, JsonNode *json)
{
	int rc;
	char *js;

	if (gc == NULL)
		return (1);

	if ((js = json_stringify(json, NULL)) == NULL) {
		olog(LOG_ERR, "gcache_json_put: CAN'T stringify JSON");
		return (1);
	}

	rc = gcache_put(gc, keystr, js);
	free(js);
	return (rc);
}
コード例 #16
0
ファイル: stringify.c プロジェクト: qute/json
int
main (void) {
  json_value_t *obj = json_new(JSON_OBJECT, "[object]");
  json_value_t *name = json_new(JSON_STRING, "joseph");
  assert(obj);
  ok("json_new");

  char *src = json_stringify(obj);
  ok("json_stringify");
  assert(src);

  json_destroy(obj);
  assert(0 == obj->size);
  ok("json_destroy");
  obj = NULL;

  ok_done();
  return 0;
}
コード例 #17
0
ファイル: gc.c プロジェクト: knudje/pilight
void gc_handler(int sig) {
	if(((sig == SIGINT || sig == SIGTERM || sig == SIGTSTP) && gc_enable == 1) || 
	  (!(sig == SIGINT || sig == SIGTERM || sig == SIGTSTP) && gc_enable == 0)) {
		if(configfile != NULL && gc_enable == 1) {
			gc_enable = 0;	
			JsonNode *joutput = config2json(-1);
			char *output = json_stringify(joutput, "\t");
			config_write(output);
			json_delete(joutput);
			sfree((void *)&output);
			joutput = NULL;
			sfree((void *)&configfile);
			configfile = NULL;
		}
		gc_enable = 0;	
		config_gc();	
		gc_run();
	}
}
コード例 #18
0
ファイル: evaluator.cpp プロジェクト: mapbox/tippecanoe
bool evaluate(std::map<std::string, mvt_value> const &feature, std::string const &layer, json_object *filter, std::set<std::string> &exclude_attributes) {
	if (filter == NULL || filter->type != JSON_HASH) {
		fprintf(stderr, "Error: filter is not a hash: %s\n", json_stringify(filter));
		exit(EXIT_FAILURE);
	}

	bool ok = true;
	json_object *f;

	f = json_hash_get(filter, layer.c_str());
	if (ok && f != NULL) {
		ok = eval(feature, f, exclude_attributes);
	}

	f = json_hash_get(filter, "*");
	if (ok && f != NULL) {
		ok = eval(feature, f, exclude_attributes);
	}

	return ok;
}
コード例 #19
0
ファイル: receive.c プロジェクト: Lyve1981/pilight
int main(int argc, char **argv) {
	// memtrack();

	atomicinit();
	gc_attach(main_gc);

	/* Catch all exit signals for gc */
	gc_catch();

	log_shell_enable();
	log_file_disable();

	log_level_set(LOG_NOTICE);

	if((progname = MALLOC(16)) == NULL) {
		fprintf(stderr, "out of memory\n");
		exit(EXIT_FAILURE);
	}
	strcpy(progname, "pilight-receive");
	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;

	char *server = NULL;
	unsigned short port = 0;
	unsigned short stats = 0;

	char *args = NULL;

	options_add(&options, 'H', "help", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'V', "version", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'S', "server", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[0-9]{1,4}");
	options_add(&options, 's', "stats", OPTION_NO_VALUE, 0, JSON_NULL, NULL, "[0-9]{1,4}");

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 1, &args);
		if(c == -1)
			break;
		if(c == -2)
			c = 'H';
		switch(c) {
			case 'H':
				printf("\t -H --help\t\t\tdisplay this message\n");
				printf("\t -V --version\t\t\tdisplay version\n");
				printf("\t -S --server=x.x.x.x\t\tconnect to server address\n");
				printf("\t -P --port=xxxx\t\t\tconnect to server port\n");
				printf("\t -s --stats\t\t\tshow CPU and RAM statistics\n");
				exit(EXIT_SUCCESS);
			break;
			case 'V':
				printf("%s v%s\n", progname, PILIGHT_VERSION);
				exit(EXIT_SUCCESS);
			break;
			case 'S':
				if((server = MALLOC(strlen(args)+1)) == NULL) {
					fprintf(stderr, "out of memory\n");
					exit(EXIT_FAILURE);
				}
				strcpy(server, args);
			break;
			case 'P':
				port = (unsigned short)atoi(args);
			break;
			case 's':
				stats = 1;
			break;
			default:
				printf("Usage: %s -l location -d device\n", progname);
				exit(EXIT_SUCCESS);
			break;
		}
	}
	options_delete(options);

	if(server != NULL && port > 0) {
		if((sockfd = socket_connect(server, port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			return EXIT_FAILURE;
		}
	} else if(ssdp_seek(&ssdp_list) == -1) {
		logprintf(LOG_NOTICE, "no pilight ssdp connections found");
		goto close;
	} else {
		if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
	}
	if(ssdp_list != NULL) {
		ssdp_free(ssdp_list);
	}
	if(server != NULL) {
		FREE(server);
	}

	struct JsonNode *jclient = json_mkobject();
	struct JsonNode *joptions = json_mkobject();
	json_append_member(jclient, "action", json_mkstring("identify"));
	json_append_member(joptions, "receiver", json_mknumber(1, 0));
	json_append_member(joptions, "stats", json_mknumber(stats, 0));
	json_append_member(jclient, "options", joptions);
	char *out = json_stringify(jclient, NULL);
	socket_write(sockfd, out);
	json_free(out);
	json_delete(jclient);

	if(socket_read(sockfd, &recvBuff, 0) != 0 ||
     strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
		goto close;
	}

	while(main_loop) {
		if(socket_read(sockfd, &recvBuff, 0) != 0) {
			goto close;
		}
		char **array = NULL;
		unsigned int n = explode(recvBuff, "\n", &array), i = 0;
		for(i=0;i<n;i++) {
			struct JsonNode *jcontent = json_decode(array[i]);
			struct JsonNode *jtype = json_find_member(jcontent, "type");
			if(jtype != NULL) {
				json_remove_from_parent(jtype);
				json_delete(jtype);
			}
			char *content = json_stringify(jcontent, "\t");
			printf("%s\n", content);
			json_delete(jcontent);
			json_free(content);
		}
		array_free(&array, n);
	}

close:
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(recvBuff != NULL) {
		FREE(recvBuff);
		recvBuff = NULL;
	}
	options_gc();
	log_shell_disable();
	log_gc();
	FREE(progname);
	return EXIT_SUCCESS;
}
コード例 #20
0
ファイル: receive.c プロジェクト: knudje/pilight
int main(int argc, char **argv) {

	log_shell_enable();
	log_file_disable();

	log_level_set(LOG_NOTICE);

	progname = malloc(16);
	if(!progname) {
		logprintf(LOG_ERR, "out of memory");
		exit(EXIT_FAILURE);
	}
	strcpy(progname, "pilight-receive");
	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;

	JsonNode *json = NULL;

	char *server = NULL;
	unsigned short port = 0;

    int sockfd = 0;
    char *recvBuff = NULL;
	char *message = NULL;
	char *args = NULL;
	steps_t steps = WELCOME;

	options_add(&options, 'H', "help", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'V', "version", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'S', "server", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[0-9]{1,4}");

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 1, &args);
		if(c == -1)
			break;
		if(c == -2)
			c = 'H';
		switch(c) {
			case 'H':
				printf("\t -H --help\t\t\tdisplay this message\n");
				printf("\t -V --version\t\t\tdisplay version\n");
				printf("\t -S --server=x.x.x.x\t\tconnect to server address\n");
				printf("\t -P --port=xxxx\t\t\tconnect to server port\n");
				exit(EXIT_SUCCESS);
			break;
			case 'V':
				printf("%s %s\n", progname, VERSION);
				exit(EXIT_SUCCESS);
			break;
			case 'S':
				server = realloc(server, strlen(args)+1);
				memset(server, '\0', strlen(args)+1);
				if(!server) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(server, args);
			break;
			case 'P':
				port = (unsigned short)atoi(args);
			break;
			default:
				printf("Usage: %s -l location -d device\n", progname);
				exit(EXIT_SUCCESS);
			break;
		}
	}
	options_delete(options);

	if(server && port > 0) {
		if((sockfd = socket_connect(server, port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			return EXIT_FAILURE;
		}
	} else if(ssdp_seek(&ssdp_list) == -1) {
		logprintf(LOG_ERR, "no pilight ssdp connections found");
		goto close;
	} else {
		if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
	}
	if(ssdp_list) {
		ssdp_free(ssdp_list);
	}
	if(server) {
		sfree((void *)&server);
	}

	while(1) {
		if(steps > WELCOME) {
			if((recvBuff = socket_read(sockfd)) == NULL) {
				goto close;
			}
		}
		switch(steps) {
			case WELCOME:
				socket_write(sockfd, "{\"message\":\"client receiver\"}");
				steps=IDENTIFY;
			break;
			case IDENTIFY:
				//extract the message
				json = json_decode(recvBuff);
				json_find_string(json, "message", &message);
				if(strcmp(message, "accept client") == 0) {
					steps=RECEIVE;
				} else if(strcmp(message, "reject client") == 0) {
					steps=REJECT;
				}
				//cleanup
				json_delete(json);
				sfree((void *)&recvBuff);
				json = NULL;
				message = NULL;
				recvBuff = NULL;
			break;
			case RECEIVE: {
				char *line = strtok(recvBuff, "\n");
				//for each line
				while(line) {
					json = json_decode(line);
					char *output = json_stringify(json, "\t");
					printf("%s\n", output);
					sfree((void *)&output);
					json_delete(json);
					line = strtok(NULL,"\n");
				}
				sfree((void *)&recvBuff);
				sfree((void *)&line);
				recvBuff = NULL;
			} break;
			case REJECT:
			default:
				goto close;
			break;
		}
	}
close:
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(recvBuff) {
		sfree((void *)&recvBuff);
	}
	options_gc();
	log_shell_disable();
	log_gc();
	sfree((void *)&progname);
	return EXIT_SUCCESS;
}
コード例 #21
0
ファイル: receive.c プロジェクト: John1988/pilight
int main(int argc, char **argv) {
	log_shell_enable();
	log_file_disable();

	log_level_set(LOG_NOTICE);

	progname = malloc(16);
	strcpy(progname, "pilight-receive");
	struct options_t *options = NULL;

	JsonNode *json = NULL;

	char *server = malloc(17);
	strcpy(server, "127.0.0.1");
	unsigned short port = PORT;

    int sockfd = 0;
    char *recvBuff = NULL;
	char *message = NULL;
	char *args = NULL;
	steps_t steps = WELCOME;

	options_add(&options, 'H', "help", no_value, 0, NULL);
	options_add(&options, 'V', "version", no_value, 0, NULL);
	options_add(&options, 'S', "server", has_value, 0, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", has_value, 0, "[0-9]{1,4}");

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 1, &args);
		if(c == -1 || c == -2)
			break;
		switch(c) {
			case 'H':
				printf("\t -H --help\t\t\tdisplay this message\n");
				printf("\t -V --version\t\t\tdisplay version\n");
				printf("\t -S --server=%s\t\tconnect to server address\n", server);
				printf("\t -P --port=%d\t\t\tconnect to server port\n", port);
				exit(EXIT_SUCCESS);
			break;
			case 'V':
				printf("%s %s\n", progname, VERSION);
				exit(EXIT_SUCCESS);
			break;
			case 'S':
				server = realloc(server, strlen(args)+1);
				strcpy(server, args);
			break;
			case 'P':
				port = (unsigned short)atoi(args);
			break;
			default:
				printf("Usage: %s -l location -d device\n", progname);
				exit(EXIT_SUCCESS);
			break;
		}
	}

	options_delete(options);
    if((sockfd = socket_connect(server, port)) == -1) {
		logprintf(LOG_ERR, "could not connect to pilight-daemon");
		return EXIT_FAILURE;
	}
	sfree((void *)&server);
	while(1) {
		if(steps > WELCOME) {
			/* Clear the receive buffer again and read the welcome message */
			recvBuff = socket_read(sockfd);
			if(recvBuff == NULL) {
				goto close;
			}
		}
		switch(steps) {
			case WELCOME:
				socket_write(sockfd, "{\"message\":\"client receiver\"}");
				steps=IDENTIFY;
			break;
			case IDENTIFY:
				//extract the message
				json = json_decode(recvBuff);
				json_find_string(json, "message", &message);
				assert(message != NULL);
				if(strcmp(message, "accept client") == 0) {
					steps=RECEIVE;
				} else if(strcmp(message, "reject client") == 0) {
					steps=REJECT;
				} else {
					assert(false);
				}
				//cleanup
				json_delete(json);
				json = NULL;
				message = NULL;
			break;
			case RECEIVE: {
					char *line = strtok(recvBuff, "\n");
					//for each line
					while(line) {
						json = json_decode(recvBuff);
						assert(json != NULL);
						char *output = json_stringify(json, "\t");
						printf("%s\n", output);
						sfree((void *)&output);
						json_delete(json);
						line = strtok(NULL,"\n");
					}
			} break;
			case REJECT:
			default:
				goto close;
			break;
		}
	}
close:
	socket_close(sockfd);

	protocol_gc();
	options_gc();
	sfree((void *)&progname);
	sfree((void *)&server);
	sfree((void *)&message);

return EXIT_SUCCESS;
}
コード例 #22
0
ファイル: ui.c プロジェクト: imgflo/imgflo
static void
ui_connection_handle_message(UiConnection *self,
                const gchar *protocol, const gchar *command, JsonObject *payload,
                SoupWebsocketConnection *ws)
{
    if (g_strcmp0(protocol, "graph") == 0) {
        handle_graph_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "network") == 0) {
        handle_network_message(self, command, payload, ws);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "list") == 0) {
        gint no_components = 0;
        gchar **operation_names = library_list_components(self->component_lib, &no_components);
        for (int i=0; i<no_components; i++) {
            const gchar *op = operation_names[i];
            if (op) {
                JsonObject *component = library_get_component(self->component_lib, op);
                send_response(ws, "component", "component", component);
            }
        }
        g_strfreev(operation_names);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "source") == 0) {
        const gchar *name = json_object_get_string_member(payload, "name");
        gchar *actual_name = library_set_source(self->component_lib,
            name,
            json_object_get_string_member(payload, "code")
        );
        if (actual_name) {
            JsonObject *component = library_get_component(self->component_lib, name);
            send_response(ws, "component", "component", component);
        } else {
            // TODO: error response
        }
        g_free(actual_name);
    } else if (g_strcmp0(protocol, "component") == 0 && g_strcmp0(command, "getsource") == 0) {
        const gchar *name = json_object_get_string_member(payload, "name");


        JsonObject *source_info = json_object_new();
        // TODO: generalize for subgraphs-as-components
        if (g_strcmp0(name, self->main_network) == 0) {

            json_object_set_string_member(source_info, "name", "main"); // FIXME: dont hardcode
            json_object_set_string_member(source_info, "library", "default"); // FIXME: dont hardcode

            Network *n = g_hash_table_lookup(self->network_map, self->main_network);
            g_assert(n);
            JsonObject *g = graph_save_json(n->graph);
            gsize len = 0;
            gchar *code = json_stringify(g, &len);
            g_assert(len);
            json_object_set_string_member(source_info, "language", "json");
            json_object_set_string_member(source_info, "code", code);
        } else {
            json_object_set_string_member(source_info, "name", name);
            gchar *code = library_get_source(self->component_lib, name);
            json_object_set_string_member(source_info, "library", "imgflo");
            json_object_set_string_member(source_info, "language", "c");
            json_object_set_string_member(source_info, "code", code);
        }

        send_response(ws, "component", "source", source_info);

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "getruntime") == 0) {

        JsonObject *runtime = json_object_new();
        json_object_set_string_member(runtime, "version", "0.4"); // protocol version
        json_object_set_string_member(runtime, "type", "imgflo");
        json_object_set_string_member(runtime, "graph", self->main_network);

        JsonArray *capabilities = json_array_new();
        json_array_add_string_element(capabilities, "protocol:component");
        json_array_add_string_element(capabilities, "protocol:graph");
        json_array_add_string_element(capabilities, "protocol:runtime");
        json_array_add_string_element(capabilities, "protocol:network");
        json_array_add_string_element(capabilities, "component:getsource");
        json_array_add_string_element(capabilities, "component:setsource");
        json_object_set_array_member(runtime, "capabilities", capabilities);

        send_response(ws, "runtime", "runtime", runtime);

        if (self->main_network) {
            send_ports(g_hash_table_lookup(self->network_map, self->main_network), ws);
        }

    } else if (g_strcmp0(protocol, "runtime") == 0 && g_strcmp0(command, "packet") == 0) {
        gchar *graph_id = g_strdup(json_object_get_string_member(payload, "graph"));
        const gchar *port = json_object_get_string_member(payload, "port");
        const gchar *event = json_object_get_string_member(payload, "event");
        if (!graph_id) {
            // NoFlo RemoteSubGraph currently does not send graph info
            graph_id = g_strdup(self->main_network);
        }
        Network *network = (graph_id) ? g_hash_table_lookup(self->network_map, graph_id) : NULL;
        g_free(graph_id);
        g_return_if_fail(network);

        if (g_strcmp0(event, "data") == 0) {
            GValue data = G_VALUE_INIT;
            json_node_get_value(json_object_get_member(payload, "payload"), &data);
            network_send_packet(network, port, &data);
        } else {
            // TODO: support connect/disconnect?
            imgflo_warning("Unknown runtime:packet event: %s", event);
        }
    } else {
        imgflo_warning("Unhandled message: protocol='%s', command='%s'", protocol, command);
    }
}
コード例 #23
0
ファイル: jo.c プロジェクト: imjerrybao/jo
char *stringify(JsonNode *json, int flags)
{
	int pretty = flags & FLAG_PRETTY;

	return json_stringify(json, (pretty) ? SPACER : NULL);
}
コード例 #24
0
ファイル: send.c プロジェクト: sieren/433.92-Raspberry-Pi
int main(int argc, char **argv) {

	disable_file_log();
	enable_shell_log();
	set_loglevel(LOG_NOTICE);

	progname = malloc((10*sizeof(char))+1);
	progname = strdup("433-send");

	options = malloc(255*sizeof(struct options_t));

	int sockfd = 0;
    char *recvBuff = NULL;
    char *message;
	steps_t steps = WELCOME;

	/* Hold the name of the protocol */
	char protobuffer[25] = "\0";
	int i;
	/* Does this protocol exists */
	int match = 0;

	/* Do we need to print the help */
	int help = 0;
	/* Do we need to print the version */
	int version = 0;
	/* Do we need to print the protocol help */
	int protohelp = 0;

	char server[16] = "127.0.0.1";
	unsigned short port = PORT;
	
	/* Hold the final protocol struct */
	protocol_t *protocol = NULL;

	JsonNode *json = json_mkobject();
	JsonNode *code = json_mkobject();

	/* Define all CLI arguments of this program */
	addOption(&options, 'H', "help", no_value, 0, NULL);
	addOption(&options, 'V', "version", no_value, 0, NULL);
	addOption(&options, 'p', "protocol", has_value, 0, NULL);
	addOption(&options, 'S', "server", has_value, 0, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	addOption(&options, 'P', "port", has_value, 0, "[0-9]{1,4}");

	/* Initialize peripheral modules */
	hw_init();

	/* Get the protocol to be used */
	while (1) {
		int c;
		c = getOptions(&options, argc, argv, 0);
		if (c == -1)
			break;
		switch(c) {
			case 'p':
				if(strlen(optarg) == 0) {
					logprintf(LOG_ERR, "options '-p' and '--protocol' require an argument");
					exit(EXIT_FAILURE);
				} else {
					strcpy(protobuffer, optarg);
				}
			break;
			case 'V':
				version = 1;
			break;
			case 'H':
				help = 1;
			break;
			case 'S':
				strcpy(server, optarg);
			break;
			case 'P':
				port = (unsigned short)atoi(optarg);
			break;
			default:;
		}
	}

	/* Check if a protocol was given */
	if(strlen(protobuffer) > 0 && strcmp(protobuffer,"-v") != 0) {
		if(strlen(protobuffer) > 0 && version) {
			printf("-p and -V cannot be combined\n");
		} else {
			for(i=0; i<protocols.nr; ++i) {
				protocol = protocols.listeners[i];
				/* Check if the protocol exists */
				if(protocol_has_device(&protocol, protobuffer) == 0 && match == 0 && protocol->createCode != NULL) {
					match=1;
					/* Check if the protocol requires specific CLI arguments
					   and merge them with the main CLI arguments */
					if(protocol->options != NULL && help == 0) {
						mergeOptions(&options, &protocol->options);
					} else if(help == 1) {
						protohelp=1;
					}
					break;
				}
			}
			/* If no protocols matches the requested protocol */
			if(!match) {
				logprintf(LOG_ERR, "this protocol is not supported");
			}
		}
	}

	/* Display help or version information */
	if(version == 1) {
		printf("%s %s\n", progname, "1.0");
		return (EXIT_SUCCESS);
	} else if(help == 1 || protohelp == 1 || match == 0) {
		if(protohelp == 1 && match == 1 && protocol->printHelp != NULL)
			printf("Usage: %s -p %s [options]\n", progname, protobuffer);
		else
			printf("Usage: %s -p protocol [options]\n", progname);
		if(help == 1) {
			printf("\t -H --help\t\t\tdisplay this message\n");
			printf("\t -V --version\t\t\tdisplay version\n");
			printf("\t -S --server=%s\t\tconnect to server address\n", server);
			printf("\t -P --port=%d\t\t\tconnect to server port\n", port);
			printf("\t -p --protocol=protocol\t\tthe protocol that you want to control\n");
		}
		if(protohelp == 1 && match == 1 && protocol->printHelp != NULL) {
			printf("\n\t[%s]\n", protobuffer);
			protocol->printHelp();
		} else {
			printf("\nThe supported protocols are:\n");
			for(i=0; i<protocols.nr; ++i) {
				protocol = protocols.listeners[i];
				if(protocol->createCode != NULL) {
					while(protocol->devices != NULL) {
						printf("\t %s\t\t\t",protocol->devices->id);
						if(strlen(protocol->devices->id)<6)
							printf("\t");
						printf("%s\n", protocol->devices->desc);
						protocol->devices = protocol->devices->next;
					}
				}
			}
		}
		return (EXIT_SUCCESS);
	}

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = getOptions(&options, argc, argv, 1);

		if(c == -1)
			break;
	}

	int itmp;
	/* Check if we got sufficient arguments from this protocol */
	while(options != NULL && strlen(options->name) > 0) {
		/* Only send the CLI arguments that belong to this protocol, the protocol name
		   and those that are called by the user */
		if((getOptionIdByName(&protocol->options, options->name, &itmp) == 0 || strcmp(options->name, "protocol") == 0)
		   && strlen(options->value) > 0) {
			json_append_member(code, options->name, json_mkstring(options->value));
		}
		options = options->next;
	}

	if(protocol->createCode(code) == 0) {
		if((sockfd = connect_to_server(strdup(server), port)) == -1) {
			logprintf(LOG_ERR, "could not connect to 433-daemon");
			goto close;
		}

		while(1) {
			/* Clear the receive buffer again and read the welcome message */
			if((recvBuff = socket_read(sockfd)) != NULL) {
				json = json_decode(recvBuff);
				json_find_string(json, "message", &message);
			} else {
				goto close;
			}
			usleep(100);
			switch(steps) {
				case WELCOME:
					if(strcmp(message, "accept connection") == 0) {
						socket_write(sockfd, "{\"message\":\"client sender\"}");
						steps=IDENTIFY;
					}
				case IDENTIFY:
					if(strcmp(message, "accept client") == 0) {
						steps=SEND;
					}
					if(strcmp(message, "reject client") == 0) {
						steps=REJECT;
					}
				case SEND:
					json_delete(json);
					json = json_mkobject();
					json_append_member(json, "message", json_mkstring("send"));
					json_append_member(json, "code", code);
					socket_write(sockfd, json_stringify(json, NULL));
					goto close;
				break;
				case REJECT:
				default:
					goto close;
				break;
			}
		}
	}
close:
	json_delete(json);
	socket_close(sockfd);
return EXIT_SUCCESS;
}
コード例 #25
0
char* attribute_generate_xml(container *attributes, int attrib_count, attr_conf *showattrp,
			struct fte_data *getfiletypep, struct adf_data *attrdescrp, query_array *qa, int outformat)
{
    int		i, j;


    /*** *** ***/
    container *A = _attribute_dissect_query_(qa, attrib_count-1);
    int *container_id = malloc(sizeof(int));
    *container_id = 0;
    struct _attr_ret_ ret = _attribute_build_tree_(attributes, showattrp, A, container_id);

    int		default_filter = 0;

    _attribute_build_items_(ret.C, A, qa, default_filter, attrib_count-1, getfiletypep, attrdescrp);
    _attribute_sort_items_(&ret.C, showattrp->sort, showattrp->flags & sort_reverse);

    buffer	*bout = buffer_init(-1);

    for (i=0; i<vector_size(A); i++)
	{
	    struct _attr_query_element_ *vquery = (struct _attr_query_element_*)vector_get(A,i).ptr;
	    if (vquery->selected)
		{
		    qa->query[vquery->query_pos].hide = 1;
		}
	    else default_filter|= (1<<vquery->filter_id);
	}

    // Hide dato from "all"-query:
    for (i=0; i<qa->n; i++)
	if (qa->query[i].operand == QUERY_DATE)
	    qa->query[i].hide = 1;

    if (outformat==_OUT_FOMRAT_SD_JSON) {
        JsonNode *root = json_mkobject();
        _attribute_print_and_delete_tree_json_(ret.C, 4, showattrp->max_items, root);
        char *tmps = json_stringify(root, "\t");
        bprintf(bout, tmps);
	    free(tmps);
    }
    else {
        bprintf(bout, "<navigation query=\"");
        bsprint_query_with_remove(bout, NULL, qa, 1);
        bprintf(bout, "\">\n");

        _attribute_print_and_delete_tree_xml_(bout, ret.C, 4, showattrp->max_items);
    }

    free(container_id);
    destroy(ret.C);

    for (i=0; i<vector_size(A); i++)
	{
	    struct _attr_query_element_ *vquery = vector_get(A,i).ptr;
	    for (j=0; j<10; j++) if (vquery->w[j]!=NULL) free(vquery->w[j]);
	    free(vquery);
	}
    destroy(A);

    char	*out = buffer_exit(bout);
    #ifdef DEBUG
        printf("%s\n", out);
    #endif

    return out;
    /*** *** ***/

}
コード例 #26
0
ファイル: plview.c プロジェクト: qrti/plview
int main(int argc, char **argv)
{
    unsigned short port = 0;
    char* server = NULL;
    unsigned short stats = 0;

    struct ssdp_list_t *ssdp_list = NULL;
    
    atomicinit();
    gc_attach(main_gc);
    gc_catch();

    if(server != NULL && port > 0) {
        if((sockfd = socket_connect(server, port)) == -1){
            printf("error: could not connect to pilight-daemon\n");
            return EXIT_FAILURE;
        }
    }
    else if(ssdp_seek(&ssdp_list) == -1){
        printf("error: no pilight ssdp connections found\n");
        goto close;
    }
    else{
        if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1){
            printf("error: could not connect to pilight-daemon\n");
            goto close;
        }
    }

    if(ssdp_list != NULL)
        ssdp_free(ssdp_list);

    if(server != NULL)
        FREE(server);

    struct JsonNode *jclient = json_mkobject();
    struct JsonNode *joptions = json_mkobject();
    json_append_member(jclient, "action", json_mkstring("identify"));
    json_append_member(joptions, "receiver", json_mknumber(1, 0));
    json_append_member(joptions, "stats", json_mknumber(stats, 0));
    json_append_member(jclient, "options", joptions);
    char *out = json_stringify(jclient, NULL);
    socket_write(sockfd, out);
    json_free(out);
    json_delete(jclient);

    if(socket_read(sockfd, &recvBuff, 0)!=0 || strcmp(recvBuff, "{\"status\":\"success\"}")!=0)
        goto close;
        
    if(iniInit("config.ini"))                       // get values from config.ini
        goto close;

    display(0, 0, 0);                               // init display

    unsigned short filteropt = 1;
    int lastmin = -1, firstrx = 0;

    while(main_loop){
        if(socket_read(sockfd, &recvBuff, 0) != 0)
            goto close;

        char **array = NULL;
        unsigned int n = explode(recvBuff, "\n", &array), i = 0;

        for(i=0; i<n; i++){
            struct JsonNode *jcontent = json_decode(array[i]);
            struct JsonNode *jtype = json_find_member(jcontent, "type");

            if(jtype != NULL){
                json_remove_from_parent(jtype);
                json_delete(jtype);
            }

            if(filteropt == 1){
                char *pr = NULL;
                double id = 0.0;
                double ch = 0.0;
                
                struct JsonNode *jmessage = json_find_member(jcontent, "message");
                json_find_string(jcontent, "protocol", &pr);
                json_find_number(jmessage, "id", &id);
                json_find_number(jmessage, "channel", &ch);                
                int j = 0;

                for(j=0; j<stations; j++){                                                          // step through protocol filters
                    if(strcmp(station[j].pr, "-")==0 || strcmp(station[j].pr, pr)==0){              // protocol not specified or found
                        if(j == 0){                                                                 // datetime protocol is the first
                            if(firstrx){
                                double min = 0.0;
                                json_find_number(jmessage, "minute", &min); 

                                if((int)min != lastmin){
                                    display(-1, 0.0, 0.0);  
                                    lastmin = (int)min;
                                }                      
                            }                          
                        }                            
                        else if(strcmp(station[j].id, "-")==0 || (int)id==atoi(station[j].id)){     // id not specified or found
                            if(strcmp(station[j].ch, "-")==0  || (int)ch==atoi(station[j].ch)){     // channel not specified or found
                                double temp = 0.0, humi = 0.0;
                                json_find_number(jmessage, "temperature", &temp);
                                json_find_number(jmessage, "humidity", &humi);
                                display(j-1, temp, humi);      
                                firstrx = 1;  
                                break;          
                            }
                        }
                    }
                }
            }
            else{
                char *content = json_stringify(jcontent, "\t");
                printf("%s\n", content);
                json_free(content);
            }

            json_delete(jcontent);
        }

        array_free(&array, n);        
    }

close:
    if(sockfd > 0)
        socket_close(sockfd);

    if(recvBuff != NULL){
        FREE(recvBuff);
        recvBuff = NULL;
    }

    iniClean();

    return EXIT_SUCCESS;
}
コード例 #27
0
ファイル: control.c プロジェクト: Johan-M/pilight
int main(int argc, char **argv) {
	// memtrack();

	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;
	struct devices_t *dev = NULL;
	struct JsonNode *json = NULL;
	struct JsonNode *tmp = NULL;
	char *recvBuff = NULL, *message = NULL, *output = NULL;
	char *device = NULL, *state = NULL, *values = NULL;
	char *server = NULL;
	int has_values = 0, sockfd = 0, hasconfarg = 0;
	unsigned short port = 0, showhelp = 0, showversion = 0;

	log_file_disable();
	log_shell_enable();
	log_level_set(LOG_NOTICE);

	if(!(progname = MALLOC(16))) {
		logprintf(LOG_ERR, "out of memory");
		exit(EXIT_FAILURE);
	}
	strcpy(progname, "pilight-control");

	/* Define all CLI arguments of this program */
	options_add(&options, 'H', "help", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'V', "version", OPTION_NO_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'd', "device", OPTION_HAS_VALUE, 0,  JSON_NULL, NULL, NULL);
	options_add(&options, 's', "state", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'v', "values", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);
	options_add(&options, 'S', "server", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
	options_add(&options, 'P', "port", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[0-9]{1,4}");
	options_add(&options, 'C', "config", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, NULL);

	/* Store all CLI arguments for later usage
	   and also check if the CLI arguments where
	   used correctly by the user. This will also
	   fill all necessary values in the options struct */
	while(1) {
		int c;
		c = options_parse(&options, argc, argv, 1, &optarg);
		if(c == -1)
			break;
		if(c == -2) {
			showhelp = 1;
			break;
		}
		switch(c) {
			case 'H':
				showhelp = 1;
			break;
			case 'V':
				showversion = 1;
			break;
			case 'd':
				if((device = REALLOC(device, strlen(optarg)+1)) == NULL) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(device, optarg);
			break;
			case 's':
				if((state = REALLOC(state, strlen(optarg)+1)) == NULL) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(state, optarg);
			break;
			case 'v':
				if((values = REALLOC(values, strlen(optarg)+1)) == NULL) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(values, optarg);
			break;
			case 'C':
				if(config_set_file(optarg) == EXIT_FAILURE) {
					return EXIT_FAILURE;
				}
				hasconfarg = 1;
			break;
			case 'S':
				if(!(server = REALLOC(server, strlen(optarg)+1))) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(server, optarg);
			break;
			case 'P':
				port = (unsigned short)atoi(optarg);
			break;
			default:
				printf("Usage: %s -l location -d device -s state\n", progname);
				goto close;
			break;
		}
	}
	options_delete(options);

	if(showversion == 1) {
		printf("%s %s\n", progname, PILIGHT_VERSION);
		goto close;
	}
	if(showhelp == 1) {
		printf("\t -H --help\t\t\tdisplay this message\n");
		printf("\t -V --version\t\t\tdisplay version\n");
		printf("\t -S --server=x.x.x.x\t\tconnect to server address\n");
		printf("\t -C --config\t\t\tconfig file\n");
		printf("\t -P --port=xxxx\t\t\tconnect to server port\n");
		printf("\t -d --device=device\t\tthe device that you want to control\n");
		printf("\t -s --state=state\t\tthe new state of the device\n");
		printf("\t -v --values=values\t\tspecific comma separated values, e.g.:\n");
		printf("\t\t\t\t\t-v dimlevel=10\n");
		goto close;
	}
	if(device == NULL || state == NULL ||
	   strlen(device) == 0 || strlen(state) == 0) {
		printf("Usage: %s -d device -s state\n", progname);
		goto close;
	}

	if(server && port > 0) {
		if((sockfd = socket_connect(server, port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
	} else if(ssdp_seek(&ssdp_list) == -1) {
		logprintf(LOG_ERR, "no pilight ssdp connections found");
		goto close;
	} else {
		if((sockfd = socket_connect(ssdp_list->ip, ssdp_list->port)) == -1) {
			logprintf(LOG_ERR, "could not connect to pilight-daemon");
			goto close;
		}
	}
	if(ssdp_list) {
		ssdp_free(ssdp_list);
	}

	protocol_init();
	config_init();
	if(hasconfarg == 1) {
		if(config_read() != EXIT_SUCCESS) {
			goto close;
		}
	}

	socket_write(sockfd, "{\"action\":\"identify\"}");
	if(socket_read(sockfd, &recvBuff, 0) != 0
	   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
		goto close;
	}

	json = json_mkobject();
	json_append_member(json, "action", json_mkstring("request config"));
	output = json_stringify(json, NULL);
	socket_write(sockfd, output);
	json_free(output);
	json_delete(json);

	if(socket_read(sockfd, &recvBuff, 0) == 0) {
		if(json_validate(recvBuff) == true) {
			json = json_decode(recvBuff);
			if(json_find_string(json, "message", &message) == 0) {
				if(strcmp(message, "config") == 0) {
					struct JsonNode *jconfig = NULL;
					if((jconfig = json_find_member(json, "config")) != NULL) {
						int match = 1;
						while(match) {
							struct JsonNode *jchilds = json_first_child(jconfig);
							match = 0;
							while(jchilds) {
								if(strcmp(jchilds->key, "devices") != 0) {
									json_remove_from_parent(jchilds);
									tmp = jchilds;
									match = 1;
								}
								jchilds = jchilds->next;
								if(tmp != NULL) {
									json_delete(tmp);
								}
								tmp = NULL;
							}
						}
						config_parse(jconfig);
						if(devices_get(device, &dev) == 0) {
							JsonNode *joutput = json_mkobject();
							JsonNode *jcode = json_mkobject();
							JsonNode *jvalues = json_mkobject();
							json_append_member(jcode, "device", json_mkstring(device));

							if(values != NULL) {
								char **array = NULL;
								unsigned int n = explode(values, ",=", &array), q = 0;
								for(q=0;q<n;q+=2) {
									char *name = MALLOC(strlen(array[q])+1);
									if(name == NULL) {
										logprintf(LOG_ERR, "out of memory\n");
										exit(EXIT_FAILURE);
									}
									strcpy(name, array[q]);
									if(q+1 == n) {
										for(q=0;q<n;q++) {
											FREE(array[q]);
										}
										FREE(array);
										logprintf(LOG_ERR, "\"%s\" is missing a value for device \"%s\"", name, device);
										FREE(name);
										break;
									} else {
										char *val = MALLOC(strlen(array[q+1])+1);
										if(val == NULL) {
											logprintf(LOG_ERR, "out of memory\n");
											exit(EXIT_FAILURE);
										}
										strcpy(val, array[q+1]);
										if(devices_valid_value(device, name, val) == 0) {
											if(isNumeric(val) == EXIT_SUCCESS) {
												char *ptr = strstr(array[q+1], ".");
												int decimals = 0;
												if(ptr != NULL) {
													decimals = (int)(strlen(array[q+1])-((size_t)(ptr-array[q+1])+1));
												}
												json_append_member(jvalues, name, json_mknumber(atof(val), decimals));
											} else {
												json_append_member(jvalues, name, json_mkstring(val));
											}
											has_values = 1;
										} else {
											logprintf(LOG_ERR, "\"%s\" is an invalid value for device \"%s\"", name, device);
											for(q=0;q<n;q++) {
												FREE(array[q]);
											}
											FREE(array);
											FREE(name);
											json_delete(json);
											goto close;
										}
									}
									FREE(name);
								}
								unsigned int z = 0;
								for(z=q;z<n;z++) {
									FREE(array[z]);
								}
								if(n > 0) {
									FREE(array);
								}
							}

							if(devices_valid_state(device, state) == 0) {
								json_append_member(jcode, "state", json_mkstring(state));
							} else {
								logprintf(LOG_ERR, "\"%s\" is an invalid state for device \"%s\"", state, device);
								json_delete(json);
								goto close;
							}

							if(has_values == 1) {
								json_append_member(jcode, "values", jvalues);
							} else {
								json_delete(jvalues);
							}
							json_append_member(joutput, "action", json_mkstring("control"));
							json_append_member(joutput, "code", jcode);
							output = json_stringify(joutput, NULL);
							socket_write(sockfd, output);
							json_free(output);
							json_delete(joutput);
							if(socket_read(sockfd, &recvBuff, 0) != 0
							   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
								logprintf(LOG_ERR, "failed to control %s", device);
							}
						} else {
							logprintf(LOG_ERR, "the device \"%s\" does not exist", device);
							json_delete(json);
							goto close;
						}
					}
				}
			}
			json_delete(json);
		}
	}
close:
	if(recvBuff) {
		FREE(recvBuff);
	}
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(server != NULL) {
		FREE(server);
	}
	if(device != NULL) {
		FREE(device);
	}
	if(state != NULL) {
		FREE(state);
	}
	if(values != NULL) {
		FREE(values);
	}
	log_shell_disable();
	socket_gc();
	config_gc();
	protocol_gc();
	options_gc();
	event_operator_gc();
	event_action_gc();
	dso_gc();
	log_gc();
	threads_gc();
	gc_clear();
	FREE(progname);
	xfree();

	return EXIT_SUCCESS;
}
コード例 #28
0
ファイル: main.c プロジェクト: qute/json
int
main (int argc, char **argv) {
  json_value_t *value = NULL;
  json_value_t *root = NULL;
  char *filename = NULL;
  char *key = NULL;
  char *src = NULL;
  int i = 0;

#define usage() printf("usage: %s <file> [key]\n", argv[0]);

  if (argc < 2) {
    usage();
    return 1;
  }

  // parse opts
  for (i = 1; i < argc; ++i) {
    if (EQ(argv[i], "--each")) {
      each = 1;
    } else if (EQ(argv[i], "--stream")) {
      stream = 1;
    } else if (EQ(argv[i], "--help")) {
      usage();
      return 0;
    }
  }

  if (ferror(stdin)) {
    return 1;
  } else if (0 == isatty(0)) {
    filename = "<stdin>";
    tty = 1;
    if (argc > 1 && '-' != argv[1][0]) {
      key = argv[1];
    }
  } else {
    filename = argv[1];
    if (0 != fs_exists(filename)) {
      printf("E: not found - `%s'\n", filename);
      return 1;
    }

    src = fs_read(filename);
    if (NULL == src) {
      return 1;
    }

    if (argc > 2 && '-' !=  argv[2][0]) {
      key = argv[2];
    }
  }

  do {
    if (tty) {
      src = read_stdin();
    }

    if (NULL == src || 0 == strlen(src)) {
      break;
    }

    // proxy source if just streaming stdin
    // without a key lookup
    if (NULL == key && stream) {
      printf("%s", src);
      continue;
    }

    root = json_parse(filename, src);

    if (NULL == root) {
      return 1;
    } else if (root->errno) {
      json_perror(root);
      return 1;
    }

    if (NULL != key) {
      value = json_get(root, key);
      if (NULL == value) {
        return 1;
      }

      free(root);
      root = value;
    } else {
      value = root;
    }

    if (1 == each && JSON_ARRAY == value->type) {
      value = value->values[0];
      while (value) {
        printf("%s\n", json_stringify(value));
        value = value->next;
      }
    } else {
      printf("%s\n", json_stringify(value));
    }

    json_destroy(root);
    free(src);
    value = NULL;
    root = NULL;
    src = NULL;

  } while (tty);

  return 0;
}
コード例 #29
0
ファイル: sass_context.cpp プロジェクト: DealerDotCom/libsass
  static int handle_error(Sass_Context* c_ctx) {
    try {
      throw;
    }
    catch (Exception::Base& e) {
      std::stringstream msg_stream;
      std::string cwd(Sass::File::get_cwd());

      std::string msg_prefix(e.errtype());
      bool got_newline = false;
      msg_stream << msg_prefix << ": ";
      const char* msg = e.what();
      while (msg && *msg) {
        if (*msg == '\r') {
          got_newline = true;
        }
        else if (*msg == '\n') {
          got_newline = true;
        }
        else if (got_newline) {
          msg_stream << std::string(msg_prefix.size() + 2, ' ');
          got_newline = false;
        }
        msg_stream << *msg;
        ++msg;
      }
      if (!got_newline) msg_stream << "\n";
      if (e.import_stack) {
        for (size_t i = 1; i < e.import_stack->size() - 1; ++i) {
          std::string path((*e.import_stack)[i]->imp_path);
          std::string rel_path(Sass::File::abs2rel(path, cwd, cwd));
          msg_stream << std::string(msg_prefix.size() + 2, ' ');
          msg_stream << (i == 1 ? " on line " : " from line ");
          msg_stream << e.pstate.line + 1 << " of " << rel_path << "\n";
        }
      }
      else {
        std::string rel_path(Sass::File::abs2rel(e.pstate.path, cwd, cwd));
        msg_stream << std::string(msg_prefix.size() + 2, ' ');
        msg_stream << " on line " << e.pstate.line + 1 << " of " << rel_path << "\n";
      }

      // now create the code trace (ToDo: maybe have util functions?)
      if (e.pstate.line != std::string::npos && e.pstate.column != std::string::npos) {
        size_t line = e.pstate.line;
        const char* line_beg = e.pstate.src;
        while (line_beg && *line_beg && line) {
          if (*line_beg == '\n') --line;
          ++line_beg;
        }
        const char* line_end = line_beg;
        while (line_end && *line_end && *line_end != '\n') {
          if (*line_end == '\n') break;
          if (*line_end == '\r') break;
          line_end++;
        }
        size_t max_left = 42; size_t max_right = 78;
        size_t move_in = e.pstate.column > max_left ? e.pstate.column - max_left : 0;
        size_t shorten = (line_end - line_beg) - move_in > max_right ?
          (line_end - line_beg) - move_in - max_right : 0;
        msg_stream << ">> " << std::string(line_beg + move_in, line_end - shorten) << "\n";
        msg_stream << "   " << std::string(e.pstate.column - move_in, '-') << "^\n";
      }

      JsonNode* json_err = json_mkobject();
      json_append_member(json_err, "status", json_mknumber(1));
      json_append_member(json_err, "file", json_mkstring(e.pstate.path));
      json_append_member(json_err, "line", json_mknumber((double)(e.pstate.line + 1)));
      json_append_member(json_err, "column", json_mknumber((double)(e.pstate.column + 1)));
      json_append_member(json_err, "message", json_mkstring(e.what()));
      json_append_member(json_err, "formatted", json_mkstream(msg_stream));
      try { c_ctx->error_json = json_stringify(json_err, "  "); }
      catch (...) {}
      c_ctx->error_message = sass_copy_string(msg_stream.str());
      c_ctx->error_text = sass_copy_c_string(e.what());
      c_ctx->error_status = 1;
      c_ctx->error_file = sass_copy_c_string(e.pstate.path);
      c_ctx->error_line = e.pstate.line + 1;
      c_ctx->error_column = e.pstate.column + 1;
      c_ctx->error_src = e.pstate.src;
      c_ctx->output_string = 0;
      c_ctx->source_map_string = 0;
      json_delete(json_err);
    }
    catch (std::bad_alloc& ba) {
      std::stringstream msg_stream;
      JsonNode* json_err = json_mkobject();
      msg_stream << "Unable to allocate memory: " << ba.what() << std::endl;
      json_append_member(json_err, "status", json_mknumber(2));
      json_append_member(json_err, "message", json_mkstring(ba.what()));
      json_append_member(json_err, "formatted", json_mkstream(msg_stream));
      try { c_ctx->error_json = json_stringify(json_err, "  "); }
      catch (...) {}
      c_ctx->error_message = sass_copy_string(msg_stream.str());
      c_ctx->error_text = sass_copy_c_string(ba.what());
      c_ctx->error_status = 2;
      c_ctx->output_string = 0;
      c_ctx->source_map_string = 0;
      json_delete(json_err);
    }
    catch (std::exception& e) {
      std::stringstream msg_stream;
      JsonNode* json_err = json_mkobject();
      msg_stream << "Internal Error: " << e.what() << std::endl;
      json_append_member(json_err, "status", json_mknumber(3));
      json_append_member(json_err, "message", json_mkstring(e.what()));
      json_append_member(json_err, "formatted", json_mkstream(msg_stream));
      try { c_ctx->error_json = json_stringify(json_err, "  "); }
      catch (...) {}
      c_ctx->error_message = sass_copy_string(msg_stream.str());
      c_ctx->error_text = sass_copy_c_string(e.what());
      c_ctx->error_status = 3;
      c_ctx->output_string = 0;
      c_ctx->source_map_string = 0;
      json_delete(json_err);
    }
    catch (std::string& e) {
      std::stringstream msg_stream;
      JsonNode* json_err = json_mkobject();
      msg_stream << "Internal Error: " << e << std::endl;
      json_append_member(json_err, "status", json_mknumber(4));
      json_append_member(json_err, "message", json_mkstring(e.c_str()));
      json_append_member(json_err, "formatted", json_mkstream(msg_stream));
      try { c_ctx->error_json = json_stringify(json_err, "  "); }
      catch (...) {}
      c_ctx->error_message = sass_copy_string(msg_stream.str());
      c_ctx->error_text = sass_copy_c_string(e.c_str());
      c_ctx->error_status = 4;
      c_ctx->output_string = 0;
      c_ctx->source_map_string = 0;
      json_delete(json_err);
    }
    catch (const char* e) {
      std::stringstream msg_stream;
      JsonNode* json_err = json_mkobject();
      msg_stream << "Internal Error: " << e << std::endl;
      json_append_member(json_err, "status", json_mknumber(4));
      json_append_member(json_err, "message", json_mkstring(e));
      json_append_member(json_err, "formatted", json_mkstream(msg_stream));
      try { c_ctx->error_json = json_stringify(json_err, "  "); }
      catch (...) {}
      c_ctx->error_message = sass_copy_string(msg_stream.str());
      c_ctx->error_text = sass_copy_c_string(e);
      c_ctx->error_status = 4;
      c_ctx->output_string = 0;
      c_ctx->source_map_string = 0;
      json_delete(json_err);
    }
    catch (...) {
      std::stringstream msg_stream;
      JsonNode* json_err = json_mkobject();
      msg_stream << "Unknown error occurred" << std::endl;
      json_append_member(json_err, "status", json_mknumber(5));
      json_append_member(json_err, "message", json_mkstring("unknown"));
      try { c_ctx->error_json = json_stringify(json_err, "  "); }
      catch (...) {}
      c_ctx->error_message = sass_copy_string(msg_stream.str());
      c_ctx->error_text = sass_copy_c_string("unknown");
      c_ctx->error_status = 5;
      c_ctx->output_string = 0;
      c_ctx->source_map_string = 0;
      json_delete(json_err);
    }
    return c_ctx->error_status;
  }
コード例 #30
0
ファイル: evaluator.cpp プロジェクト: mapbox/tippecanoe
bool eval(std::map<std::string, mvt_value> const &feature, json_object *f, std::set<std::string> &exclude_attributes) {
	if (f == NULL || f->type != JSON_ARRAY) {
		fprintf(stderr, "Filter is not an array: %s\n", json_stringify(f));
		exit(EXIT_FAILURE);
	}

	if (f->length < 1) {
		fprintf(stderr, "Array too small in filter: %s\n", json_stringify(f));
		exit(EXIT_FAILURE);
	}

	if (f->array[0]->type != JSON_STRING) {
		fprintf(stderr, "Filter operation is not a string: %s\n", json_stringify(f));
		exit(EXIT_FAILURE);
	}

	if (strcmp(f->array[0]->string, "has") == 0 ||
	    strcmp(f->array[0]->string, "!has") == 0) {
		if (f->length != 2) {
			fprintf(stderr, "Wrong number of array elements in filter: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}

		if (strcmp(f->array[0]->string, "has") == 0) {
			if (f->array[1]->type != JSON_STRING) {
				fprintf(stderr, "\"has\" key is not a string: %s\n", json_stringify(f));
				exit(EXIT_FAILURE);
			}
			return feature.count(std::string(f->array[1]->string)) != 0;
		}

		if (strcmp(f->array[0]->string, "!has") == 0) {
			if (f->array[1]->type != JSON_STRING) {
				fprintf(stderr, "\"!has\" key is not a string: %s\n", json_stringify(f));
				exit(EXIT_FAILURE);
			}
			return feature.count(std::string(f->array[1]->string)) == 0;
		}
	}

	if (strcmp(f->array[0]->string, "==") == 0 ||
	    strcmp(f->array[0]->string, "!=") == 0 ||
	    strcmp(f->array[0]->string, ">") == 0 ||
	    strcmp(f->array[0]->string, ">=") == 0 ||
	    strcmp(f->array[0]->string, "<") == 0 ||
	    strcmp(f->array[0]->string, "<=") == 0) {
		if (f->length != 3) {
			fprintf(stderr, "Wrong number of array elements in filter: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}
		if (f->array[1]->type != JSON_STRING) {
			fprintf(stderr, "\"!has\" key is not a string: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}

		auto ff = feature.find(std::string(f->array[1]->string));
		if (ff == feature.end()) {
			static bool warned = false;
			if (!warned) {
				const char *s = json_stringify(f);
				fprintf(stderr, "Warning: attribute not found for comparison: %s\n", s);
				free((void *) s);
				warned = true;
			}
			if (strcmp(f->array[0]->string, "!=") == 0) {
				return true;  //  attributes that aren't found are not equal
			}
			return false;  // not found: comparison is false
		}

		bool fail = false;
		int cmp = compare(ff->second, f->array[2], fail);

		if (fail) {
			static bool warned = false;
			if (!warned) {
				const char *s = json_stringify(f);
				fprintf(stderr, "Warning: mismatched type in comparison: %s\n", s);
				free((void *) s);
				warned = true;
			}
			if (strcmp(f->array[0]->string, "!=") == 0) {
				return true;  // mismatched types are not equal
			}
			return false;
		}

		if (strcmp(f->array[0]->string, "==") == 0) {
			return cmp == 0;
		}
		if (strcmp(f->array[0]->string, "!=") == 0) {
			return cmp != 0;
		}
		if (strcmp(f->array[0]->string, ">") == 0) {
			return cmp > 0;
		}
		if (strcmp(f->array[0]->string, ">=") == 0) {
			return cmp >= 0;
		}
		if (strcmp(f->array[0]->string, "<") == 0) {
			return cmp < 0;
		}
		if (strcmp(f->array[0]->string, "<=") == 0) {
			return cmp <= 0;
		}

		fprintf(stderr, "Internal error: can't happen: %s\n", json_stringify(f));
		exit(EXIT_FAILURE);
	}

	if (strcmp(f->array[0]->string, "all") == 0 ||
	    strcmp(f->array[0]->string, "any") == 0 ||
	    strcmp(f->array[0]->string, "none") == 0) {
		bool v;

		if (strcmp(f->array[0]->string, "all") == 0) {
			v = true;
		} else {
			v = false;
		}

		for (size_t i = 1; i < f->length; i++) {
			bool out = eval(feature, f->array[i], exclude_attributes);

			if (strcmp(f->array[0]->string, "all") == 0) {
				v = v && out;
				if (!v) {
					break;
				}
			} else {
				v = v || out;
				if (v) {
					break;
				}
			}
		}

		if (strcmp(f->array[0]->string, "none") == 0) {
			return !v;
		} else {
			return v;
		}
	}

	if (strcmp(f->array[0]->string, "in") == 0 ||
	    strcmp(f->array[0]->string, "!in") == 0) {
		if (f->length < 2) {
			fprintf(stderr, "Array too small in filter: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}

		if (f->array[1]->type != JSON_STRING) {
			fprintf(stderr, "\"!has\" key is not a string: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}

		auto ff = feature.find(std::string(f->array[1]->string));
		if (ff == feature.end()) {
			static bool warned = false;
			if (!warned) {
				const char *s = json_stringify(f);
				fprintf(stderr, "Warning: attribute not found for comparison: %s\n", s);
				free((void *) s);
				warned = true;
			}
			if (strcmp(f->array[0]->string, "!in") == 0) {
				return true;  // attributes that aren't found are not in
			}
			return false;  // not found: comparison is false
		}

		bool found = false;
		for (size_t i = 2; i < f->length; i++) {
			bool fail = false;
			int cmp = compare(ff->second, f->array[i], fail);

			if (fail) {
				static bool warned = false;
				if (!warned) {
					const char *s = json_stringify(f);
					fprintf(stderr, "Warning: mismatched type in comparison: %s\n", s);
					free((void *) s);
					warned = true;
				}
				cmp = 1;
			}

			if (cmp == 0) {
				found = true;
				break;
			}
		}

		if (strcmp(f->array[0]->string, "in") == 0) {
			return found;
		} else {
			return !found;
		}
	}

	if (strcmp(f->array[0]->string, "attribute-filter") == 0) {
		if (f->length != 3) {
			fprintf(stderr, "Wrong number of array elements in filter: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}

		if (f->array[1]->type != JSON_STRING) {
			fprintf(stderr, "\"attribute-filter\" key is not a string: %s\n", json_stringify(f));
			exit(EXIT_FAILURE);
		}

		bool ok = eval(feature, f->array[2], exclude_attributes);
		if (!ok) {
			exclude_attributes.insert(f->array[1]->string);
		}

		return true;
	}

	fprintf(stderr, "Unknown filter %s\n", json_stringify(f));
	exit(EXIT_FAILURE);
}