Free octopus image

Get OctoPrint Status via Bash

I’m working on a module to add OctoPrint status to my zsh prompt, which I’ll probably write about in the future as a bigger post about my prompt customizations.

To start with that though, I need to play around with accessing the API via curl.

So here’s my super alpha version that will request the current status via HTTP and output it:

#!/bin/bash

OCTOPRINT_API="hunter2"
BASE_URL="http://octoprint.example.com"
JOB_ENDPOINT="${BASE_URL}/api/job"
CURL_TIMEOUT="0.5"

# Fetch the JSON from OctoPrint
response="$(curl --max-time ${CURL_TIMEOUT} --silent --fail \
  --header "X-Api-Key: ${OCTOPRINT_API}" \
  "${JOB_ENDPOINT}")"

# Extract fields with jq
file_name=$(jq -r '.job.file.display' <<< "$response")
completion=$(jq -r '.progress.completion' <<< "$response")
state=$(jq -r '.state' <<< "$response")
time_elapsed=$(jq -r '.progress.printTime' <<< "$response")
time_left=$(jq -r '.progress.printTimeLeft' <<< "$response")

# Round the completion percentage to two decimals
completion_str=$(printf "%.2f" "$completion")

# Convert seconds to H:MM:SS
function fmt_time() {
  local total_seconds="$1"
  local hours=$((total_seconds / 3600))
  local minutes=$(((total_seconds % 3600) / 60))
  local seconds=$((total_seconds % 60))
  printf "%02d:%02d:%02d" "$hours" "$minutes" "$seconds"
}

# Convert the times
time_elapsed_str=$(fmt_time "$time_elapsed")
time_left_str=$(fmt_time "$time_left")

# Print a readable summary
echo "File: ${file_name}"
echo "State: ${state}"
echo "Completion: ${completion_str}%"
echo "Time Elapsed: ${time_elapsed_str}"
echo "Time Left: ${time_left_str}"
Code language: Bash (bash)

Do with this what you will.

Other Posts Not Worth Reading

Hey, You!

Like this kind of garbage? Subscribe for more! I post like once a month or so, unless I found something interesting to write about.


Comments

Leave a Reply