Skip to content

Commit

Permalink
Simplify demo
Browse files Browse the repository at this point in the history
  • Loading branch information
halter73 committed Sep 20, 2019
1 parent 71e4cdb commit 989b1b3
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 123 deletions.
45 changes: 7 additions & 38 deletions SignalR30SensorClient/Program.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Logging;

namespace SignalR30SensorClient
{
Expand All @@ -14,57 +11,29 @@ static async Task Main(string[] args)
{
var hubConnectionBuilder = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/sensors")
.WithAutomaticReconnect()
.ConfigureLogging(logBuilder =>
{
logBuilder.AddConsole();
});
.WithAutomaticReconnect();

await using var hubConnection = hubConnectionBuilder.Build();
var cancellationTokenSource = new CancellationTokenSource();

hubConnection.Reconnected += async connectionId => {
await hubConnection.SendAsync("PublishSensorData", args[0], GenerateSensorData(cancellationTokenSource.Token));
await hubConnection.SendAsync("PublishSensorData", args[0], GenerateSensorData());
};

await hubConnection.StartAsync();

Console.WriteLine("Started sensor {0}.", args[0]);

await hubConnection.SendAsync("PublishSensorData", args[0], GenerateSensorData(cancellationTokenSource.Token));

Console.ReadLine();

cancellationTokenSource.Cancel();
await hubConnection.SendAsync("PublishSensorData", args[0], GenerateSensorData());

Console.ReadLine();
}

static async IAsyncEnumerable<double> GenerateSensorData([EnumeratorCancellation] CancellationToken cancellationToken)
static async IAsyncEnumerable<double> GenerateSensorData()
{
var rng = new Random();
double currentTemp = -18;
double tempVelocity = 0.5;

while (!cancellationToken.IsCancellationRequested)
while (true)
{
tempVelocity += (rng.NextDouble() - .5) / 4;
tempVelocity = Math.Clamp(tempVelocity, -2, 2);

currentTemp += tempVelocity;

if (currentTemp < -30)
{
tempVelocity = .5;
}
else if(currentTemp > 0)
{
tempVelocity = -.5;
}

yield return currentTemp;

await Task.Delay(1000, cancellationToken);
yield return rng.NextDouble() * 10;
await Task.Delay(1000);
}
}
}
Expand Down
3 changes: 0 additions & 3 deletions SignalR30SensorClient/SignalR30SensorClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,6 @@
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client">
<Version>3.0.0-rc1.19457.4</Version>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Logging.Console">
<Version>3.0.0-rc1.19457.4</Version>
</PackageReference>
</ItemGroup>

</Project>
5 changes: 1 addition & 4 deletions SignalR30SensorWebApplication/SensorHub.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@ namespace SignalR30SensorWebApplication
public class SensorHub : Hub
{
private readonly SensorCollection _sensorCollection;
private readonly ILogger<SensorHub> _logger;

public SensorHub(SensorCollection sensorCollection, ILogger<SensorHub> logger)
public SensorHub(SensorCollection sensorCollection)
{
_sensorCollection = sensorCollection;
_logger = logger;
}

public IEnumerable<string> GetSensorNames()
Expand All @@ -34,7 +32,6 @@ public async Task PublishSensorData(string sensorName, IAsyncEnumerable<double>
{
await foreach (var measurement in sensorData)
{
_logger.LogDebug("Received sensor data from {sensorName}: {measurement}", sensorName, measurement);
_sensorCollection.PublishSensorData(sensorName, measurement);
}
}
Expand Down
93 changes: 16 additions & 77 deletions SignalR30SensorWebApplication/wwwroot/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ <h1>SignalR 3.0 Sensor Demo</h1>

<hr />
<div id="chart"></div>
<ol id="messagesList"></ol>
<hr />

<footer>
Expand All @@ -23,104 +22,44 @@ <h1>SignalR 3.0 Sensor Demo</h1>
<script src="lib/signalr/signalr.js"></script>
<script src="lib/realTimeLineChart.js"></script>
<script>
const sensorNames = [];
const lineArray = [];
const latestSensorData = { x: -18, y: -18, z: -18};
const chart = realTimeLineChart();
let olStart = 0;

function updateGraph() {
const now = new Date();
const lineData = { time: now };

Object.assign(lineData, latestSensorData);
lineArray.push(lineData);

if (lineArray.length > 30) {
lineArray.shift();
}

d3.select("#chart").datum(lineArray).call(chart);
}

function addMessage(message) {
const li = document.createElement("li");
li.textContent = message;

const ol = document.getElementById("messagesList");
ol.appendChild(li);

while (ol.childElementCount > 10) {
ol.removeChild(ol.childNodes[0]);
olStart++;
}

ol.setAttribute("start", olStart);
}

(async () => {
const latestSensorData = { x: 0, y: 0, z: 0 };

const connection = new signalR.HubConnectionBuilder()
.withUrl("/sensors")
.withAutomaticReconnect()
.configureLogging(signalR.LogLevel.Information)
.build();

let sensorNames = [];

connection.onreconnected(async connectionId => {
sensorNames = await connection.invoke("GetSensorNames");
sensorNames.forEach(addSensor);
});

await connection.start();

sensorNames = await connection.invoke("GetSensorNames");

function removeSensor(sensor) {
const index = sensorNames.indexOf(sensor);
if (index !== -1) {
sensorNames.splice(index, 1);
}
}

function addSensor(sensorName) {
function subscribeToSensor(sensorName) {
connection.stream("GetSensorData", sensorName)
.subscribe({
next: (item) => {
console.log(`${sensorName}: ${item}`);
latestSensorData[sensorName] = item;
addMessage(`${sensorName}: ${item}`);
},
complete: () => {
addMessage(`${sensorName} Completed`);
removeSensor(sensorName);
console.log(`${sensorName} Completed`);
},
error: (err) => {
addMessage(`${sensorName} error: "${err}"`);
removeSensor(sensorName);
console.log(`${sensorName} error: "${err}"`);
},
});
}

function tryAddSensor(sensorName) {
if (!sensorNames.includes(sensorName)) {
sensorNames.push(sensorName);
addSensor(sensorName);
}
}
connection.onreconnected(async connectionId => {
const sensorNames = await connection.invoke("GetSensorNames");
sensorNames.forEach(subscribeToSensor);
});

sensorNames.forEach(addSensor);
connection.on("SensorAdded", tryAddSensor);
await connection.start();

function resize() {
if (d3.select("#chart svg").empty()) {
return;
}
chart.width(+d3.select("#chart").style("width").replace(/(px)/g, ""));
d3.select("#chart").call(chart);
}
const sensorNames = await connection.invoke("GetSensorNames");

sensorNames.forEach(subscribeToSensor);
connection.on("SensorAdded", subscribeToSensor);

window.setInterval(updateGraph, 500);
d3.select(window).on('resize', resize);
startRealTimeLineChart(latestSensorData);
})();
</script>
</body>
Expand Down
30 changes: 30 additions & 0 deletions SignalR30SensorWebApplication/wwwroot/lib/realTimeLineChart.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,35 @@
// https://bl.ocks.org/pjsier/fbf9317b31f070fd540c5523fef167ac

function startRealTimeLineChart(latestSensorData) {
const chart = realTimeLineChart();
const lineArray = [];

function updateGraph() {
const now = new Date();
const lineData = { time: now };

Object.assign(lineData, latestSensorData);
lineArray.push(lineData);

if (lineArray.length > 30) {
lineArray.shift();
}

d3.select("#chart").datum(lineArray).call(chart);
}

function resize() {
if (d3.select("#chart svg").empty()) {
return;
}
chart.width(+d3.select("#chart").style("width").replace(/(px)/g, ""));
d3.select("#chart").call(chart);
}

window.setInterval(updateGraph, 500);
d3.select(window).on('resize', resize);
}

function realTimeLineChart() {
var margin = {top: 20, right: 20, bottom: 20, left: 20},
width = 600,
Expand Down
2 changes: 1 addition & 1 deletion global.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"sdk": {
"version": "3.0.100-preview8-013656"
"version": "3.0.100-rc1-014190"
}
}

0 comments on commit 989b1b3

Please sign in to comment.