import json


def cmdmule_command(ser, cmd):
    """Execute a command over the serial port in a running cmdmule.

    Args:
        ser (Serial): Serial port object
        cmd (str): Command to execute

    Returns:
        dict: Dictionary containing returncode, stdout, stderr keys.

    """

    # Write command
    ser.flush_input()
    ser.write(json.dumps(cmd).encode() + b"\n")

    # Read command sent
    ser.readline()
    # Read result
    result = ser.readline()

    # Decode result
    return json.loads(result.strip().decode("ascii", "ignore"))