mqtt.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package api
  2. import (
  3. "bytes"
  4. "crypto/hmac"
  5. "crypto/sha1"
  6. "crypto/tls"
  7. "crypto/x509"
  8. "encoding/json"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "strconv"
  13. "time"
  14. "tmr-watch/conf/setting"
  15. "tmr-watch/http/handle/restful"
  16. "tmr-watch/pkg/logging"
  17. "github.com/astaxie/beego/logs"
  18. MQTT "github.com/eclipse/paho.mqtt.golang"
  19. mqtt "github.com/eclipse/paho.mqtt.golang"
  20. "github.com/robfig/cron"
  21. )
  22. func InitMqttClient() {
  23. if setting.YynserverSetting.FarmId != "" {
  24. c, pubTopic := MqttClient()
  25. deviceHeartbeat(c, pubTopic)
  26. // now := time.Now().AddDate(0, 0, -13).Format("2006-01-02")
  27. // // now := "2024-05-11"
  28. // stirPush(c, pubTopic, now)
  29. // dustingPush(c, pubTopic, now)
  30. // equipmentAccuracyPush(c, pubTopic, now)
  31. // finishedWeightPush(c, pubTopic, now)
  32. // feedtempletPush(c, pubTopic)
  33. // CompletedTrainNumberPush(c, pubTopic, now)
  34. mqttCron := cron.New()
  35. mqttCron.AddFunc("10 06 * * *", func() {
  36. now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  37. stirPush(c, pubTopic, now)
  38. dustingPush(c, pubTopic, now)
  39. equipmentAccuracyPush(c, pubTopic, now)
  40. finishedWeightPush(c, pubTopic, now)
  41. feedtempletPush(c, pubTopic)
  42. CompletedTrainNumberPush(c, pubTopic, now)
  43. })
  44. mqttCron.Start()
  45. }
  46. }
  47. func MqttClient() (MQTT.Client, string) {
  48. // set the device info, include product key, device name, and device secret
  49. // var productKey string = "a1NmXfrjL8M"
  50. // var deviceName string = "4776_p_breed"
  51. // var deviceSecret string = "c2591b89adff22e1c9f0fc03363f56a4"
  52. // ProductKey
  53. // DeviceName
  54. // DeviceSecret
  55. var productKey string = setting.YynserverSetting.ProductKey
  56. var deviceName string = setting.YynserverSetting.DeviceName
  57. var deviceSecret string = setting.YynserverSetting.DeviceSecret
  58. // product_key =k03txxLKFae
  59. // device_name =4623_p_breed
  60. // device_secret =d06ababb2b10ba25bca3041e35ac604d
  61. // host = iot-010a5xth.mqtt.iothub.aliyuncs.com
  62. // farmId=1830004623
  63. // heartBeat=18300046234623_p_breed
  64. // TopicName=/k03txxLKFae/4623_p_breed/user/heatwatch/tmrBreed/post
  65. var timeStamp string = strconv.FormatInt(time.Now().UnixNano(), 10)
  66. var clientId string = "go" + setting.YynserverSetting.FarmId
  67. var subTopic string = "/" + productKey + "/" + deviceName + "/user/heatwatch/tmrBreed/get"
  68. var pubTopic string = "/" + productKey + "/" + deviceName + "/user/heatwatch/tmrBreed/post"
  69. // set the login broker url
  70. var raw_broker bytes.Buffer
  71. raw_broker.WriteString("tcp://")
  72. raw_broker.WriteString("iot-010a5xth.mqtt.iothub.aliyuncs.com:1883")
  73. opts := MQTT.NewClientOptions().AddBroker(raw_broker.String())
  74. // calculate the login auth info, and set it into the connection options
  75. auth := calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp)
  76. opts.SetClientID(auth.mqttClientId)
  77. opts.SetUsername(auth.username)
  78. opts.SetPassword(auth.password)
  79. opts.SetMaxReconnectInterval(1 * time.Second)
  80. opts.AutoReconnect = true
  81. // opts.SetKeepAlive(60 * 2 * time.Second)
  82. opts.OnConnect = func(c MQTT.Client) {
  83. if token := c.Subscribe(subTopic, 0, feedHeatwatch); token.Wait() && token.Error() != nil {
  84. logging.Error("mqtt Subscribe err: ", token.Error())
  85. os.Exit(1)
  86. }
  87. }
  88. c := mqtt.NewClient(opts)
  89. if token := c.Connect(); token.Wait() && token.Error() != nil {
  90. fmt.Println(token.Error())
  91. os.Exit(1)
  92. }
  93. fmt.Print("Connect aliyun IoT Cloud Sucess\n")
  94. return c, pubTopic
  95. }
  96. func NewTLSConfig() *tls.Config {
  97. // Import trusted certificates from CAfile.pem.
  98. // Alternatively, manually add CA certificates to default openssl CA bundle.
  99. certpool := x509.NewCertPool()
  100. pemCerts, err := ioutil.ReadFile("./x509/root.pem")
  101. if err != nil {
  102. fmt.Println("0. read file error, game over!!")
  103. }
  104. certpool.AppendCertsFromPEM(pemCerts)
  105. // Create tls.Config with desired tls properties
  106. return &tls.Config{
  107. // RootCAs = certs used to verify server cert.
  108. RootCAs: certpool,
  109. // ClientAuth = whether to request cert from server.
  110. // Since the server is set up for SSL, this happens
  111. // anyways.
  112. ClientAuth: tls.NoClientCert,
  113. // ClientCAs = certs used to validate client cert.
  114. ClientCAs: nil,
  115. // InsecureSkipVerify = verify that cert contents
  116. // match server. IP matches what is in cert etc.
  117. InsecureSkipVerify: false,
  118. // Certificates = list of certs client sends to server.
  119. // Certificates: []tls.Certificate{cert},
  120. }
  121. }
  122. // define a function for the default message handler
  123. var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
  124. fmt.Printf("TOPIC: %s\n", msg.Topic())
  125. fmt.Printf("MSG: %s\n", msg.Payload())
  126. }
  127. type AuthInfo struct {
  128. password, username, mqttClientId string
  129. }
  130. func calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp string) AuthInfo {
  131. var raw_passwd bytes.Buffer
  132. raw_passwd.WriteString("clientId" + clientId)
  133. raw_passwd.WriteString("deviceName")
  134. raw_passwd.WriteString(deviceName)
  135. raw_passwd.WriteString("productKey")
  136. raw_passwd.WriteString(productKey)
  137. raw_passwd.WriteString("timestamp")
  138. raw_passwd.WriteString(timeStamp)
  139. fmt.Println(raw_passwd.String())
  140. // hmac, use sha1
  141. mac := hmac.New(sha1.New, []byte(deviceSecret))
  142. mac.Write([]byte(raw_passwd.String()))
  143. password := fmt.Sprintf("%02x", mac.Sum(nil))
  144. fmt.Println(password)
  145. username := deviceName + "&" + productKey
  146. var MQTTClientId bytes.Buffer
  147. MQTTClientId.WriteString(clientId)
  148. // hmac, use sha1; securemode=2 means TLS connection
  149. MQTTClientId.WriteString("|securemode=2,_v=paho-go-1.0.0,signmethod=hmacsha1,timestamp=")
  150. MQTTClientId.WriteString(timeStamp)
  151. MQTTClientId.WriteString("|")
  152. auth := AuthInfo{password: password, username: username, mqttClientId: MQTTClientId.String()}
  153. return auth
  154. }
  155. func feedtempletPush(c MQTT.Client, pubTopic string) {
  156. tx := restful.Engine.NewSession()
  157. defer tx.Close()
  158. dataList, err := tx.SQL(`SELECT
  159. f.id AS recipeId,
  160. f.tname recipeName,
  161. ft.id ingId,
  162. ifnull(fd.fname,fdy.fname) ingName,
  163. if(fd.fname is not null, ft.fweight,fty.fweight) afQty,
  164. ft.sort mixNo,
  165. ifnull(fd.allowratio,fdy.allowratio) allowableError,
  166. ifnull(fd.fclass,fdy.fclass) ingType,
  167. if(fd.fname is not null,ft.fweight * ( fd.dry / 100 ), fty.fweight * ( fdy.dry / 100 )) dmQty,
  168. '' recipeCost
  169. FROM
  170. feedtemplet f
  171. JOIN ftdetail ft ON ft.ftid = f.id
  172. left JOIN feed fd ON fd.id = ft.fid
  173. left join feedtemplet fy on fy.id = ft.preftid
  174. left join ftdetail fty on fty.ftid = fy.id
  175. left JOIN feed fdy ON fdy.id = fty.fid
  176. `).QueryString()
  177. if err != nil {
  178. logs.Error("feedtempletPush-error-1:", err)
  179. return
  180. }
  181. pushStr := `{
  182. "apiId": "getKPTData",
  183. "param": {
  184. "farmId": "%s",
  185. "method":"getfeedtempletinfo",
  186. "rowCount": "1",
  187. "resultData":%s
  188. }
  189. }`
  190. if len(dataList) > 0 {
  191. b, _ := json.Marshal(dataList)
  192. pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, string(b))
  193. // c.Publish(pubTopic, 2, false, pushStr)
  194. token := c.Publish(pubTopic, 2, false, pushStr)
  195. fmt.Println("publish msg: ", pushStr, token.Error())
  196. // token.Wait()
  197. // time.Sleep(2 * time.Second)
  198. }
  199. }
  200. func stirPush(c MQTT.Client, pubTopic, date string) {
  201. tx := restful.Engine.NewSession()
  202. defer tx.Close()
  203. dataList, err := tx.SQL(`SELECT
  204. DATE_FORMAT(d.mydate,'%Y-%m-%d') loadDate,
  205. d.sort tmrNo,
  206. d.times loadShift,
  207. d.tempid recipeId,
  208. d.templetname recipeName,
  209. f.feedcode ingId,
  210. d1.fname ingName,
  211. 12 ingType,
  212. f.dry dmPct,
  213. d1.sort mixNo,
  214. d1.feedallowratio allowable_error,
  215. d1.lweight expWeight,
  216. d1.actualweightminus actualWeight,
  217. if((select count(1) from downloadplandtl1 where pid = d.id and sort < d1.sort order by sort desc) >0 ,(select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id and sort < d1.sort order by sort desc limit 1),DATE_FORMAT(d.intime,'%Y-%m-%d %H:%i:%s') ) startTime,
  218. DATE_FORMAT(d1.intime,'%Y-%m-%d %H:%i:%s') endTime , ifnull(if(d.driverId !=0 ,(select drivername from driver where id = d.driverId),(SELECT dr.driver FROM dutyrecord dr
  219. WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid and dr.times= d.times AND dr.operatetime <=d.mydate
  220. ORDER BY dr.operatetime DESC LIMIT 1)),'')tmrName
  221. FROM
  222. downloadedplan d
  223. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  224. JOIN feed f ON f.feedcode = d1.feedcode
  225. AND f.pastureid = d.pastureid
  226. WHERE
  227. DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = ? `, date).QueryString()
  228. if err != nil {
  229. logs.Error("feedtempletPush-error-1:", err)
  230. return
  231. }
  232. pushStr := `{
  233. "apiId": "getKPTData",
  234. "param": {
  235. "farmId": "%s",
  236. "method":"uploadadddata",
  237. "rowCount": "%d",
  238. "resultData":%s
  239. }
  240. }`
  241. if len(dataList) > 0 {
  242. b, _ := json.Marshal(dataList)
  243. pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, len(dataList), string(b))
  244. token := c.Publish(pubTopic, 2, false, pushStr)
  245. fmt.Println("publish msg: ", pushStr, token.Error())
  246. // token.Wait()
  247. // time.Sleep(2 * time.Second)
  248. }
  249. }
  250. // 撒料信息
  251. func dustingPush(c MQTT.Client, pubTopic, date string) {
  252. tx := restful.Engine.NewSession()
  253. defer tx.Close()
  254. dataList, err := tx.SQL(`SELECT
  255. ifnull(if(d.driverId !=0 ,(select drivername from driver where id = d.driverId),(SELECT dr.driver FROM dutyrecord dr
  256. WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid and dr.times= d.times AND dr.operatetime <=d.mydate
  257. ORDER BY dr.operatetime DESC LIMIT 1)),'')tmrName ,
  258. DATE_FORMAT(d.mydate,'%Y-%m-%d') dropDate,
  259. d.sort tmrNo,
  260. d.times dropShift,
  261. d2.fbarid penId,
  262. b.bname penName,
  263. fp.ccount cowCount,
  264. d2.sort feedingNo,
  265. d2.lweight expWeight,
  266. d2.actualweightminus actualWeight,
  267. if((select count(1) from downloadplandtl2 where pid = d.id and sort < d2.sort order by sort desc) >0 ,(select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl2 where pid = d.id and sort < d2.sort order by sort desc limit 1), (select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl1 where pid = d.id order by sort desc limit 1) ) startTime,
  268. DATE_FORMAT(d2.intime,'%Y-%m-%d %H:%i:%s') endTime
  269. FROM
  270. downloadedplan d
  271. JOIN downloadplandtl2 d2 ON d2.pid = d.id
  272. JOIN bar b ON b.id = d2.fbarid
  273. join feedp fp on fp.barid = b.id
  274. join tmr t on t.id = d.tmrid
  275. left join driver on driver.drivercode = t.eqcode
  276. WHERE
  277. DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = ? `, date).QueryString()
  278. if err != nil {
  279. logs.Error("feedtempletPush-error-1:", err)
  280. return
  281. }
  282. pushStr := `{
  283. "apiId": "getKPTData",
  284. "param": {
  285. "farmId": "%s",
  286. "method":"uploaddiliverdata",
  287. "rowCount": "%d",
  288. "resultData":%s
  289. }
  290. }`
  291. if len(dataList) > 0 {
  292. b, _ := json.Marshal(dataList)
  293. pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, len(dataList), string(b))
  294. token := c.Publish(pubTopic, 2, false, pushStr)
  295. fmt.Println("publish msg: ", pushStr, token.Error())
  296. // token.Wait()
  297. // time.Sleep(2 * time.Second)
  298. }
  299. }
  300. //设备心跳
  301. func deviceHeartbeat(c MQTT.Client, pubTopic string) {
  302. pushStr := fmt.Sprintf(`{"data_collect_number":%s,"status":true,"model_type":"heartbeat"}`, setting.YynserverSetting.HeartBeat)
  303. token := c.Publish(pubTopic, 2, false, pushStr)
  304. fmt.Println("publish msg: ", pushStr, token.Error())
  305. // token.Wait()
  306. // go func() {
  307. duetimecst2, _ := time.ParseInLocation("15:04:05", "00:01:00", time.Local)
  308. duetimecst3, _ := time.ParseInLocation("15:04:05", "00:00:00", time.Local)
  309. spec1 := fmt.Sprintf("@every %v", duetimecst2.Sub(duetimecst3))
  310. // for {
  311. device := cron.New()
  312. device.AddFunc(spec1, func() {
  313. token := c.Publish(pubTopic, 2, false, pushStr)
  314. fmt.Println("publish msg: ", pushStr, token.Error(), time.Now())
  315. // token.Wait()
  316. })
  317. // }
  318. device.Start()
  319. // }()
  320. }
  321. // 准确率
  322. func equipmentAccuracyPush(c MQTT.Client, pubTopic, date string) {
  323. tx := restful.Engine.NewSession()
  324. defer tx.Close()
  325. dataList, err := tx.SQL(`SELECT
  326. t.tname Name,
  327. 1-abs (
  328. sum( d1.actualweightminus )- sum( d1.lweight ))/ sum( d1.lweight ) Rate,
  329. d.mydate RateDate , DATE_FORMAT(d.intime,'%Y-%m-%d %H:%i:%s') startTime,
  330. (select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadplandtl2 where pid = d.id order by sort desc limit 1) endTime
  331. FROM
  332. downloadedplan d
  333. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  334. JOIN tmr t ON t.datacaptureno = d.datacaptureno
  335. WHERE
  336. DATE_FORMAT( d.mydate, '%Y-%m-%d' ) = ? and d.lpplantype in(0,1)
  337. GROUP BY
  338. d.datacaptureno`, date).QueryString()
  339. if err != nil {
  340. logs.Error("feedtempletPush-error-1:", err)
  341. return
  342. }
  343. pushStr := `{
  344. "apiId": "getKPTData",
  345. "param": {
  346. "resultData": %s,
  347. "farmId": "%s",
  348. "method": "uploadrate",
  349. "rowCount": %d
  350. }
  351. }`
  352. if len(dataList) > 0 {
  353. b, _ := json.Marshal(dataList)
  354. pushStr = fmt.Sprintf(pushStr, string(b), setting.YynserverSetting.FarmId, len(dataList))
  355. token := c.Publish(pubTopic, 2, false, pushStr)
  356. fmt.Println("publish msg: ", pushStr, token.Error())
  357. // token.Wait()
  358. // time.Sleep(2 * time.Second)
  359. }
  360. }
  361. // 完成重量
  362. func finishedWeightPush(c MQTT.Client, pubTopic, date string) {
  363. tx := restful.Engine.NewSession()
  364. defer tx.Close()
  365. dataList, err := tx.SQL(`SELECT
  366. sum( d1.actualweightminus ) completeWeight,
  367. sum( d1.lweight ) planWeight,
  368. d.mydate weightDate , DATE_FORMAT(d.intime,'%Y-%m-%d %H:%i:%s') startTime,
  369. (select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadedplan where mydate = d.mydate and intime is not null order by sort desc limit 1) endTime
  370. FROM
  371. downloadedplan d
  372. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  373. JOIN tmr t ON t.datacaptureno = d.datacaptureno
  374. WHERE
  375. DATE_FORMAT( d.mydate, '%Y-%m-%d' ) = ? and lpplantype in(0,1)`, date).QueryString()
  376. if err != nil {
  377. logs.Error("feedtempletPush-error-1:", err)
  378. return
  379. }
  380. pushStr := `{
  381. "apiId": "getKPTData",
  382. "param": {
  383. "resultData": %s,
  384. "farmId": "%s",
  385. "method": "uploadweight",
  386. "rowCount": "1"
  387. }
  388. }`
  389. if len(dataList) > 0 {
  390. b, _ := json.Marshal(dataList)
  391. pushStr = fmt.Sprintf(pushStr, string(b), setting.YynserverSetting.FarmId)
  392. token := c.Publish(pubTopic, 2, false, pushStr)
  393. fmt.Println("publish msg: ", pushStr, token.Error())
  394. // token.Wait()
  395. // time.Sleep(2 * time.Second)
  396. }
  397. }
  398. // 完成车次
  399. func CompletedTrainNumberPush(c MQTT.Client, pubTopic, date string) {
  400. tx := restful.Engine.NewSession()
  401. defer tx.Close()
  402. dataList, err := tx.SQL(` select (select count(1) from downloadedplan where DATE_FORMAT(mydate ,'%Y-%m-%d' ) = ? and lpplantype in(0,1) ) planCar,
  403. (select count(1) from downloadedplan where DATE_FORMAT(mydate ,'%Y-%m-%d' ) = ? and iscompleted = 1 and lpplantype in(0,1)) CompleteCar ,
  404. ? carDate,
  405. (select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadedplan where DATE_FORMAT(mydate ,'%Y-%m-%d' ) = ? and iscompleted = 1 and lpplantype in(0,1) order by intime asc limit 1 ) startTime,
  406. (select DATE_FORMAT(intime,'%Y-%m-%d %H:%i:%s') from downloadedplan where DATE_FORMAT(mydate ,'%Y-%m-%d' ) = ? and iscompleted = 1 and lpplantype in(0,1) and intime is not null order by intime desc limit 1 ) endTime
  407. `, date, date, date, date, date).QueryString()
  408. if err != nil {
  409. logs.Error("feedtempletPush-error-1:", err)
  410. return
  411. }
  412. pushStr := `{
  413. "apiId": "getKPTData",
  414. "param": {
  415. "resultData": %s,
  416. "farmId": "%s",
  417. "method": "uploadcarnumber",
  418. "rowCount": "1"
  419. }
  420. }`
  421. if len(dataList) > 0 {
  422. b, _ := json.Marshal(dataList)
  423. pushStr = fmt.Sprintf(pushStr, string(b), setting.YynserverSetting.FarmId)
  424. token := c.Publish(pubTopic, 2, false, pushStr)
  425. fmt.Println("publish msg: ", pushStr, token.Error())
  426. // token.Wait()
  427. // time.Sleep(2 * time.Second)
  428. }
  429. }
  430. func feedHeatwatch(client MQTT.Client, msg MQTT.Message) {
  431. tx := restful.Engine.NewSession()
  432. defer tx.Close()
  433. data := make(map[string]interface{})
  434. json.Unmarshal(msg.Payload(), &data)
  435. if _, ok := data["feedData"]; ok {
  436. for _, item := range data["feedData"].([]map[string]interface{}) {
  437. tx.SQL(` insert into feed(pastureid,feedcode,fname)values((SELECT column_default INTO pastureidTem FROM information_schema.COLUMNS
  438. WHERE table_name = 'recweight' AND table_schema = 'tmrwatch3' AND column_name = 'pastureid'),?,?)
  439. ON DUPLICATE KEY UPDATE feedcode = ?,fname = ? `, item["feedCode"], item["feedName"], item["feedCode"], item["feedName"]).Execute()
  440. }
  441. } else if _, ok := data["barData"]; ok {
  442. for _, item := range data["barData"].([]map[string]interface{}) {
  443. tx.SQL(` insert into bar(pastureid,bcode,bname)values((SELECT column_default INTO pastureidTem FROM information_schema.COLUMNS
  444. WHERE table_name = 'recweight' AND table_schema = 'tmrwatch3' AND column_name = 'pastureid'),?,?)
  445. ON DUPLICATE KEY UPDATE bcode = ?,bname = ? `, item["barCode"], item["barName"], item["barCode"], item["barName"]).Execute()
  446. }
  447. }
  448. }