Beispiel #1
0
        public void TestMqttOutputTime()
        {
            WriteTitleText("Starting MQTT output time test");

            Console.WriteLine("Read interval: " + ReadInterval);

            RequireMqttConnection = true;

            ConnectDevices();

            SetDeviceReadInterval(ReadInterval);

            EnableMqtt();

            Mqtt.Data.Clear();

            Console.WriteLine("Skipping next data entries in case they're out of date...");

            Mqtt.WaitUntilData(4);

            Console.WriteLine("Waiting for the next data entry...");

            var secondsBetweenData = Mqtt.WaitUntilData(1);

            Console.WriteLine("Time between data entries: " + secondsBetweenData + " seconds");

            var expectedMqttOutputTime = ReadInterval;

            AssertIsWithinRange("mqtt output time", expectedMqttOutputTime, secondsBetweenData, TimeErrorMargin);
        }
Beispiel #2
0
 static void StartMqtt()
 {
     mqtt = new Mqtt();
     mqtt.Run("localhost", 8080, "Controller", "", "");
     mqtt.Subscribe("air/toxicity", Toxicity, true);
     mqtt.Subscribe("wind/strength", WindStrength, true);
 }
Beispiel #3
0
        public Graph(SingleGraphViewModel sgvm, SingleGraphWindow sgw, string identifier, LineSeries lineSeries)
        {
            //Get queue based on identifier
            incomingQueue          = Mqtt.GetIncomingQueue();
            this.singleGraphWindow = sgw;
            this.windowToPlotOn    = sgw;
            this.sgvm       = sgvm;
            LineSeries      = lineSeries;
            this.identifier = identifier;

            if (identifier == "xacceleration" || identifier == "yacceleration" || identifier == "zacceleration")
            {
                identifier_top = "acceleration";
                topic          = new string[] { identifier_top };
            }
            else if (identifier == "pitch" || identifier == "yaw" || identifier == "roll")
            {
                identifier_top = "orientation";
                topic          = new string[] { identifier_top };
            }

            singleGraphWindow.chart.Series.Add(LineSeries);

            sgvm.Title = SetTitle(identifier);

            Mqtt.Subscribe(topic);

            switch (identifier)
            {
            case Topic.XAccTopic:
                LineSeries.Title = "AccX";
                break;

            case Topic.YAccTopic:
                LineSeries.Title = "AccY";
                break;

            case Topic.ZAccTopic:
                LineSeries.Title = "AccZ";
                break;

            case Topic.RollTopic:
                LineSeries.Title = "Roll";
                break;

            case Topic.PitchTopic:
                LineSeries.Title = "Pitch";
                break;

            case Topic.YawTopic:
                LineSeries.Title = "Yaw";
                break;

            default:
                break;
            }

            Run();
        }
        public SensorDataController()
        {
            _mqtt       = new Mqtt();
            _repository = new WeatherRepository(MongoDBConnector.GetInstance());
            HttpClient httpClient = new HttpClient();

            httpClient.PostAsync("http://sensoranalyticsservice/api/SensorAnalytics/CreateAnalyticsService", null);
        }
Beispiel #5
0
        public DataService()
        {
            _mqtt     = new Mqtt();
            _database = InfluxDBConnector.GetInstance();

            ServiceCreated += OnServiceCreated;
            ServiceCreated?.Invoke(this, EventArgs.Empty);
        }
Beispiel #6
0
        public SimpleSubscribe(string broker)
        {
            var mqtt = new Mqtt(broker);

            mqtt.On["lights/bedroom"] = msg =>
            {
                Console.WriteLine("Bedroom lights set to {0}", msg.Message);
            };
        }
Beispiel #7
0
 //private IHubContext<MessageHub> _hubContext;
 public AnalyticsService()
 {
     _mqtt     = new Mqtt();
     _database = InfluxDBConnector.GetInstance();
     //_hubContext = null;
     _model          = new WeatherAnalyzer();
     ServiceCreated += OnServiceCreated;
     ServiceCreated?.Invoke(this, EventArgs.Empty);
 }
        public WildcardSubscribe(string broker)
        {
            var mqtt = new Mqtt(broker);

            mqtt.On["{room}/sensors/{sensor}"] = msg =>
            {
                Console.WriteLine($"{msg.sensor} in {msg.room} measured {msg.Message}");
            };
        }
 public IogServicesMqttCommandsReceiverHostedService(IOptions <Forwarder> mqttConfiguration,
                                                     IServiceProvider serviceProvider, IMqttClientMethods mqttClientMethods,
                                                     IMqttClientConfiguration mqttClientConfiguration, IEventService eventService)
 {
     _mqttConfiguration       = mqttConfiguration.Value.Mqtt;
     _serviceProvider         = serviceProvider;
     _mqttClientConfiguration = mqttClientConfiguration;
     _mqttClientMethods       = mqttClientMethods;
     _eventService            = eventService;
 }
Beispiel #10
0
 public SensorData()
 {
     _db            = new DataBase();
     Data           = new ModelBase();
     _mqtt          = new Mqtt("192.168.31.123");
     Setting.UserId = 0;
     InitSensors();
     _mqtt.MqttMsgPublishReceived += _mqtt_MqttMsgPublishReceived;
     UpdatedataAsync();
 }
        public SideBarInfo(SensorsViewModel sensorsViewModel, SensorWindow sensorWindow)
        {
            this.sensorsViewModel = sensorsViewModel;
            this.sensorWindow     = sensorWindow;

            this.incomingQueue = Mqtt.GetIncomingQueue();
            Mqtt.Subscribe(new string[] { "temperature" });

            Run();
        }
    // Start is called before the first frame update
    void Start()
    {
        workQueue = new Queue <SkeletonData>();

        allSkeletons = new Dictionary <String, GameObject>();

        myMqtt = new Mqtt();
        myMqtt.InitMqtt(myMqtt.skeletonTopic);
        // register a callback-function (we have to implement, see below) which is called by the library when a message was received
        myMqtt.client.MqttMsgPublishReceived += MqttReceiveCallback;
    }
 private void Start()
 {
     mqtt          = FindObjectOfType <Mqtt>();
     queuedMessage = new List <float>();
     lastTimeStamp = Time.time;
     Debug.Log("Mapping (toppic)= " + topic);
     if (topic == "")
     {
         topic = gameObject.name;
     }
     Debug.Log("Mapping (toppic)= " + topic);
 }
Beispiel #14
0
        public void TestMqttOutput()
        {
            WriteTitleText("Starting MQTT output test");

            Console.WriteLine("Read interval: " + ReadInterval);
            Console.WriteLine("Soil moisture sensor value: " + SimulatedSoilMoistureSensorValue);

            RequireMqttConnection = true;

            ConnectDevices();

            EnableMqtt();

            SetDeviceReadInterval(ReadInterval);

            SimulateSoilMoisture(SimulatedSoilMoistureSensorValue);

            Mqtt.Data.Clear();

            Console.WriteLine("Waiting for MQTT data...");

            var numberOfEntriesToWaitFor = 3; // TODO: See if this can be reduced

            Mqtt.WaitForData(numberOfEntriesToWaitFor);

            Assert.AreEqual(numberOfEntriesToWaitFor, Mqtt.Data.Count, "Incorrect number of entries returned.");

            var latestEntry = Mqtt.Data [Mqtt.Data.Count - 1];

            Assert.IsNotNull(latestEntry, "The latest MQTT entry is null.");

            Mqtt.ConsoleWriteDataEntry(latestEntry);

            Assert.IsTrue(latestEntry.ContainsKey("C"), "The latest MQTT entry doesn't contain a 'C' key/value.");

            var valueString = latestEntry ["C"];

            //Console.WriteLine ("Calibrated value string: \"" + valueString + "\"");

            var containsWhitespace = valueString.Trim().Length != valueString.Length;

            Assert.IsFalse(containsWhitespace, "The calibrated value contains whitespace: \"" + valueString + "\"");

            var isDecimal = valueString.Contains(".");

            Assert.IsFalse(isDecimal, "The calibrated value contains a decimal point when it shouldn't.");

            Console.WriteLine("MQTT calibrated value: " + valueString);

            var value = Convert.ToInt32(valueString);

            AssertIsWithinRange("MQTT calibrated soil moisture", ApplyOffset(SimulatedSoilMoistureSensorValue, ExpectedCalibratedValueOffset), value, CalibratedValueMarginOfError);
        }
Beispiel #15
0
        public Config()
        {
            TimeoutSeconds = 300;

            Mqtt = new Mqtt
            {
                Host            = "127.0.0.1",
                Port            = 1883,
                ReportTopic     = "bluewalk/shutdown/report",
                ShutdownTopic   = "bluewalk/shutdown",
                ShutdownPayload = "yes"
            };
        }
        public void SendMqttCalibrationCommand()
        {
            Mqtt.Data.Clear();

            Mqtt.SendCommand(Key, RawSoilMoistureValue);

            // Skip some data
            WaitForData(1);

            var dataEntry = WaitForDataEntry();

            AssertDataValueEquals(dataEntry, Key, RawSoilMoistureValue);
        }
        /// <summary>
        /// Sample of a method sending numeric data
        /// </summary>
        /// <returns></returns>
        static async Task SendRandomDataAsync()
        {
            Random random = new Random();

            while (!CtSource.Token.IsCancellationRequested)
            {
                float x = 1 + 5 * random.Next();
                float y = 1 + 5 * random.Next();
                await Mqtt.SendNumericData(Topic2, DateTimeOffset.Now, new[] { x, y });

                await Task.Delay(1000);
            }
        }
Beispiel #18
0
        public SimplePublish(string broker)
        {
            var mqtt = new Mqtt(broker);

            mqtt.Client.Disconnected += (reason, message) =>
            {
                Console.WriteLine($"Disconnected {reason.ToString()}: {message}");
            };
            mqtt.On["sensors/bedroom/presence"] = async msg =>
            {
                if (msg.Message == "human present")
                {
                    await mqtt.Publish("lights/bedroom", "on");
                }
            };
        }
Beispiel #19
0
        public void SendThresholdCommand()
        {
            WriteParagraphTitleText("Sending threshold command...");

            Mqtt.SendCommand("T", Threshold);

            Console.WriteLine("Skipping the next data entries in case they're out of date...");

            WaitForData(3);

            var dataEntry = WaitForDataEntry();

            WriteParagraphTitleText("Checking threshold value...");

            AssertDataValueEquals(dataEntry, "T", Threshold);
        }
Beispiel #20
0
    public void Start()
    {
        myDict    = new Dictionary <string, GameObject>();
        workQueue = new Queue <updateStruct>();

        worldObjects = new Dictionary <string, GameObject>();

        // map render strings to GameObjects

        myDict.Add("drone", Drone);
        myDict.Add("fire", Fire);
        myDict.Add("avatar", Avatar);
        myDict.Add("line", Line);

        myMqtt = new Mqtt();
        myMqtt.InitMqtt(myMqtt.renderTopic);
        // register a callback-function (we have to implement, see below) which is called by the library when a message was received
        myMqtt.client.MqttMsgPublishReceived += MqttReceiveCallback;
    }
Beispiel #21
0
        public void TestSetReadIntervalCommand()
        {
            WriteTitleText("Starting read interval command test");

            Console.WriteLine("Read interval: " + ReadInterval);

            RequireMqttConnection = true;

            ConnectDevices();

            EnableMqtt();

            Mqtt.SendCommand("I", ReadInterval);

            WaitForData(1);

            var dataEntry = WaitForDataEntry();

            AssertDataValueEquals(dataEntry, "I", ReadInterval);
        }
Beispiel #22
0
        private async void onMqttConnectionClosed(object sender, EventArgs e)
        {
            var retryCount = 0;

            while (!Mqtt.IsConnected && retryCount < 3)
            {
                try
                {
                    Mqtt.Connect(Config.Mqtt.ClientId, null, null, false, 60);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Reconnect failed: " + exception.Message);
                }
                finally
                {
                    await Task.Delay(TimeSpan.FromSeconds(1), Token);
                }
            }
        }
Beispiel #23
0
        public void TestPumpCommand()
        {
            WriteTitleText("Starting pump command test");

            Console.WriteLine("Pump command: " + PumpCommand);
            Console.WriteLine("");

            RequireMqttConnection = true;

            ConnectDevices();

            EnableMqtt();

            Mqtt.SendCommand("P", (int)PumpCommand);

            WaitForData(2);

            var dataEntry = WaitForDataEntry();

            AssertDataValueEquals(dataEntry, "P", (int)PumpCommand);
        }
        public void TestPumpBurstOffTimeCommand()
        {
            WriteTitleText("Starting pump burst off time command test");

            Console.WriteLine("Pump burst off time: " + PumpBurstOffTime);
            Console.WriteLine("");

            RequireMqttConnection = true;

            ConnectDevices();

            EnableMqtt();

            Mqtt.SendCommand("O", PumpBurstOffTime);

            // Skip some data
            WaitForData(1);

            var dataEntry = WaitForDataEntry();

            AssertDataValueEquals(dataEntry, "O", PumpBurstOffTime);
        }
Beispiel #25
0
        public void TestSetReadIntervalCommand()
        {
            WriteTitleText("Starting read interval command test");

            Console.WriteLine("Read interval: " + ReadInterval);

            EnableMqtt();

            ConnectDevices();

            Mqtt.Data.Clear();

            // MQTT version
            Mqtt.SendCommand("I", ReadInterval);

            // Skip the first entry
            WaitForDataEntry();

            // Wait for the next entry
            var dataEntry = WaitForDataEntry();

            AssertDataValueEquals(dataEntry, "I", ReadInterval);
        }
Beispiel #26
0
        public IHttpActionResult PostPublish(Mqtt mqtt)
        {
            client = new MqttClient(MosquittoIP);                           //MQTTServer在本機
            client.MqttMsgPublishReceived += client_MqttMsgPublishReceived; //當接收到訊息時處理函式
            clientId = Guid.NewGuid().ToString();                           //取得唯一碼
            client.Connect(clientId);                                       //建立連線
            //若有輸入發佈主題
            if (mqtt.Topic != "")
            {
                //設定完整的發佈路徑
                string Topic = mqtt.Topic;
                string Text  = mqtt.Topic + "|" + mqtt.Type + '|' + mqtt.Data + "|" + mqtt.Date;

                //發佈主題、內容及設定傳送品質 QoS 0 ( 0, 1, 2 )
                client.Publish(Topic, Encoding.UTF8.GetBytes(Text), MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE, true);
            }
            else
            {
            }
            System.Diagnostics.Debug.WriteLine(mqtt.Topic);
            System.Diagnostics.Debug.WriteLine(mqtt.Data);
            return(Ok("ok"));
        }
Beispiel #27
0
        public void TestPumpBurstOnTimeCommand()
        {
            WriteTitleText("Starting pump burst on time command test");

            Console.WriteLine("Pump burst on time: " + PumpBurstOnTime);
            Console.WriteLine("");

            RequireMqttConnection = true;

            ConnectDevices();

            EnableMqtt();

            Mqtt.SendCommand("B", PumpBurstOnTime);

            Console.WriteLine("Skipping the next data entires in case they're out of date...");

            WaitForData(2);

            var dataEntry = WaitForDataEntry();

            AssertDataValueEquals(dataEntry, "B", PumpBurstOnTime);
        }
 public static void setMqtt(Mqtt m)
 {
     mqtt = m;
 }
Beispiel #29
0
        internal static ProgramContext Initialize(ILoggerFactory loggerFactory, Config config)
        {
            var logger      = loggerFactory.CreateLogger(nameof(Logic));
            var mqttClients = new List <Mqtt>();
            var logos       = new List <Logo>();

            logger.LogInformation($"MQTT broker at {config.MqttBrokerUri} using port {config.MqttBrokerPort}");

            foreach (var logoConfig in config.Logos)
            {
                logger.LogInformation($"Logo PLC at {logoConfig.IpAddress}");

                var logo = new Logo(
                    loggerFactory.CreateLogger <Logo>(),
                    logoConfig.IpAddress,
                    logoConfig.MemoryRanges);
                logos.Add(logo);

                foreach (var mqttClientConfig in logoConfig.Mqtt)
                {
                    logger.LogInformation($"- MQTT client {mqttClientConfig.ClientId}");

                    var mqttClient = new Mqtt(
                        loggerFactory.CreateLogger <Mqtt>(),
                        mqttClientConfig.ClientId,
                        config.MqttBrokerUri,
                        config.MqttBrokerPort,
                        mqttClientConfig.CleanSession,
                        config.MqttBrokerUsername,
                        config.MqttBrokerPassword,
                        mqttClientConfig.LastWill);
                    mqttClients.Add(mqttClient);

                    var mapper = new Mapper(loggerFactory, logo, mqttClient);

                    foreach (var channel in mqttClientConfig.Channels)
                    {
                        var action = channel.GetActionAsEnum();

                        logger.LogInformation($"-- {action} {channel.Topic} {channel.GetQualityOfServiceAsEnum()} retain:{channel.Retain} logo: {channel.Type}@{channel.LogoAddress}");

                        switch (action)
                        {
                        case MqttChannelConfig.Actions.Publish:
                            mapper.PublishOnChange(
                                channel.Topic,
                                channel.LogoAddress,
                                channel.GetTypeAsEnum(),
                                channel.Retain,
                                channel.GetQualityOfServiceAsEnum().ToMqttNet());
                            break;

                        case MqttChannelConfig.Actions.Subscribe:
                            mapper.WriteLogoVariable(
                                mqttClient.Subscribe(
                                    channel.Topic,
                                    channel.GetQualityOfServiceAsEnum().ToMqttNet()),
                                channel.LogoAddress,
                                channel.GetTypeAsEnum());
                            break;

                        case MqttChannelConfig.Actions.SubscribePulse:
                            mapper.PulseLogoVariable(
                                mqttClient.Subscribe(
                                    channel.Topic,
                                    channel.GetQualityOfServiceAsEnum().ToMqttNet()),
                                channel.LogoAddress,
                                channel.GetTypeAsEnum(),
                                channel.Duration);
                            break;

                        default: throw new ArgumentOutOfRangeException();
                        }
                    }
                }
            }

            return(new ProgramContext(
                       loggerFactory.CreateLogger <ProgramContext>(),
                       logos.ToImmutableArray(),
                       mqttClients.ToImmutableArray()));
        }
Beispiel #30
0
 public MessageServer()
 {
     Current = this;
     _mqtt   = new Mqtt("192.168.31.123");
     _mqtt.MqttMsgPublishReceived += _mqtt_MqttMsgPublishReceived;
 }