v_repExtUniversalRobots.cpp
Go to the documentation of this file.
1 // Copyright 2006-2014 Coppelia Robotics GmbH. All rights reserved.
2 // marc@coppeliarobotics.com
3 // www.coppeliarobotics.com
4 //
5 // -------------------------------------------------------------------
6 // THIS FILE IS DISTRIBUTED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
7 // WARRANTY. THE USER WILL USE IT AT HIS/HER OWN RISK. THE ORIGINAL
8 // AUTHORS AND COPPELIA ROBOTICS GMBH WILL NOT BE LIABLE FOR DATA LOSS,
9 // DAMAGES, LOSS OF PROFITS OR ANY OTHER KIND OF LOSS WHILE USING OR
10 // MISUSING THIS SOFTWARE.
11 //
12 // You are free to use/modify/distribute this file for whatever purpose!
13 // -------------------------------------------------------------------
14 //
15 // This file was automatically created for V-REP release V3.2.0 on Feb. 3rd 2015
16 
17 #include <boost/lexical_cast.hpp>
18 
19 #include "luaFunctionData.h"
22 
23 
24 #ifdef _WIN32
25  #include <shlwapi.h>
26  #pragma comment(lib, "Shlwapi.lib")
27 #endif /* _WIN32 */
28 
29 #if defined (__linux) || defined (__APPLE__)
30  #include <unistd.h>
31  #include <string.h>
32  #define _stricmp(x,y) strcasecmp(x,y)
33 #endif
34 
35 #define PLUGIN_VERSION 1
36 
37 LIBRARY vrepLib; // the V-REP library that we will dynamically load and bind
38 
39 
40 #define CONCAT(x,y,z) x y z
41 #define strConCat(x,y,z) CONCAT(x,y,z)
42 #define LUA_GET_SENSOR_DATA_COMMAND "simExtSkeleton_getSensorData"
43 #define LUA_KUKA_LBR_IIWA_START_COMMAND "simExtUniversalRobotsStart"
44 
45 
46 
47 std::shared_ptr<grl::vrep::UniversalRobotsVrepPlugin> kukaPluginPG;
48 
50  19, // Example Value // Parameter name
51  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint1Handle
52  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint2Handle
53  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint3Handle
54  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint4Handle
55  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint5Handle
56  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint6Handle
57  sim_lua_arg_string,0, // "LBR_iiwa_14_R820_joint1" , // Joint7Handle
58  sim_lua_arg_string,0, // "RobotFlangeTip" , // RobotFlangeTipHandle,
59  sim_lua_arg_string,0, // "RobotMillTip" , // RobotTipHandle,
60  sim_lua_arg_string,0, // "RobotMillTipTarget" , // RobotTargetHandle,
61  sim_lua_arg_string,0, // "Robotiiwa" , // RobotTargetBaseHandle,
62  sim_lua_arg_string,0, // "tcp://0.0.0.0:30010" , // LocalZMQAddress
63  sim_lua_arg_string,0, // "tcp://172.31.1.147:30010", // RemoteZMQAddress
64  sim_lua_arg_string,0, // "192.170.10.100" , // LocalHostKukaKoniUDPAddress,
65  sim_lua_arg_string,0, // "30200" , // LocalHostKukaKoniUDPPort,
66  sim_lua_arg_string,0, // "192.170.10.2" , // RemoteHostKukaKoniUDPAddress,
67  sim_lua_arg_string,0, // "30200" , // RemoteHostKukaKoniUDPPort
68  sim_lua_arg_string,0, // "JAVA" // KukaCommandMode (options are "JAVA", "FRI")
69  sim_lua_arg_string,0, // "IK_Group1_iiwa" // RobotIKGroup
70 };
71 
72 std::string LUA_KUKA_LBR_IIWA_START_CALL_TIP("number result=simExtUniversalRobotsStart(string Joint1Handle , string Joint2Handle , string Joint3Handle , string Joint4Handle , string Joint5Handle , string Joint6Handle , string Joint7Handle , string RobotFlangeTipHandle, string RobotTipHandle, string RobotTargetHandle, string RobotTargetBaseHandle, string LocalZMQAddress, string RemoteZMQAddress, string LocalHostKukaKoniUDPAddress, string LocalHostKukaKoniUDPPort, string RemoteHostKukaKoniUDPAddress, string RemoteHostKukaKoniUDPPort, string KukaCommandMode, string RobotIKGroup) -- KukaCommandMode options are JAVA and FRI");
73 
75 { // the callback function of the new Lua command ("simExtSkeleton_getSensorData")
76  // return Lua Table or arrays containing position, torque, torque minus motor force, timestamp, FRI state
77 
78  try {
79  if (!kukaPluginPG) {
80  BOOST_LOG_TRIVIAL(info) << "Starting UniversalRobots plugin connection to UR hardware\n";
81 
82  CLuaFunctionData data;
83 
85  {
86 
87  std::vector<CLuaFunctionDataItem>* inData=data.getInDataPtr();
88  std::string Joint1Handle (inData->at(0 ).stringData[0]);
89  std::string Joint2Handle (inData->at(1 ).stringData[0]);
90  std::string Joint3Handle (inData->at(2 ).stringData[0]);
91  std::string Joint4Handle (inData->at(3 ).stringData[0]);
92  std::string Joint5Handle (inData->at(4 ).stringData[0]);
93  std::string Joint6Handle (inData->at(5 ).stringData[0]);
94  std::string Joint7Handle (inData->at(6 ).stringData[0]);
95  std::string RobotTipHandle (inData->at(7 ).stringData[0]);
96  std::string RobotFlangeTipHandle (inData->at(8 ).stringData[0]);
97  std::string RobotTargetHandle (inData->at(9 ).stringData[0]);
98  std::string RobotTargetBaseHandle (inData->at(10 ).stringData[0]);
99  std::string LocalZMQAddress (inData->at(11).stringData[0]);
100  std::string RemoteZMQAddress (inData->at(12).stringData[0]);
101  std::string LocalHostKukaKoniUDPAddress (inData->at(13).stringData[0]);
102  std::string LocalHostKukaKoniUDPPort (inData->at(14).stringData[0]);
103  std::string RemoteHostKukaKoniUDPAddress (inData->at(15).stringData[0]);
104  std::string RemoteHostKukaKoniUDPPort (inData->at(16).stringData[0]);
105  std::string KukaCommandMode (inData->at(17).stringData[0]);
106  std::string IKGroupHandle (inData->at(18).stringData[0]);
107 
108 
109  kukaPluginPG=std::make_shared<grl::vrep::UniversalRobotsVrepPlugin>(
110  std::make_tuple(
111  Joint1Handle ,
112  Joint2Handle ,
113  Joint3Handle ,
114  Joint4Handle ,
115  Joint5Handle ,
116  Joint6Handle ,
117  Joint7Handle ,
118  RobotFlangeTipHandle ,
119  RobotTipHandle ,
120  RobotTargetHandle ,
121  RobotTargetBaseHandle ,
122  LocalZMQAddress ,
123  RemoteZMQAddress ,
124  LocalHostKukaKoniUDPAddress ,
125  LocalHostKukaKoniUDPPort ,
126  RemoteHostKukaKoniUDPAddress ,
127  RemoteHostKukaKoniUDPPort ,
128  KukaCommandMode ,
129  IKGroupHandle
130  )
131  );
132  kukaPluginPG->construct();
133  } else {
134  /// @todo report an error?
135  // use default params
136  kukaPluginPG=std::make_shared<grl::vrep::UniversalRobotsVrepPlugin>();
137  kukaPluginPG->construct();
138  }
139 
140 
141 
142 
143  }
144 
145  } catch (const boost::exception& e){
146  // log the error and print it to the screen, don't release the exception
147  std::string initerr("v_repExtUniversalRobots plugin encountered the following error and will disable itself:\n" + boost::diagnostic_information(e));
148  simAddStatusbarMessage( initerr.c_str());
149  BOOST_LOG_TRIVIAL(error) << initerr;
150  kukaPluginPG.reset();
151  } catch (const std::exception& e){
152  // log the error and print it to the screen, don't release the exception
153  std::string initerr("v_repExtUniversalRobots plugin encountered the following error and will disable itself:\n" + boost::diagnostic_information(e));
154  simAddStatusbarMessage( initerr.c_str());
155  BOOST_LOG_TRIVIAL(error) << initerr;
156  kukaPluginPG.reset();
157  } catch (...){
158  // log the error and print it to the screen, don't release the exception
159  std::string initerr("v_repExtUniversalRobots plugin encountered an unknown error and will disable itself. Please debug this issue! file and line:" + std::string(__FILE__) + " " + boost::lexical_cast<std::string>(__LINE__) + "\n");
160  simAddStatusbarMessage( initerr.c_str());
161  BOOST_LOG_TRIVIAL(error) << initerr;
162  kukaPluginPG.reset();
163  }
164 }
165 
166 
167 // This is the plugin start routine (called just once, just after the plugin was loaded):
168 VREP_DLLEXPORT unsigned char v_repStart(void* reservedPointer,int reservedInt)
169 {
170  // Dynamically load and bind V-REP functions:
171  // ******************************************
172  // 1. Figure out this plugin's directory:
173  char curDirAndFile[1024];
174 #ifdef _WIN32
175  GetModuleFileName(NULL,curDirAndFile,1023);
176  PathRemoveFileSpec(curDirAndFile);
177 #elif defined (__linux) || defined (__APPLE__)
178  getcwd(curDirAndFile, sizeof(curDirAndFile));
179 #endif
180  std::string currentDirAndPath(curDirAndFile);
181  // 2. Append the V-REP library's name:
182  std::string temp(currentDirAndPath);
183 #ifdef _WIN32
184  temp+="\\v_rep.dll";
185 #elif defined (__linux)
186  temp+="/libv_rep.so";
187 #elif defined (__APPLE__)
188  temp+="/libv_rep.dylib";
189 #endif /* __linux || __APPLE__ */
190  // 3. Load the V-REP library:
191  vrepLib=loadVrepLibrary(temp.c_str());
192  if (vrepLib==NULL)
193  {
194  BOOST_LOG_TRIVIAL(error) << "Error, could not find or correctly load the V-REP library. Cannot start 'v_repExtUniversalRobots' plugin.\n";
195  return(0); // Means error, V-REP will unload this plugin
196  }
198  {
199  BOOST_LOG_TRIVIAL(error) << "Error, could not find all required functions in the V-REP library. Cannot start 'v_repExtUniversalRobots' plugin.\n";
201  return(0); // Means error, V-REP will unload this plugin
202  }
203  // ******************************************
204 
205  // Check the version of V-REP:
206  // ******************************************
207  int vrepVer;
209  if (vrepVer<20604) // if V-REP version is smaller than 2.06.04
210  {
211  BOOST_LOG_TRIVIAL(error) << "Sorry, your V-REP copy is somewhat old. Cannot start 'v_repExtUniversalRobots' plugin.\n";
213  return(0); // Means error, V-REP will unload this plugin
214  }
215  // ******************************************
216 
217 
218  // Register the new Lua command "simExtSkeleton_getSensorData":
219  // ******************************************
220 
221  std::vector<int> inArgs;
222 
225  (
228  &inArgs[0],
230  );
231 
232 
233 
234  // Expected input arguments are: int sensorIndex, float floatParameters[3], int intParameters[2]
235  //int inArgs_getSensorData[]={3,sim_lua_arg_int,sim_lua_arg_float|sim_lua_arg_table,sim_lua_arg_int|sim_lua_arg_table}; // this says we expect 3 arguments (1 integer, a table of floats, and a table of ints)
236  // Return value can change on the fly, so no need to specify them here, except for the calltip.
237  // Now register the callback:
238  //simRegisterCustomLuaFunction(LUA_GET_SENSOR_DATA_COMMAND,strConCat("number result,table data,number distance=",LUA_GET_SENSOR_DATA_COMMAND,"(number sensorIndex,table_3 floatParams,table_2 intParams)"),inArgs_getSensorData,LUA_GET_SENSOR_DATA_CALLBACK);
239  // ******************************************
240 
241  BOOST_LOG_TRIVIAL(info) << "KUKA LBR iiwa plugin initialized. Build date/time: " << __DATE__ << " " << __TIME__ <<"\n";
242 
243  return(PLUGIN_VERSION); // initialization went fine, we return the version number of this plugin (can be queried with simGetModuleName)
244 }
245 
246 // This is the plugin end routine (called just once, when V-REP is ending, i.e. releasing this plugin):
247 VREP_DLLEXPORT void v_repEnd()
248 {
249  // Here you could handle various clean-up tasks
250 
251  /////////////////////////
252  // PUT OBJECT RESET CODE HERE
253  // close out as necessary
254  ////////////////////
255 
256  kukaPluginPG.reset();
257 
258  unloadVrepLibrary(vrepLib); // release the library
259 }
260 
261 // This is the plugin messaging routine (i.e. V-REP calls this function very often, with various messages):
262 VREP_DLLEXPORT void* v_repMessage(int message,int* auxiliaryData,void* customData,int* replyData)
263 { // This is called quite often. Just watch out for messages/events you want to handle
264  // Keep following 5 lines at the beginning and unchanged:
265  static bool refreshDlgFlag=true;
266  int errorModeSaved;
269  void* retVal=NULL;
270 
271  // Here we can intercept many messages from V-REP (actually callbacks). Only the most important messages are listed here.
272  // For a complete list of messages that you can intercept/react with, search for "sim_message_eventcallback"-type constants
273  // in the V-REP user manual.
274 
275 
277  refreshDlgFlag=true; // V-REP dialogs were refreshed. Maybe a good idea to refresh this plugin's dialog too
278 
280  { // A custom menu bar entry was selected..
281  // here you could make a plugin's main dialog visible/invisible
282  }
283 
285  { // This message is sent each time the scene was rendered (well, shortly after) (very often)
286  // It is important to always correctly react to events in V-REP. This message is the most convenient way to do so:
287 
288  int flags=auxiliaryData[0];
289  bool sceneContentChanged=((flags&(1+2+4+8+16+32+64+256))!=0); // object erased, created, model or scene loaded, und/redo called, instance switched, or object scaled since last sim_message_eventcallback_instancepass message
290  bool instanceSwitched=((flags&64)!=0);
291 
292  if (instanceSwitched)
293  {
294  // React to an instance switch here!!
295  }
296 
297  if (sceneContentChanged)
298  { // we actualize plugin objects for changes in the scene
299  refreshDlgFlag=true; // always a good idea to trigger a refresh of this plugin's dialog here
300  }
301 
302 
303 
304  //...
305  //////////////
306  // PUT MAIN CODE HERE
307 
308  /////////////
309  if (simGetSimulationState() != sim_simulation_advancing_abouttostop) //checks if the simulation is still running
310  {
311  //if(kukaPluginPG) BOOST_LOG_TRIVIAL(info) << "current simulation time:" << simGetSimulationTime() << std::endl; // gets simulation time point
312  }
313  // make sure it is "right" (what does that mean?)
314 
315 
316  // find the v-rep C functions to do the following:
317  ////////////////////////////////////////////////////
318  // Use handles that were found at the "start" of this simulation running
319 
320  // next few Lines get the joint angles, torque, etc from the simulation
321  if (kukaPluginPG)// && kukaPluginPG->allHandlesSet == true // allHandlesSet now handled internally
322  {
323  try
324  {
325  // run one loop synchronizing the arm and plugin
326  kukaPluginPG->run_one();
327 
328  } catch (const boost::exception& e){
329  // log the error and print it to the screen, don't release the exception
330  std::string initerr("v_repExtUniversalRobots plugin encountered the following error and will disable itself:\n" + boost::diagnostic_information(e));
331  simAddStatusbarMessage( initerr.c_str());
332  BOOST_LOG_TRIVIAL(error) << initerr;
333  kukaPluginPG.reset();
334  } catch (const std::exception& e){
335  // log the error and print it to the screen, don't release the exception
336  std::string initerr("v_repExtUniversalRobots plugin encountered the following error and will disable itself:\n" + boost::diagnostic_information(e));
337  simAddStatusbarMessage( initerr.c_str());
338  BOOST_LOG_TRIVIAL(error) << initerr;
339  kukaPluginPG.reset();
340  } catch (...){
341  // log the error and print it to the screen, don't release the exception
342  std::string initerr("v_repExtUniversalRobots plugin encountered an unknown error and will disable itself. Please debug this issue! file and line:" + std::string(__FILE__) + " " + boost::lexical_cast<std::string>(__LINE__) + "\n");
343  simAddStatusbarMessage( initerr.c_str());
344  BOOST_LOG_TRIVIAL(error) << initerr;
345  kukaPluginPG.reset();
346  }
347 
348  }
349  }
350 
352  { // The main script is about to be run (only called while a simulation is running (and not paused!))
353 
354  }
355 
357  { // Simulation is about to start
358 
359  /////////////////////////
360  // PUT OBJECT STARTUP CODE HERE
361  ////////////////////
362  // get the handles to all the objects, joints, etc that we need
363  /////////////////////
364  // simGetObjectHandle
365 
366 // try {
367 // BOOST_LOG_TRIVIAL(info) << "Starting KUKA LBR iiwa plugin connection to Kuka iiwa\n";
368 // kukaPluginPG = std::make_shared<grl::KukaVrepPlugin>();
369 // kukaPluginPG->construct();
370 // //kukaPluginPG->run_one(); // for debugging purposes only
371 // //kukaPluginPG.reset(); // for debugging purposes only
372 // } catch (boost::exception& e){
373 // // log the error and print it to the screen, don't release the exception
374 // std::string initerr("v_repExtUniversalRobots plugin initialization error:\n" + boost::diagnostic_information(e));
375 // simAddStatusbarMessage( initerr.c_str());
376 // BOOST_LOG_TRIVIAL(error) << initerr;
377 // }
378  }
379 
381  { // Simulation just ended
382 
383  /////////////////////////
384  // PUT OBJECT RESET CODE HERE
385  // close out as necessary
386  ////////////////////
387  BOOST_LOG_TRIVIAL(info) << "Ending KUKA LBR iiwa plugin connection to Kuka iiwa\n";
388  kukaPluginPG.reset();
389 
390  }
391 
393  { // A script called simOpenModule (by default the main script). Is only called during simulation.
394  if ( (customData==NULL)||(_stricmp("PluginSkeleton",(char*)customData)==0) ) // is the command also meant for this plugin?
395  {
396  // we arrive here only at the beginning of a simulation
397  }
398  }
399 
401  { // A script called simHandleModule (by default the main script). Is only called during simulation.
402  if ( (customData==NULL)||(_stricmp("PluginSkeleton",(char*)customData)==0) ) // is the command also meant for this plugin?
403  {
404  // we arrive here only while a simulation is running
405  }
406  }
407 
409  { // A script called simCloseModule (by default the main script). Is only called during simulation.
410  if ( (customData==NULL)||(_stricmp("PluginSkeleton",(char*)customData)==0) ) // is the command also meant for this plugin?
411  {
412  // we arrive here only at the end of a simulation
413  }
414  }
415 
417  { // Here the user switched the scene. React to this message in a similar way as you would react to a full
418  // scene content change. In this plugin example, we react to an instance switch by reacting to the
419  // sim_message_eventcallback_instancepass message and checking the bit 6 (64) of the auxiliaryData[0]
420  // (see here above)
421 
422  }
423 
425  { // Here we have a plugin that is broadcasting data (the broadcaster will also receive this data!)
426 
427  }
428 
430  { // The scene is about to be saved. If required do some processing here (e.g. add custom scene data to be serialized with the scene)
431 
432  }
433 
434  // You can add many more messages to handle here
435 
436  if ((message==sim_message_eventcallback_guipass)&&refreshDlgFlag)
437  { // handle refresh of the plugin's dialogs
438  // ...
439  refreshDlgFlag=false;
440  }
441 
442  // Keep following unchanged:
443  simSetIntegerParameter(sim_intparam_error_report_mode,errorModeSaved); // restore previous settings
444  return(retVal);
445 }
446 
int getVrepProcAddresses(LIBRARY lib)
Definition: v_repLib.cpp:672
LIBRARY vrepLib
LIBRARY loadVrepLibrary(const char *pathAndFilename)
Definition: v_repLib.cpp:622
bool readDataFromLua(const SLuaCallBack *p, const int *expectedArguments, int requiredArgumentCount, const char *functionName)
VREP_DLLEXPORT unsigned char v_repStart(void *reservedPointer, int reservedInt)
ptrSimSetIntegerParameter simSetIntegerParameter
Definition: v_repLib.cpp:51
#define LUA_KUKA_LBR_IIWA_START_COMMAND
void LUA_SIM_EXT_KUKA_LBR_IIWA_START(SLuaCallBack *p)
VREP_DLLEXPORT void * v_repMessage(int message, int *auxiliaryData, void *customData, int *replyData)
ptrSimGetIntegerParameter simGetIntegerParameter
Definition: v_repLib.cpp:52
void unloadVrepLibrary(LIBRARY lib)
Definition: v_repLib.cpp:641
#define PLUGIN_VERSION
static void getInputDataForFunctionRegistration(const int *dat, std::vector< int > &outDat)
ptrSimRegisterCustomLuaFunction simRegisterCustomLuaFunction
Definition: v_repLib.cpp:208
std::shared_ptr< grl::vrep::UniversalRobotsVrepPlugin > kukaPluginPG
std::string LUA_KUKA_LBR_IIWA_START_CALL_TIP("number result=simExtUniversalRobotsStart(string Joint1Handle , string Joint2Handle , string Joint3Handle , string Joint4Handle , string Joint5Handle , string Joint6Handle , string Joint7Handle , string RobotFlangeTipHandle, string RobotTipHandle, string RobotTargetHandle, string RobotTargetBaseHandle, string LocalZMQAddress, string RemoteZMQAddress, string LocalHostKukaKoniUDPAddress, string LocalHostKukaKoniUDPPort, string RemoteHostKukaKoniUDPAddress, string RemoteHostKukaKoniUDPPort, string KukaCommandMode, string RobotIKGroup) -- KukaCommandMode options are JAVA and FRI")
const int inArgs_KUKA_LBR_IIWA_START[]
ptrSimGetSimulationState simGetSimulationState
Definition: v_repLib.cpp:106
std::vector< CLuaFunctionDataItem > * getInDataPtr()
VREP_DLLEXPORT void v_repEnd()
ptrSimAddStatusbarMessage simAddStatusbarMessage
Definition: v_repLib.cpp:117