upgrade_mcu.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. func StartMCUUpgrade() error {
  12. filePath := filepath.Join(baseapp.VAR_DIR, "mcu_firmware.rbl")
  13. defer os.Remove(filePath) //升级完成后删除升级文件
  14. info, err := os.Stat(filePath)
  15. if err != nil {
  16. return err
  17. }
  18. if !info.Mode().IsRegular() {
  19. return fmt.Errorf("固件文件无效: %s", filePath)
  20. }
  21. if info.Size() <= 0 {
  22. return fmt.Errorf("固件文件为空: %s", filePath)
  23. }
  24. fileSize := info.Size()
  25. startTime := time.Now()
  26. upgradeOK := false
  27. baseapp.Logger.Warnf("====[ MCU UPGRADE PREPARE ]==== [%s] stop MCU communication", MODULE_NAME)
  28. ModuleExit() // 先退出MCU控制板的通信
  29. time.Sleep(100 * time.Millisecond) /// 延时等待串口安全关闭
  30. baseapp.Logger.Warnf("##########################################################")
  31. baseapp.Logger.Warnf("############# MCU FIRMWARE UPGRADE START #############")
  32. baseapp.Logger.Warnf("##########################################################")
  33. baseapp.Logger.Warnf("====[ MCU UPGRADE FILE ]====, file=%s, size=%dBytes", filePath, fileSize)
  34. bytes := ymodem.Send_file(filePath) // 使用ymodem发送升级文件
  35. if bytes > 0 && bytes == int(fileSize) {
  36. upgradeOK = true
  37. }
  38. if ok := ModuleInit(Board.ExtInfo); !ok { /// 重新打开串口
  39. return errors.New("mcu serial open failed")
  40. }
  41. elapsed := time.Since(startTime)
  42. if !upgradeOK {
  43. baseapp.Logger.Errorf("!!!![ MCU UPGRADE FAILED ]!!!!, written=%dBytes, expect=%dBytes", bytes, fileSize)
  44. return fmt.Errorf("MCU firmware upgrade failed, written=%dBytes, expect=%dBytes", bytes, fileSize)
  45. }
  46. baseapp.Logger.Warnf("====[ MCU UPGRADE SUCCESS ]====, 用时: %v", elapsed) //成功
  47. return nil
  48. }