Robotics StackExchange | Archived questions

how to operate simulation in gazebo through virtual keyboard via ros?

i have build a keyboard with tkinter & python with 4 buttons and i want to operate my simulation through that keys i want to modify teleoptwistkeyboard will attche files below

keyboard.py

#!/usr/bin/python3

#
#
##################################################
######## Please Don't Remove Author Name #########
############### Thanks ###########################
##################################################
#
#
__author__='Kuldeep Wadaskar'

######################################################

######################################################
Kuldeep Wadaskar, 3NOT ROBOTICS PVT LTd,
www.3notrobotics.in

######################################################


# import modules
try:
    import Tkinter
except:
    import tkinter as Tkinter

import pyautogui

keys =[ 
[
# =========================================
# ===== Keyboard Configurations ===========
# =========================================

 [
  # Layout Name
  ("Function_Keys"),

  # Layout Frame Pack arguments
  ({'side':'top','expand':'yes','fill':'both'}),
  [
   # list of Keys
   ('esc'," ", 'F1', 'F2','F3','F4',"",'F5','F6','F7','F8',"",'F9','F10','F11','F12')
  ]
 ],

 [
  ("Character_Keys"),
  ({'side':'top','expand':'yes','fill':'both'}),
  [
   ('~\n`','!\n1','@\n2','#\n3','$\n4','%\n5','^\n6','&\n7','*\n8','(\n9',')\n0','_\n-','+\n=','|\n\\','backspace'),
   ('tab','q','w','e','r','t','y','u','i','o','p','{\n[','}\n]','   '),
   ('capslock','a','s','d','f','g','h','j','k','l',':\n;',"\"\n'","enter"),
   ("shift",'z','x','c','v','b','n','m','<\n,','>\n.','?\n/',"shift"),
   ("ctrl", "[+]",'alt','\t\tspace\t\t','alt','[+]','[=]','ctrl')
  ]
 ]
],
[
 [
  ("System_Keys"),
  ({'side':'top','expand':'yes','fill':'both'}),
  [
   (
    "print\nscreen\nsys",
    "scroll\nlock",
    "pause\nbreak"
   )
  ]
 ],
 [
  ("Editing_Keys"),
  ({'side':'top','expand':'yes','fill':'both'}),
  [
   (
    "insert",
    "home",
    "page\nup"
    ),
   ( "delete",
    "end",
    "page\ndown"
    ),
  ]
 ],

 [
  ("Navigation_Keys"),
  ({'side':'top','expand':'yes','fill':'both'}),
  [
   (
    "up",
    ),
   ( "right",
    "down",
    "left"
    ),
  ]
 ],

],
[

 [
  ("Numeric_Keys"),
  ({'side':'top','expand':'yes','fill':'both'}),
  [
   ("num\nlock","/","*","-"),
   ("7","8","9","+"),
   ("4","5","6"," "),
   ("0","1","2","3"),
   ("0",".","enter")
  ]
 ],

]

]

##  Frame Class
class Keyboard(Tkinter.Frame):
 def __init__(self, *args, **kwargs):
  Tkinter.Frame.__init__(self, *args, **kwargs)

  # Function For Creating Buttons
  self.create_frames_and_buttons()

 # Function For Extracting Data From KeyBoard Table
 # and then provide us a well looking
 # keyboard gui
 def create_frames_and_buttons(self):
  # take section one by one
  for key_section in keys:
   # create Sperate Frame For Every Section
   store_section = Tkinter.Frame(self)
   store_section.pack(side='left',expand='yes',fill='both',padx=10,pady=10,ipadx=10,ipady=10)

   for layer_name, layer_properties, layer_keys in key_section:
    store_layer = Tkinter.LabelFrame(store_section)#, text=layer_name)
    #store_layer.pack(side='top',expand='yes',fill='both')
    store_layer.pack(layer_properties)
    for key_bunch in layer_keys:
     store_key_frame = Tkinter.Frame(store_layer)
     store_key_frame.pack(side='top',expand='yes',fill='both')
     for k in key_bunch:
      k=k.capitalize()
      if len(k)<=3:
       store_button = Tkinter.Button(store_key_frame, text=k, width=2, height=2)
      else:
       store_button = Tkinter.Button(store_key_frame, text=k.center(5,' '), height=2)
      if " " in k:
       store_button['state']='disable'
      #flat, groove, raised, ridge, solid, or sunken
      store_button['relief']="sunken"
      store_button['bg']="powderblue"
      store_button['command']=lambda q=k: self.button_command(q)
      store_button.pack(side='left',fill='both',expand='yes')
  return

  # Function For Detecting Pressed Keyword.
 def button_command(self, event):
  print (event)
  return

# Creating Main Window
def main():
 root = Tkinter.Tk(className=" Python Virtual KeyBoard")
 Keyboard(root).pack()
 root.mainloop()
 return

# Function Trigger
if __name__=='__main__':
 main()

teleoptwistkeyboard.py

#!/usr/bin/env python

from __future__ import print_function

import roslib; roslib.load_manifest('teleop_twist_keyboard')
import rospy

from geometry_msgs.msg import Twist

import sys, select, termios, tty

msg = """
Reading from the keyboard  and Publishing to Twist!
---------------------------
Moving around:
   u    i    o
   j    k    l
   m    ,    .

For Holonomic mode (strafing), hold down the shift key:
---------------------------
   U    I    O
   J    K    L
   M    <    >

t : up (+z)
b : down (-z)

anything else : stop

q/z : increase/decrease max speeds by 10%
w/x : increase/decrease only linear speed by 10%
e/c : increase/decrease only angular speed by 10%

CTRL-C to quit
"""

moveBindings = {
        'i':(1,0,0,0),
        'o':(1,0,0,-1),
        'j':(0,0,0,1),
        'l':(0,0,0,-1),
        'u':(1,0,0,1),
        ',':(-1,0,0,0),
        '.':(-1,0,0,1),
        'm':(-1,0,0,-1),
        'O':(1,-1,0,0),
        'I':(1,0,0,0),
        'J':(0,1,0,0),
        'L':(0,-1,0,0),
        'U':(1,1,0,0),
        '<':(-1,0,0,0),
        '>':(-1,-1,0,0),
        'M':(-1,1,0,0),
        't':(0,0,1,0),
        'b':(0,0,-1,0),
    }

speedBindings={
        'q':(1.1,1.1),
        'z':(.9,.9),
        'w':(1.1,1),
        'x':(.9,1),
        'e':(1,1.1),
        'c':(1,.9),
    }

def getKey():
    tty.setraw(sys.stdin.fileno())
    select.select([sys.stdin], [], [], 0)
    key = sys.stdin.read(1)
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
    return key


def vels(speed,turn):
    return "currently:\tspeed %s\tturn %s " % (speed,turn)

if __name__=="__main__":
    settings = termios.tcgetattr(sys.stdin)

    pub = rospy.Publisher('cmd_vel', Twist, queue_size = 1)
    rospy.init_node('teleop_twist_keyboard')

    speed = rospy.get_param("~speed", 0.5)
    turn = rospy.get_param("~turn", 1.0)
    x = 0
    y = 0
    z = 0
    th = 0
    status = 0

    try:
        print(msg)
        print(vels(speed,turn))
        while(1):
            key = getKey()
            if key in moveBindings.keys():
                x = moveBindings[key][0]
                y = moveBindings[key][1]
                z = moveBindings[key][2]
                th = moveBindings[key][3]
            elif key in speedBindings.keys():
                speed = speed * speedBindings[key][0]
                turn = turn * speedBindings[key][1]

                print(vels(speed,turn))
                if (status == 14):
                    print(msg)
                status = (status + 1) % 15
            else:
                x = 0
                y = 0
                z = 0
                th = 0
                if (key == '\x03'):
                    break

            twist = Twist()
            twist.linear.x = x*speed; twist.linear.y = y*speed; twist.linear.z = z*speed;
            twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = th*turn
            pub.publish(twist)

    except Exception as e:
        print(e)

    finally:
        twist = Twist()
        twist.linear.x = 0; twist.linear.y = 0; twist.linear.z = 0
        twist.angular.x = 0; twist.angular.y = 0; twist.angular.z = 0
        pub.publish(twist)

        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)

Asked by kuldeep on 2019-09-09 13:05:06 UTC

Comments

Answers