Skip to content

Commit

Permalink
Merge pull request #23 from lillo42/master
Browse files Browse the repository at this point in the history
Create new Release
  • Loading branch information
lillo42 authored Feb 16, 2020
2 parents e1dc8c9 + 3561cdf commit 1bde057
Show file tree
Hide file tree
Showing 43 changed files with 1,816 additions and 550 deletions.
8 changes: 8 additions & 0 deletions Mozzila.IoT.WebThing.sln
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Mozilla.IoT.WebThing.Accept
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MultiThing", "sample\MultiThing\MultiThing.csproj", "{3CDFC9FB-F240-419A-800D-79C506CBDAE2}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Github", "Github", "{425538CC-334D-4DB3-B529-48EA7CD778BF}"
ProjectSection(SolutionItems) = preProject
.github\workflows\pull-request.yml = .github\workflows\pull-request.yml
.github\workflows\build-master.yml = .github\workflows\build-master.yml
.github\workflows\release.yml = .github\workflows\release.yml
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -106,5 +113,6 @@ Global
{6FB673AA-FD52-4509-97C8-28572549F609} = {370B1F76-EFE0-44D4-A395-59F5EF266112}
{0D709627-98FA-4A39-8631-90C982ADED44} = {65C51E32-2901-4983-A238-0F931D9EB651}
{3CDFC9FB-F240-419A-800D-79C506CBDAE2} = {370B1F76-EFE0-44D4-A395-59F5EF266112}
{425538CC-334D-4DB3-B529-48EA7CD778BF} = {E90FFA85-A210-450A-AA08-528D7F8962C2}
EndGlobalSection
EndGlobal
46 changes: 20 additions & 26 deletions sample/MultiThing/Program.cs
Original file line number Diff line number Diff line change
@@ -1,26 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MultiThing
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace MultiThing
{
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
105 changes: 49 additions & 56 deletions sample/MultiThing/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,56 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.WebSockets;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MultiThing.Things;

namespace MultiThing
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddThings()
.AddThing<ExampleDimmableLight>()
.AddThing<FakeGpioHumiditySensor>();

services.AddWebSockets(opt => { });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseWebSockets();

app.UseEndpoints(endpoints =>
{
endpoints.MapThings();
});
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.WebSockets;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MultiThing.Things;

namespace MultiThing
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddThings(opt => opt.UseThingAdapterUrl = true)
.AddThing<ExampleDimmableLight>()
.AddThing<FakeGpioHumiditySensor>();

services.AddWebSockets(opt => { });
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseRouting();

app.UseWebSockets();

app.UseEndpoints(endpoints =>
{
endpoints.MapThings();
});
}
}
}
15 changes: 12 additions & 3 deletions sample/MultiThing/Things/ExampleDimmableLight.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ namespace MultiThing.Things
{
public class ExampleDimmableLight : Thing
{
private readonly ILogger<ExampleDimmableLight> _logger;

public ExampleDimmableLight(ILogger<ExampleDimmableLight> logger)
{
_logger = logger;
}

public override string Name => "my-lamp-1234";

public override string Title => "My Lamp";
Expand All @@ -27,12 +34,14 @@ public bool On
{
_on = value;

Console.WriteLine($"On-State is now {_on}");
_logger.LogInformation("On-State is now {on}", _on);
OnPropertyChanged();
}
}

private int _brightness = 50;


[ThingProperty(Type = new []{ "BrightnessProperty" }, Title = "Brightness", Description = "The level of light from 0-100",
Minimum = 0, Maximum = 100, Unit = "percent")]
public int Brightness
Expand All @@ -41,8 +50,8 @@ public int Brightness
set
{
_brightness = value;

Console.WriteLine($"Brightness is now {_brightness}");
_logger.LogInformation("Brightness is now {brightness}", _brightness);
OnPropertyChanged();
}
}

Expand Down
24 changes: 18 additions & 6 deletions sample/MultiThing/Things/FakeGpioHumiditySensor.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Mozilla.IoT.WebThing;
using Mozilla.IoT.WebThing.Attributes;

Expand All @@ -8,16 +9,17 @@ namespace MultiThing.Things
public class FakeGpioHumiditySensor : Thing
{
private readonly Random _random;
public FakeGpioHumiditySensor()
private readonly ILogger<FakeGpioHumiditySensor> _logger;
public FakeGpioHumiditySensor(ILogger<FakeGpioHumiditySensor> logger)
{
_logger = logger;
_random = new Random();
Task.Factory.StartNew(() =>
{
while (true)
{
Task.Delay(3_000).GetAwaiter().GetResult();
var newLevel = ReadFromGPIO();
Console.WriteLine("setting new humidity level: {0}", newLevel);
Level = newLevel;
}
}, TaskCreationOptions.LongRunning);
Expand All @@ -29,11 +31,21 @@ public FakeGpioHumiditySensor()
public override string[] Type { get; } = new[] {"MultiLevelSensor"};

public override string Description => "A web connected humidity sensor";


[ThingProperty(Type = new []{"LevelProperty"}, Title = "Humidity", Description = "The current humidity in %",

private double _level;

[ThingProperty(Type = new[] {"LevelProperty"}, Title = "Humidity", Description = "The current humidity in %",
Minimum = 0, Maximum = 100, Unit = "percent")]
public double Level { get; private set; }
public double Level
{
get => _level;
private set
{
_level = value;
_logger.LogInformation("setting new humidity level: {level}", value);
OnPropertyChanged();
}
}

/// <summary>
/// Mimic an actual sensor updating its reading every couple seconds.
Expand Down
2 changes: 1 addition & 1 deletion sample/MultiThing/appsettings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Default": "Debug",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
Expand Down
24 changes: 17 additions & 7 deletions src/Mozilla.IoT.WebThing/Converts/ThingConverter.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using Mozilla.IoT.WebThing.Extensions;

namespace Mozilla.IoT.WebThing.Converts
{
public class ThingConverter : JsonConverter<Thing>
{
public static JsonSerializerOptions Options { get; } = new JsonSerializerOptions

private readonly ThingOption _option;
public ThingConverter(ThingOption option)
{
WriteIndented = false,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
Converters = { new ThingConverter()}
};
_option = option;
}

public override bool CanConvert(Type typeToConvert)
{
Expand Down Expand Up @@ -45,7 +45,17 @@ public override void Write(Utf8JsonWriter writer, Thing value, JsonSerializerOpt
writer.WriteStartObject();
writer.WriteString("@context", value.Context);
var builder = new UriBuilder(value.Prefix) {Path = $"/things/{options.GetPropertyName(value.Name)}"};
WriteProperty(writer, "Id", builder.Uri.ToString(), options);
if (_option.UseThingAdapterUrl)
{
WriteProperty(writer, "Id", options.GetPropertyName(value.Name), options);
WriteProperty(writer, "href", builder.Path, options);
WriteProperty(writer, "base", builder.Uri.ToString(), options);
}
else
{
WriteProperty(writer, "Id", builder.Uri.ToString(), options);
}

value.ThingContext.Converter.Write(writer, value, options);

StartArray(writer, "Links", options);
Expand Down
6 changes: 4 additions & 2 deletions src/Mozilla.IoT.WebThing/Endpoints/DeleteAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Mozilla.IoT.WebThing.Converts;
using Mozilla.IoT.WebThing.Extensions;

namespace Mozilla.IoT.WebThing.Endpoints
{
Expand All @@ -28,8 +30,8 @@ public static Task InvokeAsync(HttpContext context)
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return Task.CompletedTask;
}
var option = ThingConverter.Options;;

var option = service.GetRequiredService<JsonSerializerOptions>();

var actionName = context.GetRouteData<string>("action");
var id = Guid.Parse(context.GetRouteData<string>("id"));
Expand Down
11 changes: 7 additions & 4 deletions src/Mozilla.IoT.WebThing/Endpoints/GetAction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
Expand All @@ -18,27 +19,29 @@ public static async Task InvokeAsync(HttpContext context)
var logger = service.GetRequiredService<ILogger<GetAction>>();
var things = service.GetRequiredService<IEnumerable<Thing>>();
var thingName = context.GetRouteData<string>("name");
logger.LogInformation("Requesting Action for Thing. [Name: {name}]", thingName);

logger.LogInformation("Requesting Action for Thing. [Thing: {name}]", thingName);
var thing = things.FirstOrDefault(x => x.Name.Equals(thingName, StringComparison.OrdinalIgnoreCase));

if (thing == null)
{
logger.LogInformation("Thing not found. [Name: {name}]", thingName);
logger.LogInformation("Thing not found. [Thing: {name}]", thingName);
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}

var option = ThingConverter.Options;
var option = service.GetRequiredService<JsonSerializerOptions>();

var actionName = context.GetRouteData<string>("action");

if (!thing.ThingContext.Actions.TryGetValue(actionName, out var actionContext))
{
logger.LogInformation("{actionName} Action not found in {thingName}", actionName, thingName);
logger.LogInformation("Action not found. [Thing: {name}][Action: {action}]", thingName, actionName);
context.Response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}

logger.LogInformation("Action found. [Thing: {name}][Action: {action}]", thingName, actionName);
await context.WriteBodyAsync(HttpStatusCode.OK, actionContext.Actions, option)
.ConfigureAwait(false);
}
Expand Down
Loading

0 comments on commit 1bde057

Please sign in to comment.