Beispiel #1
0
async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Growatt sensor."""
    config = config_entry.data
    username = config[CONF_USERNAME]
    password = config[CONF_PASSWORD]
    url = config.get(CONF_URL, DEFAULT_URL)
    name = config[CONF_NAME]

    api = growattServer.GrowattApi()
    api.server_url = url

    devices, plant_id = await hass.async_add_executor_job(get_device_list, api, config)

    probe = GrowattData(api, username, password, plant_id, "total")
    entities = [
        GrowattInverter(
            probe,
            name=f"{name} Total",
            unique_id=f"{plant_id}-{description.key}",
            description=description,
        )
        for description in TOTAL_SENSOR_TYPES
    ]

    # Add sensors for each device in the specified plant.
    for device in devices:
        probe = GrowattData(
            api, username, password, device["deviceSn"], device["deviceType"]
        )
        sensor_descriptions = ()
        if device["deviceType"] == "inverter":
            sensor_descriptions = INVERTER_SENSOR_TYPES
        elif device["deviceType"] == "tlx":
            probe.plant_id = plant_id
            sensor_descriptions = TLX_SENSOR_TYPES
        elif device["deviceType"] == "storage":
            probe.plant_id = plant_id
            sensor_descriptions = STORAGE_SENSOR_TYPES
        elif device["deviceType"] == "mix":
            probe.plant_id = plant_id
            sensor_descriptions = MIX_SENSOR_TYPES
        else:
            _LOGGER.debug(
                "Device type %s was found but is not supported right now",
                device["deviceType"],
            )

        entities.extend(
            [
                GrowattInverter(
                    probe,
                    name=f"{device['deviceAilas']}",
                    unique_id=f"{device['deviceSn']}-{description.key}",
                    description=description,
                )
                for description in sensor_descriptions
            ]
        )

    async_add_entities(entities, True)
Beispiel #2
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Growatt sensor."""
    username = config[CONF_USERNAME]
    password = config[CONF_PASSWORD]
    plant_id = config[CONF_PLANT_ID]
    name = config[CONF_NAME]

    api = growattServer.GrowattApi()

    # Log in to api and fetch first plant if no plant id is defined.
    login_response = api.login(username, password)
    if not login_response["success"] and login_response["errCode"] == "102":
        _LOGGER.error("Username or Password may be incorrect!")
        return
    user_id = login_response["userId"]
    if plant_id == DEFAULT_PLANT_ID:
        plant_info = api.plant_list(user_id)
        plant_id = plant_info["data"][0]["plantId"]

    # Get a list of devices for specified plant to add sensors for.
    devices = api.device_list(plant_id)
    entities = []
    probe = GrowattData(api, username, password, plant_id, "total")
    for sensor in TOTAL_SENSOR_TYPES:
        entities.append(
            GrowattInverter(probe, f"{name} Total", sensor, f"{plant_id}-{sensor}")
        )

    # Add sensors for each device in the specified plant.
    for device in devices:
        probe = GrowattData(
            api, username, password, device["deviceSn"], device["deviceType"]
        )
        sensors = []
        if device["deviceType"] == "inverter":
            sensors = INVERTER_SENSOR_TYPES
        elif device["deviceType"] == "storage":
            probe.plant_id = plant_id
            sensors = STORAGE_SENSOR_TYPES
        elif device["deviceType"] == "mix":
            probe.plant_id = plant_id
            sensors = MIX_SENSOR_TYPES
        else:
            _LOGGER.debug(
                "Device type %s was found but is not supported right now",
                device["deviceType"],
            )

        for sensor in sensors:
            entities.append(
                GrowattInverter(
                    probe,
                    f"{device['deviceAilas']}",
                    sensor,
                    f"{device['deviceSn']}-{sensor}",
                )
            )

    add_entities(entities, True)
Beispiel #3
0
async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the Growatt sensor."""
    config = config_entry.data
    username = config[CONF_USERNAME]
    password = config[CONF_PASSWORD]
    url = config[CONF_URL]
    name = config[CONF_NAME]

    api = growattServer.GrowattApi()
    api.server_url = url

    devices, plant_id = await hass.async_add_executor_job(
        get_device_list, api, config)

    entities = []
    probe = GrowattData(api, username, password, plant_id, "total")
    for sensor in TOTAL_SENSOR_TYPES:
        entities.append(
            GrowattInverter(probe, f"{name} Total", sensor,
                            f"{plant_id}-{sensor}"))

    # Add sensors for each device in the specified plant.
    for device in devices:
        probe = GrowattData(api, username, password, device["deviceSn"],
                            device["deviceType"])
        sensors = []
        if device["deviceType"] == "inverter":
            sensors = INVERTER_SENSOR_TYPES
        elif device["deviceType"] == "storage":
            probe.plant_id = plant_id
            sensors = STORAGE_SENSOR_TYPES
        elif device["deviceType"] == "mix":
            probe.plant_id = plant_id
            sensors = MIX_SENSOR_TYPES
        else:
            _LOGGER.debug(
                "Device type %s was found but is not supported right now",
                device["deviceType"],
            )

        for sensor in sensors:
            entities.append(
                GrowattInverter(
                    probe,
                    f"{device['deviceAilas']}",
                    sensor,
                    f"{device['deviceSn']}-{sensor}",
                ))

    async_add_entities(entities, True)
Beispiel #4
0
    def getGenerationValues(self):

        if not self.status:
            logger.debug("EMS Module Disabled. Skipping getGeneration")
            return 0

        api = growattServer.GrowattApi()

        try:
            logger.debug("Fetching Growatt EMS sensor values")
            login_response = api.login(self.username, self.password)
        except Exception as e:
            logger.log(
                logging.INFO4, "Error connecting to Growatt to fetching sensor values"
            )
            logger.debug(str(e))
            self.fetchFailed = True
            return False

        if not login_response:
            logger.log(logging.INFO4, "Empty Response from Growatt API")
            return False

        if login_response:
            plant_list = api.plant_list(login_response["userId"])["data"][0]
            plant_ID = plant_list["plantId"]
            inverter = api.device_list(plant_ID)[0]
            deviceAilas = inverter["deviceAilas"]
            status = api.mix_system_status(deviceAilas, plant_ID)
            plant_info = api.plant_info(plant_ID)
            device = plant_info["deviceList"][0]
            device_sn = device["deviceSn"]
            mix_status = api.mix_system_status(device_sn, plant_ID)
            self.batterySOC = float(mix_status["SOC"])
            gen_calc = float(status["pPv1"]) + float(status["pPv2"])
            gen_calc *= 1000
            gen_api = float(status["ppv"]) * 1000
            inTime = (
                self.now > datetime.time(00, 00) and self.now < self.useBatteryBefore
            )
            if self.discharginTill < self.batterySOC and inTime:
                self.discharginTill = self.useBatteryTill
                self.generatedW = gen_api + self.batteryMaxOutput
            else:
                self.discharginTill = self.useBatteryAt
                self.generatedW = gen_api
            self.consumedW = float(status["pLocalLoad"]) * 1000
        else:
            logger.log(logging.INFO4, "No response from Growatt API")
def read_growatt_data():
    api = growattServer.GrowattApi()

    LoginResponse = api.login(GROWATT_USERNAME, GROWATT_PASSWORD)
    PlantInfo = api.plant_list(LoginResponse['userId'])
    PlantId = PlantInfo["data"][0]["plantId"]

    PlantDeviceList = api.device_list(PlantId)
    PlantDetails = api.inverter_detail("QJB2823328")

    global VoltageString1
    VoltageString1 = int(PlantDetails["data"]["vpv1"])
    global CurrentString1
    CurrentString1 = int(PlantDetails["data"]["ipv1"])
    global PowerString1
    PowerString1 = int(PlantDetails["data"]["ppv1"])

    #print (json.dumps(PlantDetails, indent=4))
    #print (json.dumps(PlantDeviceList, indent=4))
    print(json.dumps(PlantInfo, indent=4))
    todayEnergy = PlantInfo['data'][0]['todayEnergy']  #get today energy
    # How to use find()
    if (todayEnergy.find(' kWh') != -1):
        #print("Contains substring ' kWh'")
        todayEnergy = todayEnergy.replace(" kWh", "")
        todayEnergy = float(todayEnergy) * 1000
    elif (todayEnergy.find(' Wh') != -1):
        #print("Contains substring ' Wh'")
        todayEnergy = todayEnergy.replace(" Wh", "")
        todayEnergy = float(todayEnergy)
    global EnergyGeneration
    EnergyGeneration = todayEnergy

    currentPower = PlantInfo['data'][0]['currentPower']  #get today energy
    # How to use find()
    if (currentPower.find(' kW') != -1):
        #print("Contains substring ' kW'")
        currentPower = currentPower.replace(" kW", "")
        currentPower = float(currentPower) * 1000
    elif (currentPower.find(' W') != -1):
        #print("Contains substring ' W'")
        currentPower = currentPower.replace(" W", "")
        currentPower = float(currentPower)
    global PowerGeneration
    PowerGeneration = currentPower
    return
Beispiel #6
0
def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up the Growatt sensor."""
    username = config[CONF_USERNAME]
    password = config[CONF_PASSWORD]
    plant_id = config[CONF_PLANT_ID]
    name = config[CONF_NAME]

    api = growattServer.GrowattApi()

    # Log in to api and fetch first plant if no plant id is defined.
    login_response = api.login(username, password)
    if not login_response["success"] and login_response["errCode"] == "102":
        _LOGGER.error("Username or Password may be incorrect!")
        return
    user_id = login_response["userId"]
    if plant_id == DEFAULT_PLANT_ID:
        plant_info = api.plant_list(user_id)
        plant_id = plant_info["data"][0]["plantId"]

    # Get a list of inverters for specified plant to add sensors for.
    inverters = api.inverter_list(plant_id)
    entities = []
    probe = GrowattData(api, username, password, plant_id, True)
    for sensor in TOTAL_SENSOR_TYPES:
        entities.append(
            GrowattInverter(probe, f"{name} Total", sensor, f"{plant_id}-{sensor}")
        )

    # Add sensors for each inverter in the specified plant.
    for inverter in inverters:
        probe = GrowattData(api, username, password, inverter["deviceSn"], False)
        for sensor in INVERTER_SENSOR_TYPES:
            entities.append(
                GrowattInverter(
                    probe,
                    f"{inverter['deviceAilas']}",
                    sensor,
                    f"{inverter['deviceSn']}-{sensor}",
                )
            )

    add_entities(entities, True)
 def __init__(self):
     """Initialise growatt server flow."""
     self.api = growattServer.GrowattApi()
     self.user_id = None
     self.data = {}
"""
A really hacky function to allow me to print out things with an indent in-front
"""
def indent_print(to_output, indent):
  indent_string = ""
  for x in range(indent):
    indent_string += " "
  print(indent_string + to_output)

#Prompt user for username
username=input("Enter username:"******"Enter password:"******"***Totals for all plants***")
pp.pprint(plant_list['totalData'])
print("")

print("***List of plants***")
for plant in plant_list['data']:
  indent_print("ID: %s, Name: %s"%(plant['plantId'], plant['plantName']), 2)
print("")

for plant in plant_list['data']: