<commit_before>/*--------------------------------------------------------------------------
File   : ble_intrf.cpp

Author : Hoang Nguyen Hoan          Feb. 6, 2017

Desc   : Implementation allow the creation of generic serial interface of
		 a custom Bluetooth Smart service with multiple user defined
		 characteristics.

Copyright (c) 2017, I-SYST inc., all rights reserved

Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

For info or contributing contact : hnhoan at i-syst dot com

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

----------------------------------------------------------------------------
Modified by          Date              Description

----------------------------------------------------------------------------*/
#include <string.h>

#include "cfifo.h"
#include "ble_intrf.h"
#include "ble_app.h"

#define NRFBLEINTRF_PACKET_SIZE		NRF_BLE_MAX_MTU_SIZE
#define NRFBLEINTRF_CFIFO_SIZE		CFIFO_TOTAL_MEMSIZE(2, NRFBLEINTRF_PACKET_SIZE + sizeof(BLEINTRF_PKT) - 1)

static uint8_t s_nRFBleRxFifoMem[NRFBLEINTRF_CFIFO_SIZE];
static uint8_t s_nRFBleTxFifoMem[NRFBLEINTRF_CFIFO_SIZE];

/**
 * @brief - Disable
 * 		Turn off the interface.  If this is a physical interface, provide a
 * way to turn off for energy saving. Make sure the turn off procedure can
 * be turned back on without going through the full init sequence
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return None
 */
void BleIntrfDisable(DEVINTRF *pDevIntrf)
{
	// TODO:
}

/**
 * @brief - Enable
 * 		Turn on the interface.
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return None
 */
void BleIntrfEnable(DEVINTRF *pDevIntrf)
{
	// TODO:
}

/**
 * @brief - GetRate
 * 		Get data rate of the interface in Hertz.  This is not a clock frequency
 * but rather the transfer frequency (number of transfers per second). It has meaning base on the
 * implementation as bits/sec or bytes/sec or whatever the case
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return Transfer rate per second
 */
int BleIntrfGetRate(DEVINTRF *pDevIntrf)
{
	return 0;	// BLE has no rate
}

/**
 * @brief - SetRate
 * 		Set data rate of the interface in Hertz.  This is not a clock frequency
 * but rather the transfer frequency (number of transfers per second). It has meaning base on the
 * implementation as bits/sec or bytes/sec or whatever the case
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		Rate 	  : Data rate to be set in Hertz (transfer per second)
 *
 * @return 	Actual transfer rate per second set.  It is the real capable rate
 * 			closes to rate being requested.
 */
int BleIntrfSetRate(DEVINTRF *pDevIntrf, int Rate)
{
	return 0; // BLE has no rate
}

/**
 * @brief - StartRx
 * 		Prepare start condition to receive data with subsequence RxData.
 * This can be in case such as start condition for I2C or Chip Select for
 * SPI or precondition for DMA transfer or whatever requires it or not
 * This function must check & set the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		DevAddr   : The device selection id scheme
 *
 * @return 	true - Success
 * 			false - failed.
 */
bool BleIntrfStartRx(DEVINTRF *pDevIntrf, int DevAddr)
{
	return true;
}

/**
 * @brief - RxData : retrieve 1 packet of received data
 * 		Receive data into pBuff passed in parameter.  Assuming StartRx was
 * called prior calling this function to get the actual data. BufferLen
 * to receive data must be at least 1 packet in size.  Otherwise remaining
 * bytes are dropped.
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		pBuff 	  : Pointer to memory area to receive data.
 * 		BuffLen   : Length of buffer memory in bytes. Must be at least 1 packet
 * 		            in size.  Otherwise remaining bytes are dropped.
 *
 * @return	Number of bytes read
 */
int BleIntrfRxData(DEVINTRF *pDevIntrf, uint8_t *pBuff, int BuffLen)
{
	BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
	BLEINTRF_PKT *pkt;
	int cnt = 0;

	pkt = (BLEINTRF_PKT *)CFifoGet(intrf->hRxFifo);
	if (pkt != NULL)
	{
	    cnt = min(BuffLen, pkt->Len);
		memcpy(pBuff, pkt->Data, cnt);
	}

	return cnt;
}

/**
 * @brief - StopRx
 * 		Completion of read data phase. Do require post processing
 * after data has been received via RxData
 * This function must clear the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return	None
 */
void BleIntrfStopRx(DEVINTRF *pSerDev)
{
	// TODO:
}

/**
 * @brief - StartTx
 * 		Prepare start condition to transfer data with subsequence TxData.
 * This can be in case such as start condition for I2C or Chip Select for
 * SPI or precondition for DMA transfer or whatever requires it or not
 * This function must check & set the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		DevAddr   : The device selection id scheme
 *
 * @return 	true - Success
 * 			false - failed
 */
bool BleIntrfStartTx(DEVINTRF *pDevIntrf, int DevAddr)
{
	return true;
}

bool BleIntrfNotify(BLEINTRF *pIntrf)
{
    BLEINTRF_PKT *pkt;
    uint32_t res = NRF_SUCCESS;

    if (pIntrf->TransBuffLen > 0)
    {
        res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pIntrf->TransBuff, pIntrf->TransBuffLen);
    }
    if (res != NRF_ERROR_RESOURCES)
    {
        pIntrf->TransBuffLen = 0;
        do {
            pkt = (BLEINTRF_PKT *)CFifoGet(pIntrf->hTxFifo);
            if (pkt != NULL)
            {
                uint32_t res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pkt->Data, pkt->Len);
                if (res == NRF_ERROR_RESOURCES)
                {
                    memcpy(pIntrf->TransBuff, pkt->Data, pkt->Len);
                    pIntrf->TransBuffLen = pkt->Len;
                    break;
                }
            }
        } while (pkt != NULL);
    }

    return true;
}

/**
 * @brief - TxData
 * 		Transfer data from pData passed in parameter.  Assuming StartTx was
 * called prior calling this function to send the actual data
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		pData 	: Pointer to memory area of data to send.
 * 		DataLen : Length of data memory in bytes
 *
 * @return	Number of bytes sent
 */
int BleIntrfTxData(DEVINTRF *pDevIntrf, uint8_t *pData, int DataLen)
{
	BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
    BLEINTRF_PKT *pkt;
    int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);
	int cnt = 0;

	while (DataLen > 0)
	{
		pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hTxFifo);
		if (pkt == NULL)
			break;
        int l = min(DataLen, maxlen);
		memcpy(pkt->Data, pData, l);
		pkt->Len = l;
		DataLen -= l;
		pData += l;
		cnt += l;
	}
	BleIntrfNotify(intrf);

	return cnt;
}

/**
 * @brief - StopTx
 * 		Completion of sending data via TxData.  Do require post processing
 * after all data was transmitted via TxData.
 * This function must clear the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return	None
 */
void BleIntrfStopTx(DEVINTRF *pDevIntrf)
{

}

/**
 * @brief - Reset
 *      This function perform a reset of interface.  Must provide empty
 * function of not used.
 *
 * @param
 *      pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return  None
 */
void BleIntrfReset(DEVINTRF *pDevIntrf)
{

}

/**
 *
 *
 */
void BleIntrfTxComplete(BLESRVC *pBleSvc, int CharIdx)
{
    BleIntrfNotify((BLEINTRF*)pBleSvc->pContext);
}

void BleIntrfRxWrCB(BLESRVC *pBleSvc, uint8_t *pData, int Offset, int Len)
{
	BLEINTRF *intrf = (BLEINTRF*)pBleSvc->pContext;
    BLEINTRF_PKT *pkt;
    //int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);

	while (Len > 0) {
		pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hRxFifo);
		if (pkt == NULL)
			break;
		int l = min(intrf->PacketSize, Len);
		memcpy(pkt->Data, pData, l);
		pkt->Len = l;
		Len -= l;
		pData += l;
	}

	if (CFifoUsed(intrf->hRxFifo) > 0 && intrf->DevIntrf.EvtCB != NULL)
	{
		intrf->DevIntrf.EvtCB(&intrf->DevIntrf, DEVINTRF_EVT_RX_DATA, NULL, 0);
	}
}

bool BleIntrfInit(BLEINTRF *pBleIntrf, const BLEINTRF_CFG *pCfg)
{
	if (pBleIntrf == NULL || pCfg == NULL)
		return false;

	if (pCfg->PacketSize <= 0)
	{
		pBleIntrf->PacketSize = NRFBLEINTRF_PACKET_SIZE;
	}
	else
	{
		pBleIntrf->PacketSize = pCfg->PacketSize;
	}

	if (pCfg->pRxFifoMem == NULL || pCfg->pTxFifoMem == NULL)
	{
		pBleIntrf->hRxFifo = CFifoInit(s_nRFBleRxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
		pBleIntrf->hTxFifo = CFifoInit(s_nRFBleTxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
	}
	else
	{
		pBleIntrf->hRxFifo = CFifoInit(pCfg->pRxFifoMem, pCfg->RxFifoMemSize, pBleIntrf->PacketSize, true);
		pBleIntrf->hTxFifo = CFifoInit(pCfg->pTxFifoMem, pCfg->TxFifoMemSize, pBleIntrf->PacketSize, true);
	}

	pBleIntrf->DevIntrf.pDevData = (void*)pBleIntrf;
	pBleIntrf->pBleSrv = pCfg->pBleSrv;
	pBleIntrf->pBleSrv->pContext = pBleIntrf;

	pBleIntrf->RxCharIdx = pCfg->RxCharIdx;
	pBleIntrf->TxCharIdx = pCfg->TxCharIdx;

	pBleIntrf->pBleSrv->pCharArray[pBleIntrf->RxCharIdx].WrCB = BleIntrfRxWrCB;
	pBleIntrf->pBleSrv->pCharArray[pBleIntrf->TxCharIdx].TxCompleteCB = BleIntrfTxComplete;

	pBleIntrf->DevIntrf.Enable = BleIntrfEnable;
	pBleIntrf->DevIntrf.Disable = BleIntrfDisable;
	pBleIntrf->DevIntrf.GetRate = BleIntrfGetRate;
	pBleIntrf->DevIntrf.SetRate = BleIntrfSetRate;
	pBleIntrf->DevIntrf.StartRx = BleIntrfStartRx;
	pBleIntrf->DevIntrf.RxData = BleIntrfRxData;
	pBleIntrf->DevIntrf.StopRx = BleIntrfStopRx;
	pBleIntrf->DevIntrf.StartTx = BleIntrfStartTx;
	pBleIntrf->DevIntrf.TxData = BleIntrfTxData;
	pBleIntrf->DevIntrf.StopTx = BleIntrfStopTx;
	pBleIntrf->DevIntrf.bBusy = false;
	pBleIntrf->DevIntrf.MaxRetry = 0;
	pBleIntrf->DevIntrf.EvtCB = pCfg->EvtCB;
	pBleIntrf->TransBuffLen = 0;

	return true;
}

bool BleIntrf::Init(const BLEINTRF_CFG &Cfg)
{
	return BleIntrfInit(&vBleIntrf, &Cfg);
}

bool BleIntrf::RequestToSend(int NbBytes)
{
	bool retval = false;

	// ****
	// Some threaded application firmware may stop sending when queue full
	// causing lockup
	// Try to send to free up the queue before validating.
	//
	BleIntrfNotify(&vBleIntrf);

	if (vBleIntrf.hTxFifo)
	{
		int avail = CFifoAvail(vBleIntrf.hTxFifo);
		if ((avail * vBleIntrf.PacketSize) > NbBytes)
			retval = true;
	}
	else
	{
		retval = true;
	}

	return retval;
}

<commit_msg>Fixed alignment for nRF51<commit_after>/*--------------------------------------------------------------------------
File   : ble_intrf.cpp

Author : Hoang Nguyen Hoan          Feb. 6, 2017

Desc   : Implementation allow the creation of generic serial interface of
		 a custom Bluetooth Smart service with multiple user defined
		 characteristics.

Copyright (c) 2017, I-SYST inc., all rights reserved

Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.

For info or contributing contact : hnhoan at i-syst dot com

THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

----------------------------------------------------------------------------
Modified by          Date              Description

----------------------------------------------------------------------------*/
#include <string.h>

#include "cfifo.h"
#include "ble_intrf.h"
#include "ble_app.h"

#define NRFBLEINTRF_PACKET_SIZE		(NRF_BLE_MAX_MTU_SIZE - 3)
#define NRFBLEINTRF_CFIFO_SIZE		CFIFO_TOTAL_MEMSIZE(2, NRFBLEINTRF_PACKET_SIZE + sizeof(BLEINTRF_PKT) - 1)

alignas(4) static uint8_t s_nRFBleRxFifoMem[NRFBLEINTRF_CFIFO_SIZE];
alignas(4) static uint8_t s_nRFBleTxFifoMem[NRFBLEINTRF_CFIFO_SIZE];

/**
 * @brief - Disable
 * 		Turn off the interface.  If this is a physical interface, provide a
 * way to turn off for energy saving. Make sure the turn off procedure can
 * be turned back on without going through the full init sequence
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return None
 */
void BleIntrfDisable(DEVINTRF *pDevIntrf)
{
	// TODO:
}

/**
 * @brief - Enable
 * 		Turn on the interface.
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return None
 */
void BleIntrfEnable(DEVINTRF *pDevIntrf)
{
	// TODO:
}

/**
 * @brief - GetRate
 * 		Get data rate of the interface in Hertz.  This is not a clock frequency
 * but rather the transfer frequency (number of transfers per second). It has meaning base on the
 * implementation as bits/sec or bytes/sec or whatever the case
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return Transfer rate per second
 */
int BleIntrfGetRate(DEVINTRF *pDevIntrf)
{
	return 0;	// BLE has no rate
}

/**
 * @brief - SetRate
 * 		Set data rate of the interface in Hertz.  This is not a clock frequency
 * but rather the transfer frequency (number of transfers per second). It has meaning base on the
 * implementation as bits/sec or bytes/sec or whatever the case
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		Rate 	  : Data rate to be set in Hertz (transfer per second)
 *
 * @return 	Actual transfer rate per second set.  It is the real capable rate
 * 			closes to rate being requested.
 */
int BleIntrfSetRate(DEVINTRF *pDevIntrf, int Rate)
{
	return 0; // BLE has no rate
}

/**
 * @brief - StartRx
 * 		Prepare start condition to receive data with subsequence RxData.
 * This can be in case such as start condition for I2C or Chip Select for
 * SPI or precondition for DMA transfer or whatever requires it or not
 * This function must check & set the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		DevAddr   : The device selection id scheme
 *
 * @return 	true - Success
 * 			false - failed.
 */
bool BleIntrfStartRx(DEVINTRF *pDevIntrf, int DevAddr)
{
	return true;
}

/**
 * @brief - RxData : retrieve 1 packet of received data
 * 		Receive data into pBuff passed in parameter.  Assuming StartRx was
 * called prior calling this function to get the actual data. BufferLen
 * to receive data must be at least 1 packet in size.  Otherwise remaining
 * bytes are dropped.
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		pBuff 	  : Pointer to memory area to receive data.
 * 		BuffLen   : Length of buffer memory in bytes. Must be at least 1 packet
 * 		            in size.  Otherwise remaining bytes are dropped.
 *
 * @return	Number of bytes read
 */
int BleIntrfRxData(DEVINTRF *pDevIntrf, uint8_t *pBuff, int BuffLen)
{
	BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
	BLEINTRF_PKT *pkt;
	int cnt = 0;

	pkt = (BLEINTRF_PKT *)CFifoGet(intrf->hRxFifo);
	if (pkt != NULL)
	{
	    cnt = min(BuffLen, pkt->Len);
		memcpy(pBuff, pkt->Data, cnt);
	}

	return cnt;
}

/**
 * @brief - StopRx
 * 		Completion of read data phase. Do require post processing
 * after data has been received via RxData
 * This function must clear the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return	None
 */
void BleIntrfStopRx(DEVINTRF *pSerDev)
{
	// TODO:
}

/**
 * @brief - StartTx
 * 		Prepare start condition to transfer data with subsequence TxData.
 * This can be in case such as start condition for I2C or Chip Select for
 * SPI or precondition for DMA transfer or whatever requires it or not
 * This function must check & set the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		DevAddr   : The device selection id scheme
 *
 * @return 	true - Success
 * 			false - failed
 */
bool BleIntrfStartTx(DEVINTRF *pDevIntrf, int DevAddr)
{
	return true;
}

bool BleIntrfNotify(BLEINTRF *pIntrf)
{
    BLEINTRF_PKT *pkt;
    uint32_t res = NRF_SUCCESS;

    if (pIntrf->TransBuffLen > 0)
    {
        res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pIntrf->TransBuff, pIntrf->TransBuffLen);
    }
    if (res != NRF_ERROR_RESOURCES)
    {
        pIntrf->TransBuffLen = 0;
        do {
            pkt = (BLEINTRF_PKT *)CFifoGet(pIntrf->hTxFifo);
            if (pkt != NULL)
            {
                uint32_t res = BleSrvcCharNotify(pIntrf->pBleSrv, pIntrf->TxCharIdx, pkt->Data, pkt->Len);
                if (res == NRF_ERROR_RESOURCES)
                {
                    memcpy(pIntrf->TransBuff, pkt->Data, pkt->Len);
                    pIntrf->TransBuffLen = pkt->Len;
                    break;
                }
            }
        } while (pkt != NULL);
    }

    return true;
}

/**
 * @brief - TxData
 * 		Transfer data from pData passed in parameter.  Assuming StartTx was
 * called prior calling this function to send the actual data
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 * 		pData 	: Pointer to memory area of data to send.
 * 		DataLen : Length of data memory in bytes
 *
 * @return	Number of bytes sent
 */
int BleIntrfTxData(DEVINTRF *pDevIntrf, uint8_t *pData, int DataLen)
{
	BLEINTRF *intrf = (BLEINTRF*)pDevIntrf->pDevData;
    BLEINTRF_PKT *pkt;
    int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);
	int cnt = 0;

	while (DataLen > 0)
	{
		pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hTxFifo);
		if (pkt == NULL)
			break;
        int l = min(DataLen, maxlen);
		memcpy(pkt->Data, pData, l);
		pkt->Len = l;
		DataLen -= l;
		pData += l;
		cnt += l;
	}
	BleIntrfNotify(intrf);

	return cnt;
}

/**
 * @brief - StopTx
 * 		Completion of sending data via TxData.  Do require post processing
 * after all data was transmitted via TxData.
 * This function must clear the busy state for re-entrancy
 *
 * @param
 * 		pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return	None
 */
void BleIntrfStopTx(DEVINTRF *pDevIntrf)
{

}

/**
 * @brief - Reset
 *      This function perform a reset of interface.  Must provide empty
 * function of not used.
 *
 * @param
 *      pDevIntrf : Pointer to an instance of the Device Interface
 *
 * @return  None
 */
void BleIntrfReset(DEVINTRF *pDevIntrf)
{

}

/**
 *
 *
 */
void BleIntrfTxComplete(BLESRVC *pBleSvc, int CharIdx)
{
    BleIntrfNotify((BLEINTRF*)pBleSvc->pContext);
}

void BleIntrfRxWrCB(BLESRVC *pBleSvc, uint8_t *pData, int Offset, int Len)
{
	BLEINTRF *intrf = (BLEINTRF*)pBleSvc->pContext;
    BLEINTRF_PKT *pkt;
    //int maxlen = intrf->hTxFifo->BlkSize - sizeof(pkt->Len);

	while (Len > 0) {
		pkt = (BLEINTRF_PKT *)CFifoPut(intrf->hRxFifo);
		if (pkt == NULL)
			break;
		int l = min(intrf->PacketSize, Len);
		memcpy(pkt->Data, pData, l);
		pkt->Len = l;
		Len -= l;
		pData += l;
	}

	if (CFifoUsed(intrf->hRxFifo) > 0 && intrf->DevIntrf.EvtCB != NULL)
	{
		intrf->DevIntrf.EvtCB(&intrf->DevIntrf, DEVINTRF_EVT_RX_DATA, NULL, 0);
	}
}

bool BleIntrfInit(BLEINTRF *pBleIntrf, const BLEINTRF_CFG *pCfg)
{
	if (pBleIntrf == NULL || pCfg == NULL)
		return false;

	if (pCfg->PacketSize <= 0)
	{
		pBleIntrf->PacketSize = NRFBLEINTRF_PACKET_SIZE;
	}
	else
	{
		pBleIntrf->PacketSize = pCfg->PacketSize;
	}

	if (pCfg->pRxFifoMem == NULL || pCfg->pTxFifoMem == NULL)
	{
		pBleIntrf->hRxFifo = CFifoInit(s_nRFBleRxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
		pBleIntrf->hTxFifo = CFifoInit(s_nRFBleTxFifoMem, NRFBLEINTRF_CFIFO_SIZE, pBleIntrf->PacketSize, true);
	}
	else
	{
		pBleIntrf->hRxFifo = CFifoInit(pCfg->pRxFifoMem, pCfg->RxFifoMemSize, pBleIntrf->PacketSize, true);
		pBleIntrf->hTxFifo = CFifoInit(pCfg->pTxFifoMem, pCfg->TxFifoMemSize, pBleIntrf->PacketSize, true);
	}

	pBleIntrf->DevIntrf.pDevData = (void*)pBleIntrf;
	pBleIntrf->pBleSrv = pCfg->pBleSrv;
	pBleIntrf->pBleSrv->pContext = pBleIntrf;

	pBleIntrf->RxCharIdx = pCfg->RxCharIdx;
	pBleIntrf->TxCharIdx = pCfg->TxCharIdx;

	pBleIntrf->pBleSrv->pCharArray[pBleIntrf->RxCharIdx].WrCB = BleIntrfRxWrCB;
	pBleIntrf->pBleSrv->pCharArray[pBleIntrf->TxCharIdx].TxCompleteCB = BleIntrfTxComplete;

	pBleIntrf->DevIntrf.Enable = BleIntrfEnable;
	pBleIntrf->DevIntrf.Disable = BleIntrfDisable;
	pBleIntrf->DevIntrf.GetRate = BleIntrfGetRate;
	pBleIntrf->DevIntrf.SetRate = BleIntrfSetRate;
	pBleIntrf->DevIntrf.StartRx = BleIntrfStartRx;
	pBleIntrf->DevIntrf.RxData = BleIntrfRxData;
	pBleIntrf->DevIntrf.StopRx = BleIntrfStopRx;
	pBleIntrf->DevIntrf.StartTx = BleIntrfStartTx;
	pBleIntrf->DevIntrf.TxData = BleIntrfTxData;
	pBleIntrf->DevIntrf.StopTx = BleIntrfStopTx;
	pBleIntrf->DevIntrf.bBusy = false;
	pBleIntrf->DevIntrf.MaxRetry = 0;
	pBleIntrf->DevIntrf.EvtCB = pCfg->EvtCB;
	pBleIntrf->TransBuffLen = 0;

	return true;
}

bool BleIntrf::Init(const BLEINTRF_CFG &Cfg)
{
	return BleIntrfInit(&vBleIntrf, &Cfg);
}

bool BleIntrf::RequestToSend(int NbBytes)
{
	bool retval = false;

	// ****
	// Some threaded application firmware may stop sending when queue full
	// causing lockup
	// Try to send to free up the queue before validating.
	//
	BleIntrfNotify(&vBleIntrf);

	if (vBleIntrf.hTxFifo)
	{
		int avail = CFifoAvail(vBleIntrf.hTxFifo);
		if ((avail * vBleIntrf.PacketSize) > NbBytes)
			retval = true;
	}
	else
	{
		retval = true;
	}

	return retval;
}

<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>

#include "pcl/common/time.h"
#include "pcl/features/fpfh_omp.h"
#include "pcl/features/normal_3d_omp.h"
#include "pcl/filters/crop_box.h"
#include "pcl/filters/filter.h"
#include "pcl/filters/voxel_grid.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl/registration/icp.h"
#include "pcl/registration/sample_consensus_prerejective.h"
#include "pcl/segmentation/sac_segmentation.h"
#include "pcl_conversions/pcl_conversions.h"
#include "pcl_ros/transforms.h"
#include "rapid_perception/pr2.h"
#include "rapid_perception/box3d_roi_server.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_perception/random_heat_mapper.h"
#include "rapid_msgs/GetStaticCloud.h"
#include "rapid_msgs/ListStaticClouds.h"
#include "rapid_msgs/RemoveStaticCloud.h"
#include "rapid_msgs/SaveStaticCloud.h"
#include "rapid_ros/publisher.h"
#include "ros/ros.h"
#include "sensor_msgs/Image.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"

#include "object_search/capture_roi.h"
#include "object_search/commands.h"
#include "object_search/command_line.h"
#include "object_search/cloud_database.h"

using sensor_msgs::Image;
using sensor_msgs::PointCloud2;
using pcl::FPFHSignature33;
using pcl::PointCloud;
using pcl::PointXYZRGB;
using pcl::PointXYZRGBNormal;
using visualization_msgs::Marker;
namespace rp = rapid::perception;

using namespace object_search;

int main(int argc, char** argv) {
  ros::init(argc, argv, "object_search");
  ros::NodeHandle nh;
  ros::AsyncSpinner spinner(4);
  spinner.start();

  // Build databases
  ros::ServiceClient get_cloud =
      nh.serviceClient<rapid_msgs::GetStaticCloud>("get_static_cloud");
  ros::ServiceClient list_clouds =
      nh.serviceClient<rapid_msgs::ListStaticClouds>("list_static_clouds");
  ros::ServiceClient remove_cloud =
      nh.serviceClient<rapid_msgs::RemoveStaticCloud>("remove_static_cloud");
  ros::ServiceClient save_cloud =
      nh.serviceClient<rapid_msgs::SaveStaticCloud>("save_static_cloud");
  Database object_db("object_search", "objects", get_cloud, list_clouds,
                     remove_cloud, save_cloud);
  Database scene_db("object_search", "scenes", get_cloud, list_clouds,
                    remove_cloud, save_cloud);

  // Visualization publishers
  ros::Publisher object_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
  ros::Publisher candidates_pub =
      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
  ros::Publisher alignment_pub =
      nh.advertise<PointCloud2>("/alignment", 1, true);
  ros::Publisher output_pub = nh.advertise<PointCloud2>("/output", 1, true);
  rapid_ros::Publisher<visualization_msgs::Marker> marker_pub(
      nh.advertise<visualization_msgs::Marker>("/visualization_markers", 1,
                                               true));

  // Build ROI server
  tf::TransformListener tf_listener;
  rapid::perception::Box3DRoiServer roi_server("roi");
  CaptureRoi capture(&roi_server);

  // Build heat mapper
  // rapid::perception::FpfhHeatMapper* heat_mapper =
  //    new rapid::perception::FpfhHeatMapper();
  // heat_mapper->set_name("fpfh");

  // rapid::perception::TemplateMatchingHeatMapper* heat_mapper =
  //    new rapid::perception::TemplateMatchingHeatMapper();
  // heat_mapper->set_name("template_matching");

  rapid::perception::RandomHeatMapper* heat_mapper =
      new rapid::perception::RandomHeatMapper();
  heat_mapper->set_name("random");
  heat_mapper->set_heatmap_publisher(heatmap_pub);

  // Build pose estimator
  rapid::perception::PoseEstimator pose_estimator(heat_mapper);
  pose_estimator.set_scene_publisher(scene_pub);
  pose_estimator.set_object_publisher(object_pub);
  pose_estimator.set_candidates_publisher(candidates_pub);
  pose_estimator.set_alignment_publisher(alignment_pub);
  pose_estimator.set_output_publisher(output_pub);
  pose_estimator.set_marker_publisher(&marker_pub);

  ListCommand list_objects(&object_db, "object");
  ListCommand list_scenes(&scene_db, "scene");
  RecordObjectCommand record_object(&object_db, &capture);
  RecordSceneCommand record_scene(&scene_db);
  DeleteCommand delete_object(&object_db);
  DeleteCommand delete_scene(&scene_db);
  UseCommand use_object(&object_db, &pose_estimator, "object");
  UseCommand use_scene(&scene_db, &pose_estimator, "scene");
  RunCommand run(&pose_estimator);
  SetDebugCommand set_debug(&pose_estimator);

  CommandLine cli;
  cli.set_list_objects(&list_objects);
  cli.set_list_scenes(&list_scenes);
  cli.set_record_object(&record_object);
  cli.set_record_scene(&record_scene);
  cli.set_delete_object(&delete_object);
  cli.set_delete_scene(&delete_scene);
  cli.set_use_object(&use_object);
  cli.set_use_scene(&use_scene);
  cli.set_run(&run);
  cli.set_debug(&set_debug);

  while (cli.Next()) {
  }

  spinner.stop();
  return 0;
}
<commit_msg>Cleaned up includes.<commit_after>#include <iostream>
#include <string>

#include "pcl/filters/filter.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "pcl_conversions/pcl_conversions.h"
#include "pcl_ros/transforms.h"
#include "rapid_perception/box3d_roi_server.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_perception/random_heat_mapper.h"
#include "rapid_msgs/GetStaticCloud.h"
#include "rapid_msgs/ListStaticClouds.h"
#include "rapid_msgs/RemoveStaticCloud.h"
#include "rapid_msgs/SaveStaticCloud.h"
#include "rapid_ros/publisher.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"

#include "object_search/capture_roi.h"
#include "object_search/commands.h"
#include "object_search/command_line.h"
#include "object_search/cloud_database.h"

using sensor_msgs::PointCloud2;
using pcl::PointCloud;
using pcl::PointXYZRGB;
using visualization_msgs::Marker;

using namespace object_search;

int main(int argc, char** argv) {
  ros::init(argc, argv, "object_search");
  ros::NodeHandle nh;
  ros::AsyncSpinner spinner(4);
  spinner.start();

  // Build databases
  ros::ServiceClient get_cloud =
      nh.serviceClient<rapid_msgs::GetStaticCloud>("get_static_cloud");
  ros::ServiceClient list_clouds =
      nh.serviceClient<rapid_msgs::ListStaticClouds>("list_static_clouds");
  ros::ServiceClient remove_cloud =
      nh.serviceClient<rapid_msgs::RemoveStaticCloud>("remove_static_cloud");
  ros::ServiceClient save_cloud =
      nh.serviceClient<rapid_msgs::SaveStaticCloud>("save_static_cloud");
  Database object_db("object_search", "objects", get_cloud, list_clouds,
                     remove_cloud, save_cloud);
  Database scene_db("object_search", "scenes", get_cloud, list_clouds,
                    remove_cloud, save_cloud);

  // Visualization publishers
  ros::Publisher object_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
  ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
  ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
  ros::Publisher candidates_pub =
      nh.advertise<PointCloud2>("/candidate_samples", 1, true);
  ros::Publisher alignment_pub =
      nh.advertise<PointCloud2>("/alignment", 1, true);
  ros::Publisher output_pub = nh.advertise<PointCloud2>("/output", 1, true);
  rapid_ros::Publisher<visualization_msgs::Marker> marker_pub(
      nh.advertise<visualization_msgs::Marker>("/visualization_markers", 1,
                                               true));

  // Build ROI server
  rapid::perception::Box3DRoiServer roi_server("roi");
  CaptureRoi capture(&roi_server);

  // Build heat mapper
  // rapid::perception::FpfhHeatMapper* heat_mapper =
  //    new rapid::perception::FpfhHeatMapper();
  // heat_mapper->set_name("fpfh");

  // rapid::perception::TemplateMatchingHeatMapper* heat_mapper =
  //    new rapid::perception::TemplateMatchingHeatMapper();
  // heat_mapper->set_name("template_matching");

  rapid::perception::RandomHeatMapper* heat_mapper =
      new rapid::perception::RandomHeatMapper();
  heat_mapper->set_name("random");
  heat_mapper->set_heatmap_publisher(heatmap_pub);

  // Build pose estimator
  rapid::perception::PoseEstimator pose_estimator(heat_mapper);
  pose_estimator.set_scene_publisher(scene_pub);
  pose_estimator.set_object_publisher(object_pub);
  pose_estimator.set_candidates_publisher(candidates_pub);
  pose_estimator.set_alignment_publisher(alignment_pub);
  pose_estimator.set_output_publisher(output_pub);
  pose_estimator.set_marker_publisher(&marker_pub);

  ListCommand list_objects(&object_db, "object");
  ListCommand list_scenes(&scene_db, "scene");
  RecordObjectCommand record_object(&object_db, &capture);
  RecordSceneCommand record_scene(&scene_db);
  DeleteCommand delete_object(&object_db);
  DeleteCommand delete_scene(&scene_db);
  UseCommand use_object(&object_db, &pose_estimator, "object");
  UseCommand use_scene(&scene_db, &pose_estimator, "scene");
  RunCommand run(&pose_estimator);
  SetDebugCommand set_debug(&pose_estimator);

  CommandLine cli;
  cli.set_list_objects(&list_objects);
  cli.set_list_scenes(&list_scenes);
  cli.set_record_object(&record_object);
  cli.set_record_scene(&record_scene);
  cli.set_delete_object(&delete_object);
  cli.set_delete_scene(&delete_scene);
  cli.set_use_object(&use_object);
  cli.set_use_scene(&use_scene);
  cli.set_run(&run);
  cli.set_debug(&set_debug);

  while (cli.Next()) {
  }

  spinner.stop();
  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************/
/*  thread_posix.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#if (defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)) && !defined(NO_THREADS)

#include "thread_posix.h"

#include "core/os/thread.h"
#include "core/ustring.h"

static Error set_name(const String &p_name) {
#ifdef PTHREAD_NO_RENAME
	return ERR_UNAVAILABLE;

#else

#ifdef PTHREAD_RENAME_SELF

	// check if thread is the same as caller
	int err = pthread_setname_np(p_name.utf8().get_data());

#else

	pthread_t running_thread = pthread_self();
#ifdef PTHREAD_BSD_SET_NAME
	pthread_set_name_np(running_thread, p_name.utf8().get_data());
	int err = 0; // Open/FreeBSD ignore errors in this function
#elif defined(PTHREAD_NETBSD_SET_NAME)
	int err = pthread_setname_np(running_thread, "%s", const_cast<char *>(p_name.utf8().get_data()));
#else
	int err = pthread_setname_np(running_thread, p_name.utf8().get_data());
#endif // PTHREAD_BSD_SET_NAME

#endif // PTHREAD_RENAME_SELF

	return err == 0 ? OK : ERR_INVALID_PARAMETER;

#endif // PTHREAD_NO_RENAME
}

void init_thread_posix() {
	Thread::_set_platform_funcs(&set_name, nullptr);
}

#endif
<commit_msg>Thread: Re-add pthread_np.h include for FreeBSD/OpenBSD<commit_after>/*************************************************************************/
/*  thread_posix.cpp                                                     */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#if (defined(UNIX_ENABLED) || defined(PTHREAD_ENABLED)) && !defined(NO_THREADS)

#include "thread_posix.h"

#include "core/os/thread.h"
#include "core/ustring.h"

#ifdef PTHREAD_BSD_SET_NAME
#include <pthread_np.h>
#endif

static Error set_name(const String &p_name) {
#ifdef PTHREAD_NO_RENAME
	return ERR_UNAVAILABLE;

#else

#ifdef PTHREAD_RENAME_SELF

	// check if thread is the same as caller
	int err = pthread_setname_np(p_name.utf8().get_data());

#else

	pthread_t running_thread = pthread_self();
#ifdef PTHREAD_BSD_SET_NAME
	pthread_set_name_np(running_thread, p_name.utf8().get_data());
	int err = 0; // Open/FreeBSD ignore errors in this function
#elif defined(PTHREAD_NETBSD_SET_NAME)
	int err = pthread_setname_np(running_thread, "%s", const_cast<char *>(p_name.utf8().get_data()));
#else
	int err = pthread_setname_np(running_thread, p_name.utf8().get_data());
#endif // PTHREAD_BSD_SET_NAME

#endif // PTHREAD_RENAME_SELF

	return err == 0 ? OK : ERR_INVALID_PARAMETER;

#endif // PTHREAD_NO_RENAME
}

void init_thread_posix() {
	Thread::_set_platform_funcs(&set_name, nullptr);
}

#endif
<|endoftext|>


<commit_before>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#include "EchoIndicationWrapper.h"
#include "EchoRequestProxy.h"
#include "GeneratedTypes.h"
#include "SwallowProxy.h"

#define LOOP_COUNT 1000
#define SEPARATE_EVENT_THREAD
//#define USE_MUTEX_SYNC

EchoRequestProxy *echoRequestProxy = 0;

#ifndef SEPARATE_EVENT_THREAD
typedef int SEM_TYPE;
#define SEMPOST(A) (*(A))++
#define SEMWAIT pthread_worker
#elif defined(USE_MUTEX_SYNC)
typedef pthread_mutex_t SEM_TYPE;
#define SEMINIT(A) pthread_mutex_lock(A);
#define SEMWAIT(A) pthread_mutex_lock(A);
#define SEMPOST(A) pthread_mutex_unlock(A);
#else // use semaphores
typedef sem_t SEM_TYPE;
#define SEMINIT(A) sem_init(A, 0, 0);
#define SEMWAIT(A) sem_wait(A);
#define SEMPOST(A) sem_post(A)
#endif

#ifdef SEPARATE_EVENT_THREAD
#define PREPAREWAIT(A)
#define CHECKSEM(A) 1
#else // use inline sync
#define PREPAREWAIT(A) (A) = 0
#define CHECKSEM(A) (!(A))
#endif

static SEM_TYPE sem_heard2;

static void *pthread_worker(void *ptr)
{
    void *rc = NULL;
    while (CHECKSEM(sem_heard2) && !rc)
        rc = portalExec_event(portalExec_timeout);
    return rc;
}
static void init_thread()
{
#ifdef SEPARATE_EVENT_THREAD
    pthread_t threaddata;
    SEMINIT(&sem_heard2);
    pthread_create(&threaddata, NULL, &pthread_worker, NULL);
#endif
}

class EchoIndication : public EchoIndicationWrapper
{
public:
    virtual void heard(unsigned long v) {
        fprintf(stderr, "heard an echo: %ld\n", v);
	echoRequestProxy->say2(v, 2*v);
    }
    virtual void heard2(unsigned long a, unsigned long b) {
        catch_timer(20);
        SEMPOST(&sem_heard2);
        //fprintf(stderr, "heard an echo2: %ld %ld\n", a, b);
        //catch_timer(25);
    }
    EchoIndication(unsigned int id) : EchoIndicationWrapper(id) {
    }
};

static void call_say(int v)
{
    printf("[%s:%d] %d\n", __FUNCTION__, __LINE__, v);
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    echoRequestProxy->say(v);
    SEMWAIT(&sem_heard2);
    printf("call_say: elapsed %lld\n", lap_timer(0));
}

static void call_say2(int v, int v2)
{
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    catch_timer(0);
    echoRequestProxy->say2(v, v2);
    catch_timer(19);
    SEMWAIT(&sem_heard2);
    catch_timer(30);
}

int main(int argc, const char **argv)
{
    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication);
    SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow);
    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);

    portalExec_init();
    init_thread();

    int v = 42;
    fprintf(stderr, "Saying %d\n", v);
    call_say(v);
    call_say(v*5);
    call_say(v*17);
    call_say(v*93);
    printf("[%s:%d] run %d loops\n\n", __FUNCTION__, __LINE__, LOOP_COUNT);
    init_timer();
    start_timer(1);
    for (int i = 0; i < LOOP_COUNT; i++)
        call_say2(v, v*3);
unsigned long long elapsed = lap_timer(1);
    printf("TEST TYPE: "
#ifndef SEPARATE_EVENT_THREAD
       "INLINE"
#elif defined(USE_MUTEX_SYNC)
       "MUTEX"
#else
       "SEM"
#endif
       "\n");
    print_timer(LOOP_COUNT);
    printf("call_say: elapsed %lld average %lld\n", elapsed, elapsed/LOOP_COUNT);
    echoRequestProxy->setLeds(9);
    print_dbg_requeste_intervals();
    portalExec_end();
    return 0;
}
<commit_msg>removed temp debug code<commit_after>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>

#include "EchoIndicationWrapper.h"
#include "EchoRequestProxy.h"
#include "GeneratedTypes.h"
#include "SwallowProxy.h"

#define LOOP_COUNT 1000
#define SEPARATE_EVENT_THREAD
//#define USE_MUTEX_SYNC

EchoRequestProxy *echoRequestProxy = 0;

#ifndef SEPARATE_EVENT_THREAD
typedef int SEM_TYPE;
#define SEMPOST(A) (*(A))++
#define SEMWAIT pthread_worker
#elif defined(USE_MUTEX_SYNC)
typedef pthread_mutex_t SEM_TYPE;
#define SEMINIT(A) pthread_mutex_lock(A);
#define SEMWAIT(A) pthread_mutex_lock(A);
#define SEMPOST(A) pthread_mutex_unlock(A);
#else // use semaphores
typedef sem_t SEM_TYPE;
#define SEMINIT(A) sem_init(A, 0, 0);
#define SEMWAIT(A) sem_wait(A);
#define SEMPOST(A) sem_post(A)
#endif

#ifdef SEPARATE_EVENT_THREAD
#define PREPAREWAIT(A)
#define CHECKSEM(A) 1
#else // use inline sync
#define PREPAREWAIT(A) (A) = 0
#define CHECKSEM(A) (!(A))
#endif

static SEM_TYPE sem_heard2;

static void *pthread_worker(void *ptr)
{
    void *rc = NULL;
    while (CHECKSEM(sem_heard2) && !rc)
        rc = portalExec_event(portalExec_timeout);
    return rc;
}
static void init_thread()
{
#ifdef SEPARATE_EVENT_THREAD
    pthread_t threaddata;
    SEMINIT(&sem_heard2);
    pthread_create(&threaddata, NULL, &pthread_worker, NULL);
#endif
}

class EchoIndication : public EchoIndicationWrapper
{
public:
    virtual void heard(unsigned long v) {
        fprintf(stderr, "heard an echo: %ld\n", v);
	echoRequestProxy->say2(v, 2*v);
    }
    virtual void heard2(unsigned long a, unsigned long b) {
        catch_timer(20);
        SEMPOST(&sem_heard2);
        //fprintf(stderr, "heard an echo2: %ld %ld\n", a, b);
        //catch_timer(25);
    }
    EchoIndication(unsigned int id) : EchoIndicationWrapper(id) {
    }
};

static void call_say(int v)
{
    printf("[%s:%d] %d\n", __FUNCTION__, __LINE__, v);
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    echoRequestProxy->say(v);
    SEMWAIT(&sem_heard2);
    printf("call_say: elapsed %lld\n", lap_timer(0));
}

static void call_say2(int v, int v2)
{
    start_timer(0);
    PREPAREWAIT(sem_heard2);
    catch_timer(0);
    echoRequestProxy->say2(v, v2);
    catch_timer(19);
    SEMWAIT(&sem_heard2);
    catch_timer(30);
}

int main(int argc, const char **argv)
{
    EchoIndication *echoIndication = new EchoIndication(IfcNames_EchoIndication);
    SwallowProxy *swallowProxy = new SwallowProxy(IfcNames_Swallow);
    echoRequestProxy = new EchoRequestProxy(IfcNames_EchoRequest);

    portalExec_init();
    init_thread();

    int v = 42;
    fprintf(stderr, "Saying %d\n", v);
    call_say(v);
    call_say(v*5);
    call_say(v*17);
    call_say(v*93);
    printf("[%s:%d] run %d loops\n\n", __FUNCTION__, __LINE__, LOOP_COUNT);
    init_timer();
    start_timer(1);
    for (int i = 0; i < LOOP_COUNT; i++)
        call_say2(v, v*3);
unsigned long long elapsed = lap_timer(1);
    printf("TEST TYPE: "
#ifndef SEPARATE_EVENT_THREAD
       "INLINE"
#elif defined(USE_MUTEX_SYNC)
       "MUTEX"
#else
       "SEM"
#endif
       "\n");
    print_timer(LOOP_COUNT);
    printf("call_say: elapsed %lld average %lld\n", elapsed, elapsed/LOOP_COUNT);
    echoRequestProxy->setLeds(9);
    //print_dbg_requeste_intervals();
    portalExec_end();
    return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: helper.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2002-02-21 14:28:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <string.h>
#include <psprint/helper.hxx>
#include <tools/string.hxx>
#include <osl/file.hxx>
#include <unotools/configmgr.hxx>

namespace psp {

::rtl::OUString getOfficeInstallPath( ::utl::ConfigManager::ConfigProperty eWhich )
{
    ::com::sun::star::uno::Any  aConfigProperty;
    ::rtl::OUString             aPath;

    aConfigProperty = ::utl::ConfigManager::GetDirectConfigProperty( eWhich );
    aConfigProperty >>= aPath;
    return aPath;
}

::rtl::OUString getEnvironmentPath( const char* pKey, sal_Unicode cPrefix )
{
    ::rtl::OUString aPath;

    const char* pValue = getenv( pKey );
    if( pValue && *pValue )
    {
        aPath  = ::rtl::OUString( cPrefix );
        aPath += ::rtl::OUString( pValue, strlen( pValue ), gsl_getSystemTextEncoding() );
    }
    return aPath;
}

} // namespace psp

const ::rtl::OUString& psp::getPrinterPath()
{
    static ::rtl::OUString aPath;

    if( ! aPath.getLength() )
    {
        aPath  = ::psp::getOfficeInstallPath( ::utl::ConfigManager::OFFICEINSTALL );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/share/psprint:" ) );
        aPath += ::psp::getOfficeInstallPath( ::utl::ConfigManager::INSTALLPATH );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/psprint" ) );
        aPath += ::psp::getEnvironmentPath( "SAL_PSPRINT", (sal_Unicode)':' );

#ifdef DEBUG
        fprintf( stderr, "initalizing printer path to \"%s\"\n", ::rtl::OUStringToOString( aPath, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
    }
    return aPath;
}

const ::rtl::OUString& psp::getFontPath()
{
    static ::rtl::OUString aPath;

    if( ! aPath.getLength() )
    {
        ::rtl::OUString aOfficeFontPath = ::psp::getOfficeInstallPath(
                                                   ::utl::ConfigManager::OFFICEINSTALL );
        aPath  = aOfficeFontPath;
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/share/fonts/truetype;") );
        aPath += aOfficeFontPath;
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/share/fonts/type1;") );
        aPath += ::psp::getOfficeInstallPath( ::utl::ConfigManager::INSTALLPATH );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/fonts" ) );
        aPath += ::psp::getEnvironmentPath( "SAL_FONTPATH_PRIVATE", (sal_Unicode)';' );

#ifdef DEBUG
        fprintf( stderr, "initalizing font path to \"%s\"\n", ::rtl::OUStringToOString( aPath, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
    }
    return aPath;
}

bool psp::convertPfbToPfa( ::osl::File& rInFile, ::osl::File& rOutFile )
{
    static unsigned char hexDigits[] =
        {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };

    bool bSuccess = true;
    bool bEof = false;
    unsigned char buffer[256];
    sal_uInt64 nRead;
    sal_uInt64 nOrgPos = 0;
    rInFile.getPos( nOrgPos );

    while( bSuccess && ! bEof )
    {
        // read leading bytes
        bEof = ! rInFile.read( buffer, 6, nRead ) && nRead == 6 ? false : true;
        int nType = buffer[ 1 ];
        int nBytesToRead = buffer[2] | buffer[3] << 8 | buffer[4] << 16 | buffer[5] << 24;
        if( buffer[0] != 0x80 ) // test for pfb m_agic number
        {
            // this migt be a pfa font already
            sal_uInt64 nWrite = 0;
            if( ! rInFile.read( buffer+6, 9, nRead ) && nRead == 9 &&
                ( ! strncmp( (char*)buffer, "%!FontType1-", 12 ) ||
                  ! strncmp( (char*)buffer, "%!PS-AdobeFont-", 15 ) ) )
            {
                if( rOutFile.write( buffer, 15, nWrite ) || nWrite != 15 )
                    bSuccess = false;
                while( bSuccess &&
                       ! rInFile.read( buffer, sizeof( buffer ), nRead ) &&
                       nRead != 0 )
                {
                    if( rOutFile.write( buffer, nRead, nWrite ) ||
                        nWrite != nRead )
                        bSuccess = false;
                }
                bEof = true;
            }
            else
                bSuccess = false;
        }
        else if( nType == 1 || nType == 2 )
        {
            unsigned char* pBuffer = new unsigned char[ nBytesToRead+1 ];

            if( ! rInFile.read( pBuffer, nBytesToRead, nRead ) && nRead == nBytesToRead )
            {
                if( nType == 1 )
                {
                    // ascii data, convert dos lineends( \r\n ) and
                    // m_ac lineends( \r ) to \n
                    unsigned char * pWriteBuffer = new unsigned char[ nBytesToRead ];
                    int nBytesToWrite = 0;
                    for( int i = 0; i < nBytesToRead; i++ )
                    {
                        if( pBuffer[i] != '\r' )
                            pWriteBuffer[ nBytesToWrite++ ] = pBuffer[i];
                        else if( pBuffer[ i+1 ] == '\n' )
                        {
                            i++;
                            pWriteBuffer[ nBytesToWrite++ ] = '\n';
                        }
                        else
                            pWriteBuffer[ nBytesToWrite++ ] = '\n';
                    }
                    if( rOutFile.write( pWriteBuffer, nBytesToWrite, nRead ) || nRead != nBytesToWrite )
                        bSuccess = false;

                    delete pWriteBuffer;
                }
                else
                {
                    // binary data
                    int nBuffer = 0;
                    for( int i = 0; i < nBytesToRead && bSuccess; i++ )
                    {
                        buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] >> 4 ];
                        buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] & 15 ];
                        if( nBuffer >= 80 )
                        {
                            buffer[ nBuffer++ ] = '\n';
                            if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
                                bSuccess = false;
                            nBuffer = 0;
                        }
                    }
                    if( nBuffer > 0 && bSuccess )
                    {
                        buffer[ nBuffer++ ] = '\n';
                        if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
                            bSuccess = false;
                    }
                }
            }
            else
                bSuccess = false;

            delete pBuffer;
        }
        else if( nType == 3 )
            bEof = true;
        else
            bSuccess = false;
    }

    return bSuccess;
}
<commit_msg>#98148# drop dependency to configuration<commit_after>/*************************************************************************
 *
 *  $RCSfile: helper.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: pl $ $Date: 2002-04-10 08:58:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#include <string.h>
#include <psprint/helper.hxx>
#include <tools/string.hxx>
#include <osl/file.hxx>
#include <rtl/bootstrap.hxx>

namespace psp {

enum whichOfficePath { NetPath, UserPath };

static const ::rtl::OUString& getOfficePath( enum whichOfficePath ePath )
{
    static ::rtl::OUString aNetPath;
    static ::rtl::OUString aUserPath;
    static ::rtl::OUString aEmpty;
    static bool bOnce = false;

    if( ! bOnce )
    {
        bOnce = true;
        ::rtl::Bootstrap aBootstrap( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "bootstraprc" ) ) );
        aBootstrap.getFrom( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "BaseInstallation" ) ), aNetPath );
        aBootstrap.getFrom( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "UserInstallation" ) ), aUserPath );

        if( ! aNetPath.compareToAscii( "file://", 7 ) )
            aNetPath = aNetPath.copy( 7 );
        if( ! aUserPath.compareToAscii( "file://", 7 ) )
            aUserPath = aUserPath.copy( 7 );
    }

    switch( ePath )
    {
        case NetPath: return aNetPath;
        case UserPath: return aUserPath;
    }
    return aEmpty;
}

static ::rtl::OUString getEnvironmentPath( const char* pKey, sal_Unicode cPrefix )
{
    ::rtl::OUString aPath;

    const char* pValue = getenv( pKey );
    if( pValue && *pValue )
    {
        aPath  = ::rtl::OUString( cPrefix );
        aPath += ::rtl::OUString( pValue, strlen( pValue ), gsl_getSystemTextEncoding() );
    }
    return aPath;
}

} // namespace psp

const ::rtl::OUString& psp::getPrinterPath()
{
    static ::rtl::OUString aPath;

    if( ! aPath.getLength() )
    {
        aPath  = getOfficePath( psp::NetPath );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/share/psprint:" ) );
        aPath += getOfficePath( psp::UserPath );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/psprint" ) );
        aPath += ::psp::getEnvironmentPath( "SAL_PSPRINT", (sal_Unicode)':' );

#ifdef DEBUG
        fprintf( stderr, "initalizing printer path to \"%s\"\n", ::rtl::OUStringToOString( aPath, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
    }
    return aPath;
}

const ::rtl::OUString& psp::getFontPath()
{
    static ::rtl::OUString aPath;

    if( ! aPath.getLength() )
    {
        aPath  = getOfficePath( psp::NetPath );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/share/fonts/truetype;") );
        aPath += getOfficePath( psp::NetPath );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("/share/fonts/type1;") );
        aPath += getOfficePath( psp::UserPath );
        aPath += ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "/user/fonts" ) );
        aPath += ::psp::getEnvironmentPath( "SAL_FONTPATH_PRIVATE", (sal_Unicode)';' );

#ifdef DEBUG
        fprintf( stderr, "initalizing font path to \"%s\"\n", ::rtl::OUStringToOString( aPath, RTL_TEXTENCODING_ISO_8859_1 ).getStr() );
#endif
    }
    return aPath;
}

bool psp::convertPfbToPfa( ::osl::File& rInFile, ::osl::File& rOutFile )
{
    static unsigned char hexDigits[] =
        {
            '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
        };

    bool bSuccess = true;
    bool bEof = false;
    unsigned char buffer[256];
    sal_uInt64 nRead;
    sal_uInt64 nOrgPos = 0;
    rInFile.getPos( nOrgPos );

    while( bSuccess && ! bEof )
    {
        // read leading bytes
        bEof = ! rInFile.read( buffer, 6, nRead ) && nRead == 6 ? false : true;
        int nType = buffer[ 1 ];
        int nBytesToRead = buffer[2] | buffer[3] << 8 | buffer[4] << 16 | buffer[5] << 24;
        if( buffer[0] != 0x80 ) // test for pfb m_agic number
        {
            // this migt be a pfa font already
            sal_uInt64 nWrite = 0;
            if( ! rInFile.read( buffer+6, 9, nRead ) && nRead == 9 &&
                ( ! strncmp( (char*)buffer, "%!FontType1-", 12 ) ||
                  ! strncmp( (char*)buffer, "%!PS-AdobeFont-", 15 ) ) )
            {
                if( rOutFile.write( buffer, 15, nWrite ) || nWrite != 15 )
                    bSuccess = false;
                while( bSuccess &&
                       ! rInFile.read( buffer, sizeof( buffer ), nRead ) &&
                       nRead != 0 )
                {
                    if( rOutFile.write( buffer, nRead, nWrite ) ||
                        nWrite != nRead )
                        bSuccess = false;
                }
                bEof = true;
            }
            else
                bSuccess = false;
        }
        else if( nType == 1 || nType == 2 )
        {
            unsigned char* pBuffer = new unsigned char[ nBytesToRead+1 ];

            if( ! rInFile.read( pBuffer, nBytesToRead, nRead ) && nRead == nBytesToRead )
            {
                if( nType == 1 )
                {
                    // ascii data, convert dos lineends( \r\n ) and
                    // m_ac lineends( \r ) to \n
                    unsigned char * pWriteBuffer = new unsigned char[ nBytesToRead ];
                    int nBytesToWrite = 0;
                    for( int i = 0; i < nBytesToRead; i++ )
                    {
                        if( pBuffer[i] != '\r' )
                            pWriteBuffer[ nBytesToWrite++ ] = pBuffer[i];
                        else if( pBuffer[ i+1 ] == '\n' )
                        {
                            i++;
                            pWriteBuffer[ nBytesToWrite++ ] = '\n';
                        }
                        else
                            pWriteBuffer[ nBytesToWrite++ ] = '\n';
                    }
                    if( rOutFile.write( pWriteBuffer, nBytesToWrite, nRead ) || nRead != nBytesToWrite )
                        bSuccess = false;

                    delete pWriteBuffer;
                }
                else
                {
                    // binary data
                    int nBuffer = 0;
                    for( int i = 0; i < nBytesToRead && bSuccess; i++ )
                    {
                        buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] >> 4 ];
                        buffer[ nBuffer++ ] = hexDigits[ pBuffer[ i ] & 15 ];
                        if( nBuffer >= 80 )
                        {
                            buffer[ nBuffer++ ] = '\n';
                            if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
                                bSuccess = false;
                            nBuffer = 0;
                        }
                    }
                    if( nBuffer > 0 && bSuccess )
                    {
                        buffer[ nBuffer++ ] = '\n';
                        if( rOutFile.write( buffer, nBuffer, nRead ) || nRead != nBuffer )
                            bSuccess = false;
                    }
                }
            }
            else
                bSuccess = false;

            delete pBuffer;
        }
        else if( nType == 3 )
            bEof = true;
        else
            bSuccess = false;
    }

    return bSuccess;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "modules/filesystem/DataTransferItemFileSystem.h"

#include "core/dom/Clipboard.h"
#include "core/dom/DataTransferItem.h"
#include "core/dom/ExecutionContext.h"
#include "core/fileapi/File.h"
#include "core/platform/chromium/ChromiumDataObject.h"
#include "modules/filesystem/DOMFilePath.h"
#include "modules/filesystem/DOMFileSystem.h"
#include "modules/filesystem/DirectoryEntry.h"
#include "modules/filesystem/DraggedIsolatedFileSystem.h"
#include "modules/filesystem/Entry.h"
#include "modules/filesystem/FileEntry.h"
#include "platform/AsyncFileSystemCallbacks.h"
#include "platform/FileMetadata.h"

namespace WebCore {

// static
PassRefPtr<Entry> DataTransferItemFileSystem::webkitGetAsEntry(ExecutionContext* executionContext, DataTransferItem* item)
{
    if (!item->dataObjectItem()->isFilename())
        return adoptRef(static_cast<Entry*>(0));

    // For dragged files getAsFile must be pretty lightweight.
    Blob* file = item->getAsFile().get();
    // The clipboard may not be in a readable state.
    if (!file)
        return adoptRef(static_cast<Entry*>(0));
    ASSERT(file->isFile());

    DraggedIsolatedFileSystem* filesystem = DraggedIsolatedFileSystem::from(item->clipboard()->dataObject().get());
    DOMFileSystem* domFileSystem = filesystem ? filesystem->getDOMFileSystem(executionContext) : 0;
    if (!filesystem) {
        // IsolatedFileSystem may not be enabled.
        return adoptRef(static_cast<Entry*>(0));
    }

    ASSERT(domFileSystem);

    // The dropped entries are mapped as top-level entries in the isolated filesystem.
    String virtualPath = DOMFilePath::append("/", toFile(file)->name());

    // FIXME: This involves synchronous file operation. Consider passing file type data when we dispatch drag event.
    FileMetadata metadata;
    if (!getFileMetadata(toFile(file)->path(), metadata))
        return adoptRef(static_cast<Entry*>(0));

    if (metadata.type == FileMetadata::TypeDirectory)
        return static_cast<Entry*>(DirectoryEntry::create(domFileSystem, virtualPath).get());
    return static_cast<Entry*>(FileEntry::create(domFileSystem, virtualPath).get());
}

} // namespace WebCore
<commit_msg>Remove unnecessary static_cast<>s in DataTransferItemFielSystem.cpp<commit_after>/*
 * Copyright (C) 2012 Google Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *     * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *     * Neither the name of Google Inc. nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "modules/filesystem/DataTransferItemFileSystem.h"

#include "core/dom/Clipboard.h"
#include "core/dom/DataTransferItem.h"
#include "core/dom/ExecutionContext.h"
#include "core/fileapi/File.h"
#include "core/platform/chromium/ChromiumDataObject.h"
#include "modules/filesystem/DOMFilePath.h"
#include "modules/filesystem/DOMFileSystem.h"
#include "modules/filesystem/DirectoryEntry.h"
#include "modules/filesystem/DraggedIsolatedFileSystem.h"
#include "modules/filesystem/Entry.h"
#include "modules/filesystem/FileEntry.h"
#include "platform/AsyncFileSystemCallbacks.h"
#include "platform/FileMetadata.h"

namespace WebCore {

// static
PassRefPtr<Entry> DataTransferItemFileSystem::webkitGetAsEntry(ExecutionContext* executionContext, DataTransferItem* item)
{
    if (!item->dataObjectItem()->isFilename())
        return 0;

    // For dragged files getAsFile must be pretty lightweight.
    Blob* file = item->getAsFile().get();
    // The clipboard may not be in a readable state.
    if (!file)
        return 0;
    ASSERT(file->isFile());

    DraggedIsolatedFileSystem* filesystem = DraggedIsolatedFileSystem::from(item->clipboard()->dataObject().get());
    DOMFileSystem* domFileSystem = filesystem ? filesystem->getDOMFileSystem(executionContext) : 0;
    if (!filesystem) {
        // IsolatedFileSystem may not be enabled.
        return 0;
    }

    ASSERT(domFileSystem);

    // The dropped entries are mapped as top-level entries in the isolated filesystem.
    String virtualPath = DOMFilePath::append("/", toFile(file)->name());

    // FIXME: This involves synchronous file operation. Consider passing file type data when we dispatch drag event.
    FileMetadata metadata;
    if (!getFileMetadata(toFile(file)->path(), metadata))
        return 0;

    if (metadata.type == FileMetadata::TypeDirectory)
        return DirectoryEntry::create(domFileSystem, virtualPath);
    return FileEntry::create(domFileSystem, virtualPath);
}

} // namespace WebCore
<|endoftext|>


<commit_before><commit_msg>Remove TOOLKI_VIEWS cruft from tab_contents_view_gtk.cc now that it has its own TabContentsView implementation.<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_hoofs/platform/handle_translator.hpp"

HandleTranslator& HandleTranslator::getInstance() noexcept
{
    static HandleTranslator globalHandleTranslator;
    return globalHandleTranslator;
}

HANDLE HandleTranslator::get(const int handle) const noexcept
{
    return m_handleList[static_cast<size_t>(handle)];
}

int HandleTranslator::add(HANDLE handle) noexcept
{
    for (int64_t limit = m_handleList.size(), k = 0; k < limit; ++k)
    {
        if (m_handleList[k] == nullptr)
        {
            m_handleList[k] = handle;
            return k;
        }
    }

    m_handleList.emplace_back(handle_t{handle});
    return m_handleList.size() - 1;
}

void HandleTranslator::remove(const int handle) noexcept
{
    m_handleList[static_cast<uint64_t>(handle)] = nullptr;
}
<commit_msg>iox-#33 Fix Windows handle_t Issue In HandleTranslator<commit_after>// Copyright (c) 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

#include "iceoryx_hoofs/platform/handle_translator.hpp"

HandleTranslator& HandleTranslator::getInstance() noexcept
{
    static HandleTranslator globalHandleTranslator;
    return globalHandleTranslator;
}

HANDLE HandleTranslator::get(const int handle) const noexcept
{
    return m_handleList[static_cast<size_t>(handle)];
}

int HandleTranslator::add(HANDLE handle) noexcept
{
    for (int64_t limit = m_handleList.size(), k = 0; k < limit; ++k)
    {
        if (m_handleList[k] == nullptr)
        {
            m_handleList[k] = handle;
            return k;
        }
    }

    m_handleList.emplace_back(handle);
    return m_handleList.size() - 1;
}

void HandleTranslator::remove(const int handle) noexcept
{
    m_handleList[static_cast<uint64_t>(handle)] = nullptr;
}
<|endoftext|>


<commit_before>#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<int> dp(nums.size(), 1);
        for (int i = 0; i < nums.size(); i++) {
            for (int j = 0; j < i; j++) {
                // nums[i] should be contained as the last element in subsequence.
                if (nums[j] < nums[i] && dp[j] + 1 > dp[i]) {
                    dp[i] = dp[j] + 1;
                }
            }
        }

        int res = 0;
        for (int i : dp) {
            if (i > res) {
                res = i;
            }
        }
        return res;
    }
};
<commit_msg>Implemented the O(logN) algorithm for LIS<commit_after>#include <bits/stdc++.h>

using namespace std;

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        vector<int> ans;
        for (int x : nums) {
            auto it = lower_bound(ans.begin(), ans.end(), x);
            if (it == ans.end()) {
                ans.push_back(x);
            }
            else *it = x;
        }
        return ans.size();
    }
};
<|endoftext|>