speaker.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package lc
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/sirupsen/logrus"
  7. "io"
  8. "lc-smartX/lc/model"
  9. "net/http"
  10. )
  11. // Loudspeaker 扬声器接口
  12. type Loudspeaker interface {
  13. Speak(txt string)
  14. }
  15. type IpCast struct {
  16. Name string
  17. Ip string
  18. Speed byte
  19. Volume byte
  20. Audio string
  21. liveState bool
  22. }
  23. func NewIpCast(name, ip, audio string, speed, volume byte) *IpCast {
  24. s := &IpCast{
  25. Name: name,
  26. Ip: ip,
  27. Speed: speed,
  28. Volume: volume,
  29. Audio: audio,
  30. liveState: false,
  31. }
  32. s.Reconnect()
  33. return s
  34. }
  35. func (ip *IpCast) Speak(txt string) {
  36. data := &model.PlayReq{
  37. Text: txt,
  38. Vcn: "xiaoyan",
  39. Speed: ip.Speed,
  40. Volume: ip.Volume,
  41. Rdn: "2",
  42. Rcn: "1",
  43. Reg: 0,
  44. Sync: false,
  45. Queue: false,
  46. }
  47. data.Loop.Times = 1
  48. logrus.Debugf("IpCast Speak txt : %s", txt)
  49. body, err := json.Marshal(data)
  50. if err != nil {
  51. logrus.Errorf("IpCast Marshal err : %s", err.Error())
  52. return
  53. }
  54. req, _ := http.NewRequest("POST", fmt.Sprintf("http://%s/v1/speech", ip.Ip), bytes.NewReader(body))
  55. req.Header.Set("Content-Type", "application/json")
  56. logrus.Debugf("IpCast Speak req : %+v", req)
  57. rsp, err := http.DefaultClient.Do(req)
  58. if err != nil {
  59. logrus.Errorf("IpCast Speak Do err : %s", err.Error())
  60. return
  61. }
  62. rspData, err := io.ReadAll(rsp.Body)
  63. logrus.Debugf("IpCast Speak rsp : %+v", string(rspData))
  64. }
  65. func (ip *IpCast) Reconnect() {
  66. c := http.DefaultClient
  67. req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s/v1/check_alive", ip.Ip), nil)
  68. rsp, err := c.Do(req)
  69. if err != nil {
  70. logrus.Errorf("IpCast Reconnect err : %s", err.Error())
  71. return
  72. }
  73. if rsp.StatusCode == http.StatusOK {
  74. ip.liveState = true
  75. }
  76. }
  77. func (ip IpCast) CorrectTime() {}