Skip to content

Commit

Permalink
Improve UpdateDeviceConfiguration (#343)
Browse files Browse the repository at this point in the history
  • Loading branch information
josesimoes authored Mar 23, 2022
1 parent 171931a commit 3b7be5c
Show file tree
Hide file tree
Showing 2 changed files with 140 additions and 62 deletions.
92 changes: 58 additions & 34 deletions USB Test App WPF/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -864,58 +864,82 @@ private void SetDeviceConfigButton_Click(object sender, RoutedEventArgs e)

var device = (DataContext as MainViewModel).AvailableDevices[DeviceGrid.SelectedIndex];

// get device info
var deviceConfig = device.DebugEngine.GetDeviceConfiguration(cts.Token);
//DeviceConfiguration deviceConfig;

// update new network configuration
DeviceConfiguration.NetworkConfigurationProperties newDeviceNetworkConfiguration = new DeviceConfiguration.NetworkConfigurationProperties
{
MacAddress = new byte[] { 0, 0x80, 0xe1, 0x01, 0x35, 0x56 },
InterfaceType = NetworkInterfaceType.Ethernet,
StartupAddressMode = AddressMode.DHCP,
//// get device info, if needed
//if (device.DebugEngine.ConfigBlockRequiresErase)
//{
// deviceConfig = device.DebugEngine.GetDeviceConfiguration(cts.Token);
//}

IPv4DNSAddress1 = IPAddress.Parse("192.168.1.254"),
};
//// update new network configuration
//DeviceConfiguration.NetworkConfigurationProperties newDeviceNetworkConfiguration = new DeviceConfiguration.NetworkConfigurationProperties
//{
// MacAddress = new byte[] { 0, 0x80, 0xe1, 0x01, 0x35, 0x56 },
// InterfaceType = NetworkInterfaceType.Ethernet,
// StartupAddressMode = AddressMode.DHCP,

// write device configuration to device
// IPv4DNSAddress1 = IPAddress.Parse("192.168.1.254"),
//};

//// write device configuration to device
//var returnValue = device.DebugEngine.UpdateDeviceConfiguration(newDeviceNetworkConfiguration, 0);

//// add new wireless 802.11 configuration
//DeviceConfiguration.Wireless80211ConfigurationProperties newWireless80211Configuration = new DeviceConfiguration.Wireless80211ConfigurationProperties()
//{
// Id = 44,
// Ssid = "Nice_Ssid",
// Password = "1234",
//};
// add new wireless 802.11 configuration
DeviceConfiguration.Wireless80211ConfigurationProperties newWireless80211Configuration = new DeviceConfiguration.Wireless80211ConfigurationProperties()
{
Id = 0,
Ssid = "Nice_Ssid",
Password = "1234",
Authentication = AuthenticationType.WPA2,
Encryption = EncryptionType.WPA2,
Options = Wireless80211_ConfigurationOptions.AutoConnect
};

//// write wireless configuration to device
//returnValue = device.DebugEngine.UpdateDeviceConfiguration(newWireless80211Configuration, 0);
// write wireless configuration to device
var returnValue = device.DebugEngine.UpdateDeviceConfiguration(newWireless80211Configuration, 0);

// build a CA certificate bundle
DeviceConfiguration.X509CaRootBundleProperties newX509CertificateBundle = new DeviceConfiguration.X509CaRootBundleProperties();

// add CA root certificates
//// add CA root certificates

/////////////////////////////////////////////////////////
// BECAUSE WE ARE PARSING FROM A BASE64 encoded format //
// NEED TO ADD A TERMINATOR TO THE STRING //
/////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
//// BECAUSE WE ARE PARSING FROM A BASE64 encoded format //
//// NEED TO ADD A TERMINATOR TO THE STRING //
///////////////////////////////////////////////////////////

//string caRootBundle = baltimoreCACertificate + letsEncryptCACertificate + "\0";
////string caRootBundle = baltimoreCACertificate + letsEncryptCACertificate + "\0";

//byte[] certificateRaw = Encoding.UTF8.GetBytes(caRootBundle);
////byte[] certificateRaw = Encoding.UTF8.GetBytes(caRootBundle);

using (FileStream binFile = new FileStream(@"C:\Users\JoséSimões\Downloads\DigiCertGlobalRootCA.crt", FileMode.Open))
{
newX509CertificateBundle.Certificate = new byte[binFile.Length];
binFile.Read(newX509CertificateBundle.Certificate, 0, (int)binFile.Length);
newX509CertificateBundle.CertificateSize = (uint)binFile.Length;
}
//using (FileStream binFile = new FileStream(@"C:\Users\JoséSimões\Downloads\DigiCertGlobalRootCA.crt", FileMode.Open))
//{
// newX509CertificateBundle.Certificate = new byte[binFile.Length];
// binFile.Read(newX509CertificateBundle.Certificate, 0, (int)binFile.Length);
// newX509CertificateBundle.CertificateSize = (uint)binFile.Length;
//}

//newX509CertificateBundle.Certificate = certificateRaw;

// write CA certificate to device
var returnValue = device.DebugEngine.UpdateDeviceConfiguration(newX509CertificateBundle, 0);
//var returnValue = device.DebugEngine.UpdateDeviceConfiguration(newX509CertificateBundle, 0);


//// build a device certificate
//DeviceConfiguration.X509DeviceCertificatesProperties newX509DeviceCertificate = new DeviceConfiguration.X509DeviceCertificatesProperties();

//using (FileStream binFile = new FileStream(@"C:\Users\JoséSimões\Downloads\OilLevelCert.pfx", FileMode.Open))
//{
// newX509DeviceCertificate.Certificate = new byte[binFile.Length];
// binFile.Read(newX509DeviceCertificate.Certificate, 0, (int)binFile.Length);
// newX509DeviceCertificate.CertificateSize = (uint)binFile.Length;
//}

//// write certificate to device
//var returnValue = device.DebugEngine.UpdateDeviceConfiguration(newX509DeviceCertificate, 0);



Debug.WriteLine("");
Debug.WriteLine("");
Expand Down
110 changes: 82 additions & 28 deletions nanoFramework.Tools.DebugLibrary.Shared/WireProtocol/Engine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3883,9 +3883,9 @@ public DeviceConfiguration GetDeviceConfiguration(CancellationToken cancellation
public List<DeviceConfiguration.NetworkConfigurationProperties> GetAllNetworkConfigurations()
{
List<DeviceConfiguration.NetworkConfigurationProperties> networkConfigurations = new List<DeviceConfiguration.NetworkConfigurationProperties>();

DeviceConfiguration.NetworkConfigurationProperties networkConfig = null;

uint index = 0;
DeviceConfiguration.NetworkConfigurationProperties networkConfig;

do
{
Expand Down Expand Up @@ -4065,6 +4065,12 @@ public DeviceConfiguration.NetworkConfigurationProperties GetNetworkConfiguraton
networkConfiguration.StartupAddressMode = (byte)AddressMode.Invalid;
}

if(networkConfiguration.InterfaceType > (byte)NetworkInterfaceType.Wireless80211)
{
// fix this to invalid
networkConfiguration.InterfaceType = (byte)NetworkInterfaceType.Unknown;
}

networkConfigProperties = new DeviceConfiguration.NetworkConfigurationProperties(networkConfiguration);
}
}
Expand Down Expand Up @@ -4194,9 +4200,10 @@ private IncomingMessage GetDeviceConfiguration(uint configuration, uint configur
/// </summary>
/// <param name="configuration">The device configuration</param>
/// <returns></returns>
public bool UpdateDeviceConfiguration(DeviceConfiguration configuration)
public UpdateDeviceResult UpdateDeviceConfiguration(DeviceConfiguration configuration)
{
bool okToUploadConfig = false;
byte[] configSectorBackup;
Commands.Monitor_FlashSectorMap.FlashSectorData configSector = new Commands.Monitor_FlashSectorMap.FlashSectorData();

// the requirement to erase flash before storing is dependent on CLR capabilities which is only available if the device is running nanoCLR
Expand All @@ -4214,7 +4221,7 @@ public bool UpdateDeviceConfiguration(DeviceConfiguration configuration)
// flash sector map is still empty, go get it
if (GetFlashSectorMap() == null)
{
return false;
return UpdateDeviceResult.FailedToRetrieveExistingConfig;
}
}

Expand All @@ -4229,16 +4236,20 @@ public bool UpdateDeviceConfiguration(DeviceConfiguration configuration)

if (readConfigSector.Success)
{
// copy over to backup array
configSectorBackup = readConfigSector.Buffer;

// start erasing the sector that holds the configuration block
var (ErrorCode, Success) = EraseMemory(configSector.StartAddress, 1);
var (ErrorCode, Success) = EraseMemory(configSector.StartAddress, configSector.NumBlocks * configSector.BytesPerBlock);

if (Success)
{
okToUploadConfig = true;
}
}
else
{
return false;
return UpdateDeviceResult.FailedToRetrieveExistingConfig;
}
}
}
Expand All @@ -4250,8 +4261,10 @@ public bool UpdateDeviceConfiguration(DeviceConfiguration configuration)

if (okToUploadConfig)
{
Thread.Sleep(250);

// serialize the configuration block
var configurationSerialized = CreateConverter().Serialize(((DeviceConfigurationBase)configuration));
var configurationSerialized = CreateConverter().Serialize((DeviceConfigurationBase)configuration);

// counters to manage the chunked update process
int count = configurationSerialized.Length;
Expand Down Expand Up @@ -4312,6 +4325,7 @@ public bool UpdateDeviceConfiguration(DeviceConfiguration configuration)
else
{
attemptCount--;
Thread.Sleep(100);
}
}

Expand All @@ -4321,15 +4335,16 @@ public bool UpdateDeviceConfiguration(DeviceConfiguration configuration)
// revert back old one

// TODO
return UpdateDeviceResult.UpdateFailed;
}
else
{
return true;
return UpdateDeviceResult.Sucess;
}
}

// default to false
return false;
return UpdateDeviceResult.UpdateFailed;
}

public int GetPacketMaxLength(Commands.OverheadBase cmd)
Expand All @@ -4344,7 +4359,7 @@ public int GetPacketMaxLength(Commands.OverheadBase cmd)
/// <param name="configuration">The configuration block</param>
/// <param name="blockIndex">The index of this configuration block</param>
/// <returns></returns>
public bool UpdateDeviceConfiguration<T>(T configuration, uint blockIndex)
public UpdateDeviceResult UpdateDeviceConfiguration<T>(T configuration, uint blockIndex)
{
// Create cancellation token source
CancellationTokenSource cts = new CancellationTokenSource();
Expand All @@ -4358,6 +4373,15 @@ public bool UpdateDeviceConfiguration<T>(T configuration, uint blockIndex)

if (currentConfiguration != null)
{
// perform sanity of data read by looking at the interface type
if (currentConfiguration.NetworkConfigurations.Count == 0 || currentConfiguration.NetworkConfigurations[0].InterfaceType == NetworkInterfaceType.Unknown)
{
// something wrong, can't use this configuration
Debug.WriteLine("*** INVALID configuration read from the device ***");

return UpdateDeviceResult.ExistingConfigurationInvalid;
}

// now update the specific configuration block
if (configuration.GetType().Equals(typeof(DeviceConfiguration.NetworkConfigurationProperties)))
{
Expand Down Expand Up @@ -4424,15 +4448,11 @@ public bool UpdateDeviceConfiguration<T>(T configuration, uint blockIndex)
}
}

if (UpdateDeviceConfiguration(currentConfiguration))
{
// done here
return true;
}
else
{
// write failed, the old configuration it's supposed to have been reverted by now
}
return UpdateDeviceConfiguration(currentConfiguration);
}
else
{
return UpdateDeviceResult.FailedToRetrieveExistingConfig;
}
}
else
Expand Down Expand Up @@ -4508,20 +4528,13 @@ public bool UpdateDeviceConfiguration<T>(T configuration, uint blockIndex)
if (updateFailed)
{
// failed to upload new configuration
// revert back old one

// TODO
return UpdateDeviceResult.UpdateFailed;
}
else
{
return true;
return UpdateDeviceResult.Sucess;
}

}

// default to false
return false;

}

private byte[] GetDeviceConfigurationSerialized<T>(T configuration)
Expand Down Expand Up @@ -4595,5 +4608,46 @@ private Thread CreateThreadHelper(ThreadStart ts)

return th;
}

/// <summary>
/// Enumerable with result of the call to <see cref="UpdateDeviceConfiguration"/>.
/// </summary>
public enum UpdateDeviceResult
{
/// <summary>
/// No result reported.
/// </summary>
None = 0,

/// <summary>
/// Successfully updated configuration to device.
/// </summary>
Sucess,

/// <summary>
/// Failed to retrieve existing configuration from the device
/// </summary>
FailedToRetrieveExistingConfig,

/// <summary>
/// The current configuration retrieved from the connected device is not valid.
/// </summary>
ExistingConfigurationInvalid,

/// <summary>
/// Failed to upload the new configuration to the device.
/// </summary>
UpdateFailed,

/// <summary>
/// Failed to upload the new configuration to the device and the previous configuration was restored.
/// </summary>
UpdateFailedOldConfigRestored,

/// <summary>
/// Failed to upload the new configuration to the device and failed to restore the previous configuration.
/// </summary>
UpdateFailedAndFailredToRestoreOldConfig
}
}
}

0 comments on commit 3b7be5c

Please sign in to comment.