static int32_t sendPacket()

in source/core_mqtt.c [596:670]


static int32_t sendPacket( MQTTContext_t * pContext,
                           const uint8_t * pBufferToSend,
                           size_t bytesToSend )
{
    const uint8_t * pIndex = pBufferToSend;
    size_t bytesRemaining = bytesToSend;
    int32_t totalBytesSent = 0, bytesSent;
    uint32_t lastSendTimeMs = 0U, timeSinceLastSendMs = 0U;
    bool sendError = false;

    assert( pContext != NULL );
    assert( pContext->getTime != NULL );
    assert( pContext->transportInterface.send != NULL );
    assert( pIndex != NULL );

    bytesRemaining = bytesToSend;

    /* Record the most recent time of successful transmission. */
    lastSendTimeMs = pContext->getTime();

    /* Loop until the entire packet is sent. */
    while( ( bytesRemaining > 0UL ) && ( sendError == false ) )
    {
        bytesSent = pContext->transportInterface.send( pContext->transportInterface.pNetworkContext,
                                                       pIndex,
                                                       bytesRemaining );

        if( bytesSent < 0 )
        {
            LogError( ( "Transport send failed. Error code=%ld.", ( long int ) bytesSent ) );
            totalBytesSent = bytesSent;
            sendError = true;
        }
        else if( bytesSent > 0 )
        {
            /* Record the most recent time of successful transmission. */
            lastSendTimeMs = pContext->getTime();

            /* It is a bug in the application's transport send implementation if
             * more bytes than expected are sent. To avoid a possible overflow
             * in converting bytesRemaining from unsigned to signed, this assert
             * must exist after the check for bytesSent being negative. */
            assert( ( size_t ) bytesSent <= bytesRemaining );

            bytesRemaining -= ( size_t ) bytesSent;
            totalBytesSent += bytesSent;
            pIndex += bytesSent;
            LogDebug( ( "BytesSent=%ld, BytesRemaining=%lu",
                        ( long int ) bytesSent,
                        ( unsigned long ) bytesRemaining ) );
        }
        else
        {
            /* No bytes were sent over the network. */
            timeSinceLastSendMs = calculateElapsedTime( pContext->getTime(), lastSendTimeMs );

            /* Check for timeout if we have been waiting to send any data over the network. */
            if( timeSinceLastSendMs >= MQTT_SEND_RETRY_TIMEOUT_MS )
            {
                LogError( ( "Unable to send packet: Timed out in transport send." ) );
                sendError = true;
            }
        }
    }

    /* Update time of last transmission if the entire packet is successfully sent. */
    if( totalBytesSent > 0 )
    {
        pContext->lastPacketTime = lastSendTimeMs;
        LogDebug( ( "Successfully sent packet at time %lu.",
                    ( unsigned long ) lastSendTimeMs ) );
    }

    return totalBytesSent;
}