net.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. #include "net.h"
  2. #include "iec104.h"
  3. #include "iec10x.h"
  4. static err_t bms_test_process(int fd, void *data, int len)
  5. {
  6. INT8U response[2] = {0xBB, 0xAA};
  7. if ((len == 2) && (((INT8U *)data)[0] == 0xAA) && (((INT8U *)data)[1] == 0xBB))
  8. {
  9. send(fd, (void *)response, sizeof(response), 0);
  10. }
  11. return 1;
  12. }
  13. static err_t bms_net_process(int fd, void *data, int len)
  14. {
  15. Iec10x_Scheduled(fd);
  16. Iec104_StateMachine();
  17. // INT8U response[2] = {0xBB, 0xAA};
  18. // if ((len == 2) && (((INT8U *)data)[0] == 0xAA) && (((INT8U *)data)[1] == 0xBB))
  19. // {
  20. // send(fd, (void *)response, sizeof(response), 0);
  21. // }
  22. return 1;
  23. }
  24. void net_task(void)
  25. {
  26. int StaCount = 0;
  27. INT8U buf[50];
  28. INT32S ret = 0;
  29. INT32S sockfd = -1, newfd = -1;
  30. INT32U len = 0;
  31. struct sockaddr_in svr_addr, clt_addr;
  32. INT16U Iec104_RecvLen;
  33. int err;
  34. int staid = StaCount++;
  35. svr_addr.sin_family = AF_INET;
  36. svr_addr.sin_port = htons(TCP_PORT);
  37. svr_addr.sin_addr.s_addr = htons(INADDR_ANY);
  38. while (1)
  39. {
  40. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  41. if (sockfd < 0)
  42. {
  43. continue;
  44. }
  45. ret = bind(sockfd, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
  46. if (ret < 0)
  47. {
  48. lwip_close(sockfd);
  49. sockfd = -1;
  50. continue;
  51. }
  52. ret = listen(sockfd, 1);
  53. if (ret < 0)
  54. {
  55. lwip_close(sockfd);
  56. continue;
  57. }
  58. len = sizeof(clt_addr);
  59. newfd = accept(sockfd, NULL, NULL);
  60. while (-1 != newfd)
  61. {
  62. ret = recv(newfd, buf, sizeof(buf) - 1, 0);
  63. if (ret <= 0)
  64. {
  65. lwip_close(newfd);
  66. newfd = -1;
  67. break;
  68. }
  69. bms_net_process(newfd, buf, ret);
  70. Iec104_RecvLen = read(newfd, buf, 50);
  71. if (Iec104_RecvLen <= 0 || Iec104_RecvLen > 1500)
  72. {
  73. printf("the other side has been closed (%d).\n", Iec104_RecvLen);
  74. continue;
  75. }
  76. LOG("#####################received \n");
  77. DumpHEX(buf, Iec104_RecvLen);
  78. Iex104_Receive(buf, Iec104_RecvLen);
  79. }
  80. lwip_close(sockfd);
  81. sockfd = -1;
  82. // OSTimeDly(10);
  83. }
  84. }