static void TestMqtt(MqttClientHelper mqtt) { mqtt.Client.MqttMsgPublishReceived += TestMqttReceive; mqtt.OnConnectionChange += (s, connected) => { if (connected) { mqtt.Client.Subscribe(new[] { "prueba/+" }, new[] { MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE }); } }; new Thread(() => { while (mqtt.IsRunning) { if (mqtt.IsConnected) { var msg = Encoding.UTF8.GetBytes("Hola mundo " + DateTime.Now); var r = mqtt.Client.Publish("prueba/Nada", msg); LoggerConfig.DefaultLogger.LogInformation($"Publish r:{r}"); } Task.Delay(2000).Wait(); } }).Start(); }
public async Task ICollectorOutputsArePublished() { var mqttApplicationMessages = new List <MqttApplicationMessage>();; using (var mqttServer = await MqttServerHelper.Get(_logger)) using (var mqttClient = await MqttClientHelper.Get(_logger)) using (var jobHost = await JobHostHelper <ICollectorOutputIsPublishedTestFunction> .RunFor(_testLoggerProvider)) { await mqttClient.SubscribeAsync("test/outtopic"); await mqttClient.SubscribeAsync("test/outtopic2"); mqttClient.OnMessage += (object sender, OnMessageEventArgs e) => mqttApplicationMessages.Add(e.ApplicationMessage); await jobHost.CallAsync(nameof(ICollectorOutputIsPublishedTestFunction.Testert)); await WaitFor(() => ICollectorOutputIsPublishedTestFunction.CallCount >= 1); await WaitFor(() => mqttApplicationMessages.Count > 0); } Assert.Equal(1, ICollectorOutputIsPublishedTestFunction.CallCount); Assert.Equal(2, mqttApplicationMessages.Count); Assert.Contains(mqttApplicationMessages, x => x.Topic == "test/outtopic"); Assert.Contains(mqttApplicationMessages, x => x.Topic == "test/outtopic2"); var bodyString = Encoding.UTF8.GetString(mqttApplicationMessages.First().Payload); Assert.Equal("", bodyString); }
static void Main(string[] args) { Console.WriteLine("Hello World!"); LoggerConfig.SetSerilog(); var server = TestRpcServer(); var client = TestRpcClient(); Task.WaitAll(server, client); var config = new MqttConfiguration("Mqtt"); config.ClientId = "Test JsonRpcMqtt" + Guid.NewGuid(); config.Username = "******"; config.Password = "******"; var mqtt = new MqttClientHelper(config); var taskRun = mqtt.RunAsync(); TestMqtt(mqtt); taskRun.Wait(); mqtt.Disconnect(); }
static Task TestRpcServer() { var config = new MqttConfiguration("Mqtt"); config.ClientId = "Test JsonRpcMqtt" + Guid.NewGuid(); config.Username = "******"; config.Password = "******"; var mqtt = new MqttClientHelper(config); var rpc = new Rpc(new JsonRpcMqttConnection(mqtt.Client, "test/", clientId: "TestRpcServer")); var functions = new ExampleService(rpc); rpc.Dispatcher.RegisterService(functions); mqtt.OnConnectionChange += (s, connected) => { if (connected) { rpc.UpdateRegisteredMethods(); } }; return(mqtt.RunAsync()); }
public static IRtConnector Build( MqttClientHelper mqttClient, ILoggerFactory loggerFactory = null, string prefix = null, string[] extraTopicsSbscribe = null) { return(new RtConnectorMqtt(mqttClient, loggerFactory, prefix, extraTopicsSbscribe)); }
static async Task TestRpcClient() { var logger = LoggerConfig.DefaultLogger; var config = new MqttConfiguration("Mqtt"); config.ClientId = "Test JsonRpcMqtt" + Guid.NewGuid(); config.Username = "******"; config.Password = "******"; var mqtt = new MqttClientHelper(config); mqtt.ConnectAsync().Wait(); var rpc = new Rpc(new JsonRpcMqttConnection(mqtt.Client, "test/", clientId: "TestRpcClient")); mqtt.OnConnectionChange += (s, connected) => { if (connected) { rpc.UpdateRegisteredMethods(); } }; var service = rpc.GetServices <IExampleService>(); while (mqtt.IsRunning) { var taskBroadcast = rpc.CallAsync("SendBroadcastAsync", "hola mundo " + DateTime.Now); var taskBroadcast2 = service.SendBroadcastAsync("hola mundo " + DateTime.Now); logger.LogInformation("SendBroadcastAsync taskBroadcast:{0} {1}", taskBroadcast.Status, taskBroadcast2.Status); var res = service.Sumar(1, DateTime.Now.Second); logger.LogInformation("Sumar result:{0}", res); var t = service.TaskVoidAsync(1, DateTime.Now.Second); logger.LogInformation("TaskVoidAsync t.Status:{0}", t?.Status); t.Wait(); logger.LogInformation("TaskVoidAsync t.Wait() t.Status:{0}", t?.Status); var t2 = service.TaskIntAsync(1, DateTime.Now.Second); logger.LogInformation("TaskIntAsync t2.Result:{0}", t2.Result); string rCall1 = service.Concatenar("ASDF", 1, 3); logger.LogInformation("GetCaller Concatenar Result: {0}", rCall1); CustObj resObj1 = service.FuncCustObj(1234, "hola FuncCustObj"); logger.LogInformation("GetCaller FuncCustObj Result: {@0}", resObj1); resObj1 = service.FuncCustObj(1234, "hola FuncCustObj", new CustObj { a = 23, b = new string[] { "sadf" } }); logger.LogInformation("GetCaller FuncCustObj Result: {@0} {1}", resObj1, resObj1.c[0]); await Task.Delay(5000); } }
public static IRtConnector BuildFromFactory( IConfigurationSection configuration, ILoggerFactory loggerFactory = null) { var config = new MqttConfiguration(configuration); var mqttClient = new MqttClientHelper(config); var prefix = configuration?.GetValue <string>("Prefix", ""); var extraTopicsSbscribe = configuration?.GetSection("ExtraTopicsSbscribe")?.Get <string[]>(); return(new RtConnectorMqtt(mqttClient, loggerFactory, prefix, extraTopicsSbscribe)); }
public static IRtConnector Build( string sectionName = "Mqtt", string configFileName = "common.json", ILoggerFactory loggerFactory = null, string prefix = null, string[] extraTopicsSbscribe = null) { var config = new MqttConfiguration(sectionName, configFileName); var mqttClient = new MqttClientHelper(config); return(new RtConnectorMqtt(mqttClient, loggerFactory, prefix, extraTopicsSbscribe)); }
public void SetHost(HomeGenieService hg, SchedulerItem item) { homegenie = hg; schedulerItem = item; Reset(); netHelper = new NetHelper(homegenie); serialPortHelper = new SerialPortHelper(); tcpClientHelper = new TcpClientHelper(); udpClientHelper = new UdpClientHelper(); mqttClientHelper = new MqttClientHelper(); knxClientHelper = new KnxClientHelper(); schedulerHelper = new SchedulerHelper(homegenie); programHelper = new ProgramHelperBase(homegenie); }
public JsonRpcMqttConnection(MqttClientHelper client, string prefix = null, string clientId = null) { this.client = client ?? throw new ArgumentNullException(nameof(client)); this.prefix = prefix ?? ""; this.requestPending = new ConcurrentDictionary <string, TaskCompletionSource <IMessage> >(); this.registeredMethods = new string[0]; this.ClientId = clientId ?? Guid.NewGuid().ToString("N"); this.uptime = new DateTimeOffset(DateTime.Now); this.client.Client.ConnectionClosed += MqttOnConnectionClosed; this.client.Client.MqttMsgPublishReceived += MqttOnMessageReceive; PublishInfo(); }
public async Task TriggerAndOutputReuseConnection() { var mqttApplicationMessages = new List <MqttApplicationMessage>(); var counnections = 0; var options = new MqttServerOptionsBuilder() .WithConnectionValidator(x => { counnections += (x.ClientId != "IntegrationTest") ? 1 : 0; Debug.WriteLine($"ClientId:{x.ClientId}"); }) .Build(); using (var mqttServer = await MqttServerHelper.Get(_logger, options)) using (var mqttClient = await MqttClientHelper.Get(_logger)) using (var jobHost = await JobHostHelper <TriggerAndOutputWithSameConnectionTestFunction> .RunFor(_testLoggerProvider)) { await mqttClient.SubscribeAsync("test/outtopic"); await mqttClient.SubscribeAsync("test/outtopic2"); await mqttServer.PublishAsync(DefaultMessage); var firstMessage = await mqttClient.WaitForMessage(); if (firstMessage != null) { mqttApplicationMessages.Add(firstMessage); var secondMessage = await mqttClient.WaitForMessage(); if (secondMessage != null) { mqttApplicationMessages.Add(secondMessage); } } await WaitFor(() => TriggerAndOutputWithSameConnectionTestFunction.CallCount >= 1); } Assert.Equal(1, TriggerAndOutputWithSameConnectionTestFunction.CallCount); Assert.Equal(1, counnections); Assert.Equal(2, mqttApplicationMessages.Count); Assert.Contains(mqttApplicationMessages, x => x.Topic == "test/outtopic"); Assert.Contains(mqttApplicationMessages, x => x.Topic == "test/outtopic2"); var bodyString = Encoding.UTF8.GetString(mqttApplicationMessages.First().Payload); Assert.Equal("{\"test\":\"message\"}", bodyString); }
public async Task SimpleMessageIsPublished() { MqttApplicationMessage mqttApplicationMessage = null; using (var mqttServer = await MqttServerHelper.Get(_logger)) using (var mqttClient = await MqttClientHelper.Get(_logger)) using (var jobHost = await JobHostHelper <SimpleOutputIsPublishedTestFunction> .RunFor(_testLoggerProvider)) { await mqttClient.SubscribeAsync("test/topic"); await jobHost.CallAsync(nameof(SimpleOutputIsPublishedTestFunction.Testert)); mqttApplicationMessage = await mqttClient.WaitForMessage(); } Assert.NotNull(mqttApplicationMessage); }
public async Task TriggerAndOutputUseDifferentConnection() { MqttApplicationMessage mqttApplicationMessage = null; var connectionsCountServer1 = 0; var optionsServer1 = new MqttServerOptionsBuilder() .WithDefaultEndpointPort(1337) .WithConnectionValidator(x => { connectionsCountServer1 += (x.ClientId != "IntegrationTest") ? 1 : 0; }) .Build(); var connectionsCountServer2 = 0; var optionsServer2 = new MqttServerOptionsBuilder() .WithConnectionValidator(x => { connectionsCountServer2 += (x.ClientId != "IntegrationTest") ? 1 : 0; }) .Build(); using (var mqttServer1 = await MqttServerHelper.Get(_logger, optionsServer1)) using (var mqttServer2 = await MqttServerHelper.Get(_logger, optionsServer2)) using (var mqttClientForServer2 = await MqttClientHelper.Get(_logger)) using (var jobHost = await JobHostHelper <TriggerAndOutputWithDifferentConnectionTestFunction> .RunFor(_testLoggerProvider)) { await mqttClientForServer2.SubscribeAsync("test/outtopic"); await mqttServer1.PublishAsync(DefaultMessage); mqttApplicationMessage = await mqttClientForServer2.WaitForMessage(); await WaitFor(() => TriggerAndOutputWithDifferentConnectionTestFunction.CallCount >= 1); } Assert.Equal(1, TriggerAndOutputWithDifferentConnectionTestFunction.CallCount); Assert.Equal(1, connectionsCountServer1); Assert.Equal(1, connectionsCountServer2); Assert.NotNull(mqttApplicationMessage); Assert.Equal("test/outtopic", mqttApplicationMessage.Topic); var bodyString = Encoding.UTF8.GetString(mqttApplicationMessage.Payload); Assert.Equal("{\"test\":\"message\"}", bodyString); }
private int curDataSkipped; // the number of skipped slices of current data /// <summary> /// Initializes a new instance of the class. /// </summary> public MqttDSL(ICommContext commContext, DataSourceConfig dataSourceConfig) : base(commContext, dataSourceConfig) { dsOptions = new MqttDSO(dataSourceConfig.CustomOptions); dsLog = CreateLog(DriverUtils.DriverCode); mqttClientHelper = new MqttClientHelper(dsOptions.ConnectionOptions, dsLog); commandTopic = dsOptions.PublishOptions.RootTopic + CommandTopic; dataLifetime = TimeSpan.FromSeconds(dsOptions.PublishOptions.DataLifetime); deviceFilter = dsOptions.PublishOptions.DeviceFilter.Count > 0 ? new HashSet <int>(dsOptions.PublishOptions.DeviceFilter) : null; maxQueueSize = Math.Max(dsOptions.PublishOptions.MaxQueueSize, MinQueueSize); curDataQueue = new Queue <QueueItem <DeviceSlice> >(maxQueueSize); topicByDevice = new Dictionary <int, DeviceTopics>(); thread = null; terminated = false; curDataSkipped = 0; }
public async Task SimpleMessageIsPublished() { MqttApplicationMessage mqttApplicationMessage = null; using (var mqttServer = await MqttServerHelper.Get(_logger)) using (var mqttClient = await MqttClientHelper.Get(_logger)) using (var jobHost = await JobHostHelper <SimpleOutputIsPublishedTestFunction> .RunFor(_loggerFactory)) { await mqttClient.SubscribeAsync("test/topic"); mqttClient.OnMessage += (object sender, OnMessageEventArgs e) => mqttApplicationMessage = e.ApplicationMessage; await jobHost.CallAsync(nameof(SimpleOutputIsPublishedTestFunction.Testert)); await WaitFor(() => mqttApplicationMessage != null); } Assert.NotNull(mqttApplicationMessage); }
protected RtConnectorMqtt( MqttClientHelper mqttClient, ILoggerFactory loggerFactory = null, string prefix = null, string[] extraTopicsSbscribe = null) { loggerFactory ??= Configuration.DefaultLoggerFactory; this.mqttClient = mqttClient; this.prefix = prefix ?? ""; this.logger = loggerFactory.CreateLogger($"{nameof(RtConnectorMqtt)}"); this.extraTopicsSbscribe = extraTopicsSbscribe ?? new string[0]; this.extraTopics = new HashSet <string>(); this.mqttClient.OnConnectionChange += MqttOnConnectionChange; this.mqttClient.Client.MqttMsgPublishReceived += MqttOnMessageReceive; rtTags = new HashSet <RtTagMqtt>(); }
static void Main(string[] args) { Configuration.SetDefaultLogger(); logger = Configuration.DefaultLoggerFactory.CreateLogger("Main"); logger.LogInformation("Start DeltaX.RealTime.Mqtt.FunctionalTest"); var config = new MqttConfiguration("Mqtt", "appsettings.json"); var mqtt = new MqttClientHelper(config); var conn = RtConnectorMqtt.Build(mqtt); conn.Connected += Conn_Connected; conn.ValueUpdated += Conn_ValueUpdated; var t = conn.ConnectAsync(); t.Wait(); Thread.Sleep(500); var pepe = conn.GetOrAddTag("pepe", null); // t.Wait(); var pepe2 = conn.AddTag("pepe2", "pepe"); var pruebaDate = conn.AddTag("pruebaDate"); var pruebaJson = conn.AddTag("pruebaJson"); var pruebaJsonStr = conn.AddTagDefinition("pruebaJson@JSON:arrayString[0]"); var pruebaJsonFail = conn.AddTagDefinition("pruebaJson@JSON:Fail[0]"); var pruebaJsonObj = conn.AddTagDefinition("pruebaJson@JSON:obj.programName"); var pruebaJsonCounter = conn.AddTagDefinition("pruebaJson@JSON:arrayInteger[1]"); var pruebaCount2 = conn.AddTag("pruebaCount2"); var pruebaExpression = new RtTagExpression("arg0 + arg1", "arg0 + arg1", new[] { pruebaJsonCounter, pruebaCount2 }); var pruebaExpression2 = RtTagExpression.AddExpression(conn, "{pruebaCount2} + 1000"); { using (var pruebaExpression3 = RtTagExpression.AddExpression(conn, "{pruebaCount2} + 1000")) { pruebaExpression3.ValueUpdated += OnUpdatedValue; pruebaExpression.ValueUpdated += OnUpdatedValue; Thread.Sleep(500); pruebaCount2.SetNumeric(45); Thread.Sleep(500); pruebaCount2.SetNumeric(46); Thread.Sleep(500); logger.LogInformation("FIN Bloque pruebaExpression3"); } using (var test = conn.AddTag("pruebaCount")) { test.ValueUpdated += OnUpdatedValue; Thread.Sleep(500); test.SetNumeric(45); Thread.Sleep(500); test.SetNumeric(46); Thread.Sleep(500); logger.LogInformation("FIN Bloque test"); } } var pruebaUL1 = conn.GetOrAddTag("pruebaUL1"); var asdf = conn.GetOrAddTag("pruebaUL1"); var pruebaUL1_f1 = conn.AddTag("pruebaUL1@UL:field1"); var pruebaUL1_c1f1 = conn.AddTag("pruebaUL1@UL:cmd1|counter10"); var pruebaUL1_d1c1f1 = conn.AddTag("pruebaUL1@UL:device1@cmd1|field1"); int counter = 0; while (true) { logger.LogInformation("-- {0} Status:{1} Value:{@2} ", pruebaJson.TagName, pruebaJson.Status, pruebaJson.Value.Text); logger.LogInformation("-- {0} Status:{1} Value:{@2} ", pruebaJsonStr.TagName, pruebaJsonStr.Status, pruebaJsonStr.Value.Text); logger.LogInformation("-- {0} Status:{1} Value:{@2} ", pruebaJsonFail.TagName, pruebaJsonFail.Status, pruebaJsonFail.Value.Text); logger.LogInformation("-- {0} Status:{1} Value:{@2} ", pruebaJsonObj.TagName, pruebaJsonObj.Status, pruebaJsonObj.Value.Text); logger.LogInformation("-- {0} Status:{1} Value:{@2} ", pruebaJsonCounter.TagName, pruebaJsonCounter.Status, pruebaJsonCounter.Value.Numeric); logger.LogInformation("-- EXPRESSION {0} Status:{1} GetExpresionValues:{@2} Value:{@3} ", pruebaExpression.TagName, pruebaExpression.Status, pruebaExpression, pruebaExpression.Value.Numeric); logger.LogInformation("-- EXPRESSION {0} Status:{1} GetExpresionValues:{@2} Value:{@3} ", pruebaExpression2.TagName, pruebaExpression2.Status, pruebaExpression2, pruebaExpression2.Value.Numeric); logger.LogInformation("-- ULTRALIGHT {0} Status:{1} Value:{@2}", pruebaUL1.TagName, pruebaUL1.Status, pruebaUL1.Value.Numeric); logger.LogInformation("-- ULTRALIGHT {0} Status:{1} Value:{@2}", pruebaUL1_c1f1.TagName, pruebaUL1_c1f1.Status, pruebaUL1_c1f1.Value.Numeric); Thread.Sleep(1000); string ul1 = $"device2@cmd{counter}|counter={counter}|counter10={counter * 10}"; pruebaUL1.SetText(ul1); pruebaCount2.SetNumeric(counter * 1.23); pruebaJson.SetJson(new { programName = "DeltaX.RealTime.Mqtt.FunctionalTest", date = DateTime.Now, counter = counter++, arrayString = new string[] { $"hola mundo {counter}", $"el contador es {counter / 100} k", "fake" }, arrayInteger = new int[] { counter * 10, counter, counter * 30 }, arrayDouble = new double[] { counter * 1e-2, counter * 1e-6, counter * 1e-9 }, arrayObject = new object[] { "DeltaX.RealTime.Mqtt.FunctionalTest", counter, new int[] { counter, counter * 100, counter * 10000 } }, obj = new { programName = "DeltaX.RealTime.Mqtt.FunctionalTest", date = DateTime.Now } }); Thread.Sleep(2000); } }
public async Task RunAsync() { var config = new MqttConfiguration(); config.ClientId = "Test JsonRpcMqtt" + Guid.NewGuid(); config.Username = "******"; config.Password = "******"; var mqtt = new MqttClientHelper(config); // Rpc Ojbect var rpc = new Rpc(new JsonRpcMqttConnection(mqtt, "test/", clientId: "ExampleClient")); // RPC Register methods for dispach notifications/events from server rpc.Dispatcher.RegisterMethod(this, nameof(OnNotifyBroadcast)); rpc.Dispatcher.RegisterMethod(this, nameof(OnNotifySum)); // RPC: UpdateRegisteredMethods for subscribe and receive notifications mqtt.OnConnectionChange += (s, connected) => { if (connected) { rpc.UpdateRegisteredMethods(); } }; // Map interface with rpc for call services methods. var service = rpc.GetServices <IExampleService>(); // Wait for connect mqtt.ConnectAsync().Wait(); while (mqtt.IsRunning) { // Call async without service var taskBroadcast = rpc.CallAsync("SendBroadcastAsync", $"Mensaje_1 enviado desde el cliente {rpc.Connection.ClientId} " + $"a todos lo clientes, Date:{DateTime.Now}"); // Call with service var taskBroadcast2 = service.SendBroadcastAsync($"Mensaje_2 enviado desde el cliente {rpc.Connection.ClientId} " + $"a todos lo clientes, Date:{DateTime.Now}"); logger.LogInformation("SendBroadcastAsync task 1:{0} task 2:{1}", taskBroadcast.Status, taskBroadcast2.Status); var a = 1; var b = DateTime.Now.Second; var res = service.Sum(a, b); logger.LogInformation("Sum result:{0} expected:{1}", res, (a + b)); var t = service.TaskVoidAsync(1, DateTime.Now.Second); logger.LogInformation("TaskVoidAsync t.Status:{0}", t?.Status); t.Wait(); logger.LogInformation("TaskVoidAsync affter wait t.Status:{0}", t?.Status); var t2 = service.TaskFloatAsync(a, b); t2.Wait(); logger.LogInformation("TaskFloatAsync result:{0} expected:{1} status:{2}", t2.Result, a + b + 1.2323, t2.Status); string rCall1 = service.Concat("ASDF", a, b); logger.LogInformation("Concat result:<{0}> expected:<{1}>", rCall1, $"Formated format:ASDF a:{a} b:{b}"); CustObj resObj1 = service.FuncCustObj(1234, "hola FuncCustObj"); logger.LogInformation("GetCaller FuncCustObj Result: {@0}", resObj1); resObj1 = service.FuncCustObj(1234, "hola FuncCustObj", new CustObj { a = 23, b = new string[] { "sadf" } }); logger.LogInformation("GetCaller FuncCustObj Result: {@0} {1}", resObj1, resObj1.c[0]); await Task.Delay(5000); } }