net.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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)
  14. {
  15. Iec10x_Scheduled(fd);
  16. Iec104_StateMachine();
  17. return 1;
  18. }
  19. void net_task(void)
  20. {
  21. INT8U buf[500];
  22. INT32S ret = 0;
  23. INT32S sockfd = -1, newfd = -1;
  24. INT32U len = 0;
  25. struct sockaddr_in svr_addr, clt_addr;
  26. INT16U Iec104_RecvLen;
  27. svr_addr.sin_family = AF_INET;
  28. svr_addr.sin_port = htons(TCP_PORT);
  29. svr_addr.sin_addr.s_addr = htons(INADDR_ANY);
  30. while (1)
  31. {
  32. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  33. if (sockfd < 0)
  34. {
  35. continue;
  36. }
  37. ret = bind(sockfd, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
  38. if (ret < 0)
  39. {
  40. lwip_close(sockfd);
  41. sockfd = -1;
  42. continue;
  43. }
  44. ret = listen(sockfd, 1);
  45. if (ret < 0)
  46. {
  47. lwip_close(sockfd);
  48. continue;
  49. }
  50. len = sizeof(clt_addr);
  51. newfd = accept(sockfd, NULL, NULL);
  52. while (-1 != newfd)
  53. {
  54. ret = recv(newfd, buf, sizeof(buf) - 1, 0);
  55. if (ret <= 0)
  56. {
  57. printf("the other side has been closed (%d).\n", sizeof(buf) - 1);
  58. lwip_close(newfd);
  59. newfd = -1;
  60. break;
  61. }
  62. bms_net_process(newfd);
  63. LOG("#####################received \n");
  64. DumpHEX(buf, read(newfd, buf, 1500));
  65. Iex104_Receive(buf, read(newfd, buf, 1500));
  66. }
  67. lwip_close(sockfd);
  68. sockfd = -1;
  69. // OSTimeDly(10);
  70. }
  71. }