"""
Episode1 虚拟机械臂 SDK  ⚠️ 这是仿真版，控制的是网页上的 3D 模型，不是真机
=============================================================================
零依赖：只用 Python 标准库，无需 pip install。
默认连接线上仿真：https://robot.4866.eu.org
接口与官方真机 SDK 一致，学会后可直接换成真机 IP 控制实物。

直接运行：
    python episode_sdk.py

在代码里调用：
    from episode_sdk import EpisodeAPP
    robot = EpisodeAPP()                    # 默认连线上，无需参数
    robot.angle_mode([180, 90, 83, 30, 110, 30], 0.5)
    robot.get_motor_angles()

注意：使用前请先在浏览器打开 https://robot.4866.eu.org ，
      页面上的 3D 机械臂会同步显示你的指令动作。
"""

import json
import urllib.request
import urllib.error

DEFAULT_URL = 'https://robot.4866.eu.org'


class EpisodeAPP:
    """虚拟机械臂客户端（接口与官方 SDK 一致，默认连线上仿真）"""

    def __init__(self, url=DEFAULT_URL, timeout=15):
        """
        url: 仿真服务地址，默认 https://robot.4866.eu.org
             本机开发可传 http://localhost:8080
        """
        self.url = url.rstrip('/')
        self.timeout = timeout

    def send_command(self, action, params=None):
        """底层通信：HTTP POST 到 /api/command（走 443，无需开其他端口）"""
        req = urllib.request.Request(
            self.url + '/api/command',
            data=json.dumps({'action': action, 'params': params}).encode('utf-8'),
            headers={'Content-Type': 'application/json'},
            method='POST',
        )
        try:
            with urllib.request.urlopen(req, timeout=self.timeout) as resp:
                data = json.loads(resp.read().decode('utf-8'))
                return data.get('result') if data.get('ok') else None
        except Exception as e:
            print('\n' + '=' * 56)
            print('[连接失败] 无法连接到虚拟机械臂服务')
            print('=' * 56)
            print(f'  地址: {self.url}')
            print(f'  原因: {e}')
            print('\n  请先做这两步：')
            print('  1. 用浏览器打开  https://robot.4866.eu.org')
            print('  2. 确认页面右上角显示「服务器运行中」')
            print('\n  页面打开后，重新运行你的代码即可。')
            print('=' * 56 + '\n')
            return None

    # ---------- 运动控制 ----------
    def angle_mode(self, angles, speed_ratio=1.0):
        """6 轴关节角度控制（度），返回预计运动时间（秒）"""
        return self.send_command('angle_mode', [list(angles), speed_ratio])

    def move_xyz_rotation(self, position, orientation, speed_ratio=1.0):
        """末端位置控制：position=[x,y,z](mm)，orientation=[rx,ry,rz](度)"""
        return self.send_command('move_xyz_rotation', [position, orientation, 'zyx', speed_ratio])

    # ---------- 夹爪 / 吸盘 ----------
    def servo_gripper(self, angle):
        """二指夹爪开合：0~110 度，越大越张开"""
        return self.send_command('servo_gripper', angle)

    def gripper_on(self):
        """吸盘吸住"""
        return self.send_command('gripper_on', 1)

    def gripper_off(self):
        """吸盘松开"""
        return self.send_command('gripper_off', 0)

    # ---------- 状态读取 ----------
    def get_motor_angles(self):
        """读取当前 6 个关节角度"""
        return self.send_command('get_motor_angles', None)

    def get_pose(self):
        """读取末端位姿 [x,y,z,rx,ry,rz]"""
        return self.send_command('get_pose', None)

    # ---------- 安全 ----------
    def emergency_stop(self, enable=1):
        """急停(1) / 解除急停(0)"""
        return self.send_command('emergency_stop', enable)

    def set_free_mode(self, enable=1):
        """自由拖动模式"""
        return self.send_command('set_free_mode', enable)


def demo():
    """演示：连接线上虚拟机械臂并做一组动作"""
    import time

    robot = EpisodeAPP()   # 默认连线上，无需配置
    print('连接线上虚拟机械臂: https://robot.4866.eu.org')
    print('（请先确保浏览器已打开该页面）\n')

    angles = robot.get_motor_angles()
    if angles is None:
        return
    print('当前关节角度:', angles)

    print('\n运动到 [90, 45, 120, 60, 80, 20]，速度 0.5 ...')
    duration = robot.angle_mode([90, 45, 120, 60, 80, 20], 0.5)
    print('预计用时:', duration, '秒')
    time.sleep((duration or 1) + 0.5)

    print('运动后角度:', robot.get_motor_angles())

    print('\n回到默认姿态 ...')
    robot.angle_mode([180, 90, 83, 30, 110, 30], 0.5)
    time.sleep(1.5)
    print('完成！去网页看看机械臂的动作吧。')


if __name__ == '__main__':
    demo()
