Categories
IoT

JSON on the Meadow MCU

From a thread I responded to on the Wilderness Labs forums, I got the Meadow microcontroller building a JSON object and sending the result to a .net API server

The question came from someone trying to use the NewtonSoft JSON framework which has too many associated libraries and the Meadow runs out of memory.

When I moved the code from NewtonSoft to System.JSON, it was interesting to watch how many DLLs were uninstalled from the Meadow:

[26/01/2021 20:39:02] Meadow successfully deleted 'Newtonsoft.Json.dll'
[26/01/2021 20:39:12] Meadow successfully deleted 'System.Xml.Linq.dll'
[26/01/2021 20:39:22] Meadow successfully deleted 'System.Runtime.Serialization.dll'
[26/01/2021 20:39:32] Meadow successfully deleted 'System.ServiceModel.Internals.dll'
[26/01/2021 20:39:42] Meadow successfully deleted 'System.Data.dll'
[26/01/2021 20:39:52] Meadow successfully deleted 'System.Transactions.dll'
[26/01/2021 20:40:02] Meadow successfully deleted 'System.EnterpriseServices.dll'

The other challenge was that (at the time of writing) the Meadow doesn’t support TLS and most publicly available API’s are https URLs. So I built a local API server to test against.

The class on the Meadow looked like this now

public async Task SendNotification()
{
Console.WriteLine("Start Notification: " );
try
{
string uri = "http://192.168.1.11:8002/api/MeadowLogs";
Console.WriteLine("Build object: ");
var data = new
{
LogData = "Meadow"
};
Console.WriteLine("Serialize Data: ");
string httpContent = JsonSerializer.Serialize(data);
Console.WriteLine(httpContent);
Console.WriteLine("Build httpcontent: ");
var stringContent = new StringContent(httpContent);
Console.WriteLine("Create http client: ");
var client = new HttpClient();
Console.WriteLine("Adding Headers: ");
stringContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
Console.WriteLine("Sending Message: ");
var response = await client.PostAsync(uri, stringContent).ConfigureAwait(false);
var result = response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
return true;
}
else
{
Console.WriteLine(response.ReasonPhrase);
return false;
}
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex.ToString());
return false;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}

The code for the Meadow, the API server and the sql for a backend Postgres database table are all up on github

https://github.com/unixbob/MeadowJSON