Uso de la interfaz de secuencias de comandos Trace
El complemento CODESYS Trace proporciona una interfaz de scripting. A continuación encontrará ejemplos de cómo utilizar esta interfaz.
Crear una traza
# a new trace can be created using the toplevel trace api
myApplication = projects.primary.find("Device", "PLC Logic", "Application")[0]
traceObject = trace.create(myApplication, "MyTraceName")
traceObject.task_name = "Task" # a task with the name "Task" should already exist here. If it does not exist, this assignment throws an ValueError.# the task of the trace can be set during creation
myApplication = projects.primary.find("Device", "PLC Logic", "Application")[0]
traceObjectWithTaskSet = trace.create(myApplication, "NameOfMySecondTrace", "MainTask")
assert traceObjectWithTaskSet.task_name == "MainTask"Encuentra y verifica las trazas existentes
# finding an existing trace can be done via the project.find method
foundObjects = projects.primary.find("Device", "PLC Logic", "Application", "MyTraceObject")
expectedTraceObject = foundObjects[0]
assert expectedTraceObject.is_trace_object, "Could not find trace object with the expected name" # .is_trace_object is False for all other objects of type IScriptObjectAgregar y modificar variables de trazas
myTrace = projects.primary.find("Device", "PLC Logic", "Application", "MyTraceObject")[0]
# add_variable() is a convenience method to add a new ScriptTraceVariable and set its properties during creation
addedVariable = myTrace.add_trace_variable(variableName="PLC_PRG.a1",
graphColor= 0xff000000,
graphType=GraphType.LINES,
activateMaxWarning=True,
maxWarningArea=9.0,
maxColor= 0xffff0000)
addedVariable.enabled = False
for i in range(2,11):
newVariable = myTrace.variable_list.add()
newVariable.variable_name = "PLC_PRG.a"+str(i)
newVariable.graph_type = GraphType.LINES_CROSSES
assert len(myTrace.variable_list) == 10Cambiando el ScriptTrace lista de variables
Eliminar un específico ScriptTrace variable
El siguiente fragmento de código busca la variable con el nombre especificado y la elimina del ScriptTrace lista de variables.
def remove_variable_by_name(traceObject, variableName):
index_to_remove = -1
for variable in traceObject.variable_list:
if variable.variable_name == variableName:
index_to_remove = traceObject.variable_list.index_of(variable)
break
if index_to_remove != -1:
traceObject.variable_list.remove(index_to_remove)Cambiar la configuración de grabación
Ajustar la resolución (ms/µs) del registro de trazas
El siguiente fragmento de código se basa en ??? fragmento.
traceObject.resolution = Resolution.MicroSeconds # Use Resolution.MilliSeconds if you want to have a trace recording based on milliseconds
Configuración de las condiciones de grabación
El siguiente fragmento de código se basa en ??? fragmento.
traceObject.record_condition = "PLC_PRG.bDoRecord"
Configurar el comentario
El siguiente fragmento de código se basa en ??? fragmento.
traceObject.comment = "This trace records the ..."
Configuración de la opción de inicio automático
El siguiente fragmento de código se basa en ??? fragmento.
traceObject.auto_start = True
Configurar la opción para grabar solo cada n-ésimo ciclo
El siguiente fragmento de código se basa en ??? fragmento.
traceObject.every_n_cycles = 10
Diagramas y sus variables
Creando un ScriptTrace gráfico con todos ScriptTrace variables
El siguiente script muestra cómo crear un diagrama simple y sus variables.
# first we need a ScriptTraceObject and some ScriptTraceVariables
traceObject = projects.primary.find("Device","PLC Logic","Application","Trace")[0]
assert traceObject.is_trace_object
for i in range(5):
traceObject.add_trace_variable(variableName="PLC_PRG.a"+str(i))
# create one ScriptTraceDiagram and add all ScriptTraceVariables to it
traceDiagram = traceObject.diagrams.add()
for traceVar in traceObject.variable_list:
traceDiagram.add_diagram_variable(traceVar)Creando un ScriptTrace diagrama por ScriptTrace variable
El siguiente método de Python toma una ScriptTrace objeto y añade un diagrama por ScriptTrace variable.
def one_diagram_per_variable(traceObject):
assert traceObject.is_trace_object
for traceVar in traceObject.variable_list:
diagram = traceObject.diagrams.add(traceVar)
diagram.name = traceVar.variable_nameCopiar la configuración de un ScriptTrace Diagrama
El siguiente script muestra cómo modificar y copiar la configuración de un ScriptTrace diagrama.
# we assume, that the traceObject already has multiple diagrams
traceObject = projects.primary.find("Device","PLC Logic","Application","Trace")[0]
assert traceObject.is_trace_object
# apply settings for the first diagram
traceObject.diagrams[0].y_axis.mode = AxisScaleMode.FixedLength
traceObject.diagrams[0].y_axis.range = 10.0
traceObject.diagrams[0].y_axis.color = 0xffee0000
traceObject.diagrams[0].y_axis.draw_grid = True
traceObject.diagrams[0].y_axis.grid_color = 0xffee0000
traceObject.diagrams[0].tickmark_fixed_spacing = True
traceObject.diagrams[0].tickmark_fixed_distance = 5.0
traceObject.diagrams[0].tickmark_fixed_subdivisions = 4
# copy the settings from the first diagrams to all other diagrams
for i in range(1,len(traceObject.diagrams))
traceObject.diagrams[i].y_axis.copy_from(traceObject.diagrams[0])Gestión en línea del traza
Descargar e iniciar él traza
El siguiente fragmento de código encuentra el Trace traza del Application aplicación, la descarga y la inicia.
proj = projects.open(r"<Path to the project file>")
app = proj.find("Device", "PLC Logic", "Application")[0]
with online.create_online_application(app) as onlineapp:
traceObject = proj.find("Device", "PLC Logic", "Application", "Trace")[0]
onlineapp.login(OnlineChangeOption.Never, True)
onlineapp.start()
editor = traceObject.open_editor()
editor.download()
editor.start()Guardar la traza en un archivo
El siguiente fragmento de código se basa en Descargar e iniciar él traza fragmento. Se debe detener un traza antes de poder guardarlo. Esto se puede hacer alcanzando la condición de activación o mediante una llamada explícita a stop().
# We assume, that we have an already running trace editor.stop() editor.save(r"<File path to csv file>")
Consulta de información diversa para el registro de trazas
El siguiente fragmento de código se basa en Descargar e iniciar él traza fragmento.
# We assume, that we have an already running trace
print("Packet State: {}".format(editor.get_packet_state()))
print("Trace started at {} (absolute timestamp)".format(editor.get_trace_start_timetamp()))Manejo de disparadores
Configuración de un BOOL gatillo
traceObject = proj.find("Device", "PLC Logic", "Application", "Trace")[0]
traceObject.trigger_variable = "PLC_PRG.bVar"
traceObject.trigger_edge = TriggerEdge.Positive
traceObject.post_trigger_samples = 20
# The trigger level is only needed for numeric trigger variables. It is a good coding style to set the trigger explicitly to "None"
traceObject.trigger_level = NoneConfiguración de un disparador numérico
traceObject = proj.find("Device", "PLC Logic", "Application", "Trace")[0]
traceObject.trigger_variable = "PLC_PRG.iTemperature"
traceObject.trigger_edge = TriggerEdge.PositivetraceObject.post_trigger_samples = 20
# In case of a trigger variable of REAL or LREAL type it is also possible to specify floating point trigger levels, e.g. 80.5
traceObject.trigger_level = 80Esperar un disparador y guardar los datos registrados
El siguiente fragmento de código se basa en la sección «Configuración de BOOLfragmentos de código -triggers» y «Configuración de un disparador de *».
triggerstate = editor.get_trigger_state()
while triggerstate != TriggerState.TriggerReached:
system.delay(200)
triggerstate = editor.get_trigger_state()
editor.save(r"<File path to csv file>")Consultar la información de la marca de tiempo una vez alcanzado el desencadenante
El siguiente fragmento de código se basa en la sección «Configuración de BOOLFragmentos de «-Trigger» y «Configuración de un * Trigger».
print("Trigger reached at {} (absolute timestamp)".format(editor.get_trigger_timetamp()))
print("Trigger reached at {}".format(editor.get_trigger_startdate()))
print("Trace was running {}ms until trigger has been reached".format(editor.get_trigger_timetamp() - editor.get_trace_start_timetamp()))Reanudar la grabación del rastreo después de alcanzar el disparador
El siguiente fragmento de código se basa en la sección «Configuración de BOOLFragmentos de «-Trigger» y «Configuración de un * Trigger».
editor.reset_trigger()
Traza del dispositivo
Creando un DeviceTrace
myDevice = projects.primary.find("Device")[0]
devicetrace = trace.create(myDevice, "DeviceTrace")Consulta de las grabaciones de traza actuales del dispositivo
El siguiente fragmento de código se basa en la opción «Crear un DeviceTrace« fragmento».
traceObject = projects.primary.find("Device", "DeviceTrace")[0]
# for application traces the result of get_online_traces contains only the traces of the application
# traceObject = projects.primary.find("Device", "PLC Logic", "Application", "Trace")[0]
editor = traceObject.open_editor()
for tracepacket in editor.get_online_traces():
print(tracepacket)Descargar una grabación existente a la DeviceTrace
El siguiente fragmento de código se basa en la opción «Crear un DeviceTrace« fragmento».
traceObject = projects.primary.find("Device", "DeviceTrace")[0]
editor = traceObject.open_editor()
editor.upload_to_device_trace("CpuCoreLoad")Qué es lo que no funciona con el DeviceTrace
Acceso a
traceobject.variable_listCreación de variables de traza mediante
traceobject.add_variable())Acceso a
traceobject.diagrams