Skip to content

Commit

Permalink
add reboot api
Browse files Browse the repository at this point in the history
  • Loading branch information
kuaifan committed Sep 8, 2022
1 parent 1f1571e commit 3441159
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 9 deletions.
36 changes: 27 additions & 9 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ func apiStart(br *broker) {
})
})

// 设备 action=bind|unbind devid=设备id
// 设备 action=bind|unbind|reboot devid=设备id
r.GET("/hi/device/:action/:devid", func(c *gin.Context) {
action := c.Param("action")
devid := c.Param("devid")
Expand All @@ -887,7 +887,14 @@ func apiStart(br *broker) {
return
}

authUser, authErr := userAuth(c, db, "")
var authUser *hi.UserModel
var authErr error

if action == "unbind" || action == "reboot" {
authUser, authErr = userAuth(c, db, devid)
} else {
authUser, authErr = userAuth(c, db, "")
}
if authErr != nil {
c.JSON(http.StatusOK, gin.H{
"ret": 0,
Expand Down Expand Up @@ -928,18 +935,29 @@ func apiStart(br *broker) {
}
} else if action == "unbind" {
// 取消绑定
if deviceData.BindOpenid != authUser.Openid {
db.Table("hi_wg").Where(map[string]interface{}{"devid": devid}).Update("status", "unbind")
db.Table("hi_shunt").Where(map[string]interface{}{"devid": devid}).Update("status", "unbind")
deviceData.BindOpenid = ""
db.Table("hi_device").Save(&deviceData)
} else if action == "reboot" {
// 重启设备
onlyid := devidGetOnlyid(br, devid)
if len(onlyid) == 0 {
c.JSON(http.StatusOK, gin.H{
"ret": 0,
"msg": "设备未绑定",
"msg": "设备不在线",
"data": nil,
})
return
} else {
c.JSON(http.StatusOK, gin.H{
"ret": 1,
"msg": "success",
"data": gin.H{
"token": hiRebootDevice(br, devid),
},
})
}
db.Table("hi_wg").Where(map[string]interface{}{"devid": devid}).Update("status", "unbind")
db.Table("hi_shunt").Where(map[string]interface{}{"devid": devid}).Update("status", "unbind")
deviceData.BindOpenid = ""
db.Table("hi_device").Save(&deviceData)
return
}

c.JSON(http.StatusOK, gin.H{
Expand Down
13 changes: 13 additions & 0 deletions hi.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,19 @@ func hiSynchShuntConf(br *broker, devid, callback string) string {
return hiExecBefore(br, db, devid, hi.GetCmdBatch(br.cfg.HiApiUrl, shunts), callback)
}

// 重启设备
func hiRebootDevice(br *broker, devid string) string {
if len(br.cfg.HiApiUrl) == 0 {
log.Info().Msgf("api url is empty")
return ""
}
db, err := hi.InstanceDB(br.cfg.DB)
if err != nil {
return ""
}
return hiExecBefore(br, db, devid, "#!/bin/sh\nreboot", "")
}

// 执行之前
func hiExecBefore(br *broker, db *gorm.DB, devid, cmd, callback string) string {
onlyid := devidGetOnlyid(br, devid)
Expand Down

0 comments on commit 3441159

Please sign in to comment.