/** Write a unsigned 16-bit integer * \param[in] n number to be written */ void BufferedWriter::putNum(uint16_t n) { if (n < 256) { putNum((uint8_t)n); return; } uint8_t len = n < 1000 ? 3 : n < 10000 ? 4 : 5; if ((in_ + len) >= sizeof(buf_)) { writeBuf(); } in_ += len; char* str = buf_ + in_ - 1; do { // avoid mod, it's slow. uint16_t tmp = n; n /= 10; *str-- = '0' + tmp - 10 * n; } while (n); }
/** * write HEX * \param[in] n number to be written as HEX */ void BufferedWriter::putHex(uint32_t n) { uint8_t len; if (n < 0X10000) { len = n < 0X10 ? 1 : n < 0X100 ? 2 : n < 0X1000 ? 3 : 4; } else { len = n < 0X100000 ? 5 : n < 0X1000000 ? 6 : n < 0X10000000 ? 7 : 8; } if ((in_ + len) >= sizeof(buf_)) { writeBuf(); } in_ += len; char* str = buf_ + in_ - 1; do { uint8_t h = n & 0XF; *str-- = h + (h < 10 ? '0' : 'A' - 10); n >>= 4; } while (n); }
static void txfsk () { // select FSK modem (from sleep mode) writeReg(RegOpMode, 0x10); // FSK, BT=0.5 ASSERT(readReg(RegOpMode) == 0x10); // enter standby mode (required for FIFO loading)) opmode(OPMODE_STANDBY); // set bitrate writeReg(FSKRegBitrateMsb, 0x02); // 50kbps writeReg(FSKRegBitrateLsb, 0x80); // set frequency deviation writeReg(FSKRegFdevMsb, 0x01); // +/- 25kHz writeReg(FSKRegFdevLsb, 0x99); // frame and packet handler settings writeReg(FSKRegPreambleMsb, 0x00); writeReg(FSKRegPreambleLsb, 0x05); writeReg(FSKRegSyncConfig, 0x12); writeReg(FSKRegPacketConfig1, 0xD0); writeReg(FSKRegPacketConfig2, 0x40); writeReg(FSKRegSyncValue1, 0xC1); writeReg(FSKRegSyncValue2, 0x94); writeReg(FSKRegSyncValue3, 0xC1); // configure frequency configChannel(); // configure output power configPower(); // set the IRQ mapping DIO0=PacketSent DIO1=NOP DIO2=NOP writeReg(RegDioMapping1, MAP_DIO0_FSK_READY|MAP_DIO1_FSK_NOP|MAP_DIO2_FSK_TXNOP); // initialize the payload size and address pointers writeReg(FSKRegPayloadLength, LMIC.dataLen+1); // (insert length byte into payload)) // download length byte and buffer to the radio FIFO writeReg(RegFifo, LMIC.dataLen); writeBuf(RegFifo, LMIC.frame, LMIC.dataLen); // enable antenna switch for TX hal_pin_rxtx(1); // now we actually start the transmission opmode(OPMODE_TX); }
void TGroup::draw() { if( buffer == 0 ) { getBuffer(); if( buffer != 0 ) { lockFlag++; redraw(); lockFlag--; } } if( buffer != 0 ) writeBuf( 0, 0, size.x, size.y, buffer ); else { clip = getClipRect(); redraw(); clip = getExtent(); } }
void TCluster::drawMultiBox(const char *icon, const char *marker) { TDrawBuffer b; ushort color; int i, j, cur; ushort cNorm = getColor(0x0301); ushort cSel = getColor(0x0402); ushort cDis = getColor(0x0505); for (i = 0; i <= size.y; i++) { b.moveChar(0, ' ', (uchar)cNorm, size.x); for (j = 0; j <= (strings->getCount() - 1) / size.y + 1; j++) { cur = j * size.y + i; if (cur < strings->getCount()) { int col = column(cur); if (((col + strlen((const char *)strings->at(cur)) + 5) < (sizeof(b) / sizeof(ushort))) && (col < size.x)) { if (!buttonState(cur)) color = cDis; else if ((cur == sel) && (state & sfSelected) != 0) color = cSel; else color = cNorm; b.moveChar(col, ' ', color, size.x - col); b.moveCStr(col, icon, color); b.putChar(col + 2, marker[multiMark(cur)]); b.moveCStr(col + 5, (char *)(strings->at(cur)), color); if (showMarkers && ((state & sfSelected) != 0) && cur == sel) { b.putChar(col, specialChars[0]); b.putChar(column(cur + size.y) - 1, specialChars[1]); } } } } writeBuf(0, i, size.x, 1, b); } setCursor(column(sel) + 2, row(sel)); }
static void txlora () { // select LoRa modem (from sleep mode) //writeReg(RegOpMode, OPMODE_LORA); opmodeLora(); ASSERT((readReg(RegOpMode) & OPMODE_LORA) != 0); // enter standby mode (required for FIFO loading)) opmode(OPMODE_STANDBY); // configure LoRa modem (cfg1, cfg2) configLoraModem(); // configure frequency configChannel(); // configure output power writeReg(RegPaRamp, (readReg(RegPaRamp) & 0xF0) | 0x08); // set PA ramp-up time 50 uSec configPower(); // set sync word writeReg(LORARegSyncWord, LORA_MAC_PREAMBLE); // set the IRQ mapping DIO0=TxDone DIO1=NOP DIO2=NOP writeReg(RegDioMapping1, MAP_DIO0_LORA_TXDONE|MAP_DIO1_LORA_NOP|MAP_DIO2_LORA_NOP); // clear all radio IRQ flags writeReg(LORARegIrqFlags, 0xFF); // mask all IRQs but TxDone writeReg(LORARegIrqFlagsMask, ~IRQ_LORA_TXDONE_MASK); // initialize the payload size and address pointers writeReg(LORARegFifoTxBaseAddr, 0x00); writeReg(LORARegFifoAddrPtr, 0x00); writeReg(LORARegPayloadLength, LMIC.dataLen); // download buffer to the radio FIFO writeBuf(RegFifo, LMIC.frame, LMIC.dataLen); // enable antenna switch for TX hal_pin_rxtx(1); // now we actually start the transmission opmode(OPMODE_TX); }
/** Write an unsigned 32-bit number * \param[in] n number to be written */ void BufferedWriter::putNum(uint32_t n) { uint8_t len; if (n < 0X10000) { putNum((uint16_t)n); return; } if (n < 10000000) { len = n < 100000 ? 5 : n < 1000000 ? 6 : 7; } else { len = n < 100000000 ? 8 : n < 1000000000 ? 9 : 10; } if ((in_ + len) >= sizeof(buf_)) { writeBuf(); } in_ += len; char* str = buf_ + in_ - 1; do { // avoid mod, it's slow. uint32_t tmp = n; n /= 10; *str-- = '0' + tmp - 10 * n; } while (n); }
static inline void SV_PackEntity( int edictIdx, edict_t* ent, SendTable* pSendTable, EntityChange_t changeType, CFrameSnapshot *pSnapshot ) { int iSerialNum = pSnapshot->m_Entities[ edictIdx ].m_nSerialNumber; // Check to see if this entity specifies its changes. // If so, then try to early out making the fullpack bool bUsedPrev = false; if ( changeType == ENTITY_CHANGE_NONE ) { // Now this may not work if we didn't previously send a packet; // if not, then we gotta compute it bUsedPrev = framesnapshot->UsePreviouslySentPacket( pSnapshot, edictIdx, iSerialNum ); } if ( !bUsedPrev || sv_debugmanualmode.GetInt() ) { // First encode the entity's data. char packedData[MAX_PACKEDENTITY_DATA]; bf_write writeBuf( "SV_PackEntity->writeBuf", packedData, sizeof( packedData ) ); // (avoid constructor overhead). unsigned char tempData[ sizeof( CSendProxyRecipients ) * MAX_DATATABLE_PROXIES ]; CUtlMemory< CSendProxyRecipients > recip( (CSendProxyRecipients*)tempData, pSendTable->GetNumDataTableProxies() ); if( !SendTable_Encode( pSendTable, ent->m_pEnt, &writeBuf, NULL, edictIdx, &recip ) ) { Host_Error( "SV_PackEntity: SendTable_Encode returned false (ent %d).\n", edictIdx ); } SV_EnsureInstanceBaseline( edictIdx, packedData, writeBuf.GetNumBytesWritten() ); int nFlatProps = SendTable_GetNumFlatProps( pSendTable ); IChangeFrameList *pChangeFrame; // If this entity was previously in there, then it should have a valid IChangeFrameList // which we can delta against to figure out which properties have changed. // // If not, then we want to setup a new IChangeFrameList. PackedEntity *pPrevFrame = framesnapshot->GetPreviouslySentPacket( edictIdx, pSnapshot->m_Entities[ edictIdx ].m_nSerialNumber ); if ( pPrevFrame ) { // Calculate a delta. bf_read bfPrev( "SV_PackEntity->bfPrev", pPrevFrame->LockData(), pPrevFrame->GetNumBytes() ); bf_read bfNew( "SV_PackEntity->bfNew", packedData, writeBuf.GetNumBytesWritten() ); int deltaProps[MAX_DATATABLE_PROPS]; int nChanges = SendTable_CalcDelta( pSendTable, pPrevFrame->LockData(), pPrevFrame->GetNumBits(), packedData, writeBuf.GetNumBitsWritten(), deltaProps, ARRAYSIZE( deltaProps ), edictIdx ); // If it's non-manual-mode, but we detect that there are no changes here, then just // use the previous pSnapshot if it's available (as though the entity were manual mode). // It would be interesting to hook here and see how many non-manual-mode entities // are winding up with no changes. if ( nChanges == 0 ) { if ( changeType == ENTITY_CHANGE_NONE ) { for ( int iDeltaProp=0; iDeltaProp < nChanges; iDeltaProp++ ) { Msg( "Entity %d (class '%s') reported ENTITY_CHANGE_NONE but '%s' changed.\n", edictIdx, STRING( ent->classname ), pSendTable->GetProp( deltaProps[iDeltaProp] )->GetName() ); } } else { if ( pPrevFrame->CompareRecipients( recip ) ) { if ( framesnapshot->UsePreviouslySentPacket( pSnapshot, edictIdx, iSerialNum ) ) return; } } } // Ok, now snag the changeframe from the previous frame and update the 'last frame changed' // for the properties in the delta. pChangeFrame = pPrevFrame->SnagChangeFrameList(); ErrorIfNot( pChangeFrame && pChangeFrame->GetNumProps() == nFlatProps, ("SV_PackEntity: SnagChangeFrameList returned null") ); pChangeFrame->SetChangeTick( deltaProps, nChanges, pSnapshot->m_nTickNumber ); } else { // Ok, init the change frames for the first time. pChangeFrame = AllocChangeFrameList( nFlatProps, pSnapshot->m_nTickNumber ); } // Now make a PackedEntity and store the new packed data in there. PackedEntity *pCurFrame = framesnapshot->CreatePackedEntity( pSnapshot, edictIdx ); pCurFrame->SetChangeFrameList( pChangeFrame ); pCurFrame->m_nEntityIndex = edictIdx; pCurFrame->m_pSendTable = pSendTable; pCurFrame->AllocAndCopyPadded( packedData, writeBuf.GetNumBytesWritten(), &g_PackedDataAllocator ); pCurFrame->SetRecipients( recip ); } }
void CHLTVClientState::ReadDeltaEnt( CEntityReadInfo &u ) { const int i = u.m_nNewEntity; CFrameSnapshot *pFromSnapshot = u.m_pFrom->GetSnapshot(); CFrameSnapshot *pSnapshot = u.m_pTo->GetSnapshot(); Assert( i < pFromSnapshot->m_nNumEntities ); pSnapshot->m_pEntities[i] = pFromSnapshot->m_pEntities[i]; PackedEntity *pToPackedEntity = framesnapshotmanager->CreatePackedEntity( pSnapshot, i ); // WARNING! get pFromPackedEntity after new pPackedEntity has been created, otherwise pointer may be wrong PackedEntity *pFromPackedEntity = framesnapshotmanager->GetPackedEntity( pFromSnapshot, i ); pToPackedEntity->SetServerAndClientClass( pFromPackedEntity->m_pServerClass, pFromPackedEntity->m_pClientClass ); // create a copy of the pFromSnapshot ChangeFrameList IChangeFrameList* pChangeFrame = NULL; if ( !m_bSaveMemory ) { pChangeFrame = pFromPackedEntity->GetChangeFrameList()->Copy(); pToPackedEntity->SetChangeFrameList( pChangeFrame ); } // Make space for the baseline data. char packedData[MAX_PACKEDENTITY_DATA]; const void *pFromData; int nFromBits; if ( pFromPackedEntity->IsCompressed() ) { pFromData = m_pHLTV->UncompressPackedEntity( pFromPackedEntity, nFromBits ); } else { pFromData = pFromPackedEntity->GetData(); nFromBits = pFromPackedEntity->GetNumBits(); } bf_read fromBuf( "HLTV_ReadEnterPVS1", pFromData, Bits2Bytes( nFromBits ), nFromBits ); bf_write writeBuf( "HLTV_ReadEnterPVS2", packedData, sizeof( packedData ) ); int changedProps[MAX_DATATABLE_PROPS]; // decode baseline, is compressed against zero values int nChangedProps = RecvTable_MergeDeltas( pToPackedEntity->m_pClientClass->m_pRecvTable, &fromBuf, u.m_pBuf, &writeBuf, -1, false, changedProps ); // update change tick in ChangeFrameList if ( pChangeFrame ) { pChangeFrame->SetChangeTick( changedProps, nChangedProps, pSnapshot->m_nTickCount ); } if ( m_bSaveMemory ) { int bits = writeBuf.GetNumBitsWritten(); const char *compressedData = m_pHLTV->CompressPackedEntity( pToPackedEntity->m_pServerClass, (char*)writeBuf.GetData(), bits ); // store as compressed data and don't use mem pools pToPackedEntity->AllocAndCopyPadded( compressedData, Bits2Bytes(bits) ); pToPackedEntity->SetCompressed(); } else { // store as normal pToPackedEntity->AllocAndCopyPadded( packedData, writeBuf.GetNumBytesWritten() ); } u.m_pTo->last_entity = u.m_nNewEntity; u.m_pTo->transmit_entity.Set( u.m_nNewEntity ); u.NextOldEntity(); }
void CHLTVClientState::CopyNewEntity( CEntityReadInfo &u, int iClass, int iSerialNum ) { ServerClass *pServerClass = SV_FindServerClass( iClass ); Assert( pServerClass ); ClientClass *pClientClass = GetClientClass( iClass ); Assert( pClientClass ); const int ent = u.m_nNewEntity; // copy class & serial CFrameSnapshot *pSnapshot = u.m_pTo->GetSnapshot(); pSnapshot->m_pEntities[ent].m_nSerialNumber = iSerialNum; pSnapshot->m_pEntities[ent].m_pClass = pServerClass; // Get either the static or instance baseline. const void *pFromData = NULL; int nFromBits = 0; int nFromTick = 0; // MOTODO get tick when baseline last changed PackedEntity *baseline = u.m_bAsDelta ? GetEntityBaseline( u.m_nBaseline, ent ) : NULL; if ( baseline && baseline->m_pClientClass == pClientClass ) { Assert( !baseline->IsCompressed() ); pFromData = baseline->GetData(); nFromBits = baseline->GetNumBits(); } else { // Every entity must have a static or an instance baseline when we get here. ErrorIfNot( GetClassBaseline( iClass, &pFromData, &nFromBits ), ("HLTV_CopyNewEntity: GetDynamicBaseline(%d) failed.", iClass) ); nFromBits *= 8; // convert to bits } // create new ChangeFrameList containing all properties set as changed int nFlatProps = SendTable_GetNumFlatProps( pServerClass->m_pTable ); IChangeFrameList *pChangeFrame = NULL; if ( !m_bSaveMemory ) { pChangeFrame = AllocChangeFrameList( nFlatProps, nFromTick ); } // Now make a PackedEntity and store the new packed data in there. PackedEntity *pPackedEntity = framesnapshotmanager->CreatePackedEntity( pSnapshot, ent ); pPackedEntity->SetChangeFrameList( pChangeFrame ); pPackedEntity->SetServerAndClientClass( pServerClass, pClientClass ); // Make space for the baseline data. char packedData[MAX_PACKEDENTITY_DATA]; bf_read fromBuf( "HLTV_ReadEnterPVS1", pFromData, Bits2Bytes( nFromBits ), nFromBits ); bf_write writeBuf( "HLTV_ReadEnterPVS2", packedData, sizeof( packedData ) ); int changedProps[MAX_DATATABLE_PROPS]; // decode basline, is compressed against zero values int nChangedProps = RecvTable_MergeDeltas( pClientClass->m_pRecvTable, &fromBuf, u.m_pBuf, &writeBuf, -1, false, changedProps ); // update change tick in ChangeFrameList if ( pChangeFrame ) { pChangeFrame->SetChangeTick( changedProps, nChangedProps, pSnapshot->m_nTickCount ); } if ( u.m_bUpdateBaselines ) { SetEntityBaseline( (u.m_nBaseline==0)?1:0, pClientClass, u.m_nNewEntity, packedData, writeBuf.GetNumBytesWritten() ); } pPackedEntity->AllocAndCopyPadded( packedData, writeBuf.GetNumBytesWritten() ); // If ent doesn't think it's in PVS, signal that it is Assert( u.m_pTo->last_entity <= ent ); u.m_pTo->last_entity = ent; u.m_pTo->transmit_entity.Set( ent ); }
/********************************************************************* * @fn osal_nv_write * * @brief Write a data item to NV. Function can write an entire item to NV or * an element of an item by indexing into the item with an offset. * * @param id - Valid NV item Id. * @param ndx - Index offset into item * @param len - Length of data to write. * @param *buf - Data to write. * * @return SUCCESS if successful, NV_ITEM_UNINIT if item did not * exist in NV and offset is non-zero, NV_OPER_FAILED if failure. */ uint8 osal_nv_write( uint16 id, uint16 ndx, uint16 len, void *buf ) { uint8 rtrn = SUCCESS; if ( !OSAL_NV_CHECK_BUS_VOLTAGE ) { return NV_OPER_FAILED; } else if ( len != 0 ) { osalNvHdr_t hdr; uint16 origOff, srcOff; uint16 cnt, chk; uint8 *ptr, srcPg; origOff = srcOff = findItem( id ); srcPg = findPg; if ( srcOff == OSAL_NV_ITEM_NULL ) { return NV_ITEM_UNINIT; } HalFlashRead(srcPg, (srcOff - OSAL_NV_HDR_SIZE), (uint8 *)(&hdr), OSAL_NV_HDR_SIZE); if ( hdr.len < (ndx + len) ) { return NV_OPER_FAILED; } srcOff += ndx; ptr = buf; cnt = len; chk = 0; while ( cnt-- ) { uint8 tmp; HalFlashRead(srcPg, srcOff, &tmp, 1); if ( tmp != *ptr ) { chk = 1; // Mark that at least one byte is different. // Calculate expected checksum after transferring old data and writing new data. hdr.chk -= tmp; hdr.chk += *ptr; } srcOff++; ptr++; } if ( chk != 0 ) // If the buffer to write is different in one or more bytes. { uint8 comPg = OSAL_NV_PAGE_NULL; uint8 dstPg = initItem( FALSE, id, hdr.len, &comPg ); if ( dstPg != OSAL_NV_PAGE_NULL ) { uint16 tmp = OSAL_NV_DATA_SIZE( hdr.len ); uint16 dstOff = pgOff[dstPg-OSAL_NV_PAGE_BEG] - tmp; srcOff = origOff; /* Prevent excessive re-writes to item header caused by numerous, rapid, & successive * OSAL_Nv interruptions caused by resets. */ if ( hdr.stat == OSAL_NV_ERASED_ID ) { setItem( srcPg, srcOff, eNvXfer ); } xferBuf( srcPg, srcOff, dstPg, dstOff, ndx ); srcOff += ndx; dstOff += ndx; writeBuf( dstPg, dstOff, len, buf ); srcOff += len; dstOff += len; xferBuf( srcPg, srcOff, dstPg, dstOff, (hdr.len-ndx-len) ); // Calculate and write the new checksum. dstOff = pgOff[dstPg-OSAL_NV_PAGE_BEG] - tmp; if ( hdr.chk == calcChkF( dstPg, dstOff, hdr.len ) ) { if ( hdr.chk != setChk( dstPg, dstOff, hdr.chk ) ) { rtrn = NV_OPER_FAILED; } else { hotItemUpdate(dstPg, dstOff, hdr.id); } } else { rtrn = NV_OPER_FAILED; } } else { rtrn = NV_OPER_FAILED; } if ( comPg != OSAL_NV_PAGE_NULL ) { /* Even though the page compaction succeeded, if the new item is coming from the compacted * page and writing the new value failed, then the compaction must be aborted. */ if ( (srcPg == comPg) && (rtrn == NV_OPER_FAILED) ) { erasePage( pgRes ); } else { COMPACT_PAGE_CLEANUP( comPg ); } } /* Zero of the old item must wait until after compact page cleanup has finished - if the item * is zeroed before and cleanup is interrupted by a power-cycle, the new item can be lost. */ if ( (srcPg != comPg) && (rtrn != NV_OPER_FAILED) ) { setItem( srcPg, origOff, eNvZero ); } } } return rtrn; }
void BufferedSocket::threadSendFile(InputStream* file) throw(Exception) { dcassert(sock); if(!sock) return; dcassert(file != NULL); size_t sockSize = (size_t)sock->getSocketOptInt(SO_SNDBUF); size_t bufSize = max(sockSize, (size_t)64*1024); vector<uint8_t> readBuf(bufSize); vector<uint8_t> writeBuf(bufSize); size_t readPos = 0; bool readDone = false; dcdebug("Starting threadSend\n"); while(true) { if(!readDone && readBuf.size() > readPos) { // Fill read buffer size_t bytesRead = readBuf.size() - readPos; size_t actual = file->read(&readBuf[readPos], bytesRead); if(bytesRead > 0) { fire(BufferedSocketListener::BytesSent(), bytesRead, 0); } if(actual == 0) { readDone = true; } else { readPos += actual; } } if(readDone && readPos == 0) { fire(BufferedSocketListener::TransmitDone()); return; } readBuf.swap(writeBuf); readBuf.resize(bufSize); writeBuf.resize(readPos); readPos = 0; size_t writePos = 0; while(writePos < writeBuf.size()) { if(disconnecting) return; size_t writeSize = min(sockSize / 2, writeBuf.size() - writePos); int written = sock->write(&writeBuf[writePos], writeSize); if(written > 0) { writePos += written; fire(BufferedSocketListener::BytesSent(), 0, written); } else if(written == -1) { if(!readDone && readPos < readBuf.size()) { // Read a little since we're blocking anyway... size_t bytesRead = min(readBuf.size() - readPos, readBuf.size() / 2); size_t actual = file->read(&readBuf[readPos], bytesRead); if(bytesRead > 0) { fire(BufferedSocketListener::BytesSent(), bytesRead, 0); } if(actual == 0) { readDone = true; } else { readPos += actual; } } else { while(!disconnecting) { int w = sock->wait(POLL_TIMEOUT, Socket::WAIT_WRITE | Socket::WAIT_READ); if(w & Socket::WAIT_READ) { threadRead(); } if(w & Socket::WAIT_WRITE) { break; } } } } } } }
void BufferedSocket::threadSendFile(InputStream* file) throw(Exception) { if(state != RUNNING) return; if(disconnecting) return; dcassert(file != NULL); size_t sockSize = (size_t)sock->getSocketOptInt(SO_SNDBUF); size_t bufSize = max(sockSize, (size_t)64*1024); ByteVector readBuf(bufSize); ByteVector writeBuf(bufSize); size_t readPos = 0; bool readDone = false; dcdebug("Starting threadSend\n"); UploadManager *um = UploadManager::getInstance(); size_t sendMaximum, start = 0, current= 0; bool throttling; while(true) { if(!readDone && readBuf.size() > readPos) { // Fill read buffer size_t bytesRead = readBuf.size() - readPos; size_t actual = file->read(&readBuf[readPos], bytesRead); if(bytesRead > 0) { fire(BufferedSocketListener::BytesSent(), bytesRead, 0); } if(actual == 0) { readDone = true; } else { readPos += actual; } } if(readDone && readPos == 0) { fire(BufferedSocketListener::TransmitDone()); return; } readBuf.swap(writeBuf); readBuf.resize(bufSize); writeBuf.resize(readPos); readPos = 0; size_t writePos = 0; while(writePos < writeBuf.size()) { if(disconnecting) return; throttling = BOOLSETTING(THROTTLE_ENABLE); size_t writeSize; if(throttling) { start = TimerManager::getTick(); sendMaximum = um->throttleGetSlice(); if(sendMaximum < 0) { throttling = false; writeSize = min(sockSize / 2, writeBuf.size() - writePos); } else { writeSize = min(min(sockSize / 2, writeBuf.size() - writePos), sendMaximum); } } else { writeSize = min(sockSize / 2, writeBuf.size() - writePos); } int written = sock->write(&writeBuf[writePos], writeSize); if(written > 0) { writePos += written; fire(BufferedSocketListener::BytesSent(), 0, written); if(throttling) { int32_t cycle_time = um->throttleCycleTime(); current = TimerManager::getTick(); int32_t sleep_time = cycle_time - (current - start); if (sleep_time > 0 && sleep_time <= cycle_time) { Thread::sleep(sleep_time); } } } else if(written == -1) { if(!readDone && readPos < readBuf.size()) { // Read a little since we're blocking anyway... size_t bytesRead = min(readBuf.size() - readPos, readBuf.size() / 2); size_t actual = file->read(&readBuf[readPos], bytesRead); if(bytesRead > 0) { fire(BufferedSocketListener::BytesSent(), bytesRead, 0); } if(actual == 0) { readDone = true; } else { readPos += actual; } } else { while(!disconnecting) { int w = sock->wait(POLL_TIMEOUT, Socket::WAIT_WRITE | Socket::WAIT_READ); if(w & Socket::WAIT_READ) { threadRead(); } if(w & Socket::WAIT_WRITE) { break; } } } } } } }
/********************************************************************* * @fn compactPage * * @brief Compacts the page specified. * * @param srcPg - Valid NV page to erase. * * @return none */ static void compactPage( uint8 srcPg ) { uint16 dstOff = pgOff[pgRes-OSAL_NV_PAGE_BEG]; uint16 srcOff = OSAL_NV_ZEROED_ID; osalNvHdr_t hdr; // Mark page as being in process of compaction. writeWordH( srcPg, OSAL_NV_PG_XFER, (uint8*)(&srcOff) ); srcOff = OSAL_NV_PAGE_HDR_SIZE; do { uint16 sz; HalFlashRead(srcPg, srcOff, (uint8 *)(&hdr), OSAL_NV_HDR_SIZE); if ( hdr.id == OSAL_NV_ERASED_ID ) { break; } srcOff += OSAL_NV_HDR_SIZE; if ( (srcOff + hdr.len) > OSAL_NV_PAGE_FREE ) { break; } sz = OSAL_NV_DATA_SIZE( hdr.len ); if ( hdr.id != OSAL_NV_ZEROED_ID ) { if ( hdr.chk == calcChkF( srcPg, srcOff, hdr.len ) ) { setItem( srcPg, srcOff, eNvXfer ); writeBuf( pgRes, dstOff, OSAL_NV_HDR_SIZE, (byte *)(&hdr) ); dstOff += OSAL_NV_HDR_SIZE; xferBuf( srcPg, srcOff, pgRes, dstOff, sz ); dstOff += sz; } setItem( srcPg, srcOff, eNvZero ); // Mark old location as invalid. } srcOff += sz; } while ( TRUE ); pgOff[pgRes-OSAL_NV_PAGE_BEG] = dstOff; /* In order to recover from a page compaction that is interrupted, * the logic in osal_nv_init() depends upon the following order: * 1. Compacted page is erased. * 2. State of the target of compaction is changed ePgActive to ePgInUse. */ erasePage( srcPg ); // Mark the reserve page as being in use. setPageUse( pgRes, TRUE ); // Set the reserve page to be the newly erased page. pgRes = srcPg; }
/* Write null-terminated string to dst steam. */ static void writeStr(ufwCtx h, const char *s) { writeBuf(h, strlen(s), s); }
// NOTE: This is the main output routine for strings. AOutputStream& AOutputStream::operator<<(const char *foo) { if(!foo) return *this; writeBuf(foo); return *this; }
TInt CNcmCommunicationInterface::WriteInterruptData(TInt aEndPoint, TDesC8& aDes, TInt aLength) { OstTraceFunctionEntry1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_ENTRY, this ); TInt ret; RTimer timer; ret = timer.CreateLocal(); if ( ret ) { OstTrace1( TRACE_FATAL, CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA, "\ttimer.CreateLocal = %d- returning", ret); OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_EXIT, this ); return ret; } TRequestStatus status; TRequestStatus timerStatus; TEndpointBuffer epBuffer; ret = iPort.OpenEndpoint(epBuffer, aEndPoint); if (ret != KErrNone) { timer.Close(); OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_EXIT_DUP1, this ); return ret; } TAny *buf; TUint size; ret = epBuffer.GetInBufferRange(buf, size); if (ret != KErrNone) { timer.Close(); OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_EXIT_DUP2, this ); return ret; } else if (size < aLength) { timer.Close(); OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_EXIT_DUP3, this ); return KErrArgument; } TPtr8 writeBuf((TUint8 *)buf, size); writeBuf.Copy(aDes.Ptr(), aLength); ret = epBuffer.WriteBuffer(buf, writeBuf.Size(), ETrue, status); if (ret != KErrNone) { timer.Close(); OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_EXIT_DUP4, this ); return ret; } const TInt KWriteDataTimeout = 1000000; timer.After(timerStatus, KWriteDataTimeout); User::WaitForRequest(status, timerStatus); if ( timerStatus != KRequestPending ) { // Timeout occurred, silently ignore error condition. // Assuming that the line has been disconnected OstTrace0( TRACE_ERROR, CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA1, "CNcmCommunicationInterface::WriteInterruptData() - Timeout occurred"); iPort.WriteCancel(epBuffer.BufferNumber()); User::WaitForRequest(status); ret = timerStatus.Int(); } else { OstTrace0( TRACE_ERROR, CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA2, "CNcmCommunicationInterface::WriteInterruptData() - Write completed"); timer.Cancel(); User::WaitForRequest(timerStatus); ret = status.Int(); } epBuffer.Close(); timer.Close(); OstTraceFunctionExit1( CNCMCOMMUNICATIONINTERFACE_WRITEINTERRUPTDATA_EXIT_DUP5, this ); return ret; }
int advFileCopy(int destfd, int srcfd, unsigned long size, const char *name, int semid, int logfd, int sigfd, int confd){ unsigned long size_so_far = 0; struct signalfd_siginfo fdsi; struct pollfd pollfds[2]; int readret, writeret, shellReturn; struct buffer buf; struct buffer * fbuf = &buf; if (createBuf(fbuf, 3000) < 0) return -1; /* Setting up stuff for Polling */ pollfds[0].fd = srcfd; /* data incoming from peer */ pollfds[0].events = POLLIN; pollfds[0].revents = 0; pollfds[1].fd = sigfd; /* communication with signalfd */ pollfds[1].events = POLLIN; pollfds[1].revents = 0; while (1) { if ( poll(pollfds, 2, -1) <= 0) { if (errno == EINTR || errno == EAGAIN ) continue; /* Signals */ logmsg(semid, logfd, LOGLEVEL_FATAL, "POLLING Error:%d - %s.\n", errno, strerror(errno)); return -1; } if ( pollfds[0].revents & POLLIN ) { /* peer calls */ switch((readret = readToBuf(srcfd, fbuf))){ case -1: logmsg(semid, logfd, LOGLEVEL_FATAL, "FATAL (advFileCopy): read()-error from fd.\n"); shellReturn = EXIT_FAILURE; break; case -2: logmsg(semid, logfd, LOGLEVEL_WARN, "WARNING (advFileCopy): couldn't read (EINTR or EAGAIN). This " "shouldn't happen if signalfd() is used.\n"); shellReturn = EXIT_FAILURE; break; case 0: /* end of transfer */ /* might also throw a POLLHUP */ if (size != size_so_far){ logmsg(semid, logfd, LOGLEVEL_WARN, "Error(advFileCopy) File transfer was quit from other side.\n"); shellReturn = EXIT_FAILURE; } else { logmsg(semid, logfd, LOGLEVEL_WARN, "Error(advFileCopy) File transfer completed successfully.\n"); shellReturn = EXIT_SUCCESS; } break; default: size_so_far += readret; } while (-2 == ( writeret = writeBuf(destfd, fbuf))); if (writeret < 0) { logmsg(semid, logfd, LOGLEVEL_WARN, "Error(advFileCopy) Failure on write operation.\n"); shellReturn = EXIT_FAILURE; break; } } else if(pollfds[1].revents & POLLIN) { /* incoming signal */ readret = read(sigfd, &fdsi, sizeof(struct signalfd_siginfo)); if (readret != sizeof(struct signalfd_siginfo)){ fprintf(stderr, "signalfd returned something broken"); shellReturn = EXIT_FAILURE; } switch(fdsi.ssi_signo){ case SIGINT: case SIGQUIT: logmsg(semid, logfd, LOGLEVEL_VERBOSE, "Child %d quit with status %d\n", fdsi.ssi_pid, fdsi.ssi_status); shellReturn = EXIT_SUCCESS; break; case SIGUSR1: consolemsg(semid, confd, "%s is %.1F percent done\n", name, (double)size_so_far/size); break; default: logmsg(semid, logfd, LOGLEVEL_WARN, "Encountered unknown signal on sigfd %d", fdsi.ssi_signo); } } else { /* Somethings broken with poll */ fprintf(stderr, "Dunno what to do with this poll"); shellReturn = EXIT_FAILURE; } if (shellReturn !=EXIT_NO) break; } freeBuf(fbuf); return shellReturn; }
/* Write integer value as ASCII to dst stream. */ static void writeInt(ufwCtx h, long value) { char buf[50]; sprintf(buf, "%ld", value); writeBuf(h, strlen(buf), buf); }