static int SendOemRequestHookRaw(HRilClient client, int req_id, char *data, size_t len) {
    int token = 0;
    int ret = 0;
    uint32_t header = 0;
    android::Parcel p;
    RilClientPrv *client_prv;
    int maxfd = -1;

    client_prv = (RilClientPrv *)(client->prv);

    // Allocate a token.
    token = AllocateToken(&(client_prv->token_pool));
    if (token == 0) {
        ALOGE("%s: No token.", __FUNCTION__);
        return RIL_CLIENT_ERR_AGAIN;
    }

    // Record token for the request sent.
    if (RecordReqHistory(client_prv, token, req_id) != RIL_CLIENT_ERR_SUCCESS) {
        goto error;
    }

    // Make OEM request data.
    p.writeInt32(RIL_REQUEST_OEM_HOOK_RAW);
    p.writeInt32(token);
    p.writeInt32(len);
    p.write((void *)data, len);

    // DO TX: header(size).
    header = htonl(p.dataSize());

    if (DBG) ALOGD("%s(): token = %d\n", __FUNCTION__, token);

    ret = blockingWrite(client_prv->sock, (void *)&header, sizeof(header));
    if (ret < 0) {
        ALOGE("%s: send request header failed. (%d)", __FUNCTION__, ret);
        goto error;
    }

    // Do TX: response data.
    ret = blockingWrite(client_prv->sock, p.data(), p.dataSize());
    if (ret < 0) {
        ALOGE("%s: send request data failed. (%d)", __FUNCTION__, ret);
        goto error;
    }

    return RIL_CLIENT_ERR_SUCCESS;

error:
    FreeToken(&(client_prv->token_pool), token);
    ClearReqHistory(client_prv, token);

    return RIL_CLIENT_ERR_UNKNOWN;
}
Exemple #2
0
//int SoundFile::readChunk(int n, SoundStream *s)
int SoundFile::readChunk(int n)
{
    int c;
    //if(!s) s = stream;

    int ret = blockingRead(stream, tempWindowBuffer, n);
    if(equalLoudness()) {
        applyEqualLoudnessFilter(n);
        ret = blockingWrite(filteredStream, tempWindowBufferFiltered, ret);
    }
    if(ret < n) return ret;

    FilterState filterState;

    lock();

    //nextChunk();
    for(c=0; c<numChannels(); c++) {
        channels(c)->shift_left(n);
        //channels(c)->highPassFilter->getState(&filterState);
        toChannelBuffer(c, n);
        channels(c)->processNewChunk(&filterState);
    }
    //incrementChunkNum();
    setCurrentChunk(currentStreamChunk());
    unlock();
    return ret;
}
Exemple #3
0
/** Plays one chunk of sound to the associated stream
  @return true on success. false for end of file or error
*/
bool SoundFile::playChunk()
{
    /*
      int c;
      int ret = blockingRead(stream, tempWindowBuffer, framesPerChunk());
      if(equalLoudness()) ret = blockingRead(filteredStream, tempWindowBufferFiltered, framesPerChunk());
      if(ret < framesPerChunk()) return false;
      ret = blockingWrite(gdata->audio_stream, tempWindowBuffer, framesPerChunk());
      if(ret < framesPerChunk()) {
        fprintf(stderr, "Error writing to audio device\n");
      }

      lock();
      for(c=0; c<numChannels(); c++) {
        channels(c)->shift_left(framesPerChunk());
        toChannelBuffer(c, framesPerChunk());
    	  if(gdata->doingActive() && channels(c) == gdata->getActiveChannel()) {
          channels(c)->processChunk(currentChunk()+1);
    	  }
      }
      setCurrentChunk(currentStreamChunk());
      unlock();
      return true;
    */
    if(!setupPlayChunk()) return false;
    int ret = blockingWrite(gdata->audio_stream, tempWindowBuffer, framesPerChunk());
    if(ret < framesPerChunk()) {
        fprintf(stderr, "Error writing to audio device\n");
    }
    //setCurrentChunk(currentStreamChunk());
    return true;
}
Exemple #4
0
void TCPPipe::bufferedWrite(const void* data,size_t dataSize)
	{
	const char* dPtr=static_cast<const char*>(data);
	while(dataSize>0)
		{
		/* Determine the number of bytes to write in a single go: */
		size_t bytes=dataSize;
		if(bytes>writeSize)
			bytes=writeSize;
		
		/* Copy bytes into the write buffer: */
		memcpy(wbPos,dPtr,bytes);
		wbPos+=bytes;
		writeSize-=bytes;
		dPtr+=bytes;
		dataSize-=bytes;
		
		/* Send the write buffer if full: */
		if(writeSize==0)
			{
			/* Send data across the TCP socket: */
			blockingWrite(writeBuffer,bufferSize);
			
			/* Reset the write buffer: */
			wbPos=writeBuffer;
			writeSize=bufferSize;
			}
		}
	}
int Send(const char * cmd)
	{
	LOG(ARDUINO_MSG_VERBOSE,"Arduino::SendMsg - msg [%s]",cmd);
	write_lock.Lock();

	DWORD dwwritten = 0; 
	int len = strlen(cmd);

	char buf[256];
	if(len>256)
	{
		write_lock.Unlock();
		LOG(ERR,"Arduino::Send: Msg too long!");
		return -1;
	}

#ifndef USBCAN_PROTOCOL
	// surround message with {}
	sprintf_s(buf,256,"{%s}\r",cmd);
	len += 3;	// {}\r
#else
	sprintf_s(buf,256,"%s\r",cmd);
	len += 1;	// \r
#endif

	if  ( (dwwritten=blockingWrite(buf, len )) == -1)
		{
		LOG(ERR,"Arduino::SendMsg - Blocking write failed ! \n");
		write_lock.Unlock();
		return -1;
		}

	if (dwwritten != len)
		{
		write_lock.Unlock();
		LOG(ERR,"Arduino::SendMsg - Write didn't finish (%d out of %d bytes sent)\n", dwwritten,len);
		DWORD   dwErrors;
		COMSTAT comStat;
		ClearCommError(hCommPort, &dwErrors, &comStat);
		LOG(ERR,"Arduino::SendMsg - ClearCommError: Error flags: 0x%x, bytes in output queue: %d\n", dwErrors, comStat.cbOutQue);		
		return -1;
		}
	write_lock.Unlock();

#ifndef USBCAN_PROTOCOL
	LOG(ARDUINO_MSG_VERBOSE,"Arduino::SendMsg - completed succefully: %d written (%d bytes original)",dwwritten,dwwritten-3);
	return dwwritten-3;
#else
	LOG(ARDUINO_MSG_VERBOSE,"Arduino::SendMsg - completed succefully: %d written (%d bytes original)",dwwritten,dwwritten-1);
	return dwwritten-1;
#endif
}
Exemple #6
0
void SoundFile::finishRecordChunk(int n)
{
    if(equalLoudness()) applyEqualLoudnessFilter(n);

    FilterState filterState;

    lock();
    for(int c=0; c<numChannels(); c++) {
        channels(c)->shift_left(n);
        //std::copy(tempWindowBuffer[c], tempWindowBuffer[c]+n, channels(c)->end() - n);
        //channels(c)->highPassFilter->getState(&filterState);
        toChannelBuffer(c, n);
        //if(channels(c) == gdata->getActiveChannel())
        channels(c)->processNewChunk(&filterState);
    }
    unlock();

    int ret = blockingWrite(stream, tempWindowBuffer, n);
    if(ret < n) fprintf(stderr, "Error writing to disk\n");
    if(equalLoudness()) ret = blockingWrite(filteredStream, tempWindowBufferFiltered, n);
    if(ret < n) fprintf(stderr, "Error writing to disk\n");

    setCurrentChunk(currentStreamChunk());
}
Exemple #7
0
TCPPipe::~TCPPipe(void)
	{
	try
		{
		/* Send any leftover data still in the write buffer: */
		if(writeSize<bufferSize)
			blockingWrite(writeBuffer,bufferSize-writeSize);
		}
	catch(...)
		{
		/* This was a best effort to flush the pipe; if it fails, the pipe was probably already dead anyways... */
		}
	
	/* Delete the buffers: */
	delete[] readBuffer;
	delete[] writeBuffer;
	}
Exemple #8
0
void TCPPipe::initializePipe(TCPPipe::Endianness sEndianness)
	{
	/* Set socket options: */
	TCPSocket::setNoDelay(true);
	
	if(sEndianness==LittleEndian)
		{
		#if __BYTE_ORDER==__BIG_ENDIAN
		readMustSwapEndianness=writeMustSwapEndianness=true;
		#endif
		}
	else if(sEndianness==BigEndian)
		{
		#if __BYTE_ORDER==__LITTLE_ENDIAN
		readMustSwapEndianness=writeMustSwapEndianness=true;
		#endif
		}
	else if(sEndianness==Automatic)
		{
		/* Exchange a magic value to test for endianness on the other end: */
		unsigned int magic=0x12345678U;
		blockingWrite(&magic,sizeof(unsigned int));
		blockingRead(&magic,sizeof(unsigned int));
		if(magic==0x78563412U)
			readMustSwapEndianness=true;
		else if(magic!=0x12345678U)
			Misc::throwStdErr("Comm::TCPPipe: Unable to establish connection with host %s on port %d",getPeerHostname().c_str(),getPeerPortId());
		}
	
	/* Allocate the read and write buffers: */
	int maxSegSize=-1;
	socklen_t maxSegLen=sizeof(int);
	if(getsockopt(getFd(),IPPROTO_TCP,TCP_MAXSEG,&maxSegSize,&maxSegLen)<0)
		Misc::throwStdErr("Comm::TCPPipe: Unable to determine maximum TCP segment size");
	bufferSize=size_t(maxSegSize);
	readBuffer=new char[bufferSize];
	rbPos=readBuffer;
	readSize=0;
	writeBuffer=new char[bufferSize];
	wbPos=writeBuffer;
	writeSize=bufferSize;
	}
Exemple #9
0
static ssize processIncoming(Webs *wp, char *buf, ssize size, ssize nbytes, int *readMore)
{
    Ms      *ms;
    uchar   *data, *obuf;
    ssize   toWrite, written, copied, sofar;
    uint32  dlen;
    int     rc;

    ms = (Ms*) wp->ssl;
    *readMore = 0;
    sofar = 0;

    /*
        Process the received data. If there is application data, it is returned in data/dlen
     */
    rc = matrixSslReceivedData(ms->handle, (int) nbytes, &data, &dlen);

    while (1) {
        switch (rc) {
        case PS_SUCCESS:
            return sofar;

        case MATRIXSSL_REQUEST_SEND:
            toWrite = matrixSslGetOutdata(ms->handle, &obuf);
            if ((written = blockingWrite(wp, obuf, toWrite)) < 0) {
                error("MatrixSSL: Error in process");
                return -1;
            }
            matrixSslSentData(ms->handle, (int) written);
            if (ms->handle->err != SSL_ALERT_NONE && ms->handle->err != SSL_ALLOW_ANON_CONNECTION) {
                return -1;
            }
            *readMore = 1;
            return 0;

        case MATRIXSSL_REQUEST_RECV:
            /* Partial read. More read data required */
            *readMore = 1;
            ms->more = 1;
            return 0;

        case MATRIXSSL_HANDSHAKE_COMPLETE:
            *readMore = 0;
            return 0;

        case MATRIXSSL_RECEIVED_ALERT:
            assert(dlen == 2);
            if (data[0] == SSL_ALERT_LEVEL_FATAL) {
                return -1;
            } else if (data[1] == SSL_ALERT_CLOSE_NOTIFY) {
                //  ignore - graceful close
                return 0;
            }
            rc = matrixSslProcessedData(ms->handle, &data, &dlen);
            break;

        case MATRIXSSL_APP_DATA:
            copied = min((ssize) dlen, size);
            memcpy(buf, data, copied);
            buf += copied;
            size -= copied;
            data += copied;
            dlen = dlen - (int) copied;
            sofar += copied;
            ms->more = ((ssize) dlen > size) ? 1 : 0;
            if (!ms->more) {
                /* The MatrixSSL buffer has been consumed, see if we can get more data */
                rc = matrixSslProcessedData(ms->handle, &data, &dlen);
                break;
            }
            return sofar;

        default:
            return -1;
        }
    }
}
int OpenDevice( int com_port, int baud_rate, int disable_DTR )
{
	LOG(MAINFUNC,"Arduino::OpenDevice - com port %d, baud_rate %d, disable DTR %d",com_port,baud_rate,disable_DTR);
	init_lock.Lock();
	if (isConnected)
		{
		init_lock.Unlock();
		LOG(ERR,"Arduino::OpenDevice - already connected!");
		return ARDUINO_ALREADY_CONNECTED;
		}

	if (com_port==-1)
		{
		com_port = ARDUINO_DEFAULT_COM_PORT;
		LOG(MAINFUNC,"Arduino::OpenDevice - defaulting to comport %d",com_port);
		}
	if (baud_rate==-1)
		{
		baud_rate = ARDUINO_DEFAULT_BAUD_RATE;
		LOG(MAINFUNC,"Arduino::OpenDevice - defaulting to baud rate %d",baud_rate);
		}
	if (disable_DTR==-1)
		{
		disable_DTR = ARDUINO_DEFAULT_DTR_DISABLED;
		LOG(MAINFUNC,"Arduino::OpenDevice - defaulting to dtr disabled=%d",disable_DTR);
		}
	

	TCHAR COMx[32];
	int n = _stprintf_s(COMx, 32, _T("\\\\.\\COM%d"),com_port);
	long int err;
	BOOL fSuccess;	
	DCB dcb;

	LOG(MAINFUNC,"Arduino::OpenDevice - creating file handle for com port");
	hCommPort = CreateFile(
	COMx,
    GENERIC_READ | GENERIC_WRITE,
    FILE_SHARE_WRITE, // 0,
    NULL,
    OPEN_EXISTING,
    FILE_FLAG_OVERLAPPED,
    NULL
    );

	if (hCommPort == INVALID_HANDLE_VALUE) 
	{
		err=GetLastError();
		if (err==ERROR_ALREADY_EXISTS)
			{
			LOG(ERR,"Arduino::OpenDevice - Already opened by other process!");
			init_lock.Unlock();
			return ARDUINO_IN_USE;
			} 
		else
			{
			LOG(ERR,"Arduino::OpenDevice - CreateFileA failed %d!",err);
			init_lock.Unlock();
			return ARDUINO_OPEN_FAILED;
			}
	}

	LOG(MAINFUNC,"Arduino::OpenDevice - getting comm state");
	fSuccess = GetCommState(hCommPort, &dcb);

	if (!fSuccess) 
	{
		LOG(ERR,"Arduino::OpenDevice - GetCommStateFailed %d", err=GetLastError());
		PrintError(err);
		CloseHandle(hCommPort);
		hCommPort=INVALID_HANDLE_VALUE;
		init_lock.Unlock();
		return ARDUINO_GET_COMMSTATE_FAILED;
	}

	LOG(MAINFUNC,"Arduino::OpenDevice - setting comm state");
	dcb.BaudRate = baud_rate;
	dcb.ByteSize = 8;
	dcb.Parity = NOPARITY;
	dcb.StopBits = ONESTOPBIT;
	dcb.fDtrControl = (disable_DTR==1 ? DTR_CONTROL_DISABLE : DTR_CONTROL_ENABLE);	// to prevent Arduino from reseting when first sending something
		
	fSuccess = SetCommState(hCommPort, &dcb);
	if (!fSuccess) 
	{
		err=GetLastError();
		LOG(ERR,"Arduino::OpenDevice - SetCommStateFailed %d", err);
		CloseHandle(hCommPort);
		hCommPort=INVALID_HANDLE_VALUE;
		PrintError(err);
		init_lock.Unlock();
		return ARDUINO_SET_COMMSTATE_FAILED;
	}


	LOG(MAINFUNC,"Arduino::OpenDevice - enable listening to comm events");
	DWORD      dwStoredFlags;
	// listen only for events regarding errors and receive buffer
	dwStoredFlags = /*EV_BREAK | EV_CTS |*/ EV_DSR | /* EV_ERR | EV_RING | EV_RLSD | */ EV_RXCHAR /* | EV_RXFLAG | EV_TXEMPTY*/ ;
	if (!SetCommMask(hCommPort, dwStoredFlags))
	{
		err=GetLastError();
		LOG(ERR,"Arduino::OpenDevice - Error setting communications mask (err %d); abort!", err);
		CloseHandle(hCommPort);
		hCommPort=INVALID_HANDLE_VALUE;
		PrintError(err);
		init_lock.Unlock();
		return ARDUINO_SET_COMMMASK_FAILED;
	}

	// create event for write completed
	if ((ghWriteCompleteEvent = CreateEvent(NULL, FALSE, FALSE, NULL)) == NULL)
	{
		LOG(ERR,"Arduino::OpenDevice - Create 'Write Complete Event' failed (err %d); abort!", GetLastError());
		return ARDUINO_CREATE_EVENT_FAILED;
	}


	blockingWrite("\r\r\r",3);

	isConnected=true;

#ifdef USBCAN_PROTOCOL
	Send("Z0");	// we are not interested in time stamps, we generate our own
#else
	Send(":ping");
#endif

	init_lock.Unlock();
	LOG(MAINFUNC,"Arduino::OpenDevice - port configured");
	return ARDUINO_INIT_OK;
}