device_service.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727
  1. package service
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "rtzh_elec_temperature/conf"
  8. "rtzh_elec_temperature/datachannel"
  9. "rtzh_elec_temperature/enum"
  10. "rtzh_elec_temperature/global"
  11. "rtzh_elec_temperature/logger"
  12. "rtzh_elec_temperature/models/bo"
  13. "rtzh_elec_temperature/mqtt"
  14. "rtzh_elec_temperature/rtelec_app_public_lib/utils"
  15. "rtzh_elec_temperature/tools"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "git.rtzhtech.cn/iss/public-lib/logic"
  21. "git.rtzhtech.cn/iss/public-lib/model"
  22. "github.com/astaxie/beego/orm"
  23. "github.com/spf13/cast"
  24. "github.com/wxnacy/wgo/arrays"
  25. )
  26. //设备测点映射缓存
  27. var deviceMappinInfo = sync.Map{}
  28. //设备测点列表缓存
  29. var deviceMpList = sync.Map{}
  30. //创建设备时提交的数据信息
  31. var deviceInfoData = new(sync.Map)
  32. var Device_name_id_Cache *sync.Map
  33. var Device_id_name_Cache *sync.Map
  34. var DeviceList_Cache *sync.Map
  35. //公共平台设备服务,提供设备的维护等
  36. type DeviceService struct {
  37. BaseService
  38. DeviceId int
  39. Model DeviceInfo
  40. }
  41. type DeviceInfo struct {
  42. DeviceId int
  43. DeviceName string
  44. PageIndex int
  45. PageSize int
  46. AppId int32
  47. ActionId string
  48. AttrName string
  49. }
  50. type CpInfo struct {
  51. Deviceid int `json:"deviceid"`
  52. Attrname string `json:"attrname"`
  53. Cpname string `json:"cpname"`
  54. Positionname string `json:"positionname"`
  55. State string `json:"state"`
  56. State_value string `json:"state_value"`
  57. Mpname string `json:"mpname"`
  58. }
  59. type ControlCommand struct {
  60. Deviceid int `json:"deviceid"`
  61. AttrName string `json:"attr_name"`
  62. Modelid int `json:"modelid"`
  63. Devicename string `json:"devicename"`
  64. }
  65. //设备列表及状态模型
  66. type DeviceAndStateInfo struct {
  67. Deviceid int `json:"deviceid"`
  68. Devicename string `json:"devicename"`
  69. Area string `json:"area"`
  70. Working string `json:"working"`
  71. }
  72. func init() {
  73. logger.Logger.Println("初始化设备服务")
  74. go func() {
  75. ins := new(DeviceService)
  76. //启动设备离线检查进程
  77. logger.Logger.Println("启动设备离线检查进程")
  78. ins.CheckDeviceState()
  79. }()
  80. go func() {
  81. logger.Logger.Println("启动设备添加回复处理进程")
  82. for {
  83. data, ok := <-datachannel.Service_DeviceAdd_Chanl
  84. logger.Logger.Debug(fmt.Sprintf("=======接收到中台回复的设备添加数据:%+v", data))
  85. if ok {
  86. ins := new(DeviceService)
  87. go ins.HandleAddDevice(data, tools.IsEmpty(data["mid"]))
  88. }
  89. }
  90. }()
  91. go func() {
  92. logger.Logger.Println("启动设备删除回复处理进程")
  93. for {
  94. data, ok := <-datachannel.Service_DeviceDel_Chanl
  95. logger.Logger.Debug(fmt.Sprintf("=======接收到中台回复的设备删除数据:%+v", data))
  96. if ok {
  97. ins := new(DeviceService)
  98. go ins.HandleDelete(data, tools.IsEmpty(data["mid"]))
  99. }
  100. }
  101. }()
  102. }
  103. //查询设备类型列表
  104. func (c *DeviceService) SearchDeviceTypeList() (interface{}, error) {
  105. if v, h := global.GoCahce.Get("SearchDeviceTypeList"); h {
  106. return v.([]orm.Params), nil
  107. }
  108. db := orm.NewOrm()
  109. db.Using("iss")
  110. rowset := []orm.Params{}
  111. sql := "select * from dev_type order by id"
  112. _, err := db.Raw(sql).Values(&rowset)
  113. if err != nil {
  114. logger.Logger.Error(err)
  115. return nil, err
  116. }
  117. global.GoCahce.Set("SearchDeviceTypeList", rowset, -1)
  118. return rowset, err
  119. }
  120. //创建设备信息
  121. func (t *DeviceService) CreateDevice(messageId string, field model.DevDevinfo, MpInfo []model.DevMpinfo, controlInfo []map[string]interface{}) error {
  122. var parameter = make(map[string]interface{})
  123. parameter["token"] = RtelecManageApp().AppToken
  124. parameter["mid"] = messageId
  125. //mqtt消息中的message数据处理
  126. var para = make(map[string]interface{})
  127. if field.Deviceid > 0 {
  128. para["id"] = field.Deviceid
  129. }
  130. utils.MessageIds.Set(messageId, messageId)
  131. para["model_id"] = field.Modelid
  132. para["device_name"] = field.Devicename
  133. para["serial"] = field.Serial
  134. para["baudrate"] = strconv.FormatInt(int64(field.Baudrate), 10)
  135. para["stop_bit"] = strconv.FormatInt(int64(field.Stopbit), 10)
  136. para["check_bit"] = field.Checkbit
  137. para["data_bit"] = strconv.FormatInt(int64(field.Databit), 10)
  138. para["ip"] = field.IP
  139. para["port"] = strconv.FormatInt(int64(field.Port), 10)
  140. para["eid"] = field.Eid
  141. para["client_id"] = RtelecManageApp().RegAppID
  142. para["slave_id"] = strconv.FormatInt(int64(field.Slaveid), 10)
  143. para["mqtt_topic"] = field.Mqtttopic
  144. para["dev_type_id"] = field.DevTypeId
  145. para["region_id"] = field.RegionId
  146. deviceInfoData.Store("dev_"+messageId, field) //设备信息
  147. if len(MpInfo) > 0 {
  148. deviceInfoData.Store("mp_"+messageId, MpInfo) //测点信息
  149. }
  150. if len(controlInfo) > 0 {
  151. deviceInfoData.Store("control_"+messageId, controlInfo) //控制点及动作信息
  152. }
  153. Message, _ := json.Marshal(para)
  154. msg, _ := new(utils.ToolsLogic).EncryptMsg(Message, []byte(conf.GlobalConfig["rtelec_manage_password"]), true)
  155. parameter["message"] = msg
  156. value, _ := json.Marshal(parameter)
  157. mqtt.PublishMessage(global.Rtelec_Topics["device_add"], string(value))
  158. return nil
  159. }
  160. //删除中台上的设备信息
  161. func (t *DeviceService) DeleteDeviceByMqtt(deviceId int) error {
  162. var parameter = make(map[string]interface{})
  163. var mid = fmt.Sprintf("%d_%s", deviceId, tools.GetUid())
  164. parameter["mid"] = mid
  165. parameter["token"] = RtelecManageApp().AppToken
  166. utils.MessageIds.Set(mid, mid)
  167. //mqtt消息中的message数据处理
  168. var para = make(map[string]interface{})
  169. para["id"] = deviceId
  170. Message, _ := json.Marshal(para)
  171. msg, _ := new(utils.ToolsLogic).EncryptMsg(Message, []byte(conf.GlobalConfig["rtelec_manage_password"]), true)
  172. parameter["message"] = msg
  173. value, _ := json.Marshal(parameter)
  174. mqtt.PublishMessage(global.Rtelec_Topics["device_del"], string(value))
  175. return nil
  176. }
  177. //从订阅的mqtt消息中取得deviceid并添加设备、测点、控制点、控制点动作
  178. func (t *DeviceService) HandleAddDevice(data map[string]interface{}, messageId string) {
  179. if message, ok := data["message"]; ok && tools.IsEmpty(message) != "" {
  180. var tempData map[string]interface{}
  181. if reflect.TypeOf(message).Kind() == reflect.String {
  182. bytes := []byte(message.(string))
  183. err := json.Unmarshal(bytes, &tempData)
  184. if err != nil {
  185. logger.Logger.Error(err)
  186. new(utils.MsgStateManage).SetMessageStateObj(messageId, utils.MsgState{Success: false, State: true, Message: tempData["message"].(string)})
  187. return
  188. }
  189. }
  190. if cast.ToInt(tempData["code"]) == 200 {
  191. new(utils.MsgStateManage).SetMessageStateObj(messageId, utils.MsgState{Success: true, State: true, Message: ""})
  192. deviceId := tempData["data"].(map[string]interface{})["id"]
  193. tmpV, _ := deviceInfoData.Load("dev_" + messageId)
  194. field := tmpV.(model.DevDevinfo)
  195. dev_id := strconv.FormatFloat(deviceId.(float64), 'f', 0, 64)
  196. field.Deviceid = cast.ToInt32(dev_id)
  197. logger.Logger.Debug(fmt.Sprintf("===========添加设备到ISS库:%+v", field))
  198. t.EditDevice(field, messageId)
  199. } else {
  200. logger.Logger.Debug(fmt.Sprintf("===========添加设备失败:%s", message.(string)))
  201. new(utils.MsgStateManage).SetMessageStateObj(messageId, utils.MsgState{Success: false, State: false, Message: tools.IsEmpty(tempData["message"])})
  202. }
  203. }
  204. }
  205. func (t *DeviceService) EditDevice(field model.DevDevinfo, mid string) error {
  206. deviceObject := logic.NewDeviceLogic()
  207. var err error
  208. var desc = "添加"
  209. var isAdd = true
  210. exists, online := t.exists_device(field.Deviceid)
  211. if exists {
  212. isAdd = false
  213. desc = "修改"
  214. field.Online = online
  215. field.UpdateAt = time.Now().Local()
  216. err = deviceObject.ModifyDevice(&field)
  217. } else {
  218. field.Online = 1 //添加设备时默认为离线
  219. field.Disable = 1 //默认为启用 1 启用 2禁用
  220. field.CreateAt = time.Now().Local()
  221. field.UpdateAt = time.Now().Local()
  222. err = deviceObject.AddDevice(&field)
  223. }
  224. context, _ := json.Marshal(field)
  225. if err != nil {
  226. new(LogService).SaveLog(fmt.Sprintf("%s设备记录失败!参数值:%s,失败原因:%s", desc, string(context), err.Error()))
  227. } else {
  228. //清除缓存
  229. global.GoCahce.Delete("devicelistall")
  230. global.GoCahce.Delete("GetAllDevice")
  231. //重新加载设备缓存
  232. go t.LoadDefaultDeviceAttr(true)
  233. new(LogService).SaveLog(fmt.Sprintf("%s设备记录成功!参数值:%s", desc, string(context)))
  234. ////编辑测点
  235. tmpV, ok := deviceInfoData.Load("mp_" + mid)
  236. if !ok {
  237. return nil
  238. }
  239. Mp_Field := tmpV.([]model.DevMpinfo)
  240. logger.Logger.Debug(fmt.Sprintf("================编辑测点:%+v", Mp_Field))
  241. t.EditMpInfo(Mp_Field, field.Deviceid, isAdd)
  242. tmpV, ok = deviceInfoData.Load("control_" + mid)
  243. if !ok {
  244. return nil
  245. }
  246. controlInfo := tmpV.([]map[string]interface{})
  247. //添加控制点及控制点动作
  248. t.EditControlInfo(controlInfo, field.Deviceid, isAdd)
  249. }
  250. return err
  251. }
  252. //根据deviceid或mapid删除测点
  253. func (t *DeviceService) DeleteMapByDeviceId(deviceId int32, MpId int64) error {
  254. var mpObject = logic.NewMpInfoLogic()
  255. var sqlCommandText, description = "", ""
  256. mpMap := t.GetMapInfoByDeviceId(deviceId)
  257. mpinfo := mpMap[MpId]
  258. if mpinfo == nil {
  259. return nil
  260. }
  261. description = fmt.Sprintf("MpId:%d deviceid:%d", MpId, deviceId)
  262. sqlCommandText = fmt.Sprintf("delete from dev_mpinfo where mpid=%d and deviceid=%d ", MpId, deviceId)
  263. err := mpObject.SvcCtx.DevMpinfo.Base.Exec(sqlCommandText)
  264. logdesc := fmt.Sprintf("删除设备测点,操作数据:%s", description)
  265. if err == nil {
  266. if MpId > 0 {
  267. //删除测点的历史数据
  268. new(HistoryService).DeleteHistory(deviceId, MpId)
  269. //删除关联测点分组数据
  270. mpMgr := new(MpinfoService)
  271. mpMgr.UserInfo = t.UserInfo
  272. mpMgr.DeleteMp(deviceId, MpId)
  273. //删除关联的测点告警配置
  274. //FIX...
  275. //删除关联的测点优化配置
  276. attrname := tools.IsEmpty(mpinfo["attrname"])
  277. go new(DataoptimizeService).DeleteAttrnameOptimize("invalid", deviceId, attrname)
  278. go new(DataoptimizeService).DeleteAttrnameOptimize("deletion", deviceId, attrname)
  279. //删除关联的控制点配置
  280. //FIX...
  281. }
  282. go new(LogService).SaveLog(fmt.Sprintf("删除测点数据记录成功,删除条件:%s", description))
  283. new(bo.SystemLog).Success(
  284. enum.AuditType_device,
  285. enum.LogType_Delete,
  286. enum.OptEventType_System,
  287. enum.OptEventLevel_Hight,
  288. logdesc,
  289. global.SystemLogDefaultAccount,
  290. )
  291. deviceMpList.Delete(fmt.Sprintf("MpList_%d_0", deviceId)) //清除缓存的测点列表
  292. global.GoCahce.Delete(fmt.Sprintf("MpInfo_%d", deviceId)) //清除以模型属性缓存的测点定义
  293. global.GoCahce.Delete(fmt.Sprintf("MapInfoByDeviceId_%d", deviceId)) //清除以测点id缓存的测点定义
  294. return nil
  295. } else {
  296. logger.Logger.Error(err)
  297. go new(LogService).SaveLog(fmt.Sprintf("删除测点数据记录失败,删除条件:%s", description+err.Error()))
  298. new(bo.SystemLog).Fail(
  299. enum.AuditType_device,
  300. enum.LogType_Delete,
  301. enum.OptEventType_System,
  302. enum.OptEventLevel_Hight,
  303. logdesc,
  304. global.SystemLogDefaultAccount,
  305. )
  306. return err
  307. }
  308. }
  309. //根据deviceid删除控制点及控制点动作数据记录
  310. func (t *DeviceService) DeleteControlByDeviceId(deviceId int32, controlId int64, actionId int64) {
  311. //删除控制点动作
  312. var mpObject = logic.NewMpInfoLogic()
  313. var sqlCommandText = ""
  314. if deviceId > 0 {
  315. sqlCommandText = fmt.Sprintf("delete from dev_cpaction where cpid in (select cpid from dev_cpinfo where deviceid=%d);", deviceId)
  316. } else if controlId > 0 {
  317. sqlCommandText = fmt.Sprintf("delete from dev_cpinfo where cpid=%d;", controlId)
  318. } else if actionId > 0 {
  319. sqlCommandText = fmt.Sprintf("delete from dev_cpaction where actid=%d;", actionId)
  320. }
  321. var err = mpObject.SvcCtx.AlarmStrategy.Base.Exec(sqlCommandText)
  322. if err == nil {
  323. sqlCommandText = ""
  324. if deviceId > 0 {
  325. sqlCommandText = fmt.Sprintf("delete from dev_cpinfo where deviceid=%d;", deviceId)
  326. } else if controlId > 0 {
  327. sqlCommandText = fmt.Sprintf("delete from dev_cpaction where cpid=%d;", controlId)
  328. }
  329. if sqlCommandText != "" {
  330. err = mpObject.SvcCtx.AlarmStrategy.Base.Exec(sqlCommandText)
  331. }
  332. }
  333. }
  334. func (t *DeviceService) exists_device(deviceId int32) (bool, int32) {
  335. l := logic.NewDeviceLogic()
  336. var online int32 = 0
  337. type ExistsDevice struct {
  338. Deviceid int32 `json:"deviceid"`
  339. Online int32 `json:"online"`
  340. }
  341. var list []ExistsDevice
  342. sqlCommandText := fmt.Sprintf("select deviceid,online from dev_devinfo where appid=%s and deviceid=%d ", RtelecManageApp().RegAppID, deviceId)
  343. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  344. var exists bool
  345. if err == nil {
  346. if len(list) == 0 {
  347. exists = false
  348. } else {
  349. online = list[0].Online
  350. exists = true
  351. }
  352. } else {
  353. logger.Logger.Error(err)
  354. }
  355. return exists, online
  356. }
  357. //编辑测点数据记录
  358. func (t *DeviceService) EditMpInfo(mpData []model.DevMpinfo, DeviceId int32, isAdd bool) error {
  359. if len(mpData) == 0 {
  360. if !isAdd { //如果修改的时候测点为空则删除原来的测点
  361. t.DeleteMapByDeviceId(DeviceId, 0)
  362. }
  363. } else {
  364. mpinfoObject := logic.NewMpInfoLogic()
  365. var oldMpid = make(map[int64]int64)
  366. if !isAdd { //如果为修改时获取原来的测点id
  367. mpinfo := t.GetMapInfoByDeviceId(DeviceId)
  368. for mpid, _ := range mpinfo {
  369. mpid := cast.ToInt64(mpid)
  370. oldMpid[mpid] = mpid
  371. }
  372. }
  373. var err error
  374. var mpid int64 = 0
  375. appid := cast.ToInt(RtelecManageApp().RegAppID)
  376. logger.Logger.Debug(fmt.Sprintf("============%+v保存测点=================:%+v", isAdd, mpData))
  377. for _, Record := range mpData {
  378. Record.Deviceid = DeviceId
  379. mpid = Record.Mpid
  380. if mpid == 0 {
  381. //判断模型属性是否已绑定测点
  382. hasMp := t.DeviceMpInfo(DeviceId)
  383. if hasMp[Record.Attrname] != nil {
  384. tmpObj := hasMp[Record.Attrname]
  385. return errors.New(fmt.Sprintf("模型属性名%s已关联到测点%s", Record.Attrname, tmpObj["mpname"]))
  386. }
  387. Record.Mpid = new(utils.ToolsLogic).GetOnlyId(int64(appid))
  388. err = mpinfoObject.AddMpInfo(&Record)
  389. } else {
  390. if _, ok := oldMpid[Record.Mpid]; ok {
  391. oldMpid[mpid] = 0 //不删除的记录
  392. }
  393. err = mpinfoObject.ModifyMpInfo(&Record)
  394. }
  395. if err != nil {
  396. logger.Logger.Println(fmt.Sprintf("设备测点编辑:%+v", Record))
  397. logger.Logger.Error(fmt.Sprintf("设备测点编辑错误:%+v", err))
  398. return err
  399. }
  400. }
  401. deviceMpList.Delete(fmt.Sprintf("MpList_%d_0", DeviceId)) //清除缓存的测点列表
  402. global.GoCahce.Delete(fmt.Sprintf("MpInfo_%d", DeviceId)) //清除以模型属性缓存的测点定义
  403. global.GoCahce.Delete(fmt.Sprintf("MapInfoByDeviceId_%d", DeviceId)) //清除以测点id缓存的测点定义
  404. if !isAdd && len(oldMpid) > 0 {
  405. for _, val := range oldMpid {
  406. if val > 0 {
  407. t.DeleteMapByDeviceId(0, val)
  408. }
  409. }
  410. }
  411. }
  412. return nil
  413. }
  414. //编辑控制点及控制动作数据记录
  415. func (t *DeviceService) EditControlInfo(data []map[string]interface{}, DeviceId int32, isAddRecord bool) {
  416. if len(data) == 0 {
  417. if !isAddRecord { //如果修改的时候控制点为空则删除控制点及控制动作
  418. t.DeleteControlByDeviceId(DeviceId, 0, 0)
  419. }
  420. } else {
  421. var control = make(map[int64]int64)
  422. var control_action = make(map[int64]int64)
  423. if !isAddRecord {
  424. control, control_action = t.GetControlByDeviceId(DeviceId)
  425. }
  426. appid := cast.ToInt(RtelecManageApp().RegAppID)
  427. for _, row := range data {
  428. var isAdd = false
  429. var ControlField = row["control"].(model.CpMpinfo)
  430. CpInfoObject := logic.NewCpInfoLogic()
  431. if ControlField.Cpid == 0 {
  432. isAdd = true
  433. ControlField.Cpid = new(utils.ToolsLogic).GetOnlyId(int64(appid))
  434. } else {
  435. if _, ok := control[ControlField.Cpid]; ok {
  436. control[ControlField.Cpid] = 0
  437. }
  438. }
  439. ControlField.Deviceid = DeviceId
  440. if isAdd {
  441. CpInfoObject.AddCpInfo(&ControlField)
  442. } else {
  443. CpInfoObject.ModifyCpInfo(&ControlField)
  444. }
  445. var ActionData = row["action"].([]model.DevCpaction)
  446. if len(ActionData) > 0 {
  447. ActionObject := logic.NewActInfoLogic()
  448. for _, actionRow := range ActionData {
  449. actionRow.Cpid = ControlField.Cpid
  450. isAdd = false
  451. if actionRow.Actid == 0 {
  452. isAdd = true
  453. actionRow.Actid = new(utils.ToolsLogic).GetOnlyId(int64(appid))
  454. } else {
  455. if _, ok := control_action[actionRow.Actid]; ok {
  456. control_action[actionRow.Actid] = 0
  457. }
  458. }
  459. if isAdd {
  460. ActionObject.AddActInfo(&actionRow)
  461. } else {
  462. ActionObject.ModifyActInfo(&actionRow)
  463. }
  464. }
  465. }
  466. }
  467. if !isAddRecord && len(control) > 0 {
  468. for _, val := range control {
  469. if val > 0 {
  470. fmt.Println("===delete control==", val)
  471. t.DeleteControlByDeviceId(0, val, 0)
  472. }
  473. }
  474. }
  475. if !isAddRecord && len(control_action) > 0 {
  476. for _, val := range control_action {
  477. if val > 0 {
  478. fmt.Println("===delete control_action==", val)
  479. t.DeleteControlByDeviceId(0, 0, val)
  480. }
  481. }
  482. }
  483. }
  484. }
  485. //根据DeviceId获取原来的测试id
  486. func (t *DeviceService) GetControlByDeviceId(deviceId int32) (map[int64]int64, map[int64]int64) {
  487. l := logic.NewCpInfoLogic()
  488. type ActionInfo struct {
  489. Cpid int64 `json:"cpid"`
  490. Actid int64 `json:"actid"`
  491. }
  492. var list []ActionInfo
  493. var sqlCommandText = fmt.Sprintf("select b.actid ,a.cpid from dev_cpinfo a inner join dev_cpaction b on a.cpid=b.cpid where a.deviceid=%d ", deviceId)
  494. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  495. var Control = make(map[int64]int64)
  496. var controls = []int64{}
  497. var controlAction = make(map[int64]int64)
  498. var cpid int64 = 0
  499. if err == nil && len(list) > 0 {
  500. for _, record := range list {
  501. cpid = record.Cpid
  502. controlAction[record.Actid] = record.Actid
  503. if arrays.Contains(controls, cpid) == -1 {
  504. Control[cpid] = cpid
  505. controls = append(controls, cpid)
  506. }
  507. }
  508. } else {
  509. logger.Logger.Error(err)
  510. }
  511. return Control, controlAction
  512. }
  513. //删除设备数据记录
  514. func (t *DeviceService) HandleDelete(data map[string]interface{}, messageId string) {
  515. if message, ok := data["message"]; ok && tools.IsEmpty(message) != "" {
  516. var tempData map[string]interface{}
  517. if reflect.TypeOf(message).Kind() == reflect.String {
  518. bytes := []byte(message.(string))
  519. err := json.Unmarshal(bytes, &tempData)
  520. if err == nil {
  521. if cast.ToInt(tempData["code"]) == 200 {
  522. //同时删除本地数据数据记录
  523. id := strings.Split(messageId, "_")
  524. if len(id) > 1 {
  525. deviceId := cast.ToInt32(id[0])
  526. l := logic.NewDeviceLogic()
  527. err := l.DelDevice(deviceId)
  528. if err != nil {
  529. logger.Logger.Error(err)
  530. }
  531. logdesc := fmt.Sprintf("删除设备记录(deviceId=%d)", deviceId)
  532. if err == nil {
  533. //清除缓存
  534. global.GoCahce.Delete("devicelistall")
  535. global.GoCahce.Delete("GetAllDevice")
  536. deviceMpList.Delete(fmt.Sprintf("MpList_%d_0", deviceId)) //清除缓存的测点列表
  537. global.GoCahce.Delete(fmt.Sprintf("MpInfo_%d", deviceId)) //清除以模型属性缓存的测点定义
  538. global.GoCahce.Delete(fmt.Sprintf("MapInfoByDeviceId_%d", deviceId)) //清除以测点id缓存的测点定义
  539. //重新获取数据
  540. go t.GetComboxList()
  541. //清除监测数据记录
  542. go new(HistoryService).DeleteHistory(deviceId, 0)
  543. go new(DataoptimizeService).DeleteOptimize("deletion", deviceId)
  544. go new(DataoptimizeService).DeleteOptimize("invaild", deviceId)
  545. //删除告警配置
  546. //FIX:....
  547. //删除告警记录
  548. //FIX:....
  549. new(LogService).SaveLog(logdesc)
  550. new(bo.SystemLog).Success(
  551. enum.AuditType_device,
  552. enum.LogType_Delete,
  553. enum.OptEventType_System,
  554. enum.OptEventLevel_Hight,
  555. logdesc,
  556. global.SystemLogDefaultAccount,
  557. )
  558. } else {
  559. new(LogService).SaveLog(fmt.Sprintf("删除设备记录失败(deviceId=%v)", deviceId))
  560. new(bo.SystemLog).Fail(
  561. enum.AuditType_device,
  562. enum.LogType_Delete,
  563. enum.OptEventType_System,
  564. enum.OptEventLevel_Hight,
  565. logdesc,
  566. global.SystemLogDefaultAccount,
  567. )
  568. }
  569. }
  570. }
  571. }
  572. }
  573. }
  574. }
  575. // 默认加载设备名称与设备ID对应关系
  576. func (t *DeviceService) LoadDefaultDeviceAttr(refresh bool) *sync.Map {
  577. if refresh || Device_name_id_Cache == nil {
  578. var list = []orm.Params{}
  579. var sqlCommandText = "select * from dev_devinfo where appid=? "
  580. db := orm.NewOrm()
  581. db.Using("iss")
  582. _, err := db.Raw(sqlCommandText, RtelecManageApp().RegAppID).Values(&list)
  583. if err == nil {
  584. Device_name_id_Cache = new(sync.Map)
  585. Device_id_name_Cache = new(sync.Map)
  586. for _, record := range list {
  587. Device_name_id_Cache.Store(tools.IsEmpty(record["devicename"]), tools.IsEmpty(record["deviceid"]))
  588. Device_id_name_Cache.Store(tools.IsEmpty(record["deviceid"]), tools.IsEmpty(record["devicename"]))
  589. }
  590. } else {
  591. logger.Logger.Error(err)
  592. logger.Logger.Println(fmt.Sprintf("Error SQL:%s Paramers:%s", sqlCommandText, RtelecManageApp().RegAppID))
  593. }
  594. }
  595. return Device_name_id_Cache
  596. }
  597. //设备名称与设备id对应关系
  598. func (t *DeviceService) DeviceNameByID() *sync.Map {
  599. if Device_id_name_Cache == nil {
  600. t.LoadDefaultDeviceAttr(true)
  601. }
  602. return Device_id_name_Cache
  603. }
  604. //设备名称与设备id对应关系
  605. func (t *DeviceService) DeviceIdByDeviceName() *sync.Map {
  606. if Device_name_id_Cache == nil {
  607. t.LoadDefaultDeviceAttr(true)
  608. }
  609. return Device_name_id_Cache
  610. }
  611. //设备在线状态 1离线/2 在线 /3 超时,持续超时次数5次则离线
  612. func (t *DeviceService) SetDeviceState(deviceId int, state int) error {
  613. db := orm.NewOrm()
  614. db.Using("iss")
  615. var sqlCommandText = "update dev_devinfo set online=? where deviceid=?"
  616. _, err := db.Raw(sqlCommandText, state, deviceId).Exec()
  617. if err != nil {
  618. logger.Logger.Error(err)
  619. logger.Logger.Println(fmt.Sprintf("Error SQL:%s Paramers:%d,%s", sqlCommandText, state, deviceId))
  620. }
  621. return err
  622. }
  623. //查询设备记录信息
  624. func (c *DeviceService) SearchDeviceList(params map[string]interface{}) (interface{}, int, error) {
  625. db := orm.NewOrm()
  626. db.Using("iss")
  627. sql := "select * from dev_devinfo where appid=? "
  628. sqlParamters := []interface{}{
  629. RtelecManageApp().RegAppID,
  630. }
  631. pno := cast.ToInt(params["PageIndex"])
  632. psize := cast.ToInt(params["PageSize"])
  633. sqlLimit := fmt.Sprintf(" limit %d,%d", (pno-1)*psize, psize)
  634. if v, h := params["DeviceName"]; h {
  635. v2 := v.(string)
  636. if v2 != "" {
  637. sql += " and devicename like ?"
  638. sqlParamters = append(sqlParamters, "%"+v.(string)+"%")
  639. }
  640. }
  641. if v, h := params["Regionid"]; h {
  642. v2 := cast.ToInt(v)
  643. if v2 > 0 {
  644. sql += " and region_id=?"
  645. sqlParamters = append(sqlParamters, v2)
  646. }
  647. }
  648. if v, h := params["Typeid"]; h {
  649. v2 := cast.ToInt(v)
  650. if v2 > 0 {
  651. sql += " and dev_type_id=?"
  652. sqlParamters = append(sqlParamters, v2)
  653. }
  654. }
  655. if v, h := params["Modelid"]; h {
  656. v2 := cast.ToInt(v)
  657. if v2 > 0 {
  658. sql += " and modelid=?"
  659. sqlParamters = append(sqlParamters, v2)
  660. }
  661. }
  662. list := []orm.Params{}
  663. _, err := db.Raw(sql+" order by id desc "+sqlLimit, sqlParamters).Values(&list)
  664. if err != nil {
  665. logger.Logger.Error(err, fmt.Sprintf("SQL:%s 参数:%+v", sql+sqlLimit, sqlParamters))
  666. return nil, 0, err
  667. }
  668. //获取总数
  669. totalSql := strings.Replace(sql, "*", "count(1) cnt", 1)
  670. totalRowset := []orm.Params{}
  671. _, err = db.Raw(totalSql, sqlParamters).Values(&totalRowset)
  672. if err != nil {
  673. logger.Logger.Error(err, fmt.Sprintf("SQL:%s 参数:%+v", totalSql, sqlParamters))
  674. return nil, 0, err
  675. }
  676. if len(totalRowset) == 0 {
  677. return list, 0, err
  678. }
  679. cnt := cast.ToInt(totalRowset[0]["cnt"])
  680. return list, cnt, err
  681. }
  682. //查询设备记录信息(包含设备信息、测点信息、控制点信息)
  683. func (c *DeviceService) DeviceDetail() (map[string]interface{}, error) {
  684. var result = map[string]interface{}{"device": model.DevDevinfo{}, "measure": []interface{}{}, "control": []interface{}{}}
  685. deviceObject := logic.NewDeviceLogic()
  686. var list model.DevDevinfo
  687. //设备基本信息
  688. var sqlCommandText = fmt.Sprintf("select * from dev_devinfo where deviceid=%d and appid=%s", c.DeviceId, RtelecManageApp().RegAppID)
  689. err := deviceObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  690. if err == nil {
  691. result["device"] = list
  692. }
  693. measureObject := logic.NewMpInfoLogic()
  694. var devMpList []model.DevMpinfo
  695. //设备测点信息
  696. sqlCommandText = fmt.Sprintf("select * from dev_mpinfo where deviceid=%d and appid=%s", c.DeviceId, RtelecManageApp().RegAppID)
  697. err = measureObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &devMpList)
  698. if err == nil {
  699. result["measure"] = devMpList
  700. }
  701. controlObject := logic.NewCpInfoLogic()
  702. type DevCpinfo struct {
  703. ID int32 `json:"id"`
  704. Cpid int64 `json:"cpid,string"`
  705. Cpname string `json:"cpname"`
  706. Zonename string `json:"zonename"`
  707. Positionname string `json:"positionname"`
  708. Appid int32 `json:"appid"`
  709. Modelid int32 `json:"modelid"`
  710. Deviceid int32 `json:"deviceid"`
  711. Attrname string `json:"attrname"`
  712. Mpid int64 `json:"mpid,string"`
  713. Mpname string `json:"mpname,string"`
  714. Action interface{} `json:"action"`
  715. }
  716. var controlList []DevCpinfo
  717. sqlCommandText = fmt.Sprintf("select c.*,null action ,m.attrname mattrname,m.mpname from dev_cpinfo c left JOIN dev_mpinfo m on m.mpid=c.mpid where c.deviceid=%d and c.appid=%s", c.DeviceId, RtelecManageApp().RegAppID)
  718. err = controlObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &controlList)
  719. if err == nil {
  720. for index, record := range controlList {
  721. list, err2 := c.devCpactionInfo(record.Cpid)
  722. if err2 == nil {
  723. controlList[index].Action = list
  724. }
  725. }
  726. result["control"] = controlList
  727. }
  728. return result, err
  729. }
  730. //控制动作详情
  731. func (c *DeviceService) devCpactionInfo(controlId int64) ([]model.DevCpaction, error) {
  732. var ActionList []model.DevCpaction
  733. var sqlCommandText = fmt.Sprintf("select * from dev_cpaction where cpid=%d", controlId)
  734. controlObject := logic.NewCpInfoLogic()
  735. err := controlObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &ActionList)
  736. return ActionList, err
  737. }
  738. //设备统计信息
  739. func (c *DeviceService) DeviceStatistics() (map[string]interface{}, error) {
  740. var AppId = cast.ToInt(RtelecManageApp().RegAppID)
  741. var result = make(map[string]interface{})
  742. mpObject := logic.NewMpInfoLogic()
  743. //照明灯具统计
  744. type mpTotal struct {
  745. Recordcount int `json:"recordcount"`
  746. }
  747. var total mpTotal
  748. var sqlCommandText = fmt.Sprintf("select count(1) recordcount from dev_devinfo a inner join dev_mpinfo b on a.deviceid=b.deviceid where a.appid=%d;", AppId)
  749. err := mpObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &total)
  750. if err == nil {
  751. result["bulb"] = total.Recordcount
  752. }
  753. //控制器统计
  754. controlObject := logic.NewCpInfoLogic()
  755. sqlCommandText = fmt.Sprintf("select count(1) recordcount from dev_devinfo a inner join dev_cpinfo b on a.deviceid=b.deviceid where a.appid=%d;", AppId)
  756. err = controlObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &total)
  757. if err == nil {
  758. result["controller"] = total.Recordcount
  759. }
  760. //已开启照明灯具(该处未处理)
  761. result["light"] = c.online(AppId)
  762. //故障设备数量
  763. result["fault"] = 0
  764. sqlCommandText = fmt.Sprintf("select count(1) recordcount from dev_devinfo a inner join dev_mpinfo b on a.deviceid=b.deviceid where a.online!=2 and a.appid=%d;", AppId)
  765. err = mpObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &total)
  766. if err == nil {
  767. result["fault"] = total.Recordcount
  768. }
  769. return result, err
  770. }
  771. //根据DeviceId获取设备测点定义。以map结构返回,其中Key为测点ID
  772. func (c *DeviceService) GetMapInfoByDeviceId(deviceId int32) map[int64]orm.Params {
  773. var Result = make(map[int64]orm.Params)
  774. cachekey := fmt.Sprintf("MapInfoByDeviceId_%d", deviceId)
  775. if v, h := global.GoCahce.Get(cachekey); h {
  776. return v.(map[int64]orm.Params)
  777. }
  778. list, _, err := c.DeviceMpList(deviceId, 1, 10000)
  779. if err == nil && len(list) > 0 {
  780. for _, record := range list {
  781. mpid, _ := strconv.ParseInt(tools.IsEmpty(record["mpid"]), 10, 64)
  782. Result[mpid] = record
  783. }
  784. global.GoCahce.Set(cachekey, Result, -1)
  785. }
  786. return Result
  787. }
  788. func (c *DeviceService) online(AppId int) int {
  789. var result = 0
  790. controlObject := logic.NewCpInfoLogic()
  791. type DeviceService struct {
  792. Deviceid int `json:"deviceid"`
  793. Attrname string `json:"attrname"`
  794. }
  795. var info []DeviceService
  796. var sqlCommandText = fmt.Sprintf("select b.deviceid,attrname from dev_devinfo a inner join dev_cpinfo b on a.deviceid=b.deviceid where a.appid=%d", AppId)
  797. err := controlObject.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &info)
  798. if err == nil {
  799. db := orm.NewOrm()
  800. for _, record := range info {
  801. sqlCommandText = "select val from dev_history where attrname=? and deviceid=? order by id desc limit 1"
  802. var sqlParameter = []interface{}{record.Attrname, record.Deviceid}
  803. var table []orm.Params
  804. _, err := db.Raw(sqlCommandText, sqlParameter).Values(&table)
  805. if err == nil && len(table) > 0 {
  806. var value = tools.IsEmpty(table[0]["val"])
  807. if value == "1" {
  808. result += 1
  809. }
  810. }
  811. }
  812. }
  813. return result
  814. }
  815. //获取设备控制点
  816. func (c *DeviceService) GetDeviceControlId() (interface{}, error) {
  817. l := logic.NewCpInfoLogic()
  818. type Result struct {
  819. Id int64 `json:"id,string"`
  820. Name string `json:"name"`
  821. }
  822. var list []Result
  823. var sqlCommandText = fmt.Sprintf("select actid id,concat(devicename,'/',cpname,'/',actdesc) name from dev_cpinfo a inner join dev_cpaction b on a.cpid=b.cpid inner join dev_devinfo c on a.deviceid=c.deviceid where a.appid=%s;", RtelecManageApp().RegAppID)
  824. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  825. return list, err
  826. }
  827. //获取设备测点id
  828. func (c *DeviceService) GetDeviceMpId() (interface{}, error) {
  829. l := logic.NewCpInfoLogic()
  830. type Result struct {
  831. Id int64 `json:"id,string"`
  832. Name string `json:"name"`
  833. }
  834. var list []Result
  835. var sqlCommandText = fmt.Sprintf("select mpid id,concat(devicename,' / ',mpname) name from dev_mpinfo a inner join dev_devinfo b on a.deviceid=b.deviceid where a.appid=%s;", RtelecManageApp().RegAppID)
  836. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  837. return list, err
  838. }
  839. //根据设备id返回对应的modelid
  840. func (c *DeviceService) GetModelIdByDeviceId(deviceid int) (interface{}, error) {
  841. l := logic.NewDeviceLogic()
  842. var sqlCommandText = fmt.Sprintf("select modelid from dev_devinfo where deviceid=%d", deviceid)
  843. type modeidstruct struct {
  844. Modelid int
  845. }
  846. var list modeidstruct
  847. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  848. return list, err
  849. }
  850. //获取区域名称
  851. func (c *DeviceService) GetAreaName() (interface{}, error) {
  852. l := logic.NewCpInfoLogic()
  853. type Result struct {
  854. Id string `json:"id"`
  855. Name string `json:"name"`
  856. }
  857. var list []Result
  858. var sqlCommandText = fmt.Sprintf("select distinct zonename id,zonename name from dev_cpinfo where appid=%s;", RtelecManageApp().RegAppID)
  859. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  860. return list, err
  861. }
  862. //获取所有设备的信息。返回设备详情信息
  863. func (c *DeviceService) GetAllDevice() ([]orm.Params, error) {
  864. if lst, has := global.GoCahce.Get("GetAllDevice"); has {
  865. return lst.([]orm.Params), nil
  866. }
  867. var appId = RtelecManageApp().RegAppID
  868. l := orm.NewOrm()
  869. l.Using("iss")
  870. list := []orm.Params{}
  871. var sqlCommandText = "select a.*,null children,0 mpid from dev_devinfo a where a.appid=?"
  872. _, err := l.Raw(sqlCommandText, appId).Values(&list)
  873. if err == nil {
  874. global.GoCahce.Set("GetAllDevice", list, -1)
  875. return list, nil
  876. } else {
  877. logger.Logger.Error(err, fmt.Sprintf("SQL:%s 参数:%s", sqlCommandText, appId))
  878. }
  879. return nil, err
  880. }
  881. //获取场景对应的modelid
  882. func (c *DeviceService) GetModelIdBySceneName(scenename string) string {
  883. //2022-11-08增加场景分类对应的modelid获取,根据modelid再去获取场景中的设备
  884. //---start---
  885. var params = map[string]string{}
  886. var modelidParam = ""
  887. params["scenename"] = scenename
  888. var sceneinfo = new(SceneService)
  889. modelids, modeliderr := sceneinfo.QueryScene(params)
  890. if modeliderr != nil {
  891. tools.Log(modeliderr.Error())
  892. }
  893. if len(modelids) > 0 {
  894. modelidParam = "("
  895. for _, v := range modelids {
  896. modelidParam += v["modelid"].(string) + ","
  897. }
  898. modelidParam = modelidParam[:len(modelidParam)-1] + ")"
  899. }
  900. return modelidParam
  901. //---end-----
  902. }
  903. //首页设备控制列表
  904. func (c *DeviceService) HomeDeviceList(area string, scenename string) (interface{}, error) {
  905. var AppId = cast.ToInt(RtelecManageApp().RegAppID)
  906. modelidParam := c.GetModelIdBySceneName(scenename)
  907. l := logic.NewDeviceLogic()
  908. type Result struct {
  909. Deviceid int `json:"deviced"`
  910. Devicename string `json:"devicename"`
  911. Online string `json:"online"`
  912. ControlInfo interface{} `json:"control_info"`
  913. MpValues interface{} `json:"mp_value"`
  914. }
  915. var list []Result
  916. var sqlCommandText = []string{}
  917. if area == "" {
  918. sqlCommandText = append(sqlCommandText, "select deviceid,devicename,modelid,online,null control_info,null mp_value from dev_devinfo where 1=1")
  919. if scenename != "" && modelidParam != "" {
  920. sqlCommandText = append(sqlCommandText, fmt.Sprintf(" and modelid in %s", modelidParam))
  921. }
  922. sqlCommandText = append(sqlCommandText, fmt.Sprintf(" and appid=%d;", AppId))
  923. } else {
  924. sqlCommandText = append(sqlCommandText, fmt.Sprintf("select deviceid,devicename,modelid,online,null control_info,null mp_value from dev_devinfo a where exists (select 1 from dev_cpinfo b where b.zonename='%s' and b.deviceid=a.deviceid and b.appid=%d) and appid=%d ", area, AppId, AppId))
  925. if scenename != "" && modelidParam != "" {
  926. sqlCommandText = append(sqlCommandText, fmt.Sprintf("and modelid in %s", modelidParam))
  927. }
  928. }
  929. err := l.SvcCtx.AlarmStrategy.Base.Raw(strings.Join(sqlCommandText, ""), &list)
  930. //获取设备最新的测点采集值
  931. if err == nil {
  932. var wg = sync.WaitGroup{}
  933. wg.Add(len(list))
  934. for index, record := range list {
  935. go func(ind int, rec Result) {
  936. dbo := orm.NewOrm()
  937. rowset := []orm.Params{}
  938. dt := time.Now().Local().Format("2006-01-02 15")
  939. //如果设置了当前模型指定测点的值转换参数,则判断当前值是否匹配设置时,如果相等,则将返回1(表示告警),否则返回测点原值
  940. _, err := dbo.Raw("select t1.mpname,t1.attrname,case when t1.val=(select param_value from global_sys_param where param_name=concat(?,'_',t1.attrname,'_matchvalue')) then 'Y' else t1.val end val,t1.date from dev_history t1 ,(select max(t.id) id from dev_history t where t.deviceid=? and t.`date` BETWEEN ? and ? GROUP BY t.attrname limit 0,256) t2 where t1.id=t2.id", scenename, rec.Deviceid, dt+":00:00", dt+":59:59").Values(&rowset)
  941. if err != nil {
  942. logger.Logger.Error(err)
  943. } else {
  944. list[ind].MpValues = rowset
  945. }
  946. wg.Done()
  947. }(index, record)
  948. }
  949. wg.Wait()
  950. }
  951. //2022-11-08增加判断:开关属性是否是2个控制点.如果是2个控制点对应1个采集点,则需要为前端组装“采集点”->“动作点”的数据。
  952. //如果是1个控制点本身又是采集点,则组要为前端组装“控制点”->“动作点”的数据
  953. //http方式为1个控制点本身又是采集点
  954. /*
  955. if scenename == "door" {
  956. if configure.AppConfigure.DoorWay == "http" {
  957. if err == nil {
  958. for index, record := range list {
  959. ControlInfo, mperror := getControlInfo(record.Deviceid, AppId)
  960. if mperror == nil {
  961. list[index].ControlInfo = ControlInfo
  962. }
  963. }
  964. }
  965. } else {
  966. if err == nil {
  967. for index, record := range list {
  968. //大点表的方式获取组装数据“采集点”->“动作点”
  969. ControlInfo, mperror := getControlInfo2(record.Deviceid, AppId)
  970. if mperror == nil {
  971. list[index].ControlInfo = ControlInfo
  972. }
  973. }
  974. }
  975. }
  976. return list, err
  977. }
  978. */
  979. if err == nil {
  980. for index, record := range list {
  981. //大点表的方式获取组装数据“采集点”->“动作点”
  982. ControlInfo, mperror := c.getControlInfo2(record.Deviceid, AppId)
  983. if mperror == nil {
  984. list[index].ControlInfo = ControlInfo
  985. }
  986. }
  987. }
  988. return list, err
  989. }
  990. func (c *DeviceService) getControlInfo(deviceId int, AppId int) ([]CpInfo, error) {
  991. l := logic.NewCpInfoLogic()
  992. var data []CpInfo
  993. var sqlCommandText = fmt.Sprintf("select deviceid,attrname,cpname,positionname,null state,0 state_val from dev_cpinfo where deviceid=%d and appid=%d;", deviceId, AppId)
  994. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &data)
  995. if err == nil {
  996. for index, record := range data {
  997. info := c.GetDeviceState(record.Deviceid, record.Attrname)
  998. data[index].State = info.State
  999. data[index].State_value = info.State_vale
  1000. }
  1001. } else {
  1002. logger.Logger.Error(err)
  1003. logger.Logger.Println(fmt.Sprintf("Error SQL:%s 参数:%d,%d", sqlCommandText, deviceId, AppId))
  1004. }
  1005. return data, err
  1006. }
  1007. type Res struct {
  1008. Deviceid int `json:"deviceid"`
  1009. Attrname string `json:"attrname"`
  1010. Mpid int64 `json:"mpid"`
  1011. Mpname string `json:"cpname"`
  1012. Positionname string `json:"positionname"`
  1013. State string `json:"state"`
  1014. Actions interface{} `json:"actions"`
  1015. }
  1016. //控制点和采集点分开的方式获取控制数据
  1017. func (c *DeviceService) getControlInfo2(deviceId int, AppId int) (interface{}, error) {
  1018. l := logic.NewCpInfoLogic()
  1019. var data []Res
  1020. var sqlCommandText = fmt.Sprintf("SELECT DISTINCT c.mpid,c.deviceid,m.attrname,m.mpname,m.positionname FROM dev_cpinfo c LEFT JOIN dev_mpinfo m on m.mpid=c.mpid and m.deviceid=%d where c.appid=%d and c.deviceid=%d", deviceId, AppId, deviceId)
  1021. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &data)
  1022. if err == nil {
  1023. for index, record := range data {
  1024. //采用通过网关去控制硬件的方式(大点表方式)
  1025. //这里需要去获取这个采集点的状态,从历史数据表中获取
  1026. //因为这里是根据采集点去获取的历史状态,那么控制那边下了命令以后获取采集点状态回写历史表的时候就需要回写attrname是采集点的attrname
  1027. info := c.GetDeviceState(record.Deviceid, record.Attrname)
  1028. data[index].State = info.State_vale
  1029. //获取采集点下属的动作
  1030. acts := c.GetActions(AppId, record.Deviceid, record.Mpid, true)
  1031. data[index].Actions = acts
  1032. }
  1033. }
  1034. return data, err
  1035. }
  1036. type deviceState struct {
  1037. State string `json:"state"`
  1038. State_vale string `json:"state_vale"`
  1039. }
  1040. //获取每一个控制点的状态
  1041. func (c *DeviceService) GetDeviceState(deviceId int, attrName string) deviceState {
  1042. var state deviceState
  1043. state.State_vale = "0"
  1044. o := orm.NewOrm()
  1045. var sqlCommandText = "select val from dev_history where attrname=? and deviceid=? order by id desc limit 1;"
  1046. var sqlParameter = []interface{}{attrName, deviceId}
  1047. table := []orm.Params{}
  1048. _, err := o.Raw(sqlCommandText, sqlParameter).Values(&table)
  1049. if err == nil && len(table) > 0 {
  1050. val := table[0]["val"].(string)
  1051. if val == "1" {
  1052. state.State_vale = val
  1053. }
  1054. }
  1055. return state
  1056. }
  1057. type ActionsInfo struct {
  1058. Deviceid int `json:"deviceid"` //设备id
  1059. Devicename string `json:"devicename"` //设备名称
  1060. Cpattrname string `json:"cpattrname"` //控制点属性名
  1061. Mpattrname string `json:"mpattrname"` //采集点属性名
  1062. Actdesc string `json:"actdesc"` //动作点名称
  1063. Value float64 `json:"value"` //动作点的值
  1064. }
  1065. //根据doorway参数来判断是否是modbus方式下获取采集点下面的动作点,还是其他方式下获取控制点下面的动作点
  1066. // bool==true:采用大点表方式,控制点和采集点分开
  1067. func (c *DeviceService) GetActions(AppId int, deviceId int, mpid int64, doorway bool) []ActionsInfo {
  1068. l := logic.NewCpInfoLogic()
  1069. var actSql = fmt.Sprintf("SELECT i.deviceid,c.cpid,c.mpid,c.cpname,c.attrname cpattrname,a.actdesc,a.`value`,i.devicename FROM dev_cpinfo c INNER JOIN dev_cpaction a ON c.cpid = a.cpid INNER JOIN dev_devinfo i ON i.deviceid = c.deviceid WHERE c.appid =%d AND c.deviceid =%d and c.cpid=%d", AppId, deviceId, mpid)
  1070. if doorway {
  1071. actSql = fmt.Sprintf("SELECT i.deviceid,c.cpid,c.mpid,m.mpname,m.attrname mpattrname,a.actdesc,a.`value`,i.devicename,c.attrname cpattrname FROM dev_cpinfo c INNER JOIN dev_cpaction a ON c.cpid = a.cpid INNER JOIN dev_devinfo i ON i.deviceid = c.deviceid LEFT JOIN dev_mpinfo m ON m.mpid = c.mpid WHERE c.appid =%d AND c.deviceid = %d AND c.mpid = %d", AppId, deviceId, mpid)
  1072. }
  1073. var acts []ActionsInfo
  1074. err := l.SvcCtx.AlarmStrategy.Base.Raw(actSql, &acts)
  1075. if err != nil {
  1076. tools.Log("获取动作点报错:" + err.Error())
  1077. return nil
  1078. }
  1079. return acts
  1080. }
  1081. //获取指令发送时需要的参数
  1082. //返回数据为:devicename,modelid
  1083. func (c *DeviceService) GetCommandRestart() ([]orm.Params, error) {
  1084. AppId := RtelecManageApp().RegAppID
  1085. var list = []orm.Params{}
  1086. var sqlCommandText = "select devicename,modelid from dev_devinfo where deviceid=? and appid=?"
  1087. db := orm.NewOrm()
  1088. db.Using("iss")
  1089. _, err := db.Raw(sqlCommandText, c.DeviceId, AppId).Values(&list)
  1090. if err != nil {
  1091. logger.Logger.Error(err)
  1092. }
  1093. return list, err
  1094. }
  1095. //获取指令发送时需要的参数
  1096. func (c *DeviceService) GetCommandParameter() ([]ControlCommand, error) {
  1097. AppId := cast.ToInt(RtelecManageApp().RegAppID)
  1098. l := logic.NewDeviceLogic()
  1099. var sqlCommandText = ""
  1100. var list []ControlCommand
  1101. sqlCommandText = "select b.deviceid,devicename,a.modelid,a.attrname attr_name,ifnull(mp.attrname,'') mpname from dev_cpinfo a inner join dev_devinfo b on a.deviceid=b.deviceid left join dev_mpinfo mp on a.mpid=mp.mpid where 1=1"
  1102. if c.Model.AttrName != "" {
  1103. sqlCommandText += fmt.Sprintf(" and a.attrname='%s'", c.Model.AttrName)
  1104. }
  1105. if c.DeviceId > 0 {
  1106. sqlCommandText += fmt.Sprintf(" and a.deviceid=%d", c.DeviceId)
  1107. }
  1108. sqlCommandText += fmt.Sprintf(" and b.appid=%d", AppId)
  1109. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  1110. if err != nil {
  1111. logger.Logger.Error(err)
  1112. logger.Logger.Println(sqlCommandText)
  1113. }
  1114. return list, err
  1115. }
  1116. //获取指令发送时需要的参数
  1117. func (t *DeviceService) GetCmdParameter() ([]ControlCommand, error) {
  1118. AppId := cast.ToInt(RtelecManageApp().RegAppID)
  1119. l := logic.NewDeviceLogic()
  1120. var list []ControlCommand
  1121. var sqlCommandText = "select devicename,a.modelid,attrname attr_name from dev_devinfo a inner join dev_mpinfo b on a.deviceid=b.deviceid "
  1122. sqlCommandText += fmt.Sprintf(" where a.deviceid=%d", t.DeviceId)
  1123. sqlCommandText += fmt.Sprintf(" and b.appid=%d", AppId)
  1124. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  1125. if err != nil {
  1126. logger.Logger.Error(err)
  1127. logger.Logger.Println(sqlCommandText)
  1128. }
  1129. return list, err
  1130. }
  1131. type DeviceComboxList struct {
  1132. Deviceid int `json:"deviceid"`
  1133. Name string `json:"name"`
  1134. Modelid int `json:"modelid"`
  1135. }
  1136. //根据设备名称获取指定设备名称的基本信息,包括deviceid,name,modileid
  1137. func (t *DeviceService) GetComboxListByName(devicename string) *DeviceComboxList {
  1138. lst, err := t.GetComboxList()
  1139. if err != nil {
  1140. return nil
  1141. }
  1142. for _, item := range lst {
  1143. if item.Name == devicename {
  1144. return &item
  1145. }
  1146. }
  1147. return nil
  1148. }
  1149. //根据设备ID获取指定设备名称的基本信息,包括deviceid,name,modileid
  1150. func (t *DeviceService) GetComboxListById(deviceid int32) *DeviceComboxList {
  1151. lst, err := t.GetComboxList()
  1152. if err != nil {
  1153. return nil
  1154. }
  1155. for _, item := range lst {
  1156. if item.Deviceid == int(deviceid) {
  1157. return &item
  1158. }
  1159. }
  1160. return nil
  1161. }
  1162. // 根据设备id获取该设备对应的数据表名
  1163. func (t *DeviceService) GetTableNameByDeviceId(deviceid int32) (string, error) {
  1164. devInfo := t.GetComboxListById(deviceid)
  1165. modelid := devInfo.Modelid
  1166. ormrow, err := new(bo.Global).GetCodeInfo("model_table_mapping", cast.ToString(modelid))
  1167. if err != nil || tools.IsEmpty(ormrow["name"]) == "" {
  1168. logger.Logger.Error(fmt.Sprintf("未找到模型id=d对应的数据表关系", modelid))
  1169. return "", err
  1170. }
  1171. localTable := "t_data_" + tools.IsEmpty(ormrow["name"])
  1172. return localTable, nil
  1173. }
  1174. //获取当前应用的所有设备
  1175. func (t *DeviceService) GetComboxList() ([]DeviceComboxList, error) {
  1176. if lst, has := global.GoCahce.Get("devicelistall"); has {
  1177. return lst.([]DeviceComboxList), nil
  1178. }
  1179. AppId := cast.ToInt(RtelecManageApp().RegAppID)
  1180. l := logic.NewCpInfoLogic()
  1181. var list []DeviceComboxList
  1182. var sqlCommandText = fmt.Sprintf("select deviceid,devicename name,modelid from dev_devinfo where appid=%d;", AppId)
  1183. err := l.SvcCtx.AlarmStrategy.Base.Raw(sqlCommandText, &list)
  1184. if err != nil {
  1185. logger.Logger.Error(err)
  1186. logger.Logger.Println(sqlCommandText)
  1187. } else {
  1188. global.GoCahce.Set("devicelistall", list, -1)
  1189. }
  1190. return list, err
  1191. }
  1192. //总缆设备统计
  1193. func (t *DeviceService) TotalityWorking(modelidParam string) (map[int]interface{}, error) {
  1194. AppId := cast.ToInt(RtelecManageApp().RegAppID)
  1195. var result = map[int]interface{}{}
  1196. dev := logic.NewCpInfoLogic()
  1197. type DevTotal struct {
  1198. TotalNum int `json:"TotalNum"`
  1199. Modelid int `json:"Modelid"`
  1200. OnlineNum int `json:"OnlineNum"`
  1201. OfflineNum int `json:"OfflineNum"`
  1202. }
  1203. var devTotalObj = []DevTotal{}
  1204. var sqlDevTotal = fmt.Sprintf("SELECT d.modelid, count(d.id) AS TotalNum, count(a.id) AS OnlineNum, (count(d.id)-count(a.id)) as OfflineNum FROM dev_devinfo d LEFT JOIN dev_devinfo a ON d.id = a.id and a.appid=%d and a.`online`=2 WHERE d.appid = %d ", AppId, AppId)
  1205. if len(modelidParam) > 0 {
  1206. sqlDevTotal += fmt.Sprintf(" and d.modelid in %s", modelidParam)
  1207. }
  1208. sqlDevTotal += " GROUP BY d.modelid "
  1209. err := dev.SvcCtx.AlarmStrategy.Base.Raw(sqlDevTotal, &devTotalObj)
  1210. if err == nil {
  1211. for i := 0; i < len(devTotalObj); i++ {
  1212. result[devTotalObj[i].Modelid] = devTotalObj[i]
  1213. }
  1214. } else {
  1215. logger.Logger.Error(err)
  1216. logger.Logger.Println(sqlDevTotal)
  1217. }
  1218. return result, nil
  1219. }
  1220. //检查设备状态.将超过指定时长未接收到数据的设备设置为离线状态。一般为应用完全启动成功后触发
  1221. func (t *DeviceService) CheckDeviceState() {
  1222. var sqlCommandText = ""
  1223. for {
  1224. appid := RtelecManageApp().RegAppID
  1225. if appid != "" {
  1226. devicelist, _ := t.GetComboxList()
  1227. if len(devicelist) == 0 {
  1228. time.Sleep(1 * time.Minute)
  1229. continue
  1230. }
  1231. mObject := new(ModelService)
  1232. db := orm.NewOrm()
  1233. db.Using("iss")
  1234. for _, record := range mObject.GetModelListObj() {
  1235. row := record.(map[string]interface{})
  1236. modelid := fmt.Sprintf("%s", row["id"].(json.Number))
  1237. v := fmt.Sprintf("%s", row["period"].(json.Number))
  1238. period, _ := strconv.ParseInt(v, 10, 64)
  1239. sqlCommandText = "update dev_devinfo set online=1 where update_at<date_add(now(),INTERVAL ? SECOND) and online=2 and modelid=? and appid=?"
  1240. _, err := db.Raw(sqlCommandText, -5*period, modelid, appid).Exec()
  1241. if err != nil {
  1242. logger.Logger.Error(err)
  1243. logger.Logger.Println(fmt.Sprintf("Error SQL:%s 参数:%d,%s,%s", sqlCommandText, -5*period, modelid, appid))
  1244. }
  1245. }
  1246. }
  1247. time.Sleep(1 * time.Minute)
  1248. }
  1249. }
  1250. // 根据模型属性名获取对应的设备测点属性,以map返回设备的测点定义
  1251. // 返回属性对应的mpid、mpname
  1252. func (t *DeviceService) DeviceMpInfo(deviceId int32) map[string]orm.Params {
  1253. key := fmt.Sprintf("MpInfo_%d", deviceId)
  1254. tmpMap := map[string]orm.Params{}
  1255. cacheObj, h := global.GoCahce.Get(key)
  1256. if !h {
  1257. mplist, _, err := t.DeviceMpList(deviceId, 1, 10000)
  1258. if err != nil {
  1259. return nil
  1260. }
  1261. for _, row := range mplist {
  1262. tmpMap[tools.IsEmpty(row["attrname"])] = row
  1263. }
  1264. global.GoCahce.Set(key, tmpMap, -1)
  1265. } else {
  1266. tmpMap = cacheObj.(map[string]orm.Params)
  1267. }
  1268. return tmpMap
  1269. }
  1270. // 根据模型ID获取对应的设备测点定义
  1271. // 返回对应的mpid、mpname、attrname等
  1272. func (t *DeviceService) DeviceMpList(deviceId int32, pageindex, pagesize int, modelid ...int64) ([]orm.Params, int, error) {
  1273. v_modelid := int64(0)
  1274. if len(modelid) > 0 {
  1275. v_modelid = modelid[0]
  1276. }
  1277. key := fmt.Sprintf("MpList_%d_%d", deviceId, v_modelid)
  1278. var list = []orm.Params{}
  1279. s1 := (pageindex - 1) * pagesize
  1280. s2 := pageindex * pagesize
  1281. if info, ok := deviceMpList.Load(key); ok {
  1282. all := info.([]orm.Params)
  1283. totalNum := len(all)
  1284. if s2 > totalNum {
  1285. s2 = totalNum
  1286. }
  1287. for i := s1; i < s2; i++ {
  1288. list = append(list, all[i])
  1289. }
  1290. return list, totalNum, nil
  1291. } else {
  1292. db := orm.NewOrm()
  1293. db.Using("iss")
  1294. var sqlCommandText = "select * from dev_mpinfo where deviceid=?"
  1295. sqlParam := []interface{}{deviceId}
  1296. if v_modelid > 0 {
  1297. sqlCommandText = sqlCommandText + " and modelid=?"
  1298. sqlParam = append(sqlParam, modelid)
  1299. }
  1300. _, err := db.Raw(sqlCommandText, sqlParam).Values(&list)
  1301. if err == nil {
  1302. if len(list) > 0 {
  1303. deviceMpList.Store(key, list)
  1304. relist := []orm.Params{}
  1305. totalNum := len(list)
  1306. if s2 > totalNum {
  1307. s2 = totalNum
  1308. }
  1309. for i := s1; i < s2; i++ {
  1310. relist = append(relist, list[i])
  1311. }
  1312. return relist, totalNum, nil
  1313. }
  1314. } else {
  1315. logger.Logger.Error(err)
  1316. logger.Logger.Println(fmt.Sprintf("Error SQL:%s 参数:%+v", sqlCommandText, sqlParam))
  1317. return nil, 0, err
  1318. }
  1319. }
  1320. return list, 0, nil
  1321. }
  1322. type ActionDataRow struct {
  1323. Deviceid int `json:"deviceid"`
  1324. Modelid int `json:"modelid"`
  1325. Attrname string `json:"attrname"`
  1326. Actdesc string `json:"actdesc"`
  1327. Acttype string `json:"acttype"`
  1328. Value float64 `json:"value"`
  1329. Devicename string `json:"devicename"`
  1330. Cpname string `json:"cpname"`
  1331. Mpname string `json:"mpname"`
  1332. }
  1333. //根据设备ID返回对应的动作点信息
  1334. func (t *DeviceService) GetDeviceActionPoint(deviceid int) ([]ActionDataRow, error) {
  1335. db := logic.NewDeviceLogic()
  1336. var result = []ActionDataRow{}
  1337. sql := fmt.Sprintf("select t.deviceid,t.modelid,t.attrname,t1.actdesc,t1.acttype,t1.value from dev_cpinfo t,dev_cpaction t1 where t.cpid=t1.cpid and t.deviceid=%d", deviceid)
  1338. err := db.SvcCtx.AlarmStrategy.Base.Raw(sql, &result)
  1339. if err != nil {
  1340. logger.Logger.Error(err)
  1341. }
  1342. return result, err
  1343. }
  1344. //设备导入
  1345. //导入的数据列及顺序为:序号 区域名称(必填) 模型名称(必填) 设备名称(必填) 串口号 串口波特率 串口停止位 串口检测位 串口数据位 从设备ID IP地址 端口号 MQTT主题 微功耗传感器ID 设备类型(支持开关柜\台区\输电线路\杆塔)
  1346. func (t *DeviceService) Imp(param map[string]interface{}) error {
  1347. datalist := param["datalist"].([]map[int]string)
  1348. regSrv := new(RegionService)
  1349. modelSrv := new(ModelService)
  1350. regLst, _ := regSrv.List(nil)
  1351. regMap := map[string]string{}
  1352. for _, item := range regLst {
  1353. regMap[tools.IsEmpty(item["region_name"])] = tools.IsEmpty(item["id"])
  1354. }
  1355. devType, _ := t.SearchDeviceTypeList()
  1356. devTypeMap := map[string]string{}
  1357. for _, row := range devType.([]orm.Params) {
  1358. devTypeMap[tools.IsEmpty(row["type_name"])] = tools.IsEmpty(row["id"])
  1359. }
  1360. modellist := modelSrv.GetModelListObj()
  1361. modelMap := map[string]string{}
  1362. for _, row2 := range modellist {
  1363. row := row2.(map[string]interface{})
  1364. modelMap[tools.IsEmpty(row["model_name"])] = tools.IsEmpty(row["id"])
  1365. }
  1366. logObj := new(bo.SystemLog)
  1367. user := t.UserInfo
  1368. logObj.UserInfo = map[string]interface{}{"name": user.Usrname, "ip": user.Ip}
  1369. logObj.Audittype = enum.AuditType_device
  1370. logObj.Eventtype = enum.OptEventType_Bus
  1371. logObj.Eventlevel = enum.OptEventLevel_Hight
  1372. logObj.Logtype = enum.LogType_imp
  1373. logObj.Description = "导入设备"
  1374. var AppId = cast.ToInt32(RtelecManageApp().RegAppID)
  1375. for i, row := range datalist {
  1376. var deviceField model.DevDevinfo
  1377. deviceField.Appid = AppId
  1378. pos := 1
  1379. regname := tools.IsEmpty(row[pos])
  1380. if _, h := regMap[regname]; !h {
  1381. return errors.New(fmt.Sprintf("第%d行:无效的区域名称", i+2))
  1382. }
  1383. regid, _ := strconv.Atoi(regMap[regname])
  1384. deviceField.RegionId = int32(regid)
  1385. pos = pos + 1
  1386. modename := tools.IsEmpty(row[pos])
  1387. if _, h := modelMap[modename]; !h {
  1388. return errors.New(fmt.Sprintf("第%d行:无效的模型名称", i+2))
  1389. }
  1390. modelid, _ := strconv.Atoi(modelMap[modename])
  1391. deviceField.Modelid = int32(modelid)
  1392. typename := tools.IsEmpty(row[len(row)-1])
  1393. if _, h := devTypeMap[typename]; !h {
  1394. return errors.New(fmt.Sprintf("第%d行:无效的设备类型名称", i+2))
  1395. }
  1396. typid, _ := strconv.Atoi(devTypeMap[typename])
  1397. deviceField.DevTypeId = int32(typid)
  1398. pos = pos + 1
  1399. devicename := tools.IsEmpty(row[pos])
  1400. //判断是否名称是否已存在
  1401. if _, h := t.DeviceIdByDeviceName().Load(devicename); h {
  1402. return errors.New(fmt.Sprintf("第%d行:设备名称已存在", i+2))
  1403. }
  1404. deviceField.Devicename = devicename
  1405. pos = pos + 1
  1406. serial := tools.IsEmpty(row[pos])
  1407. pos = pos + 1
  1408. rate := tools.IsEmpty(row[pos])
  1409. if serial != "" && rate == "" {
  1410. rate = "9600"
  1411. }
  1412. pos = pos + 1
  1413. stopbit := tools.IsEmpty(row[pos])
  1414. if serial != "" && stopbit == "" {
  1415. stopbit = "1"
  1416. }
  1417. pos = pos + 1
  1418. checkbit := tools.IsEmpty(row[pos])
  1419. if serial != "" && checkbit == "" {
  1420. checkbit = "N"
  1421. }
  1422. pos = pos + 1
  1423. databit := tools.IsEmpty(row[pos])
  1424. if serial != "" && databit == "" {
  1425. databit = "8"
  1426. }
  1427. pos = pos + 1
  1428. salveid := tools.IsEmpty(row[pos])
  1429. pos = pos + 1
  1430. ip := tools.IsEmpty(row[pos])
  1431. pos = pos + 1
  1432. port := tools.IsEmpty(row[pos])
  1433. pos = pos + 1
  1434. mqtttopic := tools.IsEmpty(row[pos])
  1435. pos = pos + 1
  1436. eid := tools.IsEmpty(row[pos])
  1437. if eid == "" {
  1438. eid = "0"
  1439. }
  1440. if serial == "" && ip == "" && mqtttopic == "" {
  1441. return errors.New(fmt.Sprintf("第%d行:串口号、IP、MQTT主题不能同时为空", i+2))
  1442. }
  1443. if serial != "" && salveid == "" {
  1444. return errors.New(fmt.Sprintf("第%d行:从设备号不能为空", i+2))
  1445. }
  1446. if ip != "" && port == "" {
  1447. return errors.New(fmt.Sprintf("第%d行:端口不能为空", i+2))
  1448. }
  1449. deviceField.Serial = serial
  1450. deviceField.Baudrate = cast.ToInt32(rate)
  1451. deviceField.Checkbit = checkbit
  1452. deviceField.Stopbit = cast.ToInt32(stopbit)
  1453. deviceField.Databit = cast.ToInt32(databit)
  1454. deviceField.Slaveid = cast.ToInt32(salveid)
  1455. deviceField.IP = ip
  1456. deviceField.Port = cast.ToInt32(port)
  1457. deviceField.Mqtttopic = mqtttopic
  1458. deviceField.Eid = eid
  1459. deviceField.Appid = AppId
  1460. deviceField.Disable = 1
  1461. deviceField.Online = 0
  1462. var messageId = tools.GetUid()
  1463. msgobj := new(utils.MsgStateManage)
  1464. msgobj.SetMessageStateValue(messageId, utils.MsgState{Success: false, State: false, Message: ""})
  1465. editError := t.CreateDevice(messageId, deviceField, nil, nil)
  1466. if editError != nil {
  1467. logger.Logger.Error(editError, fmt.Sprintf("操作数据:%+v", deviceField))
  1468. return editError
  1469. } else {
  1470. Result := msgobj.HanderMesage(messageId, 5)
  1471. if !Result.Success {
  1472. logdesc := fmt.Sprintf("导入设备[%s]失败,错误:%s,操作数据:%+v", deviceField.Devicename, Result.Message, deviceField)
  1473. logObj.Description = logdesc
  1474. logObj.Fail2()
  1475. logger.Logger.Error(errors.New(logdesc))
  1476. return errors.New(logdesc)
  1477. }
  1478. }
  1479. }
  1480. global.GoCahce.Delete("devicelistall")
  1481. global.GoCahce.Delete("GetAllDevice")
  1482. logObj.Success2()
  1483. return nil
  1484. }
  1485. //设备导出
  1486. func (t *DeviceService) Exp() ([]orm.Params, error) {
  1487. logObj := new(bo.SystemLog)
  1488. user := t.UserInfo
  1489. logObj.UserInfo = map[string]interface{}{"name": user.Usrname, "ip": user.Ip}
  1490. logObj.Audittype = enum.AuditType_device
  1491. logObj.Eventtype = enum.OptEventType_Bus
  1492. logObj.Eventlevel = enum.OptEventLevel_Hight
  1493. logObj.Logtype = enum.LogType_exp
  1494. logObj.Description = "导出设备数据"
  1495. list, _, err := t.SearchDeviceList(map[string]interface{}{"PageIndex": 1, "PageSize": 1000})
  1496. if err != nil {
  1497. logObj.Description = err.Error()
  1498. logObj.Fail2()
  1499. return nil, err
  1500. }
  1501. regSrv := new(RegionService)
  1502. modelSrv := new(ModelService)
  1503. regLst, _ := regSrv.List(nil)
  1504. regMap := map[string]string{}
  1505. for _, item := range regLst {
  1506. regMap[tools.IsEmpty(item["id"])] = tools.IsEmpty(item["region_name"])
  1507. }
  1508. modellist := modelSrv.GetModelListObj()
  1509. modelMap := map[string]string{}
  1510. for _, row2 := range modellist {
  1511. row := row2.(map[string]interface{})
  1512. modelMap[tools.IsEmpty(row["id"])] = tools.IsEmpty(row["model_name"])
  1513. }
  1514. devType, _ := t.SearchDeviceTypeList()
  1515. devTypeMap := map[string]string{}
  1516. for _, row := range devType.([]orm.Params) {
  1517. devTypeMap[tools.IsEmpty(row["id"])] = tools.IsEmpty(row["type_name"])
  1518. }
  1519. result := list.([]orm.Params)
  1520. for i, row := range result {
  1521. row["model_name"] = modelMap[tools.IsEmpty(row["modelid"])]
  1522. row["dev_type_name"] = devTypeMap[tools.IsEmpty(row["dev_type_id"])]
  1523. row["region_name"] = regMap[tools.IsEmpty(row["region_id"])]
  1524. result[i] = row
  1525. }
  1526. logObj.Success2()
  1527. return result, nil
  1528. }
  1529. //设备测点导出
  1530. func (t *DeviceService) ExpMp(deviceid int32) ([]orm.Params, error) {
  1531. deviceidStr := tools.IsEmpty(deviceid)
  1532. devicename := ""
  1533. if v, h := t.DeviceNameByID().Load(deviceidStr); h {
  1534. devicename = tools.IsEmpty(v)
  1535. } else {
  1536. return nil, errors.New("无效的设备ID")
  1537. }
  1538. logObj := new(bo.SystemLog)
  1539. user := t.UserInfo
  1540. logObj.UserInfo = map[string]interface{}{"name": user.Usrname, "ip": user.Ip}
  1541. logObj.Audittype = enum.AuditType_device
  1542. logObj.Eventtype = enum.OptEventType_Bus
  1543. logObj.Eventlevel = enum.OptEventLevel_Hight
  1544. logObj.Logtype = enum.LogType_exp
  1545. logObj.Description = "导出设备" + devicename + "的测点数据"
  1546. /*
  1547. regSrv := new(RegionService)
  1548. regLst, _ := regSrv.List(nil)
  1549. regMap := map[string]string{}
  1550. for _, item := range regLst {
  1551. regMap[tools.IsEmpty(item["id"])] = tools.IsEmpty(item["region_name"])
  1552. }
  1553. */
  1554. modelSrv := new(ModelService)
  1555. modellist := modelSrv.GetModelListObj()
  1556. modelMap := map[string]string{}
  1557. for _, row2 := range modellist {
  1558. row := row2.(map[string]interface{})
  1559. modelMap[tools.IsEmpty(row["id"])] = tools.IsEmpty(row["model_name"])
  1560. }
  1561. //modelAttrMap := map[string]interface{}{} //模型属性
  1562. mplist, _, err := t.DeviceMpList(deviceid, 1, 1000)
  1563. if err != nil {
  1564. return nil, err
  1565. }
  1566. result := []orm.Params{}
  1567. for _, row := range mplist {
  1568. row["devicename"] = devicename
  1569. row["modelname"] = modelMap[tools.IsEmpty(row["modelid"])]
  1570. result = append(result, row)
  1571. }
  1572. logObj.Success2()
  1573. return result, nil
  1574. }
  1575. //设备测点导入
  1576. func (t *DeviceService) ImpMp(param map[string]interface{}) error {
  1577. datalist := param["datalist"].([]map[int]string)
  1578. devicelist, _ := t.GetAllDevice()
  1579. deviceMap := map[string]int32{}
  1580. for _, row := range devicelist {
  1581. deviceMap[tools.IsEmpty(row["devicename"])] = cast.ToInt32(row["deviceid"])
  1582. }
  1583. logObj := new(bo.SystemLog)
  1584. user := t.UserInfo
  1585. logObj.UserInfo = map[string]interface{}{"name": user.Usrname, "ip": user.Ip}
  1586. logObj.Audittype = enum.AuditType_device
  1587. logObj.Eventtype = enum.OptEventType_Bus
  1588. logObj.Eventlevel = enum.OptEventLevel_Hight
  1589. logObj.Logtype = enum.LogType_imp
  1590. logObj.Description = "导入设备测点数据"
  1591. regSrv := new(RegionService)
  1592. regLst, _ := regSrv.List(nil)
  1593. regMap := map[string]string{}
  1594. for _, item := range regLst {
  1595. regMap[tools.IsEmpty(item["id"])] = tools.IsEmpty(item["region_name"])
  1596. }
  1597. modelSrv := new(ModelService)
  1598. modellist := modelSrv.GetModelListObj()
  1599. modelMap := map[string]int32{}
  1600. for _, row2 := range modellist {
  1601. row := row2.(map[string]interface{})
  1602. modelMap[tools.IsEmpty(row["model_name"])] = cast.ToInt32(tools.IsEmpty(row["id"]))
  1603. }
  1604. logger.Logger.Debug(modelMap)
  1605. modelAttrMap := map[int32]interface{}{} //模型属性
  1606. appid := cast.ToInt32(RtelecManageApp().RegAppID)
  1607. i := 2
  1608. for _, row := range datalist {
  1609. mp_Field := model.DevMpinfo{}
  1610. mp_Field.Online = 1 //新增测点时,默认为离线
  1611. mp_Field.Disable = 1 //新增时默认为启用
  1612. mp_Field.Appid = appid
  1613. if row[1] == "" {
  1614. return errors.New(fmt.Sprintf("第%d行:设备名称不能为空", i))
  1615. }
  1616. mp_Field.Deviceid = deviceMap[row[1]]
  1617. if mp_Field.Deviceid == 0 {
  1618. return errors.New(fmt.Sprintf("第%d行:无效的设备名称%s", i, row[1]))
  1619. }
  1620. if row[2] == "" {
  1621. return errors.New(fmt.Sprintf("第%d行:测点名称不能为空", i))
  1622. }
  1623. mp_Field.Mpname = row[2]
  1624. mp_Field.Zonename = row[3]
  1625. mp_Field.Positionname = row[4]
  1626. if row[5] == "" {
  1627. return errors.New(fmt.Sprintf("第%d行:模型名称不能为空", i))
  1628. }
  1629. mp_Field.Modelid = modelMap[row[5]]
  1630. if mp_Field.Modelid == 0 {
  1631. return errors.New(fmt.Sprintf("第%d行:无效的模型名称%s", i, row[5]))
  1632. }
  1633. if row[6] == "" {
  1634. return errors.New(fmt.Sprintf("第%d行:模型属性名称不能为空", i))
  1635. }
  1636. if modelAttrMap[mp_Field.Modelid] == nil {
  1637. modelAttrMap[mp_Field.Modelid] = modelSrv.GetModelAttrMap(int64(mp_Field.Modelid))
  1638. }
  1639. if _, h := modelAttrMap[mp_Field.Modelid].(map[string]interface{})[row[6]]; !h {
  1640. return errors.New(fmt.Sprintf("第%d行:无效的模型属性名称%s", i, row[6]))
  1641. }
  1642. mp_Field.Attrname = row[6]
  1643. mp_Field.Phase = row[7]
  1644. mpinfoObject := logic.NewMpInfoLogic()
  1645. mp_Field.Mpid = new(utils.ToolsLogic).GetOnlyId(int64(appid))
  1646. err := mpinfoObject.AddMpInfo(&mp_Field)
  1647. if err != nil {
  1648. logger.Logger.Error(err, fmt.Sprintf("操作数据:%+v", mp_Field))
  1649. return err
  1650. }
  1651. deviceMpList.Delete(fmt.Sprintf("MpList_%d_0", mp_Field.Deviceid)) //清除缓存的测点列表
  1652. global.GoCahce.Delete(fmt.Sprintf("MpInfo_%d", mp_Field.Deviceid)) //清除以模型属性缓存的测点定义
  1653. global.GoCahce.Delete(fmt.Sprintf("MapInfoByDeviceId_%d", mp_Field.Deviceid)) //清除以测点id缓存的测点定义
  1654. i = i + 1
  1655. }
  1656. logObj.Success2()
  1657. return nil
  1658. }