speaker.go 1.4 KB

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