Skip to content

Commit

Permalink
Merge pull request #12 from lucianor/main
Browse files Browse the repository at this point in the history
Added region switch for international customers
  • Loading branch information
faanskit authored Nov 9, 2024
2 parents 46294cf + 25fdee5 commit c305371
Show file tree
Hide file tree
Showing 5 changed files with 50 additions and 31 deletions.
3 changes: 2 additions & 1 deletion basic_test/basic_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@

USER = "NAME"
PASSWORD = "PASSWORD"
REGION="in"
OUTPUT_FILE = "output.txt"

f=open(OUTPUT_FILE, "w")
try:
print("Obtaining plant information")
plant_info = get_esolar_data(USER, PASSWORD)
plant_info = get_esolar_data(REGION, USER, PASSWORD)

print(f"\nProducing the output into {OUTPUT_FILE}")
f.write(json.dumps(plant_info))
Expand Down
5 changes: 3 additions & 2 deletions custom_components/saj_esolar_air/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import requests

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.const import CONF_REGION, CONF_PASSWORD, CONF_USERNAME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
Expand Down Expand Up @@ -487,6 +487,7 @@ def get_data(

username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
region = config.get(CONF_REGION)
plants = options.get(CONF_MONITORED_SITES)
use_pv_grid_attributes = options.get(CONF_PV_GRID_DATA)

Expand All @@ -497,7 +498,7 @@ def get_data(
plants,
use_pv_grid_attributes,
)
plant_info = get_esolar_data(username, password, plants, use_pv_grid_attributes)
plant_info = get_esolar_data(region, username, password, plants, use_pv_grid_attributes)

except requests.exceptions.HTTPError as errh:
raise requests.exceptions.HTTPError(errh)
Expand Down
12 changes: 7 additions & 5 deletions custom_components/saj_esolar_air/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.const import CONF_REGION, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError
Expand All @@ -28,6 +28,7 @@

STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_REGION, default="eu"): vol.In(["eu","in"]),
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
Expand All @@ -41,11 +42,11 @@ def __init__(self) -> None:
"""Initialize."""
self.plant_list: dict[str, Any] = {}

def auth_and_get_solar_plants(self, username: str, password: str) -> bool:
def auth_and_get_solar_plants(self, region: str, username: str, password: str) -> bool:
"""Download and list availablse inverters."""
try:
session = esolar_web_autenticate(username, password)
self.plant_list = web_get_plant(session).get("plantList")
session = esolar_web_autenticate(region, username, password)
self.plant_list = web_get_plant(region, session).get("plantList")
except requests.exceptions.HTTPError:
_LOGGER.error("Login: HTTPError")
return False
Expand All @@ -67,8 +68,9 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str,
hub = ESolarHub()
if not await hass.async_add_executor_job(
hub.auth_and_get_solar_plants,
data[CONF_REGION],
data[CONF_USERNAME],
data[CONF_PASSWORD],
data[CONF_PASSWORD]
):
raise InvalidAuth
return {"plant_list": hub.plant_list}
Expand Down
59 changes: 37 additions & 22 deletions custom_components/saj_esolar_air/esolar.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@

_LOGGER = logging.getLogger(__name__)

BASE_URL = "https://fopapp.saj-electric.com/sajAppApi/api"
BASE_URL_WEB = "https://fop.saj-electric.com/saj"
WEB_TIMEOUT = 10

BASIC_TEST = False
Expand All @@ -21,6 +19,23 @@
)


def base_url(region):
if (region == "eu"):
return "https://fopapp.saj-electric.com/sajAppApi/api"
elif (region == "in"):
return "https://intopapp.saj-electric.com/sajAppApi/api"
else:
raise ValueError("Region not set. Please run Configure again")

def base_url_web(region):
if (region == "eu"):
return "https://fop.saj-electric.com/saj"
elif (region == "in"):
return "https://intop.saj-electric.com/saj"
else:
raise ValueError("Region not set. Please run Configure again")


def add_months(sourcedate, months):
"""SAJ eSolar Helper Function - Adds a months to input."""
month = sourcedate.month - 1 + months
Expand All @@ -41,20 +56,20 @@ def add_years(source_date, years):
)


def get_esolar_data(username, password, plant_list=None, use_pv_grid_attributes=True):
def get_esolar_data(region, username, password, plant_list=None, use_pv_grid_attributes=True):
"""SAJ eSolar Data Update."""
if BASIC_TEST:
return get_esolar_data_static_h1_r5(
username, password, plant_list, use_pv_grid_attributes
region, username, password, plant_list, use_pv_grid_attributes
)

try:
plant_info = None
session = esolar_web_autenticate(username, password)
plant_info = web_get_plant(session, plant_list)
web_get_plant_details(session, plant_info)
web_get_plant_detailed_chart(session, plant_info)
web_get_device_page_list(session, plant_info, use_pv_grid_attributes)
session = esolar_web_autenticate(region, username, password)
plant_info = web_get_plant(region, session, plant_list)
web_get_plant_details(region, session, plant_info)
web_get_plant_detailed_chart(region, session, plant_info)
web_get_device_page_list(region, session, plant_info, use_pv_grid_attributes)

except requests.exceptions.HTTPError as errh:
raise requests.exceptions.HTTPError(errh)
Expand All @@ -70,15 +85,15 @@ def get_esolar_data(username, password, plant_list=None, use_pv_grid_attributes=
return plant_info


def esolar_web_autenticate(username, password):
def esolar_web_autenticate(region, username, password):
"""Authenticate the user to the SAJ's WEB Portal."""
if BASIC_TEST:
return True

try:
session = requests.Session()
response = session.post(
BASE_URL_WEB + "/login",
base_url_web(region) + "/login",
data={
"lang": "en",
"username": username,
Expand All @@ -105,7 +120,7 @@ def esolar_web_autenticate(username, password):
raise requests.exceptions.RequestException(errr)


def web_get_plant(session, requested_plant_list=None):
def web_get_plant(region, session, requested_plant_list=None):
"""Retrieve the platUid from WEB Portal using web_authenticate."""
if session is None:
raise ValueError("Missing session identifier trying to obain plants")
Expand All @@ -116,7 +131,7 @@ def web_get_plant(session, requested_plant_list=None):
try:
output_plant_list = []
response = session.post(
BASE_URL_WEB + "/monitor/site/getUserPlantList",
base_url_web(region) + "/monitor/site/getUserPlantList",
data={
"pageNo": "",
"pageSize": "",
Expand Down Expand Up @@ -157,7 +172,7 @@ def web_get_plant(session, requested_plant_list=None):
raise requests.exceptions.RequestException(errr)


def web_get_plant_details(session, plant_info):
def web_get_plant_details(region, session, plant_info):
"""Retrieve platUid from the WEB Portal using web_authenticate."""
if session is None:
raise ValueError("Missing session identifier trying to obain plants")
Expand All @@ -166,7 +181,7 @@ def web_get_plant_details(session, plant_info):
device_list = []
for plant in plant_info["plantList"]:
response = session.post(
BASE_URL_WEB + "/monitor/site/getPlantDetailInfo",
base_url_web(region) + "/monitor/site/getPlantDetailInfo",
data={
"plantuid": plant["plantuid"],
"clientDate": datetime.date.today().strftime("%Y-%m-%d"),
Expand All @@ -190,7 +205,7 @@ def web_get_plant_details(session, plant_info):
raise requests.exceptions.RequestException(errr)


def web_get_plant_detailed_chart(session, plant_info):
def web_get_plant_detailed_chart(region, session, plant_info):
"""Retrieve the kitList from the WEB Portal with web_authenticate."""
if session is None:
raise ValueError("Missing session identifier trying to obain plants")
Expand Down Expand Up @@ -227,10 +242,10 @@ def web_get_plant_detailed_chart(session, plant_info):
for inverter in plant["plantDetail"]["snList"]:
if plant["type"] == 3:
# Battery system
url = f"{BASE_URL_WEB}/monitor/site/getPlantDetailChart2?plantuid={plant['plantuid']}&chartDateType=1&energyType=0&clientDate={client_date}&deviceSnArr=&chartCountType=2&previousChartDay={previous_chart_day}&nextChartDay={next_chart_day}&chartDay={chart_day}&previousChartMonth={previous_chart_month}&nextChartMonth={next_chart_month}&chartMonth={chart_month}&previousChartYear={previous_chart_year}&nextChartYear={next_chart_year}&chartYear={chart_year}&elecDevicesn={inverter}&_={epochmilliseconds}"
url = f"{base_url_web(region)}/monitor/site/getPlantDetailChart2?plantuid={plant['plantuid']}&chartDateType=1&energyType=0&clientDate={client_date}&deviceSnArr=&chartCountType=2&previousChartDay={previous_chart_day}&nextChartDay={next_chart_day}&chartDay={chart_day}&previousChartMonth={previous_chart_month}&nextChartMonth={next_chart_month}&chartMonth={chart_month}&previousChartYear={previous_chart_year}&nextChartYear={next_chart_year}&chartYear={chart_year}&elecDevicesn={inverter}&_={epochmilliseconds}"
else:
# Normal system
url = f"{BASE_URL_WEB}/monitor/site/getPlantDetailChart2?plantuid={plant['plantuid']}&chartDateType=1&energyType=0&clientDate={client_date}&deviceSnArr={inverter}&chartCountType=2&previousChartDay={previous_chart_day}&nextChartDay={next_chart_day}&chartDay={chart_day}&previousChartMonth={previous_chart_month}&nextChartMonth={next_chart_month}&chartMonth={chart_month}&previousChartYear={previous_chart_year}&nextChartYear={next_chart_year}&chartYear={chart_year}&elecDevicesn=&_={epochmilliseconds}"
url = f"{base_url_web(region)}/monitor/site/getPlantDetailChart2?plantuid={plant['plantuid']}&chartDateType=1&energyType=0&clientDate={client_date}&deviceSnArr={inverter}&chartCountType=2&previousChartDay={previous_chart_day}&nextChartDay={next_chart_day}&chartDay={chart_day}&previousChartMonth={previous_chart_month}&nextChartMonth={next_chart_month}&chartMonth={chart_month}&previousChartYear={previous_chart_year}&nextChartYear={next_chart_year}&chartYear={chart_year}&elecDevicesn=&_={epochmilliseconds}"

_LOGGER.debug("Fetching URL : %s", url)
response = session.post(url, timeout=WEB_TIMEOUT)
Expand Down Expand Up @@ -263,7 +278,7 @@ def web_get_plant_detailed_chart(session, plant_info):
raise requests.exceptions.RequestException(errr)


def web_get_device_page_list(session, plant_info, use_pv_grid_attributes):
def web_get_device_page_list(region, session, plant_info, use_pv_grid_attributes):
"""Retrieve the platUid from the WEB Portal with web_authenticate."""
if session is None:
raise ValueError("Missing session identifier trying to obain plants")
Expand All @@ -278,7 +293,7 @@ def web_get_device_page_list(session, plant_info, use_pv_grid_attributes):
_LOGGER.debug("Plant Type: %s", plant["type"])

chart_month = datetime.date.today().strftime("%Y-%m")
url = f"{BASE_URL_WEB}/cloudMonitor/device/findDevicePageList"
url = f"{base_url_web(region)}/cloudMonitor/device/findDevicePageList"
payload = f"officeId=1&pageNo=&pageSize=&orderName=1&orderType=2&plantuid={plant['plantuid']}&deviceStatus=&localDate={datetime.date.today().strftime('%Y-%m-%d')}&localMonth={chart_month}"
_LOGGER.debug("Fetching URL : %s", url)
_LOGGER.debug("Fetching Payload: %s", payload)
Expand All @@ -298,7 +313,7 @@ def web_get_device_page_list(session, plant_info, use_pv_grid_attributes):
continue
_LOGGER.debug("Device SN: %s", device["devicesn"])
if use_pv_grid_attributes:
url = f"{BASE_URL_WEB}/cloudMonitor/deviceInfo/findRawdataPageList"
url = f"{base_url_web(region)}/cloudMonitor/deviceInfo/findRawdataPageList"
payload = f"deviceSn={device['devicesn']}&deviceType={device['type']}&timeStr={datetime.date.today().strftime('%Y-%m-%d')}"
_LOGGER.debug("Fetching URL : %s", url)
_LOGGER.debug("Fetching Payload: %s", payload)
Expand Down Expand Up @@ -336,7 +351,7 @@ def web_get_device_page_list(session, plant_info, use_pv_grid_attributes):
* 1000
)
)
url = f"{BASE_URL_WEB}/monitor/site/getStoreOrAcDevicePowerInfo"
url = f"{base_url_web(region)}/monitor/site/getStoreOrAcDevicePowerInfo"
payload = f"plantuid={plant['plantuid']}&devicesn={device['devicesn']}&_={epochmilliseconds}"
_LOGGER.debug("Fetching URL : %s", url)
_LOGGER.debug("Fetching Payload: %s", payload)
Expand Down
2 changes: 1 addition & 1 deletion custom_components/saj_esolar_air/esolar_static_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def web_get_plant_static_h1_r5():


def get_esolar_data_static_h1_r5(
username, password, plant_list, use_pv_grid_attributes
region, username, password, plant_list, use_pv_grid_attributes
):
"""SAJ eSolar Data Update - STATIC #3 TEST VERSION."""
plant_info = {
Expand Down

0 comments on commit c305371

Please sign in to comment.