private static Command ResizeImageCommand() { Command command = new Command("ResizeImage", "Save an image at a different size") { MyConsole.GetVerbosityOption(), new Option("--file", "The destination of the input image file to resize.") { Argument = new Argument <FileInfo>("Location").ExistingOnly() }, new Option("--output", "The destination for the output file (original extension will be appended).") { Argument = new Argument <string>("Location") }, new Option("--width", "The new width dimension. Required if --height is omitted.") { Argument = new Argument <int>() }, new Option("--height", "The new height dimension. Required if --width is omitted.") { Argument = new Argument <int>() }, new Option("--overwrite", @"When true, overwrites the existing file rather than creating a copy. Cannot be used with --output.") { Argument = new Argument <bool>() { Arity = ArgumentArity.ZeroOrOne, }, }, new Option("--quality", @"The compression quality to apply to the new image. Defaults to 100.") { Argument = new Argument <long>() } }; command.Handler = CommandHandler.Create(( FileInfo file, string output, int width, int height, long quality, bool overwrite, int v) => { MyConsole.Verbosity = v; MyConsole.Debug($"Verbosity set to {v}"); if (overwrite && output != default) { MyConsole.Error("Cannot use --overwrite with --output"); return; } if (quality == default) { quality = 100L; } ResizeImage.Exec(file, output, width, height, quality, overwrite); }); return(command); }
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); } }
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; } }
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); } }
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); } }
/// <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."); }