Skip to content

Commit 7741b51

Browse files
author
arlotito
committed
using interface instead of events
1 parent ce2e18e commit 7741b51

File tree

8 files changed

+151
-160
lines changed

8 files changed

+151
-160
lines changed

source/IotEdgePerf.Transmitter.Edge/Program.cs

Lines changed: 23 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ namespace IotEdgePerf.Transmitter.Edge
44
using System.Threading.Tasks;
55
using System.Text;
66

7-
using System.Collections.Generic;
8-
97
using Newtonsoft.Json;
108

119
using Microsoft.Azure.Devices.Client;
@@ -17,21 +15,12 @@ namespace IotEdgePerf.Transmitter.Edge
1715
using Serilog.Events;
1816

1917
using IotEdgePerf.Transmitter;
20-
using IotEdgePerf.Transmitter.ConfigData;
21-
using IotEdgePerf.Transmitter.Commands;
22-
18+
using IotEdgePerf.Shared;
19+
2320
class Program
2421
{
25-
static ModuleClient _ioTHubModuleClient;
26-
static string _moduleOutput = "output1";
27-
28-
static string _deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
29-
static string _iotHubHostname = Environment.GetEnvironmentVariable("IOTEDGE_IOTHUBHOSTNAME");
30-
static LoggingLevelSwitch _logLevelSwitch = new LoggingLevelSwitch();
31-
32-
static TransmitterLogic _transmitter;
3322

34-
static TwinCollection _twin;
23+
static LoggingLevelSwitch _logLevelSwitch = new LoggingLevelSwitch();
3524

3625
static void GetLogLevelFromEnv()
3726
{
@@ -70,99 +59,47 @@ static async Task Main(string[] args)
7059
//.WriteTo.File("logs/myapp.txt", rollingInterval: RollingInterval.Day)
7160
.CreateLogger();
7261

73-
Init().Wait();
62+
TransmitterLogic transmitter = await Init();
7463

7564
while (true)
7665
{
77-
await _transmitter.SendAsync();
66+
await transmitter.TransmitterLoopAsync();
7867
}
7968
}
8069

81-
82-
8370
/// <summary>
8471
/// Initializes the ModuleClient and sets up the callback to receive
8572
/// messages containing temperature information
8673
/// </summary>
87-
static async Task Init()
74+
static async Task<TransmitterLogic> Init()
8875
{
8976
MqttTransportSettings mqttSetting = new MqttTransportSettings(TransportType.Mqtt_Tcp_Only);
9077
ITransportSettings[] settings = { mqttSetting };
78+
ModuleClient ioTHubModuleClient;
79+
string moduleOutput = "output1";
9180

9281
// Open a connection to the Edge runtime
93-
_ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
94-
await _ioTHubModuleClient.OpenAsync();
82+
ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
83+
await ioTHubModuleClient.OpenAsync();
9584

96-
// Read module twin
97-
var moduleTwin = await _ioTHubModuleClient.GetTwinAsync();
98-
await OnDesiredPropertiesUpdate(moduleTwin.Properties.Desired, _transmitter);
99-
10085
Log.Information("IoT Hub module client initialized.");
101-
Log.Information($"Device id: '{_deviceId}'");
102-
Log.Information($"IoT HUB: '{_iotHubHostname}'");
86+
Log.Information($"Device id: '{Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID")}'");
87+
Log.Information($"IoT HUB: '{Environment.GetEnvironmentVariable("IOTEDGE_IOTHUBHOSTNAME")}'");
10388

10489
// applies initial configuration from twins
105-
var transmitterConfig = TransmitterConfigData.GetFromObject(_twin["config"]);
106-
_transmitter = new TransmitterLogic(transmitterConfig);
107-
108-
// transmitter events handlers
109-
_transmitter.SendMessage += SdkSendMessage;
110-
_transmitter.SendMessageBatch += null;
111-
_transmitter.CreateMessage += CreateMessage;
90+
var moduleTwin = await ioTHubModuleClient.GetTwinAsync();
91+
92+
TransmitterLogic transmitter = new TransmitterLogic(
93+
TransmitterConfigData.GetFromObject(moduleTwin.Properties.Desired["config"]),
94+
new Transport.Sdk(ioTHubModuleClient, moduleOutput),
95+
new MessageProvider.RandomMessage()
96+
);
11297

11398
// twin and dm handlers
114-
await _ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, _transmitter);
115-
await _ioTHubModuleClient.SetMethodHandlerAsync("Start", OnStartDm, _transmitter);
116-
}
117-
118-
119-
120-
private async static Task SdkSendMessage(string message)
121-
{
122-
Message azIotMessage = new Message(Encoding.ASCII.GetBytes(message));
123-
await _ioTHubModuleClient.SendEventAsync(_moduleOutput, azIotMessage);
124-
}
125-
126-
private async static Task SdkSendMessageBatch(string[] messageBatch)
127-
{
128-
List<Message> azIotMessageBatch = new List<Message>();
99+
await ioTHubModuleClient.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertiesUpdate, transmitter);
100+
await ioTHubModuleClient.SetMethodHandlerAsync("Start", OnStartDm, transmitter);
129101

130-
foreach (var message in messageBatch)
131-
{
132-
azIotMessageBatch.Add(new Message(Encoding.ASCII.GetBytes(message)));
133-
}
134-
135-
await _ioTHubModuleClient.SendEventBatchAsync(_moduleOutput, azIotMessageBatch);
136-
}
137-
138-
private static object CreateMessage(int length)
139-
{
140-
var applicationObject = new
141-
{
142-
payload = RandomString(length)
143-
};
144-
145-
return applicationObject;
146-
}
147-
148-
/// <summary>
149-
/// Creates a string of specified length with random chars
150-
/// (from "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
151-
/// </summary>
152-
/// <param name="length">Number of chars</param>
153-
/// <returns>the string</returns>
154-
private static String RandomString(int length)
155-
{
156-
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
157-
var stringChars = new char[length];
158-
var random = new Random();
159-
160-
for (int i = 0; i < length; i++)
161-
{
162-
stringChars[i] = chars[random.Next(chars.Length)];
163-
}
164-
165-
return new String(stringChars);
102+
return transmitter;
166103
}
167104

168105
private static Task<MethodResponse> OnStartDm(MethodRequest methodRequest, object userContext)
@@ -184,13 +121,10 @@ private static Task<MethodResponse> OnStartDm(MethodRequest methodRequest, objec
184121

185122
static Task OnDesiredPropertiesUpdate(TwinCollection desiredProperties, object userContext)
186123
{
187-
TransmitterLogic transmitter = (TransmitterLogic)userContext;
188-
189124
try
190125
{
191126
Log.Debug("Desired property change:\n{0}", JsonConvert.SerializeObject(desiredProperties));
192-
_twin = desiredProperties;
193-
127+
TransmitterLogic transmitter = (TransmitterLogic)userContext;
194128
transmitter.ApplyConfiguration(TransmitterConfigData.GetFromObject(desiredProperties["config"]));
195129
}
196130

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
namespace IotEdgePerf.Transmitter
2+
{
3+
public interface ITransmitterMessageProvider
4+
{
5+
object GetMessage(int length);
6+
}
7+
8+
}
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
namespace IotEdgePerf.Transmitter
2+
{
3+
using System.Threading.Tasks;
4+
using System.Collections.Generic;
5+
public interface ITransmitterTransport
6+
{
7+
Task SendMessageHandler(string message);
8+
Task SendMessageBatchHandler(List<string> message);
9+
}
10+
}

source/IotEdgePerf.Transmitter/Transmitter.cs

Lines changed: 36 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -11,47 +11,47 @@ namespace IotEdgePerf.Transmitter
1111

1212
using IotEdgePerf.Shared;
1313
using IotEdgePerf.Profiler;
14-
using IotEdgePerf.Transmitter.ConfigData;
15-
16-
public delegate Task SendMessageEventHandler(string message);
17-
public delegate Task SendMessageBatchEventHandler(List<string> messageBatch);
18-
public delegate object CreateMessageEventHandler(int length);
19-
14+
2015
public partial class TransmitterLogic
2116
{
22-
public event SendMessageEventHandler SendMessage;
23-
public event SendMessageBatchEventHandler SendMessageBatch;
24-
public event CreateMessageEventHandler CreateMessage;
25-
2617
TransmitterConfigData _config;
2718

2819
Guid _sessionId;
2920

30-
readonly AtomicBoolean _startRequested = new AtomicBoolean(false);
31-
readonly AtomicBoolean _stopRequested = new AtomicBoolean(false);
21+
readonly AtomicBoolean _startRequest = new AtomicBoolean(false);
22+
readonly AtomicBoolean _stopRequest = new AtomicBoolean(false);
23+
private ITransmitterTransport _handlers;
24+
private ITransmitterMessageProvider _messageProvider;
3225

33-
public TransmitterLogic(TransmitterConfigData config)
26+
public TransmitterLogic(
27+
TransmitterConfigData config,
28+
ITransmitterTransport transportHandlers,
29+
ITransmitterMessageProvider messageProvider
30+
)
3431
{
35-
this._startRequested.Set(false);
32+
this._startRequest.Set(false);
3633
this.ApplyConfiguration(config);
34+
35+
this._handlers=transportHandlers;
36+
this._messageProvider=messageProvider;
3737
}
3838

3939
public void Restart(Guid runId)
4040
{
41-
Log.Information($"started with id={runId.ToString()}.");
42-
this._sessionId = runId;
43-
44-
//stop a the ongoing transmission (if any)
45-
Stop();
46-
47-
//enables the transmitter
48-
this._startRequested.Set(true);
41+
Log.Information($"started with id={runId.ToString()}.");
42+
this._sessionId = runId;
43+
44+
//stop the transmission (if any)
45+
Stop();
46+
47+
//enables the transmitter
48+
this._startRequest.Set(true);
4949
}
5050

51-
public void Stop()
51+
void Stop()
5252
{
5353
Log.Information("stop requested.");
54-
this._stopRequested.Set(true); //stops transmission
54+
this._stopRequest.Set(true); //stops transmission
5555
}
5656

5757
public void ApplyConfiguration(TransmitterConfigData config)
@@ -66,18 +66,18 @@ public void ApplyConfiguration(TransmitterConfigData config)
6666
this.Stop();
6767
}
6868

69-
public async Task SendAsync()
69+
public async Task TransmitterLoopAsync()
7070
{
7171
double desiredTransmissionInterval;
7272

73-
if (!this._startRequested)
74-
return; //no transmission requested yet. nothing to do
73+
if (!this._startRequest)
74+
return; //no transmission requested yet. nothing to do
7575
else
76-
this._startRequested.Set(false);
76+
this._startRequest.Set(false);
7777

7878
// clear any pending request
79-
if (this._stopRequested)
80-
this._stopRequested.Set(false);
79+
if (this._stopRequest)
80+
this._stopRequest.Set(false);
8181

8282
// transmitter is enabled. Let's start.
8383

@@ -108,12 +108,12 @@ public async Task SendAsync()
108108
// MESSAGE loop (in a burst we have 'this._config.burstLength' messages)
109109
for (int messageIndex = 0; messageIndex < this._config.burstLength; messageIndex++)
110110
{
111-
if (this._stopRequested)
111+
if (this._stopRequest)
112112
{
113113
//stops transmission
114114
Log.Information("stopped.");
115-
return;
116-
}
115+
return;
116+
}
117117

118118
profiler.MessageCycleStart();
119119

@@ -132,7 +132,7 @@ public async Task SendAsync()
132132
//The resulting length must be equal to 'this._config.payloadLength'
133133
// {" - p - ": - <perfMessage> - , - <object> }
134134
int deltaPayloadLength = this._config.payloadLength - (2 + perfMessage.KeyName.Length + 2 + perfMessage.Json.Length + 1 + 1);
135-
object applicationObject = this.CreateMessage?.Invoke(deltaPayloadLength > 0 ? deltaPayloadLength : 0);
135+
object applicationObject = this._messageProvider.GetMessage(deltaPayloadLength > 0 ? deltaPayloadLength : 0);
136136

137137
// adds the profiling telemetry data to the application message
138138
string mergedMessageJson = perfMessage.AddTo(applicationObject);
@@ -145,9 +145,9 @@ public async Task SendAsync()
145145
// sends the message
146146
profiler.MessageTransmissionStart();
147147
if (messageBatch.Count == 1)
148-
await this.SendMessage?.Invoke(messageBatch[0]);
148+
await this._handlers.SendMessageHandler(messageBatch[0]);
149149
else
150-
await this.SendMessageBatch?.Invoke(messageBatch);
150+
await this._handlers.SendMessageBatchHandler(messageBatch);
151151
profiler.MessageTransmissionCompleted();
152152

153153
// waits to achieve desired target rate

source/IotEdgePerf.Transmitter/TransmitterCommands.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
namespace IotEdgePerf.Transmitter.Commands
1+
namespace IotEdgePerf.Transmitter
22
{
33
using System;
4-
using IotEdgePerf.Transmitter.ConfigData;
4+
using IotEdgePerf.Shared;
55

66
public class TransmitterStartCommand
77
{

source/IotEdgePerf.Transmitter/TransmitterConfigData.cs

Lines changed: 0 additions & 33 deletions
This file was deleted.

0 commit comments

Comments
 (0)