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, -5).Format("2006-01-02")
  27. // stirPush(c, pubTopic, now)
  28. // dustingPush(c, pubTopic, now)
  29. // equipmentAccuracyPush(c, pubTopic, now)
  30. // finishedWeightPush(c, pubTopic, now)
  31. // feedtempletPush(c, pubTopic)
  32. // CompletedTrainNumberPush(c, pubTopic, now)
  33. mqttCron := cron.New()
  34. mqttCron.AddFunc("10 06 * * *", func() {
  35. now := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
  36. stirPush(c, pubTopic, now)
  37. dustingPush(c, pubTopic, now)
  38. equipmentAccuracyPush(c, pubTopic, now)
  39. finishedWeightPush(c, pubTopic, now)
  40. feedtempletPush(c, pubTopic)
  41. CompletedTrainNumberPush(c, pubTopic, now)
  42. })
  43. mqttCron.Start()
  44. }
  45. }
  46. func MqttClient() (MQTT.Client, string) {
  47. // set the device info, include product key, device name, and device secret
  48. // var productKey string = "a1NmXfrjL8M"
  49. // var deviceName string = "4776_p_breed"
  50. // var deviceSecret string = "c2591b89adff22e1c9f0fc03363f56a4"
  51. // ProductKey
  52. // DeviceName
  53. // DeviceSecret
  54. var productKey string = setting.YynserverSetting.ProductKey
  55. var deviceName string = setting.YynserverSetting.DeviceName
  56. var deviceSecret string = setting.YynserverSetting.DeviceSecret
  57. // product_key =k03txxLKFae
  58. // device_name =4623_p_breed
  59. // device_secret =d06ababb2b10ba25bca3041e35ac604d
  60. // host = iot-010a5xth.mqtt.iothub.aliyuncs.com
  61. // farmId=1830004623
  62. // heartBeat=18300046234623_p_breed
  63. // TopicName=/k03txxLKFae/4623_p_breed/user/heatwatch/tmrBreed/post
  64. var timeStamp string = strconv.FormatInt(time.Now().UnixNano(), 10)
  65. var clientId string = "go" + setting.YynserverSetting.FarmId
  66. var subTopic string = "/" + productKey + "/" + deviceName + "/user/heatwatch/tmrBreed/get"
  67. var pubTopic string = "/" + productKey + "/" + deviceName + "/user/heatwatch/tmrBreed/post"
  68. // set the login broker url
  69. var raw_broker bytes.Buffer
  70. raw_broker.WriteString("tcp://")
  71. raw_broker.WriteString("iot-010a5xth.mqtt.iothub.aliyuncs.com:1883")
  72. opts := MQTT.NewClientOptions().AddBroker(raw_broker.String())
  73. // calculate the login auth info, and set it into the connection options
  74. auth := calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp)
  75. opts.SetClientID(auth.mqttClientId)
  76. opts.SetUsername(auth.username)
  77. opts.SetPassword(auth.password)
  78. opts.SetMaxReconnectInterval(1 * time.Second)
  79. opts.AutoReconnect = true
  80. // opts.SetKeepAlive(60 * 2 * time.Second)
  81. opts.OnConnect = func(c MQTT.Client) {
  82. if token := c.Subscribe(subTopic, 0, feedHeatwatch); token.Wait() && token.Error() != nil {
  83. logging.Error("mqtt Subscribe err: ", token.Error())
  84. os.Exit(1)
  85. }
  86. }
  87. c := mqtt.NewClient(opts)
  88. if token := c.Connect(); token.Wait() && token.Error() != nil {
  89. fmt.Println(token.Error())
  90. os.Exit(1)
  91. }
  92. fmt.Print("Connect aliyun IoT Cloud Sucess\n")
  93. return c, pubTopic
  94. }
  95. func NewTLSConfig() *tls.Config {
  96. // Import trusted certificates from CAfile.pem.
  97. // Alternatively, manually add CA certificates to default openssl CA bundle.
  98. certpool := x509.NewCertPool()
  99. pemCerts, err := ioutil.ReadFile("./x509/root.pem")
  100. if err != nil {
  101. fmt.Println("0. read file error, game over!!")
  102. }
  103. certpool.AppendCertsFromPEM(pemCerts)
  104. // Create tls.Config with desired tls properties
  105. return &tls.Config{
  106. // RootCAs = certs used to verify server cert.
  107. RootCAs: certpool,
  108. // ClientAuth = whether to request cert from server.
  109. // Since the server is set up for SSL, this happens
  110. // anyways.
  111. ClientAuth: tls.NoClientCert,
  112. // ClientCAs = certs used to validate client cert.
  113. ClientCAs: nil,
  114. // InsecureSkipVerify = verify that cert contents
  115. // match server. IP matches what is in cert etc.
  116. InsecureSkipVerify: false,
  117. // Certificates = list of certs client sends to server.
  118. // Certificates: []tls.Certificate{cert},
  119. }
  120. }
  121. // define a function for the default message handler
  122. var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
  123. fmt.Printf("TOPIC: %s\n", msg.Topic())
  124. fmt.Printf("MSG: %s\n", msg.Payload())
  125. }
  126. type AuthInfo struct {
  127. password, username, mqttClientId string
  128. }
  129. func calculate_sign(clientId, productKey, deviceName, deviceSecret, timeStamp string) AuthInfo {
  130. var raw_passwd bytes.Buffer
  131. raw_passwd.WriteString("clientId" + clientId)
  132. raw_passwd.WriteString("deviceName")
  133. raw_passwd.WriteString(deviceName)
  134. raw_passwd.WriteString("productKey")
  135. raw_passwd.WriteString(productKey)
  136. raw_passwd.WriteString("timestamp")
  137. raw_passwd.WriteString(timeStamp)
  138. fmt.Println(raw_passwd.String())
  139. // hmac, use sha1
  140. mac := hmac.New(sha1.New, []byte(deviceSecret))
  141. mac.Write([]byte(raw_passwd.String()))
  142. password := fmt.Sprintf("%02x", mac.Sum(nil))
  143. fmt.Println(password)
  144. username := deviceName + "&" + productKey
  145. var MQTTClientId bytes.Buffer
  146. MQTTClientId.WriteString(clientId)
  147. // hmac, use sha1; securemode=2 means TLS connection
  148. MQTTClientId.WriteString("|securemode=2,_v=paho-go-1.0.0,signmethod=hmacsha1,timestamp=")
  149. MQTTClientId.WriteString(timeStamp)
  150. MQTTClientId.WriteString("|")
  151. auth := AuthInfo{password: password, username: username, mqttClientId: MQTTClientId.String()}
  152. return auth
  153. }
  154. func feedtempletPush(c MQTT.Client, pubTopic string) {
  155. tx := restful.Engine.NewSession()
  156. defer tx.Close()
  157. dataList, err := tx.SQL(`SELECT
  158. f.id AS recipeId,
  159. f.tname recipeName,
  160. ft.id ingId,
  161. ifnull(fd.fname,fdy.fname) ingName,
  162. if(fd.fname is not null, ft.fweight,fty.fweight) afQty,
  163. ft.sort mixNo,
  164. ifnull(fd.allowratio,fdy.allowratio) allowableError,
  165. ifnull(fd.fclass,fdy.fclass) ingType,
  166. if(fd.fname is not null,ft.fweight * ( fd.dry / 100 ), fty.fweight * ( fdy.dry / 100 )) dmQty,
  167. '' recipeCost
  168. FROM
  169. feedtemplet f
  170. JOIN ftdetail ft ON ft.ftid = f.id
  171. left JOIN feed fd ON fd.id = ft.fid
  172. left join feedtemplet fy on fy.id = ft.preftid
  173. left join ftdetail fty on fty.ftid = fy.id
  174. left JOIN feed fdy ON fdy.id = fty.fid
  175. `).QueryString()
  176. if err != nil {
  177. logs.Error("feedtempletPush-error-1:", err)
  178. return
  179. }
  180. pushStr := `{
  181. "apiId": "getKPTData",
  182. "param": {
  183. "farmId": "%s",
  184. "method":"getfeedtempletinfo",
  185. "rowCount": "1",
  186. "resultData":%s
  187. }
  188. }`
  189. if len(dataList) > 0 {
  190. b, _ := json.Marshal(dataList)
  191. pushStr = fmt.Sprintf(pushStr, setting.YynserverSetting.FarmId, string(b))
  192. // c.Publish(pubTopic, 2, false, pushStr)
  193. token := c.Publish(pubTopic, 2, false, pushStr)
  194. fmt.Println("publish msg: ", pushStr, token.Error())
  195. // token.Wait()
  196. // time.Sleep(2 * time.Second)
  197. }
  198. }
  199. func stirPush(c MQTT.Client, pubTopic, date string) {
  200. tx := restful.Engine.NewSession()
  201. defer tx.Close()
  202. dataList, err := tx.SQL(`SELECT
  203. DATE_FORMAT(d.mydate,'%Y-%m-%d') loadDate,
  204. d.sort tmrNo,
  205. d.times loadShift,
  206. d.tempid recipeId,
  207. d.templetname recipeName,
  208. f.feedcode ingId,
  209. d1.fname ingName,
  210. 12 ingType,
  211. f.dry dmPct,
  212. d1.sort mixNo,
  213. d1.feedallowratio allowable_error,
  214. d1.lweight expWeight,
  215. d1.actualweightminus actualWeight,
  216. 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,
  217. 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
  218. WHERE dr.pastureid = d.pastureid AND dr.eqid = d.tmrid and dr.times= d.times AND dr.operatetime <=d.mydate
  219. ORDER BY dr.operatetime DESC LIMIT 1)),'')tmrName
  220. FROM
  221. downloadedplan d
  222. JOIN downloadplandtl1 d1 ON d1.pid = d.id
  223. JOIN feed f ON f.feedcode = d1.feedcode
  224. AND f.pastureid = d.pastureid
  225. WHERE
  226. DATE_FORMAT( d.mydate ,'%Y-%m-%d' ) = ?
  227. `, 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. }