瀏覽代碼

完成IP音柱相关功能

sixian 2 年之前
父節點
當前提交
0400e19dff

+ 10 - 11
app/data/controller/calcTask.go

@@ -31,11 +31,11 @@ func CalcTask() {
 		GarbageDataSync(deviceIds)
 	})
 
-	//【环境传感】日数据
+	//【环境传感】日数据 统计
 	_ = c.AddFunc(hourSpec, func() {
 		service.EnvironmentDataService.DataSync()
 	})
-	//【环境传感】天数据
+	//【环境传感】天数据 统计
 	_ = c.AddFunc(daySpec, func() {
 		service.EnvironmentDataService.DayDataSync()
 	})
@@ -46,22 +46,21 @@ func CalcTask() {
 		//发送告警
 		warnSer.TaskWarnService.HandlingAlarms()
 	})
-	//【一键告警】同步记录
+	//【一键告警】每59秒 同步记录
 	c.AddFunc("*/59 * * * * ?", func() {
 		recordCtl.AKeyAlarmRecord.SosRecordSync()
 	})
-	//【led信息屏】每天早上07:10同步亮度与音量
-	c.AddFunc("0 10 7 * * ?", func() {
-		//c.AddFunc("*/10 * * * * ?", func() {
+	//【led信息屏】每5分钟 同步亮度与音量
+	c.AddFunc("* */5 * * * ?", func() {
 		deviceCtl.InfoBoard.CronSyncBrightnessAndMusicvolume()
 	})
-	//【led信息屏】每天晚上18:10同步亮度与音量
-	c.AddFunc("0 10 18 * * ?", func() {
-		deviceCtl.InfoBoard.CronSyncBrightnessAndMusicvolume()
+	//【led信息屏】每59秒 播放节目同步
+	c.AddFunc("*/59 * * * * ?", func() {
+		deviceCtl.InfoBoard.CronSyncLedPaying(0)
 	})
-	//【led信息屏】播放节目同步
+	//【IP音柱】每59秒 播放节目同步
 	c.AddFunc("*/10 * * * * ?", func() {
-		deviceCtl.InfoBoard.CronSyncLedPaying(0)
+		deviceCtl.IpBroadcast.CronSyncIpCastPaying(0)
 	})
 	c.Start()
 }

+ 3 - 5
app/device/controller/infoBoardController.go

@@ -73,8 +73,7 @@ func (c *infoBoardCtl) CreateOrUpdate(ctx *gin.Context) {
 	}
 	if req.ID > 0 {
 		//更新 排程
-		c.CronSyncLedPaying(req.ID)
-		//fmt.Printf("req.ID = %v \n", req.ID)
+		service.InfoBoardService.EdgeCmd(claims.TenantId, req.Sn, 6, req.ID)
 	}
 	err := service.InfoBoardService.CreateOrUpdate(claims.UserId, claims.TenantId, req)
 	ctx.JSON(http.StatusOK, err)
@@ -166,10 +165,9 @@ func (s *infoBoardCtl) CronSyncBrightnessAndMusicvolume() {
 		fmt.Printf("err = %v \n", err)
 		return
 	}
-	//fmt.Printf("list = %v \n", list)
 	for _, led := range list {
 		_, retState := cache.GetDeviceState(led.Sn)
-		//fmt.Printf("retState = %v \n", retState)
+		// 只有设备在线 才能向边缘端下发命令
 		if retState == "1" {
 			service.InfoBoardService.EdgeCmd(led.TenantId, led.Sn, 101, led.ID)
 		}
@@ -201,7 +199,7 @@ func (s *infoBoardCtl) CronSyncLedPaying(id int) {
 				fmt.Printf("无需更新\n")
 			}
 		} else {
-			//fmt.Printf("led设备不在线Sn = %v \n", led.Sn)
+			fmt.Printf("led设备不在线Sn = %v \n", led.Sn)
 		}
 	}
 }

+ 56 - 0
app/device/controller/ipBroadcastController.go

@@ -1,12 +1,14 @@
 package controller
 
 import (
+	"fmt"
 	"github.com/gin-gonic/gin"
 	"iot_manager_service/app/device/dao"
 	"iot_manager_service/app/device/edge_service"
 	"iot_manager_service/app/device/model"
 	"iot_manager_service/app/device/service"
 	"iot_manager_service/app/middleware"
+	service2 "iot_manager_service/app/multimedia/service"
 	"iot_manager_service/util/common"
 	"math"
 	"net/http"
@@ -121,3 +123,57 @@ func (c *ipBroadcastCtl) SettingVolume(ctx *gin.Context) {
 	err := service.IpBroadcastService.CreateOrUpdate(claims.UserId, claims.TenantId, req)
 	ctx.JSON(http.StatusOK, err)
 }
+
+type settingIpCastReq struct {
+	ID        int `json:"id"`
+	Directive int `json:"directive"`
+}
+
+func (c *ipBroadcastCtl) SettingIpCast(ctx *gin.Context) {
+	var req settingIpCastReq
+	if err := ctx.ShouldBindJSON(&req); err != nil {
+		ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
+		return
+	}
+	if req.Directive == 1 {
+		err := edge_service.IpCastControlService{}.SetStop()
+		if err != nil {
+			ctx.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil))
+			return
+		}
+	}
+	if req.Directive == 2 {
+		c.CronSyncIpCastPaying(req.ID)
+	}
+	ctx.JSON(http.StatusOK, common.SuccessResponse(common.Succeeded, nil))
+}
+
+// 同步播放ip音柱节目
+func (c *ipBroadcastCtl) CronSyncIpCastPaying(id int) {
+	board := dao.IpBroadcast{}
+	if id > 0 {
+		board.ID = id
+	}
+	list, err := board.GetAllDevicesNotTenant()
+	if err != nil {
+		fmt.Printf("CronSyncIPCastPaying err = %v \n", err)
+		return
+	}
+	for _, IPCast := range list {
+		device, _ := service.IpBroadcastService.Get(IPCast.ID)
+		//fmt.Printf("device = %v \n", device)
+		if device.PlayState == "空闲" {
+			playJson, ptype := service2.PublishLibrariesService.IPCastPaying(IPCast.ID)
+			if playJson != "" {
+				fmt.Printf("需要更新 \n")
+				err := edge_service.IpCastControlService{}.PushPlay(playJson, ptype)
+				if err != nil {
+					fmt.Printf("err = %v \n", err)
+					return
+				}
+			} else {
+				fmt.Printf("无需更新\n")
+			}
+		}
+	}
+}

+ 1 - 1
app/device/dao/infoBoardDao.go

@@ -40,7 +40,7 @@ type InfoBoard struct {
 	ExteriorUid      int         `gorm:"type:bigint" json:"exteriorUid"`                   //外设ID
 	IsEnable         int         `gorm:"type:int; default 2 " json:"isEnable"`             //启用禁用:1启用,2禁用
 
-	Condition string `gorm:"type:varchar(255);" json:"condition"` //白天晚上 亮度 音量调节
+	Condition string `gorm:"type:varchar(255);default='80,30,30,5'" json:"condition"` //白天晚上 亮度 音量调节
 }
 
 func (InfoBoard) TableName() string {

+ 12 - 1
app/device/dao/ipBroadcastDao.go

@@ -19,9 +19,10 @@ type IpBroadcast struct {
 	ModelId          int         `gorm:"type:int" json:"modelId"`                          //设备型号
 	RatedPower       float32     `gorm:"type:float(8, 2); default 0.00" json:"ratedPower"` //额定功率(LED灯)
 	IPAddress        string      `gorm:"type:varchar(50)" json:"ipAddress"`                //IP地址
+	PlayState        string      `gorm:"-" json:"playState"`                               //播放状态
 	ServiceIpAddress string      `gorm:"type:varchar(50)" json:"serviceIpAddress"`         //服务IP地址
 	ServerPort       int         `gorm:"type:int" json:"serverPort"`                       //服务端口
-	SoundVolume      int         `gorm:"type:int" json:"soundVolume"`                      //音量0-100换算
+	SoundVolume      int         `gorm:"type:int;default=0" json:"soundVolume"`            //音量0-100换算
 	InstallTime      common.Time `gorm:"type:date" json:"installTime"`                     //安装时间
 	TenantId         string      `gorm:"type:varchar(12)" json:"tenantId"`                 //租户ID
 	CreateTime       time.Time   `gorm:"type:datetime" json:"createTime"`                  //新增时间
@@ -119,3 +120,13 @@ func (c IpBroadcast) GetByIds(ids string) []IpBroadcast {
 		c.IsDeleted).Where("id in (" + ids + ")").Scan(&devices)
 	return devices
 }
+
+func (c IpBroadcast) GetAllDevicesNotTenant() ([]*IpBroadcast, error) {
+	var devices []*IpBroadcast
+	db := Db.Debug().Model(&c)
+	if c.ID > 0 {
+		db.Where("id=?", c.ID)
+	}
+	err := db.Where("is_deleted = 0 ").Scan(&devices).Error
+	return devices, err
+}

+ 2 - 2
app/device/edge_service/forLightControlService.go

@@ -9,6 +9,7 @@ import (
 	"strings"
 )
 
+// ForLightControl 灯控相关操作
 type ForLightControl struct{}
 
 type ForLightControlReq struct {
@@ -24,13 +25,12 @@ type ForLightControlRes struct {
 	Msg  string `json:"msg"`
 }
 
+// SwitchLightCtr 向边缘云端发送开关灯指令
 func (f ForLightControl) SwitchLightCtr(reqData ForLightControlReq) {
 	reqData.Whole = 0
 	cfg := config.Instance()
 	url := cfg.Foreign.IotEdgeUrl + "/lamp/v1/switch"
-
 	method := "POST"
-
 	client := &http.Client{}
 	marshal, _ := json.Marshal(reqData)
 	req, err := http.NewRequest(method, url, strings.NewReader(string(marshal)))

+ 94 - 12
app/device/edge_service/ipCastControlService.go

@@ -9,6 +9,7 @@ import (
 	"iot_manager_service/util/common"
 	"iot_manager_service/util/logger"
 	"net/http"
+	"strconv"
 	"strings"
 )
 
@@ -61,6 +62,30 @@ func (f IpCastControlService) GetTermIds() (terminfos map[string]TermInfo, err e
 	return terminfos, err
 }
 
+// SetVol 设置音量
+func (f IpCastControlService) SetVol(sn string, vol int) error {
+	terminfos, err2 := f.GetTermIds()
+	if err2 != nil {
+		return err2
+	}
+	term, ok := terminfos[sn]
+	if !ok {
+		return errors.New("devices not found\tsn=" + sn)
+	}
+	var reqData IpCastControlReq
+	reqData.Action = "TermVolSet"
+	m := make(map[string]interface{})
+	m["TermIds"] = []int{term.ID}
+	m["Volume"] = int(common.MapRange(float64(vol), 1, 100, 1, 16))
+	reqData.PostData = m
+	_, err := f.RequestApi(reqData)
+	if err != nil {
+		return err
+	}
+	return nil
+}
+
+// RequestApi 公共请求
 func (f IpCastControlService) RequestApi(reqData IpCastControlReq) (map[string]interface{}, error) {
 	cfg := config.Instance()
 	url := fmt.Sprintf("%v/%v", cfg.Foreign.IpCastEdgeUrl, reqData.Action)
@@ -103,25 +128,82 @@ func (f IpCastControlService) RequestApi(reqData IpCastControlReq) (map[string]i
 	return IpCastControlRes, nil
 }
 
-// SetVol 设置音量
-func (f IpCastControlService) SetVol(sn string, vol int) error {
-	terminfos, err2 := f.GetTermIds()
-	if err2 != nil {
-		return err2
+type uploadMp3Data struct {
+	Remark   string `json:"Remark"`
+	Ret      int    `json:"Ret"`
+	NSeconds int    `json:"nSeconds"`
+}
+
+// UploadMp3GetFileId 上传素材 到ip音柱服务端
+func (f IpCastControlService) UploadMp3GetFileId(imgUrl string, fileName string) (string, error) {
+	cfg := config.Instance()
+	url := fmt.Sprintf("%v/UploadFile:%v", cfg.Foreign.IpCastEdgeUrl, fileName)
+	method := "POST"
+
+	response, err := http.Get(imgUrl)
+	if err != nil {
+		panic(err)
 	}
-	term, ok := terminfos[sn]
-	if !ok {
-		return errors.New("devices not found\tsn=" + sn)
+	defer response.Body.Close()
+	client := &http.Client{}
+	req, err := http.NewRequest(method, url, response.Body)
+	if err != nil {
+		fmt.Println(err)
+		logger.Logger.Errorf("IpCastControlService UploadMp3GetFileId 1 %v", err.Error())
+		return "", err
+	}
+	req.Header.Add("Content-Type", "audio/mpeg")
+
+	res, err := client.Do(req)
+	if err != nil {
+		fmt.Println(err)
+		logger.Logger.Errorf("IpCastControlService UploadMp3GetFileId 2 %v", err.Error())
+		return "", err
+	}
+	defer res.Body.Close()
+
+	body, err := ioutil.ReadAll(res.Body)
+	if err != nil {
+		fmt.Println(err)
+		logger.Logger.Errorf("IpCastControlService UploadMp3GetFileId 3 %v", err.Error())
+		return "", err
 	}
+	var resData uploadMp3Data
+	err = json.Unmarshal(body, &resData)
+	if err != nil {
+		return "", err
+	}
+	if resData.Ret > 0 {
+		return strconv.Itoa(resData.Ret), nil
+	}
+	return "", errors.New("上传失败啦")
+}
+
+func (f IpCastControlService) SetStop() error {
 	var reqData IpCastControlReq
-	reqData.Action = "TermVolSet"
+	reqData.Action = "StopMp3ByID"
 	m := make(map[string]interface{})
-	m["TermIds"] = []int{term.ID}
-	m["Volume"] = int(common.MapRange(float64(vol), 1, 100, 1, 16))
+	m["ID"] = 0
 	reqData.PostData = m
 	_, err := f.RequestApi(reqData)
+	return err
+}
+
+// 发布节目
+func (f IpCastControlService) PushPlay(playJson string, ptype int) error {
+	var reqData IpCastControlReq
+	if ptype == 1 {
+		reqData.Action = "PlayMp3ByID"
+	} else {
+		reqData.Action = "PlayText"
+	}
+	m := make(map[string]interface{})
+	fmt.Printf("playJson = %v \n", playJson)
+	err := json.Unmarshal([]byte(playJson), &m)
+	reqData.PostData = m
 	if err != nil {
 		return err
 	}
-	return nil
+	_, err = f.RequestApi(reqData)
+	return err
 }

+ 14 - 14
app/device/model/infoBoard.go

@@ -19,20 +19,20 @@ type ReqInfoBoardRemove struct {
 
 type InfoBoardDetail struct {
 	dao.InfoBoard
-	EndLineTime    time.Time `json:"endLineTime"`    //最后上线时间
-	NetworkState   string    `json:"networkState"`   //网络状态
-	RunState       string    `json:"runState"`       //运行状态
-	PublicName     string    `json:"publicName"`     //节目发布时使用
-	OnTheAir       string    `json:"onTheAir"`       //当前播放的节目
-	ResolutionName string    `json:"resolutionName"` //分辨率
-	Volume         string    `json:"volume"`         //音量
-	Voltage        string    `json:"voltage"`        //电压
-	Luminance      string    `json:"luminance"`      //亮度
-	Temperature    string    `json:"temperature"`    //色温
-	RebootTime     string    `json:"rebootTime"`     //重启时间
-	Power          string    `json:"power"`          //电源状态
-	BootStartTime  string    `json:"bootStartTime"`  //开关机状态
-	BootEndTime    string    `json:"bootEndTime"`    //开关机状态
+	EndLineTime         time.Time `json:"endLineTime"`         //最后上线时间
+	NetworkState        string    `json:"networkState"`        //网络状态
+	RunState            string    `json:"runState"`            //运行状态
+	PublicName          string    `json:"publicName"`          //节目发布时使用
+	OnTheAir            string    `json:"onTheAir"`            //当前播放的节目
+	ResolutionName      string    `json:"resolutionName"`      //分辨率
+	Volume              string    `json:"volume"`              //音量
+	Voltage             string    `json:"voltage"`             //电压
+	Luminance           string    `json:"luminance"`           //亮度
+	Temperature         string    `json:"temperature"`         //色温
+	RebootTime          string    `json:"rebootTime"`          //重启时间
+	RealStartAndEndTime string    `json:"realStartAndEndTime"` //开机时间和关机时间
+	Power               string    `json:"power"`               //电源状态
+
 }
 
 // CltledData 信息屏 数据

+ 33 - 11
app/device/service/infoBoardService.go

@@ -19,17 +19,19 @@ var InfoBoardService = new(infoBoardService)
 
 type infoBoardService struct{}
 
-func (s *infoBoardService) Get(id int) (*model.InfoBoardDetail, *common.Errors) {
+func (s *infoBoardService) Get(id int) (model.InfoBoardDetail, *common.Errors) {
 	// 创建查询实例
 	device := &dao.InfoBoard{
 		ID: id,
 	}
 	getDevice, err := device.GetDevice()
 	if err != nil {
-		return nil, common.FailResponse(err.Error(), nil)
+		return model.InfoBoardDetail{}, common.FailResponse(err.Error(), nil)
 	}
 	detail := s.rewriteBoardDetail(getDevice)
-	return &detail, nil
+	fmt.Printf("detail = %v \n", detail.BootStartTime)
+	fmt.Printf("detail = %v \n", detail.Condition)
+	return detail, nil
 }
 
 func (s *infoBoardService) CreateOrUpdate(userId int64, tenantId string, req dao.InfoBoard) *common.Errors {
@@ -91,6 +93,7 @@ func (s *infoBoardService) List(searchValue string, current, size int) ([]model.
 // 从缓存中读取真实状态
 func (s *infoBoardService) rewriteBoardDetail(d dao.InfoBoard) model.InfoBoardDetail {
 	endTime, state := cache.GetDeviceState(d.Sn)
+
 	detail := model.InfoBoardDetail{
 		InfoBoard:    d,
 		RunState:     state,
@@ -98,12 +101,14 @@ func (s *infoBoardService) rewriteBoardDetail(d dao.InfoBoard) model.InfoBoardDe
 		EndLineTime:  endTime,
 	}
 	cacheMap := cache.GetDeviceLedData(d.Sn)
+
 	if cacheMap != nil {
 		marshal, err := json.Marshal(cacheMap)
 		if err != nil {
 			logger.Logger.Errorf("rewriteBoardDetail err1 = %v \n", err)
 			return detail
 		}
+
 		var cltData model.CltledData
 		err = json.Unmarshal(marshal, &cltData)
 		if err != nil {
@@ -111,6 +116,7 @@ func (s *infoBoardService) rewriteBoardDetail(d dao.InfoBoard) model.InfoBoardDe
 			return detail
 		}
 		detail.Power = "边缘程序未升级"
+
 		if cltData.RealWidth != "" {
 			detail.ResolutionName = fmt.Sprintf("%v * %v", cltData.RealWidth, cltData.RealHeight)
 			detail.OnTheAir = cltData.Playing
@@ -139,11 +145,13 @@ func (s *infoBoardService) rewriteBoardDetail(d dao.InfoBoard) model.InfoBoardDe
 			}
 			if cltData.WakeupTime != "" {
 				detail.NeverCloseDown = 2
-				detail.BootStartTime = cltData.WakeupTime
-				detail.BootEndTime = cltData.SleepTime
+				//detail.BootStartTime = cltData.WakeupTime
+				//detail.BootEndTime = cltData.SleepTime
+				detail.RealStartAndEndTime = fmt.Sprintf("%v-%v", cltData.WakeupTime, cltData.SleepTime)
 			}
 		}
 	}
+
 	return detail
 }
 
@@ -209,22 +217,22 @@ func (s *infoBoardService) EdgeCmd(tenant, sn string, cmdNum, id int) {
 	case 3: //重启
 		param["command"] = "reboot"
 		s.reqEdge(tenant, edgePost, param, action)
-	case 4: //重新节目
+	//case 4: //重新节目,不在此处,处理了
 	case 6: //更新排程
 		device := &dao.InfoBoard{
 			ID: id,
 		}
 		dev, _ := device.GetDevice()
 		action = "ssched"
-		sleep := dev.BootEndTime + ":00"
-		param["sleep"] = sleep[0:8]
-		wakeup := dev.BootStartTime + ":00"
-		param["wakeup"] = wakeup[0:8]
 		if dev.NeverCloseDown == 1 {
 			param["sleep"] = ""
 			param["wakeup"] = ""
+		} else {
+			sleep, wakeup := ledTimeFormat(dev.BootEndTime, dev.BootStartTime)
+			param["sleep"] = sleep
+			param["wakeup"] = wakeup
 		}
-		param["reboot"] = "12:30:10" //每日重启时间
+		param["reboot"] = "12:30:1" //每日重启时间
 		s.reqEdge(tenant, edgePost, param, action)
 	case 101: //更新亮度 音量, 这里需要做成定时任务去跑
 		device := &dao.InfoBoard{
@@ -290,3 +298,17 @@ func isEight() bool {
 		return false
 	}
 }
+
+// ledTimeFormat led开始 结束时间格式化
+func ledTimeFormat(stime string, etime string) (string, string) {
+	startTime := fmt.Sprintf("%v %v:01", time.Now().Format("2006-01-02"), stime)
+	endTime := fmt.Sprintf("%v %v:01", time.Now().Format("2006-01-02"), etime)
+
+	ktime, _ := time.Parse("2006-01-02 15:04:05", startTime)
+	jtime, _ := time.Parse("2006-01-02 15:04:05", endTime)
+
+	atoi1, _ := strconv.Atoi(ktime.Format("15"))
+	atoi2, _ := strconv.Atoi(jtime.Format("15"))
+
+	return fmt.Sprintf("%v:%v:1", atoi1, ktime.Format("4")), fmt.Sprintf("%v:%v:1", atoi2, jtime.Format("4"))
+}

+ 10 - 0
app/device/service/ipBroadcastService.go

@@ -31,10 +31,15 @@ func (s *ipBroadcastService) Get(id int) (*model.IpBroadcastDetail, *common.Erro
 	info, ok := terms[device.CastSn]
 	state := "2"
 	if ok {
+		device.PlayState = "不在线"
 		if info.Online == 1 {
 			state = "1"
 			device.SoundVolume = info.Vol
 			device.IPAddress = info.IP
+			device.PlayState = "空闲"
+			if info.State == 2 {
+				device.PlayState = "文件广播[" + info.From + "]"
+			}
 		}
 	}
 
@@ -104,10 +109,15 @@ func (s *ipBroadcastService) List(searchValue string, current, size int) ([]mode
 		info, ok := terms[d.CastSn]
 		state := "2"
 		if ok {
+			d.PlayState = "不在线"
 			if info.Online == 1 {
 				state = "1"
 				d.SoundVolume = info.Vol
 				d.IPAddress = info.IP
+				d.PlayState = "空闲"
+				if info.State == 2 {
+					d.PlayState = "文件广播[" + info.From + "]"
+				}
 			}
 		}
 		details = append(details, model.IpBroadcastDetail{

+ 13 - 1
app/multimedia/controller/libraryController.go

@@ -1,7 +1,9 @@
 package controller
 
 import (
+	"fmt"
 	"github.com/gin-gonic/gin"
+	"iot_manager_service/app/device/edge_service"
 	"iot_manager_service/app/middleware"
 	"iot_manager_service/app/multimedia/dao"
 	"iot_manager_service/app/multimedia/model"
@@ -139,8 +141,18 @@ func (c *libraryCtl) Submit(ctx *gin.Context) {
 	}
 	value, _ := ctx.Get(middleware.Authorization)
 	claims := value.(*middleware.Claims)
-
+	if req.LibType == 4 {
+		//如果是音频, 要上传到音频服务器得到文件ID
+		fileName := fmt.Sprintf("%v/new/%v", claims.TenantId, req.LibName)
+		fileId, err := edge_service.IpCastControlService{}.UploadMp3GetFileId(req.MaterialAddress, fileName)
+		if err != nil {
+			ctx.JSON(http.StatusOK, common.FailResponse(err.Error(), nil))
+			return
+		}
+		req.FileId = fileId
+	}
 	e := service.LibraryService.Submit(claims.TenantId, claims.UserId, req)
+
 	if e != nil {
 		ctx.JSON(http.StatusOK, e)
 		return

+ 31 - 24
app/multimedia/dao/publishLibrariesDao.go

@@ -8,31 +8,32 @@ import (
 
 type PublishLibraries struct {
 	ID               int64       `gorm:"column:id;type:int(10) unsigned;primary_key;AUTO_INCREMENT;comment:编号" json:"id"`
-	Name             string      `gorm:"column:name;type:varchar(64);comment:名称" json:"name"`                                                       // 名称
-	Resolution       int         `gorm:"column:resolution;type:int(11);comment:分辨率" json:"resolution"`                                             // 分辨率
-	Duration         int64       `gorm:"column:duration;type:bigint(20);default:0;comment:统计文件时长" json:"duration"`                              // 统计文件时长
-	FileSize         int64       `gorm:"column:file_size;type:bigint(20);default:0;comment:统计文件大小" json:"fileSize"`                             // 统计文件大小
-	InfoId           string      `gorm:"column:info_id;type:varchar(4000);comment:信息屏ID 组合" json:"infoId"`                                       // 信息屏ID 组合
-	ImgDuration      int         `gorm:"column:img_duration;type:int(11);default:0;comment:图片播放时长(毫秒)" json:"imgDuration"`                    // 图片播放时长(毫秒)
-	StartTime        common.Time `gorm:"column:start_time;type:date;comment:播放开始时间" json:"startTime"`                                           // 播放开始时间
-	EndTime          common.Time `gorm:"column:end_time;type:date;comment:播放结束时间" json:"endTime"`                                               // 播放结束时间
+	Name             string      `gorm:"column:name;type:varchar(64);comment:名称" json:"name"`                                           // 名称
+	Resolution       int         `gorm:"column:resolution;type:int(11);comment:分辨率" json:"resolution"`                                  // 分辨率
+	Duration         int64       `gorm:"column:duration;type:bigint(20);default:0;comment:统计文件时长" json:"duration"`                      // 统计文件时长
+	FileSize         int64       `gorm:"column:file_size;type:bigint(20);default:0;comment:统计文件大小" json:"fileSize"`                     // 统计文件大小
+	InfoId           string      `gorm:"column:info_id;type:varchar(4000);comment:信息屏ID 组合" json:"infoId"`                              // 信息屏ID 组合
+	ImgDuration      int         `gorm:"column:img_duration;type:int(11);default:0;comment:图片播放时长(毫秒)" json:"imgDuration"`              // 图片播放时长(毫秒)
+	StartTime        common.Time `gorm:"column:start_time;type:date;comment:播放开始时间" json:"startTime"`                                   // 播放开始时间
+	EndTime          common.Time `gorm:"column:end_time;type:date;comment:播放结束时间" json:"endTime"`                                       // 播放结束时间
 	NotificationType string      `gorm:"column:notification_type;type:varchar(60);comment:通知类型 组合1短信2邮件3电话4微信" json:"notificationType"` // 通知类型 组合1短信2邮件3电话4微信
-	CreateTime       time.Time   `gorm:"column:create_time;type:datetime;comment:新增时间" json:"createTime"`                                         // 新增时间
-	CreateUser       int64       `gorm:"column:create_user;type:varchar(60);comment:增记录操作用户ID" json:"createUser"`                              // 新增记录操作用户ID
-	CreateName       string      `gorm:"column:create_name;type:varchar(64);comment:新增用户姓名" json:"createName"`                                  // 新增用户姓名
-	UpdateTime       time.Time   `gorm:"column:update_time;type:datetime;comment:修改时间" json:"updateTime"`                                         // 修改时间
-	UpdateUser       string      `gorm:"column:update_user;type:varchar(60);comment:修改用户" json:"updateUser"`                                      // 修改用户
-	IsDeleted        int         `gorm:"column:is_deleted;type:int(11);default:0;comment:是否删除 0=未删除,1=删除" json:"isDeleted"`                  // 是否删除 0=未删除,1=删除
-	Status           int         `gorm:"column:status;type:int(11);comment:状态 0审核1播放2暂停3取消4过期5审核不通过" json:"status"`                  // 状态 0审核1播放2暂停3取消4过期5审核不通过
-	TenantId         string      `gorm:"column:tenant_id;type:varchar(12);comment:租户ID" json:"tenantTd"`                                            // 租户ID
-	Remarks          string      `gorm:"column:remarks;type:varchar(4000);comment:系统类型:0-多媒体系统,1-广播系统" json:"remarks"`                   // 备注
-	SysType          int         `gorm:"column:sys_type;type:int(11);default:0;comment:编号" json:"sysStype"`                                         // 系统类型:0-多媒体系统,1-广播系统
-	KsTime           string      `gorm:"column:ks_time;type:varchar(50);comment:播放开始时间" json:"ksTime"`                                          // 播放开始时间
-	JsTime           string      `gorm:"column:js_time;type:varchar(50);comment:播放结束时间" json:"jsTime"`                                          // 播放结束时间
+	CreateTime       time.Time   `gorm:"column:create_time;type:datetime;comment:新增时间" json:"createTime"`                               // 新增时间
+	CreateUser       int64       `gorm:"column:create_user;type:varchar(60);comment:增记录操作用户ID" json:"createUser"`                       // 新增记录操作用户ID
+	CreateName       string      `gorm:"column:create_name;type:varchar(64);comment:新增用户姓名" json:"createName"`                          // 新增用户姓名
+	UpdateTime       time.Time   `gorm:"column:update_time;type:datetime;comment:修改时间" json:"updateTime"`                               // 修改时间
+	UpdateUser       string      `gorm:"column:update_user;type:varchar(60);comment:修改用户" json:"updateUser"`                            // 修改用户
+	IsDeleted        int         `gorm:"column:is_deleted;type:int(11);default:0;comment:是否删除 0=未删除,1=删除" json:"isDeleted"`             // 是否删除 0=未删除,1=删除
+	Status           int         `gorm:"column:status;type:int(11);comment:状态 0审核1播放2暂停3取消4过期5审核不通过" json:"status"`                     // 状态 0审核1播放2暂停3取消4过期5审核不通过
+	TenantId         string      `gorm:"column:tenant_id;type:varchar(12);comment:租户ID" json:"tenantTd"`                                // 租户ID
+	Remarks          string      `gorm:"column:remarks;type:varchar(4000);comment:系统类型:0-多媒体系统,1-广播系统" json:"remarks"`                  // 备注
+	SysType          int         `gorm:"column:sys_type;type:int(11);default:0;comment:编号" json:"sysStype"`                             // 系统类型:0-多媒体系统,1-广播系统
+	KsTime           string      `gorm:"column:ks_time;type:varchar(50);comment:播放开始时间" json:"ksTime"`                                  // 播放开始时间
+	JsTime           string      `gorm:"column:js_time;type:varchar(50);comment:播放结束时间" json:"jsTime"`                                  // 播放结束时间
+	Ptype            int         `gorm:"-" json:"ptype"`                                                                                // 1mp3 2文字
 	FileId           int         `gorm:"column:file_id;type:int(11);comment:文件ID,系统类型为广播系统时使用" json:"fileId"`                           // 文件ID,系统类型为广播系统时使用
-	TaskId           int         `gorm:"column:task_id;type:int(11);comment:任务ID,发布后才有用于控制启动与停止" json:"taskId"`                       // 任务ID,发布后才有用于控制启动与停止
-	PlayTime         int         `gorm:"column:play_time;type:int(11);default:1;comment:播放次数(1-100)" json:"playTime"`                             // 播放次数(1-100)
-	PlayInterval     int         `gorm:"column:play_interval;type:int(11);default:0;comment: 播放间隔(0-360秒)" json:"playInterval"`                  // 播放间隔(0-360秒)
+	TaskId           int         `gorm:"column:task_id;type:int(11);comment:任务ID,发布后才有用于控制启动与停止" json:"taskId"`                         // 任务ID,发布后才有用于控制启动与停止
+	PlayTime         int         `gorm:"column:play_time;type:int(11);default:1;comment:播放次数(1-100)" json:"playTime"`                   // 播放次数(1-100)
+	PlayInterval     int         `gorm:"column:play_interval;type:int(11);default:0;comment: 播放间隔(0-360秒)" json:"playInterval"`         // 播放间隔(0-360秒)
 
 	PlayPeriod     string `gorm:"-"  json:"playPeriod"`              //播放期间
 	ResolutionName string `gorm:"-" json:"resolutionName"`           //分辨率
@@ -70,7 +71,7 @@ func (c *PublishLibraries) GetProgram() (int, error) {
 // GetProgramByLedId 取led信息屏当前播放的节目 ID
 func (c *PublishLibraries) GetProgramByLedId(ledId int) (PublishLibraries, error) {
 	var librarie PublishLibraries
-	err := Db.Debug().Model(&c).Where("info_id IN (?) and is_deleted = 0 and status = 1 and sys_type = 0 and start_time <= CURDATE()  AND a.end_time >= CURDATE()", ledId).Order("id desc").First(&librarie).Error
+	err := Db.Debug().Model(&c).Where("find_in_set  ( ?,info_id )  and is_deleted = 0 and status = 1 and sys_type = 0 and start_time <= CURDATE()  AND end_time >= CURDATE()", ledId).Order("id desc").First(&librarie).Error
 	return librarie, err
 }
 
@@ -78,3 +79,9 @@ func (c PublishLibraries) Delete() error {
 	return Db.Debug().Model(&c).Where("id = ?", c.ID).Updates(map[string]interface{}{"update_time": c.UpdateTime,
 		"update_user": c.UpdateUser, "is_deleted": c.IsDeleted}).Error
 }
+
+func (c PublishLibraries) GetProgramByIpCastId(id int) ([]PublishLibraries, interface{}) {
+	var libraries []PublishLibraries
+	err := Db.Debug().Model(&c).Where("find_in_set  ( ?,info_id ) AND is_deleted = 0 AND status = 1 AND sys_type = 1 AND start_time <= CURDATE() AND end_time >= CURDATE() and ks_time <= date_format(now(),'%H:%i')", id).Order("id desc").Find(&libraries).Error
+	return libraries, err
+}

+ 3 - 0
app/multimedia/model/program.go

@@ -64,4 +64,7 @@ type ReqProgramAudit struct {
 	SysType            int         `json:"sysType"`            //系统类型:0-多媒体系统,1-广播系统
 	JsTime             string      `json:"jsTime"`             //播放时间
 	KsTime             string      `json:"ksTime"`             //播放时间
+
+	PlayTime     int `json:"playTime"`     //文字 播放次数
+	PlayInterval int `json:"playInterval"` //文字 有无提示音
 }

+ 141 - 0
app/multimedia/service/publishLibrariesService.go

@@ -89,6 +89,8 @@ func (s *publishLibrariesService) Create(program *dao.Program, req model.ReqProg
 		KsTime:           req.KsTime,
 		JsTime:           req.JsTime,
 		FileId:           program.ID,
+		PlayTime:         req.PlayTime,
+		PlayInterval:     req.PlayInterval,
 	}
 	libraries.CreateTime = time.Now()
 	if err := libraries.Create(); err != nil {
@@ -212,6 +214,7 @@ func (s *publishLibrariesService) LedPaying(ledId int, playing string) string {
 	cltLedLibraries.Imageinfo.InEffect.Type = "2"
 	//cltLedLibraries.Imageinfo.InEffect.Time = strconv.Itoa(relations[0].Duration)
 	cltLedLibraries.Imageinfo.InEffect.Time = "1500"
+	fmt.Printf("cltLedLibraries = %v \n", cltLedLibraries)
 	marshal, err := json.Marshal(cltLedLibraries)
 	if err != nil {
 		fmt.Printf("LedPaying err = %v \n", err)
@@ -223,3 +226,141 @@ func (s *publishLibrariesService) LedPaying(ledId int, playing string) string {
 	//fmt.Printf("str = %v \n", str)
 	return str
 }
+
+type iPCastPayingMp3Info struct {
+	Type      int   `json:"Type"`
+	PlayTimes int   `json:"PlayTimes"`
+	FileIds   []int `json:"FileIds"`
+	TermIds   []int `json:"TermIds"`
+}
+
+type iPCastPayingContentInfo struct {
+	Content    string `json:"Content"`
+	Playtime   int    `json:"Playtime"`
+	TermIds    []int  `json:"TermIds"`
+	PlayVol    int    `json:"PlayVol"`
+	PromptTone int    `json:"PromptTone"`
+}
+
+func (s *publishLibrariesService) IPCastPaying(id int) (string, int) {
+	publishLibraries := dao.PublishLibraries{}
+	libraries, err := publishLibraries.GetProgramByIpCastId(id)
+	if err != nil {
+		logger.Logger.Errorf("IPCastPaying err = %v \n", err)
+		return "", 0
+	}
+	if len(libraries) < 1 {
+		//没有新节目不更新
+		return "", 0
+	}
+	//fmt.Printf("libraries = %v \n", libraries)
+	var librarie dao.PublishLibraries
+	//判断当前到底要放哪个节目
+	for _, library := range libraries {
+		library.Ptype = 1
+		if library.JsTime == "" {
+			library.Ptype = 0
+		}
+		if library.Ptype == 1 && library.JsTime != "" {
+			currTime := time.Now()
+			parse, err := time.Parse("2006-01-02 15:04", fmt.Sprintf("%v %v", time.Now().Format("2006-01-02"), library.JsTime))
+			if err != nil {
+				fmt.Printf("IPCastPaying parse err = %v \n", err)
+				logger.Logger.Errorf("IPCastPaying parse err = %v \n", err)
+				continue
+			}
+			if parse.Before(currTime) {
+				continue
+			}
+
+		} else {
+			cTime := time.Now()
+			kTime, err := time.Parse("2006-01-02 15:04", fmt.Sprintf("%v %v", time.Now().Format("2006-01-02"), library.KsTime))
+			if err != nil {
+				fmt.Printf("IPCastPaying kTime err = %v \n", err)
+				logger.Logger.Errorf("IPCastPaying kTime err = %v \n", err)
+			}
+			//这里要作限制 ,只有是当前时分 才操作
+			if cTime.Minute() != kTime.Minute() || cTime.Hour() == kTime.Hour() {
+				continue
+			}
+		}
+		librarie = library
+	}
+	//fmt.Printf("librarie = %v \n", librarie)
+	program, _ := s.GetProgram(int(librarie.ID))
+	relation := &dao.ProgramRelation{
+		ProgramId: program,
+		TenantId:  librarie.TenantId,
+	}
+	relations, err := relation.GetByProgram()
+	if err != nil {
+		logger.Logger.Errorf("IPCastPaying err = %s \n", err)
+		return "", 0
+	}
+	var libraryIds []int
+	for _, relation := range relations {
+		libraryIds = append(libraryIds, relation.LibraryId)
+	}
+	library := &dao.Library{TenantId: librarie.TenantId}
+	getLibrariesByIds, _ := library.GetLibrariesByIds(libraryIds)
+	if len(getLibrariesByIds) < 1 {
+		logger.Logger.Errorf("无素材")
+		return "", 0
+	}
+	//fmt.Printf("getLibrariesByIds = %v \n", getLibrariesByIds)
+	// 音频播放
+	if librarie.Ptype == 1 {
+		paytime := diffTime(librarie.KsTime, librarie.JsTime)
+		if paytime < 0 {
+			logger.Logger.Errorf("播放时间出错啦")
+			return "", 0
+		}
+		fileIds := []int{}
+		for _, libs := range getLibrariesByIds {
+			fid, _ := strconv.Atoi(libs.FileId)
+			fileIds = append(fileIds, fid)
+		}
+		info := iPCastPayingMp3Info{
+			Type:      1,
+			PlayTimes: paytime,
+			FileIds:   fileIds,
+			TermIds:   []int{1, 2, 3, 4, 5, 6, 7, 8},
+		}
+		marshal, err := json.Marshal(info)
+		if err != nil {
+			logger.Logger.Errorf("IPCastPaying iPCastPayingMp3Info err = %v \n", err)
+			return "", 0
+		}
+		return string(marshal), librarie.Ptype
+		//文字播放
+	} else {
+		contentInfo := iPCastPayingContentInfo{
+			Content:    getLibrariesByIds[0].MaterialAddress,
+			Playtime:   librarie.PlayTime,
+			TermIds:    []int{1, 2, 3, 4, 5, 6, 7, 8},
+			PlayVol:    50,
+			PromptTone: librarie.PlayInterval,
+		}
+		marshal, err := json.Marshal(contentInfo)
+		if err != nil {
+			logger.Logger.Errorf("IPCastPaying contentInfo err = %v \n", err)
+			return "", 0
+		}
+		return string(marshal), librarie.Ptype
+	}
+}
+
+// 计算2个时间相差多少秒
+func diffTime(stime, etime string) int {
+	stimeT, err := time.Parse("2006-01-02 15:04", fmt.Sprintf("%v %v", time.Now().Format("2006-01-02"), stime))
+	if err != nil {
+		return -1
+	}
+	etimeT, err2 := time.Parse("2006-01-02 15:04", fmt.Sprintf("%v %v", time.Now().Format("2006-01-02"), etime))
+	if err2 != nil {
+		return -1
+	}
+	diff := int(etimeT.Sub(stimeT).Seconds())
+	return diff
+}

+ 1 - 0
router/router.go

@@ -151,6 +151,7 @@ func InitRouter(engine *gin.Engine) {
 		ipBroadCast.GET("/export-excel", device.IpBroadcast.ExportExcel)
 		ipBroadCast.GET("/export-template", device.IpBroadcast.ExportTemplate)
 		ipBroadCast.POST("/setting-volume", device.IpBroadcast.SettingVolume)
+		ipBroadCast.POST("/setting-ipcast", device.IpBroadcast.SettingIpCast)
 	}
 
 	//一键报警服务表 控制器