示例#1
0
void DAPLUGCALL Daplug_getTimeOTP(DaplugDongle *dpd, char* time){

    char get_time_apdu_str[5*2+1]="D0B0000000";

    //Set to apdu cde
    Apdu get_time_apdu;
    setApduCmd(get_time_apdu_str,&get_time_apdu);

    //exchange it
    exchangeApdu(dpd,&get_time_apdu);

    if(strcmp(get_time_apdu.sw_str,"9000")){
        fprintf(stderr,"\nget_time(): Cannot get dongle time !\n");
        return;
    }

    if(strcmp(str_sub(get_time_apdu.r_str,0,1),"00")){
        char *tmp = NULL;
        strcpy(time,tmp = str_sub(get_time_apdu.r_str,2,9));
        free(tmp);
        tmp = NULL;
    }else{
        char * tmp = NULL;
        fprintf(stderr,"\nget_time(): Dongle_info time reference not set yet !\n");
        free(tmp);
        tmp = NULL;
    }
}
示例#2
0
文件: easy.c 项目: luongnv89/c-easy
 char * str_subvalue(char *str, char* begin, char * end){
    if(str == NULL) return NULL;
    
    if(begin == NULL && end == NULL) return NULL;

    int begin_index = str_index(str,begin);
    int end_index = str_index(str,end);

    if(begin == NULL){
        return str_sub(str,0,end_index - 1);
    }

    if(end == NULL){
        return str_sub(str,begin_index + strlen(begin),strlen(str)-1);
    }
    

    if(begin_index == -1 ) return NULL;

    
    if(end_index == -1) return NULL;

    if(begin_index + strlen(begin) >= end_index) return NULL;

    int start_index = begin_index + strlen(begin);

    return str_sub(str,start_index,end_index - 1);
}
示例#3
0
/*
 * Retourne le bouton presse sur un interrupteur par le message en parametre.
 * Le message doit correspondre a un message envoye par un interrupteur, auquel cas le message ne sera pas pertinent.
 */
int getSwitch(char* message) {
	int result;
	int byteInt, statusInt;
	char * byte, *status;
	byte = str_sub(message, 2, 3);
	status = str_sub(message, 18, 19);
	byteInt = xtoi(byte); /* Extraction de l octet de donnee a partir du message */
	statusInt = xtoi(status); /* Extraction de l octet de statut a partir du message */
	if (statusInt & (1u << 4)) { /* Si le message est de type N */
		result = ((byteInt & 0xE0) >> 5); /* Extraction du bit 5 à 7 de l octet */
	} else { /* Si le message est de type U */
示例#4
0
文件: main.c 项目: Cpasjuste/pdm
void gui_app_exec(int n)
{
	pid_t childpid;
	int status;

	int lenght = strlen ( item->exec_path[n] );

	while ( item->exec_path[n][lenght] != '/' )
		lenght--;

	gui_clean();

	if ((childpid = fork()) == -1)
	{
		perror("Error in the fork");
	}
	else if (childpid == 0)
	{
   		if ( execl( pdm_dir_and("exec.sh"), pdm_dir_and("exec.sh"), item->exec_path[n], str_sub( item->exec_path[n], 0, lenght ), NULL) < 0 )
		{
			perror("Exec failed");
		}
	}
	else if (childpid != wait(&status))
	{ 
		perror("A signal occurred before the child exited");
	}

	gui_init();
	gui_load();
}
示例#5
0
/*
 * Retourne la temperature donnee par le message en parametre.
 * Le message doit correspondre a un message envoye par un capteur de temperature, auquel cas le message ne sera pas pertinent.
 */
int getTemp(char* message) {
	int temp;
	char * byte;
	byte = str_sub(message, 6, 7);
	temp = xtoi(byte); /* Extraction de la temperature a partir du message */
	gfree(byte);
	return temp;
}
示例#6
0
/*
 * Retourne la mesure de presence donnee par le message en parametre.
 * Le message doit correspondre a un message envoye par un capteur de presence, auquel cas le message ne sera pas pertinent.
 */
int getOccupancy(char* message) {
	int occupancy, byteInt;
	char * byte = str_sub(message, 8, 9);
	byteInt = xtoi(byte); /* Extraction de l octet de donnee a partir du message */
	occupancy = (byteInt & 0x02) >> 1; /* Extraction du bit 1 de l octet */
	gfree(byte);
	return occupancy;
}
示例#7
0
/*
 * Retourne la temperature donnee par le message en parametre. Celle-ci est exprimee sur deux octets.
 * Le message doit correspondre a un message envoye par un capteur de luminosite, auquel cas le message ne sera pas pertinent.
 */
int getLightBigSensor(char* message) {
	int light;
	char * byte;
	byte = str_sub(message, 4, 7);
	light = xtoi(byte); /* Extraction de la luminosite a partir du message */
	gfree(byte);
	return light;
}
示例#8
0
void snapshot(XMLNode xmlNode, TTNodePtr ttNode)
{
	TTSymbolPtr OSCaddress;
	TTValue		v, attributeNames;
	TTList		childList;
	TTNodePtr	p_node;
	TTString	s;
	
	ttNode->getOscAddress(&OSCaddress);
	ttNode->getChildren(S_WILDCARD, S_WILDCARD, childList);
	
	const char* address = OSCaddress->getCString();
	char* nodeName;
	
	XMLNode childNode = xmlNode;
	
	// don't write the first node AppName in xml because already written in application xml header
	// don't write the node name if is an instance, don't want it in xml file, replaced by dynamic instances attribute
	if (strcmp(address, AppName.c_str()) != 0 && strrchr(address, '.') == NULL) {
		
		// get the substring representing the last node name
		if (strlen(address) > 1) {
			const char* c = strrchr(address, '/');
			int start = c-address+1;
			int end = strlen(address)-1;
			nodeName = str_sub(address, start, end);

			childNode = xmlNode.addChild(nodeName);
		}
		
		if (childList.isEmpty()) {
			
			// get the Data object of the Node
			TTObjectPtr param = ttNode->getObject(); 
			
			if (param != NULL) {
				
				addAttributeToXml(param, childNode, kTTSym_type);
				addAttributeToXml(param, childNode, kTTSym_valueDefault);
				addAttributeToXml(param, childNode, kTTSym_rangeBounds);
				addAttributeToXml(param, childNode, kTTSym_rangeClipmode);
				addAttributeToXml(param, childNode, kTTSym_valueStepsize);
				addAttributeToXml(param, childNode, TTSymbol("dynamicInstances"));
				addAttributeToXml(param, childNode, TTSymbol("instanceBounds"));
				addAttributeToXml(param, childNode, kTTSym_priority);
				addAttributeToXml(param, childNode, kTTSym_description);
				addAttributeToXml(param, childNode, kTTSym_repetitionsFilter);
				addAttributeToXml(param, childNode, kTTSym_readonly);
			}
		}
	}
	
	// repeat recursively for each child
	for (childList.begin(); childList.end(); childList.next()) {
		childList.current().get(0,(TTPtr*)&p_node);
		snapshot(childNode, p_node);
	}
}
示例#9
0
void DAPLUGCALL Daplug_setTimeOTP(DaplugDongle *dpd, int keyVersion, int keyId, char *timeSrcKey, int step, int t){

    char set_time_ref_apdu_str[APDU_CMD_MAXLEN*2+1]="D0B2";
    char kv_s[1*2+1]="", kid_s[1*2+1]="";

    sprintf(kid_s,"%02X",keyId);
    sprintf(kv_s,"%02X",keyVersion);

    //Signature
    char temp_in[(11+1+4)*2+1]="",
         temp_out[(11+1+4)*2+1]="",
         signature[8*2+1]="";

    Byte nonce[11];
    char nonce_s[11*2+1]="";
    generateChallenge(nonce,11);
    bytesToStr(nonce,11,nonce_s);

    char step_s[1*2+1]="";
    if(step == 0){step = HOTP_TIME_STEP;}
    sprintf(step_s,"%02X",step);

    char time_s[4*2+1]="";
    if(t == 0){t = (int)time(NULL);}
    sprintf(time_s,"%08X",t);

    strcat(temp_in,nonce_s);
    strcat(temp_in,step_s);
    strcat(temp_in,time_s);

    tripleDES_CBC(temp_in,timeSrcKey,temp_out,DES_ENCRYPT);
    char *tmp = NULL;
    strcpy(signature, tmp = str_sub(temp_out,16,31));
    free(tmp);
    tmp = NULL;

    //Form the apdu
    strcat(set_time_ref_apdu_str,kv_s);
    strcat(set_time_ref_apdu_str,kid_s);
    strcat(set_time_ref_apdu_str,"18");
    strcat(set_time_ref_apdu_str,temp_in);
    strcat(set_time_ref_apdu_str,signature);

    //Set to apdu cde
    Apdu set_time_ref_apdu;
    setApduCmd(set_time_ref_apdu_str,&set_time_ref_apdu);

    //exchange it
    exchangeApdu(dpd,&set_time_ref_apdu);

    if(strcmp(set_time_ref_apdu.sw_str,"9000")){
        fprintf(stderr,"\nsetTimeOTP(): Cannot set time reference for dongle !\n");
        return;
    }else{
        fprintf(stderr,"\nsetTimeOTP(): Dongle_info time reference set.\n");
    }
}
示例#10
0
int str_str(char *src, char *dst)
{
	int cnt = 0;
	int index = 0;
	char tmp[N];
	for (index = 0; index < strlen(src) - strlen(dst); index++) {
		str_sub(src, tmp, index, strlen(dst));
		if (strcmp(tmp, dst) == 0) {
			cnt++;
		}
	}
	return cnt;
}
示例#11
0
int longest_dupstr(char *src, char *dst)
{
	int cnt = 0;
	int index;
	int times;
	int pos;
	for (index = 0; index < strlen(src); index++) {
		for (pos = 0; pos <= index; pos++) {
			str_sub(src, dst, pos, strlen(src) - index);
			cnt = str_str(src, dst);
			if (cnt >= 2) {
				return cnt;
			}
		}
	}
	return 0;
}
示例#12
0
void main()
{
	char str[20],sub_str[20],rep[20];
	int len,sub_len,i,pos;
	clrscr();
	printf("\n\tEnter the string  :  ");
	scanf("%[^\n]",str);
	printf("\n\tEnter the starting position of the substring	: ");
	scanf("%d",&pos);
	printf("\n\tEnter the length of the string	:  ");
	scanf("%d",&sub_len);
	str_sub(str,sub_str,pos,sub_len);
	printf("\n\tSub String is	:  ");
		printf("%s",sub_str);
	printf("\n\tEnter the string to be replaced : ");
	flushall();
	scanf("%[^\n]",rep);
	replace(str,rep,pos,sub_len);
	printf("\n\nAfter replacing string : %s",str);
	getch();
}
示例#13
0
void DAPLUGCALL Daplug_selectPath(DaplugDongle *dpd, char *path){

    if(!isHexInput(path) || strlen(path)%4 != 0){
        fprintf(stderr,"\nselectFile(): Wrong path : %s !\n",path);
        return;
    }

    int i = 0, j = 0, id;

    while(j<strlen(path)/4){
        char *tmp = NULL;
        sscanf(tmp = str_sub(path,i,i+3),"%04X",&id);
        free(tmp);
        tmp = NULL;
        Daplug_selectFile(dpd,id);
        i = i+4;
        j++;

    }

}
示例#14
0
/* Lance une action sur un actionneur de courant
 * Le courant est coupé si value = 7, et est en marche quand value = 5
 */
int actionCurrent(float value, struct Actuator * p_actuator, mqd_t smq) {
	char message[29];
	char valueHexa[3];
	char *actuatorRealID;

	sprintf(valueHexa,"%02X",(int)value);

	actuatorRealID = str_sub(p_actuator->id, strlen(p_actuator->id)-2, strlen(p_actuator->id)-1);

	/******* HEADER *******/
	strcpy(message, "A55A"); /* Début d'un message */
	strcat(message, "6B"); /* SYNC_BYTE */
	strcat(message, "05"); /* LENGTH_BYTE */
	/***** FIN HEADER *****/

	/******* DATA BYTE *******/
	strcat(message, valueHexa); /* BYTE 3 */
	strcat(message, "000000"); /* BYTE 2 à 0 */
	/***** FIN DATA BYTE *****/

	/******* ID *******/
	strcat(message, idReceptorEnOcean); /* 3 octets */
	strcat(message, actuatorRealID); /* 1 octet */
	/***** FIN ID *****/

	strcat(message, "30"); /* STATUS BYTE */
	strcat(message, "00\0"); /* CHECKSUM */
	
	p_actuator->status = value;
	if (value == (float) CURRENT_TURN_ON) {
		printf("[Actuator] Action sur l'actionneur de courant : Mise en marche.\n");
	} else {
		printf("[Actuator] Action sur l'actionneur de courant : Extinction.\n");
	}
	mq_send(smq, message, MAX_MQ_SIZE, 0);
	gLogsLog(p_actuator->id, p_actuator->status);
	gfree(actuatorRealID);
	return 0;
}
示例#15
0
int main(int argc, char **args)
{
	char *str = (char *) malloc(100);

	str_copy(str, "Hello World!");
	printf("%s\n", str);

	int cmp0 = str_compare("abcde", "abcde");
	int cmp1 = str_compare("abcde", "abcdf");
	int cmp2 = str_compare("abcdf", "abcde");
	int cmp3 = str_compare("abcde", "abcdef");
	int cmp4 = str_compare("abcdef", "abcde");
	printf("%d %d %d %d %d\n", cmp0, cmp1, cmp2, cmp3, cmp4);

	str_concat(str, "Hello ", "World!");
	printf("%s\n", str);

	str_sub(str, "Hello World!", 7, 2);
	printf("%s\n", str);

	int ind0 = str_index("Hello World!", "o", 0);
	int ind1 = str_index("Hello World!", "o", 5);
	printf("%d %d\n", ind0, ind1);

	str_copy(str, "Hello World!");
	str_insert(str, "My Beautiful ", 6);
	printf("%s\n", str);

	str_delete(str, 6, 3);
	printf("%s\n", str);

	str_delete(str, 6, 10);
	printf("%s\n", str);

	free(str);

	return 0;
}
示例#16
0
//extraction du code d'une commande
int extract_code (const char *str) {
	char *command = NULL;
	command = str_sub (str, 1, strlen (str));

	if (strcmp (command, "CREATE_ROOM") == 0) {
		return CREATE_ROOM;
	} else if (strcmp (command, "DELETE_ROOM") == 0) {
		return DELETE_ROOM;
	} else if (strcmp (command, "DISCONNECT") == 0) {
		return DISCONNECT;
	} else if (strcmp (command, "CONNECT") == 0) {
		return CONNECT;
	} else if (strcmp (command, "QUIT_ROOM") == 0) {
		return QUIT_ROOM;
	} else if (strcmp (command, "JOIN_ROOM") == 0) {
		return JOIN_ROOM;
	} else if (strcmp (command, "MESSAGE") == 0) {
		return MESSAGE;
	} else if (strcmp (command, "MP") == 0) {
		return MP;
	}

	return -1;
}
示例#17
0
void DAPLUGCALL Daplug_authenticate(DaplugDongle *dpd, Keyset keys, int mode, char *div, char *chlg){

    Byte hostChallenge[8];

    char counter[2*2+1] = "",
         cardChallenge[6*2+1] = "",
         returnedCardCryptogram[8*2+1]="",
         computedCardCryptogram[8*2+1]="",
         hostCryptogram[8*2+1] = "",
         s_hostChallenge[8*2+1]="",
         temp[APDU_CMD_MAXLEN*2+1]="";

    Apdu initialize_update,
         external_authenticate;

    //close any sc previously opened
    Daplug_deAuthenticate(dpd);

    if(!strcmp(chlg,"")){
        //generate host challenge
        generateChallenge(hostChallenge,8);
        bytesToStr(hostChallenge,8,s_hostChallenge);
    }else{
        if(strlen(chlg)!=8*2 || !isHexInput(chlg)){
            fprintf(stderr,"\nDaplug_authenticate(): Wrong value for challenge !\n");
            return;
        }
        strncpy(s_hostChallenge,chlg,16);
        s_hostChallenge[16]='\0';
    }

    //Keyset version
    char version[1*2+1]="";
    sprintf(version,"%02X",keys.version);

    //Any diversifier?
    if(strlen(div) != 0){
        if(strlen(div)!=16*2 || !isHexInput(div)){
        fprintf(stderr,"\nDaplug_authenticate(): Wrong value for diversifier !\n");
        return;
        }
    }

    if(strlen(div) == 0){
        //initialize update without diversifier
        strcat(temp,"8050");
        strcat(temp,version);
        strcat(temp,"0008");
        strcat(temp,s_hostChallenge);
        setApduCmd(temp,&initialize_update);
    }else{
        //diversified initialize update
        strcat(temp,"D050");
        strcat(temp,version);
        strcat(temp,"1018");
        strcat(temp,s_hostChallenge);
        strcat(temp,div);
        setApduCmd(temp,&initialize_update);
    }

    //exchange
    exchangeApdu(dpd,&initialize_update);

    if(strcmp(initialize_update.sw_str,"9000")){
        fprintf(stderr,"\nauthenticate(): initialize update error ! sw = %s\n",
                initialize_update.sw_str);
        return;
    }

    //extract data returned by the card
    char *tmp = NULL;
    strcpy(counter,tmp = str_sub(initialize_update.r_str, 24, 27));
    free(tmp);
    tmp = NULL;
    strcpy(cardChallenge,tmp = str_sub(initialize_update.r_str, 28, 39));
    free(tmp);
    tmp = NULL;
    strcpy(returnedCardCryptogram,tmp = str_sub(initialize_update.r_str, 40, 55));
    free(tmp);
    tmp = NULL;

    //compute session keys & update dpd
    char enc_key[GP_KEY_SIZE*2+1]="",
         mac_key[GP_KEY_SIZE*2+1]="",
         dek_key[GP_KEY_SIZE*2+1]="";

    bytesToStr(keys.key[0],GP_KEY_SIZE,enc_key);
    bytesToStr(keys.key[1],GP_KEY_SIZE,mac_key);
    bytesToStr(keys.key[2],GP_KEY_SIZE,dek_key);

    //session s-enc key
    computeSessionKey(counter,"0182",enc_key,dpd->s_enc_key);

    //session s-enc key
    computeSessionKey(counter,"0183",enc_key,dpd->r_enc_key);

    //session c-mac key
    computeSessionKey(counter, "0101", mac_key, dpd->c_mac_key);

    //session r-mac key
    computeSessionKey(counter, "0102", mac_key, dpd->r_mac_key);

    //session dek key. In case of need it will be used. (to form "put key" command for example)
    computeSessionKey(counter,"0181", dek_key, dpd->s_dek_key);

    //compute card cryptogram
    computeCardCryptogram(s_hostChallenge,cardChallenge,counter,dpd->s_enc_key,computedCardCryptogram);

    //check card cryptogram
    if(!checkCardCryptogram(returnedCardCryptogram,computedCardCryptogram)){
        fprintf(stderr,"\nauthenticate(): Card Cryptogram verification failed !\n");
        return;
    }
    else{
        //compute data that an external Daplug_authenticate apdu needs
        computeHostCryptogram(s_hostChallenge, cardChallenge, counter, dpd->s_enc_key, hostCryptogram);

        //mode
        char sec_l[1*2+1]="";
        sprintf(sec_l,"%02X",mode);

        //external Daplug_authenticate
        strcpy(temp,""),
        strcat(temp,"8082");
        strcat(temp,sec_l);
        strcat(temp,"0008");
        strcat(temp,hostCryptogram);
        setApduCmd(temp,&external_authenticate);

        //exchange
        exchangeApdu(dpd,&external_authenticate);

        if(strcmp(external_authenticate.sw_str,"9000")){
            fprintf(stderr,"\nauthenticate(): external Daplug_authenticate error ! sw = %s\n",
                    external_authenticate.sw_str);
            return;
        }

    }

    fprintf(stderr,"\nauthenticate() : Successful authentication !\n");

    //update dpd
    strcpy(dpd->r_mac,dpd->c_mac);
    dpd->securityLevel = mode;
    dpd->session_opened = 1;
}
示例#18
0
int DAPLUGCALL keyboard_addTextWindows(Keyboard *k, char *text){

    int len_text = strlen(text),
        added_len,
        nb = 0,
        i = 0;

    char last_part_len_s[1*2+1]="",
         mwtl_s[1*2+1]="",
         *part = NULL;

    sprintf(mwtl_s,"%02X",MAX_WINDOWS_TEXT_LEN);


    int last_part_len = len_text % MAX_WINDOWS_TEXT_LEN;
    sprintf(last_part_len_s,"%02X",last_part_len);

    if(last_part_len == 0) nb = len_text/MAX_WINDOWS_TEXT_LEN; else nb = (int)len_text/MAX_WINDOWS_TEXT_LEN+1;

    while(nb>0){
        added_len = strlen("04")+strlen(mwtl_s);
        added_len = added_len/2;
        if(nb > 1 || last_part_len == 0){
            if(k->currentContentSize+added_len <= MAX_KB_CONTENT_SIZE){
                strcat(k->content,"04");
                strcat(k->content,mwtl_s);
                part = str_sub(text,i,i+MAX_WINDOWS_TEXT_LEN-1);
                if(!addAsciiText(k,part)){
                    fprintf(stderr,"\nkeyboard_addTextWindows(): An error occured when adding text !\n");
                    return 0;
                }
                free(part);
                part = NULL;
                k->currentContentSize = k->currentContentSize+added_len;
            }
            else{
                fprintf(stderr,"\nkeyboard_addTextWindows(): Keyboard maximum content size exceeded !\n");
                return 0;
            }
        }else{
            if(k->currentContentSize+added_len <= MAX_KB_CONTENT_SIZE){
                strcat(k->content,"04");
                strcat(k->content,last_part_len_s);
                part = str_sub(text,i,i+last_part_len-1);
                if(!addAsciiText(k,part)){
                    fprintf(stderr,"\nkeyboard_addTextWindows(): An error occured when adding text !\n");
                    return 0;
                }
                free(part);
                part = NULL;
                k->currentContentSize = k->currentContentSize+added_len;
            }
            else{
                fprintf(stderr,"\nkeyboard_addTextWindows(): Keyboard maximum content size exceeded !\n");
                return 0;
            }
        }

        i = i+MAX_WINDOWS_TEXT_LEN;
        nb--;
    }

    return 1;
}
示例#19
0
/*
 * Fonction permettant l'écoute de périphérique SunSpot.
 * Si un composant SunSpot non enregistré communique, il sera
 * automatiquement enregistré dans notre liste de capteurs.
 */
void *ListenSunSpot(void *message1) {
	char buffer[47];
	long n;
	struct sockaddr_in serverAddr;
	char * fragmentString;
	socklen_t serverAddrLen = sizeof (serverAddr);

	/* Variable pour la trame a gerer, seront utilises bien plus tard */
	char* idCapteur;
	/* char* dateTime; */ /* (inutilisée) */
	int temperature;
	char hexTemperature[3];
	int brightness;
	float f_brightness, f_temperature;
	char hexBrightness[3];
	char frame[23];


	/* Déclaration des infos réseau */
	serverAddr.sin_family = AF_INET;
	serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* on assume que le serveur Java tournera sur la même machine */
	serverAddr.sin_port = htons(1337);

	/* Création du socket en UDP*/
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == ERROR) {
		perror("[ListenSunSpot] Erreur dans la creation du socket UDP SunSPOT ");
		return (int*) ERROR;
	}

	#if DEBUG > 0
	printf("[ListenSunSpot] Connection avec le serveur...\n");
	#endif

	/* Pas de connect à faire, il faut juste se binder */
	if (bind(sock, (struct sockaddr*) & serverAddr, serverAddrLen) == SOCKET_ERROR) {
		perror("[ListenSunSpot] Erreur dans la connection avec le serveur ");
		return (int*) SOCKET_ERROR;
	}

	#if DEBUG > 0
	printf("[ListenSunSpot] Connection avec le serveur OK\n");
	#endif

	while (1) {
		#if DEBUG > 0
		printf("[ListenSunSpot] Attente d'un début de message...\n");
		#endif

		/* on reçoit le message en une seule fois */
		if ((n = recvfrom(sock, buffer, sizeof (buffer) - 1, 0, (struct sockaddr*) & serverAddr, &serverAddrLen)) < 0) {
			perror("[ListenSunSpot] Erreur dans la réception ");

			break;
		}

		#if DEBUG > 0
		printf("[ListenSunSpot] Message d'un capteur reçu..\n");
		#endif

		/*
		 *        On va maintenant parser le message
		 *        Il a le même format que celui des capteurs EnOcean
		 */

		/* message = (char*) buffer; */ /* on mets ça dans un char*, passe à une chaîne de charactères */
		/*strncpy(message, buffer, 30);
		 *
		 * printf(message);*/

		printf("MESSAGE : %s\n",buffer);

		fragmentString = strtok(buffer, ";");
		printf("fragmentString avant A55A : %s\n",fragmentString);

			/* on regarde l'entête, vérifie que c'est bien "A55A" */
			if (strcmp(fragmentString, "A55A") != 0) {
				printf("[ListenSunSpot] Mauvais header.\n");
			}

			fragmentString = strtok(NULL, ";");
			printf("fragmentString apres A55A : %s\n",fragmentString);

				/* on vérifie maintenant si on est bien sur un vrai capteur SunSpot : type "03" */
				if (strcmp(fragmentString, "03") != 0) {
					printf("[ListenSunSpot] Bon type de capteur.\n");
				}

				/*
				 *        Maintenant on a, séparés par des ; :
				 *        adresse du capteur (id)
				 *        date/time
				 *        luminosité
				 *        température
				 *
				 *        On récupère le restant du message, pour construire une "pseudo-trame",
				 *        similaire à ce que les capteurs EnOcean envoient
				 */

				/* id du capteur :
				 *        forme 0014.4F01.0000.5620,
				 *        les 15 premiers charactères sont toujours les mêmes,
				 *        du coup on raccourcit sans problèmes pour ne garder que les 4 derniers
				 */

				idCapteur = str_sub(strtok(NULL, ";"), 15, 18);
				printf("idCapteur : %s\n",idCapteur);

					/* date et heure de la mesure : info pas utilisée pour l'instant */
					/* dateTime = strtok(NULL, ";"); */

					/* luminosité */
					brightness = atoi(strtok(NULL, ";")); /* on récupère déjà la valeur dans un int */
					printf("brightness : %i\n",brightness);

					/* il faut qu'on applique un coefficient de nouveau :
					 *        la valeur envoyée par le capteur est entre 0 et 750 (cf datasheet)
					 *        il faut que cela tienne dans un int entre 0 et 255
					 *
					 *        détail du calcul :
					 *           (750-0)/(255-0)
					 */

					f_brightness = (float)brightness / 2.94117647;				
					sprintf(hexBrightness, "%02X", (int) f_brightness);
					
					printf("hexBrightness : %s\n",hexBrightness);
					/* température - même fonctionnement */
					temperature = atoi(strtok(NULL, ";"));

					/* il faut qu'on applique un coefficient (diviseur)
					 *        détail du calcul :
					 *        (scaleMax-scaleMin)/(rangeMax/rangeMin)
					 *        on remplace avec les valeurs, issues de la datasheet pour la scale et le range est celui d'un int :
					 *        (165-0)/(255-0) = 0,647058824
					 */
					f_temperature = (float)temperature * 0.647058824;
					sprintf(hexTemperature, "%02X", (int) f_temperature);

					/*
					 *        On construit concrètement la pseudo trame maintenant :
					 *           FF : code org
					 *           00 : "trou"
					 *           LL : valeur de la luminosité
					 *           TT : valeur de la température
					 *           00 : "trou"
					 *           0000 : "faux" ID
					 *           IDID : ID réel du SPOT
					 *           0000 : "trou"
					 */
					strcpy(frame,"FF00");
					strcat(frame,hexBrightness);
					strcat(frame,hexTemperature);
					strcat(frame,"000000");
					strcat(frame,idCapteur);
					strcat(frame,"0000");

					gfree(idCapteur);
					#if DEBUG == 0
					printf("frame : %s\n",frame);
					#endif

					ManageMessage(frame);
	}

	return (void *) NULL;
}
示例#20
0
文件: easy.c 项目: luongnv89/c-easy
 char * str_replace(char * str, char * str1, char * rep){

    if(str == NULL) return NULL;

    if(str1 == NULL || rep == NULL) {
        return str_copy(str);
    }

    int * array_index = str_get_indexes(str,str1);

    if(array_index == NULL) {
        return str_copy(str);
    }
    int current_index = 0;

    int nb_element =0;
    while(array_index[nb_element] != -1){
        nb_element++;
    }

    int new_string_len = strlen(str) + nb_element * strlen(rep) - nb_element * strlen(str1)+1;
    char * new_string;
    new_string = (char * )malloc(new_string_len);
    new_string[0] = '\0';

    if(array_index[current_index] != 0){
        char * str_substr = str_sub(str,0,array_index[current_index]-1);
        strcpy(new_string,str_substr);
        free(str_substr);
    }

    while(array_index[current_index + 1] != -1){

        char * str_substr = str_sub(str,array_index[current_index] + strlen(str1),array_index[current_index + 1] -1);
        
        if(strlen(new_string)==0){
            strcpy(new_string,rep);
        }else{
            strcat(new_string,rep);
        }
        strcat(new_string,str_substr);
        free(str_substr);
        current_index ++;
    }

    // The spliter is at the end of string
    if(strlen(str) >= array_index[current_index] + strlen(str1)){
        char * str_substr = str_sub(str,array_index[current_index] + strlen(str1),strlen(str) -1);
        strcat(new_string,rep);    
        if(str_substr != NULL){
            strcat(new_string,str_substr);
            free(str_substr);
        }
    }

    new_string[new_string_len-1] = '\0';

    free(array_index);
    
    return new_string;

 }
示例#21
0
void DAPLUGCALL Daplug_writeData(DaplugDongle *dpd, int  offset, char* data_to_write){

    Apdu update_binary_apdu;

    char update_binary_apdu_str[APDU_CMD_MAXLEN*2+1]="";
    char pos[2*2+1]="";
    char last_part_len_str[2*2+1]="";

    int p = offset, length = strlen(data_to_write)/2,
        last_part_len = length % MAX_REAL_DATA_SIZE;

    sprintf(last_part_len_str,"%02X",last_part_len);

    if(length%2 !=0 || length <=0 || length + p > MAX_FS_FILE_SIZE || !isHexInput(data_to_write)){
        fprintf(stderr,"\nwriteData(): Wrong data !\n");
        return;
    }

    sprintf(pos,"%04X",p);

    //We write parts of MAX_FS_DATA_RW_SIZE bytes : EF = FF - 8 - 8 (data max len - possible mac - possible pad when enc)
    int write_nb = 0;
    if(length % MAX_REAL_DATA_SIZE== 0) write_nb = length/MAX_REAL_DATA_SIZE; else write_nb = (int)length/MAX_REAL_DATA_SIZE+1;

    char part[MAX_REAL_DATA_SIZE*2+1]="";

    int i = 0;

    while(write_nb > 0){

        strcpy(update_binary_apdu_str,"");
        strcat(update_binary_apdu_str,"80d6");
        strcat(update_binary_apdu_str,pos);

        if(write_nb > 1 || length % MAX_REAL_DATA_SIZE == 0){
            strcat(update_binary_apdu_str,"EF");
            char *tmp = NULL;
            strcpy(part,tmp = str_sub(data_to_write,i,i+MAX_REAL_DATA_SIZE*2-1));
            free(tmp);
            tmp = NULL;
        }else{
            char *tmp = NULL;
            strcat(update_binary_apdu_str,last_part_len_str);
            strcpy(part,tmp = str_sub(data_to_write,i,i+(length%MAX_REAL_DATA_SIZE)*2-1));
            free(tmp);
            tmp = NULL;
        }

        strcat(update_binary_apdu_str,part);

        //Set to apdu cde
        setApduCmd(update_binary_apdu_str,&update_binary_apdu);

        //exchange it
        exchangeApdu(dpd,&update_binary_apdu);

        if(strcmp(update_binary_apdu.sw_str,"9000")){
            fprintf(stderr,"\nwriteData(): Write failure !\n");
            return;
        }

        sscanf(pos,"%04X",&p);
        p = p + MAX_REAL_DATA_SIZE;
        sprintf(pos,"%04X",p);

        i = i+MAX_REAL_DATA_SIZE*2;
        write_nb--;

    }
}
示例#22
0
文件: conf.c 项目: flygoast/filmond
static char *conf_evaluate(conf_t *conf, char *value) {
    char    *buf = NULL;
    int     avail = MAX_LINE - 1;
    char    *scan, *p;
    int     len = 0;
    char    *var, *sub = NULL, *ret;

    if ((scan = strchr(value, '$')) == NULL) {
        return value;
    }

    if (*(scan + 1) == '\0') {
        return value;
    }

    buf = (char *)calloc(MAX_LINE, sizeof(char));
    if (!buf) {
        return NULL;
    }

    if (scan - value > avail) {
        goto error;
    }

    strncpy(buf, value, scan - value);
    avail -= scan - value;

    ++scan;
    if (*scan == '{' || *scan == '(') {
        ++scan;
    }

    p = (char *)scan;
    while (*scan && *scan != '}' && *scan != ')' && *scan != ' ') {
        ++scan;
        ++len;
    }

    if (*scan == '}' || *scan == ')') {
        ++scan;
    }

    sub = str_sub(p, 0, len);
    if (!sub) {
        goto error;
    }

    if ((var = conf_get_str_value(conf, sub, NULL)) == NULL) {
        var = getenv(sub);
    }

    if (var) {
        if (strlen(var) > avail) {
            goto error;
        }
        strncat(buf, var, avail);
        avail -= strlen(var);
    }
    strncat(buf, scan, avail);
    free(sub);

    if ((ret = conf_evaluate(conf, buf)) == NULL) {
        goto error;
    } else if (ret == buf) {
        return ret;
    } else {
        free(buf);
        return ret;
    }

error:
    if (buf) free(buf);
    if (sub) free(sub);
    return NULL;
}
示例#23
0
int DAPLUGCALL keyboard_addTextMac(Keyboard *k, char *text, int azerty, int delay){

    int len_text = strlen(text),
        added_len,
        nb = 0,
        i = 0;

    char last_part_len_s[1*2+1]="",
         mmtl_s[1*2+1]="",
         azerty_s[1*2+1]="",
         delay_s[2*2+1]="",
         *part = NULL;

    if(azerty==-1) azerty = 0;
    if(delay == -1) delay = 0x1000;

    sprintf(azerty_s,"%02X",azerty);
    sprintf(delay_s,"%04X",delay);

    sprintf(mmtl_s,"%02X",MAX_MAC_TEXT_LEN+3);

    int last_part_len = len_text % MAX_MAC_TEXT_LEN;
    sprintf(last_part_len_s,"%02X",last_part_len+3);

    if(last_part_len == 0) nb = len_text/MAX_MAC_TEXT_LEN; else nb = (int)len_text/MAX_MAC_TEXT_LEN+1;

    while(nb>0){
        added_len = strlen("11")+strlen(mmtl_s)+strlen(azerty_s)+strlen(delay_s);
        added_len = added_len/2;
        if(nb > 1 || last_part_len == 0){
            if(k->currentContentSize+added_len <= MAX_KB_CONTENT_SIZE){
                strcat(k->content,"11");
                strcat(k->content,mmtl_s);
                strcat(k->content,azerty_s);
                strcat(k->content,delay_s);
                part = str_sub(text,i,i+MAX_MAC_TEXT_LEN-1);
                if(!addAsciiText(k,part)){
                    fprintf(stderr,"\nkeyboard_addTextMac(): An error occured when adding text !\n");
                    return 0;
                }
                free(part);
                part = NULL;
                k->currentContentSize = k->currentContentSize+added_len;
            }
            else{
                fprintf(stderr,"\nkeyboard_addTextMac(): Keyboard maximum content size exceeded !\n");
                return 0;
            }
        }else{
            if(k->currentContentSize+added_len <= MAX_KB_CONTENT_SIZE){
                strcat(k->content,"11");
                strcat(k->content,last_part_len_s);
                strcat(k->content,azerty_s);
                strcat(k->content,delay_s);
                part = str_sub(text,i,i+last_part_len-1);
                if(!addAsciiText(k,part)){
                    fprintf(stderr,"\nkeyboard_addTextMac(): An error occured when adding text !\n");
                    return 0;
                }
                free(part);
                part = NULL;
                k->currentContentSize = k->currentContentSize+added_len;
            }
            else{
                fprintf(stderr,"\nkeyboard_addTextMac(): Keyboard maximum content size exceeded !\n");
                return 0;
            }
        }

        i = i+MAX_MAC_TEXT_LEN;
        nb--;
    }

    return 1;

}
示例#24
0
/**
 * \brief Parse a string
 * \param mess_src The string to parse.
 * \return A Message created from the parameter.
 */
struct Message* mess__parse(char* mess_src)
{
	if(!isEverythingInitialized) mess__base__init();
     if(!mess_src)
	  return NULL;
     struct Message* mess_dest;
     mess__init(&mess_dest);

     int i;
     int match = 0;
     char * ptr, *tmp2;

     for(i = 0; i < MESS__NB_REGEXES; i++) // trouver le moyen de staticifier ça
     {
	  if(trex_match(trex_regexes[i], mess_src))
	  {
	       match = 1;
	       break;
	  }
     }
     if(match == 0) i = -1;

     char * tmp = malloc((strlen(mess_src) + 1)* sizeof(char));
     switch(i)
     {
     case 0:
	  mess_dest->type = LOAD;
	  mess_dest->s_parameter = str_sub(mess_src, 5, strlen(mess_src) - 1);
	  break;
     case 1:
	  mess_dest->type = SAVE;
	  mess_dest->s_parameter = str_sub(mess_src, 5, strlen(mess_src) - 1);
	  break;
     case 2:
	  mess_dest->type = SHOW;
	  break;
     case 3:
	  mess_dest->type = ADDLINK;
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->node1 = strcopy(strtok(NULL, " "));
	  mess_dest->node2 = strcopy(strtok(NULL, " "));
	  mess_dest->n_parameter = atoi(strtok(NULL, " "));
	  break;
     case 4:
	  mess_dest->type = UPDATELINK;
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  mess_dest->n_parameter = atoi(strtok(NULL, " "));
	  break;
     case 5:
	  mess_dest->type = DELLINK;
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  break;
     case 6:
	  mess_dest->type = DISCONNECT;
	  strtok(mess_src, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  break;
     case 7:
	  mess_dest->type = MESSAGE;
	  strcpy(tmp, mess_src);
	  strtok(tmp, " ");

	  mess_dest->node1  = strcopy(strtok(NULL, " "));

	  ptr = strstr(mess_src, mess_dest->node1) + strlen(mess_dest->node1) + 2;
	  mess_dest->s_parameter = malloc((1 + strlen(ptr)) * sizeof(char));
	  strcpy(mess_dest->s_parameter, ptr);
	  mess_dest->s_parameter[strlen(ptr) - 1] = 0;

	  break;
     case 8:
	  mess_dest->type = ROUTE;
	  strtok(mess_src, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));

	  break;
     case 9:
	  mess_dest->type = ROUTETABLE;
	  break;
     case 10:
	  mess_dest->type = LOGIN;
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->n_parameter = atoi(strtok(NULL, " "));

	  break;
     case 11:
	  mess_dest->type = LOGIN;
	  //log in port p
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  strtok(NULL, " ");
	  mess_dest->n_parameter = atoi(strtok(NULL, " "));

	  break;
     case 12:
	  mess_dest->type = LOGOUT;
	  break;
     case 13:
	  mess_dest->type = GREETING;
	  strtok(mess_src, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  break;
     case 14:
	  mess_dest->type = BYE;
	  break;
     case 15:
	  mess_dest->type = POLL;
	  break;
     case 16:
	  mess_dest->type = NEIGHBORHOOD;
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->s_parameter  = strcopy(strtok(NULL, " "));
	  break;
     case 17:
	  mess_dest->type = NEIGHBORHOOD;
	  mess_dest->accept = OK;
	  break;
     case 18:
	  mess_dest->type = LINK;
	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  break;
     case 19:
	  mess_dest->type = LINK;
	  mess_dest->accept = OK;
	  break;
     case 20:
	  mess_dest->type = VECTOR;
	  strtok(mess_src, " ");
	  mess_dest->s_parameter  = strcopy(strtok(NULL, " "));
	  break;
     case 21:
	  mess_dest->type = VECTOR;
	  mess_dest->accept = OK;
	  break;
     case 22:
	  mess_dest->type = PACKET;

	  strcpy(tmp, mess_src);

	  strtok(tmp, " ");
	  strtok(NULL, " ");
	  mess_dest->seqnum  = atoi(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");

	  tmp2 = strtok(NULL, " ");
	  mess_dest->n_parameter = atoi(tmp2);


	  mess_dest->s_parameter = strcopy(strtok(NULL, "\0") + 5); //strstr(mess_src, tmp2) + strlen(tmp2) + 1;
	  break;

     case 23:
	  mess_dest->type = PACKET;
	  mess_dest->accept = OK;

	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->seqnum  = atoi(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  break;

     case 24:
	  mess_dest->type = PACKET;
	  mess_dest->accept = TOOFAR;

	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->seqnum  = atoi(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  break;

     case 25:
	  mess_dest->type = PING;

	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->seqnum  = atoi(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->n_parameter = atoi(strtok(NULL, " "));
	  break;

     case 26:
	  mess_dest->type = PONG;

	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->seqnum  = atoi(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->n_parameter = atoi(strtok(NULL, " "));
	  break;

     case 27:
	  mess_dest->type = PONG;
	  mess_dest->accept = TTLZERO;

	  strtok(mess_src, " ");
	  strtok(NULL, " ");
	  mess_dest->seqnum  = atoi(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  strtok(NULL, " ");
	  mess_dest->node2  = strcopy(strtok(NULL, " "));
	  break;

     case 28:
	  mess_dest->type = PING;
	  strtok(mess_src, " ");
	  mess_dest->node1  = strcopy(strtok(NULL, " "));
	  break;

     case 29:
	  mess_dest->type = QUIT;
	  break;

     case 30:
	  mess_dest->type = NEIGHBORHOOD;
	  mess_dest->s_parameter = malloc(sizeof(char));
	  mess_dest->s_parameter[0] = 0;
	  break;

     case 31:
	  mess_dest->type = VECTOR;
	  mess_dest->s_parameter = malloc(sizeof(char) * 3);
	  mess_dest->s_parameter[0] = '[';
	  mess_dest->s_parameter[1] = ']';
	  mess_dest->s_parameter[2] = 0;
	  break;

     case 32:
       	  mess_dest->type = NETWORK_DEBUG;
       break;

     default:
	  mess_dest->type = NONE;
	  fprintf(stderr, "ERREUR: Message invalide : '%s'.\n", mess_src);

	  break;
     }

     free(tmp);
     return mess_dest;
}