OpenC3/cosmos

View on GitHub
docs/assets/js/42170351.6fe86f8a.js

Summary

Maintainability
A
0 mins
Test Coverage
"use strict";(self.webpackChunkdocs_openc3_com=self.webpackChunkdocs_openc3_com||[]).push([[3440],{7305:(e,n,t)=>{t.r(n),t.d(n,{assets:()=>l,contentTitle:()=>a,default:()=>h,frontMatter:()=>r,metadata:()=>o,toc:()=>c});var i=t(4848),s=t(8453);const r={title:"Script Writing Guide"},a=void 0,o={id:"guides/script-writing",title:"Script Writing Guide",description:"Introduction",source:"@site/docs/guides/script-writing.md",sourceDirName:"guides",slug:"/guides/script-writing",permalink:"/docs/guides/script-writing",draft:!1,unlisted:!1,editUrl:"https://github.com/OpenC3/cosmos/tree/main/docs.openc3.com/docs/guides/script-writing.md",tags:[],version:"current",frontMatter:{title:"Script Writing Guide"},sidebar:"defaultSidebar",previous:{title:"Raspberry Pi",permalink:"/docs/guides/raspberrypi"},next:{title:"Scripting API Guide",permalink:"/docs/guides/scripting-api"}},l={},c=[{value:"Introduction",id:"introduction",level:2},{value:"Concepts",id:"concepts",level:2},{value:"Ruby vs Python in COSMOS",id:"ruby-vs-python-in-cosmos",level:3},{value:"Scripting Philosophy",id:"scripting-philosophy",level:2},{value:"A Super Basic Script Example",id:"a-super-basic-script-example",level:3},{value:"KISS (Keep It Simple Stupid)",id:"kiss-keep-it-simple-stupid",level:3},{value:"Keep things DRY (Don&#39;t Repeat Yourself)",id:"keep-things-dry-dont-repeat-yourself",level:3},{value:"Use Comments Appropriately",id:"use-comments-appropriately",level:3},{value:"Script Runner",id:"script-runner",level:3},{value:"Looping vs Unrolled Loops",id:"looping-vs-unrolled-loops",level:3},{value:"Script Organization",id:"script-organization",level:2},{value:"Organizing Your Scripts into a Plugin",id:"organizing-your-scripts-into-a-plugin",level:3},{value:"Organize Scripts into Methods",id:"organize-scripts-into-methods",level:3},{value:"Using Classes vs Unscoped Methods",id:"using-classes-vs-unscoped-methods",level:3},{value:"Instrumented vs Uninstrumented Lines (require vs load)",id:"instrumented-vs-uninstrumented-lines-require-vs-load",level:3},{value:"Debugging and Auditing",id:"debugging-and-auditing",level:2},{value:"Built-In Debugging Capabilities",id:"built-in-debugging-capabilities",level:3},{value:"Breakpoints",id:"breakpoints",level:3},{value:"Using Disconnect Mode",id:"using-disconnect-mode",level:3},{value:"Auditing your Scripts",id:"auditing-your-scripts",level:3},{value:"Ruby Syntax Check",id:"ruby-syntax-check",level:4},{value:"Common Scenarios",id:"common-scenarios",level:2},{value:"User Input Best Practices",id:"user-input-best-practices",level:3},{value:"Conditionally Require Manual User Input Steps",id:"conditionally-require-manual-user-input-steps",level:3},{value:"Outputting Extra Information to a Report",id:"outputting-extra-information-to-a-report",level:3},{value:"Getting the Most Recent Value of a Telemetry Point from Multiple Packets",id:"getting-the-most-recent-value-of-a-telemetry-point-from-multiple-packets",level:3},{value:"Checking Every Single Sample of a Telemetry Point",id:"checking-every-single-sample-of-a-telemetry-point",level:3},{value:"Using Variables in Mnemonics",id:"using-variables-in-mnemonics",level:3},{value:"Using Custom wait_check_expression",id:"using-custom-wait_check_expression",level:3},{value:"COSMOS Scripting Differences from Regular Ruby Scripting",id:"cosmos-scripting-differences-from-regular-ruby-scripting",level:3},{value:"Do not use single line if statements",id:"do-not-use-single-line-if-statements",level:4},{value:"When Things Go Wrong",id:"when-things-go-wrong",level:2},{value:"Common Reasons Checks Fail",id:"common-reasons-checks-fail",level:3},{value:"How to Recover from Anomalies",id:"how-to-recover-from-anomalies",level:3},{value:"Advanced Topics",id:"advanced-topics",level:2},{value:"Advanced Script Configuration with CSV or Excel",id:"advanced-script-configuration-with-csv-or-excel",level:3},{value:"When to use Ruby Modules",id:"when-to-use-ruby-modules",level:3}];function d(e){const n={a:"a",admonition:"admonition",code:"code",h2:"h2",h3:"h3",h4:"h4",li:"li",ol:"ol",p:"p",pre:"pre",table:"table",tbody:"tbody",td:"td",th:"th",thead:"thead",tr:"tr",ul:"ul",...(0,s.R)(),...e.components};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(n.h2,{id:"introduction",children:"Introduction"}),"\n",(0,i.jsx)(n.p,{children:"This guide aims to provide the best practices for using the scripting capabilities provided by COSMOS. Scripts are used to automate a series of activities for operations or testing. The goal of this document is to ensure scripts are written that are simple, easy to understand, maintainable, and correct. Guidance on some of the key details of using the COSMOS Script Runner is also provided."}),"\n",(0,i.jsx)(n.h2,{id:"concepts",children:"Concepts"}),"\n",(0,i.jsx)(n.p,{children:"COSMOS supports both Ruby and Python for writing scripts. Ruby and Python are very similar scripting languages and most of this guide applies directly to both. Where examples are used, both a Ruby and Python example are given."}),"\n",(0,i.jsx)(n.h3,{id:"ruby-vs-python-in-cosmos",children:"Ruby vs Python in COSMOS"}),"\n",(0,i.jsx)(n.p,{children:"There are many similarities and a few key differences between Ruby and Python when it comes to writing COSMOS scripts."}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsx)(n.li,{children:"There is no 80 character limit on line length. Lines can be as long as you like, but be careful to not make them too long as it makes printed reviews of scripts more difficult."}),"\n",(0,i.jsxs)(n.li,{children:["Indentation white space:","\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsxs)(n.li,{children:["Ruby: Not significant. Ruby uses the ",(0,i.jsx)(n.code,{children:"end"})," keyword to determine indented code blocks with a standard of 2 spaces."]}),"\n",(0,i.jsx)(n.li,{children:"Python: Significant. Python uses indentation to determine code blocks with a standard of 4 spaces."}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.li,{children:"Variables do not have to be declared ahead of time and can be reassigned later, i.e. Ruby and Python are dynamically typed."}),"\n",(0,i.jsxs)(n.li,{children:["Variable interpolation:","\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsxs)(n.li,{children:["Ruby: Variable values can be placed into strings using the ",(0,i.jsx)(n.code,{children:'"#{variable}"'})," syntax."]}),"\n",(0,i.jsxs)(n.li,{children:["Python: Variable values can be placed into f-strings using the ",(0,i.jsx)(n.code,{children:'f"{variable}"'})," syntax."]}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.li,{children:"A variable declared inside of a block or loop will not exist outside of that block unless it was already declared."}),"\n"]}),"\n",(0,i.jsx)(n.p,{children:"Both languages provides a script writer a lot of power. But with great power comes great responsibility. Remember when writing your scripts that you or someone else will come along later and need to understand them. Therefore use the following style guidelines:"}),"\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:"Use consistent spacing for indentation and do NOT use tabs"}),"\n",(0,i.jsxs)(n.li,{children:["Constants should be all caps with underscores","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"SPEED_OF_LIGHT = 299792458 # meters per s"})}),"\n"]}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["Variable names and method names should be in lowercase with underscores","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:'last_name = "Smith"'})}),"\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"perform_setup_operation()"})}),"\n"]}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["Class names (when used) should be camel case and the files which contain them should match but be lowercase with underscores","\n",(0,i.jsxs)(n.ul,{children:["\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"class DataUploader # in 'data_uploader.rb'"})}),"\n",(0,i.jsx)(n.li,{children:(0,i.jsx)(n.code,{children:"class CcsdsUtility: # in 'ccsds_utility.py'"})}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.li,{children:"Don't add useless comments but instead describe intent"}),"\n"]}),"\n",(0,i.jsx)("div",{style:{clear:"both"}}),"\n",(0,i.jsx)(n.p,{children:"The following is an example of good Ruby style:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"load 'TARGET/lib/upload_utility.rb' # library we do NOT want to show executing\nload_utility 'TARGET/lib/helper_utility.rb' # library we do want to show executing\n\n# Declare constants\nOUR_TARGETS = ['INST','INST2']\n\n# Clear the collect counter of the passed in target name\ndef clear_collects(target)\n  cmd(\"#{target} CLEAR\")\n  wait_check(\"#{target} HEALTH_STATUS COLLECTS == 0\", 5)\nend\n\n######################################\n# START\n######################################\nhelper = HelperUtility.new\nhelper.setup\n\n# Perform collects on all the targets\nOUR_TARGETS.each do |target|\n  collects = tlm(\"#{target} HEALTH_STATUS COLLECTS\")\n  cmd(\"#{target} COLLECT with TYPE SPECIAL\")\n  wait_check(\"#{target} HEALTH_STATUS COLLECTS == #{collects + 1}\", 5)\nend\n\nclear_collects('INST')\nclear_collects('INST2')\n"})}),"\n",(0,i.jsx)(n.p,{children:"The following is an example of good Python style:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"from openc3.script import *\n\nimport TARGET.lib.upload_utility # library we do NOT want to show executing\nload_utility('TARGET/lib/helper_utility.rb') # library we do want to show executing\n\n# Declare constants\nOUR_TARGETS = ['INST','INST2']\n\n# Clear the collect counter of the passed in target name\ndef clear_collects(target):\n    cmd(f\"{target} CLEAR\")\n    wait_check(f\"{target} HEALTH_STATUS COLLECTS == 0\", 5)\n\n######################################\n# START\n######################################\nhelper = HelperUtility()\nhelper.setup()\n\n# Perform collects on all the targets\nfor target in OUR_TARGETS:\n    collects = tlm(f\"{target} HEALTH_STATUS COLLECTS\")\n    cmd(f\"{target} COLLECT with TYPE SPECIAL\")\n    wait_check(f\"{target} HEALTH_STATUS COLLECTS == {collects + 1}\", 5)\n\nclear_collects('INST')\nclear_collects('INST2')\n"})}),"\n",(0,i.jsx)(n.p,{children:"Both examples shows several features of COSMOS scripting in action. Notice the difference between 'load' or 'import' and 'load_utility'. The first is to load additional scripts which will NOT be shown in Script Runner when executing. This is a good place to put code which takes a long time to run such as image analysis or other looping code where you just want the output. 'load_utility' will visually execute the code line by line to show the user what is happening."}),"\n",(0,i.jsx)(n.p,{children:"Next we declare our constants and create an array of strings which we store in OUR_TARGETS. Notice the constant is all uppercase with underscores."}),"\n",(0,i.jsx)(n.p,{children:"Then we declare our local methods of which we have one called clear_collects. Please provide a comment at the beginning of each method describing what it does and the parameters that it takes."}),"\n",(0,i.jsx)(n.p,{children:"The 'helper_utility' is then created. Note the similarity in the class name and the file name we loaded."}),"\n",(0,i.jsxs)(n.p,{children:["The collect example shows how you can iterate over the array of strings we previously created and use variables when commanding and checking telemetry. The Ruby pound bracket #",' notation and python f-string f"'," notation puts whatever the variable holds into the string. You can even execute additional code inside the brackets like we do when checking for the collect count to increment."]}),"\n",(0,i.jsx)(n.p,{children:"Finally we call our 'clear_collects' method on each target by passing the target name."}),"\n",(0,i.jsx)(n.h2,{id:"scripting-philosophy",children:"Scripting Philosophy"}),"\n",(0,i.jsx)(n.h3,{id:"a-super-basic-script-example",children:"A Super Basic Script Example"}),"\n",(0,i.jsx)(n.p,{children:"Most COSMOS scripts can be broken down into the simple pattern of sending a command to a system/subsystem and then verifying that the command worked as expected. This pattern is most commonly implemented with cmd() followed by wait_check(), like the following:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'cmd("INST COLLECT with TYPE NORMAL, TEMP 10.0")\nwait_check("INST HEALTH_STATUS TYPE == \'NORMAL\'", 5)\n'})}),"\n",(0,i.jsx)(n.p,{children:"or similarly with a counter that is sampled before the command."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'count = tlm("INST HEALTH_STATUS COLLECTS")\ncmd("INST COLLECT with TYPE NORMAL, TEMP 10.0")\nwait_check("INST HEALTH_STATUS COLLECTS >= #{count + 1}", 5)\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'count = tlm("INST HEALTH_STATUS COLLECTS")\ncmd("INST COLLECT with TYPE NORMAL, TEMP 10.0")\nwait_check(f"INST HEALTH_STATUS COLLECTS >= {count + 1}", 5)\n'})}),"\n",(0,i.jsx)(n.p,{children:"90% of the COSMOS scripts you write should be the simple patterns shown above except that you may need to check more than one item after each command to make sure the command worked as expected."}),"\n",(0,i.jsx)(n.h3,{id:"kiss-keep-it-simple-stupid",children:"KISS (Keep It Simple Stupid)"}),"\n",(0,i.jsx)(n.p,{children:"Ruby and Python are very powerful languages with many ways to accomplish the same thing. Given that, always choose the method that is easiest to understand for yourself and others. While it is possible to create complex one liners or obtuse regular expressions, you'll thank yourself later by expanding complex one liners and breaking up and documenting regular expressions."}),"\n",(0,i.jsx)(n.h3,{id:"keep-things-dry-dont-repeat-yourself",children:"Keep things DRY (Don't Repeat Yourself)"}),"\n",(0,i.jsx)(n.p,{children:"A widespread problem in scripts written for any command and control system is large blocks of code that are repeated multiple times. In extreme cases, this has led to 100,000+ line scripts that are impossible to maintain and review."}),"\n",(0,i.jsx)(n.p,{children:"There are two common ways repetition presents itself: exact blocks of code to perform a common action such as powering on a subsystem, and blocks of code that only differ in the name of the mnemonic being checked or the values checked against. Both are solved by removing the repetition using methods (or functions)."}),"\n",(0,i.jsx)(n.p,{children:"For example, a script that powers on a subsystem and ensures correct telemetry would become:"}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"def power_on_subsystem\n  # 100 lines of cmd(), wait_check(), etc\nend\n"})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"def power_on_subsystem():\n    # 100 lines of cmd(), wait_check(), etc\n"})}),"\n",(0,i.jsx)(n.p,{children:"Ideally, the above methods would be stored in another file where it could be used by other scripts. If it is truly only useful in the one script, then it could be at the top of the file. The updated script would then look like:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"power_on_subsystem()\n# 150 lines operating the subsystem (e.g.)\n# cmd(...)\n# wait_check(...)\n#...\npower_off_subystem()\n# Unrelated activities\npower_on_subsystem()\n# etc.\n"})}),"\n",(0,i.jsx)(n.p,{children:"Blocks of code where only the only variation is the mnemonics or values checked can be replaced by methods with arguments."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'def test_minimum_temp(enable_cmd_name, enable_tlm, temp_tlm, expected_temp)\n  cmd("TARGET #{enable_cmd_name} with ENABLE TRUE")\n  wait_check("TARGET #{enable_tlm} == \'TRUE\'", 5)\n  wait_check("TARGET #{temp_tlm} >= #{expected_temp}", 50)\nend\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'def test_minimum_temp(enable_cmd_name, enable_tlm, temp_tlm, expected_temp):\n    cmd(f"TARGET {enable_cmd_name} with ENABLE TRUE")\n    wait_check(f"TARGET {enable_tlm} == \'TRUE\'", 5)\n    wait_check(f"TARGET {temp_tlm} >= {expected_temp}", 50)\n'})}),"\n",(0,i.jsx)(n.h3,{id:"use-comments-appropriately",children:"Use Comments Appropriately"}),"\n",(0,i.jsx)(n.p,{children:"Use comments when what you are doing is unclear or there is a higher-level purpose to a set of lines. Try to avoid putting numbers or other details in a comment as they can become out of sync with the underlying code. Ruby and Python comments start with a # pound symbol and can be anywhere on a line."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'# This line sends an abort command - BAD COMMENT, UNNECESSARY\ncmd("INST ABORT")\n# Rotate the gimbal to look at the calibration target - GOOD COMMENT\ncmd("INST ROTATE with ANGLE 180.0") # Rotate 180 degrees - BAD COMMENT\n'})}),"\n",(0,i.jsx)(n.h3,{id:"script-runner",children:"Script Runner"}),"\n",(0,i.jsx)(n.p,{children:"COSMOS provides two unique ways to run scripts (also known as procedures). Script Runner provides both a script execution environment and a script editor. The script editor includes code completion for both COSMOS methods and command/telemetry item names. It is also a great environment to develop and test scripts. Script Runner provides a framework for users that are familiar with a traditional scripting model with longer style procedures, and for users that want to be able to edit their scripts in place."}),"\n",(0,i.jsx)(n.p,{children:"When opening a suite file (named with 'suite') Script Runner provides a more formal, but also more powerful, environment for running scripts. Suite files breaks scripts down into suites, groups, and scripts (individual methods). Suites are the highest-level concept and would typically cover a large procedure such as a thermal vacuum test, or a large operations scenario such as performing on orbit checkout. Groups capture a related set of scripts such as all the scripts regarding a specific mechanism. A Group might be a collection of scripts all related to a subsystem, or a specific series of tests such as an RF checkout. Scripts capture individual activities that can either pass or fail. Script Runner allows for running an entire suite, one or more groups, or one or more scripts easily. It also automatically produces reports containing timing, pass / fail counts, etc."}),"\n",(0,i.jsx)(n.p,{children:"The correct environment for the job is up to individual users, and many programs will use both script formats to complete their goals."}),"\n",(0,i.jsx)(n.h3,{id:"looping-vs-unrolled-loops",children:"Looping vs Unrolled Loops"}),"\n",(0,i.jsx)(n.p,{children:"Loops are powerful constructs that allow you to perform the same operations multiple times without having to rewrite the same code over and over (See the DRY Concept). However, they can make restarting a COSMOS script at the point of a failure difficult or impossible. If there is a low probability of something failing, then loops are an excellent choice. If a script is running a loop over a list of telemetry points, it may be a better choice to \u201cunroll\u201d the loop by making the loop body into a method, and then calling that method directly for each iteration of a loop that would have occurred."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"10.times do |temperature_number|\n  check_temperature(temperature_number + 1)\nend\n"})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"for temperature_number in range(1, 11):\n    check_temperature(temperature_number)\n"})}),"\n",(0,i.jsx)(n.p,{children:"If the above script was stopped after temperature number 3, there would be no way to restart the loop at temperature number 4. A better solution for small loop counts is to unroll the loop."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"check_temperature(1)\ncheck_temperature(2)\ncheck_temperature(3)\ncheck_temperature(4)\ncheck_temperature(5)\ncheck_temperature(6)\ncheck_temperature(7)\ncheck_temperature(8)\ncheck_temperature(9)\ncheck_temperature(10)\n"})}),"\n",(0,i.jsx)(n.p,{children:"In the unrolled version above, the COSMOS \u201cStart script at selected line\u201d feature can be used to resume the script at any point."}),"\n",(0,i.jsx)(n.h2,{id:"script-organization",children:"Script Organization"}),"\n",(0,i.jsxs)(n.p,{children:["All scripts must be part of a ",(0,i.jsx)(n.a,{href:"/docs/configuration/plugins",children:"Plugin"}),". You can create a simple plugin called SCRIPTS or PROCEDURES that only contains lib and procedures directories to store scripts. If COSMOS detects a plugin without defined cmd/tlm it will not spawn microservices for telemetry processing."]}),"\n",(0,i.jsx)(n.h3,{id:"organizing-your-scripts-into-a-plugin",children:"Organizing Your Scripts into a Plugin"}),"\n",(0,i.jsx)(n.p,{children:"As your scripts become large with many methods, it makes sense to break them up into multiple files within a plugin. Here is a recommended organization for your plugin's scripts/procedures."}),"\n",(0,i.jsxs)(n.table,{children:[(0,i.jsx)(n.thead,{children:(0,i.jsxs)(n.tr,{children:[(0,i.jsx)(n.th,{children:"Folder"}),(0,i.jsx)(n.th,{children:"Description"})]})}),(0,i.jsxs)(n.tbody,{children:[(0,i.jsxs)(n.tr,{children:[(0,i.jsx)(n.td,{children:"targets/TARGET_NAME/lib"}),(0,i.jsx)(n.td,{children:"Place script files containing reusable target specific methods here"})]}),(0,i.jsxs)(n.tr,{children:[(0,i.jsx)(n.td,{children:"targets/TARGET_NAME/procedures"}),(0,i.jsx)(n.td,{children:"Place simple procedures that are centered around one specific target here"})]})]})]}),"\n",(0,i.jsx)(n.p,{children:"In your main procedure you will usually bring in the other files with instrumentation using load_utility."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"# Ruby:\nload_utility('TARGET/lib/my_other_script.rb')\n# Python:\nload_utility('TARGET/procedures/my_other_script.py')\n"})}),"\n",(0,i.jsx)(n.h3,{id:"organize-scripts-into-methods",children:"Organize Scripts into Methods"}),"\n",(0,i.jsx)(n.p,{children:"Put each activity into a distinct method. Putting your scripts into methods makes organization easy and gives a great high-level overview of what the overall script does (assuming you name the methods well). There are no bonus points for vague, short method names. Make your method names long and clear."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'def test_1_heater_zone_control\n  puts "Verifies requirements 304, 306, and 310"\n  # Test code here\nend\n\ndef script_1_heater_zone_control\n  puts "Verifies requirements 304, 306, and 310"\n  # Test code here\nend\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'def test_1_heater_zone_control():\n    print("Verifies requirements 304, 306, and 310")\n    # Test code here\n\ndef script_1_heater_zone_control():\n    print("Verifies requirements 304, 306, and 310")\n    # Test code here\n'})}),"\n",(0,i.jsx)(n.h3,{id:"using-classes-vs-unscoped-methods",children:"Using Classes vs Unscoped Methods"}),"\n",(0,i.jsx)(n.p,{children:"Classes in object-oriented programming allow you to organize a set of related methods and some associated state. The most important aspect is that the methods work on some shared state. For example, if you have code that moves a gimbal around, and need to keep track of the number of moves, or steps, performed across methods, then that is a wonderful place to use a class. If you just need a helper method to do something that happens multiple times in a script without copy and pasting, it probably does not need to be in a class."}),"\n",(0,i.jsx)(n.p,{children:"NOTE: The convention in COSMOS is to have a TARGET/lib/target.[rb/py] file which is named after the TARGET name and contains a class called Target. This discussion refers to scripts in the TARGET/procedures directory."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'class Gimbal\n  attr_accessor :gimbal_steps\n  def initialize()\n    @gimbal_steps = 0\n  end\n  def move(steps_to_move)\n    # Move the gimbal\n    @gimbal_steps += steps_to_move\n  end\n  def home_gimbal\n    # Home the gimbal\n    @gimbal_steps = 0\n  end\nend\n\ndef perform_common_math(x, y)\n  x + y\nend\n\ngimbal = Gimbal.new\ngimbal.home_gimbal\ngimbal.move(100)\ngimbal.move(200)\nputs "Moved gimbal #{gimbal.gimbal_steps}"\nresult = perform_common_math(gimbal.gimbal_steps, 10)\nputs "Math:#{result}"\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'class Gimbal:\n    def __init__(self):\n        self.gimbal_steps = 0\n\n    def move(self, steps_to_move):\n        # Move the gimbal\n        self.gimbal_steps += steps_to_move\n\n    def home_gimbal(self):\n        # Home the gimbal\n        self.gimbal_steps = 0\n\ndef perform_common_math(x, y):\n    return x + y\n\ngimbal = Gimbal()\ngimbal.home_gimbal()\ngimbal.move(100)\ngimbal.move(200)\nprint(f"Moved gimbal {gimbal.gimbal_steps}")\nresult = perform_common_math(gimbal.gimbal_steps, 10)\nprint(f"Math:{result}")\n'})}),"\n",(0,i.jsx)(n.h3,{id:"instrumented-vs-uninstrumented-lines-require-vs-load",children:"Instrumented vs Uninstrumented Lines (require vs load)"}),"\n",(0,i.jsx)(n.p,{children:"COSMOS scripts are normally \u201cinstrumented\u201d. This means that each line has some extra code added behind the scenes that primarily highlights the current executing line and catches exceptions if things fail such as a wait_check. If your script needs to use code in other files, there are a few ways to bring in that code. Some techniques bring in instrumented code and others bring in uninstrumented code. There are reasons to use both."}),"\n",(0,i.jsx)(n.p,{children:"load_utility (and the deprecated require_utility), bring in instrumented code from other files. When COSMOS runs the code in the other file, Script Runner will dive into the other file and show each line highlighted as it executes. This should be the default way to bring in other files, as it allows continuing if something fails, and provides better visibility to operators."}),"\n",(0,i.jsx)(n.p,{children:"However, sometimes you don't want to display code executing from other files. Externally developed libraries generally do not like to be instrumented, and code that contains large loops or that just takes a long time to execute when highlighting lines, will be much faster if included in a method that does not instrument lines. Ruby provides two ways to bring in uninstrumented code. The first is the \u201cload\u201d keyword. Load will bring in the code from another file and will bring in any changes to the file if it is updated on the next call to load. \u201crequire\u201d is like load but is optimized to only bring in the code from another file once. Therefore, if you use require and then change the file it requires, you must restart Script Runner to re-require the file and bring in the changes. In general, load is recommended over require for COSMOS scripting. One gotcha with load is that it requires the full filename including extension, while the require keyword does not."}),"\n",(0,i.jsx)(n.p,{children:"In Python, libraries are included using the import syntax. Any code imported using import is not instrumented. Only the code imported using load_utility is instrumented."}),"\n",(0,i.jsx)(n.p,{children:"Finally, COSMOS scripting has a special syntax for disabling instrumentation in the middle of an instrumented script, with the disable_instrumentation method. This allows you to disable instrumentation for large loops and other activities that are too slow when running instrumented."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"temp = 0\ndisable_instrumentation do\n  # Make sure nothing in here will raise exceptions!\n  5000000.times do\n    temp += 1\n  end\nend\nputs temp\n"})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"temp = 0\nwith disable_instrumentation():\n    # Make sure nothing in here will raise exceptions!\n    for x in range(0,5000000):\n        temp += 1\nprint(temp)\n"})}),"\n",(0,i.jsx)(n.admonition,{title:"When Running Uninstrumented Code",type:"warning",children:(0,i.jsx)(n.p,{children:"Make sure that the code will not raise any exceptions or have any check failures. If an exception is raised from uninstrumented code, then your entire script will stop."})}),"\n",(0,i.jsx)(n.h2,{id:"debugging-and-auditing",children:"Debugging and Auditing"}),"\n",(0,i.jsx)(n.h3,{id:"built-in-debugging-capabilities",children:"Built-In Debugging Capabilities"}),"\n",(0,i.jsx)(n.p,{children:"Script Runner has built in debugging capabilities that can be useful in determining why your script is behaving in a certain way. Of primary importance is the ability to inspect and set script variables."}),"\n",(0,i.jsx)(n.p,{children:"To use the debugging functionality, first select the \u201cToggle Debug\u201d option from the Script Menu. This will add a small Debug: prompt to the bottom of the tool. Any code entered in this prompt will be executed when Enter is pressed. To inspect variables in a running script, pause the script and then type the variable name to print out the value of the variable in the debug prompt."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"variable_name\n"})}),"\n",(0,i.jsx)(n.p,{children:"Variables can also be set simply by using equals."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"variable_name = 5\n"})}),"\n",(0,i.jsx)(n.p,{children:"If necessary, you can also inject commands from the debug prompt using the normal commanding methods. These commands will be logged to the Script Runner message log, which may be advantageous over using a different COSMOS tool like CmdSender (where the command would only be logged in the CmdTlmServer message log)."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'cmd("INST COLLECT with TYPE NORMAL")\n'})}),"\n",(0,i.jsx)(n.p,{children:"Note that the debug prompt keeps the command history and you can scroll through the history by using the up and down arrows."}),"\n",(0,i.jsx)(n.h3,{id:"breakpoints",children:"Breakpoints"}),"\n",(0,i.jsx)(n.p,{children:"You can click the line number (left side gutter) in Script Runner to add a breakpoint. The script will automatically pause when it hits the breakpoint. Once stopped at the breakpoint, you can evaluate variables using the Debug line."}),"\n",(0,i.jsx)(n.h3,{id:"using-disconnect-mode",children:"Using Disconnect Mode"}),"\n",(0,i.jsx)(n.p,{children:"Disconnect mode is a feature of Script Runner that allows testing scripts in an environment without real hardware in the loop. Disconnect mode is started by selecting Script -> Toggle Disconnect. Once selected, the user is prompted to select which targets to disconnect. By default, all targets are disconnected, which allows for testing scripts without any real hardware. Optionally, only a subset of targets can be selected which can be useful for trying out scripts in partially integrated environments."}),"\n",(0,i.jsx)(n.p,{children:"While in disconnect mode, commands to the disconnected targets always succeed. Additionally, all checks of disconnected targets' telemetry are immediately successful. This allows for a quick run-through of procedures for logic errors and other script specific errors without having to worry about the behavior and proper functioning of hardware."}),"\n",(0,i.jsx)(n.h3,{id:"auditing-your-scripts",children:"Auditing your Scripts"}),"\n",(0,i.jsx)(n.p,{children:"Script Runner includes several tools to help audit your scripts both before and after execution."}),"\n",(0,i.jsx)(n.h4,{id:"ruby-syntax-check",children:"Ruby Syntax Check"}),"\n",(0,i.jsx)(n.p,{children:"The Ruby Syntax Check tool is found under the Script Menu. This tool uses the ruby executable with the -c flag to run a syntax check on your script. If any syntax errors are found the exact message presented by the Ruby interpreter is shown to the user. These can be cryptic, but the most common faults are not closing a quoted string, forgetting an \u201cend\u201d keyword, or using a block but forgetting the proceeding \u201cdo\u201d keyword."}),"\n",(0,i.jsx)(n.h2,{id:"common-scenarios",children:"Common Scenarios"}),"\n",(0,i.jsx)(n.h3,{id:"user-input-best-practices",children:"User Input Best Practices"}),"\n",(0,i.jsx)(n.p,{children:"COSMOS provides several different methods to gather manual user input in scripts. When using user input methods that allow for arbitrary values (like ask() and ask_string()), it is very important to validate the value given in your script before moving on. When asking for text input, it is extra important to handle different casing possibilities and to ensure that invalid input will either re-prompt the user or take a safe path."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'answer = ask_string("Do you want to continue (y/n)?")\nif answer != \'y\' and answer != \'Y\'\n  raise "User entered: #{answer}"\nend\n\ntemp = 0.0\nwhile temp < 10.0 or temp > 50.0\n  temp = ask("Enter the desired temperature between 10.0 and 50.0")\nend\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'answer = ask_string("Do you want to continue (y/n)?")\nif answer != \'y\' and answer != \'Y\':\n    raise RuntimeError(f"User entered: {answer}")\n\ntemp = 0.0\nwhile temp < 10.0 or temp > 50.0:\n    temp = ask("Enter the desired temperature between 10.0 and 50.0")\n'})}),"\n",(0,i.jsx)(n.p,{children:"When possible, always use one of the other user input methods that has a constrained list of choices for your users (message_box, vertical_message_box, combo_box)."}),"\n",(0,i.jsx)(n.p,{children:"Note that all these user input methods provide the user the option to \u201cCancel\u201d. When cancel is clicked, the script is paused but remains at the user input line. When hitting \u201cGo\u201d to the continue, the user will be re-prompted to enter the value."}),"\n",(0,i.jsx)(n.h3,{id:"conditionally-require-manual-user-input-steps",children:"Conditionally Require Manual User Input Steps"}),"\n",(0,i.jsx)(n.p,{children:"When possible, a useful design pattern is to write your scripts such that they can run without prompting for any user input. This allows the scripts to be more easily tested and provides a documented default value for any user input choices or values. To implement this pattern, all manual steps such as ask(), prompt(), and infinite wait() statements need to be wrapped with an if statement that checks the value of $manual in Ruby or RunningScript.manual in Python. If the variable is set, then the manual steps should be executed. If not, then a default value should be used."}),"\n",(0,i.jsx)(n.p,{children:"Ruby Example:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'if $manual\n  temp = ask("Please enter the temperature")\nelse\n  temp = 20.0\nend\nif !$manual\n  puts "Skipping infinite wait in auto mode"\nelse\n  wait\nend\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python Example:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'if RunningScript.manual:\n    temp = ask("Please enter the temperature")\nelse:\n    temp = 20.0\nif not RunningScript.manual:\n    print("Skipping infinite wait in auto mode")\nelse:\n    wait()\n'})}),"\n",(0,i.jsx)(n.p,{children:"When running suites, there is a checkbox at the top of the tool called \u201cManual\u201d that affects this $manual variable directly."}),"\n",(0,i.jsx)(n.h3,{id:"outputting-extra-information-to-a-report",children:"Outputting Extra Information to a Report"}),"\n",(0,i.jsx)(n.p,{children:"COSMOS Script Runner operating on a script suite automatically generates a report that shows the PASS/FAILED/SKIPPED state for each script. You can also inject arbitrary text into this report using the example as follows. Alternatively, you can simply use print text into the Script Runner message log."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'class MyGroup < OpenC3::Group\n  def script_1\n    # The following text will be placed in the report\n    OpenC3::Group.puts "Verifies requirements 304, 306, 310"\n    # This puts line will show up in the sr_messages log file\n    puts "script_1 complete"\n  end\nend\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'from openc3.script.suite import Group\nclass MyGroup(Group):\n    def script_1():\n        # The following text will be placed in the report\n        Group.print("Verifies requirements 304, 306, 310")\n        # This puts line will show up in the sr_messages log file\n        print("script_1 complete")\n'})}),"\n",(0,i.jsx)(n.h3,{id:"getting-the-most-recent-value-of-a-telemetry-point-from-multiple-packets",children:"Getting the Most Recent Value of a Telemetry Point from Multiple Packets"}),"\n",(0,i.jsx)(n.p,{children:"Some systems include high rate data points with the same name in every packet. COSMOS supports getting the most recent value of a telemetry point that is in multiple packets using a special packet name of LATEST. Assume the target INST has two packets, PACKET1 and PACKET2. Both packets have a telemetry point called TEMP."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'# Get the value of TEMP from the most recently received PACKET1\nvalue = tlm("INST PACKET1 TEMP")\n# Get the value of TEMP from the most recently received PACKET2\nvalue = tlm("INST PACKET2 TEMP")\n# Get the value of TEMP from the most recently received PACKET1 or PACKET2\nvalue = tlm("INST LATEST TEMP")\n'})}),"\n",(0,i.jsx)(n.h3,{id:"checking-every-single-sample-of-a-telemetry-point",children:"Checking Every Single Sample of a Telemetry Point"}),"\n",(0,i.jsx)(n.p,{children:"When writing COSMOS scripts, checking the most recent value of a telemetry point normally gets the job done. The tlm(), tlm_raw(), etc methods all retrieve the most recent value of a telemetry point. Sometimes you need to perform analysis on every single sample of a telemetry point. This can be done using the COSMOS packet subscription system. The packet subscription system lets you choose one or more packets and receive them all from a queue. You can then pick out the specific telemetry points you care about from each packet."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"id = subscribe_packets([['INST', 'HEALTH_STATUS'], ['INST', 'ADCS']])\nwait 1.5\nid, packets = get_packets(id)\npackets.each do |packet|\n  puts \"#{packet['PACKET_TIMESECONDS']}: #{packet['target_name']} #{packet['packet_name']}\"\nend\n# Wait for some time later and reuse the last returned ID\nid, packets = get_packets(id)\n"})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:"id = subscribe_packets([['INST', 'HEALTH_STATUS'], ['INST', 'ADCS']])\nwait(1.5)\nid, packets = get_packets(id)\nfor packet in packets:\n    print(f\"{packet['PACKET_TIMESECONDS']}: {packet['target_name']} {packet['packet_name']}\")\n# Wait for some time later and reuse the last returned ID\nid, packets = get_packets(id)\n"})}),"\n",(0,i.jsx)(n.h3,{id:"using-variables-in-mnemonics",children:"Using Variables in Mnemonics"}),"\n",(0,i.jsx)(n.p,{children:"Because command and telemetry mnemonics are just strings in COSMOS scripts, you can make use of variables in some contexts to make reusable code. For example, a method can take a target name as an input to support multiple instances of a target. You could also pass in the value for a set of numbered telemetry points."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'def example(target_name, temp_number)\n  cmd("#{target_name} COLLECT with TYPE NORMAL")\n  wait_check("#{target_name} TEMP#{temp_number} > 50.0")\nend\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'def example(target_name, temp_number):\n    cmd(f"{target_name} COLLECT with TYPE NORMAL")\n    wait_check(f"{target_name} TEMP{temp_number} > 50.0")\n'})}),"\n",(0,i.jsxs)(n.p,{children:["This can also be useful when looping through a numbered set of telemetry points but be considerate of the downsides of looping as discussed in the ",(0,i.jsx)(n.a,{href:"#looping-vs-unrolled-loops",children:"Looping vs Unrolled Loops"})," section."]}),"\n",(0,i.jsx)(n.h3,{id:"using-custom-wait_check_expression",children:"Using Custom wait_check_expression"}),"\n",(0,i.jsx)(n.p,{children:"The COSMOS wait_check_expression (and check_expression) allow you to perform more complicated checks and still stop the script with a CHECK error message if something goes wrong. For example, you can check variables against each other or check a telemetry point against a range. The exact string of text passed to wait_check_expression is repeatedly evaluated until it passes, or a timeout occurs. It is important to not use string interpolation within the actual expression or the values inside of the string interpolation syntax will only be evaluated once when it is converted into a string."}),"\n",(0,i.jsx)(n.p,{children:"Ruby:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'one = 1\ntwo = 2\n\nwait_check_expression("one == two", 1)\n# ERROR: CHECK: one == two is FALSE after waiting 1.017035 seconds\n\n# Checking an integer range\nwait_check_expression("one > 0 and one < 10 # init value one = #{one}", 1)\n'})}),"\n",(0,i.jsx)(n.p,{children:"Python:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-python",children:'one = 1\ntwo = 2\n\nwait_check_expression("one == two", 1, 0.25, locals())\n# ERROR: CHECK: one == two is FALSE after waiting 1.017035 seconds\n\n# Checking an integer range\nwait_check_expression("one > 0 and one < 10", 1, 0.25, locals())\n'})}),"\n",(0,i.jsx)(n.h3,{id:"cosmos-scripting-differences-from-regular-ruby-scripting",children:"COSMOS Scripting Differences from Regular Ruby Scripting"}),"\n",(0,i.jsx)(n.h4,{id:"do-not-use-single-line-if-statements",children:"Do not use single line if statements"}),"\n",(0,i.jsx)(n.p,{children:"COSMOS scripting instruments each line to catch exceptions if things go wrong. With single line if statements the exception handling doesn't know which part of the statement failed and cannot properly continue. If an exception is raised in a single line if statement, then the entire script will stop and not be able to continue. Do not use single line if statements in COSMOS scripts. (However, they are fine to use in interfaces and other Ruby code, just not COSMOS scripts)."}),"\n",(0,i.jsx)(n.p,{children:"Don't do this:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'run_method() if tlm("INST HEALTH_STATUS TEMP1") > 10.0\n'})}),"\n",(0,i.jsx)(n.p,{children:"Do this instead:"}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:'# It is best not to execute any code that could fail in an if statement, ie\n# tlm() could fail if the CmdTlmServer was not running or a mnemonic\n# was misspelled\ntemp1 = tlm("INST HEALTH_STATUS TEMP1")\nif temp1 > 10.0\n  run_method()\nend\n'})}),"\n",(0,i.jsx)(n.h2,{id:"when-things-go-wrong",children:"When Things Go Wrong"}),"\n",(0,i.jsx)(n.h3,{id:"common-reasons-checks-fail",children:"Common Reasons Checks Fail"}),"\n",(0,i.jsx)(n.p,{children:"There are three common reasons that checks fail in COSMOS scripts:"}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"The delay given was too short"}),"\n",(0,i.jsx)(n.p,{children:"The wait_check() method takes a timeout that indicates how long to wait for the referenced telemetry point to pass the check. The timeout needs to be large enough for the system under test to finish its action and for updated telemetry to be received. Note that the script will continue as soon as the check completes successfully. Thus, the only penalty for a longer timeout is the additional wait time in a failure condition."}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"The range or value checked against was incorrect or too stringent"}),"\n",(0,i.jsx)(n.p,{children:"Often the actual telemetry value is ok, but the expected value checked against was too tight. Loosen the ranges on checks when it makes sense. Ensure your script is using the wait_check_tolerance() routine when checking floating point numbers and verify you're using an appropriate tolerance value."}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"The check really failed"}),"\n",(0,i.jsx)(n.p,{children:"Of course, sometimes there are real failures. See the next section for how to handle them and recover."}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.h3,{id:"how-to-recover-from-anomalies",children:"How to Recover from Anomalies"}),"\n",(0,i.jsx)(n.p,{children:"Once something has failed, and your script has stopped with a pink highlighted line, how can you recover? Fortunately, COSMOS provides several mechanisms that can be used to recover after something in your script fails."}),"\n",(0,i.jsxs)(n.ol,{children:["\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"Retry"}),"\n",(0,i.jsx)(n.p,{children:"After a failure, the Script Runner \u201cPause\u201d button changes to \u201cRetry\u201d. Clicking on the Retry button will re-execute the line the failed. For failures due to timing issues, this will often resolve the issue and allow the script to continue. Make note of the failure and be sure to update your script prior to the next run."}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"Use the Debug Prompt"}),"\n",(0,i.jsx)(n.p,{children:"By selecting Script -> Toggle Debug, you can perform arbitrary actions that may be needed to correct the situation without stopping the running script. You can also inspect variables to help determine why something failed."}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"Execute Selection"}),"\n",(0,i.jsx)(n.p,{children:'If only a small section of a script needs to be run, then \u201cExecute Selection" can be used to execute only a small portion of the script. This can also be used when a script is paused or stopped in error.'}),"\n"]}),"\n",(0,i.jsxs)(n.li,{children:["\n",(0,i.jsx)(n.p,{children:"Run from here"}),"\n",(0,i.jsx)(n.p,{children:'By clicking into a script, and right clicking to select "Run from here", users can restart a script at an arbitrary point. This works well if no required variable definitions exist earlier in the script.'}),"\n"]}),"\n"]}),"\n",(0,i.jsx)(n.h2,{id:"advanced-topics",children:"Advanced Topics"}),"\n",(0,i.jsx)(n.h3,{id:"advanced-script-configuration-with-csv-or-excel",children:"Advanced Script Configuration with CSV or Excel"}),"\n",(0,i.jsx)(n.p,{children:"Using a spreadsheet to store the values for use by a script can be a great option if you have a CM-controlled script but need to be able to tweak some values for a test or if you need to use different values for different serial numbers."}),"\n",(0,i.jsx)(n.p,{children:"The Ruby CSV class be used to easily read data from CSV files (recommended for cross platform projects)."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"require 'csv'\nvalues = CSV.read('test.csv')\nputs values[0][0]\n"})}),"\n",(0,i.jsx)(n.p,{children:"If you are only using Windows, COSMOS also contains a library for reading Excel files."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"require 'openc3/win32/excel'\nss = ExcelSpreadsheet.new('C:/git/cosmos/test.xlsx')\nputs ss[0][0][0]\n"})}),"\n",(0,i.jsx)(n.h3,{id:"when-to-use-ruby-modules",children:"When to use Ruby Modules"}),"\n",(0,i.jsx)(n.p,{children:"Modules in Ruby have two purposes: namespacing and mixins. Namespacing allows having classes and methods with the same name, but with different meanings. For example, if they are namespaced, COSMOS can have a Packet class and another Ruby library can have a Packet class. This isn't typically useful for COSMOS scripting though."}),"\n",(0,i.jsx)(n.p,{children:"Mixins allow adding common methods to classes without using inheritance. Mixins can be useful to add common functionality to some classes but not others, or to break up classes into multiple files."}),"\n",(0,i.jsx)(n.pre,{children:(0,i.jsx)(n.code,{className:"language-ruby",children:"module MyModule\n  def module_method\n  end\nend\nclass MyTest < OpenC3::Group\n  include MyModule\n  def test_1\n    module_method()\n  end\nend\n"})})]})}function h(e={}){const{wrapper:n}={...(0,s.R)(),...e.components};return n?(0,i.jsx)(n,{...e,children:(0,i.jsx)(d,{...e})}):d(e)}},8453:(e,n,t)=>{t.d(n,{R:()=>a,x:()=>o});var i=t(6540);const s={},r=i.createContext(s);function a(e){const n=i.useContext(r);return i.useMemo((function(){return"function"==typeof e?e(n):{...n,...e}}),[n,e])}function o(e){let n;return n=e.disableParentContext?"function"==typeof e.components?e.components(s):e.components||s:a(e.components),i.createElement(r.Provider,{value:n},e.children)}}}]);