| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588 |
- 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<EnvironmentTemperatureEntity> environmentTemperatureList = new ObservableCollection<EnvironmentTemperatureEntity>();
- public bool IsClick = true;
- public string CurrentTlSN = null;
- public int ClearLogDay = 5;
- public Queue<DownLoadEntity> DownLoadQueue = new Queue<DownLoadEntity>();
- [ObservableProperty]
- private ObservableCollection<DownLoadEntity> downLoadFileList = new ObservableCollection<DownLoadEntity>();
- [ObservableProperty]
- private ObservableConcurrentQueue<DownLoadEntity> newdownLoadFileList = new ObservableConcurrentQueue<DownLoadEntity>();
-
- [ObservableProperty]
- private List<DownLoadEntity> listdownLoadFileList = new List<DownLoadEntity>();
- /// <summary>
- /// 设备管理界面ViewModel
- /// </summary>
- public DevManageViewModel devManageViewModel = null;
- /// <summary>
- /// 患者管理界面ViewModel
- /// </summary>
- 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<MqttHouse> mqttHouses = JsonConvert.DeserializeObject<List<MqttHouse>>(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");
- }
- }
- /// <summary>
- /// 开启同步线程
- /// </summary>
- 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<EnvironmentTemperatureEntity> currentList = new List<EnvironmentTemperatureEntity>();
- 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<DownLoadEntity> _downloadQueue = new BlockingCollection<DownLoadEntity>();
- 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")}");
- });
- }
- });
- }
- }
- }
|