mqtt.go 17 KB

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