modbus.c 66 KB

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