Example #1
0
        private async Task SettingReplyPublish(IMqttClient mqttClient, Setting settings)
        {
            try
            {
                var data = new SettingReplyPublish()
                {
                    id     = settings.machineID,
                    maxRPM = settings.standardRPM,
                    minRPM = settings.minRPM,
                    timer  = settings.timer,
                    tp     = "set"
                };
                var payload = JsonConvert.SerializeObject(data);
                var message = new MqttApplicationMessageBuilder()
                              .WithTopic(SetingReplyTopic)
                              .WithPayload(payload)
                              .Build();
                await mqttClient.PublishAsync(message);

                MyConsole.Info($"### SetingReplyTopic SENT MESSAGE {Encoding.UTF8.GetString(message.Payload)} TO SERVER ");
            }
            catch (Exception ex)
            {
                MyConsole.Error($"### SettingTopic SENT MESSAGE TO SERVER ERROR ###" + ex.Message);
            }
        }
Example #2
0
 private static void RecevicedTopic(MqttApplicationMessageReceivedEventArgs e)
 {
     MyConsole.Info("### RECEIVED APPLICATION MESSAGE ###");
     MyConsole.Info($"+ Topic = {e.ApplicationMessage.Topic}");
     MyConsole.Info($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
     MyConsole.Info($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
     MyConsole.Info($"+ Retain = {e.ApplicationMessage.Retain}");
     Console.WriteLine();
 }
Example #3
0
 /// <summary>
 /// Create a new path relative to this file. If the <paramref name="output"/> file path is
 /// absolute, uses that alone. The extension of the original file is appended to the new file.
 /// </summary>
 /// <param name="file"></param>
 /// <param name="output"></param>
 /// <returns></returns>
 public static string CreateSavePath(this FileInfo file, string output = default)
 {
     MyConsole.Info($"Creating new save path: {file}->{output}");
     if (output == default)
     {
         MyConsole.Debug($"--output not supplied: calculating from original file name ({file}).");
         output = $"{Path.GetFileNameWithoutExtension(file.Name)}_copy";
     }
     MyConsole.Debug($"Given output: {output}");
     return(Path.Combine(
                Path.GetDirectoryName(file.FullName),
                $"{output}{Path.GetExtension(file.Name)}"));
 }
Example #4
0
        private static async Task <RawData> CreateRawDataAsync(IMongoCollection <RawData> mongoCollection, RawData rawDatas)
        {
            try
            {
                await mongoCollection.InsertOneAsync(rawDatas);

                MyConsole.Info("#### ### Create Raw Data Async Successfully!");
                return(rawDatas);
            }
            catch (Exception ex)
            {
                MyConsole.Error("#### ###Create Raw Data failed" + ex.Message);

                throw;
            }
        }
Example #5
0
        /// <summary>
        ///     Logs the message from the MQTT connection validation context.
        /// </summary>
        /// <param name="context">The MQTT connection validation context.</param>
        /// <param name="showPassword">A <see cref="bool"/> value indicating whether the password is written to the log or not.</param>
        private static void LogMessage(MqttConnectionValidatorContext context, bool showPassword)
        {
            if (context == null)
            {
                return;
            }

            if (showPassword)
            {
                MyConsole.Info(
                    $"New connection: ClientId = {context.ClientId}, Endpoint = {context.Endpoint},"
                    + $" Username = {context.Username}, Password = {context.Password},"
                    + $" CleanSession = {context.CleanSession}");
            }
            else
            {
                MyConsole.Info(
                    $"New connection: ClientId = {context.ClientId}, Endpoint = {context.Endpoint},"
                    + $" Username = {context.Username}, CleanSession = {context.CleanSession}");
            }
        }
Example #6
0
        /// <summary>
        /// Resize the image to the specified width and height.
        /// <para>
        /// Source: https://stackoverflow.com/a/24199315/6789816
        /// </para>
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="width">The width to resize to.</param>
        /// <param name="height">The height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static Bitmap Resize(this Image image, int width, int height)
        {
            MyConsole.Info($"Resizing image: {width}x{height}");
            MyConsole.Debug("Creating bitmap destination image.");
            Rectangle destRect  = new Rectangle(0, 0, width, height);
            Bitmap    destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            MyConsole.Debug("Get graphics from image.");
            using (Graphics graphics = Graphics.FromImage(destImage))
            {
                MyConsole.Debug(@"Setting up graphics modes:");
                graphics.CompositingMode = CompositingMode.SourceCopy;

                MyConsole.Debug("  - CompositingQuality: HighQuality");
                graphics.CompositingQuality = CompositingQuality.HighQuality;

                MyConsole.Debug("  - InterpolationMode: HighQualityBicubic");
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

                MyConsole.Debug("  - SmoothingMode: HighQuality");
                graphics.SmoothingMode = SmoothingMode.HighQuality;

                MyConsole.Debug("  - PixelOffsetMode: HighQuality");
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                MyConsole.Debug("  - WrapMode: TileFlipXY");
                using ImageAttributes wrapMode = new ImageAttributes();
                wrapMode.SetWrapMode(WrapMode.TileFlipXY);

                MyConsole.Debug("Drawing image...");
                graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                MyConsole.Debug("Image drawn.");
            }

            return(destImage);
        }
Example #7
0
        /// <summary>
        /// Wrapper for saving a <see cref="Bitmap"/> as a JPEG file.
        /// <para>
        /// Source: https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-set-jpeg-compression-level
        /// </para>
        /// </summary>
        /// <param name="bitmap"></param>
        /// <param name="output"></param>
        /// <param name="quality"></param>
        public static void SaveJPEG(this Bitmap bitmap, string output, long quality)
        {
            MyConsole.Info($"Saving image as JPEG with {quality} compression quality.");

            MyConsole.Debug("Use ImageFormat.Jpeg encoder.");
            ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);

            // Create an Encoder object based on the GUID  for the Quality parameter category.
            MyConsole.Debug("Create a quality encoder.");
            Encoder myEncoder = Encoder.Quality;

            // Create an EncoderParameters object.
            // An EncoderParameters object has an array of EncoderParameter objects.
            // In this case, there is only one EncoderParameter object in the array.
            MyConsole.Debug("Declare 1 encoder parameter:");
            EncoderParameters myEncoderParameters = new EncoderParameters(1);
            EncoderParameter  myEncoderParameter  = new EncoderParameter(myEncoder, quality);

            MyConsole.Debug("  - Adding quality encoder.");
            myEncoderParameters.Param[0] = myEncoderParameter;
            MyConsole.Debug($"Saving bitmap to {output} with encoders.");
            bitmap.Save(output, jpgEncoder, myEncoderParameters);
        }
Example #8
0
        private async Task ConnectMqttClientAsync()
        {
            MyConsole.Info($"Signalr hub: {_connection.ConnectionId}");
            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 =>
            {
                if (e.ApplicationMessage.Topic == MyTopic)
                {
                    await RecevicedMyTopic(e);
                    // emit ve client
                    await _connection.InvokeAsync("Welcom", "1");
                }
            });
            // Connected event handler
            mqttClient.UseConnectedHandler(async e =>
            {
                Console.WriteLine("### CONNECTED WITH SERVER ###");

                // Subscribe to a topic
                await mqttClient.SubscribeAsync(new TopicFilterBuilder().WithTopic(MyTopic).Build());

                Console.WriteLine("### CONNECTED ###");
            });
            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);
            }
        }
Example #9
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);
            }
        }
Example #10
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);
                    }
                }
            }
        }
Example #11
0
        /// <summary>
        /// Execute the image resize.
        /// </summary>
        /// <param name="file">The file to resize.</param>
        /// <param name="output">Where the new file will be written to</param>
        /// <param name="width">
        /// If zero, calculated to keep current apsect ratio with new height.
        /// </param>
        /// <param name="height">
        /// If zero, calculated to keep current apsect ratio with new width.
        /// </param>
        /// <param name="overwrite">
        /// When true, ignores the <paramref name="output"/> parameter and saves over the input
        /// <paramref name="file"/>.
        /// </param>
        public static void Exec(
            this FileInfo file,
            string output,
            int width,
            int height,
            long quality   = 100L,
            bool overwrite = false)
        {
            Console.WriteLine($"Resize image {file}");
            try
            {
                MyConsole.Debug($"inputs: {file} ({width}x{height}) @ {quality} compression.");
                if (file == default)
                {
                    MyConsole.Warning("You must supply an file with --file.");
                    throw new MissingFieldException();
                }
                if (width == default && height == default)
                {
                    MyConsole.Warning("You must supply one or more of the following options: --width --height");
                    throw new MissingFieldException();
                }

                MyConsole.Debug(@$ "Reading in image from " "{file.Name}" ".");
                using (Image image = Image.FromFile(file.FullName))
                {
                    MyConsole.Debug(@$ "Done reading image.");

                    MyConsole.Info($"Original dimensions: {image.Width}x{image.Height}");
                    MyConsole.Debug($"Checking for missing height or width.");
                    if (width == default)
                    {
                        MyConsole.Debug($"Width was {width}");
                        width = (int)(image.Width * (double)height / image.Height);
                        MyConsole.Debug($"Set width relative to new height: {width}");
                    }
                    if (height == default)
                    {
                        MyConsole.Debug($"Height was {height}");
                        height = (int)(image.Height * (double)width / image.Width);
                        MyConsole.Debug($"Set height relative to new width: {height}");
                    }

                    using Bitmap bitmap = image.Resize(width, height);

                    MyConsole.Info($"Saving image.");
                    if (overwrite)
                    {
                        MyConsole.Debug("Output to temporary file for overwrite later.");
                        output = file.FullName.Replace(file.Name, "temp_" + DateTime.Now.Ticks);
                    }
                    else
                    {
                        // Create a path for the output file.
                        output = file.CreateSavePath(output);
                    }

                    MyConsole.Debug($"Computed output: {output}");
                    MyConsole.Debug($"Saving bitmap");
                    bitmap.SaveJPEG(output, quality);
                }
                if (overwrite)
                {
                    MyConsole.Debug("Delete old file to overwrite with new.");
                    file.Delete();
                    MyConsole.Debug("Rename temporary file to previous file's name.");
                    File.Move(output, file.FullName);
                    output = file.FullName;
                }
                MyConsole.Success($@"Wrote image to: {output}");
            }
            catch (Exception e)
            {
                if (e is MissingFieldException || MyConsole.Verbosity < 1)
                {
                    MyConsole.Error("Failed to write image.");
                }
                else
                {
                    throw;
                }
            }
            Console.WriteLine("Done.");
        }
Example #12
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _connection = new HubConnectionBuilder()
                          .WithUrl(_appSettings.SignalrUrl)
                          .WithAutomaticReconnect()
                          .Build();
            MyConsole.Info(JsonConvert.SerializeObject(_appSettings));
            _connection.On <string, string, string>("Welcom", (scalingMachineID, message, unit) =>
            {
                if (scalingMachineID == _appSettings.MachineID.ToString())
                {
                    var receiveValue = JsonConvert.SerializeObject(new
                    {
                        scalingMachineID,
                        message,
                        unit
                    });

                    MyConsole.Info($"#### ### Data => {receiveValue}");
                }
            });

            _connection.Closed += async(error) =>
            {
                _logger.LogError(error.Message);
                await Task.Delay(new Random().Next(0, 5) * 1000);

                _logger.LogError($"Envent: Closed - The signalr client is restarting!");
                await _connection.StartAsync();
            };
            _connection.Reconnecting += async error =>
            {
                _logger.LogInformation($"State Hub {_connection.State} - State Global {state}");
                _logger.LogInformation($"Connection started reconnecting due to an error: {error.Message}");

                if (_connection.State == HubConnectionState.Reconnecting)
                {
                    state = HubConnectionState.Disconnected;
                }
                while (state == HubConnectionState.Disconnected)
                {
                    if (await ConnectWithRetryAsync(stoppingToken))
                    {
                        break;
                    }
                }
            };
            _connection.Reconnected += async(connectionId) =>
            {
                _logger.LogInformation($"Connection successfully reconnected. The ConnectionId is now: {connectionId}");
                state = HubConnectionState.Connected;
                while (true)
                {
                    if (await ConnectWithRetryAsync(stoppingToken))
                    {
                        break;
                    }
                }
            };

            while (state == HubConnectionState.Disconnected)
            {
                if (await ConnectWithRetryAsync(stoppingToken))
                {
                    break;
                }
            }

            _logger.LogInformation($"#### ### ClientId: {_connection.ConnectionId}");

            string         message;
            StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
            Thread         readThread     = new Thread(async() =>
                                                       await Read()
                                                       );

            // Create a new SerialPort object with default settings.
            _logger.LogInformation($"#### ### Serial Port is established");

            _serialPort = new SerialPort();

            // Allow the user to set the appropriate properties.
            string port = _appSettings.PortName;

            _serialPort.PortName = port;
            string scanPortName = ScanPortName();

            while (!port.Equals(scanPortName))
            {
                if (state == HubConnectionState.Connected)
                {
                    _logger.LogWarning($"#### ### The system is scanning {port} at {DateTime.Now.ToString()}");

                    scanPortName = ScanPortName();
                    await Task.Delay(1000, stoppingToken);
                }
            }
            _logger.LogInformation($"#### ### {port}");

            _serialPort.ReadTimeout  = 500;
            _serialPort.WriteTimeout = 500;
            _serialPort.Open();
            _logger.LogWarning($"#### ### #### ### Serial Port is already open at {DateTime.Now.ToString()}");

            _continue = true;
            readThread.Start();
            while (_continue)
            {
                // emit ve client
                message = Console.ReadLine();

                if (stringComparer.Equals("quit", message))
                {
                    _continue = false;
                }
                else
                {
                    //_serialPort.WriteLine(
                    //    String.Format("<{0}>: {1}", name, message));
                }
            }
            readThread.Join();
            _serialPort.Close();
        }