upgrade_mcu.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package mcu_ctrl_board
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. "hnyfkj.com.cn/rtu/linux/baseapp"
  8. "hnyfkj.com.cn/rtu/linux/ymodem"
  9. )
  10. func StartMCUUpgrade() error {
  11. filePath := filepath.Join(baseapp.VAR_DIR, "mcu_firmware.rbl")
  12. defer os.Remove(filePath) //升级完成后删除升级文件
  13. info, err := os.Stat(filePath)
  14. if err != nil {
  15. return err
  16. }
  17. if !info.Mode().IsRegular() {
  18. return fmt.Errorf("固件文件无效: %s", filePath)
  19. }
  20. if info.Size() <= 0 {
  21. return fmt.Errorf("固件文件为空: %s", filePath)
  22. }
  23. fileSize := info.Size()
  24. startTime := time.Now()
  25. upgradeOK := false
  26. Board.uartMu.Lock()
  27. defer Board.uartMu.Unlock()
  28. baseapp.Logger.Warnf("====[ MCU UPGRADE PREPARE ]==== [%s] stop MCU communication", MODULE_NAME)
  29. mcuCtrlBoard_ComExit() /////////////// 1-关闭与控制板的串口通信
  30. time.Sleep(100 * time.Millisecond)
  31. baseapp.Logger.Warnf("##########################################################")
  32. baseapp.Logger.Warnf("############# MCU FIRMWARE UPGRADE START #############")
  33. baseapp.Logger.Warnf("##########################################################")
  34. baseapp.Logger.Warnf("====[ MCU UPGRADE FILE ]====, file=%s, size=%dBytes", filePath, fileSize)
  35. bytes := ymodem.Send_file(filePath) // 2-使用ymodem发送升级文件
  36. if bytes > 0 && bytes == int(fileSize) {
  37. upgradeOK = true
  38. }
  39. elapsed := time.Since(startTime)
  40. if !upgradeOK {
  41. baseapp.Logger.Errorf("!!!![ MCU UPGRADE FAILED ]!!!!, written=%dBytes, expect=%dBytes", bytes, fileSize)
  42. return fmt.Errorf("MCU firmware upgrade failed, written=%dBytes, expect=%dBytes", bytes, fileSize)
  43. }
  44. baseapp.Logger.Warnf("====[ MCU UPGRADE SUCCESS ]====, 用时: %v", elapsed) //成功
  45. for range 5 { ////////// 3-升级结束后,重新打开与控制板的串口通信
  46. if baseapp.IsExit1() {
  47. return nil
  48. }
  49. _, err = mcuCtrlBoard_ComInit()
  50. if err == nil {
  51. baseapp.Logger.Warnf("====[ MCU UPGRADE DONE ]==== [%s] restart MCU communication", MODULE_NAME)
  52. return nil
  53. }
  54. mcuCtrlBoard_ComExit()
  55. time.Sleep(time.Second)
  56. }
  57. return fmt.Errorf("failed to reopen MCU communication port: %w", err)
  58. }