upgrade_mcu.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. if !Board.upgradeMu.TryLock() {
  12. return fmt.Errorf("upgrade busy")
  13. }
  14. defer Board.upgradeMu.Unlock()
  15. filePath := filepath.Join(baseapp.VAR_DIR, "mcu_firmware.rbl")
  16. defer os.Remove(filePath) //升级完成后删除升级文件
  17. info, err := os.Stat(filePath)
  18. if err != nil {
  19. return err
  20. }
  21. if !info.Mode().IsRegular() {
  22. return fmt.Errorf("升级文件无效: %s", filePath)
  23. }
  24. if info.Size() <= 0 {
  25. return fmt.Errorf("升级文件为空: %s", filePath)
  26. }
  27. fileSize := info.Size()
  28. startTime := time.Now()
  29. Board.uartUseMu.Lock()
  30. defer Board.uartUseMu.Unlock()
  31. mcuCtrlBoard_ComExit() /////////////// 1-关闭与控制板的串口通信
  32. time.Sleep(100 * time.Millisecond)
  33. baseapp.Logger.Warnf("##########################################################")
  34. baseapp.Logger.Warnf("############# MCU FIRMWARE UPGRADE START #############")
  35. baseapp.Logger.Warnf("##########################################################")
  36. baseapp.Logger.Warnf("====[ MCU UPGRADE FILE ]====, file=%s, size=%dBytes", filePath, fileSize)
  37. size := ymodem.Send_file(filePath) // 2-使用ymodem发送升级文件
  38. if size <= 0 || size != int(fileSize) {
  39. baseapp.Logger.Errorf("!!!![ MCU UPGRADE FAILED ]!!!!, written=%dBytes, expect=%dBytes", size, fileSize)
  40. } else {
  41. baseapp.Logger.Warnf("====[ MCU UPGRADE SUCCESS ]====, 用时: %v", time.Since(startTime)) ////////// 成功
  42. }
  43. for range 3 { ////////// 3-升级结束后,重新打开与控制板的串口通信
  44. _, err = mcuCtrlBoard_ComInit()
  45. if err == nil {
  46. return nil
  47. }
  48. mcuCtrlBoard_ComExit()
  49. time.Sleep(time.Second)
  50. }
  51. return fmt.Errorf("failed to reopen MCU serial port: %w", err)
  52. }