Ejemplo n.º 1
0
KeyBar::KeyBar():
	Owner(nullptr),
	AltState(0),
	CtrlState(0),
	ShiftState(0),
	DisableMask(0),
	RegReaded(FALSE)
{
	_OT(SysLog(L"[%p] KeyBar::KeyBar()", this));
	ClearArray(KeyCounts);
	ClearArray(KeyTitles);
	ClearArray(KeyTitlesCustom);
}
Ejemplo n.º 2
0
void
init_telnet(void)
{
    env_init();

    SB_CLEAR();
    ClearArray(options);

    connected = ISend = localflow = donebinarytoggle = 0;
#ifdef	AUTHENTICATION
#ifdef	ENCRYPTION
    auth_encrypt_connect(connected);
#endif
#endif
    restartany = -1;

    SYNCHing = 0;

    /* Don't change NetTrace */

    escape = CONTROL(']');
    rlogin = _POSIX_VDISABLE;
#ifdef	KLUDGELINEMODE
    echoc = CONTROL('E');
#endif

    flushline = 1;
    telrcv_state = TS_DATA;
}
Ejemplo n.º 3
0
void
init_screen()
{
    bellwinup = 0;
    inHighlightMode = 0;
    ClearArray(Terminal);
}
Ejemplo n.º 4
0
void KeyBar::ClearKeyTitles(bool Custom,int Group)
{
	KeyBarTitleGroup *kb = Custom? KeyTitlesCustom : KeyTitles;

	size_t Begin=0, End=KBL_GROUP_COUNT-1;
	if (Group != -1)
		Begin=End=(size_t)Group;

	for (size_t I=Begin; I <= End; I++)
	{
		for (size_t J=0; J < (size_t)KEY_COUNT; ++J)
		{
			if (kb[I][J])
			{
				xf_free((void*)kb[I][J]);
				kb[I][J]=nullptr;
			}
		}
	}
	if (Group != -1)
		ClearArray(kb[Group]);
	else
		ClearArray(*kb);
}
Ejemplo n.º 5
0
/******************************************************************************
 * Function:        void USBStdSetCfgHandler(void)
 *
 * PreCondition:    None
 *
 * Input:           None
 *
 * Output:          None
 *
 * Side Effects:    None
 *
 * Overview:        This routine first disables all endpoints by clearing
 *                  UEP registers. It then configures (initializes) endpoints
 *                  specified in the modifiable section.
 *
 * Note:            None
 *****************************************************************************/
void USBStdSetCfgHandler(void)
{
    ctrl_trf_session_owner = MUID_USB9;
    mDisableEP1to15();                          // See usbdrv.h
    ClearArray((byte*)&usb_alt_intf,MAX_NUM_INT);
    usb_active_cfg = SetupPkt.bCfgValue;
    if(SetupPkt.bCfgValue == 0)
        usb_device_state = ADDRESS_STATE;
    else
    {
        usb_device_state = CONFIGURED_STATE;

        /* Modifiable Section */
        
        PyUSBInitEP();
        
        /* End modifiable section */

    }//end if(SetupPkt.bcfgValue == 0)
}//end USBStdSetCfgHandler
Ejemplo n.º 6
0
CProperty::~CProperty()
{
	ClearArray();
}
void Spooler::Init(UsbWrap *usb, ushort outSize, ushort inSize, uint howManyTimes, const char *prefix, bool isOverwrite, const char *policy)
{
    _usb = usb;
    _transmittedPacket = new uchar[outSize];
    _receivedPacket = new uchar[DEFAULT_IN_SIZE];
    _prefixFile = string(prefix);
    _isOverwrite = isOverwrite;

    if (strcmp(policy, "f") == 0)
    {
        _policy = SCHED_FIFO;
    }
    else if (strcmp(policy, "r") == 0)
    {
        _policy = SCHED_RR;
    }
    else
    {
        _policy = SCHED_OTHER;
    }

    ::printf("Sched policy [%s]\n",
             _policy == SCHED_OTHER ? "other" :
                                      _policy == SCHED_FIFO ? "fifo" : "rr");

    ClearArray(_transmittedPacket, outSize);

    //    przestawienie dlugosci stream
    _transmittedPacket[DEFAULT_OUT_SIZE - 1] = 'a';  // %alokacja, odpowiedniej dlugosci
    _transmittedPacket[0] = 0x05; // command 0x05
    /**
      * @todo Optymalizacja przez przesunięcia bitowe
      */
    _transmittedPacket[4] = DEFAULT_OUT_SIZE % UCHAR_RANGED; // .PacketSize low byte, skoryguj rozmiar
    _transmittedPacket[5] = (DEFAULT_OUT_SIZE - (DEFAULT_OUT_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;  // .PacketSize high byte, skoryguj rozmiar

    // %nastawy
    // wyzeruj starsze bajty
    _transmittedPacket[8] = outSize % UCHAR_RANGED; // .OUTsize low byte, skoryguj rozmiar
    _transmittedPacket[9] = (outSize -  outSize % UCHAR_RANGED) / UCHAR_RANGED; // .OUTsize high byte,

    // wyzeruj starsze bajty                                przywróć wartość na najmłodszy bajt
    _transmittedPacket[10] = inSize % UCHAR_RANGED; //.INPsize low byte, skoryguj rozmiar
    _transmittedPacket[11] =  (inSize -  inSize % UCHAR_RANGED) / UCHAR_RANGED; // .INPsize high byte

    DebugingPacket(_transmittedPacket, outSize);

    _usb->Send(_transmittedPacket, DEFAULT_OUT_SIZE);

    ClearArray(_receivedPacket, DEFAULT_IN_SIZE);

    _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);

    DebugingPacket(_receivedPacket, DEFAULT_IN_SIZE);

    ushort outSizeReceived = _receivedPacket[16] + (_receivedPacket[17] * UCHAR_RANGED);
    /**
      * @todo Rzucić wyjątkiem, gdyby rozmiar utawień się nie zgadzał
      */
    if (outSize != outSizeReceived)
    {
        cout << "outSizeReceived = " << outSizeReceived << endl;
        throw exception();
    }

    ushort inSizeReceived = _receivedPacket[18] + (_receivedPacket[19] * UCHAR_RANGED);
    /**
      * @todo Rzucić wyjątkiem, gdyby rozmiar utawień się nie zgadzał
      */
    if (inSize != inSizeReceived)
    {
        cout << "inSizeReceived = " << outSizeReceived << endl;
        throw exception();
    }

    // command 0x04
    ClearArray(_transmittedPacket, outSize);

    //    przestawienie dlugosci stream
    _transmittedPacket[DEFAULT_OUT_SIZE - 1] = 'a';  // %alokacja, odpowiedniej dlugosci
    _transmittedPacket[0] = 0x04; // command 0x04
    /**
      * @todo Optymalizacja przez przesunięcia bitowe
      */
    _transmittedPacket[4] = DEFAULT_OUT_SIZE % UCHAR_RANGED; // .PacketSize low byte, skoryguj rozmiar
    _transmittedPacket[5] = (DEFAULT_OUT_SIZE - (DEFAULT_OUT_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;  // .PacketSize high byte, skoryguj rozmiar

    DebugingPacket(_transmittedPacket, outSize);

    _usb->Send(_transmittedPacket, outSize);

    ClearArray(_receivedPacket, DEFAULT_IN_SIZE);

    _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);

    DebugingPacket(_receivedPacket, DEFAULT_IN_SIZE);

    ClearArray(_transmittedPacket, outSize);

    //           glowne wysylanie
    _transmittedPacket[outSize - 1]= 'a'; // %jako bajty, skoryguj rozmiar,uwaga nie zmniejsza sie
    _transmittedPacket[0] = 0x01;   // command 0x01 - ustaw długości pakietów dla stream streamIN, streamOUT. Ustawia parametry, ale ich nie przełącza. Karta dalej
    // pracuje w trybie COMMAND
    _transmittedPacket[4] = outSize % UCHAR_RANGED;  // PacketSize low byte, skoryguj rozmiar
    _transmittedPacket[5] = (outSize - (outSize % UCHAR_RANGED)) / UCHAR_RANGED;  // PacketSize high byte, skoryguj rozmiar

#ifdef DEBUG
    cout << "Exchange packets" << endl;
    DebugingPacket(_transmittedPacket, outSize);

    _usb->Send(_transmittedPacket, outSize);

    cout << "Receiving" << endl;
    _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);
    DebugingPacket(_receivedPacket, DEFAULT_IN_SIZE);
#endif

    delete [] _receivedPacket;

    _inSize = inSize;

    _inSize += sizeof (bool);
    _inSize += (sizeof (float) - sizeof (bool));
    _inSize += sizeof (float);

    int padding = _inSize % sizeof (float);

    if (padding != 0)
    {
        _inSize += padding;
    }

    //    inSize += (inSize % 2) == 0 ? 0 : 1;

    _receivedPacket = new uchar[_inSize];

    ClearArray(_receivedPacket, _inSize);

    if (_dt != NULL)
    {
        delete [] _dt;
        _dt = NULL;
    }

    _dt = new int[howManyTimes];
    _elapsedTime = new int[howManyTimes];
    _totals = new Total[howManyTimes];

    _outSize = outSize;
    _howManyTimes = howManyTimes;
    MULTI_RX_PACKET = 256;

#ifdef DEBUG
    cout << "Exchange packets 2" << endl;

    DebugingPacket(_transmittedPacket, outSize);

    _usb->Send(_transmittedPacket, outSize);

    cout << "Receiving 2" << endl;
    _usb->Receive((_receivedPacket + sizeof (bool) + sizeof (float)), DEFAULT_IN_SIZE);
    DebugingPacket((_receivedPacket + sizeof (bool) + sizeof (float)), DEFAULT_IN_SIZE);
#endif
}
void Spooler::Run()
{
    ushort numOfFillBytes = sizeof (float) - sizeof (bool);
    ushort shiftBuf = sizeof (bool) + numOfFillBytes + sizeof (float);
    ushort shiftUserTime = sizeof (bool) + numOfFillBytes;
    struct sched_param sp;
    ushort properInSize = _inSize - shiftBuf;
    Total total;
    int smRxPacketsFd;
    int smCounterRxPacketsFd;
    int smWaitForWritingFd;
    uchar *smRxPacketsAddr;
    uint *smCounterRxPacketsAddr;
    bool *smWaitForWritingAddr;
    const uint RxPacketsBufSize = _inSize * MULTI_RX_PACKET;

    smRxPacketsFd = shm_open(SM_RX_PACKETS_PATH, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    if (smRxPacketsFd < 0)
    {
        perror("Invoke shm_open() at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    if (ftruncate(smRxPacketsFd, RxPacketsBufSize) < 0)
    {
        perror("Invoke ftruncate() at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    smCounterRxPacketsFd = shm_open(SM_COUNTER_RX_PACKETS_PATH, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    if (smCounterRxPacketsFd < 0)
    {
        perror("Invoke shm_open() for counter at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    if (ftruncate(smCounterRxPacketsFd, sizeof (uint)) < 0)
    {
        perror("Invoke ftruncate() on smCounterRxPacketsFd at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    smWaitForWritingFd = shm_open(SM_CYCLE_TIME_RX_PACKET_PATH, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR);

    if (smWaitForWritingFd < 0)
    {
        perror("Invoke shm_open() for smWaitForWritingFd at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    if (ftruncate(smWaitForWritingFd, sizeof (bool)) < 0)
    {
        perror("Invoke ftruncate() on smWaitForWritingFd at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    smRxPacketsAddr = (uchar *)mmap(NULL, RxPacketsBufSize, PROT_READ | PROT_WRITE, MAP_SHARED, smRxPacketsFd, 0);

    if (smRxPacketsAddr == MAP_FAILED)
    {
        perror("Invoke mmap() at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    smCounterRxPacketsAddr = (uint *)mmap(NULL, sizeof (uint), PROT_READ | PROT_WRITE, MAP_SHARED, smCounterRxPacketsFd, 0);

    if (smCounterRxPacketsAddr == MAP_FAILED)
    {
        perror("Invoke mmap() at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    smWaitForWritingAddr = (bool *)mmap(NULL, sizeof (bool), PROT_READ | PROT_WRITE, MAP_SHARED, smWaitForWritingFd, 0);

    if (smWaitForWritingAddr == MAP_FAILED)
    {
        perror("Invoke mmap() at Spooler::Run() failed");

        exit(EXIT_FAILURE);
    }

    *smCounterRxPacketsAddr = 0;
    *smWaitForWritingAddr = true;

#ifdef DEBUGPRINT
    cout << "smWaitForWritingAddr start with" << *smWaitForWritingAddr << endl;
#endif

    uchar *currentPositionInRxPacketsBuf = smRxPacketsAddr;
    bool **ackPacket = (bool **)&currentPositionInRxPacketsBuf;
    float *userTime = (float *)currentPositionInRxPacketsBuf;

    for (ushort i = 0; i < MULTI_RX_PACKET; ++i) // główna pętla programu pomiarowego
    {
        currentPositionInRxPacketsBuf = (smRxPacketsAddr + (i * _inSize));

        **ackPacket = true; //(i % MULTI_RX_PACKET);
    }

    int fd = -1;

    if (_prefixFile[_prefixFile.length() - 1] != '/')
    {
        _prefixFile += '/';
    }

    ostringstream nameFile("./");
    nameFile << _prefixFile << "_" << _outSize << "_" << properInSize << "_x" << _howManyTimes << ".bin";

    if (_isOverwrite == false)
    {
        if (creat(nameFile.str().c_str(), S_IRWXU) < 0)
        {
            perror("Invoke creat() failed");

            exit(EXIT_FAILURE);
        }
    }

    fd = ::open(nameFile.str().c_str(), O_WRONLY); //  | O_SYNC | O_RSYNC | O_DSYNC

    if (fd < 0)
    {
        perror("Invoke open() failed");

        exit(EXIT_FAILURE);
    }

    FILE *file = ::fdopen(fd, "w");

    if (file == NULL)
    {
        perror("Invoke fdopen() failed");

        exit(EXIT_FAILURE);
    }

    switch(fork())
    {
    case -1:
    {
        perror("Invoke fork() failed");

        exit(EXIT_FAILURE);
    }
    case 0:  // child
    {
        ushort lastFrameNumber = 0;

        struct timespec waitForRxPacket = { 0, 10000 }; // napewno wiekszy niz 10 us na Friendlyarm

#ifdef DEBUGPRINT
        cout << "Child started" << endl;
#endif

        if (_policy != SCHED_OTHER)
        {
            if (setpriority(PRIO_PROCESS, 0, 0) < 0)
            {
                perror("Invoke setpriority() at child failed");
            }

            sp.__sched_priority = sched_get_priority_min(SCHED_OTHER);

            if (sched_setscheduler(getpid(), SCHED_OTHER, &sp) < 0)
            {
                perror("Invoke sched_setscheduler() at child failed");
            }
        }

        *smWaitForWritingAddr = false;
        uint i;

        for (i = 0; i < _howManyTimes; ++i)
        {
            while (!(i < (*(smCounterRxPacketsAddr))))
            {
#ifdef DEBUGPRINT
                cout << "Invoke nanosleep() in Rx packet =  " << properInSize << endl;
                cout << "Counter = " << (*(smCounterRxPacketsAddr)) << endl;
                cout << "Iteracja child read " << i << endl;
#endif

                if (nanosleep(&waitForRxPacket, NULL))
                {
                    perror("Invoke nanosleep() failed in child");
                }
            }

#ifdef DEBUGPRINT
            cout << "smWaitForWritingAddr in child =  " << *smWaitForWritingAddr << endl;
            cout << "Roznica = " << ((*(smCounterRxPacketsAddr)) - i) << endl;
#endif


#ifdef DEBUGPRINT
            cout << "Counter = " << (*(smCounterRxPacketsAddr)) << endl;
#endif

            //            currentIndex = (i % MULTI_RX_PACKET);
            currentPositionInRxPacketsBuf = (smRxPacketsAddr + (_inSize * (i % MULTI_RX_PACKET)));

            if (::write(fd, (const void *)currentPositionInRxPacketsBuf,
                        _inSize) < 0)
            {
                perror("Invoke write() to file failed in child");

                exit(EXIT_FAILURE);
            }

            //            ackPacket = (bool *)(currentPositionInRxPacketsBuf + sizeof (float));
            **ackPacket = true;
        }

        if (::close(fd) < 0)
        {
            perror("Closing binary write file descriptor failed in child");

            exit(EXIT_FAILURE);
        }

        fd = ::open(nameFile.str().c_str(), O_RDONLY); //

        if (fd < 0)
        {
            perror("Invoke oen() failed");

            exit(EXIT_FAILURE);
        }

        ostringstream nameFileMatlab("./");
        nameFileMatlab << _prefixFile << "data_" << _outSize << "_" << properInSize << "_x" << _howManyTimes << ".m";

        ofstream outFileMatlab(nameFileMatlab.str().c_str(), ios_base::binary | ios_base::out);

        if (!outFileMatlab.is_open())
        {
            cerr << "Couldn't open file to write matlab totals" << endl;

            exit(EXIT_FAILURE);
        }

        userTime = (float *)(smRxPacketsAddr + shiftUserTime);
        uchar *totalCard = (smRxPacketsAddr + shiftBuf);

        double sumDt = 0;
        double sumUserDt = 0;

        outFileMatlab << "dane.rozmiarWysylanegoPakietu = " << _outSize << ";" << endl;
        outFileMatlab << "dane.rozmiarOdbieranegoPakietu = " << properInSize << ";" << endl;
        outFileMatlab << "dane.wartosci = [" << endl;


        for (i = 0; i < 2; ++i) // read 2 initializing packets with error measurement
        {
#ifdef DEBUGPRINT
            cout << "Iteracja write " << i << endl;
#endif

            if (::read(fd, (void *)smRxPacketsAddr, _inSize) < 0)
            {
                perror("Invoke read() on binary file failed in child");

                exit(EXIT_FAILURE);
            }

            // TODO: Fault aligned
            total.userDt = *userTime;
            total.frameNumber = totalCard[0] + (totalCard[1] * UCHAR_RANGED); // %dFrameNum=DT
            total.dt = totalCard[4] + (totalCard[5] * UCHAR_RANGED); // %pktCnt

#ifdef DEBUGPRINT
            cout << total.frameNumber << ", " << total.userDt << ", " << total.dt << ";" << endl;
#endif

            lastFrameNumber = total.frameNumber;
            total.frameNumber = i;
            outFileMatlab << total.frameNumber << ", " << total.userDt << ", " << total.dt << ";" << endl;
            sumDt += total.dt;
            sumUserDt += total.userDt;
        }

        for ( ; i < _howManyTimes; ++i)
        {
#ifdef DEBUGPRINT
            cout << "Iteracja write " << i << endl;
#endif

            if (::read(fd, (void *)smRxPacketsAddr, _inSize) < 0)
            {
                perror("Invoke read() on binary file failed in child");

                exit(EXIT_FAILURE);
            }

            total.userDt = *userTime;

            total.frameNumber = totalCard[0] + (totalCard[1] * UCHAR_RANGED); // %dFrameNum=DT

            total.dt = totalCard[4] + (totalCard[5] * UCHAR_RANGED); // %pktCnt

#ifdef DEBUGPRINT
            cout << total.frameNumber << ", " << total.userDt << ", " << total.dt << ";" << endl;
#endif

            // %sprawdzenie ciaglosci numeracji pakietow
            if ((total.frameNumber - lastFrameNumber) != 1)
            {
                cout << "Iteration [" << i << "]" << endl;
                cout << "Current framenumber [" << total.frameNumber << "]" << endl;
                cout << "LastFrameNumber [" << lastFrameNumber << "]" << endl;
                throw UsbWrapException("Discontinuity in the reception of packets");
            }

            lastFrameNumber = total.frameNumber;

            total.frameNumber = i;

            outFileMatlab << total.frameNumber << ", " << total.userDt << ", " << total.dt << ";" << endl;

            sumDt += total.dt;
            sumUserDt += total.userDt;
        }

        outFileMatlab << "];" << endl;
        outFileMatlab << "dane.sumDT = " << sumDt << ";" << endl;
        outFileMatlab << "dane.sumUserDT = " << sumUserDt << ";" << endl;
        outFileMatlab << "dane.srednia = " << (sumDt / _howManyTimes) << ";" << endl;
        outFileMatlab << "dane.sredniaUser = "******";" << endl;
        outFileMatlab << "dane.ileRazy = " << _howManyTimes << ";" << endl;
        outFileMatlab << "dane.nazwa = '" << _outSize << "/" << properInSize << "/x" << _howManyTimes << "';" << endl;

        outFileMatlab.close();

        if (::close(fd) < 0)
        {
            perror("Closing binary write file descriptor failed in child");

            exit(EXIT_FAILURE);
        }

        if (_isOverwrite == true)
        {
            if (::remove(nameFile.str().c_str()) < 0)
            {
                perror("Removing binary file with totals failed in child");
            }
        }

#ifdef DEBUGPRINT
        cout << "Return child" << endl;
#endif
        if (::close(smRxPacketsFd) < 0)
        {
            perror("Invoke close() for SM_RX_PACKETS_PATH failed in child");
        }

        if (::close(smCounterRxPacketsFd) < 0)
        {
            perror("Invoke close() for SM_COUNTER_RX_PACKETS_PATH failed in child");
        }

        if (shm_unlink(SM_RX_PACKETS_PATH) < 0)
        {
            perror("Invoke shm_unlink() for SM_RX_PACKETS_PATH failed in child");
        }

        if (shm_unlink(SM_COUNTER_RX_PACKETS_PATH) < 0)
        {
            perror("Invoke shm_unlink() for SM_COUNTER_RX_PACKETS_PATH failed in child");
        }

        if (shm_unlink(SM_CYCLE_TIME_RX_PACKET_PATH) < 0)
        {
            perror("Invoke shm_unlink() for SM_CYCLE_TIME_RX_PACKET_PATH failed in child");
        }

        exit(EXIT_SUCCESS);
    }
    default: // parent
    {
#ifdef DEBUGPRINT
        cout << "Parent started" << endl;
#endif

        if (_policy != SCHED_OTHER)
        {
            if (setpriority(PRIO_PROCESS, 0, -20) < 0)
            {
                perror("Invoke setpriority() at parent failed");
            }

            sp.__sched_priority = sched_get_priority_max(_policy) - 1;

            if (sched_setscheduler(getpid(), _policy, &sp) < 0)
            {
                perror("Invoke sched_setscheduler() at parent failed");
            }
        }

        struct timespec waitForWriting = { 0, 10000 };

        timespec previousTime = { 0, 0 }, currentTime = { 0, 0 };

        while ((*smWaitForWritingAddr) == true)
        {
#ifdef DEBUGPRINT
            cout << "smWaitForWritingAddr in parentbefore loop = " << (*smWaitForWritingAddr) << endl;
#endif
            if (nanosleep(&waitForWriting, NULL) < 0)
            {
                perror("Invoke nanosleep() failed in parent");
            }
        }

        if (clock_gettime(CLOCK_REALTIME, &previousTime) < 0)
        {
            perror("Invoke start clock_gettime() failed");

            exit(EXIT_FAILURE);
        }

        for (ushort i = 0; i < _howManyTimes; ++i) // główna pętla programu pomiarowego
        {
#ifdef DEBUGPRINT
            cout << "Iteration in loop write:  " << i << endl;
#endif

            if (clock_gettime(CLOCK_REALTIME, &currentTime) < 0)
            {
                perror("Invoke stop clock_gettime() failed");

                exit(EXIT_FAILURE);
            }

            //            currentIndex = (i % MULTI_RX_PACKET);
            currentPositionInRxPacketsBuf = smRxPacketsAddr + ((i % MULTI_RX_PACKET) * _inSize);

#ifdef DEBUGPRINT
            cout << "After  currentPositionInRxPacketsBuf = smRxPacketsAddr + (currentIndex * _inSize);" << endl;
#endif

            //            while ((**ackPacket).ack != currentIndex)
            while (**ackPacket == false)
            {
#ifdef DEBUGPRINT
                cout << "(**ackPacket).ack == false in parent " << endl;
#endif
                if (nanosleep(&waitForWriting, NULL) < 0)
                {
                    perror("Invoke nanosleep() failed in parent");
                }
            }

            DebugingPacket(_transmittedPacket, _outSize);

            _usb->Send(_transmittedPacket, _outSize);

            _usb->Receive(currentPositionInRxPacketsBuf + shiftBuf, properInSize);

            **ackPacket = false;

            DebugingPacket((currentPositionInRxPacketsBuf + sizeof (bool) + sizeof (float)), properInSize);

            userTime = (float *)(currentPositionInRxPacketsBuf + shiftUserTime);

            *userTime = (float( currentTime.tv_sec - previousTime.tv_sec ) * 1000)
                    + (float( currentTime.tv_nsec - previousTime.tv_nsec ) / 1000000);

            ++(*smCounterRxPacketsAddr);

#ifdef DEBUGPRINT
            cout << "Counter in parent = " << (*(smCounterRxPacketsAddr)) << endl;
            cout << "Iteration in loop parent write:  " << i << endl;
#endif

            previousTime.tv_sec = currentTime.tv_sec;
            previousTime.tv_nsec = currentTime.tv_nsec;
        }

#ifdef DEBUGPRINT
        cout << "End for() loop in Parent" << endl;
#endif

        ClearArray(_transmittedPacket, _outSize);

        // %reset dlugosci - bo teraz znamy biezacy rozmiar stream
        _transmittedPacket[_outSize - 1] = 'a';
        _transmittedPacket[0] = 0x02;
        // %tutaj: wysylamy bufor dlugosci streamOUTsize !!!!
        _transmittedPacket[4] = _outSize % UCHAR_RANGED;
        _transmittedPacket[5] = (_outSize - (_outSize % UCHAR_RANGED)) /  UCHAR_RANGED;
        // nastawy
        _transmittedPacket[8] = DEFAULT_OUT_SIZE % UCHAR_RANGED;
        _transmittedPacket[9] = (DEFAULT_OUT_SIZE - (DEFAULT_OUT_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;

        _transmittedPacket[10] = DEFAULT_IN_SIZE % UCHAR_RANGED;
        _transmittedPacket[11] = (DEFAULT_IN_SIZE - (DEFAULT_IN_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;

        //DebugingPacket(_transmittedPacket, _outSize);

        _usb->Send(_transmittedPacket, _outSize);

        ClearArray(_receivedPacket, _inSize);

        _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);

        if (_receivedPacket != NULL)
        {
            delete [] _receivedPacket;
            _receivedPacket = NULL;
        }

        if (_transmittedPacket != NULL)
        {
            delete [] _transmittedPacket;
            _transmittedPacket = NULL;
        }

        wait(NULL);

        return;
    }
    }
}
Ejemplo n.º 9
0
TFileSystemInfo::TFileSystemInfo()
{
  ClearArray(IsCapable);
}
Ejemplo n.º 10
0
void CNrpLaborMarket::Reset()
{
	ClearArray( _users );
}
Ejemplo n.º 11
0
//- AN ----------------------------------------------
//  Компиляция строки BufPtr в байткод CurMacroBuffer
//- AN ----------------------------------------------
int __parseMacroString(DWORD *&CurMacroBuffer, int &CurMacroBufferSize, const wchar_t *BufPtr)
{
	_KEYMACRO(CleverSysLog Clev(L"parseMacroString"));
	//_KEYMACRO(SysLog(L"BufPtr[%p]='%s'", BufPtr,BufPtr));
	_macro_nErr = 0;
	_macro_nLine= 0;
	_macro_nPos = 0;
	pSrcString = emptyString;
	inloop = 0;
	/*pSrcString = */oSrcString = sSrcString = emptyString;

	if (!BufPtr || !*BufPtr)
	{
		keyMacroParseError(err_ZeroLengthMacro);
		return FALSE;
	}

	bool useUDL=true;
	const wchar_t *NewBufPtr;

	UserDefinedList MacroSrcList(ULF_NOTRIM|ULF_NOUNQUOTE, L"\r\n");
	if(!MacroSrcList.Set(BufPtr))
		useUDL=false; // все в одну строку
	//{
	//	_SVS(SysLog(L"MacroSrcList.GetTotal()=%d",MacroSrcList.GetTotal()));
	//	while((NewBufPtr=MacroSrcList.GetNext()) )
	//		_SVS(SysLog(L"[%s]",NewBufPtr));
	//	MacroSrcList.Reset();
	//}

	size_t SizeCurKeyText = (StrLength(BufPtr)*2)*sizeof(wchar_t);
	string strCurrKeyText;
	//- AN ----------------------------------------------
	//  Буфер под парсинг выражений
	//- AN ----------------------------------------------
	DWORD *dwExprBuff = (DWORD*)xf_malloc(SizeCurKeyText*sizeof(DWORD));

	if (!dwExprBuff)
		return FALSE;

	TExec exec;
	wchar_t varName[256];
	DWORD KeyCode, *CurMacro_Buffer = nullptr;

	if(useUDL)
		BufPtr=MacroSrcList.GetNext();

	pSrcString=BufPtr;

	for (;;)
	{
		int Size = 1;
		int SizeVarName = 0;
		const wchar_t *oldBufPtr = BufPtr;

		if (!(BufPtr = __GetNextWord(BufPtr, strCurrKeyText, _macro_nLine)))
		{
			if(!useUDL)
				break;
			NewBufPtr=MacroSrcList.GetNext();
			if(!NewBufPtr)
				break;
			_macro_nLine++;
			pSrcString=BufPtr=NewBufPtr;
			continue;
		}
		_SVS(SysLog(L"_macro_nLine   = [%d]",_macro_nLine));
		_SVS(SysLog(L"BufPtr         = [%s]",BufPtr));
		_SVS(SysLog(L"pSrcString     = [%s]",pSrcString));
		_SVS(SysLog(L"strCurrKeyText = [%s]",strCurrKeyText.CPtr()));

		//- AN ----------------------------------------------
		//  Проверка на строковый литерал
		//  Сделаем $Text опциональным
		//- AN ----------------------------------------------
		if (strCurrKeyText.At(0) == L'\"' && strCurrKeyText.At(1))
		{
			KeyCode = MCODE_OP_PLAINTEXT;
			BufPtr = oldBufPtr;
		}
		else if ((KeyCode = KeyNameMacroToKey(strCurrKeyText)) == (DWORD)-1 && (KeyCode = KeyNameToKey(strCurrKeyText)) == (DWORD)-1)
		{
			int ProcError=0;

			if (strCurrKeyText.At(0) == L'%' &&
			        (
			            (IsAlphaNum(strCurrKeyText.At(1)) || strCurrKeyText.At(1) == L'_') ||
			            (
			                strCurrKeyText.At(1) == L'%' &&
			                (IsAlphaNum(strCurrKeyText.At(2)) || strCurrKeyText.At(2)==L'_')
			            )
			        )
			   )
			{
				BufPtr = oldBufPtr;

				while (*BufPtr && (IsSpace(*BufPtr) || IsEol(*BufPtr)))
				{
					if (IsEol(*BufPtr))
					{
						_macro_nLine++;//TODO!!!
					}
					BufPtr++;
				}

				ClearArray(varName);
				KeyCode = MCODE_OP_SAVE;
				wchar_t* p = varName;
				const wchar_t* s = strCurrKeyText.CPtr()+1;

				if (*s == L'%')
					*p++ = *s++;

				wchar_t ch;
				*p++ = *s++;

				while ((iswalnum(ch = *s++) || (ch == L'_')))
					*p++ = ch;

				*p = 0;
				size_t Length = (StrLength(varName)+1)*sizeof(wchar_t);
				// строка должна быть выровнена на 4
				SizeVarName = static_cast<int>(Length/sizeof(DWORD));

				if (Length == sizeof(wchar_t) || (Length % sizeof(DWORD)) )    // дополнение до sizeof(DWORD) нулями.
					SizeVarName++;

				_SVS(SysLog(L"BufPtr=%s",BufPtr));
				BufPtr += Length/sizeof(wchar_t);
				_SVS(SysLog(L"BufPtr=%s",BufPtr));
				Size += parseExpr(BufPtr, dwExprBuff, L'=', L';');

				if (_macro_nErr)
				{
					ProcError++;
				}
			}
			else
			{
				// проверим вариант, когда вызвали функцию, но результат не присвоили,
				// например, вызвали MsgBox(), но результат неважен
				// тогда SizeVarName=1 и varName=""
				wchar_t *lpwszCurrKeyText = strCurrKeyText.GetBuffer();
				wchar_t *Brack=(wchar_t *)wcspbrk(lpwszCurrKeyText,L"( "), Chr=0;

				if (Brack)
				{
					Chr=*Brack;
					*Brack=0;
				}

				if (funcLook(lpwszCurrKeyText) != MCODE_F_NOFUNC)
				{
					if (Brack) *Brack=Chr;

					BufPtr = oldBufPtr;

					while (*BufPtr && (IsSpace(*BufPtr) || IsEol(*BufPtr)))
					{
						if (IsEol(*BufPtr))
						{
							_macro_nLine++;//TODO!!!
						}
						BufPtr++;
					}

					Size += parseExpr(BufPtr, dwExprBuff, 0, 0);

					/*
					// этого пока ненадо, считаем, что ';' идет сразу за функцией, иначе это отдельный символ ';', который нужно поместить в поток
					while ( *BufPtr && (IsSpace(*BufPtr) || IsEol(*BufPtr)) )
					{
						if (IsEol(*BufPtr))
						{
							_macro_nLine++;//TODO!!!
						}
						BufPtr++;
					}
					*/
					if (*BufPtr == L';')
						BufPtr++; // здесь Size не увеличиваем, т.к. мы прокидываем символ ';'

					//Size--; //???
					if (_macro_nErr)
					{
						ProcError++;
					}
					else
					{
						KeyCode=MCODE_OP_SAVE;
						SizeVarName=1;
						ClearArray(varName);
					}
				}
				else
				{
					if (Brack) *Brack=Chr;

					ProcError++;
				}

				strCurrKeyText.ReleaseBuffer();
			}

			if (ProcError)
			{
				if (!_macro_nErr)
					//keyMacroParseError(err_Unrecognized_keyword, strCurrKeyText, strCurrKeyText,strCurrKeyText);
					keyMacroParseError(err_Unrecognized_keyword, oldBufPtr, pSrcString, strCurrKeyText);

				if (CurMacro_Buffer )
				{
					xf_free(CurMacro_Buffer);
					CurMacroBuffer = nullptr;
				}

				CurMacroBufferSize = 0;
				xf_free(dwExprBuff);
				return FALSE;
			}
		}
		else if (!(strCurrKeyText.At(0) == L'$' && strCurrKeyText.At(1)))
		{
			Size=3;
			KeyCode=MCODE_OP_KEYS;
		}

		switch (KeyCode)
		{
			// $Text
			// -------------------------------------
			//            MCODE_OP_PLAINTEXT
			//            <expr>
			case MCODE_OP_PLAINTEXT:
			{
				Size += parseExpr(BufPtr, dwExprBuff, 0, 0);
				break;
			}
			// $If (expr) ... $End
			// -------------------------------------
			//            <expr>
			//            MCODE_OP_JZ                     p1=*+0
			//            addr1        ------------+
			//            ...                      |
			//            MCODE_OP_JMP             |
			// +--------- addr2                    |
			// |          ...          <-----------+
			// +--------> MCODE_OP_END
			// или
			//            <expr>
			//            MCODE_OP_JZ                     p1=*+0
			//            addr1        ------------+
			//            ...                      |
			//            MCODE_OP_END <-----------+
			case MCODE_OP_IF:
			{
				Size += parseExpr(BufPtr, dwExprBuff, L'(', L')');

				if (!exec.add(emmThen, CurMacroBufferSize+Size))
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				Size++;
				break;
			}
			case MCODE_OP_ELSE:
			{
				Size++;
				break;
			}
			// $Rep (expr) ... $End
			// -------------------------------------
			//            <expr>
			//            MCODE_OP_SAVEREPCOUNT       1
			// +--------> MCODE_OP_REP                    p1=*
			// |          <counter>                   3
			// |          <counter>                   4
			// |          MCODE_OP_JZ                 5   p2=*+2
			// |          addr1        ------------+
			// |          ...                      |
			// |          MCODE_OP_JMP             |
			// +--------- addr2                    |
			//            MCODE_OP_END <-----------+
			case MCODE_OP_REP:
			{
				inloop++;
				Size += parseExpr(BufPtr, dwExprBuff, L'(', L')');

				if (!exec.add(emmRep, CurMacroBufferSize+Size, CurMacroBufferSize+Size+4))   //??? 3
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				Size += 5;  // естественно, размер будет больше = 4
				break;
			}
			// $While (expr) ... $End
			// -------------------------------------
			// +--------> <expr>
			// |          MCODE_OP_JZ                    CurMacroBufferSize + Size - 2
			// |          addr1        ------------+     CurMacroBufferSize + Size - 1
			// |          ...                      |     ...
			// |          MCODE_OP_JMP             |     CurMacroBufferSize + Size - 3
			// +--------- addr2                    |     CurMacroBufferSize + Size - 2
			//            MCODE_OP_END <-----------+     CurMacroBufferSize + Size - 1
			//                                           CurMacroBufferSize + Size
			case MCODE_OP_WHILE:
			{
				inloop++;
				Size += parseExpr(BufPtr, dwExprBuff, L'(', L')');

				if (!exec.add(emmWhile, CurMacroBufferSize, CurMacroBufferSize+Size))
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				Size++;
				break;
			}
			// $continue
			// -------------------------------------
			// ^          MCODE_OP_CONTINUE
			// |          MCODE_OP_JMP
			// +--------- addr
			case MCODE_OP_CONTINUE:
			{
				Size++; // Место под адрес
				break;
			}
			// $break
			// -------------------------------------
			//            MCODE_OP_BREAK
			//            MCODE_OP_JMP
			//            addr -->
			case MCODE_OP_BREAK:
			{
				Size++; // Место под адрес
				break;
			}
			case MCODE_OP_END:
			{
				switch (exec().state)
				{
					case emmRep:
					case emmWhile:
						Size += 2; // Место под дополнительный JMP
						break;
					default:
						break;
				}

				break;
			}
		}

		if (_macro_nErr)
		{
			if (CurMacro_Buffer )
			{
				xf_free(CurMacro_Buffer);
				CurMacroBuffer = nullptr;
			}

			CurMacroBufferSize = 0;
			xf_free(dwExprBuff);
			return FALSE;
		}

		if (!BufPtr)   // ???
			break;

		// код найден, добавим этот код в буфер последовательности.
		CurMacro_Buffer = (DWORD *)xf_realloc(CurMacro_Buffer,sizeof(*CurMacro_Buffer)*(CurMacroBufferSize+Size+SizeVarName));

		if (!CurMacro_Buffer)
		{
			CurMacroBuffer = nullptr;
			CurMacroBufferSize = 0;
			xf_free(dwExprBuff);
			return FALSE;
		}

		switch (KeyCode)
		{
			case MCODE_OP_PLAINTEXT:
			{
				_SVS(SysLog(L"[%d] Size=%u",__LINE__,Size));
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
				break;
			}
			case MCODE_OP_SAVE:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
				memcpy(CurMacro_Buffer+CurMacroBufferSize+Size, varName, SizeVarName*sizeof(DWORD));
				break;
			}
			case MCODE_OP_IF:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = MCODE_OP_JZ;
				break;
			}
			case MCODE_OP_REP:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-6] = MCODE_OP_SAVEREPCOUNT;
				CurMacro_Buffer[CurMacroBufferSize+Size-5] = KeyCode;
				CurMacro_Buffer[CurMacroBufferSize+Size-4] = 0; // Initilize 0
				CurMacro_Buffer[CurMacroBufferSize+Size-3] = 0;
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = MCODE_OP_JZ;
				break;
			}
			case MCODE_OP_WHILE:
			{
				memcpy(CurMacro_Buffer+CurMacroBufferSize, dwExprBuff, Size*sizeof(DWORD));
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = MCODE_OP_JZ;
				break;
			}
			case MCODE_OP_ELSE:
			{
				if (exec().state == emmThen)
				{
					exec().state = emmElse;
					CurMacro_Buffer[exec().pos1] = CurMacroBufferSize+2;
					exec().pos1 = CurMacroBufferSize;
					CurMacro_Buffer[CurMacroBufferSize] = 0;
				}
				else // тут $else и не предвиделось :-/
				{
					keyMacroParseError(err_Not_expected_ELSE, BufPtr, pSrcString); // strCurrKeyText

					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				break;
			}
			case MCODE_OP_BREAK:
			case MCODE_OP_CONTINUE:
			{
				TExecItem *ei=nullptr;
				if (!inloop || (KeyCode==MCODE_OP_CONTINUE && exec.findnearloop(&ei) == -1))
				{
					keyMacroParseError(KeyCode==MCODE_OP_CONTINUE?err_Continue_Outside_The_Loop:err_Break_Outside_The_Loop, oldBufPtr, pSrcString);//BufPtr, pSrcString); // strCurrKeyText

					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}
				CurMacro_Buffer[CurMacroBufferSize+Size-2] = KeyCode==MCODE_OP_CONTINUE?MCODE_OP_JMP:MCODE_OP_BREAK;
				CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode==MCODE_OP_CONTINUE?ei->pos1:0;
				break;
			}
			case MCODE_OP_END:
			{
				switch (exec().state)
				{
					case emmMain:
						// тут $end и не предвиделось :-/
						keyMacroParseError(err_Not_expected_END, BufPtr, pSrcString); // strCurrKeyText

						if (CurMacro_Buffer )
						{
							xf_free(CurMacro_Buffer);
							CurMacroBuffer = nullptr;
						}

						CurMacroBufferSize = 0;
						xf_free(dwExprBuff);
						return FALSE;
					case emmThen:
						CurMacro_Buffer[exec().pos1-1] = MCODE_OP_JZ;
						CurMacro_Buffer[exec().pos1+0] = CurMacroBufferSize+Size-1;
						CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
						break;
					case emmElse:
						CurMacro_Buffer[exec().pos1-0] = MCODE_OP_JMP;
						CurMacro_Buffer[exec().pos1+1] = CurMacroBufferSize+Size-1;
						CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
						break;
					case emmRep:
					case emmWhile:
						inloop--;
						CurMacro_Buffer[exec().pos2] = CurMacroBufferSize+Size-1;
						CurMacro_Buffer[CurMacroBufferSize+Size-3] = MCODE_OP_JMP;
						CurMacro_Buffer[CurMacroBufferSize+Size-2] = exec().pos1;
						CurMacro_Buffer[CurMacroBufferSize+Size-1] = KeyCode;
						CorrectBreakCode(CurMacro_Buffer,CurMacro_Buffer+exec().pos1,CurMacro_Buffer+(CurMacroBufferSize+Size-1));
						break;
				}

				if (!exec.del())    // Вообще-то этого быть не должно,  но подстрахуемся
				{
					if (CurMacro_Buffer )
					{
						xf_free(CurMacro_Buffer);
						CurMacroBuffer = nullptr;
					}

					CurMacroBufferSize = 0;
					xf_free(dwExprBuff);
					return FALSE;
				}

				break;
			}
			case MCODE_OP_KEYS:
			{
				CurMacro_Buffer[CurMacroBufferSize+Size-3]=MCODE_OP_KEYS;
				CurMacro_Buffer[CurMacroBufferSize+Size-2]=KeyNameToKey(strCurrKeyText);
				CurMacro_Buffer[CurMacroBufferSize+Size-1]=MCODE_OP_ENDKEYS;
				break;
			}
			default:
				CurMacro_Buffer[CurMacroBufferSize]=KeyCode;
		} // end switch(KeyCode)

		CurMacroBufferSize += Size+SizeVarName;
	} // END for (;;)

	if (CurMacroBufferSize == 1)
	{
		CurMacro_Buffer = (DWORD *)xf_realloc(CurMacro_Buffer,sizeof(*CurMacro_Buffer)*(CurMacroBufferSize+1));

		if (!CurMacro_Buffer)
		{
			CurMacroBuffer = nullptr;
			CurMacroBufferSize = 0;
			xf_free(dwExprBuff);
			return FALSE;
		}

		CurMacro_Buffer[CurMacroBufferSize]=MCODE_OP_NOP;
		CurMacroBufferSize++;
	}

#ifdef _DEBUG
#ifdef SYSLOG_KEYMACRO
	SysLogDump(L"Macro Buffer",0,(LPBYTE)CurMacro_Buffer,CurMacroBufferSize*sizeof(DWORD),nullptr);
	SysLog(L"<ByteCode>{");

	if (CurMacro_Buffer)
	{
		int ii;

		for (ii = 0 ; ii < CurMacroBufferSize ; ii++)
			printKeyValue(CurMacro_Buffer, ii);
	}
	else
		SysLog(L"??? is nullptr");

	SysLog(L"}</ByteCode>");
#endif
#endif

	if (CurMacroBufferSize > 1)
		CurMacroBuffer = CurMacro_Buffer;
	else if (CurMacro_Buffer)
	{
		CurMacroBuffer = reinterpret_cast<DWORD*>((intptr_t)(*CurMacro_Buffer));
		xf_free(CurMacro_Buffer);
	}

	xf_free(dwExprBuff);

	if (exec().state != emmMain)
	{
		keyMacroParseError(err_Unexpected_EOS, strCurrKeyText, strCurrKeyText);
		return FALSE;
	}

	if (_macro_nErr)
	{
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 12
0
CSnakeArray::CSnakeArray()
{
	ClearArray();
}
void Spooler::Init(UsbWrap *usb, ushort outSize, ushort inSize, uint howManyTimes, const char *prefix, bool isOverwrite)
{
    _usb = usb;
    _transmittedPacket = new uchar[outSize];
    _receivedPacket = new uchar[DEFAULT_IN_SIZE];
    _prefixFile = string(prefix);
    
    ClearArray(_transmittedPacket, outSize);
    
    //    przestawienie dlugosci stream
    _transmittedPacket[DEFAULT_OUT_SIZE - 1] = 'a';  // %alokacja, odpowiedniej dlugosci
    _transmittedPacket[0] = 0x05; // command 0x05
    /**
      * @todo Optymalizacja przez przesunięcia bitowe
      */
    _transmittedPacket[4] = DEFAULT_OUT_SIZE % UCHAR_RANGED; // .PacketSize low byte, skoryguj rozmiar
    _transmittedPacket[5] = (DEFAULT_OUT_SIZE - (DEFAULT_OUT_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;  // .PacketSize high byte, skoryguj rozmiar
    
    // %nastawy
    // wyzeruj starsze bajty
    _transmittedPacket[8] = outSize % UCHAR_RANGED; // .OUTsize low byte, skoryguj rozmiar
    _transmittedPacket[9] = (outSize -  outSize % UCHAR_RANGED) / UCHAR_RANGED; // .OUTsize high byte,
    
    // wyzeruj starsze bajty                                przywróć wartość na najmłodszy bajt
    _transmittedPacket[10] = inSize % UCHAR_RANGED; //.INPsize low byte, skoryguj rozmiar
    _transmittedPacket[11] =  (inSize -  inSize % UCHAR_RANGED) / UCHAR_RANGED; // .INPsize high byte
    
    DebugingPacket(_transmittedPacket, outSize);
    
    _usb->Send(_transmittedPacket, DEFAULT_OUT_SIZE);
    
    ClearArray(_receivedPacket, DEFAULT_IN_SIZE);
    
    _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);
    
    DebugingPacket(_receivedPacket, DEFAULT_IN_SIZE);
    
    ushort outSizeReceived = _receivedPacket[16] + (_receivedPacket[17] * UCHAR_RANGED);
    /**
      * @todo Rzucić wyjątkiem, gdyby rozmiar utawień się nie zgadzał
      */
    if (outSize != outSizeReceived)
    {
        cout << "outSizeReceived = " << outSizeReceived << endl;
        throw exception();
    }
    
    ushort inSizeReceived = _receivedPacket[18] + (_receivedPacket[19] * UCHAR_RANGED);
    /**
      * @todo Rzucić wyjątkiem, gdyby rozmiar utawień się nie zgadzał
      */
    if (inSize != inSizeReceived)
    {
        cout << "inSizeReceived = " << outSizeReceived << endl;
        throw exception();
    }
    
    // command 0x04
    ClearArray(_transmittedPacket, outSize);
    
    //    przestawienie dlugosci stream
    _transmittedPacket[DEFAULT_OUT_SIZE - 1] = 'a';  // %alokacja, odpowiedniej dlugosci
    _transmittedPacket[0] = 0x04; // command 0x04
    /**
      * @todo Optymalizacja przez przesunięcia bitowe
      */
    _transmittedPacket[4] = DEFAULT_OUT_SIZE % UCHAR_RANGED; // .PacketSize low byte, skoryguj rozmiar
    _transmittedPacket[5] = (DEFAULT_OUT_SIZE - (DEFAULT_OUT_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;  // .PacketSize high byte, skoryguj rozmiar
    
    DebugingPacket(_transmittedPacket, outSize);
    
    _usb->Send(_transmittedPacket, outSize);
    
    ClearArray(_receivedPacket, DEFAULT_IN_SIZE);
    
    _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);
    
    DebugingPacket(_receivedPacket, DEFAULT_IN_SIZE);
    
    ClearArray(_transmittedPacket, outSize);
    
    //           glowne wysylanie
    _transmittedPacket[outSize - 1]= 'a'; // %jako bajty, skoryguj rozmiar,uwaga nie zmniejsza sie
    _transmittedPacket[0] = 0x01;   // command 0x01 - ustaw długości pakietów dla stream streamIN, streamOUT. Ustawia parametry, ale ich nie przełącza. Karta dalej
    // pracuje w trybie COMMAND
    _transmittedPacket[4] = outSize % UCHAR_RANGED;  // PacketSize low byte, skoryguj rozmiar
    _transmittedPacket[5] = (outSize - (outSize % UCHAR_RANGED)) / UCHAR_RANGED;  // PacketSize high byte, skoryguj rozmiar
    
    
    delete [] _receivedPacket;
    
    _receivedPacket = new uchar[inSize];
    
    ClearArray(_receivedPacket, inSize);
    
    if (_dt != NULL)
    {
        delete [] _dt;
        _dt = NULL;
    }
    
    _dt = new int[howManyTimes];
    _elapsedTime = new int[howManyTimes];
    _totals = new Total[howManyTimes];
    
    _inSize = inSize;
    _outSize = outSize;
    _howManyTimes = howManyTimes;
}
void Spooler::Run()
{
    //    timeval stopTimer;
    //    timeval startTimer;                             //   %start pomiaru czasu
    int pfd[2];
    ssize_t numRead;
    Total total;
    ushort totalStructSize = sizeof (Total);
    struct pollfd readPoll;


    
    if (pipe(pfd) == -1)
    {
        perror("Invoke pipe() failed");
    }
    
    switch(fork())
    {
    case -1:
    {
        perror("Invoke fork() failed");

        exit(EXIT_FAILURE);
    }
    case 0:  // child
    {
        ushort lastFrameNumber = 0;

        if (close(pfd[1]) == -1)
        {
            perror("Closing write file descriptor failed in child");
        }

        memset (&readPoll, 0, sizeof(readPoll)); // not necessary, but I am paranoid

        // first slot for readfd polled for input
        readPoll.fd = pfd[0];
        readPoll.events = POLLIN;
        readPoll.revents = 0;

        // do the poll(2) syscall with a 100 millisecond timeout
        int retPoll = poll(&readPoll, 1, 100);

        if (retPoll > 0) {
           if (readPoll.revents & POLLIN) {
              /* read from readfd,
                 since you can read from it without being blocked */
           }
        }
        else if (retPoll == 0) {
           /* the poll has timed out, nothing can be read or written */
        }
        else {
           /* the poll failed */
            perror("Invoke poll() failed");
        }

        ostringstream nameFile("./");
        nameFile << _prefixFile << "_" << _outSize << "_" << _inSize << "_x" << _howManyTimes << ".m";
        
        ofstream outFile(nameFile.str().c_str(), ios_base::binary | ios_base::out | ios_base::out);
        
        if (!outFile.is_open())
        {
            cerr << "Couldn't open file to write" << endl;
            
            exit(EXIT_FAILURE);
        }
        
        
        outFile << "dane.rozmiarWysylanegoPakietu = " << _outSize << ";" << endl;
        outFile << "dane.rozmiarOdbieranegoPakietu = " << _inSize << ";" << endl;
        outFile << "dane.wartosci = [" << endl;

        int i = 0;

        // Niewystarczy tylko raz?
        for (; i < 2; ++i)
        {
            numRead = read(pfd[0], &total, totalStructSize);

            if (numRead < 1)
            {
                if (numRead == -1)
                {
                    perror("Invoke read() failed in child");
                }

                if (numRead == 0)
                {
                    continue;
                }
            }

            lastFrameNumber = total.frameNumber;
#ifdef DEBUGPRINT
            cout << "Framenumber = " << total.frameNumber << endl;
#endif
            outFile << lastFrameNumber << ", " << total.dt << ";" << endl;
        }

        for (; i < _howManyTimes; ++i)
        {
            for (;;)
            {
                numRead = read(pfd[0], &total, totalStructSize);
                
                if (numRead < 1)
                {
                    if (numRead == -1)
                    {
                        perror("Invoke read() failed in child");
                    }
                    
                    if (numRead == 0)
                    {
                        continue;
                    }
                }
                
                break;
            }
#ifdef DEBUGPRINT
            cout << "Iteracja write " << i << endl;
            cout << "Framenumber = " << total.frameNumber << endl;
#endif

            // %sprawdzenie ciaglosci numeracji pakietow
            if ((total.frameNumber - lastFrameNumber) != 1)
            {
                throw UsbWrapException("Discontinuity in the reception of packets");
            }

            lastFrameNumber = total.frameNumber;
            
            outFile << i << ", " << total.dt << ";" << endl;
        }

        _sum = 0 ;

        for (ushort i = 0; i < _howManyTimes; i++)
        {
            _sum +=  _dt[i];
        }

        _mean =  _sum/_howManyTimes;
        
        outFile << "];" << endl;
        outFile << "dane.ileRazy = " << _howManyTimes << ";" << endl;
        outFile << "dane.sumDT = " << _sum << ";" << endl;
        outFile << "dane.sredniaDT = " << _mean << ";" << endl;
        outFile << "dane.nazwa = '" << _outSize << "_" << _inSize << "_x" << _howManyTimes << "';" << endl;
        
        outFile.close();
        
        if (close(pfd[0]) == -1)
        {
        	perror("Closing read file descriptor failed in child");
        }
        
#ifdef DEBUGPRINT
        cout << "Return child" << endl;
#endif

        exit(EXIT_SUCCESS);
    }
    default: // parent
    {
        
        if (close(pfd[0]) == -1)
        {
        	perror("Closing read file descriptor failed in parent");
        }
        
        timespec dtStart = { 0, 0 }, dtStop = { 0, 0 };
        
        for (ushort i = 0; i < _howManyTimes; ++i) // główna pętla programu pomiarowego
        {
#ifdef DEBUGPRINT
            cout << "Iteration in loop write:  " << i << endl;
#endif
            //DebugingPacket(_transmittedPacket, _outSize);
            
            //        if (gettimeofday(&startTimer, NULL))
            //        {
            //            perror("gettimeofday()");
            //        }
            
            clock_gettime(CLOCK_REALTIME, &dtStart);
            
            _usb->Send(_transmittedPacket, _outSize);
            
            //        %byc moze tutaj lepiej jest wstawic jakiekolwiek opoznienie, aby nie
            //                %za szybko wchodzic w fread
            //                %for(ii=1:5*330000)  %zachowuje sie addytywnie dla r=0
            //                %end
            
            ClearArray(_receivedPacket, _inSize);
            
            _usb->Receive(_receivedPacket, _inSize);
            
            clock_gettime(CLOCK_REALTIME, &dtStop);
            
            // DebugingPacket(_receivedPacket, _inSize);
            
            //        if (gettimeofday(&stopTimer, NULL))
            //        {
            //            perror("gettimeofday()");
            //        }
            
            //        _elapsedTime[i] = ((stopTimer.tv_sec - startTimer.tv_sec) * 1000) + ((stopTimer.tv_usec - startTimer.tv_usec) / 1000);
            
            total.frameNumber = _receivedPacket[0] + (_receivedPacket[1] * UCHAR_RANGED); // %dFrameNum=DT
            total.dt = _receivedPacket[4] + (_receivedPacket[5] * UCHAR_RANGED); // %pktCnt
            
            if (write(pfd[1], &total, totalStructSize) != totalStructSize)
            {
                perror("parent - partial/failed write");
                exit(EXIT_FAILURE);
            }
        }
        
        cout << "End for" << endl;
        
        ClearArray(_transmittedPacket, _outSize);
        
        // %reset dlugosci - bo teraz znamy biezacy rozmiar stream
        _transmittedPacket[_outSize - 1] = 'a';
        _transmittedPacket[0] = 0x02;
        // %tutaj: wysylamy bufor dlugosci streamOUTsize !!!!
        _transmittedPacket[4] = _outSize % UCHAR_RANGED;
        _transmittedPacket[5] = (_outSize - (_outSize % UCHAR_RANGED)) /  UCHAR_RANGED;
        // nastawy
        _transmittedPacket[8] = DEFAULT_OUT_SIZE % UCHAR_RANGED;
        _transmittedPacket[9] = (DEFAULT_OUT_SIZE - (DEFAULT_OUT_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;
        
        _transmittedPacket[10] = DEFAULT_IN_SIZE % UCHAR_RANGED;
        _transmittedPacket[11] = (DEFAULT_IN_SIZE - (DEFAULT_IN_SIZE % UCHAR_RANGED)) / UCHAR_RANGED;
        
        //DebugingPacket(_transmittedPacket, _outSize);
        
        _usb->Send(_transmittedPacket, _outSize);

        ClearArray(_receivedPacket, _inSize);
        
        _usb->Receive(_receivedPacket, DEFAULT_IN_SIZE);
        
        //DebugingPacket(_receivedPacket, _inSize);
        
        //    ushort currentOutSize = _receivedPacket[16] + (UCHAR_RANGED * _receivedPacket[17]);
        //    ushort currentInSize = _receivedPacket[18] + (UCHAR_RANGED * _receivedPacket[19]);
        
        if (_receivedPacket != NULL)
        {
            delete [] _receivedPacket;
            _receivedPacket = NULL;
        }
        
        if (_transmittedPacket != NULL)
        {
            delete [] _transmittedPacket;
            _transmittedPacket = NULL;
        }
        
        wait(NULL);

        if (close(pfd[1]) == -1)
        {
        	perror("Closing write file descriptor failed in parent");
        }
        
        return;
    }
    }
}
Ejemplo n.º 15
0
Archivo: c.c Proyecto: adammaj1/c
int main(){
  
  
 
  
 unsigned int p;
 
  /* unsigned int iX,iY;  indices of 2D virtual array (image) = integer coordinate */
  iXmax = iSide; /* height of image in pixels */
  iYmax = iSide;
  iLength = (iXmax*iYmax);
 
  PixelWidth =  ((ZxMax-ZxMin)/iXmax);
  PixelHeight = ((ZyMax-ZyMin)/iYmax);
 
 
  /* dynamic 1D arrays for colors ( shades of gray )  */
  
  unsigned char *data;
  data = malloc( iLength * sizeof(unsigned char) );
  
  if (data == NULL )
    {
      fprintf(stderr," Could not allocate memory");
      return 1;
    }
  

  
  
  
   
  Cx = -1.36809742955000002314; 
  Cy = 0.0; 

   
  NrOfCrOrbitPoints = pow(10,6);
 
  for (p=2;p<=2*period ;p++)
   { 
  //printf(" clear the arrays \n");       
  ClearArray( data );
  /* ------------------ draw ----------------------- */
  //printf(" Draw %llu points of critical orbit to array \n",NrOfCrOrbitPoints);       
  DrawLimitSet(NrOfCrOrbitPoints, data, p);
  
 
 
  /* ---------- file  -------------------------------------*/
  //printf(" save  data array to the pgm file \n");
  SaveArray2pgm(data, p);
  }
 
  /* --------------free memory ---------------------*/
  free(data);
 
 
 
 
 
 
  return 0;
}
Ejemplo n.º 16
0
		void ClearAllFlags() { ClearArray(FFlags); }