Example #1
0
static void conf0Dialog() {
    bool dirty = false;

    AsnLMsg msg = AsnLMsg(CONF0_BUFFER_SIZE);
    AsnLParser p = AsnLParser(msg);
    AsnLWriter w = AsnLWriter(msg);
    while (1) {
        msg.readFromSerial();
        p.init();
        if (!checkToken(p, ASNL_STRUCT)) { // invalid message (not a structure)
            result(p, w, 0);
            continue;
        }
        if (!checkToken(p, ASNL_INT)) { // invalid message (not and integer)
            result(p, w, 0);
            continue;
        }
        int command;
        p.readInt(&command);
        switch (command) {
        case 'd': dumpVars(p, w); break;
        case 'p': setPinCode(p, w); dirty = true; break;
        case 'i': app.DI = extractInt16(p, w); dirty = true; break;
        case 'f': app.DF = extractInt16(p, w); dirty = true; break;
        case 'l': app.idleColorOn = extractInt32(p, w); dirty = true; break;
        case 'm': app.idleColorOff = extractInt32(p, w); dirty = true; break;
        case '1': app.idleTicksOn = extractInt16(p, w); dirty = true; break;
        case '0': app.idleTicksOff = extractInt16(p, w); dirty = true; break;
        case 's': save(p, w, dirty); dirty = false; break;
        case 'x': result(p, w, 1); return; // exit
        default: result(p, w, 0); break; // invalid command
        }
    }
}
Example #2
0
void dumpVars(AsnLParser& p, AsnLWriter& w) {
    if (!checkToken(p, ASNL_END_STRUCT)) {
        result(p, w, 0); return;
    }
    if (!checkToken(p, ASNL_NIL)) {
        result(p, w, 0); return;
    }

    w.init();
    w.structure();
    w.integer(1, 1); // Status OK
    w.structure();
    w.string(app.pinCode);
    w.integer(2, app.DI);
    w.integer(2, app.DF);
    w.integer(4, app.idleColorOn);
    w.integer(4, app.idleColorOff);
    w.integer(2, app.idleTicksOn);
    w.integer(2, app.idleTicksOff);
    w.endStructure();
    w.endStructure();

    w.msg().writeToSerial();
    digitalWrite(13, LOW);

}
Example #3
0
Obj_ptr Quote(const ParseTree_ptr &root)
{
	if (root == nullptr)
		return nullptr;
	std::string token = root->getToken();
	bool numberFlag = true, rationalFlag = false, realFlag = false, idenFlag = true;

	checkToken(token, numberFlag, rationalFlag, realFlag, idenFlag);

	if ( numberFlag==true )		// numerical constant
	{
		//----integer-----
		if (!rationalFlag && !realFlag)
			return Obj_ptr( new IntegerObj( bigInteger(token) ) );
		//----rational----
		else if (rationalFlag)
			return Obj_ptr( new RationalObj( bigRational(token) ) );
		//----real--------
		else
			return Obj_ptr( new RealObj( bigReal(token) ) );
	}
	else if (token[0]=='\"')	// string constant
		return Obj_ptr( new StringObj(token.substr(1, token.size()-2)) );
	else if (token[0]=='#')
	{
		// character constant
		if (token[1]=='\\')
		{
			if (token=="#\\newline")
				return Obj_ptr( new CharObj('\n') );
			else if (token=="#\\space")
				return Obj_ptr( new CharObj(' ') );
			else if (token=="#\\tab")
				return Obj_ptr( new CharObj('\t') );
			else
				return Obj_ptr( new CharObj(token[2]) );
		}
		// boolean constant
		else
		{
			if (token[1]=='t')
				return Obj_ptr( new BoolObj(true) );
			else
				return Obj_ptr( new BoolObj(false) );
		}
	}
	else if (token=="\'")
		return Quote(root->getSon());
	else if (token=="`")
		throw syntaxError("unexpected \'`\' here");	
	else if (token=="()")
		return quoteMakeList(root->getSon());
	else if (token[0]==',')
		throw syntaxError("unexpected comma here");	
	else
		return Obj_ptr( new SymbolObj( token ) );
}
Example #4
0
static int32_t extractInt32(AsnLParser& p, AsnLWriter& w) {
    int32_t value;
    if (checkToken(p, ASNL_INT)) {
        if (p.readInt(&value) != 0) {
            result(p, w, 0); return -1; // failed to read int
        }
    } else {
        result(p, w, 0); return -1; // not an int
    }
    if (!checkToken(p, ASNL_END_STRUCT)) {
        result(p, w, 0); return -1;
    }
    if (!checkToken(p, ASNL_NIL)) {
        result(p, w, 0); return -1;
    }
    result(p, w, 1);
    return value;
}
Example #5
0
static void setPinCode(AsnLParser& p, AsnLWriter& w) {
    char pinCode[8];
    if (checkToken(p, ASNL_STRING)) {
        if (!p.readString(pinCode, 8)) {
            result(p, w, 0); return; // failed to read string
        }
    } else {
        result(p, w, 0); return; // not a string
    }
    if (!checkToken(p, ASNL_END_STRUCT)) {
        result(p, w, 0); return;
    }
    if (!checkToken(p, ASNL_NIL)) {
        result(p, w, 0); return;
    }
    app.pinCode = String(pinCode);
    result(p, w, 1);
}
Example #6
0
QVariant QJson::parseBool(const QString &json, int &index, bool &success, QString *errorMessage)
{
	if (checkToken(json, index, success, errorMessage, "true"))
	{
		index += 4;
		return QVariant(true);
	}
	else if (checkToken(json, index, success, errorMessage, "false"))
	{
		index += 5;
		return QVariant(false);
	}
	else
	{
		success = false;
		if (errorMessage)
			*errorMessage = QString("Can't parse value at position %1").arg(index);
		return QVariant();
	}
}
Example #7
0
int parseArguments(LPSTR szCmdLine) {
	BOOL inToken = false, result;
	int  i = 0, j=0;
	char token[MAX_TOKEN_SIZE];

	if (openDevice(FALSE)) {
		getDriverData(&cmiTopologyDev);
		currentChannelCount = -1;
	}

	while (szCmdLine[i]) {
		if (inToken) {
			if (szCmdLine[i] == ' ') {
				inToken = false;
				token[j] = 0;
				if (checkToken(token)) {
					return TRUE;
				}
			} else {
				token[j] = (char)toupper(szCmdLine[i]);
				if (j < MAX_TOKEN_SIZE-1) {
					j++;
				}
			}
		} else {
			if ((szCmdLine[i] == '-') || (szCmdLine[i] == '/')) {
				j = 0;
				inToken = true;
			}
		}

		i++;
	}
	token[j] = 0;
	checkToken(token);

	result = setDriverData(&cmiTopologyDev);
	if (currentChannelCount != -1)
		result |= setCurrentChannelConfig();
	return result;
}
Example #8
0
KQOAuthRequest* FoursquareApi::getUserInfo() {
	KQOAuth2Request *req = new KQOAuth2Request(this);
	if(!checkToken()) {
		req->initRequest(KQOAuthRequest::AuthorizedRequest, QUrl(API_BASE + "users/self"));
		req->setToken(oauthSettings.value("oauth_token").toString());
		KQOAuthParameters params;
		params.insert("v","20120501");
		req->setAdditionalParameters(params);
		req->setHttpMethod(KQOAuthRequest::GET);
	}
	return req;
}
Example #9
0
int ParallelAlgorithm::communicationLoop(void)
{
	for(int processId = 0; processId < countOfProcesses; processId++)
	{
//		if(processId == myRank) 
//			continue;

		int flag = 0;
    		MPI_Iprobe(processId, MPI_ANY_TAG, MPI_COMM_WORLD, &flag, &status);

    		if (flag)
    		{
      		//v promenne status je tag (status.MPI_TAG), cislo odesilatele (status.MPI_SOURCE)
      		//a pripadne cislo chyby (status.MPI_ERROR)
      		switch (status.MPI_TAG)
      		{
         			case MSG_WORK_REQUEST : // zadost o praci, prijmout a dopovedet
					checkWorkRequest();
					break;

         			case MSG_WORK_TRANSMIT : // prisel rozdeleny zasobnik, prijmout
					checkIncommingWork();
                              break;

         			case MSG_WORK_NOWORK : // odmitnuti zadosti o praci
					std::cout << "Process #" << myRank << " recieved MSG_NO_WORK from #" << status.MPI_SOURCE << std::endl;
                              // zkusit jiny proces
//					requestMoreWork();
					break;

         			case MSG_TOKEN : //ukoncovaci token, prijmout a nasledne preposlat
					checkToken();					
                          	break;

				case MSG_SOLUTION_TRANSMIT: //prijmeme reseni od jineho procesu
					checkSolution();
					break;

         			case MSG_END_WORK : //konec vypoctu - proces 0 pomoci tokenu zjistil, ze j*z nikdo nema praci
					std::cout << "Process #" << myRank << " recieved MSG_END_WORK from " << status.MPI_SOURCE << std::endl;
					checkWorkEnd();
					return 2;
                           	break;

				default :
					throw new Exception("ERROR: Unknown message.");
      		}
    		}
	}
	return 0;
}
bool KAbstractObjParserPrivate::parseFaceIndices()
{
  // If there is no starting integer, there is no index
  if (!parseIndex(m_index_array[0]))
  {
    return false;
  }

  // Check for subequent indices (texture)
  if (checkToken(PT_SEPARATOR))
  {
    if (!parseIndex(m_index_array[1]))
    {
      m_index_array[1] = 0;
    }
  }
  else
  {
    m_index_array[1] = 0;
  }

  // Check for subequent indices (normal)
  if (checkToken(PT_SEPARATOR))
  {
    if (!parseIndex(m_index_array[2]))
    {
       m_index_array[2] = 0;
    }
  }
  else
  {
    m_index_array[2] = 0;
  }

  return true;
}
Example #11
0
int main(int argc, const char *argv[]) {
    pinMode(LED_R, OUTPUT); 	// Set PWM LED as PWM output
    pinMode(LED_G, OUTPUT);     // Set regular LED as output
    pinMode(LED_B, OUTPUT);

    pinMode(DOOR, OUTPUT);		//tür öffner

    // nfc initiiere
    nfc_init(&context);
    if (context == NULL) {
        printf("ERROR: fehler beim dev init\n");
        exit(EXIT_FAILURE);
    }

    while (true) {
        doorCode = 0;
        // öffnet verbindung zum token
        pnd = nfc_open(context, NULL);

        led(1,1,0); //Gelb an

        if (pnd == NULL) {
            printf("ERROR: fehler beim öffnen.\n");
            exit(EXIT_FAILURE);
        }

        if (nfc_initiator_init(pnd) < 0) {
            nfc_perror(pnd, "nfc_initiator_init");
            exit(EXIT_FAILURE);
        }

        const nfc_modulation nmMifare = {
            .nmt = NMT_ISO14443A,
            .nbr = NBR_106,
        };
        if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
            toTokenKey(nt.nti.nai.abtUid);
            printf("%s\n",tokenKey);
            checkToken();
        }

        // TODO checken ob offen ist oder nicht um dann blau oder black zu zeigen

        nfc_close(pnd);
    }
    nfc_exit(context);
    exit(EXIT_SUCCESS);
}
Example #12
0
KaqazDropBox::KaqazDropBox(QObject *parent) :
    QObject(parent)
{
    p = new KaqazDropBoxPrivate;
    p->dbox = 0;
    p->loop = 0;
    p->smartio = 0;
    p->refresh_timer = 0;
    p->connected = false;
    p->rsvn_fetched = false;
    p->reupdate_flag = false;
    p->token = false;
    p->fileSyncing = true;
    p->password_setted = false;

    p->settings = new QSettings(CONFIG_PATH,QSettings::IniFormat);
    checkToken();
}
Example #13
0
int main(int argc, char** argv)
{
    //checking
    //int argc = 5;
    //char* argv[] = {"logread", "-K", "secret", "-R", "/root/Desktop/.hidden/bibifi/log1"};
    //char* argv[] = {"logread", "-B", "/root/Documents/NetBeansProjects/bibifi-final/dist/Debug/GNU-Linux-x86/hello"};
    if (argc < 5)
        normalExit(); // parameter number if too low



    //normal mode
    int sflag = 0, rflag = 0, tflag = 0, iflag = 0;
    char* token = NULL, * employeename = NULL, *guestname = NULL, *logfilename = NULL;

    int switchflag = -1;
    //reading options
    while ((switchflag = getopt(argc, argv, "K:SRTIE:G:")) != -1)
    {
        switch (switchflag)
        {
            case 'K':
                if (!checkToken(optarg)) normalExit();
                token = optarg;
                break;
            case 'S':
                sflag = true;
                break;
            case 'R':
                rflag = true;
                break;
            case 'T':
                tflag = true;
                break;
            case 'I':
                iflag = true;
                break;
            case 'E':
                if (!checkName(optarg)) normalExit();
                employeename = optarg;
                break;
            case 'G':
                if (!checkName(optarg)) normalExit();
                guestname = optarg;
                break;
            default:
                normalExit();
        }
    }
    if (argc - optind != 1)
        normalExit();
    else
    {
        if (!checkLogName(argv[optind])) normalExit();
        logfilename = argv[optind];
    }

    //here to check program syntax sanity
    int count_true = 0;
    if (sflag) count_true++;
    if (iflag) count_true++;
    if (rflag) count_true++;
    if (tflag) count_true++;

    if (token == NULL) normalExit();
    if (count_true != 1) normalExit();
    if (employeename != NULL && guestname != NULL && rflag) normalExit();
    if (employeename == NULL && guestname == NULL && rflag) normalExit();
    if (sflag && (employeename != NULL || guestname != NULL)) normalExit();
    if (tflag || iflag)
    {
        printf("unimplemented");
        exit(0);
    }
    //checking if file exists
    //getting the resolved path
    execution_argv[0] = logfilename;
    if (executeCommand("file_exists.sh", 1, execution_argv) == 0) // file found
    {
        //decrypt file
        execution_argv[0] = logfilename;
        execution_argv[1] = token;
        if (executeCommand("decrypt.sh", 2, execution_argv) != 0)
            securityExit();

        //reading from the file time, type, where, name
        FILE* input = fopen(logfilename, "r");
        if (input == NULL) normalExitWithEncryption(logfilename, token);
        int log_count = fill_log_array(input);
        fclose(input);


        if (sflag)
        {
            char ** emplist = (char **) malloc(sizeof (char*) * 1000);
            char ** guestlist = (char **) malloc(sizeof (char*) * 1000);
            int i, emp_count = 0, guest_count = 0;
            for (i = 0; i < 1000; i++)
            {
                emplist[i] = (char*) malloc(sizeof (char) * 100);
                guestlist[i] = (char*) malloc(sizeof (char) * 100);
            }
            emp_count = get_employee_names_list(emplist, log_count);
            guest_count = get_guest_names_list(guestlist, log_count);

            if (emp_count == 0)
                printf("\n");
            else
            {
                for (i = 0; i < emp_count; i++)
                {
                    if (i == emp_count - 1)
                        printf("%s\n", emplist[i]);
                    else
                        printf("%s,", emplist[i]);
                }
            }

            if (guest_count == 0)
                printf("\n");
            else
            {
                for (i = 0; i < guest_count; i++)
                {
                    if (i == guest_count - 1)
                        printf("%s\n", guestlist[i]);
                    else
                        printf("%s,", guestlist[i]);
                }
            }
            int* room_ids = (int*) malloc(sizeof (int) * 100);
            int room_count = get_room_list(room_ids, log_count);
            int j;
            for (i = 0; i < room_count; i++)
            {
                int who_count = who_is_in_room(guestlist, room_ids[i], log_count);
                if (who_count != 0)
                    printf("%d: ", room_ids[i]);

                for (j = 0; j < who_count; j++)
                {
                    if (j == who_count - 1) printf("%s\n", guestlist[j]);
                    else printf("%s,", guestlist[j]);
                }
            }
        }

        if (rflag)
        {
            char *some_name;
            int some_type;
            some_type = EMPLOYEETYPE, some_name = employeename;
            if (employeename == NULL)
                some_type = GUESTTYPE, some_name = guestname;

            int* room_ids = (int*) malloc(sizeof (int) * 100);
            int room_count = get_r_request(room_ids, some_name, some_type, log_count);
            int index;
            for (index = 0; index < room_count; index++)
            {
                if (index == room_count - 1)
                    printf("%d", room_ids[index]);
                else
                    printf("%d,", room_ids[index]);
            }
            printf("\n");
        }


        //encrypt file
        execution_argv[0] = logfilename;
        execution_argv[1] = token;
        if (executeCommand("encrypt.sh", 2, execution_argv) != 0)
            normalExitWithEncryption(logfilename, token);

    } else
        normalExit();

    return (EXIT_SUCCESS);
}
Example #14
0
bool File::ReadDataBlock(std::string block, DataBlock* datablock)
{
    blockSize = block.size();
    int currentPos = 0;
    bool optionalToken = 0;
    int elementIndex = 0;
    int propertyIndex = 0;
    for(int i = 0; i <= 4; i++)//Why this is in a for loop I will never know
    {
        if(i == 0)
        {
            datablock->elements.push_back(new DataElement());
            //element token
            int extractPos1 = block.find_first_of('{', currentPos)-currentPos;
            int extractPos2 = block.find_first_of('"', currentPos)-currentPos;
            checkExtractPos(&extractPos1);
            checkExtractPos(&extractPos2);
            if(extractPos1<extractPos2)
            {
                std::string elementToken = block.substr(currentPos, extractPos1);
                if(!checkToken(elementToken))
                {
                    Logger()<<"Element contains incorrect syntax: \n"<<elementToken<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->elementName = elementToken;
                currentPos += extractPos1+1;
                optionalToken = false;
            }
            else if(extractPos2<extractPos1)
            {
                std::string elementToken = block.substr(currentPos, extractPos2);
                if(!checkToken(elementToken))
                {
                    Logger()<<"Element contains incorrect syntax: \n"<<elementToken<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->elementName = elementToken;
                currentPos += extractPos2+1;
                optionalToken = true;
            }
            else
            {
                Logger()<<"Element doesn't contain properties OR no terminating comment: \n"
                        <<datablock->elements[elementIndex]->elementName<<" '"
                        <<datablock->elements[elementIndex]->elementIdentifier<<"'\n"<<std::endl; //error
                return false;
            }
        }
        if(i == 1)
        {
            //check for optional
            if(optionalToken)
            {
                int extractPos1 = block.find_first_of('"', currentPos)-currentPos;
                //int extractPos2 = block.find_first_of('{', currentPos)-currentPos;
                //first do the "
                std::string optionalTokenStr = block.substr(currentPos, extractPos1);
                if(!checkToken(optionalTokenStr))
                {
                    Logger()<<"Optional Identifier contains incorrect syntax: \n"
                            <<datablock->elements[elementIndex]->elementName<<" "<<optionalTokenStr<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->elementIdentifier = optionalTokenStr;
                currentPos += extractPos1+1;
                //then check if { is next, if not we have an issue
                if(block[currentPos] == '{')
                    currentPos++;
                else
                {
                    Logger()<<"Element doesn't contain properties (are you missing an '{' ?): \n"
                            <<datablock->elements[elementIndex]->elementName<<" '"
                            <<datablock->elements[elementIndex]->elementIdentifier<<"'\n"<<std::endl;
                    return false;
                }
            }
        }
        if(i == 2)
        {
            //break the properties section
            //int first = currentPos;
            int last = block.find_first_of('}', currentPos);
            while(currentPos < last)//loop through all the properties
            {
                //create a new property
                datablock->elements[elementIndex]->properties.push_back(new DataProperty());
                int extractPos1 = block.find_first_of(':', currentPos)-currentPos;
                //do the propertyToken:
                std::string propertyToken = block.substr(currentPos, extractPos1);
                if(!checkToken(propertyToken))
                {
                    Logger()<<"Property contains incorrect syntax: \n"
                            <<datablock->elements[elementIndex]->elementName<<" '"
                            <<datablock->elements[elementIndex]->elementIdentifier<<"': \n"<<propertyToken<<"\n"<<std::endl; //syntax error
                    return false;
                }
                datablock->elements[elementIndex]->properties[propertyIndex]->propertyName = propertyToken;
                currentPos += extractPos1+1;
                //do the valueToken
                int innerLast = block.find_first_of(';', currentPos);
                while(currentPos < innerLast) //loop through all the values for a specific property
                {
                    //create a new value for a property
                    extractPos1 = block.find_first_of(',', currentPos)-currentPos;
                    int extractPos2 = block.find_first_of(';', currentPos)-currentPos;
                    checkExtractPos(&extractPos1);
                    if(extractPos1<extractPos2)
                    {
                        std::string valueToken = block.substr(currentPos, extractPos1);
                        if(!checkToken(valueToken))
                        {
                            Logger()<<"Value contains incorrect syntax: \n"
                                    <<datablock->elements[elementIndex]->elementName<<" '"
                                    <<datablock->elements[elementIndex]->elementIdentifier<<"': \n"
                                    <<datablock->elements[elementIndex]->properties[propertyIndex]->propertyName<<": "<<valueToken<<"\n"<<std::endl; //syntax error;
                            return false;
                        }
                        datablock->elements[elementIndex]->properties[propertyIndex]->values.push_back(valueToken);
                        currentPos += extractPos1+1;
                    }
                    else if(extractPos2<extractPos1)
                    {
                        std::string valueToken = block.substr(currentPos, extractPos2);
                        if(!checkToken(valueToken))
                        {
                            Logger()<<"Value contains incorrect syntax: \n"
                                    <<datablock->elements[elementIndex]->elementName<<" '"
                                    <<datablock->elements[elementIndex]->elementIdentifier<<"': \n"
                                    <<datablock->elements[elementIndex]->properties[propertyIndex]->propertyName<<": "<<valueToken<<"\n"<<std::endl; //syntax error;
                            return false;
                        }
                        datablock->elements[elementIndex]->properties[propertyIndex]->values.push_back(valueToken);
                        currentPos += extractPos2+1;
                    }
                    else
                        return false;
                }
                propertyIndex++;
            }
            currentPos+=1;
            elementIndex++;
        }
        if(i == 3)
        {
            if(currentPos >= (int) block.size())
                continue;
            else
            {
                propertyIndex = 0;
                i = -1;
            }
        }
    }
    return true;
}
Example #15
0
Obj_ptr Quasiquote(const ParseTree_ptr &root, env_ptr & env)
{
	if (root == nullptr)
		return nullptr;
	std::string token = root->getToken();
	bool numberFlag = true, rationalFlag = false, realFlag = false, idenFlag = true;

	checkToken(token, numberFlag, rationalFlag, realFlag, idenFlag);

	if ( numberFlag==true )		// numerical constant
	{
		//----integer-----
		if (!rationalFlag && !realFlag)
			return Obj_ptr( new IntegerObj( bigInteger(token) ) );
		//----rational----
		else if (rationalFlag)
			return Obj_ptr( new RationalObj( bigRational(token) ) );
		//----real--------
		else
			return Obj_ptr( new RealObj( bigReal(token) ) );
	}
	else if (token[0]=='\"')	// string constant
		return Obj_ptr( new StringObj(token.substr(1, token.size()-2)) );
	else if (token[0]=='#')
	{
		// character constant
		if (token[1]=='\\')
		{
			if (token=="#\\newline")
				return Obj_ptr( new CharObj('\n') );
			else if (token=="#\\space")
				return Obj_ptr( new CharObj(' ') );
			else if (token=="#\\tab")
				return Obj_ptr( new CharObj('\t') );
			else
				return Obj_ptr( new CharObj(token[2]) );
		}
		// boolean constant
		else
		{
			if (token[1]=='t')
				return Obj_ptr( new BoolObj(true) );
			else
				return Obj_ptr( new BoolObj(false) );
		}
	}
	else if (token=="\'")
		return Quote(root->getSon());
	else if (token=="`")
		return Quasiquote(root->getSon(), env);
	else if (token=="()")
		return quasiquoteMakeList(root->getSon(), env);
	else if (token==",")
		return evaluate(root->getSon(), env);
	else if (token==",@")
	{
		Obj_ptr obj(evaluate(root->getSon(), env));
		if (!isList(obj))
			throw syntaxError("there must be a list after \',@\'");	//W.T.F.
		throw syntaxError("sorry for no support of \',@\' now");
	}
	else
		return Obj_ptr( new SymbolObj( token ) );
}
//*****
void DtmfDataLinkLayer::encode(  boost::circular_buffer< Packet > *downIn,
		boost::circular_buffer< Frame > *downOut,
		boost::circular_buffer< Frame > *upIn,
		boost::circular_buffer< unsigned int > *upOut)
{
#ifdef DEBUG
	DEBUG_OUT << std::endl << "---------- ### ENCODE ### ----------" << std::endl;
#endif

	//update pointers
	datagramDown = downIn;
	frameDown = downOut;
	frameUp = upIn;
	datagramUp = upOut;



	//do I have token?
	if(hasToken == 1)
	{
		//is the token expired?
		if(checkToken() == 1)
			return;
	}
	else
	{
#ifdef DEBUG
		DEBUG_OUT << "has no token" << std::endl;
#endif
		return;
	}

	//check if ready to process
	if(awaitsReply == 1)
	{
		//check current time
		time_t nowClock;
		time ( &nowClock );

		//compare with saved timestamp from when transmission ended
		if((nowClock-timestampAwaitsReply)>MAX_TIME_TO_REPLY)
		{
			//if time expired
#ifdef DEBUG
			DEBUG_OUT << "Time for receiver to reply is up" << std::endl;
#endif
			//resend all
			resendData(0);
		}
		else
		{
			//if there is time left to reply
#ifdef DEBUG
			std::cout << "Time left for receiver to reply: " <<
					(MAX_TIME_TO_REPLY-(nowClock-timestampAwaitsReply)) << " seconds" << std::endl;
#endif
		}
	}

	//start processing if there is data in the buffer
	if(!(datagramDown->empty()))
	{
		while(true)
		{
			//check if list is full
			if(nextInSendSequence >= 8)
			{
#ifdef DEBUG
				DEBUG_OUT << "List is full...ending transmission" << std::endl;
#endif
				endTransmission();
				break;
			}
			//check if end of datagram is reached
			if(datagramIterator >= datagramLength)
			{
				//previous datagram has ended and all data has been sent and confirmed
				if(dataInSendList == 0 && receiverNeedsUpdate == 0)
				{
					datagramDown->pop_front();
					datagramIterator = 0;
					receiverNeedsUpdate = 1;
					if(datagramDown->empty())
					{
#ifdef DEBUG
					DEBUG_OUT << "Last element popped" << std::endl;
#endif
					return;
					}
				}
				if(receiverNeedsUpdate == 1)
				{
					//get address of receiver
					currentReceiver = datagramDown->front().recvAddr();
					datagramLength = datagramDown->front().totalLength();
					receiverNeedsUpdate = 0;

#ifdef DEBUG
					DEBUG_OUT << "Setting receiver address to " << currentReceiver << std::endl;
#endif
				}
				else
				{
					//datagram has ended but sent data has not yet been confirmed
#ifdef DEBUG
					DEBUG_OUT << "Buffer is empty...ending transmission" << std::endl;
#endif
					//Set EOT bit in last frame
					endTransmission();
					break;
				}
			}
			else
			{
				//still data to process in this datagram
#ifdef DEBUG
				DEBUG_OUT << "Popping from datagrambuffer..." << (int)datagramDown->front()[datagramIterator] << std::endl;
#endif
				processDatagram((unsigned int)datagramDown->front()[datagramIterator]);
				datagramIterator++;
			}
		}
	}
	else
	{
		//buffer is empty
#ifdef DEBUG
		DEBUG_OUT << "Buffer is empty...nothing to process" << std::endl;
#endif

		if(hasToken == 1 && tokenAlreadyOffered == 0 && dataInSendList == 0)
		{
			// nothing to process. Might as well pass token
#ifdef DEBUG
			DEBUG_OUT << "No need for token...passing" << std::endl;
#endif
			offerToken();
		}
	}
}
Example #17
0
Obj_ptr evaluate(const ParseTree_ptr &root, env_ptr & env)
{
	if (root == nullptr)
		return nullptr;

	std::string token = root->getToken();
	Obj_ptr obj;
	bool numberFlag = true, rationalFlag = false, realFlag = false, idenFlag = true;

	checkToken(token, numberFlag, rationalFlag, realFlag, idenFlag);

	//----number-----
	if (numberFlag)
	{
		//----integer-----
		if (!rationalFlag && !realFlag)
			obj = Obj_ptr( new IntegerObj( bigInteger(token) ) );
		//----rational----
		else if (rationalFlag)
			obj = Obj_ptr( new RationalObj( bigRational(token) ) );
		//----real--------
		else
			obj = Obj_ptr( new RealObj( bigReal(token) ) );
		return descend(obj);
	}

	//----comma--------
	else if (token[0]==',')
		throw syntaxError("unexpected comma here");

	//----identifier----
	else if (idenFlag)
	{
		obj = findIden(env, token);
		if (obj.get() == nullptr)
		{
			if (builtInProcedure.find(token) == builtInProcedure.end())
				throw syntaxError("Undefined identifier: " + token);
			Arg_ptr nullArg(nullptr);
			ParseTree_ptr nullTree(nullptr);
			env_ptr nullEnv(nullptr);
			obj = Obj_ptr(new ProcedureObj(nullArg, nullTree, nullEnv, true, token));
		}
		return descend(obj);
	}

	//----char&bool-----
	else if (token[0]=='#')
	{
		//----char-----
		if (token[1]=='\\')
		{
			if (token=="#\\newline")
				obj = Obj_ptr( new CharObj('\n') );
			else if (token=="#\\space")
				obj = Obj_ptr( new CharObj(' ') );
			else if (token=="#\\tab")
				obj = Obj_ptr( new CharObj('\t') );
			else
				obj = Obj_ptr( new CharObj(token[2]) );

			return descend(obj);
		}
		//----bool-----
		else
		{
			
			if (token[1]=='t')
				obj = Obj_ptr( new BoolObj(true) );
			else
				obj = Obj_ptr( new BoolObj(false) );

			return descend(obj);
		}
	}

	//----string-------
	else if (token[0]=='\"')
	{
		obj = Obj_ptr( new StringObj(token.substr(1, token.size()-2)) );
		return descend(obj);
	}

	//----quote-------
	else if (token=="\'")
	{
		obj = Quote(root);
		return descend(obj);
	}

	else if (token=="`")
	{
		obj = Quasiquote(root, env);
		return descend(obj);
	}

	//----syntax&procedure----
	else if (token=="()")
	{
		ParseTree_ptr name = root->getSon();

		if (name == nullptr)
			throw syntaxError("missing expression");

		std::string iden = name->getToken();

		//--------syntax------------
		if (builtInSyntax.find(iden) != builtInSyntax.end())
		{
			return descend(evaluateSyntax(iden, name->getBrother(), env));
		}
		
		//--------procedure---------

		Obj_ptr obj = findIden(env, iden);

			//--------procedure object----
			if (iden == "()")
			{
				obj = evaluate(name, env);
				if (obj->Type != Procedure)
					throw syntaxError("not a procedure");
			}


		if (obj==nullptr)
		{
			if (builtInProcedure.find(iden) == builtInProcedure.end())
				throw syntaxError("Undefined identifier: " + iden);
		}
		else if (obj->Type != Procedure)
			throw syntaxError("\'" + iden + "\' is not a procedure");

		ParseTree_ptr para = name->getBrother();
		Para_ptr head=nullptr, tail=nullptr;

		while (para!=nullptr)
		{
			if (head==nullptr)
			{
				head = Para_ptr( new Parameters(evaluate(para, env)) );
				tail = head;
			}
			else
			{
				tail->next = Para_ptr( new Parameters(evaluate(para, env)) );
				tail = tail->next;
			}

			para = para->getBrother();
		}

		if (obj)	//define by user
		{
			return descend(evaluateUserDefined(obj, head, env));
		}
		else		// built-in
		{
			return descend(evaluateBuiltInProcedure(iden, head, env));
		}

	}

	//----else----------
	else
	{
		throw syntaxError("Illegal expression or the function you use is not available now.");
	}

}
Example #18
0
int scan(){
	memset(string_attr,'\0',strlen(string_attr));
	num_attr=-1;
	int trigger[6]={0}; //trigger of {string,number,sign,',/**/,{}}
	int wordsCount=0; //counter of words in token
	int resultToken=0;	//temp token
	int check=0;	//get "check~"function returns
	int isSep,isDef,isCom;	//get "is~"function returns
	if (lineCountTrigger==SET){	//when check some word, it feedback new line count
		lastLineNumber++;
		lineCountTrigger=RESET;
	}
	if(word==EOF){	//EOF
		return -1;
	}else if((isSep=isSeparater(word))!=0){ //line, tab or space
		word=fgetc(fp);
		return 0; //skip
	}else if(isprint(word)==0){	//leave out not printable words
		error("cannot print the word");
	}else if(islower(word)!=0||isupper(word)!=0){ //NAME
		resultToken=TNAME;
		string_attr[wordsCount++]=word;
		word=fgetc(fp);
		trigger[0]=SET;
	}else if(isdigit(word)!=0){ //Natural Number
		resultToken=TNUMBER;
		string_attr[wordsCount++]=word;
		num_attr=atoi(string_attr);
		word=fgetc(fp);
		trigger[1]=SET;
	}else if((resultToken=isSign(word))!=0){ //Sign
		string_attr[wordsCount++]=word;
		word=fgetc(fp);
		trigger[2]=SET;
	}else if((isDef=isDefString(word))!=0){ //'___' start
		resultToken=TSTRING;
		word=fgetc(fp); //next word is first count
		trigger[3]=SET;
	}else if((isCom=isComment(word))=='/'){ //comment out start /*___*/
		word=fgetc(fp); //next word is first count
		trigger[4]=SET;
	}else if((isCom=isComment(word))=='{'){ //comment out start {___}
		word=fgetc(fp); //next word is first count
		trigger[5]=SET;
	}else{ //except??
			fprintf(stderr,"Something Bug words or not define\n");
			return -2;
	}
	while(1){
		if(word==EOF){	//EOF
			if((check=checkToken(string_attr))<0){
				return resultToken;
			}
			return check;
		}else if(trigger[0]==SET){ //NAME or TOKEN
			if(wordsCount>MAXSTRSIZE-1){
				error("syntax err: too long string\n");
			}else if(islower(word)!=0||isupper(word)!=0||isdigit(word)!=0){
				string_attr[wordsCount++]=word;
				word=fgetc(fp);
			}else{
				if((check=checkToken(string_attr))<0){
					return resultToken;
				}
				return check;
			}
		}else if(trigger[1]==SET){ //NUMBER
			if(isdigit(word)!=0){
				string_attr[wordsCount++]=word;
				if((num_attr=atoi(string_attr))>32767){
					error("syntax err: number<=32767");
				}
				word=fgetc(fp);
			}else{
				return resultToken;
			}
		}else if(trigger[2]==SET){ //sign by two words
			if(isSign(word)!=0){
				string_attr[1]=word;
				check=checkWSign(string_attr);
				if(check<0){
					string_attr[1]='\0';
					return resultToken;
				}else{
					word=fgetc(fp);
					return check;
				}
			}else{
				return resultToken;
			}
		}else if(trigger[3]==SET){ //string '__'
			if(isprint(word)==0&&(isSep=isSeparater(word))==0){
				error("syntax err: about STRING start");
			}else if(isDefString(word)!=0){
				if((word=fgetc(fp))!='\''){
					return resultToken;
				}else{
					string_attr[wordsCount++]=word; //this is one before "\'"
				}
			}else if(isSep<0){
				error("not permission new line in STRING");
			}
			string_attr[wordsCount++]=word;
			word=fgetc(fp);
		}else if(trigger[4]==SET){ //comment out /**/
			if(wordsCount==0){
				if(word!='*'){
					error("syntax err: about comment out start");
				}
				word=fgetc(fp);
			}
			if(word=='*'){
				if((word=fgetc(fp))=='/'){
					word=fgetc(fp);
					return 0; //coment out end
				}
				string_attr[wordsCount++]='*';
			}
			if(isprint(word)!=0||isSeparater(word)!=0){
				string_attr[wordsCount++]=word;
				word=fgetc(fp);
			}else if(word==EOF){
				fprintf(stdout,"syntax err: comment out not END\n");
				return 0;
			}else{
				error("cannot print");
			}
		}else if(trigger[5] == SET){ //comment out {}
			if(word=='{'){
				error("comment out in comment");
			}else if(word=='}'){
				word=fgetc(fp);
				return 0; //coment out end
			}
			if(isprint(word)!=0||isSeparater(word)!=0){
				string_attr[wordsCount++]=word;
				word=fgetc(fp);
			}else if(word==EOF){
				fprintf(stdout,"syntax err: comment out not END\n");
				return 0;
			}else{
				error("cannot print");
			}
		}else{ //except??
			error("Something Bug words or not define");
			return -2;
		}
	}
	return -2;
}
Example #19
0
pskeleton md5meshfile_loadSkeleton (pmd5meshfile meshfile)
{
  FILE *fp = meshfile->fp;
  char token[25];
  char tmpLine[255];
  char *line = NULL;
  size_t length = 0;
  /* to the begining of the file */
  rewind (fp);
  pskeleton newSkeleton = getNewSkeleton (0);
  newSkeleton->name = md5basename (meshfile->filename);
  /*
   *  Parse joints 
   */
  do 
    {  
      if (line != NULL) 
	{
	  free (line);
	  line = NULL;
	  length = 0;
	}
      if (parseline (fp, &line, &length) == -1)
	{
	  fprintf (stderr, "Error parsing beginig of joints section.  Check file format.\n");
	  free (line);
	  line = NULL;
	  length = 0;
	  return NULL;
	}
    } while (sscanf (line, "joints %s", &token, &tmpLine) != 1);
  free (line);
  line = NULL;
  length = 0;

  /*  
   * Assuming the number of joints is correct parse accordingly 
   */
  int jointsParsed = 0;
  char  jN[50]; /*  Joint Name   */
  int   jP;     /*  Joint Parent */
  float px;     /*  Position X   */
  float py;     /*  Position Y   */
  float pz;     /*  Position Z   */
  float qx;     /*  Orientation X  */
  float qy;     /*  Orientation Y  */
  float qz;     /*  Orientation Z  */
  float qw;     /*  W component im told to calculate  */
  int ret;
  do
    {

      parseline (fp, &line, &length);
#ifdef DEBUG_FILE 
      printf ("Parsing line: %s\n", line);
#endif
      memset (jN, '\n', 50);
      ret = sscanf (line, "%s %d ( %f %f %f ) ( %f %f %f )",
		    &jN,  &jP, &px, &py, &pz, &qx, &qy, &qz);
      if (ret == 8)
	{
	  skeletonAddJoint (newSkeleton, jN, jP, px, py, pz, qz, qy, qz);	  
	}
      else if ( sscanf (line, "%s", &token) == 1)
	{
	  if (checkToken (token, "}", 1) == -1)
	    {
	      free (line);
	      line = NULL;
	      length = 0;
	      return NULL;
	    }
	  else
	    {
	      free (line);
	      line = NULL;
	      length = 0;
	      break;
	    }
	}
      else
	{
	  fprintf (stderr, "Error Parsing joint #%d\n sscanf ret: %d\n",jointsParsed, ret); 
	  free (line);
	  line = NULL;
	  length = 0;
	  return NULL;
	}
#ifdef DEBUG_FILE 
      printf ("DGB-MD5MESH_LOADFILE: line: %s", line);
      printf ("DGB-MD5MESH_LOADFILE: Joint: %s %d ( %.10f %.10f %.10f ) ( %.10f %.10f %.10f )\n",
	      jN, jP, px, py, pz, qx, qy, qz);
#endif	      
      free (line);
      line = NULL;
      length = 0;
    } while (1);
  return newSkeleton;
}
Example #20
0
pmesh md5meshfile_loadMesh (pmd5meshfile meshfile, int meshnumber)
{
  FILE * fp = meshfile->fp;
  char token[25];
  char tmpLine[2555];
  char *line = NULL;
  size_t length = 0;
  int cur_mesh = -1;
  /* To begining of file */
  rewind (fp);
  
  /*
   * Parse for mesh number
   */
  while (cur_mesh++ != meshnumber)
    {
      do
	{
	  if (line != NULL)
	    {
	      free (line);
	      line = NULL;
	      length = 0;
	    }
	  if (parseline (fp, &line, &length) == -1)
	    {
	      fprintf (stderr, "Error Finding mesh number %d\n", meshnumber);
	      free (line);
	      line = NULL;
	      length = 0;
	      return NULL;
	    }
	} while (sscanf (line, "mesh %s", &token, &tmpLine) != 1);
    }
  free (line);
  line = NULL;
  length = 0;
  /* We should have hit the correct mesh number */
  pmesh newmesh;
  int numverts = 0, numtris = 0, numweights = 0;
  int verti = 0, vertstartweight, vertcountweight;
  float verts = 0, vertt = 0;
  int trii = 0, triidx0 = 0, triidx1 = 0, triidx2 = 0;
  int weighti = 0, weightjoint = 0;
  float weightbias = 0, weightposx = 0, weightposy = 0, weightposz = 0;
  newmesh = (pmesh) malloc (sizeof (mesh));
  /* Parse for the associated shader */
  do {
    parseline (fp, &line, &length);
    if (sscanf (line, "shader %s", &tmpLine) == 1)
      {
	int shader_name_len = strlen(tmpLine);
	newmesh->shadername = (char *)malloc ( shader_name_len+1);
	strncpy (newmesh->shadername, tmpLine, shader_name_len);
	newmesh->shadername[shader_name_len] = '\0';
	
      }
    else if (sscanf (line, "numverts %d", &numverts) == 1)
      {
	newmesh->numverts = numverts;
	newmesh->verts = (ppvert) malloc (sizeof (pvert)*numverts);
      }
    else if (sscanf (line, "numtris %d", &numtris) == 1)
      {
	newmesh->numtris = numtris;
	newmesh->tris = (pptri) malloc (sizeof (ptri)*numtris);
      }
    else if (sscanf (line, "numweights %d", &numweights) == 1)
      {
	newmesh->numweights = numweights;
	newmesh->weights = (ppweight) malloc (sizeof (pweight)*numweights);
      }
    else if (sscanf (line, "vert %d ( %f %f ) %d %d",
		     &verti, &verts, &vertt, &vertstartweight, &vertcountweight) == 5)
      {
	if (verti < 0 || verti >= numverts)
	  return NULL;
	newmesh->verts[verti] = (pvert) malloc (sizeof (vert));
	newmesh->verts[verti]->s = verts;
	newmesh->verts[verti]->t = vertt;
	newmesh->verts[verti]->startweight = vertstartweight;
	newmesh->verts[verti]->countweight = vertcountweight;
      }
    else if (sscanf (line, "tri %d %d %d %d",
		     &trii, &triidx0, &triidx1, &triidx2) == 4 )
      {
	if (trii < 0 || trii >= numtris)
	  return NULL;
	newmesh->tris[trii] = (ptri) malloc (sizeof (tri));
	newmesh->tris[trii]->vert0 = triidx0;
	newmesh->tris[trii]->vert1 = triidx1;
	newmesh->tris[trii]->vert2 = triidx2;
      }
    else if (sscanf (line, "weight %d %d %f ( %f %f %f )",
		     &weighti, &weightjoint, &weightbias, 
		     &weightposx, &weightposy, &weightposz) == 6)
      {
	if (weighti < 0 || weighti >= numweights)
	  return NULL;

	newmesh->weights[weighti] = (pweight) malloc (sizeof (weight));
	newmesh->weights[weighti]->joint = weightjoint;
	newmesh->weights[weighti]->bias = weightbias;
	newmesh->weights[weighti]->posx = weightposx;
	newmesh->weights[weighti]->posy = weightposy;
	newmesh->weights[weighti]->posz = weightposz;
      }
    else if ( sscanf (line, "%s", &token) == 1)
      {
	if (checkToken (token, "}", 1) == -1)
	  {
	    free (line);
	    line = NULL;
	    length = 0;
	    return NULL;
	  }
	else 
	  {
	    free (line);
	    line = NULL;
	    length = 0;
	    break;
	  }
      }
    else 
      {
	fprintf (stderr, "Error Parsing mesh #%d\n sscanf ret: %s\n", cur_mesh-1, line);
	free (line);
	line = NULL;
	length = 0;
	return NULL;
      }
#ifdef DEBUG_FILE
    printf ("DGB-MD5MESH_LOADFILE: line: %s", line);
#endif
    free (line);
    line = NULL;
    length = 0;
  } while (1);
  return newmesh;
}
Example #21
0
/* This is for reference only Transitioning to functions above*/
void md5mesh_loadfile (char * fn, ppskeleton retSkeleton, ppmesh retMeshes )
{
  /*
   * Parse Mesh sections
   */
  int mdx;
  for (mdx = 0; mdx < numMeshes; mdx++)
    {
      /*
       * Parse Decleration Mesh token "mesh {"
       */
      parseline (fp, &line, &length);
      if (sscanf (line, "%s %s", &token, &tmpLine) == 2) 
	{
	  checkToken (token, "mesh", 4);
	  checkToken (tmpLine, "{", 1);
	}
      else
	{
	  fprintf (stderr, "Error parsing Opening mesh decleration.\n");
	  exit (EXIT_FAILURE);
	}
#ifdef DEBUG_FILE 
      printf ("DGB-MD5MESH_LOADFILE: line: %s", line);
#endif
      free (line);
      line = NULL;
      length = 0;
      /*
       *  Parse shader name
       */
      parseline (fp, &line, &length);
      if (sscanf (line, "%s %s", &token, &tmpLine) == 2) 
	{
	  checkToken (token, "shader", 6);
	}
      else
	{
	  fprintf (stderr, "Error parsing Opening mesh decleration.\n");
	  exit (EXIT_FAILURE);
	}
#ifdef DEBUG_FILE 
      printf ("DGB-MD5MESH_LOADFILE: line: %s", line);
#endif
      free (line);
      line = NULL;      
      length = 0;
      
      /*
       * Done Parsing Mesh decleration
       */
      parseline (fp, &line, &length);
      if (sscanf (line, "%s", &token) == 1) 
	{
	  checkToken (token, "}", 1);
	}
      else
	{
	  fprintf (stderr, "Error parsing Closing mesh decleration.\n");
	  exit (EXIT_FAILURE);
	}
#ifdef DEBUG_FILE 
      printf ("DGB-MD5MESH_LOADFILE: line: %s", line);
#endif
      free (line);
      line = NULL;
      length = 0;
            
    }

  newSkeleton->name = md5basename (fn);
}