Skip to content

Commit

Permalink
Only attempt to restart smaller Block0Wise transfer on first block
Browse files Browse the repository at this point in the history
  • Loading branch information
NZSmartie committed Dec 19, 2017
1 parent ab0549b commit 5fcb12f
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/CoAPNet/CoapBlockStream.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private async Task WriteBlocksAsync()
// Reset the message Id so it's set by CoapClient
message.Id = 0;

message.Options.Add(new Options.Block1(_writeBlockNumber++, _blockSize, _writer.Length > _blockSize));
message.Options.Add(new Options.Block1(_writeBlockNumber, _blockSize, _writer.Length > _blockSize));

message.Payload = new byte[_writer.Length < _blockSize ? _writer.Length : _blockSize];
_writer.Peek(message.Payload, 0, _blockSize);
Expand All @@ -86,6 +86,9 @@ private async Task WriteBlocksAsync()

if (result.Code.IsSuccess())
{
_writer.AdvanceQueue(message.Payload.Length);
_writeBlockNumber++;

var block = result.Options.Get<Options.Block1>();
var blockDelta = block.BlockSize - _blockSize;

Expand All @@ -98,16 +101,19 @@ private async Task WriteBlocksAsync()
else if (blockDelta > 0)
throw new CoapBlockException($"Remote endpoint requested to increase blocksize from {_blockSize} to {_blockSize + blockDelta}");

_writer.AdvanceQueue(message.Payload.Length);
}
else if (result.Code.IsClientError() || result.Code.IsServerError())
{
// Try again and attempt at sending a smaller block size.
_writeBlockNumber = 0;
_blockSize /= 2;
if (_writeBlockNumber == 0 && result.Code == CoapMessageCode.RequestEntityTooLarge && _blockSize > 16)
{
// Try again and attempt at sending a smaller block size.
_writeBlockNumber = 0;
_blockSize /= 2;

continue;
}

if(_blockSize < 16)
throw new CoapBlockException($"Failed to send block ({_writeBlockNumber}) to remote endpoint", CoapException.FromCoapMessage(result), result.Code);
throw new CoapBlockException($"Failed to send block ({_writeBlockNumber}) to remote endpoint", CoapException.FromCoapMessage(result), result.Code);
}

}
Expand Down

0 comments on commit 5fcb12f

Please sign in to comment.