asciiclient_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 TestASCIIEncoding(t *testing.T) {
  10. encoder := asciiPackager{}
  11. encoder.SlaveId = 17
  12. pdu := ProtocolDataUnit{}
  13. pdu.FunctionCode = 3
  14. pdu.Data = []byte{0, 107, 0, 3}
  15. adu, err := encoder.Encode(&pdu)
  16. if err != nil {
  17. t.Fatal(err)
  18. }
  19. expected := []byte(":1103006B00037E\r\n")
  20. if !bytes.Equal(expected, adu) {
  21. t.Fatalf("adu actual: %v, expected %v", adu, expected)
  22. }
  23. }
  24. func TestASCIIDecoding(t *testing.T) {
  25. decoder := asciiPackager{}
  26. decoder.SlaveId = 247
  27. adu := []byte(":F7031389000A60\r\n")
  28. pdu, err := decoder.Decode(adu)
  29. if err != nil {
  30. t.Fatal(err)
  31. }
  32. if 3 != pdu.FunctionCode {
  33. t.Fatalf("Function code: expected %v, actual %v", 15, pdu.FunctionCode)
  34. }
  35. expected := []byte{0x13, 0x89, 0, 0x0A}
  36. if !bytes.Equal(expected, pdu.Data) {
  37. t.Fatalf("Data: expected %v, actual %v", expected, pdu.Data)
  38. }
  39. }
  40. func BenchmarkASCIIEncoder(b *testing.B) {
  41. encoder := asciiPackager{
  42. SlaveId: 10,
  43. }
  44. pdu := ProtocolDataUnit{
  45. FunctionCode: 1,
  46. Data: []byte{2, 3, 4, 5, 6, 7, 8, 9},
  47. }
  48. for i := 0; i < b.N; i++ {
  49. _, err := encoder.Encode(&pdu)
  50. if err != nil {
  51. b.Fatal(err)
  52. }
  53. }
  54. }
  55. func BenchmarkASCIIDecoder(b *testing.B) {
  56. decoder := asciiPackager{
  57. SlaveId: 10,
  58. }
  59. adu := []byte(":F7031389000A60\r\n")
  60. for i := 0; i < b.N; i++ {
  61. _, err := decoder.Decode(adu)
  62. if err != nil {
  63. b.Fatal(err)
  64. }
  65. }
  66. }