modbus.c 69 KB

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