main.txt_C.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package main
  2. /*
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #define LEN 1024
  7. // 设备->平台
  8. void T(const char *t, const char *b, char **r_b) {
  9. size_t len1 = strlen(t);
  10. size_t len2 = strlen(b);
  11. *r_b = (char *)malloc(len1 + len2 + 1);
  12. strcpy(*r_b, t);
  13. strcat(*r_b, b);
  14. }
  15. void R(const char *t, const char *b, char **r_t, char **r_b) {
  16. size_t len1 = strlen(t);
  17. size_t len2 = strlen(b);
  18. *r_t = (char *)malloc(len1 + 1);
  19. *r_b = (char *)malloc(len2 + 1);
  20. strcpy(*r_t, t);
  21. strcpy(*r_b, b);
  22. }
  23. */
  24. import "C"
  25. /////-------
  26. import (
  27. "encoding/hex"
  28. "fmt"
  29. "strings"
  30. "unsafe"
  31. )
  32. /*
  33. 设备->平台
  34. */
  35. func T(t string, b []byte) string {
  36. var r_b *C.char
  37. C.T(C.CString(t), C.CString(string(b)), &r_b)
  38. r_b_ := C.GoString(r_b)
  39. C.free(unsafe.Pointer(r_b)) // Free the memory allocated in C code
  40. return r_b_
  41. }
  42. /*
  43. 平台->设备
  44. */
  45. func R(sn string, b string) (string, []byte) {
  46. var r_t, r_b *C.char
  47. C.R(C.CString(sn), C.CString(b), &r_t, &r_b)
  48. r_t_ := C.GoString(r_t)
  49. r_b_ := C.GoString(r_b)
  50. C.free(unsafe.Pointer(r_t)) // Free the memory allocated in C code
  51. C.free(unsafe.Pointer(r_b)) // Free the memory allocated in C code
  52. return r_t_, []byte(r_b_)
  53. }
  54. // ---DATA---
  55. var Data_hex = false
  56. var Topic = "/topic/snxxx1"
  57. var T_string = "A456"
  58. var R_string = "495051"
  59. // ///-------
  60. func main() {
  61. // -------------------------------设备->平台
  62. T_byte := []byte(T_string)
  63. if Data_hex {
  64. T_byte, _ = hex.DecodeString(T_string)
  65. }
  66. // 设备->平台(发送)
  67. if len(T_string) != 0 {
  68. data_ := T(Topic, T_byte)
  69. fmt.Print("|-=&" + data_)
  70. } else {
  71. fmt.Print("|-=&" + "无参数")
  72. }
  73. // 平台->设备(接收):
  74. if len(R_string) != 0 {
  75. topic_, data_ := R("{$sn}", R_string)
  76. fmt.Print("|-=&" + topic_)
  77. if Data_hex {
  78. fmt.Print("|-=&" + strings.ToUpper(hex.EncodeToString(data_)))
  79. } else {
  80. fmt.Print("|-=&" + string(data_))
  81. }
  82. } else {
  83. fmt.Print("|-=&" + "无参数")
  84. fmt.Print("|-=&" + "无参数")
  85. }
  86. // 返回数据: 1、 设备发送数据解析到平台json 2、topic 3、平台处理后返回给设备数据
  87. }