Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Protocol client abstraction #9

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,5 @@

# Ignore documentation Generation Output
WoT/docGeneration/api
WoT/docGeneration/_site
WoT/docGeneration/_site
/WoT/binding-http/SimpleConsumedThing.cs
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,3 +107,5 @@ For a more detailed step-by-step explanation and documentation, feel free to vis
- [ ] MQTT Consumer

... more in the future

<!-- first commit -->
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment should be removed and how new bindings can be implemented should be explained

33 changes: 28 additions & 5 deletions SimpleHTTPConsumerTester/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
// See https://aka.ms/new-console-template for more information
// See https://aka.ms/new-console-template for more informatio5n
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// See https://aka.ms/new-console-template for more informatio5n
// See https://aka.ms/new-console-template for more information

using WoT;
using WoT.Definitions;
using WoT.Implementation;

SimpleHTTPConsumer consumer = new SimpleHTTPConsumer();
ThingDescription td = await consumer.RequestThingDescription("http://plugfest.thingweb.io:8083/smart-coffee-machine");
SimpleConsumedThing? consumedThing = await consumer.Consume(td) as SimpleConsumedThing;
if(consumedThing != null) await consumedThing.WriteProperty<int>("availableResourceLevel", 100 ,new InteractionOptions { uriVariables = new Dictionary<string, object> { { "id", "water" } } });
Consumer consumer = new Consumer();
consumer.AddClient(new SimpleHTTPClient());
ThingDescription coffeeMachineTD = await consumer.RequestThingDescription("http://plugfest.thingweb.io:8083/smart-coffee-machine");
ThingDescription counterTD = await consumer.RequestThingDescription("http://plugfest.thingweb.io:8083/counter");
ConsumedThing coffeeMachineConsumedThing = consumer.Consume(coffeeMachineTD) as ConsumedThing;
ConsumedThing counterConsumedThing = consumer.Consume(counterTD) as ConsumedThing;
Action<IInteractionOutput<int>> countListener = async (IInteractionOutput<int> count) => { Console.WriteLine(await count.Value()); };
if (coffeeMachineConsumedThing != null)
{
//ReadProperty test
int count = await counterConsumedThing.ReadProperty<int>("count", new InteractionOptions { uriVariables = new Dictionary<string, object> { { "step", 5 } } }).Result.Value();
Console.WriteLine("Count = " + count);


//ObserveProperty test
ISubscription countObserver = await counterConsumedThing.ObserveProperty<int>("count", countListener);

//InvokeAction test
IInteractionOutput actionOutput = await counterConsumedThing.InvokeAction("increment", options: new InteractionOptions { uriVariables = new Dictionary<string, object> { { "step", 5 } } }) ;

//WriteProperty
await coffeeMachineConsumedThing.WriteProperty<int>("availableResourceLevel", 100, new InteractionOptions { uriVariables = new Dictionary<string, object> { { "id", "water" } } });

}


Console.WriteLine("Done");
Console.ReadLine();
905 changes: 0 additions & 905 deletions WoT/SimpleHTTPConsumer.cs

This file was deleted.

5 changes: 5 additions & 0 deletions WoT/WoT.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,9 @@
<PackagePath>\</PackagePath>
</None>
</ItemGroup>

<ItemGroup>
<Compile Remove="binding-http/SimpleConsumedThing.cs" />
</ItemGroup>

</Project>
125 changes: 125 additions & 0 deletions WoT/binding-http/SimpleHTTPClient.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Schema;
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Tavis.UriTemplates;
using WoT.Definitions;
using WoT.Errors;
using System.Threading;
using WoT.ProtocolBindings;

namespace WoT.Implementation
{
/// <summary>
/// A simple WoT Consumer that is capable of requesting TDs only from HTTP resources und consumes them to generate <see cref="SimpleConsumedThing"/>
/// </summary>
public class SimpleHTTPClient : IProtocolClient
{
private readonly JsonSerializer _serializer;
public readonly HttpClient httpClient;

public string Scheme { get; } = "http";

/// <inheritdoc/>
public SimpleHTTPClient()
{
httpClient = new HttpClient();
_serializer = new JsonSerializer();

}


public async Task<Stream> SendGetRequest(Form form)
{

HttpResponseMessage interactionResponse = await httpClient.GetAsync(form.Href);
interactionResponse.EnsureSuccessStatusCode();
Stream responseStream = await interactionResponse.Content.ReadAsStreamAsync();
return responseStream;

}



public async Task<Stream> SendGetRequest(Form form, CancellationToken cancellationToken)
{
HttpResponseMessage interactionResponse = await httpClient.GetAsync(form.Href, cancellationToken);
interactionResponse.EnsureSuccessStatusCode();
Stream responseStream = await interactionResponse.Content.ReadAsStreamAsync();
return responseStream;

}
public async Task<Stream> SendPostRequest(Form form)
{
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, form.Href);
var interactionResponse = await httpClient.SendAsync(message);
interactionResponse.EnsureSuccessStatusCode();
Stream responseStream = await interactionResponse.Content.ReadAsStreamAsync();
return responseStream;
}
public async Task<Stream> SendPostRequest<U>(Form form, U parameters)
{

string payloadString = JsonConvert.SerializeObject(parameters);
StringContent payload = new StringContent(payloadString, Encoding.UTF8, "application/json");
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, form.Href);
message.Content = payload;
var interactionResponse = await httpClient.SendAsync(message);
interactionResponse.EnsureSuccessStatusCode();
Stream responseStream = await interactionResponse.Content.ReadAsStreamAsync();
return responseStream;
}

public async Task SendPutRequest<T>(Form form, T value)
{
string payloadString = JsonConvert.SerializeObject(value);
var payload = new StringContent(payloadString, Encoding.UTF8, "application/json");
var message = new HttpRequestMessage(HttpMethod.Put, form.Href);
message.Content = payload;
HttpResponseMessage interactionResponse = await httpClient.SendAsync(message);
interactionResponse.EnsureSuccessStatusCode();

}




public async Task<ThingDescription> RequestThingDescription(string url)
{
Uri tdUrl = new Uri(url);
HttpResponseMessage tdResponse = await httpClient.GetAsync(tdUrl);
tdResponse.EnsureSuccessStatusCode();
Console.WriteLine($"Info: Fetched TD from {url} successfully");
Console.WriteLine($"Info: Parsing TD");
HttpContent body = tdResponse.Content;
string tdData = await body.ReadAsStringAsync();
TextReader reader = new StringReader(tdData);
ThingDescription td = _serializer.Deserialize(reader, typeof(ThingDescription)) as ThingDescription;
Console.WriteLine($"Info: Parsed TD successfully");
return td;
}

public async Task<ThingDescription> RequestThingDescription(Uri tdUrl)
{
if (tdUrl.Scheme != "http") throw new Exception($"The protocol for accessing the TD url {tdUrl.OriginalString} is not HTTP");
Console.WriteLine($"Info: Fetching TD from {tdUrl.OriginalString}");
HttpResponseMessage tdResponse = await httpClient.GetAsync(tdUrl);
tdResponse.EnsureSuccessStatusCode();
Console.WriteLine($"Info: Fetched TD from {tdUrl.OriginalString} successfully");
Console.WriteLine($"Info: Parsing TD");
HttpContent body = tdResponse.Content;
string tdData = await body.ReadAsStringAsync();
TextReader reader = new StringReader(tdData);
ThingDescription td = _serializer.Deserialize(reader, typeof(ThingDescription)) as ThingDescription;
Console.WriteLine($"Info: Parsed TD successfully");
return td;
}
}


}
Loading