示例#1
0
async def client_plotly():

	uname=document.getElementById("uname").value
	psw=document.getElementById("psw").value

	credentials={"password":RR.RobotRaconteurVarValue(psw,"string")}

	try:
		inst=await RRN.AsyncConnectService('rr+ws://128.113.224.144:52222/?service=SmartCam',uname,credentials,None,None)
		Sawyer=await RRN.AsyncConnectService('rr+ws://128.113.224.144:58653?service=sawyer',None,None,None,None)
		UR=await RRN.AsyncConnectService('rr+tcp://128.113.224.144:58652?service=ur_robot',None,None,None,None)
		c_host=await RRN.AsyncConnectService('rr+ws://128.113.224.144:2366?service=Webcam',uname,credentials,None,None)
		c= await c_host.async_get_Webcams(0,None)

		p= await c.FrameStream.AsyncConnect(-1,None)
		global canvas, ctx
		canvas = document.getElementById("image")
		ctx = canvas.getContext("2d")
		print_div("Running!")
		p.PacketReceivedEvent+=new_frame
		c.async_StartStreaming(None)

		#robot state flag
		robot_const = RRN.GetConstants("com.robotraconteur.robotics.robot", Sawyer)
		state_flags_enum = robot_const['RobotStateFlags']

		while True:

			await plot(UR,Sawyer, inst, state_flags_enum)
			# await RRN.AsyncSleep(0.01,None)

	except:
		
		print_div(traceback.format_exc())
		raise
示例#2
0
async def client_matplotlib():

    uname = document.getElementById("uname").value
    psw = document.getElementById("psw").value

    credentials = {"password": RR.RobotRaconteurVarValue(psw, "string")}

    try:
        c_host = await RRN.AsyncConnectService(
            'rr+ws://128.113.224.144:2366?service=Webcam', uname, credentials,
            None, None)
        c = await c_host.async_get_Webcams(0, None)

        p = await c.FrameStream.AsyncConnect(-1, None)

        global canvas, ctx
        canvas = document.getElementById("image")
        ctx = canvas.getContext("2d")

        print_div("Running!")

        while True:

            p.PacketReceivedEvent += new_frame
            c.async_StartStreaming(None)

            await RRN.AsyncSleep(0.01, None)

    except:
        import traceback
        print_div(traceback.format_exc())
        raise
示例#3
0
def render_console(*args):
    """Render console update."""

    try:
        # Run code
        inputs = document.getElementById("__playground-inputs_{}".format(globals()['id_num']))
        results = document.getElementById("__playground-results_{}".format(globals()['id_num']))
        results.innerHTML = live_color_command_formatter(inputs.value)
        scrollingElement = results.querySelector('code')
        scrollingElement.scrollTop = scrollingElement.scrollHeight
    except Exception as e:
        print(e)
async def async_move_to_angles_func():
    global d, num_joints, joint_lower_limits, joint_upper_limits, joint_vel_limits
    global is_jogging

    joint_angles = np.zeros((num_joints, ))
    element_id = "j1_angle_in"

    for j in range(1, num_joints + 1):
        element_id = "j" + str(j) + "_angle_in"
        text_container_angle = document.getElementById(element_id)
        angle = text_container_angle.value  # str and in degrees
        try:  # if not angle == None or not angle == "":
            joint_angles[j - 1] = float(angle) * np.deg2rad(1)
        except:  # else:
            print_div("Please specify angle of each joint!<br>")
            is_jogging = False
            return

    if not (joint_angles < joint_upper_limits).all() or not (
            joint_angles > joint_lower_limits).all():
        print_div("Specified joints are out of range<br>")
        is_jogging = False
        return
    else:
        try:
            await d.async_jog_joint(joint_angles, joint_vel_limits, False,
                                    True, None)
        except:
            print_div("Specified joints might be out of range<br>")

    is_jogging = False
示例#5
0
 def import_data(self):
     reader = FileReader.new()
     def remove_rev(document):
         del document['_rev']
         return document
     def on_recipes_loaded(error, result=None):
         if error:
             console.log('error', error)
         store.load_db()
     def on_plans_loaded(error, result=None):
         if error:
             console.log('error', error)
         meal_plans_store.load_plans()
     def on_lists_loaded(error, result=None):
         if error:
             console.log('error', error)
         list_store.load_list()
     def _import_data(*args):
         value = json.loads(reader.result)
         recipes_db.bulkDocs([remove_rev(recipe) for recipe in value['recipes']], on_recipes_loaded)
         plans_db.bulkDocs([remove_rev(plan) for plan in value['plans']], on_plans_loaded)
         groceries_db.bulkDocs([remove_rev(list) for list in value['groceries']], on_lists_loaded)
     file_input = document.getElementById('import_input')
     for file in file_input.files:
         reader.onload = _import_data
         reader.readAsText(file)
示例#6
0
async def client_webcam():
    # rr+ws : WebSocket connection without encryption
    # url ='rr+ws://localhost:2355?service=Webcam'
    # url ='rr+ws://192.168.1.128:2355?service=Webcam'
    # url ='rr+ws://192.168.43.241:2355?service=Webcam'
    url = 'rr+ws://192.168.50.152:2355?service=Webcam'

    try:
        c_host = await RRN.AsyncConnectService(url, None, None, None, None)
        c = await c_host.async_get_Webcams(0, None)

        p = await c.FrameStream.AsyncConnect(-1, None)

        global canvas, ctx
        canvas = document.getElementById("camera_image")
        ctx = canvas.getContext("2d")
        print_div("Camera is Running!<br>")

        finish_time = 0
        # while True:
        p.PacketReceivedEvent += new_frame

        c.async_StartStreaming(None)

        await RRN.AsyncSleep(0.01, None)
    except:
        import traceback
        print_div(traceback.format_exc())
        raise
def new_frame(pipe_ep):
    global canvas, ctx
    #Loop to get the newest frame
    while (pipe_ep.Available > 0):
        #Receive the packet
        image = pipe_ep.ReceivePacket()
        #Convert the packet to an image and set the global variable

        if (canvas == None):
            canvas = document.getElementById("image")
            ctx = canvas.getContext("2d")

        imageBytes = np.zeros(
            4 * image.width * image.height,
            dtype=np.uint8)  #dtype essential here, IndexSizeError
        for y in range(image.height):

            for x in range(image.width):

                index1 = (x + image.width * y) * 4
                index2 = (x * 3 + image.step * y)
                imageBytes[index1] = image.data[index2 + 2]
                imageBytes[index1 + 1] = image.data[index2 + 1]
                imageBytes[index1 + 2] = image.data[index2]
                imageBytes[index1 + 3] = 255

        image_data = ImageData.new(bytes(imageBytes), image.width,
                                   image.height)
        ctx.putImageData(image_data, 0, 0, 0, 0, 320, 240)
示例#8
0
async def async_select_available_robot_url(robot_urls):
    print_div("Selecting the robot URL.. <br>")
    # Read the selected robot index from the browser  
    element_id = "available_robots"
    available_robots_list = document.getElementById(element_id)
    index = available_robots_list.selectedIndex
    return robot_urls[index]
async def async_go_sel_pose_func():
    global d, num_joints, joint_lower_limits, joint_upper_limits, joint_vel_limits
    global is_jogging

    # Read the selected pose from the browser
    element_id = "saved_poses_list"
    poses_list = document.getElementById(element_id)
    index = poses_list.selectedIndex

    try:
        if index == -1:
            print_div("Please select a pose from Saved Poses.<br>")
            raise
        else:
            sel_pose = poses_list.options[index].value  # angles as str
            joint_angles = np.fromstring(sel_pose, dtype=float,
                                         sep=',') * np.deg2rad(1)  # in rad

            if not (joint_angles < joint_upper_limits).all() or not (
                    joint_angles > joint_lower_limits).all():
                print_div("Specified joints are out of range<br>")
                raise
            else:
                try:
                    await d.async_jog_joint(joint_angles, joint_vel_limits,
                                            False, True, None)
                except:
                    print_div("Specified joints might be out of range<br>")
                    raise
    except:
        is_jogging = False
    is_jogging = False
示例#10
0
def process_pie():
    df = process_input()

    df[df.columns[1]] = pd.to_numeric(df[df.columns[1]])
    df[df.columns[2]] = pd.to_numeric(df[df.columns[2]])
    df[df.columns[3]] = pd.to_numeric(df[df.columns[3]])
    col1 = df[df.columns[1]].values
    col2 = df[df.columns[2]].values
    col3 = df[df.columns[3]].values

    Plotly.plot(document.getElementById('plot1'), [{
        'values': [
            df[df.columns[1]].sum(), df[df.columns[2]].sum(),
            df[df.columns[3]].sum()
        ],
        'labels': [
            df[df.columns[1]].name, df[df.columns[2]].name,
            df[df.columns[3]].name
        ],
        'type':
        'pie'
    }], {
        'height': 350,
        'width': 500
    })
示例#11
0
async def main():
    global client
    client = await RRN.AsyncConnectService(
        "rr+ws://localhost:62354/?service=RestrictedPythonService", None, None,
        None, None)

    run_button = document.getElementById("run_button")
    run_button.onclick = on_run_button_click
示例#12
0
 def get_element(self, name):
     """
     Looks up an HTMLElement created for this figure.
     """
     # TODO: Should we store a reference here instead of always looking it
     # up? I'm a little concerned about weird Python/JS
     # cross-memory-management issues...
     return document.getElementById(self._id + name)
示例#13
0
    def __init__(self, *args, **kwargs):
        backend_agg.FigureCanvasAgg.__init__(self, *args, **kwargs)

        self._idle_scheduled = False
        self._id = "matplotlib_" + hex(id(self))[2:]
        self._title = ''
        self._ratio = 1
        matplotlib_figure_styles = self._add_matplotlib_styles()
        if document.getElementById('matplotlib-figure-styles') is None:
            document.head.appendChild(matplotlib_figure_styles)
示例#14
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self._idle_scheduled = False
        self._id = "matplotlib_" + hex(id(self))[2:]
        self._title = ""
        self._ratio = 1
        matplotlib_figure_styles = self._add_matplotlib_styles()
        if document.getElementById("matplotlib-figure-styles") is None:
            document.head.appendChild(matplotlib_figure_styles)
示例#15
0
async def async_playback_poses_func():
    # Get elements, poses and paramaters from web interface
    poses_list = document.getElementById("saved_poses_list")
    num_loops_elem = document.getElementById("num_loops_in")
    num_loops = int(num_loops_elem.value)
    joint_vel_range = document.getElementById("joint_vel_range")
    joint_vel_ratio = float(joint_vel_range.value)/100.0

    # Time to complete the playback
    time_loops_elem = document.getElementById("time_loops_in")
    t_complete = float(time_loops_elem.value) #seconds

    if poses_list.length >= 4:
        global plugin_savePlayback
        await plugin_savePlayback.async_playback_poses(num_loops, joint_vel_ratio, t_complete, None)
    else:
        print_div("You need at least 4 different points. Add some poses to Saved Poses and try again<br>")

    global is_jogging
    is_jogging = False
示例#16
0
 def create_root_element(self):
     try:
         parent = document.getElementById('imagediv')
         if parent.lastElementChild.tagName == 'DIV':
             parent.lastElementChild.innerHTML = ''
             return parent.lastElementChild
         else:
             newelement = document.createElement("div")
             parent.append(newelement)
             return newelement
     except Exception as e:
         print(e)
         return document.createElement("div")
示例#17
0
def process_scatter():
    df = process_input()
    col1 = df[df.columns[0]].values
    col2 = df[df.columns[1]].values

    Plotly.plot(document.getElementById('plot2'),
                [{
                    'x': col1,
                    'y': col2,
                    'type': 'scatter',
                    'mode': 'markers+lines',
                    'hoverinfo': 'label',
                    'label': 'Zoom Background Interest'
                }])
示例#18
0
def render():
    total = len(STATE['todos'])
    remaining = _remaining()
    completed = total - remaining

    filter = location.hash.replace('#', '')
    if not filter:
        filter = 'all'

    if filter == 'active':
        todos_to_render = [todo for todo in STATE['todos'] if not todo['completed']]
    elif filter == 'completed':
        todos_to_render = [todo for todo in STATE['todos'] if todo['completed']]
    else:
        todos_to_render = STATE['todos']

    todos = []
    for todo in todos_to_render:
        todos.append(render_todo(todo))

    rendered = lys_render((
        L.header('.header') / (
            L.h1 / 'todos',
            L.input('.new-todo', placeholder="What needs to be done?", autoFocus='', onKeyUp=new_todo),
        ),
        L.section('.main') / (
            L.input('#toggle-all.toggle-all', type="checkbox", onChange=toggle_all,
                checked=remaining == 0 and total > 0),
            L.label(htmlFor="toggle-all") / 'Mark all as complete',
        ),
        L.ul('.todo-list') / todos,
        L.footer('.footer') / (
            L.span('.todo-count') / (
                L.strong / f"{remaining} ",
                f"{'item' if remaining == 1 else 'items'} left",
            ),
            L.ul('.filters') / (
                L.li / L.a('.selected' if filter == 'all' else '', href="#") / 'All',
                L.li / L.a('.selected' if filter == 'active' else '', href="#active") / 'Active',
                L.li / L.a('.selected' if filter == 'completed' else '', href="#completed") / 'Completed',
            ),
            (L.button('.clear-completed', onClick=clear_completed) / 'Clear completed') if completed else None,
        ),
    ))

    ReactDOM.render(
      rendered,
      document.getElementById('app')
    );
示例#19
0
async def async_del_sel_pose_func():
    # Read the selected pose index from the browser
    element_id = "saved_poses_list"
    poses_list = document.getElementById(element_id)
    index = poses_list.selectedIndex
    try:
        if index == -1:
            print_div("Please select a pose from Saved Poses.<br>")
        else:
            global plugin_savePlayback
            await plugin_savePlayback.async_del_sel_pose(index,None)
            # Delete from UI too.
            poses_list.remove(index); 
    except:
        pass
示例#20
0
def process_geo_map():
    df = process_input()

    df[df.columns[1]] = pd.to_numeric(df[df.columns[1]])
    df[df.columns[2]] = pd.to_numeric(df[df.columns[2]])

    col1 = df[df.columns[1]].values
    col2 = df[df.columns[2]].values
    col3 = df[df.columns[3]].values
    Plotly.plot(document.getElementById('plot4'), [{
        'type': 'scattergeo',
        'lon': col2,
        'lat': col1,
        'text': col3
    }])
示例#21
0
 def __init__(self, target=None, interval=10, append=True, fly=False):
     target = target or sys.stdout._out
     self.target = document.getElementById(target) if isinstance(
         target, str) else target
     doc = DOMParser.new().parseFromString(
         open_url(self.url).read(), "image/svg+xml")
     self.node = doc.documentElement
     if append:
         self.target.append(self.node)
     else:
         self.target.replaceChildren(self.node)
     self.xoffset, self.yoffset = 0, 0
     self.interval = interval
     if fly:
         self.fly()
示例#22
0
async def async_save_cur_pose_func():
    # Get the current joint angles as ndarray and str
    # _, joints_text = await update_joint_info() # Current Joint angles in radian ndarray, N x 1 and str
    joints_text = await update_joint_info() # Current Joint angles in radian ndarray, N x 1 and str
    joints_text = joints_text[:-1] # Delete the last comma    

    # Add the current joint angles to the saved poses list on web browser UI
    element_id = "saved_poses_list"
    poses_list = document.getElementById(element_id)
    option = document.createElement("option")
    option.text = joints_text
    poses_list.add(option)

    # Save the cur pose to plug in as well
    global plugin_savePlayback
    await plugin_savePlayback.async_save_cur_pose(None)
def save_cur_pose_func(self):
    print_div('Saving to "Saved Poses" list..<br>')

    global d_q  # Get the current joint angles in rad ndarray
    # Convert them into degrees for text view
    joints_text = ""
    for i in d_q:
        joints_text += "%.2f," % (np.rad2deg(i))
    joints_text = joints_text[:-1]  # Delete the last comma

    # Add the current joint angles to the saved poses list
    element_id = "saved_poses_list"
    poses_list = document.getElementById(element_id)
    option = document.createElement("option")
    option.text = joints_text
    poses_list.add(option)
示例#24
0
def process_3d_maps():
    df = process_input()

    col0 = df[df.columns[0]].values
    col1 = df[df.columns[1]].values
    col2 = df[df.columns[2]].values
    col3 = df[df.columns[3]].values
    col4 = df[df.columns[4]].values
    col5 = df[df.columns[5]].values

    Plotly.plot(document.getElementById('plot6'), [{
        'x': col0,
        'y': col1,
        'z': col2,
        'mode': 'markers',
        'marker': {
            'size': 12,
            'line': {
                'color': 'rgba(217, 217, 217, 0.14)',
                'width': 0.5
            },
            'opacity': 0.8
        },
        'type': 'scatter3d'
    }, {
        'x': col3,
        'y': col4,
        'z': col5,
        'mode': 'markers',
        'marker': {
            'color': 'rgb(127, 127, 127)',
            'size': 12,
            'symbol': 'circle',
            'line': {
                'color': 'rgb(204, 204, 204)',
                'width': 1
            },
            'opacity': 0.8
        },
        'type': 'scatter3d'
    }], {'margin': {
        'l': 0,
        'r': 0,
        'b': 0,
        't': 0
    }})
示例#25
0
async def async_down_sel_pose_func():
    # Read the selected pose index from the browser
    element_id = "saved_poses_list"
    poses_list = document.getElementById(element_id)
    index = poses_list.selectedIndex
    try:
        if index == -1:
            print_div("Please select a pose from Saved Poses.<br>")
        else:
            global plugin_savePlayback
            await plugin_savePlayback.async_down_sel_pose(index,None)
            # Down it from UI too.
            if index < poses_list.length-1:
                option = poses_list.options[index];
                poses_list.remove(index);
                poses_list.add(option,index+1)

    except:
        pass
示例#26
0
def process_input():
    """
    Get data and set the header - return array 
    """
    rows = []
    file_data = document.getElementById("output").textContent
    logging.info(file_data)

    csv_reader = csv.reader(file_data.splitlines())
    for row in csv_reader:
        logging.info(row)
        rows.append(row)

    df = pd.DataFrame(data=rows)
    set_header = df.iloc[0]
    df = df[1:]
    df.columns = set_header
    logging.info(df)
    return df
示例#27
0
    def write(element_id, value, append=False, exec_id=0):
        """Writes value to the element with id "element_id"""
        console.log(f"APPENDING: {append} ==> {element_id} --> {value}")
        if append:
            child = document.createElement('div');
            element = document.querySelector(f'#{element_id}');
            if not element:
                return
            exec_id = exec_id or element.childElementCount + 1
            element_id = child.id = f"{element_id}-{exec_id}";
            element.appendChild(child);

        element = document.getElementById(element_id)
        html, mime_type = format_mime(value)
        if mime_type in ('application/javascript', 'text/html'):
            scriptEl = document.createRange().createContextualFragment(html)
            element.appendChild(scriptEl)
        else:
            element.innerHTML = html
示例#28
0
def process_heat_maps():
    df = process_input()

    df[df.columns[0]] = pd.to_numeric(df[df.columns[0]])
    df[df.columns[1]] = pd.to_numeric(df[df.columns[1]])
    df[df.columns[2]] = pd.to_numeric(df[df.columns[2]])

    col0 = df[df.columns[0]].values
    col1 = df[df.columns[1]].values
    col2 = df[df.columns[2]].values
    col3 = df[df.columns[3]].values
    col4 = df[df.columns[4]].values

    Plotly.plot(document.getElementById('plot5'), [{
        'z': [col0, col1, col2],
        'x': col3,
        'y': col4,
        'type': 'heatmap',
        'hoverongaps': 'false'
    }])
示例#29
0
async def async_move_to_angles_func():
    global is_jogging
    global plugin_jogJointSpace

    joint_angles = np.zeros((7,))
    element_id = "j1_angle_in"
    
    for j in range(1,7+1):
        element_id = "j" + str(j) + "_angle_in"
        text_container_angle = document.getElementById(element_id)
        angle = text_container_angle.value # str and in degrees
        try: # if not angle == None or not angle == "":
            joint_angles[j-1] = float(angle)* np.deg2rad(1)
        except: # else:
            print_div("Please specify angle of each joint!<br>")
            is_jogging = False
            return

    await plugin_jogJointSpace.async_jog_joints_to_angles(joint_angles,None)

    is_jogging = False
示例#30
0
def new_frame(pipe_ep):
	global canvas, ctx
	#Loop to get the newest frame
	while (pipe_ep.Available > 0):
		#Receive the packet
		image=pipe_ep.ReceivePacket()
		#Convert the packet to an image and set the global variable
		
		if (canvas == None):
			canvas = document.getElementById("image")
			ctx = canvas.getContext("2d")
		
		imageBytes=np.zeros(4*image.width*image.height, dtype=np.uint8)		#dtype essential here, IndexSizeError
		imageBytes[3::4] = 255
		imageBytes[0::4] = image.data[2::3]
		imageBytes[1::4] = image.data[1::3]
		imageBytes[2::4] = image.data[0::3]


		image_data=ImageData.new(bytes(imageBytes),image.width,image.height)
		ctx.putImageData(image_data, 0, 0,0,0,320,240)