using CommunityToolkit.Mvvm.ComponentModel; using ivf_tl_Entity.Entity; using ivf_tl_Entity.Entity.balance; using ivf_tl_Entity.Entity.DownLoad; using ivf_tl_Entity.Enums; using ivf_tl_Manage.Converts; using ivf_tl_Manage.Win; using ivf_tl_Service; using ivf_tl_Service.HttpProvider; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Policy; using System.Text; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Media.TextFormatting; using System.Windows.Threading; using static System.Windows.Forms.AxHost; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Tab; namespace ivf_tl_Manage.ViewModels { public partial class MainWindowViewModel : BaseViewModel { [ObservableProperty] private BaseViewModel currentViewModle; [ObservableProperty] private bool dishRecordChecked = false; [ObservableProperty] private bool alarmHistoryChecked = false; [ObservableProperty] private bool houseChartChecked = false; //[ObservableProperty] //private int downLoadFileCount = 0; private int downLoadFileCount; public int DownLoadFileCount { get => Interlocked.CompareExchange(ref downLoadFileCount, 0, 0); set { Interlocked.Exchange(ref downLoadFileCount, value); OnPropertyChanged(nameof(DownLoadFileCount)); //SetProperty(ref downLoadFileCount, value); } } [ObservableProperty] private ObservableCollection environmentTemperatureList = new ObservableCollection(); public bool IsClick = true; public string CurrentTlSN = null; public int ClearLogDay = 5; public Queue DownLoadQueue = new Queue(); [ObservableProperty] private ObservableCollection downLoadFileList = new ObservableCollection(); [ObservableProperty] private ObservableConcurrentQueue newdownLoadFileList = new ObservableConcurrentQueue(); [ObservableProperty] private List listdownLoadFileList = new List(); /// /// 设备管理界面ViewModel /// public DevManageViewModel devManageViewModel = null; /// /// 患者管理界面ViewModel /// public PatientManageViewModel patientManageViewModel = null; [ObservableProperty] private bool maskVisibility = false; [ObservableProperty] private UserInfo userInfo = null; public MqttHelper MqttHelper { get; set; } private string MqttIp = "211.149.139.131"; private int MqttPort = 61883; private string MqttUserName = "aivfo"; private string MqttPassword = "aivfo"; private string MqttClientId = "TL/House/pc"; private string MqttTopicName = "TL/House/pc"; int DownLoadNum = 3; public MainWindowViewModel(UserInfo userInfo, int downNum) { base.ViewModelName = nameof(MainWindowViewModel); devManageViewModel = new DevManageViewModel(); patientManageViewModel = new PatientManageViewModel(); MqttIp = AppData.Instance.MqttIp; MqttPort = AppData.Instance.MqttPort; MqttClientId = $"TL/Surafce/PC/{DateTime.Now}"; MqttHelper = new MqttHelper(MqttIp, MqttPort, MqttUserName, MqttPassword, MqttClientId, MqttTopicName); MqttHelper.ErrorLogEvent += AppData.Instance.LogService.TLLog; MqttHelper.ExceptionLogEvent += AppData.Instance.LogService.ExceptionLog; MqttHelper.MessEvent += MqttHelper_MessEvent; UserInfo = userInfo; DownLoadNum = downNum; _semaphore = new SemaphoreSlim(DownLoadNum ); DownLoadThread(); } public MainWindowViewModel() { base.ViewModelName = nameof(MainWindowViewModel); } public void Start() { devManageViewModel.UpData(); MqttHelper.StartMqtt(); StartThread(); } public void RefWindow() { devManageViewModel.UpData(); } private void MqttHelper_MessEvent(string obj) { try { if (devManageViewModel.TlInfoList == null || !devManageViewModel.TlInfoList.Any()) return; List mqttHouses = JsonConvert.DeserializeObject>(obj); if (mqttHouses == null || !mqttHouses.Any()) return; TLInfo currentTL = devManageViewModel.TlInfoList.FirstOrDefault(x => x.tlSn == mqttHouses.First().tlSn); if (currentTL == null) return; MqttHouse mqttHouseItem = null; foreach (var item in currentTL.houses) { mqttHouseItem = mqttHouses.FirstOrDefault(x => x.houseSn == item.houseSn); if (mqttHouseItem == null) continue; if (mqttHouseItem.houseSn == 11) { string ss = ""; } else { if (mqttHouseItem.cultureState == 0) { if (mqttHouseItem.houseState == (int)HouseStateEnum.AirSwapWorking) { item.HouseStateString1 = "气体"; item.HouseStateString2 = "交换空闲"; } else { //item.HouseStateString1 = "空闲监测"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0340"); item.HouseStateString2 = ""; } } else if (mqttHouseItem.cultureState == 1) { if (mqttHouseItem.houseState == (int)HouseStateEnum.AirSwapWorking) { //item.HouseStateString1 = "气体交换"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0341"); } else if (mqttHouseItem.houseState == (int)HouseStateEnum.AutoFocusWorking) { //item.HouseStateString1 = "自动对焦"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0342"); } else if (mqttHouseItem.houseState == (int)HouseStateEnum.CCDWorking) { //item.HouseStateString1 = "胚胎拍照"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0343"); } else { //item.HouseStateString1 = "温压监测"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0344"); } item.HouseStateString2 = ""; } else if (mqttHouseItem.cultureState == 2) { if (mqttHouseItem.houseState == (int)HouseStateEnum.AirSwapWorking) { //item.HouseStateString1 = "气体"; //item.HouseStateString2 = "交换平衡"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0536"); item.HouseStateString2 = ""; } else { //item.HouseStateString1 = "温压"; //item.HouseStateString2 = "监测平衡"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0536"); item.HouseStateString2 = ""; } } else { //item.HouseStateString1 = "未知"; item.HouseStateString1 = KeyToStringConvert.GetLanguageStringByKey("0246"); item.HouseStateString2 = $"{mqttHouseItem.cultureState}"; } } item.cultureState = mqttHouseItem.cultureState; item.houseState = mqttHouseItem.houseState; item.pressure = mqttHouseItem.pressure; item.temperature = mqttHouseItem.temperature; item.houseDoorState = mqttHouseItem.houseDoorState; item.pressureAlarm = mqttHouseItem.pressureAlarm; item.temperatureAlarm = mqttHouseItem.temperatureAlarm; } } catch (Exception ex) { ExLog(ex, "MqttHelper_MessEvent"); } } /// /// 开启同步线程 /// private void StartThread() { Task.Factory.StartNew(async () => { await Task.Delay(5000); bool isAdd = false; while (true) { try { //ThreadPool.GetAvailableThreads(out int worker, out int io); //Debug.WriteLine($"可用工作线程:{worker}, IO线程:{io}"); RefWindow(); } catch (Exception ex) { ExLog(ex, "UpDataTLInfo"); } finally { await Task.Delay(5000); } } }, TaskCreationOptions.LongRunning); Task.Factory.StartNew(async () => { List currentList = new List(); EnvironmentTemperatureEntity currentT = null; while (true) { try { currentList = AppData.Instance.HttpServiceCall.GetEnvironmentTemperatureApi(); //Debug.WriteLine("--------------------------------------------------"); foreach (var item in currentList) { currentT = EnvironmentTemperatureList.FirstOrDefault(x => x.tlSn == item.tlSn); if (currentT == null) { AppData.Instance.MainWindow.Dispatcher.Invoke(() => { //Debug.WriteLine($"add {DateTime.Now.ToString("HH:mm:ss.fff")}:{item.collectName}:{item.temperature}"); EnvironmentTemperatureList.Add(item); }); } else { //Debug.WriteLine($"{currentT.collectName}:{currentT.temperature}"); currentT.temperature = item.temperature; currentT.collectName = item.collectName; //if (item.collectName != "9900212203") //{ // Debug.WriteLine($"{currentT.collectName}:{currentT.temperature}"); //} } } } catch (Exception ex) { ExLog(ex, "GetEnvironmentTemperatureThread"); } finally { await Task.Delay(60000); } } }, TaskCreationOptions.LongRunning); Task.Factory.StartNew(async () => { string newPath = ""; while (true) { try { newPath = $"{AppData.Instance.DefeatPan}:\\TLData\\ivf_tl_Manage_logs"; DeleteLogDir(newPath); newPath = $"{AppData.Instance.DefeatPan}:\\TLData\\ivf_tl_Manage_logs\\Log"; DeleteLogFile(newPath); newPath = $"{AppData.Instance.DefeatPan}:\\TLData\\ivf_tl_Manage_logs\\LogError"; DeleteLogFile(newPath); } catch (Exception ex) { ExLog(ex, "DeleteLog"); } finally { await Task.Delay(1000 * 60 * 60 * 12); } } }, TaskCreationOptions.LongRunning); } private void DeleteLogDir(string newPath) { var newDir = Directory.GetDirectories(newPath, "*", SearchOption.TopDirectoryOnly); string dirName = ""; DateTime dirTime = DateTime.Now; DateTime nowTime = dirTime; foreach (var item in newDir) { dirName = System.IO.Path.GetFileName(item); if (DateTime.TryParse(dirName, out dirTime)) { if (nowTime.Subtract(dirTime).Days >= ClearLogDay) { try { Directory.Delete(item, true); } catch (Exception) { continue; } } } } } private void DeleteLogFile(string newPath) { var newDir = Directory.GetFiles(newPath, "*.htm", SearchOption.TopDirectoryOnly); string fileName = ""; DateTime fileTime = DateTime.Now; DateTime nowTime = fileTime; foreach (var item in newDir) { fileName = System.IO.Path.GetFileNameWithoutExtension(item); if (fileName.Length == 8) { fileName = fileName.Insert(6, "-"); fileName = fileName.Insert(4, "-"); if (DateTime.TryParse(fileName, out fileTime)) { if (nowTime.Subtract(fileTime).Days >= ClearLogDay) { try { File.Delete(item); } catch (Exception) { continue; } } } } } } public void DownLoadStart(DownLoadEntity downLoadEntity) { try { lock (DownLoadQueue) { downLoadEntity.state = (int)DownLoadEnum.Await; //DownLoadQueue.Enqueue(downLoadEntity); _downloadQueue.Add(downLoadEntity); if (!DownLoadFileList.Contains(downLoadEntity)) { DownLoadFileList.Add(downLoadEntity); } DownLoadFileCountAdd(); //DownLoadFileCount = DownLoadFileList.Where(x => x.state == (int)DownLoadEnum.Await).Count(); //DownLoadThread(); //if (DownLoadFileCount <= 1) DownLoadThread(); } return; } catch (Exception ex) { ExLog(ex, "DownLoadStart"); } } private void DownLoadThread() { Debug.WriteLine($"创建下载线程开始{DownLoadNum}===================================================="); for (int i = 0; i < DownLoadNum; i++) { Task.Factory.StartNew( () => DownloadWorkerAsync(), _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default ); } Debug.WriteLine("创建下载线程结束===================================================="); return; Debug.WriteLine("开启下载线程"); Task.Run(async () => { DownLoadEntity downLoadEntity = null; while (true) { try { lock (DownLoadQueue) { if (!DownLoadQueue.Any()) { Debug.WriteLine("结束下载线程"); return; } downLoadEntity = DownLoadQueue.First(); } if (downLoadEntity == null) return; int downResult = 0; downLoadEntity.state = (int)DownLoadEnum.DownLoad; if (!string.IsNullOrEmpty(downLoadEntity.Body)) { downResult = await AppData.Instance.HttpServiceCall.DownLoadFileAsync(downLoadEntity.DownLoadUrl, downLoadEntity.NewFileFullName, downLoadEntity.Body).ConfigureAwait(false); } else { downResult = await AppData.Instance.HttpServiceCall.DownLoadFileAsync(downLoadEntity.DownLoadUrl, downLoadEntity.NewFileFullName).ConfigureAwait(false); } if (downResult == 1) { AppData.Instance.MainWindow.Dispatcher.Invoke(() => { downLoadEntity.state = (int)DownLoadEnum.Success; //ToastMessageShow($"{downLoadEntity.FileName} 下载完成"); ToastMessageShow($"{downLoadEntity.FileName} {KeyToStringConvert.GetLanguageStringByKey("0540")}"); }); } else { AppData.Instance.MainWindow.Dispatcher.Invoke(() => { downLoadEntity.state = (int)DownLoadEnum.Failed; //ToastMessageShow($"{downLoadEntity.FileName} 下载失败"); ToastMessageShow($"{downLoadEntity.FileName} {KeyToStringConvert.GetLanguageStringByKey("0541")}"); }); } lock (DownLoadQueue) { DownLoadQueue.Dequeue(); DownLoadFileCount = DownLoadQueue.Count; } } catch (Exception ex) { ExLog(ex, "文件下载"); } } }); } private void DownLoadFileCountAdd() { Interlocked.Increment(ref downLoadFileCount); Debug.WriteLine($"{DateTime.Now}Add当前下载数量{DownLoadFileCount}"); System.Windows.Application.Current.Dispatcher.Invoke(() => { OnPropertyChanged(nameof(DownLoadFileCount)); }); } private void DownLoadFileCountSub() { Interlocked.Decrement(ref downLoadFileCount); Debug.WriteLine($"{DateTime.Now}Sub当前下载数量{DownLoadFileCount}"); System.Windows.Application.Current.Dispatcher.Invoke(() => { OnPropertyChanged(nameof(DownLoadFileCount)); }); } public BlockingCollection _downloadQueue = new BlockingCollection(); private SemaphoreSlim _semaphore; // N为最大并发数 private CancellationTokenSource _cts = new CancellationTokenSource(); private async Task DownloadWorkerAsync() { foreach (var item in _downloadQueue.GetConsumingEnumerable(_cts.Token)) { Debug.WriteLine($"{DateTime.Now}排队等待数量{_downloadQueue.Count}、{item.FileName}===================================================="); await _semaphore.WaitAsync(_cts.Token); try { await DownloadFileAsync(item); } finally { _semaphore.Release(); } Debug.WriteLine($"{DateTime.Now}排队等待数量{_downloadQueue.Count}、{item.FileName}、结束===================================================="); } } private async Task DownloadFileAsync(DownLoadEntity downLoadEntity) { //await Task.Delay(3000); //DownloadEndEvent(downLoadEntity, 1); //return; if (downLoadEntity == null) return; int downResult = 0; downLoadEntity.state = (int)DownLoadEnum.DownLoad; if (!string.IsNullOrEmpty(downLoadEntity.Body)) { downResult = await AppData.Instance.HttpServiceCall.DownLoadFileAsync(downLoadEntity.DownLoadUrl, downLoadEntity.NewFileFullName, downLoadEntity.Body).ConfigureAwait(false); } else { downResult = await AppData.Instance.HttpServiceCall.DownLoadFileAsync(downLoadEntity.DownLoadUrl, downLoadEntity.NewFileFullName).ConfigureAwait(false); } DownloadEndEvent(downLoadEntity, downResult); } private void DownloadEndEvent(DownLoadEntity downLoadEntity, int result) { Task.Run(() => { if (result == 1) { AppData.Instance.MainWindow.Dispatcher.Invoke(() => { DownLoadFileCountSub(); downLoadEntity.state = (int)DownLoadEnum.Success; //ToastMessageShow($"{downLoadEntity.FileName} 下载完成"); ToastMessageShow($"{downLoadEntity.FileName} {KeyToStringConvert.GetLanguageStringByKey("0540")}"); }); } else { AppData.Instance.MainWindow.Dispatcher.Invoke(() => { DownLoadFileCountSub(); downLoadEntity.state = (int)DownLoadEnum.Failed; //ToastMessageShow($"{downLoadEntity.FileName} 下载失败"); ToastMessageShow($"{downLoadEntity.FileName} {KeyToStringConvert.GetLanguageStringByKey("0541")}"); }); } }); } } }