Updating - extrusion/lydia-print-head-v1

This commit is contained in:
lovebird 2024-10-01 14:20:45 +02:00
parent ba6febc286
commit 3bc9c87db0
216 changed files with 32337 additions and 0 deletions

104
extrusion/lydia-print-head-v1/.gitignore vendored Normal file
View File

@ -0,0 +1,104 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port

View File

@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <https://unlicense.org>

View File

@ -0,0 +1,199 @@
CERN Open Hardware Licence Version 2 - Permissive
Preamble
CERN has developed this licence to promote collaboration among
hardware designers and to provide a legal tool which supports the
freedom to use, study, modify, share and distribute hardware designs
and products based on those designs. Version 2 of the CERN Open
Hardware Licence comes in three variants: this licence, CERN-OHL-P
(permissive); and two reciprocal licences: CERN-OHL-W (weakly
reciprocal) and CERN-OHL-S (strongly reciprocal).
The CERN-OHL-P is copyright CERN 2020. Anyone is welcome to use it, in
unmodified form only.
Use of this Licence does not imply any endorsement by CERN of any
Licensor or their designs nor does it imply any involvement by CERN in
their development.
1 Definitions
1.1 'Licence' means this CERN-OHL-P.
1.2 'Source' means information such as design materials or digital
code which can be applied to Make or test a Product or to
prepare a Product for use, Conveyance or sale, regardless of its
medium or how it is expressed. It may include Notices.
1.3 'Covered Source' means Source that is explicitly made available
under this Licence.
1.4 'Product' means any device, component, work or physical object,
whether in finished or intermediate form, arising from the use,
application or processing of Covered Source.
1.5 'Make' means to create or configure something, whether by
manufacture, assembly, compiling, loading or applying Covered
Source or another Product or otherwise.
1.6 'Notice' means copyright, acknowledgement and trademark notices,
references to the location of any Notices, modification notices
(subsection 3.3(b)) and all notices that refer to this Licence
and to the disclaimer of warranties that are included in the
Covered Source.
1.7 'Licensee' or 'You' means any person exercising rights under
this Licence.
1.8 'Licensor' means a person who creates Source or modifies Covered
Source and subsequently Conveys the resulting Covered Source
under the terms and conditions of this Licence. A person may be
a Licensee and a Licensor at the same time.
1.9 'Convey' means to communicate to the public or distribute.
2 Applicability
2.1 This Licence governs the use, copying, modification, Conveying
of Covered Source and Products, and the Making of Products. By
exercising any right granted under this Licence, You irrevocably
accept these terms and conditions.
2.2 This Licence is granted by the Licensor directly to You, and
shall apply worldwide and without limitation in time.
2.3 You shall not attempt to restrict by contract or otherwise the
rights granted under this Licence to other Licensees.
2.4 This Licence is not intended to restrict fair use, fair dealing,
or any other similar right.
3 Copying, Modifying and Conveying Covered Source
3.1 You may copy and Convey verbatim copies of Covered Source, in
any medium, provided You retain all Notices.
3.2 You may modify Covered Source, other than Notices.
You may only delete Notices if they are no longer applicable to
the corresponding Covered Source as modified by You and You may
add additional Notices applicable to Your modifications.
3.3 You may Convey modified Covered Source (with the effect that You
shall also become a Licensor) provided that You:
a) retain Notices as required in subsection 3.2; and
b) add a Notice to the modified Covered Source stating that You
have modified it, with the date and brief description of how
You have modified it.
3.4 You may Convey Covered Source or modified Covered Source under
licence terms which differ from the terms of this Licence
provided that:
a) You comply at all times with subsection 3.3; and
b) You provide a copy of this Licence to anyone to whom You
Convey Covered Source or modified Covered Source.
4 Making and Conveying Products
You may Make Products, and/or Convey them, provided that You ensure
that the recipient of the Product has access to any Notices applicable
to the Product.
5 DISCLAIMER AND LIABILITY
5.1 DISCLAIMER OF WARRANTY -- The Covered Source and any Products
are provided 'as is' and any express or implied warranties,
including, but not limited to, implied warranties of
merchantability, of satisfactory quality, non-infringement of
third party rights, and fitness for a particular purpose or use
are disclaimed in respect of any Source or Product to the
maximum extent permitted by law. The Licensor makes no
representation that any Source or Product does not or will not
infringe any patent, copyright, trade secret or other
proprietary right. The entire risk as to the use, quality, and
performance of any Source or Product shall be with You and not
the Licensor. This disclaimer of warranty is an essential part
of this Licence and a condition for the grant of any rights
granted under this Licence.
5.2 EXCLUSION AND LIMITATION OF LIABILITY -- The Licensor shall, to
the maximum extent permitted by law, have no liability for
direct, indirect, special, incidental, consequential, exemplary,
punitive or other damages of any character including, without
limitation, procurement of substitute goods or services, loss of
use, data or profits, or business interruption, however caused
and on any theory of contract, warranty, tort (including
negligence), product liability or otherwise, arising in any way
in relation to the Covered Source, modified Covered Source
and/or the Making or Conveyance of a Product, even if advised of
the possibility of such damages, and You shall hold the
Licensor(s) free and harmless from any liability, costs,
damages, fees and expenses, including claims by third parties,
in relation to such use.
6 Patents
6.1 Subject to the terms and conditions of this Licence, each
Licensor hereby grants to You a perpetual, worldwide,
non-exclusive, no-charge, royalty-free, irrevocable (except as
stated in this section 6, or where terminated by the Licensor
for cause) patent license to Make, have Made, use, offer to
sell, sell, import, and otherwise transfer the Covered Source
and Products, where such licence applies only to those patent
claims licensable by such Licensor that are necessarily
infringed by exercising rights under the Covered Source as
Conveyed by that Licensor.
6.2 If You institute patent litigation against any entity (including
a cross-claim or counterclaim in a lawsuit) alleging that the
Covered Source or a Product constitutes direct or contributory
patent infringement, or You seek any declaration that a patent
licensed to You under this Licence is invalid or unenforceable
then any rights granted to You under this Licence shall
terminate as of the date such process is initiated.
7 General
7.1 If any provisions of this Licence are or subsequently become
invalid or unenforceable for any reason, the remaining
provisions shall remain effective.
7.2 You shall not use any of the name (including acronyms and
abbreviations), image, or logo by which the Licensor or CERN is
known, except where needed to comply with section 3, or where
the use is otherwise allowed by law. Any such permitted use
shall be factual and shall not be made so as to suggest any kind
of endorsement or implication of involvement by the Licensor or
its personnel.
7.3 CERN may publish updated versions and variants of this Licence
which it considers to be in the spirit of this version, but may
differ in detail to address new problems or concerns. New
versions will be published with a unique version number and a
variant identifier specifying the variant. If the Licensor has
specified that a given variant applies to the Covered Source
without specifying a version, You may treat that Covered Source
as being released under any version of the CERN-OHL with that
variant. If no variant is specified, the Covered Source shall be
treated as being released under CERN-OHL-S. The Licensor may
also specify that the Covered Source is subject to a specific
version of the CERN-OHL or any later version in which case You
may apply this or any later version of CERN-OHL with the same
variant identifier published by CERN.
7.4 This Licence shall not be enforceable except by a Licensor
acting as such, and third party beneficiary rights are
specifically excluded.

View File

@ -0,0 +1,164 @@
# Robot driven print systems
***brief*** this is part of our work of PP OpenSource contributions, please check our [library](https://library.precious-plastic.org/) or our [main page](https://plastic-hub.com/products/) for more.
The print head is a modification of [Lydia-v4](https://plastic-hub.com/products/lydia-v4.html) and aims at a generic solution for most of it´s components.
**Status** : Confirmed & in progress, ETA Mid. of October
## Todos
* [x] Motor selection
* [ ] Firmware updates
+ [x] Check TCP stack memory/CPU footprint on the ControllinoMega
* [x] Sensors / Audio, LED feedback (status, etc... )
* [-] Support [RAPID - ABB robots, but uses customer spec](https://library.e.abb.com/public/688894b98123f87bc1257cc50044e809/Technical%20reference%20manual_RAPID_3HAC16581-1_revJ_en.pdf)
### Todos Frederike@3dtreehouse
* [x] Gantry mount plate, we need the size and locations of the mount holes. We'd need a test rig here.
* [x] Location and size of the cabinet, what on the control panel (controls & plugs) ?
* [x] We have to know how we share power source & ground among all digital circuits. Currently we're mostly at 24V and we need another source for 12V (fans, etc...)
* [x] Clarify RAPID ethernet connectivity
- [x] local setup / updates ?
- [x] screw tip / max. barrel length / screw mod
- [x] Fan control
## Components
### VFD
* [x] [OMRON MX2 VFD](https://industrial.omron.es/es/products/3G3MX2-A2022-E) [BOM](https://es.wiautomation.com/omron/variadores-motores-proteccion-de-circuitos/3G3MX2A2022E?SubmitCurrency=1&id_currency=1&gclid=Cj0KCQjwy8f6BRC7ARIsAPIXOjgnGbRSd_DaX-o59wjtIBqI2mGllXWWOvjhSC1sPQgOTmGMvc7toncaAqejEALw_wcB)
* [ ] [3G3MX2-A2015-E](https://es.wiautomation.com/omron/variadores-motores-proteccion-de-circuitos/3G3MX2A2015E?utm_source=shopping_free&utm_medium=organic&utm_content=ES105728&gclid=Cj0KCQjwgYSTBhDKARIsAB8KuksIYzB6ATQnPv1r7SiF5Z1-2ySXLYHNzPDPoK95TaC2jr17-ueXM_8aAtZiEALw_wcB)
### I/O Breakout
- [x] Controllino - Mega as already mentioned a few times, adds 280 Euro
- [-] Arduino - Portena - Machine Control (https://www.arduino.cc/pro/hardware/product/portenta-machine-control)
### PID Controller
* [x] ModBus capable PID controllers (3x) : [Omron - E5DC-B](https://industrial.omron.eu/en/products/E5DC-QX2ASM-002) - Din - Rail Module [WiAutomation - Out of stock](https://es.wiautomation.com/omron/plc-sistemas/E5DCQX2ASM002?SubmitCurrency=1&id_currency=1&gclid=Cj0KCQjwy8f6BRC7ARIsAPIXOjgWMeg-P2iN7wysDExpeHJHtEHAv06B2pKTz3DQlKjn67Al2K7YvvMaAs4IEALw_wcB)
* [x] ModBus capable PID controllers (2x) : [E5DC-CX2DBM-000 OMRON](https://industrial.omron.eu/en/products/E5DC-QX2ASM-002) - Din - Rail Module [WiAutomation](https://es.wiautomation.com/omron/productos-generales/E5DCCX2DBM000)
### Motor
* [ ] Motor [Cidepa](https://www.cidepa-sincron.com/en/25/cfm-parallel-shafts-gearboxes) - CFM-37.3 1/35 1 | 750W | 1.2SF
### Noah OS Variant
* [x] [PLC/Proxy for Aux, Sensors, Relays, etc... - CP1L-EM40DT1-D](http://www.ia.omron.com/products/family/1916/lineup.html), works well with [Omron NB NB3Q-TW01B](https://es.wiautomation.com/omron/hmi-pc-industriales/NB3QTW01B?SubmitCurrency=1&id_currency=1&gclid=CjwKCAjwh7H7BRBBEiwAPXjadt5G-53T-xJ8v5VmzdF5wUu8uHT1us-fzXU5913IwC3Kbz4cDg3jnBoC7g0QAvD_BwE)
### Specs
- Voltage : 220V|380V
- [ ] Max. 120Kg, first rev. might be around 60KG
- [ ] Controller cable length around 20 meter
- [ ] PID : +/- 5 degc tolerance, alarm/cooling outputs
### Gantry Mount
- [ ] : run static tests
* the tool flange is on p30, ([see also ATI Toolchanger - YuTu](https://www.youtube.com/watch?v=kDP-oofDn4w&feature=youtu.be))
* [Why ATI Manual Tool Changers?](https://www.youtube.com/watch?v=N2Pr0tAsYkU&ab_channel=ATIIndustrialAutomation)
* [x] we need a laser cut barrel shield which holds the insulation material
* [x] on the barrel tip, we need some mounting possibilties for fans which are a little heavy as well
- [ ] ATI mount ([see ATI Tool changers @ 3dcentral](https://www.3dcontentcentral.com/syndication/supplier/ATI%20Industrial%20Automation/147.aspx))
### Firmware
(https://www.controllino.biz/product/controllino-mega/) which gives us Ethernet and RS485. The board has been proven reliable and robust (ideal for prototyping).
- [-] VFD and PID control is mapped to Serial communication which might accept G-Code
- [x] VFD will be Omron-M2X series since we can use existing code. The VFD also supports Modbus (rather difficult)
- [ ] Internal registers/coils (custom PlasticHub Firmware) to Modbus rep
![](./assets/lydia-print-head-logical.jpg)
**[Diagram source](https://app.diagrams.net/#G1L7Prviy9U-2gpcZHm8Z5dj39gxDHd_V_)**
### PID Controller
* [x] We should go for [Omron E5-C](https://assets.omron.com/m/6f7cd0d93654a7a4/original/E5_C-Temperature-Controller-to-NB-Screen-Template-Tech-Guide.pdf) series which come with Modbus (consider EMI and cable length to the main controller)
* [x] Each PID will be exposed on the internal ModBus mapping
* There is currently a [custom PID controller](https://gitlab.com/plastichub/pid-controller) in development but as mentioned, it's unlikely that it sees the light before November. However, I can imagine we use sub-routines as they're avaiable
![](./assets/E5DC-B.jpg)
### Barrel
- [-] OD should be standard to EU heatbands
- [ ] Between Nozzel and barrel we might have some adaptery to exchange different screw tips, up to 10 cm
- [x] should have a mount near the nozzle
- [x] Barrel - motor flange should have some redunancy to enable different barrels
----
### Hopper interface and Hopper
* [x] should have a thread interface
## Todos
* [x] Investigate Omron - PID feedback to enable more control via M/G codes (purge, ...)
* [x] Investigate GCode to ROS mapping
* [x] Investigate screw tip machining, if lucky we get away with 4 axis
* [-] Test different VFD/PID checksum/parity settings with larger EMI around
# References
## ROS (cancelled)
* [ROS - Github](https://github.com/ros-industrial)
* [ROS - GBRL - Github](https://github.com/openautomation/ROS-GRBL/wiki/GRBLtron)
* [ROS - Matlab|SimuLnk](https://www.mathworks.com/help/ros/ug/get-started-with-ros-in-simulink.html)
* [ROS Modbus - Wiki](http://wiki.ros.org/modbus)
* [ROS Modbus - PLC - Github](https://github.com/sonyccd/ros_plc_modbus)
## ProfiBus
* [Instructables Arduino](https://www.instructables.com/Profibus-DP-Communication-Between-Arduino-and-PLC/)
* [Arduino Forum](https://forum.arduino.cc/index.php?topic=458492.0)
- [Specs - PDF](https://forum.arduino.cc/index.php?topic=458492.0)
## Related Projects
* [Project Noah](https://gitlab.com/plastichub/noah)
### Cable robotics
- [The Cable-robot Analysis and Simulation Platform for Research (CASPR)](https://github.com/darwinlau/CASPR)
- [CUHK C3 Robotics Laboratory - Youtube](https://www.youtube.com/channel/UCxadDa3g1fUarP4ldAECtLQ)
### Rapid - ABB
* [Language specs and docs](./vendor/abb/2CSG445026D0201-ANR-LAN-Modbus-TCP-Protocol.pdf)
* [ABB - AC_800M - Protocols](./vendor/abb/3BSE035982-511_en_AC_800M_5.1_Feature_Pack_Communication_Protocols.pdf)
### ABB 6600
<img src="./vendor/abb/abb-irb-6600.jpg" style="width:50%"></img>
- [ABB - IRC - 5 - Controller](https://new.abb.com/products/robotics/controllers/irc5)
- [ABB - IRC - 5 Manuals](./vendor/abb/IRC5_Operating manual_Trouble shooting_3HAC020738-001_revK_en.pdf)
- [ABB - IRC - Datasheet](./vendor/abb/IRC5-Industrial-Robot-Controller-data sheet.PDF)
- [ABB irb 6600 175-2.8](https://library.e.abb.com/public/560fa420555c2d8ac1257b4b0052112c/3HAC023933-001_rev1_en.pdf)
- [ABB irb 6600 175 - 2.8 - Local](./vendor/abb/IRB_6600_R_US 02_05.pdf)
- [ABB 660 - Specs](./vendor/abb/ABB-IR-6600-3HAC14064-1_revH_en_library.pdf)
- [ABB Robotstudio Downloads](https://new.abb.com/products/robotics/robotstudio/downloads)
## Project links
* [Project Slack channel](https://pporgworkspace.slack.com/archives/C01A8G36MRP)
* [Firmware](https://gitlab.com/plastichub/medusa/firmware)
## Follow ups
- [ ] calc. energy overhead, per printed kg of plastic
- [ ] calc. min. invest to print obvious products
- [ ] investigate possible OS verticals
- [ ] develop generic system & functional design for v2.0 candidats, for 6D robots but also cable driven 3D systems
- [ ] check displacement options for segmented prints, (cheap floor track system?)
- [ ] check material remove options (see ATIish tool changers [YT](https://www.youtube.com/watch?v=EvsgCZyQuq0&ab_channel=ATIIndustrialAutomation))

View File

@ -0,0 +1,160 @@
# Robot driven print systems
***brief*** this is part of our work of PP OpenSource contributions, please check our [library](https://library.precious-plastic.org/) or our [main page](https://plastic-hub.com/products/) for more.
The print head is a modification of [Lydia-v4](https://plastic-hub.com/products/lydia-v4.html) and aims at a generic solution for most of it´s components.
**Status** : Confirmed & in progress, ETA Mid. of October
## Todos
* [x] Motor selection
* [ ] Firmware updates
+ [x] Check TCP stack memory/CPU footprint on the ControllinoMega
* [x] Sensors / Audio, LED feedback (status, etc... )
* [ ] Support [RAPID - ABB robots, but uses customer spec](https://library.e.abb.com/public/688894b98123f87bc1257cc50044e809/Technical%20reference%20manual_RAPID_3HAC16581-1_revJ_en.pdf)
### Todos Frederike@3dtreehouse
monday memo:
* [ ] Gantry mount plate, we need the size and locations of the mount holes. We'd need a test rig here.
* [ ] Location and size of the cabinet, what on the control panel (controls & plugs) ?
* [x] We have to know how we share power source & ground among all digital circuits. Currently we're mostly at 24V and we need another source for 12V (fans, etc...)
* [ ] Clarify RAPID ethernet connectivity
- [ ] local setup / updates ?
- [ ] screw tip / max. barrel length / screw mod
- [ ] Fan control
## Components
* [x] [OMRON MX2 VFD](https://industrial.omron.es/es/products/3G3MX2-A2022-E) [BOM](https://es.wiautomation.com/omron/variadores-motores-proteccion-de-circuitos/3G3MX2A2022E?SubmitCurrency=1&id_currency=1&gclid=Cj0KCQjwy8f6BRC7ARIsAPIXOjgnGbRSd_DaX-o59wjtIBqI2mGllXWWOvjhSC1sPQgOTmGMvc7toncaAqejEALw_wcB)
* [ ] [3G3MX2-A2015-E](https://es.wiautomation.com/omron/variadores-motores-proteccion-de-circuitos/3G3MX2A2015E?utm_source=shopping_free&utm_medium=organic&utm_content=ES105728&gclid=Cj0KCQjwgYSTBhDKARIsAB8KuksIYzB6ATQnPv1r7SiF5Z1-2ySXLYHNzPDPoK95TaC2jr17-ueXM_8aAtZiEALw_wcB)
* [x] Controllino - Mega as already mentioned a few times, adds 280 Euro
* [x] a better motor and gearbox - MotoVario
* [ ] custom firmware development
* [x] ModBus capable PID controllers (3x) : [Omron - E5DC-B](https://industrial.omron.eu/en/products/E5DC-QX2ASM-002) - Din - Rail Module [BOM](https://es.wiautomation.com/omron/plc-sistemas/E5DCQX2ASM002?SubmitCurrency=1&id_currency=1&gclid=Cj0KCQjwy8f6BRC7ARIsAPIXOjgWMeg-P2iN7wysDExpeHJHtEHAv06B2pKTz3DQlKjn67Al2K7YvvMaAs4IEALw_wcB)
* [Hopper - Linear Solenoid](https://uk.farnell.com/guardian-electric/t12x19-c-24d/solenoid-pull-operation-24vdc/dp/1608128?gclid=EAIaIQobChMIn4Xa8LPz6wIVEuntCh2SvwcDEAkYASABEgK3uvD_BwE&gross_price=true&mckv=s7TWt3nIG_dc%7Cpcrid%7C459864482330%7Cplid%7C%7Ckword%7C%7Cmatch%7C%7Cslid%7C%7Cproduct%7C1608128%7Cpgrid%7C114464711464%7Cptaid%7Cpla-323868377918%7C&CMP=KNC-GUK-SHOPPING-SMEC-Whoops-Newstructure-31Aug2020)
* [ ] Motor [Cidepa](https://www.cidepa-sincron.com/en/25/cfm-parallel-shafts-gearboxes) - CFM-37.3 1/35 1 | 750W | 1.2SF
### Noah OS Variant
* [x] [PLC/Proxy for Aux, Sensors, Relays, etc... - CP1L-EM40DT1-D](http://www.ia.omron.com/products/family/1916/lineup.html), works well with [Omron NB NB3Q-TW01B](https://es.wiautomation.com/omron/hmi-pc-industriales/NB3QTW01B?SubmitCurrency=1&id_currency=1&gclid=CjwKCAjwh7H7BRBBEiwAPXjadt5G-53T-xJ8v5VmzdF5wUu8uHT1us-fzXU5913IwC3Kbz4cDg3jnBoC7g0QAvD_BwE)
### Specs
- Voltage : 220V|380V
- [ ] Max. 120Kg, first rev. might be around 60KG
- [ ] Controller cable length around 20 meter
- [ ] PID : +/- 5 degc tolerance, alarm/cooling outputs
### Gantry Mount
- [ ] : run static tests
* the tool flange is on p30, ([see also ATI Toolchanger - YuTu](https://www.youtube.com/watch?v=kDP-oofDn4w&feature=youtu.be))
* [Why ATI Manual Tool Changers?](https://www.youtube.com/watch?v=N2Pr0tAsYkU&ab_channel=ATIIndustrialAutomation)
* [x] we need a laser cut barrel shield which holds the insulation material
* [x] on the barrel tip, we need some mounting possibilties for fans which are a little heavy as well
- [ ] ATI mount ([see ATI Tool changers @ 3dcentral](https://www.3dcontentcentral.com/syndication/supplier/ATI%20Industrial%20Automation/147.aspx))
### Firmware
(https://www.controllino.biz/product/controllino-mega/) which gives us Ethernet and RS485. The board has been proven reliable and robust (ideal for prototyping).
- [-] VFD and PID control is mapped to Serial communication which might accept G-Code
- [x] VFD will be Omron-M2X series since we can use existing code. The VFD also supports Modbus (rather difficult)
- [ ] Internal registers/coils (custom PlasticHub Firmware) to Modbus rep
![](./assets/lydia-print-head-logical.jpg)
**[Diagram source](https://app.diagrams.net/#G1L7Prviy9U-2gpcZHm8Z5dj39gxDHd_V_)**
### PID Controller
* [x] We should go for [Omron E5-C](https://assets.omron.com/m/6f7cd0d93654a7a4/original/E5_C-Temperature-Controller-to-NB-Screen-Template-Tech-Guide.pdf) series which come with Modbus (consider EMI and cable length to the main controller)
* [x] Each PID will be exposed on the internal ModBus mapping
* There is currently a [custom PID controller](https://gitlab.com/plastichub/pid-controller) in development but as mentioned, it's unlikely that it sees the light before November. However, I can imagine we use sub-routines as they're avaiable
* [-] We should create logging module as well a an API to set temperature profiles for different materials. The logging module will help analyzing different PID settings as well experimenting with barrel cooling (when overshooting becomes an issue).
* [-] Additional, we forward alarms for overshooting on the internal bus
* **Changes** : Turns out that the [E5DC / E5DC-B](http://www.ia.omron.com/products/family/3242/) family is better choice.
![](./assets/E5DC-B.jpg)
### Barrel
- [-] OD should be standard to EU heatbands
- [ ] Between Nozzel and barrel we might have some adaptery to exchange different screw tips, up to 10 cm
- [x] should have a mount near the nozzle
- [x] Barrel - motor flange should have some redunancy to enable different barrels
----
### Hopper interface and Hopper
* [x] should have a thread interface
## Todos
* [x] Investigate Omron - PID feedback to enable more control via M/G codes (purge, ...)
* [x] Investigate GCode to ROS mapping
* [x] Investigate screw tip machining, if lucky we get away with 4 axis
* [-] Test different VFD/PID checksum/parity settings with larger EMI around
# References
## ROS (cancelled)
* [ROS - Github](https://github.com/ros-industrial)
* [ROS - GBRL - Github](https://github.com/openautomation/ROS-GRBL/wiki/GRBLtron)
* [ROS - Matlab|SimuLnk](https://www.mathworks.com/help/ros/ug/get-started-with-ros-in-simulink.html)
* [ROS Modbus - Wiki](http://wiki.ros.org/modbus)
* [ROS Modbus - PLC - Github](https://github.com/sonyccd/ros_plc_modbus)
## ProfiBus
* [Instructables Arduino](https://www.instructables.com/Profibus-DP-Communication-Between-Arduino-and-PLC/)
* [Arduino Forum](https://forum.arduino.cc/index.php?topic=458492.0)
- [Specs - PDF](https://forum.arduino.cc/index.php?topic=458492.0)
## Related Projects
* [Project Noah](https://gitlab.com/plastichub/noah)
### Cable robotics
- [The Cable-robot Analysis and Simulation Platform for Research (CASPR)](https://github.com/darwinlau/CASPR)
- [CUHK C3 Robotics Laboratory - Youtube](https://www.youtube.com/channel/UCxadDa3g1fUarP4ldAECtLQ)
### Rapid - ABB
* [Language specs and docs](./vendor/abb/2CSG445026D0201-ANR-LAN-Modbus-TCP-Protocol.pdf)
* [ABB - AC_800M - Protocols](./vendor/abb/3BSE035982-511_en_AC_800M_5.1_Feature_Pack_Communication_Protocols.pdf)
### ABB 6600
<img src="./vendor/abb/abb-irb-6600.jpg" style="width:50%"></img>
- [ABB - IRC - 5 - Controller](https://new.abb.com/products/robotics/controllers/irc5)
- [ABB - IRC - 5 Manuals](./vendor/abb/IRC5_Operating manual_Trouble shooting_3HAC020738-001_revK_en.pdf)
- [ABB - IRC - Datasheet](./vendor/abb/IRC5-Industrial-Robot-Controller-data sheet.PDF)
- [ABB irb 6600 175-2.8](https://library.e.abb.com/public/560fa420555c2d8ac1257b4b0052112c/3HAC023933-001_rev1_en.pdf)
- [ABB irb 6600 175 - 2.8 - Local](./vendor/abb/IRB_6600_R_US 02_05.pdf)
- [ABB 660 - Specs](./vendor/abb/ABB-IR-6600-3HAC14064-1_revH_en_library.pdf)
- [ABB Robotstudio Downloads](https://new.abb.com/products/robotics/robotstudio/downloads)
## Project links
* [Project Slack channel](https://pporgworkspace.slack.com/archives/C01A8G36MRP)
* [Firmware](https://gitlab.com/plastichub/medusa/firmware)
## Follow ups
- [ ] calc. energy overhead, per printed kg of plastic
- [ ] calc. min. invest to print obvious products
- [ ] investigate possible OS verticals
- [ ] develop generic system & functional design for v2.0 candidats, for 6D robots but also cable driven 3D systems
- [ ] check displacement options for segmented prints, (cheap floor track system?)
- [ ] check material remove options (see ATIish tool changers [YT](https://www.youtube.com/watch?v=EvsgCZyQuq0&ab_channel=ATIIndustrialAutomation))

View File

@ -0,0 +1,12 @@
product_id: lydia-print-head
tags:
- lydia-v4
- v4
- extrusion
has_spec: true
preview: ${product_preview}
buy: "mailto:sales@plastic-hub.com?subject=Inquiry%20-%20${slug}"
overview_drawing: true
teaser: "Powerful extruder for semi profesionall production. Comes with lots of extra safety electronics."
products: true
features: true

View File

@ -0,0 +1,5 @@
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch

View File

@ -0,0 +1,67 @@
# Continuous Integration (CI) is the practice, in software
# engineering, of merging all developer working copies with a shared mainline
# several times a day < https://docs.platformio.org/page/ci/index.html >
#
# Documentation:
#
# * Travis CI Embedded Builds with PlatformIO
# < https://docs.travis-ci.com/user/integration/platformio/ >
#
# * PlatformIO integration with Travis CI
# < https://docs.platformio.org/page/ci/travis.html >
#
# * User Guide for `platformio ci` command
# < https://docs.platformio.org/page/userguide/cmd_ci.html >
#
#
# Please choose one of the following templates (proposed below) and uncomment
# it (remove "# " before each line) or use own configuration according to the
# Travis CI documentation (see above).
#
#
# Template #1: General project. Test it using existing `platformio.ini`.
#
# language: python
# python:
# - "2.7"
#
# sudo: false
# cache:
# directories:
# - "~/.platformio"
#
# install:
# - pip install -U platformio
# - platformio update
#
# script:
# - platformio run
#
# Template #2: The project is intended to be used as a library with examples.
#
# language: python
# python:
# - "2.7"
#
# sudo: false
# cache:
# directories:
# - "~/.platformio"
#
# env:
# - PLATFORMIO_CI_SRC=path/to/test/file.c
# - PLATFORMIO_CI_SRC=examples/file.ino
# - PLATFORMIO_CI_SRC=path/to/test/directory
#
# install:
# - pip install -U platformio
# - platformio update
#
# script:
# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N

View File

@ -0,0 +1,7 @@
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
]
}

View File

@ -0,0 +1,660 @@
### GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing
under this license.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public
License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your
version supports such interaction) an opportunity to receive the
Corresponding Source of your version by providing access to the
Corresponding Source from a network server at no charge, through some
standard or customary means of facilitating copying of software. This
Corresponding Source shall include the Corresponding Source for any
work covered by version 3 of the GNU General Public License that is
incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever
published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for
the specific requirements.
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU AGPL, see <https://www.gnu.org/licenses/>.

View File

@ -0,0 +1,37 @@
## General Purpose Extrusion Firmware
### VFD
#### Protocols
- [x] Modbus, revA
- [x] Analog
- [ ] Profibus Mapping/Proxy
- [ ] RPM - PID
#### Sensors
- [x] Jamming, revA
- [ ] Visual feedback
- [ ] Sound
### PIDs
#### Protocols
- [ ] Modbus
- [x] Analog
- [ ] Profibus Mapping/Proxy
#### Sensors / Signals
- [ ] Burnout
- [ ] Overshoot
- [x] AT finish
- [x] Overcurrent
## Commons
- [ ] Error dispatch, rev-C
- [ ] External LED Bank, rev-C
- [ ] HMI interface for Plastic Hub Studio (PP OS build), January

View File

@ -0,0 +1,92 @@
## Controllino - Mega
- [Unit Testing](https://docs.platformio.org/en/latest/plus/unit-testing.html?utm_medium=piohome&utm_source=platformio)
- Semiphores : emulated, via ASM noops
- Memory: seems stable with modbus over ethernet
### Omron MX2
- [Programmer](./firmware/OmronMx2.cpp#L460)
### Omron - E5DC
### Calibration
- [TC calibration](https://www.tcdirect.co.uk/product_2_133_21#133/21/1)
# Extrusion Firmware
### Communication modes
- [-] Custom Serial over RS485 (Extruza, 3dtreehouse)
- [- Standard Serial (Lydia-v4.5 - touchscreen/RPI)
- [- Pure RS485 - Slave|Master (In conjunction with injection addon)
- [-] Bluetooth
- [-] App template
- [ ] TCP
- [ ] Modbus (rev 1, base abstract/odel)
- [ ] ProfiBus (rev 2)
- [ ] DeviceNet (rev 1)
- [ ] Debug Serial (Always)
### Protocol
- [ ] Internal: add duplex for RS485 feedback
- [-] Add command queue lifecycle / state response
- [-] Handshake
- [- Checksum
- [ ] Broadcast (for bluetooth as well)
- [-] User space / reserved
### Controls
- [ ] Simple cycle control via logic/analog interface
- [ ] Controllino - Mini/Uno version (http://www.kuehlschrankdichtung.de/ | PVC temp and cycle time profile storage)
### Modbus testing strategy for vendors
- [ ] 1. test basics after unboxing
- [x] 2. programmer test
- [ ] 3. stress/flood test
- [ ] 4. EMI near (scope)
- [ ] 5. EMI long / cable test (serial debugging with scope)
### PID / TC related
- [-] determine barrel empty / full ratio/constant impact on PID readings
- [-] determine actual PID values, independent via calibration devices (see [./firmware/components](./firmware/components) for more)
- [ ] ramp times, window keeping
- [ ] test PVC/PFA [TC cables](https://www.tcdirect.co.uk/product_2_270_1)
## Components
- [ ] Add HMI column
- [ ] Add register range
- [ ] Add wire labels
| Component | ID | Qty | Volt | VA | Circuit | Powersource | Source File |
|------------------------------ |----------- |----- |------ |---------- |--------- |------------- |------------- |
| VFD | VDF | | | - | Motor | Extern | |
| PID | PID 1... | 3 | 24 | 1.5W | Digital | 24V-I | |
| Controllino - Master | CM | 1 | 24 | 5W | Digital | 24V-I | |
| Fans | FAN | 6 | 12 | ? | Cooling | 12V-I | |
| Height - Sensor | SHEIGHT | 2 | 24 | 100mA | Sensor | 24V | |
| SSR | SSR 1... | 4 | 220 | 100-300W | Heating | Extern | |
| Thermocouple - Extruder | TCE 1... | 4 | | | | | |
| Hopper-Selonid | AUXH 1... | 2 | 12 | ? | Aux | 12V-II | |
| Motor-RPM Feedback | SRPM 1..2 | 2 | 12 | ? | Sensor | 12V-I | |
| Power - Circuit - Contactors | CPO 1... | 3 | 220V | - | Switch | Extern | |
| Thermo - Couple - Motor | TCM | | | | | | |
| Audio - Alarm | AA 1... | 2 | 24V | ? | Feedback | 24V-II | |
### Modbus design notes
- each issued read/write has a corrosponding state flag register, eg: issued, proccessing, processed, error code, failure
- use coils only
- when in duplex, feedback channel provides command queue id with state flag, polling should be avoided
- avoid multi bytes/long/strings
- each category shall provide additional user register space

View File

@ -0,0 +1,71 @@
# PID Controllers
The PID controller target temperatures can be set as follows:
- PID 1 : Address 17
- PID 2 : Address 18
- PID 3 : Address 19
## Set Target temperature on PID 1 to 100Degc
- **Address** : 17 (```0x11```)
- **Function** : 6 (WRITE_REGISTER)
- **Values** : 0 - Max Temperature (300)
**TCP Sequence**
```c
d2 8d 00 00 00 06 01 06 00 11 00 64
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 64 (100 Degc)
| | |
| | +----> Address (2 bytes) = 17 or 0x0011
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```
## Set Target temperature on PID 2to 100Degc
- **Address** : 18 (```0x12```)
- **Function** : 6 (WRITE_REGISTER)
- **Values** : 0 - Max Temperature (300)
**TCP Sequence**
```c
d2 8d 00 00 00 06 01 06 00 12 00 64
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 64 (100 Degc)
| | |
| | +----> Address (2 bytes) = 18 or 0x0012
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```
## Set Target temperature on PID 3 to 100Degc
- **Address** : 18 (```0x13```)
- **Function** : 6 (WRITE_REGISTER)
- **Values** : 0 - Max Temperature (300)
**TCP Sequence**
```c
d2 8d 00 00 00 06 01 06 00 13 00 64
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 64 (100 Degc)
| | |
| | +----> Address (2 bytes) = 18 or 0x0013
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```

View File

@ -0,0 +1,107 @@
# VFD
## Start & Stop
Starts or stops the VFD, be aware that a target frequency has to be set as well
- **Address** : 5
- **Function** : 6 (WRITE_REGISTER)
- **Values** :
- **On** : 1
- **Off** : 2
**TCP Sequence for Start**
```c
d2 8d 00 00 00 06 01 06 00 05 00 01
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 01
| | |
| | +----> Address (2 bytes) = 05 or 0x0005
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```
**TCP Sequence for Stop**
```c
d2 8d 00 00 00 06 01 06 00 05 00 02
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 02
| | |
| | +----> Address (2 bytes) = 05 or 0x0005
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```
## Frequency
Sets the target frequency
- **Address** : 6
- **Function** : 6 (WRITE_REGISTER)
- **Values** : 1 - 50
**TCP Sequence for setting target frequency to 50 Hz**
Remark : Please respect the max. main frequency setting on the inverter (settings)
```c
d2 8d 00 00 00 06 01 06 00 05 00 32
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 32 (for 50Hz)
| | |
| | +----> Address (2 bytes) = 06 or 0x0006
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```
## Direction
Sets the rotation
- **Address** : 7
- **Function** : 6 (WRITE_REGISTER)
- **Values** :
- **Forward** : 1
- **Reverse** : 2
- **Stop** : 3
**TCP Sequence for setting direction : Forward**
```c
d2 8d 00 00 00 06 01 06 00 07 00 01
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 01
| | |
| | +----> Address (2 bytes) = 07 or 0x0006
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```
**TCP Sequence for setting direction : Reverse**
```c
d2 8d 00 00 00 06 01 06 00 07 00 02
+ + + +
| | | |
| | | +----> Value (2 bytes) = 00 02
| | |
| | +----> Address (2 bytes) = 07 or 0x0006
| |
| +--> Function Code (Always 6)
|
+--> Slave - ID (Always 1)
```

View File

@ -0,0 +1,25 @@
# Omron VFD Registers
### State
The VFD's state is written into address 4 (defined in enums.h#MB_R_VFD_STATE)
**Values**
``` c
#define OMRON_STATE_ACCELERATING 4
#define OMRON_STATE_DECELERATING 2
#define OMRON_STATE_RUNNING 3
#define OMRON_STATE_STOPPED 1
```
### Status
The VFD's status is written into address 3 (defined in enums.h#MB_R_VFD_STATUS)
**Values**
``` c
#define OMRON_STATUS_STOPPED 2
#define OMRON_STATUS_RUNNING 0
```

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,5 @@
Debug
src
__vm
.vs
node_modules

View File

@ -0,0 +1,49 @@
#include "Addon.h"
#include <Streaming.h>
#include <Vector.h>
#include <Arduino.h>
bool Addon::hasFlag(uchar flag)
{
return TEST(flags, flag);
}
void Addon::setFlag(uchar flag)
{
flags = SBI(flags, flag);
}
void Addon::clearFlag(uchar flag)
{
CBI(flags, flag);
}
short Addon::debug(Stream *stream)
{
}
short Addon::info(Stream *stream)
{
}
void Addon::enable()
{
this->clearFlag(DISABLED);
}
void Addon::disable()
{
this->setFlag(DISABLED);
}
bool Addon::enabled()
{
return this->hasFlag(DISABLED);
}
Addon *byId(Addons addons, uchar id)
{
uchar s = addons.size();
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->id == id)
{
return addon;
}
}
return NULL;
}

View File

@ -0,0 +1,69 @@
#ifndef ADDON_H
#define ADDON_H
#include <WString.h>
#include <Vector.h>
#include "enums.h"
#include "common/macros.h"
#include "common/timer.h"
#define ADDON_NORMAL 1 << LOOP | 1 << INFO | 1 << SETUP
#ifdef HAS_STATES
#define ADDON_STATED ADDON_NORMAL | 1 << STATE
#else
#define ADDON_STATED ADDON_NORMAL
#endif
class Stream;
class App;
class Addon
{
public:
const String name;
const short id;
millis_t now;
millis_t last;
millis_t dt;
Addon(String _name, short _id) : name(_name),
id(_id),
now(0),
last(0),
dt(0)
{
flags = ADDON_NORMAL;
}
Addon(String _name, short _id, short _flags) : name(_name),
id(_id),
flags(_flags)
{
}
virtual short debug(Stream *stream);
virtual short info(Stream *stream);
virtual short setup(){};
virtual short loop(){};
virtual short ok(){};
virtual bool pause(){};
virtual bool resume(){};
virtual bool destroy(){};
virtual String state() { return ""; };
int flags;
void setFlag(uchar flag);
bool hasFlag(uchar flag);
void clearFlag(uchar flag);
void enable();
void disable();
bool enabled();
};
typedef Vector<Addon *> Addons;
Addon *byId(Addons addons, uchar id);
typedef short (Addon::*AddonFnPtr)(short);
typedef short (Addon::*AddonRxFn)(short size, uint8_t rxBuffer[]);
#endif

View File

@ -0,0 +1,408 @@
#include <Streaming.h>
#include "./Addon.h"
#include "ModbusRtu.h"
#include "ModbusBridge.h"
#include "config.h"
#include <SPI.h>
#include <Ethernet.h>
#define RS485Serial 3
#define MasterModbusAdd 0
#define SlaveModbusAdd 1
Modbus master(MasterModbusAdd, RS485Serial);
modbus_t ModbusQuery[1];
uint16_t ModbusSlaveRegisters[8];
millis_t WaitingTime;
int _state = IDLE;
bool debugQuery = true;
void ModbusBridge::setDebugSend(bool debug)
{
master.debugSend = debug;
}
Modbus *ModbusBridge::modbus()
{
return &master;
}
// Modbus TCP
short ModbusBridge::setup()
{
master.begin(MODBUS_RS485_BAUDRATE, MODBUS_RS485_PORT);
master.setTimeOut(MODBUS_RS485_TIMEOUT);
WaitingTime = millis() + nextWaitingTime;
_state = IDLE;
Ethernet.begin(MB_MAC, MB_IP, MB_GATEWAY, MB_SUBNET);
for (uchar i = 0; i < MAX_QUERY_BUFFER; i++)
{
queries[i].reset();
queries[i].id = i;
}
for (uchar i = 0; i < 50; i++)
{
mb->R[i] = MODBUS_TCP_DEFAULT_REGISTER_VALUE;
}
startTS = millis();
}
Query *ModbusBridge::nextByPrio(uchar state, int prio)
{
Query *oldest;
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
if (!oldest)
{
oldest = &queries[i];
}
if (queries[i].state == state && queries[i].prio == prio)
{
oldest = &queries[i];
}
}
return oldest;
}
bool didm = false;
Query *ModbusBridge::nextQueryByState(uchar state = DONE, int owner = -1)
{
if (owner > 0)
{
Query *q = nextQueryByOwner(state, owner);
if (q != NULL)
{
return q;
}
}
millis_t t = millis();
Query *oldest = NULL;
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
if (queries[i].state == state)
{
if (_state == QUEUED && t - queries[i].ts > 1000 * 10)
{
queries[i].reset();
continue;
}
if (_state == PROCESSING && t - queries[i].ts > 1000 * 10)
{
queries[i].reset();
continue;
}
if (queries[i].ts == 0)
{
queries[i].ts = t;
}
if (queries[i].prio != MB_QUERY_TYPE_CMD && t - queries[i].ts > 1000)
{
return &queries[i];
}
if (!oldest)
{
oldest = &queries[i];
}
if (queries[i].ts > oldest->ts)
{
oldest = &queries[i];
}
}
}
return oldest;
}
Query *ModbusBridge::nextQueryByOwner(uchar state = DONE, int owner = -1)
{
millis_t t = millis();
Query *oldest = NULL;
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
if (queries[i].state == state && queries[i].owner == owner)
{
if (_state == QUEUED && t - queries[i].ts > 1000 * 10)
{
queries[i].reset();
continue;
}
if (_state == PROCESSING && t - queries[i].ts > 1000 * 10)
{
queries[i].reset();
Serial.println("reset processing");
continue;
}
if (queries[i].ts == 0)
{
queries[i].ts = t;
}
if (queries[i].prio == MB_QUERY_TYPE_CMD && t - queries[i].ts > 300)
{
return &queries[i];
}
if (!oldest)
{
oldest = &queries[i];
}
if (queries[i].ts > oldest->ts)
{
oldest = &queries[i];
}
}
}
return oldest;
}
Query *ModbusBridge::nextSame(uchar state, short slave, int addr, short fn, int value)
{
millis_t t = millis();
Query *oldest;
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
if (queries[i].state == state)
{
Query *q = &queries[i];
if (q->addr == addr && q->fn == fn && q->value == value && q->slave == slave)
{
if (!oldest)
{
oldest = &queries[i];
}
if (queries[i].ts > oldest->ts)
{
oldest = &queries[i];
}
}
}
}
return oldest;
}
int ModbusBridge::numSame(uchar state, short slave, int addr, short fn, int value)
{
int num = 0;
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
if (queries[i].state == state)
{
Query *q = &queries[i];
if (q->addr == addr && q->fn == fn && q->value == value && q->slave == slave)
{
num++;
}
}
}
return num;
}
int ModbusBridge::numByState(int state = DONE)
{
int num = 0;
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
if (queries[i].state == state)
{
num++;
}
}
return num;
}
void ModbusBridge::print()
{
Serial.print("----- Queries : --- ");
Serial.print("Proccessing : ");
Serial.print(numByState(PROCESSING));
Serial.print(" | QUEUED : ");
Serial.print(numByState(QUEUED));
Serial.print(" | DONE: ");
Serial.print(numByState(DONE));
Serial.print(" | ADDR: ");
Serial.print(addr);
Serial.print(" | FN: ");
Serial.print(fn);
Serial.print(" | NOW : ");
Serial.print(millis());
Serial.print("-----\n");
for (int i = 0; i < MAX_QUERY_BUFFER; i++)
{
Serial.print(" - ");
Serial.print(queries[i].id);
Serial.print(". \t ");
queries[i].print();
Serial.print("\n");
}
}
short ModbusBridge::qstate()
{
return _state;
}
short ModbusBridge::loop()
{
loop_test();
mb->Run();
if (mb->R[9])
{
print();
mb->R[9] = 0;
}
}
short ModbusBridge::query(int slave, short function, long start, int coils, Addon *_addon, AddonFnPtr _mPtr)
{
if (_state != IDLE)
{
return WAITING;
}
addr = 0;
id = slave;
fn = function;
addr = start;
nb = coils;
owner = _addon;
updatedPtr = _mPtr;
if (debugQuery)
{
Serial.print("\n --------------Modbus QUERY --------- SLAVE : ");
Serial.print(id);
Serial.print(" | FN : ");
Serial.print(fn);
Serial.print(" | NB : ");
Serial.print(coils);
Serial.print(" | Address : ");
Serial.print(addr, HEX);
Serial.print(" | STATE : ");
Serial.print(_state);
Serial.print(" | OWNER : ");
Serial.println(owner->id);
Serial.println(" \n ");
}
_state = WAITING;
return E_OK;
}
short ModbusBridge::loop_test()
{
switch (_state)
{
case IDLE:
{
return;
}
case WAITING:
{
if (millis() > WaitingTime)
{
_state++; // set to query state
}
break;
}
case QUERY:
{
ModbusQuery[0].u8id = id; // slave address
ModbusQuery[0].u8fct = fn; // function code (this one is registers read)
ModbusQuery[0].u16RegAdd = addr; // start address in slave
ModbusQuery[0].u16CoilsNo = nb; // number of elements (coils or registers) to read
ModbusQuery[0].au16reg = ModbusSlaveRegisters; // pointer to a memory array in the CONTROLLINO
master.query(ModbusQuery[0]); // send query (only once)
_state++; // set to RESPONSE
break;
}
case RESPONSE:
{
master.poll(); // check incoming messages
if (master.getState() == COM_IDLE)
{
int errors = master.getErrCnt();
if (errors)
{
if (owner && onError != NULL)
{
(owner->*onError)(master.getLastError());
master.clearError();
}
else
{
Serial.print("ModbusBridge:: Have Errors : ");
Serial.println(master.getLastError());
}
_state = IDLE;
return;
}
long onMessageError = 0;
if (owner && onMessage)
{
onMessageError = (owner->*onMessage)(master.rxSize, master.rxBuffer);
}
short ret = (owner->*updatedPtr)(onMessageError);
WaitingTime = millis() + nextWaitingTime;
if (TEST(debug_flags, DEBUG_RECEIVE) && onMessageError == ERROR_OK)
{
}
/*
Serial.print("--------------Modbus RESPONSE --------- FN : ");
Serial.print(fn);
Serial.print(" | NB : ");
Serial.print(nb);
Serial.print(" | SLAVE : ");
Serial.print(id);
Serial.print(" | Address : ");
Serial.println(addr);
*/
_state = IDLE;
}
break;
}
}
}
short ModbusBridge::debug(Stream *stream)
{
// *stream << this->name << ":";
return false;
}
short ModbusBridge::info(Stream *stream)
{
// *stream << this->name << "\n\t";
}

View File

@ -0,0 +1,172 @@
#ifndef MODBUS_BRIDGE_H
#define MODBUS_BRIDGE_H
#include "Addon.h"
#include <Controllino.h>
#include "Mudbus.h"
#define MAX_QUERY_BUFFER 20
class Modbus;
// query struct
class Query
{
public:
int slave;
long addr;
long value;
int state;
long fn;
millis_t ts;
int id;
int prio;
int owner;
long printNumber(int number)
{
Serial.print(" ");
int spaces = 0;
if (number < 1000)
{
spaces = 1;
}
if (number < 100)
{
spaces = 2;
}
if (number < 10)
{
spaces = 3;
}
for (int i = 0; i < spaces; i++)
{
Serial.print(" ");
}
Serial.print(number);
}
void print()
{
Serial.print("SLAVE: ");
Serial.print(slave);
Serial.print(" \t | Address: ");
// Serial.print(addr, HEX);
printNumber(addr);
Serial.print(" \t | VALUE: ");
printNumber(value);
Serial.print(" \t | STATE ");
if (state == DONE)
{
Serial.print("Done ");
}
if (state == PROCESSING)
{
Serial.print("Processsing");
}
if (state == QUEUED)
{
Serial.print("Queued ");
}
Serial.print(" \t | FN: ");
Serial.print(fn);
Serial.print(" \t | PRIO: ");
Serial.print(prio);
Serial.print(" | ");
Serial.print(" \t | OWNER: ");
Serial.print(owner);
Serial.print(" | ");
}
Query()
{
reset();
}
void reset()
{
state = DONE;
fn = 0;
ts = 0;
value = 0;
slave = 0;
addr = 0;
prio = 0;
owner = 0;
}
};
class ModbusBridge : public Addon
{
public:
ModbusBridge() : Addon("ModbusBridge", 50, ADDON_NORMAL),
mb(new Mudbus())
{
setFlag(DEBUG);
debug_flags = 0;
debug_flags = 1 << DEBUG_RECEIVE;
nextWaitingTime = 1000;
}
uint16_t ModbusSlaveRegisters[8];
// Addon std implementation
short debug(Stream *stream);
short info(Stream *stream);
short setup();
short loop();
short loop_test();
// current query
short id;
short fn;
short addr;
int nb;
long debug_flags;
short queryState();
short query(int slave, short function, long start, int coils, Addon *_addon, AddonFnPtr _mPtr);
short qstate();
// 0x6 callback
AddonFnPtr updatedPtr;
// on Error
AddonFnPtr onError;
// on RawMessage
AddonRxFn onMessage;
// callback owner
Addon *owner;
int nextWaitingTime;
Mudbus *mb;
// Modbus query / commands
Query *nextQueryByState(uchar state = DONE, int owner = -1);
Query *nextQueryByOwner(uchar state = DONE, int owner = -1);
Query *nextByPrio(uchar state, int prio);
Query *nextSame(uchar state, short slave, int addr, short fn, int value);
int numSame(uchar state, short slave, int addr, short fn, int value);
int numByState(int state);
void print();
enum FLAGS
{
DEBUG_RECEIVE = 1,
DEBUG_SEND = 2,
};
Query queries[MAX_QUERY_BUFFER];
millis_t startTS;
Modbus *modbus();
void setDebugSend(bool debug);
////////////////////////////////////////////////////////////////
//
// TCP Gateway
//
};
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,238 @@
/*
Mudbus.cpp - an Arduino library for a Modbus TCP slave.
Copyright (C) 2011 Dee Wykoff
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Mudbus.h"
#include "enums.h"
// For Arduino 0022
// Server MbServer(MB_PORT);
// For Arduino 1.0
EthernetServer MbServer(MB_PORT);
// #define MbDebug
Mudbus::Mudbus()
{
}
void Mudbus::Run()
{
Runs = 1 + Runs * (Runs < 999);
//****************** Read from socket ****************
// For Arduino 0022
// Client client = MbServer.available();
// For Arduino 1.0
EthernetClient client = MbServer.available();
if(client.available())
{
Reads = 1 + Reads * (Reads < 999);
int i = 0;
while(client.available())
{
ByteArray[i] = client.read();
i++;
}
SetFC(ByteArray[7]); //Byte 7 of request is FC
if(!Active)
{
Active = true;
PreviousActivityTime = millis();
#ifdef MbDebug
Serial.println("Mb active");
#endif
}
}
if(millis() > (PreviousActivityTime + 60000))
{
if(Active)
{
Active = false;
#ifdef MbDebug
Serial.println("Mb not active");
#endif
}
}
int Start, WordDataLength, ByteDataLength, CoilDataLength, MessageLength;
//****************** Read Coils **********************
if(FC == MB_FC_READ_COILS)
{
Start = word(ByteArray[8],ByteArray[9]);
CoilDataLength = word(ByteArray[10],ByteArray[11]);
ByteDataLength = CoilDataLength / 8;
if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++;
CoilDataLength = ByteDataLength * 8;
#ifdef MbDebug
Serial.print(" MB_FC_READ_COILS S=");
Serial.print(Start);
Serial.print(" L=");
Serial.println(CoilDataLength);
#endif
ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
ByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data).
for(int i = 0; i < ByteDataLength ; i++)
{
for(int j = 0; j < 8; j++)
{
bitWrite(ByteArray[9 + i], j, C[Start + i * 8 + j]);
}
}
MessageLength = ByteDataLength + 9;
client.write(ByteArray, MessageLength);
Writes = 1 + Writes * (Writes < 999);
FC = MB_FC_NONE;
}
//****************** Read Registers ******************
if(FC == MB_FC_READ_REGISTERS)
{
Start = word(ByteArray[8],ByteArray[9]);
WordDataLength = word(ByteArray[10],ByteArray[11]);
ByteDataLength = WordDataLength * 2;
#ifdef MbDebug
Serial.print(" MB_FC_READ_REGISTERS S=");
Serial.print(Start);
Serial.print(" L=");
Serial.println(WordDataLength);
#endif
ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
ByteArray[8] = ByteDataLength; //Number of bytes after this one (or number of bytes of data).
for(int i = 0; i < WordDataLength; i++)
{
ByteArray[ 9 + i * 2] = highByte(R[Start + i]);
ByteArray[10 + i * 2] = lowByte(R[Start + i]);
}
MessageLength = ByteDataLength + 9;
client.write(ByteArray, MessageLength);
Writes = 1 + Writes * (Writes < 999);
FC = MB_FC_NONE;
}
//****************** Write Coil **********************
if(FC == MB_FC_WRITE_COIL)
{
Start = word(ByteArray[8],ByteArray[9]);
C[Start] = word(ByteArray[10],ByteArray[11]) > 0;
#ifdef MbDebug
Serial.print(" MB_FC_WRITE_COIL C");
Serial.print(Start);
Serial.print("=");
Serial.println(C[Start]);
#endif
ByteArray[5] = 2; //Number of bytes after this one.
MessageLength = 8;
client.write(ByteArray, MessageLength);
Writes = 1 + Writes * (Writes < 999);
FC = MB_FC_NONE;
}
//****************** Write Register ******************
if(FC == MB_FC_WRITE_REGISTER)
{
Start = word(ByteArray[8],ByteArray[9]);
R[Start] = word(ByteArray[10],ByteArray[11]);
#ifdef MbDebug
Serial.print(" MB_FC_WRITE_REGISTER R");
Serial.print(Start);
Serial.print("=");
Serial.println(R[Start]);
#endif
ByteArray[5] = 6; //Number of bytes after this one.
MessageLength = 12;
client.write(ByteArray, MessageLength);
Writes = 1 + Writes * (Writes < 999);
FC = MB_FC_NONE;
}
//****************** Write Multiple Coils **********************
//Function codes 15 & 16 by Martin Pettersson http://siamect.com
if(FC == MB_FC_WRITE_MULTIPLE_COILS)
{
Start = word(ByteArray[8],ByteArray[9]);
CoilDataLength = word(ByteArray[10],ByteArray[11]);
ByteDataLength = CoilDataLength / 8;
if(ByteDataLength * 8 < CoilDataLength) ByteDataLength++;
CoilDataLength = ByteDataLength * 8;
#ifdef MbDebug
Serial.print(" MB_FC_WRITE_MULTIPLE_COILS S=");
Serial.print(Start);
Serial.print(" L=");
Serial.println(CoilDataLength);
#endif
ByteArray[5] = ByteDataLength + 5; //Number of bytes after this one.
for(int i = 0; i < ByteDataLength ; i++)
{
for(int j = 0; j < 8; j++)
{
C[Start + i * 8 + j] = bitRead( ByteArray[13 + i], j);
}
}
MessageLength = 12;
client.write(ByteArray, MessageLength);
Writes = 1 + Writes * (Writes < 999);
FC = MB_FC_NONE;
}
//****************** Write Multiple Registers ******************
//Function codes 15 & 16 by Martin Pettersson http://siamect.com
if(FC == MB_FC_WRITE_MULTIPLE_REGISTERS)
{
Start = word(ByteArray[8],ByteArray[9]);
WordDataLength = word(ByteArray[10],ByteArray[11]);
ByteDataLength = WordDataLength * 2;
#ifdef MbDebug
Serial.print(" MB_FC_READ_REGISTERS S=");
Serial.print(Start);
Serial.print(" L=");
Serial.println(WordDataLength);
#endif
ByteArray[5] = ByteDataLength + 3; //Number of bytes after this one.
for(int i = 0; i < WordDataLength; i++)
{
R[Start + i] = word(ByteArray[ 13 + i * 2],ByteArray[14 + i * 2]);
}
MessageLength = 12;
client.write(ByteArray, MessageLength);
Writes = 1 + Writes * (Writes < 999);
FC = MB_FC_NONE;
}
#ifdef MbDebug
Serial.print("Mb runs: ");
Serial.print(Runs);
Serial.print(" reads: ");
Serial.print(Reads);
Serial.print(" writes: ");
Serial.print(Writes);
Serial.println();
#endif
}
void Mudbus::SetFC(int fc)
{
if(fc == 1) FC = MB_FC_READ_COILS;
if(fc == 3) FC = MB_FC_READ_REGISTERS;
if(fc == 5) FC = MB_FC_WRITE_COIL;
if(fc == 6) FC = MB_FC_WRITE_REGISTER;
if(fc == 15) FC = MB_FC_WRITE_MULTIPLE_COILS;
if(fc == 16) FC = MB_FC_WRITE_MULTIPLE_REGISTERS;
}

View File

@ -0,0 +1,96 @@
/*
Mudbus.h - an Arduino library for a Modbus TCP slave.
Copyright (C) 2011 Dee Wykoff
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//#define MbDebug
// For Arduino 0022
// #include "WProgram.h"
// For Arduino 1.0
#include "Arduino.h"
#include <SPI.h>
#include <Ethernet.h>
#ifndef Mudbus_h
#define Mudbus_h
#define MB_N_R 125 //Max 16 bit registers for Modbus is 125
#define MB_N_C 128 //Max coils for Modbus is 2000 - dont need that many so here is a multiple of 8
#define MB_PORT 502
/*
enum MB_FC {
MB_FC_NONE = 0,
MB_FC_READ_COILS = 1,
MB_FC_READ_REGISTERS = 3,
MB_FC_WRITE_COIL = 5,
MB_FC_WRITE_REGISTER = 6,
//Function codes 15 & 16 by Martin Pettersson http://siamect.com
MB_FC_WRITE_MULTIPLE_COILS = 15,
MB_FC_WRITE_MULTIPLE_REGISTERS = 16
};
*/
class Mudbus
{
public:
Mudbus();
void Run();
int R[MB_N_R];
bool C[MB_N_C];
bool Active;
unsigned long PreviousActivityTime;
int Runs, Reads, Writes;
private:
uint8_t ByteArray[260];
int FC;
void SetFC(int fc);
};
#endif
/* Speculations on Modbus message structure:
**********************************************
**********Master(PC) request frames***********
00 ID high 0
01 ID low 1
02 Protocol high 0
03 Protocol low 0
04 Message length high 0
05 Message length low 6 (6 bytes after this)
06 Slave number 1
07 Function code
08 Start address high maybe 0
09 Start address low maybe 0
10 Length high maybe 125 or Data high if write
11 Length low maybe 125 or Data low if write
**********************************************
**********Slave(Arduino) response frames******
00 ID high echo / 0
01 ID low echo / slave ID 1
02 Protocol high echo
03 Protocol low echo
04 Message length high echo
05 Message length low num bytes after this
06 Slave number echo
07 Function code echo
08 Start address high num bytes of data
09 Data high
10 Data low
**********************************************
*/

View File

@ -0,0 +1,332 @@
#ifndef OMRON_E5_H
#define OMRON_E5_H
// Omron EJ5 Modbus Registers & Coils
#define OR_BIT(A) (A >> 1)
#define OR_WORD(A) (A << 4)
bool OR_E5_STATUS_BIT(unsigned int high, unsigned int low, byte bit)
{
// shift down all for 16bit platforms only
if (bit <= 16)
{
return (low & (1 << 8));
}
return (OR_WORD(high) & (1 << (OR_BIT(bit))));
}
// Status Bit -1 , see h175_e5_c_communications_manual_en.pdf::3-24
enum OR_E5_STATUS_1
{
// Lower Word
OR_E5_S1_Heater_OverCurrent = 0,
OR_E5_S1_Heater_CurrentHold = 1,
OR_E5_S1_AD_ConverterError = 2,
OR_E5_S1_HS_Alarm = 3,
OR_E5_S1_RSP_InputError = 4,
OR_E5_S1_InputError = 6,
OR_E5_S1_PotentiometerInnputError = 7,
OR_E5_S1_Control_OutputOpenOutput = 8,
OR_E5_S1_Control_OutputCloseOutput = 9,
OR_E5_S1_HBAlarmCT1 = 10,
OR_E5_S1_HBAlarmCT2 = 11,
OR_E5_S1_Alarm1 = 12,
OR_E5_S1_Alarm2 = 13,
OR_E5_S1_Alarm3 = 14,
OR_E5_S1_ProgramEndOutput = 15,
// Upper Word
OR_E5_S1_EventInput1 = 16,
OR_E5_S1_EventInput2 = 17,
OR_E5_S1_EventInput3 = 18,
OR_E5_S1_EventInput4 = 19,
OR_E5_S1_WriteMode = 20,
OR_E5_S1_NonVolatileMemory = 21,
OR_E5_S1_SetupArea = 22,
OR_E5_S1_ATExcecute = 23,
OR_E5_S1_RunStop = 24,
OR_E5_S1_ComWrite = 25,
OR_E5_S1_AutoManualSwitch = 26,
OR_E5_S1_ProgramStart = 27,
OR_E5_S1_HeaterOverCurrentCT2 = 28,
OR_E5_S1_HeaterCurrentHoldCT2 = 29,
OR_E5_S1_HSAlarmCT2 = 31
};
// Status Bit - 2 , see h175_e5_c_communications_manual_en.pdf::3-25
enum OR_E5_STATUS_2
{
// Lower Word
OR_E5_S2_WorkBit1 = 0,
OR_E5_S2_WorkBit2 = 1,
OR_E5_S2_WorkBit3 = 2,
OR_E5_S2_WorkBit4 = 3,
OR_E5_S2_WorkBit5 = 4,
OR_E5_S2_WorkBit6 = 5,
OR_E5_S2_WorkBit7 = 6,
OR_E5_S2_WorkBit8 = 7,
// Upper Word
OR_E5_S2_EventInput5 = 16,
OR_E5_S2_EventInput6 = 17,
OR_E5_S2_Inverse = 20,
OR_E5_S2_SPRamp = 21,
OR_E5_S2_SPMode = 27,
OR_E5_S2_Alarm4 = 28
};
// Variable Area - Settings Range (0x06s) - 2 byte mode,
// see h175_e5_c_communications_manual_en.pdf::5-1
enum OR_E5_SWR
{
//Temperature: Use the specified range for each sensor.
// Analog: Scaling lower limit 5% FS to Scaling upper limit + 5% FS
OR_E5_SWR_PV = 0x2000,
// Refer to 5-2 Status for details (see @OR_E5_STATUS_1 and @OR_E5_STATUS_2)
OR_E5_SWR_STATUS = 0x2001,
// Internal Set Point(see appendix *1) - SP lower limit to SP upper limit
OR_E5_SWR_ISP = 0x2002,
// Heater Current 1 Value Monitor, 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_HeaterCurrentValue1_Monitor = 0x2003,
// MV Monitor (Heating)
// Standard: 0xFFFFFFCE to 0x0000041A (5.0 to 105.0)
// Heating and cooling: 0x00000000 to 0x0000041A (0.0 to 105.0)
OR_E5_SWR_MVMonitorHeating = 0x2004,
// MV Monitor (Cooling)
// 0x00000000 to 0x0000041A (0.0 to 105.0)
OR_E5_SWR_MVMonitorCooling = 0x2005,
// Set Point - SP lower limit to SP upper limit
OR_E5_SWR_SP_LIMIT = 0x2103,
// Alarm Value 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_1 = 0x2104,
// Alarm Value - Upper Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_1_UL = 0x2105,
// Alarm Value - Lower Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_1_LL = 0x2106,
// Alarm Value 2
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_2 = 0x2107,
// Alarm Value - Upper Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_2_UL = 0x2108,
// Alarm Value - Lower Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_2_LL = 0x2109,
//Temperature: Use the specified range for each sensor.
// Analog: Scaling lower limit 5% FS to Scaling upper limit + 5% FS
OR_E5_SWR_PV2 = 0x2402,
// Internal Set Point(see appendix *1) - SP lower limit to SP upper limit
OR_E5_SWR_ISP2 = 0x2403,
// Multi SP No. Monitor, 0x00000000 to 0x00000007 (0 to 7)
OR_E5_SWR_MSMON = 0x2404,
// Status,
// - Not displayed on the Controller display.
// - In 2-byte mode, the rightmost 16 bits are read.
OR_E5_SWR_STATUSEX = 0x2406,
// Status,
// - Not displayed on the Controller display.
// - In 2-byte mode, the leftmost 16 bits are read.
OR_E5_SWR_STATUSEXL = 0x2407,
// Status,
// - Not displayed on the Controller display.
// - In 2-byte mode, the rightmost 16 bits are read.
OR_E5_SWR_STATUSEXR = 0x2408,
// Decimal Point Monitor,
// 0x00000000 to 0x00000003 (0 to 3)
OR_E5_SWR_DECMON = 0x2410,
// Set Point ()
// SP lower limit to SP upper limit
OR_E5_SWR_SP = 0x2601,
// Remote Set Point Monitor
// - Remote SP lower limit 10% FS to Remote SP upper limit +10% FS
OR_E5_SWR_SP_EX_MON = 0x2602,
// Heater Current 1 Value Monitor, 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_HeaterCurrentValue1_Monitor2 = 0x2604,
// Valve Opening Monitor, 0xFFFFFF9C to 0x0000044C (10.0 to 110.0)
OR_E5_SWR_VALVE_OPENING_MON = 0x2607,
// Proportional Band (Cooling), 0x00000001 to 0x0000270F (0.1 to 999.9)
OR_E5_SWR_PRO_BAND = 0x2701,
// Integral Time (Cooling) 0x00000000 to 0x0000270F
// (0 to 9999: Integral/derivative time unit is 1 s.)
// (0.0 to 999.9: Integral/derivative time unit is 0.1 s.)
OR_E5_SWR_IT_COOLING = 0x2702,
// Derivative Time (Cooling) 0x00000000 to 0x0000270F
// (0 to 9999: Integral/derivative time unit is 1 s.)
// (0.0 to 999.9: Integral/derivative time unit is 0.1 s.)
OR_E5_SWR_D_COOLING = 0x2703,
// Dead Band 0xFFFFF831 to 0x0000270F
// (199.9 to 999.9 for temperature input)
// (19.99 to 99.99 for analog input)
OR_E5_SWR_DEADBAND = 0x2704,
// Manual Reset Value,
// 0x00000000 to 0x000003E8 (0.0 to 100.0)
OR_E5_SWR_MANUAL_RESET_VALUE = 0x2705,
// Hysteresis (Heating)
// 0x00000001 to 0x0000270F
// (0.1 to 999.9 for temperature input)
// (0.01 to 99.99 for analog input)
OR_E5_SWR_HYSTERESIS = 0x2706,
// Hysteresis (Cooling)
// 0x00000001 to 0x0000270F
// (0.1 to 999.9 for temperature input)
// (0.01 to 99.99 for analog input)
OR_E5_SWR_HYSTERESIS_COOLING = 0x2707,
// Control Period (Heating)
// 0xFFFFFFFE (2): 0.1 s
// 0xFFFFFFFF (1): 0.2 s
// 0x00000000 (0): 0.5 s
// 0x00000001 to 0x00000063 (1 to 99)
OR_E5_SWR_CONTROL_PERIOD_HEATING = 0x2708,
// Control Period (Cooling)
// 0xFFFFFFFE (2): 0.1 s
// 0xFFFFFFFF (1): 0.2 s
// 0x00000000 (0): 0.5 s
// 0x00000001 to 0x00000063 (1 to 99)
OR_E5_SWR_CONTROL_PERIOD_COOLING = 0x2709,
// Position Proportional Dead Band
// 0x00000001 to 0x00000064 (0.1 to 10.0)
OR_E5_SWR_POSITION_PROPORTIONAL_DEAD_BAND = 0x270A,
// Open/Close Hysteresis
// 0x00000001 to 0x000000C8 (0.1 to 20.0)
OR_E5_SWR_OPEN_CLOSE_HYSTERESIS = 0x270B,
// SP Ramp Time Unit 0x00000000 (0): EU/second
// 0x00000001 (1): EU/minute
// 0x00000002 (2): EU/hour
OR_E5_SWR_SP_RAMP_UNIT = 0x270C,
// SP Ramp Set Value 0x00000000 (0): OFF
// 0x00000001 to 0x0000270F (1 to 9999)
OR_E5_SWR_SP_RAMP_SET_VALUE = 0x270D,
// SP Ramp Fall Value
// 0xFFFFFFFF (1): Same (Same as SP Ramp Set Value.)
// 0x00000000 (0): OFF
// 0x00000001 to 0x0000270F (1 to 9999)
OR_E5_SWR_SP_FALL_VALUE = 0x270E,
// MV at Stop Standard Models
// Standard control:
// 0xFFFFFFCE to 0x0000041A (5.0 to 105.0)
// Heating and cooling control:
// 0xFFFFFBE6 to 0x0000041A (105.0 to 105.0)
// Position-proportional Models
// Close position-proportional control with the Direct Setting of
// Position Proportional MV parameter set to ON:
// 0xFFFFFFCE to 0x0000041A (5.0 to 105.0)
// Floating position-proportional control or the Direct Setting of
// Position Proportional MV parameter set to OFF:
// 0xFFFFFFFF to 0x00000001 (1 to 1)
OR_E5_SWR_MV_PV_ERROR = 0x2711,
// MV Change Rate Limit
// 0x00000000 to 0x000003E8 (0.0 to 100.0)
OR_E5_SWR_CHANGE_RATE_LIMIT = 0x2713,
// PV Input Slope Coefficient
// 0x00000001 to 0x0000270F (0.001 to 9.999)
OR_E5_SWR_PV_INPUT_SLOPE_COEFFICIENT = 0x2718,
// Heater Burnout Detection 1
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HEATER_BURNOUT_DETECTION_1 = 0x271B,
// Leakage Current 1 Monitor
// 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_LEAKAGE_CURRENT_MONITOR_1 = 0x271C,
// HS Alarm 1
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HS_ALARM_1 = 0x271D,
// Process Value Input Shift
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_PROCESS_VALUE_INPUT_SHIFT = 0x2723,
// Heater Burnout Detection 2
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HEATER_BURNOUT_DETECTION_2 = 0x2725,
// Leakage Current 2 Monitor
// 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_LEAKAGE_CURRENT_MONITOR_2 = 0x2726,
// HS Alarm 12
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HS_ALARM_2 = 0x2727,
// Soak Time Remain (how lovely)
// 0x00000000 to 0x0000270F (0 to 9999)
OR_E5_SWR_SOAK_REMAIN = 0x2728,
// Soak Time
// 0x00000001 to 0x0000270F (1 to 9999)
OR_E5_SWR_SOAK_TIME = 0x2729,
// Wait Band 0x00000000 (0): OFF
// 0x00000001 to 0x0000270F
// (0.1 to 999.9 for Temperature input)
// (0.01 to 99.99 for Analog input)
OR_E5_SWR_WAIT_BAND = 0x272A,
// Remote SP Input Shift
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_REMOTE_SP_SHIFT = 0x272B,
// Remote SP input Slope Coefficient
// 0x00000001 to 0x0
OR_E5_SWR_REMOTE_SP_SLOPE_COEFFICIENT = 0x272C,
// Input Digital Filter 0x00000000 to 0x0000270F (0.0 to 999.9)
OR_E5_SWR_DIGITAL_FILTER = 0x2800
// Notes :
// *1 Not displayed on the Controller display
};
#endif

View File

@ -0,0 +1,603 @@
#include "OmronPID.h"
#include "ModbusBridge.h"
#include "./components/OmronE5.h"
bool printModbus = false;
bool printPIDS = false;
bool debugUpdate = false;
bool _updateState = true;
bool printMBErrors = true;
void OmronPID::testPIDs()
{
// setAllSP(15);
// runAll();
// stopAll();
// singlePIDW(2, OR_E5_SWR::OR_E5_SWR_SP, 300);
// singlePIDW(1, 5000, 20);
// singlePID(1, ku8MBWriteSingleRegister, 0, OR_E5_CMD::OR_E5_AT_EXCECUTE);
}
short OmronPID::read10_16(int slaveAddress, int addr, int prio = 0)
{
Query *same = modbus->nextSame(QUEUED, slaveAddress, addr, ku8MBReadHoldingRegisters, 10);
if (same != NULL && millis() - same->ts < 1000)
{
return;
}
if (modbus->numByState(DONE) < 10)
{
return;
}
if (modbus->numSame(QUEUED, slaveAddress, addr, ku8MBReadHoldingRegisters, 1) > 1)
{
return;
}
Query *next = modbus->nextQueryByState(DONE);
if (next != NULL)
{
next->fn = ku8MBReadHoldingRegisters;
next->slave = slaveAddress;
next->value = 10;
next->addr = addr;
next->state = QUERY_STATE::QUEUED;
next->ts = millis();
next->prio = prio;
next->owner = OMRON_PID;
if (debugUpdate)
{
Serial.println(next->slave);
}
return E_OK;
}
else
{
Serial.print("Buffer full");
}
return E_QUERY_BUFFER_END;
}
void OmronPID::updateState()
{
if (!_updateState)
{
return;
}
OmronState *next = nextToUpdate();
if (next != NULL)
{
modbus->nextWaitingTime = MODBUS_READ_WAIT;
if (debugUpdate)
{
Serial.println("Update slave :");
Serial.println(next->slaveID);
}
next->flags = OmronState::FLAGS::UPDATING;
read10_16(next->slaveID, 0);
}
}
short OmronPID::rawResponse(short size, uint8_t rxBuffer[])
{
Query *current = modbus->nextQueryByState(PROCESSING, OMRON_PID);
/*
Serial.print("\n\t Incoming: ");
current->print();
Serial.println(" :: ");
*/
/*
for (int i = 0; i < size; i++)
{
Serial.print(rxBuffer[i], HEX);
Serial.print(" : ");
}
Serial.print("\n\t Incoming size : ");
Serial.print(size);
Serial.print("\n");
*/
if (current)
{
switch (current->fn)
{
case ku8MBWriteSingleRegister:
{
if (size == 5 && rxBuffer[1] == OR_E5_RESPONSE_CODE::OR_COMMAND_ERROR)
{
Serial.print("------ \n Command Error: ");
Serial.print(rxBuffer[2]);
Serial.print(" : ");
switch (rxBuffer[2])
{
case OR_E5_ERROR::VARIABLE_ADDRESS_ERROR:
{
Serial.println(OR_E_MSG_INVALID_ADDRESS);
break;
}
case OR_E5_ERROR::VARIABLE_RANGE_ERROR:
{
Serial.println(OR_E_MSG_INVALID_RANGE);
break;
}
case OR_E5_ERROR::VARIABLE_OPERATION_ERROR:
{
Serial.println(OR_E_MSG_OPERATION_ERROR);
break;
}
}
Serial.println("\n------");
return rxBuffer[2];
}
if (size == 8 && (rxBuffer[0] != current->slave || rxBuffer[2] != current->addr))
{
return OR_COMMAND_ERROR;
}
break;
}
}
}
return ERROR_OK;
}
OmronState *OmronPID::current()
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
if (states[i].flags == OmronState::FLAGS::UPDATING)
{
return &states[i];
}
}
return NULL;
}
short OmronPID::responseFn(short error)
{
Query *last = modbus->nextQueryByState(QUERY_STATE::PROCESSING, OMRON_PID);
if (!last)
{
Serial.println("nothing to process !");
return;
}
OmronState *state = pidBySlave(last->slave);
if (last->fn == ku8MBWriteSingleRegister)
{
last->reset();
if (state)
{
state->flags = OmronState::FLAGS::UPDATED;
}
return;
}
if (state)
{
if (state->flags != OmronState::FLAGS::UPDATING)
{
}
if (state->slaveID != last->slave)
{
Serial.println("mismatch::wrong slave id -------");
last->print();
last->reset();
return;
}
state->lastUpdated = millis();
state->statusHigh = modbus->ModbusSlaveRegisters[2];
state->statusLow = modbus->ModbusSlaveRegisters[3];
state->pv = modbus->ModbusSlaveRegisters[1];
state->sp = modbus->ModbusSlaveRegisters[5];
state->flags = OmronState::FLAGS::UPDATED;
state->ready = true;
if (printPIDS)
{
Serial.print("Updated SlaveID: ");
Serial.print(state->slaveID);
Serial.println("");
print();
}
last->reset();
updateTCP();
}
else
{
Serial.print("Invalid current PID: ");
Serial.println(last->slave);
}
}
void OmronPID::print()
{
printStates();
}
void OmronPID::fromTCP()
{
millis_t t = now;
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
switch (i)
{
case 0:
{
if (modbus->mb->R[MB_W_PID_1_SP] > 0)
{
singlePID(states[i].slaveID, ku8MBWriteSingleRegister, OR_E5_SWR::OR_E5_SWR_SP, modbus->mb->R[MB_W_PID_1_SP]);
modbus->mb->R[MB_W_PID_1_SP] = 0;
Serial.println("change");
modbus->print();
states[i].lastWritten = t;
}
break;
}
case 1:
{
if (modbus->mb->R[MB_W_PID_2_SP] > 0)
{
singlePID(states[i].slaveID, ku8MBWriteSingleRegister, OR_E5_SWR::OR_E5_SWR_SP, modbus->mb->R[MB_W_PID_2_SP]);
modbus->mb->R[MB_W_PID_2_SP] = 0;
states[i].lastWritten = t;
return true;
}
break;
}
case 2:
{
if (modbus->mb->R[MB_W_PID_3_SP])
{
singlePID(states[i].slaveID, ku8MBWriteSingleRegister, OR_E5_SWR::OR_E5_SWR_SP, modbus->mb->R[MB_W_PID_3_SP]);
modbus->mb->R[MB_W_PID_3_SP] = 0;
states[i].lastWritten = t;
}
break;
}
}
}
}
void OmronPID::updateTCP()
{
modbus->mb->R[MB_R_PID_1_PV + MB_REGISTER_OFFSET] = states[0].pv;
modbus->mb->R[MB_R_PID_2_PV + MB_REGISTER_OFFSET] = states[1].pv;
modbus->mb->R[MB_R_PID_3_PV + MB_REGISTER_OFFSET] = states[2].pv;
modbus->mb->R[MB_R_PID_1_SP + MB_REGISTER_OFFSET] = states[0].sp;
modbus->mb->R[MB_R_PID_2_SP + MB_REGISTER_OFFSET] = states[1].sp;
modbus->mb->R[MB_R_PID_3_SP + MB_REGISTER_OFFSET] = states[2].sp;
}
short OmronPID::queryResponse(short error)
{
Query *last = modbus->nextQueryByState(QUERY_STATE::PROCESSING);
if (last)
{
last->state = QUERY_STATE::DONE;
}
}
int OmronPID::singlePIDW(int slave, int addr, int value)
{
singlePID(slave, ku8MBWriteSingleRegister, addr, value);
}
int OmronPID::singlePID(int slave, short fn, int addr, int value)
{
Query *same = modbus->nextSame(QUEUED, slave, addr, fn, value);
if (modbus->numByState(DONE) < 2 && fn != ku8MBWriteSingleRegister)
{
return false;
}
if (modbus->numSame(QUEUED, slave, addr, fn, value) > 1)
{
return false;
}
OmronState *pid = pidBySlave(slave);
if (pid)
{
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = fn;
next->slave = pid->slaveID;
next->value = value;
next->addr = addr;
next->state = QUERY_STATE::QUEUED;
if (fn == ku8MBWriteSingleRegister)
{
next->prio = MB_QUERY_TYPE_CMD;
}
return E_OK;
}
}
else
{
Serial.println("No such PID");
return E_NO_SUCH_PID;
}
}
int OmronPID::eachPIDW(int addr, int value)
{
return eachPID(ku8MBWriteSingleRegister, addr, value);
}
int OmronPID::eachPID(short fn, int addr, int value)
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = fn;
next->slave = states[i].slaveID;
next->value = value;
next->addr = addr;
next->state = QUERY_STATE::QUEUED;
}
else
{
Serial.println("no buffer free");
}
}
}
OmronState *OmronPID::pidBySlave(int slave)
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
if (states[i].slaveID == slave)
{
return &states[i];
}
}
return NULL;
}
void OmronPID::stopAll()
{
eachPID(ku8MBWriteSingleRegister, 0, OR_E5_CMD::OR_E5_STOP);
}
void OmronPID::runAll()
{
eachPID(ku8MBWriteSingleRegister, 0, OR_E5_CMD::OR_E5_RUN);
}
void OmronPID::setAllSP(int sp)
{
eachPID(ku8MBWriteSingleRegister, OR_E5_SWR::OR_E5_SWR_SP, sp);
}
short OmronPID::setup()
{
statusLight.off();
}
// for manual testing
bool did = false;
short OmronPID::loop()
{
if (millis() - startTS < 2000)
{
return;
}
statusLight.loop();
if (modbus->qstate() != IDLE)
{
return;
}
if (!did)
{
testPIDs();
did = true;
}
if (millis() - interval > OMRON_PID_UPDATE_INTERVAL)
{
fromTCP();
updateState();
interval = now;
Query *nextCommand = modbus->nextQueryByState(QUERY_STATE::QUEUED);
if (nextCommand != NULL)
{
if (printModbus)
{
modbus->print();
}
nextCommand->state = QUERY_STATE::PROCESSING;
modbus->nextWaitingTime = MODBUS_CMD_WAIT;
modbus->onMessage = (AddonRxFn)&OmronPID::rawResponse;
modbus->onError = (AddonFnPtr)&OmronPID::onError;
if (debugUpdate)
{
Serial.print("query slave : ");
Serial.print(nextCommand->slave);
Serial.print(" qid: ");
Serial.print(nextCommand->id);
Serial.print(" ts: ");
Serial.print(nextCommand->ts);
Serial.print(" fn: ");
Serial.print(nextCommand->fn);
Serial.println("----");
}
modbus->query(nextCommand->slave, nextCommand->fn, nextCommand->addr, nextCommand->value, this, (AddonFnPtr)&OmronPID::responseFn);
print();
if (!isRunning())
{
statusLight.setBlink(false);
statusLight.off();
return;
}
if (isHeatingUp())
{
statusLight.setBlink(true);
}
else
{
statusLight.setBlink(false);
statusLight.on();
}
}
}
}
short OmronPID::onError(short error)
{
if (printMBErrors)
{
Serial.print("Omron PID :: onError ");
if (error == 255)
{
Serial.println("Timeout");
}
else
{
Serial.println(error);
}
}
Query *last = modbus->nextQueryByState(QUERY_STATE::PROCESSING, OMRON_PID);
if (last)
{
last->reset();
}
else
{
Serial.println("Omron PID :: onError - can't find last query! ");
}
resetStates();
}
void OmronPID::resetStates()
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
states[i].flags = OmronState::FLAGS::UPDATED;
}
}
OmronState *OmronPID::nextToUpdate()
{
OmronState *oldest = NULL;
bool isUpdating = false;
millis_t t = millis();
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
if (states[i].flags == OmronState::FLAGS::UPDATING)
{
continue;
}
if (!oldest)
{
oldest = &states[i];
}
/*
if (&states[i] != oldest && states[i].lastUpdated < oldest->lastUpdated)
{
oldest = &states[i];
}
*/
if (millis() - states[i].lastUpdated > OMRON_PID_UPDATE_INTERVAL * 2)
{
oldest = &states[i];
}
if (states[i].flags == OmronState::FLAGS::UPDATING)
{
isUpdating = true;
}
}
if (isUpdating)
{
return NULL;
}
return oldest;
}
bool OmronPID::isHeatingUp()
{
bool ret = false;
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
if (states[i].isHeating())
{
return true;
}
}
return ret;
}
bool OmronPID::isRunning()
{
bool ret = false;
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
if (states[i].isRunning())
{
return true;
}
}
return ret;
}
void OmronPID::printStates()
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
states[i].print();
}
}
OmronState *OmronPID::nextToWrite()
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
if (millis() - states[i].lastWritten > OMRON_PID_WRITE_INTERVAL)
{
return &states[i];
}
}
return NULL;
}
short OmronPID::debug(Stream *stream)
{
//*stream << this->name << ":" << this->ok();
return false;
}
short OmronPID::info(Stream *stream)
{
//*stream << this->name << "\n\t : " SPACE("Pin:" << MOTOR_IDLE_PIN);
return false;
}
void OmronPID::initPIDS()
{
for (short i = 0; i < NB_OMRON_PIDS; i++)
{
states[i].slaveID = slaveStart + i;
states[i].idx = i;
states[i].lastUpdated = millis();
states[i].lastWritten = millis();
states[i].flags = OmronState::FLAGS::UPDATED;
}
}

View File

@ -0,0 +1,179 @@
#ifndef OMRON_PID_H
#define OMRON_PID_H
#ifdef HAS_STATES
#include <ArduinoJson.h>
#endif
#include <Streaming.h>
#include "./Addon.h"
#include "./config.h"
#include "./common/macros.h"
#include "./components/OmronE5.h"
#include "components/StatusLight.h"
#include <Vector.h>
#include "ModbusBridge.h"
// actual PID, holds only values and handy functions
class OmronState
{
public:
int statusHigh;
int statusLow;
int pv;
int sp;
int flags;
int slaveID;
int idx;
millis_t lastUpdated;
millis_t lastWritten;
short state;
bool ready;
enum FLAGS
{
DIRTY = 1,
UPDATING = 2,
UPDATED = 3
};
OmronState() : statusHigh(-1),
statusLow(-1),
pv(-1),
sp(-1),
flags(DIRTY),
lastUpdated(millis()),
lastWritten(millis()),
ready(false)
{
}
bool isRunning()
{
return !OR_E5_STATUS_BIT(statusHigh, statusLow, OR_E5_STATUS_1::OR_E5_S1_RunStop);
}
bool isHeating()
{
return OR_E5_STATUS_BIT(statusHigh, statusLow, OR_E5_STATUS_1::OR_E5_S1_Control_OutputOpenOutput);
}
bool isCooling()
{
return OR_E5_STATUS_BIT(statusHigh, statusLow, OR_E5_STATUS_1::OR_E5_S1_Control_OutputCloseOutput);
}
void print()
{
Serial.print("PID - ");
Serial.print(idx);
Serial.print(" : Slave Addr : ");
Serial.print(slaveID);
Serial.print(" | PV : ");
Serial.print(pv);
Serial.print(" | SP : ");
Serial.print(sp);
Serial.print(" | LastUpdate : ");
Serial.print(millis() - lastUpdated);
Serial.print(" | Flags : ");
Serial.print(flags, HEX);
Serial.print("\n");
}
};
// Addon to deal with multiple Omron PID controllers
class OmronPID : public Addon
{
public:
OmronPID(ModbusBridge *_bridge, short _slaveStart) : modbus(_bridge),
slaveStart(_slaveStart),
statusLight(STATUS_PID_PIN),
Addon(OMRON_PID_STR, OMRON_PID, ADDON_STATED)
{
setFlag(DEBUG);
cPID = 0;
initPIDS();
startTS = millis();
}
virtual short loop();
virtual short setup();
short debug(Stream *stream);
short info(Stream *stream);
// PID access
OmronState *OmronPID::nextToUpdate();
OmronState *OmronPID::nextToWrite();
// Modbus callbacks
short responseFn(short error);
short queryResponse(short error);
short onError(short error);
short rawResponse(short size, uint8_t rxBuffer[]);
// PID programming
void stopAll();
void runAll();
void setAllSP(int sp);
bool isHeatingUp();
bool isRunning();
StatusLight statusLight;
///////////////////////////////////////////
// Modbus
Vector<Query> queries;
private:
// config
short slaveStart;
short nbPIDs;
// current PID to read updates from
short cPID;
ModbusBridge *modbus;
// actual PID states
OmronState states[NB_OMRON_PIDS];
bool mute;
// Modbus query / commands
int eachPID(short fn, int addr, int value);
int eachPIDW(int addr, int value);
int singlePID(int slave, short fn, int addr, int value);
int singlePIDW(int slave, int addr, int value);
OmronState *pidBySlave(int slave);
OmronState *current();
short read10_16(int slaveAddress, int addr, int prio = 0);
void updateState();
millis_t interval;
void printStates();
bool locked;
void updateTCP();
void fromTCP();
void print();
void resetStates();
millis_t startTS;
protected:
// initialize PID states
void initPIDS();
// for debugging and testing
void testPIDs();
};
#endif

View File

@ -0,0 +1,122 @@
#include "OmronVFD.h"
#include "ModbusBridge.h"
#include "./components/OmronMX2.h"
#include "app.h"
#define valA001 3 // A001 Frequency reference source = 03 (no need to change)
#define valA002 3 // A002 Source of the “Move” command = 1 (no need to change)
#define valC026 5 // C026 Relay output function 5 (AL: error signal) = 05
#define DEF_FC_MAX_FREQ 500
void OmronVFD::doTest()
{
Serial.println(" Do VFD Tests ");
pollState = true;
//forward();
// ping();
setTargetFreq(50);
run();
//reverse();
//run();
/*
owner->timer.in(
10000, [](OmronVFD *me) -> void {
me->stop();
},
this);
*/
// stop();
// configure();
}
uint16_t OmronVFD::configure()
{
//write_Single(MX2_A001, valA001);
//write_Single(MX2_A002, valA002);
//write_Single(MX2_C026, valC026); // C026 Relay output function 5 (AL: error signal) = 05
// write_Single(MX2_A004, DEF_FC_MAX_FREQ / 10); // A004 setting the maximum frequency
// progReg32(MX2_F002, (char *)" F002 ", FC_ACCEL_TIME); // F002 Acceleration Time
// progReg32(MX2_F002, (char *)" F003 ", FC_DEACCEL_TIME); // F003 Acceleration Braking
for (int i = 0; 0 < MB_N_R; i++)
{
modbus->mb->R[i] = 0;
}
for (int i = 0; 0 < MB_N_C; i++)
{
modbus->mb->C[i] = false;
}
}
uint16_t OmronVFD::updateState()
{
// readSingle_16(MX2_STATE);
//readSingle_16(MX2_STATUS);
if (now - readStateTS > OMRON_MX2_STATE_INTERVAL)
{
read_16(1, 5, MB_QUERY_TYPE_STATUS_POLL);
readStateTS = now;
// readSingle_16(0x1003);
}
//readSingle_16(MX2_CURRENT_FR);
//readSingle_16(MX2_AMPERAGE);
}
////////////////////////////////////////////////////////////////////////////
//
// HMI only (Manual = A2 = 2)
uint16_t OmronVFD::stop()
{
return write_Bit(MX2_START, 0);
}
uint16_t OmronVFD::run()
{
return write_Bit(MX2_START, 1);
}
uint16_t OmronVFD::reverse()
{
return write_Bit(MX2_SET_DIR, 1);
}
uint16_t OmronVFD::forward()
{
return write_Bit(MX2_SET_DIR, 0);
}
uint16_t OmronVFD::setTargetFreq(uint16_t freq)
{
return write_Single(MX2_TARGET_FR, freq * 100);
}
////////////////////////////////////////////////////////////////////////////
//
// Addon impl.
short OmronVFD::setup()
{
// configure();
}
short OmronVFD::loop()
{
modbusLoop();
status.loop();
}
short OmronVFD::debug(Stream *stream)
{
//*stream << this->name << ":" << this->ok();
return false;
}
short OmronVFD::info(Stream *stream)
{
//*stream << this->name << "\n\t : " SPACE("Pin:" << MOTOR_IDLE_PIN);
return false;
}
void OmronVFD::init()
{
}

View File

@ -0,0 +1,150 @@
#ifndef OMRON_VFD_H
#define OMRON_VFD_H
#ifdef HAS_STATES
#include <ArduinoJson.h>
#endif
#include <Streaming.h>
#include "./Addon.h"
#include "./config.h"
#include "./common/macros.h"
#include "./components/OmronE5.h"
#include <Vector.h>
#include "ModbusBridge.h"
#include "common/timer.h"
#include "components/StatusLight.h"
class App;
// actual PID, holds only values and handy functions
class OmronVFDState
{
public:
struct type_errorMX2 // error structure
{
uint16_t code; // reason
uint16_t status; // Inverter status on shutdown
uint16_t noUse; // Not used
uint16_t fr; // IF frequency during shutdown
uint16_t cur; // IF current on shutdown
uint16_t vol; // IF voltage when disconnected
uint32_t time1; // Total running time in STROKE mode when disconnected
uint32_t time2; // Total operating time of the inverter with the power on at the time of shutdown
};
union union_errorFC // Omron Error Translation
{
type_errorMX2 MX2;
uint16_t inputBuf[10];
};
int8_t err; // last error
uint16_t numErr; // number of errors
uint8_t nbComErrors; // The number of communication errors when exceeding FC_NUM_READ inverter lock 485 control
uint16_t FC; // Inverter target frequency in 0.01 hertz
uint16_t freqFC; // Read: current inverter frequency in 0.01 hertz
uint16_t power; // Read: Current inverter power in 100 watt units (3 is 300 watts)
uint16_t current; // Read: Current inverter current in 0.01 Amp units
int16_t state; // Read: State of the inverter register MX2_STATE
int16_t status; // Read: Status of the inverter register MX2_STATUS
millis_t startTS; // compressor start time
union_errorFC error; // Structure for decoding the inverter error
millis_t lastUpdated;
millis_t lastWritten;
OmronVFDState() : lastUpdated(millis()),
lastWritten(millis())
{
}
};
// Addon to deal with multiple Omron PID controllers
class OmronVFD : public Addon
{
public:
OmronVFD(ModbusBridge *_bridge, short _slaveStart) : modbus(_bridge),
slaveAddress(_slaveStart),
status(STATUS_VFD_PIN),
Addon(OMRON_VFD_STR, OMRON_VFD, ADDON_STATED)
{
setFlag(DEBUG);
init();
ready = false;
readStateTS = millis();
interval = millis();
setFQTS = millis();
}
virtual short loop();
virtual short setup();
short debug(Stream *stream);
short info(Stream *stream);
// Modbus callbacks
short responseFn(short error);
short queryResponse(short error);
short onError(short error);
short rawResponse(short size, uint8_t rxBuffer[]);
///////////////////////////////////////////
// Modbus
Vector<Query> queries;
short readSingle_16(int addr, int prio = 0);
short read_16(int addr, int num, int prio = 0);
uint16_t write_Single(uint16_t cmd, unsigned int data);
uint16_t write_Bit(uint16_t addr, int on);
///////////////////////////////////////////
// HMI
uint16_t setTargetFreq(uint16_t freq);
uint16_t stop();
uint16_t run();
uint16_t reverse();
uint16_t forward();
///////////////////////////////////////////
// Basics (mandatory)
uint16_t configure();
uint16_t updateState();
millis_t interval;
millis_t readStateTS;
millis_t debugTS;
millis_t setFQTS;
bool pollState;
void doTest();
App *owner;
millis_t last;
private:
// config
short slaveAddress;
ModbusBridge *modbus;
StatusLight status;
// actual VFD state
OmronVFDState states[1];
short ping();
void updateTCP();
void fromTCP();
void modbusLoop();
bool ready;
protected:
// initialize VFD states
void init();
};
#endif

View File

@ -0,0 +1,371 @@
#include "OmronVFD.h"
#include "ModbusBridge.h"
#include "./components/OmronMX2.h"
#include "app.h"
////////////////////////////////////////////////////////////////////////////
//
// Modbus
bool didTest = true;
bool debugReceive = false;
bool debugSend = false;
bool debugFilter = true;
bool debugMultiRegs = false;
bool debugModQueries = false;
bool printErrors = true;
short OmronVFD::onError(short error)
{
if (printErrors)
{
Serial.print("Omron VFD onError : ");
if (error == 255)
{
Serial.println("Timeout");
}
else
{
Serial.println(error);
}
}
Query *last = modbus->nextQueryByState(QUERY_STATE::PROCESSING, OMRON_VFD);
if (last)
{
last->reset();
}
else
{
Serial.println("Omron VDF :: onError - can't find last query! ");
}
}
void OmronVFD::modbusLoop()
{
if (!didTest)
{
didTest = true;
doTest();
}
updateState();
if (millis() - interval > OMRON_MX2_LOOP_INTERVAL)
{
interval = now;
if (ready)
{
fromTCP();
}
Query *nextCommand = modbus->nextQueryByState(QUERY_STATE::QUEUED, OMRON_VFD);
if (nextCommand)
{
if (modbus->qstate() != IDLE)
{
return;
}
nextCommand->state = QUERY_STATE::PROCESSING;
modbus->nextWaitingTime = MODBUS_CMD_WAIT;
modbus->onMessage = (AddonRxFn)&OmronVFD::rawResponse;
modbus->onError = (AddonFnPtr)&OmronVFD::onError;
if (debugSend)
{
if (now - debugTS > OMRON_MX2_DEBUG_INTERVAL)
{
debugTS = now;
Serial.print("next to send ");
Serial.print(nextCommand->id);
Serial.print(" | ");
Serial.print(nextCommand->ts);
Serial.print(" | Addr=");
Serial.print(nextCommand->addr);
Serial.print(" | Value=");
Serial.print(nextCommand->value);
Serial.print(" | FN=");
Serial.print(nextCommand->fn);
Serial.print("\n");
if (debugModQueries)
{
modbus->print();
}
}
}
modbus->query(nextCommand->slave, nextCommand->fn, nextCommand->addr, nextCommand->value, this, (AddonFnPtr)&OmronVFD::queryResponse);
return;
}
}
}
short OmronVFD::ping()
{
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = ku8MBLinkTestOmronMX2Only;
next->slave = slaveAddress;
next->value = 1234;
next->addr = 0;
next->state = QUERY_STATE::QUEUED;
next->ts = millis();
return E_OK;
}
return E_QUERY_BUFFER_END;
}
short OmronVFD::rawResponse(short size, uint8_t rxBuffer[])
{
if (!size)
{
return E_OK;
}
if (debugReceive)
{
Serial.print("\nIncoming:");
Serial.print(size);
Serial.print("::\t");
for (int i = 0; i < size; i++)
{
Serial.print(rxBuffer[i], HEX);
Serial.print(" : ");
}
Serial.print("\n");
}
if (size == 5)
{
Serial.println("Error");
}
return ERROR_OK;
}
short OmronVFD::responseFn(short error)
{
}
short OmronVFD::queryResponse(short error)
{
Query *last = modbus->nextQueryByState(QUERY_STATE::PROCESSING, OMRON_VFD);
if (last)
{
long first = modbus->ModbusSlaveRegisters[0];
if (last->prio == MB_QUERY_TYPE_STATUS_POLL)
{
states[0].state = modbus->ModbusSlaveRegisters[3];
states[0].status = modbus->ModbusSlaveRegisters[2];
states[0].FC = modbus->ModbusSlaveRegisters[0];
ready = true;
updateTCP();
if (debugMultiRegs)
{
Serial.print(" - regs : \n ");
for (int i = 0; i < 5; i++)
{
Serial.print(" - ");
Serial.print(modbus->ModbusSlaveRegisters[i]);
Serial.print("\n");
}
}
}
last->addr = 0;
last->value = 0;
last->slave = 0;
last->ts = 0;
last->prio = 0;
last->state = QUERY_STATE::DONE;
}
else
{
Serial.println("state error, had nothing to process");
}
}
void OmronVFD::updateTCP()
{
modbus->mb->R[MB_R_VFD_STATUS] = states[0].status;
modbus->mb->R[MB_R_VFD_STATE] = states[0].state;
modbus->mb->R[MB_R_FREQ_TARGET] = states[0].FC;
// fromTCP();
}
void OmronVFD::fromTCP()
{
if (modbus->mb->R[MB_W_VFD_RUN] == 1)
{
write_Bit(MX2_START, 1);
modbus->mb->R[MB_W_VFD_RUN] = 0;
}
if (modbus->mb->R[MB_W_VFD_RUN] == 2)
{
write_Bit(MX2_START, 0);
modbus->mb->R[MB_W_VFD_RUN] = 0;
}
if (modbus->mb->R[MB_W_VFD_RUN] == 2)
{
modbus->mb->R[MB_W_VFD_RUN] = 0;
write_Bit(MX2_START, 0);
}
if (modbus->mb->R[MB_W_DIRECTION] > 0)
{
switch (modbus->mb->R[MB_W_DIRECTION])
{
case 1:
forward();
break;
case 2:
reverse();
break;
default:
stop();
break;
}
modbus->mb->R[MB_W_DIRECTION] = 0;
}
if (states[0].state == OMRON_STATE_DECELERATING || states[0].state == OMRON_STATE_ACCELERATING)
{
status.setBlink(true);
}
if (states[0].state == OMRON_STATE_RUNNING)
{
status.setBlink(false);
status.on();
}
if (states[0].state == OMRON_STATE_STOPPED)
{
status.setBlink(false);
status.off();
}
if (modbus->mb->R[MB_W_FREQ_TARGET] > 0)
{
setTargetFreq(modbus->mb->R[MB_W_FREQ_TARGET]);
modbus->mb->R[MB_W_FREQ_TARGET] = 0;
}
}
uint16_t OmronVFD::write_Single(uint16_t addr, unsigned int data)
{
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = ku8MBWriteSingleRegister;
next->slave = slaveAddress;
// modbus->setDebugSend(true);
next->value = data;
next->addr = addr;
next->state = QUERY_STATE::QUEUED;
next->ts = millis();
next->owner = OMRON_VFD;
next->prio = MB_QUERY_TYPE_CMD;
return E_OK;
}
return E_QUERY_BUFFER_END;
}
uint16_t OmronVFD::write_Bit(uint16_t addr, int on)
{
Query *same = modbus->nextSame(QUEUED, slaveAddress, addr, ku8MBWriteSingleCoil, on);
if (same && millis() - same->ts < 300)
{
}
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = ku8MBWriteSingleCoil;
next->slave = slaveAddress;
next->addr = addr;
// modbus->setDebugSend(true);
next->value = on;
next->state = QUERY_STATE::QUEUED;
next->ts = millis();
next->owner = OMRON_VFD;
next->prio = MB_QUERY_TYPE_CMD;
return E_OK;
}
return E_QUERY_BUFFER_END;
}
short OmronVFD::readSingle_16(int addr, int prio = 0)
{
Query *same = modbus->nextSame(QUEUED, slaveAddress, addr, ku8MBReadHoldingRegisters, 1);
if (same && millis() - same->ts < OMRON_MX2_SAME_REQUEST_INTERVAL)
{
return;
}
if (modbus->numByState(DONE) < MODBUS_QUEUE_MIN_FREE)
{
return;
}
if (modbus->numSame(QUEUED, slaveAddress, addr, ku8MBReadHoldingRegisters, 1) > 1)
{
return;
}
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = ku8MBReadHoldingRegisters;
next->slave = slaveAddress;
next->value = 1;
next->addr = addr;
next->state = QUERY_STATE::QUEUED;
next->ts = millis();
next->prio = prio;
next->owner = OMRON_VFD;
return E_OK;
}
return E_QUERY_BUFFER_END;
}
short OmronVFD::read_16(int addr, int num, int prio = 0)
{
Query *same = modbus->nextSame(QUEUED, slaveAddress, addr, ku8MBReadHoldingRegisters, 1);
if (same && millis() - same->ts < OMRON_MX2_SAME_REQUEST_INTERVAL)
{
return;
}
if (modbus->numByState(DONE) < MODBUS_QUEUE_MIN_FREE)
{
return;
}
if (modbus->numSame(QUEUED, slaveAddress, addr, ku8MBReadHoldingRegisters, 1) > 1)
{
return;
}
Query *next = modbus->nextQueryByState(DONE);
if (next)
{
next->fn = ku8MBReadHoldingRegisters;
next->slave = slaveAddress;
next->value = num;
next->addr = addr;
next->state = QUERY_STATE::QUEUED;
next->ts = millis();
next->prio = prio;
next->owner = OMRON_VFD;
return E_OK;
}
return E_QUERY_BUFFER_END;
}

View File

@ -0,0 +1,5 @@
# TODOS
- new PHStudio widgets: PID control & Display
- info tab: vfd status, PID status, sensor LEDS
- HMIs: shredder, extrusion, shredder && extrusion, asterix

View File

@ -0,0 +1,54 @@
/*
* Interrupt and PWM utilities for 16 bit Timer1 on ATmega168/328
* Original code by Jesse Tane for http://labs.ideo.com August 2008
* Modified March 2009 by Jérôme Despatis and Jesse Tane for ATmega328 support
* Modified June 2009 by Michael Polli and Jesse Tane to fix a bug in setPeriod() which caused the timer to stop
* Modified Oct 2009 by Dan Clemens to work with timer1 of the ATMega1280 or Arduino Mega
* Modified April 2012 by Paul Stoffregen
* Modified again, June 2014 by Paul Stoffregen
* Modified July 2017 by Stoyko Dimitrov - added support for ATTiny85 except for the PWM functionality
*
* This is free software. You can redistribute it and/or modify it under
* the terms of Creative Commons Attribution 3.0 United States License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/us/
* or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
*
*/
#include "TimerOne.h"
TimerOne Timer1; // preinstatiate
unsigned short TimerOne::pwmPeriod = 0;
unsigned char TimerOne::clockSelectBits = 0;
void (*TimerOne::isrCallback)() = TimerOne::isrDefaultUnused;
// interrupt service routine that wraps a user defined function supplied by attachInterrupt
#if defined (__AVR_ATtiny85__)
ISR(TIMER1_COMPA_vect)
{
Timer1.isrCallback();
}
#elif defined(__AVR__)
ISR(TIMER1_OVF_vect)
{
Timer1.isrCallback();
}
#elif defined(__arm__) && defined(CORE_TEENSY)
void ftm1_isr(void)
{
uint32_t sc = FTM1_SC;
#ifdef KINETISL
if (sc & 0x80) FTM1_SC = sc;
#else
if (sc & 0x80) FTM1_SC = sc & 0x7F;
#endif
Timer1.isrCallback();
}
#endif
void TimerOne::isrDefaultUnused()
{
}

View File

@ -0,0 +1,485 @@
/*
* Interrupt and PWM utilities for 16 bit Timer1 on ATmega168/328
* Original code by Jesse Tane for http://labs.ideo.com August 2008
* Modified March 2009 by Jérôme Despatis and Jesse Tane for ATmega328 support
* Modified June 2009 by Michael Polli and Jesse Tane to fix a bug in setPeriod() which caused the timer to stop
* Modified April 2012 by Paul Stoffregen - portable to other AVR chips, use inline functions
* Modified again, June 2014 by Paul Stoffregen - support Teensy 3.x & even more AVR chips
* Modified July 2017 by Stoyko Dimitrov - added support for ATTiny85 except for the PWM functionality
*
*
* This is free software. You can redistribute it and/or modify it under
* the terms of Creative Commons Attribution 3.0 United States License.
* To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/us/
* or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
*
*/
#ifndef TimerOne_h_
#define TimerOne_h_
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "config/known_16bit_timers.h"
#if defined (__AVR_ATtiny85__)
#define TIMER1_RESOLUTION 256UL // Timer1 is 8 bit
#elif defined(__AVR__)
#define TIMER1_RESOLUTION 65536UL // Timer1 is 16 bit
#else
#define TIMER1_RESOLUTION 65536UL // assume 16 bits for non-AVR chips
#endif
// Placing nearly all the code in this .h file allows the functions to be
// inlined by the compiler. In the very common case with constant values
// the compiler will perform all calculations and simply write constants
// to the hardware registers (for example, setPeriod).
class TimerOne
{
#if defined (__AVR_ATtiny85__)
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
TCCR1 = _BV(CTC1); //clear timer1 when it matches the value in OCR1C
TIMSK |= _BV(OCIE1A); //enable interrupt when OCR1A matches the timer value
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = microseconds * ratio;
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = _BV(CS10);
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 2UL) {
clockSelectBits = _BV(CS11);
pwmPeriod = cycles / 2;
} else
if (cycles < TIMER1_RESOLUTION * 4UL) {
clockSelectBits = _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 4;
} else
if (cycles < TIMER1_RESOLUTION * 8UL) {
clockSelectBits = _BV(CS12);
pwmPeriod = cycles / 8;
} else
if (cycles < TIMER1_RESOLUTION * 16UL) {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = cycles / 16;
} else
if (cycles < TIMER1_RESOLUTION * 32UL) {
clockSelectBits = _BV(CS12) | _BV(CS11);
pwmPeriod = cycles / 32;
} else
if (cycles < TIMER1_RESOLUTION * 64UL) {
clockSelectBits = _BV(CS12) | _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 64UL;
} else
if (cycles < TIMER1_RESOLUTION * 128UL) {
clockSelectBits = _BV(CS13);
pwmPeriod = cycles / 128;
} else
if (cycles < TIMER1_RESOLUTION * 256UL) {
clockSelectBits = _BV(CS13) | _BV(CS10);
pwmPeriod = cycles / 256;
} else
if (cycles < TIMER1_RESOLUTION * 512UL) {
clockSelectBits = _BV(CS13) | _BV(CS11);
pwmPeriod = cycles / 512;
} else
if (cycles < TIMER1_RESOLUTION * 1024UL) {
clockSelectBits = _BV(CS13) | _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 1024;
} else
if (cycles < TIMER1_RESOLUTION * 2048UL) {
clockSelectBits = _BV(CS13) | _BV(CS12);
pwmPeriod = cycles / 2048;
} else
if (cycles < TIMER1_RESOLUTION * 4096UL) {
clockSelectBits = _BV(CS13) | _BV(CS12) | _BV(CS10);
pwmPeriod = cycles / 4096;
} else
if (cycles < TIMER1_RESOLUTION * 8192UL) {
clockSelectBits = _BV(CS13) | _BV(CS12) | _BV(CS11);
pwmPeriod = cycles / 8192;
} else
if (cycles < TIMER1_RESOLUTION * 16384UL) {
clockSelectBits = _BV(CS13) | _BV(CS12) | _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 16384;
} else {
clockSelectBits = _BV(CS13) | _BV(CS12) | _BV(CS11) | _BV(CS10);
pwmPeriod = TIMER1_RESOLUTION - 1;
}
OCR1A = pwmPeriod;
OCR1C = pwmPeriod;
TCCR1 = _BV(CTC1) | clockSelectBits;
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
TCCR1 = 0;
TCNT1 = 0;
resume();
}
void stop() __attribute__((always_inline)) {
TCCR1 = _BV(CTC1);
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
TCCR1 = _BV(CTC1) | clockSelectBits;
}
//****************************
// PWM outputs
//****************************
//Not implemented yet for ATTiny85
//TO DO
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
TIMSK |= _BV(OCIE1A);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
//TIMSK = 0; // Timer 0 and Timer 1 both use TIMSK register so setting it to 0 will override settings for Timer1 as well
TIMSK &= ~_BV(OCIE1A);
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
static const byte ratio = (F_CPU)/ ( 1000000 );
#elif defined(__AVR__)
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
TCCR1B = _BV(WGM13); // set mode as phase and frequency correct pwm, stop the timer
TCCR1A = 0; // clear control register A
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = (F_CPU / 2000000) * microseconds;
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = _BV(CS10);
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = _BV(CS11);
pwmPeriod = cycles / 8;
} else
if (cycles < TIMER1_RESOLUTION * 64) {
clockSelectBits = _BV(CS11) | _BV(CS10);
pwmPeriod = cycles / 64;
} else
if (cycles < TIMER1_RESOLUTION * 256) {
clockSelectBits = _BV(CS12);
pwmPeriod = cycles / 256;
} else
if (cycles < TIMER1_RESOLUTION * 1024) {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = cycles / 1024;
} else {
clockSelectBits = _BV(CS12) | _BV(CS10);
pwmPeriod = TIMER1_RESOLUTION - 1;
}
ICR1 = pwmPeriod;
TCCR1B = _BV(WGM13) | clockSelectBits;
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
TCCR1B = 0;
TCNT1 = 0; // TODO: does this cause an undesired interrupt?
resume();
}
void stop() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13);
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
TCCR1B = _BV(WGM13) | clockSelectBits;
}
//****************************
// PWM outputs
//****************************
void setPwmDuty(char pin, unsigned int duty) __attribute__((always_inline)) {
unsigned long dutyCycle = pwmPeriod;
dutyCycle *= duty;
dutyCycle >>= 10;
if (pin == TIMER1_A_PIN) OCR1A = dutyCycle;
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) OCR1B = dutyCycle;
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) OCR1C = dutyCycle;
#endif
}
void pwm(char pin, unsigned int duty) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) { pinMode(TIMER1_A_PIN, OUTPUT); TCCR1A |= _BV(COM1A1); }
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) { pinMode(TIMER1_B_PIN, OUTPUT); TCCR1A |= _BV(COM1B1); }
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) { pinMode(TIMER1_C_PIN, OUTPUT); TCCR1A |= _BV(COM1C1); }
#endif
setPwmDuty(pin, duty);
TCCR1B = _BV(WGM13) | clockSelectBits;
}
void pwm(char pin, unsigned int duty, unsigned long microseconds) __attribute__((always_inline)) {
if (microseconds > 0) setPeriod(microseconds);
pwm(pin, duty);
}
void disablePwm(char pin) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) TCCR1A &= ~_BV(COM1A1);
#ifdef TIMER1_B_PIN
else if (pin == TIMER1_B_PIN) TCCR1A &= ~_BV(COM1B1);
#endif
#ifdef TIMER1_C_PIN
else if (pin == TIMER1_C_PIN) TCCR1A &= ~_BV(COM1C1);
#endif
}
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
TIMSK1 = _BV(TOIE1);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
TIMSK1 = 0;
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
// properties
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
#elif defined(__arm__) && defined(CORE_TEENSY)
#if defined(KINETISK)
#define F_TIMER F_BUS
#elif defined(KINETISL)
#define F_TIMER (F_PLL/2)
#endif
public:
//****************************
// Configuration
//****************************
void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) {
setPeriod(microseconds);
}
void setPeriod(unsigned long microseconds) __attribute__((always_inline)) {
const unsigned long cycles = (F_TIMER / 2000000) * microseconds;
// A much faster if-else
// This is like a binary serch tree and no more than 3 conditions are evaluated.
// I haven't checked if this becomes significantly longer ASM than the simple ladder.
// It looks very similar to the ladder tho: same # of if's and else's
/*
// This code does not work properly in all cases :(
// https://github.com/PaulStoffregen/TimerOne/issues/17
if (cycles < TIMER1_RESOLUTION * 16) {
if (cycles < TIMER1_RESOLUTION * 4) {
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = 0;
pwmPeriod = cycles;
}else{
clockSelectBits = 1;
pwmPeriod = cycles >> 1;
}
}else{
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = 3;
pwmPeriod = cycles >> 3;
}else{
clockSelectBits = 4;
pwmPeriod = cycles >> 4;
}
}
}else{
if (cycles > TIMER1_RESOLUTION * 64) {
if (cycles > TIMER1_RESOLUTION * 128) {
clockSelectBits = 7;
pwmPeriod = TIMER1_RESOLUTION - 1;
}else{
clockSelectBits = 7;
pwmPeriod = cycles >> 7;
}
}
else{
if (cycles > TIMER1_RESOLUTION * 32) {
clockSelectBits = 6;
pwmPeriod = cycles >> 6;
}else{
clockSelectBits = 5;
pwmPeriod = cycles >> 5;
}
}
}
*/
if (cycles < TIMER1_RESOLUTION) {
clockSelectBits = 0;
pwmPeriod = cycles;
} else
if (cycles < TIMER1_RESOLUTION * 2) {
clockSelectBits = 1;
pwmPeriod = cycles >> 1;
} else
if (cycles < TIMER1_RESOLUTION * 4) {
clockSelectBits = 2;
pwmPeriod = cycles >> 2;
} else
if (cycles < TIMER1_RESOLUTION * 8) {
clockSelectBits = 3;
pwmPeriod = cycles >> 3;
} else
if (cycles < TIMER1_RESOLUTION * 16) {
clockSelectBits = 4;
pwmPeriod = cycles >> 4;
} else
if (cycles < TIMER1_RESOLUTION * 32) {
clockSelectBits = 5;
pwmPeriod = cycles >> 5;
} else
if (cycles < TIMER1_RESOLUTION * 64) {
clockSelectBits = 6;
pwmPeriod = cycles >> 6;
} else
if (cycles < TIMER1_RESOLUTION * 128) {
clockSelectBits = 7;
pwmPeriod = cycles >> 7;
} else {
clockSelectBits = 7;
pwmPeriod = TIMER1_RESOLUTION - 1;
}
uint32_t sc = FTM1_SC;
FTM1_SC = 0;
FTM1_MOD = pwmPeriod;
FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_CPWMS | clockSelectBits | (sc & FTM_SC_TOIE);
}
//****************************
// Run Control
//****************************
void start() __attribute__((always_inline)) {
stop();
FTM1_CNT = 0;
resume();
}
void stop() __attribute__((always_inline)) {
FTM1_SC = FTM1_SC & (FTM_SC_TOIE | FTM_SC_CPWMS | FTM_SC_PS(7));
}
void restart() __attribute__((always_inline)) {
start();
}
void resume() __attribute__((always_inline)) {
FTM1_SC = (FTM1_SC & (FTM_SC_TOIE | FTM_SC_PS(7))) | FTM_SC_CPWMS | FTM_SC_CLKS(1);
}
//****************************
// PWM outputs
//****************************
void setPwmDuty(char pin, unsigned int duty) __attribute__((always_inline)) {
unsigned long dutyCycle = pwmPeriod;
dutyCycle *= duty;
dutyCycle >>= 10;
if (pin == TIMER1_A_PIN) {
FTM1_C0V = dutyCycle;
} else if (pin == TIMER1_B_PIN) {
FTM1_C1V = dutyCycle;
}
}
void pwm(char pin, unsigned int duty) __attribute__((always_inline)) {
setPwmDuty(pin, duty);
if (pin == TIMER1_A_PIN) {
*portConfigRegister(TIMER1_A_PIN) = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
} else if (pin == TIMER1_B_PIN) {
*portConfigRegister(TIMER1_B_PIN) = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
}
}
void pwm(char pin, unsigned int duty, unsigned long microseconds) __attribute__((always_inline)) {
if (microseconds > 0) setPeriod(microseconds);
pwm(pin, duty);
}
void disablePwm(char pin) __attribute__((always_inline)) {
if (pin == TIMER1_A_PIN) {
*portConfigRegister(TIMER1_A_PIN) = 0;
} else if (pin == TIMER1_B_PIN) {
*portConfigRegister(TIMER1_B_PIN) = 0;
}
}
//****************************
// Interrupt Function
//****************************
void attachInterrupt(void (*isr)()) __attribute__((always_inline)) {
isrCallback = isr;
FTM1_SC |= FTM_SC_TOIE;
NVIC_ENABLE_IRQ(IRQ_FTM1);
}
void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) {
if(microseconds > 0) setPeriod(microseconds);
attachInterrupt(isr);
}
void detachInterrupt() __attribute__((always_inline)) {
FTM1_SC &= ~FTM_SC_TOIE;
NVIC_DISABLE_IRQ(IRQ_FTM1);
}
static void (*isrCallback)();
static void isrDefaultUnused();
private:
// properties
static unsigned short pwmPeriod;
static unsigned char clockSelectBits;
#undef F_TIMER
#endif
};
extern TimerOne Timer1;
#endif

View File

@ -0,0 +1,110 @@
#ifndef VFD_H
#define VFD_H
#include <Streaming.h>
#include "./Addon.h"
#include "./enums.h"
#include "./config.h"
#ifdef HAS_STATES
#include <ArduinoJson.h>
#endif
class VFD : public Addon
{
public:
enum DIRECTION
{
FORWARD = 1,
STOP = 0,
REVERSE = 2
};
VFD() : Addon(VFD_STR, VFD_CONTROL),
direction(STOP){};
void rev(short nop)
{
update(DIRECTION::REVERSE);
}
void fwd(short nop)
{
update(DIRECTION::FORWARD);
}
short setup()
{
pinMode(FWD_PIN, OUTPUT);
pinMode(REV_PIN, OUTPUT);
stop();
}
short stop(short nop = 0)
{
update(DIRECTION::STOP);
}
void speed(int aValue)
{
}
virtual void debug(Stream *stream)
{
// *stream << this->name << ":" << SPACE(direction);
}
virtual void info(Stream *stream)
{
// *stream << this->name << "\n\t" << SPACE(": FWD PIN " << FWD_PIN << " | REV PIN " << REV_PIN);
}
uchar direction;
uchar lastDirection;
millis_t dt;
#ifdef HAS_STATES
String state()
{
const int capacity = JSON_OBJECT_SIZE(2);
StaticJsonDocument<capacity> doc;
doc["0"] = id;
doc["1"] = direction;
return doc.as<String>();
}
#endif
private:
void update(uchar newDirection)
{
if (direction != newDirection)
{
dt = now;
lastDirection = direction;
direction = newDirection;
switch (direction)
{
case DIRECTION::FORWARD:
{
digitalWrite(REV_PIN, LOW);
digitalWrite(FWD_PIN, HIGH);
break;
}
case DIRECTION::REVERSE:
{
digitalWrite(FWD_PIN, LOW);
digitalWrite(REV_PIN, HIGH);
break;
}
case DIRECTION::STOP:
{
digitalWrite(FWD_PIN, LOW);
digitalWrite(REV_PIN, LOW);
}
}
}
}
};
#endif

View File

@ -0,0 +1,7 @@
#ifndef VERSION_H
#define VERSION_H
#define VERSION '1.0.0|fe804146360b35c845dfdaa7781350e91aab19d2'
#endif

View File

@ -0,0 +1,35 @@
#ifndef MOTOR_AUTO_REVERSE_H
#define MOTOR_AUTO_REVERSE_H
#include <Arduino.h>
#include "../Addon.h"
#include "../config.h"
#include <Streaming.h>
#include "../macros.h"
#include "../enums.h"
class App;
class AutoReverse : Addon
{
public:
AutoReverse(App *app);
AutoReverse() : Addon(AUTO_REVERSE_STR, AUTO_REVERSE) {}
virtual short setup()
{
}
virtual short ok()
{
return true;
}
void debug(Stream *stream)
{
// *stream << this->name << ":" << this->ok();
}
void info(Stream *stream)
{
// *stream << this->name << "\n\t : " SPACE("Pin:" << MOTOR_IDLE_PIN);
}
};
#endif

View File

@ -0,0 +1,45 @@
#ifndef CARTRIDGE_FULL_H
#define CARTRIDGE_FULL_H
#include <Arduino.h>
#include "Addon.h"
#include <Streaming.h>
#include "../config.h"
#include "../macros.h"
#include "../components/PhotoElectricSensor.h"
// Addon to detect when the container is full of shredded flakes.
class CartridgeFull : public Addon
{
private:
PhotoElectricSensor sensor;
public:
CartridgeFull() : sensor(CARTRIDGE_FULL_1, CARTRIDGE_FULL_1_INTERVAL),
Addon(CARTRDIGE_FULL_STR, CARTRIDGE_FULL_SENSOR_1)
{
// this->setFlag(DEBUG);
}
virtual short loop()
{
this->sensor.loop();
}
virtual short ok()
{
return sensor.ok();
}
void debug(Stream *stream)
{
//*stream << this->name << ":" << this->ok();
}
void info(Stream *stream)
{
//*stream << this->name << "\n\t : " << SPACE("CARTRIDGE FULL 1" << CARTRIDGE_FULL_1);
}
};
#endif

View File

@ -0,0 +1,51 @@
#ifndef _DIP_SWITCH_H
#define _DIP_SWITCH_H
#include "addon.h"
#include <Streaming.h>
class _DipSwitch : public Addon
{
public:
_DipSwitch(int number_of_pins, int *pins) : _number_of_pins(number_of_pins),
_pins(_pins),
Addon("Dip Switch", DIP_SWITCH)
{
// this->setFlag(DEBUG);
}
short setup()
{
for (int i = 0; i < _number_of_pins; i++)
{
pinMode(_pins[i], INPUT_PULLUP);
}
}
short loop()
{
_value = 0;
for (int i = 0; i < _number_of_pins; i++)
{
_value += digitalRead(_pins[i]) << i;
}
return _value;
}
void debug(Stream *stream)
{
//*stream << this->name << ":" << digitalRead(49);
}
void info(Stream *stream)
{
//*stream << this->name << "\n\t : ";
}
private:
int _number_of_pins;
int *_pins;
int _value;
};
#endif

View File

@ -0,0 +1,33 @@
#ifndef DIRECTION_SWITCH_H
#define DIRECTION_SWITCH_H
#include "../config.h"
#include "../components/3pos.h"
#include "../Addon.h"
#include <Streaming.h>
#include "../common/macros.h"
class DirectionSwitch : public Addon {
public:
Pos3 dir_switch;
DirectionSwitch () :
dir_switch(DIR_SWITCH_UP_PIN, DIR_SWITCH_DOWN_PIN),
Addon(DIRECTION_SWITCH_STR,DIRECTION_SWITCH){}
void debug(Stream* stream){
//*stream << this->name << ":" <<
// SPACE(dir_switch.switch_pos) << SPACE(dir_switch.last_switch);
}
void info(Stream* stream){
//*stream << this->name << "\n\t : " SPACE("Up Pin:" << DIR_SWITCH_UP_PIN) << SPACE("\t | Down Pin :" << DIR_SWITCH_DOWN_PIN);
}
short setup(){
dir_switch.setup();
return dir_switch.loop();
}
short loop(){
return dir_switch.loop();
}
};
#endif

View File

@ -0,0 +1,43 @@
#ifndef ENCLOSURE_SENSOR_H
#define ENCLOSURE_SENSOR_H
#include "../config.h"
#include "../Addon.h"
#include <Streaming.h>
#include "../macros.h"
#include "../components/Proximity_Sensor.h"
class EnclosureSensor : public Addon
{
public:
ProximitySensor sensor1;
ProximitySensor sensor2;
EnclosureSensor() : sensor1(ENCLOSURE_SENSOR_PIN_1),
sensor2(ENCLOSURE_SENSOR_PIN_2),
Addon(ENCLOSURE_SENSOR_STR, ENCLOSURE_SENSOR) {}
void debug(Stream *stream)
{
//*stream << this->name << ":"
// << SPACE(sensor1.value) << ":" << SPACE(sensor2.value) << " | ok : " << ok();
}
void info(Stream *stream)
{
//*stream << this->name << SPACE("\n\t : " << ENCLOSURE_SENSOR_PIN_1) << SPACE(" : " << ENCLOSURE_SENSOR_PIN_2);
}
short setup()
{
sensor1.setup();
sensor2.setup();
sensor1.loop();
sensor2.loop();
}
short loop()
{
sensor1.loop();
sensor2.loop();
}
short ok() { return sensor1.value == 1 && sensor2.value == 1; }
};
#endif

View File

@ -0,0 +1,32 @@
#ifndef MOTOR_IDLE_H
#define MOTOR_IDLE_H
#include <Arduino.h>
#include "Addon.h"
#include "config.h"
#include <Streaming.h>
#include "../common/macros.h"
class MotorIdle : public Addon
{
public:
MotorIdle() : Addon(MOTOR_IDLE_STR, MOTOR_IDLE) {}
virtual short setup()
{
pinMode(MOTOR_IDLE_PIN, INPUT_PULLUP);
}
virtual short ok()
{
return !digitalRead(MOTOR_IDLE_PIN);
}
void debug(Stream *stream)
{
//*stream << this->name << ":" << this->ok();
}
void info(Stream *stream)
{
//*stream << this->name << "\n\t : " SPACE("Pin:" << MOTOR_IDLE_PIN);
}
};
#endif

View File

@ -0,0 +1,145 @@
#ifndef MOTOR_OVERLOAD_H
#define MOTOR_OVERLOAD_H
#include <Arduino.h>
#include <Streaming.h>
#include "../Addon.h"
#include "../config.h"
#include "../common/macros.h"
#include "../common/ppmath.h"
#ifdef HAS_STATES
#include <ArduinoJson.h>
#endif
class MotorLoad : public Addon
{
public:
enum MSTATE
{
NONE = 0,
IDLE = 1,
LOAD = 2,
OVERLOAD = 2,
ERROR = 3
};
#ifdef HAS_STATES
String state()
{
const int capacity = JSON_OBJECT_SIZE(2);
StaticJsonDocument<capacity> doc;
doc['0'] = id;
doc['s'] = currentState;
return doc.as<String>();
}
#endif
MotorLoad(short _pin) : dt(0),
pin(_pin),
load(0),
lastIdle(0),
lastLoad(0),
lastOverload(0),
currentState(NONE),
lastState(NONE),
Addon(MOTOR_LOAD_STR, MOTOR_LOAD)
{
// this->setFlag(DEBUG);
}
short jammed()
{
return RANGE(load, MOTOR_OVERLOAD_RANGE_MIN, MOTOR_OVERLOAD_RANGE_MAX);
}
short idle()
{
return RANGE(load, MOTOR_IDLE_LOAD_RANGE_MIN, MOTOR_IDLE_LOAD_RANGE_MAX);
}
short shredding()
{
return RANGE(load, MOTOR_SHREDDING_LOAD_RANGE_MIN, MOTOR_SHREDDING_LOAD_RANGE_MAX);
}
short setup()
{
loop();
}
short loop()
{
if (now - last > MOTOR_LOAD_READ_INTERVAL)
{
load = analogRead(pin);
last = now;
uchar newState = NONE;
if (idle())
{
lastIdle = now;
newState = IDLE;
}
else if (jammed())
{
lastOverload = now;
newState = OVERLOAD;
}
else if (shredding())
{
lastLoad = now;
newState = LOAD;
}
if (newState != currentState)
{
dt = now;
lastState = currentState;
currentState = newState;
}
}
return load;
}
short ok()
{
if (currentState == IDLE &&
(now - dt) > MAX_IDLE_TIME)
{
return E_MOTOR_DT_IDLE;
}
if (currentState == LOAD &&
(now - dt) > MAX_SHRED_TIME)
{
return E_MOTOR_DT_OVERLOAD;
}
return E_OK;
}
void debug(Stream *stream)
{
// *stream << this->name << ":" << jammed() << SPACE('@') << load << SPACE(":state") << currentState;
}
void info(Stream *stream)
{
// *stream << this->name << "\n\t : " SPACE("Pin:" << pin);
}
millis_t dt;
uchar lastState;
uchar currentState;
millis_t lastIdle;
millis_t lastLoad;
millis_t lastOverload;
protected:
short pin;
short load;
};
#endif

View File

@ -0,0 +1,41 @@
#ifndef MOTOR_SPEED_H
#define MOTOR_SPEED_H
#include <Arduino.h>
#include "Addon.h"
#include "config.h"
#include <Streaming.h>
#include "../common/macros.h"
#include "IRSensor.h"
class MotorSpeed : public Addon
{
public:
MotorSpeed() :
sensor(new IRSensor()),
Addon(MOTOR_IR_SPEED_STR, MOTOR_SPEED) {}
virtual short setup()
{
sensor->setup();
}
virtual short ok()
{
return this->sensor->ok();
}
virtual short loop()
{
this->sensor->loop();
}
void debug(Stream *stream)
{
//*stream << this->name << ":" << this->ok();
}
void info(Stream *stream)
{
//*stream << this->name << "\n\t : " SPACE("Pin:" << MOTOR_IDLE_PIN);
}
protected:
IRSensor *sensor;
};
#endif

View File

@ -0,0 +1,40 @@
#ifndef MOTOR_TEMPERATURE_H
#define MOTOR_TEMPERATURE_H
#include <Arduino.h>
#include "Addon.h"
#include "config.h"
#include <Streaming.h>
#include "../common/macros.h"
#include "TemperatureSensor.h"
class MotorTemperature : public Addon
{
private:
TemperatureSensor sensor;
public:
MotorTemperature() : sensor(MOTOR_TEMPERTURE_SCK_PIN, MOTOR_TEMPERTURE_CS_PIN, MOTOR_TEMPERTURE_SO_PIN, MOTOR_TEMPERTURE_MAX, MOTOR_TEMPERTURE_INTERVAL),
Addon(MOTOR_TEMPERATURE_STR, MOTOR_TEMPERATURE) {}
virtual short ok()
{
return sensor.ok();
}
void debug(Stream *stream)
{
// *stream << this->name << ":" << this->ok();
}
void info(Stream *stream)
{
/*
*stream << this->name << "\n\t : " <<
SPACE("Pin SCK:" << MOTOR_TEMPERTURE_SCK_PIN ) <<
SPACE("Pin CS :" << MOTOR_TEMPERTURE_CS_PIN ) <<
SPACE("Pin SO:" << MOTOR_TEMPERTURE_SO_PIN ) <<
SPACE("Max" << MOTOR_TEMPERTURE_MAX ) <<
SPACE("Interval" << MOTOR_TEMPERTURE_INTERVAL );
*/
}
};
#endif

View File

@ -0,0 +1,148 @@
#ifndef OPERATION_MODE_SWITCH_H
#define OPERATION_MODE_SWITCH_H
#ifdef HAS_STATES
#include <ArduinoJson.h>
#endif
#ifndef OP_MODE_ANALOG
#include <Bounce2.h>
#endif
#include "../config.h"
#include "../Addon.h"
#include <Streaming.h>
#include "../common/macros.h"
#include "../common/ppmath.h"
class OperationModeSwitch : public Addon
{
public:
short pin1;
#ifdef OP_MODE_ANALOG
ushort level1;
ushort level2;
ushort level3;
OperationModeSwitch(short _pin1, ushort _level1, ushort _level2, ushort _level3) : pin1(_pin1),
level1(_level1),
level2(_level2),
level3(_level3),
Addon(OPERATION_MODE_SWITCH_STR, OPERATION_MODE_SWITCH)
{
//setFlag(DEBUG);
}
#ifdef HAS_STATES
String state()
{
const int capacity = JSON_OBJECT_SIZE(2);
StaticJsonDocument<capacity> doc;
doc['0'] = id;
doc['1'] = value();
return doc.as<String>();
}
#endif
void debug(Stream *stream)
{
//*stream << this->name << SPACE(value());
}
void info(Stream *stream)
{
//*stream << this->name << "\n\t ";
}
short value()
{
ushort value = analogRead(pin1);
if (RANGE(value, level1 - 10, level1 + 10))
{
return OP_DEBUG;
}
if (RANGE(value, level2 - 10, level2 + 10))
{
return OP_NORMAL;
}
if (RANGE(value, level3 - 10, level3 + 10))
{
return OP_SERVICE;
}
return OP_NONE;
}
short setup()
{
}
short loop()
{
// Serial.println(analogRead(pin1));
}
#else
Bounce debouncer1;
Bounce debouncer2;
Bounce debouncer3;
short pin1;
short pin2;
short pin3;
OperationModeSwitch(short _pin1, short _pin2, short _pin3) : pin1(_pin1), // 1-2
pin2(_pin2), // 5-6
pin3(_pin3), // 9-10
Addon(OPERATION_MODE_SWITCH_STR, OPERATION_MODE_SWITCH)
{
}
void debug(Stream *stream)
{
*stream << this->name << ": PIN1 " << SPACE(!debouncer1.read()) << ": PIN2 " << SPACE(!debouncer2.read()) << ": PIN3 " << SPACE(!debouncer3.read());
}
void info(Stream *stream)
{
*stream << this->name << "\n\t : ";
}
short value()
{
if (!debouncer1.read())
{
return OP_DEBUG;
}
if (!debouncer2.read())
{
return OP_NORMAL;
}
if (!debouncer3.read())
{
return OP_SERVICE;
}
return OP_NONE;
}
short setup()
{
this->debouncer1 = Bounce();
this->debouncer1.attach(this->pin1, INPUT_PULLUP);
this->debouncer1.interval(25);
this->debouncer2 = Bounce();
this->debouncer2.attach(this->pin2, INPUT_PULLUP);
this->debouncer2.interval(25);
this->debouncer3 = Bounce();
this->debouncer3.attach(this->pin3, INPUT_PULLUP);
this->debouncer3.interval(25);
}
short loop()
{
this->debouncer1.update();
this->debouncer2.update();
this->debouncer3.update();
}
#endif
};
#endif

View File

@ -0,0 +1,140 @@
#ifndef POWER_H
#define POWER_H
#include "../config.h"
#ifdef HAS_STATES
#include <ArduinoJson.h>
#endif
#include "../Addon.h"
#include <Streaming.h>
#include "../common/macros.h"
#include "../config.h"
#include "../components/CurrentSensor.h"
class Power : public Addon
{
public:
Power(int _power0, int _power1) : power0(_power0),
power1(_power1),
primary(false),
secondary(false),
slots({false, false}),
#ifdef POWER_CSENSOR_PRIMARY
cSensorPrim(CurrentSensor(POWER_CSENSOR_PRIMARY, 200)),
#endif
#ifdef POWER_CSENSOR_SECONDARY
cSensorSec(CurrentSensor(POWER_CSENSOR_SECONDARY, 200)),
#endif
Addon(POWER_STR, POWER)
{
// setFlag(DEBUG);
}
#ifdef HAS_STATES
String state()
{
const int capacity = JSON_OBJECT_SIZE(4);
StaticJsonDocument<capacity> doc;
doc['0'] = id;
doc['1'] = slots[0];
doc['2'] = slots[1];
return doc.as<String>();
}
#endif
void debug(Stream *stream)
{
*stream << this->name << ":" << cSensorSec.value;
}
void info(Stream *stream)
{
//*stream << this->name;
}
short setup()
{
#ifdef POWER_0
pinMode(power0, OUTPUT);
#endif
#ifdef POWER_1
pinMode(power1, OUTPUT);
#endif
#ifdef POWER_CSENSOR_PRIMARY
cSensorPrim.setup();
#endif
#ifdef POWER_CSENSOR_SECONDARY
cSensorSec.setup();
#endif
}
short on(short slot)
{
#ifdef USE_CONTROLLINO
digitalWrite(slot == POWER_PRIMARY ? power0 : power1, POWER_NC ? HIGH : LOW);
#else
analogWrite(slot == POWER_PRIMARY ? power0 : power1, POWER_NC ? 1024 : 0);
#endif
slots[slot] = true;
return slots[slot];
}
short isOn(short slot)
{
return slots[slot];
}
short off(short slot)
{
#ifdef USE_CONTROLLINO
digitalWrite(slot == POWER_PRIMARY ? power0 : power1, POWER_NC ? 1024 : 0);
#else
analogWrite(slot == POWER_PRIMARY ? power0 : power1, POWER_NC ? 0 : 1024);
#endif
slots[slot] = false;
return slots[slot];
}
short check(short slot)
{
switch (slot)
{
case POWER_PRIMARY:
{
#ifdef POWER_CSENSOR_PRIMARY
//return slot[POWER_PRIMARY] && cSenorPrim.ok();
#else
// return slots[POWER_PRIMARY];
#endif
break;
}
}
}
short loop()
{
#ifdef POWER_CSENSOR_PRIMARY
cSensorPrim.loop();
#endif
#ifdef POWER_CSENSOR_SECONDARY
cSensorSec.loop(now);
#endif
}
int power0;
int power1;
bool primary;
bool secondary;
int slots[2];
#ifdef POWER_CSENSOR_SECONDARY
CurrentSensor cSensorSec;
#endif
#ifdef POWER_CSENSOR_PRIMARY
CurrentSensor cSensorPrim;
#endif
protected:
};
#endif

View File

@ -0,0 +1,30 @@
#ifndef RESET_H
#define RESET_H
// This module uses currently a normally closed momentary button.
static millis_t sw_reset_TS = 0;
static void reset_setup()
{
pinMode(RESET_PIN, INPUT_PULLUP);
sw_reset_TS = millis();
}
static void reset_loop()
{
if (millis() - sw_reset_TS > RESET_INTERVAL) {
#if RESET_NC == true
// globals.isReset = digitalRead(RESET_PIN);
#else
// globals.isReset = !digitalRead(RESET_PIN);
#endif
sw_reset_TS = millis();
// if(globals.isReset && DEBUG){
// Serial.println("reset");
// }
}
}
#endif

View File

@ -0,0 +1,64 @@
#ifndef STATUS_H
#define STATUS_H
static millis_t status_blink_TS = 0;
static bool doBlink = false;
static bool last_blink = true;
static millis_t blink_start_ts;
static millis_t max_blink_time = HOUR_MS; // stop blinking in an hour
// This is using currently 2 LEDs : red & green, running at 220V via relay.
static void status_setup() { }
static void status_loop(){
if (millis() - status_blink_TS > 1000 ) {
status_blink_TS = millis();
last_blink = !last_blink;
if(doBlink){
//analogWrite(STATUS_ERROR_PIN, last_blink ? RELAY_ON : RELAY_OFF);
}
if(millis() - status_blink_TS > max_blink_time ){
doBlink = false;
}
}
}
static void status_blink(bool blink){
if(!doBlink && blink){
blink_start_ts = millis();
}
doBlink = blink;
}
static void setStatusAllOn(){
if(doBlink){
return;
}
digitalWrite(STATUS_POWER_PIN, HIGH);
}
static void setStatusAllOff(){
if(doBlink){
return;
}
digitalWrite(STATUS_POWER_PIN, LOW);
}
static void setStatus(bool error) {
/*
if(doBlink){
return;
}
if (error) {
analogWrite(STATUS_ERROR_PIN, RELAY_ON);
analogWrite(STATUS_OK_PIN, RELAY_OFF);
} else {
analogWrite(STATUS_OK_PIN, RELAY_ON);
analogWrite(STATUS_ERROR_PIN, RELAY_OFF);
}
*/
}
#endif

View File

@ -0,0 +1,42 @@
#ifndef TEMPERATURE_SENSOR_H
#define TEMPERATURE_SENSOR_H
#include <max6675.h>
#include "../config.h"
#include "../macros.h"
#include "../time.h"
class TemperatureSensor
{
public:
TemperatureSensor(short sck, short cs, short so, short _max, short _interval) : ktc(MAX6675(sck, cs, so)),
temperature(),
temperature_TS(millis()),
maxTemp(_max),
interval(_interval) {}
bool ok()
{
return temperature < maxTemp;
}
void loop()
{
if (millis() - temperature_TS > interval)
{
temperature_TS = millis();
temperature = ktc.readCelsius();
}
}
private:
MAX6675 ktc;
short temperature;
short maxTemp;
short interval;
millis_t temperature_TS;
};
#endif

View File

@ -0,0 +1,307 @@
#include <Vector.h>
#include <Streaming.h>
#include <Arduino.h>
#include "app.h"
#include "features.h"
#include <MemoryFree.h>
static Addon *addonsArray[10];
short App::ok()
{
return E_OK;
}
App::App() : Addon("APP", APP, 1 << STATE),
#ifdef HAS_DIRECTION_SWITCH
dirSwitch(new DirectionSwitch()),
#endif
#ifdef ENCLOSURE_SENSOR
enclosureSensor(new EnclosureSensor()),
#endif
#ifdef HAS_VFD
vfd(new VFD()),
#endif
#ifdef MOTOR_HAS_TEMPERTURE
mHeat(new MotorTemperature()),
#endif
#ifdef HAS_MOTOR_IR_SENSOR
mSpeed(new MotorSpeed()),
#endif
#ifdef MOTOR_LOAD_PIN
mLoad(new MotorLoad(MOTOR_LOAD_PIN)),
#endif
#ifdef HAS_SERIAL
serialBridge(new PPSerial(Serial)),
#endif
#ifdef HAS_OP_MODE_SWITCH
#ifdef OP_MODE_ANALOG
opModeSwitch(new OperationModeSwitch(OP_MODE_1_PIN, 120, 60, 30)),
#else
opModeSwitch(new OperationModeSwitch(OP_MODE_1_PIN, OP_MODE_2_PIN, OP_MODE_3_PIN)),
#endif
#endif
#ifdef HAS_MODBUS_BRIDGE
modbusBridge(new ModbusBridge()),
#endif
#ifdef HAS_OMRON_VFD_MODBUS
omronVFD(new OmronVFD(modbusBridge, OMRON_MX2_SLAVE_ID)),
#endif
#ifdef OMRON_PID_SLAVE_START
pids(new OmronPID(modbusBridge, OMRON_PID_SLAVE_START)),
#endif
shredState(0)
{
//#if defined(MODBUS_BRIDGE) && defined(HAS_VFD)
// vfd->modbus = modbusBridge;
//#endif
/// modbusBridge->debug(&Serial);
}
#ifdef HAS_STATES
String App::state()
{
const int capacity = JSON_OBJECT_SIZE(6);
StaticJsonDocument<capacity> doc;
doc["0"] = id;
doc["1"] = _state;
doc["2"] = shredState;
doc["3"] = overloaded;
doc["4"] = _error;
doc["5"] = freeMemory();
return doc.as<String>();
}
#endif
short App::getAppState(short val)
{
return _state;
}
void (*resetFunction)(void) = 0; // Self reset (to be used with watchdog)
short App::setAppState(short newState)
{
}
void printMem()
{
Serial.print("mem: ");
Serial.print(freeMemory());
Serial.println('--');
}
short App::setup()
{
Serial.begin(DEBUG_BAUD_RATE);
Serial.println("Booting Firmware ...................... ");
addons.setStorage(addonsArray);
setup_addons();
printMem();
digitalWrite(STATUS_POWER_PIN, HIGH);
/*
powerSwitch->on(0);
powerSwitch->on(1);
delay(4000);
dFC.initFC();
*/
#ifdef MEARSURE_PERFORMANCE
printPerfTS = 0;
addonLoopTime = 0;
bridgeLoopTime = 0;
#endif
debugTS = 0;
comTS = 0;
loopTS = 0;
shredState = 0;
overloaded = 0;
_state = 0;
/*
timer.every(5000, [](App *app) -> void {
printMem();
},
this);
*/
}
void App::loop_service()
{
#ifdef HAS_POWER
powerSwitch->on(POWER_PRIMARY);
#endif
// _loop_motor_manual();
}
void App::_loop_motor_manual()
{
#if defined(HAS_DIRECTION_SWITCH) && defined(HAS_VFD)
uchar sw = this->dirSwitch->loop();
if (sw == 2)
{
this->vfd->fwd(true);
}
else if (sw == 1)
{
this->vfd->rev(true);
}
else
{
this->vfd->stop();
}
#endif
}
void App::loop_normal()
{
}
void App::debug_mode_loop()
{
uchar s = addons.size();
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->hasFlag(LOOP))
{
addon->loop();
}
}
}
short App::loop()
{
loop_addons();
loop_com();
timer.tick();
now = millis();
short error = ok();
if (error)
{
_error = error;
return;
}
#ifdef HAS_OP_MODE_SWITCH
short op = opModeSwitch->value();
switch (op)
{
case OP_DEBUG:
{
#ifdef HAS_POWER
powerSwitch->on(POWER_PRIMARY);
powerSwitch->on(POWER_SECONDARY);
#endif
break;
}
case OP_NORMAL:
{
#ifdef HAS_POWER
// powerSwitch->on(POWER_PRIMARY);
// powerSwitch->on(POWER_SECONDARY);
#endif
loop_normal();
debug();
break;
}
case OP_NONE:
{
#ifdef HAS_POWER
// powerSwitch->off(POWER_PRIMARY);
#endif
// vfd->stop();
// plunger->stop();
// loopShred();
break;
}
case OP_SERVICE:
{
// loop_normal();
// powerSwitch->on(POWER_PRIMARY);
// powerSwitch->on(POWER_SECONDARY);
// vfd->rev(true);
break;
}
}
#endif
}
void App::loop_com()
{
if (millis() - comTS > 300)
{
#if defined(HAS_BRIDGE) && defined(HAS_SERIAL)
PPSerial::Message *msg = serialBridge->read();
if (msg)
{
switch (msg->verb)
{
case Bridge::EC_METHOD:
{
char *strings[3];
char *ptr = NULL;
byte index = 0;
ptr = strtok(msg->payload, ":");
while (ptr != NULL && index < 4)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, ":");
}
int id = atoi(strings[0]);
char *_method = strings[1];
SKeyVal *method = VSL::instance()->hasMethod(id, _method);
if (method)
{
int arg = atoi(strings[2]);
Addon *addon = (Addon *)method->instance;
AddonFnPtr ptr = method->mPtr;
short ret = (addon->*ptr)(arg);
if (TEST(msg->flags, Bridge::STATE))
{
#ifdef HAS_STATES
this->appState(0);
#endif
}
else if (TEST(msg->flags, Bridge::RECEIPT))
{
#ifdef BRIDGE_HAS_RESPONSE
const char *response = Bridge::CreateResponse(msg->id, 0, ret);
Serial.write(response);
#endif
}
if (TEST(msg->flags, Bridge::DEBUG))
{
// Serial.println("Called command");
}
}
else
{
VSL::instance()->debug();
if (TEST(msg->flags, Bridge::DEBUG))
{
/*
Serial.print("Incoming message, cant find class & method ");
Serial.print(_class);
Serial.print(":");
Serial.print(_method);
Serial.print("\n");
*/
}
}
break;
}
}
msg->payload = NULL;
}
#endif
comTS = millis();
}
}

View File

@ -0,0 +1,126 @@
#ifndef APP_H
#define APP_H
#include "config.h"
#include <Vector.h>
#include "types.h"
#include "Addon.h"
#include "common/timer.h"
class DirectionSwitch;
class EnclosureSensor;
class VFD;
class MotorIdle;
class MotorTemperature;
class MotorSpeed;
class OperationModeSwitch;
class Power;
class MotorLoad;
class RMotorControl;
class PPSerial;
class ModbusBridge;
class OmronPID;
class OmronVFD;
class App : public Addon
{
public:
App();
DirectionSwitch *dirSwitch;
EnclosureSensor *enclosureSensor;
VFD *vfd;
MotorIdle *mIdle;
MotorTemperature *mHeat;
MotorSpeed *mSpeed;
Power *powerSwitch;
OperationModeSwitch *opModeSwitch;
MotorLoad *mLoad;
PPSerial *serialBridge;
ModbusBridge *modbusBridge;
OmronPID *pids;
OmronVFD *omronVFD;
Addon *byId(short id);
short setup();
short loop();
short debug();
short info();
short ok();
void loop_service();
void loop_normal();
ushort loop_auto_reverse();
void loop_com();
void _loop_motor_manual();
void loop_addons();
void setup_addons();
ushort numByFlag(ushort flag);
void App::debug_mode_loop();
short extrude(short value = 0);
ushort loopExtrude();
Vector<Addon *> addons;
// bridge
short setFlag(ushort addonId, ushort flag);
#ifdef HAS_STATES
short appState(short nop = 0);
String state();
#endif
millis_t comTS;
millis_t loopTS;
millis_t wait;
millis_t waitTS;
Timer<10, millis> timer; // 10 concurrent tasks, using micros as resolution
short plungerCB(short val);
short setOverload(short val);
short overloaded;
enum SHRED_STATE
{
};
short shredState;
short shredStateLast;
short shredCancelState;
short jamCounter;
short setShredState(short newState);
enum APP_STATE
{
RESET = 0,
EXTRUDING = 1,
STANDBY = 2,
ERROR = 5
};
short _state;
short _error;
short getLastError(short val = 0)
{
return _error;
}
short setLastError(short val = 0);
short setAppState(short newState);
short getAppState(short val);
private:
#ifdef MEARSURE_PERFORMANCE
millis_t addonLoopTime;
millis_t bridgeLoopTime;
millis_t printPerfTS;
#endif
millis_t debugTS;
};
#endif

View File

@ -0,0 +1,238 @@
#include <Vector.h>
#include <Streaming.h>
#include <Arduino.h>
#include "app.h"
#include "config.h"
#include "types.h"
#include "common/macros.h"
#include "Addon.h"
#include "features.h"
short App::setFlag(ushort addonId, ushort flag)
{
Addon *addon = byId(addonId);
if (addon)
{
addon->setFlag(flag);
return E_OK;
}
return ERROR_WARNING;
}
ushort App::numByFlag(ushort flag)
{
uchar s = addons.size();
uchar l = 0;
String out = "";
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (!!(addon->hasFlag(flag)))
{
l++;
}
}
return l;
}
#ifdef HAS_STATES
short App::appState(short nop)
{
uchar s = addons.size();
uchar si = 0;
String out = "";
uchar l = numByFlag(STATE);
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (!!(addon->hasFlag(STATE)))
{
si++;
out += addon->state();
if (si < l)
{
out += ",";
}
}
}
const char *response = Bridge::CreateResponse(STATE_RESPONSE_CODE, 0, out.c_str());
Serial.write(response);
}
#endif
short App::debug()
{
#ifndef MEARSURE_PERFORMANCE
if (millis() - debugTS > DEBUG_INTERVAL)
{
uchar s = addons.size();
uchar nb = 0;
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->hasFlag(DEBUG))
{
if ((addon->debug)(&Serial))
{
Serial.println("\n");
nb++;
}
}
}
if (nb)
{
Serial.println("\n");
}
debugTS = millis();
}
#endif
}
short App::info()
{
uchar s = addons.size();
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->hasFlag(INFO))
{
addon->info(&Serial);
Serial << "\n";
}
}
}
Addon *App::byId(short id)
{
uchar s = addons.size();
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->id == id)
{
return addon;
}
}
return NULL;
}
void App::setup_addons()
{
#ifdef HAS_POWER
addons.push_back((Addon *)powerSwitch);
#endif
#ifdef HAS_DIRECTION_SWITCH
addons.push_back((Addon *)dirSwitch);
#endif
#ifdef ENCLOSURE_SENSOR
addons.push_back((Addon *)enclosureSensor);
#endif
#ifdef MOTOR_OVERLOAD_PIN
addons.push_back((Addon *)mOverload);
#endif
#ifdef MOTOR_IDLE_PIN
addons.push_back((Addon *)mIdle);
#endif
#ifdef HAS_OP_MODE_SWITCH
addons.push_back((Addon *)opModeSwitch);
#endif
#ifdef HAS_SERIAL
addons.push_back((Addon *)serialBridge);
#endif
#ifdef MOTOR_LOAD_PIN
addons.push_back((Addon *)mLoad);
#endif
#if ENABLED(MOTOR_HAS_TEMPERTURE)
addons.push_back((Addon *)mHeat);
#endif
#if ENABLED(HAS_MOTOR_IR_SENSOR)
addons.push_back((Addon *)mSpeed);
#endif
#ifdef HAS_VFD
addons.push_back((Addon *)vfd);
#endif
#ifdef HAS_MODBUS_BRIDGE
addons.push_back((Addon *)modbusBridge);
#endif
#ifdef OMRON_PID_SLAVE_START
addons.push_back((Addon *)pids);
#endif
#ifdef HAS_OMRON_VFD_MODBUS
addons.push_back((Addon *)omronVFD);
omronVFD->owner = this;
#endif
addons.push_back((Addon *)this);
uchar s = addons.size();
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->hasFlag(SETUP))
{
addon->setup();
}
}
#ifdef HAS_BRIDGE
REGISTER_CLASS_MEMBER_FN(POWER, powerSwitch, "on", (AddonFnPtr)&Power::on, short);
REGISTER_CLASS_MEMBER_FN(POWER, powerSwitch, "off", (AddonFnPtr)&Power::off, short);
REGISTER_CLASS_MEMBER_FN(VFD_CONTROL, vfd, "fwd", (AddonFnPtr)&VFD::fwd, short);
REGISTER_CLASS_MEMBER_FN(VFD_CONTROL, vfd, "rev", (AddonFnPtr)&VFD::rev, short);
REGISTER_CLASS_MEMBER_FN(VFD_CONTROL, vfd, "stop", (AddonFnPtr)&VFD::stop, short);
// REGISTER_CLASS_MEMBER_FN(APP, this, "shred", (AddonFnPtr)&App::shred, short);
REGISTER_CLASS_MEMBER_FN(APP, this, "setOverload", (AddonFnPtr)&App::setOverload, short);
REGISTER_CLASS_MEMBER_FN(APP, this, "setAppState", (AddonFnPtr)&App::setAppState, short);
REGISTER_CLASS_MEMBER_FN(APP, this, "getAppState", (AddonFnPtr)&App::getAppState, short);
#ifdef HAS_MODBUS_BRIDGE
REGISTER_CLASS_MEMBER_FN(ModbusBridge, modbusBridge, "setFn", (AddonFnPtr)&ModbusBridge::setFn, short);
REGISTER_CLASS_MEMBER_FN(ModbusBridge, modbusBridge, "setAddr", (AddonFnPtr)&ModbusBridge::setAddr, short);
REGISTER_CLASS_MEMBER_FN(ModbusBridge, modbusBridge, "setNb", (AddonFnPtr)&ModbusBridge::setNb, short);
#endif
#ifdef HAS_STATES
REGISTER_CLASS_MEMBER_FN(APP, this, "appState", (AddonFnPtr)&App::appState, short);
#endif
#endif
}
void App::loop_addons()
{
#ifdef MEARSURE_PERFORMANCE
millis_t now = millis();
#endif
uchar s = addons.size();
for (uchar i = 0; i < s; i++)
{
Addon *addon = addons[i];
if (addon->hasFlag(LOOP))
{
addon->now = millis();
addon->loop();
}
}
#ifdef MEARSURE_PERFORMANCE
addonLoopTime = millis() - now;
if (millis() - printPerfTS > 3000)
{
printPerfTS = now;
Serial << SPACE("Addon loop time") << addonLoopTime << "\n";
}
#endif
debug();
}

View File

@ -0,0 +1,19 @@
#include <Vector.h>
#include <Streaming.h>
#include <Arduino.h>
#include "app.h"
#include "features.h"
#ifdef HAS_EXTRUDE_DEBUG
#define EXTRUDE_DEBUG(A) Serial.println(A);
#else
#define EXTRUDE_DEBUG(A)
#endif
short App::extrude(short value)
{
}
ushort App::loopExtrude()
{
}

View File

@ -0,0 +1,121 @@
#include "bridge.h"
#include <Vector.h>
#include <Streaming.h>
#include "constants.h"
typedef struct
{
short key;
char *value;
} TAddons;
const TAddons addonsDict[]{};
static VSL *_instance;
class SKeyVal;
SKeyVal *clazzMaps[20];
Vector<SKeyVal *> clazzes;
class SKeyValS
{
public:
void *instance;
ushort id;
SKeyValS() {}
SKeyValS(void *_instance, ushort _id) : instance(_instance),
id(_id) {}
};
char *getAddonName(short key)
{
for (uchar i = 0; i < sizeof(addonsDict) / sizeof(TAddons); ++i)
{
if (addonsDict[i].key == key)
{
return addonsDict[i].value;
}
}
return NULL;
}
short getAddonKey(String name)
{
for (uchar i = 0; i < sizeof(addonsDict) / sizeof(TAddons); ++i)
{
if (name.equals(String(addonsDict[i].value)))
{
return addonsDict[i].value;
}
}
return -1;
}
void VSL::init()
{
_instance = new VSL();
clazzes.setStorage(clazzMaps);
}
VSL *VSL::instance()
{
if (!_instance)
{
VSL::init();
}
return _instance;
}
SKeyVal *VSL::hasMethod(ushort id, String methodName)
{
uchar s = clazzes.size();
for (uchar i = 0; i < s; i++)
{
SKeyVal *val = clazzes.at(i);
if (val->key == id && val->methodName.equals(methodName))
{
return val;
}
}
return NULL;
}
void VSL::debug()
{
#ifdef BRIDGE_DEBUG
uchar s = clazzes.size();
for (uchar i = 0; i < s; i++)
{
SKeyVal *val = clazzes.at(i);
Serial.print(val->className);
Serial.print(":");
Serial.print(val->methodName);
Serial.print("\n");
}
#endif
}
SKeyVal *VSL::registerMemberFunction(ushort id, Addon *clazz, char *method, AddonFnPtr ptr, char *ret)
{
SKeyVal *meth = hasMethod(id, method);
if (meth)
{
#ifdef BRIDGE_DEBUG
Serial << "Register class member: "
<< SPACE(name << "::" << method)
<< "already registered! \n";
#endif
}
else
{
#ifdef BRIDGE_DEBUG
if (!getAddonKey(name))
{
Serial.println("invalid addon key");
}
#endif
meth = new SKeyVal(id, clazz, method, ptr);
//Serial << "Register member method:"
// << SPACE(meth->className << "::" << meth->methodName)
// << "\n";
clazzes.push_back(meth);
}
}

View File

@ -0,0 +1,81 @@
#ifndef BRDIGE_H
#define BRIDGE_H
#include "Addon.h"
#include <WString.h>
class App;
class SKeyVal;
class SKeyValS;
class SKeyVal
{
public:
short key;
void *instance;
String methodName;
AddonFnPtr mPtr;
SKeyVal() {}
SKeyVal(ushort _key, void *_instance, String _methodName, AddonFnPtr _mPtr) : key(_key),
instance(_instance),
methodName(_methodName),
mPtr(_mPtr) {}
};
class VSL
{
public:
SKeyVal *registerMemberFunction(
ushort id,
Addon *clazz,
char *method,
AddonFnPtr ptr,
char *ret);
static void init();
static VSL *instance();
SKeyVal *VSL::hasMethod(ushort id, String method);
void debug();
};
#define REGISTER_CLASS_MEMBER_FN(id, inst, methodName, method, ret) \
{ \
VSL::instance()->registerMemberFunction(id, inst, methodName, method, "2"); \
}
#endif
namespace Bridge
{
static const char *START_STR = "<<";
static const char *END_STR = ">>";
static const char RESPONSE_DEL = ';';
static const char *CreateResponse(short id, short error, short ret)
{
static char response[1024] = {'\0'};
snprintf(response, sizeof(response), "%s%d%c%d%c%d%s\r", START_STR, id, RESPONSE_DEL, error, RESPONSE_DEL, ret, END_STR);
return response;
}
static const char *CreateResponse(short id, short error, const char *ret)
{
static char response[1024] = {'\0'};
snprintf(response, sizeof(response), "%s%d%c%d%c%s%s\r", START_STR, id, RESPONSE_DEL, error, RESPONSE_DEL, ret, END_STR);
return response;
}
enum ECALLS
{
EC_COMMAND = 1,
EC_METHOD = 2,
EC_FUNC = 3,
EC_USER = 10
};
enum MessageFlags
{
NEW = 1,
PROCESSING = 2,
PROCESSED = 3,
DEBUG = 4,
RECEIPT = 5,
STATE = 6
};
} // namespace Bridge

View File

@ -0,0 +1,98 @@
#ifndef MACROS_H
#define MACROS_H
#include "../types.h"
// Macros for adding
#define INC_0 1
#define INC_1 2
#define INC_2 3
#define INC_3 4
#define INC_4 5
#define INC_5 6
#define INC_6 7
#define INC_7 8
#define INC_8 9
#define INCREMENT_(n) INC_ ##n
#define INCREMENT(n) INCREMENT_(n)
// Macros for subtracting
#define DEC_1 0
#define DEC_2 1
#define DEC_3 2
#define DEC_4 3
#define DEC_5 4
#define DEC_6 5
#define DEC_7 6
#define DEC_8 7
#define DEC_9 8
#define DECREMENT_(n) DEC_ ##n
#define DECREMENT(n) DECREMENT_(n)
// compiler - & C quirks
#define FORCE_INLINE __attribute__((always_inline)) inline
#define _UNUSED __attribute__((unused))
// fallback noop
#define NOOP do{} while(0)
//Option testing
#define _CAT(a, ...) a ## __VA_ARGS__
#define SWITCH_ENABLED_ 1
#define ENABLED(b) _CAT(SWITCH_ENABLED_, b)
// time
#define PENDING(NOW,SOON) ((long)(NOW-(SOON))<0)
#define ELAPSED(NOW,SOON) (!PENDING(NOW,SOON))
#define MMM_TO_MMS(MM_M) ((MM_M)/60.0f)
#define MMS_TO_MMM(MM_S) ((MM_S)*60.0f)
#define HOUR_MS ((millis_t)1000 * (millis_t)(60 * 60))
#define MIN_MS ((millis_t)1000 * (millis_t)(60))
#define SECS ((millis_t)1000)
// bit masks
#undef _BV
#define _BV(b) (1 << (b))
#define TEST(n,b) !!((n)&_BV(b))
#define SBI(n,b) (n |= _BV(b))
#define CBI(n,b) (n &= ~_BV(b))
#define SET_BIT_TO(N,B,TF) do{ if (TF) SBI(N,B); else CBI(N,B); }while(0)
#define _BV32(b) (1UL << (b))
#define TEST32(n,b) !!((n)&_BV32(b))
#define SBI32(n,b) (n |= _BV32(b))
#define CBI32(n,b) (n &= ~_BV32(b))
#define SIGN(a) ((a>0)-(a<0))
// math basics
#define WITHIN(V,L,H) ((V) >= (L) && (V) <= (H))
#define NUMERIC(a) WITHIN(a, '0', '9')
#define DECIMAL(a) (NUMERIC(a) || a == '.')
#define NUMERIC_SIGNED(a) (NUMERIC(a) || (a) == '-' || (a) == '+')
#define DECIMAL_SIGNED(a) (DECIMAL(a) || (a) == '-' || (a) == '+')
#define COUNT(a) (sizeof(a)/sizeof(*a))
#define ZERO(a) memset(a,0,sizeof(a))
#define COPY(a,b) memcpy(a,b,MIN(sizeof(a),sizeof(b)))
// #define M_PI 3.14159265358979323846f
#define RADIANS(d) ((d)*M_PI/180.0f)
#define DEGREES(r) ((r)*180.0f/M_PI)
#define CEILING(x,y) (((x) + (y) - 1) / (y))
// Macros for initializing arrays
#define ARRAY_6(v1, v2, v3, v4, v5, v6, ...) { v1, v2, v3, v4, v5, v6 }
#define ARRAY_5(v1, v2, v3, v4, v5, ...) { v1, v2, v3, v4, v5 }
#define ARRAY_4(v1, v2, v3, v4, ...) { v1, v2, v3, v4 }
#define ARRAY_3(v1, v2, v3, ...) { v1, v2, v3 }
#define ARRAY_2(v1, v2, ...) { v1, v2 }
#define ARRAY_1(v1, ...) { v1 }
#define _ARRAY_N(N, ...) ARRAY_ ##N(__VA_ARGS__)
#define ARRAY_N(N, ...) _ARRAY_N(N, __VA_ARGS__)
#define SPACE(A) " " << A << " "
#endif

View File

@ -0,0 +1,14 @@
#ifndef PPMATH_H
#define PPMATH_H
template <typename T>
T clamp(const T &value, const T &low, const T &high)
{
return value < low ? low : (value > high ? high : value);
}
#define RANGE(i, min, max) ((i > min) && (i < max)) ? true : false
#define NCLAMP(x, min, max) (x - min) / (max - min)
#endif

View File

@ -0,0 +1,17 @@
#include "ppmath_motor.h"
int vfd_calc_vsi(int rpm)
{
return ((rpm * VFD_VSI_MAX_V_SPEED) / MOTOR_FREQ_CMAX);
}
int vfd_calc_vsi_grinder(int rpm){
return VFD_VSI_SCALE *
vfd_calc_vsi(
clamp<int>(rpm * RPM_GRINDER_SHREDDER_SCALE, RPM_GRINDING_MIN, RPM_GRINDING_MAX)
);
}
int vfd_calc_vsi_shredder(int rpm){
return VFD_VSI_SCALE *
vfd_calc_vsi(
clamp<int>(rpm, RPM_SHREDDERING_MIN, RPM_SHREDDERING_MAX)
);
}

View File

@ -0,0 +1,18 @@
#ifndef PPMATH_MOTOR_H
#define PPMATH_MOTOR_H
#include "ppmath.h"
#include "constants.h"
// Base calculation for the corresponding V per RPM,
// taking the VFD VSI Voltage level for the max. operating frequency
// into account. The max. operating frequency is set in the VFD !
int vfd_calc_vsi(int rpm);
// safe VSI version for grinder
int vfd_calc_vsi_grinder(int rpm);
// safe VSI version for shredder
int vfd_calc_vsi_shredder(int rpm);
#endif

View File

@ -0,0 +1,136 @@
#ifndef TIMER_H
#define TIMER_H
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include "macros.h"
#ifndef TIMER_MAX_TASKS
#define TIMER_MAX_TASKS 0x10
#endif
template <
size_t max_tasks = TIMER_MAX_TASKS, /* max allocated tasks */
unsigned long (*time_func)() = millis /* time function for timer */
>
class Timer
{
public:
typedef bool (*handler_t)(void *opaque); /* task handler func signature */
/* Calls handler with opaque as argument in delay units of time */
bool
in(unsigned long delay, handler_t h, void *opaque = NULL)
{
return add_task(time_func(), delay, h, opaque);
}
/* Calls handler with opaque as argument at time */
bool
at(unsigned long time, handler_t h, void *opaque = NULL)
{
const unsigned long now = time_func();
return add_task(now, time - now, h, opaque);
}
/* Calls handler with opaque as argument every interval units of time */
bool
every(unsigned long interval, handler_t h, void *opaque = NULL)
{
return add_task(time_func(), interval, h, opaque, interval);
}
/* Ticks the timer forward - call this function in loop() */
void
tick()
{
tick(time_func());
}
/* Ticks the timer forward - call this function in loop() */
inline void
tick(unsigned long t)
{
for (size_t i = 0; i < max_tasks; ++i)
{
struct task *const task = &tasks[i];
const unsigned long duration = t - task->start;
if (task->handler && duration >= task->expires)
{
task->repeat = task->handler(task->opaque) && task->repeat;
if (task->repeat)
task->start = t;
else
remove(task);
}else{
}
}
}
private:
struct task
{
handler_t handler; /* task handler callback func */
void *opaque; /* argument given to the callback handler */
unsigned long start,
expires, /* when the task expires */
repeat; /* repeat task */
} tasks[max_tasks];
inline void
remove(struct task *task)
{
task->handler = NULL;
task->opaque = NULL;
task->start = 0;
task->expires = 0;
task->repeat = 0;
}
inline struct task *
next_task_slot()
{
for (size_t i = 0; i < max_tasks; ++i)
{
struct task *const slot = &tasks[i];
if (slot->handler == NULL)
return slot;
}
return NULL;
}
inline struct task *
add_task(unsigned long start, unsigned long expires,
handler_t h, void *opaque, bool repeat = 0)
{
struct task *const slot = next_task_slot();
if (!slot){
return NULL;
}
slot->handler = h;
slot->opaque = opaque;
slot->start = start;
slot->expires = expires;
slot->repeat = repeat;
return slot;
}
};
/* create a timer with the default settings */
inline Timer<>
timer_create_default()
{
return Timer<>();
}
#endif

View File

@ -0,0 +1,81 @@
#ifndef POS3_H
#define POS3_H
#include <Bounce2.h>
#include "../enums.h"
class Pos3
{
public:
Pos3(int _upPin, int _downPin) : upPin(_upPin), downPin(_downPin)
{
}
int setup()
{
this->debouncerUp = Bounce();
this->debouncerUp.attach(this->upPin, INPUT_PULLUP);
this->debouncerUp.interval(25);
this->debouncerDown = Bounce();
this->debouncerDown.attach(this->downPin, INPUT_PULLUP);
this->debouncerDown.interval(25);
return 0;
}
int loop()
{
int newDirection = this->read();
if (newDirection != this->switch_pos)
{
this->last_switch = this->switch_pos;
}
this->switch_pos = newDirection;
return this->switch_pos;
}
int last_switch = -1; // Track last switch position
int switch_pos = -1; // Current switch position
protected:
int upPin;
int downPin;
Bounce debouncerUp;
Bounce debouncerDown;
private:
int read()
{
this->debouncerUp.update();
this->debouncerDown.update();
bool up = this->debouncerUp.read() == 0 ? true : false;
bool down = this->debouncerDown.read() == 0 ? true : false;
int newDirection = 0;
if (up)
{
newDirection = POS3_DIRECTION::UP;
}
if (down)
{
newDirection = POS3_DIRECTION::DOWN;
}
if (!up && !down)
{
newDirection = POS3_DIRECTION::MIDDLE;
}
if (up && down)
{
newDirection = POS3_DIRECTION::INVALID;
}
return newDirection;
}
};
#endif

View File

@ -0,0 +1,39 @@
#ifndef CURRENT_SENSOR_H
#define CURRENT_SENSOR_H
#include "../config.h"
#include "../common/macros.h"
class CurrentSensor
{
public:
CurrentSensor(short _pin, short _interval) : pin(_pin),
interval(_interval),
ts(0) {}
bool ok()
{
}
bool setup()
{
}
void loop(millis_t now)
{
if (now - ts > interval)
{
value = analogRead(pin);
ts = now;
}
}
float value;
private:
short interval;
short pin;
millis_t ts;
};
#endif

View File

@ -0,0 +1,96 @@
#include "IRSensor.h"
#include "config.h"
#include <Streaming.h>
IRSensor::IRSensor()
{
this->highTS = 0;
this->lowTS = 0;
this->dt = 0;
this->now = 0;
this->ir_moving = 0;
}
void IRSensor::debug(Stream &stream)
{
#ifdef IR_SPEED
stream
<< "IR-MOVING : " << ir_moving << "IR-SPEED: " << (int)this->velocity;
#else
stream << "IR-MOVING : " << (int)this->ir_moving;
#endif
}
void IRSensor::count()
{
#ifdef IR_SPEED
if (digitalRead(IR_PIN) && (micros() - this->debounce > IR_INTERVAL) && digitalRead(IR_PIN))
{
// Check again that the encoder sends a good signal and then check that the time is greater than 1000 microseconds and check again that the signal is correct.
this->debounce = micros(); // Store the time to verify that we do not count the rebound in the signal.
pulses++;
}
#endif
}
short IRSensor::setup()
{
#ifdef IR_SPEED
pinMode(IR_PIN, INPUT);
attachInterrupt(0, ir_count, RISING); // Configuration of interrupt 0, where it is connected.
this->pulses = 0;
this->rpm = 0;
this->timeold = 0;
#endif
}
short IRSensor::loop()
{
#ifdef IR_SPEED
if (millis() - this->timeold >= IR_INTERVAL)
{
noInterrupts(); // Don't process interrupts during calculations // We disconnect the interrupt so it doesn't act in this part of the program.
this->rpm = (minute / this->pulsesperturn) / (millis() - timeold) * pulses; // Calculate the revolutions per minute
this->velocity = this->rpm * 3.1416 * this->wheel_diameter * 60 / 1000000; // Speed calculation in [Km / h]
timeold = millis(); // We store the current time.
this->pulses = 0; // Initialize the pulses.
this->interrupts(); // Restart the interrupt processing // Reiniciamos la interrupción
}
#endif
this->ir_value = digitalRead(IR_PIN);
this->now = millis();
if (this->ir_value == HIGH)
{
this->highTS = this->now;
}
else
{
this->lowTS = this->now;
}
if (this->highTS <= this->lowTS)
{
this->dt = this->lowTS - this->highTS;
}
else
{
this->dt = this->highTS - this->lowTS;
}
this->dt = abs(this->dt);
if (this->dt > IR_TIMEOUT)
{
this->ir_moving = 0;
}
else
{
this->ir_moving = 1;
}
}
short IRSensor::ok()
{
return this->ir_moving == 1;
}

View File

@ -0,0 +1,42 @@
#ifndef IRSENSOR_H
#define IRSENSOR_H
#include <Streaming.h>
#include "types.h"
/*/
@link : http://androminarobot-english.blogspot.com/2017/03/encoder-and-arduinotutorial-about-ir.html
*/
class IRSensor
{
public:
IRSensor();
#ifdef IR_SPEED
unsigned int rpm; // RPM
volatile byte pulses; // Pulses per secs
millis_t timeold;
millis_t minute;
unsigned int pulsesperturn; // Number of notches the encoder disc has
const int wheel_diameter; // diameter [mm]
static volatile unsigned long debounce; // poor man's debouncer
#endif
short ir_value;
bool ir_moving;
short ok();
void debug(Stream &stream);
void count();
short setup();
short loop();
protected:
millis_t highTS; // Last HIGH TS
millis_t lowTS; // Last LOW TS
millis_t dt; // Last delta time between HIGH / LOW
millis_t now; // Temp. variable to store tick TS
};
#endif

View File

@ -0,0 +1,360 @@
#ifndef OMRON_E5_H
#define OMRON_E5_H
// Omron EJ5 Modbus Registers & Coils
#define OR_BIT(A) (A >> 1)
#define OR_WORD(A) (A << 4)
#define OR_E5_STATUS_BIT(H, L, B) (B <= 16 ? (L & (1 << 8)) : (OR_WORD(H) & (1 << (OR_BIT(B)))))
#define OR_E5_CMD(CMD, VALUE) (CMD | VALUE)
// Status Bit -1 , see h175_e5_c_communications_manual_en.pdf::3-24
enum OR_E5_STATUS_1
{
// Lower Word
OR_E5_S1_Heater_OverCurrent = 0,
OR_E5_S1_Heater_CurrentHold = 1,
OR_E5_S1_AD_ConverterError = 2,
OR_E5_S1_HS_Alarm = 3,
OR_E5_S1_RSP_InputError = 4,
OR_E5_S1_InputError = 6,
OR_E5_S1_PotentiometerInnputError = 7,
OR_E5_S1_Control_OutputOpenOutput = 8,
OR_E5_S1_Control_OutputCloseOutput = 9,
OR_E5_S1_HBAlarmCT1 = 10,
OR_E5_S1_HBAlarmCT2 = 11,
OR_E5_S1_Alarm1 = 12,
OR_E5_S1_Alarm2 = 13,
OR_E5_S1_Alarm3 = 14,
OR_E5_S1_ProgramEndOutput = 15,
// Upper Word
OR_E5_S1_EventInput1 = 16,
OR_E5_S1_EventInput2 = 17,
OR_E5_S1_EventInput3 = 18,
OR_E5_S1_EventInput4 = 19,
OR_E5_S1_WriteMode = 20,
OR_E5_S1_NonVolatileMemory = 21,
OR_E5_S1_SetupArea = 22,
OR_E5_S1_ATExcecute = 23,
OR_E5_S1_RunStop = 24,
OR_E5_S1_ComWrite = 25,
OR_E5_S1_AutoManualSwitch = 26,
OR_E5_S1_ProgramStart = 27,
OR_E5_S1_HeaterOverCurrentCT2 = 28,
OR_E5_S1_HeaterCurrentHoldCT2 = 29,
OR_E5_S1_HSAlarmCT2 = 31
};
// Status Bit - 2 , see h175_e5_c_communications_manual_en.pdf::3-25
enum OR_E5_STATUS_2
{
// Lower Word
OR_E5_S2_WorkBit1 = 0,
OR_E5_S2_WorkBit2 = 1,
OR_E5_S2_WorkBit3 = 2,
OR_E5_S2_WorkBit4 = 3,
OR_E5_S2_WorkBit5 = 4,
OR_E5_S2_WorkBit6 = 5,
OR_E5_S2_WorkBit7 = 6,
OR_E5_S2_WorkBit8 = 7,
// Upper Word
OR_E5_S2_EventInput5 = 16,
OR_E5_S2_EventInput6 = 17,
OR_E5_S2_Inverse = 20,
OR_E5_S2_SPRamp = 21,
OR_E5_S2_SPMode = 27,
OR_E5_S2_Alarm4 = 28
};
// Variable Area - Settings Range (0x06s) - 2 byte mode,
// see h175_e5_c_communications_manual_en.pdf::5-1
enum OR_E5_SWR
{
//Temperature: Use the specified range for each sensor.
// Analog: Scaling lower limit 5% FS to Scaling upper limit + 5% FS
OR_E5_SWR_PV = 0x2000,
// Refer to 5-2 Status for details (see @OR_E5_STATUS_1 and @OR_E5_STATUS_2)
OR_E5_SWR_STATUS = 0x2001,
// Internal Set Point(see appendix *1) - SP lower limit to SP upper limit
OR_E5_SWR_ISP = 0x2002,
// Heater Current 1 Value Monitor, 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_HeaterCurrentValue1_Monitor = 0x2003,
// MV Monitor (Heating)
// Standard: 0xFFFFFFCE to 0x0000041A (5.0 to 105.0)
// Heating and cooling: 0x00000000 to 0x0000041A (0.0 to 105.0)
OR_E5_SWR_MVMonitorHeating = 0x2004,
// MV Monitor (Cooling)
// 0x00000000 to 0x0000041A (0.0 to 105.0)
OR_E5_SWR_MVMonitorCooling = 0x2005,
// Set Point - SP lower limit to SP upper limit
OR_E5_SWR_SP_LIMIT = 0x2103,
// Alarm Value 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_1 = 0x2104,
// Alarm Value - Upper Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_1_UL = 0x2105,
// Alarm Value - Lower Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_1_LL = 0x2106,
// Alarm Value 2
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_2 = 0x2107,
// Alarm Value - Upper Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_2_UL = 0x2108,
// Alarm Value - Lower Limit 1
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_ALARM_2_LL = 0x2109,
//Temperature: Use the specified range for each sensor.
// Analog: Scaling lower limit 5% FS to Scaling upper limit + 5% FS
OR_E5_SWR_PV2 = 0x2402,
// Internal Set Point(see appendix *1) - SP lower limit to SP upper limit
OR_E5_SWR_ISP2 = 0x2403,
// Multi SP No. Monitor, 0x00000000 to 0x00000007 (0 to 7)
OR_E5_SWR_MSMON = 0x2404,
// Status,
// - Not displayed on the Controller display.
// - In 2-byte mode, the rightmost 16 bits are read.
OR_E5_SWR_STATUSEX = 0x2406,
// Status,
// - Not displayed on the Controller display.
// - In 2-byte mode, the leftmost 16 bits are read.
OR_E5_SWR_STATUSEXL = 0x2407,
// Status,
// - Not displayed on the Controller display.
// - In 2-byte mode, the rightmost 16 bits are read.
OR_E5_SWR_STATUSEXR = 0x2408,
// Decimal Point Monitor,
// 0x00000000 to 0x00000003 (0 to 3)
OR_E5_SWR_DECMON = 0x2410,
// Set Point ()
// SP lower limit to SP upper limit
OR_E5_SWR_SP = 0x2601,
// Remote Set Point Monitor
// - Remote SP lower limit 10% FS to Remote SP upper limit +10% FS
OR_E5_SWR_SP_EX_MON = 0x2602,
// Heater Current 1 Value Monitor, 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_HeaterCurrentValue1_Monitor2 = 0x2604,
// Valve Opening Monitor, 0xFFFFFF9C to 0x0000044C (10.0 to 110.0)
OR_E5_SWR_VALVE_OPENING_MON = 0x2607,
// Proportional Band (Cooling), 0x00000001 to 0x0000270F (0.1 to 999.9)
OR_E5_SWR_PRO_BAND = 0x2701,
// Integral Time (Cooling) 0x00000000 to 0x0000270F
// (0 to 9999: Integral/derivative time unit is 1 s.)
// (0.0 to 999.9: Integral/derivative time unit is 0.1 s.)
OR_E5_SWR_IT_COOLING = 0x2702,
// Derivative Time (Cooling) 0x00000000 to 0x0000270F
// (0 to 9999: Integral/derivative time unit is 1 s.)
// (0.0 to 999.9: Integral/derivative time unit is 0.1 s.)
OR_E5_SWR_D_COOLING = 0x2703,
// Dead Band 0xFFFFF831 to 0x0000270F
// (199.9 to 999.9 for temperature input)
// (19.99 to 99.99 for analog input)
OR_E5_SWR_DEADBAND = 0x2704,
// Manual Reset Value,
// 0x00000000 to 0x000003E8 (0.0 to 100.0)
OR_E5_SWR_MANUAL_RESET_VALUE = 0x2705,
// Hysteresis (Heating)
// 0x00000001 to 0x0000270F
// (0.1 to 999.9 for temperature input)
// (0.01 to 99.99 for analog input)
OR_E5_SWR_HYSTERESIS = 0x2706,
// Hysteresis (Cooling)
// 0x00000001 to 0x0000270F
// (0.1 to 999.9 for temperature input)
// (0.01 to 99.99 for analog input)
OR_E5_SWR_HYSTERESIS_COOLING = 0x2707,
// Control Period (Heating)
// 0xFFFFFFFE (2): 0.1 s
// 0xFFFFFFFF (1): 0.2 s
// 0x00000000 (0): 0.5 s
// 0x00000001 to 0x00000063 (1 to 99)
OR_E5_SWR_CONTROL_PERIOD_HEATING = 0x2708,
// Control Period (Cooling)
// 0xFFFFFFFE (2): 0.1 s
// 0xFFFFFFFF (1): 0.2 s
// 0x00000000 (0): 0.5 s
// 0x00000001 to 0x00000063 (1 to 99)
OR_E5_SWR_CONTROL_PERIOD_COOLING = 0x2709,
// Position Proportional Dead Band
// 0x00000001 to 0x00000064 (0.1 to 10.0)
OR_E5_SWR_POSITION_PROPORTIONAL_DEAD_BAND = 0x270A,
// Open/Close Hysteresis
// 0x00000001 to 0x000000C8 (0.1 to 20.0)
OR_E5_SWR_OPEN_CLOSE_HYSTERESIS = 0x270B,
// SP Ramp Time Unit 0x00000000 (0): EU/second
// 0x00000001 (1): EU/minute
// 0x00000002 (2): EU/hour
OR_E5_SWR_SP_RAMP_UNIT = 0x270C,
// SP Ramp Set Value 0x00000000 (0): OFF
// 0x00000001 to 0x0000270F (1 to 9999)
OR_E5_SWR_SP_RAMP_SET_VALUE = 0x270D,
// SP Ramp Fall Value
// 0xFFFFFFFF (1): Same (Same as SP Ramp Set Value.)
// 0x00000000 (0): OFF
// 0x00000001 to 0x0000270F (1 to 9999)
OR_E5_SWR_SP_FALL_VALUE = 0x270E,
// MV at Stop Standard Models
// Standard control:
// 0xFFFFFFCE to 0x0000041A (5.0 to 105.0)
// Heating and cooling control:
// 0xFFFFFBE6 to 0x0000041A (105.0 to 105.0)
// Position-proportional Models
// Close position-proportional control with the Direct Setting of
// Position Proportional MV parameter set to ON:
// 0xFFFFFFCE to 0x0000041A (5.0 to 105.0)
// Floating position-proportional control or the Direct Setting of
// Position Proportional MV parameter set to OFF:
// 0xFFFFFFFF to 0x00000001 (1 to 1)
OR_E5_SWR_MV_PV_ERROR = 0x2711,
// MV Change Rate Limit
// 0x00000000 to 0x000003E8 (0.0 to 100.0)
OR_E5_SWR_CHANGE_RATE_LIMIT = 0x2713,
// PV Input Slope Coefficient
// 0x00000001 to 0x0000270F (0.001 to 9.999)
OR_E5_SWR_PV_INPUT_SLOPE_COEFFICIENT = 0x2718,
// Heater Burnout Detection 1
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HEATER_BURNOUT_DETECTION_1 = 0x271B,
// Leakage Current 1 Monitor
// 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_LEAKAGE_CURRENT_MONITOR_1 = 0x271C,
// HS Alarm 1
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HS_ALARM_1 = 0x271D,
// Process Value Input Shift
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_PROCESS_VALUE_INPUT_SHIFT = 0x2723,
// Heater Burnout Detection 2
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HEATER_BURNOUT_DETECTION_2 = 0x2725,
// Leakage Current 2 Monitor
// 0x00000000 to 0x00000226 (0.0 to 55.0)
OR_E5_SWR_LEAKAGE_CURRENT_MONITOR_2 = 0x2726,
// HS Alarm 12
// 0x00000000 to 0x000001F4 (0.0 to 50.0)
OR_E5_SWR_HS_ALARM_2 = 0x2727,
// Soak Time Remain (how lovely)
// 0x00000000 to 0x0000270F (0 to 9999)
OR_E5_SWR_SOAK_REMAIN = 0x2728,
// Soak Time
// 0x00000001 to 0x0000270F (1 to 9999)
OR_E5_SWR_SOAK_TIME = 0x2729,
// Wait Band 0x00000000 (0): OFF
// 0x00000001 to 0x0000270F
// (0.1 to 999.9 for Temperature input)
// (0.01 to 99.99 for Analog input)
OR_E5_SWR_WAIT_BAND = 0x272A,
// Remote SP Input Shift
// 0xFFFFF831 to 0x0000270F (1999 to 9999)
OR_E5_SWR_REMOTE_SP_SHIFT = 0x272B,
// Remote SP input Slope Coefficient
// 0x00000001 to 0x0
OR_E5_SWR_REMOTE_SP_SLOPE_COEFFICIENT = 0x272C,
// Input Digital Filter 0x00000000 to 0x0000270F (0.0 to 999.9)
OR_E5_SWR_DIGITAL_FILTER = 0x2800
// Notes :
// *1 Not displayed on the Controller display
};
// Operation Command Address
enum OR_E5_CMD_ADDRESS
{
OR_E5_CMD_STOP_RUN = 0x100,
OR_E5_CMD_COM_WRITE = 0x000,
// Auto-Tune
OR_E5_CMD_AT = 0x200
};
enum OR_E5_CMD
{
OR_E5_STOP = OR_E5_CMD(OR_E5_CMD_ADDRESS::OR_E5_CMD_STOP_RUN, 1),
OR_E5_RUN = OR_E5_CMD(OR_E5_CMD_ADDRESS::OR_E5_CMD_STOP_RUN, 0),
OR_E5_AT_CANCEL = OR_E5_CMD(OR_E5_CMD_ADDRESS::OR_E5_CMD_AT, 0),
OR_E5_AT_EXCECUTE = OR_E5_CMD(OR_E5_CMD_ADDRESS::OR_E5_CMD_AT, 1)
};
enum OR_E5_ERROR
{
VARIABLE_ADDRESS_ERROR = 0x2,
VARIABLE_RANGE_ERROR = 0x3,
VARIABLE_OPERATION_ERROR = 0x4
};
enum OR_E5_RESPONSE_CODE
{
OR_READ_ERROR = 0x83,
OR_RESPONSE_OK = 0x10,
OR_OPERATION_ERROR = 0x90,
OR_COMMAND_ERROR = 0x86
};
#define OR_E_MSG_INVALID_ADDRESS "Invalid Variable Address"
#define OR_E_MSG_INVALID_RANGE "Invalid Variable Range"
#define OR_E_MSG_OPERATION_ERROR "OPERATION ERROR"
#endif

View File

@ -0,0 +1,86 @@
#ifndef OMRON_MX2_H
#define OMRON_MX2_H
// Omron MX2 Registers
#define MX2_STATE 0x0003 // (2 bytes) Status of the inverter
#define MX2_STATUS 0x004 // (2 bytes) Status of the inverter
#define MX2_TARGET_FR 0x0001 // (4 bytes) Source (reference) of the frequency reference (0,01 [Hz])
#define MX2_ACCEL_TIME 0x1103 // (4 bytes) Acceleration time (cm compressor) in 0.01 sec
#define MX2_DEACCEL_TIME 0x1105 // (4 bytes) Braking time (cm compressor) in 0.01 sec
#define MX2_CURRENT_FR 0x1001 // (4 bytes) Output frequency control (0,01 [Hz])
#define MX2_AMPERAGE 0x1003 // (2 bytes) Output current monitoring (0,01 [A])
#define MX2_VOLTAGE 0x1011 // (2 bytes) Monitoring output voltage 0.1 [V]
#define MX2_POWER 0x1012 // (2 bytes) Power control 0.1 [kW]
#define MX2_POWER_HOUR 0x1013 // (4 bytes) Watt-hour control 0.1 [kW / h]
#define MX2_HOUR 0x1015 // (4 bytes) Control of operating time in the "Run" mode 1 [h]
#define MX2_HOUR1 0x1017 // (4 bytes) Monitoring of running hours with power on 1 [h]
#define MX2_TEMP 0x1019 // (2 bytes) Radiator temperature control (0.1 degree) -200 ... 1500
#define MX2_VOLTAGE_DC 0x1026 // (2 bytes) DC voltage control (PN) 0.1 [V]
#define MX2_NUM_ERR 0x0011 // (2 bytes) Trip counter 0 ... 65530
#define MX2_ERROR1 0x0012 // (20 bytes) Description 1 trip the remaining 5 lie sequentially behind the first address error are calculated MX2_ERROR1 + i * 0x0a
#define MX2_INIT_DEF 0x1357 // (2 bytes) Set the initialization mode to 0 (nothing), 1 (clearing the shutdown history), 2 (clearing the shutdown history and initializing data), 4 (clearing the shutdown history, initializing data and the program EzSQ)
#define MX2_INIT_RUN 0x13b7 // (2 bytes) Initialization start 0 (off), 1 (on)
#define MX2_SOURCE_FR 0x1201 // (2 bytes) Frequency reference source
#define MX2_SOURCE_CMD 0x1202 // (2 bytes) Command source
#define MX2_BASE_FR 0x1203 // (2 bytes) Main frequency 300 ... "maximum frequency" 0.1 Hz
#define MX2_MAX_FR 0x1204 // (2 bytes) Maximum frequency 300 ... 4000 (10000) 0.1 Hz
#define MX2_DC_BRAKING 0x1245 // (2 bytes) Enable DC Braking
#define MX2_STOP_MODE 0x134e // (2 bytes) Choosing a stop method B091 = 01
#define MX2_MODE 0x13ae // (2 bytes) IF mode selection b171 = 03
// Setting the inverter for a specific compressor Registers Hxxx Permanent magnet motor (PM motor)
#define MX2_b171 0x13ae // b171 Inverter selection b171 read / write 0 (off), 1 (IM mode), 2 (high frequency mode), 3 (PM mode) = 03
#define MX2_b180 0x13b7 // b180 Initialization trigger = 01
#define MX2_H102 0x1571 // H102 Setting the PM engine code 00 (standard Omron data) 01 (auto-tuning data) = 1
#define MX2_H103 0x1572 // H103 PM engine power (0.1 / 0.2 / 0.4 / 0.55 / 0.75 / 1.1 / 1.5 / 2.2 / 3.0 / 3, 7 / 4.0 / 5.5 / 7.5 / 11.0 / 15.0 / 18.5) = 7
#define MX2_H104 0x1573 // H104 Setting the number of poles of the PM motor = 4
#define MX2_H105 0x1574 // H105 Rated current of the PM motor = 1000 (this is 11A)
#define MX2_H106 0x1575 // H106 PM motor constant R From 0.001 to 65.535 Ohms = 0.55
#define MX2_H107 0x1576 // H107 PM Engine Ld Constant From 0.01 to 655.35 mH = 2.31
#define MX2_H108 0x1577 // H108 Lq constant of PM engine From 0.01 to 655.35 mH = 2.7
#define MX2_H109 0x1578 // H109 Ke Engine Constant PM-motor 0.0001 ... 6.5535 Vmax ./ (rad / s) = 750 must be selected it affects consumption and noise
#define MX2_H110 0x1579 // (4 bytes) H110 PM motor constant J From 0.001 to 9999,000 kg / m² = 0.01
#define MX2_H111 0x157B // H111 Auto tuning constant R From 0.001 to 65.535 Ohms
#define MX2_H112 0x157C // H112 Auto-tuning constant Ld From 0.01 to 655.35 mH
#define MX2_H113 0x157D // H113 Auto tuning constant Lq From 0.01 to 655.35 mH
#define MX2_H116 0x1581 // H116 The response of the PM motor at a speed of 1 ... 1000 = 100 (default)
#define MX2_H117 0x1582 // H117 Starting current of the PM motor From 20.00 to 100.00% = 70 (default)
#define MX2_H118 0x1583 // H118 Starting time of the PM motor 0.01 ... 60.00 s = 1 (default)
#define MX2_H119 0x1584 // H119 Engine PM stabilization constant From 0 to 120% s = 100
#define MX2_H121 0x1586 // H121 Minimum frequency of the PM motor From 0.0 to 25.5% = 0
#define MX2_H122 0x1587 // H122 Idling current PM motor From 0.00 to 100.00% = 50 (default)
#define MX2_H123 0x1588 // H123 Choice of PM engine start method 00 (off) 01 (on) = 0 (default)
#define MX2_H131 0x158A // H131 Estimation of the initial position of the rotor of the PM motor: standby time 0 V 0 ... 255 = 10 (default)
#define MX2_H132 0x158B // H132 Assessment of the initial position of the rotor of the PM motor: waiting time for determination 0 ... 255 = 10 (default)
#define MX2_H133 0x158C // H133 Assessment of the initial position of the rotor of the PM motor: determination time 0 ... 255 = 30 (default)
#define MX2_H134 0x158D // H134 Assessment of the initial position of the rotor of the PM motor: voltage gain 0 ... 200 = 100 (default)
#define MX2_C001 0x1401 // C001 Input function [1] 0 (FW: go forward) = 0
#define MX2_C004 0x1404 // C004 Input function [4] 18 (RS: reset) = 18
#define MX2_C005 0x1405 // C005 Input function [5] [also input “PTC”] = 19 PTC Thermistor with positive TCS for thermal protection (only C005)
#define MX2_C026 0x1404 // C026 Relay output function 5 (AL: error signal) = 05
#define MX2_b091 0x135E // b091 Choice of stopping method 0 (braking to a complete stop), 1 (coasting stop) = 1
#define MX2_b021 0x1316 // b021 Operating mode with overload limitation 0 (off), 1 (enabled during acceleration and rotation at a constant speed), \
// 2 (enabled during rotation at a constant speed), 3 (enabled during acceleration and rotation at a constant speed [increase \
// speed in generator mode]) = 1
#define MX2_b022 0x1317 // b022 Overload restriction level 200 ... 2000 (0.1%) =
#define MX2_b023 0x1318 // b023 Braking time with overload limitation (0.1 sec) = 10
#define MX2_F002 0x1103 // (4 bytes) F002 Acceleration time (1) Standard, default acceleration, range from 0.001 to 3600 s (0.01 sec) = 20 * 100
#define MX2_F003 0x1105 // (4 bytes) F003 Deceleration time (1) Standard, default acceleration, range from 0.001 to 3600 s (0.01 sec) = 20 * 100
#define MX2_A001 0x1201 // A001 Frequency reference source 00 ... Potent. on external panels 01 ... Control terminals 02 ... Setting parameter F001 \
// 03 ... Input via ModBus network 04 ... Add. card 06 ... Entrance imp. after 07 ... via EzSQ 10 ... Result of arithmetic operation = 03
#define MX2_A002 0x1202 // A002 Source of the “Run” command 01 .. Control terminals 02 ... “Run” key on the keypad or digital panel 03 ... Input via the ModBus network 04 ... Add. card = 01
#define MX2_A003 0x1203 // A003 Main frequency Can be set in the range from 30 Hz to the maximum frequency (A004) (0.1 Hz) = 120 * 10
#define MX2_A004 0x1204 // A004 Maximum frequency Can be set in the range from the fundamental frequency to 400 Hz (0.1 Hz) = 120 * 10
// Omron MX2 Bits
#define MX2_START 0x0000 // (bit) Run command 1: Run, 0: Stop (valid with A002 = 03)
#define MX2_SET_DIR 0x0001 // (bit) Command of direction of rotation 1: Reverse rotation, 0: Rotation in the forward direction (valid with A002 = 03)
#define MX2_RESET 0x0004 // (bit) Reset emergency shutdown (RS) 1: Reset
#define MX2_READY 0x0011 // (bit) Ready IF 1: Ready, 0: Not ready
#define MX2_DIRECTION 0x0010 // (bit) Direction of rotation 1: Reverse rotation, 0: Rotation in the forward direction (deadlock with "d003")
#define TEST_NUMBER 1234 // Verification code for function 0x08
#endif

View File

@ -0,0 +1,89 @@
#ifndef PHOTO_ELECTRIC_SENSOR
#define PHOTO_ELECTRIC_SENSOR
// Typical photo electric sensor. This needs debouncing.
// Currently used : OMRON - E3FB-DN22, see vendor files
#include "../types.h"
#include "../common/macros.h"
#include "../common/ppmath.h"
#define PES_TIMEOUT 1600
class PhotoElectricSensor
{
public:
PhotoElectricSensor(short pin, short interval)
{
this->pin = pin;
this->interval = interval;
this->highTS = 0;
this->lowTS = 0;
this->dt = 0;
this->now = 0;
this->moving = 0;
this->setup();
}
short setup(){}
short loop()
{
now = millis();
if (now - dt > 800)
{
this->value = RANGE(analogRead(this->pin), 50 - 10, 50 + 10);
dt = now;
}
/*
this->debouncer.update();
this->value = !this->debouncer.read();
if (this->last != this->value)
{
this->last = this->value;
this->highTS = 0;
this->lowTS = 0;
}
this->now = millis();
if (this->value == HIGH)
{
this->highTS = this->now;
}
else
{
this->lowTS = this->now;
}
if (this->highTS <= this->lowTS)
{
this->dt = this->lowTS - this->highTS;
}
else
{
this->dt = this->highTS - this->lowTS;
}
this->dt = abs(this->dt);
*/
return this->value;
}
short ok()
{
return this->value;
}
short value;
short moving;
millis_t highTS; // Last HIGH TS
millis_t lowTS; // Last LOW TS
millis_t dt; // Last delta time between HIGH / LOW
millis_t now; // Temp. variable to store tick TS
bool last;
protected:
short pin;
short interval;
};
#endif

View File

@ -0,0 +1,39 @@
#ifndef PROXIMITY_SENSOR_H
#define PROXIMITY_SENSOR_H
// Typical proximity switch. This needs debouncing.
// Wiring :
// Blue -> GND
// Brown -> 6 - 36 V
// Black -> Digital In
#include <Bounce2.h>
#include "../types.h"
class ProximitySensor
{
public:
ProximitySensor(short _pin) : pin(_pin){}
short setup()
{
this->debouncer = Bounce();
this->debouncer.attach(this->pin, INPUT_PULLUP);
this->debouncer.interval(25);
this->loop();
return this->value;
}
short loop()
{
this->debouncer.update();
this->value = !this->debouncer.read();
return this->value;
}
bool value;
protected:
uchar pin;
Bounce debouncer;
};
#endif

View File

@ -0,0 +1,67 @@
#ifndef STATUSLIGHT_H
#define STATUSLIGHT_H
class StatusLight
{
public:
StatusLight(short _pin) : pin(_pin)
{
doBlink = false;
status_blink_TS = 0;
last_blink = !digitalRead(pin);
}
short setup()
{
}
void setBlink(bool blink)
{
doBlink = blink;
}
void on()
{
digitalWrite(pin, HIGH);
}
void off()
{
digitalWrite(pin, LOW);
}
short loop()
{
if (doBlink)
{
if (millis() - status_blink_TS > 1000)
{
status_blink_TS = millis();
last_blink = !last_blink;
digitalWrite(pin, last_blink);
}
}
}
void status_loop()
{
}
void status_blink(bool blink)
{
if (!doBlink && blink)
{
blink_start_ts = millis();
}
doBlink = blink;
}
short pin;
millis_t status_blink_TS;
bool doBlink;
bool last_blink;
millis_t blink_start_ts;
millis_t max_blink_time; // stop blinking in an hour
};
#endif

View File

@ -0,0 +1,42 @@
#ifndef TEMPERATURE_SENSOR_H
#define TEMPERATURE_SENSOR_H
#include <max6675.h>
#include "../config.h"
#include "../macros.h"
#include "../time.h"
class TemperatureSensor
{
public:
TemperatureSensor(short sck, short cs, short so, short _max, short _interval) : ktc(MAX6675(sck, cs, so)),
temperature(),
temperature_TS(millis()),
maxTemp(_max),
interval(_interval) {}
bool ok()
{
return temperature < maxTemp;
}
void loop()
{
if (millis() - temperature_TS > interval)
{
temperature_TS = millis();
temperature = ktc.readCelsius();
}
}
private:
MAX6675 ktc;
short temperature;
short maxTemp;
short interval;
millis_t temperature_TS;
};
#endif

View File

@ -0,0 +1,134 @@
#ifndef CONFIG_H
#define CONFIG_H
#include "enums.h"
#include "common/macros.h"
#include <Controllino.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Core settings
//
#define LOOP_DELAY 100 // Our frame time, exluding delays in some places
#define BOOT_DELAY 1000 // Wait at least this amount in ms after boot before doing anything
// Please consider to set this to false for production - especially with the full feature set since this is requiring extra
// time for the serial communication and will affect the overall framerate/performance
// #define DEBUG true
#define DEBUG_INTERVAL 1000
#define DEBUG_BAUD_RATE 19200 // Serial port speed
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Machine settings
//
#define USE_CONTROLLINO
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// VFD related
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Motor related
//
// Motor overload pin, if defined, this will be used to detect jamming
// On an OmronM2X, set the output via C21 (for output pin 11) to 03 for
// 'Overload' (which is set in C41 )
// #define MOTOR_LOAD_PIN CONTROLLINO_A2
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Extrusion related
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// General switches
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Feedback
#define HAS_STATUS
#define STATUS_POWER_PIN CONTROLLINO_R6
#define STATUS_PID_PIN CONTROLLINO_R7
#define STATUS_VFD_PIN CONTROLLINO_R8
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Plastic Hub Studio - internals : used by external controller setups
// Make sure it's matching
#define FIRMATA_BAUD_RATE 19200
#define FIRMWARE_VERSION 0.8
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Omron Pids
//
#define NB_OMRON_PIDS 3
#define OMRON_PID_SLAVE_START 1
#define OMRON_PID_UPDATE_INTERVAL 1000
#define OMRON_PID_WRITE_INTERVAL 500
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Omron - MX2 - VFD
#define OMRON_MX2_SLAVE_ID 10
#define OMRON_MX2_STATE_INTERVAL 1000
#define OMRON_MX2_DEBUG_INTERVAL 3000
#define OMRON_MX2_READ_INTERVAL 1000
#define OMRON_MX2_LOOP_INTERVAL 500
#define OMRON_MX2_SAME_REQUEST_INTERVAL 2000
#define MODBUS_QUEUE_MIN_FREE 5
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Modbus
#define MODBUS_RS485_BAUDRATE 19200
#define MODBUS_RS485_PORT SERIAL_8E1
#define MODBUS_RS485_TIMEOUT 2000
#define MODBUS_TCP_DEFAULT_REGISTER_VALUE 0
#define HAS_MODBUS_BRIDGE
static uint8_t MB_MAC[] = {0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02};
static uint8_t MB_IP[]{192, 168, 1, 111};
static uint8_t MB_GATEWAY[] = {192, 168, 1, 1};
static uint8_t MB_SUBNET[] = {255, 255, 255, 0};
////////////////////////////////////////////////////////////////
//
// Instrumentation
//
// #define MEARSURE_PERFORMANCE
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// externals
//
// pull in internal constants
#include "constants.h"
// pull in internal configs
#include "config_adv.h"
// The user_config.h is initially added to the github repository but changes will be ignored via .gitignore. Please keep this file safe and possibly
// on a per tenant base stored. You can override parameters in this file by using #undef SOME_PARAMETER and then re-define again if needed, otherwise disable
// default features by using #undef FEATURE_OR_PARAMETER.
// This presents the possibilty to play with the code whilst staying in the loop with latest updates.
#include "user_config.h"
// At last we check all configs and spit compiler errors
#include "config_validator.h"
#endif

View File

@ -0,0 +1,153 @@
#ifndef known_16bit_timers_header_
#define known_16bit_timers_header_
// Wiring-S
//
#if defined(__AVR_ATmega644P__) && defined(WIRING)
#define TIMER1_A_PIN 5
#define TIMER1_B_PIN 4
#define TIMER1_ICP_PIN 6
// Teensy 2.0
//
#elif defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY)
#define TIMER1_A_PIN 14
#define TIMER1_B_PIN 15
#define TIMER1_C_PIN 4
#define TIMER1_ICP_PIN 22
#define TIMER1_CLK_PIN 11
#define TIMER3_A_PIN 9
#define TIMER3_ICP_PIN 10
// Teensy++ 2.0
#elif defined(__AVR_AT90USB1286__) && defined(CORE_TEENSY)
#define TIMER1_A_PIN 25
#define TIMER1_B_PIN 26
#define TIMER1_C_PIN 27
#define TIMER1_ICP_PIN 4
#define TIMER1_CLK_PIN 6
#define TIMER3_A_PIN 16
#define TIMER3_B_PIN 15
#define TIMER3_C_PIN 14
#define TIMER3_ICP_PIN 17
#define TIMER3_CLK_PIN 13
// Teensy 3.0
//
#elif defined(__MK20DX128__)
#define TIMER1_A_PIN 3
#define TIMER1_B_PIN 4
#define TIMER1_ICP_PIN 4
// Teensy 3.1 / Teensy 3.2
//
#elif defined(__MK20DX256__)
#define TIMER1_A_PIN 3
#define TIMER1_B_PIN 4
#define TIMER1_ICP_PIN 4
#define TIMER3_A_PIN 32
#define TIMER3_B_PIN 25
#define TIMER3_ICP_PIN 32
// Teensy 3.5 / Teensy 3.6
//
#elif defined(__MK64FX512__) || defined(__MK66FX1M0__)
#define TIMER1_A_PIN 3
#define TIMER1_B_PIN 4
#define TIMER1_ICP_PIN 4
#define TIMER3_A_PIN 29
#define TIMER3_B_PIN 30
#define TIMER3_ICP_PIN 29
// Teensy-LC
//
#elif defined(__MKL26Z64__)
#define TIMER1_A_PIN 16
#define TIMER1_B_PIN 17
#define TIMER1_ICP_PIN 17
#define TIMER3_A_PIN 3
#define TIMER3_B_PIN 4
#define TIMER3_ICP_PIN 4
// Arduino Mega
//
#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
#define TIMER1_A_PIN 11
#define TIMER1_B_PIN 12
#define TIMER1_C_PIN 13
#define TIMER3_A_PIN 5
#define TIMER3_B_PIN 2
#define TIMER3_C_PIN 3
#define TIMER4_A_PIN 6
#define TIMER4_B_PIN 7
#define TIMER4_C_PIN 8
#define TIMER4_ICP_PIN 49
#define TIMER5_A_PIN 46
#define TIMER5_B_PIN 45
#define TIMER5_C_PIN 44
#define TIMER3_ICP_PIN 48
#define TIMER3_CLK_PIN 47
// Arduino Leonardo, Yun, etc
//
#elif defined(__AVR_ATmega32U4__)
#define TIMER1_A_PIN 9
#define TIMER1_B_PIN 10
#define TIMER1_C_PIN 11
#define TIMER1_ICP_PIN 4
#define TIMER1_CLK_PIN 12
#define TIMER3_A_PIN 5
#define TIMER3_ICP_PIN 13
// Uno, Duemilanove, LilyPad, etc
//
#elif defined (__AVR_ATmega168__) || defined (__AVR_ATmega328P__)
#define TIMER1_A_PIN 9
#define TIMER1_B_PIN 10
#define TIMER1_ICP_PIN 8
#define TIMER1_CLK_PIN 5
// Sanguino
//
#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__)
#define TIMER1_A_PIN 13
#define TIMER1_B_PIN 12
#define TIMER1_ICP_PIN 14
#define TIMER1_CLK_PIN 1
// Wildfire - Wicked Devices
//
#elif defined(__AVR_ATmega1284P__) && defined(WILDFIRE_VERSION) && WILDFIRE_VERSION >= 3
#define TIMER1_A_PIN 5 // PD5
#define TIMER1_B_PIN 8 // PD4
#define TIMER1_ICP_PIN 6 // PD6
#define TIMER1_CLK_PIN 23 // PB1
#define TIMER3_A_PIN 12 // PB6
#define TIMER3_B_PIN 13 // PB7
#define TIMER3_ICP_PIN 9 // PB5
#define TIMER3_CLK_PIN 0 // PD0
#elif defined(__AVR_ATmega1284P__) && defined(WILDFIRE_VERSION) && WILDFIRE_VERSION < 3
#define TIMER1_A_PIN 5 // PD5
#define TIMER1_B_PIN 4 // PD4
#define TIMER1_ICP_PIN 6 // PD6
#define TIMER1_CLK_PIN 15 // PB1
#define TIMER3_A_PIN 12 // PB6
#define TIMER3_B_PIN 13 // PB7
#define TIMER3_ICP_PIN 11 // PB5
#define TIMER3_CLK_PIN 0 // PD0
// Mighty-1284 - Maniacbug
//
#elif defined(__AVR_ATmega1284P__)
#define TIMER1_A_PIN 12 // PD5
#define TIMER1_B_PIN 13 // PD4
#define TIMER1_ICP_PIN 14 // PD6
#define TIMER1_CLK_PIN 1 // PB1
#define TIMER3_A_PIN 6 // PB6
#define TIMER3_B_PIN 7 // PB7
#define TIMER3_ICP_PIN 5 // PB5
#define TIMER3_CLK_PIN 8 // PD0
#endif
#endif

View File

@ -0,0 +1,115 @@
#ifndef CONFIG_ADV_H
#define CONFIG_ADV_H
//#define BRIDGE_DEBUG // enable bridge debugging
////////////////////////////////////////////////////////////////////////////////
//
// Modbus
#define MODBUS_CMD_WAIT 200
#define MODBUS_READ_WAIT 200
#define MODBUS_R_RETRY 2 // max read queries
#define MODBUS_W_RETRY 4 // max write queries
// @todo
// - advance config validation for the settings above
// - accumulate global modbus query timeout
////////////////////////////////////////////////////////////////////////////////
//
// Power settings
// optional current sensor to validate primary power is there
// #define POWER_CSENSOR_PRIMARY CONTROLLINO_A15
// optional current sensor to validate primary power is there
#define POWER_CSENSOR_SECONDARY CONTROLLINO_A14
/////////////////////////////////////////////////////////////
//
// Motor load settings, this requires a current sensor or can be
// taken from the VFD's output.
// the interval to read the current
#define MOTOR_LOAD_READ_INTERVAL 100
// the current measured when the motor runs idle, min - max range
#define MOTOR_IDLE_LOAD_RANGE_MIN 30
#define MOTOR_IDLE_LOAD_RANGE_MAX 50
// the current measured when the motor is under load, min - max range
#define MOTOR_SHREDDING_LOAD_RANGE_MIN 50
#define MOTOR_SHREDDING_LOAD_RANGE_MAX 99
// the current measured when the motor is overloaded, min - max range
#define MOTOR_OVERLOAD_RANGE_MIN 100
#define MOTOR_OVERLOAD_RANGE_MAX 400
#define MOTOR_MIN_DT 2500
/////////////////////////////////////////////////////////////
//
// Bridge related
#define STATE_RESPONSE_CODE 1000
// #define BRIDGE_HAS_RESPONSE
/////////////////////////////////////////////////////////////
//
// Error codes
//
#define E_MSG_OK "Ok"
#define E_MSG_STUCK "Shredder is stuck"
// common operating failures
#define E_OK 0 //all good
#define E_STUCK 100 //Shredder stuck
#define E_NO_SUCH_PID 2001 //cant find PID
#define E_QUERY_BUFFER_END 99 // have no free query buffer slot
// power failures
#define E_POWER_PRIM_ON 145 // Power is on whilst it shouldn't be
#define E_POWER_PRIM_OFF 146 // Power is off whilst it should be
#define E_POWER_SEC_ON 147 // Power is on whilst it shouldn't be
#define E_POWER_SEC_OFF 148 // Power is off whilst it should be
#define E_POWER 150 // Nothing is online
#define E_VFD_OFFLINE E_POWER_PRIM_OFF // VFD should be online
// sensor failures
#define E_VFD_CURRENT 200 // VFD current abnormal: below or above average
#define E_OPERATING_SWITCH 220 // Operating switch invalid value
#define E_CARTRIDGE_OPEN 240 // Cartridge open sensor doesn't work
#define E_SERVICE_OPEN 241 // Sensor open sensor doesn't work
////////////////////////////
//
// sub system failures
//
#define E_USER_START 1000 // base offset for sub system errors
// vfd
#define E_VFD_RUN 300 // Motor should spin but doesnt
#define E_VFD_LOSS 301 // Motor should not spin but does
#define E_VFD_CUSTOM(A) E_USER_START+A // Custom VFD error
// motor
#define E_MOTOR_DT_IDLE 320 // Motor runs idle longer as defined
#define E_MOTOR_DT_OVERLOAD 321 // Motor runs overloaded longer as defined
#define E_BRIDGE_LOSS 400 // bridge poll timeout
// bridge
#define E_BRIDGE_START 2000 // base offset for custom bridge errors
#define E_BRIDGE_CUSTOM(A) E_USER_START+A // Custom bridge error
#define E_BRIDGE_PARITY E_BRIDGE_CUSTOM(1) // @todo, parity check failure
#define E_BRIDGE_CRC E_BRIDGE_CUSTOM(2) // @todo, crc failure
#define E_BRIDGE_FLOOD E_BRIDGE_CUSTOM(3) // @todo, msg queue
// extrusion
#define E_EX_BASE 3000 // base offset extruder
#define E_EX_CUSTOM(A) E_EX_BASE+A // Custom bridge error
#endif

View File

@ -0,0 +1,21 @@
#ifndef CONFIG_VALIDATOR
#define CONFIG_VALIDATOR
#include "common/macros.h"
#if defined(ENABLE_AUTO_REVERSE_PIN) && defined(HAS_AUTO_REVERSE_MODE)
#error "You can not have auto-revese toggle and a 3 pos mode switch"
#endif
#if DEBUG == true && USE_FIRMATA && DEBUG_BAUD_RATE !=FIRMATA_BAUD_RATE
#error "Debug baud rate must match firmata baud rate"
#endif
#if defined(USE_UNO) && defined(IR_SPEED)
#if IR_PIN !=2 && IR_PIN !=3
#error "For speed computation on the UNO, you need to use pins D2 or D3!"
#endif
#endif
#endif

View File

@ -0,0 +1,129 @@
#ifndef CONSTANTS_H
#define CONSTANTS_H
#include "enums.h"
/////////////////////////////////////////////////////////////////////////
//
// Primary - Motor related (shredder, extrusion, grinder)
#define MOTOR_FREQ_NORMAL 50 // set this to 60 Hz if needed
#define MOTOR_RPM 1480 // the actual motor speed
#define MOTOR_REDUCTION 0.03 // ie: 0.03 means 1:30
// Thresholds
// the maximum override in %, eg: 0.5 = 50% and it's not recommeded to run
// the motor below 50% of it's designed operating frequency - it's getting hot
#define MOTOR_LOW_FREQ_LIMIT 0.50
// the maximum override in %, eg: 0.5 = 50% and it's not recommeded to run
// the motor above 50% of it's designed operating frequency
#define MOTOR_HIGH_FREQ_LIMIT 0.50
// - PRE-CALCS
#define MOTOR_FREQ_CMIN MOTOR_FREQ_NORMAL - (MOTOR_FREQ_NORMAL * MOTOR_LOW_FREQ_LIMIT)
#define MOTOR_FREQ_CMAX MOTOR_FREQ_NORMAL + (MOTOR_FREQ_NORMAL * MOTOR_HIGH_FREQ_LIMIT)
/////////////////////////////////////////////////////////////////////////
//
// Shredder related
// default shredding speed, when chaning machine mode, it will snap to this
// value - if quick speed dial is available or other reasons (eg: remote)
// those values are currently based on v3 observations
#define RPM_SHREDDERING_DEFAULT 60
// min. shredding speed - when in shredder only mode, it won't go below
#define RPM_SHREDDERING_MIN 30
// max. shredding speed - when in shredder only mode, it won't go above
#define RPM_SHREDDERING_MAX 130
/////////////////////////////////////////////////////////////////////////
//
// Grinder related - Standalone/Combo
// default grinding speed, when chaning machine mode, it will snap to this
// value - if quick speed dial is available or other reasons (eg: remote)
// those values are currently for a 28 mm hexbar
#define RPM_GRINDING_DEFAULT 440
// min. grinding speed - when in grinder only mode, it won't go below
#define RPM_GRINDING_MIN 400
// max. grinding speed - when in grinder only mode, it won't go above
#define RPM_GRINDING_MAX 500
// user - land scaler (ie: radius)
#define RPM_GRINDER_SCALE 1
// transmission ratio from motor to grinder
// ie: 0.03 means 1:30
#define RPM_GRINDER_SHREDDER_SCALE 1
/////////////////////////////////////////////////////////////////////////
//
// Extrusion related - Standalone
// default extrusion speed, when chaning machine mode, it will snap to this
// value - if quick speed dial is available or other reasons (eg: remote)
#define RPM_EXTRUSION_DEFAULT 50
// min. extrusion speed - when in extrusion only mode, it won't go below
#define RPM_EXTRUSION_MIN 25
// max. extrusion speed - when in extrusion only mode, it won't go above
#define RPM_EXTRUSION_MAX 150
// user - land scaler
#define RPM_EXTRUSION_SCALE 1
/////////////////////////////////////////////////////////////////////////
//
// VFD - Standalone
// Speed in (VSI)
#define VFD_VSI_MIN_V_SPEED 0 //
#define VFD_VSI_MAX_V_SPEED 5 // most VFDs take speed regulation from 0 - 10
#define VFD_VSI_SCALE 1.0 // For noise, ie: voltage loss
#define VFD_QSPEED_1 1 // VFD quick speed dial profile 1
#define VFD_QSPEED_2 2 // VFD quick speed dial profile 2
#define VFD_QSPEED_3 3 // VFD quick speed dial profile 3
#define VFD_QSPEED_4 4 // VFD quick speed dial profile 4
#define VFD_QSPEED_5 5 // VFD quick speed dial profile 5
#define VFD_QSPEED_6 6 // VFD quick speed dial profile 5
#define ADDON_MOTOR_IDLE "MotorIdle"
/////////////////////////////////////////////////////////////////////////
//
// Plastic type related scaling
// @TODO : RPM scaling per plastic type
#define RPM_GRINDING_PET 440
/////////////////////////////////////////////////////////////////////////
//
// Addons
//
#define HOPPER_LOADED_STR "HopperLoaded"
#define MOTOR_IDLE_STR "MotorIdle"
#define VFD_STR "VFD"
#define DIRECTION_SWITCH_STR "DirectionSwitch"
#define MOTOR_LOAD_STR "MotorLoad"
#define ENCLOSURE_SENSOR_STR "EnclosureSensor"
#define MOTOR_TEMPERATURE_STR "MotorTemperature"
#define POWER_STR "Power"
#define PLUNGER_STR "Plunger"
#define CARTRDIGE_FULL_STR "CartridgeFull"
#define MOTOR_IR_SPEED_STR "MotorIRSpeed"
#define AUTO_REVERSE_STR "AutoReverse"
#define OPERATION_MODE_SWITCH_STR "OperationModeSwitch"
#define APP_STR "App"
#define RMOTOR_CONTROL_STR "RMotorControl"
#define OMRON_PID_STR "OmronE5PID"
#define OMRON_VFD_STR "OmronMx2"
#endif

View File

@ -0,0 +1,76 @@
# Extruder - Serial Protocol
## Protocols
### Serial
#### Request
Since it's serial, we receive for each command a reply matching an issue id as well a payload with the requested data or command replies.
**Command construction** :
Send Data/Command Syntax : `` `ID ; VERB ; FLAGS ; VERSION ; PAYLOAD` ``
**ID** : queued/issued command id, used to confirm command on sender side
**VERB** : COMMAND,STATUS,DATA
**FLAGS** :
```c++
enum MessageFlags
{
NEW = 1 << 1, // set on target when inbound
// set on target
PROCESSING = 1 << 2,
// set on target when inbound
PROCESSED = 1 << 3,
// set on host, turn on debugging through the entire processing chain
DEBUG = 1 << 4,
RECEIPT = 1 << 5 // set on host, this will return the new state
};
```
**PAYLOAD**: String, this string depends on the verb (see *ECALLS*).
Payloads is the actual call, in the form of Class:Function:Parameter(short),
### Example
```
"1;2;64;1;VFD:fwd:1"
```
```c++
enum ECALLS
{
// global function
EC_COMMAND = 1,
// addon method
EC_METHOD = 2,
// external function
EC_FUNC = 3,
// user space
EC_USER = 10
};
```
**Format for Verb EC_METHOD** : Addon-Class-Name:Addon-Class-MemberFunction-Name:Argument
#### Response
Response construction via delimitter : 10|x0A - line by line
Response syntax : `` `ID ; STATUS ; PAYLOAD` ``
**ID**: queued/issued command id, used to confirm command on sender side
**STATUS** : Error code, OK=0, SERVERITY Mask (syslog)
**PAYLOAD** : String - this string contains all enabled module states. The payload depends upon the sent query type (see **ECALLS**).
**Format for Verb EC_METHOD**, ie: ``` `Power:off:1` ``` = NEW_VALUE (the new state)
------------------------------------------------------------

View File

@ -0,0 +1,183 @@
#ifndef ENUMS_H
#define ENUMS_H
enum MB_FC
{
MB_FC_NONE = 0, /*!< null operator */
MB_FC_READ_COILS = 1, /*!< FCT=1 -> read coils or digital outputs */
MB_FC_READ_DISCRETE_INPUT = 2, /*!< FCT=2 -> read digital inputs */
MB_FC_READ_REGISTERS = 3, /*!< FCT=3 -> read registers or analog outputs */
MB_FC_READ_INPUT_REGISTER = 4, /*!< FCT=4 -> read analog inputs */
MB_FC_WRITE_COIL = 5, /*!< FCT=5 -> write single coil or output */
MB_FC_WRITE_REGISTER = 6, /*!< FCT=6 -> write single register */
MB_FC_WRITE_MULTIPLE_COILS = 15, /*!< FCT=15 -> write multiple coils or outputs */
MB_FC_WRITE_MULTIPLE_REGISTERS = 16 /*!< FCT=16 -> write multiple registers */
};
enum BOARD
{
MEGA
};
enum POS3_DIRECTION
{
UP = 1,
MIDDLE = 0,
DOWN = 2,
INVALID = -1
};
enum MODE
{
};
enum AR_MODE
{
NORMAL = 1, // Shredding
EXTRUSION = 2, // Extrusion (no reverse)
NONE = 3, // Disable any jamming detection
REMOTE = 4 // User land, ie: Firmata, I2C or PlasticHub-Studio
};
enum ADDON_FLAGS
{
DEBUG = 1,
INFO = 2,
LOOP = 3,
DISABLED = 4,
SETUP = 5,
MAIN = 6,
STATE = 7
};
enum ADDONS
{
MOTOR_IDLE = 1,
MOTOR_LOAD = 2,
MOTOR_TEMPERATURE = 3,
VFD_CONTROL = 4,
DIRECTION_SWITCH = 5,
ENCLOSURE_SENSOR = 6,
MOTOR_SPEED = 7,
POWER = 11,
OPERATION_MODE_SWITCH = 20,
SERIAL_BRIDGE = 23,
APP = 25,
MODBUS_BRIDGE = 26,
RMOTOR_CONTROL = 30,
OMRON_PID = 31,
OMRON_VFD = 32,
LAST = 64
};
enum POWER_CIRCUIT
{
POWER_PRIMARY = 0,
POWER_SECONDARY = 1
};
enum OPERATION_MODE
{
OP_NONE = 0,
OP_NORMAL = 1,
OP_DEBUG = 2,
OP_SERVICE = 3,
OP_TEST
};
enum ERROR
{
ERROR_OK = 0,
ERROR_WARNING = 1,
ERROR_FATAL = 2
};
enum MBB_STATE
{
WAITING = 0,
QUERY = 1,
RESPONSE = 2,
IDLE = 3
};
// Modbus query state
enum QUERY_STATE
{
QUEUED = 1,
PROCESSING = 2,
SENT = 3,
RESPONDED = 4,
DONE = 5
};
#define ku8MBReadCoils 0x01 ///< Modbus function 0x01 Read Coils
#define ku8MBReadDiscreteInputs 0x02 ///< Modbus function 0x02 Read Discrete Inputs
#define ku8MBWriteSingleCoil 0x05 ///< Modbus function 0x05 Write Single Coil
#define ku8MBWriteMultipleCoils 0x0F ///< Modbus function 0x0F Write Multiple Coils
// Modbus function codes for 16 bit access
#define ku8MBReadHoldingRegisters 0x03 ///< Modbus function 0x03 Read Holding Registers
#define ku8MBReadInputRegisters 0x04 ///< Modbus function 0x04 Read Input Registers
#define ku8MBWriteSingleRegister 0x06 ///< Modbus function 0x06 Write Single Register
#define ku8MBWriteMultipleRegisters 0x10 ///< Modbus function 0x10 Write Multiple Registers
#define ku8MBMaskWriteRegister 0x16 ///< Modbus function 0x16 Mask Write Register
#define ku8MBReadWriteMultipleRegisters 0x17 ///< Modbus function 0x17 Read Write Multiple Registers
#define ku8MBLinkTestOmronMX2Only 0x08 ///< Modbus function 0x08 Test
// Modbus protocol errors
#define ERR_MODBUS_0x01 -41 // Modbus 0x01 protocol illegal function exception
#define ERR_MODBUS_0x02 -42 // Modbus 0x02 protocol illegal data address exception
#define ERR_MODBUS_0x03 -43 // Modbus 0x03 protocol illegal data value exception
#define ERR_MODBUS_0x04 -44 // Modbus 0x4 protocol slave device failure exception
#define ERR_MODBUS_0xe0 -45 // Modbus 0xe0 Master invalid response slave ID exception
#define ERR_MODBUS_0xe1 -46 // Modbus 0xe1 Master invalid response function exception
#define ERR_MODBUS_0xe2 -47 // Modbus 0xe2 Master response timed out exception
#define ERR_MODBUS_0xe3 -48 // Modbus 0xe3 Master invalid response CRC exception
#define ERR_MODBUS_UNKNOW -56 // Modbus unknown error (protocol failure)
#define ERR_MODBUS_STATE -57 // Forbidden ( invalid ) state of the inverter
#define ERR_MODBUS_BLOCK -58 // Attempt to turn on the VT with the inverter locked
// Omron Mx2 specific
#define ERR_MODBUS_MX2_0x01 -49 // Omron mx2 Exception code 0x01 The specified function is not supported
#define ERR_MODBUS_MX2_0x02 -50 // Omron mx2 Exception code 0x02 The specified function was not found.
#define ERR_MODBUS_MX2_0x03 -52 // Omron mx2 Exception code 0x03 Unacceptable data format
#define ERR_MODBUS_MX2_0x05 -52 // Omron mx2 communication error over Modbus (function communication check 0x08 Omron mx2)
#define ERR_MODBUS_MX2_0x21 -53 // Omron mx2 Exception code 0x21 Data written to the storage register is outside the inverter
#define ERR_MODBUS_MX2_0x22 -54 // Omron mx2 Exception code 0x22 These functions are not available for the inverter
#define ERR_MODBUS_MX2_0x23 -55 // Omron mx2 Exception code 0x23 The register (bit) into which the value should be written is read-only
#define MB_REGISTER_OFFSET 10
// Omron Plastic - Hub Register Mapping (Read mirror)
#define MB_R_VFD_STATE 4
#define MB_R_VFD_STATUS 3
#define MB_R_FREQ_TARGET 1
// Omron Plastic - Hub Coil Mapping (Write)
#define MB_W_VFD_RUN 5
#define MB_W_FREQ_TARGET 6
#define MB_W_DIRECTION 7
#define MB_R_PID_1_PV (MB_REGISTER_OFFSET) + 1
#define MB_R_PID_1_SP (MB_REGISTER_OFFSET) + 2
#define MB_R_PID_2_PV (MB_REGISTER_OFFSET) + 3
#define MB_R_PID_2_SP (MB_REGISTER_OFFSET) + 4
#define MB_R_PID_3_PV (MB_REGISTER_OFFSET) + 5
#define MB_R_PID_3_SP (MB_REGISTER_OFFSET) + 6
#define MB_W_PID_1_SP MB_REGISTER_OFFSET + 7
#define MB_W_PID_2_SP MB_REGISTER_OFFSET + 8
#define MB_W_PID_3_SP MB_REGISTER_OFFSET + 9
#define MB_QUERY_TYPE_STATUS_POLL 10
#define MB_QUERY_TYPE_CMD 100
#define OMRON_STATE_ACCELERATING 4
#define OMRON_STATE_DECELERATING 2
#define OMRON_STATE_RUNNING 3
#define OMRON_STATE_STOPPED 1
#define OMRON_STATE_ERROR 8
#define OMRON_STATUS_STOPPED 2
#define OMRON_STATUS_RUNNING 0
#endif

View File

@ -0,0 +1,113 @@
#ifndef FEATURES_H
#define FEATURES_H
#ifdef HAS_BRIDGE
#include "bridge.h"
#endif
#ifdef HAS_SERIAL
#include "serial.h"
#endif
#ifdef HAS_TEMPERTURE
#include "temperature.h"
#endif
#ifdef HAS_EXTRUDER_TEMPERATUR
#include "ex_temperature.h"
#endif
#ifdef HAS_SOUND
#include "alarm.h"
#endif
#ifdef HAS_HALL
#include "hall.h"
#endif
#ifdef HAS_STATUS
#include "addons/Status.h"
#endif
#ifdef HAS_RESET
#include "reset.h"
#endif
#ifdef HAS_AUTOREVERSE
#include "auto-reverse.h"
#ifdef HAS_IR
#include "IRSensor.h"
#endif
#endif
#if defined(ENCLOSURE_SENSOR_PIN_1) || defined(ENCLOSURE_SENSOR_PIN_2)
#include "EnclosureSensor.h"
#define HAS_ENCLOSURE_SENSOR
#endif
#if defined(POWER_0) || defined(POWER_1)
#include "addons/Power.h"
#define HAS_POWER
#endif
#ifdef MOTOR_LOAD_PIN
#include "addons/MotorLoad.h"
#endif
#ifdef MOTOR_HAS_TEMPERTURE
#include "addons/MotorTemperature.h"
#endif
#ifdef HAS_DIP
#include "addons/_DipSwitch.h"
#endif
#ifdef HAS_MOTOR_IR_SENSOR
#include "addons/MotorSpeed.h"
#endif
#if defined(OP_MODE_1_PIN)
#include "addons/OperationModeSwitch.h"
#define HAS_OP_MODE_SWITCH
#endif
#if defined(FWD_PIN) && defined(REV_PIN)
#include "addons/DirectionSwitch.h"
#define HAS_DIRECTION_SWITCH
#endif
#if defined(FWD_PIN) && defined(REV_PIN)
#include "VFD.h"
#define HAS_VFD
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Plastic Hub - Addons
//
// Plastic Hub Studio - remote control
#ifdef USE_FIRMATA
#include "firmata_link.h"
#endif
#ifdef HAS_PLUNGER
#include "Plunger.h"
#endif
#ifdef OMRON_MX2_SLAVE_ID
#include "OmronVFD.h"
#define HAS_MODBUS_BRIDGE
#define HAS_OMRON_VFD_MODBUS
#endif
#if defined(OMRON_PID_SLAVE_START)
#include "OmronPID.h"
#define HAS_MODBUS_BRIDGE
#endif
#ifdef HAS_MODBUS_BRIDGE
#include "ModbusBridge.h"
#endif
#endif

View File

@ -0,0 +1,11 @@
#include "app.h"
App app = App();
void setup(){
app.setup();
app.info();
}
void loop(){
app.loop();
}

View File

@ -0,0 +1,26 @@
{
"name": "@plastichub/hydra",
"version": "0.0.4",
"description": "Extruder Firmware with serial/modbus interface",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://gitlab.com/plastichub/hydra.git"
},
"keywords": [
"preciousplastic"
],
"author": "PlasticHub",
"license": "GPL-3.0-or-later",
"bugs": {
"url": "https://gitlab.com/plastichub/hydra/issues"
},
"homepage": "https://gitlab.com/plastichub/hydra#readme",
"dependencies": {
"@plastichub/fs": "^0.13.19",
"simple-git": "^1.131.0"
}
}

View File

@ -0,0 +1,93 @@
#include "ppmath_statistics.h"
Statistic::Statistic()
{
clear();
}
// resets all counters
void Statistic::clear()
{
_cnt = 0;
_sum = 0;
_min = 0;
_max = 0;
#ifdef STAT_USE_STDEV
_ssqdif = 0.0; // not _ssq but sum of square differences
// which is SUM(from i = 1 to N) of
// (f(i)-_ave_N)**2
#endif
}
// adds a new value to the data-set
void Statistic::add(const float value)
{
if (_cnt == 0)
{
_min = value;
_max = value;
}
else
{
if (value < _min)
_min = value;
else if (value > _max)
_max = value;
}
_sum += value;
_cnt++;
#ifdef STAT_USE_STDEV
if (_cnt > 1)
{
float _store = (_sum / _cnt - value);
_ssqdif = _ssqdif + _cnt * _store * _store / (_cnt - 1);
// ~10% faster but limits the amount of samples to 65K as _cnt*_cnt overflows
// float _store = _sum - _cnt * value;
// _ssqdif = _ssqdif + _store * _store / (_cnt*_cnt - _cnt);
}
#endif
}
// returns the average of the data-set added sofar
float Statistic::average() const
{
if (_cnt == 0)
return NAN; // original code returned 0
return _sum / _cnt;
}
// Population standard deviation = s = sqrt [ S ( Xi - <20> )2 / N ]
// http://www.suite101.com/content/how-is-standard-deviation-used-a99084
#ifdef STAT_USE_STDEV
float Statistic::variance() const
{
if (_cnt == 0)
return NAN; // otherwise DIV0 error
return _ssqdif / _cnt;
}
float Statistic::mean() const
{
if (_cnt == 0)
return NAN; // otherwise DIV0 error
return this->sum() / _cnt;
}
float Statistic::pop_stdev() const
{
if (_cnt == 0)
return NAN; // otherwise DIV0 error
return sqrt(_ssqdif / _cnt);
}
float Statistic::unbiased_stdev() const
{
if (_cnt < 2)
return NAN; // otherwise DIV0 error
return sqrt(_ssqdif / (_cnt - 1));
}
#endif
// END OF FILE

View File

@ -0,0 +1,112 @@
#ifndef PPMATH_STATISTICS_H
#define PPMATH_STATISTICS_H
#include <Arduino.h>
#include <math.h>
#define STAT_USE_STDEV
#ifdef __cplusplus
// C++11 solution that is standards compliant. Return type is deduced automatically
template <class L, class R>
static inline constexpr auto MIN(const L lhs, const R rhs) -> decltype(lhs + rhs)
{
return lhs < rhs ? lhs : rhs;
}
template <class L, class R>
static inline constexpr auto MAX(const L lhs, const R rhs) -> decltype(lhs + rhs)
{
return lhs > rhs ? lhs : rhs;
}
template <class T>
static inline constexpr const T ABS(const T v)
{
return v >= 0 ? v : -v;
}
#else
// Using GCC extensions, but Travis GCC version does not like it and gives
// "error: statement-expressions are not allowed outside functions nor in template-argument lists"
#define MIN(a, b) \
({__typeof__(a) _a = (a); \
__typeof__(b) _b = (b); \
_a < _b ? _a : _b; })
#define MAX(a, b) \
({__typeof__(a) _a = (a); \
__typeof__(b) _b = (b); \
_a > _b ? _a : _b; })
#define ABS(a) \
({__typeof__(a) _a = (a); \
_a >= 0 ? _a : -_a; })
#endif
class Statistic
{
public:
Statistic(); // "switches on/off" stdev run time
void clear(); // "switches on/off" stdev run time
void add(const float);
// returns the number of values added
uint32_t count() const { return _cnt; }; // zero if empty
float sum() const { return _sum; }; // zero if empty
float minimum() const { return _min; }; // zero if empty
float maximum() const { return _max; }; // zero if empty
float average() const; // NAN if empty
float mean() const; // zero if empty
#ifdef STAT_USE_STDEV
float variance() const; // NAN if empty
float pop_stdev() const; // population stdev // NAN if empty
float unbiased_stdev() const; // NAN if empty
#endif
protected:
uint32_t _cnt;
float _sum;
float _min;
float _max;
#ifdef STAT_USE_STDEV
float _ssqdif; // sum of squares difference
#endif
};
/**
* Returns the kth q-quantile.
* @link http://en.wikipedia.org/wiki/Quantile#Quantiles_of_a_population
* ie: median is 1st 2-quantile
* ie: upper quartile is 3rd 4-quantile
* @return {Number} q-quantile of values.
*/
/*
const quantile = (arr: number[], i: number, n: number) => {
if (i === 0) return Math.min.apply(null, arr);
if (i === n) return Math.max.apply(null, arr);
let sorted = arr.slice(0);
sorted.sort((a, b) => a - b);
let index = sorted.length * i / n;
if (index % 1 === 0) {
return 0.5 * sorted[index - 1] + 0.5 * sorted[index];
}
return sorted[~~index];
};
export const median = (arr: number[]) => quantile(arr, 1, 2);
export const sum = (arr: number[]) => arr.reduce((a, b) => a + b, 0);
export const mean = (arr: number[]) => sum(arr) / arr.length;
// sqare errors along mean
const sdiff = (arr: number[], mean: number) => arr.map((v) => Math.pow(v - mean, 2));
export const standardDeviation = (arr: number[]) => Math.sqrt(mean(sdiff(arr, mean(arr))));
*/
#endif

View File

@ -0,0 +1,127 @@
#include "serial.h"
#include <Streaming.h>
#include <Vector.h>
#include "bridge.h"
#include "common/macros.h"
#define START_STR "<<"
#define END_STR ">>"
#define START_LENGTH 2
#define END_LENGTH 2
#define SPLIT_STR ";"
static PPSerial::Message *_messages[10];
short PPSerial::setup()
{
messages.setStorage(_messages);
}
short PPSerial::loop()
{
}
PPSerial::Message *PPSerial::parse(const char *string)
{
Message *msg = new Message(1, 2, 0, 3);
const char *strings[5];
char *ptr = NULL;
byte index = 0;
ptr = strtok(string, SPLIT_STR);
while (ptr != NULL && index < 5)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, SPLIT_STR);
}
msg->id = atoi(strings[0]);
msg->verb = atoi(strings[1]);
msg->flags = atoi(strings[2]);
msg->flags = SBI(msg->flags, Bridge::NEW);
msg->version = atoi(strings[3]);
msg->payload = strings[4];
return msg;
}
void PPSerial::readMessages()
{
while (stream.available())
{
String message = stream.readString();
message.trim();
if (message.startsWith(START_STR) && message.endsWith(END_STR))
{
String data = message.substring(START_LENGTH, message.length() - END_LENGTH);
char *ptr = NULL;
byte index = 0;
ptr = strtok(data.c_str(), '\n');
while (ptr != NULL && index < 5)
{
if (strlen(ptr) > 4)
{
Message *msg = parse(String(ptr).c_str());
if (msg != NULL)
{
messages.push_back(msg);
}
}
index++;
ptr = strtok(NULL, '\n');
}
}
}
}
PPSerial::Message *PPSerial::read()
{
/*
readMessages();
Message *m = messages.at(0);
if (m != NULL && messages.size())
{
messages.remove(0);
return m;
}
return NULL;
*/
while (stream.available())
{
String message = stream.readString();
message.trim();
if (message.startsWith(START_STR) && message.endsWith(END_STR))
{
msg->payload = NULL;
String data = message.substring(START_LENGTH, message.length() - END_LENGTH);
const char *strings[5];
char *ptr = NULL;
byte index = 0;
ptr = strtok(data.c_str(), SPLIT_STR);
while (ptr != NULL && index < 5)
{
strings[index] = ptr;
index++;
ptr = strtok(NULL, SPLIT_STR);
}
msg->id = atoi(strings[0]);
msg->verb = atoi(strings[1]);
msg->flags = atoi(strings[2]);
msg->version = atoi(strings[3]);
msg->payload = strings[4];
return msg;
}
else
{
Serial.print(message);
Serial.println(" : invalid message");
}
}
return NULL;
}

View File

@ -0,0 +1,47 @@
#ifndef PPSERIAL_H
#define PPSERIAL_H
#include <Streaming.h>
#include "Addon.h"
// Message struct: << id,verb,flags,version,payload >>
// Example :<<1;2;0;1;Power:on:1>>
class PPSerial : public Addon
{
public:
PPSerial(Stream &_stream) : stream(_stream),
Addon("Serial", SERIAL_BRIDGE),
msg(new Message(0, 0, 0, 0))
{
flags = 0;
}
struct Message
{
public:
int id;
uchar verb;
int flags;
uchar version;
char *payload;
millis_t ts;
Message(int _id, int _verb, int _flags, int _version) : id(_id),
verb(_verb),
flags(_flags),
version(_version) {}
};
short loop();
Message *read();
Message *msg;
Message *parse(const char *string);
Vector<Message *> messages;
void readMessages();
short setup();
protected:
Stream &stream;
};
#endif

View File

@ -0,0 +1,11 @@
#ifndef TYPES_H
#define TYPES_H
#include <stdint.h>
typedef unsigned long millis_t;
typedef unsigned short ushort;
typedef unsigned char uchar;
#endif

View File

@ -0,0 +1,4 @@
#ifndef USER_CONFIG_H
#define USER_CONFIG_H
#endif

View File

@ -0,0 +1,88 @@
/**
@file
CRC Computations
@defgroup util_crc16 "util/crc16.h": CRC Computations
@code#include "util/crc16.h"@endcode
This header file provides functions for calculating
cyclic redundancy checks (CRC) using common polynomials.
Modified by Doc Walker to be processor-independent (removed inline
assembler to allow it to compile on SAM3X8E processors).
@par References:
Jack Crenshaw's "Implementing CRCs" article in the January 1992 issue of @e
Embedded @e Systems @e Programming. This may be difficult to find, but it
explains CRC's in very clear and concise terms. Well worth the effort to
obtain a copy.
*/
/* Copyright (c) 2002, 2003, 2004 Marek Michalkiewicz
Copyright (c) 2005, 2007 Joerg Wunsch
Copyright (c) 2013 Dave Hylands
Copyright (c) 2013 Frederic Nadeau
Copyright (c) 2015 Doc Walker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name of the copyright holders nor the names of
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE. */
#ifndef _UTIL_CRC16_H_
#define _UTIL_CRC16_H_
/** @ingroup util_crc16
Processor-independent CRC-16 calculation.
Polynomial: x^16 + x^15 + x^2 + 1 (0xA001)<br>
Initial value: 0xFFFF
This CRC is normally used in disk-drive controllers.
@param uint16_t crc (0x0000..0xFFFF)
@param uint8_t a (0x00..0xFF)
@return calculated CRC (0x0000..0xFFFF)
*/
uint16_t crc16_update(uint16_t crc, uint8_t a);
/*{
int i;
crc ^= a;
for (i = 0; i < 8; ++i)
{
if (crc & 1)
crc = (crc >> 1) ^ 0xA001;
else
crc = (crc >> 1);
}
return crc;
}
*/
#endif /* _UTIL_CRC16_H_ */

View File

@ -0,0 +1,64 @@
/**
@file
Utility Functions for Manipulating Words
@defgroup util_word "util/word.h": Utility Functions for Manipulating Words
@code#include "util/word.h"@endcode
This header file provides utility functions for manipulating words.
*/
/*
word.h - Utility Functions for Manipulating Words
This file is part of ModbusMaster.
ModbusMaster is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ModbusMaster is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with ModbusMaster. If not, see <http://www.gnu.org/licenses/>.
Written by Doc Walker (Rx)
Copyright © 2009-2015 Doc Walker <4-20ma at wvfans dot net>
*/
#ifndef _UTIL_WORD_H_
#define _UTIL_WORD_H_
/** @ingroup util_word
Return low word of a 32-bit integer.
@param uint32_t ww (0x00000000..0xFFFFFFFF)
@return low word of input (0x0000..0xFFFF)
*/
static inline uint16_t lowWord(uint32_t ww)
{
return (uint16_t) ((ww) & 0xFFFF);
}
/** @ingroup util_word
Return high word of a 32-bit integer.
@param uint32_t ww (0x00000000..0xFFFFFFFF)
@return high word of input (0x0000..0xFFFF)
*/
static inline uint16_t highWord(uint32_t ww)
{
return (uint16_t) ((ww) >> 16);
}
#endif /* _UTIL_WORD_H_ */

View File

@ -0,0 +1,32 @@
const read = require('@plastichub/fs/read');
const write = require('@plastichub/fs/write');
const path = require('path');
const cwd = path.resolve('../../');
const pkgVersion = read.sync('package.json', 'json').version;
async function status(workingDir) {
const git = require('simple-git/promise');
let statusSummary = null;
try {
statusSummary = await git(workingDir).log();
}
catch (e) {
// handle the error
}
return statusSummary;
}
status(cwd).then((status) => {
const version =
`#ifndef VERSION_H \n
#define VERSION_H \n
#define VERSION '${pkgVersion}|${status.latest.hash}'\n
#endif`;
write.sync('./Version.h', version);
console.log(version);
}
);

View File

@ -0,0 +1,42 @@
# Logs
logs
*.log
npm-debug.log*
yarn.lock
yarn-error.log
credentials.json
gcreds.json
token.json
# Runtime data
pids
*.pid
*.seed
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules
jspm_packages
# Optional npm cache directory
.npm
# Optional REPL history
.node_repl_history

View File

@ -0,0 +1,5 @@
datasets
gcreds.json
xcredentials.json
tests
src

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,35 @@
# Precious Plastic Command Line Tools
## Requirments
- Please install [NodeJS](https://nodejs.org/en/download/)
## Optional requirements
- [GhostScript](https://www.ghostscript.com/download/gsdnld.html) (needed for converting PDF to JPG)
- [Imagick](https://imagemagick.org/script/download.php) (needed for resizing images)
- [PP Open Factory](https://gitlab.com/plastichub/factory) (needed for templates)
- [Your product folder](https://gitlab.com/plastichub/products) (needed to generate documentation and creating Bazar descriptions)
<hr/>
## Todos
## Conversions
- v3 forum to local MD
- [x] BOM to pretty local MD
- SVG annotation parser (schematic documentation)
### Infrastructure
- [x] cs-cart docker image for previews via API
- [x] github issue collector
- [x] onarmy crawler (->manuals,..)
- [ ] video converter & publisher for assembly animations (mark snapshots for manuals)
### Discord Bot
- [ ] to HTML
- [ ] Link collector & Verifier/Rating (as lib)

View File

@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defaults = void 0;
// tweaks and handlers
exports.defaults = () => {
// default command
const DefaultCommand = 'summary';
if (process.argv.length === 2) {
process.argv.push(DefaultCommand);
}
// currently no default handler, display only :
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection, reason: ', reason);
});
};
//# sourceMappingURL=_cli.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"_cli.js","sourceRoot":"","sources":["../src/_cli.ts"],"names":[],"mappings":";;;AAAA,sBAAsB;AACT,QAAA,QAAQ,GAAG,GAAG,EAAE;IACzB,kBAAkB;IAClB,MAAM,cAAc,GAAG,SAAS,CAAC;IACjC,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,EAAE;QAC3B,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;KACrC;IAED,+CAA+C;IAC/C,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,MAAc,EAAE,EAAE;QAChD,OAAO,CAAC,KAAK,CAAC,+BAA+B,EAAE,MAAM,CAAC,CAAC;IAC3D,CAAC,CAAC,CAAC;AACP,CAAC,CAAC"}

View File

@ -0,0 +1,66 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.register = void 0;
const debug = require("../../log");
// Programmer for E5DC-QX2ASM-002 Omron
/**
*
* @link Modbus Docs https://www.npmjs.com/package/modbus-serial
*
* @link Serial Port CLI https://serialport.io/docs/guide-cli
*/
const defaultOptions = (yargs) => {
return yargs.option('port', {
default: 'COM7',
describe: 'serial port'
});
};
let options = (yargs) => defaultOptions(yargs);
// npm run build ; node ./build/main.js pid:program
exports.register = (cli) => {
return cli.command('pid:program', 'Omron PID programmer', options, (argv) => __awaiter(void 0, void 0, void 0, function* () {
if (argv.help) {
return;
}
const port = argv.port;
/*
const sp = new SerialPort(port,{ baudRate: 256000,parity:'even', dataBits:8 });
parser.on('data', line => console.log(`> ${line}`))*/
const ModbusRTU = require("modbus-serial");
const client = new ModbusRTU();
function end() {
console.log('read registers');
client.close();
}
function read() {
client.setID(1);
// on device number 1.
console.log('read registers');
// 01 03 00 00 00 02 C4 0B
client.readHoldingRegisters(2, 0).then((v) => {
console.log('v', v);
end();
});
}
function write() {
console.log('write registers');
// 01 03 20 00 00 01 8FCA
// write the values 0, 0xffff to registers starting at address 0
// on device number 1.
// client.writeRegisters(1, [0]).then(read);
}
debug.info(`Connecting to ${argv.port}`);
// open connection to a serial port
client.connectRTU(argv.port, { baudRate: 9600, parity: 'even' }, read);
}));
};
//# sourceMappingURL=program.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"program.js","sourceRoot":"","sources":["../../../src/commands/pid/program.ts"],"names":[],"mappings":";;;;;;;;;;;;AACA,mCAAmC;AAWnC,uCAAuC;AAEvC;;;;;GAKG;AAGH,MAAM,cAAc,GAAG,CAAC,KAAe,EAAE,EAAE;IACvC,OAAO,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE;QACxB,OAAO,EAAE,MAAM;QACf,QAAQ,EAAE,aAAa;KAC1B,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,IAAI,OAAO,GAAG,CAAC,KAAe,EAAE,EAAE,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;AAEzD,oDAAoD;AACvC,QAAA,QAAQ,GAAG,CAAC,GAAa,EAAE,EAAE;IACtC,OAAO,GAAG,CAAC,OAAO,CAAC,aAAa,EAAE,sBAAsB,EAAE,OAAO,EAAE,CAAO,IAAmB,EAAE,EAAE;QAC7F,IAAI,IAAI,CAAC,IAAI,EAAE;YAAE,OAAO;SAAE;QAG1B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAc,CAAC;QAGjC;;6DAEqD;QACrD,MAAM,SAAS,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;QAC3C,MAAM,MAAM,GAAG,IAAI,SAAS,EAAE,CAAC;QAG/B,SAAS,GAAG;YACR,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;YAC9B,MAAM,CAAC,KAAK,EAAE,CAAC;QACnB,CAAC;QAGD,SAAS,IAAI;YACT,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAChB,sBAAsB;YACtB,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAC;YAC9B,0BAA0B;YAE1B,MAAM,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EACvC,EAAE;gBACA,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC;gBACpB,GAAG,EAAE,CAAC;YACV,CAAC,CAAC,CAAC;QACP,CAAC;QAED,SAAS,KAAK;YAGV,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC;YAC/B,yBAAyB;YACzB,gEAAgE;YAChE,sBAAsB;YACtB,4CAA4C;QAChD,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,iBAAiB,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;QACzC,mCAAmC;QACnC,MAAM,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,CAAC,CAAC;IAC3E,CAAC,CAAA,CAAC,CAAC;AACP,CAAC,CAAC"}

View File

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.render = void 0;
const types_1 = require("./types");
const log_1 = require("./log");
exports.render = (result, options) => {
switch (options.format) {
case types_1.OutputFormat.text: {
//@TODO: human readable format
return JSON.stringify(result, null, 2);
}
case types_1.OutputFormat.json: {
return JSON.stringify(result, null, 2);
}
default: {
//private, should never happen since options had to be sanitized
log_1.error('format::render Invalid value in options.format');
return '';
}
}
};
//# sourceMappingURL=format.js.map

Some files were not shown because too many files have changed in this diff Show More