// 获取按钮和状态元素
const forwardBtn = document.getElementById('forwardBtn');
const backwardBtn = document.getElementById('backwardBtn');
const status = document.getElementById('status');

// 实际控制函数
function controlMotor(direction) {
    status.innerHTML = `<p>正在${direction === 'forward' ? '前进' : '后退'}...</p>`;
    
    // 发送AJAX请求到后端服务器
    fetch('/control', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ direction: direction })
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            status.innerHTML = `<p>${data.message}</p>`;
        } else {
            status.innerHTML = `<p>错误: ${data.message}</p>`;
        }
    })
    .catch(error => {
        status.innerHTML = `<p>通信错误: ${error.message}</p>`;
    });
}

// 按钮点击事件
forwardBtn.addEventListener('click', () => {
    controlMotor('forward');
});

backwardBtn.addEventListener('click', () => {
    controlMotor('backward');
});