Python Script: how to create a Sensor

As I am trying to complete my first Python script in the evolution of my newly acquired knowledge in Python, I am trying to finalize a script. I can already get the data from the web service, but I can’t have it available in HA, except by creating a sensor. Given this, I ask: does anyone have any experience with creating sensors?

I have the code below that I even tried to evolve the sensor, but I can’t conclude that I don’t know Python and HA development in depth:

# -*- coding: utf-8 -*-
import appdaemon.plugins.hass.hassapi as hass
import hassapi as hass
import requests
import json
import time
import threading

class Cotacao(hass.Hass):
#    def initialize(self):
#        self.log("Ola do AppDaemon")
#        self.log("Voce estar visualizando o seu app rodando!")

    def initialize(self):
        requisicao = requests.get("")
        cotacao = json.loads(requisicao.text)
        preco_dolar = float(cotacao['results']['currencies']['USD']['buy'])
        preco_euro = float(cotacao['results']['currencies']['EUR']['buy'])
        print("Cotação USD: R$ {:.2f}".format(preco_dolar))
        print("Cotação EUR: R$ {:.2f}".format(preco_euro))

#         safeName = ("cotacao")
#         preco_usd = (format(preco_dolar))
#         nomeSensor = "sensor.{}".format(safeName)
#         defaultIcon = "mdi:calendar-star"
#         hass.states.set(nomeSensor , preco_usd ,
#             {
#                 "icon" : data.get("icon", defaultIcon) #,
# #                "unit_of_measurement" : "days" ,
# #                "friendly_name" : "{}".format(friendlyName),
# #                "nextoccur" : "{}/{}/{}".format( , nextOccur.month , nextOccur.year) ,
# #                "years" : years
#             }
#         )

Hi Pedro,

Did you saw my reply at the Brazilian Forum? Python_Scripts in HA doesnt work the way you are expecting. There’s at least 3 other ways to do what you want: 1) sensor.command line ; 2) custom_component; 3) use the REST sensor.

1 Like

@clyra thanks for the feedback. From what I’ve studied so far, the best way will be to implement a Custom Component. You have some “basic” way of implementing the creation of these sensors.