Help with python requests script for letterbox sensor and new auth system

I’m using the following code for my homemade letterbox sensor. It works fine although i’m aware it isn’t very efficient or elegant.
I’ve now started moving away from using the api password. I can’t work out where to put the long living token and if there are any other changes required. Has anyone done anything similar and could offer suggestions. It’s pickling my brain and i don’t want to lose the use of the letterbox sensor when the api password is finally discontinued.

import requests
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)

while True:
    input_state = GPIO.input(16)
    if input_state == False:
        headers = {
            'x-ha-access': 'password',
            'Content-Type': 'application/json',
        }

        data = '{ "entity_id": "script.letterbox_shut" }'

        response = requests.post('http://192.168.200.35:8123/api/services/script/turn_on', headers=headers, data=data)


        time.sleep(2.0)


    else:
        headers = {
            'x-ha-access': 'super1',
            'Content-Type': 'application/json',
        }

        data = '{ "entity_id": "script.letterbox_open" }'

        response = requests.post('http://192.168.200.35:8123/api/services/script/turn_on', headers=headers, data=data)

        time.sleep(2.0)

Maybe try this:

import requests
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.IN, pull_up_down=GPIO.PUD_UP)
headers = {
    'Authorization': 'Bearer ABCDEFGH',
    'Content-Type': 'application/json',
}

while True:
    if GPIO.input(16):
        script = 'script.letterbox_open'
    else:
        script = 'script.letterbox_shut'
    data = {
        'entity_id': script,
    }
    requests.post('http://192.168.200.35:8123/api/services/script/turn_on',
                  headers=headers,
                  data=data)
    time.sleep(2.0)

Many thanks Phil…that looks so much neater. I’ve changed Bearer to my own long lasting access token. It’s failing without leaving any trace in the home assistant log unfortunately.

Try doing it once from a Python prompt and see what requests.post is returning.

I’m not sure how to see what requests post is returning. when i run it from the cli the window hangs until i hit ctrl+c. theres no output.

I mean something like this:

python3

to invoke the Python command line interpreter. Then:

import requests
headers = {
    'Authorization': 'Bearer ABCDEFGH',
    'Content-Type': 'application/json',
}
result = requests.post(
    'http://192.168.200.35:8123/api/services/script/turn_on',
    headers=headers,
    data={'entity_id': 'script.letterbox_open'}
)
print(result)
print(result.text)