mqtt.go 18 KB

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