SMACC2
keyboard_server_node.py
Go to the documentation of this file.
1#!/bin/env python3
2
3# Copyright 2021 RobosoftAI Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import sys
18import select
19import termios
20import tty
21
22import rclpy
23from rclpy.node import Node
24
25from std_msgs.msg import UInt16
26
27settings = termios.tcgetattr(sys.stdin)
28
29
30def getKey():
31 global settings
32 tty.setraw(sys.stdin.fileno())
33 select.select([sys.stdin], [], [], 0)
34 key = sys.stdin.read(1)
35 termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
36 return key
37
38
40 def __init__(self):
41 super().__init__("keyboard_node")
42 self.pub = self.create_publisher(UInt16, "keyboard_unicode", 1)
43 timer_period = 0.20 # seconds
44 self.timer = self.create_timer(timer_period, self.timer_update)
45 self.i = 0
46
47 def timer_update(self):
48 try:
49 key = getKey()
50 # rospy.loginfo(type(key))
51 msg = UInt16()
52 msg.data = ord(key)
53
54 self.pub.publish(msg)
55
56 except Exception as e:
57 print(e)
58
59 finally:
60 termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
61
62
63def main(args=None):
64 rclpy.init(args=args)
65
66 node = KeyboardPublisher()
67
68 rclpy.spin(node)
69
70 # Destroy the node explicitly
71 # (optional - otherwise it will be done automatically
72 # when the garbage collector destroys the node object)
73 node.destroy_node()
74 rclpy.shutdown()
75
76
77if __name__ == "__main__":
78 main()
79
80
81# ---------------------------------
82
83# import std_msgs
84#
85
86
87# class KeyboardPublisher(Node):
88# def __init__(self):
89# super().__init__('keyboard_node')
90# self.pub = self.create_publisher(UInt16, 'keyboard_unicode', 1)
91# timer_period = 0.20 # seconds
92# self.timer = self.create_timer(timer_period, self.timer_update)
93# self.i = 0
94
95# def timer_update(self):
96# try:
97# key = getKey()
98# #rospy.loginfo(type(key))
99# msg = UInt16()
100# msg.data = ord(key)
101
102# self.pub.publish(msg)
103
104# except Exception as e:
105# print(e)
106
107# finally:
108# termios.tcsetattr(sys.stdin, termios.TCSADRAIN, settings)
109
110# def main(args=None):
111# rclpy.init(args=args)
112# node = KeyboardPublisher()
113
114# rclpy.spin(node)
115
116# node.destroy_node()
117# rclpy.shutdown()
118
119
120# if __name__ == '__main__':
121# main()