├── LICENSE
├── PhpSerial.php
├── PhpSerialModbus.php
├── README.md
└── example.php
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 | {description}
294 | Copyright (C) {year} {fullname}
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | {signature of Ty Coon}, 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------
/PhpSerial.php:
--------------------------------------------------------------------------------
1 |
13 | * @author Rizwan Kassim
14 | * @thanks Aurélien Derouineau for finding how to open serial ports with windows
15 | * @thanks Alec Avedisyan for help and testing with reading
16 | * @thanks Jim Wright for OSX cleanup/fixes.
17 | * @copyright under GPL 2 licence
18 | */
19 | class PhpSerial
20 | {
21 | public $_device = null;
22 | public $_winDevice = null;
23 | public $_dHandle = null;
24 | public $_dState = SERIAL_DEVICE_NOTSET;
25 | public $_buffer = "";
26 | public $_os = "";
27 |
28 | /**
29 | * This var says if buffer should be flushed by sendMessage (true) or
30 | * manually (false)
31 | *
32 | * @var bool
33 | */
34 | public $autoFlush = true;
35 |
36 | /**
37 | * Constructor. Perform some checks about the OS and setserial
38 | *
39 | * @return void
40 | */
41 | public function __construct()
42 | {
43 | setlocale(LC_ALL, "en_US");
44 |
45 | $sysName = php_uname();
46 |
47 | if (substr($sysName, 0, 5) === "Linux") {
48 | $this->_os = "linux";
49 |
50 | if ($this->_exec("stty --version") === 0) {
51 | register_shutdown_function(array($this, "deviceClose"));
52 | } else {
53 | trigger_error(
54 | "No stty available, unable to run.",
55 | E_USER_ERROR
56 | );
57 | }
58 | } elseif (substr($sysName, 0, 6) === "Darwin") {
59 | $this->_os = "osx";
60 | register_shutdown_function(array($this, "deviceClose"));
61 | } elseif (substr($sysName, 0, 7) === "Windows") {
62 | $this->_os = "windows";
63 | register_shutdown_function(array($this, "deviceClose"));
64 | } else {
65 | trigger_error("Host OS is neither osx, linux nor windows, unable " .
66 | "to run.", E_USER_ERROR);
67 | exit();
68 | }
69 | }
70 |
71 | //
72 | // OPEN/CLOSE DEVICE SECTION -- {START}
73 | //
74 |
75 | /**
76 | * Device set function : used to set the device name/address.
77 | * -> linux : use the device address, like /dev/ttyS0
78 | * -> osx : use the device address, like /dev/tty.serial
79 | * -> windows : use the COMxx device name, like COM1 (can also be used
80 | * with linux)
81 | *
82 | * @param string $device the name of the device to be used
83 | * @return bool
84 | */
85 | public function deviceSet($device)
86 | {
87 | if ($this->_dState !== SERIAL_DEVICE_OPENED) {
88 | if ($this->_os === "linux") {
89 | if (preg_match("@^COM(\\d+):?$@i", $device, $matches)) {
90 | $device = "/dev/ttyS" . ($matches[1] - 1);
91 | }
92 |
93 | if ($this->_exec("stty -F " . $device) === 0) {
94 | $this->_device = $device;
95 | $this->_dState = SERIAL_DEVICE_SET;
96 |
97 | return true;
98 | }
99 | } elseif ($this->_os === "osx") {
100 | if ($this->_exec("stty -f " . $device) === 0) {
101 | $this->_device = $device;
102 | $this->_dState = SERIAL_DEVICE_SET;
103 |
104 | return true;
105 | }
106 | } elseif ($this->_os === "windows") {
107 | if (preg_match("@^COM(\\d+):?$@i", $device, $matches)
108 | and $this->_exec(
109 | exec("mode " . $device . " xon=on BAUD=9600")
110 | ) === 0
111 | ) {
112 | $this->_winDevice = "COM" . $matches[1];
113 | $this->_device = "\\.com" . $matches[1];
114 | $this->_dState = SERIAL_DEVICE_SET;
115 |
116 | return true;
117 | }
118 | }
119 |
120 | trigger_error("Specified serial port is not valid", E_USER_WARNING);
121 |
122 | return false;
123 | } else {
124 | trigger_error("You must close your device before to set an other " .
125 | "one", E_USER_WARNING);
126 |
127 | return false;
128 | }
129 | }
130 |
131 | /**
132 | * Opens the device for reading and/or writing.
133 | *
134 | * @param string $mode Opening mode : same parameter as fopen()
135 | * @return bool
136 | */
137 | public function deviceOpen($mode = "r+b")
138 | {
139 | if ($this->_dState === SERIAL_DEVICE_OPENED) {
140 | trigger_error("The device is already opened", E_USER_NOTICE);
141 |
142 | return true;
143 | }
144 |
145 | if ($this->_dState === SERIAL_DEVICE_NOTSET) {
146 | trigger_error(
147 | "The device must be set before to be open",
148 | E_USER_WARNING
149 | );
150 |
151 | return false;
152 | }
153 |
154 | if (!preg_match("@^[raw]\\+?b?$@", $mode)) {
155 | trigger_error(
156 | "Invalid opening mode : ".$mode.". Use fopen() modes.",
157 | E_USER_WARNING
158 | );
159 |
160 | return false;
161 | }
162 |
163 | $this->_dHandle = @fopen($this->_device, $mode);
164 |
165 | if ($this->_dHandle !== false) {
166 | stream_set_blocking($this->_dHandle, 0);
167 | $this->_dState = SERIAL_DEVICE_OPENED;
168 |
169 | return true;
170 | }
171 |
172 | $this->_dHandle = null;
173 | trigger_error("Unable to open the device", E_USER_WARNING);
174 |
175 | return false;
176 | }
177 |
178 | /**
179 | * Closes the device
180 | *
181 | * @return bool
182 | */
183 | public function deviceClose()
184 | {
185 | if ($this->_dState !== SERIAL_DEVICE_OPENED) {
186 | return true;
187 | }
188 |
189 | if (fclose($this->_dHandle)) {
190 | $this->_dHandle = null;
191 | $this->_dState = SERIAL_DEVICE_SET;
192 |
193 | return true;
194 | }
195 |
196 | trigger_error("Unable to close the device", E_USER_ERROR);
197 |
198 | return false;
199 | }
200 |
201 | //
202 | // OPEN/CLOSE DEVICE SECTION -- {STOP}
203 | //
204 |
205 | //
206 | // CONFIGURE SECTION -- {START}
207 | //
208 |
209 | /**
210 | * Configure the Baud Rate
211 | * Possible rates : 110, 150, 300, 600, 1200, 2400, 4800, 9600, 38400,
212 | * 57600 and 115200.
213 | *
214 | * @param int $rate the rate to set the port in
215 | * @return bool
216 | */
217 | public function confBaudRate($rate)
218 | {
219 | if ($this->_dState !== SERIAL_DEVICE_SET) {
220 | trigger_error("Unable to set the baud rate : the device is " .
221 | "either not set or opened", E_USER_WARNING);
222 |
223 | return false;
224 | }
225 |
226 | $validBauds = array (
227 | 110 => 11,
228 | 150 => 15,
229 | 300 => 30,
230 | 600 => 60,
231 | 1200 => 12,
232 | 2400 => 24,
233 | 4800 => 48,
234 | 9600 => 96,
235 | 19200 => 19,
236 | 38400 => 38400,
237 | 57600 => 57600,
238 | 115200 => 115200
239 | );
240 |
241 | if (isset($validBauds[$rate])) {
242 | if ($this->_os === "linux") {
243 | $ret = $this->_exec(
244 | "stty -F " . $this->_device . " " . (int) $rate,
245 | $out
246 | );
247 | } elseif ($this->_os === "osx") {
248 | $ret = $this->_exec(
249 | "stty -f " . $this->_device . " " . (int) $rate,
250 | $out
251 | );
252 | } elseif ($this->_os === "windows") {
253 | $ret = $this->_exec(
254 | "mode " . $this->_winDevice . " BAUD=" . $validBauds[$rate],
255 | $out
256 | );
257 | } else {
258 | return false;
259 | }
260 |
261 | if ($ret !== 0) {
262 | trigger_error(
263 | "Unable to set baud rate: " . $out[1],
264 | E_USER_WARNING
265 | );
266 |
267 | return false;
268 | }
269 |
270 | return true;
271 | } else {
272 | return false;
273 | }
274 | }
275 |
276 | /**
277 | * Configure parity.
278 | * Modes : odd, even, none
279 | *
280 | * @param string $parity one of the modes
281 | * @return bool
282 | */
283 | public function confParity($parity)
284 | {
285 | if ($this->_dState !== SERIAL_DEVICE_SET) {
286 | trigger_error(
287 | "Unable to set parity : the device is either not set or opened",
288 | E_USER_WARNING
289 | );
290 |
291 | return false;
292 | }
293 |
294 | $args = array(
295 | "none" => "-parenb",
296 | "odd" => "parenb parodd",
297 | "even" => "parenb -parodd",
298 | );
299 |
300 | if (!isset($args[$parity])) {
301 | trigger_error("Parity mode not supported", E_USER_WARNING);
302 |
303 | return false;
304 | }
305 |
306 | if ($this->_os === "linux") {
307 | $ret = $this->_exec(
308 | "stty -F " . $this->_device . " " . $args[$parity],
309 | $out
310 | );
311 | } elseif ($this->_os === "osx") {
312 | $ret = $this->_exec(
313 | "stty -f " . $this->_device . " " . $args[$parity],
314 | $out
315 | );
316 | } else {
317 | $ret = $this->_exec(
318 | "mode " . $this->_winDevice . " PARITY=" . $parity[0],
319 | $out
320 | );
321 | }
322 |
323 | if ($ret === 0) {
324 | return true;
325 | }
326 |
327 | trigger_error("Unable to set parity : " . $out[1], E_USER_WARNING);
328 |
329 | return false;
330 | }
331 |
332 | /**
333 | * Sets the length of a character.
334 | *
335 | * @param int $int length of a character (5 <= length <= 8)
336 | * @return bool
337 | */
338 | public function confCharacterLength($int)
339 | {
340 | if ($this->_dState !== SERIAL_DEVICE_SET) {
341 | trigger_error("Unable to set length of a character : the device " .
342 | "is either not set or opened", E_USER_WARNING);
343 |
344 | return false;
345 | }
346 |
347 | $int = (int) $int;
348 | if ($int < 5) {
349 | $int = 5;
350 | } elseif ($int > 8) {
351 | $int = 8;
352 | }
353 |
354 | if ($this->_os === "linux") {
355 | $ret = $this->_exec(
356 | "stty -F " . $this->_device . " cs" . $int,
357 | $out
358 | );
359 | } elseif ($this->_os === "osx") {
360 | $ret = $this->_exec(
361 | "stty -f " . $this->_device . " cs" . $int,
362 | $out
363 | );
364 | } else {
365 | $ret = $this->_exec(
366 | "mode " . $this->_winDevice . " DATA=" . $int,
367 | $out
368 | );
369 | }
370 |
371 | if ($ret === 0) {
372 | return true;
373 | }
374 |
375 | trigger_error(
376 | "Unable to set character length : " .$out[1],
377 | E_USER_WARNING
378 | );
379 |
380 | return false;
381 | }
382 |
383 | /**
384 | * Sets the length of stop bits.
385 | *
386 | * @param float $length the length of a stop bit. It must be either 1,
387 | * 1.5 or 2. 1.5 is not supported under linux and on
388 | * some computers.
389 | * @return bool
390 | */
391 | public function confStopBits($length)
392 | {
393 | if ($this->_dState !== SERIAL_DEVICE_SET) {
394 | trigger_error("Unable to set the length of a stop bit : the " .
395 | "device is either not set or opened", E_USER_WARNING);
396 |
397 | return false;
398 | }
399 |
400 | if ($length != 1
401 | and $length != 2
402 | and $length != 1.5
403 | and !($length == 1.5 and $this->_os === "linux")
404 | ) {
405 | trigger_error(
406 | "Specified stop bit length is invalid",
407 | E_USER_WARNING
408 | );
409 |
410 | return false;
411 | }
412 |
413 | if ($this->_os === "linux") {
414 | $ret = $this->_exec(
415 | "stty -F " . $this->_device . " " .
416 | (($length == 1) ? "-" : "") . "cstopb",
417 | $out
418 | );
419 | } elseif ($this->_os === "osx") {
420 | $ret = $this->_exec(
421 | "stty -f " . $this->_device . " " .
422 | (($length == 1) ? "-" : "") . "cstopb",
423 | $out
424 | );
425 | } else {
426 | $ret = $this->_exec(
427 | "mode " . $this->_winDevice . " STOP=" . $length,
428 | $out
429 | );
430 | }
431 |
432 | if ($ret === 0) {
433 | return true;
434 | }
435 |
436 | trigger_error(
437 | "Unable to set stop bit length : " . $out[1],
438 | E_USER_WARNING
439 | );
440 |
441 | return false;
442 | }
443 |
444 | /**
445 | * Configures the flow control
446 | *
447 | * @param string $mode Set the flow control mode. Available modes :
448 | * -> "none" : no flow control
449 | * -> "rts/cts" : use RTS/CTS handshaking
450 | * -> "xon/xoff" : use XON/XOFF protocol
451 | * @return bool
452 | */
453 | public function confFlowControl($mode)
454 | {
455 | if ($this->_dState !== SERIAL_DEVICE_SET) {
456 | trigger_error("Unable to set flow control mode : the device is " .
457 | "either not set or opened", E_USER_WARNING);
458 |
459 | return false;
460 | }
461 |
462 | $linuxModes = array(
463 | "none" => "clocal -crtscts -ixon -ixoff",
464 | "rts/cts" => "-clocal crtscts -ixon -ixoff",
465 | "xon/xoff" => "-clocal -crtscts ixon ixoff"
466 | );
467 | $windowsModes = array(
468 | "none" => "xon=off octs=off rts=on",
469 | "rts/cts" => "xon=off octs=on rts=hs",
470 | "xon/xoff" => "xon=on octs=off rts=on",
471 | );
472 |
473 | if ($mode !== "none" and $mode !== "rts/cts" and $mode !== "xon/xoff") {
474 | trigger_error("Invalid flow control mode specified", E_USER_ERROR);
475 |
476 | return false;
477 | }
478 |
479 | if ($this->_os === "linux") {
480 | $ret = $this->_exec(
481 | "stty -F " . $this->_device . " " . $linuxModes[$mode],
482 | $out
483 | );
484 | } elseif ($this->_os === "osx") {
485 | $ret = $this->_exec(
486 | "stty -f " . $this->_device . " " . $linuxModes[$mode],
487 | $out
488 | );
489 | } else {
490 | $ret = $this->_exec(
491 | "mode " . $this->_winDevice . " " . $windowsModes[$mode],
492 | $out
493 | );
494 | }
495 |
496 | if ($ret === 0) {
497 | return true;
498 | } else {
499 | trigger_error(
500 | "Unable to set flow control : " . $out[1],
501 | E_USER_ERROR
502 | );
503 |
504 | return false;
505 | }
506 | }
507 |
508 | /**
509 | * Sets a setserial parameter (cf man setserial)
510 | * NO MORE USEFUL !
511 | * -> No longer supported
512 | * -> Only use it if you need it
513 | *
514 | * @param string $param parameter name
515 | * @param string $arg parameter value
516 | * @return bool
517 | */
518 | public function setSetserialFlag($param, $arg = "")
519 | {
520 | if (!$this->_ckOpened()) {
521 | return false;
522 | }
523 |
524 | $return = exec(
525 | "setserial " . $this->_device . " " . $param . " " . $arg . " 2>&1"
526 | );
527 |
528 | if ($return[0] === "I") {
529 | trigger_error("setserial: Invalid flag", E_USER_WARNING);
530 |
531 | return false;
532 | } elseif ($return[0] === "/") {
533 | trigger_error("setserial: Error with device file", E_USER_WARNING);
534 |
535 | return false;
536 | } else {
537 | return true;
538 | }
539 | }
540 |
541 | //
542 | // CONFIGURE SECTION -- {STOP}
543 | //
544 |
545 | //
546 | // I/O SECTION -- {START}
547 | //
548 |
549 | /**
550 | * Sends a string to the device
551 | *
552 | * @param string $str string to be sent to the device
553 | * @param float $waitForReply time to wait for the reply (in seconds)
554 | */
555 | public function sendMessage($str, $waitForReply = 0.1)
556 | {
557 | $this->_buffer .= $str;
558 |
559 | if ($this->autoFlush === true) {
560 | $this->serialflush();
561 | }
562 |
563 | usleep((int) ($waitForReply * 1000000));
564 | }
565 |
566 | /**
567 | * Reads the port until no new datas are available, then return the content.
568 | *
569 | * @param int $count Number of characters to be read (will stop before
570 | * if less characters are in the buffer)
571 | * @return string
572 | */
573 | public function readPort($count = 0)
574 | {
575 | if ($this->_dState !== SERIAL_DEVICE_OPENED) {
576 | trigger_error("Device must be opened to read it", E_USER_WARNING);
577 |
578 | return false;
579 | }
580 |
581 | if ($this->_os === "linux" || $this->_os === "osx") {
582 | // Behavior in OSX isn't to wait for new data to recover, but just
583 | // grabs what's there!
584 | // Doesn't always work perfectly for me in OSX
585 | $content = ""; $i = 0;
586 |
587 | if ($count !== 0) {
588 | do {
589 | if ($i > $count) {
590 | $content .= fread($this->_dHandle, ($count - $i));
591 | } else {
592 | $content .= fread($this->_dHandle, 128);
593 | }
594 | } while (($i += 128) === strlen($content));
595 | } else {
596 | do {
597 | $content .= fread($this->_dHandle, 128);
598 | } while (($i += 128) === strlen($content));
599 | }
600 |
601 | return $content;
602 | } elseif ($this->_os === "windows") {
603 | // Windows port reading procedures still buggy
604 | $content = ""; $i = 0;
605 |
606 | if ($count !== 0) {
607 | do {
608 | if ($i > $count) {
609 | $content .= fread($this->_dHandle, ($count - $i));
610 | } else {
611 | $content .= fread($this->_dHandle, 128);
612 | }
613 | } while (($i += 128) === strlen($content));
614 | } else {
615 | do {
616 | $content .= fread($this->_dHandle, 128);
617 | } while (($i += 128) === strlen($content));
618 | }
619 |
620 | return $content;
621 | }
622 |
623 | return false;
624 | }
625 |
626 | /**
627 | * Flushes the output buffer
628 | * Renamed from flush for osx compat. issues
629 | *
630 | * @return bool
631 | */
632 | public function serialflush()
633 | {
634 | if (!$this->_ckOpened()) {
635 | return false;
636 | }
637 |
638 | if (fwrite($this->_dHandle, $this->_buffer) !== false) {
639 | $this->_buffer = "";
640 |
641 | return true;
642 | } else {
643 | $this->_buffer = "";
644 | trigger_error("Error while sending message", E_USER_WARNING);
645 |
646 | return false;
647 | }
648 | }
649 |
650 | //
651 | // I/O SECTION -- {STOP}
652 | //
653 |
654 | //
655 | // INTERNAL TOOLKIT -- {START}
656 | //
657 |
658 | public function _ckOpened()
659 | {
660 | if ($this->_dState !== SERIAL_DEVICE_OPENED) {
661 | trigger_error("Device must be opened", E_USER_WARNING);
662 |
663 | return false;
664 | }
665 |
666 | return true;
667 | }
668 |
669 | public function _ckClosed()
670 | {
671 | if ($this->_dState === SERIAL_DEVICE_OPENED) {
672 | trigger_error("Device must be closed", E_USER_WARNING);
673 |
674 | return false;
675 | }
676 |
677 | return true;
678 | }
679 |
680 | public function _exec($cmd, &$out = null)
681 | {
682 | $desc = array(
683 | 1 => array("pipe", "w"),
684 | 2 => array("pipe", "w")
685 | );
686 |
687 | $proc = proc_open($cmd, $desc, $pipes);
688 |
689 | $ret = stream_get_contents($pipes[1]);
690 | $err = stream_get_contents($pipes[2]);
691 |
692 | fclose($pipes[1]);
693 | fclose($pipes[2]);
694 |
695 | $retVal = proc_close($proc);
696 |
697 | if (func_num_args() == 2) $out = array($ret, $err);
698 | return $retVal;
699 | }
700 |
701 | //
702 | // INTERNAL TOOLKIT -- {STOP}
703 | //
704 | }
705 |
--------------------------------------------------------------------------------
/PhpSerialModbus.php:
--------------------------------------------------------------------------------
1 | serial = new PhpSerial();
46 | }
47 |
48 | // Initialize serial port with specified parameters
49 | public function deviceInit($port='/dev/ttyUSB0', $baud=115200, $parity='none', $char=8, $sbits=1, $flow='none')
50 | {
51 | $this->serial->deviceSet($port);
52 | $this->serial->confBaudRate($baud);
53 | $this->serial->confParity($parity);
54 | $this->serial->confCharacterLength($char);
55 | $this->serial->confStopBits($sbits);
56 | $this->serial->confFlowControl($flow);
57 | exec('stty -F '.$port.' -brkint -icrnl -imaxbel -opost -isig -icanon -echo -echoe');
58 | return $this->serial->_dState;
59 | }
60 |
61 | // Open serial port
62 | public function deviceOpen()
63 | {
64 | $this->serial->deviceOpen();
65 | return $this->serial->_dState;
66 | }
67 |
68 | // Close serial port
69 | public function deviceClose()
70 | {
71 | $this->serial->deviceClose();
72 | return $this->serial->_dState;
73 | }
74 |
75 | // Calculate CRC16 (ModBus)
76 | public function crc16($data)
77 | {
78 | $crc = 0xFFFF;
79 | for ($i = 0; $i < strlen($data); $i++)
80 | {
81 | $crc ^=ord($data[$i]);
82 | for ($j = 8; $j !=0; $j--)
83 | {
84 | if (($crc & 0x0001) !=0)
85 | {
86 | $crc >>= 1;
87 | $crc ^= 0xA001;
88 | }
89 | else
90 | $crc >>= 1;
91 | }
92 | }
93 | $highCrc=floor($crc/256);
94 | $lowCrc=($crc-$highCrc*256);
95 | return chr($lowCrc).chr($highCrc);
96 | }
97 |
98 | // Convert bin string to readable hex
99 | private function bin2hexString ($binString)
100 | {
101 | $hexString=bin2hex($binString);
102 | $hexString=chunk_split($hexString,2,"\\x");
103 | $hexString= "\\x" . substr($hexString,0,-2);
104 | return $hexString;
105 | }
106 |
107 |
108 | private function Hex2String($hex){
109 | $string='';
110 | for ($i=0; $i < strlen($hex)-1; $i+=2){
111 | $string .= chr(hexdec($hex[$i].$hex[$i+1]));
112 | }
113 | return $string;
114 | }
115 |
116 | //convert from uint16_t to int16_t or any other format
117 | public function convertResponse($input, $format = 'uint16_t'){
118 |
119 | $output = [];
120 |
121 | for($i = 0; $i < count($input); $i+=2)
122 | {
123 |
124 | $output[$i] = hexdec($input[$i].$input[($i+1)]);
125 |
126 | //conv. for 16-bit signed integer
127 | if($format == 'int16_t'){
128 | if($output[$i] > 32767) $output[$i] -= 65536;
129 | }
130 | else if($format == 'str')
131 | {
132 | $output[$i] = $this->Hex2String($input[$i].$input[($i+1)]);
133 | }
134 | }
135 |
136 | return array_values($output);
137 | }
138 |
139 | //send raw query
140 | public function sendRawQuery ($string, $response = true) {
141 | $this->serial->sendMessage($string);
142 | if ($this->debug) print "DEBUG [query sent]: ".$this->bin2hexString($string)."\n";
143 | if ($response) return $this->getResponse(); else return 1;
144 | }
145 |
146 | // Send Modbus query to slave
147 | public function sendQuery ($slaveId, $functionCode, $registerAddress, $regCountOrData, $response = true, $validateWrite = false)
148 | {
149 | if ( ($functionCode > 6 ) || ($functionCode < 1) ) {
150 | if ($this->debug) print "DEBUG [invalid function code]\n";
151 | return 0;
152 | }
153 |
154 | if ($functionCode < 5) $regCountOrData = dechex($regCountOrData);
155 |
156 | $regHighByte=hexdec(substr($registerAddress,0,2));
157 | $regLowByte=hexdec(substr($registerAddress,2));
158 |
159 | $regCountOrData = str_pad($regCountOrData,4,"0",STR_PAD_LEFT);
160 |
161 | $rcdHighByte=hexdec(substr($regCountOrData,0,2));
162 | $rcdLowByte=hexdec(substr($regCountOrData,2));
163 |
164 | // Create query and convert to a binary string
165 | $query=array($slaveId, hexdec($functionCode), $regHighByte, $regLowByte, $rcdHighByte, $rcdLowByte);
166 | $queryString=implode(array_map("chr",$query));
167 |
168 | // Calculate CRC
169 | $queryString.=$this->crc16($queryString);
170 |
171 | if ($this->debug) print "DEBUG [query sent]: ".$this->bin2hexString($queryString)."\n";
172 |
173 | // Send over serial port
174 | $this->serial->sendMessage($queryString);
175 |
176 | // Modbus slave returns command on successful write
177 | if ($validateWrite) return $this->getResponse(false, 0, 0, $this->bin2hexString($queryString));
178 |
179 | if ($response) return $this->getResponse(); else return 1;
180 | }
181 |
182 | // Read response from slave
183 | public function getResponse ($raw=false,$offsetl=0,$offsetr=0, $sentQuery=null)
184 | {
185 | // Time started (for timing)
186 | $startTime = microtime(true);
187 |
188 | $responseString = '';
189 |
190 | // Allow until one second for the respone
191 | while(((microtime(true)-$startTime)<1) && ($responseString=='') )
192 | {
193 | // Read serial port buffer (with three seconds timeout)
194 | while( ($byte = $this->serial->ReadPort()) && ((microtime(true)-$startTime)<3.0)) {
195 | $responseString=$responseString.$byte;
196 | usleep(50);
197 | }
198 | }
199 |
200 | if ($this->debug) print "DEBUG [response received]: ".$this->bin2hexString($responseString)."\n";
201 |
202 | //validate write command by comparing response from modbus slave, if response is equal to sent query from master -> write was successful
203 | if ($this->debug && $sentQuery !== null) print "DEBUG [write verification will be done against sent query]: ".$sentQuery."\n";
204 | if ($sentQuery !== null)
205 | {
206 | if ($sentQuery == $this->bin2hexString($responseString))
207 | {
208 | if ($this->debug) print "DEBUG [ sent - received -> MATCH!] \n";
209 | return true;
210 | }
211 | else
212 | {
213 | if ($this->debug) print "DEBUG [ sent - received -> NO MATCH!] \n";
214 | return false;
215 | }
216 | }
217 |
218 | if ($raw) return $responseString;
219 |
220 | $stringLength=strlen($responseString);
221 |
222 | // If we have at least 5 bytes...
223 | if ($stringLength>=5)
224 | {
225 | // ...but no more than 5
226 | if ($stringLength==5) {
227 | if ($this->debug) print "DEBUG [no valid data]\n";
228 | return 0;
229 | }
230 |
231 | // CRC Check
232 | $checkArray=(str_split($responseString,strlen($responseString)-2));
233 | $crc=$this->crc16($checkArray[0]);
234 | if ($crc!=$checkArray[1]) {
235 | if ($this->debug) print "DEBUG [crc check failed]: (expected ".$this->bin2hexString($crc)." received ".$this->bin2hexString($checkArray[1]).")\n";
236 | return 0;
237 | }
238 |
239 | // Convert string in array of bytes
240 | $responseArray = str_split($responseString);
241 | // This is the byte containing the numbere of data bytes
242 | $bytesNum = hexdec(bin2hex($responseArray[2]));
243 |
244 | // Create a new array with data without headers and CRC
245 | $responseData = array_slice($responseArray,3+$offsetl,$bytesNum-$offsetr);
246 |
247 | if ($this->debug) print "DEBUG [data]: ".$this->bin2hexString(implode($responseData))."\n";
248 |
249 | // Return an array with hex data bytes
250 | return array_map("bin2hex",$responseData);
251 | } else
252 | {
253 | if ($this->debug) print "DEBUG [no response]\n";
254 | return 0;
255 | }
256 | return 0;
257 | }
258 | }
259 | ?>
260 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Php Serial Modbus
2 | ======
3 |
4 | This class is an implementation of the [ModBus RTU serial protocol][modbus] (for example via RS485 port) acting as ModBus master allowing easy-to-use ModBus communication.
5 |
6 | Features
7 | -------
8 | - Native support of function codes 01, 02, 03, 04, 05, 06
9 | - Additional function codes allowed by advanced methods
10 | - Simple single line method for communicating with slave
11 | - Timeout control
12 | - CRC check
13 |
14 | Quick start example
15 | ------
16 | ```php
17 | deviceInit('/dev/ttyUSB0',115200,'none',8,1,'none');
21 | $modbus->deviceOpen();
22 | $result=$modbus->sendQuery(1,4,"310C",3);
23 | print_r($result);
24 | print "\nVoltage: ".(hexdec($result[0].$result[1])/100);
25 | $modbus->deviceClose();
26 | ?>
27 | ```
28 | This example will query the slave with id "1" asking the contents of Input Registers 310C, 310D and 310E and will produce the following output (on a Raspberry Pi connected via USB/RS485 converter to my Epever/Epsolar Tracer 2215BN MPPT solar charger controller):
29 | ```SH
30 | Array
31 | (
32 | [0] => 04
33 | [1] => be
34 | [2] => 00
35 | [3] => 44
36 | [4] => 03
37 | [5] => 39
38 | )
39 |
40 | Voltage: 12.14
41 | ```
42 | The output is an array containing the bytes received by the slave in HEX format. Modbus registry datas are 16bit (8bit for Hi byte and 8bit for Lo byte) so the array count is 6. In order to convert this HEX data to readable format you have to convert the bytes received two by two. In the above example in order to get decimal contents of registry 310C, we have to concatenate the first two bytes received and we will obtain "04be", that in decimal is 1214 (the battery voltage * 100).
43 |
44 |
45 | Class methods and properties
46 | -------
47 | **deviceInit** ($port='/dev/ttyUSB0', $baud=115200, $parity='none', $char=8, $sbits=1, $flow='none')
48 | >Initialize the serial port with the given parameters
49 |
50 | **deviceOpen** ()
51 | >Open the serial port
52 |
53 | **sendQuery** ($slaveId, $functionCode, $registerAddress, $regNumOrCount, $response = true)
54 | >Send a query to the ModBus slave where $slaveid is the ID of the device, $functionCode is the ModBus functions code, $registerAddress is HEX address of the register we want to read/write, $regCountOrData is the count of register we want to read or the data we want to write and $getResponse (default is true) is a boolean to control if the datas have to return by the sendQuery() method or by the successive readResponse() method. The returned data is an array of HEX bytes without headers and without CRC.
55 |
56 | **readResponse** ($raw=false,$offsetl=0,$offsetr=0)
57 | >Get response from serial port. Useful for some advanced use. You can send the query with the command sendQuery() and get response after a while. If $raw is set to true you will get "raw" binary response with headers and with CRC bytes, useful for advanced data manipulation. You can optionally insert a left offset ($offsetl) and a right offset ($offsetr) on the received data (only if not in "raw" mode.
58 |
59 | **sendRawQuery** ($string, $response = true)
60 | >This method permits to send a raw query without functions or CRC control. Very useful for advanced use and for non-standard Modbus functions codes. It sends the $strings to the serial device (You can use the format \x - For example the command sendQuery(1,4,"310C",3) is equivalent to sendRawQuery("\x01\x04\x31\x0c\x00\x03\x7e\xf4")
61 |
62 | **crc16** ($data)
63 | >This function return the binary CRC16 (ModBus) of $data. Userful with sendRawQuery or for additional CRC control
64 |
65 | **$debug** = false
66 | >Setting this property to TRUE will print HEX data sent and received through serial port. Useful for analyze raw data.
67 |
68 | Note
69 | ------
70 | If you use this class in HTTPD and not CLI don't forget to give the user the permission to use serial port (for example with Apache on Debian: usermod -a -G dialout www-data)
71 |
72 | Contributors
73 | --------
74 | This project is developed by Luca Soltoggio and is based on the class [PhpSerial] by Rémy Sanchez / Rizwan Kassim and partially inspired by Francesco Vettore's [blog][vettore].
75 |
76 | http://arduinoelectronics.wordpress.com/ ~ http://minibianpi.wordpress.com
77 |
78 | ## Help us
79 |
80 | If you find this project useful and would like to support its development, consider making a donation. Any contribution is greatly appreciated!
81 |
82 | **Bitcoin (BTC) Addresses:**
83 | - **1LToggio**f3rNUTCemJZSsxd1qubTYoSde6
84 | - **3LToggio**7Xx8qMsjCFfiarV4U2ZR9iU9ob
85 |
86 | License
87 | ------
88 | Copyright (C) 2016 Luca Soltoggio
89 |
90 | This program is free software; you can redistribute it and/or modify
91 | it under the terms of the GNU General Public License as published by
92 | the Free Software Foundation; either version 2 of the License, or
93 | (at your option) any later version.
94 |
95 | This program is distributed in the hope that it will be useful,
96 | but WITHOUT ANY WARRANTY; without even the implied warranty of
97 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
98 | GNU General Public License for more details.
99 |
100 | You should have received a copy of the GNU General Public License along
101 | with this program; if not, write to the Free Software Foundation, Inc.,
102 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
103 |
104 | [//]: #
105 |
106 | [phpserial]:
107 | [vettore]:
108 | [modbus]: http://modbustools.com/modbus.html
109 |
--------------------------------------------------------------------------------
/example.php:
--------------------------------------------------------------------------------
1 | 04
11 | [1] => b8
12 | [2] => 00
13 | [3] => 3d
14 | [4] => 02
15 | [5] => e0
16 | )
17 | DEBUG [query sent]: \x01\x04\x31\x0c\x00\x03\x7e\xf4
18 | DEBUG [response received]: \x01\x04\x06\x04\xb7\x00\x49\x03\x71\x84\x0f
19 | ▒Iq▒
20 | */
21 |
22 | // Include Php Serial Modbus Class
23 | require 'PhpSerialModbus.php';
24 |
25 | // Crate an instance of the class
26 | $modbus = new PhpSerialModbus();
27 |
28 | // Initialize port
29 | $modbus->deviceInit('/dev/ttyUSB0',115200,'none',8,1,'none');
30 |
31 | // Open port
32 | $modbus->deviceOpen();
33 |
34 | // Enable debug
35 | $modbus->debug = true;
36 |
37 | // Send query to slave 1 with function code 4, asking for 3 registers from 310C
38 | $result=$modbus->sendQuery(1,4,"310C",3);
39 | print_r($result);
40 |
41 | // Send raw query
42 | $rawquery="\x01\x04\x31\x0c\x00\x03";
43 | $modbus->sendRawQuery($rawquery.$modbus->crc16($rawquery),false);
44 |
45 | // Get response with raw data
46 | $result=$modbus->getResponse(true);
47 | print_r($result);
48 |
49 | // Close device
50 | $modbus->deviceClose();
51 | ?>
--------------------------------------------------------------------------------