speaker.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. body, err := json.Marshal(data)
  49. if err != nil {
  50. logrus.Errorf("IpCast Marshal err : %s", err.Error())
  51. return
  52. }
  53. req, _ := http.NewRequest("POST", fmt.Sprintf("http://%s/v1/speech", ip.Ip), bytes.NewReader(body))
  54. req.Header.Set("Content-Type", "application/json")
  55. rsp, err := http.DefaultClient.Do(req)
  56. if err != nil {
  57. logrus.Errorf("IpCast Speak Do err : %s", err.Error())
  58. return
  59. }
  60. rspData, err := io.ReadAll(rsp.Body)
  61. logrus.Debugf("IpCast Speak rsp : %+v", string(rspData))
  62. }
  63. func (ip *IpCast) Reconnect() {
  64. c := http.DefaultClient
  65. req, _ := http.NewRequest("GET", fmt.Sprintf("http://%s/v1/check_alive", ip.Ip), nil)
  66. rsp, err := c.Do(req)
  67. if err != nil {
  68. logrus.Errorf("IpCast Reconnect err : %s", err.Error())
  69. return
  70. }
  71. if rsp.StatusCode == http.StatusOK {
  72. ip.liveState = true
  73. }
  74. }
  75. func (ip IpCast) CorrectTime() {}