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;
  }
Exemple #2
0
/** @internal Recursive Lua/JSON serialization. */
static JsonNode *l_pack_elem(lua_State *L, int top)
{
	switch(lua_type(L, top)) {
	case LUA_TSTRING:  return json_mkstring(lua_tostring(L, top));
	case LUA_TNUMBER:  return json_mknumber(lua_tonumber(L, top));
	case LUA_TBOOLEAN: return json_mkbool(lua_toboolean(L, top));
	case LUA_TTABLE:   break; /* Table, iterate it. */
	default:           return json_mknull();
	}
	/* Use absolute indexes here, as the table may be nested. */
	JsonNode *node = NULL;
	lua_pushnil(L);
	while(lua_next(L, top) != 0) {
		JsonNode *val = l_pack_elem(L, top + 2);
		const bool no_key = lua_isnumber(L, top + 1);
		if (!node) {
			node = no_key ? json_mkarray() : json_mkobject();
			if (!node) {
				return NULL;
			}
		}
		/* Insert to array/table */
		if (no_key) {
			json_append_element(node, val);
		} else {
			json_append_member(node, lua_tostring(L, top + 1), val);
		}
		lua_pop(L, 1);
	}
	return node;
}
GT_INLINE JsonNode* gt_json_int_array(const uint64_t start, const uint64_t len, uint64_t* const data){
  JsonNode* a = json_mkarray();
  uint64_t i= 0;
  for (i=0;i<len;++i) {
    json_append_element(a, json_mknumber((double)data[start + i]));
  }
  return a;
}
Exemple #4
0
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);
}
Exemple #5
0
JsonNode *json_splitter(char *s, char *sep)
{
	char *token, *ds = strdup(s);
	JsonNode *array = json_mkarray();

	if (!ds || !array)
		return (NULL);

	for (token = strtok(ds, sep); token && *token; token = strtok(NULL, sep)) {
		json_append_element(array, json_mkstring(token));
        }

	free(ds);
	return (array);
}
Exemple #6
0
/** @internal Pack address list into JSON array. */
static JsonNode *pack_addrs(pack_t *pack)
{
	char buf[SOCKADDR_STRLEN];
	JsonNode *root = json_mkarray();
	uint8_t *addr = pack_head(*pack);
	while (addr != pack_tail(*pack)) {
		size_t len = pack_obj_len(addr);
		int family = len == sizeof(struct in_addr) ? AF_INET : AF_INET6;
		if (!inet_ntop(family, pack_obj_val(addr), buf, sizeof(buf))) {
			break;
		}
		json_append_element(root, json_mkstring(buf));
		addr = pack_obj_next(addr);
	}
	return root;
}
Exemple #7
0
char* combineJObjs(JsonNode** objs, int nObjs)
{
	char* szRet;

	int idx;
	JsonNode* arrayRet = json_mkarray();
	for (idx = 0; idx < nObjs; idx++) {
		JsonNode* temp = *(objs + idx);

		json_append_element(arrayRet, *(objs + idx));
	}
	szRet = json_encode(arrayRet);

	json_delete(arrayRet);

	return szRet;
}
Exemple #8
0
JsonNode *last_users(char *in_user, char *in_device)
{
	JsonNode *obj = json_mkobject();
	JsonNode *un, *dn, *userlist = json_mkarray();
	char path[BUFSIZ], user[BUFSIZ], device[BUFSIZ];

	snprintf(path, BUFSIZ, "%s/last", STORAGEDIR);

	// fprintf(stderr, "last_users(%s, %s)\n", (in_user) ? in_user : "******",
	// 	(in_device) ? in_device : "<nil>");

	if (user_device_list(path, 0, obj) == 1)
		return (obj);

	/* Loop through users, devices */
	json_foreach(un, obj) {
		if (un->tag != JSON_ARRAY)
			continue;
		strcpy(user, un->key);
		json_foreach(dn, un) {
			if (dn->tag == JSON_STRING) {
				strcpy(device, dn->string_);
			} else if (dn->tag == JSON_NUMBER) {	/* all digits? */
				sprintf(device, "%.lf", dn->number_);
			}

			if (!in_user && !in_device) {
				append_device_details(userlist, user, device);
			} else if (in_user && !in_device) {
				if (strcmp(user, in_user) == 0) {
					append_device_details(userlist, user, device);
				}
			} else if (in_user && in_device) {
				if (strcmp(user, in_user) == 0 && strcmp(device, in_device) == 0) {
					append_device_details(userlist, user, device);
				}
			}
		}
	}
	json_delete(obj);

	return (userlist);
}
Exemple #9
0
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 if (node->tag == JSON_ARRAY) {
				JsonNode       *array = json_mkarray();
				json_copy_to_object(array, node, clobber);
				json_append_member(obj, node->key, array);
			} else if (node->tag == JSON_OBJECT) {
				JsonNode       *newobj = json_mkobject();
				json_copy_to_object(newobj, node, clobber);
				json_append_member(obj, node->key, newobj);
			} else
				printf("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);
}
Exemple #10
0
static void lsscan(char *pathpat, time_t s_lo, time_t s_hi, JsonNode *obj, int reverse)
{
	struct dirent **namelist;
	int i, n;
	JsonNode *jarr = json_mkarray();
	static UT_string *path = NULL;

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

	utstring_renew(path);

	/* Set global t_ values */
	t_lo = s_lo;
	t_hi = s_hi;

	if ((n = scandir(pathpat, &namelist, filter_filename, cmp)) < 0) {
		json_append_member(obj, "error", json_mkstring("Cannot lsscan requested directory"));
                return;
	}

	if (reverse) {
		for (i = n - 1; i >= 0; i--) {
			utstring_clear(path);
			utstring_printf(path, "%s/%s", pathpat, namelist[i]->d_name);
			json_append_element(jarr, json_mkstring(UB(path)));
			free(namelist[i]);
		}
	} else {
		for (i = 0; i < n; i++) {
			utstring_clear(path);
			utstring_printf(path, "%s/%s", pathpat, namelist[i]->d_name);
			json_append_element(jarr, json_mkstring(UB(path)));
			free(namelist[i]);
		}
	}
	free(namelist);

	json_append_member(obj, "results", jarr);
}
Exemple #11
0
static void ls(char *path, JsonNode *obj)
{
        DIR *dirp;
        struct dirent *dp;
	JsonNode *jarr = json_mkarray();

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

        if ((dirp = opendir(path)) == NULL) {
		json_append_member(obj, "error", json_mkstring("Cannot open requested directory"));
                return;
        }

        while ((dp = readdir(dirp)) != NULL) {
                if ((*dp->d_name != '.') && (dp->d_type == DT_DIR)) {
			json_append_element(jarr, json_mkstring(dp->d_name));
                }
        }

	json_append_member(obj, "results", jarr);
        closedir(dirp);
}
Exemple #12
0
static int user_device_list(char *name, int level, JsonNode *obj)
{
	DIR *dirp;
	struct dirent *dp;
	char path[BUFSIZ];
	JsonNode *devlist;
	int rc = 0;
	struct stat sb;

	if ((dirp = opendir(name)) == NULL) {
		perror(name);
		return (1);
	}
	while ((dp = readdir(dirp)) != NULL) {
		if (*dp->d_name != '.') {
			sprintf(path, "%s/%s", name, dp->d_name);

			if (stat(path, &sb) != 0) {
				continue;
			}
			if (!S_ISDIR(sb.st_mode))
				continue;


			if (level == 0) {
				devlist = json_mkarray();
				json_append_member(obj, dp->d_name, devlist);
				rc = user_device_list(path, level + 1, devlist);
			} else if (level == 1) {
				json_append_element(obj, json_mkstring(dp->d_name));
			}
		}
	}
	closedir(dirp);
	return (rc);
}
Exemple #13
0
void *pt_mem_test(void *args)
{
  mem_test_t arg = *(mem_test_t *) args; 
  free(args);

  XL3_Packet packet;
  mem_test_args_t *packet_args = (mem_test_args_t *) packet.payload;
  mem_test_results_t *packet_results = (mem_test_results_t *) packet.payload;

  packet.cmdHeader.packet_type = MEM_TEST_ID;
  packet_args->slot_num = arg.slot_num;

  SwapLongBlock(packet_args,sizeof(mem_test_args_t)/sizeof(uint32_t));

  fd_set thread_fdset;
  FD_ZERO(&thread_fdset);
  FD_SET(rw_xl3_fd[arg.crate_num],&thread_fdset);

  pt_printsend("Getting crate configuration\n");
  update_crate_config(arg.crate_num,(0x1<<arg.slot_num),&thread_fdset);

  pt_printsend("Starting mem_test\n");

  do_xl3_cmd(&packet,arg.crate_num,&thread_fdset);

  SwapLongBlock(packet_results,sizeof(mem_test_results_t)/sizeof(uint32_t));

  if (arg.update_db){
    pt_printsend("updating the database\n");
    char hextostr[50];
    int i;
    JsonNode *newdoc = json_mkobject();
    json_append_member(newdoc,"type",json_mkstring("mem_test"));

    // results of address test, which address bits are broken
    JsonNode* address_test = json_mkarray();
    for (i=0;i<20;i++){
      json_append_element(address_test,
          json_mkbool(!(packet_results->address_bit_failures & (0x1<<i))));
    }
    json_append_member(newdoc,"address_test_ok",address_test);

    // results of pattern test, where first error was
    JsonNode* pattern_test = json_mkobject();
    json_append_member(pattern_test,"error",json_mkbool(packet_results->error_location!=0xFFFFFFFF));
    sprintf(hextostr,"%08x",packet_results->error_location);
    json_append_member(pattern_test,"error_location",json_mkstring(hextostr));
    sprintf(hextostr,"%08x",packet_results->expected_data);
    json_append_member(pattern_test,"expected_data",json_mkstring(hextostr));
    sprintf(hextostr,"%08x",packet_results->read_data);
    json_append_member(pattern_test,"read_data",json_mkstring(hextostr));
    json_append_member(newdoc,"pattern_test",pattern_test);

    json_append_member(newdoc,"pass",
        json_mkbool((packet_results->address_bit_failures == 0x0) &&
          (packet_results->error_location == 0xFFFFFFFF)));

    if (arg.final_test)
      json_append_member(newdoc,"final_test_id",json_mkstring(arg.ft_id));	

    post_debug_doc_mem_test(arg.crate_num,arg.slot_num,newdoc,&thread_fdset);
    json_delete(newdoc); // Only have to delete the head node
  }

  unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
}
void _attribute_print_and_delete_tree_json_(container *X, int indent, int max_items, JsonNode *root)
{
    if (X==NULL) return;


    int		i, j;
    JsonNode *jsonitems = NULL;
    int isgroup = 0;

    jsonitems = json_mkarray();


    for (i=0; i<vector_size(X); i++)
	{
        JsonNode *jsonitem = json_mkobject();
	    struct _attr_tree_	*item = vector_get(X, i).ptr;

	    if ((item->container_id == 0 && (item->hits == 0 || indent==-1)) || (item->hits==0 && !item->show_empty))
		{
		    if (item->children!=NULL)
			{
			    _attribute_print_and_delete_tree_json_(item->children, -1, item->max_items, jsonitem);
			}

		    if (item->free_value) free(item->value);
		    if (item->free_name) free(item->name);
		    if (item->querystr != NULL) free(item->querystr);
		    destroy(item->children);
		    destroy(item->query_param);
		    free(item);
		    continue;
		}


	    if (!(max_items > 0 && i>=max_items))
		{
		    char buf[1024];

		    if (item->children!=NULL) {
                isgroup = 1;
		    }
		    else { 
                isgroup = 0;
		    }


		    //if (item->key!=NULL) json_append_member(jsonitem, "key", json_mkstring(item->key) ); 
		    //if (item->value!=NULL) json_append_member(jsonitem, "value", json_mkstring(item->value) ); 
		    if (item->name!=NULL) json_append_member(jsonitem, "name", json_mkstring(item->name) ); 
		    if (item->icon!=NULL) json_append_member(jsonitem, "icon", json_mkstring(item->icon) );
		    if (item->querystr!=NULL) json_append_member(jsonitem, "query", json_mkstring(item->querystr) );
            if (item->container_id == 0) json_append_member(jsonitem, "hits", json_mknumber(item->hits) );

		    if (item->children!=NULL)
			{
			    _attribute_print_and_delete_tree_json_(item->children, indent+4, item->max_items, jsonitem);

			}
		}

	    if (item->free_value) free(item->value);
	    if (item->free_name) free(item->name);
	    if (item->querystr != NULL) free(item->querystr);
	    destroy(item->children);
	    destroy(item->query_param);
	    free(item);

        json_append_element(jsonitems, jsonitem );
	}


    if (isgroup==1)
        json_append_member(root, "group", jsonitems );
    else
        json_append_member(root, "items", jsonitems );
}
Exemple #15
0
int main(int argc, char **argv)
{
	int c, showversion = FALSE;
	char *kv, *js_string, *progname, buf[BUFSIZ], *p;
	int ttyin = isatty(fileno(stdin)), ttyout = isatty(fileno(stdout));
	int flags = 0;
	JsonNode *json, *op;

#if HAVE_PLEDGE
	if (pledge("stdio", NULL) == -1) {
		err(1, "pledge");
	}
#endif

	progname = (progname = strrchr(*argv, '/')) ? progname + 1 : *argv;

	while ((c = getopt(argc, argv, "aBpvV")) != EOF) {
		switch (c) {
			case 'a':
				flags |= FLAG_ARRAY;
				break;
			case 'B':
				flags |= FLAG_NOBOOL;
				break;
			case 'p':
				flags |= FLAG_PRETTY;
				break;
			case 'v':
				printf("jo %s\n", PACKAGE_VERSION);
				exit(0);
			case 'V':
				showversion = TRUE;
				break;
			default:
				exit(usage(progname));
		}
	}

	if (showversion) {
		return(version(flags));
	}

	argc -= optind;
	argv += optind;

	pile = json_mkobject();
	json = (flags & FLAG_ARRAY) ? json_mkarray() : json_mkobject();

	if (argc == 0) {
		while (fgets(buf, sizeof(buf), stdin) != NULL) {
			if (buf[strlen(buf) - 1] == '\n')
				buf[strlen(buf) - 1] = 0;
			p = ttyin ? utf8_from_locale(buf, -1) : buf;
			append_kv(json, flags, p);
			if (ttyin) utf8_free(p);
		}
	} else {
		while ((kv = *argv++)) {
			p = utf8_from_locale(kv, -1);
			append_kv(json, flags, p);
			utf8_free(p);
		}
	}

	/*
	 * See if we have any nested objects or arrays in the pile,
	 * and copy these into our main object if so.
	 */

	json_foreach(op, pile) {
		JsonNode *o;

		if (op->tag == JSON_ARRAY) {
			o = json_mkarray();
		} else if (op->tag == JSON_OBJECT) {
			o = json_mkobject();
		} else {
			continue;
		}
		json_copy_to_object(o, op, 0);
		json_append_member(json, op->key, o);
	}
Exemple #16
0
int CGTTest(int crateNum, uint32_t slotMask, uint32_t channelMask, int updateDB, int finalTest, int ecal)
{
  lprintf("*** Starting CGT Test ******************\n");

  uint32_t result;

  uint32_t bundles[3];
  int crate_id,slot_id,chan_id,nc_id,gt16_id,gt8_id,es16;

  int missing_bundles[16],chan_errors[16][32];
  char error_history[16][5000];
  char cur_msg[1000];
  int max_errors[16];
  uint32_t badchanmask;
  int num_chans;

  // zero some stuff
  memset(cur_msg,'\0',1000);
  num_chans = 0;
  for (int i=0;i<32;i++)
    if ((0x1<<i) & channelMask)
      num_chans++;
  for (int i=0;i<16;i++){
    for (int j=0;j<32;j++)
      chan_errors[i][j] = 0;
    missing_bundles[i] = 0;
    max_errors[i] = 0;
    memset(error_history[i],'\0',5000);
  }

  try{

    // set up mtc
    mtc->ResetMemory();
    //if (setup_pedestals(0,25,150,0,(0x1<<arg.crate_num)+MSK_TUB,(0x1<<arg.crate_num)+MSK_TUB))
    if (mtc->SetupPedestals(0,DEFAULT_PED_WIDTH,DEFAULT_GT_DELAY,DEFAULT_GT_FINE_DELAY,
          (0x1<<crateNum)+MSK_TUB,(0x1<<crateNum)+MSK_TUB)){
      lprintf("Error setting up mtc. Exiting\n");
      return -1;
    }
    mtc->SetGTCounter(0);

    // set up crate
    for (int i=0;i<16;i++){
      uint32_t select_reg = FEC_SEL*i;
      uint32_t crate_val = crateNum << FEC_CSR_CRATE_OFFSET;
      xl3s[crateNum]->RW(PED_ENABLE_R + select_reg + WRITE_REG,0x0,&result);
      xl3s[crateNum]->RW(CMOS_CHIP_DISABLE_R + select_reg + WRITE_REG,0xFFFFFFFF,&result);
      xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + WRITE_REG,crate_val | 0x6,&result);
      xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + WRITE_REG,crate_val,&result);
      xl3s[crateNum]->RW(CMOS_CHIP_DISABLE_R + select_reg + WRITE_REG,0x0,&result);
    }
    xl3s[crateNum]->DeselectFECs();

    lprintf("Crate number: %d\n"
        "Slot and Channel mask: %08x %08x\n",crateNum,slotMask,channelMask);

    // select desired fecs
    if (xl3s[crateNum]->SetCratePedestals(slotMask,channelMask)){
      lprintf("Error setting up crate for pedestals. Exiting\n");
      return -1;
    }
    xl3s[crateNum]->DeselectFECs();

    uint32_t num_peds = 0xFFFF + 10000;
    lprintf("Going to fire pulser %u times.\n",num_peds);

    XL3Packet packet;
    int total_pulses = 0;
    int numgt = 0;
    // we now send out gts in bunches, checking periodically
    // that we are getting the right count at the fecs
    for (int j=0;j<16;j++){
      // we skip 4999 gtids then check each 5000th one
      if (j != 13)
        numgt = 4999;
      else
        numgt = 534;

      mtc->MultiSoftGT(numgt);

      // now loop over slots and make sure we got all the gts
      for (int i=0;i<16;i++){
        if (((0x1<<i) & slotMask) && (max_errors[i] == 0)){
          xl3s[crateNum]->RW(FIFO_DIFF_PTR_R + FEC_SEL*i + READ_REG,0x0,&result);
          if ((result & 0x000FFFFF) != numgt*3*num_chans){
            sprintf(cur_msg,"Not enough bundles slot %d: expected %d, found %u\n",
                i,numgt*3*num_chans,result & 0x000FFFFF);
            lprintf("%s",cur_msg);
            if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
              sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
            else
              max_errors[i] = 2;
            missing_bundles[i] = 1;
          }

        } // end if in slot mask and not max errors
      } // end loop over slots

      // reset the fifo
      packet.header.packetType = RESET_FIFOS_ID;
      ResetFifosArgs *args = (ResetFifosArgs *) packet.payload;
      args->slotMask = slotMask;
      SwapLongBlock(args,sizeof(ResetFifosArgs)/sizeof(uint32_t));
      xl3s[crateNum]->SendCommand(&packet);
      for (int i=0;i<16;i++)
        if ((0x1<<i) & slotMask && (max_errors[i] == 0))
          xl3s[crateNum]->RW(GENERAL_CSR_R + FEC_SEL*i + WRITE_REG,
              (crateNum << FEC_CSR_CRATE_OFFSET),&result);



      // now send a single soft gt and make sure it looks good
      mtc->SoftGT();

      total_pulses += numgt+1;
      if (j == 13)
        total_pulses++; // rollover bug

      for (int i=0;i<16;i++){
        if (((0x1<<i) & slotMask) && (max_errors[i] == 0)){
          uint32_t select_reg = FEC_SEL*i;
          xl3s[crateNum]->RW(FIFO_DIFF_PTR_R + select_reg + READ_REG,0x0,&result);
          if ((result & 0x000FFFFF) != 3*num_chans){
            sprintf(cur_msg,"Not enough bundles slot %d: expected %d, found %u\n",
                i,3*num_chans,result & 0x000FFFFF);
            lprintf("%s",cur_msg);
            if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
              sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
            else
              max_errors[i] = 2;
            missing_bundles[i] = 1;
          }

          // read out one bundle for each channel
          badchanmask = channelMask;
          for (int k=0;k<((result&0x000FFFFF)/3);k++){
            xl3s[crateNum]->RW(READ_MEM + select_reg,0x0,&bundles[0]);
            xl3s[crateNum]->RW(READ_MEM + select_reg,0x0,&bundles[1]);
            xl3s[crateNum]->RW(READ_MEM + select_reg,0x0,&bundles[2]);

            crate_id = (int) UNPK_CRATE_ID(bundles); 
            slot_id = (int) UNPK_BOARD_ID(bundles);
            chan_id = (int) UNPK_CHANNEL_ID(bundles);
            nc_id = (int) UNPK_NC_CC(bundles);
            gt16_id = (int) UNPK_FEC_GT16_ID(bundles);
            gt8_id = (int) UNPK_FEC_GT8_ID(bundles);
            es16 = (int) UNPK_CGT_ES_16(bundles);

            badchanmask &= ~(0x1<<chan_id);

            if (crate_id != crateNum){
              sprintf(cur_msg,"Crate wrong for slot %d, chan %u: expected %d, read %u\n",
                  i,chan_id,crateNum,crate_id);
              lprintf("%s",cur_msg);
              if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
              else
                max_errors[i] = 2;
              chan_errors[i][chan_id] = 1;
            } 
            if (slot_id != i){
              sprintf(cur_msg,"Slot wrong for slot %d chan %u: expected %d, read %u\n",
                  i,chan_id,i,slot_id);
              lprintf("%s",cur_msg);
              if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
              else
                max_errors[i] = 2;
              chan_errors[i][chan_id] = 1;
            } 
            if (nc_id != 0x0){
              sprintf(cur_msg,"NC_CC wrong for slot %d chan %u: expected %d, read %u\n",
                  i,chan_id,0,nc_id);
              lprintf("%s",cur_msg);
              if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
              else
                max_errors[i] = 2;
              chan_errors[i][chan_id] = 1;
            } 
            if ((gt16_id + (65536*gt8_id)) != total_pulses){
              if (gt16_id == total_pulses%65536){
                sprintf(cur_msg,"Bad upper 8 Gtid bits for slot %d chan %u: expected %d, read %u\n"
                    "%08x %08x %08x\n",
                    i,chan_id,total_pulses-total_pulses%65536,(65536*gt8_id),bundles[0],
                    bundles[1],bundles[2]);
                lprintf("%s",cur_msg);
                if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                  sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
                else
                  max_errors[i] = 2;

              }else if (gt8_id == total_pulses/65536){
                sprintf(cur_msg,"Bad lower 16 gtid bits for slot %d chan %u: expected %d, read %u\n"
                    "%08x %08x %08x\n",
                    i,chan_id,total_pulses%65536,gt16_id,bundles[0],
                    bundles[1],bundles[2]);
                lprintf("%s",cur_msg);
                if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                  sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
                else
                  max_errors[i] = 2;
              }else{
                sprintf(cur_msg,"Bad gtid for slot %d chan %u: expected %d, read %u\n"
                    "%08x %08x %08x\n",
                    i,chan_id,total_pulses,gt16_id+(65536*gt8_id),bundles[0],
                    bundles[1],bundles[2]);
                lprintf("%s",cur_msg);
                if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                  sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
                else
                  max_errors[i] = 2;
              }
              chan_errors[i][chan_id] = 1;
            } 
            if (es16 != 0x0 && j >= 13){
              sprintf(cur_msg,"Synclear error for slot %d chan %u.\n",
                  i,chan_id);
              lprintf("%s",cur_msg);
              if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
              else
                max_errors[i] = 2;
              chan_errors[i][chan_id] = 1;
            } 
          } // end loop over bundles being read out

          for (int k=0;k<32;k++){
            if ((0x1<<k) & badchanmask){
              sprintf(cur_msg,"No bundle found for slot %d chan %d\n",i,k);
              lprintf("%s",cur_msg);
              if ((strlen(error_history[i]) + strlen(cur_msg)) < sizeof(error_history[i]))
                sprintf(error_history[i]+strlen(error_history[i]),"%s",cur_msg);
              else
                max_errors[i] = 2;
              chan_errors[i][k] = 1;
            }
          }

        } // end if in slot mask and not max errors
      } // end loop over slots

      // check if we should stop any slot
      // because there are too many errors
      for (int i=0;i<16;i++){
        if (((strlen(error_history[i]) > 5000) && (max_errors[i] == 0)) || (max_errors[i] == 2)){
          lprintf("Too many errors slot %d. Skipping that slot\n",i);
          max_errors[i] = 1;
        }
      }

      lprintf("%d pulses\n",total_pulses);
      for (int i=0;i<16;i++)
        sprintf(error_history[i]+strlen(error_history[i]),"%d pulses\n",total_pulses);

    } // end loop over gt bunches

    if (updateDB){
      lprintf("updating the database\n");
      int passflag;
      for (int slot=0;slot<16;slot++){
        if ((0x1<<slot) & slotMask){
          lprintf("updating slot %d\n",slot);
          passflag = 1;
          JsonNode *newdoc = json_mkobject();
          json_append_member(newdoc,"type",json_mkstring("cgt_test"));
          json_append_member(newdoc,"missing_bundles",json_mkbool(missing_bundles[slot]));
          if (missing_bundles[slot] > 0)
            passflag = 0;
          JsonNode *chan_errs = json_mkarray();
          for (int i=0;i<32;i++){
            json_append_element(chan_errs,json_mkbool(chan_errors[slot][i]));
            if (chan_errors[slot][i] > 0)
              passflag = 0;
          }
          json_append_member(newdoc,"errors",chan_errs);
          json_append_member(newdoc,"printout",json_mkstring(error_history[slot]));
          json_append_member(newdoc,"pass",json_mkbool(passflag));

          if (finalTest)
            json_append_member(newdoc,"final_test_id",json_mkstring(finalTestIDs[crateNum][slot]));	
          if (ecal)
            json_append_member(newdoc,"ecal_id",json_mkstring(ecalID));	
          PostDebugDoc(crateNum,slot,newdoc);
          json_delete(newdoc); // only delete the head node
        }
      }
    }

  }
  catch(const char* s){
    lprintf("CGTTest: %s\n",s);
  }

  lprintf("Ending cgt test\n");
  lprintf("****************************************\n");
  return 0;
}
Exemple #17
0
  std::string SourceMap::render_srcmap(Context &ctx) {

    const bool include_sources = ctx.c_options.source_map_contents;
    const std::vector<std::string> links = ctx.srcmap_links;
    const std::vector<Resource>& sources(ctx.resources);

    JsonNode* json_srcmap = json_mkobject();

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

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

    // 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);
    }

    JsonNode *json_includes = json_mkarray();
    for (size_t i = 0; i < source_index.size(); ++i) {
      std::string include(links[source_index[i]]);
      if (ctx.c_options.source_map_file_urls) {
        include = File::rel2abs(include);
        // check for windows abs path
        if (include[0] == '/') {
          // ends up with three slashes
          include = "file://" + include;
        } else {
          // needs an additional slash
          include = "file:///" + include;
        }
      }
      const char* inc = include.c_str();
      JsonNode *json_include = json_mkstring(inc);
      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 Resource& resource(sources[source_index[i]]);
        JsonNode *json_content = json_mkstring(resource.contents);
        json_append_element(json_contents, json_content);
      }
      if (json_contents->children.head)
        json_append_member(json_srcmap, "sourcesContent", json_contents);
    }

    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);

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

    char *str = json_stringify(json_srcmap, "\t");
    std::string result = std::string(str);
    free(str);
    json_delete(json_srcmap);
    return result;
  }
Exemple #18
0
int GTValidTest(int crateNum, uint32_t slotMask, uint32_t channelMask, float gtCutoff, int twiddleOn, int updateDB, int finalTest, int ecal)
{
  lprintf("*** Starting GT Valid Test *************\n");

  uint32_t result;
  int error;
  int slot_errors;
  int chan_errors[32];

  uint16_t tacbits[32];
  uint16_t max_isetm[32],isetm[2];
  float max_gtvalid[32], gtvalid_first[2][32], gtvalid_second[2][32], gtvalid_final[2][32];
  float gmax[2],gmin[2];
  int cmax[2],cmin[2];


  try{

    // setup crate
    for (int i=0;i<16;i++){
      if ((0x1<<i) & slotMask){
        uint32_t select_reg = FEC_SEL*i;
        // disable pedestals
        xl3s[crateNum]->RW(PED_ENABLE_R + select_reg + WRITE_REG,0x0,&result);
        // reset fifo
        xl3s[crateNum]->RW(CMOS_CHIP_DISABLE_R + select_reg + WRITE_REG,0xFFFFFFFF,&result);
        xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + READ_REG,0x0,&result);
        xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + WRITE_REG,
            result | (crateNum << FEC_CSR_CRATE_OFFSET) | 0x6,&result);
        xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + WRITE_REG,
            (crateNum << FEC_CSR_CRATE_OFFSET),&result);
        xl3s[crateNum]->RW(CMOS_CHIP_DISABLE_R + select_reg + WRITE_REG,0x0,&result);
      }
    }
    xl3s[crateNum]->DeselectFECs();

    if (mtc->SetupPedestals(0,DEFAULT_PED_WIDTH,10,0,(0x1<<crateNum),(0x1<<crateNum))){
      lprintf("Error setting up mtc. Exiting\n");
      return -1;
    }

    // loop over slot
    for (int i=0;i<16;i++){
      if ((0x1<<i) & slotMask){
        uint32_t select_reg = FEC_SEL*i;

        slot_errors = 0;
        for (int j=0;j<32;j++){
          chan_errors[j] = 0;
        }
        error = xl3s[crateNum]->LoadsDac(d_vmax,VMAX,i);
        error+= xl3s[crateNum]->LoadsDac(d_tacref,TACREF,i);

        // We first need to find the max gtvalid per channel, and find the
        // ISETM settings per channel for max gtvalid 
        lprintf("Finding max possible gtvalids\n");
        
        // turn off twiddle bits
        error+= xl3s[crateNum]->LoadsDac(d_iseta[0],ISETA_NO_TWIDDLE,i);
        error+= xl3s[crateNum]->LoadsDac(d_iseta[1],ISETA_NO_TWIDDLE,i);
        for (int j=0;j<32;j++)
          tacbits[j] = 0x00;
        error+= xl3s[crateNum]->LoadTacbits(i,tacbits);
        if (error){
          lprintf("Error setting up TAC voltages. Exiting\n");
          return -1;
        }

        // loop over channels
        for (int j=0;j<32;j++){
          if ((0x1<<j) & channelMask){
            xl3s[crateNum]->RW(PED_ENABLE_R + FEC_SEL*i + WRITE_REG,1<<j,&result);
            max_gtvalid[j] = 0;
            // first try with the default ISETM
            error+= xl3s[crateNum]->LoadsDac(d_isetm[0],ISETM_MAX_GTVALID,i);
            error+= xl3s[crateNum]->LoadsDac(d_isetm[1],ISETM_MAX_GTVALID,i);
            if (IsGTValidLonger(crateNum,i,GTMAX)){
              max_gtvalid[j] = GTMAX;
              max_isetm[j] = ISETM_MAX_GTVALID;
            }else{
              // scan to see if any ISETM value puts this channel over GTMAX
              int done = 0;
              for (int k=0;k<8;k++){
                float max_time = 1000.0-100.0*k;
                for (int l=0;l<50;l++){
                  uint32_t isetm_temp = l*5;
                  error+= xl3s[crateNum]->LoadsDac(d_isetm[0],isetm_temp,i);
                  error+= xl3s[crateNum]->LoadsDac(d_isetm[1],isetm_temp,i);
                  if (IsGTValidLonger(crateNum,i,max_time)){
                    max_gtvalid[j] = max_time;
                    max_isetm[j] = isetm_temp;
                    done = 1;
                    break;
                  }
                }
                if (done)
                  break;
              }
              // if the max gtvalid time is too small, fail this channel
              if (max_gtvalid[j] == 0)
                chan_errors[j] = 1; 
            }
          } // end channel mask
        } // end loop over channels




        // ok we now know what the max gtvalid is for each channel and what
        // isetm value will get us it
        // now we increment isetm until every channels gtvalid is shorter than
        // gtcutoff
        for (int wt=0;wt<2;wt++){
          lprintf("Finding ISETM values for crate %d, slot %d TAC %d\n",
              crateNum,i,wt);
          int ot = (wt+1)%2;
          isetm[wt] = ISETM_MIN;
          for (int j=0;j<32;j++){
            lprintf(".");
            fflush(stdout);
            xl3s[crateNum]->RW(PED_ENABLE_R + FEC_SEL*i + WRITE_REG,1<<j,&result);
            error+= xl3s[crateNum]->LoadsDac(d_isetm[ot],max_isetm[j],i);
            while (isetm[wt] < 255){
              error+= xl3s[crateNum]->LoadsDac(d_isetm[wt],isetm[wt],i);
              if (IsGTValidLonger(crateNum,i,gtCutoff)){
                isetm[wt]++;
              }else{
                break;
              }
            }
          }
          for (int j=0;j<32;j++){
            lprintf(".");
            fflush(stdout);
            xl3s[crateNum]->RW(PED_ENABLE_R + FEC_SEL*i + WRITE_REG,1<<j,&result);
            error+= xl3s[crateNum]->LoadsDac(d_isetm[ot],max_isetm[j],i);
            while (isetm[wt] < 255){
              error+= xl3s[crateNum]->LoadsDac(d_isetm[wt],isetm[wt],i);
              if (IsGTValidLonger(crateNum,i,gtCutoff)){
                isetm[wt]++;
                printf("incremented again!\n");
              }else{
                break;
              }
            }
          }

          printf("\n");
        } // end loop over tacs


        // we are done getting our dac values. lets measure and display the final gtvalids
        for (int wt=0;wt<2;wt++){
          lprintf("\nMeasuring GTVALID for crate %d, slot %d, TAC %d\n",
              crateNum,i,wt);

          // loop over channel to measure inital GTVALID and find channel with max
          for (int j=0;j<32;j++){
            if ((0x1<<j) & channelMask){
              error+= xl3s[crateNum]->LoadsDac(d_isetm[0],isetm[0],i);
              error+= xl3s[crateNum]->LoadsDac(d_isetm[1],isetm[1],i);
              xl3s[crateNum]->RW(PED_ENABLE_R + FEC_SEL*i + WRITE_REG,1<<j,&result);
              gtvalid_final[wt][j] = MeasureGTValid(crateNum,i,wt,max_gtvalid[j],max_isetm[j]);
            } // end if chan mask
          } // end loop over channels
          // find maximum gtvalid time
          gmax[wt] = 0.0;
          cmax[wt] = 0;
          for (int j=0;j<32;j++)
            if ((0x1<<j) & channelMask)
              if (gtvalid_final[wt][j] > gmax[wt]){
                gmax[wt] = gtvalid_final[wt][j];
                cmax[wt] = j;
              }

          // find minimum gtvalid time
          gmin[wt] = 9999.0;
          cmin[wt] = 0;
          for (int j=0;j<32;j++)
            if ((0x1<<j) & channelMask)
              if (gtvalid_final[wt][j] < gmin[wt]){
                gmin[wt] = gtvalid_final[wt][j];
                cmin[wt] = j;
              }


        } // end loop over tacs

        // print out
        lprintf("\n--------------------------------------------------------\n");
        lprintf("Crate %d Slot %d - GTVALID FINAL results, time in ns:\n",crateNum,i);
        lprintf("--------------------------------------------------------\n");
        if (!twiddleOn)
          lprintf(" >>> ISETA0/1 = 0, no TAC twiddle bits set\n");
        lprintf("set up: VMAX: %hu, TACREF: %hu, ",VMAX,TACREF);
        if (twiddleOn)
          lprintf("ISETA: %hu\n",ISETA);
        else
          lprintf("ISETA: %hu\n",ISETA_NO_TWIDDLE);
        lprintf("Found ISETM0: %d, ISETM1: %d\n",isetm[0],isetm[1]);
        lprintf("Chan Tacbits GTValid 0/1:\n");
        for (int j=0;j<32;j++){
          if ((0x1<<j) & channelMask){
            lprintf("%02d 0x%02x %4.1f %4.1f",
                j,tacbits[j],
                gtvalid_final[0][j],gtvalid_final[1][j]);
            if (isetm[0] == ISETM_MIN || isetm[1] == ISETM_MIN)
              lprintf(">>> Warning: isetm not adjusted\n");
            else
              lprintf("\n");
          }
        }

        lprintf(">>> Maximum TAC0 GTValid - Chan %02d: %4.1f\n",
            cmax[0],gmax[0]);
        lprintf(">>> Minimum TAC0 GTValid - Chan %02d: %4.1f\n",
            cmin[0],gmin[0]);
        lprintf(">>> Maximum TAC1 GTValid - Chan %02d: %4.1f\n",
            cmax[1],gmax[1]);
        lprintf(">>> Minimum TAC1 GTValid - Chan %02d: %4.1f\n",
            cmin[1],gmin[1]);

        if (abs(isetm[1] - isetm[0]) > 10)
          slot_errors |= 0x1;
        for (int j=0;j<32;j++){
          if ((gtvalid_final[0][j] < 0) || gtvalid_final[1][j] < 0)
            chan_errors[j] = 1;
        }


        //store in DB
        if (updateDB){
          lprintf("updating the database\n");
          JsonNode *newdoc = json_mkobject();
          json_append_member(newdoc,"type",json_mkstring("cmos_m_gtvalid"));

          json_append_member(newdoc,"vmax",json_mknumber((double)VMAX));
          json_append_member(newdoc,"tacref",json_mknumber((double)TACREF));

          JsonNode* isetm_new = json_mkarray();
          JsonNode* iseta_new = json_mkarray();
          json_append_element(isetm_new,json_mknumber((double)isetm[0]));
          json_append_element(isetm_new,json_mknumber((double)isetm[1]));
          if (twiddleOn){
            json_append_element(iseta_new,json_mknumber((double)ISETA));
            json_append_element(iseta_new,json_mknumber((double)ISETA));
          }else{
            json_append_element(iseta_new,json_mknumber((double)ISETA_NO_TWIDDLE));
            json_append_element(iseta_new,json_mknumber((double)ISETA_NO_TWIDDLE));
          }
          json_append_member(newdoc,"isetm",isetm_new);
          json_append_member(newdoc,"iseta",iseta_new);

          JsonNode* channels = json_mkarray();
          for (int j=0;j<32;j++){
            JsonNode *one_chan = json_mkobject();
            json_append_member(one_chan,"id",json_mknumber((double) j));
            json_append_member(one_chan,"tac_shift",json_mknumber((double) (tacbits[j])));
            json_append_member(one_chan,"gtvalid0",json_mknumber((double) (gtvalid_final[0][j])));
            json_append_member(one_chan,"gtvalid1",json_mknumber((double) (gtvalid_final[1][j])));
            json_append_member(one_chan,"errors",json_mkbool(chan_errors[j]));
            if (chan_errors[j])
              slot_errors |= 0x2;
            json_append_element(channels,one_chan);
          }
          json_append_member(newdoc,"channels",channels);

          json_append_member(newdoc,"pass",json_mkbool(!(slot_errors)));
          json_append_member(newdoc,"slot_errors",json_mknumber(slot_errors));
          if (finalTest)
            json_append_member(newdoc,"final_test_id",json_mkstring(finalTestIDs[crateNum][i]));	
          if (ecal)
            json_append_member(newdoc,"ecal_id",json_mkstring(ecalID));	
          PostDebugDoc(crateNum,i,newdoc);
          json_delete(newdoc); // only delete the head
        }
        lprintf("******************************************\n");



      } // end in slotmask
    } // end loop over slots
  } // end try
  catch(const char* s){
    lprintf("GTValidTest: %s\n",s);
  }
  return 0;
}
Exemple #19
0
static int event_parse_action(char *action, struct rules_t *obj, int validate) {
	logprintf(LOG_STACK, "%s(...)", __FUNCTION__);

	struct JsonNode *jvalues = NULL;
	char *var1 = NULL, *func = NULL, *var2 = NULL, *tmp = action;
	char *var3 = NULL, *var4 = NULL;
	int element = 0, match = 0, error = 0, order = 0;
	int hasaction = 0, hasquote = 0, match1 = 0, match2 = 0;
	unsigned long len = strlen(tmp), pos = 0, word = 0, hadquote = 0;

	if(obj->arguments == NULL) {
		obj->arguments = json_mkobject();
		while(pos <= len) {
			/* If we encounter a space we have the formula part */
			if(tmp[pos] == '"') {
				hasquote ^= 1;
				if(hasquote == 1) {
					word++;
				} else {
					hadquote = 1;
				}
			}
			if(hasquote == 0 && (tmp[pos] == ' ' || pos == len)) {
				switch(element) {
					/* The first value of three is always the first variable.
						 The second value is always the function.
						 The third value of the three is always the second variable (or second formula).
					*/
					case 0:
						var1 = REALLOC(var1, ((pos-word)+1));
						memset(var1, '\0', ((pos-word)+1));
						strncpy(var1, &tmp[word], (pos-word)-hadquote);
					break;
					case 1:
						func = REALLOC(func, ((pos-word)+1));
						memset(func, '\0', ((pos-word)+1));
						strncpy(func, &tmp[word], (pos-word)-hadquote);
					break;
					case 2:
						var2 = REALLOC(var2, ((pos-word)+1));
						memset(var2, '\0', ((pos-word)+1));
						strncpy(var2, &tmp[word], (pos-word)-hadquote);
					break;
					default:;
				}
				hadquote = 0;
				word = pos+1;
				element++;
				if(element > 2) {
					element = 0;
				}
			}
			if(hasaction == 0 && var1 && strlen(var1) > 0) {
				match = 0;
				obj->action = event_actions;
				while(obj->action) {
					if(strcmp(obj->action->name, var1) == 0) {
						match = 1;
						break;
					}
					obj->action = obj->action->next;
				}
				if(match == 1) {
					hasaction = 1;
					element = 0;
				} else {
					logprintf(LOG_ERR, "action \"%s\" doesn't exists", var1);
					error = 1;
					break;
				}
			} else if(func && strlen(func) > 0 &&
				 var1 && strlen(var1) > 0 &&
				 var2 && strlen(var2) > 0) {
				 int hasand = 0;
				if(strcmp(var2, "AND") == 0) {
					hasand = 1;
					word -= strlen(var2)+1;
					if(jvalues == NULL) {
						jvalues = json_mkarray();
					}
					if(isNumeric(func) == 0) {
						json_append_element(jvalues, json_mknumber(atof(func), nrDecimals(func)));
					} else {
						json_append_element(jvalues, json_mkstring(func));
					}
					element = 0;
					while(pos <= len) {
						if(tmp[pos] == '"') {
							hasquote ^= 1;
							if(hasquote == 1) {
								word++;
							} else {
								hadquote = 1;
							}
						}
						if(hasquote == 0 && (tmp[pos] == ' ' || pos == len)) {
							switch(element) {
								/* The first value of three is always the first variable.
									 The second value is always the function.
									 The third value of the three is always the second variable (or second formula).
								*/
								case 0:
									var3 = REALLOC(var3, ((pos-word)+1));
									memset(var3, '\0', ((pos-word)+1));
									strncpy(var3, &tmp[word], (pos-word)-hadquote);
								break;
								case 1:
									var4 = REALLOC(var4, ((pos-word)+1));
									memset(var4, '\0', ((pos-word)+1));
									strncpy(var4, &tmp[word], (pos-word)-hadquote);
								break;
								default:;
							}
							hadquote = 0;
							word = pos+1;
							element++;
							if(element > 1) {
								element = 0;
							}
						}
						pos++;
						if(var3 && strlen(var3) > 0 &&
							 var4 && strlen(var4) > 0) {
							if(strcmp(var3, "AND") != 0) {
								var2 = REALLOC(var2, strlen(var3)+1);
								strcpy(var2, var3);
								pos -= strlen(var3)+strlen(var4)+2;
								word -= strlen(var3)+strlen(var4)+2;
								break;
							}
							if(isNumeric(var4) == 0) {
								json_append_element(jvalues, json_mknumber(atof(var4), nrDecimals(var4)));
							} else {
								json_append_element(jvalues, json_mkstring(var4));
							}
							element = 0;
							if(var3) {
								memset(var3, '\0', strlen(var3));
							} if(var4) {
								memset(var4, '\0', strlen(var4));
							}
						}
					}
				}
				match1 = 0, match2 = 0;
				struct options_t *opt = obj->action->options;
				while(opt) {
					if(strcmp(opt->name, var1) == 0) {
						match1 = 1;
					}
					if(strcmp(opt->name, var2) == 0) {
						match2 = 1;
					}
					if(match1 == 1 && match2 == 1) {
						break;
					}
					opt = opt->next;
				}
				/* If we are at the end of our rule
					 we only match the first option */
				if(pos == len+1) {
					match2 = 1;
				}
				if(match1 == 1 && match2 == 1) {
					struct JsonNode *jobj = json_mkobject();
					order++;
					if(hasand == 1) {
						json_append_member(jobj, "value", jvalues);
						json_append_member(jobj, "order", json_mknumber(order, 0));
						jvalues = NULL;
					} else {
						jvalues = json_mkarray();
						if(isNumeric(func) == 0) {
							json_append_element(jvalues, json_mknumber(atof(func), nrDecimals(func)));
							json_append_member(jobj, "value", jvalues);
							json_append_member(jobj, "order", json_mknumber(order, 0));
							jvalues = NULL;
						} else {
							json_append_element(jvalues, json_mkstring(func));
							json_append_member(jobj, "value", jvalues);
							json_append_member(jobj, "order", json_mknumber(order, 0));
							jvalues = NULL;
						}
					}
					json_append_member(obj->arguments, var1, jobj);
				} else if(match1 == 0) {
					logprintf(LOG_ERR, "action \"%s\" doesn't accept option \"%s\"", obj->action->name, var1);
					error = 1;
					if(jvalues) {
						json_delete(jvalues);
					}
					break;
				} else if(match2 == 0) {
					logprintf(LOG_ERR, "action \"%s\" doesn't accept option \"%s\"", obj->action->name, var2);
					error = 1;
					if(jvalues) {
						json_delete(jvalues);
					}
					break;
				}
				element = 0, match1 = 0, match2 = 0;
				if(hasand == 0) {
					pos -= strlen(var2)+1;
					word -= strlen(var2)+1;
				}
				if(var1) {
					memset(var1, '\0', strlen(var1));
				} if(func) {
					memset(func, '\0', strlen(func));
				} if(var2) {
					memset(var2, '\0', strlen(var2));
				} if(var3) {
					memset(var3, '\0', strlen(var3));
				} if(var4) {
					memset(var4, '\0', strlen(var4));
				}
				hasand = 0;
			}
			pos++;
		}
		if(error == 0) {
			if(var1 && strlen(var1) > 0 &&
				 func && strlen(func) > 0) {
				match1 = 0;
				struct options_t *opt = obj->action->options;
				while(opt) {
					if(strcmp(opt->name, var1) == 0) {
						match1 = 1;
					}
					if(match1 == 1) {
						break;
					}
					opt = opt->next;
				}
				if(match1 == 1) {
					struct JsonNode *jobj = json_mkobject();
					order++;
					jvalues = json_mkarray();
					if(isNumeric(func) == 0) {
						json_append_element(jvalues, json_mknumber(atof(func), nrDecimals(func)));
						json_append_member(jobj, "value", jvalues);
						json_append_member(jobj, "order", json_mknumber(order, 0));
						jvalues = NULL;
					} else {
						json_append_element(jvalues, json_mkstring(func));
						json_append_member(jobj, "value", jvalues);
						json_append_member(jobj, "order", json_mknumber(order, 0));
						jvalues = NULL;
					}
					json_append_member(obj->arguments, var1, jobj);
				} else {
					error = 1;
				}
			}
		}
		if(error == 0) {
			struct options_t *opt = obj->action->options;
			struct JsonNode *joption = NULL;
			struct JsonNode *jvalue = NULL;
			struct JsonNode *jchild = NULL;
			while(opt) {
				if((joption = json_find_member(obj->arguments, opt->name)) == NULL) {
					if(opt->conftype == DEVICES_VALUE) {
						logprintf(LOG_ERR, "action \"%s\" is missing option \"%s\"", obj->action->name, opt->name);
						error = 1;
						break;
					}
				} else {
					if((jvalue = json_find_member(joption, "value")) != NULL) {
						if(jvalue->tag == JSON_ARRAY) {
							jchild = json_first_child(jvalue);
							while(jchild) {
								if(jchild->tag != JSON_NUMBER && opt->vartype == JSON_NUMBER) {
									logprintf(LOG_ERR, "action \"%s\" option \"%s\" only accepts numbers", obj->action->name, opt->name);
									error = 1;
									break;
								}
								if(jchild->tag != JSON_STRING && opt->vartype == JSON_STRING) {
									logprintf(LOG_ERR, "action \"%s\" option \"%s\" only accepts strings", obj->action->name, opt->name);
									error = 1;
									break;
								}
								jchild = jchild->next;
							}
						}
					}
				}
				opt = opt->next;
			}
			if(error == 0) {
				jchild = json_first_child(obj->arguments);
				while(jchild) {
					match = 0;
					opt = obj->action->options;
					while(opt) {
						if(strcmp(jchild->key, opt->name) == 0) {
							match = 1;
							break;
						}
						opt = opt->next;
					}
					if(match == 0) {
						logprintf(LOG_ERR, "action \"%s\" doesn't accept option \"%s\"", obj->action->name, jchild->key);
						error = 1;
						break;
					}
					jchild = jchild->next;
				}
			}
		}
	}

	if(error == 0) {
		if(validate == 1) {
			if(obj->action->checkArguments) {
				error = obj->action->checkArguments(obj->arguments);
			}
		} else {
			if(obj->action->run) {
				error = obj->action->run(obj->arguments);
			}
		}
	}
	if(var1) {
		FREE(var1);
		var1 = NULL;
	} if(func) {
		FREE(func);
		func = NULL;
	} if(var2) {
		FREE(var2);
		var2 = NULL;
	}	if(var3) {
		FREE(var3);
		var3 = NULL;
	} if(var4) {
		FREE(var4);
		var4 = NULL;
	}
	return error;
}
Exemple #20
0
int ChinjScan(int crateNum, uint32_t slotMask, uint32_t channelMask, float frequency, int gtDelay, int pedWidth, int numPedestals, float upper, float lower, int qSelect, int pedOn, int updateDB, int finalTest)
{
  lprintf("*** Starting Charge Injection Test *****\n");

  float *qhls;
  float *qhss;
  float *qlxs;
  float *tacs;
  int *scan_errors;
  int errors = 0;
  int count,crateID,ch,cell,num_events;
  uint16_t dacvalue;
  uint32_t *pmt_buffer,*pmt_iter;
  struct pedestal *ped;
  uint32_t result, select_reg;
  uint32_t default_ch_mask;
  int chinj_err[16];

  pmt_buffer = (uint32_t *) malloc( 0x20000*sizeof(uint32_t));
  ped = (struct pedestal *) malloc( 32 * sizeof(struct pedestal));
  qhls = (float *) malloc(32*16*2*26*sizeof(float));
  qhss = (float *) malloc(32*16*2*26*sizeof(float));
  qlxs = (float *) malloc(32*16*2*26*sizeof(float));
  tacs = (float *) malloc(32*16*2*26*sizeof(float));
  scan_errors = (int *) malloc(32*16*2*26*sizeof(int));
  if (pmt_buffer == NULL || ped == NULL || qhls == NULL || qhss == NULL || qlxs == NULL || tacs == NULL || scan_errors == NULL){
    lprintf("Problem mallocing! Exiting\n");
    if (pmt_buffer != NULL)
      free(pmt_buffer);
    if (ped != NULL)
      free(ped);
    if (qhls != NULL)
      free(qhls);
    if (qhss != NULL)
      free(qhss);
    if (qlxs != NULL)
      free(qlxs);
    if (tacs != NULL)
      free(tacs);
    if (scan_errors != NULL)
      free(scan_errors);
    return -1;
  }

  for (int i=0;i<16;i++){
    chinj_err[i] = 0;
    for (int j=0;j<32;j++)
      for (int k=0;k<26;k++)
        for (int l=0;l<2;l++){
          qhls[k*16*32*2+i*32*2+j*2+l] = 0;
          qhss[k*16*32*2+i*32*2+j*2+l] = 0;
          qlxs[k*16*32*2+i*32*2+j*2+l] = 0;
          tacs[k*16*32*2+i*32*2+j*2+l] = 0;
          scan_errors[k*16*32*2+i*32*2+j*2+l] = 0;
        }
  }

  try {

    for (int dac_iter=0;dac_iter<26;dac_iter++){

      dacvalue = dac_iter*10;

      for (int slot_iter = 0; slot_iter < 16; slot_iter ++){
        if ((0x1 << slot_iter) & slotMask){
          select_reg = FEC_SEL*slot_iter;
          xl3s[crateNum]->RW(CMOS_CHIP_DISABLE_R + select_reg + WRITE_REG,0xFFFFFFFF,&result);
          xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + WRITE_REG,0x2,&result);
          xl3s[crateNum]->RW(GENERAL_CSR_R + select_reg + WRITE_REG,0x0,&result);
          xl3s[crateNum]->RW(CMOS_CHIP_DISABLE_R + select_reg + WRITE_REG,~channelMask,&result);
        }
      }
      xl3s[crateNum]->DeselectFECs(); 

      //pt_printsend("Reset FECs\n");

      errors = 0;
      errors += xl3s[crateNum]->LoadCrateAddr(slotMask);
      if (pedOn){
        //pt_printsend("enabling pedestals.\n");
        errors += xl3s[crateNum]->SetCratePedestals(slotMask, channelMask);
      }
      xl3s[crateNum]->DeselectFECs(); 

      if (errors){
        lprintf("error setting up FEC crate for pedestals. Exiting.\n");
        free(pmt_buffer);
        free(ped);
        free(qhls);
        free(qhss);
        free(qlxs);
        free(tacs);
        free(scan_errors);
        return -1;
      }

      //setup charge injection
      xl3s[crateNum]->SetupChargeInjection(slotMask,channelMask,dacvalue);

      errors = mtc->SetupPedestals(0,pedWidth,gtDelay,DEFAULT_GT_FINE_DELAY,(0x1<<crateNum),(0x1<<crateNum));
      if (errors){
        lprintf("Error setting up MTC for pedestals. Exiting.\n");
        mtc->UnsetPedCrateMask(MASKALL);
        mtc->UnsetGTCrateMask(MASKALL);
        free(pmt_buffer);
        free(ped);
        free(qhls);
        free(qhss);
        free(qlxs);
        free(tacs);
        free(scan_errors);
        return -1;
      }

      // send the softgts
      mtc->MultiSoftGT(numPedestals*16);

      // LOOP OVER SLOTS
      for (int slot_iter = 0; slot_iter < 16; slot_iter ++){
        if ((0x1<<slot_iter) & slotMask){

          // initialize pedestal struct
          for (int i=0;i<32;i++){
            //pedestal struct
            ped[i].channelnumber = i; //channel numbers start at 0!!!
            ped[i].per_channel = 0;

            for (int j=0;j<16;j++){
              ped[i].thiscell[j].cellno = j;
              ped[i].thiscell[j].per_cell = 0;
              ped[i].thiscell[j].qlxbar = 0;
              ped[i].thiscell[j].qlxrms = 0;
              ped[i].thiscell[j].qhlbar = 0;
              ped[i].thiscell[j].qhlrms = 0;
              ped[i].thiscell[j].qhsbar = 0;
              ped[i].thiscell[j].qhsrms = 0;
              ped[i].thiscell[j].tacbar = 0;
              ped[i].thiscell[j].tacrms = 0;
            }
          }


          /////////////////////
          // READOUT BUNDLES //
          /////////////////////

          count = xl3s[crateNum]->ReadOutBundles(slot_iter, pmt_buffer, numPedestals*32*16,1);

          //check for readout errors
          if (count <= 0){
            lprintf("there was an error in the count!\n");
            lprintf("Errors reading out MB(%2d) (errno %i)\n", slot_iter, count);
            errors+=1;
            continue;
          }else{
            //pt_printsend("MB(%2d): %5d bundles read out.\n", slot_iter, count);
          }

          if (count < numPedestals*32*16)
            errors += 1;

          //process data
          pmt_iter = pmt_buffer;

          for (int i=0;i<count;i++){
            crateID = (int) UNPK_CRATE_ID(pmt_iter);
            if (crateID != crateNum){
              lprintf("Invalid crate ID seen! (crate ID %2d, bundle %2i)\n", crateID, i);
              pmt_iter+=3;
              continue;
            }
            ch = (int) UNPK_CHANNEL_ID(pmt_iter);
            cell = (int) UNPK_CELL_ID(pmt_iter);
            ped[ch].thiscell[cell].qlxbar += (double) MY_UNPK_QLX(pmt_iter);
            ped[ch].thiscell[cell].qhsbar += (double) UNPK_QHS(pmt_iter);
            ped[ch].thiscell[cell].qhlbar += (double) UNPK_QHL(pmt_iter);
            ped[ch].thiscell[cell].tacbar += (double) UNPK_TAC(pmt_iter);

            ped[ch].thiscell[cell].qlxrms += pow((double) MY_UNPK_QLX(pmt_iter),2.0);
            ped[ch].thiscell[cell].qhsrms += pow((double) UNPK_QHS(pmt_iter),2.0);
            ped[ch].thiscell[cell].qhlrms += pow((double) UNPK_QHL(pmt_iter),2.0);
            ped[ch].thiscell[cell].tacrms += pow((double) UNPK_TAC(pmt_iter),2.0);

            ped[ch].per_channel++;
            ped[ch].thiscell[cell].per_cell++;

            pmt_iter += 3; //increment pointer
          }

          // do final step
          // final step of calculation
          for (int i=0;i<32;i++){
            if (ped[i].per_channel > 0){
              for (int j=0;j<16;j++){
                num_events = ped[i].thiscell[j].per_cell;

                //don't do anything if there is no data here or n=1 since
                //that gives 1/0 below.
                if (num_events > 1){

                  // now x_avg = sum(x) / N, so now xxx_bar is calculated
                  ped[i].thiscell[j].qlxbar /= num_events;
                  ped[i].thiscell[j].qhsbar /= num_events;
                  ped[i].thiscell[j].qhlbar /= num_events;
                  ped[i].thiscell[j].tacbar /= num_events;

                  // now x_rms^2 = n/(n-1) * (<xxx^2>*N/N - xxx_bar^2)
                  ped[i].thiscell[j].qlxrms = num_events / (num_events -1)
                    * ( ped[i].thiscell[j].qlxrms / num_events
                        - pow( ped[i].thiscell[j].qlxbar, 2.0));
                  ped[i].thiscell[j].qhlrms = num_events / (num_events -1)
                    * ( ped[i].thiscell[j].qhlrms / num_events
                        - pow( ped[i].thiscell[j].qhlbar, 2.0));
                  ped[i].thiscell[j].qhsrms = num_events / (num_events -1)
                    * ( ped[i].thiscell[j].qhsrms / num_events
                        - pow( ped[i].thiscell[j].qhsbar, 2.0));
                  ped[i].thiscell[j].tacrms = num_events / (num_events -1)
                    * ( ped[i].thiscell[j].tacrms / num_events
                        - pow( ped[i].thiscell[j].tacbar, 2.0));

                  // finally x_rms = sqrt(x_rms^2)
                  ped[i].thiscell[j].qlxrms = sqrt(ped[i].thiscell[j].qlxrms);
                  ped[i].thiscell[j].qhsrms = sqrt(ped[i].thiscell[j].qhsrms);
                  ped[i].thiscell[j].qhlrms = sqrt(ped[i].thiscell[j].qhlrms);
                  ped[i].thiscell[j].tacrms = sqrt(ped[i].thiscell[j].tacrms);
                }else{
                  ped[i].thiscell[j].qlxrms = 0;
                  ped[i].thiscell[j].qhsrms = 0;
                  ped[i].thiscell[j].qhlrms = 0;
                  ped[i].thiscell[j].tacrms = 0;
                }
              }
            }
          }

          ///////////////////
          // PRINT RESULTS //
          ///////////////////

          lprintf("########################################################\n");
          lprintf("Slot (%2d)\n", slot_iter);
          lprintf("########################################################\n");

          for (int i = 0; i<32; i++){
            //pt_printsend("Ch Cell  #   Qhl         Qhs         Qlx         TAC\n");
            for (int j=0;j<16;j++){
              if (j == 0){
                qhls[dac_iter*16*32*2+slot_iter*32*2+i*2] = ped[i].thiscell[j].qhlbar;
                qhss[dac_iter*16*32*2+slot_iter*32*2+i*2] = ped[i].thiscell[j].qhsbar;
                qlxs[dac_iter*16*32*2+slot_iter*32*2+i*2] = ped[i].thiscell[j].qlxbar;
                tacs[dac_iter*16*32*2+slot_iter*32*2+i*2] = ped[i].thiscell[j].tacbar;
              }
              if (j == 1){
                qhls[dac_iter*16*32*2+slot_iter*32*2+i*2+1] = ped[i].thiscell[j].qhlbar;
                qhss[dac_iter*16*32*2+slot_iter*32*2+i*2+1] = ped[i].thiscell[j].qhsbar;
                qlxs[dac_iter*16*32*2+slot_iter*32*2+i*2+1] = ped[i].thiscell[j].qlxbar;
                tacs[dac_iter*16*32*2+slot_iter*32*2+i*2+1] = ped[i].thiscell[j].tacbar;
              }
              if (qSelect == 0){
                if (ped[i].thiscell[j].qhlbar < lower ||
                    ped[i].thiscell[j].qhlbar > upper) {
                  chinj_err[slot_iter]++;
                  //pt_printsend(">>>>>Qhl Extreme Value<<<<<\n");
                  if (j%2 == 0)
                    scan_errors[dac_iter*16*32*2+slot_iter*32*2+i*2]++;
                  else
                    scan_errors[dac_iter*16*32*2+slot_iter*32*2+i*2+1]++;
                }
              }
              else if (qSelect == 1){
                if (ped[i].thiscell[j].qhsbar < lower ||
                    ped[i].thiscell[j].qhsbar > upper) {
                  chinj_err[slot_iter]++;
                  //pt_printsend(">>>>>Qhs Extreme Value<<<<<\n");
                  if (j%2 == 0)
                    scan_errors[dac_iter*16*32*2+slot_iter*32*2+i*2]++;
                  else
                    scan_errors[dac_iter*16*32*2+slot_iter*32*2+i*2+1]++;
                }
              }
              else if (qSelect == 2){
                if (ped[i].thiscell[j].qlxbar < lower ||
                    ped[i].thiscell[j].qlxbar > upper) {
                  chinj_err[slot_iter]++;
                  //pt_printsend(">>>>>Qlx Extreme Value<<<<<\n");
                  if (j%2 == 0)
                    scan_errors[dac_iter*16*32*2+slot_iter*32*2+i*2]++;
                  else
                    scan_errors[dac_iter*16*32*2+slot_iter*32*2+i*2+1]++;
                }
              }
              if (j==0){
                lprintf("%2d %3d %4d %6.1f %4.1f %6.1f %4.1f %6.1f %4.1f %6.1f %4.1f\n",
                    dacvalue,i,ped[i].thiscell[j].per_cell,
                    ped[i].thiscell[j].qhlbar, ped[i].thiscell[j].qhlrms,
                    ped[i].thiscell[j].qhsbar, ped[i].thiscell[j].qhsrms,
                    ped[i].thiscell[j].qlxbar, ped[i].thiscell[j].qlxrms,
                    ped[i].thiscell[j].tacbar, ped[i].thiscell[j].tacrms);
              }
            }
          }

        } // end if slotmask
      } // end loop over slots


      //    if (arg.q_select == 0){
      //    pt_printsend("Qhl lower, Upper bounds = %f %f\n",arg.chinj_lower,arg.chinj_upper);
      //    pt_printsend("Number of Qhl overflows = %d\n",chinj_err[slot_iter]);
      //    }
      //    else if (arg.q_select == 1){
      //    pt_printsend("Qhs lower, Upper bounds = %f %f\n",arg.chinj_lower,arg.chinj_upper);
      //    pt_printsend("Number of Qhs overflows = %d\n",chinj_err[slot_iter]);
      //    }
      //    else if (arg.q_select == 2){
      //    pt_printsend("Qlx lower, Upper bounds = %f %f\n",arg.chinj_lower,arg.chinj_upper);
      //    pt_printsend("Number of Qlx overflows = %d\n",chinj_err[slot_iter]);
      //    }



      //disable trigger enables
      mtc->UnsetPedCrateMask(MASKALL);
      mtc->UnsetGTCrateMask(MASKALL);

      //unset pedestalenable
      errors += xl3s[crateNum]->SetCratePedestals(slotMask, 0x0);

      xl3s[crateNum]->DeselectFECs();
    } // end loop over dacvalue

    free(pmt_buffer);
    free(ped);

    // lets update this database
    if (updateDB){
      lprintf("updating the database\n");
      for (int i=0;i<16;i++)
      {
        if ((0x1<<i) & slotMask){
          JsonNode *newdoc = json_mkobject();
          JsonNode *qhl_even = json_mkarray();
          JsonNode *qhl_odd = json_mkarray();
          JsonNode *qhs_even = json_mkarray();
          JsonNode *qhs_odd = json_mkarray();
          JsonNode *qlx_even = json_mkarray();
          JsonNode *qlx_odd = json_mkarray();
          JsonNode *tac_even = json_mkarray();
          JsonNode *tac_odd = json_mkarray();
          JsonNode *error_even = json_mkarray();
          JsonNode *error_odd = json_mkarray();
          for (int j=0;j<32;j++){
            JsonNode *qhleventemp = json_mkarray();
            JsonNode *qhloddtemp = json_mkarray();
            JsonNode *qhseventemp = json_mkarray();
            JsonNode *qhsoddtemp = json_mkarray();
            JsonNode *qlxeventemp = json_mkarray();
            JsonNode *qlxoddtemp = json_mkarray();
            JsonNode *taceventemp = json_mkarray();
            JsonNode *tacoddtemp = json_mkarray();
            JsonNode *erroreventemp = json_mkarray();
            JsonNode *erroroddtemp = json_mkarray();
            for (int k=0;k<26;k++){
              json_append_element(qhleventemp,json_mknumber(qhls[k*16*32*2+i*32*2+j*2]));	
              json_append_element(qhloddtemp,json_mknumber(qhls[k*16*32*2+i*32*2+j*2+1]));	
              json_append_element(qhseventemp,json_mknumber(qhss[k*16*32*2+i*32*2+j*2]));	
              json_append_element(qhsoddtemp,json_mknumber(qhss[k*16*32*2+i*32*2+j*2+1]));	
              json_append_element(qlxeventemp,json_mknumber(qlxs[k*16*32*2+i*32*2+j*2]));	
              json_append_element(qlxoddtemp,json_mknumber(qlxs[k*16*32*2+i*32*2+j*2+1]));	
              json_append_element(taceventemp,json_mknumber(tacs[k*16*32*2+i*32*2+j*2]));	
              json_append_element(tacoddtemp,json_mknumber(tacs[k*16*32*2+i*32*2+j*2+1]));	
              json_append_element(erroreventemp,json_mkbool(scan_errors[k*16*32*2+i*32*2+j*2]));	
              json_append_element(erroroddtemp,json_mkbool(scan_errors[k*16*32*2+i*32*2+j*2+1]));	
            }
            json_append_element(qhl_even,qhleventemp);
            json_append_element(qhl_odd,qhloddtemp);
            json_append_element(qhs_even,qhseventemp);
            json_append_element(qhs_odd,qhsoddtemp);
            json_append_element(qlx_even,qlxeventemp);
            json_append_element(qlx_odd,qlxoddtemp);
            json_append_element(tac_even,taceventemp);
            json_append_element(tac_odd,tacoddtemp);
            json_append_element(error_even,erroreventemp);
            json_append_element(error_odd,erroroddtemp);
          }
          json_append_member(newdoc,"type",json_mkstring("chinj_scan"));
          json_append_member(newdoc,"QHL_even",qhl_even);
          json_append_member(newdoc,"QHL_odd",qhl_odd);
          json_append_member(newdoc,"QHS_even",qhs_even);
          json_append_member(newdoc,"QHS_odd",qhs_odd);
          json_append_member(newdoc,"QLX_even",qlx_even);
          json_append_member(newdoc,"QLX_odd",qlx_odd);
          json_append_member(newdoc,"TAC_even",tac_even);
          json_append_member(newdoc,"TAC_odd",tac_odd);
          json_append_member(newdoc,"errors_even",error_even);
          json_append_member(newdoc,"errors_odd",error_odd);
          json_append_member(newdoc,"pass",json_mkbool(!(chinj_err[i])));
          if (finalTest){
            json_append_member(newdoc,"final_test_id",json_mkstring(finalTestIDs[crateNum][i]));	
          }
          PostDebugDoc(crateNum,i,newdoc);
        }
      }
    }

    if (errors)
      lprintf("There were %d errors\n", errors);
    else
      lprintf("No errors seen\n");

    free(qhls);
    free(qhss);
    free(qlxs);
    free(tacs);
    free(scan_errors);

  }
  catch(const char* s){
    lprintf("ChinjScan: %s\n",s);
    if (pmt_buffer != NULL)
      free(pmt_buffer);
    if (ped != NULL)
      free(ped);
    if (qhls != NULL)
      free(qhls);
    if (qhss != NULL)
      free(qhss);
    if (qlxs != NULL)
      free(qlxs);
    if (tacs != NULL)
      free(tacs);
    if (scan_errors != NULL)
      free(scan_errors);

  }

  lprintf("****************************************\n");
  return 0;
}
static void test_array(void)
{
    JsonNode *array;
    JsonNode *children[5 + 1];

    array = json_mkarray();
    should_be(array, "[]");

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

    json_append_element(array, children[3]);
    should_be(array, "[3]");

    json_remove_from_parent(children[3]);
    should_be(array, "[]");

    json_prepend_element(array, children[3]);
    should_be(array, "[3]");

    json_prepend_element(array, children[2]);
    should_be(array, "[2,3]");

    json_append_element(array, children[4]);
    should_be(array, "[2,3,4]");

    json_delete(children[3]);
    should_be(array, "[2,4]");

    json_prepend_element(array, children[1]);
    should_be(array, "[1,2,4]");

    json_delete(children[1]);
    should_be(array, "[2,4]");

    json_delete(children[4]);
    should_be(array, "[2]");

    ok1(json_find_element(array, 0) == children[2]);
    ok1(json_find_element(array, -1) == NULL);
    ok1(json_find_element(array, 1) == NULL);

    json_append_element(array, children[5]);
    should_be(array, "[2,5]");

    ok1(json_find_element(array, 0) == children[2]);
    ok1(json_find_element(array, 1) == children[5]);
    ok1(json_find_element(array, -1) == NULL);
    ok1(json_find_element(array, 2) == NULL);

    json_delete(children[2]);
    json_delete(children[5]);
    should_be(array, "[]");

    ok1(json_find_element(array, -1) == NULL);
    ok1(json_find_element(array, 0) == NULL);
    ok1(json_find_element(array, 1) == NULL);

    json_delete(array);
}
Exemple #22
0
int get_ttot(char * buffer)
{
    if (sbc_is_connected == 0){
        printsend("SBC not connected.\n");
        
        return -1;
    }
    int errors;
    int targettime = 400;
    int crate = 2;
    uint32_t slot_mask = 0x2000;
    uint16_t times[32*16];
    int tot_errors[16][32];
    int result;
    int i,j,slot,passflag;
    int update_db = 0;
    int final_test = 0;
    char ft_ids[16][50];
    char *words,*words2;
    words = strtok(buffer, " ");
    while (words != NULL){
        if (words[0] == '-'){
            if (words[1] == 'c'){
                words2 = strtok(NULL, " ");
                crate = atoi(words2);
            }else if (words[1] == 's'){
                words2 = strtok(NULL, " ");
                slot_mask = strtoul(words2,(char**)NULL,16);
            }else if (words[1] == 'd'){
                update_db = 1;
            }else if (words[1] == '#'){
                final_test = 1;
                for (i=0;i<16;i++){
                    if ((0x1<<i) & slot_mask){
                        words2 = strtok(NULL, " ");
                        sprintf(ft_ids[i],"%s",words2);
                    }
                }
            }else if (words[1] == 't'){
                words2 = strtok(NULL, " ");
                targettime = atoi(words2);
            }else if (words[1] == 'h'){
                printsend("Usage: get_ttot -c"
                        " [crate_num] -s [slot_mask (hex)] -t [target time] -d (update debug db)\n");
                
                return 0;
            }
        }
        words = strtok(NULL, " ");
    }

    unset_gt_mask(MASKALL);
    errors = setup_pedestals(0.0,60,100,0); //freq=0,width=60,delay=100+0
    unset_gt_crate_mask(MASKALL);
    set_gt_crate_mask(MSK_CRATE21); //turn on the TUB
    set_ped_crate_mask(MSK_CRATE21); //turn on the TUB
    unset_ped_crate_mask(MASKALL);
    set_ped_crate_mask(0x1<<crate | MSK_CRATE21); // leave TUB masked in

    result = disc_m_ttot(crate,slot_mask,150,times);

   printsend("crate\t slot\t channel\t time\n");

    for (i=0;i<16;i++){
        if ((0x1<<i) & slot_mask){
            for(j=0;j<32;j++){
                tot_errors[i][j] = 0;
               printsend("%d\t %d\t %d\t %d",crate,i,j,times[i*32+j]);
                if (targettime > times[i*32+j]){
                   printsend(">>>Warning: time less than %d nsec",targettime);
                    tot_errors[i][j] = 1;
                }
               printsend("\n");
            }
        }
    }

    if (update_db){
       printsend("updating the database\n");
        ;
        for (slot=0;slot<16;slot++){
            if ((0x1<<slot) & slot_mask){
                JsonNode *newdoc = json_mkobject();
                json_append_member(newdoc,"type",json_mkstring("get_ttot"));
                json_append_member(newdoc,"targettime",json_mknumber((double)targettime));
                JsonNode *times_node = json_mkarray();
                JsonNode *error_node = json_mkarray();
                passflag = 0;
                for (i=0;i<32;i++){
                    if (tot_errors[slot][i] == 1)
                        passflag = 1;
                    json_append_element(error_node,json_mknumber((double)tot_errors[slot][i]));
                    json_append_element(times_node,json_mknumber((double)times[slot*32+i]));
                }
                json_append_member(newdoc,"times",times_node);
                json_append_member(newdoc,"errors",error_node);
                if (passflag == 0){
                    json_append_member(newdoc,"pass",json_mkstring("yes"));
                }else{
                    json_append_member(newdoc,"pass",json_mkstring("no"));
                }
                if (final_test)
                    json_append_member(newdoc,"final_test_id",json_mkstring(ft_ids[slot]));	
                post_debug_doc(crate,slot,newdoc);
                json_delete(newdoc); // delete the head ndoe
            }
        }
    }

    return 0;
}
Exemple #23
0
void *pt_fec_test(void *args)
{
  fec_test_t arg = *(fec_test_t *) args; 
  free(args);

  XL3_Packet packet;
  fec_test_args_t *packet_args = (fec_test_args_t *) packet.payload;
  fec_test_results_t *packet_results = (fec_test_results_t *) packet.payload;

  packet.cmdHeader.packet_type = FEC_TEST_ID;
  packet_args->slot_mask = arg.slot_mask;

  SwapLongBlock(packet.payload,1);

  fd_set thread_fdset;
  FD_ZERO(&thread_fdset);
  FD_SET(rw_xl3_fd[arg.crate_num],&thread_fdset);

  /*
  MultiFC *commands = (MultiFC *) packet.payload;
  commands->howmany = 50;
  int i;
  for (i=0;i<25;i++){
    commands->cmd[i*2].address = 0x10F00023;
    commands->cmd[i*2+1].address = 0x00F00023;
    commands->cmd[i*2+1].data = i<<16;
  SwapLongBlock(&(commands->cmd[i*2].address),1);
  SwapLongBlock(&(commands->cmd[i*2+1].address),1);
  SwapLongBlock(&(commands->cmd[i*2+1].data),1);
  }
  SwapLongBlock(&(commands->howmany),1);

  packet.cmdHeader.packet_type = QUEUE_CMDS_ID;
  int errors = do_xl3_cmd(&packet,arg.crate_num,&thread_fdset);
  if (errors < 0){
    pt_printsend("Error queuing command\n");
    unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
    return;
  }
  
  uint32_t result[50];
  errors = wait_for_multifc_results(50,command_number[arg.crate_num]-1,arg.crate_num,&result,&thread_fdset);
  if (errors < 0){
    pt_printsend("Error getting result\n");
    unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
    return;
  }

  for (i=0;i<50;i++){
    pt_printsend("%d - %08x\n",i,result[i]);
  }


  unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
  return;
//////////////////////////////////
*/
  do_xl3_cmd(&packet,arg.crate_num,&thread_fdset);

  SwapLongBlock(packet_results,sizeof(fec_test_results_t)/sizeof(uint32_t));

  if (arg.update_db){
    pt_printsend("updating the database\n");
    int slot,i;
    for (slot=0;slot<16;slot++){
      if ((0x1<<slot) & arg.slot_mask){
        pt_printsend("updating slot %d\n",slot);
        JsonNode *newdoc = json_mkobject();
        json_append_member(newdoc,"type",json_mkstring("fec_test"));
        json_append_member(newdoc,"pedestal",
            json_mkbool(!(packet_results->discrete_reg_errors[slot] & 0x1)));
        json_append_member(newdoc,"chip_disable",
            json_mkbool(!(packet_results->discrete_reg_errors[slot] & 0x2)));
        json_append_member(newdoc,"lgi_select",
            json_mkbool(!(packet_results->discrete_reg_errors[slot] & 0x4)));
        json_append_member(newdoc,"cmos_prog_low",
            json_mkbool(!(packet_results->discrete_reg_errors[slot] & 0x8)));
        json_append_member(newdoc,"cmos_prog_high",
            json_mkbool(!(packet_results->discrete_reg_errors[slot] & 0x10)));
        JsonNode *cmos_test_array = json_mkarray();
        for (i=0;i<32;i++){
          json_append_element(cmos_test_array,
              json_mkbool(!(packet_results->cmos_test_reg_errors[slot] & (0x1<<i))));
        }
        json_append_element(cmos_test_array,
            json_mkbool(packet_results->cmos_test_reg_errors[slot] == 0x0));
        json_append_member(newdoc,"cmos_test_reg",cmos_test_array);
        json_append_member(newdoc,"pass",
            json_mkbool((packet_results->discrete_reg_errors[slot] == 0x0) 
              && (packet_results->cmos_test_reg_errors[slot] == 0x0)));
        if (arg.final_test)
          json_append_member(newdoc,"final_test_id",json_mkstring(arg.ft_ids[slot]));	
        if (arg.ecal)
          json_append_member(newdoc,"ecal_id",json_mkstring(arg.ecal_id));	
        post_debug_doc(arg.crate_num,slot,newdoc,&thread_fdset);
        json_delete(newdoc); // Only have to delete the head node
      }
    }
  }

  unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
}
Exemple #24
0
JsonNode *last_users(char *in_user, char *in_device, JsonNode *fields)
{
	JsonNode *obj = json_mkobject();
	JsonNode *un, *dn, *userlist = json_mkarray();
	char path[BUFSIZ], user[BUFSIZ], device[BUFSIZ];

	snprintf(path, BUFSIZ, "%s/last", STORAGEDIR);

	// fprintf(stderr, "last_users(%s, %s)\n", (in_user) ? in_user : "******",
	// 	(in_device) ? in_device : "<nil>");

	if (user_device_list(path, 0, obj) == 1) {
		json_delete(userlist);
		return (obj);
	}

	/* Loop through users, devices */
	json_foreach(un, obj) {
		if (un->tag != JSON_ARRAY)
			continue;
		strcpy(user, un->key);
		json_foreach(dn, un) {
			if (dn->tag == JSON_STRING) {
				strcpy(device, dn->string_);
			} else if (dn->tag == JSON_NUMBER) {	/* all digits? */
				sprintf(device, "%.lf", dn->number_);
			}

			if (!in_user && !in_device) {
				append_device_details(userlist, user, device);
			} else if (in_user && !in_device) {
				if (strcmp(user, in_user) == 0) {
					append_device_details(userlist, user, device);
				}
			} else if (in_user && in_device) {
				if (strcmp(user, in_user) == 0 && strcmp(device, in_device) == 0) {
					append_device_details(userlist, user, device);
				}
			}
		}
	}
	json_delete(obj);

	/*
	 * userlist now is an array of user objects. If fields were
	 * specified, re-create that array with object which have
	 * only the requested fields. It's a shame we have to re-do
	 * this here, but I can't think of an alternative way at
	 * the moment.
	 */

	if (fields) {
		JsonNode *new_userlist = json_mkarray(), *user;

		json_foreach(user, userlist) {
			JsonNode *o = json_mkobject(), *f, *j;

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

				if ((j = json_find_member(user, field_name)) != NULL) {
					json_copy_element_to_object(o, field_name, j);
				}
			}
			json_append_element(new_userlist, o);
		}
Exemple #25
0
int set_ttot(char * buffer)
{
   printsend(".%s.\n",buffer);
    if (sbc_is_connected == 0){
        printsend("SBC not connected.\n");
        
        return -1;
    }
    int errors;
    int targettime = 400;
    int crate = 2;
    uint32_t slot_mask = 0x2000;
    int i,j;
    int slot, passflag;
    int update_db = 0;
    int final_test = 0;
    char ft_ids[16][50];
    char *words,*words2;
    words = strtok(buffer, " ");
    while (words != NULL){
        if (words[0] == '-'){
            if (words[1] == 'c'){
                words2 = strtok(NULL, " ");
                crate = atoi(words2);
            }else if (words[1] == 's'){
                words2 = strtok(NULL, " ");
                slot_mask = strtoul(words2,(char**)NULL,16);
            }else if (words[1] == 'd'){
                update_db = 1;
            }else if (words[1] == '#'){
                final_test = 1;
                for (i=0;i<16;i++){
                    if ((0x1<<i) & slot_mask){
                        words2 = strtok(NULL, " ");
                        sprintf(ft_ids[i],"%s",words2);
                    }
                }
            }else if (words[1] == 't'){
                words2 = strtok(NULL, " ");
                targettime = atoi(words2);
            }else if (words[1] == 'h'){
                printsend("Usage: set_ttot -c"
                        " [crate_num] -s [slot_mask (hex)] -t [target time] -d (update debug db)\n");
                
                return 0;
            }
        }
        words = strtok(NULL, " ");
    }

    unset_gt_mask(MASKALL);
    errors = setup_pedestals(0.0,60,100,0); //freq=0,width=60,delay=100+0
    unset_gt_crate_mask(MASKALL);
    set_gt_crate_mask(MSK_CRATE21); //turn on the TUB
    set_ped_crate_mask(MSK_CRATE21); //turn on the TUB
    unset_ped_crate_mask(MASKALL);
    set_ped_crate_mask(0x1<<crate | MSK_CRATE21); // leave TUB masked in

    uint16_t allrmps[16*8],allvsis[16*8],alltimes[16*32];
    int tot_errors[16*8];
    disc_s_ttot(crate,slot_mask,targettime,allrmps,allvsis,alltimes,tot_errors);

    if (update_db){
       printsend("updating the database\n");
        ;
        for (slot=0;slot<16;slot++){
            if ((0x1<<slot) & slot_mask){
                JsonNode *newdoc = json_mkobject();
                json_append_member(newdoc,"type",json_mkstring("set_ttot"));
                json_append_member(newdoc,"targettime",json_mknumber((double)targettime));
                JsonNode *rmp = json_mkarray();
                JsonNode *vsi = json_mkarray();
                JsonNode *times = json_mkarray();
                JsonNode *error_node = json_mkarray();
                passflag = 0;
                for (i=0;i<8;i++){
                    if (tot_errors[slot*8+i] == 1)
                        passflag = 1;
                    json_append_element(rmp,json_mknumber((double)allrmps[slot*8+i]));
                    json_append_element(vsi,json_mknumber((double)allvsis[slot*8+i]));
                    json_append_element(error_node,json_mknumber((double)tot_errors[slot*8+i]));
                    JsonNode *times_temp = json_mkarray();
                    for (j=0;j<4;j++){
                        json_append_element(times_temp,json_mknumber((double)alltimes[slot*32+i*4+j]));
                    }
                    json_append_element(times,times_temp);
                }
                json_append_member(newdoc,"rmp",rmp);
                json_append_member(newdoc,"vsi",vsi);
                json_append_member(newdoc,"times",times);
                json_append_member(newdoc,"errors",error_node);
                if (passflag == 0){
                    json_append_member(newdoc,"pass",json_mkstring("yes"));
                }else{
                    json_append_member(newdoc,"pass",json_mkstring("no"));
                }
                if (final_test)
                    json_append_member(newdoc,"final_test_id",json_mkstring(ft_ids[slot]));	
                post_debug_doc(crate,slot,newdoc);
                json_delete(newdoc); // head node needs deleting
            }
        }
    }

    return 0;
}
Exemple #26
0
void *pt_set_ttot(void *args)
{
  set_ttot_t arg = *(set_ttot_t *) args; 
  free(args);

  fd_set thread_fdset;
  FD_ZERO(&thread_fdset);
  FD_SET(rw_xl3_fd[arg.crate_num],&thread_fdset);

  uint16_t allrmps[16][8],allvsis[16][8],alltimes[16*32];
  int tot_errors[16][32];
  int i,j,k,l;
  uint16_t rmp[8],vsi[8],rmpup[8],vli[8];
  uint16_t rmp_high[8],rmp_low[8];
  uint16_t chips_not_finished;
  int diff[32];
  uint32_t dac_nums[50],dac_values[50];
  int num_dacs;
  int result;

  // setup the mtc with the triggers going to the TUB
  int errors = setup_pedestals(0,60,100,0,(0x1<<arg.crate_num) | MSK_CRATE21,MSK_CRATE21);

  for (i=0;i<16;i++){
    if ((0x1<<i) & arg.slot_mask){
      // set default values
      for (j=0;j<8;j++){
        rmpup[j] = RMPUP_DEFAULT;
        vsi[j] = VSI_DEFAULT;
        vli[j] = VLI_DEFAULT;
        rmp_high[j] = MAX_RMP_VALUE;
        rmp_low[j] = RMP_DEFAULT-10;
        rmp[j] = (int) (rmp_high[j] + rmp_low[j])/2;
      }

      // first check that if we make ttot as short as possible, triggers show up 
      num_dacs = 0;
      for (j=0;j<8;j++){
        dac_nums[num_dacs] = d_rmpup[j];
        dac_values[num_dacs] = rmpup[j];
        num_dacs++;
        dac_nums[num_dacs] = d_vli[j];
        dac_values[num_dacs] = vli[j];
        num_dacs++;
        dac_nums[num_dacs] = d_rmp[j];
        dac_values[num_dacs] = rmp_low[j];
        num_dacs++;
        dac_nums[num_dacs] = d_vsi[j];
        dac_values[num_dacs] = vsi[j];
        num_dacs++;
      }
      multi_loadsDac(num_dacs,dac_nums,dac_values,arg.crate_num,i,&thread_fdset);

      for (k=0;k<32;k++){
        result = disc_check_ttot(arg.crate_num,i,(0x1<<k),MAX_TIME,diff,&thread_fdset);
        tot_errors[i][k] = 0;
        if (diff[k] == 1){
          pt_printsend("Error - Not getting TUB triggers on channel %d!\n",k);
          tot_errors[i][k] = 2;
        }
      }

      // load default values
      num_dacs = 0;
      for (j=0;j<8;j++){
        dac_nums[num_dacs] = d_rmp[j];
        dac_values[num_dacs] = rmp[j];
        num_dacs++;
        dac_nums[num_dacs] = d_vsi[j];
        dac_values[num_dacs] = vsi[j];
        num_dacs++;
      }
      multi_loadsDac(num_dacs,dac_nums,dac_values,arg.crate_num,i,&thread_fdset);

      pt_printsend("Setting ttot for crate/board %d %d, target time %d\n",arg.crate_num,i,arg.target_time);
      chips_not_finished = 0xFF;

      // loop until all ttot measurements are larger than target ttime
      while(chips_not_finished){

        // measure ttot for all chips
        result = disc_check_ttot(arg.crate_num,i,0xFFFFFFFF,arg.target_time,diff,&thread_fdset);

        // loop over disc chips
        for (j=0;j<8;j++){
          if ((0x1<<j) & chips_not_finished){

            // check if above or below
            if ((diff[4*j+0] > 0) && (diff[4*j+1] > 0) && (diff[4*j+2] > 0)
                && (diff[4*j+3] > 0)){
              //pt_printsend("above\n");
              rmp_high[j] = rmp[j];

              // if we have narrowed it down to the first setting that works, we are done
              if ((rmp[j] - rmp_low[j]) == 1){
                pt_printsend("Chip %d finished\n",j);
                chips_not_finished &= ~(0x1<<j);
                allrmps[i][j] = rmp[j];
                allvsis[i][j] = vsi[j];
              }
            }else{
              //pt_printsend("below\n");
              rmp_low[j] = rmp[j];
              if (rmp[j] == MAX_RMP_VALUE){
                if (vsi[j] > MIN_VSI_VALUE){
                  rmp_high[j] = MAX_RMP_VALUE;
                  rmp_low[j] = RMP_DEFAULT-10;
                  vsi[j] -= 2;
                  //pt_printsend("%d - vsi: %d\n",j,vsi[j]);
                }else{
                  // out of bounds, end loop with error
                  pt_printsend("RMP/VSI is too big for disc chip %d! (%d %d)\n",j,rmp[j],vsi[j]);
                  pt_printsend("Aborting slot %d setup.\n",i);
                  tot_errors[i][j*4+0] = 1;
                  tot_errors[i][j*4+1] = 1;
                  tot_errors[i][j*4+2] = 1;
                  tot_errors[i][j*4+3] = 1;
                  for (l=0;l<8;l++)
                    if (chips_not_finished & (0x1<<l)){
                      pt_printsend("Slot %d Chip %d\tRMP/VSI: %d %d <- unfinished\n",i,l,rmp[l],vsi[l]);
                      allrmps[i][l] = rmp[l];
                      allvsis[i][l] = vsi[l];
                    }
                  chips_not_finished = 0x0;
                }
              }else if (rmp[j] == rmp_high[j]){
                // in case it screws up and fails after it succeeded already
                rmp_high[j]++;
              }
            }

            rmp[j] = (int) ((float) (rmp_high[j] + rmp_low[j])/2.0 + 0.5);

          } // end if this chip not finished
        } // end loop over disc chips

        // load new values
        num_dacs = 0;
        for (j=0;j<8;j++){
          dac_nums[num_dacs] = d_rmp[j];
          dac_values[num_dacs] = rmp[j];
          num_dacs++;
          dac_nums[num_dacs] = d_vsi[j];
          dac_values[num_dacs] = vsi[j];
          num_dacs++;
        }
        multi_loadsDac(num_dacs,dac_nums,dac_values,arg.crate_num,i,&thread_fdset);

      } // end while chips_not_finished

      // now get the final timing measurements
      num_dacs = 0;
      for (j=0;j<8;j++){
        dac_nums[num_dacs] = d_rmp[j];
        dac_values[num_dacs] = allrmps[i][j];
        num_dacs++;
        dac_nums[num_dacs] = d_vsi[j];
        dac_values[num_dacs] = allvsis[i][j];
        num_dacs++;
      }
      multi_loadsDac(num_dacs,dac_nums,dac_values,arg.crate_num,i,&thread_fdset);

      result = disc_m_ttot(arg.crate_num,(0x1<<i),150,alltimes,&thread_fdset);

      pt_printsend("Final timing measurements:\n");
      for (j=0;j<8;j++){
        pt_printsend("Chip %d (RMP/VSI %d %d) Times:\t%d\t%d\t%d\t%d\n",
            j,rmp[j],vsi[j],alltimes[i*32+j*4+0],alltimes[i*32+j*4+1],
            alltimes[i*32+j*4+2],alltimes[i*32+j*4+3]);
      }

      if (arg.update_db){
        pt_printsend("updating the database\n");
        JsonNode *newdoc = json_mkobject();
        json_append_member(newdoc,"type",json_mkstring("set_ttot"));
        json_append_member(newdoc,"targettime",json_mknumber((double)arg.target_time));

        JsonNode *all_chips = json_mkarray();
        int passflag = 1;
        int k;
        for (k=0;k<8;k++){
          JsonNode *one_chip = json_mkobject();
          json_append_member(one_chip,"rmp",json_mknumber((double) allrmps[i][k]));
          json_append_member(one_chip,"vsi",json_mknumber((double) allvsis[i][k]));

          JsonNode *all_chans = json_mkarray();
          for (j=0;j<4;j++){
            JsonNode *one_chan = json_mkobject();
            if (tot_errors[i][k*4+j]> 0)
              passflag = 0;
            json_append_member(one_chan,"id",json_mknumber((double) k*4+j));
            json_append_member(one_chan,"time",json_mknumber((double) alltimes[i*32+k*4+j]));
            json_append_member(one_chan,"errors",json_mknumber(tot_errors[i][k*4+j]));
            json_append_element(all_chans,one_chan);
          }
          json_append_member(one_chip,"channels",all_chans);

          json_append_element(all_chips,one_chip);
        }
        json_append_member(newdoc,"chips",all_chips);

        json_append_member(newdoc,"pass",json_mkbool(passflag));
        if (arg.final_test)
          json_append_member(newdoc,"final_test_id",json_mkstring(arg.ft_ids[i]));	
        if (arg.ecal)
          json_append_member(newdoc,"ecal_id",json_mkstring(arg.ecal_id));	
        post_debug_doc(arg.crate_num,i,newdoc,&thread_fdset);
        json_delete(newdoc); // head node needs deleting
      }
    } // if in slot mask
  } // end loop over slots

  pt_printsend("Set ttot complete\n");
  pt_printsend("**************************\n");

  unthread_and_unlock(1,(0x1<<arg.crate_num),arg.thread_num);
}
Exemple #27
0
void *pt_cald_test(void *args)
{
  cald_test_t arg = *(cald_test_t *) args; 
  free(args);

  fd_set thread_fdset;
  FD_ZERO(&thread_fdset);
  FD_SET(rw_xl3_fd[arg.crate_num],&thread_fdset);

  pt_printsend("Starting cald test! Make sure you have inited the right xilinx!\n");

  uint16_t *point_buf;
  uint16_t *adc_buf;
  point_buf = malloc(16*MAX_SAMPLES*sizeof(uint16_t));
  adc_buf = malloc(16*4*MAX_SAMPLES*sizeof(uint16_t));
  if ((point_buf == NULL) || (adc_buf == NULL)){
    pt_printsend("Problem mallocing for cald test. Exiting\n");
    unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
    return;
  }

  int i,j;
  int num_slots = 0;
  for (i=0;i<16;i++)
    if ((0x1<<i) & arg.slot_mask)
      num_slots++;

  XL3_Packet packet;
  cald_test_args_t *packet_args = (cald_test_args_t *) packet.payload;

  packet.cmdHeader.packet_type = CALD_TEST_ID;
  packet_args->slot_mask = arg.slot_mask;
  packet_args->num_points = arg.num_points;
  packet_args->samples = arg.samples;
  packet_args->upper = arg.upper;
  packet_args->lower = arg.lower;
  SwapLongBlock(packet_args,sizeof(cald_test_args_t)/sizeof(uint32_t));
  do_xl3_cmd_no_response(&packet,arg.crate_num,&thread_fdset);

  int total_points = wait_for_cald_test_results(arg.crate_num,point_buf,adc_buf,&thread_fdset);
  pt_printsend("Got results of cald test. %d points received.\n",total_points);

  if (arg.update_db){
    pt_printsend("updating database\n");
    for (i=0;i<16;i++){
      if ((0x1<<i) & arg.slot_mask){
        JsonNode *newdoc = json_mkobject();
        json_append_member(newdoc,"type",json_mkstring("cald_test"));
        JsonNode *points = json_mkarray();
        JsonNode *adc0 = json_mkarray();
        JsonNode *adc1 = json_mkarray();
        JsonNode *adc2 = json_mkarray();
        JsonNode *adc3 = json_mkarray();
        int iter = 0;
        while(iter<=MAX_SAMPLES){
          if (iter != 0 && point_buf[i*MAX_SAMPLES+iter] == 0)
            break;
          pt_printsend("Slot %d - %u : %4u %4u %4u %4u\n",i,point_buf[i*MAX_SAMPLES+iter],adc_buf[i*4*MAX_SAMPLES+iter*4],adc_buf[i*4*MAX_SAMPLES+iter*4+1],adc_buf[i*4*MAX_SAMPLES+iter*4+2],adc_buf[i*4*MAX_SAMPLES+iter*4+3]);
          json_append_element(points,json_mknumber((double)point_buf[i*MAX_SAMPLES+iter]));
          json_append_element(adc0,json_mknumber((double)adc_buf[i*4*MAX_SAMPLES+iter*4]));
          json_append_element(adc1,json_mknumber((double)adc_buf[i*4*MAX_SAMPLES+iter*4+1]));
          json_append_element(adc2,json_mknumber((double)adc_buf[i*4*MAX_SAMPLES+iter*4+2]));
          json_append_element(adc3,json_mknumber((double)adc_buf[i*4*MAX_SAMPLES+iter*4+3]));
          iter++;
        }
        json_append_member(newdoc,"dac_value",points);
        json_append_member(newdoc,"adc_0",adc0);
        json_append_member(newdoc,"adc_1",adc1);
        json_append_member(newdoc,"adc_2",adc2);
        json_append_member(newdoc,"adc_3",adc3);
        json_append_member(newdoc,"pass",json_mkbool(1)); //FIXME
        if (arg.final_test)
          json_append_member(newdoc,"final_test_id",json_mkstring(arg.ft_ids[i]));	
        post_debug_doc(arg.crate_num,i,newdoc,&thread_fdset);
        json_delete(newdoc); // only delete the head node
      }
    }
  }

  free(point_buf);
  free(adc_buf);
  unthread_and_unlock(0,(0x1<<arg.crate_num),arg.thread_num);
}
Exemple #28
0
void *pt_get_ttot(void *args)
{
  get_ttot_t arg = *(get_ttot_t *) args; 
  free(args);

  printf("**********************************\n");
  printf("Starting get_ttot\n");

  fd_set thread_fdset;
  FD_ZERO(&thread_fdset);
  FD_SET(rw_xl3_fd[arg.crate_num],&thread_fdset);

  uint16_t times[32*16];
  int tot_errors[16][32];

  // setup the mtc with the triggers going to the TUB
  int errors = setup_pedestals(0,60,100,0,(0x1<<arg.crate_num) | MSK_CRATE21,MSK_CRATE21);

  int result = disc_m_ttot(arg.crate_num,arg.slot_mask,150,times,&thread_fdset);

  // print out results
  pt_printsend("Crate\t Slot\t Channel\t Time:\n");
  int i,j;
  for (i=0;i<16;i++){
    if ((0x1<<i) & arg.slot_mask){
      for (j=0;j<32;j++){
        tot_errors[i][j] = 0;
        pt_printsend("%d\t %d\t %d\t %d",arg.crate_num,i,j,times[i*32+j]);
        if (arg.target_time > times[i*32+j]){
          if (arg.target_time < 9999){
            pt_printsend(">>> Warning: Time less than %d nsec",arg.target_time);
            tot_errors[i][j] = 1;
          }
        }else if(arg.target_time == 9999){
          pt_printsend(">>> Problem measuring time for this channel\n");
          tot_errors[i][j] = 2;
        }
        pt_printsend("\n");
      }
    }
  }

  if (arg.update_db){
    printsend("updating the database\n");
    int slot;
    for (slot=0;slot<16;slot++){
      if ((0x1<<slot) & arg.slot_mask){
        JsonNode *newdoc = json_mkobject();
        json_append_member(newdoc,"type",json_mkstring("get_ttot"));
        json_append_member(newdoc,"targettime",json_mknumber((double)arg.target_time));

        JsonNode *channels = json_mkarray();
        int passflag = 1;
        for (i=0;i<32;i++){
          if (tot_errors[slot][i] == 1)
            passflag = 0;
          JsonNode *one_chan = json_mkobject();
          json_append_member(one_chan,"id",json_mknumber((double) i));
          json_append_member(one_chan,"time",json_mknumber((double) times[slot*32+i]));
          json_append_member(one_chan,"errors",json_mknumber(tot_errors[slot][i]));
          json_append_element(channels,one_chan);
        }
        json_append_member(newdoc,"channels",channels);

        json_append_member(newdoc,"pass",json_mkbool(passflag));
        if (arg.final_test)
          json_append_member(newdoc,"final_test_id",json_mkstring(arg.ft_ids[slot]));	
        if (arg.ecal)
          json_append_member(newdoc,"ecal_id",json_mkstring(arg.ecal_id));	
        post_debug_doc(arg.crate_num,slot,newdoc,&thread_fdset);
        json_delete(newdoc); // delete the head ndoe
      }
    }
  }

  unthread_and_unlock(1,(0x1<<arg.crate_num),arg.thread_num);
}
Exemple #29
0
void get_defaults(char *filename, struct udata *ud)
{
	config_t cfg, *cf;
	const char *value;
#if LIBCONFIG_VER_MAJOR == 1
# if LIBCONFIG_VER_MINOR >= 4
	int ival;
# endif
# else
	long ival;
#endif

	if (access(filename, R_OK) == -1) {
		olog(LOG_ERR, "Cannot read defaults from %s: %s", filename, strerror(errno));
		return;
	}

	config_init(cf = &cfg);

	if (!config_read_file(cf, filename)) {
		olog(LOG_ERR, "Syntax error in %s:%d - %s",
			filename,
			config_error_line(cf),
			config_error_text(cf));
		config_destroy(cf);
		exit(2);
	}

	if (config_lookup_string(cf, "OTR_STORAGEDIR", &value) != CONFIG_FALSE)
		strcpy(STORAGEDIR, value);

	if (ud == NULL) {
		/* being invoked by ocat; return */
		return;
	}
#if WITH_MQTT
	if (config_lookup_string(cf, "OTR_HOST", &value) != CONFIG_FALSE) {
		if (ud->hostname) free(ud->hostname);
		ud->hostname = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_PORT", &ival) != CONFIG_FALSE) {
		ud->port = ival;
	}
	if (config_lookup_string(cf, "OTR_USER", &value) != CONFIG_FALSE) {
		if (ud->username) free(ud->username);
		ud->username = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_string(cf, "OTR_PASS", &value) != CONFIG_FALSE) {
		if (ud->password) free(ud->password);
		ud->password = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_QOS", &ival) != CONFIG_FALSE) {
		ud->qos = ival;
	}
	if (config_lookup_string(cf, "OTR_CLIENTID", &value) != CONFIG_FALSE) {
		if (ud->clientid) free(ud->clientid);
		ud->clientid = (value) ? strdup(value) : NULL;
	}

	if (config_lookup_string(cf, "OTR_CAFILE", &value) != CONFIG_FALSE) {
		if (ud->cafile) free(ud->cafile);
		ud->cafile = (value) ? strdup(value) : NULL;
	}

	/* Topics is a blank-separated string of words; split and add to JSON array */
	if (config_lookup_string(cf, "OTR_TOPICS", &value) != CONFIG_FALSE) {
		char *parts[40];
		int np, n;
		if (ud->topics) json_delete(ud->topics);

		if ((np = splitter((char *)value, " ", parts)) < 1) {
			olog(LOG_ERR, "Illegal value in OTR_TOPICS");
			exit(2);
		}
		ud->topics = json_mkarray();

		for (n = 0; n < np; n++) {
			json_append_element(ud->topics, json_mkstring(parts[n]));
		}
		splitterfree(parts);
	}
#endif /* WITH_MQTT */

	if (config_lookup_string(cf, "OTR_GEOKEY", &value) != CONFIG_FALSE) {
		if (ud->geokey) free(ud->geokey);
		ud->geokey = (value) ? strdup(value) : NULL;
	}

	if (config_lookup_int(cf, "OTR_PRECISION", &ival) != CONFIG_FALSE) {
		geohash_setprec(ival);
	}

#if WITH_HTTP
	if (config_lookup_string(cf, "OTR_HTTPHOST", &value) != CONFIG_FALSE) {
		if (ud->http_host) free(ud->http_host);
		ud->http_host = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_int(cf, "OTR_HTTPPORT", &ival) != CONFIG_FALSE) {
		ud->http_port = ival;
	}
	if (config_lookup_string(cf, "OTR_HTTPLOGDIR", &value) != CONFIG_FALSE) {
		if (ud->http_logdir) free(ud->http_logdir);
		ud->http_logdir = (value) ? strdup(value) : NULL;
	}
	if (config_lookup_string(cf, "OTR_BROWSERAPIKEY", &value) != CONFIG_FALSE) {
		if (ud->browser_apikey) free(ud->browser_apikey);
		ud->browser_apikey = (value) ? strdup(value) : NULL;
	}
#endif /* WITH_HTTP */

#if WITH_LUA
	if (config_lookup_string(cf, "OTR_LUASCRIPT", &value) != CONFIG_FALSE) {
		if (ud->luascript) free(ud->luascript);
		ud->luascript = (value) ? strdup(value) : NULL;
	}
#endif

	config_destroy(cf);
}
Exemple #30
0
int main(int argc, char **argv) {
	// memtrack();

	wiringXLog = _lognone;

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

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

	struct options_t *options = NULL;
	struct ssdp_list_t *ssdp_list = NULL;

	int sockfd = 0;
	char *args = NULL, *recvBuff = NULL;

	/* Hold the name of the protocol */
	char *protobuffer = NULL;
	/* 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 *uuid = NULL;
	char *server = NULL;
	unsigned short port = 0;

	/* Hold the final protocol struct */
	protocol_t *protocol = NULL;
	JsonNode *code = NULL;

	/* 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, 'p', "protocol", 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, 'U', "uuid", OPTION_HAS_VALUE, 0, JSON_NULL, NULL, "[a-zA-Z0-9]{4}-[a-zA-Z0-9]{2}-[a-zA-Z0-9]{2}-[a-zA-Z0-9]{2}-[a-zA-Z0-9]{6}");

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

	/* Initialize protocols */
	protocol_init();

	/* Check if a protocol was given */
	if(protobuffer && strlen(protobuffer) > 0 && strcmp(protobuffer, "-V") != 0) {
		if(strlen(protobuffer) > 0 && version) {
			printf("-p and -V cannot be combined\n");
		} else {
			struct protocols_t *pnode = protocols;
			/* Retrieve the used protocol */
			while(pnode) {
				/* Check if the protocol exists */
				protocol = pnode->listener;
				if(protocol_device_exists(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 && help == 0) {
						options_merge(&options, &protocol->options);
					} else if(help == 1) {
						protohelp=1;
					}
					break;
				}
				pnode = pnode->next;
			}
			/* If no protocols matches the requested protocol */
			if(!match) {
				logprintf(LOG_ERR, "this protocol is not supported or doesn't support sending");
			}
		}
	}

	/* 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, 2, &args);

		if(c == -1)
			break;
		if(c == -2) {
			if(match == 1) {
				protohelp = 1;
			} else {
				help = 1;
			}
		break;
		}
	}

	/* Display help or version information */
	if(version == 1) {
		printf("%s %s\n", progname, PILIGHT_VERSION);
		goto close;
	} else if(help == 1 || protohelp == 1 || match == 0) {
		if(protohelp == 1 && match == 1 && protocol->printHelp)
			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 -p --protocol=protocol\t\tthe protocol that you want to control\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 -C --config\t\t\tconfig file\n");
			printf("\t -U --uuid=xxx-xx-xx-xx-xxxxxx\tUUID\n");
		}
		if(protohelp == 1 && match == 1 && protocol->printHelp) {
			printf("\n\t[%s]\n", protobuffer);
			protocol->printHelp();
		} else {
			printf("\nThe supported protocols are:\n");
			struct protocols_t *pnode = protocols;
			/* Retrieve the used protocol */
			while(pnode) {
				protocol = pnode->listener;
				if(protocol->createCode) {
					struct protocol_devices_t *tmpdev = protocol->devices;
					while(tmpdev) {
						struct pname_t *node = MALLOC(sizeof(struct pname_t));
						if(!node) {
							logprintf(LOG_ERR, "out of memory");
							exit(EXIT_FAILURE);
						}
						if(!(node->name = MALLOC(strlen(tmpdev->id)+1))) {
							logprintf(LOG_ERR, "out of memory");
							exit(EXIT_FAILURE);
						}
						strcpy(node->name, tmpdev->id);
						if(!(node->desc = MALLOC(strlen(tmpdev->desc)+1))) {
							logprintf(LOG_ERR, "out of memory");
							exit(EXIT_FAILURE);
						}
						strcpy(node->desc, tmpdev->desc);
						node->next = pname;
						pname = node;
						tmpdev = tmpdev->next;
					}
				}
				pnode = pnode->next;
			}
			sort_list();
			struct pname_t *ptmp = NULL;
			while(pname) {
				ptmp = pname;
				printf("\t %s\t\t",ptmp->name);
				if(strlen(ptmp->name) < 7)
					printf("\t");
				if(strlen(ptmp->name) < 15)
					printf("\t");
				printf("%s\n", ptmp->desc);
				FREE(ptmp->name);
				FREE(ptmp->desc);
				pname = pname->next;
				FREE(ptmp);
			}
			FREE(pname);
		}
		goto close;
	}

	code = json_mkobject();
	int itmp = 0;
	/* Check if we got sufficient arguments from this protocol */
	struct options_t *tmp = options;
	while(tmp) {
		if(strlen(tmp->name) > 0) {
			/* Only send the CLI arguments that belong to this protocol, the protocol name
			and those that are called by the user */
			if((options_get_id(&protocol->options, tmp->name, &itmp) == 0)
			    && tmp->vartype == JSON_STRING && tmp->string_ != NULL
				&& (strlen(tmp->string_) > 0)) {
				if(isNumeric(tmp->string_) == 0) {
					char *ptr = strstr(tmp->string_, ".");
					int decimals = 0;
					if(ptr != NULL) {
						decimals = (int)(strlen(tmp->string_)-((size_t)(ptr-tmp->string_)+1));
					}
					json_append_member(code, tmp->name, json_mknumber(atof(tmp->string_), decimals));
				} else {
					json_append_member(code, tmp->name, json_mkstring(tmp->string_));
				}
			}
			if(strcmp(tmp->name, "protocol") == 0 && strlen(tmp->string_) > 0) {
				JsonNode *jprotocol = json_mkarray();
				json_append_element(jprotocol, json_mkstring(tmp->string_));
				json_append_member(code, "protocol", jprotocol);
			}
		}
		tmp = tmp->next;
	}

	if(protocol->createCode(code) == 0) {
		if(protocol->message) {
			json_delete(protocol->message);
		}
		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);
		}

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

		JsonNode *json = json_mkobject();
		json_append_member(json, "action", json_mkstring("send"));
		if(uuid != NULL) {
			json_append_member(code, "uuid", json_mkstring(uuid));
		}
		json_append_member(json, "code", code);
		char *output = json_stringify(json, NULL);
		socket_write(sockfd, output);
		json_free(output);
		json_delete(json);

		if(socket_read(sockfd, &recvBuff, 0) != 0
		   || strcmp(recvBuff, "{\"status\":\"success\"}") != 0) {
			logprintf(LOG_ERR, "failed to send codes");
			goto close;
		}
	}
close:
	if(sockfd > 0) {
		socket_close(sockfd);
	}
	if(recvBuff != NULL) {
		FREE(recvBuff);
	}
	if(server != NULL) {
		FREE(server);
	}
	if(protobuffer != NULL) {
		FREE(protobuffer);
	}
	if(uuid != NULL) {
		FREE(uuid);
	}
	log_shell_disable();
	protocol_gc();
	options_delete(options);
	options_gc();
	config_gc();
	threads_gc();
	dso_gc();
	log_gc();
	FREE(progname);
	xfree();

	return EXIT_SUCCESS;
}