modbus.c 67 KB

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