├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── ethercat-derive ├── Cargo.toml └── src │ └── lib.rs ├── ethercat-plc ├── Cargo.toml └── src │ ├── beckhoff.rs │ ├── image.rs │ ├── lib.rs │ ├── mlz_spec.rs │ ├── plc.rs │ └── server.rs └── src ├── io_demo.rs └── magnet_demo.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | 3 | [package] 4 | name = "ethercat-testplc" 5 | version = "0.1.4" 6 | authors = ["Georg Brandl "] 7 | edition = "2021" 8 | 9 | [[bin]] 10 | name = "magnet_demo" 11 | path = "src/magnet_demo.rs" 12 | 13 | [[bin]] 14 | name = "io_demo" 15 | path = "src/io_demo.rs" 16 | 17 | [dependencies] 18 | byteorder = "1.3" 19 | ethercat = "0.3.0" 20 | ethercat-plc = { path = "ethercat-plc" } 21 | ethercat-derive = { path = "ethercat-derive" } 22 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 The Rust Project Developers 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # The `ethercat-plc` crate 2 | 3 | [![Apache 2.0 licensed](https://img.shields.io/badge/license-Apache2.0-blue.svg)](./LICENSE-APACHE) 4 | [![MIT licensed](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE-MIT) 5 | [![crates.io](http://meritbadge.herokuapp.com/ethercat-plc)](https://crates.io/crates/ethercat-plc) 6 | [![docs](https://docs.rs/ethercat-plc/badge.svg)](https://docs.rs/ethercat-plc) 7 | 8 | ## About 9 | 10 | **Note: the crates in this repository are experimental.** 11 | 12 | The `ethercat-plc` crate builds on the [`ethercat` 13 | crate](https://github.com/ethercat-rs/ethercat) and tries to provide building 14 | blocks for writing PLC like applications in Rust, talking to EtherCAT slaves. 15 | 16 | ## Building 17 | 18 | The main EtherCAT functionality builds on the IgH/Etherlab [EtherCAT Master for 19 | Linux](https://etherlab.org/en/ethercat/). 20 | 21 | The IgH repository is located at . 22 | Please switch to the ``stable-1.5`` branch in the checkout. 23 | 24 | In order to build the raw wrapper crate `ethercat-sys`, you need to set the 25 | environment variable `ETHERCAT_PATH` to the location of a checkout of the IgH 26 | Etherlab repository, *after running `configure` there*. 27 | 28 | The minimum tested Rust version is 1.63.0. 29 | 30 | ## Licensing 31 | 32 | This crate uses the dual MIT/Apache-2 license commonly used for Rust crates. 33 | -------------------------------------------------------------------------------- /ethercat-derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ethercat-derive" 3 | description = "Automatic deriving of traits in the ethercat-plc crate" 4 | readme = "../README.md" 5 | version = "0.2.0" 6 | authors = ["Georg Brandl "] 7 | license = "MIT/Apache-2.0" 8 | edition = "2021" 9 | 10 | [lib] 11 | proc-macro = true 12 | 13 | [dependencies] 14 | quote = "1.0" 15 | syn = "1.0" 16 | proc-macro2 = "1.0" 17 | -------------------------------------------------------------------------------- /ethercat-derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | //! Support for deriving ethercat-plc traits for a struct. 5 | 6 | extern crate proc_macro; // needed even in 2018 7 | 8 | use self::proc_macro::TokenStream; 9 | use syn::parse_macro_input; 10 | use proc_macro2::TokenStream as TokenStream2; 11 | use quote::quote; 12 | use quote::ToTokens; 13 | 14 | 15 | #[proc_macro_derive(SlaveProcessImage, attributes(pdos, watchdog, dc, entry, no_arrays))] 16 | pub fn derive_single_process_image(input: TokenStream) -> TokenStream { 17 | let input = parse_macro_input!(input as syn::DeriveInput); 18 | let ident = input.ident; 19 | 20 | let id_str = ident.to_string(); 21 | let slave_id = if id_str.starts_with("EK") { 22 | let nr = id_str[2..6].parse::().unwrap(); 23 | quote!(ethercat::SlaveId { vendor_id: 2, product_code: (#nr << 16) | 0x2c52 }) 24 | } else if id_str.starts_with("EL") { 25 | let nr = id_str[2..6].parse::().unwrap(); 26 | quote!(ethercat::SlaveId { vendor_id: 2, product_code: (#nr << 16) | 0x3052 }) 27 | } else { 28 | panic!("cannot interpret struct name '{}' into a slave ID", id_str); 29 | }; 30 | 31 | let mut sync_infos = vec![]; 32 | let mut wd_config = quote!(None); 33 | let mut dc_config = quote!(None); 34 | let mut pdo_regs = vec![]; 35 | let mut running_size = 0usize; 36 | let mut pdo_mapping = std::collections::HashMap::new(); 37 | 38 | if let syn::Data::Struct(syn::DataStruct { 39 | fields: syn::Fields::Named(flds), .. 40 | }) = input.data { 41 | for field in flds.named { 42 | let ty = field.ty.into_token_stream().to_string(); 43 | let bitlen = match &*ty { 44 | "u8" | "i8" => 8, 45 | "u16" | "i16" => 16, 46 | "u32" | "i32" | "f32" => 32, 47 | "u64" | "i64" | "f64" => 64, 48 | _ => panic!("cannot handle type '{}' in image", ty) 49 | }; 50 | for attr in &field.attrs { 51 | if attr.path.is_ident("entry") { 52 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 53 | attr.parse_meta().unwrap() 54 | { 55 | let (pdo_str, ix, subix) = if nested.len() == 2 { 56 | ("".into(), &nested[0], &nested[1]) 57 | } else { 58 | let pdo = &nested[0]; 59 | (quote!(#pdo).to_string(), &nested[1], &nested[2]) 60 | }; 61 | pdo_regs.push(quote! { 62 | (ethercat::PdoEntryIdx { idx: ethercat::Idx::from(#ix), 63 | sub_idx: ethercat::SubIdx::from(#subix) }, 64 | ethercat::Offset { byte: #running_size, bit: 0 }) 65 | }); 66 | pdo_mapping.entry(pdo_str).or_insert_with(Vec::new).push(quote! { 67 | ethercat::PdoEntryInfo { 68 | entry_idx: ethercat::PdoEntryIdx { 69 | idx: ethercat::Idx::from(#ix), 70 | sub_idx: ethercat::SubIdx::from(#subix) 71 | }, 72 | bit_len: #bitlen as u8, 73 | name: String::new(), 74 | pos: ethercat::PdoEntryPos::from(0), // unused 75 | } 76 | }); 77 | } 78 | } 79 | } 80 | running_size += bitlen / 8; 81 | } 82 | } else { 83 | panic!("SlaveProcessImage must be a struct with named fields"); 84 | } 85 | 86 | let mut no_arrays = false; 87 | for attr in &input.attrs { 88 | if attr.path.is_ident("no_arrays") { 89 | no_arrays = true; 90 | } else if attr.path.is_ident("pdos") { 91 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 92 | attr.parse_meta().unwrap() 93 | { 94 | let sm = &nested[0]; 95 | let sd = &nested[1]; 96 | let mut pdos = vec![]; 97 | for pdo_index in nested.iter().skip(2) { 98 | let pdo_str = quote!(#pdo_index).to_string(); 99 | let entries = &pdo_mapping.get(&pdo_str).map_or(&[][..], |v| v); 100 | pdos.push(quote! { 101 | ethercat::PdoCfg { 102 | idx: ethercat::PdoIdx::from(#pdo_index), 103 | entries: vec![#( #entries ),*] 104 | } 105 | }) 106 | } 107 | sync_infos.push(quote! { 108 | ( 109 | ethercat::SmCfg { 110 | idx: ethercat::SmIdx::from(#sm), 111 | direction: ethercat::SyncDirection::#sd, 112 | watchdog_mode: ethercat::WatchdogMode::Default, 113 | }, 114 | vec![#( #pdos ),*] 115 | ) 116 | }); 117 | } 118 | } else if attr.path.is_ident("watchdog") { 119 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 120 | attr.parse_meta().unwrap() 121 | { 122 | let a = &nested[0]; 123 | let b = &nested[1]; 124 | wd_config = quote!( Some((#a, #b)) ); 125 | } 126 | } else if attr.path.is_ident("dc") { 127 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 128 | attr.parse_meta().unwrap() 129 | { 130 | let a = &nested[0]; 131 | let b = &nested[1]; 132 | let c = &nested[2]; 133 | let d = &nested[3]; 134 | let e = &nested[4]; 135 | dc_config = quote!( Some((#a, #b, #c, #d, #e)) ); 136 | } 137 | } 138 | } 139 | 140 | let sync_infos = if sync_infos.is_empty() { 141 | quote!(None) 142 | } else { 143 | quote!(Some(vec![#( #sync_infos ),*])) 144 | }; 145 | 146 | let mut generated = quote! { 147 | #[automatically_derived] 148 | impl ProcessImage for #ident { 149 | const SLAVE_COUNT: usize = 1; 150 | fn get_slave_ids() -> Vec { vec![#slave_id] } 151 | fn get_slave_pdos() -> Vec)>>> { 152 | vec![#sync_infos] 153 | } 154 | fn get_slave_regs() -> Vec> { 155 | vec![vec![ #( #pdo_regs ),* ]] 156 | } 157 | fn get_slave_wd_dc() -> Vec<(Option<(u16, u16)>, Option<(u16, u32, i32, u32, i32)>)> { 158 | vec![(#wd_config, #dc_config)] 159 | } 160 | } 161 | }; 162 | 163 | if !no_arrays { 164 | generated = quote! { 165 | #generated 166 | 167 | macro_rules! impl_it { 168 | ($n:literal) => { 169 | impl ProcessImage for [#ident; $n] { 170 | const SLAVE_COUNT: usize = $n; 171 | fn get_slave_ids() -> Vec { vec![#slave_id; $n] } 172 | fn get_slave_pdos() -> Vec)>>> { 173 | vec![#sync_infos; $n] 174 | } 175 | fn get_slave_regs() -> Vec> { 176 | vec![vec![ #( #pdo_regs ),* ]; $n] 177 | } 178 | fn get_slave_wd_dc() -> Vec<(Option<(u16, u16)>, Option<(u16, u32, i32, u32, i32)>)> { 179 | vec![(#wd_config, #dc_config); $n] 180 | } 181 | } 182 | }; 183 | } 184 | 185 | impl_it!(2); 186 | impl_it!(3); 187 | impl_it!(4); 188 | impl_it!(5); 189 | impl_it!(6); 190 | impl_it!(7); 191 | impl_it!(8); 192 | }; 193 | } 194 | 195 | // println!("{}", generated); 196 | generated.into() 197 | } 198 | 199 | 200 | fn sdo_extract(ix: &syn::NestedMeta, subix: &syn::NestedMeta, val: &syn::NestedMeta, 201 | complete: bool, sdos: &mut Vec) { 202 | match val { 203 | syn::NestedMeta::Lit(syn::Lit::Str(s)) => { 204 | let data_str = syn::parse_str::(&s.value()).unwrap(); 205 | sdos.push(quote! { 206 | (ethercat::SdoIdx { idx: ethercat::Idx::from(#ix), 207 | sub_idx: ethercat::SubIdx::from(#subix) }, 208 | #complete, 209 | &#data_str) 210 | }); 211 | } 212 | syn::NestedMeta::Meta(syn::Meta::Path(p)) => { 213 | sdos.push(quote! { 214 | (ethercat::SdoIdx { idx: ethercat::Idx::from(#ix), 215 | sub_idx: ethercat::SubIdx::from(#subix) }, 216 | #complete, 217 | { 218 | match cfg.get_sdo_var(stringify!(#p)) { 219 | None => panic!(concat!("required config value ", 220 | stringify!(#p), " not given")), 221 | Some(x) => x 222 | } 223 | }) 224 | }); 225 | } 226 | _ => panic!("invalid SDO value, must be a string or identifier"), 227 | }; 228 | } 229 | 230 | 231 | #[proc_macro_derive(ProcessImage, attributes(slave_id, sdo, array_sdo, complete_sdo))] 232 | pub fn derive_process_image(input: TokenStream) -> TokenStream { 233 | let input = parse_macro_input!(input as syn::DeriveInput); 234 | let ident = input.ident; 235 | 236 | let mut slave_sdos = vec![]; 237 | let mut slave_tys = vec![]; 238 | let mut slave_ids = vec![]; 239 | 240 | if let syn::Data::Struct(syn::DataStruct { 241 | fields: syn::Fields::Named(flds), .. 242 | }) = input.data { 243 | for field in flds.named { 244 | let mut single_sdos = vec![]; 245 | let mut array_sdos = vec![]; 246 | let mut id = None; 247 | for attr in &field.attrs { 248 | if attr.path.is_ident("sdo") { 249 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 250 | attr.parse_meta().unwrap() 251 | { 252 | sdo_extract(&nested[0], &nested[1], &nested[2], false, &mut single_sdos); 253 | } 254 | } else if attr.path.is_ident("complete_sdo") { 255 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 256 | attr.parse_meta().unwrap() 257 | { 258 | sdo_extract(&nested[0], &nested[1], &nested[2], true, &mut single_sdos); 259 | } 260 | } else if attr.path.is_ident("array_sdo") { 261 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 262 | attr.parse_meta().unwrap() 263 | { 264 | let ix: usize = match &nested[0] { 265 | syn::NestedMeta::Lit(syn::Lit::Int(lit)) => lit.base10_parse().unwrap(), 266 | _ => panic!("invalid sdo_array index") 267 | }; 268 | if array_sdos.len() < ix + 1 { 269 | array_sdos.resize(ix + 1, vec![]); 270 | } 271 | sdo_extract(&nested[1], &nested[2], &nested[3], false, &mut array_sdos[ix]); 272 | } 273 | } else if attr.path.is_ident("slave_id") { 274 | if let syn::Meta::List(syn::MetaList { nested, .. }) = 275 | attr.parse_meta().unwrap() 276 | { 277 | if let syn::NestedMeta::Lit(syn::Lit::Int(p)) = &nested[0] { 278 | id = Some(quote!( 279 | vec![ethercat::SlaveId { vendor_id: 2, product_code: (#p << 16) | 0x3052 }] 280 | )); 281 | } 282 | } 283 | } 284 | } 285 | let ty = field.ty; 286 | if !array_sdos.is_empty() { 287 | for single in array_sdos { 288 | slave_sdos.push(quote!( res.push(vec![#( #single ),*]); )); 289 | } 290 | } else if !single_sdos.is_empty() { 291 | slave_sdos.push(quote!( res.push(vec![#( #single_sdos ),*]); )); 292 | } else { 293 | slave_sdos.push(quote!( res.extend(#ty::get_slave_sdos(&())); )); 294 | } 295 | let id = id.unwrap_or(quote!( <#ty>::get_slave_ids() )); 296 | slave_tys.push(ty); 297 | slave_ids.push(id); 298 | } 299 | } else { 300 | return compile_error("only structs with named fields can be a process image"); 301 | } 302 | 303 | let generated = quote! { 304 | #[automatically_derived] 305 | impl ProcessImage for #ident { 306 | const SLAVE_COUNT: usize = #( <#slave_tys>::SLAVE_COUNT )+*; 307 | fn get_slave_ids() -> Vec { 308 | let mut res = vec![]; #( res.extend(#slave_ids); )* res 309 | } 310 | fn get_slave_pdos() -> Vec)>>> { 311 | let mut res = vec![]; #( res.extend(<#slave_tys>::get_slave_pdos()); )* res 312 | } 313 | fn get_slave_regs() -> Vec> { 314 | let mut res = vec![]; #( res.extend(<#slave_tys>::get_slave_regs()); )* res 315 | } 316 | fn get_slave_wd_dc() -> Vec<(Option<(u16, u16)>, Option<(u16, u32, i32, u32, i32)>)> { 317 | let mut res = vec![]; #( res.extend(<#slave_tys>::get_slave_wd_dc()); )* res 318 | } 319 | fn get_slave_sdos(cfg: &C) -> 320 | Vec> 321 | { 322 | let mut res = vec![]; #(#slave_sdos)* res 323 | } 324 | } 325 | }; 326 | 327 | // println!("{}", generated); 328 | generated.into() 329 | } 330 | 331 | #[proc_macro_derive(ExternImage, attributes(plc))] 332 | pub fn derive_extern_image(input: TokenStream) -> TokenStream { 333 | let input = parse_macro_input!(input as syn::DeriveInput); 334 | let ident = input.ident; 335 | 336 | // currently a no-op, later: auto-generate Default from #[plc] attributes 337 | let generated = quote! { 338 | impl ExternImage for #ident {} 339 | }; 340 | generated.into() 341 | } 342 | 343 | fn compile_error(message: impl Into) -> TokenStream { 344 | let message = message.into(); 345 | quote!(compile_error! { #message }).into() 346 | } 347 | -------------------------------------------------------------------------------- /ethercat-plc/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "ethercat-plc" 3 | description = "Tools to build a PLC like program using the ethercat crate" 4 | readme = "../README.md" 5 | keywords = ["ethercat", "plc", "automation"] 6 | version = "0.2.1" 7 | authors = ["Georg Brandl "] 8 | license = "MIT/Apache-2.0" 9 | edition = "2021" 10 | 11 | [dependencies] 12 | log = "0.4.6" 13 | libc = "0.2.49" 14 | mlzlog = "0.8.1" 15 | byteorder = "1.3.1" 16 | crossbeam-channel = "0.5.8" 17 | anyhow = "1.0" 18 | ethercat = "0.3.0" 19 | ethercat-derive = { path = "../ethercat-derive", version = "0.2.0" } 20 | -------------------------------------------------------------------------------- /ethercat-plc/src/beckhoff.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | use ethercat_derive::SlaveProcessImage; 5 | use crate::image::ProcessImage; 6 | 7 | #[repr(C, packed)] 8 | #[derive(SlaveProcessImage, Default)] 9 | pub struct EK1100 {} 10 | 11 | #[repr(C, packed)] 12 | #[derive(SlaveProcessImage, Default)] 13 | pub struct EK1110 {} 14 | 15 | #[repr(C, packed)] 16 | #[derive(SlaveProcessImage, Default)] 17 | pub struct EK1818 { 18 | #[entry(0x6000, 1)] pub input: u8, 19 | #[entry(0x7000, 1)] pub output: u8, 20 | } 21 | 22 | #[repr(C, packed)] 23 | #[derive(SlaveProcessImage, Default)] 24 | pub struct EL1008 { 25 | #[entry(0x6000, 1)] pub input: u8, 26 | } 27 | 28 | #[repr(C, packed)] 29 | #[derive(SlaveProcessImage, Default)] 30 | pub struct EL1034 { 31 | #[entry(0x6000, 1)] pub input: u8, 32 | } 33 | 34 | #[repr(C, packed)] 35 | #[derive(SlaveProcessImage, Default)] 36 | pub struct EL1018 { 37 | #[entry(0x6000, 1)] pub input: u8, 38 | } 39 | 40 | #[repr(C, packed)] 41 | #[derive(SlaveProcessImage, Default)] 42 | #[pdos(3, Input, 0x1A00, 0x1A01)] 43 | #[pdos(2, Output, 0x1600, 0x1601)] 44 | pub struct EL1502 { 45 | #[entry(0x1A00, 0x6000, 1)] pub status_ch1: u16, 46 | #[entry(0x1A00, 0x6000, 17)] pub value_ch1: u32, 47 | #[entry(0x1A01, 0x6010, 1)] pub status_ch2: u16, 48 | #[entry(0x1A01, 0x6010, 17)] pub value_ch2: u32, 49 | 50 | #[entry(0x1600, 0x7000, 1)] pub control_ch1: u16, 51 | #[entry(0x1600, 0x7000, 17)] pub setvalue_ch1: u32, 52 | #[entry(0x1601, 0x7010, 1)] pub control_ch2: u16, 53 | #[entry(0x1601, 0x7010, 17)] pub setvalue_ch2: u32, 54 | } 55 | 56 | #[repr(C, packed)] 57 | #[derive(SlaveProcessImage, Default)] 58 | #[pdos(3, Input, 0x1A02)] 59 | #[pdos(2, Output, 0x1602)] 60 | #[allow(non_camel_case_types)] 61 | pub struct EL1502_UpDown { 62 | #[entry(0x1A02, 0x6020, 1)] pub status: u16, 63 | #[entry(0x1A02, 0x6020, 17)] pub value: u32, 64 | 65 | #[entry(0x1602, 0x7020, 1)] pub control: u16, 66 | #[entry(0x1602, 0x7020, 17)] pub setvalue: u32, 67 | } 68 | 69 | #[repr(C, packed)] 70 | #[derive(SlaveProcessImage, Default)] 71 | pub struct EL1859 { 72 | #[entry(0x6000, 1)] pub input: u8, 73 | #[entry(0x7080, 1)] pub output: u8, 74 | } 75 | 76 | #[repr(C, packed)] 77 | #[derive(SlaveProcessImage, Default)] 78 | pub struct EL2008 { 79 | #[entry(0x7000, 1)] pub output: u8, 80 | } 81 | 82 | #[repr(C, packed)] 83 | #[derive(SlaveProcessImage, Default)] 84 | #[pdos(3, Input, 0x1A00, 0x1A02)] 85 | #[pdos(2, Output, 0x1600, 0x1601)] 86 | pub struct EL2535 { 87 | #[entry(0x1A00, 0x6000, 1)] pub state_ch1: u16, 88 | #[entry(0x1A02, 0x6010, 1)] pub state_ch2: u16, 89 | 90 | #[entry(0x1600, 0x7000, 1)] pub control_ch1: u16, 91 | #[entry(0x1600, 0x7000, 0x11)] pub output_ch1: u16, 92 | #[entry(0x1601, 0x7010, 1)] pub control_ch2: u16, 93 | #[entry(0x1601, 0x7010, 0x11)] pub output_ch2: u16, 94 | } 95 | 96 | #[repr(C, packed)] 97 | #[derive(SlaveProcessImage, Default)] 98 | #[pdos(3, Input, 0x1A00)] 99 | #[pdos(2, Output, 0x1600)] 100 | #[allow(non_camel_case_types)] 101 | pub struct EL2574_1Ch { 102 | #[entry(0x1A00, 0x6000, 1)] pub ch1_status: u16, 103 | 104 | #[entry(0x1600, 0x7000, 1)] pub ch1_control: u8, 105 | #[entry(0x1600, 0x7000, 9)] pub ch1_command: u16, 106 | #[entry(0x1600, 0x7000, 0x11)] pub ch1_index: u16, 107 | #[entry(0x1600, 0x7000, 0x12)] pub ch1_length: u16, 108 | #[entry(0x1600, 0x7000, 0x13)] pub ch1_param: u8, 109 | #[entry(0x1600, 0x7000, 0x21)] pub ch1_red: u8, 110 | #[entry(0x1600, 0x7000, 0x22)] pub ch1_green: u8, 111 | #[entry(0x1600, 0x7000, 0x23)] pub ch1_blue: u8, 112 | #[entry(0x1600, 0x7000, 0x24)] pub ch1_white: u8, 113 | } 114 | 115 | #[repr(C, packed)] 116 | #[derive(SlaveProcessImage, Default)] 117 | #[pdos(3, Input, 0x1A00)] 118 | #[pdos(2, Output, 0x1601)] 119 | #[allow(non_camel_case_types)] 120 | pub struct EL2574_1Ch_Extended { 121 | #[entry(0x1A00, 0x6000, 1)] pub ch1_status: u16, 122 | 123 | #[entry(0x1601, 0x7001, 1)] pub ch1_control: u8, 124 | #[entry(0x1601, 0x7001, 9)] pub ch1_index: u8, 125 | #[entry(0x1601, 0x7001, 0x11)] pub ch1_el0: u32, 126 | #[entry(0x1601, 0x7001, 0x12)] pub ch1_el1: u32, 127 | #[entry(0x1601, 0x7001, 0x13)] pub ch1_el2: u32, 128 | #[entry(0x1601, 0x7001, 0x14)] pub ch1_el3: u32, 129 | #[entry(0x1601, 0x7001, 0x15)] pub ch1_el4: u32, 130 | #[entry(0x1601, 0x7001, 0x16)] pub ch1_el5: u32, 131 | #[entry(0x1601, 0x7001, 0x17)] pub ch1_el6: u32, 132 | #[entry(0x1601, 0x7001, 0x18)] pub ch1_el7: u32, 133 | } 134 | 135 | #[repr(C, packed)] 136 | #[derive(SlaveProcessImage, Default)] 137 | pub struct EL2612 { 138 | #[entry(0x7000, 1)] pub output: u8, 139 | } 140 | 141 | #[repr(C, packed)] 142 | #[derive(SlaveProcessImage, Default)] 143 | pub struct EL2622 { 144 | #[entry(0x7000, 1)] pub output: u8, 145 | } 146 | 147 | #[repr(C, packed)] 148 | #[derive(SlaveProcessImage, Default)] 149 | pub struct EL2624 { 150 | #[entry(0x7000, 1)] pub output: u8, 151 | } 152 | 153 | #[repr(C, packed)] 154 | #[derive(SlaveProcessImage, Default)] 155 | pub struct EL3104 { 156 | #[entry(0x6000, 1)] pub ch1_status: u16, 157 | #[entry(0x6000, 17)] pub ch1: i16, 158 | #[entry(0x6010, 1)] pub ch2_status: u16, 159 | #[entry(0x6010, 17)] pub ch2: i16, 160 | #[entry(0x6020, 1)] pub ch3_status: u16, 161 | #[entry(0x6020, 17)] pub ch3: i16, 162 | #[entry(0x6030, 1)] pub ch4_status: u16, 163 | #[entry(0x6030, 17)] pub ch4: i16, 164 | } 165 | 166 | #[repr(C, packed)] 167 | #[derive(SlaveProcessImage, Default)] 168 | #[pdos(3, Input, 0x1A02, 0x1A04)] 169 | pub struct EL3152 { 170 | #[entry(0x1A02, 0x6000, 1)] pub ch1_status: u16, 171 | #[entry(0x1A02, 0x6000, 17)] pub ch1: i16, 172 | #[entry(0x1A04, 0x6010, 1)] pub ch2_status: u16, 173 | #[entry(0x1A04, 0x6010, 17)] pub ch2: i16, 174 | } 175 | 176 | #[repr(C, packed)] 177 | #[derive(SlaveProcessImage, Default)] 178 | pub struct EL4132 { 179 | #[entry(0x3001, 1)] pub ch1: i16, 180 | #[entry(0x3002, 1)] pub ch2: i16, 181 | } 182 | 183 | #[repr(C, packed)] 184 | #[derive(SlaveProcessImage, Default)] 185 | pub struct EL5001 { 186 | #[entry(0x3101, 1)] pub status_ch1: u8, 187 | #[entry(0x3101, 2)] pub value_ch1: u32, 188 | } 189 | 190 | #[repr(C, packed)] 191 | #[derive(SlaveProcessImage, Default)] 192 | #[pdos(3, Input, 0x1A00, 0x1A01)] 193 | pub struct EL5002 { 194 | #[entry(0x1A00, 0x6000, 1)] pub status_ch1: u16, 195 | #[entry(0x1A00, 0x6000, 11)] pub value_ch1: u32, 196 | #[entry(0x1A01, 0x6010, 1)] pub status_ch2: u16, 197 | #[entry(0x1A01, 0x6010, 11)] pub value_ch2: u32, 198 | } 199 | 200 | #[repr(C, packed)] 201 | #[derive(SlaveProcessImage, Default)] 202 | #[pdos(3, Input, 0x1A00, 0x1A01)] 203 | #[watchdog(1, 1)] 204 | pub struct EL5032 { 205 | #[entry(0x1A00, 0x6000, 1)] pub status_ch1: u16, 206 | #[entry(0x1A00, 0x6000, 11)] pub value_ch1: u64, 207 | #[entry(0x1A01, 0x6010, 1)] pub status_ch2: u16, 208 | #[entry(0x1A01, 0x6010, 11)] pub value_ch2: u64, 209 | } 210 | 211 | #[repr(C, packed)] 212 | #[derive(SlaveProcessImage, Default)] 213 | #[pdos(3, Input, 0x1A00, 0x1A02)] 214 | #[pdos(2, Output, 0x1600, 0x1601)] 215 | pub struct EL5072 { 216 | #[entry(0x1A00, 0x6000, 1)] pub status_ch1: u16, 217 | #[entry(0x1A00, 0x6001, 1)] pub value_ch1: i32, 218 | #[entry(0x1A00, 0x6001, 2)] pub latch_ch1: i32, 219 | #[entry(0x1A02, 0x6010, 1)] pub status_ch2: u16, 220 | #[entry(0x1A02, 0x6011, 1)] pub value_ch2: i32, 221 | #[entry(0x1A02, 0x6011, 2)] pub latch_ch2: i32, 222 | 223 | #[entry(0x1600, 0x7000, 1)] pub control_ch1: u32, 224 | #[entry(0x1600, 0x7000, 0x11)] pub set_counter_ch1: u32, 225 | #[entry(0x1601, 0x7010, 1)] pub control_ch2: u32, 226 | #[entry(0x1601, 0x7010, 0x11)] pub set_counter_ch2: u32, 227 | } 228 | 229 | #[repr(C, packed)] 230 | #[derive(SlaveProcessImage, Default)] 231 | #[pdos(3, Input, 0x1A01, 0x1A03, 0x1A04, 0x1A08)] 232 | #[pdos(2, Output, 0x1601, 0x1602, 0x1604)] 233 | #[allow(non_camel_case_types)] 234 | pub struct EL7031_Velocity { 235 | #[entry(0x1A01, 0x6000, 1)] pub enc_status: u16, 236 | #[entry(0x1A01, 0x6000, 0x11)] pub enc_counter: u32, 237 | #[entry(0x1A01, 0x6000, 0x12)] pub enc_latch: u32, 238 | #[entry(0x1A03, 0x6010, 1)] pub mot_status: u16, 239 | #[entry(0x1A04, 0x6010, 0x11)] pub info_data1: u16, 240 | #[entry(0x1A04, 0x6010, 0x12)] pub info_data2: u16, 241 | #[entry(0x1A08, 0x6010, 0x14)] pub mot_position: i32, 242 | 243 | #[entry(0x1601, 0x7000, 1)] pub enc_control: u16, 244 | #[entry(0x1601, 0x7000, 0x11)] pub enc_set_counter: u32, 245 | #[entry(0x1602, 0x7010, 1)] pub mot_control: u16, 246 | #[entry(0x1604, 0x7010, 0x21)] pub mot_velocity: i16, 247 | } 248 | 249 | #[repr(C, packed)] 250 | #[derive(SlaveProcessImage, Default)] 251 | #[pdos(3, Input, 0x1A01, 0x1A03, 0x1A04, 0x1A07)] 252 | #[pdos(2, Output, 0x1601, 0x1602, 0x1604)] 253 | #[allow(non_camel_case_types)] 254 | pub struct EL7041_Velocity { 255 | #[entry(0x1A01, 0x6000, 1)] pub enc_status: u16, 256 | #[entry(0x1A01, 0x6000, 0x11)] pub enc_counter: u32, 257 | #[entry(0x1A01, 0x6000, 0x12)] pub enc_latch: u32, 258 | #[entry(0x1A03, 0x6010, 1)] pub mot_status: u16, 259 | #[entry(0x1A04, 0x6010, 0x11)] pub info_data1: u16, 260 | #[entry(0x1A04, 0x6010, 0x12)] pub info_data2: u16, 261 | #[entry(0x1A07, 0x6010, 0x14)] pub mot_position: i32, 262 | 263 | #[entry(0x1601, 0x7000, 1)] pub enc_control: u16, 264 | #[entry(0x1601, 0x7000, 0x11)] pub enc_set_counter: u32, 265 | #[entry(0x1602, 0x7010, 1)] pub mot_control: u16, 266 | #[entry(0x1604, 0x7010, 0x21)] pub mot_velocity: i16, 267 | } 268 | 269 | #[repr(C, packed)] 270 | #[derive(SlaveProcessImage, Default)] 271 | #[pdos(3, Input, 0x1A01, 0x1A03, 0x1A04, 0x1A08)] 272 | #[pdos(2, Output, 0x1601, 0x1602, 0x1604)] 273 | #[allow(non_camel_case_types)] 274 | pub struct EL7047_Velocity { 275 | #[entry(0x1A01, 0x6000, 1)] pub enc_status: u16, 276 | #[entry(0x1A01, 0x6000, 0x11)] pub enc_counter: u32, 277 | #[entry(0x1A01, 0x6000, 0x12)] pub enc_latch: u32, 278 | #[entry(0x1A03, 0x6010, 1)] pub mot_status: u16, 279 | #[entry(0x1A04, 0x6010, 0x11)] pub info_data1: u16, 280 | #[entry(0x1A04, 0x6010, 0x12)] pub info_data2: u16, 281 | #[entry(0x1A08, 0x6010, 0x14)] pub mot_position: i32, 282 | 283 | #[entry(0x1601, 0x7000, 1)] pub enc_control: u16, 284 | #[entry(0x1601, 0x7000, 0x11)] pub enc_set_counter: u32, 285 | #[entry(0x1602, 0x7010, 1)] pub mot_control: u16, 286 | #[entry(0x1604, 0x7010, 0x21)] pub mot_velocity: i16, 287 | } 288 | 289 | #[repr(C, packed)] 290 | #[derive(SlaveProcessImage, Default)] 291 | #[pdos(3, Input, 0x1A01, 0x1A03, 0x1A04, 0x1A08)] 292 | #[pdos(2, Output, 0x1601, 0x1602, 0x1603)] 293 | #[allow(non_camel_case_types)] 294 | pub struct EL7047_Position { 295 | #[entry(0x1A01, 0x6000, 1)] pub enc_status: u16, 296 | #[entry(0x1A01, 0x6000, 11)] pub enc_counter: u32, 297 | #[entry(0x1A01, 0x6000, 12)] pub enc_latch: u32, 298 | #[entry(0x1A03, 0x6010, 1)] pub mot_status: u16, 299 | #[entry(0x1A04, 0x6010, 11)] pub info_data1: u16, 300 | #[entry(0x1A04, 0x6010, 12)] pub info_data2: u16, 301 | #[entry(0x1A08, 0x6010, 14)] pub mot_position: i32, 302 | 303 | #[entry(0x1601, 0x7000, 1)] pub enc_control: u16, 304 | #[entry(0x1601, 0x7000, 11)] pub enc_set_counter: u32, 305 | #[entry(0x1602, 0x7010, 1)] pub mot_control: u16, 306 | #[entry(0x1603, 0x7010, 11)] pub mot_target: i32, 307 | } 308 | 309 | #[repr(C, packed)] 310 | #[derive(SlaveProcessImage, Default)] 311 | #[pdos(3, Input, 0x1A01, 0x1A03, 0x1A07)] 312 | #[pdos(2, Output, 0x1601, 0x1602, 0x1606)] 313 | #[allow(non_camel_case_types)] 314 | pub struct EL7047_Positioning { 315 | #[entry(0x1A01, 0x6000, 1)] pub enc_status: u16, 316 | #[entry(0x1A01, 0x6000, 11)] pub enc_counter: u32, 317 | #[entry(0x1A01, 0x6000, 12)] pub enc_latch: u32, 318 | #[entry(0x1A03, 0x6010, 1)] pub mot_status: u16, 319 | #[entry(0x1A07, 0x6020, 1)] pub pos_status: u16, 320 | #[entry(0x1A07, 0x6020, 11)] pub act_pos: i32, 321 | #[entry(0x1A07, 0x6020, 21)] pub act_velo: u16, 322 | #[entry(0x1A07, 0x6020, 22)] pub drv_time: u32, 323 | 324 | #[entry(0x1601, 0x7000, 1)] pub enc_control: u16, 325 | #[entry(0x1601, 0x7000, 11)] pub enc_set_counter: u32, 326 | #[entry(0x1602, 0x7010, 1)] pub mot_control: u16, 327 | #[entry(0x1606, 0x7020, 1)] pub pos_control: u16, 328 | #[entry(0x1606, 0x7020, 11)] pub target_pos: u32, 329 | #[entry(0x1606, 0x7020, 21)] pub target_velo: u16, 330 | #[entry(0x1606, 0x7020, 22)] pub start_type: u16, 331 | #[entry(0x1606, 0x7020, 23)] pub accel: u16, 332 | #[entry(0x1606, 0x7020, 24)] pub decel: u16, 333 | } 334 | 335 | #[repr(C, packed)] 336 | #[derive(SlaveProcessImage, Default)] 337 | #[pdos(3, Input, 0x1A00, 0x1A01, 0x1A02, 0x1A03, 0x1A04, 0x1A05, 0x1A06, 0x1A0E)] 338 | #[pdos(2, Output, 0x1600, 0x1601, 0x1608)] 339 | #[dc(0x700, 2000000, 30000, 2000000, 1000)] 340 | #[allow(non_camel_case_types)] 341 | pub struct EL7211_0010_Velocity { 342 | #[entry(0x1A00, 0x6000, 0x11)] pub act_pos: u32, 343 | #[entry(0x1A01, 0x6010, 1)] pub mot_status: u16, 344 | #[entry(0x1A02, 0x6010, 7)] pub act_velo: i32, 345 | #[entry(0x1A03, 0x6010, 8)] pub act_torq: i16, 346 | #[entry(0x1A04, 0x6010, 0x12)] pub info_data1: u16, 347 | #[entry(0x1A05, 0x6010, 0x13)] pub info_data2: u16, 348 | #[entry(0x1A06, 0x6010, 6)] pub drag_error: i32, 349 | #[entry(0x1A0E, 0x6010, 3)] pub mot_curr_mode: u8, 350 | 351 | #[entry(0x1600, 0x7010, 1)] pub mot_control: u16, 352 | #[entry(0x1601, 0x7010, 6)] pub target_velo: i32, 353 | #[entry(0x1608, 0x7010, 3)] pub mot_mode: u8, 354 | } 355 | 356 | #[repr(C, packed)] 357 | #[derive(SlaveProcessImage, Default)] 358 | #[pdos(3, Input, 0x1A00, 0x1A01, 0x1A02, 0x1A04, 0x1A05, 0x1A06, 0x1A07, 0x1A0E)] 359 | #[pdos(2, Output, 0x1600, 0x1601, 0x1608)] 360 | #[dc(0x700, 2000000, 30000, 2000000, 1000)] 361 | #[allow(non_camel_case_types)] 362 | pub struct EL7221_9014_Velocity { 363 | #[entry(0x1A00, 0x6000, 0x11)] pub act_pos: u32, 364 | #[entry(0x1A01, 0x6010, 1)] pub mot_status: u16, 365 | #[entry(0x1A02, 0x6010, 7)] pub act_velo: i32, 366 | #[entry(0x1A04, 0x6010, 0x12)] pub info_data1: u16, 367 | #[entry(0x1A05, 0x6010, 0x13)] pub info_data2: u16, 368 | #[entry(0x1A06, 0x6010, 6)] pub drag_error: i32, 369 | #[entry(0x1A07, 0x6010, 8)] pub act_torq: i16, 370 | #[entry(0x1A0E, 0x6010, 3)] pub mot_curr_mode: u8, 371 | 372 | #[entry(0x1600, 0x7010, 1)] pub mot_control: u16, 373 | #[entry(0x1601, 0x7010, 6)] pub target_velo: i32, 374 | #[entry(0x1608, 0x7010, 3)] pub mot_mode: u8, 375 | } 376 | 377 | #[repr(C, packed)] 378 | #[derive(SlaveProcessImage, Default)] 379 | pub struct EL9505 { 380 | } 381 | -------------------------------------------------------------------------------- /ethercat-plc/src/image.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | //! Tools to create a typesafe process image matching with possible slave PDOs. 5 | 6 | use ethercat::*; 7 | 8 | pub trait ProcessImage { 9 | // configuration APIs 10 | const SLAVE_COUNT: usize; 11 | fn get_slave_ids() -> Vec; 12 | fn get_slave_pdos() -> Vec)>>> { vec![None] } 13 | fn get_slave_regs() -> Vec> { vec![vec![]] } 14 | fn get_slave_sdos(_: &C) -> Vec> { vec![vec![]] } 15 | fn get_slave_wd_dc() -> Vec<(Option<(u16, u16)>, Option<(u16, u32, i32, u32, i32)>)> { 16 | vec![(None, None)] 17 | } 18 | 19 | fn size() -> usize where Self: Sized { 20 | std::mem::size_of::() 21 | } 22 | 23 | fn cast(data: &mut [u8]) -> &mut Self where Self: Sized { 24 | unsafe { &mut *data.as_mut_ptr().cast() } 25 | } 26 | } 27 | 28 | pub trait ExternImage : Default { 29 | fn size() -> usize where Self: Sized { 30 | std::mem::size_of::() 31 | } 32 | 33 | fn cast(&mut self) -> &mut [u8] where Self: Sized { 34 | unsafe { 35 | std::slice::from_raw_parts_mut(self as *mut _ as *mut u8, Self::size()) 36 | } 37 | } 38 | } 39 | 40 | pub trait ProcessConfig { 41 | fn get_sdo_var(&self, var: &str) -> Option<&dyn SdoData>; 42 | } 43 | 44 | impl ProcessConfig for () { 45 | fn get_sdo_var(&self, _: &str) -> Option<&dyn SdoData> { 46 | None 47 | } 48 | } 49 | 50 | impl ProcessConfig for std::collections::HashMap> { 51 | fn get_sdo_var(&self, var: &str) -> Option<&dyn SdoData> { 52 | self.get(var).map(|s| &**s) 53 | } 54 | } 55 | 56 | impl<'a> ProcessConfig for std::collections::HashMap<&'a str, Box> { 57 | fn get_sdo_var(&self, var: &str) -> Option<&dyn SdoData> { 58 | self.get(var).map(|s| &**s) 59 | } 60 | } 61 | 62 | // TODO: add a derive macro for ProcessConfig so that you can configure 63 | // the PLC using a well typed struct 64 | -------------------------------------------------------------------------------- /ethercat-plc/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | #![allow(clippy::type_complexity)] 5 | 6 | mod plc; 7 | mod image; 8 | mod server; 9 | 10 | pub mod beckhoff; 11 | pub mod mlz_spec; 12 | 13 | pub use self::plc::{Plc, PlcBuilder, PlcSimulator}; 14 | pub use self::image::{ExternImage, ProcessImage, ProcessConfig}; 15 | pub use self::server::{Server, NoServer, TcpServer, ModbusHandler, SimpleHandler}; 16 | pub use ethercat_derive::{ExternImage, ProcessImage, SlaveProcessImage}; 17 | -------------------------------------------------------------------------------- /ethercat-plc/src/mlz_spec.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | use byteorder::{ByteOrder, NativeEndian as NE}; 5 | 6 | pub const MAGIC: f32 = 2015.02; 7 | 8 | pub const RESET: u16 = 0x0000; 9 | pub const IDLE: u16 = 0x1000; 10 | pub const WARN: u16 = 0x3000; 11 | pub const START: u16 = 0x5000; 12 | pub const BUSY: u16 = 0x6000; 13 | pub const STOP: u16 = 0x7000; 14 | pub const ERROR: u16 = 0x8000; 15 | 16 | #[repr(C)] 17 | #[derive(Default)] 18 | pub struct DiscreteOutput { 19 | pub value: i16, 20 | pub target: i16, 21 | pub status: u16, 22 | } 23 | 24 | #[repr(C)] 25 | #[derive(Default)] 26 | pub struct FlatOutput1 { 27 | pub value: f32, 28 | pub target: f32, 29 | pub status: u16, 30 | pub aux: u16, 31 | pub param1: f32, 32 | } 33 | 34 | pub fn copy_string(dst: &mut [u16], src: &str) { 35 | let mut nbytes = src.len().min(dst.len() * 2); 36 | let mut src_vec; 37 | let src = if nbytes % 2 == 1 { 38 | src_vec = src.to_string(); 39 | src_vec.push('\0'); 40 | nbytes += 1; 41 | &src_vec 42 | } else { 43 | src 44 | }; 45 | NE::read_u16_into(src[..nbytes].as_bytes(), &mut dst[..nbytes/2]) 46 | } 47 | 48 | pub fn copy_float(dst: &mut [u16], f: f32) { 49 | let mut buf = [0u8; 4]; 50 | NE::write_f32(&mut buf, f); 51 | NE::read_u16_into(&buf, &mut dst[..2]); 52 | } 53 | -------------------------------------------------------------------------------- /ethercat-plc/src/plc.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | //! Wrap an EtherCAT master and slave configuration and provide a PLC-like 5 | //! environment for cyclic task execution. 6 | 7 | use std::{thread, time::{Instant, Duration}, marker::PhantomData}; 8 | use anyhow::{bail, Context}; 9 | use crossbeam_channel::{unbounded, Sender, Receiver}; 10 | use log::*; 11 | use ethercat as ec; 12 | 13 | use crate::image::{ProcessImage, ExternImage, ProcessConfig}; 14 | use crate::server::{Server, Request, Response}; 15 | 16 | #[derive(Default)] 17 | pub struct PlcBuilder { 18 | name: String, 19 | master_id: Option, 20 | cycle_freq: Option, 21 | server_addr: Option, 22 | logfile_base: Option, 23 | debug_logging: bool, 24 | } 25 | 26 | impl PlcBuilder { 27 | pub fn new(name: impl Into) -> Self { 28 | Self { 29 | name: name.into(), 30 | .. Self::default() 31 | } 32 | } 33 | 34 | pub fn master_id(mut self, id: u32) -> Self { 35 | self.master_id = Some(id); 36 | self 37 | } 38 | 39 | pub fn cycle_freq(mut self, freq: u32) -> Self { 40 | self.cycle_freq = Some(freq); 41 | self 42 | } 43 | 44 | pub fn with_server(mut self, addr: impl Into) -> Self { 45 | self.server_addr = Some(addr.into()); 46 | self 47 | } 48 | 49 | pub fn logging_cfg(mut self, logfile_base: Option, debug_logging: bool) -> Self { 50 | self.logfile_base = logfile_base; 51 | self.debug_logging = debug_logging; 52 | self 53 | } 54 | 55 | pub fn build_simulator(self) -> anyhow::Result> { 56 | mlzlog::init(self.logfile_base, &self.name, 57 | mlzlog::Settings { show_appname: false, 58 | debug: self.debug_logging, 59 | ..Default::default() }) 60 | .context("setting up logging")?; 61 | 62 | let channels = if let Some(addr) = self.server_addr { 63 | let (w_from_plc, r_from_plc) = unbounded(); 64 | let (w_to_plc, r_to_plc) = unbounded(); 65 | S::start(&addr, w_to_plc, r_from_plc) 66 | .context("starting external server")?; 67 | Some((r_to_plc, w_from_plc)) 68 | } else { 69 | None 70 | }; 71 | 72 | Ok(PlcSimulator { 73 | server_channel: channels, 74 | sleep: 1_000_000_000 / self.cycle_freq.unwrap_or(1000) as u64, 75 | _types: PhantomData, 76 | }) 77 | } 78 | 79 | pub fn build(self, cfg: PC) -> anyhow::Result> { 81 | mlzlog::init(self.logfile_base, &self.name, 82 | mlzlog::Settings { show_appname: false, 83 | debug: self.debug_logging, 84 | ..Default::default() }) 85 | .context("setting up logging")?; 86 | 87 | let channels = if let Some(addr) = self.server_addr { 88 | let (w_from_plc, r_from_plc) = unbounded(); 89 | let (w_to_plc, r_to_plc) = unbounded(); 90 | S::start(&addr, w_to_plc, r_from_plc) 91 | .context("starting external server")?; 92 | Some((r_to_plc, w_from_plc)) 93 | } else { 94 | None 95 | }; 96 | 97 | let mut master = ec::Master::open(self.master_id.unwrap_or(0), 98 | ec::MasterAccess::ReadWrite) 99 | .context("opening Ethercat master")?; 100 | master.reserve()?; 101 | let domain = master.create_domain() 102 | .context("creating Ethercat domain")?; 103 | 104 | debug!("PLC: EtherCAT master opened"); 105 | 106 | let slave_ids = P::get_slave_ids(); 107 | let slave_pdos = P::get_slave_pdos(); 108 | let slave_regs = P::get_slave_regs(); 109 | let slave_sdos = P::get_slave_sdos(&cfg); 110 | let slave_wd_dcs = P::get_slave_wd_dc(); 111 | for (i, ((((id, pdos), regs), sdos), wd_dc)) in slave_ids.into_iter() 112 | .zip(slave_pdos) 113 | .zip(slave_regs) 114 | .zip(slave_sdos) 115 | .zip(slave_wd_dcs) 116 | .enumerate() 117 | { 118 | let mut config = master.configure_slave(ec::SlaveAddr::ByPos(i as u16), id) 119 | .with_context(|| format!("configuring slave {} with id {:?}", i, id))?; 120 | 121 | if let Some(sm_pdos) = pdos { 122 | for (sm, pdos) in sm_pdos { 123 | config.config_sm_pdos(sm, &pdos) 124 | .with_context(|| format!("configuring slave {} with pdos for sync \ 125 | manager {:?}", i, sm))?; 126 | } 127 | } 128 | let mut first_byte = 0; 129 | for (j, (entry, mut expected_position)) in regs.into_iter().enumerate() { 130 | let pos = config.register_pdo_entry(entry, domain) 131 | .with_context(|| format!("registering slave {} pdo {:?}", i, entry))?; 132 | if j == 0 { 133 | if pos.bit != 0 { 134 | bail!("first PDO of slave {} not byte-aligned", i); 135 | } 136 | first_byte = pos.byte; 137 | } else { 138 | expected_position.byte += first_byte; 139 | if pos != expected_position { 140 | bail!("slave {} pdo {}: {:?} != {:?}", i, j, pos, expected_position); 141 | } 142 | } 143 | } 144 | 145 | for (sdo_index, complete, data) in sdos { 146 | if complete { 147 | config.add_complete_sdo( 148 | sdo_index, 149 | unsafe { 150 | std::slice::from_raw_parts(data.data_ptr(), data.data_size()) 151 | }) 152 | .with_context(|| format!("adding slave {} complete sdo {:?}", i, sdo_index))?; 153 | } else { 154 | config.add_sdo(sdo_index, data) 155 | .with_context(|| format!("adding slave {} sdo {:?}", i, sdo_index))?; 156 | } 157 | } 158 | 159 | if let Some((div, int)) = wd_dc.0 { 160 | config.config_watchdog(div, int) 161 | .with_context(|| format!("configuring slave {} watchdog", i))?; 162 | } 163 | 164 | if let Some((act, cyc0, sh0, cyc1, sh1)) = wd_dc.1 { 165 | config.config_dc(act, cyc0, sh0, cyc1, sh1) 166 | .with_context(|| format!("configuring slave {} dist. clock", i))?; 167 | } 168 | 169 | let cfg_index = config.index(); 170 | 171 | // ensure that the slave is actually present 172 | if master.get_config_info(cfg_index)?.slave_position.is_none() { 173 | bail!("slave {} does not match config", i); 174 | } 175 | } 176 | 177 | info!("PLC: EtherCAT slaves configured"); 178 | 179 | let domain_size = master.domain(domain).size()?; 180 | if domain_size != P::size() { 181 | bail!("domain size mismatch: real {} != assumed {}", domain_size, P::size()); 182 | } 183 | 184 | master.set_application_time(1) 185 | .context("setting application time")?; // 0 is not good 186 | master.activate() 187 | .context("activating master")?; 188 | info!("PLC: EtherCAT master activated"); 189 | 190 | Ok(Plc { 191 | master, 192 | domain, 193 | server_channel: channels, 194 | sleep: 1_000_000_000 / self.cycle_freq.unwrap_or(1000) as u64, 195 | _types: PhantomData, 196 | }) 197 | } 198 | } 199 | 200 | pub type ServerChannels = (Receiver>, Sender>); 201 | 202 | pub fn data_exchange(chan: &mut ServerChannels, ext: &mut E) { 203 | while let Ok(mut req) = chan.0.try_recv() { 204 | let mut done = false; 205 | debug!("PLC sim got request: {:?}", req); 206 | let data = ext.cast(); 207 | let resp = if req.addr + req.count > E::size() { 208 | Response::Error(req, 2) 209 | } else { 210 | let from = req.addr; 211 | let to = from + req.count; 212 | if let Some(ref mut values) = req.write { 213 | // write request 214 | data[from..to].copy_from_slice(values); 215 | let values = req.write.take().unwrap(); 216 | // let a PLC cycle run after a write request 217 | done = true; 218 | Response::Ok(req, values) 219 | } else { 220 | // read request 221 | Response::Ok(req, data[from..to].to_vec()) 222 | } 223 | }; 224 | debug!("PLC sim response: {:?}", resp); 225 | if let Err(e) = chan.1.send(resp) { 226 | warn!("could not send back response: {}", e); 227 | } 228 | if done { 229 | break; 230 | } 231 | } 232 | } 233 | 234 | 235 | pub struct Plc { 236 | master: ec::Master, 237 | domain: ec::DomainIdx, 238 | sleep: u64, 239 | server_channel: Option>, 240 | _types: PhantomData<(P, E)>, 241 | } 242 | 243 | impl Plc { 244 | pub fn run(&mut self, mut cycle_fn: F) 245 | where F: FnMut(&mut P, &mut E) 246 | { 247 | let mut ext = E::default(); 248 | let mut cycle_start = Instant::now(); 249 | 250 | loop { 251 | // process data exchange + logic 252 | if let Err(e) = self.single_cycle(&mut cycle_fn, &mut ext) { 253 | // XXX: logging unconditionally here is bad, could repeat endlessly 254 | warn!("error in cycle: {}", e); 255 | } 256 | 257 | // external data exchange 258 | if let Some(chan) = self.server_channel.as_mut() { 259 | data_exchange(chan, &mut ext); 260 | } 261 | 262 | // wait until next cycle 263 | let now = Instant::now(); 264 | cycle_start += Duration::from_nanos(self.sleep); 265 | if cycle_start > now { 266 | thread::sleep(cycle_start - now); 267 | } 268 | } 269 | } 270 | 271 | fn single_cycle(&mut self, mut cycle_fn: F, ext: &mut E) -> anyhow::Result<()> 272 | where F: FnMut(&mut P, &mut E) 273 | { 274 | self.master.receive() 275 | .context("receiving Ethercat data")?; 276 | self.master.domain(self.domain).process() 277 | .context("processing domain data")?; 278 | 279 | // XXX: check working counters periodically, etc. 280 | // println!("master state: {:?}", self.master.state()); 281 | // println!("domain state: {:?}", self.master.domain(self.domain).state()); 282 | 283 | let data = P::cast(self.master.domain_data(self.domain)?); 284 | cycle_fn(data, ext); 285 | 286 | self.master.domain(self.domain).queue() 287 | .context("queueing new domain data")?; 288 | self.master.send() 289 | .context("sending Ethercat data")?; 290 | Ok(()) 291 | } 292 | } 293 | 294 | 295 | /// An object similar to Plc, but not connected to an Ethercat master. 296 | pub struct PlcSimulator { 297 | sleep: u64, 298 | server_channel: Option<(Receiver>, Sender>)>, 299 | _types: PhantomData, 300 | } 301 | 302 | impl PlcSimulator { 303 | pub fn run(&mut self, mut cycle_fn: F) 304 | where F: FnMut(&mut E) 305 | { 306 | let mut ext = E::default(); 307 | let mut cycle_start = Instant::now(); 308 | 309 | loop { 310 | // simulate a cycle 311 | cycle_fn(&mut ext); 312 | 313 | // data exchange with upper layer 314 | if let Some(chan) = self.server_channel.as_mut() { 315 | data_exchange(chan, &mut ext); 316 | } 317 | 318 | // wait until next cycle 319 | let now = Instant::now(); 320 | cycle_start += Duration::from_nanos(self.sleep); 321 | if cycle_start > now { 322 | thread::sleep(cycle_start - now); 323 | } 324 | } 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /ethercat-plc/src/server.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | //! Modbus server allowing access to the PLC "memory" variables. 5 | 6 | use std::collections::BTreeMap; 7 | use std::fmt::Debug; 8 | use std::io::{Result, Read, Write, ErrorKind}; 9 | use std::net::{TcpListener, TcpStream}; 10 | use std::thread; 11 | use log::*; 12 | use byteorder::{ByteOrder, BE, LE}; 13 | use crossbeam_channel::{unbounded, Sender, Receiver}; 14 | 15 | 16 | #[derive(Debug)] 17 | pub struct Request { 18 | pub hid: usize, 19 | pub addr: usize, 20 | pub count: usize, 21 | pub write: Option>, 22 | pub extra: T, 23 | } 24 | 25 | #[derive(Debug)] 26 | pub enum Response { 27 | Ok(Request, Vec), 28 | Error(Request, u8), 29 | } 30 | 31 | pub trait Server { 32 | type Extra: Debug + Send + 'static; 33 | fn start(addr: &str, w_to_plc: Sender>, 34 | r_from_plc: Receiver>,) -> Result<()>; 35 | } 36 | 37 | 38 | pub struct NoServer; 39 | 40 | impl Server for NoServer { 41 | type Extra = (); 42 | 43 | fn start(_: &str, _: Sender>, _: Receiver>) -> Result<()> { 44 | Ok(()) 45 | } 46 | } 47 | 48 | 49 | pub enum HandlerEvent { 50 | Request(Request), 51 | New((usize, Sender>)), 52 | Finished(usize), 53 | } 54 | 55 | pub trait Handler { 56 | type Extra: Debug + Send + 'static; 57 | fn new(client: TcpStream, hid: usize, requests: Sender>, 58 | replies: Receiver>) -> Self; 59 | fn sender(client: TcpStream, replies: Receiver>); 60 | fn handle(self); 61 | } 62 | 63 | pub struct TcpServer { 64 | to_plc: Sender>, 65 | from_plc: Receiver>, 66 | } 67 | 68 | impl Server for TcpServer { 69 | type Extra = H::Extra; 70 | 71 | fn start(addr: &str, w_to_plc: Sender>, 72 | r_from_plc: Receiver>,) -> Result<()> { 73 | let (w_clients, r_clients) = unbounded(); 74 | let tcp_sock = TcpListener::bind(addr)?; 75 | 76 | let srv: Self = TcpServer { to_plc: w_to_plc, from_plc: r_from_plc }; 77 | 78 | thread::spawn(move || Self::tcp_listener(tcp_sock, w_clients)); 79 | thread::spawn(move || srv.dispatcher(r_clients)); 80 | 81 | Ok(()) 82 | } 83 | } 84 | 85 | impl TcpServer { 86 | /// Listen for connections on the TCP socket and spawn handlers for it. 87 | fn tcp_listener(tcp_sock: TcpListener, handler_sender: Sender>) { 88 | mlzlog::set_thread_prefix("TCP: "); 89 | 90 | info!("listening on {}", tcp_sock.local_addr().unwrap()); 91 | let mut handler_id = 0; 92 | 93 | while let Ok((stream, _)) = tcp_sock.accept() { 94 | let (w_rep, r_rep) = unbounded(); 95 | let w_req = handler_sender.clone(); 96 | handler_id += 1; 97 | if let Err(e) = w_req.send(HandlerEvent::New((handler_id, w_rep))) { 98 | warn!("couldn't send new handler event: {}", e); 99 | } else { 100 | thread::spawn(move || H::new(stream, handler_id, 101 | w_req, r_rep).handle()); 102 | } 103 | } 104 | } 105 | 106 | fn dispatcher(self, r_clients: Receiver>) { 107 | mlzlog::set_thread_prefix("Dispatcher: "); 108 | 109 | let mut handlers = BTreeMap::new(); 110 | 111 | for event in r_clients { 112 | match event { 113 | HandlerEvent::New((id, chan)) => { 114 | handlers.insert(id, chan); 115 | } 116 | HandlerEvent::Finished(id) => { 117 | handlers.remove(&id); 118 | } 119 | HandlerEvent::Request(req) => { 120 | let hid = req.hid; 121 | if let Err(e) = self.to_plc.send(req) { 122 | warn!("couldn't send request to PLC: {}", e); 123 | } else { 124 | let resp = self.from_plc.recv().unwrap(); 125 | if let Err(e) = handlers[&hid].send(resp) { 126 | warn!("couldn't send reply to handler: {}", e); 127 | } 128 | } 129 | } 130 | } 131 | } 132 | } 133 | } 134 | 135 | #[derive(Debug)] 136 | pub struct ModbusExtra { 137 | tid: u16, 138 | fc: u8, 139 | } 140 | 141 | pub struct ModbusHandler { 142 | hid: usize, 143 | client: TcpStream, 144 | requests: Sender>, 145 | } 146 | 147 | impl Handler for ModbusHandler { 148 | type Extra = ModbusExtra; 149 | 150 | fn new(client: TcpStream, hid: usize, requests: Sender>, 151 | replies: Receiver>) -> Self { 152 | let send_client = client.try_clone().expect("could not clone socket"); 153 | thread::spawn(move || ModbusHandler::sender(send_client, replies)); 154 | ModbusHandler { client, hid, requests } 155 | } 156 | 157 | fn sender(mut client: TcpStream, replies: Receiver>) { 158 | let mut buf = [0u8; 256]; 159 | mlzlog::set_thread_prefix(format!("{} sender: ", client.peer_addr().unwrap())); 160 | 161 | for response in replies { 162 | debug!("sending response: {:?}", response); 163 | let count = match response { 164 | Response::Ok(req, values) => { 165 | BE::write_u16(&mut buf, req.extra.tid); 166 | buf[7] = req.extra.fc; 167 | match req.extra.fc { 168 | 3 | 4 => { 169 | let nbytes = values.len(); 170 | buf[8] = nbytes as u8; 171 | buf[9..9+nbytes].copy_from_slice(&values); 172 | 9 + nbytes 173 | } 174 | 6 => { 175 | BE::write_u16(&mut buf[8..], req.addr as u16); 176 | buf[10..12].copy_from_slice(&values); 177 | 12 178 | } 179 | 16 => { 180 | BE::write_u16(&mut buf[8..], req.addr as u16); 181 | BE::write_u16(&mut buf[10..], values.len() as u16 / 2); 182 | 12 183 | } 184 | x => panic!("impossible function code {}", x) 185 | } 186 | } 187 | Response::Error(req, ec) => { 188 | BE::write_u16(&mut buf, req.extra.tid); 189 | buf[7] = req.extra.fc | 0x80; 190 | buf[8] = ec; 191 | 9 192 | } 193 | }; 194 | BE::write_u16(&mut buf[4..], (count - 6) as u16); 195 | if let Err(err) = client.write_all(&buf[..count]) { 196 | warn!("write error: {}", err); 197 | break; 198 | } 199 | } 200 | } 201 | 202 | fn handle(mut self) { 203 | let mut headbuf = [0u8; 8]; 204 | let mut bodybuf = [0u8; 250]; // max frame size is 255 205 | let mut errbuf = [0, 0, 0, 0, 0, 9, 0, 0, 0]; 206 | 207 | mlzlog::set_thread_prefix(format!("{}: ", self.client.peer_addr().unwrap())); 208 | info!("connection accepted"); 209 | 210 | loop { 211 | if let Err(err) = self.client.read_exact(&mut headbuf) { 212 | if err.kind() != ErrorKind::UnexpectedEof { 213 | warn!("error reading request head: {}", err); 214 | } 215 | break; 216 | } 217 | if headbuf[2..4] != [0, 0] { 218 | warn!("protocol ID mismatch: {:?}", headbuf); 219 | break; 220 | } 221 | let tid = BE::read_u16(&headbuf); 222 | let data_len = BE::read_u16(&headbuf[4..6]) as usize; 223 | if let Err(err) = self.client.read_exact(&mut bodybuf[..data_len - 2]) { 224 | warn!("error reading request body: {}", err); 225 | break; 226 | } 227 | if headbuf[6] != 0 { 228 | warn!("invalid slave {}", headbuf[6]); 229 | continue; 230 | } 231 | let fc = headbuf[7]; 232 | let req = match fc { 233 | 3 | 4 => { // read registers 234 | if data_len != 6 { 235 | warn!("invalid data length for fc {}", fc); 236 | continue; 237 | } 238 | let addr = 2 * BE::read_u16(&bodybuf[..2]) as usize; 239 | let count = 2 * BE::read_u16(&bodybuf[2..4]) as usize; 240 | Request { hid: self.hid, addr, count, write: None, 241 | extra: ModbusExtra { tid, fc } } 242 | } 243 | 6 => { // write single register 244 | if data_len != 6 { 245 | warn!("invalid data length for fc {}", fc); 246 | continue; 247 | } 248 | let addr = 2 * BE::read_u16(&bodybuf[..2]) as usize; 249 | Request { hid: self.hid, addr, count: 2, write: Some(bodybuf[2..4].to_vec()), 250 | extra: ModbusExtra { tid, fc } } 251 | } 252 | 16 => { // write multiple registers 253 | if data_len < 7 { 254 | warn!("insufficient data length for fc {}", fc); 255 | continue; 256 | } 257 | let addr = 2 * BE::read_u16(&bodybuf[..2]) as usize; 258 | let bytecount = bodybuf[4] as usize; 259 | if data_len != 7 + bytecount { 260 | warn!("invalid data length for fc {}", fc); 261 | continue; 262 | } 263 | let values = bodybuf[5..5+bytecount].to_vec(); 264 | Request { hid: self.hid, addr, count: values.len(), write: Some(values), 265 | extra: ModbusExtra { tid, fc } } 266 | } 267 | _ => { 268 | warn!("unknown function code {}", fc); 269 | BE::write_u16(&mut errbuf, tid); 270 | errbuf[7] = fc | 0x80; 271 | errbuf[8] = 1; 272 | if let Err(err) = self.client.write_all(&errbuf) { 273 | warn!("error writing error response: {}", err); 274 | break; 275 | } 276 | continue; 277 | } 278 | }; 279 | debug!("got request: {:?}", req); 280 | if let Err(e) = self.requests.send(HandlerEvent::Request(req)) { 281 | warn!("couldn't send request to server: {}", e); 282 | } 283 | } 284 | info!("connection closed"); 285 | if let Err(e) = self.requests.send(HandlerEvent::Finished(self.hid)) { 286 | warn!("couldn't send finish event to server: {}", e); 287 | } 288 | } 289 | } 290 | 291 | 292 | pub struct SimpleHandler { 293 | hid: usize, 294 | client: TcpStream, 295 | requests: Sender>, 296 | } 297 | 298 | const SIMPLE_READ: u32 = 0x7EAD; 299 | const SIMPLE_WRITE: u32 = 0xF71E; 300 | const SIMPLE_ERR: u32 = 0xE770; 301 | 302 | impl Handler for SimpleHandler { 303 | type Extra = bool; 304 | 305 | fn new(client: TcpStream, hid: usize, requests: Sender>, 306 | replies: Receiver>) -> Self { 307 | client.set_nodelay(true).unwrap(); 308 | let send_client = client.try_clone().expect("could not clone socket"); 309 | thread::spawn(move || SimpleHandler::sender(send_client, replies)); 310 | SimpleHandler { client, hid, requests } 311 | } 312 | 313 | fn sender(mut client: TcpStream, replies: Receiver>) { 314 | let mut buf = [0u8; 12]; 315 | mlzlog::set_thread_prefix(format!("{} sender: ", client.peer_addr().unwrap())); 316 | 317 | for response in replies { 318 | debug!("sending response: {:?}", response); 319 | match response { 320 | Response::Ok(req, values) => { 321 | if req.extra { 322 | LE::write_u32(&mut buf, SIMPLE_READ); 323 | LE::write_u32(&mut buf[4..], req.addr as u32); 324 | LE::write_u32(&mut buf[8..], req.count as u32); 325 | if let Err(err) = client.write_all(&buf) { 326 | warn!("write error: {}", err); 327 | break; 328 | } 329 | if let Err(err) = client.write_all(&values) { 330 | warn!("write error: {}", err); 331 | break; 332 | } 333 | } else { 334 | LE::write_u32(&mut buf, SIMPLE_WRITE); 335 | LE::write_u32(&mut buf[4..], req.addr as u32); 336 | LE::write_u32(&mut buf[8..], req.count as u32); 337 | if let Err(err) = client.write_all(&buf) { 338 | warn!("write error: {}", err); 339 | break; 340 | } 341 | } 342 | } 343 | Response::Error(req, ec) => { 344 | LE::write_u32(&mut buf, SIMPLE_ERR); 345 | LE::write_u32(&mut buf[4..], req.addr as u32); 346 | LE::write_u32(&mut buf[4..], ec as u32); 347 | if let Err(err) = client.write_all(&buf) { 348 | warn!("write error: {}", err); 349 | break; 350 | } 351 | } 352 | } 353 | } 354 | } 355 | 356 | fn handle(mut self) { 357 | let mut headbuf = [0u8; 12]; 358 | 359 | mlzlog::set_thread_prefix(format!("{}: ", self.client.peer_addr().unwrap())); 360 | info!("connection accepted"); 361 | 362 | loop { 363 | if let Err(err) = self.client.read_exact(&mut headbuf) { 364 | if err.kind() != ErrorKind::UnexpectedEof { 365 | warn!("error reading request head: {}", err); 366 | } 367 | break; 368 | } 369 | let func = LE::read_u32(&headbuf); 370 | let addr = LE::read_u32(&headbuf[4..]) as usize; 371 | let count = LE::read_u32(&headbuf[8..]) as usize; 372 | let req = if func == SIMPLE_READ { 373 | Request { hid: self.hid, addr, count, write: None, extra: true } 374 | } else if func == SIMPLE_WRITE { 375 | let mut bodybuf = Vec::new(); 376 | if let Err(err) = std::io::Write::by_ref(&mut self.client) 377 | .take(count as u64).read_to_end(&mut bodybuf) 378 | { 379 | warn!("error reading request body: {}", err); 380 | break; 381 | } 382 | if bodybuf.len() != count { 383 | warn!("error reading request body: connection closed"); 384 | break; 385 | } 386 | Request { hid: self.hid, addr, count, write: Some(bodybuf), extra: false } 387 | } else { 388 | warn!("invalid function {}", func); 389 | continue; 390 | }; 391 | debug!("got request: {:?}", req); 392 | if let Err(e) = self.requests.send(HandlerEvent::Request(req)) { 393 | warn!("couldn't send request to server: {}", e); 394 | } 395 | } 396 | info!("connection closed"); 397 | if let Err(e) = self.requests.send(HandlerEvent::Finished(self.hid)) { 398 | warn!("couldn't send finish event to server: {}", e); 399 | } 400 | } 401 | } 402 | -------------------------------------------------------------------------------- /src/io_demo.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | use ethercat_plc::{PlcBuilder, ProcessImage, ExternImage, TcpServer, ModbusHandler}; 5 | use ethercat_plc::beckhoff::*; 6 | 7 | #[repr(C, packed)] 8 | #[derive(ProcessImage)] 9 | struct Image { 10 | coupler: EK1100, 11 | ios: EL1859, 12 | } 13 | 14 | #[repr(C)] 15 | #[derive(Default, ExternImage)] 16 | struct Extern { 17 | magic: f32, 18 | } 19 | 20 | fn main() { 21 | let mut plc = PlcBuilder::new("plc") 22 | .cycle_freq(2) 23 | .with_server("0.0.0.0:5020") 24 | .logging_cfg(None, false) 25 | .build::>(()).unwrap(); 26 | 27 | plc.run(|img, _| { 28 | img.ios.output ^= 1; 29 | println!("{}", img.ios.input); 30 | }); 31 | } 32 | -------------------------------------------------------------------------------- /src/magnet_demo.rs: -------------------------------------------------------------------------------- 1 | // Part of ethercat-rs. Copyright 2018-2024 by the authors. 2 | // This work is dual-licensed under Apache 2.0 and MIT terms. 3 | 4 | use ethercat_plc::{PlcBuilder, ProcessImage, ExternImage, TcpServer, ModbusHandler}; 5 | use ethercat_plc::beckhoff::*; 6 | use ethercat_plc::mlz_spec::*; 7 | 8 | const PLC_NAME: &str = "testplc"; 9 | const PLC_VERSION: &str = "v0.0.5beta"; 10 | const PLC_AUTHOR_1: &str = "some very long strings that I think"; 11 | const PLC_AUTHOR_2: &str = "won't really fit into the indexer"; 12 | 13 | const INDEXER_SIZE: u16 = std::mem::size_of::() as u16; 14 | const INDEXER_OFFS: u16 = 6; 15 | 16 | 17 | #[repr(C, packed)] 18 | #[derive(ProcessImage)] 19 | struct Image { 20 | coupler: EK1100, 21 | #[sdo(0x8010, 1, motor_current)] // normal current 750 mA 22 | #[sdo(0x8010, 2, "250u16")] // reduced current 250 mA 23 | #[sdo(0x8010, 3, "2400u16")] // supply is 24 V 24 | #[sdo(0x8010, 4, "1000u16")] // resistance is 10 Ohm 25 | #[sdo(0x8012, 8, "1u8")] // feedback internal 26 | #[sdo(0x8012, 0x11, "7u8")] // info data 1: velocity 27 | #[sdo(0x8012, 0x19, "13u8")] // info data 2: motor current 28 | motor: EL7047_Position, 29 | dig_in: EL1008, 30 | dig_out: EL2008, 31 | ana_in: EL3104, 32 | ana_out: EL4132, 33 | } 34 | 35 | #[repr(C)] 36 | #[derive(Default)] 37 | struct Indexer { 38 | request: u16, 39 | data: [u16; 17], 40 | } 41 | 42 | #[repr(C)] 43 | #[derive(Default, ExternImage)] 44 | struct Extern { 45 | magic: f32, 46 | offset: u16, 47 | indexer: Indexer, 48 | if_blink: DiscreteOutput, 49 | if_magnet: FlatOutput1, 50 | } 51 | 52 | #[derive(Default)] 53 | struct MagnetVars { 54 | target: f32, 55 | start: f32, 56 | step: f32, 57 | current: f32, 58 | cycles: u32, 59 | } 60 | 61 | #[derive(Default)] 62 | struct Globals { 63 | cycle: u16, 64 | indexer_is_init: bool, 65 | devices: Vec, 66 | v_magnet: MagnetVars, 67 | } 68 | 69 | #[derive(Default)] 70 | struct DeviceInfo { 71 | typcode: u16, 72 | size: u16, 73 | offset: u16, 74 | unit: u16, 75 | flags: u8, 76 | all_flags: u32, 77 | params: [u16; 16], 78 | name: &'static str, 79 | aux: &'static [&'static str], 80 | absmax: f32, 81 | absmin: f32, 82 | } 83 | 84 | fn indexer(ext: &mut Extern, globals: &mut Globals) { 85 | if !globals.indexer_is_init { 86 | let mut calc_offset = INDEXER_OFFS + INDEXER_SIZE; 87 | for dev in &mut globals.devices { 88 | dev.all_flags = (dev.flags as u32) << 24; 89 | for j in 0..8 { 90 | if dev.aux.len() > j && !dev.aux[j].is_empty() { 91 | dev.all_flags |= 1 << j; 92 | } 93 | } 94 | if dev.size < (dev.typcode & 0xff) << 1 { 95 | dev.size = (dev.typcode & 0xff) << 1; 96 | } 97 | if dev.offset == 0 { 98 | dev.offset = calc_offset; 99 | } else { 100 | calc_offset = dev.offset; 101 | } 102 | calc_offset += dev.size; 103 | } 104 | globals.indexer_is_init = true; 105 | } 106 | 107 | ext.magic = MAGIC; 108 | ext.offset = INDEXER_OFFS; 109 | 110 | let devnum = ext.indexer.request as usize & 0xff; 111 | let infotype = (ext.indexer.request as usize >> 8) & 0x7f; 112 | 113 | let data = &mut ext.indexer.data; 114 | data.copy_from_slice(&[0; 17]); 115 | 116 | match devnum { 117 | 0 => match infotype { 118 | 0 => { 119 | data[..10].copy_from_slice( 120 | &[0, INDEXER_SIZE, ext.offset, 0, 0, 0x8000, 0, 0, 0, 0]); 121 | copy_string(&mut data[10..], PLC_NAME); 122 | } 123 | 1 => data[0] = INDEXER_SIZE, 124 | 4 => copy_string(data, PLC_NAME), 125 | 5 => copy_string(data, PLC_VERSION), 126 | 6 => copy_string(data, PLC_AUTHOR_1), 127 | 7 => copy_string(data, PLC_AUTHOR_2), 128 | _ => {} 129 | }, 130 | n if n <= globals.devices.len() => { 131 | let dev = &globals.devices[n-1]; 132 | match infotype { 133 | 0 => { 134 | data[..6].copy_from_slice(&[ 135 | dev.typcode, dev.size, dev.offset, dev.unit, 136 | dev.all_flags as u16, (dev.all_flags >> 16) as u16, 137 | ]); 138 | copy_float(&mut data[6..], dev.absmin); 139 | copy_float(&mut data[8..], dev.absmax); 140 | copy_string(&mut data[10..], dev.name); 141 | } 142 | 1 => data[0] = dev.size, 143 | 2 => data[0] = dev.offset, 144 | 3 => data[0] = dev.unit, 145 | 4 => copy_string(data, dev.name), 146 | 15 => data[..16].copy_from_slice(&dev.params), 147 | 0x10 ..= 0x17 => copy_string(data, dev.aux.get(infotype-0x10).unwrap_or(&"")), 148 | _ => {} 149 | } 150 | }, 151 | _ => {} 152 | } 153 | 154 | if infotype == 127 { 155 | data[0] = globals.cycle; 156 | } 157 | 158 | ext.indexer.request |= 0x8000; 159 | globals.cycle = globals.cycle.wrapping_add(1); 160 | } 161 | 162 | fn fb_blink(data_in: &mut EL1008, data_out: &mut EL2008, iface: &mut DiscreteOutput) { 163 | match iface.status & 0xf000 { 164 | RESET => { 165 | data_out.output = 0; 166 | iface.target = 0; 167 | iface.status = IDLE; 168 | } 169 | IDLE | WARN => { 170 | iface.status = if iface.target == iface.value { IDLE } else { WARN }; 171 | } 172 | START => { 173 | data_out.output = iface.target as u8; 174 | iface.status = IDLE; 175 | } 176 | _ => iface.status = ERROR, 177 | } 178 | 179 | iface.value = data_in.input as i16; 180 | } 181 | 182 | fn fb_magnet(inp: &mut EL3104, outp: &mut EL4132, 183 | iface: &mut FlatOutput1, vars: &mut MagnetVars) { 184 | iface.target = iface.target.max(-15.0).min(15.0); 185 | iface.param1 = iface.param1.max(-10.0).min(10.0); 186 | 187 | const SLOPE: f32 = 2000.; 188 | 189 | match iface.status & 0xf000 { 190 | RESET => { 191 | iface.status = IDLE; 192 | iface.target = 0.; 193 | } 194 | IDLE | WARN => {} 195 | START => { 196 | vars.target = iface.target; 197 | vars.start = iface.value; 198 | vars.current = iface.value; 199 | vars.cycles = 0; 200 | vars.step = iface.param1 / 100.; 201 | if vars.target < vars.start { 202 | vars.step = -vars.step; 203 | } 204 | if (vars.current - vars.target).abs() <= vars.step.abs() { 205 | vars.current = vars.target; 206 | iface.status = IDLE; 207 | } else { 208 | iface.status = BUSY; 209 | } 210 | } 211 | BUSY => { 212 | vars.current = vars.start + (vars.cycles as f32) * vars.step; 213 | if (vars.current - vars.target).abs() <= vars.step.abs() { 214 | vars.current = vars.target; 215 | iface.status = IDLE; 216 | } else { 217 | vars.cycles += 1; 218 | } 219 | } 220 | STOP => { 221 | iface.status = IDLE; 222 | } 223 | ERROR => { 224 | iface.value = 0.; 225 | } 226 | _ => iface.status = ERROR, 227 | } 228 | 229 | outp.ch1 = (vars.current * SLOPE) as i16; 230 | iface.value = inp.ch1 as f32 / SLOPE; 231 | } 232 | 233 | fn main() { 234 | let mut config = std::collections::HashMap::new(); 235 | config.insert("motor_current", Box::new(750u16) as Box); 236 | 237 | let mut plc = PlcBuilder::new("plc") 238 | .cycle_freq(100) 239 | .with_server("0.0.0.0:5020") 240 | .logging_cfg(None, false) 241 | .build::>(config).unwrap(); 242 | 243 | let mut globals = Globals::default(); 244 | globals.devices = vec![ 245 | DeviceInfo { typcode: 0x1E03, name: "Blink", offset: 42, .. Default::default() }, 246 | DeviceInfo { typcode: 0x3008, name: "Magnet", unit: 0x0007, 247 | params: [0x3c, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 248 | aux: &["output disabled", "emergency shutdown"], 249 | absmin: -15.0, absmax: 15.0, .. Default::default() }, 250 | ]; 251 | 252 | plc.run(|data, ext| { 253 | indexer(ext, &mut globals); 254 | fb_blink(&mut data.dig_in, &mut data.dig_out, &mut ext.if_blink); 255 | fb_magnet(&mut data.ana_in, &mut data.ana_out, &mut ext.if_magnet, 256 | &mut globals.v_magnet); 257 | 258 | if data.motor.mot_status & 1 != 0 { 259 | data.motor.mot_control = 0x1; 260 | } 261 | if data.motor.mot_status & 2 != 0 { 262 | data.motor.mot_target = (globals.v_magnet.current * 10000.) as _; 263 | } 264 | // let info1 = data.motor.info_data1; 265 | // let info2 = data.motor.info_data2; 266 | // println!("st = {:#x}, id = {:#x}, {:#x}", data.motor.mot_status & 0xfff, 267 | // info1, info2); 268 | println!("pos = {}", data.motor.mot_position + 0); 269 | }); 270 | } 271 | --------------------------------------------------------------------------------