终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

68 regels
2.3 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace BPASmartClient.DRCoffee
  8. {
  9. public class DrCoffee
  10. {
  11. public const int LENGTH = 26;
  12. public const byte HEADER = 0x7E;
  13. public const byte END = 0x7E;
  14. public static DrCoffeePackage UnPack(byte[] datagram)
  15. {
  16. if (LENGTH != datagram.Length)
  17. return default(DrCoffeePackage);
  18. // 分配结构体大小的内存空间
  19. IntPtr structPtr = Marshal.AllocHGlobal(LENGTH);
  20. // 将byte数组拷到分配好的内存空间
  21. Marshal.Copy(datagram, 0, structPtr, LENGTH);
  22. // 将内存空间转换为目标结构体
  23. DrCoffeePackage obj = (DrCoffeePackage)Marshal.PtrToStructure(structPtr, typeof(DrCoffeePackage));
  24. // 释放内存空间
  25. Marshal.FreeHGlobal(structPtr);
  26. // 返回结构体
  27. return obj;
  28. }
  29. public static byte[] Packe(DrCoffeePackage package)
  30. {
  31. package.Header = HEADER;
  32. package.Length = LENGTH;
  33. package.End = END;
  34. package.CalcCode = PackageCalcValideCode(package);
  35. // 创建byte数组
  36. byte[] bytes = new byte[LENGTH];
  37. // 分配结构体大小的内存空间
  38. IntPtr structPtr = Marshal.AllocHGlobal(LENGTH);
  39. // 将结构体拷到分配好的内存空间
  40. Marshal.StructureToPtr(package, structPtr, false);
  41. //从 内存空间拷到byte数组
  42. Marshal.Copy(structPtr, bytes, 0, LENGTH);
  43. // 释放内存空间
  44. Marshal.FreeHGlobal(structPtr);
  45. // 返回byte数组
  46. return bytes;
  47. }
  48. public static byte PackageCalcValideCode(DrCoffeePackage package)
  49. {
  50. var sum = (long)package.Length
  51. + (long)package.Warning
  52. + (long)package.Fault
  53. + (long)package.Status
  54. + (long)package.CommCmd
  55. + (long)package.ApplicationStatus
  56. + (long)package.DrinksCode
  57. + (long)package.ApplicationCode
  58. + (long)package.Retain;
  59. return (byte)(sum & 0xff);
  60. }
  61. }
  62. }