bandwidth-slave-one.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright © 2008-2010 Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. #include <stdio.h>
  18. #include <unistd.h>
  19. #include <string.h>
  20. #include <stdlib.h>
  21. #include <errno.h>
  22. #include <modbus.h>
  23. #define SLAVE 0x11
  24. int main(void)
  25. {
  26. int socket;
  27. modbus_param_t mb_param;
  28. modbus_mapping_t mb_mapping;
  29. int rc;
  30. modbus_init_tcp(&mb_param, "127.0.0.1", 1502, SLAVE);
  31. rc = modbus_mapping_new(&mb_mapping, MAX_STATUS, 0, MAX_REGISTERS, 0);
  32. if (rc == -1) {
  33. fprintf(stderr, "Failed to allocate the mapping: %s\n",
  34. modbus_strerror(errno));
  35. return -1;
  36. }
  37. socket = modbus_slave_listen_tcp(&mb_param, 1);
  38. modbus_slave_accept_tcp(&mb_param, &socket);
  39. for(;;) {
  40. uint8_t query[MAX_MESSAGE_LENGTH];
  41. rc = modbus_slave_receive(&mb_param, -1, query);
  42. if (rc >= 0) {
  43. modbus_slave_manage(&mb_param, query, rc, &mb_mapping);
  44. } else {
  45. /* Connection closed by the client or server */
  46. break;
  47. }
  48. }
  49. printf("Quit the loop: %s\n", modbus_strerror(errno));
  50. close(socket);
  51. modbus_mapping_free(&mb_mapping);
  52. modbus_close(&mb_param);
  53. return 0;
  54. }