FileTransferReader.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Threading;
  5. using System.Threading.Tasks;
  6. using Vinno.FIS.TRTCClient.Common.Log;
  7. namespace Vinno.FIS.TRTCClient.Common.FileTransfer
  8. {
  9. public class FileTransferReader : IDisposable
  10. {
  11. private readonly CancellationTokenSource _cts;
  12. private readonly Task _task;
  13. private bool _disposed;
  14. private byte[] _currentByteArray;
  15. private bool _hasReserveFolder => !string.IsNullOrEmpty(ReserveStorageFolderPath);
  16. /// <summary>
  17. /// Name Of File Reader and Folder Name
  18. /// </summary>
  19. public string Name { get; private set; }
  20. /// <summary>
  21. /// Parent Folder Name
  22. /// </summary>
  23. public string ParentFolderName { get; private set; }
  24. /// <summary>
  25. /// Parent Folder Path
  26. /// </summary>
  27. public string ParentFolderPath { get; private set; }
  28. /// <summary>
  29. /// Folder Storage Path
  30. /// </summary>
  31. public string StorageFolderPath { get; private set; }
  32. /// <summary>
  33. /// Basic Folder under FIS Folder
  34. /// </summary>
  35. public string ImageTransferBaseFolderPath { get; private set; }
  36. /// <summary>
  37. /// 预留文件夹路径
  38. /// </summary>
  39. public string ReserveStorageFolderPath { get; private set; }
  40. /// <summary>
  41. /// Raised when log msg throw
  42. /// </summary>
  43. public event EventHandler<LogEventArgs> LogMsgThrow;
  44. public event EventHandler<byte[]> DataReceived;
  45. public FileTransferReader(string name, string parentFolderName, string fisFolderPath, string reserveName)
  46. {
  47. Name = name;
  48. ParentFolderName = parentFolderName;
  49. ImageTransferBaseFolderPath = Path.Combine(fisFolderPath, FISTRTCConsts.DataTransferFolder);
  50. ParentFolderPath = Path.Combine(ImageTransferBaseFolderPath, ParentFolderName);
  51. StorageFolderPath = Path.Combine(ParentFolderPath, Name);
  52. if (!string.IsNullOrEmpty(reserveName))
  53. {
  54. ReserveStorageFolderPath = Path.Combine(ParentFolderPath, reserveName);
  55. }
  56. CreateDirectory(ImageTransferBaseFolderPath);
  57. CreateDirectory(ParentFolderPath);
  58. CreateDirectory(StorageFolderPath);
  59. if (_hasReserveFolder)
  60. {
  61. CreateDirectory(ReserveStorageFolderPath);
  62. var existFiles = Directory.GetFiles(ReserveStorageFolderPath);
  63. if (existFiles.Length > 0)
  64. {
  65. foreach (var existFile in existFiles.OrderBy(x => x))
  66. {
  67. var fileName = Path.GetFileName(existFile);
  68. var copyFilePath = Path.Combine(StorageFolderPath, fileName);
  69. File.Copy(existFile, copyFilePath, true);
  70. }
  71. }
  72. }
  73. _cts = new CancellationTokenSource();
  74. _currentByteArray = new byte[0];
  75. }
  76. private void CreateDirectory(string directory)
  77. {
  78. if (!Directory.Exists(directory))
  79. {
  80. Directory.CreateDirectory(directory);
  81. }
  82. }
  83. public void StartContinuousRead()
  84. {
  85. Task.Run(() =>
  86. {
  87. while (!_cts.IsCancellationRequested && !_disposed)
  88. {
  89. try
  90. {
  91. if (!Directory.Exists(StorageFolderPath))
  92. {
  93. break;
  94. }
  95. var files = Directory.GetFiles(StorageFolderPath, "*.fis");
  96. var oldestFile = files.OrderBy(x => x).FirstOrDefault();
  97. if (oldestFile == null)
  98. {
  99. Thread.Sleep(100);
  100. continue;
  101. }
  102. try
  103. {
  104. using (FileStream fileStream = new FileStream(oldestFile, FileMode.Open, FileAccess.Read))
  105. {
  106. using (BinaryReader reader = new BinaryReader(fileStream))
  107. {
  108. var dataLength = reader.ReadInt32();
  109. if (_currentByteArray == null)
  110. {
  111. _currentByteArray = new byte[dataLength];
  112. }
  113. if (_currentByteArray.Length != dataLength)
  114. {
  115. Array.Resize(ref _currentByteArray, dataLength);
  116. }
  117. _currentByteArray = reader.ReadBytes(dataLength);
  118. }
  119. }
  120. }
  121. catch (Exception ex)
  122. {
  123. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Error, $"FileTransferReader: {Name} ReadContinuous Error:{ex}"));
  124. }
  125. finally
  126. {
  127. DeleteFile(oldestFile);
  128. }
  129. DataReceived?.Invoke(this, _currentByteArray);
  130. }
  131. catch (Exception ex)
  132. {
  133. if (!((ex is FileNotFoundException) || (ex is DirectoryNotFoundException)))
  134. {
  135. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Error, $"FileTransferReader: {Name} ReadContinuous Error:{ex}"));
  136. }
  137. }
  138. }
  139. }, _cts.Token);
  140. }
  141. /// <summary>
  142. /// Delete file
  143. /// </summary>
  144. /// <param name="filePath">The file to be deleted.</param>
  145. private void DeleteFile(string filePath)
  146. {
  147. if (string.IsNullOrEmpty(filePath))
  148. {
  149. return;
  150. }
  151. try
  152. {
  153. if (File.Exists(filePath))
  154. {
  155. File.SetAttributes(filePath, FileAttributes.Normal);
  156. File.Delete(filePath);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Error, $"Exception when delete file {filePath},detail:{ex}"));
  162. }
  163. }
  164. /// <summary>
  165. /// 用于写一个,读一个
  166. /// </summary>
  167. /// <param name="dataLength"></param>
  168. /// <returns></returns>
  169. public byte[] ReadFromFile(int dataLength)
  170. {
  171. try
  172. {
  173. if (_disposed || !Directory.Exists(StorageFolderPath))
  174. {
  175. return null;
  176. }
  177. var files = Directory.GetFiles(StorageFolderPath, "*.fis");
  178. var oldestFile = files.OrderBy(x => x).FirstOrDefault();
  179. if (oldestFile == null)
  180. {
  181. return null;
  182. }
  183. try
  184. {
  185. using (FileStream fileStream = new FileStream(oldestFile, FileMode.Open, FileAccess.Read))
  186. {
  187. using (BinaryReader reader = new BinaryReader(fileStream))
  188. {
  189. if (_currentByteArray.Length != dataLength)
  190. {
  191. Array.Resize(ref _currentByteArray, dataLength);
  192. }
  193. _currentByteArray = reader.ReadBytes(dataLength);
  194. }
  195. }
  196. }
  197. catch (Exception ex)
  198. {
  199. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Error, $"FileTransferReader: {Name} ReadFromFile Error:{ex}"));
  200. }
  201. finally
  202. {
  203. DeleteFile(oldestFile);
  204. }
  205. return _currentByteArray;
  206. }
  207. catch (Exception ex)
  208. {
  209. if (!((ex is FileNotFoundException) || (ex is DirectoryNotFoundException)))
  210. {
  211. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Error, $"FileTransferReader: {Name} ReadFromFile Error:{ex}"));
  212. }
  213. return null;
  214. }
  215. }
  216. public void Dispose()
  217. {
  218. try
  219. {
  220. if (_disposed)
  221. {
  222. return;
  223. }
  224. _cts.Cancel();
  225. try
  226. {
  227. _task?.Wait(200);//因Task在Wait过程中Cancel有几率会出错
  228. }
  229. catch
  230. {
  231. }
  232. _disposed = true;
  233. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Info, $"FileTransferReader:{Name} Dispose Success"));
  234. }
  235. catch (Exception ex)
  236. {
  237. LogMsgThrow?.Invoke(this, new LogEventArgs(DeviceLogCategory.Error, $"FileTransferReader:{Name} Dispose Error:{ex}"));
  238. }
  239. }
  240. }
  241. }