├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── example └── main.go ├── handler.go ├── handler_test.go ├── logo.png ├── logo.svg ├── message.go ├── message_test.go ├── server.go └── server_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | .coverage.out 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: go 2 | 3 | go: 4 | - 1.8 5 | 6 | install: 7 | - make install 8 | 9 | # Move the code to the namespace advancedclimatesystems instead of 10 | # AdvancedClimateSystems to prevent import problems. 11 | - mkdir -p $HOME/gopath/src/github.com/advancedclimatesystems/ 12 | - mv $HOME/gopath/src/github.com/AdvancedClimateSystems/goldfish $HOME/gopath/src/github.com/advancedclimatesystems/ 13 | - cd $HOME/gopath/src/github.com/advancedclimatesystems/goldfish 14 | 15 | script: 16 | - make lint 17 | - make test 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 3 | 1. Definitions 4 | 5 | 1.1. "Contributor" 6 | 7 | means each individual or legal entity that creates, contributes to the 8 | creation of, or owns Covered Software. 9 | 10 | 1.2. "Contributor Version" 11 | 12 | means the combination of the Contributions of others (if any) used by a 13 | Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | 17 | means Covered Software of a particular Contributor. 18 | 19 | 1.4. "Covered Software" 20 | 21 | means Source Code Form to which the initial Contributor has attached the 22 | notice in Exhibit A, the Executable Form of such Source Code Form, and 23 | Modifications of such Source Code Form, in each case including portions 24 | thereof. 25 | 26 | 1.5. "Incompatible With Secondary Licenses" 27 | means 28 | 29 | a. that the initial Contributor has attached the notice described in 30 | Exhibit B to the Covered Software; or 31 | 32 | b. that the Covered Software was made available under the terms of 33 | version 1.1 or earlier of the License, but not also under the terms of 34 | a Secondary License. 35 | 36 | 1.6. "Executable Form" 37 | 38 | means any form of the work other than Source Code Form. 39 | 40 | 1.7. "Larger Work" 41 | 42 | means a work that combines Covered Software with other material, in a 43 | separate file or files, that is not Covered Software. 44 | 45 | 1.8. "License" 46 | 47 | means this document. 48 | 49 | 1.9. "Licensable" 50 | 51 | means having the right to grant, to the maximum extent possible, whether 52 | at the time of the initial grant or subsequently, any and all of the 53 | rights conveyed by this License. 54 | 55 | 1.10. "Modifications" 56 | 57 | means any of the following: 58 | 59 | a. any file in Source Code Form that results from an addition to, 60 | deletion from, or modification of the contents of Covered Software; or 61 | 62 | b. any new file in Source Code Form that contains any Covered Software. 63 | 64 | 1.11. "Patent Claims" of a Contributor 65 | 66 | means any patent claim(s), including without limitation, method, 67 | process, and apparatus claims, in any patent Licensable by such 68 | Contributor that would be infringed, but for the grant of the License, 69 | by the making, using, selling, offering for sale, having made, import, 70 | or transfer of either its Contributions or its Contributor Version. 71 | 72 | 1.12. "Secondary License" 73 | 74 | means either the GNU General Public License, Version 2.0, the GNU Lesser 75 | General Public License, Version 2.1, the GNU Affero General Public 76 | License, Version 3.0, or any later versions of those licenses. 77 | 78 | 1.13. "Source Code Form" 79 | 80 | means the form of the work preferred for making modifications. 81 | 82 | 1.14. "You" (or "Your") 83 | 84 | means an individual or a legal entity exercising rights under this 85 | License. For legal entities, "You" includes any entity that controls, is 86 | controlled by, or is under common control with You. For purposes of this 87 | definition, "control" means (a) the power, direct or indirect, to cause 88 | the direction or management of such entity, whether by contract or 89 | otherwise, or (b) ownership of more than fifty percent (50%) of the 90 | outstanding shares or beneficial ownership of such entity. 91 | 92 | 93 | 2. License Grants and Conditions 94 | 95 | 2.1. Grants 96 | 97 | Each Contributor hereby grants You a world-wide, royalty-free, 98 | non-exclusive license: 99 | 100 | a. under intellectual property rights (other than patent or trademark) 101 | Licensable by such Contributor to use, reproduce, make available, 102 | modify, display, perform, distribute, and otherwise exploit its 103 | Contributions, either on an unmodified basis, with Modifications, or 104 | as part of a Larger Work; and 105 | 106 | b. under Patent Claims of such Contributor to make, use, sell, offer for 107 | sale, have made, import, and otherwise transfer either its 108 | Contributions or its Contributor Version. 109 | 110 | 2.2. Effective Date 111 | 112 | The licenses granted in Section 2.1 with respect to any Contribution 113 | become effective for each Contribution on the date the Contributor first 114 | distributes such Contribution. 115 | 116 | 2.3. Limitations on Grant Scope 117 | 118 | The licenses granted in this Section 2 are the only rights granted under 119 | this License. No additional rights or licenses will be implied from the 120 | distribution or licensing of Covered Software under this License. 121 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 122 | Contributor: 123 | 124 | a. for any code that a Contributor has removed from Covered Software; or 125 | 126 | b. for infringements caused by: (i) Your and any other third party's 127 | modifications of Covered Software, or (ii) the combination of its 128 | Contributions with other software (except as part of its Contributor 129 | Version); or 130 | 131 | c. under Patent Claims infringed by Covered Software in the absence of 132 | its Contributions. 133 | 134 | This License does not grant any rights in the trademarks, service marks, 135 | or logos of any Contributor (except as may be necessary to comply with 136 | the notice requirements in Section 3.4). 137 | 138 | 2.4. Subsequent Licenses 139 | 140 | No Contributor makes additional grants as a result of Your choice to 141 | distribute the Covered Software under a subsequent version of this 142 | License (see Section 10.2) or under the terms of a Secondary License (if 143 | permitted under the terms of Section 3.3). 144 | 145 | 2.5. Representation 146 | 147 | Each Contributor represents that the Contributor believes its 148 | Contributions are its original creation(s) or it has sufficient rights to 149 | grant the rights to its Contributions conveyed by this License. 150 | 151 | 2.6. Fair Use 152 | 153 | This License is not intended to limit any rights You have under 154 | applicable copyright doctrines of fair use, fair dealing, or other 155 | equivalents. 156 | 157 | 2.7. Conditions 158 | 159 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 160 | Section 2.1. 161 | 162 | 163 | 3. Responsibilities 164 | 165 | 3.1. Distribution of Source Form 166 | 167 | All distribution of Covered Software in Source Code Form, including any 168 | Modifications that You create or to which You contribute, must be under 169 | the terms of this License. You must inform recipients that the Source 170 | Code Form of the Covered Software is governed by the terms of this 171 | License, and how they can obtain a copy of this License. You may not 172 | attempt to alter or restrict the recipients' rights in the Source Code 173 | Form. 174 | 175 | 3.2. Distribution of Executable Form 176 | 177 | If You distribute Covered Software in Executable Form then: 178 | 179 | a. such Covered Software must also be made available in Source Code Form, 180 | as described in Section 3.1, and You must inform recipients of the 181 | Executable Form how they can obtain a copy of such Source Code Form by 182 | reasonable means in a timely manner, at a charge no more than the cost 183 | of distribution to the recipient; and 184 | 185 | b. You may distribute such Executable Form under the terms of this 186 | License, or sublicense it under different terms, provided that the 187 | license for the Executable Form does not attempt to limit or alter the 188 | recipients' rights in the Source Code Form under this License. 189 | 190 | 3.3. Distribution of a Larger Work 191 | 192 | You may create and distribute a Larger Work under terms of Your choice, 193 | provided that You also comply with the requirements of this License for 194 | the Covered Software. If the Larger Work is a combination of Covered 195 | Software with a work governed by one or more Secondary Licenses, and the 196 | Covered Software is not Incompatible With Secondary Licenses, this 197 | License permits You to additionally distribute such Covered Software 198 | under the terms of such Secondary License(s), so that the recipient of 199 | the Larger Work may, at their option, further distribute the Covered 200 | Software under the terms of either this License or such Secondary 201 | License(s). 202 | 203 | 3.4. Notices 204 | 205 | You may not remove or alter the substance of any license notices 206 | (including copyright notices, patent notices, disclaimers of warranty, or 207 | limitations of liability) contained within the Source Code Form of the 208 | Covered Software, except that You may alter any license notices to the 209 | extent required to remedy known factual inaccuracies. 210 | 211 | 3.5. Application of Additional Terms 212 | 213 | You may choose to offer, and to charge a fee for, warranty, support, 214 | indemnity or liability obligations to one or more recipients of Covered 215 | Software. However, You may do so only on Your own behalf, and not on 216 | behalf of any Contributor. You must make it absolutely clear that any 217 | such warranty, support, indemnity, or liability obligation is offered by 218 | You alone, and You hereby agree to indemnify every Contributor for any 219 | liability incurred by such Contributor as a result of warranty, support, 220 | indemnity or liability terms You offer. You may include additional 221 | disclaimers of warranty and limitations of liability specific to any 222 | jurisdiction. 223 | 224 | 4. Inability to Comply Due to Statute or Regulation 225 | 226 | If it is impossible for You to comply with any of the terms of this License 227 | with respect to some or all of the Covered Software due to statute, 228 | judicial order, or regulation then You must: (a) comply with the terms of 229 | this License to the maximum extent possible; and (b) describe the 230 | limitations and the code they affect. Such description must be placed in a 231 | text file included with all distributions of the Covered Software under 232 | this License. Except to the extent prohibited by statute or regulation, 233 | such description must be sufficiently detailed for a recipient of ordinary 234 | skill to be able to understand it. 235 | 236 | 5. Termination 237 | 238 | 5.1. The rights granted under this License will terminate automatically if You 239 | fail to comply with any of its terms. However, if You become compliant, 240 | then the rights granted under this License from a particular Contributor 241 | are reinstated (a) provisionally, unless and until such Contributor 242 | explicitly and finally terminates Your grants, and (b) on an ongoing 243 | basis, if such Contributor fails to notify You of the non-compliance by 244 | some reasonable means prior to 60 days after You have come back into 245 | compliance. Moreover, Your grants from a particular Contributor are 246 | reinstated on an ongoing basis if such Contributor notifies You of the 247 | non-compliance by some reasonable means, this is the first time You have 248 | received notice of non-compliance with this License from such 249 | Contributor, and You become compliant prior to 30 days after Your receipt 250 | of the notice. 251 | 252 | 5.2. If You initiate litigation against any entity by asserting a patent 253 | infringement claim (excluding declaratory judgment actions, 254 | counter-claims, and cross-claims) alleging that a Contributor Version 255 | directly or indirectly infringes any patent, then the rights granted to 256 | You by any and all Contributors for the Covered Software under Section 257 | 2.1 of this License shall terminate. 258 | 259 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 260 | license agreements (excluding distributors and resellers) which have been 261 | validly granted by You or Your distributors under this License prior to 262 | termination shall survive termination. 263 | 264 | 6. Disclaimer of Warranty 265 | 266 | Covered Software is provided under this License on an "as is" basis, 267 | without warranty of any kind, either expressed, implied, or statutory, 268 | including, without limitation, warranties that the Covered Software is free 269 | of defects, merchantable, fit for a particular purpose or non-infringing. 270 | The entire risk as to the quality and performance of the Covered Software 271 | is with You. Should any Covered Software prove defective in any respect, 272 | You (not any Contributor) assume the cost of any necessary servicing, 273 | repair, or correction. This disclaimer of warranty constitutes an essential 274 | part of this License. No use of any Covered Software is authorized under 275 | this License except under this disclaimer. 276 | 277 | 7. Limitation of Liability 278 | 279 | Under no circumstances and under no legal theory, whether tort (including 280 | negligence), contract, or otherwise, shall any Contributor, or anyone who 281 | distributes Covered Software as permitted above, be liable to You for any 282 | direct, indirect, special, incidental, or consequential damages of any 283 | character including, without limitation, damages for lost profits, loss of 284 | goodwill, work stoppage, computer failure or malfunction, or any and all 285 | other commercial damages or losses, even if such party shall have been 286 | informed of the possibility of such damages. This limitation of liability 287 | shall not apply to liability for death or personal injury resulting from 288 | such party's negligence to the extent applicable law prohibits such 289 | limitation. Some jurisdictions do not allow the exclusion or limitation of 290 | incidental or consequential damages, so this exclusion and limitation may 291 | not apply to You. 292 | 293 | 8. Litigation 294 | 295 | Any litigation relating to this License may be brought only in the courts 296 | of a jurisdiction where the defendant maintains its principal place of 297 | business and such litigation shall be governed by laws of that 298 | jurisdiction, without reference to its conflict-of-law provisions. Nothing 299 | in this Section shall prevent a party's ability to bring cross-claims or 300 | counter-claims. 301 | 302 | 9. Miscellaneous 303 | 304 | This License represents the complete agreement concerning the subject 305 | matter hereof. If any provision of this License is held to be 306 | unenforceable, such provision shall be reformed only to the extent 307 | necessary to make it enforceable. Any law or regulation which provides that 308 | the language of a contract shall be construed against the drafter shall not 309 | be used to construe this License against a Contributor. 310 | 311 | 312 | 10. Versions of the License 313 | 314 | 10.1. New Versions 315 | 316 | Mozilla Foundation is the license steward. Except as provided in Section 317 | 10.3, no one other than the license steward has the right to modify or 318 | publish new versions of this License. Each version will be given a 319 | distinguishing version number. 320 | 321 | 10.2. Effect of New Versions 322 | 323 | You may distribute the Covered Software under the terms of the version 324 | of the License under which You originally received the Covered Software, 325 | or under the terms of any subsequent version published by the license 326 | steward. 327 | 328 | 10.3. Modified Versions 329 | 330 | If you create software not governed by this License, and you want to 331 | create a new license for such software, you may create and use a 332 | modified version of this License if you rename the license and remove 333 | any references to the name of the license steward (except to note that 334 | such modified license differs from this License). 335 | 336 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 337 | Licenses If You choose to distribute Source Code Form that is 338 | Incompatible With Secondary Licenses under the terms of this version of 339 | the License, the notice described in Exhibit B of this License must be 340 | attached. 341 | 342 | Exhibit A - Source Code Form License Notice 343 | 344 | This Source Code Form is subject to the 345 | terms of the Mozilla Public License, v. 346 | 2.0. If a copy of the MPL was not 347 | distributed with this file, You can 348 | obtain one at 349 | http://mozilla.org/MPL/2.0/. 350 | 351 | If it is not possible or desirable to put the notice in a particular file, 352 | then You may include the notice in a location (such as a LICENSE file in a 353 | relevant directory) where a recipient would be likely to look for such a 354 | notice. 355 | 356 | You may add additional accurate notices of copyright ownership. 357 | 358 | Exhibit B - "Incompatible With Secondary Licenses" Notice 359 | 360 | This Source Code Form is "Incompatible 361 | With Secondary Licenses", as defined by 362 | the Mozilla Public License, v. 2.0. 363 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .DEFAULT_GOAL := help 2 | 3 | help: ## Print help text. 4 | @grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' 5 | 6 | lint: ## Check code using various linters and static checkers. 7 | @gofmt -d . 8 | @go vet -v . || exit 1 9 | @golint -set_exit_status . || exit 1 10 | @errcheck -ignoretests || exit 1 11 | @misspell -locale uk . 12 | 13 | install: ## Install or update development dependencies. 14 | @go get -u github.com/stretchr/testify/assert 15 | @go get -u github.com/kisielk/errcheck 16 | @go get -u github.com/client9/misspell/cmd/misspell 17 | @go get -u github.com/golang/lint/golint 18 | 19 | 20 | test: ## Run unit tests and print test coverage. 21 | @touch .coverage.out 22 | @go test -coverprofile .coverage.out && go tool cover -func=.coverage.out 23 | 24 | .PHONY: help lint test 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![logo](logo.png) 2 | 3 | Goldfish [![GoDoc](https://godoc.org/github.com/AdvancedClimateSystems/goldfish?status.svg)](https://godoc.org/github.com/AdvancedClimateSystems/goldfish) [![Build Status](https://travis-ci.org/AdvancedClimateSystems/goldfish.svg?branch=master)](https://travis-ci.org/AdvancedClimateSystems/goldfish) 4 | ======== 5 | 6 | Goldfish is a Go package for creating Modbus TCP servers. See 7 | [example/main.go][example] for an example. 8 | 9 | ## License 10 | 11 | Goldfish is licensed under [Mozilla Public License][mpl] © 2017 [Advanced 12 | Climate Systems][acs]. 13 | 14 | [acs]: climotion.com 15 | [example]: example/main.go 16 | [mpl]: LICENSE 17 | -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | 8 | modbus "github.com/advancedclimatesystems/goldfish" 9 | ) 10 | 11 | // handleCoils is a handler that responds to Modbus requests with function code 12 | // 1 (read coils) and 2 (read discrete inputs). 13 | // 14 | // The handler is called with 3 parameters: the unit/slave id, the number of 15 | // the first requested address and the total address requested. 16 | // 17 | // The handler must return a slice representing the values of the requested 18 | // addresses like [0, 1, 0, 1, 0, 1]. 19 | func handleReadCoils(unitID, start, quantity int) ([]modbus.Value, error) { 20 | coils := make([]modbus.Value, quantity) 21 | for i := 0; i < quantity; i++ { 22 | v, err := modbus.NewValue((i + start) % 2) 23 | if err != nil { 24 | return coils, modbus.SlaveDeviceFailureError 25 | } 26 | 27 | coils[i] = v 28 | } 29 | 30 | return coils, nil 31 | } 32 | 33 | // handleRegisters is a handler that responds to Modbus request with function 34 | // code 3 (read holding registers) and 4 (read input registers). 35 | // 36 | // The handler is called with 3 parameters: the unit/slave id, the number of 37 | // the first requested address and the total address requested. 38 | // 39 | // The handler must return a slice with the values of the registers like 40 | // [31, 298, 1999]. 41 | func handleRegisters(unitID, start, quantity int) ([]modbus.Value, error) { 42 | registers := make([]modbus.Value, quantity) 43 | for i := 0; i < quantity; i++ { 44 | v, err := modbus.NewValue(i + start) 45 | if err != nil { 46 | return registers, modbus.SlaveDeviceFailureError 47 | } 48 | 49 | registers[i] = v 50 | } 51 | 52 | return registers, nil 53 | } 54 | 55 | func handleWriteRegisters(unitID, start int, values []modbus.Value) error { 56 | for i, value := range values { 57 | fmt.Printf("[%d]: %d\n", i+start, value.Get()) 58 | } 59 | 60 | return nil 61 | } 62 | 63 | func handleWriteCoils(unitID, start int, values []modbus.Value) error { 64 | if start == 1 { 65 | return modbus.IllegalAddressError 66 | } 67 | return nil 68 | } 69 | 70 | func main() { 71 | addr := flag.String("addr", ":502", "address to listen on.") 72 | flag.Parse() 73 | 74 | s, err := modbus.NewServer(*addr) 75 | 76 | if err != nil { 77 | log.Fatal(fmt.Sprintf("Failed to start Modbus server: %v", err)) 78 | } 79 | 80 | s.Handle(modbus.ReadCoils, modbus.NewReadHandler(handleReadCoils)) 81 | s.Handle(modbus.ReadHoldingRegisters, modbus.NewReadHandler(handleRegisters)) 82 | s.Handle(modbus.WriteSingleCoil, modbus.NewWriteHandler(handleWriteCoils, modbus.Signed)) 83 | s.Handle(modbus.WriteSingleRegister, modbus.NewWriteHandler(handleWriteRegisters, modbus.Signed)) 84 | s.Handle(modbus.WriteMultipleRegisters, modbus.NewWriteHandler(handleWriteRegisters, modbus.Signed)) 85 | 86 | s.Listen() 87 | } 88 | -------------------------------------------------------------------------------- /handler.go: -------------------------------------------------------------------------------- 1 | package modbus 2 | 3 | import ( 4 | "encoding/binary" 5 | "fmt" 6 | "io" 7 | "log" 8 | ) 9 | 10 | // Signedness controls the signedness of values for Writehandler's. A value can 11 | // be unsigned (capabale of representing only non-negative integers) or signed 12 | // (capable of representing negative integers as well). 13 | type Signedness int 14 | 15 | const ( 16 | // Unsigned set signedness to unsigned. 17 | Unsigned Signedness = iota 18 | 19 | // Signed sets signedness to signed. 20 | Signed 21 | ) 22 | 23 | // A Handler responds to a Modbus request. 24 | type Handler interface { 25 | ServeModbus(w io.Writer, r Request) 26 | } 27 | 28 | // ReadHandlerFunc is an adapter to allow the use of ordinary functions as 29 | // handlers for Modbus read functions. 30 | type ReadHandlerFunc func(unitID, start, quantity int) ([]Value, error) 31 | 32 | // ReadHandler can be used to respond on Modbus request with function codes 33 | // 1, 2, 3 and 4. 34 | type ReadHandler struct { 35 | handle ReadHandlerFunc 36 | } 37 | 38 | // NewReadHandler creates a new ReadHandler. 39 | func NewReadHandler(h ReadHandlerFunc) *ReadHandler { 40 | return &ReadHandler{ 41 | handle: h, 42 | } 43 | } 44 | 45 | // ServeModbus writes a Modbus response. 46 | func (h ReadHandler) ServeModbus(w io.Writer, req Request) { 47 | start := int(binary.BigEndian.Uint16(req.Data[:2])) 48 | quantity := int(binary.BigEndian.Uint16(req.Data[2:4])) 49 | 50 | values, err := h.handle(int(req.UnitID), start, quantity) 51 | if err != nil { 52 | respond(w, NewErrorResponse(req, err)) 53 | return 54 | } 55 | 56 | var data []byte 57 | 58 | switch req.FunctionCode { 59 | case ReadCoils, ReadDiscreteInputs: 60 | data = append(data, reduce(values)...) 61 | default: 62 | for _, v := range values { 63 | b, err := v.MarshalBinary() 64 | if err != nil { 65 | respond(w, NewErrorResponse(req, SlaveDeviceFailureError)) 66 | return 67 | } 68 | 69 | data = append(data, b...) 70 | } 71 | } 72 | 73 | respond(w, NewResponse(req, data)) 74 | } 75 | 76 | func respond(w io.Writer, resp *Response) { 77 | data, err := resp.MarshalBinary() 78 | if err != nil { 79 | log.Printf("Failed to marshal response: %v", err) 80 | return 81 | } 82 | 83 | if _, err := w.Write(data); err != nil { 84 | log.Printf("Failed to respond to client: %v", err) 85 | } 86 | } 87 | 88 | // reduce takes slice like [1, 0, 1, 0, 0, 1] and reduces that to a byte. 89 | func reduce(values []Value) []byte { 90 | length := len(values) / 8 91 | if len(values)%8 > 0 { 92 | length++ 93 | } 94 | reduced := make([]byte, length) 95 | 96 | n := length - 1 97 | 98 | // Iterate over 8 values a time. 99 | for i := 0; i <= len(values); i = i + 8 { 100 | end := i + 8 101 | if end > len(values)-1 { 102 | end = len(values) 103 | } 104 | 105 | b := values[i:end] 106 | for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 { 107 | b[i], b[j] = b[j], b[i] 108 | } 109 | 110 | for _, v := range b { 111 | reduced[n] = reduced[n] << 1 112 | if v.Get() > 0 { 113 | reduced[n] = reduced[n] | 1 114 | } 115 | } 116 | 117 | n-- 118 | } 119 | 120 | return reduced 121 | } 122 | 123 | // WriteHandlerFunc is an adapter to allow the use of ordinary functions as 124 | // handlers for Modbus write functions. 125 | type WriteHandlerFunc func(unitID, start int, values []Value) error 126 | 127 | // WriteHandler can be used to respond on Modbus request with function codes 128 | // 5 and 6. 129 | type WriteHandler struct { 130 | handler WriteHandlerFunc 131 | signedness Signedness 132 | } 133 | 134 | // NewWriteHandler creates a new WriteHandler. 135 | func NewWriteHandler(h WriteHandlerFunc, s Signedness) *WriteHandler { 136 | return &WriteHandler{ 137 | handler: h, 138 | signedness: s, 139 | } 140 | } 141 | 142 | // ServeModbus handles a Modbus request and returns a response. 143 | func (h WriteHandler) ServeModbus(w io.Writer, req Request) { 144 | var err error 145 | var resp *Response 146 | var values []Value 147 | start := int(binary.BigEndian.Uint16(req.Data[:2])) 148 | 149 | switch req.FunctionCode { 150 | case WriteSingleCoil: 151 | values, err = h.handleWriteSingleCoil(req) 152 | case WriteSingleRegister: 153 | values, err = h.handleWriteSingleRegister(req) 154 | case WriteMultipleRegisters: 155 | values, err = h.handleWriteMultipleRegisters(req) 156 | } 157 | 158 | if err != nil { 159 | respond(w, NewErrorResponse(req, err)) 160 | return 161 | } 162 | 163 | err = h.handler(int(req.UnitID), start, values) 164 | 165 | if err != nil { 166 | respond(w, NewErrorResponse(req, err)) 167 | return 168 | } 169 | 170 | resp = NewResponse(req, req.Data[0:4]) 171 | respond(w, resp) 172 | } 173 | 174 | func (h WriteHandler) handleWriteSingleCoil(req Request) ([]Value, error) { 175 | var v Value 176 | values := make([]Value, 1) 177 | if err := v.UnmarshalBinary(req.Data[2:4], Unsigned); err != nil { 178 | return values, fmt.Errorf("failed to hande write single coil request: %v", err) 179 | } 180 | 181 | if v.Get() != 0 { 182 | if err := v.Set(1); err != nil { 183 | return values, IllegalDataValueError 184 | } 185 | } 186 | values[0] = v 187 | 188 | return values, nil 189 | } 190 | 191 | func (h WriteHandler) handleWriteSingleRegister(req Request) ([]Value, error) { 192 | var v Value 193 | if err := v.UnmarshalBinary(req.Data[2:4], h.signedness); err != nil { 194 | return []Value{}, fmt.Errorf("failed to hande write single register request: %v", err) 195 | } 196 | return []Value{v}, nil 197 | } 198 | 199 | func (h WriteHandler) handleWriteMultipleRegisters(req Request) ([]Value, error) { 200 | quantity := int(binary.BigEndian.Uint16(req.Data[2:4])) 201 | values := []Value{} 202 | 203 | // The byte slice request.Data follows this format: 204 | // 205 | // ================ =============== 206 | // Field Length (bytes) 207 | // ================ =============== 208 | // Starting Address 2 209 | // Quantity 2 210 | // Byte count 1 211 | // Values n 212 | // ================ =============== 213 | // 214 | // The values are prepended with 5 bytes of meta data. 215 | // Every value is 2 bytes long. 216 | offset := 5 217 | if len(req.Data) != offset+(quantity*2) { 218 | return values, IllegalDataValueError 219 | } 220 | 221 | for i := 0; i < quantity*2; i += 2 { 222 | var v Value 223 | if err := v.UnmarshalBinary(req.Data[offset+i:offset+i+2], h.signedness); err != nil { 224 | return values, fmt.Errorf("failed to hande write multiple registers request: %v", err) 225 | } 226 | 227 | values = append(values, v) 228 | } 229 | 230 | return values, nil 231 | } 232 | -------------------------------------------------------------------------------- /handler_test.go: -------------------------------------------------------------------------------- 1 | package modbus 2 | 3 | import ( 4 | "bytes" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestReadHandler(t *testing.T) { 11 | h := NewReadHandler(func(unitID, start, quantity int) ([]Value, error) { 12 | assert.Equal(t, 0, unitID) 13 | assert.Equal(t, 5, start) 14 | assert.Equal(t, 3, quantity) 15 | 16 | return []Value{Value{0}, Value{1}, Value{1}}, nil 17 | }) 18 | 19 | tests := []struct { 20 | req Request 21 | expected []byte 22 | }{ 23 | { 24 | Request{MBAP{}, ReadCoils, []byte{0x0, 0x5, 0x0, 0x3}}, 25 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x1, 0x1, 0x6}, 26 | }, 27 | { 28 | Request{MBAP{}, ReadHoldingRegisters, []byte{0x0, 0x5, 0x0, 0x3}}, 29 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x9, 0x0, 0x3, 0x6, 0x0, 0x0, 0x0, 0x1, 0x0, 0x1}, 30 | }, 31 | } 32 | 33 | for _, test := range tests { 34 | buf := new(bytes.Buffer) 35 | h.ServeModbus(buf, test.req) 36 | assert.Equal(t, test.expected, buf.Bytes()) 37 | } 38 | } 39 | 40 | func TestReduce(t *testing.T) { 41 | tests := []struct { 42 | input []Value 43 | expected []byte 44 | }{ 45 | {[]Value{Value{0}, Value{1}, Value{1}, Value{1}}, []byte{0xe}}, 46 | {[]Value{Value{1}, Value{0}, Value{1}, Value{0}, Value{1}, Value{0}, Value{1}, Value{0}, Value{1}}, []byte{0x1, 0x55}}, 47 | {[]Value{Value{1}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}, Value{1}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}, Value{0}}, []byte{0x0, 0x1, 0x1}}, 48 | } 49 | 50 | for _, test := range tests { 51 | assert.Equal(t, test.expected, reduce(test.input)) 52 | } 53 | } 54 | 55 | func newWriteHandler(t *testing.T, unitID, start int, values []Value, response error, s Signedness) *WriteHandler { 56 | return NewWriteHandler(func(u, s int, v []Value) error { 57 | assert.Equal(t, unitID, u) 58 | assert.Equal(t, start, s) 59 | assert.Equal(t, values, v) 60 | 61 | return response 62 | }, s) 63 | } 64 | 65 | func TestWriteHandler(t *testing.T) { 66 | tests := []struct { 67 | req Request 68 | h *WriteHandler 69 | expected []byte 70 | }{ 71 | { 72 | Request{MBAP{}, WriteSingleCoil, []byte{0x0, 0x1, 0x0, 0x0}}, 73 | newWriteHandler(t, 0, 1, []Value{Value{0}}, nil, Signed), 74 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x5, 0x0, 0x01, 0x0, 0x0}, 75 | }, 76 | { 77 | Request{MBAP{}, WriteSingleCoil, []byte{0x0, 0x1, 0xc, 0x1}}, 78 | newWriteHandler(t, 0, 1, []Value{Value{1}}, IllegalFunctionError, Signed), 79 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x85, 0x01}, 80 | }, 81 | { 82 | Request{MBAP{}, WriteSingleRegister, []byte{0x0, 0x1, 0xf3, 0x88}}, 83 | newWriteHandler(t, 0, 1, []Value{Value{-3192}}, nil, Signed), 84 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x6, 0x0, 0x01, 0xf3, 0x88}, 85 | }, 86 | { 87 | Request{MBAP{}, WriteSingleRegister, []byte{0x0, 0x1, 0xf3, 0x88}}, 88 | newWriteHandler(t, 0, 1, []Value{Value{62344}}, nil, Unsigned), 89 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x6, 0x0, 0x01, 0xf3, 0x88}, 90 | }, 91 | { 92 | Request{MBAP{}, WriteSingleRegister, []byte{0x0, 0x1, 0xc, 0x78}}, 93 | newWriteHandler(t, 0, 1, []Value{Value{3192}}, SlaveDeviceBusyError, Signed), 94 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x86, 0x6}, 95 | }, 96 | { 97 | // Valid write multiple registers request. 98 | Request{MBAP{}, WriteMultipleRegisters, []byte{0x0, 0x1, 0x0, 0x2, 0x4, 0x3c, 0x13, 0xf3, 0x88}}, 99 | newWriteHandler(t, 0, 1, []Value{Value{0x3c13}, Value{-3192}}, nil, Signed), 100 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x10, 0x0, 0x1, 0x0, 0x2}, 101 | }, 102 | { 103 | // Valid write multiple registers request. 104 | Request{MBAP{}, WriteMultipleRegisters, []byte{0x0, 0x1, 0x0, 0x2, 0x4, 0x3c, 0x13, 0xf3, 0x88}}, 105 | newWriteHandler(t, 0, 1, []Value{Value{0x3c13}, Value{62344}}, nil, Unsigned), 106 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x6, 0x0, 0x10, 0x0, 0x1, 0x0, 0x2}, 107 | }, 108 | { 109 | // Invalid write multiple registers request, the length doesn't match. 110 | Request{MBAP{}, WriteMultipleRegisters, []byte{0x0, 0x1, 0x0, 0x2, 0x4, 0x3c, 0x13, 0x01}}, 111 | newWriteHandler(t, 0, 1, []Value{}, nil, Signed), 112 | []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x90, 0x3}, 113 | }, 114 | } 115 | 116 | for _, test := range tests { 117 | buf := new(bytes.Buffer) 118 | test.h.ServeModbus(buf, test.req) 119 | assert.Equal(t, test.expected, buf.Bytes()) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AdvancedClimateSystems/goldfish/7c577fff5f3fe44d4a1f3b7153b396c3e190c0ee/logo.png -------------------------------------------------------------------------------- /logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 48 | 49 | 50 | 54 | 55 | 56 | 60 | 61 | 62 | 68 | 69 | 70 | 76 | 77 | 79 | 81 | 82 | 93 | 94 | 96 | 97 | 120 | 121 | 122 | 145 | 146 | 147 | 152 | 153 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 164 | 166 | 167 | 168 | 169 | -------------------------------------------------------------------------------- /message.go: -------------------------------------------------------------------------------- 1 | package modbus 2 | 3 | import ( 4 | "bytes" 5 | "encoding/binary" 6 | "errors" 7 | "fmt" 8 | ) 9 | 10 | const ( 11 | // ReadCoils is Modbus function code 1. 12 | ReadCoils uint8 = iota + 1 13 | 14 | // ReadDiscreteInputs is Modbus function code 2. 15 | ReadDiscreteInputs 16 | 17 | // ReadHoldingRegisters is Modbus function code 3. 18 | ReadHoldingRegisters 19 | 20 | // ReadInputRegisters is Modbus function code 4. 21 | ReadInputRegisters 22 | 23 | // WriteSingleCoil is Modbus function code 5. 24 | WriteSingleCoil 25 | 26 | // WriteSingleRegister is Modbus function code 6. 27 | WriteSingleRegister 28 | 29 | // WriteMultipleCoils is Modbus function code 15. 30 | WriteMultipleCoils = 15 + 1 31 | 32 | // WriteMultipleRegisters is Modbus function code 16. 33 | WriteMultipleRegisters 34 | ) 35 | 36 | // Error represesents a Modbus protocol error. 37 | type Error struct { 38 | // Code contains the Modbus exception code. 39 | Code uint8 40 | msg string 41 | } 42 | 43 | func (e Error) Error() string { 44 | return fmt.Sprintf("Modbus exception code: %d: %v", e.Code, e.msg) 45 | } 46 | 47 | var ( 48 | // IllegalFunctionError with exception code 1, is returned when the 49 | // function received is not an allowable action fwith the slave. 50 | IllegalFunctionError = Error{Code: 1, msg: "illegal function"} 51 | 52 | // IllegalAddressError with exception code 2, is returned when the 53 | // address received is not an allowable address fwith the slave. 54 | IllegalAddressError = Error{Code: 2, msg: "illegal address"} 55 | 56 | // IllegalDataValueError with exception code 3, is returned if the 57 | // request contains an value that is not allowable fwith the slave. 58 | IllegalDataValueError = Error{Code: 3, msg: "illegal data value"} 59 | 60 | // SlaveDeviceFailureError with exception code 4, is returned when 61 | // the server isn't able to handle the request. 62 | SlaveDeviceFailureError = Error{Code: 4, msg: "slave device failure"} 63 | 64 | // AcknowledgeError with exception code 5, is returned when the 65 | // server has received the request successfully, but needs a long time 66 | // to process the request. 67 | AcknowledgeError = Error{Code: 5, msg: "acknowledge"} 68 | 69 | // SlaveDeviceBusyError with exception 6, is returned when master is 70 | // busy processing a long-running command. 71 | SlaveDeviceBusyError = Error{Code: 6, msg: "slave device busy"} 72 | 73 | // NegativeAcknowledgeError with exception code 7, is returned for an 74 | // unsuccessful programming request using function code 13 or 14. 75 | NegativeAcknowledgeError = Error{Code: 7, msg: "negative acknowledge"} 76 | 77 | // MemoryParityError with exception code 8 is returned to indicate that 78 | // the extended file area failed to pass a consistency check. May only 79 | // returned for requests with function code 20 or 21. 80 | MemoryParityError = Error{Code: 8, msg: "memory parity error"} 81 | 82 | // GatewayPathUnavailableError with exception code 10 indicates that 83 | // the gateway was unable to allocate an internal communication path 84 | // from the input port to the output port for processing the request. 85 | GatewayPathUnavailableError = Error{Code: 10, msg: "gateway path unavailable"} 86 | 87 | // GatewayTargetDeviceFailedToRespondError with exception code 11 88 | // indicates that the device is not present on the network. 89 | GatewayTargetDeviceFailedToRespondError = Error{Code: 11, msg: "gateway target device failed to respond"} 90 | ) 91 | 92 | // Value is a value an integer ranging from range of -32768 through 65535. 93 | type Value struct { 94 | v int 95 | } 96 | 97 | // NewValue creates a Value. It returns an error when given value is outside 98 | // range of -32768 through 65535. 99 | func NewValue(v int) (Value, error) { 100 | var value Value 101 | 102 | if err := value.Set(v); err != nil { 103 | return value, err 104 | } 105 | 106 | return value, nil 107 | } 108 | 109 | // Set sets the value. It returns an error when given value is outside range of 110 | // -32768 through 65535. 111 | func (v *Value) Set(value int) error { 112 | if value < -32768 || value > 65535 { 113 | return fmt.Errorf("%d doesn't fit in 16 bytes", value) 114 | } 115 | 116 | v.v = value 117 | return nil 118 | } 119 | 120 | // Get returns the value. 121 | func (v *Value) Get() int { 122 | return v.v 123 | } 124 | 125 | // MarshalBinary marshals a Value into byte slice with length of 2 126 | // bytes. 127 | func (v *Value) MarshalBinary() ([]byte, error) { 128 | buf := new(bytes.Buffer) 129 | var value interface{} 130 | if v.v < 0 { 131 | value = int16(v.v) 132 | } else { 133 | value = uint16(v.v) 134 | } 135 | 136 | if err := binary.Write(buf, binary.BigEndian, value); err != nil { 137 | return buf.Bytes(), fmt.Errorf("failed to marshal ResponseValue: %v", err) 138 | } 139 | 140 | return buf.Bytes(), nil 141 | } 142 | 143 | // UnmarshalBinary value from a byte slice. 144 | func (v *Value) UnmarshalBinary(d []byte, s Signedness) error { 145 | if len(d) != 2 { 146 | return errors.New("can't unmarshal value: byte slice isn't of length 2") 147 | } 148 | 149 | v.v = int(int16(binary.BigEndian.Uint16(d))) 150 | if s == Unsigned { 151 | v.v = int(binary.BigEndian.Uint16(d)) 152 | } 153 | 154 | return nil 155 | } 156 | 157 | // MBAP is the Modbus Application Header. Only Modbus TCP/IP message have an 158 | // MBAP header. The MBAP header has 4 fields with a total length of 7 bytes. 159 | type MBAP struct { 160 | // TransactionID identifies a request/response transaction. 161 | TransactionID uint16 162 | 163 | // ProtocolID defines the protocol, for Modbus it's always 0. 164 | ProtocolID uint16 165 | 166 | // Length shows how much bytes are following. 167 | Length uint16 168 | 169 | // UnitID or slave id identifies a slave. 170 | UnitID uint8 171 | } 172 | 173 | // UnmarshalBinary unmarshals a binary representation of MBAP. 174 | func (m *MBAP) UnmarshalBinary(b []byte) error { 175 | if len(b) != 7 { 176 | return fmt.Errorf("failed to unmarshal byte slice to MBAP: byte slice has invalid length of %d", len(b)) 177 | } 178 | 179 | m.TransactionID = binary.BigEndian.Uint16(b[:2]) 180 | m.ProtocolID = binary.BigEndian.Uint16(b[2:4]) 181 | m.Length = binary.BigEndian.Uint16(b[4:6]) 182 | m.UnitID = uint8(b[6]) 183 | 184 | return nil 185 | } 186 | 187 | // MarshalBinary marshals a MBAP to it binary form. 188 | func (m *MBAP) MarshalBinary() ([]byte, error) { 189 | buf := new(bytes.Buffer) 190 | 191 | data := []interface{}{ 192 | m.TransactionID, 193 | m.ProtocolID, 194 | m.Length, 195 | m.UnitID, 196 | } 197 | 198 | for _, v := range data { 199 | err := binary.Write(buf, binary.BigEndian, v) 200 | 201 | if err != nil { 202 | return buf.Bytes(), fmt.Errorf("failed to marshal MBAP to binary form: %v", err) 203 | } 204 | 205 | } 206 | 207 | return buf.Bytes(), nil 208 | } 209 | 210 | // Request is a Modbus request. 211 | type Request struct { 212 | // Request is a Modbus request. 213 | MBAP 214 | 215 | FunctionCode uint8 216 | Data []byte 217 | } 218 | 219 | // UnmarshalBinary unmarshals binary representation of Request. 220 | func (r *Request) UnmarshalBinary(b []byte) error { 221 | if err := r.MBAP.UnmarshalBinary(b[0:7]); err != nil { 222 | return err 223 | } 224 | 225 | r.FunctionCode = uint8(b[7]) 226 | r.Data = b[8:] 227 | 228 | return nil 229 | } 230 | 231 | // Response is a Modbus response. 232 | type Response struct { 233 | MBAP 234 | FunctionCode uint8 235 | Data []byte 236 | 237 | exception bool 238 | } 239 | 240 | // NewResponse creates a Response for a Request. 241 | func NewResponse(r Request, data []byte) *Response { 242 | resp := &Response{ 243 | MBAP: r.MBAP, 244 | FunctionCode: r.FunctionCode, 245 | Data: data, 246 | } 247 | 248 | resp.MBAP.Length = uint16(len(data) + 3) 249 | switch r.FunctionCode { 250 | case WriteSingleCoil, WriteSingleRegister, WriteMultipleRegisters: 251 | resp.MBAP.Length = uint16(len(data) + 2) 252 | } 253 | 254 | return resp 255 | } 256 | 257 | // NewErrorResponse creates a error response. 258 | func NewErrorResponse(r Request, err error) *Response { 259 | resp := &Response{ 260 | MBAP: r.MBAP, 261 | FunctionCode: r.FunctionCode + 0x80, 262 | exception: true, 263 | } 264 | 265 | resp.Data = []byte{5} 266 | if err, ok := err.(Error); ok { 267 | resp.Data = []byte{err.Code} 268 | } 269 | 270 | resp.MBAP.Length = 3 271 | return resp 272 | } 273 | 274 | // MarshalBinary marshals a Response to it binary form. 275 | func (r *Response) MarshalBinary() ([]byte, error) { 276 | mbap, err := r.MBAP.MarshalBinary() 277 | if err != nil { 278 | return nil, fmt.Errorf("failed to marshal response to its binary form: %v", err) 279 | } 280 | 281 | pdu := new(bytes.Buffer) 282 | data := []interface{}{ 283 | r.FunctionCode, 284 | } 285 | 286 | switch r.FunctionCode { 287 | case ReadCoils, ReadDiscreteInputs, ReadHoldingRegisters, ReadInputRegisters: 288 | if !r.exception { 289 | data = append(data, uint8(len(r.Data))) 290 | } 291 | } 292 | 293 | data = append(data, r.Data) 294 | for _, v := range data { 295 | err := binary.Write(pdu, binary.BigEndian, v) 296 | if err != nil { 297 | return nil, fmt.Errorf("failed to marshal response to its binary form: %v", err) 298 | } 299 | } 300 | 301 | return append(mbap, pdu.Bytes()...), nil 302 | } 303 | -------------------------------------------------------------------------------- /message_test.go: -------------------------------------------------------------------------------- 1 | package modbus 2 | 3 | import ( 4 | "errors" 5 | "testing" 6 | 7 | "github.com/stretchr/testify/assert" 8 | ) 9 | 10 | func TestNewValue(t *testing.T) { 11 | tests := []struct { 12 | value int 13 | expected []byte 14 | }{ 15 | {19, []byte{0x0, 0x13}}, 16 | {-128, []byte{0xff, 0x80}}, 17 | {-2391, []byte{0xf6, 0xa9}}, 18 | {14459, []byte{0x38, 0x7b}}, 19 | } 20 | 21 | for _, test := range tests { 22 | rv, err := NewValue(test.value) 23 | assert.Nil(t, err) 24 | 25 | bytes, err := rv.MarshalBinary() 26 | assert.Nil(t, err) 27 | assert.Equal(t, test.expected, bytes) 28 | } 29 | } 30 | 31 | func TestValueSet(t *testing.T) { 32 | tests := []struct { 33 | value int 34 | expected error 35 | }{ 36 | {-9, nil}, 37 | {-129431, errors.New("-129431 doesn't fit in 16 bytes")}, 38 | {12, nil}, 39 | {73892, errors.New("73892 doesn't fit in 16 bytes")}, 40 | } 41 | 42 | for _, test := range tests { 43 | var v Value 44 | err := v.Set(test.value) 45 | assert.Equal(t, test.expected, err) 46 | } 47 | } 48 | 49 | func TestMBAP(t *testing.T) { 50 | tests := []struct { 51 | mbap MBAP 52 | data []byte 53 | }{ 54 | {MBAP{TransactionID: 18, ProtocolID: 1, Length: 18, UnitID: 2}, []byte{0x0, 0x12, 0x0, 0x1, 0x0, 0x12, 0x2}}, 55 | {MBAP{TransactionID: 18493, ProtocolID: 1, Length: 300, UnitID: 25}, []byte{0x48, 0x3d, 0x0, 0x1, 0x1, 0x2c, 0x19}}, 56 | {MBAP{TransactionID: 54602, ProtocolID: 1, Length: 20110, UnitID: 91}, []byte{0xd5, 0x4a, 0x0, 0x1, 0x4e, 0x8e, 0x5b}}, 57 | } 58 | 59 | for _, test := range tests { 60 | var m MBAP 61 | assert.Nil(t, m.UnmarshalBinary(test.data)) 62 | assert.Equal(t, test.mbap, m) 63 | 64 | data, err := m.MarshalBinary() 65 | assert.Nil(t, err) 66 | assert.Equal(t, test.data, data) 67 | } 68 | 69 | var m MBAP 70 | 71 | // UnmarshalBinary should return error if length of given byte slice is not 7. 72 | assert.NotNil(t, m.UnmarshalBinary([]byte{})) 73 | } 74 | 75 | func TestRequest(t *testing.T) { 76 | mbap := MBAP{ 77 | TransactionID: 1, 78 | ProtocolID: 1, 79 | Length: 6, 80 | UnitID: 3, 81 | } 82 | 83 | tests := []struct { 84 | request Request 85 | data []byte 86 | }{ 87 | // Read 5 coils starting from address 2. 88 | {Request{MBAP: mbap, FunctionCode: 1, Data: []byte{0x0, 0x2, 0x0, 0x5}}, []byte{0x0, 0x1, 0x0, 0x1, 0x0, 0x06, 0x3, 0x1, 0x0, 0x2, 0x0, 0x5}}, 89 | // Read 2 read discrete inputs starting from address 19. 90 | {Request{MBAP: mbap, FunctionCode: 2, Data: []byte{0x0, 0x14, 0x0, 0x2}}, []byte{0x0, 0x1, 0x0, 0x1, 0x0, 0x06, 0x3, 0x2, 0x0, 0x14, 0x0, 0x2}}, 91 | } 92 | 93 | for _, test := range tests { 94 | var r Request 95 | assert.Nil(t, r.UnmarshalBinary(test.data)) 96 | assert.Equal(t, test.request, r) 97 | } 98 | } 99 | 100 | func TestResponse(t *testing.T) { 101 | request := Request{ 102 | MBAP: MBAP{ 103 | TransactionID: 1, 104 | ProtocolID: 1, 105 | Length: 5, 106 | UnitID: 3, 107 | }, 108 | FunctionCode: 4, 109 | Data: []byte{}, 110 | } 111 | 112 | tests := []struct { 113 | response *Response 114 | data []byte 115 | }{ 116 | {NewErrorResponse(request, IllegalFunctionError), []byte{0x0, 0x1, 0x0, 0x1, 0x0, 0x03, 0x3, 0x84, 0x1}}, 117 | {NewErrorResponse(request, AcknowledgeError), []byte{0x0, 0x1, 0x0, 0x1, 0x0, 0x03, 0x3, 0x84, 0x5}}, 118 | {NewResponse(request, []byte{0x24, 0x41}), []byte{0x0, 0x1, 0x0, 0x1, 0x0, 0x05, 0x3, 0x4, 0x2, 0x24, 0x41}}, 119 | {NewResponse(request, []byte{0x1, 0x9, 0x12, 0x3}), []byte{0x0, 0x1, 0x0, 0x1, 0x0, 0x07, 0x3, 0x4, 0x4, 0x1, 0x9, 0x12, 0x3}}, 120 | } 121 | 122 | for _, test := range tests { 123 | data, err := test.response.MarshalBinary() 124 | assert.Nil(t, err) 125 | assert.Equal(t, test.data, data) 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /server.go: -------------------------------------------------------------------------------- 1 | package modbus 2 | 3 | import ( 4 | "bufio" 5 | "encoding/binary" 6 | "fmt" 7 | "io" 8 | "log" 9 | "net" 10 | "time" 11 | ) 12 | 13 | // Server is a Modbus server listens on a port and responds on incoming Modbus 14 | // requests. 15 | type Server struct { 16 | l net.Listener 17 | handlers map[uint8]Handler 18 | timeout time.Duration 19 | ErrorLog *log.Logger 20 | } 21 | 22 | // NewServer creates a new server on given address. 23 | func NewServer(address string) (*Server, error) { 24 | l, err := net.Listen("tcp", address) 25 | if err != nil { 26 | return nil, fmt.Errorf("failed to start Modbus server: %v", err) 27 | } 28 | 29 | return &Server{ 30 | l: l, 31 | timeout: 0, 32 | handlers: make(map[uint8]Handler), 33 | }, nil 34 | } 35 | 36 | // SetTimeout sets the timeout, which is the maximum duraion a request can take. 37 | func (s *Server) SetTimeout(t time.Duration) { 38 | s.timeout = t 39 | } 40 | 41 | // Listen start listening for requests. 42 | func (s *Server) Listen() { 43 | for { 44 | conn, err := s.l.Accept() 45 | 46 | if err != nil { 47 | s.logf("golfish: failed to accept incoming connection: %v", err) 48 | continue 49 | } 50 | if d := s.timeout; d != 0 { 51 | if err := conn.SetReadDeadline(time.Now().Add(d)); err != nil { 52 | s.logf("goldfish: failed set timeout %v: %v", conn.RemoteAddr(), err) 53 | if err := conn.Close(); err != nil { 54 | s.logf("goldfish: failed to close connection with %v: %v", conn.RemoteAddr(), err) 55 | } 56 | } 57 | } 58 | 59 | go func() { 60 | if err := s.handleConn(conn); err != nil { 61 | s.logf("goldfish: unable to handle request from %v: %v", conn.RemoteAddr(), err) 62 | } 63 | 64 | if err := conn.Close(); err != nil { 65 | s.logf("goldfish: failed to close connection with %v: %v", conn.RemoteAddr(), err) 66 | } 67 | }() 68 | } 69 | } 70 | 71 | func (s *Server) handleConn(conn io.ReadWriteCloser) error { 72 | r := bufio.NewReader(conn) 73 | for { 74 | buf, err := s.readMessage(r) 75 | 76 | if err != nil { 77 | // An EOF error indicates the connection did not send new data. This 78 | // means the connection can be closed, but its not an error in the program. 79 | if err == io.EOF { 80 | return nil 81 | } 82 | return fmt.Errorf("failed to read message from connection: %v", err) 83 | } 84 | 85 | var req Request 86 | if err := req.UnmarshalBinary(buf); err != nil { 87 | return fmt.Errorf("failed to parse request: %v", err) 88 | } 89 | 90 | if err := s.executeAndRespond(conn, &req); err != nil { 91 | return fmt.Errorf("something went horribly wrong and server has to close connection: %v", err) 92 | } 93 | } 94 | } 95 | 96 | func (s *Server) readMessage(r *bufio.Reader) ([]byte, error) { 97 | b, err := r.Peek(6) 98 | if err != nil { 99 | return nil, err 100 | } 101 | length := binary.BigEndian.Uint16(b[4:6]) 102 | 103 | buf := make([]byte, 6+length) 104 | _, err = r.Read(buf) 105 | 106 | if err != nil { 107 | return nil, fmt.Errorf("failed to read request: %v", err) 108 | } 109 | 110 | return buf, nil 111 | } 112 | 113 | func (s *Server) executeAndRespond(conn io.Writer, req *Request) error { 114 | h, ok := s.handlers[req.FunctionCode] 115 | if ok { 116 | h.ServeModbus(conn, *req) 117 | return nil 118 | } 119 | 120 | resp := NewErrorResponse(*req, IllegalFunctionError) 121 | data, err := resp.MarshalBinary() 122 | if err != nil { 123 | return fmt.Errorf("failed to create response: %v", err) 124 | } 125 | 126 | if _, err := conn.Write(data); err != nil { 127 | return fmt.Errorf("failed to write response: %v", err) 128 | } 129 | 130 | return nil 131 | } 132 | 133 | // Handle registers the handler for the given function code. 134 | func (s *Server) Handle(functionCode uint8, h Handler) { 135 | s.handlers[functionCode] = h 136 | } 137 | 138 | func (s *Server) logf(format string, args ...interface{}) { 139 | if s.ErrorLog != nil { 140 | s.ErrorLog.Printf(format, args...) 141 | } else { 142 | log.Printf(format, args...) 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /server_test.go: -------------------------------------------------------------------------------- 1 | package modbus 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "errors" 7 | "io" 8 | "testing" 9 | "time" 10 | 11 | "github.com/stretchr/testify/assert" 12 | ) 13 | 14 | // ErrorWriter is a writer that always fails to write. 15 | type ErrorWriter struct{} 16 | 17 | func (e ErrorWriter) Write([]byte) (int, error) { return 0, errors.New("") } 18 | 19 | type RawHandler struct { 20 | handle func(w io.Writer, r Request) 21 | } 22 | 23 | func (h RawHandler) ServeModbus(w io.Writer, r Request) { 24 | h.handle(w, r) 25 | } 26 | 27 | func TestSetTimeout(t *testing.T) { 28 | s, err := NewServer(":") 29 | assert.Nil(t, err) 30 | assert.Equal(t, 0*time.Second, s.timeout) 31 | 32 | s.SetTimeout(5 * time.Second) 33 | assert.Equal(t, 5*time.Second, s.timeout) 34 | } 35 | 36 | // Connection is a struct implemention the io.ReadWriteCloser interface. 37 | type Connection struct { 38 | read func([]byte) (int, error) 39 | write func([]byte) (int, error) 40 | close func() error 41 | } 42 | 43 | func (c Connection) Read(b []byte) (int, error) { return c.read(b) } 44 | 45 | func (c Connection) Write(b []byte) (int, error) { return c.write(b) } 46 | 47 | func (c Connection) Close() error { return c.close() } 48 | 49 | func TestListen(t *testing.T) { 50 | s := Server{} 51 | 52 | conn := Connection{ 53 | read: func(b []byte) (int, error) { 54 | copy(b, []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x4, 0x0, 0x0, 0x0}) 55 | return 6, nil 56 | }, 57 | 58 | write: func(b []byte) (int, error) { 59 | return 0, errors.New("") 60 | }, 61 | } 62 | 63 | err := s.handleConn(conn) 64 | assert.NotNil(t, err) 65 | 66 | conn.read = func(b []byte) (int, error) { 67 | return 0, errors.New("") 68 | } 69 | 70 | err = s.handleConn(conn) 71 | assert.NotNil(t, err) 72 | } 73 | 74 | func TestReadMessage(t *testing.T) { 75 | s := Server{} 76 | 77 | tests := []struct { 78 | data []byte 79 | }{ 80 | {[]byte{}}, 81 | {[]byte{0x0}}, 82 | {[]byte{0x0, 0x0}}, 83 | {[]byte{0x0, 0x0, 0x0}}, 84 | {[]byte{0x0, 0x0, 0x0, 0x0}}, 85 | {[]byte{0x0, 0x0, 0x0, 0x0, 0x0}}, 86 | } 87 | 88 | for _, test := range tests { 89 | _, err := s.readMessage(bufio.NewReader(bytes.NewReader(test.data))) 90 | assert.NotNil(t, err) 91 | } 92 | 93 | data := []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x0} 94 | msg, err := s.readMessage(bufio.NewReader(bytes.NewReader(data))) 95 | 96 | assert.Nil(t, err) 97 | assert.Equal(t, msg, data) 98 | } 99 | 100 | func TestExecuteAndRespond(t *testing.T) { 101 | s, _ := NewServer(":") 102 | writer := new(bytes.Buffer) 103 | req := &Request{FunctionCode: ReadCoils} 104 | 105 | // Try to execute a non-implemented function code. This fails, 106 | // therefore the server tries to send a IllegalFunction exception 107 | // response the the client. This should fail too because the writer 108 | // fails to write the response. 109 | err := s.executeAndRespond(ErrorWriter{}, req) 110 | assert.NotNil(t, err) 111 | 112 | // Again trying to execute a non-implemented function code. Now with 113 | // a function writer. This should succeed and the bytes making up a 114 | // IllegalFunction response should be written on the writer. 115 | err = s.executeAndRespond(writer, req) 116 | 117 | assert.Nil(t, err) 118 | assert.Equal(t, []byte{0x0, 0x0, 0x0, 0x0, 0x0, 0x3, 0x0, 0x81, 0x1}, writer.Bytes()) 119 | 120 | // Try again, but now executing an implemented function code. 121 | // Everything should work. 122 | h := RawHandler{ 123 | handle: func(w io.Writer, r Request) { 124 | assert.Equal(t, req, &r) 125 | assert.Equal(t, writer, w) 126 | }, 127 | } 128 | 129 | s.Handle(ReadCoils, h) 130 | err = s.executeAndRespond(writer, req) 131 | assert.Nil(t, err) 132 | } 133 | --------------------------------------------------------------------------------