modbus.c 67 KB

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