├── .gitignore
├── ACQ810.yml
├── ACS310.yml
├── Documentacion
├── Modbus_Logger ABB ACQ810.pdf
└── Modbus_Logger ABB ACS310.pdf
├── LICENSE
├── Modbus-Gateway-esp8266
├── .gitignore
├── 3D Case for PCB
│ ├── Case Bridge TCP-RTU V1-230V.FCStd
│ ├── Case Bridge TCP-RTU V1.FCStd
│ ├── Case Bridge TCP-RTU V2.FCStd
│ ├── Case Bridge v1 230V TOP.stl
│ ├── Case Bridge v1 230V.stl
│ ├── Case Bridge v1 TOP.stl
│ ├── Case Bridge v1.stl
│ ├── Case Bridge v2 TOP.stl
│ ├── Case Bridge v2.stl
│ └── README.md
├── Connection examples
│ ├── README.md
│ ├── esp-485_5V.png
│ └── esp8266-485.jpg
├── LICENSE
├── Library Modbus RTU ESP8266
│ ├── ModBusMasterMax485
│ │ ├── ModBusMasterMax485.cpp
│ │ ├── ModBusMasterMax485.h
│ │ └── keywords.txt
│ └── README.md
├── ModbusTCPSlaveRTUMasterMAX485
│ ├── ModbusTCPSlaveRTUMasterMAX485.ino
│ └── README.md
├── PCB
│ ├── ESP8266-RS485_DIP-230.fzz
│ ├── ESP8266-RS485_DIP-Gerber.zip
│ ├── ESP8266-RS485_DIP-V2-Gerber.zip
│ ├── ESP8266-RS485_DIP-V2.fzz
│ ├── ESP8266-RS485_DIP.fzz
│ ├── ESP8266-RS485_DIP_230V-Gerber.zip
│ └── README.md
└── README.md
├── Phyton3, modbus_tk tcp, esp8266, multi_influx
├── README.md
├── Recommended mount for Orange Pi Zero
└── Din_Mount_Orange_Pi_Zero.zip
├── Recommended mount for Raspberry Pi
└── Raspberry_Pi_Wall_Mounted_Case_-_Ideal_for_Pi-Hole.zip
├── VACON20.yml
├── devices.yml
├── influx_config.yml
├── read_modbus_device.py
├── setup.py
└── start_status_reboot.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 | MANIFEST
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 | .pytest_cache/
49 |
50 | # Translations
51 | *.mo
52 | *.pot
53 |
54 | # Django stuff:
55 | *.log
56 | local_settings.py
57 | db.sqlite3
58 |
59 | # Flask stuff:
60 | instance/
61 | .webassets-cache
62 |
63 | # Scrapy stuff:
64 | .scrapy
65 |
66 | # Sphinx documentation
67 | docs/_build/
68 |
69 | # PyBuilder
70 | target/
71 |
72 | # Jupyter Notebook
73 | .ipynb_checkpoints
74 |
75 | # pyenv
76 | .python-version
77 |
78 | # celery beat schedule file
79 | celerybeat-schedule
80 |
81 | # SageMath parsed files
82 | *.sage.py
83 |
84 | # Environments
85 | .env
86 | .venv
87 | env/
88 | venv/
89 | ENV/
90 | env.bak/
91 | venv.bak/
92 |
93 | # Spyder project settings
94 | .spyderproject
95 | .spyproject
96 |
97 | # Rope project settings
98 | .ropeproject
99 |
100 | # mkdocs documentation
101 | /site
102 |
103 | # mypy
104 | .mypy_cache/
105 |
--------------------------------------------------------------------------------
/ACQ810.yml:
--------------------------------------------------------------------------------
1 | E/S datos 1:
2 | - 4 # Adress dec data
3 | - 1 # Length word
4 | - 3 # Data Type. 1=Float(ABCD), 2=Long(ABCD), 3=Integer, 4=Long(CDAB), 5=Word (Unsigned Int), 6=Dword (Unsigned Long), 7=Float(CDAB)*
5 | E/S datos 2:
6 | - 5
7 | - 1
8 | - 3
9 | E/S datos 3:
10 | - 6
11 | - 1
12 | - 3
13 | E/S datos 4:
14 | - 7
15 | - 1
16 | - 3
17 | E/S datos 5:
18 | - 8
19 | - 1
20 | - 3
21 | E/S datos 6:
22 | - 9
23 | - 1
24 | - 3
25 | E/S datos 7:
26 | - 10
27 | - 1
28 | - 3
29 | E/S datos 8:
30 | - 11
31 | - 1
32 | - 3
33 | E/S datos 9:
34 | - 12
35 | - 1
36 | - 3
37 | E/S datos 10:
38 | - 13
39 | - 1
40 | - 3
41 | E/S datos 11:
42 | - 14
43 | - 1
44 | - 3
45 | E/S datos 12:
46 | - 15
47 | - 1
48 | - 3
49 | E/S datos 13:
50 | - 54
51 | - 1
52 | - 3
53 | E/S datos 14:
54 | - 55
55 | - 1
56 | - 3
57 | E/S datos 15:
58 | - 56
59 | - 1
60 | - 3
61 | E/S datos 16:
62 | - 57
63 | - 1
64 | - 3
65 | E/S datos 17:
66 | - 58
67 | - 1
68 | - 3
69 | E/S datos 18:
70 | - 59
71 | - 1
72 | - 3
73 | E/S datos 19:
74 | - 60
75 | - 1
76 | - 3
77 | E/S datos 20:
78 | - 61
79 | - 1
80 | - 3
81 | E/S datos 21:
82 | - 62
83 | - 1
84 | - 3
85 | E/S datos 22:
86 | - 63
87 | - 1
88 | - 3
89 | E/S datos 23:
90 | - 64
91 | - 1
92 | - 3
93 | E/S datos 24:
94 | - 65
95 | - 1
96 | - 3
--------------------------------------------------------------------------------
/ACS310.yml:
--------------------------------------------------------------------------------
1 | PAR BCI 10 :
2 | - 4 # Adress dec data
3 | - 1 # Length word
4 | - 3 # Data Type. 1=Float(ABCD), 2=Long(ABCD), 3=Integer, 4=Long(CDAB), 5=Word (Unsigned Int), 6=Dword (Unsigned Long), 7=Float(CDAB)*
5 | PAR BCI 11 :
6 | - 5
7 | - 1
8 | - 3
9 | PAR BCI 12 :
10 | - 6
11 | - 1
12 | - 3
13 | PAR BCI 13 :
14 | - 7
15 | - 1
16 | - 3
17 | PAR BCI 14 :
18 | - 8
19 | - 1
20 | - 3
21 | PAR BCI 15 :
22 | - 9
23 | - 1
24 | - 3
25 | PAR BCI 16 :
26 | - 10
27 | - 1
28 | - 3
29 | PAR BCI 17 :
30 | - 11
31 | - 1
32 | - 3
--------------------------------------------------------------------------------
/Documentacion/Modbus_Logger ABB ACQ810.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Documentacion/Modbus_Logger ABB ACQ810.pdf
--------------------------------------------------------------------------------
/Documentacion/Modbus_Logger ABB ACS310.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Documentacion/Modbus_Logger ABB ACS310.pdf
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/.gitignore:
--------------------------------------------------------------------------------
1 | # Prerequisites
2 | *.d
3 |
4 | # Compiled Object files
5 | *.slo
6 | *.lo
7 | *.o
8 | *.obj
9 |
10 | # Precompiled Headers
11 | *.gch
12 | *.pch
13 |
14 | # Compiled Dynamic libraries
15 | *.so
16 | *.dylib
17 | *.dll
18 |
19 | # Fortran module files
20 | *.mod
21 | *.smod
22 |
23 | # Compiled Static libraries
24 | *.lai
25 | *.la
26 | *.a
27 | *.lib
28 |
29 | # Executables
30 | *.exe
31 | *.out
32 | *.app
33 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge TCP-RTU V1-230V.FCStd:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge TCP-RTU V1-230V.FCStd
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge TCP-RTU V1.FCStd:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge TCP-RTU V1.FCStd
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge TCP-RTU V2.FCStd:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge TCP-RTU V2.FCStd
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1 230V TOP.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1 230V TOP.stl
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1 230V.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1 230V.stl
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1 TOP.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1 TOP.stl
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v1.stl
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v2 TOP.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v2 TOP.stl
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v2.stl:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/3D Case for PCB/Case Bridge v2.stl
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/3D Case for PCB/README.md:
--------------------------------------------------------------------------------
1 | # 3D Printed case for PCB boards.
2 |
3 | Available stl and freecad file (in case you want to customize or improve)
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Connection examples/README.md:
--------------------------------------------------------------------------------
1 | # Examples of how to connect an ESP-01 and MAX485 obtained from the internet.
2 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Connection examples/esp-485_5V.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/Connection examples/esp-485_5V.png
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Connection examples/esp8266-485.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/Connection examples/esp8266-485.jpg
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Library Modbus RTU ESP8266/ModBusMasterMax485/ModBusMasterMax485.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | @file
3 | Arduino library for communicating with Modbus slaves over RS232/485 (via RTU protocol).
4 | */
5 | /*
6 |
7 | ModbusMaster.cpp - Arduino library for communicating with Modbus slaves
8 | over RS232/485 (via RTU protocol).
9 |
10 | This file is part of ModbusMaster.
11 |
12 | ModbusMaster is free software: you can redistribute it and/or modify
13 | it under the terms of the GNU General Public License as published by
14 | the Free Software Foundation, either version 3 of the License, or
15 | (at your option) any later version.
16 |
17 | ModbusMaster is distributed in the hope that it will be useful,
18 | but WITHOUT ANY WARRANTY; without even the implied warranty of
19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 | GNU General Public License for more details.
21 |
22 | You should have received a copy of the GNU General Public License
23 | along with ModbusMaster. If not, see .
24 |
25 | Written by Doc Walker (Rx)
26 | Copyright © 2009-2013 Doc Walker <4-20ma at wvfans dot net>
27 |
28 | Modificado para esp8266
29 | - Function crc16
30 | - Function makeWord
31 | - Function half duplex RS485_ENABLE_PIN
32 | - Function to auto update slaveID (232 to 485)
33 |
34 | */
35 | #include "ModBusMasterMax485.h"
36 |
37 |
38 | #include "Arduino.h"
39 |
40 |
41 | /* _____PUBLIC FUNCTIONS_____________________________________________________ */
42 |
43 | /**
44 | Constructor.
45 | Creates class object using default serial port 0, Modbus slave ID 1.
46 | @ingroup setup
47 | */
48 | ModBusMasterMax485::ModBusMasterMax485(void)
49 | {
50 | _u8SerialPort = 0;
51 | _u8MBSlave = 1;
52 | }
53 |
54 |
55 | /**
56 | Constructor.
57 |
58 | Creates class object using default serial port 0, specified Modbus slave ID.
59 |
60 | @overload void ModbusMaster::ModbusMaster(uint8_t u8MBSlave)
61 | @param u8MBSlave Modbus slave ID (1..255)
62 | @ingroup setup
63 | */
64 | /*
65 | ModBusMasterMax485::ModBusMasterMax485(uint8_t u8MBSlave)
66 | {
67 | _u8SerialPort = 0;
68 | _u8MBSlave = u8MBSlave;
69 | }
70 | */
71 |
72 | /**
73 | Constructor.
74 |
75 | Creates class object using default serial port 0, specified Modbus slave ID, and specified pin enabled RS485 adapter and enabled function.
76 |
77 | @overload void ModbusMaster::ModbusMaster(uint8_t u8PinEnableTx)
78 | @param u8PinEnableTx gpio pin to half duplex rs485
79 | @ingroup setup
80 | */
81 | ModBusMasterMax485::ModBusMasterMax485(uint8_t u8PinEnableTx)
82 | {
83 | _u8SerialPort = 0;
84 | _u8MBSlave = 1;
85 | _u8PinEnableTx = u8PinEnableTx;
86 | _PinEnableTx = true;
87 | }
88 |
89 | /**
90 | Constructor.
91 |
92 | Creates class object using default serial port 0, specified Modbus slave ID, and specified pin enabled RS485 adapter and enabled function.
93 |
94 | @overload void ModbusMaster::ModbusMaster((uint8_t u8MBSlave, uint8_t u8PinEnableTx)
95 | @param u8MBSlave Modbus slave ID (1..255)
96 | @param u8PinEnableTx gpio pin to half duplex rs485
97 | @ingroup setup
98 | */
99 | /*
100 | ModBusMasterMax485::ModBusMasterMax485(uint8_t u8MBSlave, uint8_t u8PinEnableTx)
101 | {
102 | _u8SerialPort = 0;
103 | _u8MBSlave = u8MBSlave;
104 | _u8PinEnableTx = u8PinEnableTx;
105 | _PinEnableTx = true;
106 |
107 | }
108 | */
109 |
110 | void ModBusMasterMax485::slaveID(uint8_t u8MBSlave)
111 | {
112 | _u8MBSlave = u8MBSlave;
113 | }
114 |
115 | //Function crc16 created for ESP8266 - PDAControl
116 | //http://www.atmel.com/webdoc/AVRLibcReferenceManual/group__util__crc_1ga95371c87f25b0a2497d9cba13190847f.html
117 | // append CRC
118 |
119 | uint16_t _crc16_update2 (uint16_t crc, uint8_t a)
120 | {
121 | int i;
122 |
123 | crc ^= a;
124 | for (i = 0; i < 8; ++i)
125 | {
126 | if (crc & 1)
127 | crc = (crc >> 1) ^ 0xA001;
128 | else
129 | crc = (crc >> 1);
130 | }
131 |
132 | return crc;
133 | }
134 |
135 |
136 |
137 | /**
138 | Initialize class object.
139 |
140 | Sets up the serial port using default 19200 baud rate.
141 | Call once class has been instantiated, typically within setup().
142 |
143 | @ingroup setup
144 | */
145 | void ModBusMasterMax485::begin(void)
146 | {
147 | Serial.begin(9600);
148 |
149 | if (_PinEnableTx){
150 | pinMode(_u8PinEnableTx, OUTPUT); //Enable rs485
151 | digitalWrite(_u8PinEnableTx, HIGH);
152 | }
153 | }
154 |
155 |
156 | /**
157 | Initialize class object.
158 |
159 | Sets up the serial port using specified baud rate.
160 | Call once class has been instantiated, typically within setup().
161 |
162 | @overload ModbusMaster::begin(uint16_t u16BaudRate)
163 | @param u16BaudRate baud rate, in standard increments (300..115200)
164 | @ingroup setup
165 | */
166 | void ModBusMasterMax485::begin(unsigned long BaudRate )
167 | {
168 | // txBuffer = (uint16_t*) calloc(ku8MaxBufferSize, sizeof(uint16_t));
169 | _u8TransmitBufferIndex = 0;
170 | u16TransmitBufferLength = 0;
171 |
172 | delay(100);
173 | Serial.begin(BaudRate);
174 |
175 | if (_PinEnableTx){
176 | pinMode(_u8PinEnableTx, OUTPUT); //Enable rs485
177 | digitalWrite(_u8PinEnableTx, HIGH);
178 | }
179 | }
180 |
181 |
182 | void ModBusMasterMax485::beginTransmission(uint16_t u16Address)
183 | {
184 | _u16WriteAddress = u16Address;
185 | _u8TransmitBufferIndex = 0;
186 | u16TransmitBufferLength = 0;
187 | }
188 |
189 | // eliminate this function in favor of using existing MB request functions
190 | uint8_t ModBusMasterMax485::requestFrom(uint16_t address, uint16_t quantity)
191 | {
192 | uint8_t read;
193 | // clamp to buffer length
194 | if(quantity > ku8MaxBufferSize)
195 | {
196 | quantity = ku8MaxBufferSize;
197 | }
198 | // set rx buffer iterator vars
199 | _u8ResponseBufferIndex = 0;
200 | _u8ResponseBufferLength = read;
201 |
202 | return read;
203 | }
204 |
205 |
206 | void ModBusMasterMax485::sendBit(bool data)
207 | {
208 | uint8_t txBitIndex = u16TransmitBufferLength % 16;
209 | if ((u16TransmitBufferLength >> 4) < ku8MaxBufferSize)
210 | {
211 | if (0 == txBitIndex)
212 | {
213 | _u16TransmitBuffer[_u8TransmitBufferIndex] = 0;
214 | }
215 | bitWrite(_u16TransmitBuffer[_u8TransmitBufferIndex], txBitIndex, data);
216 | u16TransmitBufferLength++;
217 | _u8TransmitBufferIndex = u16TransmitBufferLength >> 4;
218 | }
219 | }
220 |
221 |
222 | void ModBusMasterMax485::send(uint16_t data)
223 | {
224 | if (_u8TransmitBufferIndex < ku8MaxBufferSize)
225 | {
226 | _u16TransmitBuffer[_u8TransmitBufferIndex++] = data;
227 | u16TransmitBufferLength = _u8TransmitBufferIndex << 4;
228 | }
229 | }
230 |
231 |
232 | void ModBusMasterMax485::send(uint32_t data)
233 | {
234 | send(lowWord(data));
235 | send(highWord(data));
236 | }
237 |
238 |
239 | void ModBusMasterMax485::send(uint8_t data)
240 | {
241 | send(uint16_t(data));
242 | }
243 |
244 |
245 |
246 | uint8_t ModBusMasterMax485::available(void)
247 | {
248 | return _u8ResponseBufferLength - _u8ResponseBufferIndex;
249 | }
250 |
251 |
252 | uint16_t ModBusMasterMax485::receive(void)
253 | {
254 | if (_u8ResponseBufferIndex < _u8ResponseBufferLength)
255 | {
256 | return _u16ResponseBuffer[_u8ResponseBufferIndex++];
257 | }
258 | else
259 | {
260 | return 0xFFFF;
261 | }
262 | }
263 |
264 |
265 |
266 |
267 | /**
268 | Set idle time callback function (cooperative multitasking).
269 |
270 | This function gets called in the idle time between transmission of data
271 | and response from slave. Do not call functions that read from the serial
272 | buffer that is used by ModbusMaster. Use of i2c/TWI, 1-Wire, other
273 | serial ports, etc. is permitted within callback function.
274 |
275 | @see ModbusMaster::ModbusMasterTransaction()
276 | */
277 | void ModBusMasterMax485::idle(void (*idle)())
278 | {
279 | _idle = idle;
280 | }
281 |
282 |
283 | /**
284 | Retrieve data from response buffer.
285 |
286 | @see ModbusMaster::clearResponseBuffer()
287 | @param u8Index index of response buffer array (0x00..0x3F)
288 | @return value in position u8Index of response buffer (0x0000..0xFFFF)
289 | @ingroup buffer
290 | */
291 | uint16_t ModBusMasterMax485::getResponseBuffer(uint8_t u8Index)
292 | {
293 | if (u8Index < ku8MaxBufferSize)
294 | {
295 | return _u16ResponseBuffer[u8Index];
296 | }
297 | else
298 | {
299 | return 0xFFFF;
300 | }
301 | }
302 |
303 |
304 | /**
305 | Clear Modbus response buffer.
306 |
307 | @see ModbusMaster::getResponseBuffer(uint8_t u8Index)
308 | @ingroup buffer
309 | */
310 | void ModBusMasterMax485::clearResponseBuffer()
311 | {
312 | uint8_t i;
313 |
314 | for (i = 0; i < ku8MaxBufferSize; i++)
315 | {
316 | _u16ResponseBuffer[i] = 0;
317 | }
318 | }
319 |
320 |
321 | /**
322 | Place data in transmit buffer.
323 |
324 | @see ModbusMaster::clearTransmitBuffer()
325 | @param u8Index index of transmit buffer array (0x00..0x3F)
326 | @param u16Value value to place in position u8Index of transmit buffer (0x0000..0xFFFF)
327 | @return 0 on success; exception number on failure
328 | @ingroup buffer
329 | */
330 | uint8_t ModBusMasterMax485::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value)
331 | {
332 | if (u8Index < ku8MaxBufferSize)
333 | {
334 | _u16TransmitBuffer[u8Index] = u16Value;
335 | return ku8MBSuccess;
336 | }
337 | else
338 | {
339 | return ku8MBIllegalDataAddress;
340 | }
341 | }
342 |
343 |
344 | /**
345 | Clear Modbus transmit buffer.
346 |
347 | @see ModbusMaster::setTransmitBuffer(uint8_t u8Index, uint16_t u16Value)
348 | @ingroup buffer
349 | */
350 | void ModBusMasterMax485::clearTransmitBuffer()
351 | {
352 | uint8_t i;
353 |
354 | for (i = 0; i < ku8MaxBufferSize; i++)
355 | {
356 | _u16TransmitBuffer[i] = 0;
357 | }
358 | }
359 |
360 |
361 | /**
362 | Modbus function 0x01 Read Coils.
363 |
364 | This function code is used to read from 1 to 2000 contiguous status of
365 | coils in a remote device. The request specifies the starting address,
366 | i.e. the address of the first coil specified, and the number of coils.
367 | Coils are addressed starting at zero.
368 |
369 | The coils in the response buffer are packed as one coil per bit of the
370 | data field. Status is indicated as 1=ON and 0=OFF. The LSB of the first
371 | data word contains the output addressed in the query. The other coils
372 | follow toward the high order end of this word and from low order to high
373 | order in subsequent words.
374 |
375 | If the returned quantity is not a multiple of sixteen, the remaining
376 | bits in the final data word will be padded with zeros (toward the high
377 | order end of the word).
378 |
379 | @param u16ReadAddress address of first coil (0x0000..0xFFFF)
380 | @param u16BitQty quantity of coils to read (1..2000, enforced by remote device)
381 | @return 0 on success; exception number on failure
382 | @ingroup discrete
383 | */
384 | uint8_t ModBusMasterMax485::readCoils(uint16_t u16ReadAddress, uint16_t u16BitQty)
385 | {
386 | _u16ReadAddress = u16ReadAddress;
387 | _u16ReadQty = u16BitQty;
388 | return ModbusMasterTransaction(ku8MBReadCoils);
389 | }
390 |
391 |
392 | /**
393 | Modbus function 0x02 Read Discrete Inputs.
394 |
395 | This function code is used to read from 1 to 2000 contiguous status of
396 | discrete inputs in a remote device. The request specifies the starting
397 | address, i.e. the address of the first input specified, and the number
398 | of inputs. Discrete inputs are addressed starting at zero.
399 |
400 | The discrete inputs in the response buffer are packed as one input per
401 | bit of the data field. Status is indicated as 1=ON; 0=OFF. The LSB of
402 | the first data word contains the input addressed in the query. The other
403 | inputs follow toward the high order end of this word, and from low order
404 | to high order in subsequent words.
405 |
406 | If the returned quantity is not a multiple of sixteen, the remaining
407 | bits in the final data word will be padded with zeros (toward the high
408 | order end of the word).
409 |
410 | @param u16ReadAddress address of first discrete input (0x0000..0xFFFF)
411 | @param u16BitQty quantity of discrete inputs to read (1..2000, enforced by remote device)
412 | @return 0 on success; exception number on failure
413 | @ingroup discrete
414 | */
415 | uint8_t ModBusMasterMax485::readDiscreteInputs(uint16_t u16ReadAddress,
416 | uint16_t u16BitQty)
417 | {
418 | _u16ReadAddress = u16ReadAddress;
419 | _u16ReadQty = u16BitQty;
420 | return ModbusMasterTransaction(ku8MBReadDiscreteInputs);
421 | }
422 |
423 |
424 | /**
425 | Modbus function 0x03 Read Holding Registers.
426 |
427 | This function code is used to read the contents of a contiguous block of
428 | holding registers in a remote device. The request specifies the starting
429 | register address and the number of registers. Registers are addressed
430 | starting at zero.
431 |
432 | The register data in the response buffer is packed as one word per
433 | register.
434 |
435 | @param u16ReadAddress address of the first holding register (0x0000..0xFFFF)
436 | @param u16ReadQty quantity of holding registers to read (1..125, enforced by remote device)
437 | @return 0 on success; exception number on failure
438 | @ingroup register
439 | */
440 | uint8_t ModBusMasterMax485::readHoldingRegisters(uint16_t u16ReadAddress,
441 | uint16_t u16ReadQty)
442 | {
443 | _u16ReadAddress = u16ReadAddress;
444 | _u16ReadQty = u16ReadQty;
445 | return ModbusMasterTransaction(ku8MBReadHoldingRegisters);
446 | }
447 |
448 |
449 | /**
450 | Modbus function 0x04 Read Input Registers.
451 |
452 | This function code is used to read from 1 to 125 contiguous input
453 | registers in a remote device. The request specifies the starting
454 | register address and the number of registers. Registers are addressed
455 | starting at zero.
456 |
457 | The register data in the response buffer is packed as one word per
458 | register.
459 |
460 | @param u16ReadAddress address of the first input register (0x0000..0xFFFF)
461 | @param u16ReadQty quantity of input registers to read (1..125, enforced by remote device)
462 | @return 0 on success; exception number on failure
463 | @ingroup register
464 | */
465 | uint8_t ModBusMasterMax485::readInputRegisters(uint16_t u16ReadAddress,
466 | uint8_t u16ReadQty)
467 | {
468 | _u16ReadAddress = u16ReadAddress;
469 | _u16ReadQty = u16ReadQty;
470 | return ModbusMasterTransaction(ku8MBReadInputRegisters);
471 | }
472 |
473 |
474 | /**
475 | Modbus function 0x05 Write Single Coil.
476 |
477 | This function code is used to write a single output to either ON or OFF
478 | in a remote device. The requested ON/OFF state is specified by a
479 | constant in the state field. A non-zero value requests the output to be
480 | ON and a value of 0 requests it to be OFF. The request specifies the
481 | address of the coil to be forced. Coils are addressed starting at zero.
482 |
483 | @param u16WriteAddress address of the coil (0x0000..0xFFFF)
484 | @param u8State 0=OFF, non-zero=ON (0x00..0xFF)
485 | @return 0 on success; exception number on failure
486 | @ingroup discrete
487 | */
488 | uint8_t ModBusMasterMax485::writeSingleCoil(uint16_t u16WriteAddress, uint8_t u8State)
489 | {
490 | _u16WriteAddress = u16WriteAddress;
491 | _u16WriteQty = (u8State ? 0xFF00 : 0x0000);
492 | return ModbusMasterTransaction(ku8MBWriteSingleCoil);
493 | }
494 |
495 |
496 | /**
497 | Modbus function 0x06 Write Single Register.
498 |
499 | This function code is used to write a single holding register in a
500 | remote device. The request specifies the address of the register to be
501 | written. Registers are addressed starting at zero.
502 |
503 | @param u16WriteAddress address of the holding register (0x0000..0xFFFF)
504 | @param u16WriteValue value to be written to holding register (0x0000..0xFFFF)
505 | @return 0 on success; exception number on failure
506 | @ingroup register
507 | */
508 | uint8_t ModBusMasterMax485::writeSingleRegister(uint16_t u16WriteAddress,
509 | uint16_t u16WriteValue)
510 | {
511 | _u16WriteAddress = u16WriteAddress;
512 | _u16WriteQty = 0;
513 | _u16TransmitBuffer[0] = u16WriteValue;
514 | return ModbusMasterTransaction(ku8MBWriteSingleRegister);
515 | }
516 |
517 |
518 | /**
519 | Modbus function 0x0F Write Multiple Coils.
520 |
521 | This function code is used to force each coil in a sequence of coils to
522 | either ON or OFF in a remote device. The request specifies the coil
523 | references to be forced. Coils are addressed starting at zero.
524 |
525 | The requested ON/OFF states are specified by contents of the transmit
526 | buffer. A logical '1' in a bit position of the buffer requests the
527 | corresponding output to be ON. A logical '0' requests it to be OFF.
528 |
529 | @param u16WriteAddress address of the first coil (0x0000..0xFFFF)
530 | @param u16BitQty quantity of coils to write (1..2000, enforced by remote device)
531 | @return 0 on success; exception number on failure
532 | @ingroup discrete
533 | */
534 | uint8_t ModBusMasterMax485::writeMultipleCoils(uint16_t u16WriteAddress,
535 | uint16_t u16BitQty)
536 | {
537 | _u16WriteAddress = u16WriteAddress;
538 | _u16WriteQty = u16BitQty;
539 | return ModbusMasterTransaction(ku8MBWriteMultipleCoils);
540 | }
541 | uint8_t ModBusMasterMax485::writeMultipleCoils()
542 | {
543 | _u16WriteQty = u16TransmitBufferLength;
544 | return ModbusMasterTransaction(ku8MBWriteMultipleCoils);
545 | }
546 |
547 |
548 | /**
549 | Modbus function 0x10 Write Multiple Registers.
550 |
551 | This function code is used to write a block of contiguous registers (1
552 | to 123 registers) in a remote device.
553 |
554 | The requested written values are specified in the transmit buffer. Data
555 | is packed as one word per register.
556 |
557 | @param u16WriteAddress address of the holding register (0x0000..0xFFFF)
558 | @param u16WriteQty quantity of holding registers to write (1..123, enforced by remote device)
559 | @return 0 on success; exception number on failure
560 | @ingroup register
561 | */
562 | uint8_t ModBusMasterMax485::writeMultipleRegisters(uint16_t u16WriteAddress,
563 | uint16_t u16WriteQty)
564 | {
565 | _u16WriteAddress = u16WriteAddress;
566 | _u16WriteQty = u16WriteQty;
567 | return ModbusMasterTransaction(ku8MBWriteMultipleRegisters);
568 | }
569 |
570 | // new version based on Wire.h
571 | uint8_t ModBusMasterMax485::writeMultipleRegisters()
572 | {
573 | _u16WriteQty = _u8TransmitBufferIndex;
574 | return ModbusMasterTransaction(ku8MBWriteMultipleRegisters);
575 | }
576 |
577 |
578 | /**
579 | Modbus function 0x16 Mask Write Register.
580 |
581 | This function code is used to modify the contents of a specified holding
582 | register using a combination of an AND mask, an OR mask, and the
583 | register's current contents. The function can be used to set or clear
584 | individual bits in the register.
585 |
586 | The request specifies the holding register to be written, the data to be
587 | used as the AND mask, and the data to be used as the OR mask. Registers
588 | are addressed starting at zero.
589 |
590 | The function's algorithm is:
591 |
592 | Result = (Current Contents && And_Mask) || (Or_Mask && (~And_Mask))
593 |
594 | @param u16WriteAddress address of the holding register (0x0000..0xFFFF)
595 | @param u16AndMask AND mask (0x0000..0xFFFF)
596 | @param u16OrMask OR mask (0x0000..0xFFFF)
597 | @return 0 on success; exception number on failure
598 | @ingroup register
599 | */
600 | uint8_t ModBusMasterMax485::maskWriteRegister(uint16_t u16WriteAddress,
601 | uint16_t u16AndMask, uint16_t u16OrMask)
602 | {
603 | _u16WriteAddress = u16WriteAddress;
604 | _u16TransmitBuffer[0] = u16AndMask;
605 | _u16TransmitBuffer[1] = u16OrMask;
606 | return ModbusMasterTransaction(ku8MBMaskWriteRegister);
607 | }
608 |
609 |
610 | /**
611 | Modbus function 0x17 Read Write Multiple Registers.
612 |
613 | This function code performs a combination of one read operation and one
614 | write operation in a single MODBUS transaction. The write operation is
615 | performed before the read. Holding registers are addressed starting at
616 | zero.
617 |
618 | The request specifies the starting address and number of holding
619 | registers to be read as well as the starting address, and the number of
620 | holding registers. The data to be written is specified in the transmit
621 | buffer.
622 |
623 | @param u16ReadAddress address of the first holding register (0x0000..0xFFFF)
624 | @param u16ReadQty quantity of holding registers to read (1..125, enforced by remote device)
625 | @param u16WriteAddress address of the first holding register (0x0000..0xFFFF)
626 | @param u16WriteQty quantity of holding registers to write (1..121, enforced by remote device)
627 | @return 0 on success; exception number on failure
628 | @ingroup register
629 | */
630 | uint8_t ModBusMasterMax485::readWriteMultipleRegisters(uint16_t u16ReadAddress,
631 | uint16_t u16ReadQty, uint16_t u16WriteAddress, uint16_t u16WriteQty)
632 | {
633 | _u16ReadAddress = u16ReadAddress;
634 | _u16ReadQty = u16ReadQty;
635 | _u16WriteAddress = u16WriteAddress;
636 | _u16WriteQty = u16WriteQty;
637 | return ModbusMasterTransaction(ku8MBReadWriteMultipleRegisters);
638 | }
639 | uint8_t ModBusMasterMax485::readWriteMultipleRegisters(uint16_t u16ReadAddress,
640 | uint16_t u16ReadQty)
641 | {
642 | _u16ReadAddress = u16ReadAddress;
643 | _u16ReadQty = u16ReadQty;
644 | _u16WriteQty = _u8TransmitBufferIndex;
645 | return ModbusMasterTransaction(ku8MBReadWriteMultipleRegisters);
646 | }
647 |
648 |
649 | /* _____PRIVATE FUNCTIONS____________________________________________________ */
650 | /**
651 | Modbus transaction engine.
652 | Sequence:
653 | - assemble Modbus Request Application Data Unit (ADU),
654 | based on particular function called
655 | - transmit request over selected serial port
656 | - wait for/retrieve response
657 | - evaluate/disassemble response
658 | - return status (success/exception)
659 |
660 | @param u8MBFunction Modbus function (0x01..0xFF)
661 | @return 0 on success; exception number on failure
662 | */
663 | uint8_t ModBusMasterMax485::ModbusMasterTransaction(uint8_t u8MBFunction)
664 | {
665 | uint8_t u8ModbusADU[256];
666 | uint8_t u8ModbusADUSize = 0;
667 | uint8_t i, u8Qty;
668 | uint16_t u16CRC;
669 | uint32_t u32StartTime;
670 | uint8_t u8BytesLeft = 8;
671 | uint8_t u8MBStatus = ku8MBSuccess;
672 |
673 | // assemble Modbus Request Application Data Unit
674 | u8ModbusADU[u8ModbusADUSize++] = _u8MBSlave;
675 | u8ModbusADU[u8ModbusADUSize++] = u8MBFunction;
676 |
677 | switch(u8MBFunction)
678 | {
679 | case ku8MBReadCoils:
680 | case ku8MBReadDiscreteInputs:
681 | case ku8MBReadInputRegisters:
682 | case ku8MBReadHoldingRegisters:
683 | case ku8MBReadWriteMultipleRegisters:
684 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadAddress);
685 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadAddress);
686 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16ReadQty);
687 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16ReadQty);
688 | break;
689 | }
690 |
691 | switch(u8MBFunction)
692 | {
693 | case ku8MBWriteSingleCoil:
694 | case ku8MBMaskWriteRegister:
695 | case ku8MBWriteMultipleCoils:
696 | case ku8MBWriteSingleRegister:
697 | case ku8MBWriteMultipleRegisters:
698 | case ku8MBReadWriteMultipleRegisters:
699 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteAddress);
700 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteAddress);
701 | break;
702 | }
703 |
704 | switch(u8MBFunction)
705 | {
706 | case ku8MBWriteSingleCoil:
707 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty);
708 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty);
709 | break;
710 |
711 | case ku8MBWriteSingleRegister:
712 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[0]);
713 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[0]);
714 | break;
715 |
716 | case ku8MBWriteMultipleCoils:
717 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty);
718 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty);
719 | u8Qty = (_u16WriteQty % 8) ? ((_u16WriteQty >> 3) + 1) : (_u16WriteQty >> 3);
720 | u8ModbusADU[u8ModbusADUSize++] = u8Qty;
721 | for (i = 0; i < u8Qty; i++)
722 | {
723 | switch(i % 2)
724 | {
725 | case 0: // i is even
726 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[i >> 1]);
727 | break;
728 |
729 | case 1: // i is odd
730 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[i >> 1]);
731 | break;
732 | }
733 | }
734 | break;
735 |
736 | case ku8MBWriteMultipleRegisters:
737 | case ku8MBReadWriteMultipleRegisters:
738 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16WriteQty);
739 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty);
740 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16WriteQty << 1);
741 |
742 | for (i = 0; i < lowByte(_u16WriteQty); i++)
743 | {
744 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[i]);
745 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[i]);
746 | }
747 | break;
748 |
749 | case ku8MBMaskWriteRegister:
750 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[0]);
751 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[0]);
752 | u8ModbusADU[u8ModbusADUSize++] = highByte(_u16TransmitBuffer[1]);
753 | u8ModbusADU[u8ModbusADUSize++] = lowByte(_u16TransmitBuffer[1]);
754 | break;
755 | }
756 |
757 | // append CRC
758 | u16CRC = 0xFFFF;
759 | for (i = 0; i < u8ModbusADUSize; i++)
760 | {
761 | u16CRC = _crc16_update2(u16CRC, u8ModbusADU[i]);
762 | }
763 | u8ModbusADU[u8ModbusADUSize++] = lowByte(u16CRC);
764 | u8ModbusADU[u8ModbusADUSize++] = highByte(u16CRC);
765 | u8ModbusADU[u8ModbusADUSize] = 0;
766 |
767 |
768 | // transmit request on the rs485 interface
769 | if (_PinEnableTx){
770 | digitalWrite(_u8PinEnableTx, LOW); // activate pin
771 | delay(1);
772 | }
773 | for (i = 0; i < u8ModbusADUSize; i++)
774 | {
775 | Serial.print(char(u8ModbusADU[i]));
776 | }
777 |
778 | Serial.flush();
779 | //delay(2);
780 |
781 | if (_PinEnableTx)
782 | digitalWrite(_u8PinEnableTx, HIGH); // deactivate pin
783 |
784 | u8ModbusADUSize = 1;
785 |
786 | // loop until we run out of time or bytes, or an error occurs
787 | u32StartTime = millis();
788 |
789 | int val = 0xFF;
790 | long cont = 0;
791 |
792 | while((val != _u8MBSlave) && (cont < 100)) {
793 | val = Serial.read();
794 | delay(5);
795 | cont ++;
796 | }
797 |
798 | u8ModbusADU[u8ModbusADUSize] = val;
799 |
800 |
801 | while (u8BytesLeft && !u8MBStatus)
802 | {
803 | if (Serial.available())
804 | {
805 | u8ModbusADU[u8ModbusADUSize] = Serial.read();
806 | u8BytesLeft--;
807 | u8ModbusADUSize ++;
808 |
809 | }
810 | else
811 | {
812 |
813 | if (_idle)
814 | {
815 | _idle();
816 | }
817 |
818 | }
819 |
820 | // evaluate slave ID, function code once enough bytes have been read
821 | if (u8ModbusADUSize == 5)
822 | {
823 |
824 | // verify response is for correct Modbus slave
825 | if (u8ModbusADU[0] != _u8MBSlave)
826 | {
827 | u8MBStatus = ku8MBInvalidSlaveID;
828 | break;
829 | }
830 |
831 | // verify response is for correct Modbus function code (mask exception bit 7)
832 | if ((u8ModbusADU[1] & 0x7F) != u8MBFunction)
833 | {
834 | u8MBStatus = ku8MBInvalidFunction;
835 | break;
836 | }
837 |
838 | // check whether Modbus exception occurred; return Modbus Exception Code
839 | if (bitRead(u8ModbusADU[1], 7))
840 | {
841 | u8MBStatus = u8ModbusADU[2];
842 | break;
843 | }
844 |
845 | // evaluate returned Modbus function code
846 | switch(u8ModbusADU[1])
847 | {
848 | case ku8MBReadCoils:
849 | case ku8MBReadDiscreteInputs:
850 | case ku8MBReadInputRegisters:
851 | case ku8MBReadHoldingRegisters:
852 | case ku8MBReadWriteMultipleRegisters:
853 | u8BytesLeft = u8ModbusADU[2];
854 | break;
855 |
856 | case ku8MBWriteSingleCoil:
857 | case ku8MBWriteMultipleCoils:
858 | case ku8MBWriteSingleRegister:
859 | case ku8MBWriteMultipleRegisters:
860 | u8BytesLeft = 3;
861 | break;
862 |
863 | case ku8MBMaskWriteRegister:
864 | u8BytesLeft = 5;
865 | break;
866 | }
867 | }
868 | if (millis() > (u32StartTime + ku8MBResponseTimeout))
869 | {
870 | u8MBStatus = ku8MBResponseTimedOut;
871 | }
872 | }
873 |
874 | // verify response is large enough to inspect further
875 | if (!u8MBStatus && u8ModbusADUSize >= 5)
876 | {
877 | // calculate CRC
878 | u16CRC = 0xFFFF;
879 | for (i = 0; i < (u8ModbusADUSize - 2); i++)
880 | {
881 | u16CRC = _crc16_update2(u16CRC, u8ModbusADU[i]);
882 | }
883 |
884 | // verify CRC
885 | if (!u8MBStatus && (lowByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 2] ||
886 | highByte(u16CRC) != u8ModbusADU[u8ModbusADUSize - 1]))
887 | {
888 | u8MBStatus = ku8MBInvalidCRC;
889 | }
890 | }
891 |
892 | // disassemble ADU into words
893 | if (!u8MBStatus)
894 | {
895 | // evaluate returned Modbus function code
896 | switch(u8ModbusADU[1])
897 | {
898 | case ku8MBReadCoils:
899 | case ku8MBReadDiscreteInputs:
900 | // load bytes into word; response bytes are ordered L, H, L, H, ...
901 | for (i = 0; i < (u8ModbusADU[2] >> 1); i++)
902 | {
903 | if (i < ku8MaxBufferSize)
904 | {
905 | _u16ResponseBuffer[i] = (u8ModbusADU[2 * i + 4] << 8) | u8ModbusADU[2 * i + 3];
906 | }
907 |
908 | _u8ResponseBufferLength = i;
909 | }
910 |
911 | // in the event of an odd number of bytes, load last byte into zero-padded word
912 | if (u8ModbusADU[2] % 2)
913 | {
914 | if (i < ku8MaxBufferSize)
915 | {
916 | _u16ResponseBuffer[i] = (0 << 8) | u8ModbusADU[2 * i + 3];
917 | }
918 |
919 | _u8ResponseBufferLength = i + 1;
920 | }
921 | break;
922 |
923 | case ku8MBReadInputRegisters:
924 | case ku8MBReadHoldingRegisters:
925 | case ku8MBReadWriteMultipleRegisters:
926 | // load bytes into word; response bytes are ordered H, L, H, L, ...
927 | for (i = 0; i < (u8ModbusADU[2] >> 1); i++)
928 | {
929 | if (i < ku8MaxBufferSize)
930 | {
931 | _u16ResponseBuffer[i] = (u8ModbusADU[2 * i + 3] << 8) | u8ModbusADU[2 * i + 4];
932 | }
933 |
934 | _u8ResponseBufferLength = i;
935 | }
936 | break;
937 | }
938 | }
939 |
940 |
941 | _u8TransmitBufferIndex = 0;
942 | u16TransmitBufferLength = 0;
943 | _u8ResponseBufferIndex = 0;
944 | return u8MBStatus;
945 | }
946 |
947 | /*
948 |
949 | MakeWord function deleted -for ESP8266 PDAControl
950 |
951 | unsigned int ModBusMasterMax485::makeWord(unsigned int w)
952 | {
953 | return w;
954 | }
955 |
956 |
957 | unsigned int ModBusMasterMax485::makeWord(uint8_t h, uint8_t l)
958 | {
959 | return (h << 8) | l;
960 | }
961 | */
962 | void ModBusMasterMax485::setSlaveAddress(uint8_t u8MBSlave){
963 |
964 | _u8MBSlave = u8MBSlave;
965 | }
966 |
967 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Library Modbus RTU ESP8266/ModBusMasterMax485/ModBusMasterMax485.h:
--------------------------------------------------------------------------------
1 | /**
2 | @file
3 | Arduino library for communicating with Modbus slaves over RS232/485 (via RTU protocol).
4 |
5 | @defgroup setup ModbusMaster Object Instantiation/Initialization
6 | @defgroup buffer ModbusMaster Buffer Management
7 | @defgroup discrete Modbus Function Codes for Discrete Coils/Inputs
8 | @defgroup register Modbus Function Codes for Holding/Input Registers
9 | @defgroup constant Modbus Function Codes, Exception Codes
10 | */
11 | /*
12 |
13 | ModbusMaster.h - Arduino library for communicating with Modbus slaves
14 | over RS232/485 (via RTU protocol).
15 |
16 | This file is part of ModbusMaster.
17 |
18 | ModbusMaster is free software: you can redistribute it and/or modify
19 | it under the terms of the GNU General Public License as published by
20 | the Free Software Foundation, either version 3 of the License, or
21 | (at your option) any later version.
22 |
23 | ModbusMaster is distributed in the hope that it will be useful,
24 | but WITHOUT ANY WARRANTY; without even the implied warranty of
25 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 | GNU General Public License for more details.
27 |
28 | You should have received a copy of the GNU General Public License
29 | along with ModbusMaster. If not, see .
30 |
31 | Written by Doc Walker (Rx)
32 | Copyright © 2009-2013 Doc Walker <4-20ma at wvfans dot net>
33 |
34 | Modificado para esp8266
35 | - Function crc16
36 | - Function makeWord
37 | - Function half duplex RS485_ENABLE_PIN
38 | - Function to auto update slaveID (232 to 485)
39 |
40 | */
41 |
42 |
43 |
44 | #ifndef _MODBUSMASTERMAX485_H_INCLUDED
45 | #define _MODBUSMASTERMAX485_H_INCLUDED
46 |
47 |
48 | /**
49 | @def __MODBUSMASTER_DEBUG__ (1).
50 | Set to 1 to enable debugging features within class:
51 | - pin 4 cycles for each byte read in the Modbus response
52 | - pin 5 cycles for each millisecond timeout during the Modbus response
53 | */
54 | #define __MODBUSMASTER_DEBUG__ (1)
55 |
56 |
57 | /* _____STANDARD INCLUDES____________________________________________________ */
58 |
59 | // include types & constants of Wiring core API
60 |
61 | #ifndef inttypes_h
62 | #include
63 | #endif
64 |
65 |
66 |
67 | /* _____UTILITY MACROS_______________________________________________________ */
68 | /**
69 | @def lowWord(ww) ((uint16_t) ((ww) & 0xFFFF))
70 | Macro to return low word of a 32-bit integer.
71 | */
72 | #define lowWord(ww) ((uint16_t) ((ww) & 0xFFFF))
73 |
74 |
75 | /**
76 | @def highWord(ww) ((uint16_t) ((ww) >> 16))
77 | Macro to return high word of a 32-bit integer.
78 | */
79 | #define highWord(ww) ((uint16_t) ((ww) >> 16))
80 |
81 |
82 |
83 | /**
84 | @def LONG(hi, lo) ((uint32_t) ((hi) << 16 | (lo)))
85 | Macro to generate 32-bit integer from (2) 16-bit words.
86 | */
87 | #define LONG(hi, lo) ((uint32_t) ((hi) << 16 | (lo)))
88 |
89 | #define lowByte(w) ((uint8_t) ((w) & 0xff))
90 | #define highByte(w) ((uint8_t) ((w) >> 8))
91 |
92 | #define bitRead(value, bit) (((value) >> (bit)) & 0x01)
93 | #define bitSet(value, bit) ((value) |= (1UL << (bit)))
94 | #define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
95 | #define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
96 |
97 |
98 | /* _____PROJECT INCLUDES_____________________________________________________ */
99 | // functions to calculate Modbus Application Data Unit CRC
100 | //#include
101 |
102 |
103 |
104 | /* _____CLASS DEFINITIONS____________________________________________________ */
105 | /**
106 | Arduino class library for communicating with Modbus slaves over
107 | RS232/485 (via RTU protocol).
108 | */
109 | class ModBusMasterMax485
110 | {
111 | public:
112 |
113 | ModBusMasterMax485();
114 | ModBusMasterMax485(uint8_t);
115 | // ModBusMasterMax485(uint8_t, uint8_t);
116 |
117 | void begin();
118 | void begin(unsigned long);
119 | void idle(void (*)());
120 | void slaveID(uint8_t);
121 |
122 | // Modbus exception codes
123 | /**
124 | Modbus protocol illegal function exception.
125 |
126 | The function code received in the query is not an allowable action for
127 | the server (or slave). This may be because the function code is only
128 | applicable to newer devices, and was not implemented in the unit
129 | selected. It could also indicate that the server (or slave) is in the
130 | wrong state to process a request of this type, for example because it is
131 | unconfigured and is being asked to return register values.
132 |
133 | @ingroup constant
134 | */
135 | static const uint8_t ku8MBIllegalFunction = 0x01;
136 |
137 | /**
138 | Modbus protocol illegal data address exception.
139 |
140 | The data address received in the query is not an allowable address for
141 | the server (or slave). More specifically, the combination of reference
142 | number and transfer length is invalid. For a controller with 100
143 | registers, the ADU addresses the first register as 0, and the last one
144 | as 99. If a request is submitted with a starting register address of 96
145 | and a quantity of registers of 4, then this request will successfully
146 | operate (address-wise at least) on registers 96, 97, 98, 99. If a
147 | request is submitted with a starting register address of 96 and a
148 | quantity of registers of 5, then this request will fail with Exception
149 | Code 0x02 "Illegal Data Address" since it attempts to operate on
150 | registers 96, 97, 98, 99 and 100, and there is no register with address
151 | 100.
152 |
153 | @ingroup constant
154 | */
155 | static const uint8_t ku8MBIllegalDataAddress = 0x02;
156 |
157 | /**
158 | Modbus protocol illegal data value exception.
159 |
160 | A value contained in the query data field is not an allowable value for
161 | server (or slave). This indicates a fault in the structure of the
162 | remainder of a complex request, such as that the implied length is
163 | incorrect. It specifically does NOT mean that a data item submitted for
164 | storage in a register has a value outside the expectation of the
165 | application program, since the MODBUS protocol is unaware of the
166 | significance of any particular value of any particular register.
167 |
168 | @ingroup constant
169 | */
170 | static const uint8_t ku8MBIllegalDataValue = 0x03;
171 |
172 | /**
173 | Modbus protocol slave device failure exception.
174 |
175 | An unrecoverable error occurred while the server (or slave) was
176 | attempting to perform the requested action.
177 |
178 | @ingroup constant
179 | */
180 | static const uint8_t ku8MBSlaveDeviceFailure = 0x04;
181 |
182 | // Class-defined success/exception codes
183 | /**
184 | ModbusMaster success.
185 |
186 | Modbus transaction was successful; the following checks were valid:
187 | - slave ID
188 | - function code
189 | - response code
190 | - data
191 | - CRC
192 |
193 | @ingroup constant
194 | */
195 | static const uint8_t ku8MBSuccess = 0x00;
196 |
197 | /**
198 | ModbusMaster invalid response slave ID exception.
199 |
200 | The slave ID in the response does not match that of the request.
201 |
202 | @ingroup constant
203 | */
204 | static const uint8_t ku8MBInvalidSlaveID = 0xE0;
205 |
206 | /**
207 | ModbusMaster invalid response function exception.
208 |
209 | The function code in the response does not match that of the request.
210 |
211 | @ingroup constant
212 | */
213 | static const uint8_t ku8MBInvalidFunction = 0xE1;
214 |
215 | /**
216 | ModbusMaster response timed out exception.
217 |
218 | The entire response was not received within the timeout period,
219 | ModbusMaster::ku8MBResponseTimeout.
220 |
221 | @ingroup constant
222 | */
223 | static const uint8_t ku8MBResponseTimedOut = 0xE2;
224 |
225 | /**
226 | ModbusMaster invalid response CRC exception.
227 |
228 | The CRC in the response does not match the one calculated.
229 |
230 | @ingroup constant
231 | */
232 | static const uint8_t ku8MBInvalidCRC = 0xE3;
233 |
234 | uint16_t getResponseBuffer(uint8_t);
235 | void clearResponseBuffer();
236 | uint8_t setTransmitBuffer(uint8_t, uint16_t);
237 | void clearTransmitBuffer();
238 |
239 | void beginTransmission(uint16_t);
240 | uint8_t requestFrom(uint16_t, uint16_t);
241 | void sendBit(bool);
242 | void send(uint8_t);
243 | void send(uint16_t);
244 | void send(uint32_t);
245 | void setSlaveAddress(uint8_t);
246 |
247 | uint8_t available(void);
248 | uint16_t receive(void);
249 |
250 |
251 | uint8_t readCoils(uint16_t, uint16_t);
252 | uint8_t readDiscreteInputs(uint16_t, uint16_t);
253 | uint8_t readHoldingRegisters(uint16_t, uint16_t);
254 | uint8_t readInputRegisters(uint16_t, uint8_t);
255 | uint8_t writeSingleCoil(uint16_t, uint8_t);
256 | uint8_t writeSingleRegister(uint16_t, uint16_t);
257 | uint8_t writeMultipleCoils(uint16_t, uint16_t);
258 | uint8_t writeMultipleCoils();
259 | uint8_t writeMultipleRegisters(uint16_t, uint16_t);
260 | uint8_t writeMultipleRegisters();
261 | uint8_t maskWriteRegister(uint16_t, uint16_t, uint16_t);
262 | uint8_t readWriteMultipleRegisters(uint16_t, uint16_t, uint16_t, uint16_t);
263 | uint8_t readWriteMultipleRegisters(uint16_t, uint16_t);
264 |
265 |
266 | private:
267 | uint8_t _u8SerialPort; ///< serial port (0..3) initialized in constructor
268 | uint8_t _u8PinEnableTx; ///< pin enabled for rs485 adaptor initialized in constructor
269 | uint8_t _PinEnableTx = false; ///< if pin enabled activate pin initialized in constructor
270 | uint8_t _u8MBSlave; ///< Modbus slave (1..255) initialized in constructor
271 | uint16_t _u16BaudRate; ///< baud rate (300..115200) initialized in begin()
272 | static const uint8_t ku8MaxBufferSize = 64; ///< size of response/transmit buffers
273 | uint16_t _u16ReadAddress; ///< slave register from which to read
274 | uint16_t _u16ReadQty; ///< quantity of words to read
275 | uint16_t _u16ResponseBuffer[ku8MaxBufferSize]; ///< buffer to store Modbus slave response; read via GetResponseBuffer()
276 | uint16_t _u16WriteAddress; ///< slave register to which to write
277 | uint16_t _u16WriteQty; ///< quantity of words to write
278 | uint16_t _u16TransmitBuffer[ku8MaxBufferSize]; ///< buffer containing data to transmit to Modbus slave; set via SetTransmitBuffer()
279 | uint16_t* txBuffer; // from Wire.h -- need to clean this up Rx
280 | uint8_t _u8TransmitBufferIndex;
281 | uint16_t u16TransmitBufferLength;
282 | uint16_t* rxBuffer; // from Wire.h -- need to clean this up Rx
283 | uint8_t _u8ResponseBufferIndex;
284 | uint8_t _u8ResponseBufferLength;
285 |
286 | // Modbus function codes for bit access
287 | static const uint8_t ku8MBReadCoils = 0x01; ///< Modbus function 0x01 Read Coils
288 | static const uint8_t ku8MBReadDiscreteInputs = 0x02; ///< Modbus function 0x02 Read Discrete Inputs
289 | static const uint8_t ku8MBWriteSingleCoil = 0x05; ///< Modbus function 0x05 Write Single Coil
290 | static const uint8_t ku8MBWriteMultipleCoils = 0x0F; ///< Modbus function 0x0F Write Multiple Coils
291 |
292 | // Modbus function codes for 16 bit access
293 | static const uint8_t ku8MBReadHoldingRegisters = 0x03; ///< Modbus function 0x03 Read Holding Registers
294 | static const uint8_t ku8MBReadInputRegisters = 0x04; ///< Modbus function 0x04 Read Input Registers
295 | static const uint8_t ku8MBWriteSingleRegister = 0x06; ///< Modbus function 0x06 Write Single Register
296 | static const uint8_t ku8MBWriteMultipleRegisters = 0x10; ///< Modbus function 0x10 Write Multiple Registers
297 | static const uint8_t ku8MBMaskWriteRegister = 0x16; ///< Modbus function 0x16 Mask Write Register
298 | static const uint8_t ku8MBReadWriteMultipleRegisters = 0x17; ///< Modbus function 0x17 Read Write Multiple Registers
299 |
300 | // Modbus timeout [milliseconds]
301 | static const uint8_t ku8MBResponseTimeout = 200; ///< Modbus timeout [milliseconds]
302 |
303 | // master function that conducts Modbus transactions
304 | uint8_t ModbusMasterTransaction(uint8_t u8MBFunction);
305 |
306 | // idle callback function; gets called during idle time between TX and RX
307 | void (*_idle)();
308 |
309 | uint16_t makeWord(uint16_t w);
310 | uint16_t makeWord(uint8_t h, uint8_t l);
311 |
312 | };
313 | #endif
314 |
315 | /**
316 | @example examples/Basic/Basic.pde
317 | @example examples/PhoenixContact_nanoLC/PhoenixContact_nanoLC.pde
318 | */
319 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Library Modbus RTU ESP8266/ModBusMasterMax485/keywords.txt:
--------------------------------------------------------------------------------
1 | ModBusMasterMax485 KEYWORD1
2 | node KEYWORD2
3 | slaveID KEYWORD2
4 |
5 |
6 | getResponseBuffer KEYWORD2
7 | clearResponseBuffer KEYWORD2
8 | setTransmitBuffer KEYWORD2
9 | clearTransmitBuffer KEYWORD2
10 | setSlaveAddress KEYWORD2
11 | send KEYWORD2
12 | available KEYWORD2
13 | receive KEYWORD2
14 | readCoils KEYWORD2
15 | readDiscreteInputs KEYWORD2
16 | readHoldingRegisters KEYWORD2
17 | readInputRegisters KEYWORD2
18 | writeSingleCoil KEYWORD2
19 | writeSingleRegister KEYWORD2
20 | writeMultipleCoils KEYWORD2
21 | writeMultipleCoils KEYWORD2
22 | writeMultipleRegisters KEYWORD2
23 | writeMultipleRegisters KEYWORD2
24 | maskWriteRegister KEYWORD2
25 | readWriteMultipleRegisters KEYWORD2
26 | readWriteMultipleRegisters KEYWORD2
27 |
28 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/Library Modbus RTU ESP8266/README.md:
--------------------------------------------------------------------------------
1 | # Modified library necessary to operate the sketch.
2 |
3 | Within the files, the changes made are detailed in the comments.
4 |
5 | Add this folder to the libraries directory of your arduino IDE to be able to compile the sketch.
6 |
7 | Possibility of using an ESP8266 or an Arduino + W5100 shield.
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/ModbusTCPSlaveRTUMasterMAX485/ModbusTCPSlaveRTUMasterMAX485.ino:
--------------------------------------------------------------------------------
1 | // Include these libraries for using the RS-232 to RS-485 adaptor and Modbus functions
2 | #include
3 |
4 | //---------------------------------- ONLY CONFIG THIS ----------------------------------------------------
5 |
6 | #define MB_PORT 502
7 | #define BAUDRATE 9600 //rate de baud a comunicate RS485
8 | #define RS485_ENABLE_PIN 0 //pinul GPIO0 or GPIO2 (GPIO0 use in PCB Git), if use arduino with ethernet shield any unused pin
9 |
10 | // Select board (possibility to use ethernet)
11 | //#define MB_ETHERNET // Only with W5100 and library versión 1.1.2
12 | #define MB_ESP8266
13 |
14 | // ArduinoOTA Enabled (only with ESP8266 board)
15 | #define OTA
16 |
17 | // Update these with values suitable for your network.
18 | #define STATIC_MODE // static IP address config (DHCP or static DHCP lease if comment this line)
19 | #ifdef STATIC_MODE
20 | byte ip[] = { 192, 168, 0, 22 };
21 | byte subnet[] = { 255, 255, 255, 0 };
22 | byte gateway[] = { 192, 168, 0, 1 };
23 | #endif
24 |
25 | #ifdef MB_ESP8266
26 | // Wifi Settings
27 | const char* ssid = "......";
28 | const char* password = "......";
29 |
30 | #ifdef OTA
31 | // OTA config
32 | long Port = 8266; // Port defaults to 8266
33 | const char* Hostname = "BridgeTCP/RTU";
34 | const char* Password = "admin";
35 |
36 | #endif
37 | #endif
38 |
39 | //----------------------------------------------------------------------------------------------------
40 |
41 | #ifdef MB_ETHERNET
42 | #include
43 | #define LED_PIN 13
44 | #endif
45 | #ifdef MB_ESP8266
46 | #define LED_PIN 5
47 | #include
48 | #ifdef OTA
49 | #include
50 | #include
51 | #include
52 | #endif
53 | #endif
54 |
55 | //
56 | // MODBUS Function Codes
57 | //
58 | #define MB_FC_NONE 0
59 | #define MB_FC_READ_COILS 1 //implemented
60 | #define MB_FC_READ_DISCRETE_INPUT 2 //implemented
61 | #define MB_FC_READ_REGISTERS 3 //implemented
62 | #define MB_FC_READ_INPUT_REGISTERS 4 //implemented
63 | #define MB_FC_WRITE_COIL 5 //implemented
64 | #define MB_FC_WRITE_REGISTER 6 //implemented
65 | #define MB_FC_WRITE_MULTIPLE_COILS 15
66 | #define MB_FC_WRITE_MULTIPLE_REGISTERS 16 //implemented
67 | //
68 | // MODBUS Error Codes
69 | //
70 | #define MB_EC_NONE 0
71 | #define MB_EC_ILLEGAL_FUNCTION 1
72 | #define MB_EC_ILLEGAL_DATA_ADDRESS 2
73 | #define MB_EC_ILLEGAL_DATA_VALUE 3
74 | #define MB_EC_SLAVE_DEVICE_FAILURE 4
75 | //
76 | // MODBUS MBAP offsets
77 | //
78 | #define MB_TCP_TID 0
79 | #define MB_TCP_PID 2
80 | #define MB_TCP_LEN 4
81 | #define MB_TCP_UID 6
82 | #define MB_TCP_FUNC 7
83 | #define MB_TCP_REGISTER_START 8
84 | #define MB_TCP_REGISTER_NUMBER 10
85 |
86 | #ifdef MB_ETHERNET
87 | EthernetServer MBServer(MB_PORT);
88 | #endif
89 |
90 | #ifdef MB_ESP8266
91 | WiFiServer MBServer(MB_PORT);
92 | #endif
93 |
94 | // Instantiate ModbusMaster object as set GPIO to RS485_ENABLE_PIN half duplex adaptor.
95 | ModBusMasterMax485 node(RS485_ENABLE_PIN);
96 |
97 | byte ByteArray[260];
98 | bool ledPinStatus = LOW;
99 |
100 | void setup()
101 | {
102 |
103 | #ifdef MB_ETHERNET
104 | byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
105 | pinMode(LED_PIN, OUTPUT);
106 | digitalWrite(LED_PIN, LOW);
107 | #ifndef STATIC_MODE
108 | // DHCP mode
109 | if (Ethernet.begin(mac) == 0) {
110 | while (1);
111 | }
112 | #else
113 | // Static Mode
114 | Ethernet.begin(mac, ip, gateway, subnet);
115 | #endif
116 | digitalWrite(LED_PIN, HIGH);
117 | #endif
118 |
119 | #ifdef MB_ESP8266
120 | pinMode(LED_PIN, OUTPUT);
121 | digitalWrite(LED_PIN, LOW);
122 | ledPinStatus = LOW;
123 | // Static Mode
124 | #ifdef STATIC_MODE
125 | WiFi.config(IPAddress(ip), IPAddress(gateway), IPAddress(subnet));
126 | #endif
127 | WiFi.mode(WIFI_STA);
128 | WiFi.begin(ssid, password);
129 | while (WiFi.status() != WL_CONNECTED) {
130 | // Blink the LED
131 | digitalWrite(LED_PIN, ledPinStatus); // Write LED high/low
132 | ledPinStatus = (ledPinStatus == HIGH) ? LOW : HIGH;
133 | delay(100);
134 | }
135 | #ifdef OTA
136 | // Port defaults to 8266
137 | ArduinoOTA.setPort(Port);
138 |
139 | // Hostname defaults to esp8266-[ChipID]
140 | ArduinoOTA.setHostname(Hostname);
141 |
142 | // No authentication by default
143 | ArduinoOTA.setPassword(Password);
144 |
145 | // Password can be set with it's md5 value as well
146 | // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
147 | // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
148 |
149 | ArduinoOTA.begin();
150 | #endif
151 | // Start the server
152 | digitalWrite(LED_PIN, HIGH);
153 | MBServer.begin();
154 | #endif
155 |
156 | // Initialize Modbus communication baud rate
157 | node.begin(BAUDRATE);
158 |
159 | }
160 |
161 | void loop()
162 | {
163 | #ifdef MB_ESP8266
164 | #ifdef OTA
165 | ArduinoOTA.handle();
166 | #endif
167 | #endif
168 |
169 | byte byteFN = MB_FC_NONE;
170 | byte UID = 1;
171 | int Start;
172 | int WordDataLength;
173 | int ByteDataLength;
174 | int MessageLength;
175 |
176 | //****************** Read from socket ****************
177 | #ifdef MB_ETHERNET
178 | EthernetClient client = MBServer.available();
179 | #endif
180 | #ifdef MB_ESP8266
181 | WiFiClient client = MBServer.available();
182 | #endif
183 |
184 | while (client.connected()) {
185 | if (client.available())
186 | {
187 | int i = 0;
188 | while (client.available())
189 | {
190 | ByteArray[i] = client.read();
191 | i++;
192 | }
193 | #ifdef MB_ESP8266
194 | client.flush();
195 | #endif
196 | byteFN = ByteArray[MB_TCP_FUNC];
197 | UID = ByteArray[MB_TCP_UID];
198 | Start = word(ByteArray[MB_TCP_REGISTER_START], ByteArray[MB_TCP_REGISTER_START + 1]);
199 | WordDataLength = word(ByteArray[MB_TCP_REGISTER_NUMBER], ByteArray[MB_TCP_REGISTER_NUMBER + 1]);
200 | }
201 |
202 | // Handle request
203 |
204 | switch (byteFN) {
205 | case MB_FC_NONE:
206 | {
207 | }
208 | break;
209 |
210 |
211 | case MB_FC_READ_COILS: // 01 Read Coils
212 | {
213 | ByteDataLength = WordDataLength * 2;
214 | ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
215 | ByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data).
216 |
217 | node.slaveID(UID);
218 |
219 | int result = node.readCoils(Start, WordDataLength);
220 |
221 | for (int i = 0; i < WordDataLength; i++)
222 | {
223 | if (result == 0) {
224 | ByteArray[ 9 + i * 2] = highByte(node.getResponseBuffer(i));
225 | ByteArray[10 + i * 2] = lowByte(node.getResponseBuffer(i));
226 | }
227 | }
228 |
229 | MessageLength = ByteDataLength + 9;
230 | client.write((const uint8_t *)ByteArray, MessageLength);
231 | node.clearResponseBuffer(); // Clear the response buffer
232 | byteFN = MB_FC_NONE;
233 | }
234 | break;
235 |
236 |
237 | case MB_FC_READ_DISCRETE_INPUT: // 02 Read Discrete Input
238 | {
239 | ByteDataLength = WordDataLength * 2;
240 | ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
241 | ByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data).
242 |
243 | node.slaveID(UID);
244 |
245 | int result = node.readDiscreteInputs(Start, WordDataLength);
246 |
247 | for (int i = 0; i < WordDataLength; i++)
248 | {
249 | if (result == 0) {
250 | ByteArray[ 9 + i * 2] = highByte(node.getResponseBuffer(i));
251 | ByteArray[10 + i * 2] = lowByte(node.getResponseBuffer(i));
252 | }
253 | }
254 |
255 | MessageLength = ByteDataLength + 9;
256 | client.write((const uint8_t *)ByteArray, MessageLength);
257 | node.clearResponseBuffer(); // Clear the response buffer
258 | byteFN = MB_FC_NONE;
259 | }
260 | break;
261 |
262 | case MB_FC_READ_REGISTERS: // 03 Read Holding Registers
263 | {
264 | ByteDataLength = WordDataLength * 2;
265 | ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
266 | ByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data).
267 |
268 | node.slaveID(UID);
269 |
270 | int result = node.readHoldingRegisters(Start, WordDataLength);
271 |
272 | for (int i = 0; i < WordDataLength; i++)
273 | {
274 | if (result == 0) {
275 | ByteArray[ 9 + i * 2] = highByte(node.getResponseBuffer(i));
276 | ByteArray[10 + i * 2] = lowByte(node.getResponseBuffer(i));
277 | }
278 | }
279 |
280 | MessageLength = ByteDataLength + 9;
281 | client.write((const uint8_t *)ByteArray, MessageLength);
282 | node.clearResponseBuffer(); // Clear the response buffer
283 | byteFN = MB_FC_NONE;
284 | }
285 | break;
286 |
287 | case MB_FC_READ_INPUT_REGISTERS: // 04 Read Input Registers
288 | {
289 | ByteDataLength = WordDataLength * 2;
290 | ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
291 | ByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data).
292 |
293 | node.slaveID(UID);
294 |
295 | int result = node.readInputRegisters(Start, WordDataLength);
296 |
297 | for (int i = 0; i < WordDataLength; i++)
298 | {
299 | if (result == 0) {
300 | ByteArray[ 9 + i * 2] = highByte(node.getResponseBuffer(i));
301 | ByteArray[10 + i * 2] = lowByte(node.getResponseBuffer(i));
302 | }
303 | }
304 | MessageLength = ByteDataLength + 9;
305 | client.write((const uint8_t *)ByteArray, MessageLength);
306 | node.clearResponseBuffer(); // Clear the response buffer
307 | byteFN = MB_FC_NONE;
308 | }
309 | break;
310 |
311 | case MB_FC_WRITE_COIL: // 05 Write Coils
312 | {
313 | node.slaveID(UID);
314 |
315 | int result = node.writeSingleCoil(Start, ByteArray[MB_TCP_REGISTER_NUMBER + 1]);
316 | ByteArray[5] = 6; //Number of bytes after this one.
317 | MessageLength = 12;
318 | client.write((const uint8_t *)ByteArray, MessageLength);
319 | //client.stop();
320 | node.clearTransmitBuffer(); // Clear the response buffer
321 | byteFN = MB_FC_NONE;
322 | }
323 | break;
324 |
325 | case MB_FC_WRITE_REGISTER: // 06 Write Holding Register
326 | {
327 | node.slaveID(UID);
328 |
329 | int result = node.writeSingleRegister(Start, word(ByteArray[MB_TCP_REGISTER_NUMBER], ByteArray[MB_TCP_REGISTER_NUMBER + 1]));
330 | ByteArray[5] = 6; //Number of bytes after this one.
331 | MessageLength = 12;
332 | client.write((const uint8_t *)ByteArray, MessageLength);
333 | node.clearTransmitBuffer(); // Clear the response buffer
334 | byteFN = MB_FC_NONE;
335 | }
336 | break;
337 |
338 | case MB_FC_WRITE_MULTIPLE_REGISTERS: //16 Write Multiple Registers
339 | {
340 | node.slaveID(UID);
341 |
342 | ByteDataLength = WordDataLength * 2;
343 | ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
344 | for (int i = 0; i < WordDataLength; i++)
345 | {
346 | int result = node.writeSingleRegister(Start + i, word(ByteArray[ 13 + i * 2], ByteArray[14 + i * 2]));
347 | }
348 | MessageLength = 12;
349 | client.write((const uint8_t *)ByteArray, MessageLength);
350 | node.clearTransmitBuffer(); // Clear the response buffer
351 | byteFN = MB_FC_NONE;
352 | }
353 | break;
354 |
355 | }
356 |
357 | }
358 | client.stop();
359 | }
360 |
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/ModbusTCPSlaveRTUMasterMAX485/README.md:
--------------------------------------------------------------------------------
1 | # Sketch with the TCP / RTU bridge code via ESP8266 / MAX485.
2 |
3 | Possibility of using an arduino + shield W5100 ethernet instead of ESP8266 if there is no wifi (or you do not want to depend on wifi and you want to use cable)
4 |
5 | It works like a transparent bridge TCP/RTU, being able to have several RTU devices in a single bridge (simplifies and saves the installation a lot)
6 |
7 | Using an ESP8266, it is possible to update via ArduinoOTA (optional). Within the sketch, the necessary configuration is detailed.
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-230.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-230.fzz
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-Gerber.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-Gerber.zip
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-V2-Gerber.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-V2-Gerber.zip
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-V2.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP-V2.fzz
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP.fzz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP.fzz
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP_230V-Gerber.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Modbus-Gateway-esp8266/PCB/ESP8266-RS485_DIP_230V-Gerber.zip
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/PCB/README.md:
--------------------------------------------------------------------------------
1 | # PCB for bridge TCP to RTU via ESP-01 and MAX485.
2 |
3 | Fritzing file and gerber zip available.
4 |
5 | ### 3 versions:
6 |
7 | * ESP8266-RS485_DIP -> First PCB design, tested and working (perfect for PZEM-016).
8 |
9 | * ESP8266-RS485_DIP-230-> Modified version to be fed directly to 230v, for meters that do not provide 5V power. Tested and working.
10 |
11 | * ESP8266-RS485_DIP-V2 -> Reduced version of the first design. Not yet tested, although only the components have been redistributed, it would work perfectly.
--------------------------------------------------------------------------------
/Modbus-Gateway-esp8266/README.md:
--------------------------------------------------------------------------------
1 | # Modbus-Gateway-esp8266
--------------------------------------------------------------------------------
/Phyton3, modbus_tk tcp, esp8266, multi_influx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Phyton3, modbus_tk tcp, esp8266, multi_influx
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Modbus-Logger
2 | Log your modbus-rtu device data on a Raspberry Pi/Orange Pi and plot graphs of your data.
3 | Its been verified to work with a Raspberry Pi with a Linksprite RS485 shield and Orange Pi Zero with USB to RS485 adapter for reading values from ABB ACS310 anda ABB ACS810. By changing the devices.yml file and making a corresponding [model].yml file it should be possible to use other modbus enabled models.
4 |
5 | Add support for ModbusTCP and add bridge RTU to TCP vía ESP8266 and multi Influx_DB databases
6 |
7 | ### Requirements
8 |
9 | #### Hardware
10 |
11 | * Raspberry Pi 3 / Orange Pi Zero
12 | * [Linksprite RS485 Shield V3 for RPi](http://linksprite.com/wiki/index.php5?title=RS485/GPIO_Shield_for_Raspberry_Pi_V3.0) or a simpe [USB RS485 adapter](https://es.aliexpress.com/item/HOT-SALE-2pcs-lot-USB-to-RS485-485-Converter-Adapter-Support-Win7-XP-Vista-Linux-Mac/1699271296.html)
13 | * Modbus based device.
14 |
15 | #### Software
16 |
17 | * Rasbian or armbian
18 | * Python 3.4 and PIP3
19 | * PyYAML 5.1 (pip3 install -U PyYAML if installed)
20 | * [modbus_tk](https://github.com/ljean/modbus-tk)
21 | * [InfluxDB](https://docs.influxdata.com/influxdb/v2.7/)
22 | * [Grafana](http://docs.grafana.org/)
23 |
24 | ### Prerequisite
25 |
26 | ### Installation
27 | #### Install InfluxDB*
28 |
29 | ##### Step-by-step instructions
30 | * Add the InfluxData repository
31 | ```sh
32 | $ wget -q https://repos.influxdata.com/influxdata-archive_compat.key
33 | $ echo '393e8779c89ac8d958f81f942f9ad7fb82a25e133faddaf92e15b16e6ac9ce4c influxdata-archive_compat.key' | sha256sum -c && cat influxdata-archive_compat.key | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/influxdata-archive_compat.gpg > /dev/null
34 | $ echo 'deb [signed-by=/etc/apt/trusted.gpg.d/influxdata-archive_compat.gpg] https://repos.influxdata.com/debian stable main' | sudo tee /etc/apt/sources.list.d/influxdata.list
35 | ```
36 | * Download and install
37 | ```sh
38 | $ sudo apt-get update && sudo apt-get install influxdb2
39 | ```
40 | * Start the influxdb service
41 | ```sh
42 | $ sudo systemctl start influxdb
43 | ```
44 | * Create the database (databases are named buckets in influxdb2)
45 | ```sh
46 | $ influx bucket create -n db_modbus --org myorg
47 | ```
48 | or user webui at `http://localhost:8086`
49 | * Create a token
50 | ```sh
51 | $ influx auth create -o myorg --all-access
52 | ```
53 | or user webui at `http://localhost:8086`
54 |
55 | [*manual installation without apt](https://docs.influxdata.com/influxdb/v2.7/install/)
56 |
57 | #### Install Grafana*
58 |
59 | ##### Step-by-step instructions
60 | * Add APT Repository
61 | ```sh
62 | $ echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee -a /etc/apt/sources.list.d/grafana.list
63 | ```
64 | * Add Bintray key
65 | ```sh
66 | $ curl https://packages.grafana.com/gpg.key | sudo apt-key add -
67 | ```
68 | * Now install
69 | ```sh
70 | $ sudo apt-get update && sudo apt-get install grafana
71 | ```
72 | * Start the service using systemd:
73 | ```sh
74 | $ sudo systemctl daemon-reload
75 | $ sudo systemctl start grafana-server
76 | $ systemctl status grafana-server
77 | ```
78 | * Enable the systemd service so that Grafana starts at boot.
79 | ```sh
80 | $ sudo systemctl enable grafana-server.service
81 | ```
82 | * Go to http://localhost:3000 and login using admin / admin (remember to change password)
83 | [*source](http://docs.grafana.org/installation/debian/)
84 |
85 | #### Install Modbus Logger:
86 | * Download and install from Github and install pip3
87 | ```sh
88 | $ git clone https://github.com/GuillermoElectrico/modbus-logger.git
89 | $ sudo apt-get install python3-pip
90 | ```
91 | * Run setup script (must be executed as root (sudo) if the application needs to be started from rc.local, see below)
92 | ```sh
93 | $ cd modbus-logger
94 | $ sudo python3 setup.py install
95 | ```
96 | * Make script file executable
97 | ```sh
98 | $ chmod 777 read_modbus_device.py
99 | ```
100 | * Edit devices.yml to match your configuration
101 | * Test the configuration by running:
102 | ```sh
103 | ./read_modbus_device.py
104 | ./read_modbus_device.py --help # Shows you all available parameters
105 | ```
106 | * To run the python script at system startup. Add to following lines to the end of /etc/rc.local but before exit:
107 | ```sh
108 | # Start Modbus-Logger
109 | /home/pi/Modbus-Logger/read_modbus_device.py --interval 60 > /var/log/modbus-logger.log &
110 | ```
111 | Log with potential errors are found in /var/log/modbus-logger.log
112 |
--------------------------------------------------------------------------------
/Recommended mount for Orange Pi Zero/Din_Mount_Orange_Pi_Zero.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Recommended mount for Orange Pi Zero/Din_Mount_Orange_Pi_Zero.zip
--------------------------------------------------------------------------------
/Recommended mount for Raspberry Pi/Raspberry_Pi_Wall_Mounted_Case_-_Ideal_for_Pi-Hole.zip:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/GuillermoElectrico/modbus-logger/b39b8f96c2d627aad7720d01a1525afeaae310e1/Recommended mount for Raspberry Pi/Raspberry_Pi_Wall_Mounted_Case_-_Ideal_for_Pi-Hole.zip
--------------------------------------------------------------------------------
/VACON20.yml:
--------------------------------------------------------------------------------
1 | Frecuencia Salida :
2 | - 0 # Adress dec data
3 | - 1 # Length word
4 | - 3 # Data Type. 1=Float(ABCD), 2=Long(ABCD), 3=Integer, 4=Long(CDAB), 5=Word (Unsigned Int), 6=Dword (Unsigned Long), 7=Float(CDAB)*
5 | Intensidad Motor :
6 | - 2
7 | - 1
8 | - 3
9 | Tension del Motor :
10 | - 5
11 | - 1
12 | - 3
13 | Tensión del BUS CC :
14 | - 6
15 | - 1
16 | - 3
17 | Temperatura del convertidor :
18 | - 7
19 | - 1
20 | - 3
21 | Potencia de salida :
22 | - 78
23 | - 1
24 | - 3
25 | DIN1-DIN2-DIN3 :
26 | - 14
27 | - 1
28 | - 3
29 | DIN4-DIN5-DIN6 :
30 | - 15
31 | - 1
32 | - 3
33 | RO1-RO2-DO :
34 | - 16
35 | - 1
36 | - 3
37 | Valor actual de presion :
38 | - 1615
39 | - 1
40 | - 3
--------------------------------------------------------------------------------
/devices.yml:
--------------------------------------------------------------------------------
1 | devices:
2 | - name : Device Group 1
3 | type : ACQ810.yml
4 | conexion: R # R = RTU 232/485 | T = TCP IPv4
5 | id : 1 # this is the slave address number
6 | baudrate : 9600 # Baud
7 | bytesize : 8
8 | parity : 'N' # 'N' = none | 'E' = even | 'O' = odd | 'S' = space| 'M' = mark
9 | stopbits : 1
10 | timeout : 0.5 # seconds
11 | function : 3 # 3 = Read Holding register or 4 = Read Input register
12 | - name : Device Group 2
13 | type : ACS310.yml
14 | conexion: R # R = RTU 232/485 | T = TCP IPv4
15 | id : 10 # this is the slave address number
16 | baudrate : 9600 # Baud
17 | bytesize : 8
18 | parity : 'N' # 'N' = none | 'E' = even | 'O' = odd | 'S' = space| 'M' = mark
19 | stopbits : 1
20 | timeout : 0.5 # seconds
21 | function : 3 # 3 = Read Holding register or 4 = Read Input register
22 | - name : Meter Group 3
23 | type : VACON20.yml
24 | conexion: T # R = RTU 232/485 | T = TCP IPv4
25 | id : 1 # this is the slave address number
26 | direction : 192.168.0.123 # IPv4 destination address
27 | port : 502 # destination port
28 | timeout : 5.0 # seconds
29 | function : 4 # 3 = Read Holding register or 4 = Read Input register
30 |
--------------------------------------------------------------------------------
/influx_config.yml:
--------------------------------------------------------------------------------
1 | influxdb:
2 | - name : Local InfluxDB
3 | url : 'http://localhost:8086'
4 | token: 'WW91ciBiYXNlNjQgZW5jb2RlZCB0b2tlbiBnb2VzIGhlcmUu' #Your base64 encoded token goes here.
5 | org: 'myorg'
6 | dbname : 'db_modbus' #keep in mind that dbname will be db_modbus/autogen after upgrading form 1.8 to 2.x
7 | interval : 1
--------------------------------------------------------------------------------
/read_modbus_device.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | from influxdb_client import InfluxDBClient
4 | from influxdb_client.client.write_api import SYNCHRONOUS
5 | from datetime import datetime, timedelta
6 | from os import path
7 | import sys
8 | import os
9 | import serial
10 | import time
11 | import yaml
12 | import logging
13 | import modbus_tk
14 | import modbus_tk.defines as cst
15 | from modbus_tk import modbus_rtu
16 | from modbus_tk import modbus_tcp
17 | import struct
18 |
19 | #PORT = 1
20 | PORT = '/dev/ttyUSB0'
21 | #PORT = '/dev/serial/by-id/usb-1a86_USB2.0-Serial-if00-port0'
22 |
23 | # Change working dir to the same dir as this script
24 | os.chdir(sys.path[0])
25 |
26 | class DataCollector:
27 | def __init__(self, influx_yaml, device_yaml):
28 | self.influx_yaml = influx_yaml
29 | self.influx_map = None
30 | self.influx_map_last_change = -1
31 | self.influx_inteval_save = dict()
32 | log.info('InfluxDB:')
33 | for influx_config in sorted(self.get_influxdb(), key=lambda x:sorted(x.keys())):
34 | log.info('\t {} <--> {}'.format(influx_config['url'], influx_config['name']))
35 | self.device_yaml = device_yaml
36 | self.max_iterations = None # run indefinitely by default
37 | self.device_map = None
38 | self.device_map_last_change = -1
39 | log.info('Devices:')
40 | for device in sorted(self.get_devices(), key=lambda x:sorted(x.keys())):
41 | log.info('\t {} <--> {}'.format( device['id'], device['name']))
42 |
43 | def get_devices(self):
44 | assert path.exists(self.device_yaml), 'Device map not found: %s' % self.device_yaml
45 | if path.getmtime(self.device_yaml) != self.device_map_last_change:
46 | try:
47 | log.info('Reloading device map as file changed')
48 | new_map = yaml.load(open(self.device_yaml), Loader=yaml.FullLoader)
49 | self.device_map = new_map['devices']
50 | self.device_map_last_change = path.getmtime(self.device_yaml)
51 | except Exception as e:
52 | log.warning('Failed to re-load device map, going on with the old one.')
53 | log.warning(e)
54 | return self.device_map
55 |
56 | def get_influxdb(self):
57 | assert path.exists(self.influx_yaml), 'InfluxDB map not found: %s' % self.influx_yaml
58 | if path.getmtime(self.influx_yaml) != self.influx_map_last_change:
59 | try:
60 | log.info('Reloading influxDB map as file changed')
61 | new_map = yaml.load(open(self.influx_yaml), Loader=yaml.FullLoader)
62 | self.influx_map = new_map['influxdb']
63 | self.influx_map_last_change = path.getmtime(self.influx_yaml)
64 | list = 0
65 | for influx_config in sorted(self.get_influxdb(), key=lambda x:sorted(x.keys())):
66 | list = list + 1
67 | self.influx_inteval_save[list] = influx_config['interval']
68 | except Exception as e:
69 | log.warning('Failed to re-load influxDB map, going on with the old one.')
70 | log.warning(e)
71 | return self.influx_map
72 |
73 | def collect_and_store(self):
74 | #instrument.debug = True
75 | devices = self.get_devices()
76 | influxdb = self.get_influxdb()
77 | t_utc = datetime.utcnow()
78 | t_str = t_utc.isoformat() + 'Z'
79 |
80 | datas = dict()
81 | device_id_name = dict() # mapping id to name
82 | device_slave_id = dict() # mapping list to id
83 | list = 0
84 |
85 | for device in devices:
86 | list = list + 1
87 | device_id_name[list] = device['name']
88 | device_slave_id[list] = device['id']
89 |
90 | try:
91 | if device['conexion'] == 'R':
92 | masterRTU = modbus_rtu.RtuMaster(
93 | serial.Serial(port=PORT, baudrate=device['baudrate'], bytesize=device['bytesize'], parity=device['parity'], stopbits=device['stopbits'], xonxoff=0)
94 | )
95 |
96 | masterRTU.set_timeout(device['timeout'])
97 | masterRTU.set_verbose(True)
98 |
99 | log.debug('Reading device %s.' % (device['name']))
100 | start_time = time.time()
101 | parameters = yaml.load(open(device['type']), Loader=yaml.FullLoader)
102 | datas[list] = dict()
103 |
104 | for parameter in parameters:
105 | # If random readout errors occour, e.g. CRC check fail, test to uncomment the following row
106 | #time.sleep(0.5) # Sleep for 500 ms between each parameter read to avoid errors
107 | retries = 10
108 | while retries > 0:
109 | try:
110 | retries -= 1
111 | if device['function'] == 3:
112 | if parameters[parameter][2] == 1:
113 | resultado = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>f')
114 | elif parameters[parameter][2] == 2:
115 | resultado = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>l')
116 | elif parameters[parameter][2] == 3:
117 | resultado = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1])
118 | elif parameters[parameter][2] == 4:
119 | resultadoTemp = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1])
120 | resultado = [0,0]
121 | resultado[0] = (resultadoTemp[1]<<16)|resultadoTemp[0]
122 | elif parameters[parameter][2] == 5:
123 | resultado = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>I')
124 | elif parameters[parameter][2] == 6:
125 | resultado = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>L')
126 | elif parameters[parameter][2] == 7:
127 | resultadoTemp = masterRTU.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1])
128 | resultado = [0,0]
129 | resultado[0] = struct.unpack('f', struct.pack('I', (resultadoTemp[1]<<16)|resultadoTemp[0]))[0]
130 | elif device['function'] == 4:
131 | if parameters[parameter][2] == 1:
132 | resultado = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>f')
133 | elif parameters[parameter][2] == 2:
134 | resultado = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>l')
135 | elif parameters[parameter][2] == 3:
136 | resultado = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1])
137 | elif parameters[parameter][2] == 4:
138 | resultadoTemp = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1])
139 | resultado = [0,0]
140 | resultado[0] = (resultadoTemp[1]<<16)|resultadoTemp[0]
141 | elif parameters[parameter][2] == 5:
142 | resultado = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>I')
143 | elif parameters[parameter][2] == 6:
144 | resultado = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>L')
145 | elif parameters[parameter][2] == 7:
146 | resultadoTemp = masterRTU.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1])
147 | resultado = [0,0]
148 | resultado[0] = struct.unpack('f', struct.pack('I', (resultadoTemp[1]<<16)|resultadoTemp[0]))[0]
149 | datas[list][parameter] = resultado[0]
150 | retries = 0
151 | pass
152 | except ValueError as ve:
153 | log.warning('Value Error while reading register {} from device {}. Retries left {}.'
154 | .format(parameters[parameter], device['id'], retries))
155 | log.error(ve)
156 | if retries == 0:
157 | raise RuntimeError
158 | except TypeError as te:
159 | log.warning('Type Error while reading register {} from device {}. Retries left {}.'
160 | .format(parameters[parameter], device['id'], retries))
161 | log.error(te)
162 | if retries == 0:
163 | raise RuntimeError
164 | except IOError as ie:
165 | log.warning('IO Error while reading register {} from device {}. Retries left {}.'
166 | .format(parameters[parameter], device['id'], retries))
167 | log.error(ie)
168 | if retries == 0:
169 | raise RuntimeError
170 | except:
171 | log.error("Unexpected error:", sys.exc_info()[0])
172 | raise
173 |
174 | datas[list]['ReadTime'] = time.time() - start_time
175 | elif device['conexion'] == 'T':
176 | masterTCP = modbus_tcp.TcpMaster(host=device['direction'],port=device['port'])
177 |
178 | masterTCP.set_timeout(device['timeout'])
179 |
180 | log.debug('Reading device %s.' % (device['name']))
181 | start_time = time.time()
182 | parameters = yaml.load(open(device['type']), Loader=yaml.FullLoader)
183 | datas[list] = dict()
184 |
185 | for parameter in parameters:
186 | # If random readout errors occour, e.g. CRC check fail, test to uncomment the following row
187 | #time.sleep(0.01) # Sleep for 10 ms between each parameter read to avoid errors
188 | retries = 10
189 | while retries > 0:
190 | try:
191 | retries -= 1
192 | if device['function'] == 3:
193 | if parameters[parameter][2] == 1:
194 | resultado = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>f')
195 | elif parameters[parameter][2] == 2:
196 | resultado = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>l')
197 | elif parameters[parameter][2] == 3:
198 | resultado = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1])
199 | elif parameters[parameter][2] == 4:
200 | resultadoTemp = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1])
201 | resultado = [0,0]
202 | resultado[0] = (resultadoTemp[1]<<16)|resultadoTemp[0]
203 | elif parameters[parameter][2] == 5:
204 | resultado = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>I')
205 | elif parameters[parameter][2] == 6:
206 | resultado = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>L')
207 | elif parameters[parameter][2] == 7:
208 | resultadoTemp = masterTCP.execute(device['id'], cst.READ_HOLDING_REGISTERS, parameters[parameter][0], parameters[parameter][1])
209 | resultado = [0,0]
210 | resultado[0] = struct.unpack('f', struct.pack('I', (resultadoTemp[1]<<16)|resultadoTemp[0]))[0]
211 | elif device['function'] == 4:
212 | if parameters[parameter][2] == 1:
213 | resultado = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>f')
214 | elif parameters[parameter][2] == 2:
215 | resultado = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>l')
216 | elif parameters[parameter][2] == 3:
217 | resultado = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1])
218 | elif parameters[parameter][2] == 4:
219 | resultadoTemp = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1])
220 | resultado = [0,0]
221 | resultado[0] = (resultadoTemp[1]<<16)|resultadoTemp[0]
222 | elif parameters[parameter][2] == 5:
223 | resultado = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>I')
224 | elif parameters[parameter][2] == 6:
225 | resultado = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1], data_format='>L')
226 | elif parameters[parameter][2] == 7:
227 | resultadoTemp = masterTCP.execute(device['id'], cst.READ_INPUT_REGISTERS, parameters[parameter][0], parameters[parameter][1])
228 | resultado = [0,0]
229 | resultado[0] = struct.unpack('f', struct.pack('I', (resultadoTemp[1]<<16)|resultadoTemp[0]))[0]
230 | datas[list][parameter] = resultado[0]
231 | retries = 0
232 | pass
233 | except ValueError as ve:
234 | log.warning('Value Error while reading register {} from device {}. Retries left {}.'
235 | .format(parameters[parameter], device['id'], retries))
236 | log.error(ve)
237 | if retries == 0:
238 | raise RuntimeError
239 | except TypeError as te:
240 | log.warning('Type Error while reading register {} from device {}. Retries left {}.'
241 | .format(parameters[parameter], device['id'], retries))
242 | log.error(te)
243 | if retries == 0:
244 | raise RuntimeError
245 | except IOError as ie:
246 | log.warning('IO Error while reading register {} from device {}. Retries left {}.'
247 | .format(parameters[parameter], device['id'], retries))
248 | log.error(ie)
249 | if retries == 0:
250 | raise RuntimeError
251 | except:
252 | log.error("Unexpected error:", sys.exc_info()[0])
253 | raise
254 |
255 | datas[list]['ReadTime'] = time.time() - start_time
256 |
257 | except modbus_tk.modbus.ModbusError as exc:
258 | log.error("%s- Code=%d", exc, exc.get_exception_code())
259 |
260 | json_body = [
261 | {
262 | 'measurement': 'ModbusLog',
263 | 'tags': {
264 | 'id': device_slave_id[device_id],
265 | 'device': device_id_name[device_id],
266 | },
267 | 'time': t_str,
268 | 'fields': datas[device_id]
269 | }
270 | for device_id in datas
271 | ]
272 | if len(json_body) > 0:
273 |
274 | # log.debug(json_body)
275 |
276 | list = 0
277 |
278 | for influx_config in influxdb:
279 | list = list + 1
280 | if self.influx_inteval_save[list] > 0:
281 | if self.influx_inteval_save[list] <= 1:
282 | self.influx_inteval_save[list] = influx_config['interval']
283 |
284 | DBclient = InfluxDBClient(url=influx_config['url'], token=influx_config['token'], org=influx_config['org'])
285 | write_api = DBclient.write_api(write_options=SYNCHRONOUS)
286 | try:
287 | write_api.write(bucket=influx_config['dbname'],org=influx_config['org'],record=json_body)
288 | log.info(t_str + ' Data written for %d meters in {}.' .format(influx_config['name']) % len(json_body) )
289 | except Exception as e:
290 | log.error('Data not written! in {}' .format(influx_config['name']))
291 | log.error(e)
292 | raise
293 | else:
294 | self.influx_inteval_save[list] = self.influx_inteval_save[list] - 1
295 | else:
296 | log.warning(t_str, 'No data sent.')
297 |
298 |
299 | def repeat(interval_sec, max_iter, func, *args, **kwargs):
300 | from itertools import count
301 | import time
302 | starttime = time.time()
303 | for i in count():
304 | if interval_sec > 0:
305 | time.sleep(interval_sec - ((time.time() - starttime) % interval_sec))
306 | if i % 1000 == 0:
307 | log.info('Collected %d readouts' % i)
308 | try:
309 | func(*args, **kwargs)
310 | except Exception as ex:
311 | log.error(ex)
312 | if max_iter and i >= max_iter:
313 | return
314 |
315 |
316 | if __name__ == '__main__':
317 |
318 | import argparse
319 |
320 | parser = argparse.ArgumentParser()
321 | parser.add_argument('--interval', default=60,
322 | help='Device readout interval (seconds), default 60')
323 | parser.add_argument('--devices', default='devices.yml',
324 | help='YAML file containing Device ID, name, type etc. Default "devices.yml"')
325 | parser.add_argument('--influxdb', default='influx_config.yml',
326 | help='YAML file containing Influx Host, port, user etc. Default "influx_config.yml"')
327 | parser.add_argument('--log', default='CRITICAL',
328 | help='Log levels, DEBUG, INFO, WARNING, ERROR or CRITICAL')
329 | parser.add_argument('--logfile', default='',
330 | help='Specify log file, if not specified the log is streamed to console')
331 | args = parser.parse_args()
332 | interval = int(args.interval)
333 | loglevel = args.log.upper()
334 | logfile = args.logfile
335 |
336 | # Setup logging
337 | log = logging.getLogger('modbus-logger')
338 | log.setLevel(getattr(logging, loglevel))
339 |
340 | if logfile:
341 | loghandle = logging.FileHandler(logfile, 'w')
342 | formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
343 | loghandle.setFormatter(formatter)
344 | else:
345 | loghandle = logging.StreamHandler()
346 |
347 | log.addHandler(loghandle)
348 |
349 | log.info('Started app')
350 |
351 | collector = DataCollector(influx_yaml=args.influxdb,
352 | device_yaml=args.devices)
353 |
354 | repeat(interval,
355 | max_iter=collector.max_iterations,
356 | func=lambda: collector.collect_and_store())
357 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import sys
2 | from setuptools import setup
3 |
4 | setup(name='modbus_logger',
5 | version=1.1,
6 | description='Read data using RS485 Modbus '+
7 | 'and store in local database.',
8 | url='https://github.com/GuillermoElectrico/modbus-logger',
9 | download_url='',
10 | author='Samuel Vestlin',
11 | author_email='samuel@elphy.se',
12 | platforms='Raspberry Pi',
13 | classifiers=[
14 | 'Development Status :: 4 - Beta',
15 | 'Intended Audience :: Developers',
16 | 'License :: MIT License',
17 | 'Operating System :: Raspbian-Armbian',
18 | 'Programming Language :: Python :: 3.5'
19 | ],
20 | keywords='Logger RS485 Modbus',
21 | install_requires=[]+(['setuptools','ez_setup','pyserial','modbus_tk', 'influxdb-client', 'pyyaml'] if "linux" in sys.platform else []),
22 | license='MIT',
23 | packages=[],
24 | include_package_data=True,
25 | tests_require=[],
26 | test_suite='',
27 | zip_safe=True)
28 |
--------------------------------------------------------------------------------
/start_status_reboot.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ## Service or script to monitor if it is running
4 | SERVICE=read_modbus_device.py
5 |
6 | while :
7 | do
8 | result=$(ps ax|grep -v grep|grep $SERVICE)
9 | # echo ${#result}
10 | if [ ${#result} != 0 ]
11 | then
12 | # everything is ok
13 | # every 10 seconds we test if it is still ok
14 | sleep 10
15 | else
16 | # is not working
17 | # start script (in this case a python script)
18 | home/pi/Modbus-Logger/$SERVICE --interval 60 > /var/log/modbus-logger.log &
19 | # we wait for it to load
20 | sleep 10
21 | fi
22 | done
--------------------------------------------------------------------------------