rtuclient_test.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Copyright 2014 Quoc-Viet Nguyen. All rights reserved.
  2. // This software may be modified and distributed under the terms
  3. // of the BSD license. See the LICENSE file for details.
  4. package modbus
  5. import (
  6. "bytes"
  7. "testing"
  8. )
  9. func TestRTUEncoding(t *testing.T) {
  10. encoder := rtuPackager{}
  11. encoder.SlaveId = 0x01
  12. pdu := ProtocolDataUnit{}
  13. pdu.FunctionCode = 0x03
  14. pdu.Data = []byte{0x50, 0x00, 0x00, 0x18}
  15. adu, err := encoder.Encode(&pdu)
  16. if err != nil {
  17. t.Fatal(err)
  18. }
  19. expected := []byte{0x01, 0x03, 0x50, 0x00, 0x00, 0x18, 0x54, 0xC0}
  20. if !bytes.Equal(expected, adu) {
  21. t.Fatalf("adu: expected %v, actual %v", expected, adu)
  22. }
  23. }
  24. func TestRTUDecoding(t *testing.T) {
  25. decoder := rtuPackager{}
  26. adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
  27. pdu, err := decoder.Decode(adu)
  28. if err != nil {
  29. t.Fatal(err)
  30. }
  31. if 16 != pdu.FunctionCode {
  32. t.Fatalf("Function code: expected %v, actual %v", 16, pdu.FunctionCode)
  33. }
  34. expected := []byte{0x8A, 0x00, 0x00, 0x03}
  35. if !bytes.Equal(expected, pdu.Data) {
  36. t.Fatalf("Data: expected %v, actual %v", expected, pdu.Data)
  37. }
  38. }
  39. var responseLengthTests = []struct {
  40. adu []byte
  41. length int
  42. }{
  43. {[]byte{4, 1, 0, 0xA, 0, 0xD, 0xDD, 0x98}, 7},
  44. {[]byte{4, 2, 0, 0xA, 0, 0xD, 0x99, 0x98}, 7},
  45. {[]byte{1, 3, 0, 0, 0, 2, 0xC4, 0xB}, 9},
  46. {[]byte{0x11, 5, 0, 0xAC, 0xFF, 0, 0x4E, 0x8B}, 8},
  47. {[]byte{0x11, 6, 0, 1, 0, 3, 0x9A, 0x9B}, 8},
  48. {[]byte{0x11, 0xF, 0, 0x13, 0, 0xA, 2, 0xCD, 1, 0xBF, 0xB}, 8},
  49. {[]byte{0x11, 0x10, 0, 1, 0, 2, 4, 0, 0xA, 1, 2, 0xC6, 0xF0}, 8},
  50. }
  51. func TestCalculateResponseLength(t *testing.T) {
  52. for _, input := range responseLengthTests {
  53. output := calculateResponseLength(input.adu)
  54. if output != input.length {
  55. t.Errorf("Response length of %x: expected %v, actual: %v",
  56. input.adu, input.length, output)
  57. }
  58. }
  59. }
  60. func BenchmarkRTUEncoder(b *testing.B) {
  61. encoder := rtuPackager{
  62. SlaveId: 10,
  63. }
  64. pdu := ProtocolDataUnit{
  65. FunctionCode: 1,
  66. Data: []byte{2, 3, 4, 5, 6, 7, 8, 9},
  67. }
  68. for i := 0; i < b.N; i++ {
  69. _, err := encoder.Encode(&pdu)
  70. if err != nil {
  71. b.Fatal(err)
  72. }
  73. }
  74. }
  75. func BenchmarkRTUDecoder(b *testing.B) {
  76. decoder := rtuPackager{
  77. SlaveId: 10,
  78. }
  79. adu := []byte{0x01, 0x10, 0x8A, 0x00, 0x00, 0x03, 0xAA, 0x10}
  80. for i := 0; i < b.N; i++ {
  81. _, err := decoder.Decode(adu)
  82. if err != nil {
  83. b.Fatal(err)
  84. }
  85. }
  86. }