net.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #include "net.h"
  2. static err_t bms_net_process(int fd, void *data, int len)
  3. {
  4. INT8U response[2] = {0xBB, 0xAA};
  5. if ((len == 2) && (((INT8U *)data)[0] == 0xAA) && (((INT8U *)data)[1] == 0xBB))
  6. {
  7. send(fd, (void *)response, sizeof(response), 0);
  8. }
  9. return 1;
  10. }
  11. void net_task(void)
  12. {
  13. INT8U buf[50];
  14. INT32S ret = 0;
  15. INT32S sockfd = -1, newfd = -1;
  16. INT32U len = 0;
  17. struct sockaddr_in svr_addr, clt_addr;
  18. svr_addr.sin_family = AF_INET;
  19. svr_addr.sin_port = htons(TCP_PORT);
  20. svr_addr.sin_addr.s_addr = htons(INADDR_ANY);
  21. while (1)
  22. {
  23. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  24. if (sockfd < 0)
  25. {
  26. continue;
  27. }
  28. ret = bind(sockfd, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
  29. if (ret < 0)
  30. {
  31. lwip_close(sockfd);
  32. sockfd = -1;
  33. continue;
  34. }
  35. ret = listen(sockfd, 1);
  36. if (ret < 0)
  37. {
  38. lwip_close(sockfd);
  39. continue;
  40. }
  41. len = sizeof(clt_addr);
  42. newfd = accept(sockfd, NULL, NULL);
  43. while (-1 != newfd)
  44. {
  45. ret = recv(newfd, buf, sizeof(buf) - 1, 0);
  46. if (ret <= 0)
  47. {
  48. lwip_close(newfd);
  49. newfd = -1;
  50. break;
  51. }
  52. bms_net_process(newfd, buf, ret);
  53. }
  54. lwip_close(sockfd);
  55. sockfd = -1;
  56. // OSTimeDly(10);
  57. }
  58. }