Ejemplo n.º 1
0
static JsonNode *line_to_location(char *line)
{
	JsonNode *json, *o, *j;
	char *ghash;
	char tstamp[64], *bp;
	double lat, lon;
	long tst;

	snprintf(tstamp, 21, "%s", line);

	if ((bp = strchr(line, '{')) == NULL)
		return (NULL);

	if ((json = json_decode(bp)) == NULL) {
		return (NULL);
	}

	if ((j = json_find_member(json, "_type")) == NULL) {
		json_delete(json);
		return (NULL);
	}
	if (j->tag != JSON_STRING || strcmp(j->string_, "location") != 0) {
		json_delete(json);
		return (NULL);
	}

	o = json_mkobject();

	if (json_copy_to_object(o, json, FALSE) == FALSE) {
		json_delete(o);
		json_delete(json);
		return (NULL);
	}
	json_delete(json);	/* Done with this -- we've copied it. */

	lat = lon = 0.0;
	if ((j = json_find_member(o, "lat")) != NULL) {
		lat = j->number_;
	}
	if ((j = json_find_member(o, "lon")) != NULL) {
		lon = j->number_;
	}

	if ((ghash = geohash_encode(lat, lon, geohash_prec())) != NULL) {
		json_append_member(o, "ghash", json_mkstring(ghash));
		get_geo(o, ghash);
		free(ghash);
	}

	json_append_member(o, "isorcv", json_mkstring(tstamp));

	tst = 0L;
	if ((j = json_find_member(o, "tst")) != NULL) {
		tst = j->number_;
	}
	json_append_member(o, "isotst", json_mkstring(isotime(tst)));

	return (o);
}
Ejemplo n.º 2
0
static int registry_get_value_recursive(struct JsonNode *root, const char *key, void **value, void **decimals, int type) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	char *sub = strstr(key, ".");
	char *buff = MALLOC(strlen(key)+1);
	strcpy(buff, key);
	if(sub != NULL) {
		int pos = sub-key;
		buff[pos] = '\0';
	}
	struct JsonNode *member = json_find_member(root, buff);
	if(member != NULL) {
		if(member->tag == type) {
			if(type == JSON_NUMBER) {
				*value = (void *)&member->number_;
				*decimals = (void *)&member->decimals_;
			} else if(type == JSON_STRING) {
				*value = (void *)member->string_;
			}
			FREE(buff);
			return 0;
		} else if(member->tag == JSON_OBJECT) {
			if(sub != NULL) {
				int pos = sub-key;
				strcpy(buff, &key[pos+1]);
			}
			int ret = registry_get_value_recursive(member, buff, value, decimals, type);
			FREE(buff);
			return ret;
		}
	}
	FREE(buff);
	return -1;
}
Ejemplo n.º 3
0
int config_parse(JsonNode *root) {
    logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

    struct JsonNode *jconfig = NULL;
    unsigned short error = 0;

    sort_list(1);
    struct config_t *listeners = config;
    while(listeners) {
        if((jconfig = json_find_member(root, listeners->name))) {
            if(listeners->parse) {
                if(listeners->parse(jconfig) == EXIT_FAILURE) {
                    error = 1;
                    break;
                }
            }
        }
        listeners = listeners->next;
    }

    if(error == 1) {
        config_gc();
        return EXIT_FAILURE;
    } else {
        return EXIT_SUCCESS;
    }
}
Ejemplo n.º 4
0
Archivo: jo.c Proyecto: imjerrybao/jo
int json_copy_to_object(JsonNode * obj, JsonNode * object_or_array, int clobber)
{
	JsonNode *node;

	if (obj->tag != JSON_OBJECT && obj->tag != JSON_ARRAY)
		return (FALSE);

	json_foreach(node, object_or_array) {
		if (!clobber & (json_find_member(obj, node->key) != NULL))
			continue;	/* Don't clobber existing keys */
		if (obj->tag == JSON_OBJECT) {
			if (node->tag == JSON_STRING)
				json_append_member(obj, node->key, json_mkstring(node->string_));
			else if (node->tag == JSON_NUMBER)
				json_append_member(obj, node->key, json_mknumber(node->number_));
			else if (node->tag == JSON_BOOL)
				json_append_member(obj, node->key, json_mkbool(node->bool_));
			else if (node->tag == JSON_NULL)
				json_append_member(obj, node->key, json_mknull());
			else
				fprintf(stderr, "PANIC: unhandled JSON type %d\n", node->tag);
		} else if (obj->tag == JSON_ARRAY) {
			if (node->tag == JSON_STRING)
				json_append_element(obj, json_mkstring(node->string_));
			if (node->tag == JSON_NUMBER)
				json_append_element(obj, json_mknumber(node->number_));
			if (node->tag == JSON_BOOL)
				json_append_element(obj, json_mkbool(node->bool_));
			if (node->tag == JSON_NULL)
				json_append_element(obj, json_mknull());
		}
	}
	return (TRUE);
}
Ejemplo n.º 5
0
void csv_output(JsonNode *json, output_type otype, JsonNode *fields)
{
    JsonNode *node, *inttypes;
    JsonNode *arr, *one, *j;
    short virgin = 1;

    /* Prime the inttypes object with types we consider "integer" */
    inttypes = json_mkobject();
    json_append_member(inttypes, "batt", json_mkbool(1));
    json_append_member(inttypes, "vel", json_mkbool(1));
    json_append_member(inttypes, "cog", json_mkbool(1));
    json_append_member(inttypes, "tst", json_mkbool(1));
    json_append_member(inttypes, "alt", json_mkbool(1));
    json_append_member(inttypes, "dist", json_mkbool(1));
    json_append_member(inttypes, "trip", json_mkbool(1));

    arr = json_find_member(json, "locations");
    json_foreach(one, arr) {
        /* Headings */
        if (virgin) {
            virgin = !virgin;

            if (fields) {
                json_foreach(node, fields) {
                    printf("%s%c", node->string_, (node->next) ? ',' : '\n');
                }
            } else {
                json_foreach(j, one) {
                    if (j->key)
                        printf("%s%c", j->key, (j->next) ? ',' : '\n');
                }
            }
        }
Ejemplo n.º 6
0
static void *thread(void *param) {
	struct protocol_threads_t *node = (struct protocol_threads_t *)param;
	struct JsonNode *json = (struct JsonNode *)node->param;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;
	int id = 0, state = 0, nstate = 0;
	double itmp = 0.0;

	threads++;

	if((jid = json_find_member(json, "id"))) {
		jchild = json_first_child(jid);
		if(json_find_number(jchild, "gpio", &itmp) == 0) {
			id = (int)round(itmp);
			pinMode(id, PINMODE_INPUT);
			state = digitalRead(id);
		}
	}

	createMessage(id, state);

	while(loop) {
		nstate = digitalRead(id);
		if(nstate != state) {
			state = nstate;
			createMessage(id, state);
		}
		usleep(100000);
	}

	threads--;
	return (void *)NULL;
}
Ejemplo n.º 7
0
static int registry_remove_value_recursive(struct JsonNode *root, const char *key) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	char *sub = strstr(key, ".");
	char *buff = MALLOC(strlen(key)+1);
	strcpy(buff, key);
	if(sub != NULL) {
		int pos = sub-key;
		buff[pos] = '\0';
	}
	struct JsonNode *member = json_find_member(root, buff);
	if(member != NULL) {
		if(sub == NULL) {
			json_remove_from_parent(member);
			json_delete(member);
			registry_remove_empty_parent(root);
			FREE(buff);
			return 0;
		}
		if(member->tag == JSON_OBJECT) {
			if(sub != NULL) {
				int pos = sub-key;
				strcpy(buff, &key[pos+1]);
			}
			int ret = registry_remove_value_recursive(member, buff);
			FREE(buff);
			return ret;
		}
	}
	FREE(buff);
	return -1;
}
Ejemplo n.º 8
0
int main(void)
{
    JsonNode *node;

    (void) chomp;

    plan_tests(49);

    ok1(json_find_element(NULL, 0) == NULL);
    ok1(json_find_member(NULL, "") == NULL);
    ok1(json_first_child(NULL) == NULL);

    node = json_mknull();
    should_be(node, "null");
    json_delete(node);

    node = json_mkbool(false);
    should_be(node, "false");
    json_delete(node);

    node = json_mkbool(true);
    should_be(node, "true");
    json_delete(node);

    test_string();
    test_number();
    test_array();
    test_object();

    return exit_status();
}
Ejemplo n.º 9
0
static int checkValues(struct JsonNode *jvalues) {
	struct JsonNode *jid = NULL;

	if((jid = json_find_member(jvalues, "id"))) {
		struct settings_t *snode = NULL;
		struct JsonNode *jchild = NULL;
		struct JsonNode *jchild1 = NULL;
		double channel = -1, id = -1;
		int match = 0;

		jchild = json_first_child(jid);
		while(jchild) {
			jchild1 = json_first_child(jchild);
			while(jchild1) {
				if(strcmp(jchild1->key, "channel") == 0) {
					channel = jchild1->number_;
				}
				if(strcmp(jchild1->key, "id") == 0) {
					id = jchild1->number_;
				}
				jchild1 = jchild1->next;
			}
			jchild = jchild->next;
		}

		struct settings_t *tmp = settings;
		while(tmp) {
			if(fabs(tmp->id-id) < EPSILON && fabs(tmp->channel-channel) < EPSILON) {
				match = 1;
				break;
			}
			tmp = tmp->next;
		}

		if(match == 0) {
			if((snode = MALLOC(sizeof(struct settings_t))) == NULL) {
				fprintf(stderr, "out of memory\n");
				exit(EXIT_FAILURE);
			}
			snode->id = id;
			snode->channel = channel;
			snode->temp = 0;
			snode->humi = 0;

			json_find_number(jvalues, "temperature-offset", &snode->temp);
			json_find_number(jvalues, "humidity-offset", &snode->humi);

			snode->next = settings;
			settings = snode;
		}
	}
	return 0;
}
Ejemplo n.º 10
0
Archivo: jo.c Proyecto: imjerrybao/jo
int nested(int flags, char *key, char *value)
{
	char *member = NULL, *bo, *bc;		/* bracket open, close */
	JsonNode *op;
	int found = FALSE;

	/* Check for geo[] or geo[lat] */
	if ((bo = strchr(key, '[')) != NULL) {
		if (*(bo+1) == ']') {
			*bo = 0;
		} else if ((bc = strchr(bo + 1, ']')) == NULL) {
			fprintf(stderr, "missing closing bracket on %s\n", key);
			return (-1);
		} else {
			*bo = *bc = 0;
			member = bo + 1;
		}

		/*
		 * key is now `geo' for both `geo[]` and `geo[lat]`
		 * member is null for the former and "lat" for the latter.
		 * Find an existing object in the pile for this member name
		 * or create a new one if we don't have it.
		 */

		if ((op = json_find_member(pile, key)) != NULL) {
			found = TRUE;
		} else {
			op = (member == NULL) ? json_mkarray() : json_mkobject();
		}

		if (member == NULL) {		/* we're doing an array */
			if (flags & FLAG_BOOLEAN) {
				json_append_element(op, boolnode(value));
			} else {
				json_append_element(op, vnode(value, flags));
			}
		} else {			/* we're doing an object */
			if (flags & FLAG_BOOLEAN) {
				json_append_member(op, member, boolnode(value));
			} else {
				json_append_member(op, member, vnode(value, flags));
			}
		}

		if (!found) {
			json_append_member(pile, key, op);
		}

		return (TRUE);
	}
	return (FALSE);
}
Ejemplo n.º 11
0
struct command *bgame_join_map_create(struct dictionary *dict)
{
	int x;
	int y;
	struct s_vmap *map;
	JsonNode *tmp;
	struct command_join_map *join;

	/* get map ID */
	tmp = json_find_member(dict->json, "map_id");
	if (!tmp || tmp->tag != JSON_NUMBER)
		return NULL;
	map = s_vmap_find((uint32_t)tmp->number_);
	if (!map)
		return NULL;
	json_delete(tmp);
	/* get x */
	tmp = json_find_member(dict->json, "x");
	if (!tmp || tmp->tag != JSON_NUMBER)
		return NULL;
	x = (int)tmp->number_;
	json_delete(tmp);
	/* get y */
	tmp = json_find_member(dict->json, "y");
	if (!tmp || tmp->tag != JSON_NUMBER)
		return NULL;
	y = (int)tmp->number_;
	json_delete(tmp);

	join = malloc(sizeof(struct command_join_map));
	if (!join)
		return NULL;

	join->vmap = map;
	join->x = x;
	join->y = y;
	join->command.handle = command_join_map_handle;

	return &join->command;
}
Ejemplo n.º 12
0
static int registry_set_value_recursive(struct JsonNode *root, const char *key, void *value, int decimals, int type) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	char *sub = strstr(key, ".");
	char *buff = MALLOC(strlen(key)+1);
	strcpy(buff, key);
	if(sub != NULL) {
		int pos = sub-key;
		buff[pos] = '\0';
	}
	struct JsonNode *member = json_find_member(root, buff);
	if(member != NULL) {
		if(member->tag == type) {
			if(type == JSON_NUMBER) {
				member->number_ = *(double *)value;
				member->decimals_ = decimals;
			} else if(type == JSON_STRING) {
				member->string_ = REALLOC(member->string_, strlen(value)+1);
				strcpy(member->string_, (char *)value);
			}
			FREE(buff);
			return 0;
		} else if(member->tag == JSON_OBJECT) {
			if(sub != NULL) {
				int pos = sub-key;
				strcpy(buff, &key[pos+1]);
			}
			int ret = registry_set_value_recursive(member, buff, value, decimals, type);
			FREE(buff);
			return ret;
		}
	} else if(sub != NULL) {
		member = json_mkobject();
		json_append_member(root, buff, member);
		int pos = sub-key;
		strcpy(buff, &key[pos+1]);
		int ret = registry_set_value_recursive(member, buff, value, decimals, type);
		FREE(buff);
		return ret;
	} else {
		if(type == JSON_NUMBER) {
			json_append_member(root, buff, json_mknumber(*(double *)value, decimals));
		} else if(type == JSON_STRING) {
			json_append_member(root, buff, json_mkstring(value));
		}
		FREE(buff);
		return 0;
	}
	FREE(buff);
	return -1;
}
Ejemplo n.º 13
0
static int actionDimRun(struct JsonNode *arguments) {
	struct JsonNode *jdevice = NULL;
	struct JsonNode *jto = NULL;
	struct JsonNode *jsvalues = NULL;
	struct JsonNode *jdvalues = NULL;
	struct JsonNode *jdchild = NULL;
	struct JsonNode *jdimlevel = NULL;
	double dimlevel = 0.0;
	char state[3];
	if((jdevice = json_find_member(arguments, "DEVICE")) != NULL &&
		 (jto = json_find_member(arguments, "TO")) != NULL) {
		if((jdvalues = json_find_member(jdevice, "value")) != NULL) {
			jdchild = json_first_child(jdvalues);
			while(jdchild) {
				if(jdchild->tag == JSON_STRING) {
					struct devices_t *dev = NULL;
					if(devices_get(jdchild->string_, &dev) == 0) {
						if((jsvalues = json_find_member(jto, "value")) != NULL) {
							jdimlevel = json_find_element(jsvalues, 0);
							if(jdimlevel != NULL && jdimlevel->tag == JSON_NUMBER) {
								dimlevel = (int)jdimlevel->number_;
								strcpy(state, "on");
								JsonNode *jvalues = json_mkobject();
								json_append_member(jvalues, "dimlevel", json_mknumber(dimlevel, 0));
								pilight.control(dev, state, json_first_child(jvalues));
								json_delete(jvalues);
							}
						}
					}
				}
				jdchild = jdchild->next;
			}
		}
	}
	return 0;
}
Ejemplo n.º 14
0
void append_device_details(JsonNode *userlist, char *user, char *device)
{
	char path[BUFSIZ];
	JsonNode *node, *last;

	snprintf(path, BUFSIZ, "%s/last/%s/%s/%s-%s.json",
		STORAGEDIR, user, device, user, device);

	last = json_mkobject();
	if (json_copy_from_file(last, path) == TRUE) {
		JsonNode *tst;

		if ((tst = json_find_member(last, "tst")) != NULL) {
			json_append_member(last, "isotst", json_mkstring(isotime(tst->number_)));
			json_append_member(last, "disptst", json_mkstring(disptime(tst->number_)));
		}
	}

	append_card_to_object(last, user, device);


	if ((node = json_find_member(last, "ghash")) != NULL) {
		if (node->tag == JSON_STRING) {
			get_geo(last, node->string_);
		}
	}

	/* Extra data */
	snprintf(path, BUFSIZ, "%s/last/%s/%s/extra.json",
		STORAGEDIR, user, device);
	json_copy_from_file(last, path);
#if WITH_GREENWICH
	get_gw_data(user, device, last);
#endif
	json_append_element(userlist, last);
}
Ejemplo n.º 15
0
void append_device_details(JsonNode *userlist, char *user, char *device)
{
	char path[BUFSIZ];
	JsonNode *node, *last, *card;

	snprintf(path, BUFSIZ, "%s/last/%s/%s/%s-%s.json",
		STORAGEDIR, user, device, user, device);

	last = json_mkobject();
	if (json_copy_from_file(last, path) == TRUE) {
		JsonNode *tst;

		if ((tst = json_find_member(last, "tst")) != NULL) {
			json_append_member(last, "isotst", json_mkstring(isotime(tst->number_)));
		}

		json_append_element(userlist, last);
	} else {
		json_delete(last);
	}

	snprintf(path, BUFSIZ, "%s/cards/%s/%s.json",
		STORAGEDIR, user, user);

	card = json_mkobject();
	if (json_copy_from_file(card, path) == TRUE) {
		json_copy_to_object(last, card, FALSE);
	}
	json_delete(card);

	if ((node = json_find_member(last, "ghash")) != NULL) {
		if (node->tag == JSON_STRING) {
			get_geo(last, node->string_);
		}
	}
}
Ejemplo n.º 16
0
static int checkValues(struct JsonNode *jvalues) {
	double readonly = 0.0;
	char *platform = GPIO_PLATFORM;

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

	struct JsonNode *jid = NULL;
	if((jid = json_find_member(jvalues, "id"))) {
		struct JsonNode *jchild = NULL;
		struct JsonNode *jchild1 = NULL;

		jchild = json_first_child(jid);
		while(jchild) {
			jchild1 = json_first_child(jchild);
			while(jchild1) {
				if(strcmp(jchild1->key, "gpio") == 0) {
					if(wiringXValidGPIO((int)round(jchild1->number_)) != 0) {
						return -1;
					}
				}
				jchild1 = jchild1->next;
			}
			jchild = jchild->next;
		}
	}

	if(json_find_number(jvalues, "readonly", &readonly) == 0) {
		if((int)readonly != 1) {
			return -1;
		}
	}

	return 0;
}
Ejemplo n.º 17
0
static void print_one(JsonNode *j, JsonNode *inttypes)
{
    /* Check if the value should be an "integer" (ie not float) */
    if (j->tag == JSON_NUMBER) {
        if (json_find_member(inttypes, j->key)) {
            printf("%.lf", j->number_);
        } else {
            printf("%lf", j->number_);
        }
    } else if (j->tag == JSON_STRING) {
        printf("%s", j->string_);
    } else if (j->tag == JSON_BOOL) {
        printf("%s", (j->bool_) ? "true" : "false");
    } else if (j->tag == JSON_NULL) {
        printf("null");
    }
}
Ejemplo n.º 18
0
static void do_hook(char *hookname, struct udata *ud, char *topic, JsonNode *fullo)
{
	struct luadata *ld = ud->luadata;
	char *_type = "unknown";
	JsonNode *j;

	lua_settop(ld->L, 0);
	lua_getglobal(ld->L, hookname);
	if (lua_type(ld->L, -1) != LUA_TFUNCTION) {
		olog(LOG_NOTICE, "cannot invoke %s in Lua script", hookname);
		return;
	}

	lua_pushstring(ld->L, topic);			/* arg1: topic */

	if ((j = json_find_member(fullo, "_type")) != NULL) {
		if (j->tag == JSON_STRING)
			_type = j->string_;
	}

	lua_pushstring(ld->L, _type);			/* arg2: record type */

	lua_newtable(ld->L);				/* arg3: table */
	json_foreach(j, fullo) {
		lua_pushstring(ld->L, j->key);		/* table key */
		if (j->tag == JSON_STRING) {
			lua_pushstring(ld->L, j->string_);
		} else if (j->tag == JSON_NUMBER) {
			lua_pushnumber(ld->L, j->number_);
		} else if (j->tag == JSON_NULL) {
			lua_pushnil(ld->L);
		} else if (j->tag == JSON_BOOL) {
			lua_pushboolean(ld->L, j->bool_);
		}
		lua_rawset(ld->L, -3);

	}
Ejemplo n.º 19
0
static void send_last(struct mg_connection *conn)
{
    struct udata *ud = (struct udata *)conn->server_param;
    JsonNode *user_array, *o, *one;
    char *u = NULL, *d = NULL;

    u	  = field(conn, "user");
    d	  = field(conn, "device");

    if ((user_array = last_users(u, d)) != NULL) {

        if (u) free(u);
        if (d) free(d);

        json_foreach(one, user_array) {
            JsonNode *f;

            o = json_mkobject();

            json_append_member(o, "_type", json_mkstring("location"));
            if ((f = json_find_member(one, "lat")) != NULL)
                json_copy_element_to_object(o, "lat", f);
            if ((f = json_find_member(one, "lon")) != NULL)
                json_copy_element_to_object(o, "lon", f);

            if ((f = json_find_member(one, "tst")) != NULL)
                json_copy_element_to_object(o, "tst", f);
            if ((f = json_find_member(one, "tid")) != NULL)
                json_copy_element_to_object(o, "tid", f);
            if ((f = json_find_member(one, "addr")) != NULL)
                json_copy_element_to_object(o, "addr", f);
            if ((f = json_find_member(one, "topic")) != NULL)
                json_copy_element_to_object(o, "topic", f);

            http_ws_push_json(ud->mgserver, o);
            json_delete(o);
        }
        json_delete(user_array);
    }
Ejemplo n.º 20
0
Archivo: plview.c Proyecto: 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;
}
Ejemplo n.º 21
0
static void *dht22Parse(void *param) {
	struct protocol_threads_t *node = (struct protocol_threads_t *)param;
	struct JsonNode *json = (struct JsonNode *)node->param;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;
	int *id = 0;
	int nrid = 0, y = 0, interval = 10, nrloops = 0;
	double temp_offset = 0.0, humi_offset = 0.0, itmp = 0.0;

	dht22_threads++;

	if((jid = json_find_member(json, "id"))) {
		jchild = json_first_child(jid);
		while(jchild) {
			if(json_find_number(jchild, "gpio", &itmp) == 0) {
				id = REALLOC(id, (sizeof(int)*(size_t)(nrid+1)));
				id[nrid] = (int)round(itmp);
				nrid++;
			}
			jchild = jchild->next;
		}
	}

	if(json_find_number(json, "poll-interval", &itmp) == 0)
		interval = (int)round(itmp);
	json_find_number(json, "temperature-offset", &temp_offset);
	json_find_number(json, "humidity-offset", &humi_offset);

	while(dht22_loop) {
		if(protocol_thread_wait(node, interval, &nrloops) == ETIMEDOUT) {
			pthread_mutex_lock(&dht22lock);
			for(y=0;y<nrid;y++) {
				int tries = 5;
				unsigned short got_correct_date = 0;
				while(tries && !got_correct_date && dht22_loop) {

					uint8_t laststate = HIGH;
					uint8_t counter = 0;
					uint8_t j = 0, i = 0;

					int dht22_dat[5] = {0,0,0,0,0};

					// pull pin down for 18 milliseconds
					pinMode(id[y], OUTPUT);
					digitalWrite(id[y], HIGH);
					usleep(500000);  // 500 ms
					// then pull it up for 40 microseconds
					digitalWrite(id[y], LOW);
					usleep(20000);
					// prepare to read the pin
					pinMode(id[y], INPUT);

					// detect change and read data
					for(i=0; (i<MAXTIMINGS && dht22_loop); i++) {
						counter = 0;
						delayMicroseconds(10);
						while(sizecvt(digitalRead(id[y])) == laststate && dht22_loop) {
							counter++;
							delayMicroseconds(1);
							if(counter == 255) {
								break;
							}
						}
						laststate = sizecvt(digitalRead(id[y]));

						if(counter == 255)
							break;

						// ignore first 3 transitions
						if((i >= 4) && (i%2 == 0)) {

							// shove each bit into the storage bytes
							dht22_dat[(int)((double)j/8)] <<= 1;
							if(counter > 16)
								dht22_dat[(int)((double)j/8)] |= 1;
							j++;
						}
					}

					// check we read 40 bits (8bit x 5 ) + verify checksum in the last byte
					// print it out if data is good
					if((j >= 40) && (dht22_dat[4] == ((dht22_dat[0] + dht22_dat[1] + dht22_dat[2] + dht22_dat[3]) & 0xFF))) {
						got_correct_date = 1;

						double h = dht22_dat[0] * 256 + dht22_dat[1];
						double t = (dht22_dat[2] & 0x7F)* 256 + dht22_dat[3];
						t += temp_offset;
						h += humi_offset;

						if((dht22_dat[2] & 0x80) != 0)
							t *= -1;

						dht22->message = json_mkobject();
						JsonNode *code = json_mkobject();
						json_append_member(code, "gpio", json_mknumber(id[y], 0));
						json_append_member(code, "temperature", json_mknumber(t/10, 1));
						json_append_member(code, "humidity", json_mknumber(h/10, 1));

						json_append_member(dht22->message, "message", code);
						json_append_member(dht22->message, "origin", json_mkstring("receiver"));
						json_append_member(dht22->message, "protocol", json_mkstring(dht22->id));

						if(pilight.broadcast != NULL) {
							pilight.broadcast(dht22->id, dht22->message);
						}
						json_delete(dht22->message);
						dht22->message = NULL;
					} else {
						logprintf(LOG_DEBUG, "dht22 data checksum was wrong");
						tries--;
						protocol_thread_wait(node, 1, &nrloops);
					}
				}
			}
			pthread_mutex_unlock(&dht22lock);
		}
	}
	pthread_mutex_unlock(&dht22lock);

	FREE(id);
	dht22_threads--;
	return (void *)NULL;
}
Ejemplo n.º 22
0
static int checkValues(JsonNode *code) {
	char *def = NULL;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;
	int free_def = 0;
	double itmp = -1;

	if(json_find_string(code, "default-state", &def) != 0) {
		if((def = MALLOC(4)) == NULL) {
			fprintf(stderr, "out of memory\n");
			exit(EXIT_FAILURE);
		}
		strcpy(def, "off");
		free_def = 1;
	}
	if(strcmp(def, "on") != 0 && strcmp(def, "off") != 0) {
		if(free_def == 1) {
			FREE(def);
		}
		return 1;
	}

	/* Get current relay state and validate GPIO number */
	if((jid = json_find_member(code, "id")) != NULL) {
		if((jchild = json_find_element(jid, 0)) != NULL) {
			if(json_find_number(jchild, "gpio", &itmp) == 0) {
				if(wiringXSupported() == 0) {
					int gpio = (int)itmp;
					int state = -1;
					if(wiringXSetup() < 0) {
						logprintf(LOG_ERR, "unable to setup wiringX") ;
						return -1;
					} else if(wiringXValidGPIO(gpio) != 0) {
						logprintf(LOG_ERR, "relay: invalid gpio range");
						return -1;
					} else {
						pinMode(gpio, INPUT);
						state = digitalRead(gpio);
						if(strcmp(def, "on") == 0) {
							state ^= 1;
						}

						relay->message = json_mkobject();
						JsonNode *code = json_mkobject();
						json_append_member(code, "gpio", json_mknumber(gpio, 0));
						if(state == 1) {
							json_append_member(code, "state", json_mkstring("on"));
						} else {
							json_append_member(code, "state", json_mkstring("off"));
						}

						json_append_member(relay->message, "message", code);
						json_append_member(relay->message, "origin", json_mkstring("sender"));
						json_append_member(relay->message, "protocol", json_mkstring(relay->id));
						if(pilight.broadcast != NULL) {
							pilight.broadcast(relay->id, relay->message, PROTOCOL);
						}
						json_delete(relay->message);
						relay->message = NULL;
					}
				}
			}
		}
	}

	if(free_def == 1) {
		FREE(def);
	}
	return 0;
}
Ejemplo n.º 23
0
static void *thread(void *param) {
	struct protocol_threads_t *node = (struct protocol_threads_t *)param;
	struct JsonNode *json = (struct JsonNode *)node->param;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;

#ifndef _WIN32
	struct dirent *file = NULL;
	struct stat st;

	DIR *d = NULL;
	FILE *fp = NULL;
	char crcVar[5];
	int w1valid = 0;
	double w1temp = 0.0;
	size_t bytes = 0;
#endif
	char **id = NULL, *stmp = NULL, *content = NULL;
	char *ds18s20_sensor = NULL;
	int nrid = 0, interval = 10, nrloops = 0, y = 0;
	double temp_offset = 0.0, itmp = 0.0;

	threads++;

	if((jid = json_find_member(json, "id"))) {
		jchild = json_first_child(jid);
		while(jchild) {
			if(json_find_string(jchild, "id", &stmp) == 0) {
				if((id = REALLOC(id, (sizeof(char *)*(size_t)(nrid+1)))) == NULL) {
					fprintf(stderr, "out of memory\n");
					exit(EXIT_FAILURE);
				}
				if((id[nrid] = MALLOC(strlen(stmp)+1)) == NULL) {
					fprintf(stderr, "out of memory\n");
					exit(EXIT_FAILURE);
				}
				strcpy(id[nrid], stmp);
				nrid++;
			}
			jchild = jchild->next;
		}
	}

	if(json_find_number(json, "poll-interval", &itmp) == 0)
		interval = (int)round(itmp);
	json_find_number(json, "temperature-offset", &temp_offset);

	while(loop) {
		if(protocol_thread_wait(node, interval, &nrloops) == ETIMEDOUT) {
#ifndef _WIN32
			pthread_mutex_lock(&lock);
			for(y=0;y<nrid;y++) {
				if((ds18s20_sensor = REALLOC(ds18s20_sensor, strlen(source_path)+strlen(id[y])+5)) == NULL) {
					fprintf(stderr, "out of memory\n");
					exit(EXIT_FAILURE);
				}
				sprintf(ds18s20_sensor, "%s10-%s/", source_path, id[y]);
				if((d = opendir(ds18s20_sensor))) {
					while((file = readdir(d)) != NULL) {
						if(file->d_type == DT_REG) {
							if(strcmp(file->d_name, "w1_slave") == 0) {
								size_t w1slavelen = strlen(ds18s20_sensor)+10;
								char ds18s20_w1slave[w1slavelen];
								memset(ds18s20_w1slave, '\0', w1slavelen);
								strncpy(ds18s20_w1slave, ds18s20_sensor, strlen(ds18s20_sensor));
								strcat(ds18s20_w1slave, "w1_slave");

								if(!(fp = fopen(ds18s20_w1slave, "rb"))) {
									logprintf(LOG_ERR, "cannot read w1 file: %s", ds18s20_w1slave);
									break;
								}

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

								if(!(content = REALLOC(content, bytes+1))) {
									fprintf(stderr, "out of memory\n");
									fclose(fp);
									break;
								}
								memset(content, '\0', bytes+1);

								if(fread(content, sizeof(char), bytes, fp) == -1) {
									logprintf(LOG_ERR, "cannot read config file: %s", ds18s20_w1slave);
									fclose(fp);
									break;
								}
								fclose(fp);
								w1valid = 0;

								char **array = NULL;
								unsigned int n = explode(content, "\n", &array);
								if(n > 0) {
									sscanf(array[0], "%*x %*x %*x %*x %*x %*x %*x %*x %*x : crc=%*x %s", crcVar);
									if(strncmp(crcVar, "YES", 3) == 0 && n > 1) {
										w1valid = 1;
										sscanf(array[1], "%*x %*x %*x %*x %*x %*x %*x %*x %*x t=%lf", &w1temp);
										w1temp = (w1temp/1000)+temp_offset;
									}
								}
								array_free(&array, n);

								if(w1valid) {
									ds18s20->message = json_mkobject();

									JsonNode *code = json_mkobject();

									json_append_member(code, "id", json_mkstring(id[y]));
									json_append_member(code, "temperature", json_mknumber(w1temp, 1));

									json_append_member(ds18s20->message, "message", code);
									json_append_member(ds18s20->message, "origin", json_mkstring("receiver"));
									json_append_member(ds18s20->message, "protocol", json_mkstring(ds18s20->id));

									if(pilight.broadcast != NULL) {
										pilight.broadcast(ds18s20->id, ds18s20->message, PROTOCOL);
									}
									json_delete(ds18s20->message);
									ds18s20->message = NULL;
								}
							}
						}
					}
					closedir(d);
				} else {
					logprintf(LOG_ERR, "1-wire device %s does not exists", ds18s20_sensor);
				}
			}
#endif
			pthread_mutex_unlock(&lock);
		}
	}
	pthread_mutex_unlock(&lock);

	if(ds18s20_sensor) {
		FREE(ds18s20_sensor);
	}
	if(content) {
		FREE(content);
	}
	for(y=0;y<nrid;y++) {
		FREE(id[y]);
	}
	FREE(id);
	threads--;
	return (void *)NULL;
}
Ejemplo n.º 24
0
void *ds18b20Parse(void *param) {
	struct protocol_threads_t *node = (struct protocol_threads_t *)param;
	struct JsonNode *json = (struct JsonNode *)node->param;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;
	struct dirent *file = NULL;
	struct stat st;

	DIR *d = NULL;
	FILE *fp = NULL;
	char *ds18b20_sensor = NULL;
	char *stmp = NULL;
	char **id = NULL;
	char *content = NULL;
	int w1valid = 0, w1temp = 0, interval = 10, x = 0;
	int temp_offset = 0, nrid = 0, y = 0, nrloops = 0;
	double itmp = 0;
	size_t bytes = 0;

	ds18b20_threads++;

	if((jid = json_find_member(json, "id"))) {
		jchild = json_first_child(jid);
		while(jchild) {
			if(json_find_string(jchild, "id", &stmp) == 0) {
				id = realloc(id, (sizeof(char *)*(size_t)(nrid+1)));
				if(!id) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				id[nrid] = malloc(strlen(stmp)+1);
				if(!id[nrid]) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				strcpy(id[nrid], stmp);
				nrid++;
			}
			jchild = jchild->next;
		}
	}

	if(json_find_number(json, "poll-interval", &itmp) == 0)
		interval = (int)round(itmp);
	if(json_find_number(json, "device-temperature-offset", &itmp) == 0)
		temp_offset = (int)round(itmp);

	while(ds18b20_loop) {
		if(protocol_thread_wait(node, interval, &nrloops) == ETIMEDOUT) {
			for(y=0;y<nrid;y++) {
				ds18b20_sensor = realloc(ds18b20_sensor, strlen(ds18b20_path)+strlen(id[y])+5);
				if(!ds18b20_sensor) {
					logprintf(LOG_ERR, "out of memory");
					exit(EXIT_FAILURE);
				}
				sprintf(ds18b20_sensor, "%s28-%s/", ds18b20_path, id[y]);
				if((d = opendir(ds18b20_sensor))) {
					while((file = readdir(d)) != NULL) {
						if(file->d_type == DT_REG) {
							if(strcmp(file->d_name, "w1_slave") == 0) {
								size_t w1slavelen = strlen(ds18b20_sensor)+10;
								char ds18b20_w1slave[w1slavelen];
								memset(ds18b20_w1slave, '\0', w1slavelen);
								strncpy(ds18b20_w1slave, ds18b20_sensor, strlen(ds18b20_sensor));
								strcat(ds18b20_w1slave, "w1_slave");

								if(!(fp = fopen(ds18b20_w1slave, "rb"))) {
									logprintf(LOG_ERR, "cannot read w1 file: %s", ds18b20_w1slave);
									break;
								}

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

								if(!(content = realloc(content, bytes+1))) {
									logprintf(LOG_ERR, "out of memory");
									fclose(fp);
									break;
								}
								memset(content, '\0', bytes+1);

								if(fread(content, sizeof(char), bytes, fp) == -1) {
									logprintf(LOG_ERR, "cannot read config file: %s", ds18b20_w1slave);
									fclose(fp);
									break;
								}
								fclose(fp);
								w1valid = 0;
								char *pch = strtok(content, "\n=: ");
								x = 0;
								while(pch) {
									if(strlen(pch) > 2) {
										if(x == 1 && strstr(pch, "YES")) {
											w1valid = 1;
										}
										if(x == 2) {	
											w1temp = atoi(pch)+temp_offset;
										}
										x++;
									}
									pch = strtok(NULL, "\n=: ");
								}

								if(w1valid) {
									ds18b20->message = json_mkobject();
									
									JsonNode *code = json_mkobject();
									
									json_append_member(code, "id", json_mkstring(id[y]));
									json_append_member(code, "temperature", json_mknumber(w1temp));
									
									json_append_member(ds18b20->message, "message", code);
									json_append_member(ds18b20->message, "origin", json_mkstring("receiver"));
									json_append_member(ds18b20->message, "protocol", json_mkstring(ds18b20->id));
									
									pilight.broadcast(ds18b20->id, ds18b20->message);
									json_delete(ds18b20->message);
									ds18b20->message = NULL;
								}
							}
						}
					}
					closedir(d);
				} else {
					logprintf(LOG_ERR, "1-wire device %s does not exists", ds18b20_sensor);
				}
			}
		}
	}
	if(ds18b20_sensor) {
		sfree((void *)&ds18b20_sensor);
	}
	if(content) {
		sfree((void *)&content);
	}
	for(y=0;y<nrid;y++) {
		sfree((void *)&id[y]);
	}
	sfree((void *)&id);
	ds18b20_threads--;
	return (void *)NULL;
}
Ejemplo n.º 25
0
static int candidate_line(char *line, void *param)
{
	long counter = 0L;
	JsonNode *j, *o;
	struct jparam *jarg = (struct jparam*)param;
	char *bp;
	JsonNode *obj	= jarg->obj;
	JsonNode *locs	= jarg->locs;
	int limit	= jarg->limit;
	time_t s_lo	= jarg->s_lo;
	time_t s_hi	= jarg->s_hi;
	JsonNode *fields = jarg->fields;
	output_type otype = jarg->otype;

	if (obj == NULL || obj->tag != JSON_OBJECT)
		return (-1);
	if (locs == NULL || locs->tag != JSON_ARRAY)
		return (-1);

	if (limit == 0) {
		/* Reading forwards; account for time */

		char *p;
		struct tm tmline;
		time_t secs;

		if ((p = strptime(line, "%Y-%m-%dT%H:%M:%SZ", &tmline)) == NULL) {
			fprintf(stderr, "no strptime on %s", line);
			return (0);
		}
		secs = mktime(&tmline);

		if (secs <= s_lo || secs >= s_hi) {
			return (0);
		}

		if (otype == RAW) {
			printf("%s\n", line);
			return (0);
		} else if (otype == RAWPAYLOAD) {
			char *bp;

			if ((bp = strchr(line, '{')) != NULL) {
				printf("%s\n", bp);
			}
		}

	}
	if (limit > 0 && otype == RAW) {
		printf("%s\n", line);
		return (1); /* make it 'count' or tac() will not decrement line counter and continue until EOF */
	}

	/* Do we have location line? */
	if ((bp = strstr(line, "Z\t* ")) == NULL) {	/* Not a location line */
		return (0);
	}

	if ((bp = strrchr(bp, '\t')) == NULL) {
		return (0);
	}

	/* Initialize our counter to what the JSON obj currently has */
	if ((j = json_find_member(obj, "count")) != NULL) {
		counter = j->number_;
		json_delete(j);
	}

	// fprintf(stderr, "-->[%s]\n", line);

	if ((o = line_to_location(line)) != NULL) {
		if (fields) {
			/* Create a new object, copying members we're interested in into it */
			JsonNode *f, *node;
			JsonNode *newo = json_mkobject();

			json_foreach(f, fields) {
				char *key = f->string_;

				if ((node = json_find_member(o, key)) != NULL) {
					json_copy_element_to_object(newo, key, node);
				}
			}
			json_delete(o);
			o = newo;
		}
		json_append_element(locs, o);
		++counter;
	}
Ejemplo n.º 26
0
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;
}
Ejemplo n.º 27
0
static void test_object(void)
{
    JsonNode *object;
    JsonNode *children[5 + 1];

    object = json_mkobject();
    should_be(object, "{}");

    children[1] = json_mknumber(1);
    children[2] = json_mknumber(2);
    children[3] = json_mknumber(3);

    ok1(json_find_member(object, "one") == NULL);
    ok1(json_find_member(object, "two") == NULL);
    ok1(json_find_member(object, "three") == NULL);

    json_append_member(object, "one", children[1]);
    should_be(object, "{\"one\":1}");

    ok1(json_find_member(object, "one") == children[1]);
    ok1(json_find_member(object, "two") == NULL);
    ok1(json_find_member(object, "three") == NULL);

    json_prepend_member(object, "two", children[2]);
    should_be(object, "{\"two\":2,\"one\":1}");

    ok1(json_find_member(object, "one") == children[1]);
    ok1(json_find_member(object, "two") == children[2]);
    ok1(json_find_member(object, "three") == NULL);

    json_append_member(object, "three", children[3]);
    should_be(object, "{\"two\":2,\"one\":1,\"three\":3}");

    ok1(json_find_member(object, "one") == children[1]);
    ok1(json_find_member(object, "two") == children[2]);
    ok1(json_find_member(object, "three") == children[3]);

    json_delete(object);
}
Ejemplo n.º 28
0
void *xbmcParse(void *param) {
	struct protocol_threads_t *node = (struct protocol_threads_t *)param;
	struct JsonNode *json = (struct JsonNode *)node->param;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;
	struct JsonNode *jchild1 = NULL;
	struct sockaddr_in serv_addr;
	struct xbmc_data_t *xnode = malloc(sizeof(struct xbmc_data_t));

	char recvBuff[BUFFER_SIZE], action[10], media[15];
	char *m = NULL, *t = NULL;
	char shut[] = "shutdown";
	char home[] = "home";
	char none[] = "none";
	int nrloops = 0, bytes = 0, n = 0, has_server = 0;
	int has_port = 0, reset = 1, maxfd = 0;
	fd_set fdsread;	
	struct timeval timeout;
	timeout.tv_sec = 1;
	timeout.tv_usec = 0;

	if(!xnode) {
		logprintf(LOG_ERR, "out of memory");
		exit(EXIT_FAILURE);
	}	
	
	/* Clear the server address */
    memset(&serv_addr, '\0', sizeof(serv_addr));
	memset(&recvBuff, '\0', BUFFER_SIZE);
	memset(&action, '\0', 10);
	memset(&media, '\0', 15);
	
	xbmc_threads++;

	if((jid = json_find_member(json, "id"))) {
		jchild = json_first_child(jid);
		while(jchild) {
			jchild1 = json_first_child(jchild);

			while(jchild1) {
				if(strcmp(jchild1->key, "server") == 0) {
					if(!(xnode->server = malloc(strlen(jchild1->string_)+1))) {
						logprintf(LOG_ERR, "out of memory");
						exit(EXIT_FAILURE);
					}
					strcpy(xnode->server, jchild1->string_);
					has_server = 1;
				}
				if(strcmp(jchild1->key, "port") == 0) {
					xnode->port = (int)round(jchild1->number_);
					has_port = 1;
				}
				jchild1 = jchild1->next;
			}
			if(has_server == 1 && has_port == 1) {
				xnode->sockfd = -1;
				xnode->next = xbmc_data;
				xbmc_data = xnode;
			} else {
				if(has_server == 1) {
					sfree((void *)&xnode->server);
				}
				sfree((void *)&xnode);
				xnode = NULL;
			}
			jchild = jchild->next;
		}
	}

	if(!xnode) {
		return 0;
	}

	while(xbmc_loop) {

		if(reset == 1) {
			xbmcCreateMessage(xnode->server, xnode->port, shut, none);
			reset = 0;
		}

		if(xnode->sockfd > -1) {
			close(xnode->sockfd);
			xnode->sockfd = -1;
		}

		/* Try to open a new socket */
		if((xnode->sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
			logprintf(LOG_DEBUG, "could not create XBMC socket");
			break;
		}

		serv_addr.sin_family = AF_INET;
		serv_addr.sin_port = htons((unsigned short)xnode->port);
		inet_pton(AF_INET, xnode->server, &serv_addr.sin_addr);	
		
		/* Connect to the server */
		if(connect(xnode->sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
			protocol_thread_wait(node, 3, &nrloops);
			continue;
		} else {
			xbmcCreateMessage(xnode->server, xnode->port, home, none);
			reset = 1;
		}

		struct xbmc_data_t *xtmp = xbmc_data;
		while(xtmp) {
			if(xtmp->sockfd > -1) {
				if(maxfd < xtmp->sockfd) {
					maxfd = xtmp->sockfd;
				}
			}
			xtmp = xtmp->next;
		}
		
		while(xbmc_loop) {
			FD_ZERO(&fdsread);
			FD_SET((unsigned long)xnode->sockfd, &fdsread);

			do {
				n = select(maxfd+1, &fdsread, NULL, NULL, &timeout);
			} while(n == -1 && errno == EINTR && xbmc_loop);

			if(xbmc_loop == 0) {
				break;
			}

			if(n == -1) {			
				break;
			} else if(n == 0) {
				usleep(10000);
			} else if(n > 0) {
				if(FD_ISSET((unsigned long)xnode->sockfd, &fdsread)) {
					bytes = (int)recv(xnode->sockfd, recvBuff, BUFFER_SIZE, 0);
					if(bytes <= 0) {
						break;
					} else {
						if(json_validate(recvBuff) == true) {
							JsonNode *joutput = json_decode(recvBuff);
							JsonNode *params = NULL;
							JsonNode *data = NULL;
							JsonNode *item = NULL;

							if(json_find_string(joutput, "method", &m) == 0) {
								if(strcmp(m, "GUI.OnScreensaverActivated") == 0) {
									strcpy(media, "screensaver");
									strcpy(action, "active");
								} else if(strcmp(m, "GUI.OnScreensaverDeactivated") == 0) {
									strcpy(media, "screensaver");
									strcpy(action, "inactive");
								} else {
									if((params = json_find_member(joutput, "params")) != NULL) {
										if((data = json_find_member(params, "data")) != NULL) {
											if((item = json_find_member(data, "item")) != NULL) {
												if(json_find_string(item, "type", &t) == 0) {
													xbmc->message = json_mkobject();

													strcpy(media, t);
													if(strcmp(m, "Player.OnPlay") == 0) {
														strcpy(action, "play");
													} else if(strcmp(m, "Player.OnStop") == 0) {
														strcpy(action, home);
														strcpy(media, none);
													} else if(strcmp(m, "Player.OnPause") == 0) {
														strcpy(action, "pause");
													}
												}
											}
										}
									}
								}
								if(strlen(media) > 0 && strlen(action) > 0) {
									xbmcCreateMessage(xnode->server, xnode->port, action, media);
									reset = 1;
								}							
							}
							json_delete(joutput);
						}
						memset(recvBuff, '\0', BUFFER_SIZE);
						memset(&action, '\0', 10);
						memset(&media, '\0', 15);
					}
				}
			}
		}
	}	
	
	xbmc_threads--;
	return (void *)NULL;
}
Ejemplo n.º 29
0
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;
}
Ejemplo n.º 30
0
void *programParse(void *param) {
	struct protocol_threads_t *pnode = (struct protocol_threads_t *)param;
	struct JsonNode *json = (struct JsonNode *)pnode->param;
	struct JsonNode *jid = NULL;
	struct JsonNode *jchild = NULL;
	struct JsonNode *jchild1 = NULL;
	char *prog = NULL, *args = NULL, *stopcmd = NULL, *startcmd = NULL;
	
	int interval = 1, nrloops = 0, currentstate = 0, laststate = -1;
	int pid = 0;
	double itmp = 0;

	program_threads++;

	json_find_string(json, "program", &prog);	
	json_find_string(json, "arguments", &args);
	json_find_string(json, "stop-command", &stopcmd);
	json_find_string(json, "start-command", &startcmd);
	
	struct programs_t *lnode = malloc(sizeof(struct programs_t));	
	lnode->wait = 0;
	lnode->pth = 0;
	
	if(args && strlen(args) > 0) {
		if(!(lnode->arguments = malloc(strlen(args)+1))) {
			logprintf(LOG_ERR, "out of memory");
			exit(EXIT_FAILURE);
		}
		strcpy(lnode->arguments, args);
	} else {
		lnode->arguments = NULL;
	}

	if(prog) {
		if(!(lnode->program = malloc(strlen(prog)+1))) {
			logprintf(LOG_ERR, "out of memory");
			exit(EXIT_FAILURE);
		}
		strcpy(lnode->program, prog);
	} else {
		lnode->program = NULL;
	}

	if(stopcmd) {
		if(!(lnode->stop = malloc(strlen(stopcmd)+1))) {
			logprintf(LOG_ERR, "out of memory");
			exit(EXIT_FAILURE);
		}
		strcpy(lnode->stop, stopcmd);
	} else {
		lnode->stop = NULL;
	}

	if(startcmd) {
		if(!(lnode->start = malloc(strlen(startcmd)+1))) {
			logprintf(LOG_ERR, "out of memory");
			exit(EXIT_FAILURE);
		}
		strcpy(lnode->start, startcmd);
	} else {
		lnode->start = NULL;
	}

	if((jid = json_find_member(json, "id"))) {
		jchild = json_first_child(jid);
		while(jchild) {
			jchild1 = json_first_child(jchild);
			while(jchild1) {
				if(strcmp(jchild1->key, "name") == 0) {
					if(!(lnode->name = malloc(strlen(jchild1->string_)+1))) {
						logprintf(LOG_ERR, "out of memory");
						exit(EXIT_FAILURE);
					}
					strcpy(lnode->name, jchild1->string_);
				}
				jchild1 = jchild1->next;
			}
			jchild = jchild->next;
		}
	}

	struct programs_t *tmp = programs;
	if(tmp) {
		while(tmp->next != NULL) {
			tmp = tmp->next;
		}
		tmp->next = lnode;
	} else {
		lnode->next = tmp;
		programs = lnode;
	}
	
	if(json_find_number(json, "poll-interval", &itmp) == 0)
		interval = (int)round(itmp);

	while(program_loop) {
		if(protocol_thread_wait(pnode, interval, &nrloops) == ETIMEDOUT) {
			if(lnode->wait == 0) {
				program->message = json_mkobject();

				JsonNode *code = json_mkobject();
				json_append_member(code, "name", json_mkstring(lnode->name));

				if((pid = (int)findproc(lnode->program, lnode->arguments)) > 0) {
					currentstate = 1;
					json_append_member(code, "state", json_mkstring("running"));
					json_append_member(code, "pid", json_mknumber((int)pid));
				} else {
					currentstate = 0;
					json_append_member(code, "state", json_mkstring("stopped"));
					json_append_member(code, "pid", json_mknumber(0));
				}

				json_append_member(program->message, "message", code);
				json_append_member(program->message, "origin", json_mkstring("receiver"));
				json_append_member(program->message, "protocol", json_mkstring(program->id));

				if(currentstate != laststate) {
					laststate = currentstate;									
					pilight.broadcast(program->id, program->message);
				}

				json_delete(program->message);
				program->message = NULL;
			}
		}
	}

	program_threads--;
	return (void *)NULL;
}