Exemplo n.º 1
0
/**
*
* roamingMngr_smHandover 
*
* \b Description: 
*
* This procedure is called when handover should be invoked.
*   Go over the candidate APs and start handover to each of them. 
 * If there's no candidate APs, disconnect.
 * Handover to the current AP is allowed only if the trigger is
 * low quality.
 * 
* \b ARGS:
*
*  I   - hRoamingMngr - roamingMngr SM context  \n
*
* \b RETURNS:
*
*  TI_OK if successful, TI_NOK otherwise.
*
* 
*/
static void roamingMngr_smHandover(TI_HANDLE hRoamingMngr)
{
    roamingMngr_t           *pRoamingMngr;
    bssEntry_t              *pApToConnect;
    apConn_connRequest_t    requestToApConn;

    pRoamingMngr = (roamingMngr_t*)hRoamingMngr;

    if ((pRoamingMngr->handoverWasPerformed) && (pRoamingMngr->candidateApIndex == CURRENT_AP_INDEX))
    {   /* Handover with the current AP already failed, Disconnect */
        roamingMngr_smEvent(ROAMING_EVENT_FAILURE, pRoamingMngr);
        return;
    }
    if (pRoamingMngr->listOfCandidateAps.numOfNeighborBSS > 0)
    {   /* Neighbor APs are the highest priority to Roam */
        pRoamingMngr->candidateApIndex = 
            pRoamingMngr->listOfCandidateAps.neighborBSSList[pRoamingMngr->listOfCandidateAps.numOfNeighborBSS-1];
        pRoamingMngr->listOfCandidateAps.numOfNeighborBSS--;
    }
    else if (pRoamingMngr->listOfCandidateAps.numOfPreAuthBSS > 0)
    {   /* Pre-Auth APs are the second priority to Roam */
        pRoamingMngr->candidateApIndex = 
            pRoamingMngr->listOfCandidateAps.preAuthBSSList[pRoamingMngr->listOfCandidateAps.numOfPreAuthBSS-1];
        pRoamingMngr->listOfCandidateAps.numOfPreAuthBSS--;
    }
    else if (pRoamingMngr->listOfCandidateAps.numOfRegularBSS > 0)
    {   /* Regular APs are APs that are not pre-authenticated and not Neighbor */
        pRoamingMngr->candidateApIndex = 
            pRoamingMngr->listOfCandidateAps.regularBSSList[pRoamingMngr->listOfCandidateAps.numOfRegularBSS-1];
        pRoamingMngr->listOfCandidateAps.numOfRegularBSS--;
    }
    else
    {   /* No Candidate APs */
        pRoamingMngr->candidateApIndex = INVALID_CANDIDATE_INDEX;
    }

    TRACE1(pRoamingMngr->hReport, REPORT_SEVERITY_INFORMATION, "roamingMngr_smHandover, candidateApIndex=%d \n", pRoamingMngr->candidateApIndex);


    if (pRoamingMngr->candidateApIndex == INVALID_CANDIDATE_INDEX)
    {   /* No cnadidate to Roam to, only the current AP is candidate */
        if (pRoamingMngr->roamingTrigger <= ROAMING_TRIGGER_LOW_QUALITY_GROUP)
        {   /* If the trigger to Roam is low quality, and there are no candidate APs
                to roam to, retain connected to the current AP */
            requestToApConn.requestType = (pRoamingMngr->handoverWasPerformed) ? AP_CONNECT_RECONNECT_CURR_AP : AP_CONNECT_RETAIN_CURR_AP;
            pRoamingMngr->candidateApIndex = CURRENT_AP_INDEX;
        }
        else
        {   /* Disconnect the BSS, there are no more APs to roam to */
            roamingMngr_smEvent(ROAMING_EVENT_FAILURE, pRoamingMngr);
            return;
        }
    }
    else
    {   /* There is a valid candidate AP */
        if (pRoamingMngr->roamingTrigger > ROAMING_TRIGGER_FAST_CONNECT_GROUP)
        {   /* Full re-connection should be perfromed */
            requestToApConn.requestType = AP_CONNECT_FULL_TO_AP; 
        }
        else
        {   /* Fast re-connection should be perfromed */
            requestToApConn.requestType = AP_CONNECT_FAST_TO_AP; 
        }
    }
#ifdef TI_DBG
    /* For debug */
    if (!pRoamingMngr->handoverWasPerformed)
    {   /* Take the time before the first handover started */
        pRoamingMngr->roamingHandoverStartedTimestamp = os_timeStampMs(pRoamingMngr->hOs);
    }
#endif
    
    if (pRoamingMngr->candidateApIndex == CURRENT_AP_INDEX)
    {   /* get the current AP */
        pApToConnect = apConn_getBSSParams(pRoamingMngr->hAPConnection);
    }
    else
    {   /* get the candidate AP */
        pRoamingMngr->handoverWasPerformed = TI_TRUE;
        pApToConnect = &pRoamingMngr->pListOfAPs->BSSList[pRoamingMngr->candidateApIndex];
    }
    TRACE3(pRoamingMngr->hReport, REPORT_SEVERITY_INFORMATION, "roamingMngr_smHandover, candidateApIndex=%d, requestType = %d, channel=%d \n", 							 pRoamingMngr->candidateApIndex, requestToApConn.requestType, pApToConnect->channel);

    requestToApConn.dataBufLength = 0;
    apConn_connectToAP(pRoamingMngr->hAPConnection, pApToConnect, &requestToApConn, TI_TRUE);
}
// for each ALSA device, call iterator. userData is passed to the iterator
// returns total number of iterations
static int iterateRawmidiDevices(snd_rawmidi_stream_t direction,
                                 DeviceIteratorPtr iterator,
                                 void* userData) {
    int count = 0;
    int subdeviceCount;
    int card, dev, subDev;
    char devname[16];
    int err;
    snd_ctl_t *handle;
    snd_rawmidi_t *rawmidi;
    snd_rawmidi_info_t *rawmidi_info;
    snd_ctl_card_info_t *card_info, *defcardinfo = NULL;
    UINT32 deviceID;
    int doContinue = TRUE;

    snd_rawmidi_info_malloc(&rawmidi_info);
    snd_ctl_card_info_malloc(&card_info);

    // 1st try "default" device
    if (direction == SND_RAWMIDI_STREAM_INPUT) {
        err = snd_rawmidi_open(&rawmidi, NULL, ALSA_DEFAULT_DEVICE_NAME,
                               SND_RAWMIDI_NONBLOCK);
    } else if (direction == SND_RAWMIDI_STREAM_OUTPUT) {
        err = snd_rawmidi_open(NULL, &rawmidi, ALSA_DEFAULT_DEVICE_NAME,
                               SND_RAWMIDI_NONBLOCK);
    } else {
        ERROR0("ERROR: iterateRawmidiDevices(): direction is neither"
               " SND_RAWMIDI_STREAM_INPUT nor SND_RAWMIDI_STREAM_OUTPUT\n");
        err = MIDI_INVALID_ARGUMENT;
    }
    if (err < 0) {
        ERROR1("ERROR: snd_rawmidi_open (\"default\"): %s\n",
               snd_strerror(err));
    } else {
        err = snd_rawmidi_info(rawmidi, rawmidi_info);

        snd_rawmidi_close(rawmidi);
        if (err < 0) {
            ERROR1("ERROR: snd_rawmidi_info (\"default\"): %s\n",
                    snd_strerror(err));
        } else {
            // try to get card info
            card = snd_rawmidi_info_get_card(rawmidi_info);
            if (card >= 0) {
                sprintf(devname, ALSA_HARDWARE_CARD, card);
                if (snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK) >= 0) {
                    if (snd_ctl_card_info(handle, card_info) >= 0) {
                        defcardinfo = card_info;
                    }
                    snd_ctl_close(handle);
                }
            }
            // call calback function for the device
            if (iterator != NULL) {
                doContinue = (*iterator)(ALSA_DEFAULT_DEVICE_ID, rawmidi_info,
                                         defcardinfo, userData);
            }
            count++;
        }
    }

    // iterate cards
    card = -1;
    TRACE0("testing for cards...\n");
    if (snd_card_next(&card) >= 0) {
        TRACE1("Found card %d\n", card);
        while (doContinue && (card >= 0)) {
            sprintf(devname, ALSA_HARDWARE_CARD, card);
            TRACE1("Opening control for alsa rawmidi device \"%s\"...\n", devname);
            err = snd_ctl_open(&handle, devname, SND_CTL_NONBLOCK);
            if (err < 0) {
                ERROR2("ERROR: snd_ctl_open, card=%d: %s\n", card, snd_strerror(err));
            } else {
                TRACE0("snd_ctl_open() SUCCESS\n");
                err = snd_ctl_card_info(handle, card_info);
                if (err < 0) {
                    ERROR2("ERROR: snd_ctl_card_info, card=%d: %s\n", card, snd_strerror(err));
                } else {
                    TRACE0("snd_ctl_card_info() SUCCESS\n");
                    dev = -1;
                    while (doContinue) {
                        if (snd_ctl_rawmidi_next_device(handle, &dev) < 0) {
                            ERROR0("snd_ctl_rawmidi_next_device\n");
                        }
                        TRACE0("snd_ctl_rawmidi_next_device() SUCCESS\n");
                        if (dev < 0) {
                            break;
                        }
                        snd_rawmidi_info_set_device(rawmidi_info, dev);
                        snd_rawmidi_info_set_subdevice(rawmidi_info, 0);
                        snd_rawmidi_info_set_stream(rawmidi_info, direction);
                        err = snd_ctl_rawmidi_info(handle, rawmidi_info);
                        TRACE0("after snd_ctl_rawmidi_info()\n");
                        if (err < 0) {
                            if (err != -ENOENT) {
                                ERROR2("ERROR: snd_ctl_rawmidi_info, card=%d: %s", card, snd_strerror(err));
                            }
                        } else {
                            TRACE0("snd_ctl_rawmidi_info() SUCCESS\n");
                            subdeviceCount = needEnumerateSubdevices(ALSA_RAWMIDI)
                                ? snd_rawmidi_info_get_subdevices_count(rawmidi_info)
                                : 1;
                            if (iterator!=NULL) {
                                for (subDev = 0; subDev < subdeviceCount; subDev++) {
                                    TRACE3("  Iterating %d,%d,%d\n", card, dev, subDev);
                                    deviceID = encodeDeviceID(card, dev, subDev);
                                    doContinue = (*iterator)(deviceID, rawmidi_info,
                                                             card_info, userData);
                                    count++;
                                    TRACE0("returned from iterator\n");
                                    if (!doContinue) {
                                        break;
                                    }
                                }
                            } else {
                                count += subdeviceCount;
                            }
                        }
                    } // of while(doContinue)
                }
                snd_ctl_close(handle);
            }
            if (snd_card_next(&card) < 0) {
                break;
            }
        }
    } else {
        ERROR0("No cards found!\n");
    }
    snd_ctl_card_info_free(card_info);
    snd_rawmidi_info_free(rawmidi_info);
    return count;
}
Exemplo n.º 3
0
bregonig *recompile_onig_ex(bregonig *rxold,
                            pattern_type type, const TCHAR *ptn,
                            const TCHAR *patternp, const TCHAR *patternendp,
                            const TCHAR *prerepp, const TCHAR *prerependp,
                            const TCHAR *optionp, const TCHAR *optionendp,
                            TCHAR *msg)
{
    int flag, compare;
    bregonig *rx;
    OnigOptionType option;
    OnigEncoding enc;
    TRACE0(_T("recompile_onig_ex()\n"));
    TRACE2(_T("patternp: %s, len: %d\n"), patternp, patternendp-patternp);
    TRACE2(_T("prerepp: %s, len: %d\n"), prerepp, prerependp-prerepp);
    TRACE2(_T("optionp: %s, len: %d\n"), optionp, optionendp-optionp);


    compare = compare_pattern(rxold, type, patternp, patternendp,
                              prerepp, prerependp, optionp, optionendp);
    TRACE1(_T("compare: %d\n"), compare);
    if (compare < 0) {
        // need to compile
        delete rxold;
        rxold = NULL;

        if (patternp == NULL
                || ((type == PTN_SUBST || type == PTN_TRANS) && prerepp == NULL)) {
            asc2tcs(msg, "invalid reg parameter", BREGEXP_MAX_ERROR_MESSAGE_LEN);
            return NULL;
        }
    } else {
        // no need to compile
        if (rxold->outp) {
            delete [] rxold->outp;
            rxold->outp = NULL;
        }
        if (rxold->splitp) {
            delete [] rxold->splitp;
            rxold->splitp = NULL;
        }
    }

    parse_option(optionp, optionendp, &option, &enc, &flag);

    if (type == PTN_TRANS) {
        if (compare == 0) {
            // no need to compile
            TRACE1(_T("rxold(1):0x%08x\n"), rxold);
            return rxold;
        }
        rx = trcomp(patternp, patternendp, prerepp, prerependp, flag, msg);
        if (rx == NULL) {
            return NULL;
        }
    } else {
        if (compare == 0) {
            // no need to compile
            TRACE1(_T("rxold(2):0x%08x\n"), rxold);
            return rxold;
        } else if (compare < 0) {
            // pattern string needs to compile.
            rx = new (std::nothrow) bregonig();
            if (rx == NULL) {
                asc2tcs(msg, "out of space regexp", BREGEXP_MAX_ERROR_MESSAGE_LEN);
                return NULL;
            }
            OnigErrorInfo err_info;
            int err_code = onig_new(&rx->reg,
                                    (UChar*) patternp, (UChar*) patternendp,
                                    option, enc, &OnigSyntaxPerl_NG_EX, &err_info);
            if (err_code != ONIG_NORMAL) {
                onig_err_to_bregexp_msg(err_code, &err_info, msg);
                delete rx;
                return NULL;
            }

            rx->nparens = onig_number_of_captures(rx->reg);	//
            rx->pmflags = flag;
        } else {
            // only replace string needs to compile.
            rx = rxold;
        }
        if (rxold != NULL && rxold->repstr != NULL) {
            delete rxold->repstr;
            rxold->repstr = NULL;
        }
        if (type == PTN_SUBST) {						// substitute
            try {
                rx->pmflags |= PMf_SUBSTITUTE;
                rx->repstr = compile_rep(rx, prerepp, prerependp);	// compile replace string
            } catch (std::exception& ex) {
                asc2tcs(msg, ex.what(), BREGEXP_MAX_ERROR_MESSAGE_LEN);
                delete rx;
                return NULL;
            }
        }
    }

    if (ptn != NULL) {
        size_t plen = _tcslen(ptn);
        delete [] rx->parap;
        rx->parap = new (std::nothrow) TCHAR[plen+1];	// parameter copy
        if (rx->parap == NULL) {
            asc2tcs(msg, "precompile out of space", BREGEXP_MAX_ERROR_MESSAGE_LEN);
            delete rx;
            return NULL;
        }
        memcpy(rx->parap, ptn, (plen+1)*sizeof(TCHAR));	// copy include null
        rx->paraendp = rx->parap + plen;
    }

    TCHAR *oldpatternp = rx->patternp;

    if (patternp == NULL) {
        patternp = rx->patternp;
        patternendp = rx->patternendp;
        optionp = rx->optionp;
        optionendp = rx->optionendp;
    }

    /* save pattern, replace and option string */
    ptrdiff_t len1 = patternendp - patternp;
    ptrdiff_t len2 = prerependp - prerepp;
    ptrdiff_t len3 = optionendp - optionp;
    rx->patternp = new (std::nothrow) TCHAR[len1+1 + len2+1 + len3+1];
    if (rx->patternp == NULL) {
        delete rx;
        delete [] oldpatternp;
        return NULL;
    }
    memcpy(rx->patternp, patternp, len1*sizeof(TCHAR));
    rx->patternp[len1] = 0;
    rx->patternendp = rx->patternp + len1;

    rx->prerepp = rx->patternp + len1 + 1;
    memcpy(rx->prerepp, prerepp, len2*sizeof(TCHAR));
    rx->prerepp[len2] = 0;
    rx->prerependp = rx->prerepp + len2;

    rx->optionp = rx->prerepp + len2 + 1;
    memcpy(rx->optionp, optionp, len3*sizeof(TCHAR));
    rx->optionp[len3] = 0;
    rx->optionendp = rx->optionp + len3;


    delete [] oldpatternp;

    TRACE1(_T("rx:0x%08x\n"), rx);
    return rx;
}
Exemplo n.º 4
0
/**
 * \fn     scanCncn_AppScanResultCB
 * \brief  Scan result callback for application scan
 *
 * Scan result callback for application scan
 *
 * \param  hScanCncn - handle to the scan concentrator object
 * \param  status - the scan result status (scan complete, result received etc.)
 * \param  frameInfo - a pointer to the structure holding all frame related info (in case a frame was received)
 * \param  SPSStatus - a bitmap indicating on which channels scan was attempted (valid for SPS scan only!)
 * \return None
 */
void scanCncn_AppScanResultCB (TI_HANDLE hScanCncn, EScanCncnResultStatus status,
                               TScanFrameInfo* frameInfo, TI_UINT16 SPSStatus)
{
    TScanCncn   *pScanCncn = (TScanCncn*)hScanCncn;
    TI_UINT32	statusData;

    /* Since in Manual Mode the app and the SME use the same table
     * there is no need to forward data to SME */

    switch (status)
    {
    case SCAN_CRS_RECEIVED_FRAME:
        /* Save the result in the app scan result table */
        if (TI_OK != scanResultTable_UpdateEntry (pScanCncn->hScanResultTable, frameInfo->bssId, frameInfo))
        {
            TRACE0(pScanCncn->hReport, REPORT_SEVERITY_WARNING , "scanCncn_AppScanResultCB, scanResultTable_UpdateEntry() failed\n");
        }
        break;

    case SCAN_CRS_SCAN_COMPLETE_OK:

        TRACE1(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncn_AppScanResultCB, received scan complete with status :%d\n", status);

        /* if OS scan is running */
        if (TI_TRUE == pScanCncn->bOSScanRunning)
        {
            /* send a scan complete event to the OS scan SM. It will stabliza the table when needed */
            genSM_Event (pScanCncn->hOSScanSm, SCAN_CNCN_OS_SM_EVENT_SCAN_COMPLETE, hScanCncn);
        }
        else
        {
            /* move the scan result table to stable state */
            scanResultTable_SetStableState (pScanCncn->hScanResultTable);

            /* mark that no app scan is running */
            pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_NO_CLIENT;
            /*
             * The scan was finished, send a scan complete event to the user
             * (regardless of why the scan was completed)
             */
            statusData = SCAN_STATUS_COMPLETE;	/* Completed status */
            EvHandlerSendEvent (pScanCncn->hEvHandler, IPC_EVENT_SCAN_COMPLETE, (TI_UINT8 *)&statusData, sizeof(TI_UINT32));
        }
        break;

    case SCAN_CRS_SCAN_STOPPED:

        TRACE1(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncn_AppScanResultCB, received scan complete with status :%d\n", status);

        /* if OS scan is running */
        if (TI_TRUE == pScanCncn->bOSScanRunning)
        {
            /* send a scan complete event to the OS scan SM. It will stabliza the table when needed */
            genSM_Event (pScanCncn->hOSScanSm, SCAN_CNCN_OS_SM_EVENT_SCAN_COMPLETE, hScanCncn);
        }
        else
        {
            /* move the scan result table to stable state */
            scanResultTable_SetStableState (pScanCncn->hScanResultTable);

            /* mark that no app scan is running */
            pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_NO_CLIENT;
            /*
             * The scan was finished, send a scan complete event to the user
             * (regardless of why the scan was completed)
             */
            statusData = SCAN_STATUS_STOPPED;	/* Stopped status */
            EvHandlerSendEvent (pScanCncn->hEvHandler, IPC_EVENT_SCAN_COMPLETE, (TI_UINT8 *)&statusData, sizeof(TI_UINT32));
        }
        break;

    case SCAN_CRS_TSF_ERROR:
    case SCAN_CRS_SCAN_RUNNING:
    case SCAN_CRS_SCAN_FAILED:
    case SCAN_CRS_SCAN_ABORTED_HIGHER_PRIORITY:
    case SCAN_CRS_SCAN_ABORTED_FW_RESET:

        TRACE1(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncn_AppScanResultCB, received scan complete with status :%d\n", status);

        /* if OS scan is running */
        if (TI_TRUE == pScanCncn->bOSScanRunning)
        {
            /* send a scan complete event to the OS scan SM. It will stabliza the table when needed */
            genSM_Event (pScanCncn->hOSScanSm, SCAN_CNCN_OS_SM_EVENT_SCAN_COMPLETE, hScanCncn);
        }
        else
        {
            /* move the scan result table to stable state */
            scanResultTable_SetStableState (pScanCncn->hScanResultTable);

            /* mark that no app scan is running */
            pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_NO_CLIENT;
            /*
             * The scan was finished, send a scan complete event to the user
             * (regardless of why the scan was completed)
             */
            statusData = SCAN_STATUS_FAILED;		/* Failed status */
            EvHandlerSendEvent (pScanCncn->hEvHandler, IPC_EVENT_SCAN_COMPLETE, (TI_UINT8 *)&statusData, sizeof(TI_UINT32));
        }
        break;

    case SCAN_CRS_NUM_OF_RES_STATUS:
    default:
        TRACE1(pScanCncn->hReport, REPORT_SEVERITY_ERROR , "scanCncn_AppScanResultCB, received erroneuos scan result with status :%d\n", status);
        break;
    }
}
Exemplo n.º 5
0
// Aquire and enabled audio card
// return 0 if ok, -1 if failed
int HAE_AquireAudioCapture(void *context, UINT32 encoding, UINT32 sampleRate, UINT32 channels, UINT32 bits,
			   UINT32 audioFramesPerBuffer, UINT_PTR *pCaptureHandle) {
    audio_info_t sunAudioHeader;
    INT32 error = -1;
	
    char* pAudioDev = HAE_GetAudioDevRec(g_soundDeviceIndex, 0);
    INT32 minFramesPerBuffer;

    //fprintf(stderr, "Entering HAE_AquireAudioCapture(encoding=%d, samplerate=%d, channels=%d, bits=%d, framesPerBuffer=%d)\n", 
    //	encoding, sampleRate, channels, bits, audioFramesPerBuffer);

    g_encoding = encoding;
    g_bitSize = bits;
    g_channels = channels;
    g_sampleRate = sampleRate;	

    if( audioFramesPerBuffer == 0 ) {
	audioFramesPerBuffer = sampleRate * HAE_SOLARIS_DEFAULT_BUFFERSIZE_IN_MS / 1000;
    }

    g_audioFramesToRead = audioFramesPerBuffer / g_audioCaptureBufferSizeDivisor;

    if (pCaptureHandle) {
	*pCaptureHandle = 0L;
    }

    // try to open wave device for recording
    // $$kk: 12.17.97: need O_NONBLOCK flag to be compatible with windows

    // $$kk: 10.13.98: we want O_NONBLOCK so that we return failure immediately if the
    // device is busy (or absent or whatever) rather than blocking.  however, i think that
    // this same O_NONBLOCK flag dictates whether the read() calls should block.  even 
    // without the O_NONBLOCK flag set, read() does *not* block for me, so i'm keeping 
    // the flag for now....
	
    g_captureSound = open(pAudioDev,O_RDONLY|O_NONBLOCK);

    if (g_captureSound > 0) {

	/* set to multiple open */
	if (ioctl(g_captureSound, AUDIO_MIXER_MULTIPLE_OPEN, NULL) >= 0) {
	    TRACE1("HAE_AquireAudioCapture: %s set to multiple open\n", pAudioDev);
	} else {
	    ERROR1("HAE_AquireAudioCapture: ioctl AUDIO_MIXER_MULTIPLE_OPEN failed on %s!\n", pAudioDev);
	}

	AUDIO_INITINFO(&sunAudioHeader);
		
	// Set capture format of the sun device.
	sunAudioHeader.record.sample_rate = sampleRate;
	sunAudioHeader.record.precision = bits;
	sunAudioHeader.record.channels = channels;
	sunAudioHeader.record.buffer_size = g_audioFramesToRead * channels * bits / 8;
		
	sunAudioHeader.record.encoding = AUDIO_ENCODING_LINEAR;
	if (g_encoding == ULAW) {
	    sunAudioHeader.record.encoding = AUDIO_ENCODING_ULAW;			
	} 
	else if (g_encoding == ALAW) {
	    sunAudioHeader.record.encoding = AUDIO_ENCODING_ALAW;			
	} 



	// start out paused so we don't overflow the device driver buffers
	sunAudioHeader.record.pause = 1;
	error = ioctl(g_captureSound, AUDIO_SETINFO, &sunAudioHeader);

	if (error != -1) {
	    // flush anything we might have accumulated in the capture queue before pausing
	    error = ioctl(g_captureSound, I_FLUSH, FLUSHR);

	    error = ioctl(g_captureSound, AUDIO_GETINFO, &sunAudioHeader);
	    g_audioFramesToRead = sunAudioHeader.record.buffer_size / (channels * bits / 8);


	    if (error != -1) {
		if (pCaptureHandle) {
		    *pCaptureHandle = (UINT_PTR)g_captureSound;
		}
	    } 
	}
    }

    if (error == -1) {	// something failed
	HAE_ReleaseAudioCapture(context);
    }

    //fprintf(stderr, "<< HAE_API_SolarisOS_Capture: HAE_AquireAudioCapture() returning %d\n", error);
    return error;
}
Exemplo n.º 6
0
int CSAStatusLog::MapOpen(int nType)
{
	if( m_csFileName.IsEmpty() ) 
		return -1; 
	
	m_nType	= nType;
	CString strPath	= m_csFileName;
	//	if( !FolderExist( strPath ) )

    // 创建文件对象

    HANDLE hFile = (HANDLE)CreateFile(strPath, GENERIC_READ,\
        0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE)
    {
        TRACE1("创建文件对象失败,错误代码:%d\n ", GetLastError());
        return -1;
    }
	// 得到文件尺寸
    DWORD dwFileSizeHigh;
    m_qwFileSize = GetFileSize(hFile, &dwFileSizeHigh);
    m_qwFileSize |= (((__int64)dwFileSizeHigh) << 32);
    m_qwFileSize+=sizeof(char);
	if( m_qwFileSize >= __MAX_LOGFILE_SIZE__)
	{
		CloseHandle(hFile);
		return -1;
	}
    // 创建文件映射对象
	if( nType == OT_WRITE )
		m_hFileMap = CreateFileMapping(hFile, NULL, PAGE_READWRITE, 0, __MAX_LOGFILE_SIZE__, NULL);
	else
		m_hFileMap = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
    if (m_hFileMap == NULL)
    {
		// 关闭文件对象
		CloseHandle(hFile);
        TRACE1("%s",GetLastError);
		TRACE1("创建文件映射对象失败,错误代码:%d ", GetLastError());
        return -1;
    }
    // 得到系统分配粒度
    SYSTEM_INFO SysInfo;
    GetSystemInfo(&SysInfo);
    DWORD dwGran = SysInfo.dwAllocationGranularity;
		  //   当数据写满60%时,为防数据溢出,需要在其后开辟一新的映射视图   

	// 得到文件尺寸
    __int64 qwFileSize = GetFileSize(hFile, &dwFileSizeHigh);
    qwFileSize |= (((__int64)dwFileSizeHigh) << 32);
    // 关闭文件对象
    CloseHandle(hFile);
    // 块大小
    DWORD dwBlockBytes = 1000 * dwGran;
    if (qwFileSize < 1000 * dwGran)
        dwBlockBytes = (DWORD)qwFileSize;
	
    // 映射视图
    m_lpbMapAddress = (TCHAR *)MapViewOfFile(m_hFileMap,FILE_MAP_READ, 0, 0, dwBlockBytes);
	if (m_lpbMapAddress == NULL)
    {
		AfxMessageBox("映射文件映射失败,错误代码:%d ", GetLastError());
		return -1;
	}
	
	m_fMapOpen		= TRUE;
	
	return 0;
}
// 生成时统报文设置帧
void CTailTimeFrameSocket::MakeTimeDelayFrameData(CInstrument* pInstrument, unsigned int uiTimeHigh, unsigned int uiTimeLow)
{
	unsigned int uiIPSource =	0;
	unsigned int uiIPAim	=	0;
	unsigned int usPortAim	=	0;
	unsigned int usCommand	=	0;
	for(int i=0; i<SndFrameSize; i++)
	{
		m_pTimeDelayData[i] = 0x00;
	}
	m_pTimeDelayData[0] = 0x11;
	m_pTimeDelayData[1] = 0x22;
	m_pTimeDelayData[2] = 0x33;
	m_pTimeDelayData[3] = 0x44;
	m_pTimeDelayData[4] = 0x00;
	m_pTimeDelayData[5] = 0x00;
	m_pTimeDelayData[6] = 0x00;
	m_pTimeDelayData[7] = 0x00;
	m_pTimeDelayData[8] = 0x00;
	m_pTimeDelayData[9] = 0x00;
	m_pTimeDelayData[10] = 0x00;
	m_pTimeDelayData[11] = 0x00;
	m_pTimeDelayData[12] = 0x00;
	m_pTimeDelayData[13] = 0x00;
	m_pTimeDelayData[14] = 0x00;
	m_pTimeDelayData[15] = 0x00;

	uiIPSource	=	inet_addr(m_csIPSource);
	uiIPAim		=	pInstrument->m_uiIPAddress;
	usPortAim	=	TimeSetPort;
	usCommand	=	SendSetCmd;
	// 源IP地址
	memcpy(&m_pTimeDelayData[16], &uiIPSource, 4);
	// 目标IP地址
	memcpy(&m_pTimeDelayData[20], &uiIPAim, 4);
	TRACE1("时统设置帧-仪器IP地址:%d\r\n", uiIPAim);
	// 目标端口号
	memcpy(&m_pTimeDelayData[24], &usPortAim, 2);
	// 命令号 1-设置命令应答;2-查询命令应答;3-AD采样数据重发
	memcpy(&m_pTimeDelayData[26], &usCommand, 2);

	int iPos = 32;
	// 命令字0x05修正时延高位
	m_pTimeDelayData[iPos] = 0x05;
	iPos++;
	memcpy(&m_pTimeDelayData[iPos], &uiTimeHigh, 4);
	iPos = iPos + 4;

	// 命令字0x06修正时延低位
	m_pTimeDelayData[iPos] = 0x06;
	iPos++;
	memcpy(&m_pTimeDelayData[iPos], &uiTimeLow, 4);
	iPos = iPos + 4;

	// 设置命令字结束
	m_pTimeDelayData[iPos] = 0x00;

	unsigned short usCRC16 = 0;
	usCRC16 = get_crc_16(&m_pTimeDelayData[FrameHeadSize], SndFrameSize - FrameHeadSize - CRCCheckSize);
	memcpy(&m_pTimeDelayData[SndFrameSize - CRCSize], &usCRC16, 2);
}
Exemplo n.º 8
0
/*
 =======================================================================================================================
 =======================================================================================================================
 */
void Flashram_Command(unsigned __int32 data)
{
	DEBUG_FLASHRAM_TRACE(TRACE1("*** CMD = %08X ***", data));
	switch(data >> 24)
	{
	case 0x4b:	/* Set Erase Block Mode (128 Byte - aligned ) */
		DEBUG_FLASHRAM_TRACE(TRACE0("Flash Erase Mode"));
		FlashRAM_Mode = FLASH_ERASE;
		FlashRAM_Offset = (data & 0xFFFF) * 128;
		break;

	case 0x78:	/* Second part of the Erase Block */
		DEBUG_FLASHRAM_TRACE(TRACE0("Flash Erase Block"));
		FlashRAM_Status[0] = 0x11118008;
		FlashRAM_Status[1] = 0x00c20000;
		break;

	/* Init a FlashWrite */
	case 0xb4:
		DEBUG_FLASHRAM_TRACE(TRACE0("Flash FlashWrite Init"));
		FlashRAM_Mode = FLASH_WRITE;
		break;

	/* Sets the Block for the FlashWrite (128 Byte - aligned ) */
	case 0xa5:
		DEBUG_FLASHRAM_TRACE(TRACE0("Flash FlashWrite"));
		FlashRAM_Offset = (data & 0xFFFF) * 128;
		FlashRAM_Status[0] = 0x11118004;
		FlashRAM_Status[1] = 0x00c20000;
		break;

	case 0xD2:
		{		/* Flash RAM Execute */
			switch(FlashRAM_Mode)
			{
			case FLASH_NOOP:
				break;
			case FLASH_ERASE:
				DEBUG_FLASHRAM_TRACE(TRACE1("Executed Erase: %08X", FlashRAM_Offset));
				memset(pLOAD_UBYTE_PARAM(0xA8000000) + FlashRAM_Offset, 0xFF, 128);
				FileIO_WriteFLASHRAM(0,0,0);	//Write to disk
				break;
			case FLASH_WRITE:
				DEBUG_FLASHRAM_TRACE(TRACE1("Executed Write: %08X", FlashRAM_Offset));
				memcpy(pLOAD_UBYTE_PARAM(0xA8000000) + FlashRAM_Offset, &FlashRAM_Buffer[0], 128);
				FileIO_WriteFLASHRAM(0,0,0);	//Write to disk
				break;
			}
		}
		break;
	case 0xE1:
		{		/* Set FlashRAM Status */
			DEBUG_FLASHRAM_TRACE(TRACE0("Flash Status"));
			FlashRAM_Mode = FLASH_STATUS;
			FlashRAM_Status[0] = 0x11118001;
			FlashRAM_Status[1] = 0x00c20000;
		}
		break;
	case 0xF0:	/* Set FlashRAM Read */
		/* DEBUG_FLASHRAM_TRACE(TRACE0 ("Flash Read")); */
		FlashRAM_Mode = FLASH_NOOP;
		FlashRAM_Offset = 0;
		FlashRAM_Status[0] = 0x11118004;
		FlashRAM_Status[1] = 0xf0000000;
		break;
	}
}
Exemplo n.º 9
0
void genSM_Event (TI_HANDLE hGenSM, TI_UINT32 uEvent, void *pData)
{
	TGenSM              *pGenSM =       (TGenSM*)hGenSM;
	TGenSM_actionCell   *pCell;

#ifdef TI_DBG
	/* sanity check */
	if (pGenSM == NULL)
	{
		os_printf("genSM_Event: Handle is NULL!!\n");
		return;
	}
	if (uEvent >= pGenSM->uEventNum)
	{
		TRACE3(pGenSM->hReport, REPORT_SEVERITY_ERROR , "genSM_Event: module: %d received event %d, which is out of events boundry %d\n", pGenSM->uModuleLogIndex, uEvent, pGenSM->uEventNum);
	}
	if (TI_TRUE == pGenSM->bEventPending)
	{
		TRACE3(pGenSM->hReport, REPORT_SEVERITY_ERROR , "genSM_Event: module: %d received event %d, when event %d is pending execution!\n", pGenSM->uModuleLogIndex, uEvent, pGenSM->uEvent);
	}
#endif

	/* mark that an event is pending */
	pGenSM->bEventPending = TI_TRUE;

	/* save event and data */
	pGenSM->uEvent = uEvent;
	pGenSM->pData = pData;

	/* if an event is currently executing, return (new event will be handled when current event is done) */
	if (TI_TRUE == pGenSM->bInAction)
	{
		TRACE1(pGenSM->hReport, REPORT_SEVERITY_INFORMATION , ": module: %d delaying execution of event \n", pGenSM->uModuleLogIndex);
		return;
	}

	/* execute events, until none is pending */
	while (TI_TRUE == pGenSM->bEventPending)
	{
		/* get the cell pointer for the current state and event */
		pCell = &(pGenSM->tMatrix[ (pGenSM->uCurrentState * pGenSM->uEventNum) + pGenSM->uEvent ]);


		/* print state transition information */
		TRACE4(pGenSM->hReport, REPORT_SEVERITY_INFORMATION, "genSM_Event: module %d <currentState = %d, event = %d> --> nextState = %d\n", pGenSM->uModuleLogIndex, pGenSM->uCurrentState, uEvent, pCell->uNextState);

		/* mark that event execution is in place */
		pGenSM->bInAction = TI_TRUE;

		/* mark that pending event is being handled */
		pGenSM->bEventPending = TI_FALSE;

		/* update current state */
		pGenSM->uCurrentState = pCell->uNextState;

		/* run transition function */
		(*(pCell->fAction)) (pGenSM->pData);

		/* mark that event execution is complete */
		pGenSM->bInAction = TI_FALSE;
	}
}
/****************************************************************************
 *                      cmdBld_BitIeTestCmd()
 ****************************************************************************
 * DESCRIPTION:
 * INPUTS: None
 *
 * OUTPUT:  None
 *
 * RETURNS: TI_OK or TI_NOK
 ****************************************************************************/
TI_STATUS cmdBld_CmdIeTest (TI_HANDLE hCmdBld, void *fCb, TI_HANDLE hCb, TTestCmd* pTestCmd)
{
	TCmdBld      *pCmdBld = (TI_HANDLE)hCmdBld;
	TI_UINT32    paramLength;
	TI_BOOL      bIsCBfuncNecessary = TI_TRUE;

	if (NULL == pTestCmd) {
		TRACE0(pCmdBld->hReport, REPORT_SEVERITY_ERROR, " pTestCmd_Buf = NULL!!!\n");
		return TI_NOK;
	}

	if ( (TestCmdID_enum)pTestCmd->testCmdId < MAX_TEST_CMD_ID ) {
		bIsCBfuncNecessary = TI_TRUE;
	} else {
		TRACE1(pCmdBld->hReport, REPORT_SEVERITY_WARNING, " Unsupported testCmdId (%d)\n", pTestCmd->testCmdId);
	}

	if (bIsCBfuncNecessary && fCb == NULL) {
		return TI_OK;
	}

	switch( pTestCmd->testCmdId ) {
	case TEST_CMD_PD_BUFFER_CAL:
		paramLength = sizeof(TTestCmdPdBufferCal);
		break;

	case TEST_CMD_P2G_CAL:
		paramLength = sizeof(TTestCmdP2GCal);
		break;

	case TEST_CMD_RX_STAT_GET:
		paramLength = sizeof(RadioRxStatistics);
		break;

		/* packet */
	case TEST_CMD_FCC:
		paramLength = sizeof(TPacketParam);
		break;

		/* tone */
	case TEST_CMD_TELEC:
		paramLength = sizeof(TToneParam);
		break;

	case TEST_CMD_PLT_TEMPLATE:
		paramLength = sizeof(TTxTemplate);
		break;

		/* channel tune */
	case TEST_CMD_CHANNEL_TUNE:
		paramLength = sizeof(TTestCmdChannel);
		break;

	case TEST_CMD_GET_FW_VERSIONS:
		paramLength = sizeof(TFWVerisons);
		break;

	case TEST_CMD_INI_FILE_RADIO_PARAM:
		paramLength = sizeof(IniFileRadioParam);
		break;

	case TEST_CMD_INI_FILE_GENERAL_PARAM:
		paramLength = sizeof(IniFileGeneralParam);
		break;

	case TEST_CMD_PLT_GAIN_ADJUST:
		paramLength = sizeof(uint32);
		break;

	case TEST_CMD_RUN_CALIBRATION_TYPE:
		paramLength = sizeof(TTestCmdRunCalibration);
		break;

	case TEST_CMD_TX_GAIN_ADJUST:
		paramLength = sizeof(TTxGainAdjust);
		break;
	case TEST_CMD_TEST_TONE:
		paramLength = sizeof(TestToneParams_t);
		break;

	case TEST_CMD_SET_EFUSE:
		paramLength = sizeof(EfuseParameters_t);
		break;
	case TEST_CMD_GET_EFUSE:
		paramLength = sizeof(EfuseParameters_t);
		break;

	case TEST_CMD_RX_PLT_CAL:
		paramLength = sizeof(RadioRxPltCal);
		break;

	case TEST_CMD_UPDATE_PD_REFERENCE_POINT:
		paramLength = sizeof(TTestCmdUpdateReferncePoint);
		break;

	case TEST_CMD_UPDATE_PD_BUFFER_ERRORS:
		paramLength = sizeof(TTestCmdPdBufferErrors);
		break;

	case TEST_CMD_POWER_MODE:
		paramLength = sizeof(TTestCmdPowerMode);
		break;

	case TEST_CMD_STOP_TX:
	case TEST_CMD_RX_STAT_STOP:
	case TEST_CMD_RX_STAT_START:
	case TEST_CMD_RX_STAT_RESET:
	case TEST_CMD_RX_PLT_ENTER:
	case TEST_CMD_RX_PLT_EXIT:
		paramLength = 0;
		break;

	default:
		paramLength = sizeof(pTestCmd->testCmd_u);
	}

	return cmdQueue_SendCommand (pCmdBld->hCmdQueue,
	                             CMD_TEST,
	                             (void *)pTestCmd,
	                             paramLength + RESEARVED_SIZE_FOR_RESPONSE,
	                             fCb,
	                             hCb,
	                             (void*)pTestCmd);
}
Exemplo n.º 11
0
// Parses Ecmt packets
void CEcmtMidpDebugPlugin::HandleNotifyL(const CEcmtMessageEvent& aEvent)
{
    static const TInt KMinMsgSize[] = {
        0,
        ECMT_MIDP_DEBUG_OPEN_SIZE,
        ECMT_MIDP_DEBUG_CLOSE_SIZE,
        ECMT_MIDP_DEBUG_SEND_MIN_SIZE,
        ECMT_MIDP_DEBUG_CONNECT_SIZE,
        ECMT_MIDP_DEBUG_RESET_SIZE
    };

    static const TInt KMaxMsgSize[] = {
        0,
        ECMT_MIDP_DEBUG_OPEN_SIZE,
        ECMT_MIDP_DEBUG_CLOSE_SIZE,
        ECMT_MIDP_DEBUG_SEND_MAX_SIZE,
        ECMT_MIDP_DEBUG_CONNECT_SIZE,
        ECMT_MIDP_DEBUG_RESET_SIZE
    };

    const TPtrC8 msg = iMessaging->Message(aEvent);
    TInt msglen = msg.Length();
    if (msglen >= ECMT_MIDP_DEBUG_HEADER_SIZE)
    {
        // Decode the header
        TUint opcode = msg[ECMT_MIDP_DEBUG_HEADER_OPCODE_OFFSET];
        TUint sid = (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET] << 24) | 
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+1] << 16) |
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+2] << 8) |
            (msg[ECMT_MIDP_DEBUG_HEADER_SID_OFFSET+3]);

        // Check opcode
        if (opcode < ECMT_MIDP_DEBUG_OPCODE_MIN ||
            opcode > ECMT_MIDP_DEBUG_OPCODE_MAX)
        {
            TRACE1("invalid opcode: %u",opcode);
            return;
        }

        // Check message size
        if (msglen < KMinMsgSize[opcode] || 
            msglen > KMaxMsgSize[opcode])
        {
            TRACE2("opcode %u, invalid message size %u",opcode,msglen);
            return;
        }

        // Try to find existing session
        TInt index = -1;
        CEcmtMidpDebugSession* session = FindSession(sid, index);
        switch (opcode) {
        case ECMT_MIDP_DEBUG_OPCODE_OPEN:
            if (session)
            {
                TRACE2("OPEN: destroying session %08X (%d)",session,sid);
                delete session;
                iSessions.Remove(index);
            }
            session = CEcmtMidpDebugSession::NewL(sid,this,iMessaging);
            CleanupStack::PushL(session);
            LEAVE_IF_ERROR(iSessions.Append(session));
            CleanupStack::Pop(session);
            TRACE2("OPEN: created new session %08X (%u)",session,sid);
            break;
                
        case ECMT_MIDP_DEBUG_OPCODE_CLOSE:
            if (session)
            {
                TRACE2("CLOSE: destroying session %08X (%u)",session,sid);
                delete session;
                iSessions.Remove(index);
            }
            else
            {
                TRACE1("CLOSE: no such session: %u",sid); 
            }
            break;

        case ECMT_MIDP_DEBUG_OPCODE_SEND:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_SEND_CID_OFFSET+3]);
                TUint seq = (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_SEND_SEQ_OFFSET+3]);
                session->Send(cid, seq,
                    msg.Right(msglen - ECMT_MIDP_DEBUG_SEND_DATA_OFFSET));
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("SEND: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;

        case ECMT_MIDP_DEBUG_OPCODE_CONNECT:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_CONNECT_CID_OFFSET+3]);
                TUint port = (msg[ECMT_MIDP_DEBUG_CONNECT_PORT_OFFSET] << 8) | 
                    (msg[ECMT_MIDP_DEBUG_CONNECT_PORT_OFFSET+1]);
                session->ConnectL(cid, port);
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("CONNECT: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;


        case ECMT_MIDP_DEBUG_OPCODE_RESET:
            if (session)
            {
                TUint cid = (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET] << 24) | 
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+1] << 16) |
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+2] << 8) |
                    (msg[ECMT_MIDP_DEBUG_RESET_CID_OFFSET+3]);
                session->Reset(cid);
            }
            else
            {
                // Tell the other side that this session id is invalid
                TRACE1("RESET: invalid sid %u",sid);
                SendSessionCloseMessage(sid);
            }
            break;

        }
    }
}
Exemplo n.º 12
0
/**
* GetFtpDirectory
*
* Description: 1) Conect to ftp server, change directory. 
*	2) Get dir listing.
*	3) Read existing listing file, 
*	4) If listing has changed, write new dir listing file.
*
* Parameters:	CConnection - describes ftp connection info, user, host etc.
*				dir - ftp remote directory
*				ftpClient - optional ftpclient. if null, will create, connect and close.
* Return:
*				bool - success
* ??? was it updated?
*/
bool CFtpManager::GetFtpDirectory(CConnection * con, CString &directory, CRealFtpClient * ftpClient)
{
	bool result = false;
	//TRACE1(" con %s \n ", con->name);

	//Connect(con, m_ftpClient);
	//if(!m_ftpClient.IsConnected()) // Not connected
	//{
	//	return;
	//}
	bool closeConnection = false;
	if(!ftpClient)
	{
		ftpClient = new CRealFtpClient();
		closeConnection = true;
	}
	if(!ftpClient->IsConnected()) // Not connected
	{
		int retcode = 11;
		retcode = ftpClient->FTPConnect(con->host, con->user, con->password, _T(""));
		if(retcode == UTE_SUCCESS)
		{
			ftpClient->SetFireWallMode(TRUE);
		}
	}

	//m_ftpClient.SetFireWallMode(TRUE);
	//ftpClient->SetFireWallMode(TRUE);

	CString localStorePath;
	GetLocalStorePath(con, localStorePath);
	localStorePath = localStorePath + directory + CString(_T(""));
	localStorePath.Replace('/', '\\');

	CString dirContentListing(_T(""));
	CString fileListing(_T(""));
	CString folderListing(_T(""));

	CUT_DIRINFO di;
	_TCHAR entry[HISTORY_ENTRY_SIZE];
	_TCHAR dir[MAX_PATH];
	int valRet;
	{
		valRet = ftpClient->ChDir( directory );
		if (valRet != UTE_SUCCESS){
			//m_history.AddLine(CUT_ERR::GetErrorString (valRet));
			TRACE1(" chdir failed: %s \n ", CUT_ERR::GetErrorString(valRet) );
		}
		else 
		{
			int dirInfo = ftpClient->GetDirInfo();

			int count = ftpClient->GetDirInfoCount();
			for(int t=0;t<count;t++){
				ftpClient->GetDirEntry(t, &di);
				// v4.2 dir info now has _TCHAR
				// Format: Name,size,time, time display
				_sntprintf(entry, 
					sizeof(entry)/sizeof(_TCHAR), 
					_T("<n>%s</n><s>%ld</s><d>%2.2d/%2.2d/%2.2d %2.2d:%2.2d</d><p>%d</p><o>%s</o><g>%s</g>"),
					di.fileName, di.fileSize,
					di.year, di.month, di.day, di.hour, di.minute, di.permissions, di.owner, di.group);
					
				//m_history.AddLine(entry);

				if(di.isDir)
				{
					CString folderPath(localStorePath + _T("") + di.fileName );
					if(GetFileAttributes(folderPath) == INVALID_FILE_ATTRIBUTES){
						CreateDirectory(folderPath, NULL);
					}

					CString fileInfo(_T(""));
					fileInfo = fileInfo + CString(_T("<t>d</t>")) + CString(entry) + _T("\n");
					folderListing = folderListing + fileInfo;
				} else {
					// File
					CString fileInfo(_T(""));
					fileInfo = fileInfo + CString(_T("<t>f</t>")) + CString(entry) + _T("\n");
					fileListing = fileListing + fileInfo;
				}
			}
			dirContentListing = CString(folderListing + fileListing);

			
			// write dir descriptor
			// dirContentListing
			CString dirContentFile(localStorePath + _T(".files.rftp"));


			// Check existing files.rftp. Don't rewrite if its the same. SSD safety.
			CString existingListing(_T(""));
			CFileStatus status;
			if(CFile::GetStatus(dirContentFile, status))
			{
				CStdioFile file (dirContentFile, CStdioFile::modeRead | CFile::shareDenyNone);
				CString buffer;
				while (file.ReadString(buffer))
				{
					existingListing = existingListing + buffer + _T("\n");
				}
			}

			
			if(existingListing.Compare(dirContentListing) != 0)
			{
				CFile theFile(dirContentFile, CFile::modeReadWrite | CFile::modeCreate);
				
				char buffer[200000];
				sprintf(buffer, "%S", dirContentListing); // CString to char *
				int len = strlen(buffer);
				//theFile.Write( (LPCTSTR) dirContentListing, dirContentListing.GetLength() * sizeof(TCHAR));
				
				//
				// Error here ***********
				//
				CString buffy(dirContentFile);
				if(buffy.Find(CString(_T("newsletter-form"))) != 1){
					int i  = 0;
				}

				theFile.Write(buffer, len);

				TRACE0(" GetFtpDirectory Updated \n");
				m_directoryUpdated = true;  
			} else {
				//TRACE0(" GetFtpDirectory Allready up to date \n");
				m_directoryUpdated = false;
			}

			//TRACE1(" file: %s \n", entry);
			result = true;
		} // chdir success		
	}
	if(closeConnection){
		ftpClient->Close();
		delete ftpClient;
	}
	return result;
}
Exemplo n.º 13
0
/**
* ReadLocalDirectory
*
* Description: Read files folders from directory.
*
* Param: con - describes connection information
*        dir - path. 
*		 files - output list
*
* Return: bool - true. False if file does not exist, has not been read.
*/
bool CFtpManager::ReadLocalDirectory(CConnection * con, CString &dir, std::vector<CFileContainer> &files)
{
	bool result = true;
	if(con->host.GetLength() == 0)
	{
		return false;
	}

	if(dir.GetAt( dir.GetLength() - 1 ) != '/')
	{
		dir = dir + CString(_T("/"));
	}

	CString localStorePath;
	GetLocalStorePath(con, localStorePath);

	// Read files and folders in directory.
	localStorePath = localStorePath + CString(dir);
	localStorePath.Replace('/', '\\');
	CString localStoreSearchPath = CString(localStorePath + CString(_T("*.*")));
	/*
	CFileFind finder; 
	BOOL bWorking = finder.FindFile(localStoreSearchPath);
	while (bWorking)
	{
		bWorking = finder.FindNextFile();
		if(finder.IsDirectory())
		{
			CFileContainer f;
			f.dir = 1;
			f.name = finder.GetFileName(); //  .GetFileTitle();
			f.path = CString(dir); //finder.GetFilePath();
			f.localPath = CString(localStorePath);
			if(f.name.Trim().Compare(_T(".")) != 0 && f.name.Trim().Compare(_T("..")) != 0){
				//files.push_back(f);
			}
		} 
		// else sync local file
	}
	finder.Close();
	*/

	// Read file 
	CString dirContentFile(localStorePath + _T(".files.rftp"));

	//char nameBuffer[100];
	//sprintf(nameBuffer, "%S", dirContentFile); // CString to char *
	
	CFileStatus status;
	if(CFile::GetStatus(dirContentFile, status))
	{
		CStdioFile file (dirContentFile, CStdioFile::modeRead | CFile::shareDenyNone);
		CString buffer;
		//CString string;
		while (file.ReadString(buffer))
		{
			CXml xml;

			CString type(_T(""));
			xml.GetTag(buffer, CString(_T("t")), type);
			bool isDir = false;
			if(type.Compare(_T("d")) == 0){
				isDir = true;
			}
			

			CString fileName(_T(""));
			xml.GetTag(buffer, CString(_T("n")), fileName);

			
			// size
			long size = 0;
			CString fileSize(_T(""));
			if(xml.GetTag(buffer, CString(_T("s")), fileSize)){
				fileSize = fileSize.Trim();
				if(fileSize.GetLength() > 0){
					size = _wtol(fileSize);
				}
			}

			// Date
			CString fileDate(_T(""));
			xml.GetTag(buffer, CString(_T("d")), fileDate);	
			fileDate = fileDate.Trim();
			

			// permissions
			CString filePermissions(_T(""));
			xml.GetTag(buffer, CString(_T("p")), filePermissions);	
			filePermissions = filePermissions.Trim();

			//TRACE1(" line: %s \n", buffer);
			CFileContainer f;
			if(isDir){
				f.dir = 1;
			} else {
				f.dir = 0;
			}
			f.name = fileName; 
			f.path = CString(dir); 
			f.localPath = CString(localStorePath);
			f.size = size;
			f.remoteDate = CString(fileDate);
			f.host = CString(con->host);
			//TRACE1("filePermissions %s \n " , filePermissions);
			f.permissions = CString(filePermissions);
			
			if(f.name.Trim().Compare(_T(".")) != 0 && f.name.Trim().Compare(_T("..")) != 0 ){
				int i = 0;
				files.push_back(f);
			}
		}
	} 
	else 
	{
		// Directory not read.
		//GetFtpDirectory(con, dir, NULL);
		TRACE1(" ReadLocalDirectory not found: %s \n", dir);
		result = false;
	}
	return result;
}
Exemplo n.º 14
0
static int __init EplLinInit(void)
{

	tEplKernel EplRet;
	int iErr;
	int iRet;
#ifdef CONFIG_DEVFS_FS
	int nMinorNumber;
#endif

	TRACE0("EPL: + EplLinInit...\n");
	TRACE2("EPL:   Driver build: %s / %s\n", __DATE__, __TIME__);

	iRet = 0;

	// initialize global variables
	atomic_set(&AtomicEventState_g, EVENT_STATE_INIT);
	sema_init(&SemaphoreCbEvent_g, 1);
	init_waitqueue_head(&WaitQueueCbEvent_g);
	init_waitqueue_head(&WaitQueueProcess_g);
	init_waitqueue_head(&WaitQueueRelease_g);

#ifdef CONFIG_DEVFS_FS

	// register character device handler
	TRACE2("EPL:   Installing Driver '%s', Version %s...\n",
	       EPLLIN_DRV_NAME, EPL_PRODUCT_VERSION);
	TRACE0("EPL:   (using dynamic major number assignment)\n");
	nDrvMajorNumber_g =
	    register_chrdev(0, EPLLIN_DRV_NAME, &EplLinFileOps_g);
	if (nDrvMajorNumber_g != 0) {
		TRACE2
		    ("EPL:   Driver '%s' installed successful, assigned MajorNumber=%d\n",
		     EPLLIN_DRV_NAME, nDrvMajorNumber_g);
	} else {
		TRACE1
		    ("EPL:   ERROR: Driver '%s' is unable to get a free MajorNumber!\n",
		     EPLLIN_DRV_NAME);
		iRet = -EIO;
		goto Exit;
	}

	// create device node in DEVFS
	nMinorNumber = 0;
	TRACE1("EPL:   Creating device node '/dev/%s'...\n", EPLLIN_DEV_NAME);
	iErr =
	    devfs_mk_cdev(MKDEV(nDrvMajorNumber_g, nMinorNumber),
			  S_IFCHR | S_IRUGO | S_IWUGO, EPLLIN_DEV_NAME);
	if (iErr == 0) {
		TRACE1("EPL:   Device node '/dev/%s' created successful.\n",
		       EPLLIN_DEV_NAME);
	} else {
		TRACE1("EPL:   ERROR: unable to create device node '/dev/%s'\n",
		       EPLLIN_DEV_NAME);
		iRet = -EIO;
		goto Exit;
	}

#else

	// register character device handler
	// only one Minor required
	TRACE2("EPL:   Installing Driver '%s', Version %s...\n",
	       EPLLIN_DRV_NAME, EPL_PRODUCT_VERSION);
	iRet = alloc_chrdev_region(&nDevNum_g, 0, 1, EPLLIN_DRV_NAME);
	if (iRet == 0) {
		TRACE2
		    ("EPL:   Driver '%s' installed successful, assigned MajorNumber=%d\n",
		     EPLLIN_DRV_NAME, MAJOR(nDevNum_g));
	} else {
		TRACE1
		    ("EPL:   ERROR: Driver '%s' is unable to get a free MajorNumber!\n",
		     EPLLIN_DRV_NAME);
		iRet = -EIO;
		goto Exit;
	}

	// register cdev structure
	pEpl_cdev_g = cdev_alloc();
	pEpl_cdev_g->ops = &EplLinFileOps_g;
	pEpl_cdev_g->owner = THIS_MODULE;
	iErr = cdev_add(pEpl_cdev_g, nDevNum_g, 1);
	if (iErr) {
		TRACE2("EPL:   ERROR %d: Driver '%s' could not be added!\n",
		       iErr, EPLLIN_DRV_NAME);
		iRet = -EIO;
		goto Exit;
	}
#endif

	// create device node in PROCFS
	EplRet = EplLinProcInit();
	if (EplRet != kEplSuccessful) {
		goto Exit;
	}

      Exit:

	TRACE1("EPL: - EplLinInit (iRet=%d)\n", iRet);
	return (iRet);

}
Exemplo n.º 15
0
//==============================================================================================
// FUNCTION: WindowProc
// PURPOSE:  
//
LRESULT CMCTeleServerDlg::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
   // process telegraph open message
   // add the sender's HWND to the client list
   // send a telegraph packet to that HWND
   if( message == s_uMCTGOpenMessage )
   {
      UINT uSerialNum = atoi(m_mctdCurrentState.szSerialNumber);
      UINT uChannelID = m_mctdCurrentState.uChannelID;
      if( !MCTG_Match700BSignalIDs( uSerialNum,
                                    uChannelID, 
                                    lParam      ) )

      {
         // this request is for another MultiClamp device / channel
         // ignore it
         return TRUE;
      }

      UINT uX = 0;

      // see if the sender's HWND is already in the client list
      for(uX = 0; uX < MCTG_MAX_CLIENTS; ++ uX)
      {
         if(m_ClientHwndList[uX] == (HWND) wParam)
         {
            // failed to add sender's HWND to client list
            // this HWND is already connected
            TRACE2("server(%s,%d): ",
                   m_mctdCurrentState.szSerialNumber,
                   m_mctdCurrentState.uChannelID );
            TRACE1("open failed for 0x%08X: already open\n", wParam);
            return TRUE;
         }
      }

      // attempt to add the sender's HWND to the client list
      // place it in the first available blank slot
      ASSERT(wParam != NULL);
      BOOL bSuccess = FALSE;
      for(uX = 0; uX < MCTG_MAX_CLIENTS; ++ uX)
      {
         if(m_ClientHwndList[uX] == NULL)
         {
            m_ClientHwndList[uX] = (HWND) wParam;
            bSuccess = TRUE;
            break;
         }
      }

      if( bSuccess )
      {
         // successfully added HWND to client list
         TRACE2("server(%s,%d): ",
                m_mctdCurrentState.szSerialNumber,
                m_mctdCurrentState.uChannelID );
         TRACE1("open connection to 0x%08X\n", wParam);
      }
      else
      {
         // failed to add sender's HWND to client list
         // no free slots available
         TRACE2("server(%s,%d): ",
                m_mctdCurrentState.szSerialNumber,
                m_mctdCurrentState.uChannelID );
         TRACE1("open failed for 0x%08X: no free slots\n", wParam);
         return TRUE;
      }

      if( IsWindow( (HWND) wParam ) )
      {
         // HWND is valid, send telegraph packet
         COPYDATASTRUCT cpds;
         cpds.dwData = (DWORD) s_uMCTGRequestMessage;
         cpds.cbData = sizeof(MC_TELEGRAPH_DATA);
         cpds.lpData = &m_mctdCurrentState;

         ::SendMessage ( (HWND) wParam,
                         WM_COPYDATA ,
                         NULL, 
                         (LPARAM) &cpds );

         return TRUE;
      }
      else
      {
         // invalid HWND, remove from client list
         TRACE2("server(%s,%d): ",
                m_mctdCurrentState.szSerialNumber,
                m_mctdCurrentState.uChannelID );
         TRACE1("invalid HWND, removing 0x%08X\n", m_ClientHwndList[uX]);
         m_ClientHwndList[uX] = NULL;
         return TRUE;
      }
   }

   // process telegraph request message
   // *do not* add the sender's HWND to the client list
   // simply send a telegraph packet to that HWND
   if( message == s_uMCTGRequestMessage )
   {
      UINT uSerialNum = atoi(m_mctdCurrentState.szSerialNumber);
      UINT uChannelID = m_mctdCurrentState.uChannelID;
      if( !MCTG_Match700BSignalIDs( uSerialNum,
                                    uChannelID,
                                    lParam      ) )
      {
         // this request is for another MultiClamp device / channel
         // ignore it
         return TRUE;
      }

      ASSERT(wParam != NULL);

      COPYDATASTRUCT cpds;
      cpds.dwData = (DWORD) s_uMCTGRequestMessage;
      cpds.cbData = sizeof(MC_TELEGRAPH_DATA);
      cpds.lpData = &m_mctdCurrentState;

      TRACE2("server(%s,%d): ",
             m_mctdCurrentState.szSerialNumber,
             m_mctdCurrentState.uChannelID );
      TRACE1("service packet request from 0x%08X\n", wParam);

      ::SendMessage ( (HWND) wParam,
                      WM_COPYDATA ,
                      NULL, 
                      (LPARAM) &cpds  ); 

      return TRUE;
   }

   // process timer message
   // send a telegraph packet to all HWNDS
   // in the recipient list
   if( ( message      == WM_TIMER        ) &&
       ( wParam       == cuTimerEventID  )    )
   {
      COPYDATASTRUCT cpds;
      cpds.dwData = (DWORD) s_uMCTGRequestMessage;
      cpds.cbData = sizeof(MC_TELEGRAPH_DATA);
      cpds.lpData = &m_mctdCurrentState;

      const UINT cuNumUnitsIDs = 8;
      m_mctdCurrentState.uOperatingMode       = s_uDummyData % MCTG_MODE_NUMCHOICES;
      m_mctdCurrentState.uScaledOutSignal     = s_uDummyData % AXMCD_OUT_NAMES_NUMCHOICES;
      m_mctdCurrentState.uRawOutSignal        = s_uDummyData % AXMCD_OUT_NAMES_NUMCHOICES;
      m_mctdCurrentState.dAlpha               = 1.0e+00 + (s_uDummyData % 2000);
      m_mctdCurrentState.dSecondaryAlpha      = 1.0e+00 + (s_uDummyData % 100);
      m_mctdCurrentState.dScaleFactor         = 5.0e-02 * pow(10.0, (s_uDummyData % 4) );
      m_mctdCurrentState.uScaleFactorUnits    = s_uDummyData % cuNumUnitsIDs;
      m_mctdCurrentState.dRawScaleFactor      = 5.0e-02 * pow(10.0, (s_uDummyData % 4) );
      m_mctdCurrentState.uRawScaleFactorUnits = s_uDummyData % cuNumUnitsIDs;
      m_mctdCurrentState.dLPFCutoff           = 1.0e+02 * (s_uDummyData %  321);
      m_mctdCurrentState.dSecondaryLPFCutoff  = 2.0e+04 * (s_uDummyData % 2) + 1.0e+04;
      m_mctdCurrentState.dMembraneCap         = 1.0e-14 * (s_uDummyData % 1001);

      // dummy version data
      UINT uMajor  = s_uDummyData % 10;
      UINT uMinor  = s_uDummyData % 4;;
      UINT uBugFix = s_uDummyData % 6;;
      UINT uBuild  = s_uDummyData % 100;
      sprintf( m_mctdCurrentState.szAppVersion, "%1d.%1d.%1d.%2.2d", uMajor, uMinor, uBugFix, uBuild );
      sprintf( m_mctdCurrentState.szFirmwareVersion, "%1d.%1d.%1d.%2.2d", uMajor, uMinor, uBugFix, uBuild );
      sprintf( m_mctdCurrentState.szDSPVersion, "%1d.%1d.%1d.%2.2d", uMajor, uMinor, uBugFix, uBuild );

      switch( m_mctdCurrentState.uOperatingMode )
      {
         case MCTG_MODE_VCLAMP:
         {
            m_mctdCurrentState.dExtCmdSens = 1.0e-3  * (s_uDummyData % 101);
            break;
         }
         case MCTG_MODE_ICLAMP:
         {
            m_mctdCurrentState.dExtCmdSens = 1.0e-9  * (s_uDummyData % 101);
            break;
         }
         case MCTG_MODE_ICLAMPZERO:
         {
            // all command signals disabled for I=0
            m_mctdCurrentState.dExtCmdSens = 0.0;
            break;
         }
         default:
         {
            m_mctdCurrentState.dExtCmdSens = 0.0;
            break;
         }
      }

      // iterate over client list and send telegraph packet
      // to each valid HWND
      for(UINT uX = 0; uX < MCTG_MAX_CLIENTS; ++ uX)
      {
         if( m_ClientHwndList[uX] != NULL )
         {
            if( IsWindow( m_ClientHwndList[uX] ) )
            {
               // HWND is valid, send telegraph packet
               TRACE2("server(%s,%d): ",
                      m_mctdCurrentState.szSerialNumber,
                      m_mctdCurrentState.uChannelID );
               TRACE1("send telegraph packet to 0x%08X\n", m_ClientHwndList[uX]);

               ::SendMessage ( m_ClientHwndList[uX],
                               WM_COPYDATA ,
                               NULL, 
                               (LPARAM) &cpds        );
            }
            else
            {
               // invalid HWND, remove from client list
               TRACE2("server(%s,%d): ",
                      m_mctdCurrentState.szSerialNumber,
                      m_mctdCurrentState.uChannelID );
               TRACE1("invalid HWND, removing 0x%08X\n", m_ClientHwndList[uX]);
               m_ClientHwndList[uX] = NULL;
            }
         }
      }

      ++s_uDummyData;
      return TRUE;
   }


   // process telegraph close message
   // delete the sender's HWND from the recipient list
   if( message == s_uMCTGCloseMessage )
   {
      UINT uSerialNum = atoi(m_mctdCurrentState.szSerialNumber);
      UINT uChannelID = m_mctdCurrentState.uChannelID;
      if( !MCTG_Match700BSignalIDs( uSerialNum,
                                    uChannelID,
                                    lParam      ) )
      {
         // this request is for another MultiClamp device / channel
         // ignore it
         return TRUE;
      }

      // remove the sender's HWND from the client list
      ASSERT(wParam != NULL);
      BOOL bSuccess = FALSE;
      for( UINT uX = 0; uX < MCTG_MAX_CLIENTS; ++ uX )
      {
         if( m_ClientHwndList[uX] == (HWND) wParam )
         {
            TRACE2("server(%s,%d): ",
                   m_mctdCurrentState.szSerialNumber,
                   m_mctdCurrentState.uChannelID ); 
            TRACE1("close connection to 0x%08X\n", m_ClientHwndList[uX]);
            m_ClientHwndList[uX] = NULL;
            bSuccess = TRUE;
            break;
         }
      }

      if( !bSuccess )
      {
         // failed to remove sender's HWND from client list
         // matching value not found
         TRACE2("server(%s,%d): ",
                m_mctdCurrentState.szSerialNumber,
                m_mctdCurrentState.uChannelID );
         TRACE1("connection to 0x%08X not found\n", wParam);
         return TRUE;
      }

      return TRUE;
   }

   // process telegraph broadcast message
   // respond to sender with an id message
   if( message == s_uMCTGBroadcastMessage )
   {
      UINT uSerialNum = atoi(m_mctdCurrentState.szSerialNumber);
      UINT uChannelID = m_mctdCurrentState.uChannelID;
      LPARAM lparamSignalIDs = MCTG_Pack700BSignalIDs( uSerialNum,
                                                       uChannelID  );

      BOOL bSuccess = ::PostMessage( (HWND) wParam,
                                     s_uMCTGIdMessage,
                                     (WPARAM)m_hWnd,
                                     lparamSignalIDs  );

      if( !bSuccess )
      {
         // failed to post ID message
         TRACE2("server(%s,%d): ",
                m_mctdCurrentState.szSerialNumber,
                m_mctdCurrentState.uChannelID );
         TRACE1("connection to 0x%08X not found\n", wParam);
         return TRUE;
      }

      return TRUE;
   }

	return CDialog::WindowProc(message, wParam, lParam);
}
Exemplo n.º 16
0
static void receiver_receive(receiver_t *self, bytecode_stream_t *message,
                             context_t *context)
{
    atom_t selector;
    message_fifo_t *fifo;
    message_node_t *node;
    node_iterator_t it;

    if (!message || !message->end) {
        WARNING1("message === NULL");
        return;
    }

    selector = message->end->code.verb;
    fifo = get_fifo(self, selector);
    node = calloc(sizeof(message_node_t), 1);

    if (!fifo)
        fifo = add_fifo(self, selector);

    if (fifo->closed_p) {
        /* destroy the message and the context objects */
        bytecode_stream_retire(message);
        context_retire(context);

        return;
    }

    /*
       insert message in the right position

       messages are ordered by decreasing context from beginning to end.
    */
    if (get_node_iterator(fifo, &it)) {
        message_node_t *current = NULL;
        message_node_t *last = NULL;

        TRACE3("adding at: %f in fifo: %s", context->ms,
               atom_get_cstring_value(fifo->atom));

        while ((current = node_iterator_next(&it)) &&
               context->is_in(context, current->context)) {
            /* advance until context is not anymore in current context */
            TRACE2("current at: %f", current->context->ms);
            last = current;
        }

        if (last == NULL) {
            if (fifo->end == NULL) {
                TRACE1("append to empty fifo");
                node->next = node;
                node->prev = node;
                fifo->end = node;
            } else {
                if (context->is_in(context, current->context)) {
                    TRACE2("insert after current at %f", current->context->ms);
                    node->prev = current;
                    node->next = current->next;
                    current->next = node;
                    node->next->prev = node;
                } else {
                    TRACE2("insert before current at %f", current->context->ms);
                    node->next = current;
                    node->prev = current->prev;
                    current->prev = node;
                    node->prev->next = node;
                }
                if (current == fifo->end)
                    fifo->end = node;
            }
        } else {
            if (context->is_in(context, last->context)) {
                TRACE2("insert after last at %f", last->context->ms);
                node->prev = last;
                node->next = last->next;
                last->next = node;
                node->next->prev = node;
            } else {
                TRACE2("insert before last at %f", last->context->ms);
                node->next = last;
                node->prev = last->prev;
                last->prev = node;
                node->prev->next = node;
            }
            if (last == fifo->end)
                fifo->end = node;
        }
    }
    node->bytecodes = message;
    node->context = context;
    node->dispatched_p = 0;

    if (node->context->dispatch_now_p) {
        self->eval(self, node->bytecodes, node->context);
        node->dispatched_p = 1;
    }
}
Exemplo n.º 17
0
void CTraceClipboardData::SendOut(LPCSTR pszData)
{
	int nLength;
	if (pszData == NULL || (nLength = lstrlenA(pszData)) == 0)
		return;

	// send it to TRACE (can be redirected)
	if (m_dwTarget & AFX_STACK_DUMP_TARGET_TRACE)
		TRACE1("%hs", pszData);

	// send it to OutputDebugString() (can't redirect)
	if (m_dwTarget & AFX_STACK_DUMP_TARGET_ODS)
		OutputDebugStringA(pszData);

	// build a buffer for the clipboard
	if (m_dwTarget & AFX_STACK_DUMP_TARGET_CLIPBOARD)
	{
		if (m_hMemory == NULL)
		{
		   m_hMemory = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, 1024);
			if (m_hMemory == NULL)
			{
				TRACE0("AfxDumpStack Error: No memory available for clipboard.\n");
				m_dwTarget &= ~AFX_STACK_DUMP_TARGET_CLIPBOARD;
			}
			else
			{
				m_dwUsed = nLength;
				m_dwSize = 1024;
				LPSTR pstr = (LPSTR) GlobalLock(m_hMemory);
				if (pstr != NULL)
				{
					lstrcpyA(pstr, pszData);
					GlobalUnlock(m_hMemory);
				}
				else
				{
					TRACE0("AfxDumpStack Error: Couldn't lock memory!\n");
					GlobalFree(m_hMemory);
					m_hMemory = NULL;
					m_dwTarget &= ~AFX_STACK_DUMP_TARGET_CLIPBOARD;
				}
			}
		}
		else
		{
			if ((m_dwUsed + nLength + 1) >= m_dwSize)
			{
				// grow by leaps and bounds
				m_dwSize *= 2;
				if (m_dwSize > (1024L*1024L))
				{
					TRACE0("AfxDumpStack Error: more than one megabyte on clipboard.\n");
					m_dwTarget &= ~AFX_STACK_DUMP_TARGET_CLIPBOARD;
				}

				HGLOBAL hMemory = GlobalReAlloc(m_hMemory, m_dwSize, GMEM_MOVEABLE);
				if (hMemory == NULL)
				{
					TRACE1("AfxDumpStack Error: Couldn't get %d bytes!\n", m_dwSize);
					m_dwTarget &= ~AFX_STACK_DUMP_TARGET_CLIPBOARD;
				}
				else
					m_hMemory = hMemory;
			}

			LPSTR pstr = (LPSTR) GlobalLock(m_hMemory);
			if (pstr != NULL)
			{
				lstrcpyA(pstr + m_dwUsed, pszData);
				m_dwUsed += nLength;
				GlobalUnlock(m_hMemory);
			}
			else
			{
				TRACE0("AfxDumpStack Error: Couldn't lock memory!\n");
				m_dwTarget &= ~AFX_STACK_DUMP_TARGET_CLIPBOARD;
			}
		}
	}

	return;
}
Exemplo n.º 18
0
BOOL CSqlCommand::bind(void)
{  
	ASSERT(m_pCursor->isConnected());
	
	if (!m_bCompiled){
		TRACE0("can't bind until compiled\n");
		return FALSE;
		}
	
	if (m_pBinds->GetSize() < m_nBindsNeeded){
		TRACE0("can't bind - too few binds !\n");		
		return FALSE;
		}

#ifdef _DEBUG
	if (m_bBound)
		TRACE0("already bound...\n");
	else
		TRACE0("binding...\n");		
#endif	
	
	if (!m_bBound){
		
		// first make sure we're cleared from any previous binds..
		if(::sqlcbv(*m_pCursor)){
			cleanUp();
			THROW(new CSqlCsrException(*m_pCursor));
			}
		
		ASSERT_VALID(m_pBinds);
			
		for (int j = 0 ; j < m_nBindsNeeded ; j++){ 
		    
		    CSqlType* pItem = (CSqlType*)m_pBinds->GetAt(j);
		    
    		switch(pItem->m_ObjType){  
    			case CSqlType::csqlInt: 
    				TRACE2("int bind[%d] = %d\n", j, (int)*(CSqlNumber*)pItem); 
    				break;
    			case CSqlType::csqlShort: 
    				TRACE2("short bind[%d] = %hd\n", j, (short)*(CSqlNumber*)pItem); 
    				break;
    			case CSqlType::csqlUInt:
   					TRACE2("unsigned int bind[%d] = %u\n", j, (unsigned int)*(CSqlNumber*)pItem); 
    				break;    
    			case CSqlType::csqlUShort:
    				TRACE2("unsigned short bind[%d] = %hu\n", j, (unsigned short)*(CSqlNumber*)pItem); 
    				break;    
    			case CSqlType::csqlDouble:
					TRACE2("double bind[%d] = %lf\n", j, (double)*(CSqlNumber*)pItem);    	
					break;
    			case CSqlType::csqlFloat:
					TRACE2("float bind[%d] = %f\n", j, (float)*(CSqlNumber*)pItem);    	
					break;
				case CSqlType::csqlLong:
					TRACE2("long bind[%d] = %ld\n", j, (long)*(CSqlNumber*)pItem);    	
					break;
				case CSqlType::csqlULong:	
					TRACE2("unsigned long bind[%d] = %lu\n", j, (unsigned long)*(CSqlNumber*)pItem);    	
					break; 
				case CSqlType::csqlString:
					TRACE2("string bind[%d] = %s\n", j, (const char *)*(CSqlString*)pItem);						
					break; 
				case CSqlType::csqlIntNum:
					TRACE1("internal numeric bind[%d]\n", j);
					break;    
				case CSqlType::csqlIntDate:
					TRACE1("internal date bind[%d]\n", j);
					break;  
				case CSqlType::csqlDateTime:
					TRACE2("date/time bind[%d] = %s\n", j, (const char *)(((CSqlDateTime*)pItem)->asSqlTimeStr()));						
					break; 
				case CSqlType::csqlLongVarChar: 
					TRACE1("long varchar bind[%d]\n", j);
					continue;	// will do it separately..					
				default:
					TRACE1("unknown bind[%d] !\n", j); 
					ASSERT(FALSE);
					break;
				}			    			
		    
			SQLTDAP buff = pItem->dataBuffer();
			
			SQLTDAL len =  (SQLTDAL)pItem->dataLength();
			
		    SQLTPDT type = pItem->m_BindType;
		    
		    ASSERT(::AfxIsValidAddress(buff, len));
		    
			if(::sqlbnn(*m_pCursor, j+1, buff, len, 0, type)){
				cleanUp();
				THROW(new CSqlCsrException(*m_pCursor));
				}
				
			}// bind loop..
			
		}// if !bound       

	return (m_bBound = TRUE);		
}       
Exemplo n.º 19
0
/** 
 * \fn     mgmtQueuesSM
 * \brief  The module state-machine (static function)
 * 
 * The SM follows the system management states (see ETxConnState) and the Mgmt queues
 *   status (empty or not), and contorls the Tx queues flow accordingly (mgmt and data queues).
 * For detailed explanation, see the Tx-Path LLD document!
 * 
 * \note   To avoid recursion issues, all SM actions are done at the end of the function, 
 *            since some of them may invoke the SM again.
 * \param  pTxMgmtQ - The module's object                                          
 * \param  eSmEvent - The event to act upon                                          
 * \return void 
 * \sa     txMgmtQ_SetConnState
 */ 
static void mgmtQueuesSM (TTxMgmtQ *pTxMgmtQ, ESmEvent eSmEvent)
{
	ESmState  ePrevState = pTxMgmtQ->eSmState;
	ESmAction eSmAction  = SM_ACTION_NULL;

	switch(eSmEvent)
	{
		case SM_EVENT_CLOSE:
			/* 
			 * Tx link is closed (expected in any state), so disable both mgmt queues  
			 *   and if data-queues are active disable them via txPort module.
			 */
			pTxMgmtQ->eSmState = SM_STATE_CLOSE;
			pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_MGMT]  = TI_FALSE;
			pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_EAPOL] = TI_FALSE;
			if (ePrevState == SM_STATE_OPEN_DATA)
				eSmAction = SM_ACTION_ENABLE_MGMT;
			break;

		case SM_EVENT_MGMT:
			/* 
			 * Only Mgmt packets are permitted (expected from any state):
			 *   - Enable the mgmt queue and disable the Eapol queue.
			 *   - If data-queues are active disable them via txPort (this will run the scheduler).
			 *   - Else run the scheduler (to send mgmt packets if waiting).
			 */
			pTxMgmtQ->eSmState = SM_STATE_MGMT;
			pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_MGMT]  = TI_TRUE;
			pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_EAPOL] = TI_FALSE;
			if (ePrevState == SM_STATE_OPEN_DATA)
				eSmAction = SM_ACTION_ENABLE_MGMT;
			else
				eSmAction = SM_ACTION_RUN_SCHEDULER;
			break;

		case SM_EVENT_EAPOL:
			/* 
			 * EAPOL packets are also permitted (expected in MGMT or CLOSE state), so enable the 
			 *   EAPOL queue and run the scheduler (to send packets from EAPOL queue if waiting).
			 */
			if ( (ePrevState != SM_STATE_CLOSE) && (ePrevState != SM_STATE_MGMT) )
			{
TRACE1(pTxMgmtQ->hReport, REPORT_SEVERITY_ERROR, "mgmtQueuesSM: Got SmEvent=EAPOL when eSmState=%d\n", ePrevState);
			}
			pTxMgmtQ->eSmState = SM_STATE_EAPOL;
			pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_MGMT]  = TI_TRUE;
			pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_EAPOL] = TI_TRUE;
			eSmAction = SM_ACTION_RUN_SCHEDULER;
			break;

		case SM_EVENT_OPEN:
			/* 
			 * All packets are now permitted (expected in EAPOL state), so if the mgmt-queues
			 *   are empty disable them and enable the data queues via txPort module.
			 */
			if (ePrevState != SM_STATE_EAPOL)
			{
TRACE1(pTxMgmtQ->hReport, REPORT_SEVERITY_ERROR, "mgmtQueuesSM: Got SmEvent=OPEN when eSmState=%d\n", ePrevState);
			}
			if ( ARE_ALL_MGMT_QUEUES_EMPTY(pTxMgmtQ->aQueues) )
			{
				pTxMgmtQ->eSmState = SM_STATE_OPEN_DATA;
				pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_MGMT]  = TI_FALSE;
				pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_EAPOL] = TI_FALSE;
				eSmAction = SM_ACTION_ENABLE_DATA;
			}
			else
			{
				pTxMgmtQ->eSmState = SM_STATE_OPEN_MGMT;
			}
			break;

		case SM_EVENT_QUEUES_EMPTY:
			/* 
			 * The mgmt-queues are empty, so if in OPEN_MGMT state disable the 
			 *   mgmt-queues and enable the data-queues via txPort module.
			 */
			if (ePrevState == SM_STATE_OPEN_MGMT)
			{
				pTxMgmtQ->eSmState = SM_STATE_OPEN_DATA;
				pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_MGMT]  = TI_FALSE;
				pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_EAPOL] = TI_FALSE;
				eSmAction = SM_ACTION_ENABLE_DATA;
			}
			else
			{
				/* This may happen so it's just a warning and not an error. */
TRACE1(pTxMgmtQ->hReport, REPORT_SEVERITY_WARNING, "mgmtQueuesSM: Got SmEvent=QUEUES_EMPTY when eSmState=%d\n", ePrevState);
			}
			break;

		case SM_EVENT_QUEUES_NOT_EMPTY:

			/* A packet was inserted to the mgmt-queues */

			/* 
			 * If in OPEN_DATA state, enable mgmt-queues and disable data-queues via txPort module.
			 *
			 * Note: The scheduler is not run here because the txPort will call
			 *   txMgmtQueue_wakeAll() which will run the scheduler.
			 */
			if (ePrevState == SM_STATE_OPEN_DATA)
			{
				pTxMgmtQ->eSmState = SM_STATE_OPEN_MGMT;
				pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_MGMT]  = TI_TRUE;
				pTxMgmtQ->aQueueEnabledBySM[QUEUE_TYPE_EAPOL] = TI_TRUE;
				eSmAction = SM_ACTION_ENABLE_MGMT;
			}

			/* 
			 * If in MGMT or EAPOL state, run the scheduler to transmit the packet.
			 */
			else if ( (ePrevState == SM_STATE_MGMT) || (ePrevState == SM_STATE_EAPOL) )
			{
				eSmAction = SM_ACTION_RUN_SCHEDULER;
			}

			else
			{
				/* This may happen so it's just a warning and not an error. */
TRACE1(pTxMgmtQ->hReport, REPORT_SEVERITY_WARNING, "mgmtQueuesSM: Got SmEvent=QUEUES_NOT_EMPTY when eSmState=%d\n", ePrevState);
			}
			break;

		default:
TRACE1(pTxMgmtQ->hReport, REPORT_SEVERITY_ERROR, "mgmtQueuesSM: Unknown SmEvent = %d\n", eSmEvent);
			break;
	}

TRACE6( pTxMgmtQ->hReport, REPORT_SEVERITY_INFORMATION, "mgmtQueuesSM: <currentState = %d, event = %d> --> nextState = %d, action = %d, MgmtQueEnbl=%d, EapolQueEnbl=%d\n", ePrevState, eSmEvent, pTxMgmtQ->eSmState, eSmAction, pTxMgmtQ->aQueueEnabledBySM[0], pTxMgmtQ->aQueueEnabledBySM[1]);

	/* 
	 * Execute the required action. 
	 * Note: This is done at the end of the SM because it may start a sequence that will call the SM again!
	 */
	switch (eSmAction)
	{
		case SM_ACTION_NULL:
			break;

		case SM_ACTION_ENABLE_DATA:
			txPort_enableData(pTxMgmtQ->hTxPort);
			break;

		case SM_ACTION_ENABLE_MGMT:
			txPort_enableMgmt(pTxMgmtQ->hTxPort);
			break;

		case SM_ACTION_RUN_SCHEDULER:
			runScheduler(pTxMgmtQ);
			break;

		default:
TRACE1(pTxMgmtQ->hReport, REPORT_SEVERITY_ERROR, ": Unknown SmAction = %d\n", eSmAction);
			break;
	}
}
/************************************************************************
 *                        findAndInsertSiteEntry									*
 ************************************************************************
DESCRIPTION: Perform the following things:
			-	Compute the site's hash entry based on the site BSSID and hash function
			-	Look for the site entry in the linked list pointed by the hash entry
			-	If the site is found in the site table, returns a pointer to the site entry
			-	If the site is not found in the site table, tries to add the site
				-	If succeeds, returns a pointer to the site entry
				-	Otherwise, returns NULL

INPUT:      pSiteMgr	-	Handle to site mgr
			mac			-	The site BSSID
            band        -   The site band


OUTPUT:

RETURN:     Pointer to the site entry if site found/inserted, NULL otherwise

************************************************************************/
siteEntry_t	*findAndInsertSiteEntry(siteMgr_t		*pSiteMgr,
                                    TMacAddr    	*mac,
                                    ERadioBand      band)
{
	TI_UINT8             i, emptySiteIndex=0, nextSite2Remove=0;
	siteEntry_t         *pSiteEntry, *pPrimarySite=pSiteMgr->pSitesMgmtParams->pPrimarySite;
	sitesMgmtParams_t   *pSitesMgmtParams  = pSiteMgr->pSitesMgmtParams;
	siteTablesParams_t  *pCurrentSiteTable;
	TI_BOOL              firstEmptySiteFound = TI_FALSE;
	TI_UINT32            oldestTS;


	/* choose site table according to AP's band */
	if ( RADIO_BAND_2_4_GHZ == band ) {
		pCurrentSiteTable = &(pSitesMgmtParams->dot11BG_sitesTables);
	} else if (RADIO_BAND_5_0_GHZ == band) {
		pCurrentSiteTable = (siteTablesParams_t*) &(pSitesMgmtParams->dot11A_sitesTables);
	} else {
		TRACE1(pSiteMgr->hReport, REPORT_SEVERITY_ERROR, "Bad band: %d\n\n", band);
		pCurrentSiteTable = &(pSitesMgmtParams->dot11BG_sitesTables);
	}

	/* Set the first TS to a site which is not the Primary site */
	if (pPrimarySite != &(pCurrentSiteTable->siteTable[0])) {
		oldestTS = pCurrentSiteTable->siteTable[0].localTimeStamp;
	} else {
		oldestTS = pCurrentSiteTable->siteTable[1].localTimeStamp;
	}
	/* It looks like it never happens. Anyway decided to check */
	if ( pCurrentSiteTable->maxNumOfSites > MAX_SITES_BG_BAND ) {
		TRACE2( pSiteMgr->hReport, REPORT_SEVERITY_ERROR,
		        "findAndInsertSiteEntry. pCurrentSiteTable->maxNumOfSites=%d exceeds the limit %d\n",
		        pCurrentSiteTable->maxNumOfSites, MAX_SITES_BG_BAND);
		handleRunProblem(PROBLEM_BUF_SIZE_VIOLATION);
		return NULL;
	}
	/* Loop all the sites till the desired MAC is found */
	for (i = 0; i < pCurrentSiteTable->maxNumOfSites; i++) {
		pSiteEntry = &(pCurrentSiteTable->siteTable[i]);

		if (MAC_EQUAL (pSiteEntry->bssid, *mac)) {

			TRACE6(pSiteMgr->hReport, REPORT_SEVERITY_INFORMATION, "FIND success, bssid: %X-%X-%X-%X-%X-%X\n\n", (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5]);

			return pSiteEntry;
		} else if (pSiteEntry->siteType == SITE_NULL) {
			/* Save the first empty site, in case the
			desired MAC is not found */
			if (!firstEmptySiteFound) {
				emptySiteIndex = i;
				firstEmptySiteFound=TI_TRUE;
			}

		} else if (oldestTS == pSiteEntry->localTimeStamp) {
			/* Save the oldest site's index, according to TS */
			nextSite2Remove = i;
		}
	}

	TRACE4(pSiteMgr->hReport, REPORT_SEVERITY_INFORMATION, "INSERT failure, no free entry!, oldestTS=%d, nextSite2Remove=%d, "
	       "[0].localTimeStamp=%d, [1]localTimeStamp%d \n",
	       oldestTS, nextSite2Remove,
	       pCurrentSiteTable->siteTable[0].localTimeStamp,
	       pCurrentSiteTable->siteTable[1].localTimeStamp);

	if ((!firstEmptySiteFound) || (pCurrentSiteTable->numOfSites>=pCurrentSiteTable->maxNumOfSites)) {
		/* No NULL entry has been found. Remove the oldest site */
		pSiteEntry =  &(pCurrentSiteTable->siteTable[nextSite2Remove]);
		TRACE9(pSiteMgr->hReport, REPORT_SEVERITY_INFORMATION, "INSERT failure, no free entry!, numOfSites=%d, removing site index=%d,\n                                bssid: %X-%X-%X-%X-%X-%X, ts=%d \n", pCurrentSiteTable->numOfSites, nextSite2Remove, pSiteEntry->bssid[0], pSiteEntry->bssid[1], pSiteEntry->bssid[2], pSiteEntry->bssid[3], pSiteEntry->bssid[4], pSiteEntry->bssid[5], pSiteEntry->localTimeStamp);
		removeSiteEntry(pSiteMgr, pCurrentSiteTable, pSiteEntry);
		emptySiteIndex = nextSite2Remove;

	}


	pCurrentSiteTable->numOfSites++;

	pSiteEntry = &(pCurrentSiteTable->siteTable[emptySiteIndex]);

	/* fill the entry with the station mac */
	MAC_COPY (pSiteEntry->bssid, *mac);

	/* Some parameters have to be initialized immediately after entry allocation */

	if(pSiteMgr->siteMgrOperationalMode == DOT11_G_MODE)
		pSiteEntry->currentSlotTime = pSiteMgr->pDesiredParams->siteMgrDesiredSlotTime;

	TRACE8(pSiteMgr->hReport, REPORT_SEVERITY_INFORMATION, "INSERT success, bssid: %X-%X-%X-%X-%X-%X, band=%d, index=%d\n\n", (*mac)[0], (*mac)[1], (*mac)[2], (*mac)[3], (*mac)[4], (*mac)[5], band, emptySiteIndex);


	return pSiteEntry;
}
Exemplo n.º 21
0
// **** Audio card support
// Aquire and enabled audio card
// return 0 if ok, -1 if failed
int HAE_AquireAudioCard(void *context, UINT32 sampleRate, UINT32 channels, UINT32 bits) {
    int flag;
    short int count;
    INT32 error;
    audio_info_t sunAudioHeader;
    char* pAudioDev = HAE_GetAudioDevPlay(g_currentDeviceID, 0);
	
    flag = 0;
    g_activeDoubleBuffer = FALSE;
    g_shutDownDoubleBuffer = TRUE;

    g_audioFramesToGenerate = HAE_GetMaxSamplePerSlice();	// get number of frames per sample rate slice

    // we're going to build this many buffers at a time
    g_synthFramesPerBlock = HAE_SOLARIS_FRAMES_PER_BLOCK;
    g_audioPeriodSleepTime = HAE_SOLARIS_SOUND_PERIOD;
    g_bitSize = bits;
    g_channels = channels;
    if (bits == 8) {
	g_audioByteBufferSize = ((INT32)sizeof(char) * g_audioFramesToGenerate);
    } else {
	g_audioByteBufferSize = ((INT32)sizeof(short int) * g_audioFramesToGenerate);
    }
    g_audioByteBufferSize *= channels;

    flag = 1;
    // allocate buffer blocks
    g_audioBufferBlock = HAE_Allocate(g_audioByteBufferSize * HAE_SOLARIS_FRAMES_PER_BLOCK);
    if (g_audioBufferBlock) {
	// try to open wave device
	// $$kk: 12.17.97: need O_NONBLOCK flag to be compatible with windows
#ifdef __linux__
            g_waveDevice = open(pAudioDev,O_WRONLY);
#else
            g_waveDevice = open(pAudioDev,O_WRONLY|O_NONBLOCK);
#endif

	if (g_waveDevice > 0) {

	    /* set to multiple open */
	    if (ioctl(g_waveDevice, AUDIO_MIXER_MULTIPLE_OPEN, NULL) >= 0) {
		TRACE1("HAE_AquireAudioCard: %s set to multiple open\n", pAudioDev);
	    } else {
		ERROR1("HAE_AquireAudioCard: ioctl AUDIO_MIXER_MULTIPLE_OPEN failed on %s!\n", pAudioDev);
	    }

	    AUDIO_INITINFO(&sunAudioHeader);
	    // $$kk: 12.17.97: need AUDIO_GETINFO ioctl to get this to work on solaris x86 
	    // add next 1 line
	    error = ioctl(g_waveDevice, AUDIO_GETINFO, &sunAudioHeader);

	    // $$kk: 03.16.98: not valid to call AUDIO_SETINFO ioctl with all the fields from AUDIO_GETINFO,
	    // so let's try init'ing again....
	    AUDIO_INITINFO(&sunAudioHeader);

	    // Set rendering format of the sun device.
	    sunAudioHeader.play.sample_rate = sampleRate;
	    sunAudioHeader.play.precision = bits;
	    sunAudioHeader.play.channels = channels;
	    sunAudioHeader.play.encoding = AUDIO_ENCODING_LINEAR;
		
	    error = ioctl(g_waveDevice, AUDIO_SETINFO, &sunAudioHeader);

	    if (error == 0) {
		g_shutDownDoubleBuffer = FALSE;
		g_activeDoubleBuffer = TRUE;	// must enable process, before thread begins


				/* Spin threads for device service and possibly
				 * stream service.
				 */
				// create thread to manage and render audio frames
		error = HAE_CreateFrameThread(context, PV_AudioWaveOutFrameThread);

		if (error == 0) {	// ok
		    flag = 0;
#ifdef USE_RAWDATA_CHECK
		    { 
			char* fname = "javasound_debug_output.pcm";
			debugrawfile = HAE_FileOpenForWrite(fname);
		    }
#endif

		} else {
		    flag = 1;
		    g_activeDoubleBuffer = FALSE;
		}
	    }
	}
    }

    if (flag) {	// something failed
	HAE_ReleaseAudioCard(context);
    }
    return flag;
}
Exemplo n.º 22
0
TI_STATUS mlme_assocRecv(TI_HANDLE hMlme, mlmeFrameInfo_t *pFrame)
{
    TI_STATUS       status = TI_OK;
	mlme_t			*pMlme = (mlme_t*)hMlme;
    assoc_t         *pAssoc;
    TTwdParamInfo   tTwdParam;
    TI_UINT16           rspStatus;

    if (pMlme == NULL)
    {
        return TI_NOK;
    }

	pAssoc = &(pMlme->assocInfo);

    /* ensure that the SM is waiting for assoc response */
    if(pAssoc->currentState != MLME_SM_STATE_ASSOC_WAIT)
        return TI_OK;


    if ((pFrame->subType != ASSOC_RESPONSE) && (pFrame->subType != RE_ASSOC_RESPONSE))
    {
        return TI_NOK;
    }

    /* check response status */
    rspStatus  = pFrame->content.assocRsp.status;

    if (rspStatus == 0)
    {
        dot11_RSN_t    *pRsnIe;
        TI_UINT8       curRsnData[255];
        TI_UINT8       length = 0;


        TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "MLME_SM: DEBUG Success associating to AP \n");

        /* set AID to HAL */
        tTwdParam.paramType = TWD_AID_PARAM_ID;
        tTwdParam.content.halCtrlAid  = pFrame->content.assocRsp.aid;
        TWD_SetParam (pMlme->hTWD, &tTwdParam);


        /* Get the RSN IE data */
        pRsnIe = pFrame->content.assocRsp.pRsnIe;
        while (length < pFrame->content.assocRsp.rsnIeLen && (pFrame->content.assocRsp.rsnIeLen < 255))
        {
            curRsnData[0+length] = pRsnIe->hdr[0];
            curRsnData[1+length] = pRsnIe->hdr[1];
            os_memoryCopy(pMlme->hOs, &curRsnData[2+length], (void *)pRsnIe->rsnIeData, pRsnIe->hdr[1]);
            length += pRsnIe->hdr[1] + 2;
            pRsnIe += 1;
        }


        /* update siteMgr with capabilities and whether we are connected to Cisco AP */
        siteMgr_assocReport(pMlme->hSiteMgr,
                            pFrame->content.assocRsp.capabilities, pFrame->content.assocRsp.ciscoIEPresent);

        /* update QoS Manager - it the QOS active protocol is NONE, or no WME IE present, it will return TI_OK */
        /* if configured by AP, update MSDU lifetime */
        status = qosMngr_setSite(pMlme->hQosMngr, &pFrame->content.assocRsp);

        if(status != TI_OK)
        {
            TRACE0(pMlme->hReport, REPORT_SEVERITY_ERROR, "MLME_SM: DEBUG - Association failed : qosMngr_setSite error \n");
            /* in case we wanted to work with qosAP and failed to connect to qos AP we want to reassociated again
               to another one */
        	pMlme->mlmeData.mgmtStatus = STATUS_UNSPECIFIED;
        	pMlme->mlmeData.uStatusCode = status;
            mlme_smEvent(pMlme->hMlmeSm, MLME_SM_EVENT_FAIL, pMlme);
        }
        else
        {
            mlme_smEvent(pMlme->hMlmeSm, MLME_SM_EVENT_SUCCESS, pMlme);
        }
    }
    else
    {
        pAssoc->assocRejectCount++;

        /* If there was attempt to renegotiate voice settings, update QoS Manager */
        qosMngr_checkTspecRenegResults(pMlme->hQosMngr, &pFrame->content.assocRsp);

        /* check failure reason */
        switch (rspStatus)
        {
        case 0:
            break;
        case 1:
            /* print debug message */
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Unspecified error \n");
            break;
        case 10:
            /* print debug message */
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Cannot support all requested capabilities in the Capability Information field \n");
            break;
        case 11:
            /* print debug message */
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Reassociation denied due to inability to confirm that association exists \n");
            break;
        case 12:
            /* print debug message */
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Association denied due to reason outside the scope of this standard \n");
            rsn_reportAuthFailure(pMlme->hRsn, RSN_AUTH_STATUS_INVALID_TYPE);
            break;
        case 13:
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Association denied due to wrong authentication algorithm \n");
            rsn_reportAuthFailure(pMlme->hRsn, RSN_AUTH_STATUS_INVALID_TYPE);
            break;
        case 17:
            /* print debug message */
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Association denied because AP is unable to handle additional associated stations \n");
            break;
        case 18:
            /* print debug message */
            TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "ASSOC_SM: DEBUG - Association denied: Association denied due to requesting station not supporting all of the data rates in the BSSBasicRateSet parameter \n");
            break;
        default:
            /* print error message on wrong error code for association response */
            TRACE1(pMlme->hReport, REPORT_SEVERITY_ERROR, "ASSOC_SM: ERROR - Association denied: error code (%d) irrelevant \n", rspStatus);
            break;
        }

       pMlme->mlmeData.mgmtStatus = STATUS_ASSOC_REJECT;
       pMlme->mlmeData.uStatusCode = TI_OK;
       mlme_smEvent(pMlme->hMlmeSm, MLME_SM_EVENT_FAIL, pMlme);
    }

    return status;
}
Exemplo n.º 23
0
/**
 * \fn     scanCncnApp_SetParam
 * \brief  Parses and executes a set param command
 *
 * Parses and executes a set param command (start/stop one-shot/periodic/OS scan)
 *
 * \param  hScanCncn - handle to the scan concentrator object
 * \param  pParam - the param to set
 * \return operation status (OK / NOK / PARAM_NOT_SUPPORTED)
 * \sa     scanCncnApp_GetParam
 */
TI_STATUS scanCncnApp_SetParam (TI_HANDLE hScanCncn, paramInfo_t *pParam)
{
    TScanCncn   *pScanCncn = (TScanCncn*)hScanCncn;
    TI_UINT32   uCurrentTimeStamp;

    TRACE1(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncnApp_SetParam: recevived request of type 0x%x\n", pParam->paramType);

    switch (pParam->paramType)
    {
    case SCAN_CNCN_START_APP_SCAN:

        /* verify that scan is not currently running */
        if (pScanCncn->eCurrentRunningAppScanClient != SCAN_SCC_NO_CLIENT)
        {
            TRACE1(pScanCncn->hReport, REPORT_SEVERITY_WARNING, "scanCncnApp_SetParam: trying to start app one-shot scan when client %d is currently running!\n", pScanCncn->eCurrentRunningAppScanClient);
            /* Scan was not started successfully, send a scan complete event to the user */
            return TI_NOK;
        }

        /* set one-shot scan as running app scan client */
        pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_APP_ONE_SHOT;

        /* Perform aging process before the scan */
        scanResultTable_PerformAging(pScanCncn->hScanResultTable);

        /* start the scan */
        if (SCAN_CRS_SCAN_RUNNING !=
                scanCncn_Start1ShotScan (hScanCncn, SCAN_SCC_APP_ONE_SHOT, pParam->content.pScanParams))
        {
            /* Scan was not started successfully, mark that no app scan is running */
            pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_NO_CLIENT;
            return TI_NOK;
        }
        break;

    case SCAN_CNCN_STOP_APP_SCAN:
        /* verify that scan is currently running */
        if (pScanCncn->eCurrentRunningAppScanClient != SCAN_SCC_NO_CLIENT)
        {
            scanCncn_StopScan (hScanCncn, SCAN_SCC_APP_ONE_SHOT);
        }
        break;

    case SCAN_CNCN_START_PERIODIC_SCAN:
        /* verify that scan is not currently running */
        if (SCAN_SCC_NO_CLIENT != pScanCncn->eCurrentRunningAppScanClient)
        {
            TRACE1(pScanCncn->hReport, REPORT_SEVERITY_WARNING, "scanCncnApp_SetParam: trying to start app periodic scan when client %d is currently running!\n", pScanCncn->eCurrentRunningAppScanClient);
            /* Scan was not started successfully, send a scan complete event to the user */
            return TI_NOK;
        }

        /* set one-shot scan as running app scan client */
        pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_APP_PERIODIC;

        /* Perform aging process before the scan */
        scanResultTable_PerformAging(pScanCncn->hScanResultTable);

        /* start the scan */
        if (SCAN_CRS_SCAN_RUNNING !=
                scanCncn_StartPeriodicScan (hScanCncn, SCAN_SCC_APP_PERIODIC, pParam->content.pPeriodicScanParams))
        {
            TRACE0(pScanCncn->hReport, REPORT_SEVERITY_CONSOLE , "Scan was not started. Verify scan parametrs or SME mode\n");
            WLAN_OS_REPORT (("Scan was not started. Verify scan parametrs or SME mode\n"));

            /* Scan was not started successfully, mark that no app scan is running */
            pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_NO_CLIENT;
            return TI_NOK;
        }
        break;

    case SCAN_CNCN_STOP_PERIODIC_SCAN:
        /* verify that scan is currently running */
        if (pScanCncn->eCurrentRunningAppScanClient != SCAN_SCC_NO_CLIENT)
        {
            scanCncn_StopPeriodicScan (hScanCncn, SCAN_SCC_APP_PERIODIC);
        }
        break;

    case SCAN_CNCN_BSSID_LIST_SCAN_PARAM:
        /* check if OID scans are enabled in the registry */
        if (0 == pScanCncn->tInitParams.uMinimumDurationBetweenOsScans)
        {
            TRACE0(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncnApp_SetParam: received OS scan request when OS scans are disabled, quitting...\n");
            return TI_NOK;
        }

        /* check if the last OID scan didn't start at a shorter duration than the configured minimum */
        uCurrentTimeStamp = os_timeStampMs (pScanCncn->hOS);
        if ( (uCurrentTimeStamp - pScanCncn->uOSScanLastTimeStamp) <
                (pScanCncn->tInitParams.uMinimumDurationBetweenOsScans * 1000) ) /*converted to ms */
        {
            TRACE3(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncnApp_SetParam: last OID scan performed at: %d, now is: %d, min duration is: %d, too early for another scan!\n", pScanCncn->uOSScanLastTimeStamp, uCurrentTimeStamp, pScanCncn->tInitParams.uMinimumDurationBetweenOsScans);
            return TI_NOK;
        }

        /* check that no other scan is currently running */
        if (SCAN_SCC_NO_CLIENT != pScanCncn->eCurrentRunningAppScanClient)
        {
            TRACE1(pScanCncn->hReport, REPORT_SEVERITY_ERROR , "scanCncnApp_SetParam: received OS scan request when client %d is currently running!\n", pScanCncn->eCurrentRunningAppScanClient);
            return TI_NOK;
        }

        /* set one-shot scan as running app scan client */
        pScanCncn->eCurrentRunningAppScanClient = SCAN_SCC_APP_ONE_SHOT;

        /* mark that an OID scan process has started */
        pScanCncn->bOSScanRunning = TI_TRUE;
        pScanCncn->uOSScanLastTimeStamp = uCurrentTimeStamp;
        TRACE0(pScanCncn->hReport, REPORT_SEVERITY_INFORMATION , "scanCncnApp_SetParam: starting OID scan process...\n");

        if(0 != pParam->content.pScanParams->desiredSsid.len)
        {
            pScanCncn->tOsScanParams.desiredSsid.len = pParam->content.pScanParams->desiredSsid.len;
            os_memoryCopy(pScanCncn->hOS, pScanCncn->tOsScanParams.desiredSsid.str, pParam->content.pScanParams->desiredSsid.str, pParam->content.pScanParams->desiredSsid.len);
        }
        else
        {
            pScanCncn->tOsScanParams.desiredSsid.len = 0;
            pScanCncn->tOsScanParams.desiredSsid.str[ 0 ] = '\0'; /* broadcast scan */
        }

        pScanCncn->tOsScanParams.scanType = pParam->content.pScanParams->scanType;

        /* Perform aging process before the scan */
        scanResultTable_PerformAging(pScanCncn->hScanResultTable);

        /* and actually start the scan */
        genSM_Event (pScanCncn->hOSScanSm, SCAN_CNCN_OS_SM_EVENT_START_SCAN, hScanCncn);

        break;

    case SCAN_CNCN_SET_SRA:
        scanResultTable_SetSraThreshold(pScanCncn->hScanResultTable, pParam->content.uSraThreshold);
        break;

    case SCAN_CNCN_SET_RSSI:
        pScanCncn->tInitParams.nRssiThreshold = pParam->content.nRssiThreshold;
        break;

    default:
        TRACE1(pScanCncn->hReport, REPORT_SEVERITY_ERROR , "scanCncnApp_SetParam: unrecognized param type :%d\n", pParam->paramType);
        return PARAM_NOT_SUPPORTED;
    }

    return TI_OK;
}
Exemplo n.º 24
0
TI_STATUS mlme_getParam(TI_HANDLE           hMlme,
                        paramInfo_t         *pParam)
{
    mlme_t *pMlme = (mlme_t *)hMlme;

    switch(pParam->paramType)
    {
    case MLME_LEGACY_TYPE_PARAM:
        pParam->content.mlmeLegacyAuthType = pMlme->authInfo.authType;
        break;

    case MLME_CAPABILITY_PARAM:
        pParam->content.mlmeLegacyAuthType = pMlme->legacyAuthType;
        mlme_assocCapBuild(pMlme, &(pParam->content.siteMgrSiteCapability));
        break;

    case MLME_BEACON_RECV:
        pParam->content.siteMgrTiWlanCounters.BeaconsRecv = pMlme->BeaconsCounterPS;
        break;

	case MLME_AUTH_RESPONSE_TIMEOUT_PARAM:
		pParam->content.authResponseTimeout = pMlme->authInfo.timeout;
		break;

	case MLME_AUTH_COUNTERS_PARAM:
		pParam->content.siteMgrTiWlanCounters.AuthRejects = pMlme->authInfo.authRejectCount;
		pParam->content.siteMgrTiWlanCounters.AuthTimeouts = pMlme->authInfo.authTimeoutCount;
		break;

	case MLME_ASSOC_RESPONSE_TIMEOUT_PARAM:
		pParam->content.assocResponseTimeout = pMlme->assocInfo.timeout;
		break;

	case MLME_ASSOCIATION_REQ_PARAM:
        pParam->content.assocReqBuffer.buffer = pMlme->assocInfo.assocReqBuffer;
        pParam->content.assocReqBuffer.bufferSize = pMlme->assocInfo.assocReqLen;
		pParam->content.assocReqBuffer.reAssoc = pMlme->reAssoc;
        break;

	case MLME_ASSOCIATION_RESP_PARAM:
        pParam->content.assocReqBuffer.buffer = pMlme->assocInfo.assocRespBuffer;
        pParam->content.assocReqBuffer.bufferSize = pMlme->assocInfo.assocRespLen;
		pParam->content.assocReqBuffer.reAssoc = pMlme->assocInfo.reAssocResp;
        break;

	case MLME_ASSOC_COUNTERS_PARAM:
        pParam->content.siteMgrTiWlanCounters.AssocRejects = pMlme->assocInfo.assocRejectCount;
        pParam->content.siteMgrTiWlanCounters.AssocTimeouts = pMlme->assocInfo.assocTimeoutCount;
        break;

	case MLME_ASSOCIATION_INFORMATION_PARAM:
       {
           TI_UINT8  reqBuffIEOffset, respBuffIEOffset;
           TI_UINT32 RequestIELength = 0;
           TI_UINT32 ResponseIELength = 0;
           paramInfo_t  *lParam;
           ScanBssType_enum bssType;

           TRACE0(pMlme->hReport, REPORT_SEVERITY_SM, "MLME: DEBUG - Association Information Get:  \n");
           lParam = (paramInfo_t *)os_memoryAlloc(pMlme->hOs, sizeof(paramInfo_t));
           if (!lParam)
           {
               return TI_NOK;
           }

           /* Assoc exists only in Infrastructure */
           lParam->paramType = CTRL_DATA_CURRENT_BSS_TYPE_PARAM;
           ctrlData_getParam(pMlme->hCtrlData, lParam);
           bssType = lParam->content.ctrlDataCurrentBssType;
           os_memoryFree(pMlme->hOs, lParam, sizeof(paramInfo_t));
           if (bssType != BSS_INFRASTRUCTURE)
           {
               TRACE0(pMlme->hReport, REPORT_SEVERITY_ERROR, "Not in Infrastructure BSS, No ASSOC Info for GET ASSOC_ASSOCIATION_INFORMATION_PARAM\n");
               return TI_NOK;
           }

           /* Init the result buffer to 0 */
           os_memoryZero(pMlme->hOs ,&pParam->content, sizeof(OS_802_11_ASSOCIATION_INFORMATION));

           reqBuffIEOffset  = 4;  /* In Assoc request frame IEs are located from byte 4 */
           respBuffIEOffset = 6;  /* In Assoc response frame the IEs are located from byte 6 */

            /* If the last associate was re-associciation, the current AP MAC address */
            /* is placed before the IEs. Copy it to the result parameters.            */
            if (pMlme->reAssoc)
            {
                MAC_COPY (pParam->content.assocAssociationInformation.RequestFixedIEs.CurrentAPAddress,
                          &pMlme->assocInfo.assocReqBuffer[reqBuffIEOffset]);
                reqBuffIEOffset += MAC_ADDR_LEN;
            }

            /* Calculate length of Info elements in assoc request and response frames */
            if(pMlme->assocInfo.assocReqLen > reqBuffIEOffset)
                RequestIELength = pMlme->assocInfo.assocReqLen - reqBuffIEOffset;

            if(pMlme->assocInfo.assocRespLen > respBuffIEOffset)
                ResponseIELength = pMlme->assocInfo.assocRespLen - respBuffIEOffset;

            /* Copy the association request information */
            pParam->content.assocAssociationInformation.Length = sizeof(OS_802_11_ASSOCIATION_INFORMATION);
            pParam->content.assocAssociationInformation.AvailableRequestFixedIEs = OS_802_11_AI_REQFI_CAPABILITIES | OS_802_11_AI_REQFI_LISTENINTERVAL;
            pParam->content.assocAssociationInformation.RequestFixedIEs.Capabilities = *(TI_UINT16*)&(pMlme->assocInfo.assocReqBuffer[0]);
            pParam->content.assocAssociationInformation.RequestFixedIEs.ListenInterval = *(TI_UINT16*)(&pMlme->assocInfo.assocReqBuffer[2]);

            pParam->content.assocAssociationInformation.RequestIELength = RequestIELength;
            pParam->content.assocAssociationInformation.OffsetRequestIEs = 0;
            if (RequestIELength > 0)
            {
                pParam->content.assocAssociationInformation.OffsetRequestIEs = (TI_UINT32)&pMlme->assocInfo.assocReqBuffer[reqBuffIEOffset];
            }
            /* Copy the association response information */
            pParam->content.assocAssociationInformation.AvailableResponseFixedIEs =
                OS_802_11_AI_RESFI_CAPABILITIES | OS_802_11_AI_RESFI_STATUSCODE | OS_802_11_AI_RESFI_ASSOCIATIONID;
            pParam->content.assocAssociationInformation.ResponseFixedIEs.Capabilities = *(TI_UINT16*)&(pMlme->assocInfo.assocRespBuffer[0]);
            pParam->content.assocAssociationInformation.ResponseFixedIEs.StatusCode = *(TI_UINT16*)&(pMlme->assocInfo.assocRespBuffer[2]);
            pParam->content.assocAssociationInformation.ResponseFixedIEs.AssociationId = *(TI_UINT16*)&(pMlme->assocInfo.assocRespBuffer[4]);
            pParam->content.assocAssociationInformation.ResponseIELength = ResponseIELength;
            pParam->content.assocAssociationInformation.OffsetResponseIEs = 0;
            if (ResponseIELength > 0)
            {
                pParam->content.assocAssociationInformation.OffsetResponseIEs = (TI_UINT32)&pMlme->assocInfo.assocRespBuffer[respBuffIEOffset];
            }
	   }
	   break;
    default:
        TRACE1(pMlme->hReport, REPORT_SEVERITY_ERROR, "Get param, Params is not supported, %d\n\n", pParam->content.mlmeLegacyAuthType);
        return PARAM_NOT_SUPPORTED;
    }

    return TI_OK;
}
/*
  direction has to be either SND_RAWMIDI_STREAM_INPUT or
  SND_RAWMIDI_STREAM_OUTPUT.
  Returns 0 on success. Otherwise, MIDI_OUT_OF_MEMORY, MIDI_INVALID_ARGUMENT
   or a negative ALSA error code is returned.
*/
INT32 openMidiDevice(snd_rawmidi_stream_t direction, INT32 deviceIndex,
                     MidiDeviceHandle** handle) {
    snd_rawmidi_t* native_handle;
    snd_midi_event_t* event_parser = NULL;
    int err;
    UINT32 deviceID;
    char devicename[100];
#ifdef ALSA_MIDI_USE_PLUGHW
    int usePlugHw = 1;
#else
    int usePlugHw = 0;
#endif

    TRACE0("> openMidiDevice()\n");

    (*handle) = (MidiDeviceHandle*) calloc(sizeof(MidiDeviceHandle), 1);
    if (!(*handle)) {
        ERROR0("ERROR: openDevice: out of memory\n");
        return MIDI_OUT_OF_MEMORY;
    }

    // TODO: iterate to get dev ID from index
    err = getMidiDeviceID(direction, deviceIndex, &deviceID);
    TRACE1("  openMidiDevice(): deviceID: %d\n", (int) deviceID);
    getDeviceStringFromDeviceID(devicename, deviceID,
                                usePlugHw, ALSA_RAWMIDI);
    TRACE1("  openMidiDevice(): deviceString: %s\n", devicename);

    // finally open the device
    if (direction == SND_RAWMIDI_STREAM_INPUT) {
        err = snd_rawmidi_open(&native_handle, NULL, devicename,
                               SND_RAWMIDI_NONBLOCK);
    } else if (direction == SND_RAWMIDI_STREAM_OUTPUT) {
        err = snd_rawmidi_open(NULL, &native_handle, devicename,
                               SND_RAWMIDI_NONBLOCK);
    } else {
        ERROR0("  ERROR: openMidiDevice(): direction is neither SND_RAWMIDI_STREAM_INPUT nor SND_RAWMIDI_STREAM_OUTPUT\n");
        err = MIDI_INVALID_ARGUMENT;
    }
    if (err < 0) {
        ERROR1("<  ERROR: openMidiDevice(): snd_rawmidi_open() returned %d\n", err);
        free(*handle);
        (*handle) = NULL;
        return err;
    }
    /* We opened with non-blocking behaviour to not get hung if the device
       is used by a different process. Writing, however, should
       be blocking. So we change it here. */
    if (direction == SND_RAWMIDI_STREAM_OUTPUT) {
        err = snd_rawmidi_nonblock(native_handle, 0);
        if (err < 0) {
            ERROR1("  ERROR: openMidiDevice(): snd_rawmidi_nonblock() returned %d\n", err);
            snd_rawmidi_close(native_handle);
            free(*handle);
            (*handle) = NULL;
            return err;
        }
    }
    if (direction == SND_RAWMIDI_STREAM_INPUT) {
        err = snd_midi_event_new(EVENT_PARSER_BUFSIZE, &event_parser);
        if (err < 0) {
            ERROR1("  ERROR: openMidiDevice(): snd_midi_event_new() returned %d\n", err);
            snd_rawmidi_close(native_handle);
            free(*handle);
            (*handle) = NULL;
            return err;
        }
    }

    (*handle)->deviceHandle = (void*) native_handle;
    (*handle)->startTime = getTimeInMicroseconds();
    (*handle)->platformData = event_parser;
    TRACE0("< openMidiDevice(): succeeded\n");
    return err;
}
Exemplo n.º 26
0
/** 
 * \fn     mlme_assocRequestMsgBuild 
 * \brief  buils association request
 * 
 * The function builds the association request according to the given parames
 * 
 * \param  pCtx - pointer to mlme_t
 * \param  reqBuf - <output> pointer to built assoc request buffer
 * \param  reqLen - <output> length of built assoc request buffer
 * 
 * \return TI_OK if auth send successfully
 *         TI_NOK otherwise
 * 
 * \sa     mlme_sendAssocRequest 
 */ 
TI_STATUS mlme_assocRequestMsgBuild(mlme_t *pCtx, TI_UINT8* reqBuf, TI_UINT32* reqLen)
{
    TI_STATUS       status;
    TI_UINT8        *pRequest;
    TI_UINT32       len;
    paramInfo_t     param;
    TTwdParamInfo   tTwdParam;
    TI_UINT16       capabilities;
	TI_BOOL spectrumManagementEnabled;
	ECipherSuite    eCipherSuite = TWD_CIPHER_NONE; /* To be used for checking whether

                                                       AP supports HT rates and TKIP */
    pRequest = reqBuf;
    *reqLen = 0;


    /* insert capabilities */
    status = mlme_assocCapBuild(pCtx, &capabilities);
    if (status == TI_OK)
    {
         *(TI_UINT16*)pRequest = ENDIAN_HANDLE_WORD(capabilities);
    }
    else
	{
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build assoc Capa\n");
        return TI_NOK;
	}

    pRequest += sizeof(TI_UINT16);
    *reqLen += sizeof(TI_UINT16);

    /* insert listen interval */
    tTwdParam.paramType = TWD_LISTEN_INTERVAL_PARAM_ID;
    status =  TWD_GetParam (pCtx->hTWD, &tTwdParam);
    if (status == TI_OK)
    {
        *(TI_UINT16*)pRequest = ENDIAN_HANDLE_WORD((TI_UINT16)tTwdParam.content.halCtrlListenInterval);
    } else {
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to get listen interval\n");
        return TI_NOK;
    }

    pRequest += sizeof(TI_UINT16);
    *reqLen += sizeof(TI_UINT16);

	if (pCtx->reAssoc)
    {   /* Insert currentAPAddress element only in reassoc request*/
        param.paramType = SITE_MGR_PREV_SITE_BSSID_PARAM;
        status = siteMgr_getParam(pCtx->hSiteMgr, &param);
        if (status == TI_OK)
        {
            MAC_COPY (pRequest, param.content.siteMgrDesiredBSSID);
            TRACE6(pCtx->hReport, REPORT_SEVERITY_INFORMATION, "ASSOC_SM: ASSOC_REQ - prev AP = %x-%x-%x-%x-%x-%x\n", param.content.siteMgrDesiredBSSID[0], param.content.siteMgrDesiredBSSID[1], param.content.siteMgrDesiredBSSID[2], param.content.siteMgrDesiredBSSID[3], param.content.siteMgrDesiredBSSID[4], param.content.siteMgrDesiredBSSID[5]);


            pRequest += MAC_ADDR_LEN;
            *reqLen += MAC_ADDR_LEN;
        }
        else
        {
            TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: ASSOC_REQ - No prev AP \n");
            return status;

        }
    }

    /* insert SSID element */
    status = mlme_assocSSIDBuild(pCtx, pRequest, &len);
    if (status != TI_OK)
    {
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build SSID IE\n");
        return TI_NOK;
    }

    pRequest += len;
    *reqLen += len;

    /* insert Rates element */
    status = mlme_assocRatesBuild(pCtx, pRequest, &len);
    if (status != TI_OK)
    {
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build rates IE\n");
        return TI_NOK;
    }
    pRequest += len;
    *reqLen += len;

	/* Checking if the station supports Spectrum Management (802.11h) */
    param.paramType = REGULATORY_DOMAIN_MANAGEMENT_CAPABILITY_ENABLED_PARAM;
    status = regulatoryDomain_getParam(pCtx->hRegulatoryDomain,&param);
	spectrumManagementEnabled = param.content.spectrumManagementEnabled;

	/* Checking the selected AP capablities */
    param.paramType = SITE_MGR_SITE_CAPABILITY_PARAM;
    status =  siteMgr_getParam(pCtx->hSiteMgr,&param);
    if (status == TI_OK &&
    		spectrumManagementEnabled &&
    		param.content.siteMgrSiteCapability & (DOT11_SPECTRUM_MANAGEMENT != 0))
    {
         /* insert Power capability element */
         status = mlme_assocPowerCapabilityBuild(pCtx, pRequest, &len);
         if (status != TI_OK)
         {
			 TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build Power IE\n");
             return TI_NOK;
         }
         pRequest += len;
         *reqLen += len;
    }


#ifdef XCC_MODULE_INCLUDED
    status = rsn_getXCCExtendedInfoElement(pCtx->hRsn, pRequest, (TI_UINT8*)&len);
    if (status != TI_OK)
    {
        return TI_NOK;
    }
    pRequest += len;
    *reqLen += len;

    if (pCtx->reAssoc)
    {   /* insert CCKM information element only in reassoc */
        status = XCCMngr_getCckmInfoElement(pCtx->hXCCMngr, pRequest, (TI_UINT8*)&len);

        if (status != TI_OK)
        {
            return TI_NOK;
        }
        pRequest += len;
        *reqLen += len;
    }
    status = XCCMngr_getXCCVersionInfoElement(pCtx->hXCCMngr, pRequest, (TI_UINT8*)&len);
    if (status != TI_OK)
    {
        return TI_NOK;
    }
    pRequest += len;
    *reqLen += len;

    /* Insert Radio Mngt Capability IE */
    status = measurementMgr_radioMngtCapabilityBuild(pCtx->hMeasurementMgr, pRequest, (TI_UINT8*)&len);
    if (status != TI_OK)
    {
        return TI_NOK;
    }
    pRequest += len;
    *reqLen += len;
#endif

     /* Get Simple-Config state */
    param.paramType = SITE_MGR_SIMPLE_CONFIG_MODE;
    status = siteMgr_getParam(pCtx->hSiteMgr, &param);

   if (param.content.siteMgrWSCMode.WSCMode == TIWLN_SIMPLE_CONFIG_OFF)
   {
   /* insert RSN information elements */
    status = rsn_getInfoElement(pCtx->hRsn, pRequest, &len);

	if (status != TI_OK)
	{
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build RSN IE\n");
		return TI_NOK;
	}
	pRequest += len;
	*reqLen += len;
  }

  /* Privacy - Used later on HT */

    param.paramType = RSN_ENCRYPTION_STATUS_PARAM;

    status          = rsn_getParam(pCtx->hRsn, &param);



    if(status == TI_OK)

    {

        eCipherSuite = param.content.rsnEncryptionStatus;

    }



	/* insert QoS capability information element */
    status = qosMngr_getQosCapabiltyInfeElement(pCtx->hQosMngr,pRequest,&len);
    if (status != TI_OK)
    {
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build QoS capa IE\n");
        return TI_NOK;
    }
    pRequest += len;
    *reqLen += len;


    /* Primary Site support HT ? */
    param.paramType = SITE_MGR_PRIMARY_SITE_HT_SUPPORT;
    siteMgr_getParam(pCtx->hSiteMgr, &param);


    /* Disallow TKIP with HT Rates: If this is the case - discard HT rates from Association Request */
    if((TI_TRUE == param.content.bPrimarySiteHtSupport) && (eCipherSuite != TWD_CIPHER_TKIP))
    {

        status = StaCap_GetHtCapabilitiesIe (pCtx->hStaCap, pRequest, &len);
    	if (status != TI_OK)
    	{
    		return TI_NOK;
    	}
    	pRequest += len;
    	*reqLen += len;
    }

	status = qosMngr_assocReqBuild(pCtx->hQosMngr,pRequest,&len);
	if (status != TI_OK)
	{
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build QoS IE\n");
		return TI_NOK;
	}
	pRequest += len;
	*reqLen += len;

	status = apConn_getVendorSpecificIE(pCtx->hApConn, pRequest, &len);
	if (status != TI_OK)
	{
		TRACE0(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build vendor IE\n");
		return TI_NOK;
	}
	pRequest += len;
	*reqLen += len;

    if (*reqLen>=MAX_ASSOC_MSG_LENGTH)
    {
		TRACE1(pCtx->hReport, REPORT_SEVERITY_ERROR, "mlme_assocRequestMsgBuild: failed to build, reqLen = %u\n", *reqLen);
        return TI_NOK;
    }



    return TI_OK;
}
Exemplo n.º 27
0
void parse_option(const TCHAR *optionp, const TCHAR *optionendp,
                  OnigOptionType *onigoption, OnigEncoding *enc, int *flagp)
{
    const TCHAR *p = optionp;
    int flag = 0;
    OnigOptionType option = ONIG_OPTION_NONE;
#ifdef UNICODE
    *enc = ONIG_ENCODING_UTF16_LE;
#else
    *enc = ONIG_ENCODING_ASCII;
#endif
    TRACE1(_T("option: %s"), optionp);
    while (p < optionendp) {
        switch (*p++) {
        case 'g':
            flag |= PMf_GLOBAL;
            break;
        case 'i':
            flag |= PMf_FOLD;
            option |= ONIG_OPTION_IGNORECASE;
            break;
        case 'm':
            //flag |= PMf_MULTILINE;
            option |= ONIG_OPTION_NEGATE_SINGLELINE;
            break;
        case 'o':
            flag |= PMf_KEEP;
            break;
        case 'k':
            flag |= PMf_KANJI;
#ifndef UNICODE
            *enc = ONIG_ENCODING_CP932;
#endif
            break;
#if !defined(UNICODE) && !defined(_K2REGEXP_)
        case '8':		/* bregonig.dll extension */
            *enc = ONIG_ENCODING_UTF8;
            break;
#endif
        case 'c':
            flag |= PMf_TRANS_COMPLEMENT;
            break;
        case 'd':
            flag |= PMf_TRANS_DELETE;
            option &= ~ONIG_OPTION_ASCII_RANGE;
            break;
        case 's':
            flag |= PMf_TRANS_SQUASH;
            //flag |= PMf_SINGLELINE;
            option |= ONIG_OPTION_MULTILINE;
            break;
        case 'x':
            option |= ONIG_OPTION_EXTEND;
            break;
        case 'a':
            option |= ONIG_OPTION_ASCII_RANGE;
            break;
        case 'l':
        case 'u':
            option &= ~ONIG_OPTION_ASCII_RANGE;
            break;
        case 'R':
            option |= ONIG_OPTION_NEWLINE_CRLF;
            break;
        default:
            break;
        }
    }
    *flagp = flag;
    *onigoption = option;
}
Exemplo n.º 28
0
/***************************************************************************
*					SoftGemini_setEnableParam					    	       *
****************************************************************************
* DESCRIPTION:	The function sets the  appropriate Enable value,
*				configures SCR , POWER MGR , DATA CTRL , FW.   
*
* INPUTS:		pSoftGemini - the object		
***************************************************************************/
static TI_STATUS SoftGemini_setEnableParam(TI_HANDLE hSoftGemini, ESoftGeminiEnableModes SoftGeminiEnable, TI_BOOL recovery)
{
	SoftGemini_t *pSoftGemini = (SoftGemini_t *)hSoftGemini;
	TTwdParamInfo	param;
	TI_STATUS return_value = TI_OK;

TRACE0(pSoftGemini->hReport, REPORT_SEVERITY_INFORMATION, "  setSoftGeminiEnableParam() - Old value = , New value = \n");


    /*
     * PsPoll work around is active. Just save the value and configure it later
     */
    if ( pSoftGemini->bPsPollFailureActive )
    {
        TRACE0(pSoftGemini->hReport, REPORT_SEVERITY_INFORMATION, "  setSoftGeminiEnableParam() - while PsPollFailure is active\n");

        pSoftGemini->PsPollFailureLastEnableValue = SoftGeminiEnable;
        return TI_OK;
    }

	/**********************************/
	/* Sanity check on enable values */
	/********************************/

	/*				Old Value						New Value		    */        
	/*					|							    |			    */        
	/*			  	   \|/							   \|/			    */        

	if ((pSoftGemini->SoftGeminiEnable == SoftGeminiEnable) && !recovery)
	{
TRACE0(pSoftGemini->hReport, REPORT_SEVERITY_ERROR, "   - setting same value \n");
		return TI_NOK;
	}

	/*******************************/
	/* Make the necessary actions */
	/*****************************/
	
	switch (SoftGeminiEnable)
	{
	case SG_PROTECTIVE:
	case SG_OPPORTUNISTIC:
		
		/* set FW with SG_ENABLE */ 
		param.paramType = TWD_SG_ENABLE_PARAM_ID;
		param.content.SoftGeminiEnable = SoftGeminiEnable;
		return_value = TWD_SetParam (pSoftGemini->hTWD, &param);

		break;

	case SG_DISABLE:
		
		/* set FW with SG_DISABLE */
		param.paramType = TWD_SG_ENABLE_PARAM_ID;
		param.content.SoftGeminiEnable = SG_DISABLE;
		return_value = TWD_SetParam (pSoftGemini->hTWD, &param);

		if (pSoftGemini->bDriverEnabled)
		{	
			SoftGemini_DisableDriver(hSoftGemini);
		}
		
		break;

	default:
TRACE1(pSoftGemini->hReport, REPORT_SEVERITY_ERROR, " defualt :%d\n",SoftGeminiEnable);
		return TI_NOK;
	}

	/* Pass to the new enable state */
	pSoftGemini->SoftGeminiEnable = SoftGeminiEnable;

	if (TI_OK != return_value)
	{
TRACE0(pSoftGemini->hReport, REPORT_SEVERITY_ERROR, " can't configure enable param to FW :\n");
	}
	
	return return_value;
}
Exemplo n.º 29
0
int regexec_onig(bregonig *rx, const TCHAR *stringarg,
                 const TCHAR *strend,	/* pointer to null at end of string */
                 const TCHAR *strbeg,	/* real beginning of string */
                 int minend,		/* end of match must be at least minend after stringarg */
                 int safebase,	/* no need to remember string in subbase */
                 int one_shot,	/* if not match then break without proceed str pointer */
                 TCHAR *msg)		/* fatal error message */
{
    TRACE1(_T("one_shot: %d\n"), one_shot);
    OnigPosition err_code;

    if (one_shot) {
        OnigOptionType option = (minend > 0) ?
                                ONIG_OPTION_FIND_NOT_EMPTY : ONIG_OPTION_NONE;
        err_code = onig_match(rx->reg, (UChar*) strbeg, (UChar*) strend,
                              (UChar*) stringarg, rx->region,
                              option);
    } else {
        const TCHAR *global_pos = stringarg;		/* \G */
        if (minend > 0) {
#ifdef UNICODE
            int kanjiflag = 1;
#else
            int kanjiflag = rx->pmflags & PMf_KANJI;
#endif
            if (kanjiflag && is_char_pair((TBYTE*) stringarg)) {
                stringarg += 2;
            } else {
                stringarg++;
            }
        }
        err_code = onig_search_gpos(rx->reg, (UChar*) strbeg, (UChar*) strend,
                                    (UChar*) global_pos,
                                    (UChar*) stringarg, (UChar*) strend, rx->region,
                                    ONIG_OPTION_NONE);
    }

    if (err_code >= 0) {
        /* FOUND */
        if (rx->startp) {
            delete [] rx->startp;
        }
        rx->nparens = rx->region->num_regs - 1;
        rx->startp = new (std::nothrow) TCHAR*[rx->region->num_regs * 2];
        /* allocate startp and endp together */
        if (rx->startp == NULL) {
            asc2tcs(msg, "out of space", BREGEXP_MAX_ERROR_MESSAGE_LEN);
            return -1;
        }
        rx->endp = rx->startp + rx->region->num_regs;

        for (int i = 0; i < rx->region->num_regs; i++) {
            if (rx->region->beg[i] != ONIG_REGION_NOTPOS) {
                // found
                rx->startp[i] = const_cast<TCHAR *>(strbeg) + rx->region->beg[i] / sizeof(TCHAR);
                rx->endp[i] = const_cast<TCHAR *>(strbeg) + rx->region->end[i] / sizeof(TCHAR);
            } else {
                // not found
                rx->startp[i] = NULL;
                rx->endp[i] = NULL;
            }
        }
        return 1;
    } else if (err_code == ONIG_MISMATCH) {
        /* NOT FOUND */
        return 0;
    } else {
        /* ERROR */
        onig_err_to_bregexp_msg(err_code, NULL, msg);
        return -1;
    }
}
Exemplo n.º 30
0
static void UpdateScreenStep2 (void)
{
    status.bVIOriginIsUpdated = false;

    if( status.ToToggleFullScreen && status.gDlistCount > 0 )
    {
        ChangeWindowStep2();
        return;
    }
    if (status.ToResize && status.gDlistCount > 0)
    {
        ResizeStep2();
        return;
    }

    g_CritialSection.Lock();

    //framskip, count vi
    numvi++;

    if( status.bHandleN64RenderTexture )
        g_pFrameBufferManager->CloseRenderTexture(true);

    if (skipping) {
        g_CritialSection.Unlock();
        return;
    }
    
    g_pFrameBufferManager->SetAddrBeDisplayed(*g_GraphicsInfo.VI_ORIGIN_REG);

    if(status.gDlistCount == 0)
    {
        // CPU frame buffer update
        uint32 width = *g_GraphicsInfo.VI_WIDTH_REG;
        if( (*g_GraphicsInfo.VI_ORIGIN_REG & (g_dwRamSize-1) ) > width*2 && *g_GraphicsInfo.VI_H_START_REG != 0 && width != 0 )
        {
            SetVIScales();
            CRender::GetRender()->DrawFrameBuffer(true);
            CGraphicsContext::Get()->UpdateFrame();
        }
        g_CritialSection.Unlock();
        return;
    }

    TXTRBUF_DETAIL_DUMP(TRACE1("VI ORIG is updated to %08X", *g_GraphicsInfo.VI_ORIGIN_REG));

    if( currentRomOptions.screenUpdateSetting == SCREEN_UPDATE_AT_VI_UPDATE )
    {
        CGraphicsContext::Get()->UpdateFrame();

        DEBUGGER_IF_DUMP( pauseAtNext, TRACE1("Update Screen: VIORIG=%08X", *g_GraphicsInfo.VI_ORIGIN_REG));
        DEBUGGER_PAUSE_COUNT_N_WITHOUT_UPDATE(NEXT_FRAME);
        DEBUGGER_PAUSE_COUNT_N_WITHOUT_UPDATE(NEXT_SET_CIMG);
        g_CritialSection.Unlock();
        return;
    }

    TXTRBUF_DETAIL_DUMP(TRACE1("VI ORIG is updated to %08X", *g_GraphicsInfo.VI_ORIGIN_REG));

    if( currentRomOptions.screenUpdateSetting == SCREEN_UPDATE_AT_VI_UPDATE_AND_DRAWN )
    {
        if( status.bScreenIsDrawn )
        {
            CGraphicsContext::Get()->UpdateFrame();
            DEBUGGER_IF_DUMP( pauseAtNext, TRACE1("Update Screen: VIORIG=%08X", *g_GraphicsInfo.VI_ORIGIN_REG));
        }
        else
        {
            DEBUGGER_IF_DUMP( pauseAtNext, TRACE1("Skip Screen Update: VIORIG=%08X", *g_GraphicsInfo.VI_ORIGIN_REG));
        }

        DEBUGGER_PAUSE_COUNT_N_WITHOUT_UPDATE(NEXT_FRAME);
        DEBUGGER_PAUSE_COUNT_N_WITHOUT_UPDATE(NEXT_SET_CIMG);
        g_CritialSection.Unlock();
        return;
    }

    if( currentRomOptions.screenUpdateSetting==SCREEN_UPDATE_AT_VI_CHANGE )
    {

        if( *g_GraphicsInfo.VI_ORIGIN_REG != status.curVIOriginReg )
        {
            if( *g_GraphicsInfo.VI_ORIGIN_REG < status.curDisplayBuffer || *g_GraphicsInfo.VI_ORIGIN_REG > status.curDisplayBuffer+0x2000  )
            {
                status.curDisplayBuffer = *g_GraphicsInfo.VI_ORIGIN_REG;
                status.curVIOriginReg = status.curDisplayBuffer;
                //status.curRenderBuffer = NULL;

                CGraphicsContext::Get()->UpdateFrame();
                DEBUGGER_IF_DUMP( pauseAtNext, TRACE1("Update Screen: VIORIG=%08X", *g_GraphicsInfo.VI_ORIGIN_REG));
                DEBUGGER_PAUSE_COUNT_N_WITHOUT_UPDATE(NEXT_FRAME);
                DEBUGGER_PAUSE_COUNT_N_WITHOUT_UPDATE(NEXT_SET_CIMG);
            }
            else
            {
                status.curDisplayBuffer = *g_GraphicsInfo.VI_ORIGIN_REG;
                status.curVIOriginReg = status.curDisplayBuffer;
                DEBUGGER_PAUSE_AND_DUMP_NO_UPDATE(NEXT_FRAME, {DebuggerAppendMsg("Skip Screen Update, closed to the display buffer, VIORIG=%08X", *g_GraphicsInfo.VI_ORIGIN_REG);});
            }
        }
        else
        {