Skip to content

Commit

Permalink
Visualize transport upgrade (#182)
Browse files Browse the repository at this point in the history
* Logging
* Visualize upgrade via icon
  • Loading branch information
ShortDevelopment authored Oct 24, 2024
1 parent 813e21b commit 5b086a6
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 39 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using ShortDev.Microsoft.ConnectedDevices.NearShare.Apps;
using ShortDev.Microsoft.ConnectedDevices.NearShare.Messages;
using ShortDev.Microsoft.ConnectedDevices.Serialization;
using ShortDev.Microsoft.ConnectedDevices.Transports;
using System.Buffers;
using System.Diagnostics;

Expand All @@ -13,9 +14,11 @@ public sealed class NearShareSender(ConnectedDevicesPlatform platform)
{
public ConnectedDevicesPlatform Platform { get; } = platform;

public event EventHandler<CdpTransportType>? TransportUpgraded;

async Task<SenderStateMachine> PrepareTransferInternalAsync(EndpointInfo endpoint, CancellationToken cancellationToken)
{
var session = await Platform.ConnectAsync(endpoint);
var session = await Platform.ConnectAsync(endpoint, options: new() { TransportUpgraded = TransportUpgraded });

Guid operationId = Guid.NewGuid();

Expand Down
7 changes: 7 additions & 0 deletions lib/ShortDev.Microsoft.ConnectedDevices/CdpLog.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using Microsoft.Extensions.Logging;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;
using ShortDev.Microsoft.ConnectedDevices.Messages.Control;
using ShortDev.Microsoft.ConnectedDevices.Transports;

Expand Down Expand Up @@ -71,4 +72,10 @@ internal static partial class CdpLog

[LoggerMessage(EventId = 304, Level = LogLevel.Warning, Message = "Upgrade failed")]
public static partial void UpgradeFailed(this ILogger logger, Exception ex);

[LoggerMessage(EventId = 305, Level = LogLevel.Debug, Message = "Sending upgrade request {UpgradeId} to {UpgradeTypes}")]
public static partial void SendingUpgradeRequest(this ILogger logger, Guid upgradeId, IEnumerable<EndpointMetadata> upgradeTypes);

[LoggerMessage(EventId = 306, Level = LogLevel.Debug, Message = "Upgrade response {UpgradeId} to {Endpoints}")]
public static partial void UpgradeResponse(this ILogger logger, Guid upgradeId, IEnumerable<EndpointInfo> endpoints);
}
6 changes: 5 additions & 1 deletion lib/ShortDev.Microsoft.ConnectedDevices/CdpSession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ internal static CdpSession GetOrCreate(ConnectedDevicesPlatform platform, Endpoi
), out _);
}

internal static async Task<CdpSession> ConnectClientAsync(ConnectedDevicesPlatform platform, CdpSocket socket)
internal static async Task<CdpSession> ConnectClientAsync(ConnectedDevicesPlatform platform, CdpSocket socket, ConnectOptions? options = null)
{
var session = _sessionRegistry.Create(localSessionId => new(
platform,
Expand All @@ -81,6 +81,10 @@ internal static async Task<CdpSession> ConnectClientAsync(ConnectedDevicesPlatfo
), out _);

var connectHandler = (ClientConnectHandler)session._connectHandler;

if (options is not null)
connectHandler.UpgradeHandler.Upgraded += options.TransportUpgraded;

await connectHandler.ConnectAsync(socket);

return session;
Expand Down
8 changes: 8 additions & 0 deletions lib/ShortDev.Microsoft.ConnectedDevices/ConnectOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using ShortDev.Microsoft.ConnectedDevices.Transports;

namespace ShortDev.Microsoft.ConnectedDevices;

public record ConnectOptions
{
public EventHandler<CdpTransportType>? TransportUpgraded { get; init; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -140,10 +140,10 @@ await Task.WhenAll(_transportMap.Values
}
}

public async Task<CdpSession> ConnectAsync([NotNull] EndpointInfo endpoint)
public async Task<CdpSession> ConnectAsync([NotNull] EndpointInfo endpoint, ConnectOptions? options = null)
{
var socket = await CreateSocketAsync(endpoint).ConfigureAwait(false);
return await CdpSession.ConnectClientAsync(this, socket).ConfigureAwait(false);
return await CdpSession.ConnectClientAsync(this, socket, options).ConfigureAwait(false);
}

internal async Task<CdpSocket> CreateSocketAsync(EndpointInfo endpoint)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static EndpointMetadata Parse(ref EndianReader reader)
return new(type, data.ToArray());
}

public static EndpointMetadata[] ParseArray(ref EndianReader reader)
public static IReadOnlyList<EndpointMetadata> ParseArray(ref EndianReader reader)
{
var arrayLength = reader.ReadUInt16();
var endpoints = new EndpointMetadata[arrayLength];
Expand All @@ -31,9 +31,9 @@ public void Write(EndianWriter writer)
writer.Write(Data);
}

public static void WriteArray(EndianWriter writer, EndpointMetadata[] endpoints)
public static void WriteArray(EndianWriter writer, IReadOnlyList<EndpointMetadata> endpoints)
{
writer.Write((ushort)endpoints.Length);
writer.Write((ushort)endpoints.Count);
foreach (var endpoint in endpoints)
endpoint.Write(writer);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public sealed class UpgradeRequest : ICdpPayload<UpgradeRequest>
/// A random GUID identifying this upgrade process across transports.
/// </summary>
public required Guid UpgradeId { get; init; }
public required EndpointMetadata[] Endpoints { get; init; }
public required IReadOnlyList<EndpointMetadata> Endpoints { get; init; }

public static UpgradeRequest Parse(ref EndianReader reader)
=> new()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ public sealed class UpgradeResponse : ICdpPayload<UpgradeResponse>
/// <summary>
/// A length-prefixed list of endpoint structures (see following) that are provided by each transport on the host device.
/// </summary>
public required EndpointInfo[] Endpoints { get; init; }
public required EndpointMetadata[] MetaData { get; init; }
public required IReadOnlyList<EndpointInfo> Endpoints { get; init; }
public required IReadOnlyList<EndpointMetadata> MetaData { get; init; }

public static UpgradeResponse Parse(ref EndianReader reader)
{
Expand All @@ -37,7 +37,7 @@ public static UpgradeResponse Parse(ref EndianReader reader)

public void Write(EndianWriter writer)
{
writer.Write((ushort)Endpoints.Length);
writer.Write((ushort)Endpoints.Count);
foreach (var endpoint in Endpoints)
{
writer.WriteWithLength(endpoint.Address);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ public long CalcSize()

public interface ICdpArraySerializable<T> where T : ICdpArraySerializable<T>
{
static abstract T[] ParseArray(ref EndianReader reader);
static abstract void WriteArray(EndianWriter writer, T[] array);
static abstract IReadOnlyList<T> ParseArray(ref EndianReader reader);
static abstract void WriteArray(EndianWriter writer, IReadOnlyList<T> array);
}

public interface ICdpWriteable
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using ShortDev.Microsoft.ConnectedDevices.Messages;
using Microsoft.Extensions.Logging;
using ShortDev.Microsoft.ConnectedDevices.Messages;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection;
using ShortDev.Microsoft.ConnectedDevices.Messages.Connection.TransportUpgrade;
using ShortDev.Microsoft.ConnectedDevices.Transports;
Expand All @@ -8,6 +9,8 @@
namespace ShortDev.Microsoft.ConnectedDevices.Session.Upgrade;
internal sealed class ClientUpgradeHandler(CdpSession session, EndpointInfo initialEndpoint) : UpgradeHandler(session, initialEndpoint)
{
private readonly ILogger _logger = session.Platform.CreateLogger<ClientUpgradeHandler>();

protected override bool TryHandleConnectInternal(CdpSocket socket, ConnectionHeader connectionHeader, ref EndianReader reader)
{
if (!IsSocketAllowed(socket))
Expand All @@ -34,6 +37,8 @@ protected override bool TryHandleConnectInternal(CdpSocket socket, ConnectionHea
return false;
}

static readonly IReadOnlyList<EndpointMetadata> UpgradeEndpoints = [EndpointMetadata.Tcp];

UpgradeInstance? _currentUpgrade;
public async ValueTask<CdpSocket> RequestUpgradeAsync(CdpSocket oldSocket)
{
Expand All @@ -43,15 +48,16 @@ public async ValueTask<CdpSocket> RequestUpgradeAsync(CdpSocket oldSocket)
_currentUpgrade = new();
try
{
SendUpgradeRequest(oldSocket, _currentUpgrade.Id);
_logger.SendingUpgradeRequest(_currentUpgrade.Id, UpgradeEndpoints);
SendUpgradeRequest(oldSocket, _currentUpgrade.Id, UpgradeEndpoints);
return await _currentUpgrade.Promise.Task;
}
finally
{
_currentUpgrade = null;
}

void SendUpgradeRequest(CdpSocket socket, Guid upgradeId)
void SendUpgradeRequest(CdpSocket socket, Guid upgradeId, IReadOnlyList<EndpointMetadata> endpoints)
{
CommonHeader header = new()
{
Expand All @@ -68,10 +74,7 @@ void SendUpgradeRequest(CdpSocket socket, Guid upgradeId)
new UpgradeRequest()
{
UpgradeId = upgradeId,
Endpoints =
[
EndpointMetadata.Tcp
]
Endpoints = endpoints
}.Write(writer);

_session.SendMessage(socket, header, writer);
Expand All @@ -84,6 +87,8 @@ void HandleUpgradeResponse(CdpSocket oldSocket, ref EndianReader reader)
return;

var msg = UpgradeResponse.Parse(ref reader);
_logger.UpgradeResponse(_currentUpgrade.Id, msg.Endpoints);

FindNewEndpoint();

async void FindNewEndpoint()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,18 @@ internal abstract class UpgradeHandler(CdpSession session, EndpointInfo initialE
public bool IsSocketAllowed(CdpSocket socket)
=> _allowedAddresses.Contains(socket.Endpoint.Address);

public EndpointInfo RemoteEndpoint { get; protected set; } = initialEndpoint;
public event EventHandler<CdpTransportType>? Upgraded;

EndpointInfo _remoteEndpoint = initialEndpoint;
public EndpointInfo RemoteEndpoint
{
get => _remoteEndpoint;
protected set
{
_remoteEndpoint = value;
Upgraded?.Invoke(this, value.TransportType);
}
}

public bool IsUpgradeSupported
=> (/* ToDo: header131Value & */ _session.ClientCapabilities & _session.HostCapabilities & PeerCapabilities.UpgradeSupport) != 0;
Expand Down
47 changes: 29 additions & 18 deletions src/SendActivity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ namespace NearShare.Droid;
[Activity(Label = "@string/app_name", Exported = true, Theme = "@style/AppTheme.TranslucentOverlay", ConfigurationChanges = UIHelper.ConfigChangesFlags)]
public sealed class SendActivity : AppCompatActivity
{
NearShareSender NearShareSender = null!;
NearShareSender _nearShareSender = null!;

BottomSheetDialog _dialog = null!;
RecyclerView DeviceDiscoveryListView = null!;
Expand Down Expand Up @@ -78,13 +78,7 @@ protected override void OnCreate(Bundle? savedInstanceState)
view.FindViewById<ImageView>(Resource.Id.deviceTypeImageView)!.SetImageResource(
device.Type.IsMobile() ? Resource.Drawable.ic_fluent_phone_24_regular : Resource.Drawable.ic_fluent_desktop_24_regular
);
view.FindViewById<ImageView>(Resource.Id.transportTypeImageView)!.SetImageResource(device.Endpoint.TransportType switch
{
CdpTransportType.Tcp => Resource.Drawable.ic_fluent_wifi_1_20_regular,
CdpTransportType.Rfcomm => Resource.Drawable.ic_fluent_bluetooth_20_regular,
CdpTransportType.WifiDirect => Resource.Drawable.ic_fluent_live_20_regular,
_ => Resource.Drawable.ic_fluent_question_circle_20_regular
});
view.FindViewById<ImageView>(Resource.Id.transportTypeImageView)!.SetImageResource(GetTransportIcon(device.Endpoint.TransportType));
view.FindViewById<TextView>(Resource.Id.deviceNameTextView)!.Text = device.Name;
view.Click += (s, e) => SendData(device);
}
Expand Down Expand Up @@ -137,7 +131,7 @@ void InitializePlatform()
_cdp.DeviceDiscovered += Platform_DeviceDiscovered;
_cdp.Discover(_discoverCancellationTokenSource.Token);

NearShareSender = new NearShareSender(_cdp);
_nearShareSender = new NearShareSender(_cdp);
}

readonly ObservableCollection<CdpDevice> RemoteSystems = [];
Expand Down Expand Up @@ -190,13 +184,10 @@ private async void SendData(CdpDevice remoteSystem)
sendingDataLayout.FindViewById<ImageView>(Resource.Id.deviceTypeImageView)!.SetImageResource(
remoteSystem.Type.IsMobile() ? Resource.Drawable.ic_fluent_phone_24_regular : Resource.Drawable.ic_fluent_desktop_24_regular
);
sendingDataLayout.FindViewById<ImageView>(Resource.Id.transportTypeImageView)!.SetImageResource(remoteSystem.Endpoint.TransportType switch
{
CdpTransportType.Tcp => Resource.Drawable.ic_fluent_wifi_1_20_regular,
CdpTransportType.Rfcomm => Resource.Drawable.ic_fluent_bluetooth_20_regular,
CdpTransportType.WifiDirect => Resource.Drawable.ic_fluent_live_20_regular,
_ => Resource.Drawable.ic_fluent_question_circle_20_regular
});

var transportTypeImage = sendingDataLayout.FindViewById<ImageView>(Resource.Id.transportTypeImageView)!;
transportTypeImage.SetImageResource(GetTransportIcon(remoteSystem.Endpoint.TransportType));
_nearShareSender.TransportUpgraded += OnTransportUpgrade;

var deviceNameTextView = sendingDataLayout.FindViewById<TextView>(Resource.Id.deviceNameTextView)!;
var progressIndicator = sendingDataLayout.FindViewById<CircularProgressIndicator>(Resource.Id.sendProgressIndicator)!;
Expand All @@ -220,7 +211,7 @@ private async void SendData(CdpDevice remoteSystem)
if (files != null)
{
progress = new();
transferPromise = NearShareSender.SendFilesAsync(
transferPromise = _nearShareSender.SendFilesAsync(
remoteSystem,
files,
progress,
Expand All @@ -229,7 +220,7 @@ private async void SendData(CdpDevice remoteSystem)
}
else if (uri != null)
{
transferPromise = NearShareSender.SendUriAsync(
transferPromise = _nearShareSender.SendUriAsync(
remoteSystem,
uri
);
Expand Down Expand Up @@ -308,6 +299,15 @@ private async void SendData(CdpDevice remoteSystem)

progressIndicator.Indeterminate = false;
progressIndicator.Progress = progressIndicator.Max;

_nearShareSender.TransportUpgraded -= OnTransportUpgrade;
}

void OnTransportUpgrade(object? sender, CdpTransportType transportType)
{
RunOnUiThread(() =>
transportTypeImage.SetImageResource(GetTransportIcon(transportType))
);
}
}

Expand Down Expand Up @@ -386,6 +386,17 @@ public override void Finish()
_cdp?.Dispose();
}

static int GetTransportIcon(CdpTransportType transportType)
{
return transportType switch
{
CdpTransportType.Tcp => Resource.Drawable.ic_fluent_wifi_1_20_regular,
CdpTransportType.Rfcomm => Resource.Drawable.ic_fluent_bluetooth_20_regular,
CdpTransportType.WifiDirect => Resource.Drawable.ic_fluent_live_20_regular,
_ => Resource.Drawable.ic_fluent_question_circle_20_regular
};
}

sealed class FinishActivityBottomSheetCallback(Activity activity) : BottomSheetBehavior.BottomSheetCallback
{
public override void OnSlide(View bottomSheet, float newState) { }
Expand Down

0 comments on commit 5b086a6

Please sign in to comment.