Skip to content

Instantly share code, notes, and snippets.

@ghys
Last active March 17, 2023 21:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ghys/071cf630ede8e61634f4f7b2d90df260 to your computer and use it in GitHub Desktop.
Save ghys/071cf630ede8e61634f4f7b2d90df260 to your computer and use it in GitHub Desktop.
A shell script to sync your openHAB objects as YAML files
#!/bin/bash
OH_HOST=http://localhost:8080
OH_API_TOKEN=oh.ohadm.123abc...
operation=$1
objtype=$2
uid=$3
if [[ "$objtype" == *s ]]; then
objtype=${objtype%?}
fi
case $objtype in
"page") endpoint=ui/components/ui:page;;
"widget") endpoint=ui/components/ui:widget;;
"panelconfig") endpoint=ui/components/habpanel:panelconfig;;
"rule") endpoint=rules;;
"thing") endpoint=things;;
"item") endpoint=items;;
*) echo >&2 "Invalid object type: $objtype"; exit 1;;
esac
case $operation in
get)
case $objtype in
page|widget)
header="UID,COMPONENT,TIMESTAMP"
map="[.uid, .component, .timestamp]"
;;
rule)
header="UID,NAME,STATUS,DETAIL"
map="[.uid, .name, .status.status, .status.statusDetail]"
;;
thing)
header="UID,LABEL,TYPE,STATUS,DETAIL"
map="[.UID, .label, .thingTypeUID, .statusInfo.status, .statusInfo.statusDetail]"
;;
item)
header="NAME,TYPE,LABEL"
map="[.name, .type, .label]"
;;
esac
(echo $header; curl -sS $OH_HOST/rest/$endpoint -H "X-openhab-token: $OH_API_TOKEN" | yq e "map($map)" -o=csv - | sort) | column -t -s","
;;
describe)
curl -sS "$OH_HOST/rest/$endpoint/$uid?summary=true" -H "X-openhab-token: $OH_API_TOKEN" | yq -P e
;;
fetch)
key=uid
if [ "$objtype" == thing ]; then key=UID; fi
if [ "$objtype" == item ]; then key=name; fi
echo "Fetching ${objtype}s..."
mkdir -p ${objtype}s
curl -s -S -o ${objtype}s/_all.json $OH_HOST/rest/$endpoint -H "X-openhab-token: $OH_API_TOKEN"
yq -P e '.[]' ${objtype}s/_all.json -s "\"${objtype}s/\" + .$key"
rm ${objtype}s/_all.json
;;
create)
yq e -o=j ${objtype}s/$uid.yml | curl -i -s -S -X POST $OH_HOST/rest/$endpoint -H "Content-type: application/json" -H "X-openhab-token: $OH_API_TOKEN" --data-binary @-
echo
;;
update)
yq e -o=j ${objtype}s/$uid.yml | curl -i -s -S -X PUT $OH_HOST/rest/$endpoint/$uid -H "Content-type: application/json" -H "X-openhab-token: $OH_API_TOKEN" --data-binary @-
echo
;;
delete)
curl -i -X DELETE $OH_HOST/rest/$endpoint/$uid -H "Content-type: application/json" -H "X-openhab-token: $OH_API_TOKEN"
rm -f ${objtype}s/$uid.yml
;;
*)
echo >&2 "Invalid operation: $@"; exit 1;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment