modbus.c 66 KB

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