Read the output of a Python script from RoboDK

Hello Node-Red Community. I am currently working with a Robot linked to RoboDk Software and I have a Python Script whose output are the values from the Robot (like Axis-Position, Torque, etc). Now I want this output to be shown in Node-Red. I have tried something like this before and it worked, but this time, It is creating a problem

What problem?

Are you using an exec node to do it? That is the way I would do it.

Typically yes. But with the execition node, it is not working. Would it be okay, if i send the python script here so you can maybe have a look at it?

What do you mean by not working?

Add debug nodes (showing the full message) to all outputs of the exec node and see what you get.

Well, when I am executing the script in cmd, it works. But when I am doing the same in my execution node, I can't see any output on the debug window

Here's a very simple flow (an adder) to test running a Python script on a Raspberry Pi.
Sorry - I have no experience of RoboDK.
It passes two arguments to the Python script which returns a result.

[{"id":"8d24364b9ad2a570","type":"function","z":"669661901b39aedb","name":"Run Python script on .152","func":"msg.num1 = 5;\nmsg.num2 = 6;\n\nmsg.payload = \"python3 /home/pi/adder.py \"+ msg.num1 + \" \" + msg.num2;\n\nreturn msg;","outputs":1,"timeout":"","noerr":0,"initialize":"","finalize":"","libs":[],"x":360,"y":380,"wires":[["4296a5d3bae3fd90"]]},{"id":"1fefcdbcb1c8013f","type":"inject","z":"669661901b39aedb","name":"Run script on Pi","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"1","payloadType":"num","x":120,"y":380,"wires":[["8d24364b9ad2a570"]]},{"id":"4296a5d3bae3fd90","type":"exec","z":"669661901b39aedb","command":"","addpay":"payload","append":"","useSpawn":"false","timer":"","winHide":false,"oldrc":false,"name":"main_exec","x":610,"y":380,"wires":[["b2bf7b2e86a489df","453996b9df974c39"],["b2bf7b2e86a489df"],["b2bf7b2e86a489df"]]},{"id":"b2bf7b2e86a489df","type":"debug","z":"669661901b39aedb","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":830,"y":380,"wires":[]}]
#!/usr/bin/env python3
import sys

a = int(sys.argv[1])
b = int(sys.argv[2])
# c = int(sys.argv[3])
result = a * b
print('Result of multiplying ',a," by ",b, " is ",result)
print(result)

This is what appears in the Debug node.
thurs_python_b

I appreciate for your Input. A Python Script has already worked on node red, It is only this time that I am using a module from Robodk in Python which i believe is causing the trouble. It would be helpful if I shared the python script.

Type help("robodk.robolink") or help("robodk.robomath") for more information

Press F5 to run the script

Documentation: RoboDK API - RoboDK Documentation

Reference: 2. RoboDK API (robodk package) — RoboDK API Documentation

Note: It is not required to keep a copy of this file, your Python script is saved with your RDK project

from robodk import robolink #RoboDK API
from robodk import robomath # Robot toolbox

The following 2 lines keep your code compatible with older versions or RoboDK:

from robodk import * # RoboDK API
from robolink import * # Robot toolbox

import time
import numpy as np
import os
#os.environ['PYDEVD_DISABLE_FILE_VALIDATION'] = '1'
import sys

import socket
import threading
import time

g_data = None
def tcp_server():
host = '192.168.1.135'
port = 3000

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((host, port))
server_socket.listen(1)

#print("TCP server is listening on port", port)

global g_data
while True:
    client_socket, client_address = server_socket.accept()
    #print("Connected by", client_address)

    while True:
        g_data 	= client_socket.recv(1024)
        #g_data 		= readdata
        #data = data.decode('utf-8')
        #data = float(data[0:6])
        if not g_data:
            break
        #print("Received number:", g_data)
    #print("Connection closed by", client_address)
    client_socket.close()

def write_in_txt_file(boValue, m_path):
f = open(m_path, 'w')
f.write(str(boValue) + "\n")
f.close
def read_from_txt_file(m_path):
f = open(m_path, 'r')
try:
#Read martrix from file
a1 = float(f.readline())
a2 = float(f.readline())
a3 = float(f.readline())
a4 = float(f.readline())
b1 = float(f.readline())
b2 = float(f.readline())
b3 = float(f.readline())
b4 = float(f.readline())
c1 = float(f.readline())
c2 = float(f.readline())
c3 = float(f.readline())
c4 = float(f.readline())
d1 = float(f.readline())
d2 = float(f.readline())
d3 = float(f.readline())
d4 = float(f.readline())
#Create cam pose matrix
mat = Mat([[a1],[a2],[a3],[a4],[b1],[b2],[b3],[b4]])
except Exception as e:
mat = Mat([[0],[0],[0],[0],[0],[0],[0],[0]])
f.close()
return mat
def RobotSectionMove(m_PosName, m_OVPRO, m_MovementType):
m_target = RDK.Item( m_PosName )
m_target.Pose()
m_target.setParam("Recalculate")
m_approach = m_target.Pose()
robot.setParam("Driver", m_OVPRO)
print("Script is running", file=sys.stdout)#check
if m_MovementType == 'MoveJ':
robot.MoveJ(m_approach) # joint move to the approach posi mmtion
if m_MovementType == 'MoveL':
robot.MoveL(m_approach) # linear move to the approach posi mmtion
else:
robot.MoveJ(m_approach) # joint move to the approach posi mmtion

Function definition to create a list of points (line)

def MakePoints(xStart, xEnd, numPoints):
"""Generates a list of points"""
if len(xStart) != 3 or len(xEnd) != 3:
raise Exception("Start and end point must be 3-dimensional vectors")
if numPoints < 2:
raise Exception("At least two points are required")

# Starting Points
pt_list = []
x = xStart[0]
y = xStart[1]
z = xStart[2]


# How much we add/subtract between each interpolated point
x_steps = (xEnd[0] - xStart[0]) / (numPoints - 1)
y_steps = (xEnd[1] - xStart[1]) / (numPoints - 1)
z_steps = (xEnd[2] - xStart[2]) / (numPoints - 1)

# Incrementally add to each point until the end point is reached
for i in range(numPoints):
    point_i = [x, y, z]  # create a point
    #append the point to the list
    pt_list.append(point_i)
    x = x + x_steps
    y = y + y_steps
    z = z + z_steps
return pt_list

Link to RoboDK

RDK = robolink.Robolink()
#RDK = robolink()

Retrieving the robot in Station

ITEM_TYPE_ROBOT = 2
robot = RDK.Item('',ITEM_TYPE_ROBOT)

robottest = RDK.Item('', 2)# robolink.ITEM_TYPE_ROBOT)
robottest.Connect()

######### Online Verbindung konfigurieren !!!!!!!!!!!AUSKOMMENTIERT!!!!!!!!!!!!!!!

Connect to the robot using default connetion parameters

##success = robot.Connect()

##status, status_msg = robot.ConnectedState()

##if status != ROBOTCOM_READY:

# Stop if the connection did not succeed

raise Exception("Failed to connect: " + status_msg)

##################### Run mode definieren
RDK.setRunMode(RUNMODE_RUN_ROBOT)
#RDK.setRunMode(RUNMODE_SIMULATE)

Variablen definieren

zurĂĽck = 1 #Variable fĂĽr Farbwechsel 0=> GrĂĽne Farbe behalten
# 1=> ZurĂĽcksetzen der Farbe

var = 'ja' # Definieren der Variable um wiederholfen Durchlauf des Programms zu steuern

OVPRO_100 = "SET $OV_PRO 100"
OVPRO_90 = "SET $OV_PRO 90"
OVPRO_80 = "SET $OV_PRO 80"
OVPRO_70 = "SET $OV_PRO 70"
OVPRO_60 = "SET $OV_PRO 60"
OVPRO_50 = "SET $OV_PRO 50"
OVPRO_40 = "SET $OV_PRO 40"
OVPRO_30 = "SET $OV_PRO 30"
OVPRO_20 = "SET $OV_PRO 20"
OVPRO_10 = "SET $OV_PRO 10"
OVPRO_5 = "SET $OV_PRO 5"

START = '1'
CLEAR = '0'

#PathToScanner = 'Y:/FKS-Archiv/Archiv_Projekte - Layouts/FKS/7230158_AddGleis/7230158_AddGleis_Entwicklung/Simulation/RoboDK/ScannerInput.txt'
#PathFromScanner = 'Y:/FKS-Archiv/Archiv_Projekte - Layouts/FKS/7230158_AddGleis/7230158_AddGleis_Entwicklung/Simulation/RoboDK/ScannerOutput.txt'

#server_thread = threading.Thread(target=tcp_server)
#server_thread.start()

def InputDataConversion(m_InpData):
#print("Script is running", file=sys.stdout)#check
m_data = m_InpData
m_data = m_data.decode('utf-8')
m_value = float(m_data[0:6])
#print("m_data:", m_data)
return m_value

def Logic(m_InpList):
m_ProzList = [0,0,0,0]

m_mean 				= (m_InpList[0] + m_InpList[1] + m_InpList[2] + m_InpList[3])/4
m_SymMinMaxRange	= abs(max(m_InpList)-min(m_InpList))/2
#print("Script is running", file=sys.stdout)#check
#print('m_mean',m_mean)
#print('m_SymMinMaxRange',m_SymMinMaxRange)

#print('min=',min(m_InpList))
#print('max=',max(m_InpList))
for i in range(0,4):
	m_tempdiff 	= abs(m_mean - m_InpList[i])
	#print('m_tempdiff',m_tempdiff)
	m_proz			= abs(m_tempdiff/m_SymMinMaxRange)*0.7
	#print('m_proz',m_proz)
	
	if m_proz > 1:
		m_ProzList[i] 	= "SET $OV_PRO 100"
	else:
		m_ProzList[i] 	= "SET $OV_PRO " + str(int(m_proz*100))
	#print('m_ProzList',m_ProzList)
return m_ProzList

AreaList = ['0','0','0','0']
while True :
#for i in range(0,4):
################################## read robots internal System variables #########################################################

ov_pro              = robot.setParam("Driver", "GET $OV_PRO")         # $OV_PRO
POS_ACT_MES_X       = robot.setParam("Driver", "GET $POS_ACT_MES.X")    # $POS_ACT_MES.X
POS_ACT_X           = robot.setParam("Driver", "GET $POS_ACT.X")        # $POS_ACT.X

TORQUE_AXIS_ACT1    = robot.setParam("Driver", "GET $TORQUE_AXIS_ACT[1]")# $TORQUE_AXIS_ACT[1]
TORQUE_AXIS_ACT2    = robot.setParam("Driver", "GET $TORQUE_AXIS_ACT[2]")# $TORQUE_AXIS_ACT[1]
TORQUE_AXIS_ACT3    = robot.setParam("Driver", "GET $TORQUE_AXIS_ACT[3]")# $TORQUE_AXIS_ACT[1]
TORQUE_AXIS_ACT4    = robot.setParam("Driver", "GET $TORQUE_AXIS_ACT[4]")# $TORQUE_AXIS_ACT[1]
TORQUE_AXIS_ACT5    = robot.setParam("Driver", "GET $TORQUE_AXIS_ACT[5]")# $TORQUE_AXIS_ACT[1]
TORQUE_AXIS_ACT6    = robot.setParam("Driver", "GET $TORQUE_AXIS_ACT[6]")# $TORQUE_AXIS_ACT[1]
TORQUE_AXIS_ACT = [TORQUE_AXIS_ACT1,TORQUE_AXIS_ACT2,TORQUE_AXIS_ACT3,TORQUE_AXIS_ACT4,TORQUE_AXIS_ACT5,TORQUE_AXIS_ACT6]





InfoStr1 =' POS_ACT_MES_X = '       + str(POS_ACT_MES_X)
InfoStr2 =' POS_ACT_X = '           + str(POS_ACT_X)
InfoStr3 =' TORQUE_AXIS_ACT = '    + str(TORQUE_AXIS_ACT)
print("Script is running", file=sys.stdout)#check
InfoStr = InfoStr1 + InfoStr2 + InfoStr3 
print('InfoStr = ', InfoStr)

#RDK.ShowMessage(InfoStr)
#RDK.ShowMessage('ov_pro= ' + ov_pro + '; POS_ACT_MES= ' + POS_ACT_MES + '; POS_ACT= ' + POS_ACT + '; TORQUE_AXIS_ACT[1]= ' + TORQUE_AXIS_ACT1)

####################################### Grunglagen fĂĽr zu erstellendes Programm einstellen############################################

#######################################################################################
############################ Test routine #############################################
#######################################################################################

'''

# Set Frame (Bezugsrahmen aktivieren)
#TableFrame  = RDK.Item('TableFrame',ITEM_TYPE_FRAME) #REFERENCE_NAME,ITEM_TYPE_FRAME
#robot.setPoseFrame(TableFrame)
# Set Tool
#tool = RDK.Item('Tool 7', ITEM_TYPE_TOOL)
#robot.setPoseTool(tool)

#Zu Homeposition fahren
#Target = RDK.Item('Home', ITEM_TYPE_TARGET)  # Target Vorposition Definieren
#robot.MoveJ(Target)
#RobotSectionMove('Home', OVPRO_100, 'MoveJ')

#RobotSectionMove('Modul_1', OVPRO_100, 'MoveJ')
#if g_data is not None:
    #tempInpData = g_data
    #floatdata	= InputDataConversion(tempInpData)
    #AreaList[0] = floatdata
    #floatdata   = None
    #g_data      = None

#RobotSectionMove('Modul_2', OVPRO_100, 'MoveJ')
#if g_data is not None:
    #tempInpData = g_data
    #floatdata	= InputDataConversion(tempInpData)
    #AreaList[1] = floatdata
    #RDK.ShowMessage(str(floatdata))
    #floatdata   = None
    #g_data      = None
    
#RobotSectionMove('Modul_3', OVPRO_100, 'MoveJ')
#    if g_data is not None:
    #tempInpData = g_data
    #floatdata	= InputDataConversion(tempInpData)
    #AreaList[2] = floatdata
    #RDK.ShowMessage(str(floatdata))
    #floatdata   = None
    #g_data      = None

#RobotSectionMove('Modul_4', OVPRO_100, 'MoveJ')
#if g_data is not None and floatdata is None:
    #tempInpData = g_data
    #floatdata	= InputDataConversion(tempInpData)
    #AreaList[3] = floatdata
    #RDK.ShowMessage(str(floatdata))
    #floatdata   = None
    #g_data      = None

#InfoStr = 'Module#1 = ' + str(AreaList[0]) + ' Module#2 = ' + str(AreaList[1]) + ' Module#3 = ' + str(AreaList[2]) + ' Module#4 = ' + str(AreaList[3])
#write_in_txt_file(InfoStr, PathToScanner)             # write all scanresults to file
#RDK.ShowMessage(InfoStr)

#Logic for speeds
#ProzList = Logic(AreaList)

#InfoStr = 'Speed#1 = ' + str(ProzList[0]) + ' Speed#2 = ' + str(ProzList[1]) + ' Speed#3 = ' + str(ProzList[2]) + ' Speed#4 = ' + str(ProzList[3])
#RDK.ShowMessage(InfoStr)

#RobotSectionMove('Modul_1_Start', OVPRO_100, 'MoveJ')
#RobotSectionMove('Modul_2_Start', ProzList[0], 'MoveJ')
#RobotSectionMove('Modul_3_Start', ProzList[1], 'MoveJ')
#RobotSectionMove('Modul_4_Start', ProzList[2], 'MoveJ')
#RobotSectionMove('Modul_4_End', ProzList[3], 'MoveJ')
#RobotSectionMove('Home', OVPRO_100, 'MoveJ')


#break               # Schleife verlassen wenn "var" == nein
#'''

Have you added debug nodes to all three outputs?

Does a pid value appear under the node when you run it?

A pid value does appear. But no success

Please answer all questions

  1. Does the script terminate (the PID will disappear). If the script continues running, make sure that you have 'Output while the command is running selected - spawn mode' selected in the Exec node.

  2. Have you added debug nodes to all three outputs?

  3. Is there any output on any of the debug nodes?

Really sorry - I do not time to wade through your Python script.

Did you try my simple 'adder' script because if that works, with your RoboDK, then that would illiminate one part of the jigsaw puzzle?

Thank you for your help. I have already executed a python script on node red, where I am calling the values from my influxdb database. In this instance, The values that i want node red to display on the debug screen is not really happening through the execution node. Meanwhile using the cmd, It is working just fine.

  1. The script does not terminate, as the values keep on coming from the robot.
  2. I will add the debug nodes now to check is I can see anything
  3. I will get back to you on this .

Thank you for your Input

Nope, not helpful.
How did you copy and paste that?
A python comment such as

# Documentation: [RoboDK API - RoboDK Documentation](https://robodk.com/doc/en/RoboDK-API.html)
appears in the forum as an Hi header:

This is an H1 header

And indented python text just posted in the forum loses it's indentation, making it invalid python code.

The solution to these difficulties is to wrap the entire script between triple backtick lines like this
image
You seem to have managed this for fragments of your script.

Your topic title is "Read the output of a Python script..."
How does this equate with "the values keep on coming from the robot" and "I can't see any output on the debug window"?


I would like to thank the all of you for your help. I was finally able to achieve my result

For the sake of future visitors to the forum who may read your thread, would you like to share what the problem was and how you sorted it out?

I would put a bet on it being that spawn mode output had not been selected.

1 Like

Sorry for my late reply. The problem was sorted thanks to Colin's suggestion about the spawn mode.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.