DeviceHelper.cs 3.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using static IoTIntegrationPlatform.Model.Enum.EnumDevice;
  7. namespace IoTIntegrationPlatform.Common
  8. {
  9. /// <summary>
  10. /// 设备公共类
  11. /// </summary>
  12. public static class DeviceHelper
  13. {
  14. /// <summary>
  15. /// 计算时间差及返回当前状态
  16. /// </summary>
  17. /// <param name="oldState"></param>
  18. /// <param name="currentTime"></param>
  19. /// <param name="value"></param>
  20. /// <param name="changeState"></param>
  21. /// <returns></returns>
  22. public static bool CalcTimeDifference(EnumDeviceStatus oldState, DateTime currentTime, DateTime value, ref EnumDeviceStatus changeState)
  23. {
  24. bool isTrue = false;
  25. try
  26. {
  27. if (currentTime != null && value != null)
  28. {
  29. double minutes = TimeHelper.DiffMinutes(value, currentTime);
  30. if (minutes >= 2 && oldState == EnumDeviceStatus.Open)
  31. {
  32. isTrue = true;
  33. changeState = 0;//离线
  34. }
  35. else if (minutes < 3 && oldState == 0)
  36. {
  37. isTrue = true;
  38. changeState = EnumDeviceStatus.Open;//在线
  39. }
  40. }
  41. }
  42. catch (Exception ex)
  43. {
  44. Logging.Error(ex, ex.Message);
  45. }
  46. return isTrue;
  47. }
  48. /// <summary>
  49. /// 生成网关设备的mac地址
  50. /// </summary>
  51. /// <param name="serialNumber">设备序列号 32位 </param>
  52. /// <returns></returns>
  53. public static string GenerateDeviceMacAddress(string serialNumber)
  54. {
  55. string macAddress = string.Empty;
  56. try
  57. {
  58. // 制造商标识符
  59. string manufacturerId = "0123456789ABCDEF"; // 24位
  60. // 将字符串转换为字节数组
  61. byte[] manufacturerBytes = new byte[6];
  62. byte[] serialBytes = new byte[6];
  63. for (int i = 0; i < 6; i++)
  64. {
  65. manufacturerBytes[i] = Convert.ToByte(manufacturerId.Substring(i * 2, 2), 16);
  66. serialBytes[i] = Convert.ToByte(serialNumber.Substring(i * 2, 2), 16);
  67. }
  68. // 按位或(|)制造商标识符和序列号,得到完整的MAC地址
  69. byte[] macBytes = new byte[6];
  70. for (int i = 0; i < 6; i++)
  71. {
  72. macBytes[i] = (byte)(manufacturerBytes[i] | serialBytes[i]);
  73. }
  74. // 将MAC地址转换为16进制字符串并打印出来
  75. StringBuilder sb = new StringBuilder();
  76. for (int i = 0; i < 6; i++)
  77. {
  78. sb.Append(macBytes[i].ToString("X2")); // 使用"X2"格式将字节转换为两位的16进制数字,不足两位的会在前面补0
  79. if (i < 5) sb.Append(":"); // 每两个字节之间添加一个短横线"-"
  80. }
  81. macAddress = sb.ToString();
  82. }
  83. catch (Exception ex)
  84. {
  85. Logging.Error(ex, ex.Message);
  86. }
  87. return macAddress;
  88. }
  89. }
  90. }