Esempio n. 1
0
        private static double TimeDifferent(DateTime lastDateTime)
        {
            var time = DateTime.Now - lastDateTime;

            MyConsole.Data("TimeDifferent" + time.TotalSeconds);

            return(time.TotalSeconds);
        }
Esempio n. 2
0
        private async Task CreateMqttClientAsync()
        {
            // signalr
            HubConnection _connection = new HubConnectionBuilder()
                                        .WithUrl(new Uri(_appSettings.SignalrUri))
                                        .WithAutomaticReconnect(new RandomRetryPolicy())
                                        .Build();

            // mongodb
            MongoClient                _mongoClient        = new MongoClient(_appSettings.MongoConnection);
            IMongoDatabase             _db                 = _mongoClient.GetDatabase(_appSettings.MongoDb);
            IMongoCollection <RawData> _rawDatasCollection = _db.GetCollection <RawData>(RAWDATA_SCHEMA);
            IMongoCollection <Setting> _settingsCollection = _db.GetCollection <Setting>(SETTING_SCHEMA);

            // redis
            RedisManagerPool _redisClient = new RedisManagerPool(_appSettings.RedisHost);

            MqttFactory factory = new MqttFactory();
            // Create a new MQTT client.
            var mqttClient = factory.CreateMqttClient();
            var options    = new MqttClientOptionsBuilder()
                             .WithTcpServer(_appSettings.Host, _appSettings.Port)
                             .Build();

            // Reconnecting event handler
            mqttClient.UseDisconnectedHandler(async e =>
            {
                MyConsole.Warning("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));
                try
                {
                    await mqttClient.ConnectAsync(options, CancellationToken.None);
                }
                catch
                {
                    MyConsole.Error("### RECONNECTING FAILED ###");
                }
            });

            // Message received event handler
            // Consuming messages
            mqttClient.UseApplicationMessageReceivedHandler(async e =>
            {
                // RecevicedTopic(e);
                if (e.ApplicationMessage.Topic == RPMTopic)
                {
                    await RecevicedRPMTopic(e, _rawDatasCollection, _redisClient);
                    // emit ve client
                    await _connection.InvokeAsync(MQTT_SERVER.Constants.Constants.MESSAGE, true);
                }

                if (e.ApplicationMessage.Topic == SettingTopic)
                {
                    var payload   = e.ApplicationMessage.Payload;
                    string result = Encoding.UTF8.GetString(payload);
                    MyConsole.Info("#### ### Someone ask for setting ###" + result);

                    var settingTopicData = JsonConvert.DeserializeObject <SettingTopic>(result);
                    var settingItem      = _settingsCollection.AsQueryable <Setting>().Where(x => x.machineID == settingTopicData.id).FirstOrDefault();
                    await SettingReplyPublish(mqttClient, settingItem);
                }
            });
            // Connected event handler
            mqttClient.UseConnectedHandler(async e =>
            {
                // Subscribe to topics
                await mqttClient.SubscribeAsync(RPMTopic);
                await mqttClient.SubscribeAsync(RSSITopic);
                await mqttClient.SubscribeAsync(SettingTopic);

                // Subscribe all topics
                await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic("#").Build());
                MyConsole.Data($"### SUBSCRIBED TOPICS ### :  ' {SettingTopic} ', ' {RPMTopic} ', ' {RSSITopic} '");
            });
            mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async e =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try
                {
                    await mqttClient.ConnectAsync(options);
                }
                catch
                {
                    Console.WriteLine("### RECONNECTING FAILED ###");
                }
            });
            // Try to connect to MQTT server
            try
            {
                await mqttClient.ConnectAsync(options, CancellationToken.None);
            }
            catch (Exception exception)
            {
                Console.WriteLine("### CONNECTING FAILED ###" + Environment.NewLine + exception);
            }
        }
Esempio n. 3
0
        private async Task RecevicedRPMTopic(MqttApplicationMessageReceivedEventArgs e,
                                             IMongoCollection <RawData> rawDatasCollection,
                                             RedisManagerPool redisClient)
        {
            using (var client = redisClient.GetClient())
            {
                var    payload  = e.ApplicationMessage.Payload;
                string result   = System.Text.Encoding.UTF8.GetString(payload);
                var    rpmTopic = JsonConvert.DeserializeObject <RPMTopic>(result);

                MyConsole.Data($"RPM data = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");

                var RPM = client.GetAllEntriesFromHash("RPM");
                // Neu chua co trong redis thi vao db tim roi set vao redis
                if (RPM.Count == 0)
                {
                    MyConsole.Warning("Chua co trong redis vao db tim cai latest");

                    var rawData = rawDatasCollection.AsQueryable().Where(x => x.machineID == rpmTopic.i).OrderByDescending(x => x.createddatetime).FirstOrDefault();
                    // Neu trong db cua co thi gan sequen bang 1 va current vao redis
                    if (rawData != null)
                    {
                        MyConsole.Warning("Tim duoc cai latest gan vao redis");

                        SetRPMRedis(client, rawData.sequence, rawData.createddatetime);
                    }
                    else
                    {
                        MyConsole.Warning("Khong duoc cai latest them moi vao sequence 1 va currentdate");

                        var currentTime = DateTime.Now.ToLocalTime();
                        int sequence    = 1;
                        await CreateRawDataAsync(rawDatasCollection, new RawData
                        {
                            machineID       = rpmTopic.i,
                            RPM             = rpmTopic.r,
                            duration        = rpmTopic.d,
                            sequence        = sequence,
                            createddatetime = currentTime
                        });

                        SetRPMRedis(client, sequence, currentTime);
                    }
                    MyConsole.Info($"RPM In Redis: {String.Join(",", client.GetAllEntriesFromHash("RPM").Values.ToList())}");
                }
                else
                {
                    var lastDatetime            = RPM.FirstOrDefault(x => x.Key == MQTT_SERVER.Constants.Constants.CREATED_DATE_TIME).Value.ToSafetyString();
                    var sequence                = RPM.FirstOrDefault(x => x.Key == MQTT_SERVER.Constants.Constants.SEQUENCE).Value.ToInt();
                    var datetime                = Convert.ToDateTime(lastDatetime);
                    var timedifferent           = TimeDifferent(datetime);
                    var sequencetempelseInRedis = sequence;
                    var sequencetempifInRedis   = sequence + 1;

                    if (timedifferent > 10)
                    {
                        MyConsole.Info("#### ### roi vao if ###");
                        MyConsole.Info("#### ### Sequence trong if ###: " + sequencetempifInRedis);
                        DateTime currentDate = DateTime.Now;
                        var      rawData     = await CreateRawDataAsync(rawDatasCollection, new RawData
                        {
                            machineID       = rpmTopic.i,
                            RPM             = rpmTopic.r,
                            duration        = rpmTopic.d,
                            sequence        = sequencetempifInRedis,
                            createddatetime = currentDate
                        });

                        SetRPMRedis(client, sequencetempifInRedis, currentDate);
                    }
                    else
                    {
                        DateTime currentDate = DateTime.Now.ToLocalTime();
                        MyConsole.Info($"#### ### roi vao if ### {currentDate}");
                        MyConsole.Info("#### ### Khuay luot moi ###");
                        MyConsole.Info("#### ### Sequence trong if ###: " + sequencetempelseInRedis);
                        var rawData = await CreateRawDataAsync(rawDatasCollection, new RawData
                        {
                            machineID       = rpmTopic.i,
                            RPM             = rpmTopic.r,
                            duration        = rpmTopic.d,
                            sequence        = sequencetempelseInRedis,
                            createddatetime = currentDate
                        });;
                        SetRPMRedis(client, sequencetempelseInRedis, currentDate);
                    }
                }
            }
        }