No Curl? No problem

I’m trying to reduce the number of apk adds I use. I found by searching online there were no real solutions for clean NetCat use. I wanted it clean, and I wanted to use built-in’s only. This is a script which can replace curl. It may be slow, but for my needs it doesn’t need to be fast. This will run in hassio terminal.

echo $(nc -i 1 hassio 80 <<<unix2dos<<EOF
GET /core/api/events HTTP/1.1
Host: supervisor
User-Agent: curl/7.69.1
Accept: */*
Authorization: Bearer ${SUPERVISOR_TOKEN}
Content-Type: application/json

EOF
)|sed -e 's/.*\x0d\x20\x0d//1'

Breakdown:

echo $(nc -i 1 (HOST NAME OR IP ADDRESS) 80<<<unix2dos<<EOF
(HTTP METHOD) (API ENDPOINT) HTTP/1.1
Host: supervisor
User-Agent: curl/7.69.1
Accept: */*
Authorization: Bearer ${SUPERVISOR_TOKEN}
Content-Type: application/json

(REQUEST BODY GOES HERE FOR POST REQUESTS)

EOF
)|sed -e 's/.*\x0d\x20\x0d//1'

example of getting number of startup listeners from the supervisor into a variable called “listeners”

listeners=$(echo $(nc -i 1 hassio 80 <<<unix2dos<<EOF
GET /core/api/events HTTP/1.1
Host: supervisor
User-Agent: curl/7.69.1
Accept: */*
Authorization: Bearer ${SUPERVISOR_TOKEN}
Content-Type: application/json

EOF
)|sed -e 's/.*\x0d\x20\x0d//1'|jq '.[]|select(.event=="homeassistant_start").listener_count')
1 Like

Hacky … I love it.

So what’s the purpose of creating the variable listeners?
Is this intended to be used in a bash script or something?

Also what’s the point of running a unix2dos on the reply?
I assume this is a Linux host which would be happy with the existing line-endings on the reply

1 Like

Yes! Exactly. The variable is for a BASH script. When starting an Addon you are in BASH. Launching python would require an additional apk add the overhead of installation, and running a script in that environment. BASH is already running. So instead of launching python, I’ve been writing Add-ons that use BASH.

Http request require /r/n. Linux uses /n. unix2dos converts the heredocument into http format. This is required because the included busybox nc isn’t smart in formatting your request, and the Home Assistant server isn’t forgiving.

Didn’t know about that nuance. Guess most applications take care of that for the user!

Thanks for sharing; definitely has me thinking about a similar use case :slight_smile:

1 Like

Yeah. I’m going to create/update a sensor from my addon, and it only needs to occur once every couple of minutes on a different process from the main, so this is perfect.