device.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. package drviers
  2. import (
  3. "encoding/hex"
  4. "reflect"
  5. bus "github.com/ammeter/Bus"
  6. "github.com/ammeter/protocol"
  7. "github.com/yuguorong/go/log"
  8. )
  9. type IDevice interface {
  10. Probe(name string, drv IDriver) error
  11. Open(...interface{}) error
  12. Close() error
  13. Ctrl(...interface{}) error
  14. Suspend() error
  15. Resume() error
  16. GetDevice(string) interface{}
  17. SetRoute(evt bus.IBusEvent, prot string, busName string, chn string, param ...interface{}) int
  18. }
  19. type routePath struct {
  20. iChn bus.IChannel
  21. ibus bus.IBus
  22. iproto protocol.IProtocol
  23. router []chan interface{}
  24. }
  25. type baseDevice struct {
  26. DeviceName string
  27. drv IDriver
  28. Route []routePath
  29. }
  30. func (dev *baseDevice) Probe(name string, driver IDriver) error {
  31. dev.Route = make([]routePath, 0)
  32. dev.DeviceName = name
  33. dev.drv = driver
  34. return nil
  35. }
  36. //bus.IBusEvent
  37. func (dev *baseDevice) OnAttach(chn bus.IChannel) {
  38. }
  39. func (dev *baseDevice) OnDetach(chn bus.IChannel) {
  40. }
  41. func (dev *baseDevice) ChannelDispatch(stream []byte, args interface{}) bus.ChnDispResult {
  42. log.Info(dev.drv.Name(), "-", dev.DeviceName, " try Dispatch: ", hex.EncodeToString(stream))
  43. k := reflect.TypeOf(args).Kind()
  44. if k == reflect.Ptr {
  45. iprot := args.(protocol.IProtocol)
  46. return bus.ChnDispResult(iprot.ChannelDispatch(stream))
  47. }
  48. return bus.DispatchNone
  49. }
  50. func (dev *baseDevice) Create(model interface{}) interface{} {
  51. return nil
  52. }
  53. func (dev *baseDevice) Open(...interface{}) error {
  54. return nil
  55. }
  56. func (dev *baseDevice) Close() error {
  57. return nil
  58. }
  59. func (dev *baseDevice) Ctrl(...interface{}) error {
  60. return nil
  61. }
  62. func (dev *baseDevice) GetDevice(string) interface{} {
  63. return dev
  64. }
  65. func (dev *baseDevice) Suspend() error {
  66. return nil
  67. }
  68. func (dev *baseDevice) Resume() error {
  69. return nil
  70. }
  71. func (dev *baseDevice) SetRoute(evt bus.IBusEvent, prot string, busName string, chn string, param ...interface{}) int {
  72. r := new(routePath)
  73. r.router = make([]chan interface{}, 1)
  74. r.router[0] = make(chan interface{}, 16)
  75. r.iproto = protocol.LoadProtocol(prot)
  76. r.iproto.Init(prot)
  77. r.ibus = bus.MountBus(busName, param)
  78. r.ibus.Init()
  79. r.iChn = r.ibus.OpenChannel(chn, r.router)
  80. r.iChn.SetEvent(evt, r.iproto)
  81. dev.Route = append(dev.Route, *r)
  82. return len(dev.Route)
  83. }