├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── go.mod ├── go.sum ├── mcp ├── access_route.go ├── client.go ├── client_test.go ├── code.go ├── code_test.go ├── response_parser.go ├── response_parser_test.go ├── station.go └── station_test.go └── mirror └── mirror.go /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: [push, pull_request] 4 | jobs: 5 | test: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Checkout 9 | uses: actions/checkout@v2 10 | - name: Setup go 11 | uses: actions/setup-go@v2 12 | with: 13 | go-version: 1.x 14 | - name: Test mcp 15 | run: cd mcp && go test -race -v ./... 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Binaries for programs and plugins 2 | *.exe 3 | *.exe~ 4 | *.dll 5 | *.so 6 | *.dylib 7 | 8 | # Test binary, build with `go test -c` 9 | *.test 10 | 11 | # Output of the go coverage tool, specifically when used with LiteIDE 12 | *.out 13 | 14 | # Goland 15 | *idea -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # go-mcprotocol 2 | 3 | go-mcprotocol is a library for PLC (Programmable Logic Controller) access 4 | 5 | ## Project Status 6 | 7 | **Work In Progress** 8 | 9 | ## Usage for Library 10 | 11 | You can read plc register bellow codes. 12 | 13 | ```go 14 | client, _ := mcp.New3EClient(opts.Host, opts.Port, mcp.NewLocalStation()) 15 | read, _ := client.Read("D", 100, 3) 16 | registerBinary, _ := mcp.NewParser().Do(read) 17 | 18 | fmt.Println(string(registerBinary.Payload)) 19 | ``` 20 | 21 | #### Health Check 22 | 23 | ```go 24 | if err := client.HealthCheck(); err != nil { 25 | log.Fatalf("failed health check for plc: %v", err) 26 | } 27 | ``` 28 | 29 | ## Usage Tool 30 | 31 | ## Output file format 32 | 33 | Format is CSV. Items are timestamp and Base64 encoded MC Protocol response. 34 | 35 | ```csv 36 | 2019-10-07T07:08:00.3623052Z,0AAA//8DAAwAAAAAAAAAAAAAAAAA 37 | 2019-10-07T07:08:00.8622182Z,0AAA//8DAAwAAAAAAAAAAAAAAAAA 38 | 2019-10-07T07:08:01.3616205Z,0AAA//8DAAwAAAAAAAAAAAAAAAAA 39 | ... 40 | ``` 41 | 42 | ## Usage for tool 43 | 44 | Collect the register values​of PLC by MC Protocol(MELSEC Communication Protocol). 45 | This tools is gather plc register data and dump local files. 46 | 47 | ### Examples 48 | 49 | ```bash 50 | $ plcmirror -H -P --device D --offset 100 --num 10 --dir /var/log/plcmirror 51 | ``` 52 | 53 | ### Options 54 | 55 | ```bash 56 | > plcmirror -help 57 | Usage: 58 | plcmirror [OPTIONS] 59 | 60 | Application Options: 61 | /H, /host: PLC hostname 62 | /P, /port: Melsec communication protocol port number 63 | /D, /device: Register name like D that is mirror target 64 | /O, /offset: PLC register offset addr that is mirror target 65 | /N, /num: number of device points 66 | /dir: file output path (default: .) 67 | /I, /interval: mirroring interval [milli sec] (default: 500) 68 | 69 | Help Options: 70 | /? Show this help message 71 | /h, /help Show this help message 72 | ``` 73 | 74 | 75 | 76 | # License 77 | Apache 2 78 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/future-architect/go-mcprotocol 2 | 3 | go 1.13 4 | 5 | require github.com/google/go-cmp v0.5.2 6 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= 2 | github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 3 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 4 | -------------------------------------------------------------------------------- /mcp/access_route.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | type AccessRoute struct { 4 | Sts station 5 | Code Code 6 | } 7 | 8 | func (r *AccessRoute) BinaryRoute() []byte { 9 | 10 | return nil 11 | } 12 | 13 | func (r *AccessRoute) AsciiRoute() []byte { 14 | 15 | return nil 16 | } 17 | 18 | func (r *AccessRoute) Len() int64 { 19 | return 0 20 | } 21 | -------------------------------------------------------------------------------- /mcp/client.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "encoding/hex" 5 | "errors" 6 | "fmt" 7 | "net" 8 | ) 9 | 10 | type Client interface { 11 | Read(deviceName string, offset, numPoints int64) ([]byte, error) 12 | BitRead(deviceName string, offset, numPoints int64) ([]byte, error) 13 | Write(deviceName string, offset, numPoints int64, writeData []byte) ([]byte, error) 14 | HealthCheck() error 15 | } 16 | 17 | // client3E is 3E frame mcp client 18 | type client3E struct { 19 | // PLC address 20 | tcpAddr *net.TCPAddr 21 | // PLC station 22 | stn *station 23 | } 24 | 25 | func New3EClient(host string, port int, stn *station) (Client, error) { 26 | tcpAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%v:%v", host, port)) 27 | if err != nil { 28 | return nil, err 29 | } 30 | return &client3E{tcpAddr: tcpAddr, stn: stn}, nil 31 | } 32 | 33 | // MELSECコミュニケーションプロトコル p180 34 | // 11.4折返しテスト 35 | func (c *client3E) HealthCheck() error { 36 | requestStr := c.stn.BuildHealthCheckRequest() 37 | 38 | // binary protocol 39 | payload, err := hex.DecodeString(requestStr) 40 | if err != nil { 41 | return err 42 | } 43 | 44 | // TODO Keep-Alive 45 | conn, err := net.DialTCP("tcp", nil, c.tcpAddr) 46 | if err != nil { 47 | return err 48 | } 49 | defer conn.Close() 50 | 51 | // Send message 52 | if _, err = conn.Write(payload); err != nil { 53 | return err 54 | } 55 | 56 | // Receive message 57 | readBuff := make([]byte, 30) 58 | readLen, err := conn.Read(readBuff) 59 | if err != nil { 60 | return err 61 | } 62 | 63 | resp := readBuff[:readLen] 64 | 65 | if readLen != 18 { 66 | return errors.New("plc connect test is fail: return length is [" + fmt.Sprintf("%X", resp) + "]") 67 | } 68 | 69 | // decodeString is 折返しデータ数ヘッダ[1byte] 70 | if "0500" != fmt.Sprintf("%X", resp[11:13]) { 71 | return errors.New("plc connect test is fail: return header is [" + fmt.Sprintf("%X", resp[11:13]) + "]") 72 | } 73 | 74 | // 折返しデータ[5byte]=ABCDE 75 | if "4142434445" != fmt.Sprintf("%X", resp[13:18]) { 76 | return errors.New("plc connect test is fail: return body is [" + fmt.Sprintf("%X", resp[13:18]) + "]") 77 | } 78 | 79 | return nil 80 | } 81 | 82 | // Read is send read as word command to remote plc by mc protocol 83 | // deviceName is device code name like 'D' register. 84 | // offset is device offset addr. 85 | // numPoints is number of read device points. 86 | func (c *client3E) Read(deviceName string, offset, numPoints int64) ([]byte, error) { 87 | requestStr := c.stn.BuildReadRequest(deviceName, offset, numPoints) 88 | 89 | // TODO binary protocol 90 | payload, err := hex.DecodeString(requestStr) 91 | if err != nil { 92 | return nil, err 93 | } 94 | 95 | conn, err := net.DialTCP("tcp", nil, c.tcpAddr) 96 | if err != nil { 97 | return nil, err 98 | } 99 | defer conn.Close() 100 | 101 | // Send message 102 | if _, err = conn.Write(payload); err != nil { 103 | return nil, err 104 | } 105 | 106 | // Receive message 107 | readBuff := make([]byte, 22+2*numPoints) // 22 is response header size. [sub header + network num + unit i/o num + unit station num + response length + response code] 108 | readLen, err := conn.Read(readBuff) 109 | if err != nil { 110 | return nil, err 111 | } 112 | 113 | return readBuff[:readLen], nil 114 | } 115 | 116 | // BitRead is send read as bit command to remote plc by mc protocol 117 | // deviceName is device code name like 'D' register. 118 | // offset is device offset addr. 119 | // numPoints is number of read device points. 120 | // results of payload of BitRead will return []byte contains 0, 1, 16 or 17(hex encoded 00, 01, 10, 11) 121 | func (c *client3E) BitRead(deviceName string, offset, numPoints int64) ([]byte, error) { 122 | requestStr := c.stn.BuildBitReadRequest(deviceName, offset, numPoints) 123 | // TODO binary protocol 124 | payload, err := hex.DecodeString(requestStr) 125 | if err != nil { 126 | return nil, err 127 | } 128 | 129 | conn, err := net.DialTCP("tcp", nil, c.tcpAddr) 130 | if err != nil { 131 | return nil, err 132 | } 133 | defer conn.Close() 134 | 135 | // Send message 136 | if _, err = conn.Write(payload); err != nil { 137 | return nil, err 138 | } 139 | 140 | // Receive message 141 | readBuff := make([]byte, 22+2*numPoints) // 22 is response header size. [sub header + network num + unit i/o num + unit station num + response length + response code] 142 | readLen, err := conn.Read(readBuff) 143 | if err != nil { 144 | return nil, err 145 | } 146 | 147 | return readBuff[:readLen], nil 148 | } 149 | 150 | // Write is send write command to remote plc by mc protocol 151 | // deviceName is device code name like 'D' register. 152 | // offset is device offset addr. 153 | // writeData is data to write. 154 | // numPoints is number of write device points. 155 | // writeData is the data to be written. If writeData is larger than 2*numPoints bytes, 156 | // data larger than 2*numPoints bytes is ignored. 157 | func (c *client3E) Write(deviceName string, offset, numPoints int64, writeData []byte) ([]byte, error) { 158 | requestStr := c.stn.BuildWriteRequest(deviceName, offset, numPoints, writeData) 159 | payload, err := hex.DecodeString(requestStr) 160 | if err != nil { 161 | return nil, err 162 | } 163 | conn, err := net.DialTCP("tcp", nil, c.tcpAddr) 164 | if err != nil { 165 | return nil, err 166 | } 167 | defer conn.Close() 168 | 169 | // Send message 170 | if _, err = conn.Write(payload); err != nil { 171 | return nil, err 172 | } 173 | 174 | // Receive message 175 | readBuff := make([]byte, 22) // 22 is response header size. [sub header + network num + unit i/o num + unit station num + response length + response code] 176 | 177 | readLen, err := conn.Read(readBuff) 178 | if err != nil { 179 | return nil, err 180 | } 181 | return readBuff[:readLen], nil 182 | } 183 | -------------------------------------------------------------------------------- /mcp/client_test.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "encoding/hex" 5 | "os" 6 | "strconv" 7 | "strings" 8 | "testing" 9 | ) 10 | 11 | var ( 12 | testPLCHost string 13 | testPLCPort int 14 | ) 15 | 16 | func init() { 17 | testPLCHost = os.Getenv("PLC_TEST_HOST") 18 | if p := os.Getenv("PLC_TEST_PORT"); p != "" { 19 | if port, err := strconv.Atoi(p); err == nil { 20 | testPLCPort = port 21 | } 22 | } 23 | } 24 | 25 | func TestClient3E_Read(t *testing.T) { 26 | // running only when there is and plc that can be accepted mc protocol 27 | if testPLCHost == "" { 28 | t.Skip("environment variable PLC_TEST_HOST is not set") 29 | } 30 | if testPLCPort == 0 { 31 | t.Skip("environment variable PLC_TEST_PORT is not set") 32 | } 33 | 34 | client, err := New3EClient(testPLCHost, testPLCPort, NewLocalStation()) 35 | if err != nil { 36 | t.Fatalf("PLC does not exists? %v", err) 37 | } 38 | 39 | // 1 device 40 | resp1, err := client.Read("D", 100, 1) 41 | if err != nil { 42 | t.Fatalf("unexpected mcp read err: %v", err) 43 | } 44 | 45 | if len(resp1) != 13 { 46 | t.Fatalf("expected %v but actual is %v", 13, len(resp1)) 47 | } 48 | if hex.EncodeToString(resp1) != strings.ReplaceAll("d000 00 ff ff03 0004 0000 0000 00", " ", "") { 49 | t.Fatalf("expected %v but actual is %v", "d00000ffff0300040000000000", hex.EncodeToString(resp1)) 50 | } 51 | 52 | // 3 device 53 | resp2, err := client.Read("D", 100, 5) 54 | if err != nil { 55 | t.Fatalf("unexpected mcp read err: %v", err) 56 | } 57 | 58 | if len(resp2) != 21 { 59 | t.Fatalf("expected %v but actual is %v", 21, len(resp2)) 60 | } 61 | 62 | if hex.EncodeToString(resp2) != strings.ReplaceAll("d000 00 ff ff03 000c 0000 0000 000000000000000000", " ", "") { 63 | t.Fatalf("expected %v but actual is %v", "d00000ffff03000c00000000000000000000000000", hex.EncodeToString(resp2)) 64 | } 65 | 66 | } 67 | 68 | func TestClient3E_BitRead(t *testing.T) { 69 | // running only when there is and plc that can be accepted mc protocol 70 | if testPLCHost == "" { 71 | t.Skip("environment variable PLC_TEST_HOST is not set") 72 | } 73 | if testPLCPort == 0 { 74 | t.Skip("environment variable PLC_TEST_PORT is not set") 75 | } 76 | 77 | client, err := New3EClient(testPLCHost, testPLCPort, NewLocalStation()) 78 | if err != nil { 79 | t.Fatalf("PLC does not exists? %v", err) 80 | } 81 | 82 | // 1 device 83 | resp1, err := client.BitRead("B", 0, 1) 84 | if err != nil { 85 | t.Fatalf("unexpected mcp read err: %v", err) 86 | } 87 | 88 | if len(resp1) != 12 { 89 | t.Fatalf("expected %v but actual is %v", 12, len(resp1)) 90 | } 91 | if hex.EncodeToString(resp1) != strings.ReplaceAll("d000 00 ff ff03 0003 0000 0000", " ", "") { 92 | t.Fatalf("expected %v but actual is %v", "d00000ffff03000300000000", hex.EncodeToString(resp1)) 93 | } 94 | 95 | // 3 device 96 | resp2, err := client.BitRead("B", 0, 5) 97 | if err != nil { 98 | t.Fatalf("unexpected mcp read err: %v", err) 99 | } 100 | 101 | if len(resp2) != 14 { 102 | t.Fatalf("expected %v but actual is %v", 14, len(resp2)) 103 | } 104 | 105 | if hex.EncodeToString(resp2) != strings.ReplaceAll("d000 00 ff ff03 0005 0000 0000 0000", " ", "") { 106 | t.Fatalf("expected %v but actual is %v", "d00000ffff030005000000000000", hex.EncodeToString(resp2)) 107 | } 108 | 109 | // numpoints 5 and 6 will return same responce length 110 | resp3, err := client.BitRead("B", 0, 6) 111 | if err != nil { 112 | t.Fatalf("unexpected mcp read err: %v", err) 113 | } 114 | 115 | if len(resp2) != 14 { 116 | t.Fatalf("expected %v but actual is %v", 14, len(resp3)) 117 | } 118 | 119 | if hex.EncodeToString(resp2) != strings.ReplaceAll("d000 00 ff ff03 0005 0000 0000 0000", " ", "") { 120 | t.Fatalf("expected %v but actual is %v", "d00000ffff030005000000000000", hex.EncodeToString(resp3)) 121 | } 122 | } 123 | 124 | func TestClient3E_Write(t *testing.T) { 125 | // running only when there is and plc that can be accepted mc protocol 126 | if testPLCHost == "" { 127 | t.Skip("environment variable PLC_TEST_HOST is not set") 128 | } 129 | if testPLCPort == 0 { 130 | t.Skip("environment variable PLC_TEST_PORT is not set") 131 | } 132 | 133 | client, err := New3EClient(testPLCHost, testPLCPort, NewLocalStation()) 134 | if err != nil { 135 | t.Fatalf("PLC does not exists? %v", err) 136 | } 137 | 138 | _, err = client.Write("D", 100, 4, []byte("test")) 139 | if err != nil { 140 | t.Fatalf("unexpected mcp write err: %v", err) 141 | } 142 | } 143 | 144 | func TestClient3E_Ping(t *testing.T) { 145 | // running only when there is and plc that can be accepted mc protocol 146 | if testPLCHost == "" { 147 | t.Skip("environment variable PLC_TEST_HOST is not set") 148 | } 149 | if testPLCPort == 0 { 150 | t.Skip("environment variable PLC_TEST_PORT is not set") 151 | } 152 | 153 | client, err := New3EClient(testPLCHost, testPLCPort, NewLocalStation()) 154 | if err != nil { 155 | t.Fatalf("PLC does not exists? %v", err) 156 | } 157 | 158 | if err := client.HealthCheck(); err != nil { 159 | t.Fatalf("unexpected error occured %v", err) 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /mcp/code.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "encoding/hex" 7 | ) 8 | 9 | // PLC Data communication code. 10 | // This item is operating byte order. 11 | type Code int 12 | 13 | const ( 14 | // Ascii code is normal mode. 15 | // Stored from upper byte to lower byte. 16 | Ascii Code = iota 17 | 18 | // Binary code is approximately half the amount of communication data compared to communication using ASCII code 19 | // Stored from lower byte to upper byte. 20 | Binary 21 | ) 22 | 23 | func (c Code) EncodeHex(s string) ([]byte, error) { 24 | if c == Ascii { 25 | return []byte(s), nil 26 | } 27 | 28 | decode, err := hex.DecodeString(s) 29 | if err != nil { 30 | return nil, err 31 | } 32 | 33 | buff := new(bytes.Buffer) 34 | _ = binary.Write(buff, binary.LittleEndian, decode) 35 | return buff.Bytes(), nil 36 | } 37 | -------------------------------------------------------------------------------- /mcp/code_test.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "encoding/hex" 5 | "testing" 6 | ) 7 | 8 | func TestCode_EncodeHex(t *testing.T) { 9 | cases := []struct { 10 | input string 11 | expected string 12 | }{ 13 | {input: "0401", expected: "0104"}, 14 | } 15 | 16 | for _, v := range cases { 17 | actual, err := Binary.EncodeHex(v.input) 18 | if err != nil { 19 | t.Errorf("something wrong: input is %v", v.input) 20 | continue 21 | } 22 | 23 | if hex.EncodeToString(actual) != v.expected { 24 | t.Errorf("wrong result: expected is %v but actual is %v", "0104", hex.EncodeToString(actual)) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /mcp/response_parser.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | type parser struct { 9 | } 10 | 11 | func NewParser() *parser { 12 | return &parser{} 13 | } 14 | 15 | // Response represents mcp response 16 | type Response struct { 17 | // Sub header 18 | SubHeader string 19 | // network number 20 | NetworkNum string 21 | // PC number 22 | PCNum string 23 | // Request Unit I/O number 24 | UnitIONum string 25 | // Request Unit station number 26 | UnitStationNum string 27 | // Response data length 28 | DataLen string 29 | // Response data code 30 | EndCode string 31 | // Response data 32 | Payload []byte 33 | // error data 34 | ErrInfo []byte 35 | } 36 | 37 | func (p *parser) Do(resp []byte) (*Response, error) { 38 | if len(resp) < 11 { 39 | return nil, errors.New("length must be larger than 22 byte") 40 | } 41 | 42 | subHeaderB := resp[0:2] 43 | networkNumB := resp[2:3] 44 | pcNumB := resp[3:4] 45 | unitIONumB := resp[4:6] 46 | unitStationNumB := resp[6:7] 47 | dataLenB := resp[7:9] 48 | endCodeB := resp[9:11] 49 | payloadB := resp[11:] 50 | 51 | return &Response{ 52 | SubHeader: fmt.Sprintf("%X", subHeaderB), 53 | NetworkNum: fmt.Sprintf("%X", networkNumB), 54 | PCNum: fmt.Sprintf("%X", pcNumB), 55 | UnitIONum: fmt.Sprintf("%X", unitIONumB), 56 | UnitStationNum: fmt.Sprintf("%X", unitStationNumB), 57 | DataLen: fmt.Sprintf("%X", dataLenB), 58 | EndCode: fmt.Sprintf("%X", endCodeB), 59 | Payload: payloadB, 60 | }, nil 61 | } 62 | -------------------------------------------------------------------------------- /mcp/response_parser_test.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "encoding/hex" 5 | "github.com/google/go-cmp/cmp" 6 | "testing" 7 | ) 8 | 9 | func TestParser_Do(t *testing.T) { 10 | mcResp, _ := hex.DecodeString("d00000ffff0300040000000000") 11 | 12 | p := NewParser() 13 | response, err := p.Do(mcResp) 14 | if err != nil { 15 | t.Fatalf("unexpected parser err: %v", err) 16 | } 17 | 18 | expected := &Response{ 19 | SubHeader: "D000", 20 | NetworkNum: "00", 21 | PCNum: "FF", 22 | UnitIONum: "FF03", 23 | UnitStationNum: "00", 24 | DataLen: "0400", 25 | EndCode: "0000", 26 | Payload: []uint8{0x00, 0x00}, 27 | ErrInfo: nil, 28 | } 29 | 30 | if diff := cmp.Diff(response, expected); diff != "" { 31 | t.Errorf("parse Resp differs: (-got +want)\n%s", diff) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /mcp/station.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "fmt" 7 | ) 8 | 9 | const ( 10 | SUB_HEADER = "5000" // 3Eフレームでは固定 11 | 12 | HEALTH_CHECK_COMMAND = "1906" // binary mode expression. if ascii mode then 0619 13 | HEALTH_CHECK_SUBCOMMAND = "0000" 14 | 15 | READ_COMMAND = "0104" // binary mode expression. if ascii mode then 0401 16 | READ_SUB_COMMAND = "0000" 17 | BIT_READ_SUB_COMMAND = "0100" 18 | 19 | WRITE_COMMAND = "0114" // binary mode expression. if ascii mode then 1401 20 | WRITE_SUB_COMMAND = "0000" 21 | 22 | MONITORING_TIMER = "1000" // 3[sec] 23 | ) 24 | 25 | // deviceCodes is device name and hex value map 26 | var deviceCodes = map[string]string{ 27 | "X": "9C", 28 | "Y": "9D", 29 | "M": "90", 30 | "L": "92", 31 | "F": "93", 32 | "V": "94", 33 | "B": "A0", 34 | "W": "B4", 35 | "D": "A8", 36 | } 37 | 38 | // Each single PLC that is connected on MELSECNET and CC-Link IE is called a station. 39 | type station struct { 40 | // PLC Network number 41 | networkNum string 42 | // PC Number 43 | pcNum string 44 | // PLC stn Unit I/O Number 45 | unitIONum string 46 | // PLC stn Unit Station Number 47 | unitStationNum string 48 | } 49 | 50 | func NewStation(networkNum, pcNum, unitIONum, unitStationNum string) *station { 51 | return &station{ 52 | networkNum: networkNum, 53 | pcNum: pcNum, 54 | unitIONum: unitIONum, 55 | unitStationNum: unitStationNum, 56 | } 57 | } 58 | 59 | // local stn stn. local stn is 自局. 60 | func NewLocalStation() *station { 61 | return &station{ 62 | networkNum: "00", // 自局の場合は00固定 63 | pcNum: "FF", // 自局の場合はFF固定 64 | unitIONum: "FF03", // マルチドロップ接続などでない場合はFF03固定値 65 | unitStationNum: "00", // マルチドロップ接続などでない場合は00固定値 66 | } 67 | } 68 | 69 | func (h *station) BuildHealthCheckRequest() string { 70 | 71 | returnDataNum := "0500" // 5 device. if ascii mode then 0005 72 | returnData := "4142434445" // value is "ABCDE". 73 | 74 | requestStr := HEALTH_CHECK_COMMAND + HEALTH_CHECK_SUBCOMMAND + returnDataNum + returnData 75 | 76 | // data length 77 | requestCharLen := len(MONITORING_TIMER+requestStr) / 2 // 1byte=2char 78 | dataLenBuff := new(bytes.Buffer) 79 | _ = binary.Write(dataLenBuff, binary.LittleEndian, int64(requestCharLen)) 80 | dataLen := fmt.Sprintf("%X", dataLenBuff.Bytes()[0:2]) // 2byte固定 81 | 82 | return SUB_HEADER + 83 | h.networkNum + 84 | h.pcNum + 85 | h.unitIONum + 86 | h.unitStationNum + 87 | dataLen + 88 | MONITORING_TIMER + 89 | requestStr 90 | } 91 | 92 | // BuildReadRequest represents MCP read as word command. 93 | // deviceName is device code name like 'D' register. 94 | // offset is device offset addr. 95 | // numPoints is number of read device points. 96 | func (h *station) BuildReadRequest(deviceName string, offset, numPoints int64) string { 97 | 98 | // get device symbol hex layout 99 | deviceCode := deviceCodes[deviceName] 100 | 101 | // offset convert to little endian layout 102 | // MELSECコミュニケーションプロトコル リファレンス(p67) MELSEC-Q/L: 3[byte], MELSEC iQ-R: 4[byte] 103 | offsetBuff := new(bytes.Buffer) 104 | _ = binary.Write(offsetBuff, binary.LittleEndian, offset) 105 | offsetHex := fmt.Sprintf("%X", offsetBuff.Bytes()[0:3]) // 仮にQシリーズとするので3byte trim 106 | 107 | // read points 108 | pointsBuff := new(bytes.Buffer) 109 | _ = binary.Write(pointsBuff, binary.LittleEndian, numPoints) 110 | points := fmt.Sprintf("%X", pointsBuff.Bytes()[0:2]) // 2byte固定 111 | 112 | // data length 113 | requestCharLen := len(MONITORING_TIMER+READ_COMMAND+READ_SUB_COMMAND+deviceCode+offsetHex+points) / 2 // 1byte=2char 114 | dataLenBuff := new(bytes.Buffer) 115 | _ = binary.Write(dataLenBuff, binary.LittleEndian, int64(requestCharLen)) 116 | dataLen := fmt.Sprintf("%X", dataLenBuff.Bytes()[0:2]) // 2byte固定 117 | 118 | return SUB_HEADER + 119 | h.networkNum + 120 | h.pcNum + 121 | h.unitIONum + 122 | h.unitStationNum + 123 | dataLen + 124 | MONITORING_TIMER + 125 | READ_COMMAND + 126 | READ_SUB_COMMAND + 127 | offsetHex + 128 | deviceCode + 129 | points 130 | } 131 | 132 | // BuildReadRequest represents MCP read as bit command. 133 | // deviceName is device code name like 'D' register. 134 | // offset is device offset addr. 135 | // numPoints is number of read device points. 136 | func (h *station) BuildBitReadRequest(deviceName string, offset, numPoints int64) string { 137 | 138 | // get device symbol hex layout 139 | deviceCode := deviceCodes[deviceName] 140 | 141 | // offset convert to little endian layout 142 | // MELSECコミュニケーションプロトコル リファレンス(p67) MELSEC-Q/L: 3[byte], MELSEC iQ-R: 4[byte] 143 | offsetBuff := new(bytes.Buffer) 144 | _ = binary.Write(offsetBuff, binary.LittleEndian, offset) 145 | offsetHex := fmt.Sprintf("%X", offsetBuff.Bytes()[0:3]) // 仮にQシリーズとするので3byte trim 146 | 147 | // read points 148 | pointsBuff := new(bytes.Buffer) 149 | _ = binary.Write(pointsBuff, binary.LittleEndian, numPoints) 150 | points := fmt.Sprintf("%X", pointsBuff.Bytes()[0:2]) // 2byte固定 151 | 152 | // data length 153 | requestCharLen := len(MONITORING_TIMER+READ_COMMAND+BIT_READ_SUB_COMMAND+deviceCode+offsetHex+points) / 2 // 1byte=2char 154 | dataLenBuff := new(bytes.Buffer) 155 | _ = binary.Write(dataLenBuff, binary.LittleEndian, int64(requestCharLen)) 156 | dataLen := fmt.Sprintf("%X", dataLenBuff.Bytes()[0:2]) // 2byte固定 157 | 158 | return SUB_HEADER + 159 | h.networkNum + 160 | h.pcNum + 161 | h.unitIONum + 162 | h.unitStationNum + 163 | dataLen + 164 | MONITORING_TIMER + 165 | READ_COMMAND + 166 | BIT_READ_SUB_COMMAND + 167 | offsetHex + 168 | deviceCode + 169 | points 170 | } 171 | 172 | // BuildWriteRequest represents MCP write command. 173 | // deviceName is device code name like 'D' register. 174 | // offset is device offset addr. 175 | // writeData is data to write. 176 | // numPoints is number of write device points. 177 | // writeData is the data to be written. If writeData is larger than 2*numPoints bytes, 178 | // data larger than 2*numPoints bytes is ignored. 179 | func (h *station) BuildWriteRequest(deviceName string, offset, numPoints int64, writeData []byte) string { 180 | 181 | // get device symbol hex layout 182 | deviceCode := deviceCodes[deviceName] 183 | 184 | // offset convert to little endian layout 185 | // MELSECコミュニケーションプロトコル リファレンス(p67) MELSEC-Q/L: 3[byte], MELSEC iQ-R: 4[byte] 186 | offsetBuff := new(bytes.Buffer) 187 | _ = binary.Write(offsetBuff, binary.LittleEndian, offset) 188 | offsetHex := fmt.Sprintf("%X", offsetBuff.Bytes()[0:3]) // 仮にQシリーズとするので3byte trim 189 | 190 | // convert write data to little endian word 191 | writeBuff := new(bytes.Buffer) 192 | _ = binary.Write(writeBuff, binary.LittleEndian, writeData) 193 | writeHex := fmt.Sprintf("%X", writeBuff.Bytes()[0:2*numPoints]) // 2 byte per 1 device point 194 | 195 | // write points 196 | pointsBuff := new(bytes.Buffer) 197 | _ = binary.Write(pointsBuff, binary.LittleEndian, numPoints) 198 | points := fmt.Sprintf("%X", pointsBuff.Bytes()[0:2]) // 2byte固定 199 | 200 | // data length 201 | requestCharLen := len(MONITORING_TIMER+WRITE_COMMAND+WRITE_SUB_COMMAND+deviceCode+offsetHex+points+writeHex) / 2 // 1byte=2char 202 | dataLenBuff := new(bytes.Buffer) 203 | _ = binary.Write(dataLenBuff, binary.LittleEndian, int64(requestCharLen)) 204 | dataLen := fmt.Sprintf("%X", dataLenBuff.Bytes()[0:2]) // 2byte固定 205 | return SUB_HEADER + 206 | h.networkNum + 207 | h.pcNum + 208 | h.unitIONum + 209 | h.unitStationNum + 210 | dataLen + 211 | MONITORING_TIMER + 212 | WRITE_COMMAND + 213 | WRITE_SUB_COMMAND + 214 | offsetHex + 215 | deviceCode + 216 | points + 217 | writeHex 218 | } 219 | 220 | func (h *station) BuildAccessPath() { 221 | 222 | } 223 | -------------------------------------------------------------------------------- /mcp/station_test.go: -------------------------------------------------------------------------------- 1 | package mcp 2 | 3 | import "testing" 4 | 5 | func TestStation_BuildRRequest(t *testing.T) { 6 | station := NewLocalStation() 7 | request := station.BuildReadRequest("D", 300, 3) 8 | 9 | if request != "500000FFFF03000C001000010400002C0100A80300" { 10 | t.Fatalf("expected %v but actual is %v", "500000FFFF03000C001000010400002C0100A80300", request) 11 | } 12 | 13 | request2 := station.BuildReadRequest("D", 500, 50) 14 | if request2 != "500000FFFF03000C00100001040000F40100A83200" { 15 | t.Fatalf("expected %v but actual is %v", "500000FFFF03000C00100001040000F40100A83200", request2) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /mirror/mirror.go: -------------------------------------------------------------------------------- 1 | package mirror 2 | 3 | import ( 4 | "encoding/base64" 5 | "fmt" 6 | "github.com/pj-cancan/plcmirror/mcp" 7 | "io" 8 | "log" 9 | "sync" 10 | "time" 11 | ) 12 | 13 | var ( 14 | mu sync.Mutex 15 | permitRW bool 16 | ) 17 | 18 | type fileMirror struct { 19 | c mcp.Client 20 | w io.Writer 21 | deviceName string 22 | offset int64 23 | numPoints int64 24 | interval time.Duration 25 | } 26 | 27 | func NewFileMirror(c mcp.Client, w io.Writer, deviceName string, offset, numPoints int64, interval time.Duration) *fileMirror { 28 | return &fileMirror{ 29 | c: c, 30 | w: w, 31 | deviceName: deviceName, 32 | offset: offset, 33 | numPoints: numPoints, 34 | interval: interval, 35 | } 36 | } 37 | 38 | func (m *fileMirror) RunAndServe() error { 39 | c := time.Tick(m.interval) 40 | for { 41 | select { 42 | case <-c: 43 | go m.readAndWrite() 44 | } 45 | } 46 | } 47 | 48 | func (m *fileMirror) readAndWrite() { 49 | 50 | if !m.Lock() { 51 | log.Printf("[INFO] skip readAndWrite because goroutine cannnot get lock") 52 | // skip because cannot get lock 53 | return 54 | } 55 | defer m.Unlock() 56 | 57 | bytes, err := m.c.Read(m.deviceName, m.offset, m.numPoints) 58 | if err != nil { 59 | log.Printf("[ERROR] plc read error: %v\n", err) 60 | return 61 | } 62 | payload := base64.StdEncoding.EncodeToString(bytes) 63 | now := time.Now().UTC().Format(time.RFC3339Nano) 64 | 65 | _, err = m.w.Write([]byte(fmt.Sprintf("%v,%v\n", now, payload))) 66 | if err != nil { 67 | log.Printf("[ERROR] plc data file write error: %v\n", err) 68 | } 69 | 70 | } 71 | 72 | // Guards duplicate plc access and skip when delay read operation for reducing plc workload 73 | func (m *fileMirror) Lock() bool { 74 | mu.Lock() 75 | defer mu.Unlock() 76 | if permitRW { 77 | return false 78 | } 79 | permitRW = true 80 | return true 81 | } 82 | 83 | func (m *fileMirror) Unlock() { 84 | mu.Lock() 85 | permitRW = false 86 | mu.Unlock() 87 | } 88 | --------------------------------------------------------------------------------