张世豪
8 天以前 de75ec84e295c3f952a200897aa22aa73d7d5867
src/zhuye/Shouye.java
@@ -15,7 +15,10 @@
import dikuai.Dikuaiguanli;
import dikuai.addzhangaiwu;
import gecaoji.Device;
import gecaoji.Gecaoji;
import gecaoji.MowerBoundaryChecker;
import set.Sets;
import set.debug;
import udpdell.UDPServer;
import zhangaiwu.AddDikuai;
import yaokong.Control04;
@@ -64,7 +67,7 @@
   private JLabel mowerSpeedValueLabel;
   private JLabel mowerSpeedUnitLabel;
   private JLabel mowingProgressLabel;
   private FixQualityIndicator fixQualityIndicator;
   private gpszhuangtai fixQualityIndicator;
   // 导航按钮
   private JButton homeNavBtn;
@@ -88,10 +91,20 @@
   private Sets settingsDialog;
   private BaseStation baseStation;
   private final Consumer<String> serialLineListener = line -> SwingUtilities.invokeLater(this::updateDataPacketCountLabel);
   // 地图渲染器
   private MapRenderer mapRenderer;
   private final Consumer<String> serialLineListener = line -> {
      SwingUtilities.invokeLater(() -> {
         updateDataPacketCountLabel();
         // 如果收到$GNGGA数据,立即更新拖尾
         if (line != null && line.trim().startsWith("$GNGGA")) {
            if (mapRenderer != null) {
               mapRenderer.forceUpdateIdleMowerTrail();
            }
         }
      });
   };
   private static final int FLOAT_ICON_SIZE = 32;
   private JButton endDrawingButton;
   private JButton drawingPauseButton;
@@ -205,15 +218,46 @@
               SwingUtilities.invokeLater(() -> {
                  Shouye.this.checkIdentifiersAndPromptIfNeeded();
                  Shouye.this.showInitialMowerSelfCheckDialogIfNeeded();
                  // 设置窗口关闭监听器,在关闭时保存缩放比例
                  setupWindowCloseListener();
               });
            }
         }
      };
      addHierarchyListener(listener);
   }
   /**
    * 设置窗口关闭监听器,在窗口关闭时保存当前缩放比例
    */
   private void setupWindowCloseListener() {
      Window window = SwingUtilities.getWindowAncestor(this);
      if (window != null && window instanceof JFrame) {
         JFrame frame = (JFrame) window;
         frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
               // 保存当前缩放比例
               saveCurrentScale();
            }
         });
      }
   }
   /**
    * 保存当前地图缩放比例到配置文件
    */
   public void saveCurrentScale() {
      if (mapRenderer != null) {
         double currentScale = mapRenderer.getScale();
         Setsys setsys = new Setsys();
         setsys.updateProperty("mapScale", String.valueOf(currentScale));
      }
   }
   private void showInitialMowerSelfCheckDialogIfNeeded() {
      zijian.showInitialPromptIfNeeded(this, this::showRemoteControlDialog);
      // 已移除进入主页时的自检提示(按用户要求删除)
      // 以前这里会调用 zijian.showInitialPromptIfNeeded(...) 展示自检对话框,现已禁用。
   }
   private void applyIdleTrailDurationFromSettings() {
@@ -348,6 +392,37 @@
      // 可视化区域 - 使用MapRenderer进行绘制
      visualizationPanel = new JPanel() {
         private ImageIcon gecaojiIcon = null;
         private static final int GECAOJI_ICON_X = 37;
         private static final int GECAOJI_ICON_Y = 10;
         private static final int GECAOJI_ICON_SIZE = 20;
         {
            // 加载割草机图标,大小20x20像素
            gecaojiIcon = loadScaledIcon("image/gecaoji.png", GECAOJI_ICON_SIZE, GECAOJI_ICON_SIZE);
            // 启用工具提示
            setToolTipText("");
         }
         /**
          * 检查鼠标位置是否在割草机图标区域内
          */
         private boolean isMouseOnGecaojiIcon(Point mousePoint) {
            return mousePoint.x >= GECAOJI_ICON_X &&
                   mousePoint.x <= GECAOJI_ICON_X + GECAOJI_ICON_SIZE &&
                   mousePoint.y >= GECAOJI_ICON_Y &&
                   mousePoint.y <= GECAOJI_ICON_Y + GECAOJI_ICON_SIZE;
         }
         @Override
         public String getToolTipText(MouseEvent event) {
            // 如果鼠标在割草机图标区域内,显示提示文字
            if (isMouseOnGecaojiIcon(event.getPoint())) {
               return "以割草机为中心";
            }
            return super.getToolTipText(event);
         }
         @Override
         protected void paintComponent(Graphics g) {
            super.paintComponent(g);
@@ -355,14 +430,48 @@
            if (mapRenderer != null) {
               mapRenderer.renderMap(g);
            }
            // 在地图左上角绘制割草机图标
            // 水平方向与速度指示器对齐(x=37)
            // 垂直方向与卫星状态图标对齐(y=10,速度指示器面板顶部边距10像素,使图标中心对齐)
            if (gecaojiIcon != null) {
               g.drawImage(gecaojiIcon.getImage(), GECAOJI_ICON_X, GECAOJI_ICON_Y, null);
            }
         }
      };
      visualizationPanel.setLayout(new BorderLayout());
      // 添加鼠标点击监听器,检测是否点击了割草机图标
      visualizationPanel.addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isLeftMouseButton(e)) {
               Point clickPoint = e.getPoint();
               // 检查是否点击了割草机图标区域(37, 10, 20, 20)
               if (clickPoint.x >= 37 && clickPoint.x <= 57 &&
                   clickPoint.y >= 10 && clickPoint.y <= 30) {
                  // 点击了割草机图标,将地图视图中心移动到割草机位置
                  if (mapRenderer != null) {
                     Gecaoji mower = mapRenderer.getMower();
                     if (mower != null && mower.hasValidPosition()) {
                        Point2D.Double mowerPosition = mower.getPosition();
                        if (mowerPosition != null) {
                           // 获取当前缩放比例
                           double currentScale = mapRenderer.getScale();
                           // 设置视图变换,使割草机位置对应到屏幕中心
                           // translateX = -mowerX, translateY = -mowerY 可以让割草机在屏幕中心
                           mapRenderer.setViewTransform(currentScale, -mowerPosition.x, -mowerPosition.y);
                        }
                     }
                  }
               }
            }
         }
      });
      JPanel speedIndicatorPanel = createSpeedIndicatorPanel();
      visualizationPanel.add(speedIndicatorPanel, BorderLayout.NORTH);
      // 创建功能按钮面板(放在左上角)
      // 创建功能按钮面板
      JPanel functionButtonsPanel = new JPanel();
      functionButtonsPanel.setLayout(new BoxLayout(functionButtonsPanel, BoxLayout.Y_AXIS));
      functionButtonsPanel.setOpaque(false);
@@ -1125,32 +1234,121 @@
         return;
      }
      if (startButtonShowingPause) {
         if (!zijian.ensureBeforeMowing(this, this::showRemoteControlDialog)) {
            return;
         }
         // 点击开始按钮时不再弹出自检提示(按用户要求删除)
         // 旧逻辑:调用 zijian.ensureBeforeMowing(...) 并在未确认自检时阻止开始
         // 新逻辑:直接允许开始作业
      }
      startButtonShowingPause = !startButtonShowingPause;
      if (!startButtonShowingPause) {
         statusLabel.setText("作业中");
         if (stopButtonActive) {
            stopButtonActive = false;
            updateStopButtonIcon();
         }
         if (!beginMowingSession()) {
         // 检查割草机是否在作业地块边界范围内
         if (!checkMowerInBoundary()) {
            startButtonShowingPause = true;
            statusLabel.setText("待机");
            updateStartButtonAppearance();
            return;
         }
         Control04.sendStartCommandIfDebugSerialOpen();
         statusLabel.setText("作业中");
         if (stopButtonActive) {
            stopButtonActive = false;
            updateStopButtonIcon();
         }
      if (!beginMowingSession()) {
         startButtonShowingPause = true;
         statusLabel.setText("待机");
         updateStartButtonAppearance();
         return;
      }
      } else {
         statusLabel.setText("暂停中");
         pauseMowingSession();
         Control04.sendPauseCommandIfDebugSerialOpen();
      }
      updateStartButtonAppearance();
   }
   /**
    * 检查割草机是否在当前选中的作业地块边界范围内
    * @return 如果割草机在边界内返回true,否则返回false并显示提示
    */
   private boolean checkMowerInBoundary() {
      if (mapRenderer == null) {
         return true; // 如果没有地图渲染器,跳过检查
      }
      // 获取当前边界
      List<Point2D.Double> boundary = mapRenderer.getCurrentBoundary();
      if (boundary == null || boundary.size() < 3) {
         return true; // 如果没有边界或边界点不足,跳过检查
      }
      // 获取割草机位置
      Gecaoji mower = mapRenderer.getMower();
      if (mower == null || !mower.hasValidPosition()) {
         showCustomMessageDialog("无法获取割草机位置,请检查设备连接", "提示");
         return false;
      }
      Point2D.Double mowerPosition = mower.getPosition();
      if (mowerPosition == null) {
         showCustomMessageDialog("无法获取割草机位置,请检查设备连接", "提示");
         return false;
      }
      // 使用 MowerBoundaryChecker 检查是否在边界内
      boolean isInside = MowerBoundaryChecker.isInsideBoundaryPoints(
         boundary,
         mowerPosition.x,
         mowerPosition.y
      );
      if (!isInside) {
         showCustomMessageDialog("请将割草机开到作业地块内然后点击开始作业", "提示");
         return false;
      }
      return true;
   }
   /**
    * 显示自定义消息对话框,使用 buttonset 创建确定按钮
    * @param message 消息内容
    * @param title 对话框标题
    */
   private void showCustomMessageDialog(String message, String title) {
      Window parentWindow = SwingUtilities.getWindowAncestor(this);
      JDialog dialog = new JDialog(parentWindow, title, Dialog.ModalityType.APPLICATION_MODAL);
      dialog.setLayout(new BorderLayout(20, 20));
      dialog.setResizable(false);
      // 内容面板
      JPanel contentPanel = new JPanel(new BorderLayout(0, 15));
      contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 10, 20));
      contentPanel.setBackground(Color.WHITE);
      // 消息标签
      JLabel messageLabel = new JLabel("<html><div style='text-align: center;'>" + message + "</div></html>");
      messageLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
      messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
      contentPanel.add(messageLabel, BorderLayout.CENTER);
      // 按钮面板
      JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
      buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
      buttonPanel.setOpaque(false);
      // 使用 buttonset 创建确定按钮
      JButton okButton = buttonset.createStyledButton("确定", THEME_COLOR);
      okButton.addActionListener(e -> dialog.dispose());
      buttonPanel.add(okButton);
      contentPanel.add(buttonPanel, BorderLayout.SOUTH);
      dialog.add(contentPanel, BorderLayout.CENTER);
      dialog.pack();
      dialog.setLocationRelativeTo(this);
      dialog.setVisible(true);
   }
   private void handleStopAction() {
      if (handheldCaptureInlineUiActive) {
         handleHandheldFinishAction();
@@ -1166,7 +1364,6 @@
         statusLabel.setText("已结束");
         startButtonShowingPause = false;
         stopMowingSession();
         Control04.sendStopCommandIfDebugSerialOpen();
      } else {
         statusLabel.setText("待机");
         startButtonShowingPause = true;
@@ -1458,19 +1655,15 @@
      if (bluetoothBtn == null) {
         return;
      }
      if (Bluelink.isConnected()) {
         Bluelink.disconnect();
         bluetoothConnected = false;
      } else {
         boolean success = Bluelink.connect();
         if (success) {
            bluetoothConnected = true;
         } else {
            bluetoothConnected = false;
            JOptionPane.showMessageDialog(this, "蓝牙连接失败,请重试", "提示", JOptionPane.WARNING_MESSAGE);
         }
      }
      updateBluetoothButtonIcon();
      // 弹出系统调试页面
      showDebugDialog();
   }
   private void showDebugDialog() {
      Window parentWindow = SwingUtilities.getWindowAncestor(this);
      debug debugDialog = new debug(parentWindow, THEME_COLOR);
      debugDialog.setLocationRelativeTo(this); // 居中显示在首页
      debugDialog.setVisible(true);
   }
   private void updateBluetoothButtonIcon() {
@@ -1496,7 +1689,7 @@
      JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
      rightPanel.setOpaque(false);
      fixQualityIndicator = new FixQualityIndicator();
   fixQualityIndicator = new gpszhuangtai(THEME_COLOR);
      fixQualityIndicator.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      fixQualityIndicator.addMouseListener(new MouseAdapter() {
         @Override
@@ -3289,47 +3482,7 @@
      return !"未选择地块".equals(trimmed);
   }
   private final class FixQualityIndicator extends JComponent {
      private static final long serialVersionUID = 1L;
      private static final int DIAMETER = 16;
      private String currentCode;
      private Color currentColor = new Color(160, 160, 160);
      private FixQualityIndicator() {
         setPreferredSize(new Dimension(DIAMETER, DIAMETER));
         setMinimumSize(new Dimension(DIAMETER, DIAMETER));
         setMaximumSize(new Dimension(DIAMETER, DIAMETER));
         setToolTipText("未知");
      }
      private void setQuality(String code) {
         if (Objects.equals(currentCode, code)) {
            return;
         }
         currentCode = code;
         currentColor = resolveFixQualityColor(code);
         setToolTipText(resolveFixQualityDescription(code));
         repaint();
      }
      @Override
      protected void paintComponent(Graphics g) {
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D) g.create();
         try {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            int diameter = Math.min(getWidth(), getHeight()) - 2;
            int x = (getWidth() - diameter) / 2;
            int y = (getHeight() - diameter) / 2;
            g2.setColor(currentColor);
            g2.fillOval(x, y, diameter, diameter);
            g2.setColor(new Color(255, 255, 255, 128));
            g2.drawOval(x, y, diameter, diameter);
         } finally {
            g2.dispose();
         }
      }
   }
   // 测试方法
    public static void main(String[] args) {