| PST SDK 6.0.0.0-272350a

listener.py
1 """Listener example of the PST SDK
2
3 This example shows how to implement the PST SDK using the Tracker class
4 and how to receive data by implementing the Listener class. The example
5 initializes the PST Tracker and grabs 100 data points.
6
7 In order to be able to run this example, the PST Tracker has to be initialized first.
8 This can be done by starting the PST-Server and the PST-Client application and making
9 sure the calibration files have been downloaded and a tracking target is available.
10 The tracking target can be the default Reference target or a newly trained or imported
11 target. For more information, please see the Initialization section of the PST SDK manual
12 or check the PST Manual.
13
14 Copyright PS-Tech B.V. All Rights Reserved.
15 """
16 import context
17 import time
18 import sys
19 import pstech.pstsdk.tracker as pst
20 import pstech.pstsdk.errors as psterrors
21
22 # Control variable for main loop
23 running = True
24
25 # Number of data points to grab before application termination
26 max_samples = 100
27
28 # Global number of samples
29 samples = 0
30
31 # Flag for signaling tracker restart
32 restart = False
33
34 """Helper function for clear printing of 4x4 matrices."""
35 def print_matrix(matrix):
36 idx = 0
37 for y in range(4):
38 for x in range(4):
39 print(str(matrix[x + y * 4]), end="\t")
40 print("")
41 print("\n")
42
43 """Implementation of the pst.Listener class to receive tracking data and mode changes."""
44 class MyListener(pst.Listener):
45
46 """Implementation of a tracker data callback function
47
48 Implementation of a tracker data callback function. The on_tracker_data
49 function receives the data as soon as it becomes available and prints the
50 tracking target pose to the command line.
51
52 Args:
53 tracker_data: Object containing tracking information retrieved from tracker
54 status_message: Status message reported by the tracker.
55
56 See Also:
57 pstech.pstdk.trackerdata.TrackerData
58 pstech.pstsdk.errors.EStatusMessage
59 """
60 def on_tracker_data(self, tracker_data, status_message):
61 global samples
62 global running
63
64 if samples >= max_samples:
65 running = False
66
67 if len(tracker_data.targetlist) > 0:
68 for target_pose in tracker_data.targetlist:
69 print("Pose for " + target_pose.name)
70 print_matrix(target_pose.pose)
71
72 samples += 1
73
74 """Implementation of a tracker mode callback function
75
76 Implementation of a tracker mode callback function. The on_tracker_mode
77 function receives any mode update as soon as it become available and prints it.
78
79 Args:
80 mode: Current mode reported by the tracker.
81
82 See Also:
83 pstech.pstsdk.tracker.ETrackerMode
84 """
85 def on_tracker_mode(self, mode):
86 global restart
87 if mode == pst.ETrackerMode.MODE_TRACKING:
88 print("Tracker tracking")
89 elif mode == pst.ETrackerMode.MODE_LOWPOWER:
90 print("Tracker paused")
91 elif mode == pst.ETrackerMode.MODE_DISCONNECT:
92 print("Tracker disconnected")
93 elif mode == pst.ETrackerMode.MODE_RECONNECT:
94 print("Tracker reconnected")
95 restart = True
96 else:
97 print("Mode " + str(mode))
98
99 """Helper function to register the exit handler with the application"""
100 def register_exit_handler():
101 if sys.platform.startswith("linux"):
102 import signal
103 signal.signal(signal.SIGTERM, exit_handler)
104 signal.signal(signal.SIGHUP, exit_handler)
105 signal.signal(signal.SIGQUIT, exit_handler)
106 signal.signal(signal.SIGINT, exit_handler)
107 elif sys.platform.startswith("win"):
108 import win32api
109 win32api.SetConsoleCtrlHandler(exit_handler, True)
110
111 """Implement the exit handler to shut-down the PST Tracker connection on application termination."""
112 def exit_handler(*args):
113 global running
114 pst.Tracker.shutdown()
115 running = False
116 return True
117
118 def main():
119 if(len(sys.argv) < 2):
120 print("\nConfiguration Error: A camera configuration file needs to be specified. This file can be found in the Redist folder of your installation. "
121 "See the documentation of the Python bindings for more information.")
122 exit(0)
123
124 # Register exit_handler for proper shutdown
125 register_exit_handler()
126
127 try:
128 # Use Context Manager to prevent improper Tracker shutdown on errors.
129 # Create an instance of the Tracker object using the default configuration path and file names.
130 with pst.Tracker("", "","", sys.argv[1]) as tracker:
131
132 # Check if calibration information is available for all cameras. When this is not the case, provide a warning and exit.
133 if(len(tracker.get_uncalibrated_camera_urls()) > 0):
134 print("\nNo calibration information could be found in the configuration directory.\n"
135 "Please use the PST Server and PST Client application to initialize the PST Tracker and create/import a tracking target.\n"
136 "More information can be found in the Initialization section of the PST SDK manual and the PST Manual.\n"
137 )
138 sys.exit()
139
140 # Print version number of the tracker server being used.
141 print("Running PST Server version " + tracker.get_version_info())
142
143 # Create listener with callback functions for data and/or mode updates.
144 listener = MyListener()
145
146 # Register the listener object to the tracker server.
147 tracker.add_tracker_listener(listener)
148
149 print("Put the Reference card in front of the PST in order to see tracking results.\n")
150
151 # Start the tracker server.
152 tracker.start()
153
154 # Perform a system check to see if the tracker server is running OK and print the result.
155 print("System check: " + str(tracker.system_check()))
156
157 # Set the frame rate to 30 Hz.
158 tracker.set_framerate(30)
159
160 # Print the new frame rate to see if it was set correctly. Note that for PST HD and Pico
161 # trackers the frame rate actually being set can differ from the value provided to Tracker.set_framerate().
162 print("Frame rate set to: " + str(tracker.get_framerate()))
163
164 # Main loop, wait for auto-termination.
165 while running:
166 # If tracker has reconnected, restart it.
167 global restart
168 if restart:
169 tracker.start()
170 restart = False
171
172 time.sleep(0.1)
173
174 except psterrors.TrackerError as err:
175 # Catch TrackerError and print error messages.
176 print(err.message)
177
178 if __name__ == "__main__":
179 main()