Extending Mikado Control¶
JavaScript Task¶
The JavaScript Task allows you to execute your own JavaScript/ECMAScript code as a task. In addition to all the functionalities of JavaScript, this task allows direct access to some Mikado variables via predefined modules. The following table provides an overview of the interfaces provided by the modules.
Allows access to the visualization of the task and the setting of follow-up sequences. |
|
Allows read and write access to all Mikado variables. |
|
Allows access to the results of the handle search. |
|
Module for kinematics, collision checking and reachability considerations. |
|
Allows access to product-specific properties. |
|
Access to the status of the robot |
|
Allows access to scene objects such as crates, ROIs and obstacles |
|
Allows access to files |
|
Allows access to Mikado programs |
|
Allows access to Mikado-specific, rarely used but still useful functions. |
|
Allows access to attributes of the point cloud |
Ready-to-use templates for specific use cases are listed here:
General information¶
You can print text to the log console within a JavaScript task using:
console.log("My log message")
Further links to JavaScript in general:
http://doc.qt.io/qt-5/qtqml-javascript-functionlist.html
task¶
The task module can be accessed via the variable task. The status text can be edited via task.status. If task.setNextSequence is set, the sequence with this name is executed next; if the string is empty, the current sequence is continued:
task.status = "Running"
task.setNextSequence("Run to goal")
In case of problems the Mikado program flow can be stopped permanently by calling task.setError("description") or temporarily by calling task.setErrorMightRetry("Beschreibung").
dataStore¶
Variables can be accessed using the dataStore object, using dataStore.data(name) or dataStore.setData(name, value) respectively. See the following sample code:
var a = dataStore.data("a")
a = a + 1
var success = dataStore.setData("a", a)
The function dataStore.setData(name, value) returns true if the value was written successfully. In the event of an error, the return value is false and details of the corresponding error can be found in the log (e.g. in the event of a formatting error).
However, for some variable types (Pose, JointPosition and PoseList), the dataStore.data(name) function returns internal data types. In this case, the dataStore.getJsObject(name) function can be used instead. This returns a JavaScript-typical array or object. It can then be edited directly and, if necessary, written back with dataStore.setJsObject(name, value):
var b = dataStore.getJsObject('einePose')
if (b.x < 0)
b.x = 1.2
dataStore.setJsObject('einePose', b)
var c = dataStore.getJsObject('eineJointPosition')
console.log("J1 ist bei " + c[0])
The dataStore.addVariable(name, type) function can also be used to create new variables. dataStore.setVariableInitialValue(name) causes the current value of the variable to be adopted as the initial value.
picksearch¶
The picksearch module provides access to the results of the pick- and object-search. The following operators are available:
getBestPick¶
Read information about the best known pick at the time of the call. A Start handle search task must have been executed beforehand.
Returns a JavaScript object with the following properties:
All information that is also contained in a
Grasp, see e.g. getLastUsedGraspobjectName(String): Name of the grasped objectobjectPose(Pose): Pose of the grasped object in the world coordinate systemgraspTcpPose(Pose): TCP pose of the grasp in the world coordinate systemgraspTool0Pose(Pose): Tool0 pose of the grasp in the world coordinate systemstartTcpPose(Pose): Start pose of the grasp (see Gripping process)approachTcpPose(Pose): Approach pose of the grasp (see Gripping process)retractTcpPose(Pose): Rectract pose of the grasp (see Gripping process)finalTcpPose(Pose): Final pose of the grasp (see Gripping process)distanceJointSpace(Double): Trajectory distance in joint space
Use: pick = picksearch.getBestPick(timeout)
task.status = ""
// eine Sekunde warten falls noch kein Griff gefunden wurde
var bestPickObj = picksearch.getBestPick(1000)
// Informationen über den besten Griff ausgeben
if (bestPickObj != null) {
task.status = "Object: "+bestPickObj["objectName"]+"\n"
+ "Best pick: "+bestPickObj["graspName"]+"\n"
+ "Category: "+bestPickObj["category"]+"\n"
+ "Distance: "+bestPickObj["distanceJointSpace"]
dataStore.setJsObject("bestObjectPose", bestPickObj["objectPose"])
dataStore.setJsObject("bestPickTcp", bestPickObj["graspTcpPose"])
dataStore.setJsObject("bestPickTool0", bestPickObj["graspTool0Pose"])
dataStore.setJsObject("bestPickStartTcp", bestPickObj["startTcpPose"])
dataStore.setJsObject("bestPickApproachTcp", bestPickObj["approachTcpPose"])
dataStore.setJsObject("bestPickRetractTcp", bestPickObj["retractTcpPose"])
dataStore.setJsObject("bestPickFinalTcp", bestPickObj["finalTcpPose"])
} else {
task.status = "Kein Griff gefunden"
}
getFoundObjectPoses¶
Returns a list of the positions of all objects found.
Optionally accepts the name of a product (productName) and the name of a box (boxName) as arguments to select a specific pick-search. If the function is called without arguments, the last pick-search started is used.
Use without arguments: PoseList = picksearch.getFoundObjectPoses()
// eine Liste aller gefundenen Objekte auslesen und in eine Mikado
// Variable speichern
var foundPoses = picksearch.getFoundObjectPoses()
dataStore.setJsObject("foundPoses", foundPoses)
Use with arguments: PoseList = picksearch.getFoundObjectPoses(String productName, String boxName)
// eine Liste aller gefundenen Objekte einer bestimmten Griffsuche auslesen und in eine Mikado
// Variable speichern
var foundPoses = picksearch.getFoundObjectPoses("productName", "boxName")
dataStore.setJsObject("foundPoses", foundPoses)
setUserBins¶
This function can be used to set a bin-value for each object, which can be used with the user_binning sorting criteria (see Prioritization). The number of entries in the list (bins) must correspond exactly to the number of objects found.
Optionally accepts the name of a product (productName) and the name of a box (boxName) as arguments to select a specific pick-search. If the function is called without arguments, the last pick-search started is used.
Use without arguments: picksearch.setUserBins(IntegerList bins)
// User-Bins setzen ([0, 1, 2, ...]). Die Anzahl der Objekte wird über die Objekt-Liste ausgelesen.
var numObjects = picksearch.getFoundObjectPoses().length
var bins = []
for (var i = 0; i < numObjects; ++i) bins.push(i)
picksearch.setUserBins(bins)
Use with arguments: picksearch.setUserBins(IntegerList bins, String productName, String boxName)
// User-Bins einer bestimmten Griffsuche setzen ([0, 1, 2, ...]). Die Anzahl der Objekte wird über die Objekt-Liste ausgelesen.
var numObjects = picksearch.getFoundObjectPoses("productName", "boxName").length
var bins = []
for (var i = 0; i < numObjects; ++i) bins.push(i)
picksearch.setUserBins(bins, "productName", "boxName")
getSucceededPicks¶
Returns a list of all previously successful picks. The sorting follows the normal PickSearch criteria.
Optionally accepts the name of a product (productName) and the name of a box (boxName) as arguments to select a specific pick-search. If the function is called without arguments, the last pick-search started is used.
Use without arguments: picks = picksearch.getSucceededPicks()
// Liste aller erfolgreichen Griffe auf der Konsole ausgeben
var picks = picksearch.getSucceededPicks()
for (var i = 0; i < picks.length; ++i) {
console.info( "Object: "+picks[i].objectName+"\n"
+ "grasp: "+picks[i].graspName+"\n"
+ "Category: "+picks[i].category+"\n"
+ "Distance: "+picks[i].distanceJointSpace);
}
Use with arguments: picks = picksearch.getSucceededPicks(String productName, String boxName)
// Liste aller erfolgreichen Griffe auf der Konsole ausgeben
var picks = picksearch.getSucceededPicks("productName", "boxName")
for (var i = 0; i < picks.length; ++i) {
console.info( "Object: "+picks[i].objectName+"\n"
+ "grasp: "+picks[i].graspName+"\n"
+ "Category: "+picks[i].category+"\n"
+ "Distance: "+picks[i].distanceJointSpace);
}
getLastUsedGrasp¶
Read information about the current (last used) grasp. An object must have been picked beforehand with the Pick object task .
Returns a JavaScript object with the following properties:
graspName(String): Name of the graspcategory(String): Grasp category (“Preferred” / “Standard” / “Experimental”)objectToTcpTransform(Pose): TCP pose of the grasp in the local coordinate system of the objectobjectToTool0Transform(Pose): Tool0 pose of the grasp in the local coordinate system of the objectgraspOffset(Pose): Transformation between grasped object and gripper tcpisInwards(Bool): Grasp is inwards (true) oder outwards (false)gripper(String): Name of the gripper used for this grasptcpName(String): Name of the tcp used for this grasp
Use: grasp = picksearch.getLastUsedGrasp()
// Informationen über den aktuellen Griff ausgegeben
var grasp = picksearch.getLastUsedGrasp()
task.status = "Verwendeter Griff: "+grasp["graspName"]+"\n"
+ "Kategorie: "+grasp["category"]+"\n"
rerunPickSearch¶
Rerun a previously started pick-search without repeating the object search. This function is mainly used in applications with several grippers (or TCPs) to calculate picks for different grippers one after the other without having to repeat the object search each time.
Optionally accepts the name of a product (productName) and the name of a box (boxName) as arguments to select a specific pick-search. If the function is called without arguments, the last pick-search started is used.
Use without arguments: Bool = rerunPickSearch()
var success = picksearch.rerunPickSearch()
Use with arguments: Bool = rerunPickSearch(String productName, String boxName)
var success = picksearch.rerunPickSearch("productName", "boxName")
awaitBestPickPerObject¶
Wait until the pick-search is finished and return a list of the best valid pick per object. The returned list contains JavaScript objects with the properties of a Pick, see getBestPick.
Optionally accepts the name of a product (productName) and the name of a box (boxName) as arguments to select a specific pick-search. If the function is called without arguments, the last pick-search started is used.
Use without arguments: GraspList = awaitBestPickPerObject()
var bestPickPerObjectList = picksearch.awaitBestPickPerObject()
Use with arguments: GraspList = awaitBestPickPerObject(String productName, String boxName)
var bestPickPerObjectList = picksearch.awaitBestPickPerObject("productName", "boxName")
kinematics¶
The kinematics module allows access to functions for calculating the forward and backward kinematics. It also provides functions for checking the achievability of a target pose for a given start pose. The following operators are available:
forwardKinematics¶
Calculates the pose of a target link for given joint angles. The pose of “tool0” is calculated by default.
Returns a QMap with the following keys:
success(Bool): Forward kinematics could be solved?result(Pose): Pose of the target link. Is only set if successfully executed.
Usage: Var = forwardKinematics(JointPose, String = "tool0")
// Berechne TCP-Pose zu gegebenen Gelenkwinkeln
var jointPose = dataStore.getJsObject('EineJointPose')
var map = kinematics.forwardKinematics(jointPose, "gripper_tcp")
if (map.success) {
dataStore.setJsObject('Pose_TCP', map.result)
}
inverseKinematics¶
Calculates the robot’s joint angles so that a target link assumes the given pose. By default, “tool0” is used as the target link. Optionally, an initial value can be set for the joint angle optimization.
Returns a QMap with the following keys:
success(Bool): Have errors occurred? The following return values are only set if the execution was successful.ikCollisionFree(Bool): Collision-free solution found?ikSolutionFound(Bool): Solution found?result(JointPose): Gelenkwinkel des Roboters.
Usage: Var = inverseKinematics(Pose, JointPose = [0,0,0,0,0,0], String = "tool0")
// Berechne die Gelenkwinkel zu gegebener TCP-Pose
var tcpPose = dataStore.getJsObject('Pose_TCP')
var map = kinematics.inverseKinematics(tcpPose, [0,0,0,0,0,0] ,"gripper_tcp")
dataStore.setJsObject('JPose_Griff', map.result)
if (!map.ikSolutionFound) {
task.setNextSequence("Griff ist nicht erreichbar")
} elseif (!map.ikCollisionFree) {
task.setNextSequence("Griff ist kollisionsbehaftet")
}
isMovePossible¶
Checks whether a collision-free path can be found from the start pose to the target pose. By default, the current robot pose is used as the start pose. Both the start and target pose must be passed as JointPose. If necessary, use inverseKinematics to convert a pose into a JointPose.
Returns a QMap with the following keys:
success(Bool): Have errors occurred? The following return values are only set if the execution was successful.isPossible(Bool): Collision-free path found?reason(String): Information on why the destination may not be reachable.
Verwendung: Var = isMovePossible(JointPose goal, JointPose start = Var())
var goal = dataStore.getJsObject('EineJointPose')
var start = dataStore.getJsObject('AndereJointPose')
var map = kinematics.isMovePossible(goal, start)
console.log("move possible: " + map.isPossible)
console.log("reason: " + map.reason)
isMovePossibleCartesian¶
Checks whether a Cartesian, collision-free path can be found from the start pose to the target pose. A Cartesian path is the direct line between the start and target pose in Cartesian space. The target pose must be passed as a pose.
The start pose must be transferred as a JointPose. By default, the current robot pose is used as the start pose. If necessary, use inverseKinematics to convert a pose into a JointPose.
Optionally, a target link can be transferred, which is to be moved cartesian to a given pose. By default, “tool0” is used as the target link.
Returns a QMap with the following keys:
success(Bool): Have errors occurred? The following return values are only set if the execution was successful.isPossible(Bool): Collision-free path found?goalJointPosition(JointPosition): last point of trajectory (goal) but only given if isPossible = true (type: JointPosition)reason(String): Information on why the destination may not be reachable.
Verwendung: Var = isMovePossibleCartesian(Pose goal, JointPose start = Var(), String targetLink = "tool0")
// Überprüfen ob sich der Greifer 10cm senkrecht nach unten fahren lässt
var start_pose = dataStore.getJsObject('Pose_TCP')
var start_pose_IK = kinematics.inverseKinematics(start_pose, [0,0,0,0,0,0], "gripper_tcp") // convert to JointPose
dataStore.setJsObject('start_pose_IK', start_pose_IK.result)
var goal_pose = dataStore.getJsObject('Pose_TCP')
goal_pose.z = goal_pose.z - 0.1
var map = kinematics.isMovePossibleCartesian(goal_pose, start_pose_IK.result, "gripper_tcp")
dataStore.setJsObject('goal_pose', map.goalJointPosition)
console.log("move possible: " + map.isPossible)
console.log("reason: " + map.reason)
product¶
The product module provides access to product-specific properties. The following operators are available:
activeProduct¶
Reads or sets the current product. The current product can also be set using the Set active product task.
Usage: String = activeProduct or activeProduct = String
// Setzen des aktiven Produkts
product.activeProduct = "P_1"
// Lesen des aktiven Produkts
task.status = "active product is " + product.activeProduct
getUsedEndEffectorNames¶
For applications with several grippers, this function can be used to query a list of all grippers that are configured for the active product. A gripper is configured for a product on the product page.
Note
This function is not relevant for applications with only one gripper.
Usage: StringList = getUsedEndEffectorNames()
// gibt Liste an angelegten Greifern von aktivem Produkt zurück
var greiferListe = product.getUsedEndEffectorNames()
getGraspOffset¶
Reading the grip pose (or the position of the part in the gripper) of a specific grip for the active product.
Use: Pose = getGraspOffset(String)
// Lese die Pose eines bestimmten Griffs
var graspPos = product.getGraspOffset("Außengriffe | Basisgriff")
task.status = "x: " + graspPos.x + " y: " + graspPos.y + " z: " + graspPos.z
+ " r: " + graspPos.roll + " p: " + graspPos.pitch + " y: " + graspPos.yaw
// Überschreibe die Pose des angehängten Teils
lab.setCurrentGraspOffset(graspPos)
In the example code above, the pose of the “basic handle” is read. The handle definition matching the example code is shown in the screenshot below. The handle pose is then used to overwrite the pose of the currently attached part. This can be useful, for example, if the part is centered in the gripper due to positive locking. See also the example for setCurrentGraspOffset.
Example entries in the handle editor¶
getDimensions¶
Calculates the smallest possible enclosing cuboid for the specified product and returns its dimensions. The orientation is aligned with the product coordinate system (Axis-align Bounding Box AABB). If no product is specified, the dimensions of the active product are calculated.
Returns a QMap with the following keys:
x(Double): Dimension in X-direction of the product coordinate system [m]y(Double): Dimension in Y-direction of the product coordinate system [m]z(Double): Dimension in Z-direction of the product coordinate system [m]
Use: Var = getDimensions(String productName = "")
// Auslesen der aktuellen Produktabmessungen
var dims = product.getDimensions()
task.status = "active product has following dimensions:\nx: " + dims.x + "\ny: " + dims.y + "\nz: " + dims.z
// Auslesen von spezifischen Produktabmessungen
var dims = product.getDimensions("P_1")
task.status = task.status + "\nSpecific product has following dimensions:\nx: " + dims.x + "\ny: " + dims.y + "\nz: " + dims.z
Hint
The product dimensions can also be accessed using the Read out product dimensions task.
getAllProductNames¶
Read out list with all product names of the active product list.
Use: productList = product.getAllProductNames()
var productList = product.getAllProductNames()
// Beispiel: Überprüfe, ob ein bestimmtes Produkt existiert
if(productList.includes("Produkt_1")){
task.status = "Produkt_1 ist vorhanden"
} else {
task.status = "Produkt_1 ist nicht vorhanden"
}
robot¶
getLinkTransform¶
Returns the absolute transformation of a link relative to the world frame based on the target position after all previous tasks have been executed. To read out the actual position without preprocessing, getTF can be used.
Use: pose = robot.getLinkTransform(LinkName):
var pose = robot.getLinkTransform("gripper_tcp")
if (pose.z < 0.1) {
console.log("Greifer ist nahe am Boden")
task.setNextSequence("Abstand gewinnen")
}
readInput¶
Retrieves the value of a robot input or field-bus bit depending on configuration.
Use: value = robot.readInput(Number)
var input = robot.readInput(23)
readOutput¶
Retrieves the value of a robot output or field-bus bit depending on configuration.
Use: value = robot.readOutput(Number)
var output = robot.readOutput(23)
writeOutput¶
Sets the value of a robot output or field-bus bit depending on configuration.
Use: value = robot.writeOutput(Number, Value):
var output = robot.writeOutput(23, true)
getCurrentTipLink¶
Read the name of the currently active TCP. Particularly useful for robot cells with interchangeable grippers, where there are several grippers and therefore several TCPs, but only one of which is active at any one time.
Use: tipLinkName = robot.getCurrentTipLink():
var tipLinkName = robot.getCurrentTipLink()
task.status = "Aktiver TCP: " + tipLinkName
getCurrentEndEffectorGroupName¶
Read the name of the currently active gripper. Particularly useful for robot cells with interchangeable grippers, where there are several grippers, but only one of them is active at any one time.
Use: endEffectorName = robot.getCurrentEndEffectorGroupName():
var endEffectorName = robot.getCurrentEndEffectorGroupName()
task.status = "Aktiver Greifer: " + endEffectorName
isObjectAttached¶
Reads out whether an object is currently attached to the gripper in Mikado, i.e. an object has been gripped. Returns true if an object is attached, otherwise false.
Use: objectAttached = robot.isObjectAttached():
var objectAttached = robot.isObjectAttached()
if(objectAttached) {
task.status = "Objekt am Greifer angehängt"
} else {
task.status = "Kein Objekt am Greifer angehängt"
}
scene¶
getSceneObjectDimensions¶
Returns the size of an ROI or the size of the placeholder (default size) for an obstacle or a box. The size of a mesh/CAD is not taken into account.
Use: size = scene.getSceneObjectDimensions(Name)
var size = scene.getSceneObjectDimensions("ROI1")
console.log("ROI1 ist "+size.x+" * "+size.y+" * "+size.z+" [m] groß")
setSceneObjectDimensions¶
Changes back the size of an ROI or the size of the placeholder (default size) for an obstacle or a box. The size/scaling of a mesh/CAD is not changed.
Verwendung: scene.setSceneObjectDimensions(Name, valueX, valueY, valueZ):
var size = scene.getSceneObjectDimensions("ROI1")
scene.setSceneObjectDimensions("ROI1", size.x, size.y, 0.23)
getSceneObjectPose¶
Returns the pose of a scene object (in meters and radians).
Use: Pose = scene.getSceneObjectPose(Name):
var pose = scene.getSceneObjectPose("ROI1")
console.log("ROI1 ist bei x: "+pose.x+" y: "+pose.y+" z: "+pose.z+" roll: "+pose.roll+" pitch: "+pose.pitch+" yaw: "+pose.yaw)
setSceneObjectPose¶
Sets the position of a scene object.
Usage: scene.setSceneObjectPose(Name, Pose):
var pose = scene.getSceneObjectPose("ROI1")
console.log("ROI1 ist bei x: "+pose.x+" y: "+pose.y+" z: "+pose.z+" roll: "+pose.roll+" pitch: "+pose.pitch+" yaw: "+pose.yaw)
pose.z += 0.1
scene.setSceneObjectPose("ROI1", pose)
roiContainsPoint¶
Check whether a point in three-dimensional space lies within a specific ROI. name is the name of the ROI to be checked. The coordinates x, y and z must be passed in meters as a unit. Returns true if the point is within the ROI, otherwise false.
Use: scene.setSceneObjectDimensions(name, x, y, z):
var pose = dataStore.getJsObject('einePose')
var result = scene.roiContainsPoint("ROI", pose.x, pose.y, pose.z)
if(result){
task.status = "Punkt liegt innerhalb der ROI"
} else {
task.status = "Punkt liegt außerhalb der ROI"
}
file¶
The file module provides access to text files. The following operators are available:
readCsvAsDict¶
This function reads in a text file in CSV format. It returns a JavaScript dictonary (keys/values). The first column is used as key, the remaining columns are returned as list.
The very first line is ignored as it typically contains a table header comment.
Relative file names are interpreted with respect to the cell directory.
Usage: dict = file.readCsvAsDict(filename, separator)
//path aus der Variablen „output_folder“ laden
var path = dataStore.data("ausgabe_ordner")
var filename = path + "test.csv"
var dict = file.readCsvAsDict(filename, ";");
console.log("JS Dictionary Ausgabe: " + JSON.stringify(dict));
task.status = "Wert für Produkt 1: "+dict["Produkt1"][0]
In this example the file test.csv is read from a configurable folder (Mikado Variable ausgabe_ordner). The first parameter (column) after the name is printed to the Task status.
program¶
The JavaScript program module provides access to Mikado programs. The following functions are available:
save¶
Save the current Mikado program. This function can be used, for example, to automatically save changes to initial values of variables during program execution so that they are retained even after the application is restarted. An error is triggered if saving fails.
Use: program.save()
lab¶
The JavaScript Lab provides access to rarely used but nevertheless useful functions. The following operators are available:
invertPose¶
Inverts a Pose.
Use: Pose = invertPose(Pose)
var pose = dataStore.getJsObject('einePose')
var pose_inv = lab.invertPose(pose)
getPoseDistanceTrans¶
Calculates the Euclidean distance between the positions of two poses.
Use: Double = getPoseDistanceTrans(Pose, Pose)
var pose1 = dataStore.getJsObject('einePose')
var pose2 = dataStore.getJsObject('anderePose')
var Abstand = lab.getPoseDistanceTrans(pose1, pose2)
getPoseDistanceRot¶
Calculates the relative rotation between the orientations of two poses.
Use: Double = getPoseDistanceRed(Pose, Pose)
var pose1 = dataStore.getJsObject('einePose')
var pose2 = dataStore.getJsObject('anderePose')
var Verdrehung = lab.getPoseDistanceRot(pose1, pose2)
getPoseDifference¶
Calculates the difference between two poses according to the following scheme, where \(R_i\) describes the rotational component and \(t_i\) the translational component of the pose \(i\):
Use: Pose = getPoseDifference(Pose, Pose)
var pose1 = dataStore.getJsObject('einePose')
var pose2 = dataStore.getJsObject('anderePose')
var poseDiff = lab.getPoseDifference(pose1, pose2)
dataStore.setJsObject("poseDiff", poseDiff)
getPoseRotAxis¶
Calculates the angular deviation between the z-axis of a pose with the rotation component \(R\) and the z-axis of the global coordinate system:
By default, the angular deviation from the z-axis is calculated. By adding a second parameter, the operator can also be used to calculate the deviation from the x or y axis.
Use: Double = getPoseRotAxis(Pose, String = "Z")
var pose1 = dataStore.getJsObject('einePose')
var zRotOffset = lab.getPoseRotAxis(pose1)
var xRotOffset = lab.getPoseRotAxis(pose1, "X")
// überprüfen ob Teil aufrecht gegriffen werden kann
var Teilpose = dataStore.getJsObject("Teilpose")
var rot_z = 180/Math.PI*lab.getPoseRotAxis(Teilpose, "Z")
var TeilAufrecht = (rot_z < 10) ? true : false // Abweichung kleiner als 10 deg?
dataStore.setData("TeilAufrecht", TeilAufrecht)
task.status = "TeilAufrecht: " + TeilAufrecht
writeStringToFile¶
Writes a string to a file.
Verwendung: Bool = writeStringToFile(String outputFilePath, String fileContent, Bool appendToExisting = false)
// save data
var append = false // überschreibt Datei, falls false
var path = dataStore.data("Ausgabe_Ordner")
var content = "Test Output"
var filename = path + "test.csv"
lab.writeStringToFile(filename, content, append)
console.log("JS Auswertung: AUSGABE nach: " + filename)
getCurrentDateTime¶
Returns the current time.
Use: String = getCurrentDateTime()
var dateTime = lab.getCurrentDateTime() // dateTime = <YYYY>-<MM>-<DD>T<hh>:<mm>:<ss>
getPoseAsJson¶
Converts the given pose into Json format so that it can be used in NxTreeEdit, for example.
Use: String = getPoseAsJson(Pose)
var pose1 = dataStore.getJsObject('einePose')
var poseAsJson = lab.getPoseAsJson(pose1)
console.log("Json Darstellung:\n" + poseAsJson)
getTF¶
Calculates the transformation between two Urdf objects. Urdf objects are defined in Cell geometry.
Usage: Pose = getTF(String originFrameName, String goalFrameName)
var tool0_zu_gripperTcp = lab.getTF('tool0', 'gripper_tcp')
dataStore.setJsObject("tool0_zu_gripperTcp", tool0_zu_gripperTcp)
sendRobotCommand¶
Sends an R3 command to the connected robot.
Warning
Only works with Mitsubishi robots.
Use: String = sendRobotCommand(String)
var response = lab.sendRobotCommand('1;1;OVRD=25') // setze Geschwindigkeit auf 25%
getRobotVelocityScaling¶
Reads out the currently used speed scaling for the robot’s path planning.
Use: Double = getRobotVelocityScaling()
var velocityScaling = lab.getRobotVelocityScaling()
setRobotVelocityScaling¶
Sets the velocity scaling for the robot’s path planning, see Speed settings for details.
Use: setRobotVelocityScaling(Double)
lab.setRobotVelocityScaling(0.4) // setze Geschwindigkeit-Skalierung auf 40%
getRobotAccelerationScaling¶
Reads out the currently used acceleration scaling for the robot’s path planning.
Use: Double = getRobotAccelerationScaling()
var accScaling = lab.getRobotAccelerationScaling()
setRobotAccelerationScaling¶
Sets the acceleration scaling for the robot’s path planning, see Speed settings for details.
Usage: setRobotAccelerationScaling(Double)
lab.setRobotAccelerationScaling(0.4) // setze Beschleunigungs-Skalierung auf 40%
getCurrentGraspName¶
Reads the name of the last handle used. The names of the handles are displayed in the Handle inspection and are derived from the Gripping poses of a product. If the pick poses are named in the same way, the handle name can be used to draw conclusions about the position of the part in the picker.
Use: String = getCurrentGraspName()
var name = lab.getCurrentGraspName();
var drehung = 0.0
if (name.includes("180 gedreht")) {
drehung = 180.
}
dataStore.setData("Var_Drehwinkel", drehung);
dataStore.setData("Var_GraspName", name);
task.status = "CurrentGraspName = " + name + " Var_Drehwinkel = " + dataStore.data("Var_Drehwinkel")
getCurrentGraspOffset¶
Reads the pose representation of the transformation matrix from attached part to handle point (see Details for description of the position of the handle point) of the last used handle.
See also getCurrentGraspPieceToToolTransform for the transformation from the attached part to Tool0.
In the following example, the position of a part in the gripper is analyzed. The situation shown in the figure below is considered. The coordinate system (red, green, blue corresponds to x, y, z) of the gripper TCP and the part is shown. For the depositing process of the part, we are interested in the orientation of the part in the gripper. In the case shown, the z-axis of the part can point either in the positive or negative y-direction of the gripper TCP. This results from the definition of the ‘gripper_tcp’ (see Mikado Key-Links) and the grips created for the product (part). In our example, both axes point in opposite directions. The following sample code provides the desired result.
Use: Pose = getCurrentGraspOffset()
// Check ob die z-Achse des momentan gegriffenen Teils in positive y-Richtung des TCP zeigt
// Transformation von Teil zu Griffpunkt
var part_T_grasp = lab.getCurrentGraspOffset()
// Translation null setzen -> "verschiebt" Teil in Griffpunkt
part_T_grasp.x = 0
part_T_grasp.y = 0
part_T_grasp.z = 0
// mit Einheitsvektor Z multiplizieren
var zDir = lab.mult(part_T_grasp, [0,0,1]) // (part)e_z = (part)T_(grasp) * (grasp)e_z
var aligned = (zDir[1] > 0) // Vergleich mit der Y-Achse des Griffpunkts
task.status = "z-Achse Teil und y-Achse TCP zeigen in die gleiche Richtung?: " + aligned
Illustration of the example for the analysis of the currently accessed part¶
Details¶
The following sketch illustrates the position of the grip point:
Sketch of the position of the grip point¶
The grasp point transformation \(^{\mathrm{part}}T_{\mathrm{grasp}}\) describes the relative position of the attached part to the grasp point. It should be noted here that there is a \(y\) flip \(^{\mathrm{tcp}}T_{\mathrm{grasp}}\) between the reference system TCP and the reference system grasp:
setCurrentGraspOffset¶
Overwrites the transformation matrix from attached part to handle point (see Details).
This can be useful if the physical position of the part in the gripper deviates from the modeled position. This deviation can be caused, for example, by an integrated centering device or form fit of the gripper used. Or also due to inaccuracies in the object recognition and consequently in the gripping process. The actual position of the part in the gripper can, for example, be determined by an additional camera image (“grip check”).
This operator can be used to update the model representation and subsequent tasks such as Move part to change their behavior accordingly.
See also getCurrentGraspOffset for the corresponding read function.
Note
This operator only has an effect if a part is currently in the gripper.
Note
The collision check and path planning only uses the new position of the part in the gripper from this JavaScript task onwards. If there are still jobs in the robot action queue at the time this task is executed, these were planned with the old part position. The corrected part position is not taken into account retroactively for trips that have already been planned.
Use: bool = setCurrentGraspOffset(Pose)
// Transformation von Teil zu Grasp
var part_T_grasp = lab.getCurrentGraspOffset()
// Nick null setzen -> Teil-Koordinatensystem wird an TCP-Koordinaten System ausgerichtet
part_T_grasp.pitch = 0
// aktualisiere Pose des gegriffenen Teils
lab.setCurrentGraspOffset(part_T_grasp)
In the figure below, the gripper is centered by positive locking, i.e. it can be assumed that each gripped part is aligned with the gripper fingers (left image). However, since the part was approached slightly tilted with the gripped part, this tilting is also taken into account in the model representation (middle image). This leads to a significant deviation between the model and the actual scene. To correct this deviation, the model representation can be updated by applying the example code above (see right image).
Positive fit results from gripper and part geometry¶ |
Initial situation¶ |
Situation after using the |
If the position of the gripped part in the world coordinate system is known, for example by using the Find object task, the position of the attached part in the gripper can be readjusted using the following transformation:
The following JavaScript example demonstrates the readjustment of the gripped part using the return of the Find object task:
// create the y-flip transformation
var yFlip = lab.getTF("world_frame", "world_frame") // get a random pose object
yFlip.x = 0
yFlip.y = 0
yFlip.z = 0
yFlip.roll = 0
yFlip.pitch = 3.14159 // 180 deg
yFlip.yaw = 0
// get match position
var matches = dataStore.getJsObject("Pose_im_Greifer") // PoseList as returned by FindObject Task
if (matches.length != 1) {
task.status = "Expected exactly 1 match, but got " + matches.length
}
var world_T_match = matches[0]
// transform to tcp coordinate frame
var tcp_T_world = lab.getTF("gripper_tcp", "world_frame")
var tcp_T_match = lab.mult(tcp_T_world, world_T_match)
// compare to model
var part_T_grasp = lab.getCurrentGraspOffset()
var grasp_T_part = lab.invertPose(part_T_grasp)
var tcp_T_part = lab.mult(yFlip, grasp_T_part) // respect the transformation between grasp and tcp
var dist_trans = lab.getPoseDistanceTrans(tcp_T_part, tcp_T_match)
var dist_rot = lab.getPoseDistanceRot(tcp_T_part, tcp_T_match)
task.status = "Distance model -> match is: trans: " + Math.round(dist_trans *1000 * 100) / 100 + "mm, rot: " + Math.round(dist_rot* 180/3.14159 * 100) / 100 + "deg"
+ "\ntcp_T_match: " + "\nx: " + tcp_T_match.x*1000 + "\ny: " + tcp_T_match.y*1000 + "\nz: " + tcp_T_match.z*1000
+ "\nr: " + tcp_T_match.roll + "\np: " + tcp_T_match.pitch + "\ny: " + tcp_T_match.yaw
// set current Grasp Offset
var match_T_tcp = lab.invertPose(tcp_T_match)
var match_T_grasp = lab.mult(match_T_tcp, yFlip)
lab.setCurrentGraspOffset(match_T_grasp)
getCurrentGraspPieceToToolTransform¶
Calculates the transformation between the currently gripped part and tool0.
See also getCurrentGraspOffset for the transformation from the appended part to the TCP.
Use: Pose = getCurrentGraspPieceToToolTransform()
var pieceToToolTF = lab.getCurrentGraspPieceToToolTransform()
// Pose könnte per Feldbus-Schnittstelle an SPS übertragen werden
mult¶
Multiplies the transformation representation of a pose by the transformation representation of a pose or a 3D vector.
Use: [Pose, Vector3] = mult(Pose, [Pose, Vector3])
// Pose mit Vector multiplizieren
var pose = dataStore.getJsObject('einePose')
var vec = lab.mult(pose, [1,0,0])
console.log(vec)
// Pose mit Pose multiplizieren
var pose2 = dataStore.getJsObject('anderePose')
var pose_res = lab.mult(pose, pose2)
console.log(pose_res.x, pose_res.y, pose_res.z, pose_res.roll, pose_res.pitch, pose_res.yaw)
The following illustration shows an example of the analysis of a found object. The coordinate system (red, green, blue corresponds to x, y, z) of the world and the part is shown. The following example code indicates whether the z-axis of the part and the x-axis of the world point in the same direction (in the example shown, both axes point in the same direction).
Illustration of the example for analyzing a found part¶
Example: Examine parts pose
// Check ob die z-Achse des gefundenen Teils in positive x-Richtung der Welt zeigt
// Transformation von TCP zum Teil
// Annahme Teilepose 'currentMatch' wurde vorher mit dem Task "Finde Objekt" ermittelt
var pose_worldToPart = dataStore.getJsObject("currentMatch");
// Translation null setzen -> "verschiebt" Teil in Ursprung von Welt
pose_worldToPart.x = 0
pose_worldToPart.y = 0
pose_worldToPart.z = 0
// mit Einheitsvektor Z multiplizieren
var zDir = lab.mult(pose_tcpToPart, [0,0,1]) // (world)e_z = (world)T_(part) * (part)e_z
// Ergebnis ist Z-Richtung des Teils beschrieben im Welt-KOS
var aligned = (zDir[0] > 0) // Vergleich mit der X-Achse der Welt
task.status = "z-Achse Teil und x-Achse Welt zeigen in die gleiche Richtung?: " + aligned
clearAllRecognizedObjects¶
Deletes all objects found from the collision world. After calling this operator, a completely new search is started despite the “Reuse previous matches” flag being activated (see also Halcon-specific object recognition parameters).
Verwendung: Bool = clearAllRecognizedObjects()
var success = lab.clearAllRecognizedObjects()
updateOctomap¶
Calculates and publishes the octomap from the current point cloud. It can therefore be used for collision checking during placing, for example. The optional parameter waitUntilUpdateReceived specifies whether the call should block.
Use: Bool = updateOctomap(Bool waitUntilUpdateReceived=True)
var success = lab.updateOctomap()
setSceneObjectDimension¶
Sets the default size of a scene object. Scene objects can be Obstacle, Region of Interest (ROI) or Box.
Verwendung: Bool = setSceneObjectDimension(String sceneObjectName, Double x, Double y, Double z)
// Anpassen der Größe einer ROI
var pose = dataStore.getJsObject('ROI_Dimensions')
var success = lab.setSceneObjectDimension('ROI_Bildaufnahme', pose.x, pose.y, pose.z)
callExtensionService¶
Can be used to call a ROS Service Call of type mikado_extension_msgs::RunExtensionBasic and wait for the results. The service could be implemented in Python and can be used to implement project specific functionality.
Use: dict = lab.callExtensionService(String name)
result = lab.callExtensionService("/screw_check/check")
if (result.success)
task.status = "Check erfolgreich"
else
task.status = "Check gescheitert. Fehler: "+result.msg
setGetJsonFromCamera¶
This function can be used to write and/or read directly into the variable tree of the nxLib (nxTreeEdit) of an Ensenso camera. It can be used, for example, to read or change parameters or to execute actions of the nxLib directly via the /command node.
Equivalent to the procedure in the Halcon task ensenso_set_get_json.
Use: String = setGetJsonFromCamera(String camera, String setJson, String getPath)
// Setze die Eigenschaft "Test/abc" auf den Wert "123"
task.setGetJsonFromCamera("Ensenso_Camera_0", "{"Test":{"abc": "123"}}", "")
// Lese die Eigenschaft "Version" des NxTree
string version = task.setGetJsonFromCamera("Ensenso_Camera_0", "", "/Version")
pointCloud¶
getXyzMinMax¶
This function allows access to the properties of the point cloud. It provides its minimum and maximum X, Y and Z values as well as the number of points. If an ROI is active, the output refers to the selected ROI.
The function can be used, among other things, to check whether a crate has been completely emptied. Another use case would be to place parts back into the crate depending on the filling level by calculating a discharge height depending on the maximum height determined.
Returns an object with the following keys:
x_min` (``Double): Minimum in X-direction of the product coordinate system [m]x_max(Double): Maximum in X-direction of the product coordinate system [m]y_min(Double): Minimum in Y-direction of the product coordinate system [m]y_max(Double): Maximum in Y-direction of the product coordinate system [m]z_min(Double): Minimum in Z-direction of the product coordinate system [m]z_max(Double): Maximum in Z-direction of the product coordinate system [m]number_points(Integer): Number of points of the point cloud (in the active ROI)
Use: pointCloud = getXyzMinMax()
// Berechne Eigenschaften der aktuellen (ROI-)Punktwolke
var pointCloudInfo = pointCloud.getXyzMinMax()
// Informationen über Punktwolke ausgeben
console.log(JSON.stringify(pointCloudInfo))
// Zähle Punkte in ROI zur Überprüfung ob sich Bauteil darin befindet
var punkteInROI = pointCloudInfo.number_points
if (punkteInROI < 100) { // Durch Rauschen kann es vorkommen, dass sich vereinzelt Punkte in der ROI befinden.
var ablageFrei = true // Die Überprüfung "punkteInROI == 0" wäre somit fehleranfällig.
} else {
var ablageFrei = false
}
// Schreibe Wert in Mikado Variable "ablage_frei"
dataStore.setData("ablage_frei", ablageFrei)
console.log(task.status = "Ablage ist frei: " + ablageFrei)
The example above checks whether there are points in the active ROI. If yes, the position is considered occupied, if not, the position is free.
Halcon Script Task¶
The Halcon image processing library from MVTec Software GmbH makes it possible to develop your own image processing algorithms in a Halcon-specific script language. If user-defined Halcon scripts are to be added to an application, simple integration can be carried out using the Run Halcon Script task. To do this, you develop your own algorithms in the Halcon development environment, HDevelop. An extension provides the same access to the Mikado system as later in the task. To develop, you need a separate developer license for HDevelop, currently in version 13. If the program developed in this way works satisfactorily, it can now be integrated into a Mikado process via the task Run Halcon Script.
If you would like to implement your own algorithms for object recognition using Halcon, see section User-defined object recognition with Halcon.
The following HDevelop operators are provided by the Mikado extension for HDevelop:
mikado_get_2d_image¶
Read out the last capture of an Ensenso camera integrated in Mikado. Use tasks such as ‘Load camera configuration’ and ‘Record point cloud’ to execute the image capture and then use this Halcon operator to access the capture.
If a monocular camera is connected to Mikado, this command can be used to capture an image. Please note that the function call only triggers a new image at the same time for monocular cameras. Use the ‘CameraTarget’ parameter to transmit the serial number of the camera and thus request the raw or rectified image.
The following table describes the individual parameters of the operator.
Parameter |
Parameter name |
Description |
Example |
|---|---|---|---|
Issue |
Image2D |
The image is stored in this variable after the operator is called |
OutputImage |
Input |
CameraName |
Name of the camera |
'Ensenso_Camera_0' |
CameraTarget |
Right or left camera (Ensenso). Serial number for mono cameras. |
'left', 'right', '4101230815' |
|
ImageType |
Image type |
'raw', 'rectified', 'withOverlay' |
Hint
Examples for using the HDevelop operator:
mikado_get_2d_image(Image2D, 'Ensenso_Camera_0', 'left', 'raw')mikado_get_2d_image(Image2D, 'Ensenso_Fix', 'right', 'raw')mikado_get_2d_image(Image2D, 'Ensenso_Robot', 'left', 'withOverlay')mikado_get_2d_image(Image2D, 'Ensenso_Camera_0', '4101230815', 'raw')
Warning
This operator does not trigger a capture. You must trigger the capture beforehand, e.g. with the task Record point cloud.
mikado_publish_2d_image¶
Publishes a 2D image for display in Mikado. The image, whether grayscale or RGB(A), can then be viewed in the Mikado interface in the right half of the live camera view by selecting it from the list.
The following table describes the individual parameters of the operator.
Parameter |
Parameter name |
Description |
Example |
|---|---|---|---|
Input |
Image2D |
Image to be displayed |
Image2D |
Hint
Examples for using the HDevelop operator:
mikado_publish_2d_image (Image2D)
mikado_get_point_cloud¶
Read out the last point cloud of an Ensenso camera integrated in Mikado. Use tasks like ‘Load camera configuration’ and ‘Record point cloud’ to execute the image capture and then use this Halcon operator to access the capture. As Halcon does not deal well with NaN values, these are set to zero. These can be filtered with the additional output region.
The following table describes the individual parameters of the operator.
Parameter |
Parameter name |
Description |
Example |
|---|---|---|---|
Issue |
ImageX |
The X-component of the point cloud |
OutputX |
ImageY |
The Y-component of the point cloud |
OutputY |
|
ImageZ |
The Z-component of the point cloud |
OutputZ |
|
Region |
Valid points of the point cloud |
ValidRegion |
|
Input |
CameraName |
Name of the camera |
'Ensenso_Camera_0' |
Hint
Examples for using the HDevelop operator:
mikado_get_point_cloud (ImageX, ImageY, ImageZ, ValidRegion, 'Ensenso_Camera_0')
Warning
This operator does not trigger a capture. You must trigger the capture beforehand, e.g. using the Record point cloud task.
mikado_write_variable¶
Set the value of a Mikado variable.
The following table describes the individual parameters of the operator.
Parameter |
Parameter name |
Description |
|---|---|---|
Input |
VariableName |
Name of the variable to be changed |
VariableValueType |
Type of variable |
|
VariableStringValue |
Value of the variable if the variable type is String or StringList |
|
VariableNumericValue |
Value of the variable if the variable type is an integer, bool or double |
All Mikado variable types are listed in the following table. The assignment of which value is used for which variable type is listed in this table together with examples.
Variablentyp |
Writing possible |
Input via VariableStringValue / VariableNumericValue |
Examples |
|---|---|---|---|
Integer |
✓ |
Numeric |
1
42
|
Double |
✓ |
Numeric |
1.1
3.14
|
String |
✓ |
String |
'myValue' |
StringList |
✓ |
String |
['StringListWert1', 'StringListWert2'] |
JointPosition |
– |
||
Pose |
✓ |
Numeric |
Halcon pose, is converted internally into radians and meters |
PoseList |
✓ |
Numeric |
Tuple from Halcon Posen |
Bool |
✓ |
Numeric |
0
1
|
JScript |
– |
Hint
Examples for using the HDevelop operator:
mikado_write_variable('MeineMikadoIntegerVariable', 'Integer', [], 42)mikado_write_variable('MeineMikadoStringVariable', 'String', 'test', [])mikado_write_variable('MeineMikadoStringListVariable', 'StringList', ['test1', 'test2', 'test3'], [])
mikado_read_variable¶
Read out the value of a Mikado variable.
The following table describes the individual parameters of the operator.
Parameter |
Parameter name |
Description |
Examples |
|---|---|---|---|
Input |
VariableName |
Name of the Mikado variable to be read |
'VarName' |
Issue |
VariableValueType |
Type of variable read |
String’, ‘Integer’, … |
VariableStringValue |
Value of the variable as a string |
'myValue', '42',
['StringListWert1', 'StringListWert2']
|
|
VariableNumericValue |
Value of the variable if the Mikado variable had a numeric type |
42, 3.14, 0 |
All Mikado variable types are listed in the following table. The assignment of which value is described for which variable type is listed in this table together with examples.
Variablentyp |
Output via VariableStringValue / VariableNumericValue |
Examples |
|---|---|---|
Integer |
Numeric |
1
42
|
Double |
Numeric |
1.1
3.14
|
String |
String |
'myValue' |
StringList |
String |
['StringListValue_1', 'StringListValue2'] |
JointPosition |
String |
'90.0 0.0 0.0 10.1 90.0 0.0' |
Pose |
String |
'xyz: 0.00 0.10 0.21 rpy: 3.14 0.00 1.65' |
PoseList |
String |
'xyz: 0.00 0.07 0.00 rpy: 0.00 0.00 1.54nxyz: 0.10 0.20 0.30 rpy: 3.14 0.00 0.00' |
Bool |
Numeric |
0
1
|
Hint
Examples for using the HDevelop operator:
mikado_read_variable ('MeineMikadoVariable', VariableValueType, VariableStringValue, VariableNumericValue)mikado_read_variable ('ProduktName', VariableValueType, VariableStringValue, VariableNumericValue)
ensenso_set_get_json¶
This procedure can be used to write and/or read directly into the variable tree of the nxLib of an Ensenso camera. It can be used, for example, to read or change parameters or to execute actions of the NxLib directly via the /command node. This procedure is equivalent to the function call in the JavaScript task setGetJsonFromCamera.
The following table describes the individual parameters of the operator.
Parameter |
Parameter name |
Description |
Examples |
|---|---|---|---|
Input |
CameraName |
Name of the camera |
'Ensenso_Camera_0' |
SetJson |
Json subtree to be written. Empty if necessary. |
'{}', '{“Execute”:{“Aufnahme”: {“Command”: “Capture”}}}' |
|
GetJsonPath |
Path whose json is to be read |
'/Version’, '', '/Execute/Result' |
|
Issue |
SetSuccess |
Was the writing/setting successful? |
true', 'false' |
SetError |
Error message when setting |
'', 'CouldNotInterpretJsonText', … |
|
GetError |
Error message when reading |
“", “ItemInexistent”. |
Hint
Examples for using the HDevelop operator:
ensenso_set_get_json('Ensenso_Camera_0', '', '/Version', SetSuccess, GetValue, SetError, GetError)ensenso_set_get_json('Ensenso_Camera_0', '{"Test":{"abc": "123"}}', '', SetSuccess, GetValue, SetError, GetError)ensenso_set_get_json('Ensenso_Camera_0', '{"Execute":{"Aufnahme": {"Command": "Capture"}}}', '/Execute/Aufnahme/Result/', SetSuccess, GetValue, SetError, GetError)
* valid for N30, N35, N40, N45 and S10
* get size of sensor pixels in microns.
ensenso_set_get_json ('Ensenso_Camera_0', '', \
'/Cameras/205044/Sensor/PixelSize',\
_, PixelSize, SetError, GetError)
S := PixelSize // same for x and y
* get width / height of sensor
ensenso_set_get_json ('Ensenso_Camera_0', '', \
'/Cameras/205044/Sensor/Size',\
_, SensorSize, SetError, GetError)
sensorWidth := SensorSize[0]
sensorHeight := SensorSize[1]
* get rectified camera coordinate system
ensenso_set_get_json ('Ensenso_Camera_0', '', \
'/Cameras/205044/Calibration/Dynamic/Stereo/Left/Camera',\
_, CameraCOS, SetError, GetError)
Fx := CameraCOS[0][0]
Fy := CameraCOS[1][1]
F := Fx*S
gen_cam_par_area_scan_polynomial (F, 0, 0, 0, 0, 0, S, S,\
sensorWidth/2, sensorHeight/2, sensorWidth, sensorHeight,\
CamParams)
User-defined object recognition with Halcon¶
Mikado offers an interface to Halcon (for information on Halcon, see Halcon Script Task) to integrate your own algorithms for object recognition. To integrate your scripts you must
Create an .hdev script that contains the corresponding procedures
Extend the object_recognition.yaml (information about configuration files in section Configuration files) to tell Mikado for which products which script should be called
Hdev script¶
The first prerequisite for your own object recognition is a suitable Hdev script that can be integrated into Mikado. We recommend installing HDevelop directly on the Mikado controller so that you can test directly on the controller and use the Mikado extension.
Define a new program with the following procedures using the development environment for Halcon:
load_modelInput control parameters (product properties)
ModelName: Product name of the product to be loaded.
MeshFilename: File path of the CAD file of the product.
RecognitionMeshFilename (optional): File path of the CAD file of the product to be used for object recognition. Value is empty if not specified.
ParamNames (optional): List of parameter names that are specified in object_recognition.yaml for this product.
ParamValues (optional): List of parameter values that are specified in object_recognition.yaml for this product.
Minimal example:
1global tuple SurfaceModelID 2 3if (RecognitionMeshFilename == '') 4 RecognitionMeshFilename := MeshFilename 5endif 6 7read_object_model_3d(RecognitionMeshFilename, 1.0, ParamNames, ParamValues, ObjModel3D, Status) 8 9create_surface_model(ObjModel3D, 0.03, [], [], SurfaceModelID) 10 11return ()
Hint
Using
global tuple, tuples can be declared that are also available in other procedures such as thefind_objectsprocedure.find_objectsInput control parameters (product properties)
ModelNames: Product name of the product to be recognized.
MinimumScores: Minimum score of the product.
MaxTotalMatches: Expected number of finds (sum of all product finds).
Output control parameters (return values to Mikado)
RecognizedModels: Product names of the finds. If this list remains empty, the first product is used by default for all find poses.
Poses: Recognized object poses
Scores: Score values of the individual objects
Minimal example:
In the following example, the function mikado_get_point_cloud is used to retrieve the point cloud of the last recording and use it for the object search.
1* Simple Example: assumes that only one model is searched; ignore ModelNames and just use first MinScore 2 3mikado_get_point_cloud(ImageX, ImageY, ImageZ, Region, 'Ensenso_Camera_0') 4 5reduce_domain (ImageX, Region, ImageX) 6reduce_domain (ImageY, Region, ImageY) 7reduce_domain (ImageZ, Region, ImageZ) 8 9xyz_to_object_model_3d(ImageX, ImageY, ImageZ, ObjectModel3D) 10 11global tuple SurfaceModelID 12 13find_surface_model (SurfaceModelID, ObjectModel3D, 0.05, 0.2, MinimalScores[0], 'false', ['num_matches'], [MaxTotalMatches], Poses, Scores, SurfaceMatchingResultID) 14 15return ()
Customizing the configuration file¶
The object_recognition.yaml configuration file contains the parameterization for object recognition. You can also integrate your user-defined Hdev script at this point.
Exit the Mikado interface.
Open the ‘object_recognition.yaml’ file in the ‘config’ directory
Search for the section
models:and create entries for the products with their own object recognition in the following form:[..] models: MyProductName1: use_halcon_script: true script_filename: "/home/mikado/cells/my_mikado_cell/scripts/MyHalconObjectRecognition1.hdev" # Params are passed through to halcon function params: my_param_1: false my_param_2: 'text_parameter' MyProductName2: use_halcon_script: true script_filename: "/home/mikado/cells/my_mikado_cell/scripts/MyHalconObjectRecognition2.hdev"
Start Mikado.
Hint
You can check whether your configuration is correct by loading your product in the Mikado interface and then looking at the logs. There you will find an info entry: “[HDevEngine node] Request received to load model for object recognition via halcon script: [..]”.
Own pages with QML¶
The user interface of Mikado is programmed in QML and can easily be expanded to include two customer-specific pages. For example, a system-specific status is displayed to the operator on the first page. On another page, more detailed information can be added or parameters can be set. If activated, this second page is password-protected.
Konfiguration¶
In the folder qml you will find the file pages.yaml in which you can configure which two files are to be displayed as pages. After restarting Mikado, these will now appear between Welcome and Status in Run mode. You can edit these files with any text editor; kate is pre-installed on the controller. If you set the parameter debug_qml: true in the config/mikado.yaml file, another page appears on the right-hand side of the screen where you can reload your code live. This allows you to make quick and easy adjustments to the pages, ideally on a second monitor.
Introduction to QML¶
QML is a declarative language very similar to HTML, and JavaScript can also be used for dynamic aspects. Let’s start with a simple example:
1import QtQuick 2.12
2
3Item {
4
5 // Example: Header of user page
6 Rectangle {
7 id: header
8 y: 20
9 width: 700
10 height: 50
11 color: "blue"
12 radius: 20
13 anchors.horizontalCenter: parent.horizontalCenter
14
15 Text {
16 anchors.centerIn: parent
17 text: "MIKADO - User Page"
18 verticalAlignment: Text.AlignVCenter
19 horizontalAlignment: Text.AlignHCenter
20 font.bold: true
21 font.pixelSize: 32
22 color: "white"
23 }
24 }
25}
The basic package for QtQuick is loaded here first. It provides some basics such as rectangles (Rectangle), text displays (Text) and images (Image). The object hierarchy then begins with a minimum element (Item), which is automatically adapted to the window in the Mikado interface and therefore does not require a size specification. This contains a blue rectangle with rounded corners (radius: 20). Interesting here is the relative positioning in the middle of the page via an anchor. This rectangle again contains a white text.
It gets a little more exciting when we add a button and trigger a sequence when clicked:
1import QtQuick 2.12
2import QtQuick.Controls 2.12
3
4//...
5
6Button {
7 text: "Starte Test-Sequenz"
8 onClicked: startSequence("Test")
9}
10
11function startSequence(name) {
12 if (core.selectSequence(name)){
13 core.run();
14 return true
15 } else {
16 print("Sequenz existiert nicht")
17 return false
18 }
19}
Here, the JavaScript function startSequence is executed after a click (onClicked). This accesses Mikado via the core object and attempts to switch the program to the sequence named Test. If this does not exist, a message is output to the console (and the logs). Otherwise the Mikado program sequence is activated.
Some other predefined elements can be found in the following excerpts.
Display Mikado variable:
1VariableLabel {
2 variable: "TeilZaehler"
3}
Customize Mikado variable in text format:
1VariableTextField {
2 id: varTextField
3 variable: "Zeit"
4 setAsInitial: true
5}
Otherwise, all other blocks from e.g. Qt Quick Controls 2 can also be used.
Further information¶
The QML book ‘Qt5 Cadaques’ at https://qmlbook.github.io and the official QML documentation at https://doc.qt.io/qt-5/qmlreference.html provide a very comprehensive and comprehensible introduction to QML. We use the Qt Quick Controls 2 whose documentation can be found at https://doc.qt.io/qt-5/qtquickcontrols-index.html.
External control with ROS/Python¶
Both for external control by a PLC or a control system and for the integration of special hardware components such as individual grippers, swivel units, … Mikado offers an ROS interface. This API can be accessed with different languages, in the following Python is used as it generally results in compact and understandable source code. If you prefer to work with C, C++, C# or node.js, please ask us directly for instructions and examples.
Example program¶
Let’s start with a simple example program:
1from mikado_msgs.srv import *
2import rospy
3
4# Variable aus Mikado lesen
5get_var = rospy.ServiceProxy('read_variable', ReadVariable)
6max_ansicht = get_var('MaxAnsicht')
7print "MaxAnsicht = " + max_ansicht.value_ints[0]
8
9# Mikado Sequenz starten
10run_sequence = rospy.ServiceProxy('run_sequence', RunSequence)
11run_sequence(name='Init', check_existence_only=False,
12 stop_after_first=False, blocking=False)
13# oder
14run_sequence('Init', False, False, False)
In this example, the API for communication with Mikado Control is loaded first (1). An example then explains how a variable is read from Mikado via a ServiceCall, i.e. a function call. First a function object is defined (5) and then its function is called (6). The return value is stored in max_view. As variables in Mikado can have different types, this is in the format of a collection object. The value_ints property can now be used to access an array of all integer return values, for example.
In the second section, we start a Mikado sequence called Init (a name assigned in the Mikado program). Again, a function object is created (10) and then called. Either the detailed variant (11) with named arguments or the compact variant (14) can be used.
Mikado ROS Services¶
With a running Mikado, the ROS service interface can be conveniently inspected and tested on the command line. rosservice list displays the available services, rosservice info /run for example displays the information for the function to start the Mikado process and with rosservice call /run ... it can be called directly. Press the Tab key twice to complete the list of arguments. The most important commands are listed below:
Mikado¶
- mikado_msgs.pause()
Pauses the currently running Mikado program after the currently running task has ended. The function is asynchronous, i.e. the robot can still move after the function has ended, for example. To ensure that Mikado has been paused, please use the
/engine_statetopic.
- mikado_msgs.read_variable()
Reads a Mikado variable and returns its value. Call in code: rospy.ServiceProxy(‘read_variable’, ReadVariable)
- Parameters:
name (string) – Name of the variable
- Returns:
Wert der Variable success (bool): Variable existiert value_type (string): Typ der Variable (
Integer,Double,String,StringList,Pose,PoseList,JointPosition,Bool,JScript) value_string (string): Textdarstellung der Variable value_strings (string[]): value_ints (int[]): value_floats (double[]): value_poses (geometry_msgs::Pose[]):
- mikado_msgs.run()
Aufruf in Code: rospy.ServiceProxy(‘run’, Run)
- Parameters:
step (bool) – Pause after a step (single step) Starts execution at the beginning of the Mikado program or at the current position of the program pointer. The
stepargument specifies whether only the next task is to be executed or whether automatic mode is to be started.
- mikado_msgs.run_sequence()
Aufruf in Code: rospy.ServiceProxy(‘run_sequence’, RunSequence)
- Parameters:
name (string) – Name of the sequence to be executed
check_existence_only (bool) – the function ends with
success = trueif the sequence existsstop_after_first (bool) – Executes only the first task in the desired sequence, can then be executed in individual steps with
run(step=true)
Starts the program execution with a desired sequence
name.
- mikado_msgs.stop()
Aufruf in Code: rospy.ServiceProxy(‘stop’, Stop)
Terminates the program execution, resets all variables to their initial value and removes dynamic data. This includes point clouds, object finds, handles, positions of scene objects … Call in code: rospy.ServiceProxy(‘stop’, Stop)
- mikado_msgs.write_variable()
Aufruf in Code: rospy.ServiceProxy(‘write_variable’, WriteVariable)
- Parameters:
name (string) –
value_type (string) –
Integer,Double,String,StringList,Pose,PoseList,JointPosition,Bool,JScriptvalue_strings (string[]) –
value_ints (int[]) –
value_floats (float[]) –
value_poses (Pose[]) – Sets the value of a Mikado variable that must have the specified
value_type. The value must be in the corresponding fields.JointPositionis read fromvalue_floats,JScript(JavaScript) fromvalue_strings.
Ensenso¶
- isys_object_recognition_msgs.calibrate()
/cameras/Ensenso_Camera_0/calibrate
- Parameters:
store (bool) – Saving the calibration in the camera
calibration_setup (string) –
MovingorFixed, is the camera moving (attached to the robot) or in a fixed position in the cell
Performs the camera calibration with the images captured with
capture_for_calibration.
- isys_object_recognition_msgs.calibrate_workspace()
/cameras/Ensenso_Camera_0/calibrate_workspace
- Parameters:
defined_pose_transform (Pose) –
Sets the coordinate system of the camera based on a calibration plate so that the pattern is located at the
defined_pose_transformpose. (Only useful for Mikado Select, replaces an existing hand-eye calibration)
- isys_object_recognition_msgs.capture_for_calibration()
/cameras/Ensenso_Camera_0/capture_for_calibration
- Parameters:
reset (bool) – Discard previous recordings and start from the beginning
tool0_pose (Pose) – Position of the robot flange (
tool0)
Makes a recording and saves the positions of the pattern and robot for subsequent calibration with
calibrate.
- isys_object_recognition_msgs.estimate_pattern_pose()
/cameras/Ensense_Camera_0/estimate_pattern_pose
- Returns:
success (bool): a pattern was visible and its position could be determined pattern_pose (geometry_msgs.Pose):
Captures a camera image, searches it for an Ensenso calibration pattern and returns its position as
pattern_pose.
- isys_object_recognition_msgs.get_captured_images()
/cameras/Ensenso_Camera_0/get_captured_images
- Parameters:
left_image_type (int) –
right_image_type (int) –
- Returns:
success (bool) left_image, right_image (sensor_msgs.Image)
Returns an image from the last capture,
typecan be 0 (NO_IMAGE), 1 (RAW_IMAGE), 2 (RECTIFIED_IMAGE) or 3 (OVERLAY_IMAGE) and refers to the analog stages of Ensenso image processing.
- isys_object_recognition_msgs.get_point_cloud()
/cameras/Ensenso_Camera_0/get_point_cloud
- Returns:
point_clouds (sensor_msgs.PointCloud2) List of point clouds
Returns the last recorded point cloud. In the case of multiple recordings, these are returned as individual point clouds.
- isys_object_recognition_msgs.is_calibration_pattern_visible()
/cameras/Ensenso_Camera_0/is_calibration_pattern_visible
- Parameters:
calibration_setup (string) –
MovingorFixed, is the camera moving (attached to the robot) or in a fixed position in the celltool0_pose (Pose) – Pose of the robot flange
Checks whether the pattern is in the camera’s field of view for the given pose. This requires at least a pre-calibration using
run_precalibrationor a complete calibration.
- isys_object_recognition_msgs.load_camera_config()
/cameras/Ensenso_Camera_0/load_camera_config
- Parameters:
filename (string) –
load_capture_parameters (bool) –
load_link (bool) –
Loads a camera configuration saved in NxView in JSON format into the current camera. Only the capture parameters (
load_capture_parameters), only the transformation/link (load_link) or both can be loaded.
- isys_object_recognition_msgs.recalibrate()
/cameras/Ensenso_Camera_0/recalibrate
Performs an estimation and recalibration of the vergence angle. A calibration pattern must be visible for this.
- isys_object_recognition_msgs.run_precalibration()
/cameras/Ensenso_Camera_0/run_precalibration
- Parameters:
calibration_setup (string) –
MovingorFixed, is the camera moving (attached to the robot) or in a fixed position in the cell
Performs an initial rough hand-eye calibration. After this,
is_calibration_pattern_visiblecan be used to check the visibility of random calibration positions, for example.
- isys_object_recognition_msgs.save_camera_config()
/cameras/Ensenso_Camera_0/save_camera_config
- Parameters:
filename (string) –
Writes the current camera configuration to a JSON file.
- isys_object_recognition_msgs.save_raw_data()
/cameras/Ensenso_Camera_0/save_raw_data
- Parameters:
path (string) – Target folder, relative to the
Homedirectory (personal folder in Dolphin)prefix (string) – The file name is preceded by a prefix
rectified (bool) – If the image is to be saved in a rectified version, set this parameter to true
Saves the current recording, the resulting set of images can be used for a Filecam camera, for example.
- isys_object_recognition_msgs.set_capture_mode()
/cameras/Ensenso_Camera_0/set_capture_mode
- Parameters:
front_light (bool) –
projector (bool) –
For 2D recordings with the Ensenso camera, the projector can be switched off and the frontlight switched on if necessary. Must be reset for 3D recordings.
- isys_object_recognition_msgs.set_get_json()
/cameras/Ensenso_Camera_0/set_get_json
- Parameters:
set_json (string) –
wait_for_null_json (string) –
get_json (string) –
- Returns:
bool set_success: Write successful string get_result: string set_error: string get_error:
This function makes it easy to interact with the NxLib. Parameters can be written with
set_json, but commands can also be started. To do this, you write anexecutenode and specify the path to itscommandnode inwait_for_null_json. When the command has been executed, this node is then set tonullby the NxLib. Usingget_json, either a parameter can be read or theResultnode of a command can be queried.
- isys_object_recognition_msgs.set_roi_rotated_box()
/cameras/Ensenso_Camera_0/set_roi_rotated_box
- Parameters:
box_pose (geometry_msgs.Pose) –
box_size (geometry_msgs.Vector3) –
Sets a region of interest (ROI) to which the point cloud is clipped.
- isys_object_recognition_msgs.start_capture()
/cameras/Ensenso_Camera_0/start_capture
- Parameters:
left_camera (bool) – Should the left or right camera be used
- Returns:
success: true
Starts a continuous recording (2D), the left or right 2D raw image is published to the topic
/cameras/Ensenso_Camera_0/camera_imageand displayed in Mikado on the camera page.
- isys_object_recognition_msgs.stop_capture()
/cameras/Ensenso_Camera_0/stop_capture
- Returns:
success: true
Ends the continuous image recording run
Robots/Hardware¶
- extra_industrial_msgs.control_hand(bool open)
Aufruf in Code: rospy.ServiceProxy(‘control_hand’, ControlHand)
- Parameters:
open (bool) –
Switches the gripper.
- extra_industrial_msgs.read_input_signal(int signal_number)
- Parameters:
signal_number (int) –
- Returns:
returnValue: bool success: bool
- Code example:
read_input_signal = rospy.ServiceProxy(‘read_input_signal’, ReadSignal)
res = read_input_signal(signal_number=23)
if res.success:
print res.returnValue
Reads the value of a digital input.
- extra_industrial_msgs.read_output_signal(int signal_number)
Aufruf in Code: rospy.ServiceProxy(‘run_output_signal’, ReadSignal)
- Parameters:
signal_number (int) –
- Returns:
returnValue (bool): success (bool):
- Code example:
read_output_signal = rospy.ServiceProxy(‘read_output_signal’, ReadSignal)
res = read_output_signal(signal_number=23)
if res.success:
print res.returnValue
Reads the value of a digital output.
- extra_industrial_msgs.set_output_signal(int signal_number, bool value)
Aufruf in Code: rospy.ServiceProxy(‘set_output_signal’, SetSignal)
- Parameters:
signal_number (int) –
value (bool) –
- Returns:
success (bool):
Sets a digital output.
- extra_industrial_msgs.run_program()
- Parameters:
program_name (string) –
int_args (named_int[]) – Ein Array von Kombinationen aus [string variable_name, int int_value]
float_args (named_float[]) – Ein Array von Kombinationen aus [string variable_name, float float_value]
string_args (named_string[]) – Ein Array von Kombinationen aus [string variable_name, string string_value]
pose_args (named_pose[]) – Ein Array von Kombinationen aus [string variable_name, pose pose_value]
- Returns:
returnValue (int): A freely assignable return value success (bool): If the execution was successful
Executes a classic robot program that is stored on the robot controller.
- industrial_msgs.industrial_io_read()
Aufruf in Code: rospy.ServiceProxy(‘industrial_io_read’, IORead)
- Parameters:
items (industrial_msgs.IOReadRequestItem[]) – Ein Array von [int type, int index]
- Returns:
items (industrial_msgs.IOReadReplyItem[]): Ein Array von [int type, int index, int result, int value]
Allows several inputs or outputs to be read at the same time, this is particularly interesting for recording entire data blocks on a fieldbus.
typespecifies the type of field, possible values areDigitalIn = 1 (read one input bit)
DigitalOut = 2 (read one output bit)
AnalogueIn = 3
AnalogueOut = 4
GroupedIn = 5 (One input word, 16 bit, read)
GroupedOut = 6 (One output word, 16 bit, read)
Not every end device supports all types; for fieldbuses (Hilscher), for example, only the digital inputs/outputs and word-wise read/write are available.
- industrial_msgs.industrial_io_write()
- Parameters:
items (industrial_msgs.IOWriteRequestItem[]) – Ein Array von [int type, int index, int value]
- Returns:
items (industrial_msgs.IOWriteReplyItem[]): Ein Array von [int type, int index, int result]
Writes several outputs or fields in one pass, particularly interesting for fieldbus interfaces. Sets one or more fields with the type
type, the addressindexto the valuevalue. The return value contains the information for each field as to whether it could be written (result = 1) or not (result = 0). Whichtypebelongs to input or output can be found in the list under industrial_io_read.
Mikado ROS Actions¶
In addition to the ROS services, ROS actions also exist as an external interface. These can be used via action clients and allow asynchronous commands and feedback. For detailed information on the use of ROS actions, please refer to the official ROS documentation.
The ROS actions offered by Mikado are listed below.
- mikado_msgs.calibration.cancel()
Cancel hand-eye calibration
- Returns:
error_code
EC_SUCCESS
0
EC_ERROR
1
EC_ACTION_RUNNING
2
EC_DISABLED
3
- mikado_msgs.calibration.capture()
Trigger recording for hand-eye calibration
- Parameters:
current_pose (geometry_msgs.Pose) – Current robot pose
- Returns:
error_code
EC_SUCCESS
0
EC_ERROR
1
EC_ACTION_RUNNING
2
EC_DISABLED
3
EC_NO_CALIBRATION_STARTED
4
- mikado_msgs.calibration.finish()
Calculate hand-eye calibration and save it on the camera if successful.
In addition to the error number, the return values contain values for the calibration result (average deviations).
- Returns:
error_code
EC_SUCCESS
0
EC_ERROR
1
EC_ACTION_RUNNING
2
EC_DISABLED
3
EC_NO_CALIBRATION_STARTED
4
- Returns:
meanDist [mm]
- Returns:
meanX [mm]
- Returns:
meanY [mm]
- Returns:
meanZ [mm]
- Returns:
meanAngle [radian]
- Returns:
maxDist [mm]
- mikado_msgs.calibration.set_origin()
Setting the origin using a calibration plate
- Parameters:
pose_of_measured_object (geometry_msgs.Pose) – Pose of the calibration plate at the time of recording relative to the desired origin
camera_name (string) – Camera name (e.g. “Ensenso_Camera_0”)
frontlight (bool) – Activate the front light of the camera for recording (if available)
- Returns:
error_code
EC_SUCCESS
0
EC_ERROR
1
EC_ACTION_RUNNING
2
EC_DISABLED
3
EC_CALIBRATION_IN_PROGRESS
4
EC_UNKNOWN_CAMERA_NAME
5
- mikado_msgs.calibration.start()
Initialize calibration process (manual mode) or start automatic (automatic mode).
- Parameters:
calibration_mode –
CALIB_MODE_MANUAL
0
CALIB_MODE_AUTO
1
- Parameters:
pose_list_name (string) – (optional) Variable name of the PoseList to be used as the list of calibration poses
camera_name (string) – Camera name (e.g. “Ensenso_Camera_0”)
frontlight (bool) – Activate the front light of the camera for recording (if available)
- Returns:
error_code
EC_SUCCESS
0
EC_ERROR
1
EC_ACTION_RUNNING
2
EC_DISABLED
3
EC_CALIBRATION_IN_PROGRESS
4
EC_UNKNOWN_CALIB_MODE
5
EC_UNKNOWN_CAMERA_NAME
6
Systemstatus¶
A script can contribute its own information to the system status in Mikado, e.g. an error status leads to a query before the program is executed and is also displayed in the list on the left-hand side of the status bar. To do this, an entry must be added to config/status.yaml:
status:
- name: Robot
type: RobotStatus
topic: robot_status
- name: Profinet
type: RosDiagnosticStatus
topic: profinet/status
enabled_if_rosparam: /profinet
- name: Beispiel Status
type: RosDiagnosticStatus
topic: sps_status
A message must now be published on the newly added topic at least every 10s. Here is a minimal example
1#!/usr/bin/env python
2import rospy
3from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus
4
5pub = rospy.Publisher('sps_status', DiagnosticArray, queue_size=10)
6rospy.init_node('sps_script', anonymous=True)
7rate = rospy.Rate(10) # 10hz
8while not rospy.is_shutdown():
9 diag_array = DiagnosticArray()
10 status = DiagnosticStatus()
11 status.name = "SPS"
12 status.level = DiagnosticStatus.OK
13 status.message = "Es laueft bestens"
14 diag_array.status = [status]
15 pub.publish(diag_array)
16 rate.sleep()
In return, the script can also read a summary of the current system status on the /system_status topic.
Launchfile¶
To start and end a script automatically with Mikado, save it in the Scripts folder of the cell (create the folder if necessary). Now open the file launch/main.launch and add the following text block:
<node name="adapter_script" pkg="meine_zelle" type="ProfinetMikadoAdapter.py" output="screen" />
Here, our script with the file name ProfinetMikadoAdapter.py is started from the cell my_cell under the freely selectable name [1] adapter_script.
Footnotes