upgrade_mcu.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package mcu_ctrl_board
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "time"
  8. "hnyfkj.com.cn/rtu/linux/baseapp"
  9. "hnyfkj.com.cn/rtu/linux/ymodem"
  10. )
  11. const (
  12. DefaultSendFileName = "rtthread.rbl" // 默认发送的升级文件名
  13. )
  14. func StartMCUUpgrade() error {
  15. fwPath := filepath.Join(baseapp.VAR_DIR, DefaultSendFileName)
  16. defer os.Remove(fwPath)
  17. info, err := os.Stat(fwPath)
  18. if err != nil {
  19. return err
  20. }
  21. if !info.Mode().IsRegular() {
  22. return fmt.Errorf("固件文件无效: %s", fwPath)
  23. }
  24. if info.Size() <= 0 {
  25. return fmt.Errorf("固件文件为空: %s", fwPath)
  26. }
  27. fwSize := info.Size()
  28. startTime := time.Now()
  29. upgradeOK := false
  30. baseapp.Logger.Warnf("====[ MCU UPGRADE PREPARE ]==== [%s] stop MCU communication", MODULE_NAME)
  31. ModuleExit() // 先退出MCU控制板的通信
  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", fwPath, fwSize)
  37. bytes := ymodem.Send_file(fwPath) // 使用ymodem发送升级文件
  38. if bytes > 0 && bytes == int(fwSize) {
  39. upgradeOK = true
  40. }
  41. if ok := ModuleInit(Board.ExtInfo); !ok { /// 重新打开串口
  42. return errors.New("mcu serial open failed")
  43. }
  44. elapsed := time.Since(startTime)
  45. if !upgradeOK {
  46. baseapp.Logger.Errorf("!!!![ MCU UPGRADE FAILED ]!!!!, written=%dBytes, expect=%dBytes", bytes, fwSize)
  47. return fmt.Errorf("MCU firmware upgrade failed, written=%dBytes, expect=%dBytes", bytes, fwSize)
  48. }
  49. baseapp.Logger.Warnf("====[ MCU UPGRADE SUCCESS ]====, 用时: %v", elapsed) //成功
  50. return nil
  51. }