예제 #1
0
        private async Task <MethodResponse> SendMessageToConverter(MethodRequest methodRequest, object userContext)
        {
            if (!string.IsNullOrEmpty(methodRequest.DataAsJson))
            {
                //if (!(userContext is MqttHub mqttClient))
                //{
                //    throw new InvalidOperationException("UserContext doesn't contain " + "expected values");
                //}

                Console.WriteLine($"Received Direct method: {methodRequest.Name} sent to Converter module");
                ForegroundColorSuccess(methodRequest.DataAsJson);
                await MqttHub.PublishAsync("MessageToConverter", methodRequest.DataAsJson);

                await MqttHub.PublishAsync("MessageToConverter", "");

                // Acknowlege the direct method call with a 200 success message
                string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}";
                return(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
            }
            else
            {
                // Acknowlege the direct method call with a 400 error message
                string result = "{\"result\":\"Invalid parameter\"}";
                return(new MethodResponse(Encoding.UTF8.GetBytes(result), 400));
            }
        }
예제 #2
0
        static async Task Init()
        {
            Console.WriteLine("Starting Proxy Module");
            MqttHub mqtt    = new MqttHub();
            var     _client = mqtt.Client;

            //Handler: Mqtt broker Online Connection.
            _client.UseConnectedHandler(eventArgs =>
            {
                Console.WriteLine("Connected successfully with MQTT Brokers.");
                Console.WriteLine("IsSessionPresent: " + eventArgs.AuthenticateResult.IsSessionPresent);
                Console.WriteLine("ResultCode: " + eventArgs.AuthenticateResult.ResultCode);
                //Console.WriteLine(eventArgs.AuthenticateResult.AssignedClientIdentifier);
                //Console.WriteLine(eventArgs.AuthenticateResult.AuthenticationMethod);
                //Console.WriteLine(eventArgs.AuthenticateResult.MaximumPacketSize);
                //Console.WriteLine(eventArgs.AuthenticateResult.ReasonString);
                //Console.WriteLine(eventArgs.AuthenticateResult.SessionExpiryInterval);
                //Console.WriteLine(eventArgs.AuthenticateResult.ServerReference);
                //Console.WriteLine(eventArgs.AuthenticateResult.ServerKeepAlive);
                //Console.WriteLine(eventArgs.AuthenticateResult.RetainAvailable);
                //Console.WriteLine(eventArgs.AuthenticateResult.ResponseInformation);
                //Console.WriteLine(Encoding.UTF8.GetString(eventArgs.AuthenticateResult.AuthenticationData));

                //Subscribe to topic
                MqttHub.SubscribeAsync("MessageToProxy").Wait();
            });

            string deviceConnectionString = "HostName=iot-abb-dev.azure-devices.net;" +
                                            "DeviceId=abb-Device1;" +
                                            "SharedAccessKey=WGVpiMpu5noKqH19Ru4xKv75oslkD21sI2wOSzIUq8s=";

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString,
                                                                       TransportType.Mqtt_Tcp_Only);

            var device = new Device(deviceClient);
            await device.InvokeEventHandlersAsync().ConfigureAwait(false);

            //Handler: Mqtt broker Online Connection.
            _client.UseDisconnectedHandler(e =>
            {
                Console.WriteLine("Disconnected from MQTT Brokers.");
            });

            //Handler: Receive message.
            _client.UseApplicationMessageReceivedHandler(e =>
            {
                if (e.ApplicationMessage.Payload != null)
                {
                    Console.WriteLine();
                    Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                    Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                    Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                    Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                    Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");

                    //Task.Run(() => _client.PublishAsync("hello/world"));

                    var payloadIn = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                    payloadIn     = payloadIn.Substring(payloadIn.IndexOf('{'));
                    var jsonData  = JsonConvert.DeserializeObject <DeviceTelemetry>(payloadIn);

                    Console.WriteLine("message send to cloud");
                    Console.WriteLine();
                    device.SendEventAsync(JsonConvert.SerializeObject(jsonData)).Wait();
                }
                else
                {
                    Console.WriteLine("Payload empty");
                }
            });

            Console.WriteLine("Press key to exit");
            Console.ReadLine();

            Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait();
            //await _client.StopAsync();
        }
예제 #3
0
        static void Main(string[] args)
        {
            Console.WriteLine("Starting Converter module");
            try
            {
                CPMBaseData obj  = new CPMBaseData();
                string      json = "[{\"model\": \"abb.ability.metadata\",\"typeId\": \"abb.ability.PM\",\"version\": \"1.0.0\",\"variables\": {\"DetectorEmptyPipe2.value\": {\"dataType\": \"string\",\"dataTypeExt\": \"uint64\"}},\"properties\": {\"UserSystemSpanRatio.value\": {\"dataType\": \"string\",\"dataTypeExt\": \"float64\"},\"HardwareVersion\": {\"dataType\": \"string\"},\"sensorElectrodeMaterials\": {\"dataType\": \"number\",\"dataTypeExt\": \"int64\"},\"DetectorEmptyPipe2.unitsCode\": {\"dataType\": \"number\",\"dataTypeExt\": \"int64\"},\"SensorName\": {\"dataType\": \"String\"}}}]";
                obj.EquipmentDetails();
                MqttHub mqtt    = new MqttHub();
                var     _client = mqtt.Client;

                //Handlers
                _client.UseConnectedHandler(e =>
                {
                    Console.WriteLine("Connected successfully with MQTT Brokers.");

                    //Subscribe to topic

                    MqttHub.SubscribeAsync("MessageToConverter").Wait();
                });
                _client.UseDisconnectedHandler(e =>
                {
                    Console.WriteLine("Disconnected from MQTT Brokers.");
                });
                _client.UseApplicationMessageReceivedHandler(e =>
                {
                    if (e.ApplicationMessage.Payload != null)
                    {
                        Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                        Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                        Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                        Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                        Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");

                        var payloadIn = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
                        payloadIn     = payloadIn.Substring(payloadIn.IndexOf('{'));

                        var desireDeviceId = JsonConvert.DeserializeObject <JObject>(payloadIn)["deviceid"]
                                             .ToString();

                        Console.WriteLine($"Received Device id: {desireDeviceId}");

                        var desireDeviceInfo = GetData(desireDeviceId);
                        var payloadOut       = JsonConvert.SerializeObject(desireDeviceInfo);

                        var r = MqttHub.PublishAsync("MessageToProxy", payloadOut).Result;
                        r     = MqttHub.PublishAsync("MessageToProxy", "").Result;
                    }
                    else
                    {
                        Console.WriteLine("Payload empty");
                    }
                });

                Console.WriteLine("Press key to exit");
                Console.ReadLine();

                Task.Run(() => Thread.Sleep(Timeout.Infinite)).Wait();
                //_client.StopAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }