modbus.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629
  1. /*
  2. Copyright (C) 2001-2008 Stéphane Raimbault <stephane.raimbault@gmail.com>
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the
  13. Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  14. Boston, MA 02111-1307, USA.
  15. */
  16. /*
  17. The library is designed to send and receive data from a device that
  18. communicate via the Modbus protocol.
  19. The function names used are inspired by the Modicon Modbus Protocol
  20. Reference Guide which can be obtained from Schneider at
  21. www.schneiderautomation.com.
  22. Documentation:
  23. http://www.easysw.com/~mike/serial/serial.html
  24. */
  25. #include <fcntl.h>
  26. #include <stdio.h>
  27. #include <string.h>
  28. #include <stdlib.h>
  29. #include <termio.h>
  30. #include <sys/time.h>
  31. #include <unistd.h>
  32. #include <errno.h>
  33. /* TCP */
  34. #include <sys/types.h>
  35. #include <sys/socket.h>
  36. #include <sys/ioctl.h>
  37. #include <netinet/in.h>
  38. #include <netinet/ip.h>
  39. #include <netinet/tcp.h>
  40. #include <modbus/modbus.h>
  41. #define UNKNOWN_ERROR_MSG "Not defined in modbus specification"
  42. static const int SIZE_TAB_ERROR_MSG = 12;
  43. static const char *TAB_ERROR_MSG[] = {
  44. /* 0x00 */ UNKNOWN_ERROR_MSG,
  45. /* 0x01 */ "Illegal function code",
  46. /* 0x02 */ "Illegal data address",
  47. /* 0x03 */ "Illegal data value",
  48. /* 0x04 */ "Slave device or server failure",
  49. /* 0x05 */ "Acknowledge",
  50. /* 0x06 */ "Slave device or server busy",
  51. /* 0x07 */ "Negative acknowledge",
  52. /* 0x08 */ "Memory parity error",
  53. /* 0x09 */ UNKNOWN_ERROR_MSG,
  54. /* 0x0A */ "Gateway path unavailable",
  55. /* 0x0B */ "Target device failed to respond"
  56. };
  57. /* Table of CRC values for high-order byte */
  58. static unsigned char table_crc_hi[] = {
  59. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  60. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  61. 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  62. 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  63. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  64. 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
  65. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  66. 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  67. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  68. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  69. 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  70. 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  71. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  72. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  73. 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  74. 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
  75. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  76. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  77. 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  78. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  79. 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
  80. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
  81. 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
  82. 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
  83. 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
  84. 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
  85. };
  86. /* Table of CRC values for low-order byte */
  87. static unsigned char table_crc_lo[] = {
  88. 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
  89. 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
  90. 0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
  91. 0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
  92. 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
  93. 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
  94. 0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
  95. 0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
  96. 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
  97. 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
  98. 0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
  99. 0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
  100. 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
  101. 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
  102. 0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
  103. 0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
  104. 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
  105. 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
  106. 0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
  107. 0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
  108. 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
  109. 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
  110. 0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
  111. 0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
  112. 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
  113. 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
  114. };
  115. /* Local declaration */
  116. static int read_reg_response(modbus_param_t *mb_param,
  117. int *data_dest,
  118. unsigned char *query);
  119. /* Treats errors and flush or close connection if necessary */
  120. static void error_treat(int ret, const char *string, modbus_param_t *mb_param)
  121. {
  122. if (ret == -1)
  123. perror(string);
  124. printf("\n\nERROR %s\n\n", string);
  125. if (mb_param->type_com == RTU) {
  126. tcflush(mb_param->fd, TCIOFLUSH);
  127. } else {
  128. modbus_close(mb_param);
  129. modbus_connect(mb_param);
  130. }
  131. }
  132. /* Computes the size of the expected response */
  133. static unsigned int compute_response_size(modbus_param_t *mb_param,
  134. unsigned char *query)
  135. {
  136. int response_size_computed;
  137. int offset;
  138. offset = mb_param->header_length;
  139. switch (query[offset + 1]) {
  140. case FC_READ_COIL_STATUS:
  141. case FC_READ_INPUT_STATUS: {
  142. /* Header + nb values (code from force_multiple_coils) */
  143. int coil_count = (query[offset + 4] << 8) | query[offset + 5];
  144. response_size_computed = 3 +
  145. (coil_count / 8) + ((coil_count % 8) ? 1 : 0);
  146. }
  147. break;
  148. case FC_READ_HOLDING_REGISTERS:
  149. case FC_READ_INPUT_REGISTERS:
  150. /* Header + 2 * nb values */
  151. response_size_computed = 3 +
  152. 2 * (query[offset + 4] << 8 | query[offset + 5]);
  153. break;
  154. case FC_READ_EXCEPTION_STATUS:
  155. response_size_computed = 4;
  156. break;
  157. default:
  158. response_size_computed = 6;
  159. }
  160. response_size_computed += offset + mb_param->checksum_size;
  161. return response_size_computed;
  162. }
  163. /* Buils a RTU header */
  164. int build_query_packet_rtu(int slave, int function, int start_addr,
  165. int count, unsigned char *packet)
  166. {
  167. packet[0] = slave;
  168. packet[1] = function;
  169. packet[2] = start_addr >> 8;
  170. packet[3] = start_addr & 0x00ff;
  171. packet[4] = count >> 8;
  172. packet[5] = count & 0x00ff;
  173. return PRESET_QUERY_SIZE_RTU;
  174. }
  175. /* Builds a TCP header */
  176. int build_query_packet_tcp(int slave, int function, int start_addr,
  177. int count, unsigned char *packet)
  178. {
  179. static unsigned short t_id = 0;
  180. /* Transaction ID */
  181. if (t_id < USHRT_MAX)
  182. t_id++;
  183. else
  184. t_id = 0;
  185. packet[0] = t_id >> 8;
  186. packet[1] = t_id & 0x00ff;
  187. /* Protocol Modbus */
  188. packet[2] = 0;
  189. packet[3] = 0;
  190. /* Length to fix later with set_packet_length_tcp (4 and 5) */
  191. packet[6] = slave;
  192. packet[7] = function;
  193. packet[8] = start_addr >> 8;
  194. packet[9] = start_addr & 0x00ff;
  195. packet[10] = count >> 8;
  196. packet[11] = count & 0x00ff;
  197. return PRESET_QUERY_SIZE_TCP;
  198. }
  199. int build_query_packet(modbus_param_t *mb_param, int slave,
  200. int function, int start_addr,
  201. int count, unsigned char *packet)
  202. {
  203. if (mb_param->type_com == RTU)
  204. return build_query_packet_rtu(slave, function, start_addr,
  205. count, packet);
  206. else
  207. return build_query_packet_tcp(slave, function, start_addr,
  208. count, packet);
  209. }
  210. int build_response_packet_rtu(int slave, int function, int byte_count, unsigned char *packet)
  211. {
  212. packet[0] = slave;
  213. packet[1] = function;
  214. packet[2] = byte_count;
  215. /* FIXME +1 */
  216. return PRESET_RESPONSE_SIZE_RTU+1;
  217. }
  218. int build_response_packet_tcp(int slave, int function, int byte_count, unsigned char *packet)
  219. {
  220. static unsigned short t_id = 0;
  221. /* Transaction ID */
  222. if (t_id < USHRT_MAX)
  223. t_id++;
  224. else
  225. t_id = 0;
  226. packet[0] = t_id >> 8;
  227. packet[1] = t_id & 0x00ff;
  228. /* Protocol Modbus */
  229. packet[2] = 0;
  230. packet[3] = 0;
  231. /* Length to fix later with set_packet_length_tcp (4 and 5) */
  232. packet[6] = slave;
  233. packet[7] = function;
  234. packet[8] = byte_count;
  235. /* FIXME +1 */
  236. return PRESET_RESPONSE_SIZE_TCP+1;
  237. }
  238. int build_response_packet(modbus_param_t *mb_param, int slave,
  239. int function, int byte_count, unsigned char *packet)
  240. {
  241. if (mb_param->type_com == RTU)
  242. return build_response_packet_rtu(slave, function, byte_count, packet);
  243. else
  244. return build_response_packet_tcp(slave, function, byte_count, packet);
  245. }
  246. /* Sets the length of TCP message in the message */
  247. void set_packet_length_tcp(unsigned char *packet, size_t packet_size)
  248. {
  249. unsigned short mbap_length;
  250. /* Substract MBAP header length */
  251. mbap_length = packet_size - 6;
  252. packet[4] = mbap_length >> 8;
  253. packet[5] = mbap_length & 0x00FF;
  254. }
  255. /* Fast CRC */
  256. static unsigned short crc16(unsigned char *buffer,
  257. unsigned short buffer_length)
  258. {
  259. unsigned char crc_hi = 0xFF; /* high CRC byte initialized */
  260. unsigned char crc_lo = 0xFF; /* low CRC byte initialized */
  261. unsigned int i; /* will index into CRC lookup */
  262. /* pass through message buffer */
  263. while (buffer_length--) {
  264. i = crc_hi ^ *buffer++; /* calculate the CRC */
  265. crc_hi = crc_lo ^ table_crc_hi[i];
  266. crc_lo = table_crc_lo[i];
  267. }
  268. return (crc_hi << 8 | crc_lo);
  269. }
  270. /* If CRC is correct returns 0 else returns INVALID_CRC */
  271. int check_crc16(modbus_param_t *mb_param,
  272. unsigned char *msg,
  273. int msg_size)
  274. {
  275. int ret;
  276. if (mb_param->type_com == RTU) {
  277. unsigned short crc_calc;
  278. unsigned short crc_received;
  279. crc_calc = crc16(msg, msg_size - 2);
  280. crc_received = (msg[msg_size - 2] << 8) | msg[msg_size - 1];
  281. /* Check CRC of msg */
  282. if (crc_calc == crc_received) {
  283. ret = 0;
  284. } else {
  285. char s_error[64];
  286. sprintf(s_error, "invalid crc received %0X - crc_calc %0X",
  287. crc_received, crc_calc);
  288. error_treat(0, s_error, mb_param);
  289. ret = INVALID_CRC;
  290. }
  291. } else {
  292. /* In TCP, the modbus CRC is not present (see HDLC level) */
  293. ret = 0;
  294. }
  295. return ret;
  296. }
  297. /* Sends a query/response over a serial or a TCP communication */
  298. static int modbus_send(modbus_param_t *mb_param, unsigned char *query,
  299. size_t query_size)
  300. {
  301. int write_ret;
  302. unsigned short s_crc;
  303. int i;
  304. if (mb_param->type_com == RTU) {
  305. s_crc = crc16(query, query_size);
  306. query[query_size++] = s_crc >> 8;
  307. query[query_size++] = s_crc & 0x00FF;
  308. } else {
  309. set_packet_length_tcp(query, query_size);
  310. }
  311. if (mb_param->debug) {
  312. printf("\n");
  313. for (i = 0; i < query_size; i++)
  314. printf("[%.2X]", query[i]);
  315. printf("\n");
  316. }
  317. if (mb_param->type_com == RTU)
  318. write_ret = write(mb_param->fd, query, query_size);
  319. else
  320. write_ret = send(mb_param->fd, query, query_size, 0);
  321. /* Return the number of bytes written (0 to n)
  322. or PORT_SOCKET_FAILURE on error */
  323. if ((write_ret == -1) || (write_ret != query_size)) {
  324. error_treat(write_ret, "Write port/socket failure", mb_param);
  325. write_ret = PORT_SOCKET_FAILURE;
  326. }
  327. return write_ret;
  328. }
  329. /* Computes the size of the header following the function code */
  330. int compute_query_size_header(int function)
  331. {
  332. int byte;
  333. if (function <= FC_FORCE_SINGLE_COIL)
  334. /* Read and single write */
  335. byte = 4;
  336. else if (function == FC_FORCE_MULTIPLE_COILS ||
  337. function == FC_PRESET_MULTIPLE_REGISTERS)
  338. /* Multiple write */
  339. byte = 5;
  340. else
  341. byte = 0;
  342. printf("compute_query_size_header FC %d, B%d\n", function, byte);
  343. return byte;
  344. }
  345. /* Computes the size of the data to write in the query */
  346. int compute_query_size_data(modbus_param_t *mb_param, unsigned char *msg)
  347. {
  348. int function = msg[mb_param->header_length + 1];
  349. int byte;
  350. if (function == FC_FORCE_MULTIPLE_COILS ||
  351. function == FC_PRESET_MULTIPLE_REGISTERS)
  352. byte = msg[mb_param->header_length + 6];
  353. else
  354. byte = 0;
  355. byte += mb_param->checksum_size;
  356. printf("compute_query_size_data FC %d, B %d\n", function, byte);
  357. return byte;
  358. }
  359. #define WAIT_DATA() \
  360. { \
  361. while ((select_ret = select(mb_param->fd+1, &rfds, NULL, NULL, &tv)) == -1) { \
  362. if (errno == EINTR) { \
  363. printf("A non blocked signal was caught\n"); \
  364. /* Necessary after an error */ \
  365. FD_ZERO(&rfds); \
  366. FD_SET(mb_param->fd, &rfds); \
  367. } else { \
  368. error_treat(select_ret, "Select failure", mb_param); \
  369. return SELECT_FAILURE; \
  370. } \
  371. } \
  372. \
  373. if (select_ret == 0) { \
  374. /* Call to error_treat is done later to manage exceptions */ \
  375. return COMM_TIME_OUT; \
  376. } \
  377. }
  378. /* Monitors for the reply from the modbus slave or to receive query
  379. from a modbus master.
  380. This function blocks for timeout seconds if there is no reply.
  381. msg_size_computed must be set to MSG_SIZE_COMPUTED if undefined
  382. Returns:
  383. - 0: OK, <0: error
  384. - msg_size: number of characters received. */
  385. int receive_msg(modbus_param_t *mb_param,
  386. int msg_size_computed,
  387. unsigned char *msg,
  388. int *msg_size)
  389. {
  390. int select_ret;
  391. int read_ret;
  392. fd_set rfds;
  393. struct timeval tv;
  394. int size_to_read;
  395. unsigned char *p_msg;
  396. enum { FUNCTION, BYTE, COMPLETE };
  397. int state;
  398. if (mb_param->debug) {
  399. if (msg_size_computed == MSG_SIZE_UNDEFINED)
  400. printf("Waiting for a message...\n");
  401. else
  402. printf("Waiting for a message (%d bytes)...\n", msg_size_computed);
  403. }
  404. /* Add a file descriptor to the set */
  405. FD_ZERO(&rfds);
  406. FD_SET(mb_param->fd, &rfds);
  407. if (msg_size_computed == MSG_SIZE_UNDEFINED) {
  408. /* Wait for a message */
  409. tv.tv_sec = 60;
  410. tv.tv_usec = 0;
  411. /* The message size is undefined (query receiving) so
  412. * we need to analyse the message step by step.
  413. * In the first step, we want to reach the function code */
  414. msg_size_computed = mb_param->header_length + 2;
  415. state = FUNCTION;
  416. } else {
  417. tv.tv_sec = 0;
  418. tv.tv_usec = TIME_OUT_BEGIN_OF_TRAME;
  419. state = COMPLETE;
  420. }
  421. size_to_read = msg_size_computed;
  422. WAIT_DATA();
  423. /* Read the msg */
  424. (*msg_size) = 0;
  425. p_msg = msg;
  426. while (select_ret) {
  427. if (mb_param->type_com == RTU)
  428. read_ret = read(mb_param->fd, p_msg, size_to_read);
  429. else
  430. read_ret = recv(mb_param->fd, p_msg, size_to_read, 0);
  431. if (read_ret == -1) {
  432. error_treat(read_ret, "Read port/socket failure", mb_param);
  433. return PORT_SOCKET_FAILURE;
  434. }
  435. /* Sums bytes received */
  436. (*msg_size) += read_ret;
  437. if ((*msg_size) > MAX_PACKET_SIZE) {
  438. error_treat(0, "Too many datas", mb_param);
  439. return TOO_MANY_DATAS;
  440. }
  441. /* Display the hex code of each character received */
  442. if (mb_param->debug) {
  443. int i;
  444. for (i=0; i < read_ret; i++)
  445. printf("<%.2X>", p_msg[i]);
  446. }
  447. if ((*msg_size) < msg_size_computed) {
  448. /* Message incomplete */
  449. size_to_read = msg_size_computed - (*msg_size);
  450. } else {
  451. switch (state) {
  452. case FUNCTION:
  453. /* Function code position */
  454. size_to_read = compute_query_size_header(msg[mb_param->header_length + 1]);
  455. msg_size_computed += size_to_read;
  456. state = BYTE;
  457. printf("\nBYTE:");
  458. break;
  459. case BYTE:
  460. size_to_read = compute_query_size_data(mb_param, msg);
  461. msg_size_computed += size_to_read;
  462. state = COMPLETE;
  463. printf("\nCOMPLETE:");
  464. break;
  465. case COMPLETE:
  466. size_to_read = 0;
  467. break;
  468. }
  469. }
  470. printf(" size to read %d\n", size_to_read);
  471. /* Moves the pointer to receive other datas */
  472. p_msg = &(p_msg[read_ret]);
  473. if (size_to_read > 0) {
  474. /* If no character at the buffer wait
  475. TIME_OUT_END_OF_TRAME before to generate an error. */
  476. tv.tv_sec = 0;
  477. tv.tv_usec = TIME_OUT_END_OF_TRAME;
  478. WAIT_DATA();
  479. } else {
  480. /* All chars are received */
  481. select_ret = FALSE;
  482. }
  483. }
  484. if (mb_param->debug)
  485. printf("\n");
  486. /* OK */
  487. return 0;
  488. }
  489. /* Checks whether the right response is returned with good checksum.
  490. Returns:
  491. - the numbers of values (bits or word) if success
  492. - less than 0 for exception errors
  493. Note: All functions used to send or receive data with modbus return
  494. these values. */
  495. static int modbus_check_response(modbus_param_t *mb_param,
  496. unsigned char *query,
  497. unsigned char *response)
  498. {
  499. int response_size;
  500. int response_size_computed; int offset = mb_param->header_length;
  501. int ret;
  502. response_size_computed = compute_response_size(mb_param, query);
  503. ret = receive_msg(mb_param, response_size_computed, response, &response_size);
  504. if (ret == 0) {
  505. /* Check message */
  506. ret = check_crc16(mb_param, response, response_size);
  507. if (ret != 0)
  508. return ret;
  509. /* Good response */
  510. switch (response[offset + 1]) {
  511. case FC_READ_COIL_STATUS:
  512. case FC_READ_INPUT_STATUS:
  513. /* Read functions 1 value = 1 byte */
  514. response_size = response[offset + 2];
  515. break;
  516. case FC_READ_HOLDING_REGISTERS:
  517. case FC_READ_INPUT_REGISTERS:
  518. /* Read functions 1 value = 2 bytes */
  519. response_size = response[offset + 2] / 2;
  520. break;
  521. case FC_FORCE_MULTIPLE_COILS:
  522. case FC_PRESET_MULTIPLE_REGISTERS:
  523. /* N Write functions */
  524. response_size = response[offset + 4] << 8 |
  525. response[offset + 5];
  526. break;
  527. case FC_REPORT_SLAVE_ID:
  528. /* Report slave ID (bytes received) */
  529. break;
  530. default:
  531. /* 1 Write functions & others */
  532. response_size = 1;
  533. }
  534. } else if (ret == COMM_TIME_OUT &&
  535. response_size == offset + 3 + mb_param->checksum_size) {
  536. /* Optimisation allowed because exception response is
  537. the smallest trame in modbus protocol (3) so always
  538. raise an timeout error */
  539. /* CRC */
  540. ret = check_crc16(mb_param, response, response_size);
  541. if (ret != 0)
  542. return ret;
  543. /* Check for exception response
  544. 0x80 + function */
  545. if (0x80 + query[offset + 1] == response[offset + 1]) {
  546. if (response[offset + 2] < SIZE_TAB_ERROR_MSG) {
  547. error_treat(0,
  548. TAB_ERROR_MSG[response[offset + 2]],
  549. mb_param);
  550. /* Modbus error code (negative) */
  551. return -response[offset + 2];
  552. } else {
  553. /* The chances are low to hit this
  554. case but can avoid a vicious
  555. segfault */
  556. char s_error[64];
  557. sprintf(s_error, "Invalid exception code %d", response[offset + 2]);
  558. error_treat(0, s_error, mb_param);
  559. free(s_error);
  560. return INVALID_EXCEPTION_CODE;
  561. }
  562. }
  563. } else if (ret == COMM_TIME_OUT) {
  564. error_treat(0, "Communication time out", mb_param);
  565. return COMM_TIME_OUT;
  566. } else {
  567. return ret;
  568. }
  569. return response_size;
  570. }
  571. int response_io_status(int address, int count,
  572. int nb_io_status, unsigned char *tab_io_status,
  573. unsigned char *response, int offset)
  574. {
  575. unsigned char shift = 0;
  576. unsigned char byte = 0;
  577. int i;
  578. for (i = address; i < address+count; i++) {
  579. byte |= tab_io_status[i] << shift;
  580. if (shift == 7) {
  581. /* Byte is full */
  582. response[offset++] = byte;
  583. byte = shift = 0;
  584. } else {
  585. shift++;
  586. }
  587. }
  588. if (shift != 0)
  589. response[offset++] = byte;
  590. return offset;
  591. }
  592. /* Manages the received query.
  593. Analyses the query and constructs a response */
  594. void manage_query(modbus_param_t *mb_param, unsigned char *query,
  595. int query_size, modbus_mapping_t *mb_mapping)
  596. {
  597. int offset = mb_param->header_length;
  598. int slave = query[offset];
  599. int function = query[offset+1];
  600. int address = (query[offset+2] << 8) + query[offset+3];
  601. /* FIXME count/data */
  602. int count;
  603. int data;
  604. unsigned char response[MAX_PACKET_SIZE];
  605. int byte_count;
  606. int i;
  607. /* FIXME address illegal used in mb_mapping->tab_X */
  608. switch (function) {
  609. case FC_READ_COIL_STATUS:
  610. count = (query[offset+4] << 8) + query[offset+5];
  611. byte_count = (count / 8.0) + ((count % 8) ? 1 : 0);
  612. offset = build_response_packet(mb_param, slave, function, byte_count, response);
  613. offset = response_io_status(address, count,
  614. mb_mapping->nb_coil_status, mb_mapping->tab_coil_status,
  615. response, offset);
  616. break;
  617. case FC_READ_INPUT_STATUS:
  618. count = (query[offset+4] << 8) + query[offset+5];
  619. byte_count = (count / 8.0) + ((count % 8) ? 1 : 0);
  620. offset = build_response_packet(mb_param, slave, function, byte_count, response);
  621. offset = response_io_status(address, count,
  622. mb_mapping->nb_input_status, mb_mapping->tab_input_status,
  623. response, offset);
  624. break;
  625. case FC_READ_HOLDING_REGISTERS:
  626. count = (query[offset+4] << 8) + query[offset+5];
  627. byte_count = 2 * count;
  628. offset = build_response_packet(mb_param, slave, function, byte_count, response);
  629. printf("offset %d\n", offset);
  630. for (i = address; i < address + count; i++) {
  631. response[offset++] = mb_mapping->tab_holding_registers[i] >> 8;
  632. response[offset++] = mb_mapping->tab_holding_registers[i] & 0xFF;
  633. }
  634. printf("fin offset %d\n", offset);
  635. break;
  636. case FC_READ_INPUT_REGISTERS:
  637. count = (query[offset+4] << 8) + query[offset+5];
  638. byte_count = 2 * count;
  639. offset = build_response_packet(mb_param, slave, function, byte_count, response);
  640. for (i = address; i < address + count; i++) {
  641. response[offset++] = mb_mapping->tab_input_registers[i] >> 8;
  642. response[offset++] = mb_mapping->tab_input_registers[i] & 0xFF;
  643. }
  644. break;
  645. case FC_FORCE_SINGLE_COIL:
  646. data = (query[offset+4] << 8) + query[offset+5];
  647. if (data == 0xFF00)
  648. mb_mapping->tab_coil_status[address] = ON;
  649. else if (data == 0x0)
  650. mb_mapping->tab_coil_status[address] = OFF;
  651. else
  652. printf("FIXME Error %d\n", data);
  653. printf("FIXME works only in TCP mode (CRC)");
  654. memcpy(response, query, query_size);
  655. offset = query_size;
  656. break;
  657. case FC_PRESET_SINGLE_REGISTER:
  658. case FC_READ_EXCEPTION_STATUS:
  659. case FC_FORCE_MULTIPLE_COILS:
  660. case FC_PRESET_MULTIPLE_REGISTERS:
  661. case FC_REPORT_SLAVE_ID:
  662. printf("Not implemented\n");
  663. break;
  664. }
  665. modbus_send(mb_param, response, offset);
  666. }
  667. /* Listens any message on a socket or file descriptor.
  668. Returns:
  669. - 0 if OK, or a negative error number if the request fails
  670. - query, message received
  671. - query_size, size in bytes of the message */
  672. int modbus_listen(modbus_param_t *mb_param, unsigned char *query, int *query_size)
  673. {
  674. int ret;
  675. ret = receive_msg(mb_param, MSG_SIZE_UNDEFINED, query, query_size);
  676. if (ret == 0) {
  677. ret = check_crc16(mb_param, query, *query_size);
  678. }
  679. return ret;
  680. }
  681. /* Reads IO status */
  682. static int read_io_status(modbus_param_t *mb_param, int slave, int function,
  683. int start_addr, int count, int *data_dest)
  684. {
  685. int query_size;
  686. int query_ret;
  687. int response_ret;
  688. unsigned char query[MIN_QUERY_SIZE];
  689. unsigned char response[MAX_PACKET_SIZE];
  690. query_size = build_query_packet(mb_param, slave, function,
  691. start_addr, count, query);
  692. query_ret = modbus_send(mb_param, query, query_size);
  693. if (query_ret > 0) {
  694. int i, temp, bit;
  695. int pos = 0;
  696. int processed = 0;
  697. int offset;
  698. int offset_length;
  699. response_ret = modbus_check_response(mb_param, query, response);
  700. offset = mb_param->header_length;
  701. offset_length = offset + response_ret;
  702. for (i = offset; i < offset_length; i++) {
  703. /* Shift reg hi_byte to temp */
  704. temp = response[3 + i];
  705. for (bit = 0x01; (bit & 0xff) && (processed < count);) {
  706. data_dest[pos++] = (temp & bit) ? TRUE : FALSE;
  707. processed++;
  708. bit = bit << 1;
  709. }
  710. }
  711. } else {
  712. response_ret = query_ret;
  713. }
  714. return response_ret;
  715. }
  716. /* Reads the boolean status of coils and sets the array elements
  717. in the destination to TRUE or FALSE. */
  718. int read_coil_status(modbus_param_t *mb_param, int slave, int start_addr,
  719. int count, int *data_dest)
  720. {
  721. int status;
  722. status = read_io_status(mb_param, slave, FC_READ_COIL_STATUS,
  723. start_addr, count, data_dest);
  724. if (status > 0)
  725. status = count;
  726. return status;
  727. }
  728. /* Same as read_coil_status but reads the slaves input table */
  729. int read_input_status(modbus_param_t *mb_param, int slave, int start_addr,
  730. int count, int *data_dest)
  731. {
  732. int status;
  733. status = read_io_status(mb_param, slave, FC_READ_INPUT_STATUS,
  734. start_addr, count, data_dest);
  735. if (status > 0)
  736. status = count;
  737. return status;
  738. }
  739. /* Reads the data from a modbus slave and put that data into an array */
  740. static int read_registers(modbus_param_t *mb_param, int slave, int function,
  741. int start_addr, int count, int *data_dest)
  742. {
  743. int query_size;
  744. int status;
  745. int query_ret;
  746. unsigned char query[MIN_QUERY_SIZE];
  747. query_size = build_query_packet(mb_param, slave, function,
  748. start_addr, count, query);
  749. query_ret = modbus_send(mb_param, query, query_size);
  750. if (query_ret > 0)
  751. status = read_reg_response(mb_param, data_dest, query);
  752. else
  753. status = query_ret;
  754. return status;
  755. }
  756. /* Reads the holding registers in a slave and put the data into an
  757. array */
  758. int read_holding_registers(modbus_param_t *mb_param, int slave,
  759. int start_addr, int count, int *data_dest)
  760. {
  761. int status;
  762. if (count > MAX_READ_HOLD_REGS) {
  763. printf("WARNING Too many holding registers requested\n");
  764. count = MAX_READ_HOLD_REGS;
  765. }
  766. status = read_registers(mb_param, slave, FC_READ_HOLDING_REGISTERS,
  767. start_addr, count, data_dest);
  768. return status;
  769. }
  770. /* Reads the input registers in a slave and put the data into
  771. an array */
  772. int read_input_registers(modbus_param_t *mb_param, int slave,
  773. int start_addr, int count, int *data_dest)
  774. {
  775. int status;
  776. if (count > MAX_READ_INPUT_REGS) {
  777. printf("WARNING Too many input registers requested\n");
  778. count = MAX_READ_INPUT_REGS;
  779. }
  780. status = read_registers(mb_param, slave, FC_READ_INPUT_REGISTERS,
  781. start_addr, count, data_dest);
  782. return status;
  783. }
  784. /* Reads the response data from a slave and puts the data into an
  785. array */
  786. static int read_reg_response(modbus_param_t *mb_param, int *data_dest,
  787. unsigned char *query)
  788. {
  789. unsigned char response[MAX_PACKET_SIZE];
  790. int response_ret;
  791. int offset;
  792. int i;
  793. response_ret = modbus_check_response(mb_param, query, response);
  794. offset = mb_param->header_length;
  795. /* If response_ret is negative, the loop is jumped ! */
  796. for (i = 0; i < response_ret; i++) {
  797. /* shift reg hi_byte to temp OR with lo_byte */
  798. data_dest[i] = response[offset + 3 + (i << 1)] << 8 |
  799. response[offset + 4 + (i << 1)];
  800. }
  801. return response_ret;
  802. }
  803. /* Gets the raw data from the input stream */
  804. static int preset_response(modbus_param_t *mb_param, unsigned char *query)
  805. {
  806. int ret;
  807. unsigned char response[MAX_PACKET_SIZE];
  808. ret = modbus_check_response(mb_param, query, response);
  809. return ret;
  810. }
  811. /* Sends a value to a register in a slave */
  812. static int set_single(modbus_param_t *mb_param, int slave, int function,
  813. int addr, int value)
  814. {
  815. int status;
  816. int query_size;
  817. int query_ret;
  818. unsigned char query[MAX_PACKET_SIZE];
  819. query_size = build_query_packet(mb_param, slave, function,
  820. addr, value, query);
  821. query_ret = modbus_send(mb_param, query, query_size);
  822. if (query_ret > 0)
  823. status = preset_response(mb_param, query);
  824. else
  825. status = query_ret;
  826. return status;
  827. }
  828. /* Turns on or off a single coil on the slave device */
  829. int force_single_coil(modbus_param_t *mb_param, int slave,
  830. int coil_addr, int state)
  831. {
  832. int status;
  833. if (state)
  834. state = 0xFF00;
  835. status = set_single(mb_param, slave, FC_FORCE_SINGLE_COIL, coil_addr, state);
  836. return status;
  837. }
  838. /* Sets a value in one holding register in the slave device */
  839. int preset_single_register(modbus_param_t *mb_param, int slave,
  840. int reg_addr, int value)
  841. {
  842. int status;
  843. status = set_single(mb_param, slave, FC_PRESET_SINGLE_REGISTER, reg_addr, value);
  844. return status;
  845. }
  846. /* Takes an array of ints and sets or resets the coils on a slave
  847. appropriatly */
  848. int force_multiple_coils(modbus_param_t *mb_param, int slave,
  849. int start_addr, int coil_count,
  850. int *data_src)
  851. {
  852. int i;
  853. int byte_count;
  854. int query_size;
  855. int coil_check = 0;
  856. int status;
  857. int query_ret;
  858. int pos = 0;
  859. unsigned char query[MAX_PACKET_SIZE];
  860. if (coil_count > MAX_WRITE_COILS) {
  861. printf("WARNING Writing to too many coils\n");
  862. coil_count = MAX_WRITE_COILS;
  863. }
  864. query_size = build_query_packet(mb_param, slave, FC_FORCE_MULTIPLE_COILS,
  865. start_addr, coil_count, query);
  866. byte_count = (coil_count / 8) + ((coil_count % 8) ? 1 : 0);
  867. query[query_size++] = byte_count;
  868. for (i = 0; i < byte_count; i++) {
  869. int bit;
  870. bit = 0x01;
  871. query[query_size] = 0;
  872. while ((bit & 0xFF) && (coil_check++ < coil_count)) {
  873. if (data_src[pos++])
  874. query[query_size] |= bit;
  875. else
  876. query[query_size] &=~ bit;
  877. bit = bit << 1;
  878. }
  879. query_size++;
  880. }
  881. query_ret = modbus_send(mb_param, query, query_size);
  882. if (query_ret > 0)
  883. status = preset_response(mb_param, query);
  884. else
  885. status = query_ret;
  886. return status;
  887. }
  888. /* Copies the values in an array to an array on the slave */
  889. int preset_multiple_registers(modbus_param_t *mb_param, int slave,
  890. int start_addr, int reg_count, int *data_src)
  891. {
  892. int i;
  893. int query_size;
  894. int byte_count;
  895. int status;
  896. int query_ret;
  897. unsigned char query[MAX_PACKET_SIZE];
  898. if (reg_count > MAX_WRITE_REGS) {
  899. printf("WARNING Trying to write to too many registers\n");
  900. reg_count = MAX_WRITE_REGS;
  901. }
  902. query_size = build_query_packet(mb_param, slave,
  903. FC_PRESET_MULTIPLE_REGISTERS,
  904. start_addr, reg_count, query);
  905. byte_count = reg_count * 2;
  906. query[query_size++] = byte_count;
  907. for (i = 0; i < reg_count; i++) {
  908. query[query_size++] = data_src[i] >> 8;
  909. query[query_size++] = data_src[i] & 0x00FF;
  910. }
  911. query_ret = modbus_send(mb_param, query, query_size);
  912. if (query_ret > 0)
  913. status = preset_response(mb_param, query);
  914. else
  915. status = query_ret;
  916. return status;
  917. }
  918. /* Returns the slave id ! */
  919. int report_slave_id(modbus_param_t *mb_param, int slave,
  920. unsigned char *data_dest)
  921. {
  922. int query_size;
  923. int query_ret;
  924. int response_ret;
  925. unsigned char query[MIN_QUERY_SIZE];
  926. unsigned char response[MAX_PACKET_SIZE];
  927. query_size = build_query_packet(mb_param, slave, FC_REPORT_SLAVE_ID,
  928. 0, 0, query);
  929. /* start_addr and count are not used */
  930. query_size -= 4;
  931. query_ret = modbus_send(mb_param, query, query_size);
  932. if (query_ret > 0) {
  933. int i;
  934. int offset;
  935. int offset_length;
  936. /* Byte count, slave id, run indicator status,
  937. additional data */
  938. response_ret = modbus_check_response(mb_param, query, response);
  939. offset = mb_param->header_length;
  940. offset_length = offset + response_ret;
  941. for (i = offset; i < offset_length; i++)
  942. data_dest[i] = response[i];
  943. } else {
  944. response_ret = query_ret;
  945. }
  946. return response_ret;
  947. }
  948. /* Initialises the modbus_param_t structure for RTU */
  949. void modbus_init_rtu(modbus_param_t *mb_param, char *device,
  950. int baud_i, char *parity, int data_bit,
  951. int stop_bit)
  952. {
  953. memset(mb_param, 0, sizeof(modbus_param_t));
  954. strcpy(mb_param->device, device);
  955. mb_param->baud_i = baud_i;
  956. strcpy(mb_param->parity, parity);
  957. mb_param->debug = FALSE;
  958. mb_param->data_bit = data_bit;
  959. mb_param->stop_bit = stop_bit;
  960. mb_param->type_com = RTU;
  961. mb_param->header_length = HEADER_LENGTH_RTU;
  962. mb_param->checksum_size = CHECKSUM_SIZE_RTU;
  963. }
  964. /* Initialises the modbus_param_t structure for TCP.
  965. Set the port to MODBUS_TCP_DEFAULT_PORT to use the default one
  966. (502). It's convenient to use a port number greater than or equal
  967. to 1024 because it's not necessary to be root to use this port
  968. number.
  969. */
  970. void modbus_init_tcp(modbus_param_t *mb_param, char *ip, uint16_t port)
  971. {
  972. memset(mb_param, 0, sizeof(modbus_param_t));
  973. strncpy(mb_param->ip, ip, sizeof(char)*16);
  974. mb_param->port = port;
  975. mb_param->type_com = TCP;
  976. mb_param->header_length = HEADER_LENGTH_TCP;
  977. mb_param->checksum_size = CHECKSUM_SIZE_TCP;
  978. }
  979. /* This function sets up a serial port for RTU communications to
  980. modbus */
  981. static int modbus_connect_rtu(modbus_param_t *mb_param)
  982. {
  983. struct termios tios;
  984. speed_t baud_rate;
  985. if (mb_param->debug) {
  986. printf("Opening %s at %d bauds (%s)\n",
  987. mb_param->device, mb_param->baud_i, mb_param->parity);
  988. }
  989. /* The O_NOCTTY flag tells UNIX that this program doesn't want
  990. to be the "controlling terminal" for that port. If you
  991. don't specify this then any input (such as keyboard abort
  992. signals and so forth) will affect your process
  993. Timeouts are ignored in canonical input mode or when the
  994. NDELAY option is set on the file via open or fcntl */
  995. mb_param->fd = open(mb_param->device, O_RDWR | O_NOCTTY | O_NDELAY);
  996. if (mb_param->fd < 0) {
  997. perror("open");
  998. printf("ERROR Opening device %s (no : %d)\n",
  999. mb_param->device, errno);
  1000. return -1;
  1001. }
  1002. /* Save */
  1003. tcgetattr(mb_param->fd, &(mb_param->old_tios));
  1004. memset(&tios, 0, sizeof(struct termios));
  1005. /* C_ISPEED Input baud (new interface)
  1006. C_OSPEED Output baud (new interface)
  1007. */
  1008. switch (mb_param->baud_i) {
  1009. case 110:
  1010. baud_rate = B110;
  1011. break;
  1012. case 300:
  1013. baud_rate = B300;
  1014. break;
  1015. case 600:
  1016. baud_rate = B600;
  1017. break;
  1018. case 1200:
  1019. baud_rate = B1200;
  1020. break;
  1021. case 2400:
  1022. baud_rate = B2400;
  1023. break;
  1024. case 4800:
  1025. baud_rate = B4800;
  1026. break;
  1027. case 9600:
  1028. baud_rate = B9600;
  1029. break;
  1030. case 19200:
  1031. baud_rate = B19200;
  1032. break;
  1033. case 38400:
  1034. baud_rate = B38400;
  1035. break;
  1036. case 57600:
  1037. baud_rate = B57600;
  1038. break;
  1039. case 115200:
  1040. baud_rate = B115200;
  1041. break;
  1042. default:
  1043. baud_rate = B9600;
  1044. printf("WARNING Unknown baud rate %d for %s (B9600 used)\n",
  1045. mb_param->baud_i, mb_param->device);
  1046. }
  1047. /* Set the baud rate */
  1048. if ((cfsetispeed(&tios, baud_rate) < 0) ||
  1049. (cfsetospeed(&tios, baud_rate) < 0)) {
  1050. perror("cfsetispeed/cfsetospeed\n");
  1051. return -1;
  1052. }
  1053. /* C_CFLAG Control options
  1054. CLOCAL Local line - do not change "owner" of port
  1055. CREAD Enable receiver
  1056. */
  1057. tios.c_cflag |= (CREAD | CLOCAL);
  1058. /* CSIZE, HUPCL, CRTSCTS (hardware flow control) */
  1059. /* Set data bits (5, 6, 7, 8 bits)
  1060. CSIZE Bit mask for data bits
  1061. */
  1062. tios.c_cflag &= ~CSIZE;
  1063. switch (mb_param->data_bit) {
  1064. case 5:
  1065. tios.c_cflag |= CS5;
  1066. break;
  1067. case 6:
  1068. tios.c_cflag |= CS6;
  1069. break;
  1070. case 7:
  1071. tios.c_cflag |= CS7;
  1072. break;
  1073. case 8:
  1074. default:
  1075. tios.c_cflag |= CS8;
  1076. break;
  1077. }
  1078. /* Stop bit (1 or 2) */
  1079. if (mb_param->stop_bit == 1)
  1080. tios.c_cflag &=~ CSTOPB;
  1081. else /* 2 */
  1082. tios.c_cflag |= CSTOPB;
  1083. /* PARENB Enable parity bit
  1084. PARODD Use odd parity instead of even */
  1085. if (strncmp(mb_param->parity, "none", 4) == 0) {
  1086. tios.c_cflag &=~ PARENB;
  1087. } else if (strncmp(mb_param->parity, "even", 4) == 0) {
  1088. tios.c_cflag |= PARENB;
  1089. tios.c_cflag &=~ PARODD;
  1090. } else {
  1091. /* odd */
  1092. tios.c_cflag |= PARENB;
  1093. tios.c_cflag |= PARODD;
  1094. }
  1095. /* Read your man page for the meaning of all this (man
  1096. termios). Its a bit to involved to comment here :) */
  1097. tios.c_line = 0;
  1098. /* C_LFLAG Line options
  1099. ISIG Enable SIGINTR, SIGSUSP, SIGDSUSP, and SIGQUIT signals
  1100. ICANON Enable canonical input (else raw)
  1101. XCASE Map uppercase \lowercase (obsolete)
  1102. ECHO Enable echoing of input characters
  1103. ECHOE Echo erase character as BS-SP-BS
  1104. ECHOK Echo NL after kill character
  1105. ECHONL Echo NL
  1106. NOFLSH Disable flushing of input buffers after
  1107. interrupt or quit characters
  1108. IEXTEN Enable extended functions
  1109. ECHOCTL Echo control characters as ^char and delete as ~?
  1110. ECHOPRT Echo erased character as character erased
  1111. ECHOKE BS-SP-BS entire line on line kill
  1112. FLUSHO Output being flushed
  1113. PENDIN Retype pending input at next read or input char
  1114. TOSTOP Send SIGTTOU for background output
  1115. Canonical input is line-oriented. Input characters are put
  1116. into a buffer which can be edited interactively by the user
  1117. until a CR (carriage return) or LF (line feed) character is
  1118. received.
  1119. Raw input is unprocessed. Input characters are passed
  1120. through exactly as they are received, when they are
  1121. received. Generally you'll deselect the ICANON, ECHO,
  1122. ECHOE, and ISIG options when using raw input
  1123. */
  1124. /* Raw input */
  1125. tios.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
  1126. /* C_IFLAG Input options
  1127. Constant Description
  1128. INPCK Enable parity check
  1129. IGNPAR Ignore parity errors
  1130. PARMRK Mark parity errors
  1131. ISTRIP Strip parity bits
  1132. IXON Enable software flow control (outgoing)
  1133. IXOFF Enable software flow control (incoming)
  1134. IXANY Allow any character to start flow again
  1135. IGNBRK Ignore break condition
  1136. BRKINT Send a SIGINT when a break condition is detected
  1137. INLCR Map NL to CR
  1138. IGNCR Ignore CR
  1139. ICRNL Map CR to NL
  1140. IUCLC Map uppercase to lowercase
  1141. IMAXBEL Echo BEL on input line too long
  1142. */
  1143. if (strncmp(mb_param->parity, "none", 4) == 0) {
  1144. tios.c_iflag &= ~INPCK;
  1145. } else {
  1146. tios.c_iflag |= INPCK;
  1147. }
  1148. /* Software flow control is disabled */
  1149. tios.c_iflag &= ~(IXON | IXOFF | IXANY);
  1150. /* C_OFLAG Output options
  1151. OPOST Postprocess output (not set = raw output)
  1152. ONLCR Map NL to CR-NL
  1153. ONCLR ant others needs OPOST to be enabled
  1154. */
  1155. /* Raw ouput */
  1156. tios.c_oflag &=~ OPOST;
  1157. /* C_CC Control characters
  1158. VMIN Minimum number of characters to read
  1159. VTIME Time to wait for data (tenths of seconds)
  1160. UNIX serial interface drivers provide the ability to
  1161. specify character and packet timeouts. Two elements of the
  1162. c_cc array are used for timeouts: VMIN and VTIME. Timeouts
  1163. are ignored in canonical input mode or when the NDELAY
  1164. option is set on the file via open or fcntl.
  1165. VMIN specifies the minimum number of characters to read. If
  1166. it is set to 0, then the VTIME value specifies the time to
  1167. wait for every character read. Note that this does not mean
  1168. that a read call for N bytes will wait for N characters to
  1169. come in. Rather, the timeout will apply to the first
  1170. character and the read call will return the number of
  1171. characters immediately available (up to the number you
  1172. request).
  1173. If VMIN is non-zero, VTIME specifies the time to wait for
  1174. the first character read. If a character is read within the
  1175. time given, any read will block (wait) until all VMIN
  1176. characters are read. That is, once the first character is
  1177. read, the serial interface driver expects to receive an
  1178. entire packet of characters (VMIN bytes total). If no
  1179. character is read within the time allowed, then the call to
  1180. read returns 0. This method allows you to tell the serial
  1181. driver you need exactly N bytes and any read call will
  1182. return 0 or N bytes. However, the timeout only applies to
  1183. the first character read, so if for some reason the driver
  1184. misses one character inside the N byte packet then the read
  1185. call could block forever waiting for additional input
  1186. characters.
  1187. VTIME specifies the amount of time to wait for incoming
  1188. characters in tenths of seconds. If VTIME is set to 0 (the
  1189. default), reads will block (wait) indefinitely unless the
  1190. NDELAY option is set on the port with open or fcntl.
  1191. */
  1192. /* Unused because we use open with the NDELAY option */
  1193. tios.c_cc[VMIN] = 0;
  1194. tios.c_cc[VTIME] = 0;
  1195. if (tcsetattr(mb_param->fd, TCSANOW, &tios) < 0) {
  1196. perror("tcsetattr\n");
  1197. return -1;
  1198. }
  1199. return 0;
  1200. }
  1201. /* Establishes a modbus connection with a modbus slave */
  1202. static int modbus_connect_tcp(modbus_param_t *mb_param)
  1203. {
  1204. int ret;
  1205. int option;
  1206. struct sockaddr_in addr;
  1207. addr.sin_family = AF_INET;
  1208. addr.sin_port = htons(mb_param->port);
  1209. addr.sin_addr.s_addr = inet_addr(mb_param->ip);
  1210. mb_param->fd = socket(AF_INET, SOCK_STREAM, 0);
  1211. if (mb_param->fd < 0) {
  1212. return mb_param->fd;
  1213. }
  1214. /* Set the TCP no delay flag */
  1215. /* SOL_TCP = IPPROTO_TCP */
  1216. option = 1;
  1217. ret = setsockopt(mb_param->fd, SOL_TCP, TCP_NODELAY,
  1218. (const void *)&option, sizeof(int));
  1219. if (ret < 0) {
  1220. perror("setsockopt");
  1221. close(mb_param->fd);
  1222. return ret;
  1223. }
  1224. /* Set the IP low delay option */
  1225. option = IPTOS_LOWDELAY;
  1226. ret = setsockopt(mb_param->fd, SOL_TCP, IP_TOS,
  1227. (const void *)&option, sizeof(int));
  1228. if (ret < 0) {
  1229. perror("setsockopt");
  1230. close(mb_param->fd);
  1231. return ret;
  1232. }
  1233. if (mb_param->debug) {
  1234. printf("Connecting to %s\n", mb_param->ip);
  1235. }
  1236. ret = connect(mb_param->fd, (struct sockaddr *)&addr,
  1237. sizeof(struct sockaddr_in));
  1238. if (ret < 0) {
  1239. perror("connect");
  1240. close(mb_param->fd);
  1241. return ret;
  1242. }
  1243. return 0;
  1244. }
  1245. /* Establishes a modbus connexion */
  1246. int modbus_connect(modbus_param_t *mb_param)
  1247. {
  1248. int ret;
  1249. if (mb_param->type_com == RTU)
  1250. ret = modbus_connect_rtu(mb_param);
  1251. else
  1252. ret = modbus_connect_tcp(mb_param);
  1253. return ret;
  1254. }
  1255. /* Allocates 4 arrays to store coils, input status, input registers and
  1256. holding registers. The pointers are stored in modbus_mapping structure.
  1257. Returns: TRUE if ok, FALSE on failure
  1258. */
  1259. int modbus_mapping_new(modbus_mapping_t *mb_mapping,
  1260. int nb_coil_status, int nb_input_status,
  1261. int nb_input_registers, int nb_holding_registers)
  1262. {
  1263. /* 0X */
  1264. mb_mapping->nb_coil_status = nb_coil_status;
  1265. mb_mapping->tab_coil_status = (unsigned char *) malloc(nb_coil_status * sizeof(unsigned char));
  1266. memset(mb_mapping->tab_coil_status, 0, nb_coil_status * sizeof(unsigned char));
  1267. if (mb_mapping->tab_coil_status == NULL)
  1268. return FALSE;
  1269. /* 1X */
  1270. mb_mapping->nb_input_status = nb_input_status;
  1271. mb_mapping->tab_input_status = (unsigned char *) malloc(nb_input_status * sizeof(unsigned char));
  1272. memset(mb_mapping->tab_input_status, 0, nb_input_status * sizeof(unsigned char));
  1273. if (mb_mapping->tab_input_status == NULL) {
  1274. free(mb_mapping->tab_coil_status);
  1275. return FALSE;
  1276. }
  1277. /* 3X */
  1278. mb_mapping->nb_input_registers = nb_input_registers;
  1279. mb_mapping->tab_input_registers = (unsigned short *) malloc(nb_input_registers * sizeof(unsigned short));
  1280. memset(mb_mapping->tab_input_registers, 0, nb_input_registers * sizeof(unsigned short));
  1281. if (mb_mapping->tab_input_registers == NULL) {
  1282. free(mb_mapping->tab_coil_status);
  1283. free(mb_mapping->tab_input_status);
  1284. return FALSE;
  1285. }
  1286. /* 4X */
  1287. mb_mapping->nb_holding_registers = nb_holding_registers;
  1288. mb_mapping->tab_holding_registers = (unsigned short *) malloc(nb_holding_registers * sizeof(unsigned short));
  1289. memset(mb_mapping->tab_holding_registers, 0, nb_holding_registers * sizeof(unsigned short));
  1290. if (mb_mapping->tab_holding_registers == NULL) {
  1291. free(mb_mapping->tab_coil_status);
  1292. free(mb_mapping->tab_input_status);
  1293. free(mb_mapping->tab_input_registers);
  1294. return FALSE;
  1295. }
  1296. return TRUE;
  1297. }
  1298. /* Frees the 4 arrays */
  1299. void modbus_mapping_free(modbus_mapping_t *mb_mapping)
  1300. {
  1301. free(mb_mapping->tab_coil_status);
  1302. free(mb_mapping->tab_input_status);
  1303. free(mb_mapping->tab_input_registers);
  1304. free(mb_mapping->tab_holding_registers);
  1305. }
  1306. /* Listens for any query from a modbus master */
  1307. int modbus_init_listen_tcp(modbus_param_t *mb_param)
  1308. {
  1309. int ret;
  1310. int new_socket;
  1311. struct sockaddr_in addr;
  1312. socklen_t addrlen;
  1313. addr.sin_family = AF_INET;
  1314. /* If the modbus port is < to 1024, we need the setuid root. */
  1315. addr.sin_port = htons(mb_param->port);
  1316. addr.sin_addr.s_addr = INADDR_ANY;
  1317. memset(&(addr.sin_zero), '\0', 8);
  1318. new_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  1319. if (new_socket < 0) {
  1320. perror("socket");
  1321. exit(1);
  1322. } else {
  1323. printf("Socket OK\n");
  1324. }
  1325. ret = bind(new_socket, (struct sockaddr *)&addr,
  1326. sizeof(struct sockaddr_in));
  1327. if (ret < 0) {
  1328. perror("bind");
  1329. close(new_socket);
  1330. exit(1);
  1331. } else {
  1332. printf("Bind OK\n");
  1333. }
  1334. ret = listen(new_socket, 1);
  1335. if (ret != 0) {
  1336. perror("listen");
  1337. close(new_socket);
  1338. exit(1);
  1339. } else {
  1340. printf("Listen OK\n");
  1341. }
  1342. addrlen = sizeof(struct sockaddr_in);
  1343. mb_param->fd = accept(new_socket, (struct sockaddr *)&addr, &addrlen);
  1344. if (ret < 0) {
  1345. perror("accept");
  1346. close(new_socket);
  1347. new_socket = 0;
  1348. exit(1);
  1349. } else {
  1350. printf("The client %s is connected\n",
  1351. inet_ntoa(addr.sin_addr));
  1352. }
  1353. return new_socket;
  1354. }
  1355. /* Closes the file descriptor in RTU mode */
  1356. static void modbus_close_rtu(modbus_param_t *mb_param)
  1357. {
  1358. if (tcsetattr(mb_param->fd, TCSANOW, &(mb_param->old_tios)) < 0)
  1359. perror("tcsetattr");
  1360. close(mb_param->fd);
  1361. }
  1362. /* Closes the network connection and socket in TCP mode */
  1363. static void modbus_close_tcp(modbus_param_t *mb_param)
  1364. {
  1365. shutdown(mb_param->fd, SHUT_RDWR);
  1366. close(mb_param->fd);
  1367. }
  1368. /* Closes a modbus connection */
  1369. void modbus_close(modbus_param_t *mb_param)
  1370. {
  1371. if (mb_param->type_com == RTU)
  1372. modbus_close_rtu(mb_param);
  1373. else
  1374. modbus_close_tcp(mb_param);
  1375. }
  1376. /* Activates the debug messages */
  1377. void modbus_set_debug(modbus_param_t *mb_param, int boolean)
  1378. {
  1379. mb_param->debug = boolean;
  1380. }