RESTful Switch and Flask Server

Hello, I have a Raspberry Pi where i run Home Assistant and a small Flask Web server that I use to turn on and off a (kind of) smart bluetooth bulb from CHSmart. On Lovelace I added a RESTful switch entity and I can turn the bulb on when I toggle the switch. Unfortunately the switch quickly comes back to the “off” state even though the bulb is on and my guess is that my “get” answer on flask is wrong.
Can someone help me out?
Here is my configuration.yaml part relative to the RESTful switch:

  - platform: rest
    resource: http://127.0.0.1:8765/CHSmartBulb
    name:  CHSmartBulb
    body_on: 'true'
    body_off: 'false'

and here is the Flask python code:

@app.route(‘/CHSmartBulb’, methods = [‘GET’, ‘POST’])
def CHSmartBulb():
if request.data == b"true":
Bulb = CHSmart.CHSmartControl()
Bulb.on()
Bulb.close()
return b"true"
elif request.data == b"false":
Bulb = CHSmart.CHSmartControl()
Bulb.off()
Bulb.close()
return b"false"
else:
return “none”

Thank you in advance!

I found the right configuration, I will post it here in case it’s useful for somebody else:

Flask:

from flask import Flask, request, jsonify
import CHSmart

app = Flask(name)
app.wsgi_app = DebuggedApplication(app.wsgi_app, True)
app.debug = True

class DataStore():
CHBulbState = False
data = DataStore()

@app.route(‘/CHSmartBulb’, methods = [‘GET’, ‘POST’])
def CHSmartBulb():
if request.data == b’{“active”: “true”}‘:
Bulb = CHSmart.CHSmartControl()
Bulb.on()
Bulb.close()
data.CHBulbState = True
return jsonify({“is_active”: “true”})
elif request.data == b’{“active”: “false”}':
Bulb = CHSmart.CHSmartControl()
Bulb.off()
Bulb.close()
data.CHBulbState = False
return jsonify({“is_active”: “false”})
else:
if data.CHBulbState == True:
out = {“is_active”: “true”}
else:
out = {“is_active”: “false”}
return jsonify(out)

And my configuration.yaml:

  • platform: rest
    resource: http://127.0.0.1:8765/CHSmartBulb
    name: CHSmartBulb
    body_on: ‘{“active”: “true”}’
    body_off: ‘{“active”: “false”}’
    is_on_template: ‘{{ value_json.is_active }}’
    headers:
    Content-Type: application/json

I had to implement the “else” case with the variable because when i was toggling the switch the Home Assistant was sending twice a get request with no body and I had to handle that case as well. I guess there is something wrong and some advices on that would be appreciated, but at least in this way it works :slight_smile: