pax_global_header00006660000000000000000000000064147221571570014525gustar00rootroot0000000000000052 comment=ecb7784936747b72e560389dc6516a3989a6e322 PyPi_GrowattServer-1.6.0/000077500000000000000000000000001472215715700153105ustar00rootroot00000000000000PyPi_GrowattServer-1.6.0/.github/000077500000000000000000000000001472215715700166505ustar00rootroot00000000000000PyPi_GrowattServer-1.6.0/.github/workflows/000077500000000000000000000000001472215715700207055ustar00rootroot00000000000000PyPi_GrowattServer-1.6.0/.github/workflows/release.yml000077500000000000000000000017671472215715700230660ustar00rootroot00000000000000name: Release on: release: types: - published jobs: release: name: Build & Deploy to PyPI runs-on: ubuntu-latest steps: - name: Clone repo uses: actions/checkout@v2 # - name: Ensure latest tag is in setup.py if i forgot # run: | # sed -i "s/version=\"[0-9\.]*\"/version=\"$(git describe --tags)\"/g" setup.py # git config user.name github-actions # git config user.email github-actions@github.com # git add setup.py # git commit -m "Ensure setup.py contains the latest tag" # git push - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install dependencies run: pip install wheel - name: Build package run: python setup.py sdist bdist_wheel - name: Upload package uses: pypa/gh-action-pypi-publish@release/v1 with: user: __token__ password: ${{ secrets.PYPI_API_TOKEN }} PyPi_GrowattServer-1.6.0/.gitignore000066400000000000000000000005271472215715700173040ustar00rootroot00000000000000### Python ### # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] *$py.class image.jpg # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ pip-wheel-metadata/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # Symlink examples/growattServer PyPi_GrowattServer-1.6.0/LICENSE000066400000000000000000000021001472215715700163060ustar00rootroot00000000000000MIT License Copyright (c) 2018 Sjoerd Langkemper & Indy Koning Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PyPi_GrowattServer-1.6.0/README.md000077500000000000000000000407141472215715700166000ustar00rootroot00000000000000# Growatt Server Package to retrieve PV information from the growatt server. Special thanks to [Sjoerd Langkemper](https://github.com/Sjord) who has provided a strong base to start off from https://github.com/Sjord/growatt_api_client These projects may merge in the future since they are simmilar in code and function. ## Usage ```python import growattServer api = growattServer.GrowattApi() login_response = api.login(, ) #Get a list of growatt plants. print(api.plant_list(login_response['user']['id'])) ``` ## Methods and Variables ### Methods Any methods that may be useful. `api.login(username, password)` Log into the growatt API. This must be done before making any request. After this you will be logged in. You will want to capture the response to get the `userId` variable. `api.plant_list(user_id)` Get a list of plants registered to your account. `api.plant_info(plant_id)` Get info for specified plant. `api.plant_settings(plant_id)` Get the current settings for the specified plant `api.plant_detail(plant_id, timespan<1=day, 2=month>, date)` Get details of a specific plant. `api.plant_energy_data(plant_id)` Get energy data for the specified plant. `api.inverter_list(plant_id)` Get a list of inverters in specified plant. (May be deprecated in the future, since it gets all devices. Use `device_list` instead). `api.device_list(plant_id)` Get a list of devices in specified plant. `api.inverter_data(inverter_id, date)` Get some basic data of a specific date for the inverter. `api.inverter_detail(inverter_id)` Get detailed data on inverter. `api.tlx_system_status(plant_id, tlx_id)` Get system status. `api.tlx_energy_overview(plant_id, tlx_id)` Get energy overview of the system. `api.tlx_energy_prod_cons(plant_id, tlx_id)` Get energy production and consumption for the system. `api.tlx_data(tlx_id, date)` Get some basic data of a specific date for the tlx type inverter. `api.tlx_detail(tlx_id)` Get detailed data on a tlx type inverter. `api.tlx_params(tlx_id)` Get parameters for the tlx type inverter. `api.tlx_get_all_settings(tlx_id)` Get all possible settings for the tlx type inverter. `api.tlx_get_enabled_settings(tlx_id)` Get all enabled settings for the tlx type inverter. `api.tlx_battery_info(serial_num)` Get battery info for tlx systems. `api.tlx_battery_info_detailed(serial_num)` Get detailed battery info. `api.mix_info(mix_id, plant_id=None)` Get high level information about the Mix system including daily and overall totals. NOTE: `plant_id` is an optional parameter, it does not appear to be used by the remote API, but is used by the mobile app these calls were reverse-engineered from. `api.mix_totals(mix_id, plant_id)` Get daily and overall total information for the Mix system (duplicates some of the information from `mix_info`). `api.mix_system_status(mix_id, plant_id)` Get instantaneous values for Mix system e.g. current import/export, generation, charging rates etc. `api.mix_detail(mix_id, plant_id, timespan=<0=hour, 1=day, 2=month>, date)` Get detailed values for a timespan, the API call also returns totals data for the same values in this time window `api.dashboard_data(plant_id, timespan=<0=hour, 1=day, 2=month>, date)` Get dashboard values for a timespan, the API call also returns totals data for the same values in this time window. NOTE: Many of the values on this API call are incorrect for 'Mix' systems, however it still provides some accurate values that are unavailable on other API calls. `api.storage_detail(storage_id)` Get detailed data on storage (battery). `api.storage_params(storage_id)` Get a ton of info on storage (More info, more convoluted). `api.storage_energy_overview(plant_id, storage_id)` Get the information you see in the "Generation overview". `api.is_plant_noah_system(plant_id)` Get the Information if noah devices are configured for the specified plant `api.noah_system_status(serial_number)` Get the current status for the specified noah device e.g. workMode, soc, chargePower, disChargePower, current import/export etc. `api.noah_info(serial_number)` Get all information for the specified noah device e.g. configured Operation Modes, configured Battery Management charging upper & lower limit, configured System Default Output Power, Firmware Version `api.update_plant_settings(plant_id, changed_settings, current_settings)` Update the settings for a plant to the values specified in the dictionary, if the `current_settings` are not provided it will look them up automatically using the `get_plant_settings` function - See 'Plant settings' below for more information `api.update_tlx_inverter_setting(serial_number, setting_type, parameter)` Applies the provided parameter for the specified setting on the specified tlx inverter; see 'Inverter settings' below for more information. `api.update_tlx_inverter_time_segment(serial_number, segment_id, batt_mode, start_time, end_time, enabled)` Updates one of the 9 time segments with the specified battery mode (load, battery, grid first); see 'Inverter settings' below for more information. `api.update_mix_inverter_setting(serial_number, setting_type, parameters)` Applies the provided parameters (dictionary or array) for the specified setting on the specified mix inverter; see 'Inverter settings' below for more information `api.update_ac_inverter_setting(serial_number, setting_type, parameters)` Applies the provided parameters (dictionary or array) for the specified setting on the specified AC-coupled inverter; see 'Inverter settings' below for more information `api.update_noah_settings(serial_number, setting_type, parameters)` Applies the provided parameters (dictionary or array) for the specified setting on the specified noah device; see 'Noah settings' below for more information ### Variables Some variables you may want to set. `api.server_url` The growatt server URL, default: 'https://openapi.growatt.com/' You may need a different URL depending on where your account is registered: 'https://openapi-cn.growatt.com/' (Chinese server) 'https://openapi-us.growatt.com/' (North American server) 'https://openapi.growatt.com/' (Other regional server: e.g. Europe) ## Note This is based on the endpoints used on the mobile app and could be changed without notice. ## Initialisation The library can be initialised to introduce randomness into the User Agent field that is used when communicating with the servers. This has been added since the Growatt servers started checking for the presence of a `User-Agent` field in the headers that are sent. By default the library will use a pre-set `User-Agent` value which identifies this library while also appearing like an Android device. However, it is also possible to pass in parameters to the intialisation of the library to override this entirely, or just add a random ID to the value. e.g. ```python api = growattServer.GrowattApi() # The default way to initialise api = growattServer.GrowattApi(True) # Adds a randomly generated User ID to the default User-Agent api = growattServer.GrowattApi(False, "my_user_agent_value") # Overrides the default and uses "my_user_agent_value" in the User-Agent header ``` Please see the `user_agent_options.py` example in the `examples` directory if you wish to investigate further. ## Examples The `examples` directory contains example usage for the library. You are required to have the library installed to use them `pip install growattServer`. However, if you are contributing to the library and want to use the latest version from the git repository, simply create a symlink to the growattServer directory inside the `examples` directory. ## Plant Settings The plant settings function(s) allow you to re-configure the settings for a specified plant. The following settings are required (and are therefore pre-populated based on the existing values for these settings) * `plantCoal` - The formula used to calculate equivalent coal usage * `plantSo2` - The formula used to calculate So2 generation/saving * `accountName` - The username that the system is assigned to * `plantID` - The ID of the plant * `plantFirm` - The 'firm' of the plant (unknown what this relates to - hardcoded to '0') * `plantCountry` - The Country that the plant resides in * `plantType` - The 'type' of plant (numerical value - mapped to an Enum) * `plantIncome` - The formula used to calculate money per kwh * `plantAddress` - The address of the plant * `plantTimezone` - The timezone of the plant (relative to UTC) * `plantLng` - The longitude of the plant's location * `plantCity` - The city that the plant is located in * `plantCo2` - The formula used to calculate Co2 saving/reduction * `plantMoney` - The local currency e.g. gbp * `plantPower` - The capacity/size of the plant in W e.g. 6400 (6.4kw) * `plantLat` - The latitude of the plant's location * `plantDate` - The date that the plant was installed * `plantName` - The name of the plant The function `update_plant_settings` allows you to provide a python dictionary of any/all of the above settings and change their value. ## Inverter Settings NOTE: The inverter settings function appears to only work with 'mix' and 'tlx' systems based on the API call that it makes being specific to those inverter types The inverter settings function(s) allow you to change individual values on your inverter e.g. time, charging period etc. From what has been reverse engineered from the api, each setting has a `setting_type` and a set of `parameters` that are relevant to it. Known working settings & parameters are as follows (all parameter values are strings): * **Time/Date** * type: `pf_sys_year` * params: * `param1`: datetime in format: `YYYY-MM-DD HH:MM:SS` * **Hybrid inverter AC charge times** * function: `api.update_mix_inverter_setting` * setting type: `mix_ac_charge_time_period` * params: * `param1`: Charging power % (value between 0 and 100) * `param2`: Stop charging Statement of Charge % (value between 0 and 100) * `param3`: Allow AC charging (0 = Disabled, 1 = Enabled) * `param4`: Schedule 1 - Start time - Hour e.g. "01" (1am) * `param5`: Schedule 1 - Start time - Minute e.g. "00" (0 minutes) * `param6`: Schedule 1 - End time - Hour e.g. "02" (2am) * `param7`: Schedule 1 - End time - Minute e.g. "00" (0 minutes) * `param8`: Schedule 1 - Enabled/Disabled (0 = Disabled, 1 = Enabled) * `param9`: Schedule 2 - Start time - Hour e.g. "01" (1am) * `param10`: Schedule 2 - Start time - Minute e.g. "00" (0 minutes) * `param11`: Schedule 2 - End time - Hour e.g. "02" (2am) * `param12`: Schedule 2 - End time - Minute e.g. "00" (0 minutes) * `param13`: Schedule 2 - Enabled/Disabled (0 = Disabled, 1 = Enabled) * `param14`: Schedule 3 - Start time - Hour e.g. "01" (1am) * `param15`: Schedule 3 - Start time - Minute e.g. "00" (0 minutes) * `param16`: Schedule 3 - End time - Hour e.g. "02" (2am) * `param17`: Schedule 3 - End time - Minute e.g. "00" (0 minutes) * `param18`: Schedule 3 - Enabled/Disabled (0 = Disabled, 1 = Enabled) * **AC-coupled inverter AC charge times** * function: `api.update_ac_inverter_setting` * setting type: `spa_ac_charge_time_period` * params: * `param1`: Charging power % (value between 0 and 100) * `param2`: Stop charging Statement of Charge % (value between 0 and 100) * `param3`: Schedule 1 - Start time - Hour e.g. "01" (1am) * `param4`: Schedule 1 - Start time - Minute e.g. "00" (0 minutes) * `param5`: Schedule 1 - End time - Hour e.g. "02" (2am) * `param6`: Schedule 1 - End time - Minute e.g. "00" (0 minutes) * `param7`: Schedule 1 - Enabled/Disabled (0 = Disabled, 1 = Enabled) * `param8`: Schedule 2 - Start time - Hour e.g. "01" (1am) * `param9`: Schedule 2 - Start time - Minute e.g. "00" (0 minutes) * `param10`: Schedule 2 - End time - Hour e.g. "02" (2am) * `param11`: Schedule 2 - End time - Minute e.g. "00" (0 minutes) * `param12`: Schedule 2 - Enabled/Disabled (0 = Disabled, 1 = Enabled) * `param13`: Schedule 3 - Start time - Hour e.g. "01" (1am) * `param14`: Schedule 3 - Start time - Minute e.g. "00" (0 minutes) * `param15`: Schedule 3 - End time - Hour e.g. "02" (2am) * `param16`: Schedule 3 - End time - Minute e.g. "00" (0 minutes) * `param17`: Schedule 3 - Enabled/Disabled (0 = Disabled, 1 = Enabled) * **TLX inverter settings** * function: `api.update_tlx_inverter_setting` * type: `charge_power` * param1: Charging power % (value between 0 and 100) * type: `charge_stop_soc` * param1: Charge Stop SOC * type: `discharge_power` * param1: Discharging power % (value between 0 and 100) * type: `on_grid_discharge_stop_soc` * param1: On-grid discharge Stop SOC * type: `discharge_stop_soc` * param1: Off-grid discharge Stop SOC * type: `ac_charge` * param1: Allow AC (grid) charging (0 = Disabled, 1 = Enabled) * type: `pf_sys_year` * param1: datetime in format: `YYYY-MM-DD HH:MM:SS` * function: `api.update_tlx_inverter_time_segment` * segment_id: The segment to update (1-9) * batt_mode: Battery Mode for the segment: 0=Load First(Self-Consumption), 1=Battery First, 2=Grid First * start_time: timedate object with start time of segment with format HH:MM * end_time: timedate object with end time of segment with format HH:MM * enabled: time segment enabled, boolean: True (Enabled), False (Disabled) The four functions `update_tlx_inverter_setting`, `update_mix_inverter_setting`, `update_ac_inverter_setting`, and `update_inverter_setting` take either a dictionary or an array. If an array is passed it will automatically generate the `paramN` key based on array index since all params for settings seem to used the same numbering scheme. Only the settings described above have been tested with `update_tlx_inverter_setting` and they all take only one single parameter. It is very likely that the function works with all settings returned by `tlx_get_enabled_settings`, but this has not been tested. A helper function `update_tlx_inverter_time_segment` is provided for the settings that require more than one parameter. ## Noah Settings The noah settings function allow you to change individual values on your noah system e.g. system default output power, battery management, operation mode and currency From what has been reverse engineered from the api, each setting has a `setting_type` and a set of `parameters` that are relevant to it. Known working settings & parameters are as follows (all parameter values are strings): * **Change "System Default Output Power"** * function: `api.update_noah_settings` * setting type: `default_power` * params: * `param1`: System default output power in watt * **Change "Battery Management"** * function: `api.update_noah_settings` * setting type: `charging_soc` * params: * `param1`: Charge upper limit in % * `param2`: Charge lower limit in % * **Change "Operation Mode" Time Segment** * function: `api.update_noah_settings` * setting type: `time_segment` key from `api.noah_info(serial_number)`, for new `time_segment` count the ending number up * params: * `param1`: Workingmode (0 = Load First, 1 = Battery First) * `param2`: Start time - Hour e.g. "01" (1am) * `param3`: Start time - Minute e.g. "00" (0 minutes) * `param4`: End time - Hour e.g. "02" (2am) * `param5`: End time - Minute e.g. "00" (0 minutes) * `param6`: Output power in watt (For Workingmode "Battery First" always "0") * `param7`: Enabled/Disabled (0 = Disabled, 1 = Enabled) * **Change "Currency"** * function: `api.update_noah_settings` * setting type: `updatePlantMoney` * params: * `param1`: Plant Id * `param2`: Cost per kWh e.g. "0.22" * `param3`: Unit value from `api.noah_info(serial_number)` - `unitList` ## Settings Discovery The settings for the Plant and Inverter have been reverse engineered by using the ShinePhone Android App and the NetCapture SSL application together to inspect the API calls that are made by the application and the parameters that are provided with it. ## Disclaimer The developers & maintainers of this library accept no responsibility for any damage, problems or issues that arise with your Growatt systems as a result of its use. The library contains functions that allow you to modify the configuration of your plant & inverter which carries the ability to set values outside of normal operating parameters, therefore, settings should only be modified if you understand the consequences. To the best of our knowledge only the `settings` functions perform modifications to your system and all other operations are read only. Regardless of the operation: ***The library is used entirely at your own risk.*** PyPi_GrowattServer-1.6.0/examples/000077500000000000000000000000001472215715700171265ustar00rootroot00000000000000PyPi_GrowattServer-1.6.0/examples/mix_example.py000077500000000000000000000251471472215715700220240ustar00rootroot00000000000000import growattServer import datetime import getpass import pprint """ This is a very trivial script that logs into a user's account and prints out useful data for a "Mix" system (Hybrid). The first half of the logic is applicable to all types of system. There is a clear point (marked in the script) where we specifically make calls to the "mix" WebAPI calls, at this point other types of systems will no longer work. This has been tested against my personal system (muppet3000) which is a hybrid inverter system. Throughout the script there are points where 'pp.pprint' has been commented out. If you wish to see all the data that is returned from those specific library calls, just uncomment them and they will appear as part of the output. NOTE - For some reason (not sure if this is just specific to my system or not) the "export to grid" daily total and overall total values don't seem to be populating. As such they are untested. This has been causing problems on my WebUI and mobile app too, it is not a bug in this library, the output from this script has been updated to reflect it's inaccuracy. """ pp = pprint.PrettyPrinter(indent=4) """ 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:") #Prompt user to input password user_pass=getpass.getpass("Enter password:") api = growattServer.GrowattApi() login_response = api.login(username, user_pass) plant_list = api.plant_list(login_response['user']['id']) #pp.pprint(plant_list) print("***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']: plant_id = plant['plantId'] plant_name = plant['plantName'] plant_info=api.plant_info(plant_id) #pp.pprint(plant_info) print("***Info for Plant %s - %s***"%(plant_id, plant_name)) #There are more values in plant_info, but these are some of the useful/interesting ones indent_print("CO2 Reducion: %s"%(plant_info['Co2Reduction']),2) indent_print("Nominal Power (w): %s"%(plant_info['nominal_Power']),2) indent_print("Solar Energy Today (kw): %s"%(plant_info['todayEnergy']),2) indent_print("Solar Energy Total (kw): %s"%(plant_info['totalEnergy']),2) print("") indent_print("Devices in plant:",2) for device in plant_info['deviceList']: device_sn = device['deviceSn'] device_type = device['deviceType'] indent_print("- Device - SN: %s, Type: %s"%(device_sn, device_type),4) print("") for device in plant_info['deviceList']: device_sn = device['deviceSn'] device_type = device['deviceType'] indent_print("**Device - SN: %s, Type: %s**"%(device_sn, device_type),2) #NOTE - This is the bit where we specifically only handle information on Mix devices - this won't work for non-mix devices #These two API calls return lots of duplicated information, but each also holds unique information as well mix_info = api.mix_info(device_sn, plant_id) pp.pprint(mix_info) mix_totals = api.mix_totals(device_sn, plant_id) #pp.pprint(mix_totals) indent_print("*TOTAL VALUES*", 4) indent_print("==Today Totals==", 4) indent_print("Battery Charge (kwh): %s"%(mix_info['eBatChargeToday']),6) indent_print("Battery Discharge (kwh): %s"%(mix_info['eBatDisChargeToday']),6) indent_print("Solar Generation (kwh): %s"%(mix_info['epvToday']),6) indent_print("Local Load (kwh): %s"%(mix_totals['elocalLoadToday']),6) indent_print("Export to Grid (kwh): %s"%(mix_totals['etoGridToday']),6) indent_print("==Overall Totals==",4) indent_print("Battery Charge: %s"%(mix_info['eBatChargeTotal']),6) indent_print("Battery Discharge (kwh): %s"%(mix_info['eBatDisChargeTotal']),6) indent_print("Solar Generation (kwh): %s"%(mix_info['epvTotal']),6) indent_print("Local Load (kwh): %s"%(mix_totals['elocalLoadTotal']),6) indent_print("Export to Grid (kwh): %s"%(mix_totals['etogridTotal']),6) print("") mix_detail = api.mix_detail(device_sn, plant_id) #pp.pprint(mix_detail) #Some of the 'totals' values that are returned by this function do not align to what we would expect, however the graph data always seems to be accurate. #Therefore, here we take a moment to calculate the same values provided elsewhere but based on the graph data instead #The particular stats that we question are 'load consumption' (elocalLoad) and 'import from grid' (etouser) which seem to be calculated from one-another #It would appear that 'etouser' is calculated on the backend incorrectly for systems that use AC battery charged (e.g. during cheap nighttime rates) pacToGridToday = 0.0 pacToUserToday = 0.0 pdischargeToday = 0.0 ppvToday = 0.0 sysOutToday = 0.0 chartData = mix_detail['chartData'] for time_entry, data_points in chartData.items(): #For each time entry convert it's wattage into kWh, this assumes that the wattage value is #the same for the whole 5 minute window (it's the only assumption we can make) #We Multiply the wattage by 5/60 (the number of minutes of the time window divided by the number of minutes in an hour) #to give us the equivalent kWh reading for that 5 minute window pacToGridToday += float(data_points['pacToGrid']) * (5/60) pacToUserToday += float(data_points['pacToUser']) * (5/60) pdischargeToday += float(data_points['pdischarge']) * (5/60) ppvToday += float(data_points['ppv']) * (5/60) sysOutToday += float(data_points['sysOut']) * (5/60) mix_detail['calculatedPacToGridTodayKwh'] = round(pacToGridToday,2) mix_detail['calculatedPacToUserTodayKwh'] = round(pacToUserToday,2) mix_detail['calculatedPdischargeTodayKwh'] = round(pdischargeToday,2) mix_detail['calculatedPpvTodayKwh'] = round(ppvToday,2) mix_detail['calculatedSysOutTodayKwh'] = round(sysOutToday,2) #Option to print mix_detail again now we've made the additions #pp.pprint(mix_detail) dashboard_data = api.dashboard_data(plant_id) #pp.pprint(dashboard_data) indent_print("*TODAY TOTALS BREAKDOWN*", 4) indent_print("Self generation total (batteries & solar - from API) (kwh): %s"%(mix_detail['eCharge']),6) indent_print("Load consumed from solar (kwh): %s"%(mix_detail['eChargeToday']),6) indent_print("Load consumed from batteries (kwh): %s"%(mix_detail['echarge1']),6) indent_print("Self consumption total (batteries & solar - from API) (kwh): %s"%(mix_detail['eChargeToday1']),6) indent_print("Load consumed from grid (kwh): %s"%(mix_detail['etouser']),6) indent_print("Total imported from grid (Load + AC charging) (kwh): %s"%(dashboard_data['etouser'].replace('kWh','')),6) calculated_consumption = float(mix_detail['eChargeToday']) + float(mix_detail['echarge1']) + float(mix_detail['etouser']) indent_print("Load consumption (calculated) (kwh): %s"%(round(calculated_consumption,2)),6) indent_print("Load consumption (API) (kwh): %s"%(mix_detail['elocalLoad']),6) indent_print("Exported (kwh): %s"%(mix_detail['eAcCharge']), 6) solar_to_battery = round(float(mix_info['epvToday']) - float(mix_detail['eAcCharge']) - float(mix_detail['eChargeToday']),2) indent_print("Solar battery charge (calculated) (kwh): %s"%(solar_to_battery), 6) ac_to_battery = round(float(mix_info['eBatChargeToday']) - solar_to_battery,2) indent_print("AC battery charge (calculated) (kwh): %s"%(ac_to_battery), 6) print("") indent_print("*TODAY TOTALS COMPARISONS*", 4) indent_print("Export to Grid (kwh) - TRUSTED:", 6) indent_print("mix_totals['etoGridToday']: %s"%(mix_totals['etoGridToday']), 8) indent_print("mix_detail['eAcCharge']: %s"%(mix_detail['eAcCharge']), 8) indent_print("mix_detail['calculatedPacToGridTodayKwh']: %s"%(mix_detail['calculatedPacToGridTodayKwh']), 8) print("") indent_print("Imported from Grid (kwh) - TRUSTED:", 6) indent_print("dashboard_data['etouser']: %s"%(dashboard_data['etouser'].replace('kWh','')), 8) indent_print("mix_detail['calculatedPacToUserTodayKwh']: %s"%(mix_detail['calculatedPacToUserTodayKwh']), 8) print("") indent_print("Battery discharge (kwh) - TRUSTED:", 6) indent_print("mix_info['eBatDisChargeToday']: %s"%(mix_info['eBatDisChargeToday']), 8) indent_print("mix_totals['edischarge1Today']: %s"%(mix_totals['edischarge1Today']), 8) indent_print("mix_detail['echarge1']: %s"%(mix_detail['echarge1']), 8) indent_print("mix_detail['calculatedPdischargeTodayKwh']: %s"%(mix_detail['calculatedPdischargeTodayKwh']), 8) print("") indent_print("Solar generation (kwh) - TRUSTED:", 6) indent_print("mix_info['epvToday']: %s"%(mix_info['epvToday']), 8) indent_print("mix_totals['epvToday']: %s"%(mix_totals['epvToday']), 8) indent_print("mix_detail['calculatedPpvTodayKwh']: %s"%(mix_detail['calculatedPpvTodayKwh']), 8) print("") indent_print("Load Consumption (kwh) - TRUSTED:", 6) indent_print("mix_totals['elocalLoadToday']: %s"%(mix_totals['elocalLoadToday'],), 8) indent_print("mix_detail['elocalLoad']: %s"%(mix_detail['elocalLoad']), 8) indent_print("mix_detail['calculatedSysOutTodayKwh']: %s"%(mix_detail['calculatedSysOutTodayKwh']), 8) print("") #This call gets all of the instantaneous values from the system e.g. current load, generation etc. mix_status = api.mix_system_status(device_sn, plant_id) #pp.pprint(mix_status) #NOTE - There are some other values available in mix_status, however these are the most useful ones indent_print("*CURRENT VALUES*",4) indent_print("==Batteries==",4) indent_print("Charging Batteries at (kw): %s"%(mix_status['chargePower']),6) indent_print("Discharging Batteries at (kw): %s"%(mix_status['pdisCharge1']),6) indent_print("Batteries %%: %s"%(mix_status['SOC']),6) indent_print("==PVs==",4) indent_print("PV1 wattage: %s"%(mix_status['pPv1']),6) indent_print("PV2 wattage: %s"%(mix_status['pPv2']),6) calc_pv_total = (float(mix_status['pPv1']) + float(mix_status['pPv2']))/1000 indent_print("PV total wattage (calculated) - KW: %s"%(round(calc_pv_total,2)),6) indent_print("PV total wattage (API) - KW: %s"%(mix_status['ppv']),6) indent_print("==Consumption==",4) indent_print("Local load/consumption - KW: %s"%(mix_status['pLocalLoad']),6) indent_print("==Import/Export==",4) indent_print("Importing from Grid - KW: %s"%(mix_status['pactouser']),6) indent_print("Exporting to Grid - KW: %s"%(mix_status['pactogrid']),6) PyPi_GrowattServer-1.6.0/examples/noah_example.py000066400000000000000000000057461472215715700221540ustar00rootroot00000000000000import growattServer import datetime import getpass import pprint """ This is a very trivial script that logs into a user's account and prints out useful data for a "NOAH" system. This has been tested against my personal system (NOAH2000) which is a 2kW Balcony Storage system. Throughout the script there are points where 'pp.pprint' has been commented out. If you wish to see all the data that is returned from those specific library calls, just uncomment them and they will appear as part of the output. """ pp = pprint.PrettyPrinter(indent=4) """ 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:") #Prompt user to input password user_pass=getpass.getpass("Enter password:") api = growattServer.GrowattApi() login_response = api.login(username, user_pass) plant_list = api.plant_list(login_response['user']['id']) #pp.pprint(plant_list) print("***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']: plant_id = plant['plantId'] plant_name = plant['plantName'] plant_info=api.plant_info(plant_id) #pp.pprint(plant_info) print("***Info for Plant %s - %s***"%(plant_id, plant_name)) #There are more values in plant_info, but these are some of the useful/interesting ones indent_print("CO2 Reducion: %s"%(plant_info['Co2Reduction']),2) indent_print("Nominal Power (w): %s"%(plant_info['nominal_Power']),2) indent_print("Solar Energy Today (kw): %s"%(plant_info['todayEnergy']),2) indent_print("Solar Energy Total (kw): %s"%(plant_info['totalEnergy']),2) print("") indent_print("Devices in plant:",2) for device in plant_info['deviceList']: device_sn = device['deviceSn'] device_type = device['deviceType'] indent_print("- Device - SN: %s, Type: %s"%(device_sn, device_type),4) is_noah = api.is_plant_noah_system(plant['plantId']) if is_noah['result'] == 1 and (is_noah['obj']['isPlantNoahSystem'] or is_noah['obj']['isPlantHaveNoah']): device_sn = is_noah['obj']['deviceSn'] indent_print("**NOAH - SN: %s**"%(device_sn),2) noah_system = api.noah_system_status(is_noah['obj']['deviceSn']) pp.pprint(noah_system['obj']) print("") noah_infos = api.noah_info(is_noah['obj']['deviceSn']) pp.pprint(noah_infos['obj']['noah']) print("") indent_print("Remaining battery (" + "%" + "): %s"%(noah_system['obj']['soc']),2) indent_print("Solar Power (w): %s"%(noah_system['obj']['ppv']),2) indent_print("Charge Power (w): %s"%(noah_system['obj']['chargePower']),2) indent_print("Discharge Power (w): %s"%(noah_system['obj']['disChargePower']),2) indent_print("Output Power (w): %s"%(noah_system['obj']['pac']),2)PyPi_GrowattServer-1.6.0/examples/settings_example.py000077500000000000000000000062261472215715700230640ustar00rootroot00000000000000import growattServer import datetime import getpass import pprint """ This is a very trivial script to show how to interface with the configuration settings of a plant and it's inverters This has been tested against my personal system (muppet3000) which is a hybrid (aka 'mix') inverter system. Throughout the script there are points where 'pp.pprint' has been commented out. If you wish to see all the data that is returned from those specific library calls, just uncomment them and they will appear as part of the output. """ pp = pprint.PrettyPrinter(indent=4) #Prompt user for username username=input("Enter username:") #Prompt user to input password user_pass=getpass.getpass("Enter password:") api = growattServer.GrowattApi() login_response = api.login(username, user_pass) plant_list = api.plant_list(login_response['user']['id']) #Simple logic to just get the first inverter from the first plant #Expand this using a for-loop to perform for more systems (see mix_example for more detail) plant = plant_list['data'][0] #This is an array - we just take the first - would need a for-loop for more systems plant_id = plant['plantId'] plant_name = plant['plantName'] plant_info=api.plant_info(plant_id) device = plant_info['deviceList'][0] #This is an array - we just take the first - would need a for-loop for more systems device_sn = device['deviceSn'] device_type = device['deviceType'] #Get plant settings - This is performed for us inside 'update_plant_settings' but you can get ALL of the settings using this current_settings = api.get_plant_settings(plant_id) #pp.pprint(current_settings) #Change the timezone of the plant plant_settings_changes = { 'plantTimezone': '0' } print("Changing the following plant setting(s):") pp.pprint(plant_settings_changes) response = api.update_plant_settings(plant_id, plant_settings_changes) print(response) print("") #Set inverter time now = datetime.datetime.now() dt_string = now.strftime("%Y-%m-%d %H:%M:%S") time_settings={ 'param1': dt_string } print("Setting inverter time to: %s" %(dt_string)) response = api.update_mix_inverter_setting(device_sn, 'pf_sys_year', time_settings) print(response) print("") #Set inverter schedule (Uses the 'array' method which assumes all parameters are named param1....paramN) schedule_settings = ["100", #Charging power % "100", #Stop charging SoC % "1", #Allow AC charging (1 = Enabled) "00", "40", #Schedule 1 - Start time "04", "20", #Schedule 1 - End time "1", #Schedule 1 - Enabled/Disabled (1 = Enabled) "00", "00", #Schedule 2 - Start time "00", "00", #Schedule 2 - End time "0", #Schedule 2 - Enabled/Disabled (0 = Disabled) "00", "00", #Schedule 3 - Start time "00", "00", #Schedule 3 - End time "0"] #Schedule 3 - Enabled/Disabled (0 = Disabled) print("Setting the inverter charging schedule to:") pp.pprint(schedule_settings) response = api.update_mix_inverter_setting(device_sn, 'mix_ac_charge_time_period', schedule_settings) print(response) PyPi_GrowattServer-1.6.0/examples/settings_example_AC.py000066400000000000000000000043641472215715700234250ustar00rootroot00000000000000import growattServer import sys import json ''' Sample script to set AC battery charging Takes commandline arguments for terminal SOC, start time, end time, and whether to run, with default arguments if none are given Tested on an SPA3000 ''' # check for SOC percent and whether to run if len(sys.argv) != 7: SOC = '40' startH = '0' startM = '40' endH = '04' endM = '30' run = '1' else: SOC = str(sys.argv[1]) startH = '{:02.0f}'.format(int(sys.argv[2])) startM = '{:02.0f}'.format(int(sys.argv[3])) endH = '{:02.0f}'.format(int(sys.argv[4])) endM = '{:02.0f}'.format(int(sys.argv[5])) run = str(sys.argv[6]) api = growattServer.GrowattApi() # This part needs to be adapted by the user login_response = api.login('USERNAME_AS_STRING', 'PASSWORD_AS_STRING') if login_response['success']: # Get a list of growatt plants. plant_list = api.plant_list(login_response['user']['id']) plant = plant_list['data'][0] plant_id = plant['plantId'] plant_info = api.plant_info(plant_id) device = plant_info['deviceList'][0] device_sn = device['deviceSn'] # All parameters need to be given, including zeros # All parameters must be strings schedule_settings = ['100', # Charging power % SOC, # Stop charging at SoC % startH, startM, # Schedule 1 - Start time endH, endM, # Schedule 1 - End time run, # Schedule 1 - Enabled/Disabled (1 = Enabled) '00','00', # Schedule 2 - Start time '00','00', # Schedule 2 - End time '0', # Schedule 2 - Enabled/Disabled (1 = Enabled) '00','00', # Schedule 3 - Start time '00','00', # Schedule 3 - End time '0'] # Schedule 3 - Enabled/Disabled (1 = Enabled) response = api.update_ac_inverter_setting(device_sn, 'spa_ac_charge_time_period', schedule_settings) else: response = login_response print(json.dumps(response)) PyPi_GrowattServer-1.6.0/examples/simple.py000077500000000000000000000002751472215715700210000ustar00rootroot00000000000000import growattServer api = growattServer.GrowattApi() login_response = api.login(, ) #Get a list of growatt plants. print(api.plant_list(login_response['user']['id'])) PyPi_GrowattServer-1.6.0/examples/tlx_example.py000066400000000000000000000115431472215715700220260ustar00rootroot00000000000000import growattServer import datetime import getpass import json """ # Example script controlling a Growatt MID-30KTL3-XH + APX battery hybrid system by emulating the ShinePhone iOS app. # The same API calls are used by the ShinePhone Android app as well. Traffic intercepted using HTTP Toolkit. # # The plant / energy / device APIs seem to be generic for all Growatt systems, while the inverter and battery APIs use the TLX APIs. # # The available settings under the 'Control' tab in ShinePhone are created by combining the results from two function calls: # tlx_get_all_settings() seem to returns the sum of all settings for all systems while tlx_get_enabled_settings() tells # which of these settings are valid for the TLX system. # # Settings that takes a single parameter can be set using update_tlx_inverter_setting(). A helper function, update_tlx_inverter_time_segment() # is provided for updating time segments which take several parameters. The inverter is picky and time intervals can't be overlapping, # even if they are disabled. # # The set functions are commented out in the example, uncomment to test, and use at your own risk. Most likely all settings returned in # tlx_get_enabled_settings() can be set using update_tlx_inverter_setting(), but has not been tested. # """ # Prompt user for username username=input("Enter username:") # Prompt user to input password user_pass=getpass.getpass("Enter password:") user_agent = 'ShinePhone/8.1.17 (iPhone; iOS 15.6.1; Scale/2.00)' api = growattServer.GrowattApi(agent_identifier=user_agent) login_response = api.login(username, user_pass) user_id = login_response['user']['id'] print("Login successful, user_id:", user_id) # Plant info plant_list = api.plant_list_two() plant_id = plant_list[0]['id'] plant_info = api.plant_info(plant_id) print("Plant info:", json.dumps(plant_info, indent=4, sort_keys=True)) # Energy data (used in the 'Plant' Tab) energy_data = api.plant_energy_data(plant_id) print("Plant Energy data", json.dumps(energy_data, indent=4, sort_keys=True)) # Devices devices = api.device_list(plant_id) print("Devices:", json.dumps(devices, indent=4, sort_keys=True)) for device in devices: if device['deviceType'] == 'tlx': # Inverter info (used in inverter view) inverter_sn = device['deviceSn'] inverter_info = api.tlx_params(inverter_sn) print("Inverter info:", json.dumps(inverter_info, indent=4, sort_keys=True)) # PV production data data = api.tlx_data(inverter_sn, datetime.datetime.now()) print("PV production data:", json.dumps(data, indent=4, sort_keys=True)) # System settings all_settings = api.tlx_all_settings(inverter_sn) enabled_settings = api.tlx_enabled_settings(inverter_sn) # 'on_grid_discharge_stop_soc' is present in web UI, but for some reason not # returned in enabled settings so we enable it manually here instead enabled_settings['enable']['on_grid_discharge_stop_soc'] = '1' enabled_keys = enabled_settings['enable'].keys() available_settings = {k: v for k, v in all_settings.items() if k in enabled_keys} print("System settings:", json.dumps(available_settings, indent=4, sort_keys=True)) # System status data = api.tlx_system_status(plant_id, inverter_sn) print("System status:", json.dumps(data, indent=4, sort_keys=True)) # Energy overview data = api.tlx_energy_overview(plant_id, inverter_sn) print("Energy overview:", json.dumps(data, indent=4, sort_keys=True)) # Energy production & consumption data = api.tlx_energy_prod_cons(plant_id, inverter_sn) print("Energy production & consumption:", json.dumps(data, indent=4, sort_keys=True)) elif device['deviceType'] == 'bat': # Battery info batt_info = api.tlx_battery_info(device['deviceSn']) print("Battery info:", json.dumps(batt_info, indent=4, sort_keys=True)) batt_info_detailed = api.tlx_battery_info_detailed(plant_id, device['deviceSn']) print("Battery info: detailed", json.dumps(batt_info_detailed, indent=4, sort_keys=True)) # Examples of updating settings, uncomment to use # Set charging power to 95% #res = api.update_tlx_inverter_setting(inverter_sn, 'charge_power', 95) #print(res) # Turn on AC charging #res = api.update_tlx_inverter_setting(inverter_sn, 'ac_charge', 1) #print(res) # Enable Load First between 00:01 and 11:59 using time segment 1 #res = api.update_tlx_inverter_time_segment(serial_number = inverter_sn, # segment_id = 1, # batt_mode = growattServer.BATT_MODE_LOAD_FIRST, # start_time = datetime.time(00, 1), # end_time = datetime.time(11, 59), # enabled=True) #print(res)PyPi_GrowattServer-1.6.0/examples/tlx_example_dashboard.py000066400000000000000000000151461472215715700240400ustar00rootroot00000000000000 import growattServer import getpass # Example script fetching key power and today+total energy metrics from a Growatt MID-30KTL3-XH (TLX) + APX battery hybrid system # # There is a lot of overlap in what the various Growatt APIs returns. # tlx_detail() contains the bulk of the needed data, but some info is missing and is fetched from # tlx_system_status(), tlx_energy_overview() and tlx_battery_info_detailed() instead # Prompt user for username username=input("Enter username:") # Prompt user to input password user_pass=getpass.getpass("Enter password:") # Login, emulating the Growatt app user_agent = 'ShinePhone/8.1.17 (iPhone; iOS 15.6.1; Scale/2.00)' api = growattServer.GrowattApi(agent_identifier=user_agent) login_response = api.login(username, user_pass) if not login_response['success']: print(f"Failed to log in, msg: {login_response['msg']}, error: {login_response['error']}") exit() # Get plant(s) plant_list = api.plant_list_two() plant_id = plant_list[0]['id'] # Get devices in plant devices = api.device_list(plant_id) # Iterate over all devices. Here we are interested in data from 'tlx' inverters and 'bat' devices batteries_info = [] for device in devices: if device['deviceType'] == 'tlx': inverter_sn = device['deviceSn'] # Inverter detail, contains the bulk of energy and power values inverter_detail = api.tlx_detail(inverter_sn).get('data') # Energy overview is used to retrieve "epvToday" which is not present in tlx_detail() for some reason energy_overview = api.tlx_energy_overview(plant_id, inverter_sn) # System status, contains power values, not available in inverter_detail() system_status = api.tlx_system_status(plant_id, inverter_sn) if device['deviceType'] == 'bat': batt_info = api.tlx_battery_info(device['deviceSn']) if batt_info.get('lost'): # Disconnected batteries are listed with 'old' power/energy/SOC data # Therefore we check it it's 'lost' and skip it in that case. print("'Lost' battery found, skipping") continue # Battery info batt_info = api.tlx_battery_info_detailed(plant_id, device['deviceSn']).get('data') if float(batt_info['chargeOrDisPower']) > 0: bdcChargePower = float(batt_info['chargeOrDisPower']) bdcDischargePower = 0 else: bdcChargePower = 0 bdcDischargePower = float(batt_info['chargeOrDisPower']) bdcDischargePower = -bdcDischargePower battery_data = { 'serialNum': device['deviceSn'], 'bdcChargePower': bdcChargePower, 'bdcDischargePower': bdcDischargePower, 'dischargeTotal': batt_info['dischargeTotal'], 'soc': batt_info['soc'] } batteries_info.append(battery_data) solar_production = f'{float(energy_overview["epvToday"]):.1f}/{float(energy_overview["epvTotal"]):.1f}' solar_production_pv1 = f'{float(inverter_detail["epv1Today"]):.1f}/{float(inverter_detail["epv1Total"]):.1f}' solar_production_pv2 = f'{float(inverter_detail["epv2Today"]):.1f}/{float(inverter_detail["epv2Total"]):.1f}' energy_output = f'{float(inverter_detail["eacToday"]):.1f}/{float(inverter_detail["eacTotal"]):.1f}' system_production = f'{float(inverter_detail["esystemToday"]):.1f}/{float(inverter_detail["esystemTotal"]):.1f}' battery_charged = f'{float(inverter_detail["echargeToday"]):.1f}/{float(inverter_detail["echargeTotal"]):.1f}' battery_grid_charge = f'{float(inverter_detail["eacChargeToday"]):.1f}/{float(inverter_detail["eacChargeTotal"]):.1f}' battery_discharged = f'{float(inverter_detail["edischargeToday"]):.1f}/{float(inverter_detail["edischargeTotal"]):.1f}' exported_to_grid = f'{float(inverter_detail["etoGridToday"]):.1f}/{float(inverter_detail["etoGridTotal"]):.1f}' imported_from_grid = f'{float(inverter_detail["etoUserToday"]):.1f}/{float(inverter_detail["etoUserTotal"]):.1f}' load_consumption = f'{float(inverter_detail["elocalLoadToday"]):.1f}/{float(inverter_detail["elocalLoadTotal"]):.1f}' self_consumption = f'{float(inverter_detail["eselfToday"]):.1f}/{float(inverter_detail["eselfTotal"]):.1f}' battery_charged = f'{float(inverter_detail["echargeToday"]):.1f}/{float(inverter_detail["echargeTotal"]):.1f}' print("\nGeneration overview Today/Total(kWh)") print(f'Solar production {solar_production:>22}') print(f' Solar production, PV1 {solar_production_pv1:>22}') print(f' Solar production, PV2 {solar_production_pv2:>22}') print(f'Energy Output {energy_output:>22}') print(f'System production {system_production:>22}') print(f'Self consumption {self_consumption:>22}') print(f'Load consumption {load_consumption:>22}') print(f'Battery Charged {battery_charged:>22}') print(f' Charged from grid {battery_grid_charge:>22}') print(f'Battery Discharged {battery_discharged:>22}') print(f'Import from grid {imported_from_grid:>22}') print(f'Export to grid {exported_to_grid:>22}') print("\nPower overview (Watts)") print(f'AC Power {float(inverter_detail["pac"]):>22.1f}') print(f'Self power {float(inverter_detail["pself"]):>22.1f}') print(f'Export power {float(inverter_detail["pacToGridTotal"]):>22.1f}') print(f'Import power {float(inverter_detail["pacToUserTotal"]):>22.1f}') print(f'Local load power {float(inverter_detail["pacToLocalLoad"]):>22.1f}') print(f'PV power {float(inverter_detail["psystem"]):>22.1f}') print(f'PV #1 power {float(inverter_detail["ppv1"]):>22.1f}') print(f'PV #2 power {float(inverter_detail["ppv2"]):>22.1f}') print(f'Battery charge power {float(system_status["chargePower"])*1000:>22.1f}') if len(batteries_info) > 0: print(f'Batt #1 charge power {float(batteries_info[0]["bdcChargePower"]):>22.1f}') if len(batteries_info) > 1: print(f'Batt #2 charge power {float(batteries_info[1]["bdcChargePower"]):>22.1f}') print(f'Battery discharge power {float(system_status["pdisCharge"])*1000:>18.1f}') if len(batteries_info) > 0: print(f'Batt #1 discharge power {float(batteries_info[0]["bdcDischargePower"]):>22.1f}') if len(batteries_info) > 1: print(f'Batt #2 discharge power {float(batteries_info[1]["bdcDischargePower"]):>22.1f}') if len(batteries_info) > 0: print(f'Batt #1 SOC {int(batteries_info[0]["soc"]):>21}%') if len(batteries_info) > 1: print(f'Batt #2 SOC {int(batteries_info[1]["soc"]):>21}%') PyPi_GrowattServer-1.6.0/examples/user_agent_options.py000077500000000000000000000035041472215715700234140ustar00rootroot00000000000000import growattServer import getpass """ This is a simple script that demonstrates the various ways to initialise the library to set a User Agent """ #Prompt user for username username=input("Enter username:") #Prompt user to input password user_pass=getpass.getpass("Enter password:") api = growattServer.GrowattApi() login_response = api.login(username, user_pass) print("Default initialisation") print("User-Agent: %s\nLogged in User id: %s" % (api.agent_identifier, login_response['userId'])) print("") api = growattServer.GrowattApi(True) login_response = api.login(username, user_pass) print("Add random ID to default User-Agent") print("User-Agent: %s\nLogged in User id: %s" % (api.agent_identifier, login_response['userId'])) print("") api = growattServer.GrowattApi(False, "my-user-id") login_response = api.login(username, user_pass) print("Override default User-Agent") print("User-Agent: %s\nLogged in User id: %s" % (api.agent_identifier, login_response['userId'])) print("") api = growattServer.GrowattApi(True, "my-user-id") login_response = api.login(username, user_pass) print("Override default User-Agent and add random ID") print("User-Agent: %s\nLogged in User id: %s" % (api.agent_identifier, login_response['userId'])) print("") api = growattServer.GrowattApi(False, growattServer.GrowattApi.agent_identifier + " - my-user-id") login_response = api.login(username, user_pass) print("Extend default User-Agent") print("User-Agent: %s\nLogged in User id: %s" % (api.agent_identifier, login_response['userId'])) print("") api = growattServer.GrowattApi(True, growattServer.GrowattApi.agent_identifier + " - my-user-id") login_response = api.login(username, user_pass) print("Extend default User-Agent and add random ID") print("User-Agent: %s\nLogged in User id: %s" % (api.agent_identifier, login_response['userId'])) print("") PyPi_GrowattServer-1.6.0/growattServer/000077500000000000000000000000001472215715700201665ustar00rootroot00000000000000PyPi_GrowattServer-1.6.0/growattServer/__init__.py000077500000000000000000001315431472215715700223110ustar00rootroot00000000000000import datetime from enum import IntEnum import requests from random import randint import warnings import hashlib name = "growattServer" BATT_MODE_LOAD_FIRST = 0 BATT_MODE_BATTERY_FIRST = 1 BATT_MODE_GRID_FIRST = 2 def hash_password(password): """ Normal MD5, except add c if a byte of the digest is less than 10. """ password_md5 = hashlib.md5(password.encode('utf-8')).hexdigest() for i in range(0, len(password_md5), 2): if password_md5[i] == '0': password_md5 = password_md5[0:i] + 'c' + password_md5[i + 1:] return password_md5 class Timespan(IntEnum): hour = 0 day = 1 month = 2 class GrowattApi: server_url = 'https://openapi.growatt.com/' agent_identifier = "Dalvik/2.1.0 (Linux; U; Android 12; https://github.com/indykoning/PyPi_GrowattServer)" def __init__(self, add_random_user_id=False, agent_identifier=None): if (agent_identifier != None): self.agent_identifier = agent_identifier #If a random user id is required, generate a 5 digit number and add it to the user agent if (add_random_user_id): random_number = ''.join(["{}".format(randint(0,9)) for num in range(0,5)]) self.agent_identifier += " - " + random_number self.session = requests.Session() self.session.hooks = { 'response': lambda response, *args, **kwargs: response.raise_for_status() } headers = {'User-Agent': self.agent_identifier} self.session.headers.update(headers) def __get_date_string(self, timespan=None, date=None): if timespan is not None: assert timespan in Timespan if date is None: date = datetime.datetime.now() date_str="" if timespan == Timespan.month: date_str = date.strftime('%Y-%m') else: date_str = date.strftime('%Y-%m-%d') return date_str def get_url(self, page): """ Simple helper function to get the page URL. """ return self.server_url + page def login(self, username, password, is_password_hashed=False): """ Log the user in. Returns 'data' -- A List containing Objects containing the folowing 'plantName' -- Friendly name of the plant 'plantId' -- The ID of the plant 'service' 'quality' 'isOpenSmartFamily' 'totalData' -- An Object 'success' -- True or False 'msg' 'app_code' 'user' -- An Object containing a lot of user information 'uid' 'userLanguage' 'inverterGroup' -- A List 'timeZone' -- A Number 'lat' 'lng' 'dataAcqList' -- A List 'type' 'accountName' -- The username 'password' -- The password hash of the user 'isValiPhone' 'kind' 'mailNotice' -- True or False 'id' 'lasLoginIp' 'lastLoginTime' 'userDeviceType' 'phoneNum' 'approved' -- True or False 'area' -- Continent of the user 'smsNotice' -- True or False 'isAgent' 'token' 'nickName' 'parentUserId' 'customerCode' 'country' 'isPhoneNumReg' 'createDate' 'rightlevel' 'appType' 'serverUrl' 'roleId' 'enabled' -- True or False 'agentCode' 'inverterList' -- A list 'email' 'company' 'activeName' 'codeIndex' 'appAlias' 'isBigCustomer' 'noticeType' """ if not is_password_hashed: password = hash_password(password) response = self.session.post(self.get_url('newTwoLoginAPI.do'), data={ 'userName': username, 'password': password }) data = response.json()['back'] if data['success']: data.update({ 'userId': data['user']['id'], 'userLevel': data['user']['rightlevel'] }) return data def plant_list(self, user_id): """ Get a list of plants connected to this account. Args: user_id (str): The ID of the user. Returns: list: A list of plants connected to the account. Raises: Exception: If the request to the server fails. """ response = self.session.get( self.get_url('PlantListAPI.do'), params={'userId': user_id}, allow_redirects=False ) return response.json().get('back', []) def plant_detail(self, plant_id, timespan, date=None): """ Get plant details for specified timespan. Args: plant_id (str): The ID of the plant. timespan (Timespan): The ENUM value conforming to the time window you want e.g. hours from today, days, or months. date (datetime, optional): The date you are interested in. Defaults to datetime.datetime.now(). Returns: dict: A dictionary containing the plant details. Raises: Exception: If the request to the server fails. """ date_str = self.__get_date_string(timespan, date) response = self.session.get(self.get_url('PlantDetailAPI.do'), params={ 'plantId': plant_id, 'type': timespan.value, 'date': date_str }) return response.json().get('back', {}) def plant_list_two(self): """ Get a list of all plants with detailed information. Returns: list: A list of plants with detailed information. """ response = self.session.post( self.get_url('newTwoPlantAPI.do'), params={'op': 'getAllPlantListTwo'}, data={ 'language': '1', 'nominalPower': '', 'order': '1', 'pageSize': '15', 'plantName': '', 'plantStatus': '', 'toPageNum': '1' } ) return response.json().get('PlantList', []) def inverter_data(self, inverter_id, date=None): """ Get inverter data for specified date or today. Args: inverter_id (str): The ID of the inverter. date (datetime, optional): The date you are interested in. Defaults to datetime.datetime.now(). Returns: dict: A dictionary containing the inverter data. Raises: Exception: If the request to the server fails. """ date_str = self.__get_date_string(date=date) response = self.session.get(self.get_url('newInverterAPI.do'), params={ 'op': 'getInverterData', 'id': inverter_id, 'type': 1, 'date': date_str }) return response.json() def inverter_detail(self, inverter_id): """ Get detailed data from PV inverter. Args: inverter_id (str): The ID of the inverter. Returns: dict: A dictionary containing the inverter details. Raises: Exception: If the request to the server fails. """ response = self.session.get(self.get_url('newInverterAPI.do'), params={ 'op': 'getInverterDetailData', 'inverterId': inverter_id }) return response.json() def inverter_detail_two(self, inverter_id): """ Get detailed data from PV inverter (alternative endpoint). Args: inverter_id (str): The ID of the inverter. Returns: dict: A dictionary containing the inverter details. Raises: Exception: If the request to the server fails. """ response = self.session.get(self.get_url('newInverterAPI.do'), params={ 'op': 'getInverterDetailData_two', 'inverterId': inverter_id }) return response.json() def tlx_system_status(self, plant_id, tlx_id): """ Get status of the system Args: plant_id (str): The ID of the plant. tlx_id (str): The ID of the TLX inverter. Returns: dict: A dictionary containing system status. Raises: Exception: If the request to the server fails. """ response = self.session.post( self.get_url("newTlxApi.do"), params={"op": "getSystemStatus_KW"}, data={"plantId": plant_id, "id": tlx_id} ) return response.json().get('obj', {}) def tlx_energy_overview(self, plant_id, tlx_id): """ Get energy overview Args: plant_id (str): The ID of the plant. tlx_id (str): The ID of the TLX inverter. Returns: dict: A dictionary containing energy data. Raises: Exception: If the request to the server fails. """ response = self.session.post( self.get_url("newTlxApi.do"), params={"op": "getEnergyOverview"}, data={"plantId": plant_id, "id": tlx_id} ) return response.json().get('obj', {}) def tlx_energy_prod_cons(self, plant_id, tlx_id, timespan=Timespan.hour, date=None): """ Get energy production and consumption (KW) Args: tlx_id (str): The ID of the TLX inverter. timespan (Timespan): The ENUM value conforming to the time window you want e.g. hours from today, days, or months. date (datetime): The date you are interested in. Returns: dict: A dictionary containing energy data. Raises: Exception: If the request to the server fails. """ date_str = self.__get_date_string(timespan, date) response = self.session.post( self.get_url("newTlxApi.do"), params={"op": "getEnergyProdAndCons_KW"}, data={'date': date_str, "plantId": plant_id, "language": "1", "id": tlx_id, "type": timespan.value} ) return response.json().get('obj', {}) def tlx_data(self, tlx_id, date=None): """ Get TLX inverter data for specified date or today. Args: tlx_id (str): The ID of the TLX inverter. date (datetime, optional): The date you are interested in. Defaults to datetime.datetime.now(). Returns: dict: A dictionary containing the TLX inverter data. Raises: Exception: If the request to the server fails. """ date_str = self.__get_date_string(date=date) response = self.session.get(self.get_url('newTlxApi.do'), params={ 'op': 'getTlxData', 'id': tlx_id, 'type': 1, 'date': date_str }) return response.json() def tlx_detail(self, tlx_id): """ Get detailed data from TLX inverter. Args: tlx_id (str): The ID of the TLX inverter. Returns: dict: A dictionary containing the detailed TLX inverter data. Raises: Exception: If the request to the server fails. """ response = self.session.get(self.get_url('newTlxApi.do'), params={ 'op': 'getTlxDetailData', 'id': tlx_id }) return response.json() def tlx_params(self, tlx_id): """ Get parameters for TLX inverter. Args: tlx_id (str): The ID of the TLX inverter. Returns: dict: A dictionary containing the TLX inverter parameters. Raises: Exception: If the request to the server fails. """ response = self.session.get(self.get_url('newTlxApi.do'), params={ 'op': 'getTlxParams', 'id': tlx_id }) return response.json() def tlx_all_settings(self, tlx_id): """ Get all possible settings from TLX inverter. Args: tlx_id (str): The ID of the TLX inverter. Returns: dict: A dictionary containing all possible settings for the TLX inverter. Raises: Exception: If the request to the server fails. """ response = self.session.post(self.get_url('newTlxApi.do'), params={ 'op': 'getTlxSetData' }, data={ 'serialNum': tlx_id }) return response.json().get('obj', {}).get('tlxSetBean') def tlx_enabled_settings(self, tlx_id): """ Get "Enabled settings" from TLX inverter. Args: tlx_id (str): The ID of the TLX inverter. Returns: dict: A dictionary containing the enabled settings. Raises: Exception: If the request to the server fails. """ string_time = datetime.datetime.now().strftime('%Y-%m-%d') response = self.session.post( self.get_url('newLoginAPI.do'), params={'op': 'getSetPass'}, data={'deviceSn': tlx_id, 'stringTime': string_time, 'type': '5'} ) return response.json().get('obj', {}) def tlx_battery_info(self, serial_num): """ Get battery information. Args: serial_num (str): The serial number of the battery. Returns: dict: A dictionary containing the battery information. Raises: Exception: If the request to the server fails. """ response = self.session.post( self.get_url('newTlxApi.do'), params={'op': 'getBatInfo'}, data={'lan': 1, 'serialNum': serial_num} ) return response.json().get('obj', {}) def tlx_battery_info_detailed(self, plant_id, serial_num): """ Get detailed battery information. Args: plant_id (str): The ID of the plant. serial_num (str): The serial number of the battery. Returns: dict: A dictionary containing the detailed battery information. Raises: Exception: If the request to the server fails. """ response = self.session.post( self.get_url('newTlxApi.do'), params={'op': 'getBatDetailData'}, data={'lan': 1, 'plantId': plant_id, 'id': serial_num} ) return response.json() def mix_info(self, mix_id, plant_id = None): """ Returns high level values from Mix device Keyword arguments: mix_id -- The serial number (device_sn) of the inverter plant_id -- The ID of the plant (the mobile app uses this but it does not appear to be necessary) (default None) Returns: 'acChargeEnergyToday' -- ??? 2.7 'acChargeEnergyTotal' -- ??? 25.3 'acChargePower' -- ??? 0 'capacity': '45' -- The current remaining capacity of the batteries (same as soc but without the % sign) 'eBatChargeToday' -- Battery charged today in kWh 'eBatChargeTotal' -- Battery charged total (all time) in kWh 'eBatDisChargeToday' -- Battery discharged today in kWh 'eBatDisChargeTotal' -- Battery discharged total (all time) in kWh 'epvToday' -- Energy generated from PVs today in kWh 'epvTotal' -- Energy generated from PVs total (all time) in kWh 'isCharge'-- ??? 0 - Possible a 0/1 based on whether or not the battery is charging 'pCharge1' -- ??? 0 'pDischarge1' -- Battery discharging rate in W 'soc' -- Statement of charge including % symbol 'upsPac1' -- ??? 0 'upsPac2' -- ??? 0 'upsPac3' -- ??? 0 'vbat' -- Battery Voltage 'vbatdsp' -- ??? 51.8 'vpv1' -- Voltage PV1 'vpv2' -- Voltage PV2 """ request_params={ 'op': 'getMixInfo', 'mixId': mix_id } if (plant_id): request_params['plantId'] = plant_id response = self.session.get(self.get_url('newMixApi.do'), params=request_params) return response.json().get('obj', {}) def mix_totals(self, mix_id, plant_id): """ Returns "Totals" values from Mix device Keyword arguments: mix_id -- The serial number (device_sn) of the inverter plant_id -- The ID of the plant Returns: 'echargetoday' -- Battery charged today in kWh (same as eBatChargeToday from mix_info) 'echargetotal' -- Battery charged total (all time) in kWh (same as eBatChargeTotal from mix_info) 'edischarge1Today' -- Battery discharged today in kWh (same as eBatDisChargeToday from mix_info) 'edischarge1Total' -- Battery discharged total (all time) in kWh (same as eBatDisChargeTotal from mix_info) 'elocalLoadToday' -- Load consumption today in kWh 'elocalLoadTotal' -- Load consumption total (all time) in kWh 'epvToday' -- Energy generated from PVs today in kWh (same as epvToday from mix_info) 'epvTotal' -- Energy generated from PVs total (all time) in kWh (same as epvTotal from mix_info) 'etoGridToday' -- Energy exported to the grid today in kWh 'etogridTotal' -- Energy exported to the grid total (all time) in kWh 'photovoltaicRevenueToday' -- Revenue earned from PV today in 'unit' currency 'photovoltaicRevenueTotal' -- Revenue earned from PV total (all time) in 'unit' currency 'unit' -- Unit of currency for 'Revenue' """ response = self.session.post(self.get_url('newMixApi.do'), params={ 'op': 'getEnergyOverview', 'mixId': mix_id, 'plantId': plant_id }) return response.json().get('obj', {}) def mix_system_status(self, mix_id, plant_id): """ Returns current "Status" from Mix device Keyword arguments: mix_id -- The serial number (device_sn) of the inverter plant_id -- The ID of the plant Returns: 'SOC' -- Statement of charge (remaining battery %) 'chargePower' -- Battery charging rate in kw 'fAc' -- Frequency (Hz) 'lost' -- System status e.g. 'mix.status.normal' 'pLocalLoad' -- Load conumption in kW 'pPv1' -- PV1 Wattage in W 'pPv2' -- PV2 Wattage in W 'pactogrid' -- Export to grid rate in kW 'pactouser' -- Import from grid rate in kW 'pdisCharge1' -- Discharging batteries rate in kW 'pmax' -- ??? 6 ??? PV Maximum kW ?? 'ppv' -- PV combined Wattage in kW 'priorityChoose' -- Priority setting - 0=Local load 'status' -- System statue - ENUM - Unknown values 'unit' -- Unit of measurement e.g. 'kW' 'upsFac' -- ??? 0 'upsVac1' -- ??? 0 'uwSysWorkMode' -- ??? 6 'vAc1' -- Grid voltage in V 'vBat' -- Battery voltage in V 'vPv1' -- PV1 voltage in V 'vPv2' -- PV2 voltage in V 'vac1' -- Grid voltage in V (same as vAc1) 'wBatteryType' -- ??? 1 """ response = self.session.post(self.get_url('newMixApi.do'), params={ 'op': 'getSystemStatus_KW', 'mixId': mix_id, 'plantId': plant_id }) return response.json().get('obj', {}) def mix_detail(self, mix_id, plant_id, timespan=Timespan.hour, date=None): """ Get Mix details for specified timespan Keyword arguments: mix_id -- The serial number (device_sn) of the inverter plant_id -- The ID of the plant timespan -- The ENUM value conforming to the time window you want e.g. hours from today, days, or months (Default Timespan.hour) date -- The date you are interested in (Default datetime.datetime.now()) Returns: A chartData object where each entry is for a specific 5 minute window e.g. 00:05 and 00:10 respectively (below) 'chartData': { '00:05': { 'pacToGrid' -- Export rate to grid in kW 'pacToUser' -- Import rate from grid in kW 'pdischarge' -- Battery discharge in kW 'ppv' -- Solar generation in kW 'sysOut' -- Load consumption in kW }, '00:10': { 'pacToGrid': '0', 'pacToUser': '0.93', 'pdischarge': '0', 'ppv': '0', 'sysOut': '0.93'}, ...... } 'eAcCharge' -- Exported to grid in kWh 'eCharge' -- System production in kWh = Self-consumption + Exported to Grid 'eChargeToday' -- Load consumption from solar in kWh 'eChargeToday1' -- Self-consumption in kWh 'eChargeToday2' -- Self-consumption in kWh (eChargeToday + echarge1) 'echarge1' -- Load consumption from battery in kWh 'echargeToat' -- Total battery discharged (all time) in kWh 'elocalLoad' -- Load consumption in kW (battery + solar + imported) 'etouser' -- Load consumption imported from grid in kWh 'photovoltaic' -- Load consumption from solar in kWh (same as eChargeToday) 'ratio1' -- % of system production that is self-consumed 'ratio2' -- % of system production that is exported 'ratio3' -- % of Load consumption that is "self consumption" 'ratio4' -- % of Load consumption that is "imported from grid" 'ratio5' -- % of Self consumption that is directly from Solar 'ratio6' -- % of Self consumption that is from batteries 'unit' -- Unit of measurement e.g kWh 'unit2' -- Unit of measurement e.g kW NOTE - It is possible to calculate the PV generation that went into charging the batteries by performing the following calculation: Solar to Battery = Solar Generation - Export to Grid - Load consumption from solar epvToday (from mix_info) - eAcCharge - eChargeToday """ date_str = self.__get_date_string(timespan, date) response = self.session.post(self.get_url('newMixApi.do'), params={ 'op': 'getEnergyProdAndCons_KW', 'plantId': plant_id, 'mixId': mix_id, 'type': timespan.value, 'date': date_str }) return response.json().get('obj', {}) def dashboard_data(self, plant_id, timespan=Timespan.hour, date=None): """ Get 'dashboard' data for specified timespan NOTE - All numerical values returned by this api call include units e.g. kWh or % - Many of the 'total' values that are returned for a Mix system are inaccurate on the system this was tested against. However, the statistics that are correct are not available on any other interface, plus these values may be accurate for non-mix types of system. Where the values have been proven to be inaccurate they are commented below. Keyword arguments: plant_id -- The ID of the plant timespan -- The ENUM value conforming to the time window you want e.g. hours from today, days, or months (Default Timespan.hour) date -- The date you are interested in (Default datetime.datetime.now()) Returns: A chartData object where each entry is for a specific 5 minute window e.g. 00:05 and 00:10 respectively (below) NOTE: The keys are interpreted differently, the examples below describe what they are used for in a 'Mix' system 'chartData': { '00:05': { 'pacToUser' -- Power from battery in kW 'ppv' -- Solar generation in kW 'sysOut' -- Load consumption in kW 'userLoad' -- Export in kW }, '00:10': { 'pacToUser': '0', 'ppv': '0', 'sysOut': '0.7', 'userLoad': '0'}, ...... } 'chartDataUnit' -- Unit of measurement e.g. 'kW', 'eAcCharge' -- Energy exported to the grid in kWh e.g. '20.5kWh' (not accurate for Mix systems) 'eCharge' -- System production in kWh = Self-consumption + Exported to Grid e.g '23.1kWh' (not accurate for Mix systems - actually showing the total 'load consumption' 'eChargeToday1' -- Self-consumption of PPV (possibly including excess diverted to batteries) in kWh e.g. '2.6kWh' (not accurate for Mix systems) 'eChargeToday2' -- Total self-consumption (PPV consumption(eChargeToday2Echarge1) + Battery Consumption(echarge1)) e.g. '10.1kWh' (not accurate for Mix systems) 'eChargeToday2Echarge1' -- Self-consumption of PPV only e.g. '0.8kWh' (not accurate for Mix systems) 'echarge1' -- Self-consumption from Battery only e.g. '9.3kWh' 'echargeToat' -- Not used on Dashboard view, likely to be total battery discharged e.g. '152.1kWh' 'elocalLoad' -- Total load consumption (etouser + eChargeToday2) e.g. '20.3kWh', (not accurate for Mix systems) 'etouser'-- Energy imported from grid today (includes both directly used by load and AC battery charging e.g. '10.2kWh' 'keyNames' -- Keys to be used for the graph data e.g. ['Solar', 'Load Consumption', 'Export To Grid', 'From Battery'] 'photovoltaic' -- Same as eChargeToday2Echarge1 e.g. '0.8kWh' 'ratio1' -- % of 'Solar production' that is self-consumed e.g. '11.3%' (not accurate for Mix systems) 'ratio2' -- % of 'Solar production' that is exported e.g. '88.7%' (not accurate for Mix systems) 'ratio3' -- % of 'Load consumption' that is self consumption e.g. '49.8%' (not accurate for Mix systems) 'ratio4' -- % of 'Load consumption' that is imported from the grid e.g '50.2%' (not accurate for Mix systems) 'ratio5' -- % of Self consumption that is from batteries e.g. '92.1%' (not accurate for Mix systems) 'ratio6' -- % of Self consumption that is directly from Solar e.g. '7.9%' (not accurate for Mix systems) NOTE: Does not return any data for a tlx system. Use plant_energy_data() instead. """ date_str = self.__get_date_string(timespan, date) response = self.session.post(self.get_url('newPlantAPI.do'), params={ 'action': "getEnergyStorageData", 'date': date_str, 'type': timespan.value, 'plantId': plant_id }) return response.json() def plant_settings(self, plant_id): """ Returns a dictionary containing the settings for the specified plant Keyword arguments: plant_id -- The id of the plant you want the settings of Returns: A python dictionary containing the settings for the specified plant """ response = self.session.get(self.get_url('newPlantAPI.do'), params={ 'op': 'getPlant', 'plantId': plant_id }) return response.json() def storage_detail(self, storage_id): """ Get "All parameters" from battery storage. """ response = self.session.get(self.get_url('newStorageAPI.do'), params={ 'op': 'getStorageInfo_sacolar', 'storageId': storage_id }) return response.json() def storage_params(self, storage_id): """ Get much more detail from battery storage. """ response = self.session.get(self.get_url('newStorageAPI.do'), params={ 'op': 'getStorageParams_sacolar', 'storageId': storage_id }) return response.json() def storage_energy_overview(self, plant_id, storage_id): """ Get some energy/generation overview data. """ response = self.session.post(self.get_url('newStorageAPI.do?op=getEnergyOverviewData_sacolar'), params={ 'plantId': plant_id, 'storageSn': storage_id }) return response.json().get('obj', {}) def inverter_list(self, plant_id): """ Use device_list, it's more descriptive since the list contains more than inverters. """ warnings.warn("This function may be deprecated in the future because naming is not correct, use device_list instead", DeprecationWarning) return self.device_list(plant_id) def __get_all_devices(self, plant_id): """ Get basic plant information with device list. """ response = self.session.get(self.get_url('newTwoPlantAPI.do'), params={'op': 'getAllDeviceList', 'plantId': plant_id, 'language': 1}) return response.json().get('deviceList', {}) def device_list(self, plant_id): """ Get a list of all devices connected to plant. """ device_list = self.plant_info(plant_id).get('deviceList', []) if not device_list: # for tlx systems, the device_list in plant is empty, so use __get_all_devices() instead device_list = self.__get_all_devices(plant_id) return device_list def plant_info(self, plant_id): """ Get basic plant information with device list. """ response = self.session.get(self.get_url('newTwoPlantAPI.do'), params={ 'op': 'getAllDeviceListTwo', 'plantId': plant_id, 'pageNum': 1, 'pageSize': 1 }) return response.json() def plant_energy_data(self, plant_id): """ Get the energy data used in the 'Plant' tab in the phone """ response = self.session.post(self.get_url('newTwoPlantAPI.do'), params={'op': 'getUserCenterEnertyDataByPlantid'}, data={ 'language': 1, 'plantId': plant_id}) return response.json() def is_plant_noah_system(self, plant_id): """ Returns a dictionary containing if noah devices are configured for the specified plant Keyword arguments: plant_id -- The id of the plant you want the noah devices of (str) Returns 'msg' 'result' -- True or False 'obj' -- An Object containing if noah devices are configured 'isPlantNoahSystem' -- Is the specified plant a noah system (True or False) 'plantId' -- The ID of the plant 'isPlantHaveNoah' -- Are noah devices configured in the specified plant (True or False) 'deviceSn' -- Serial number of the configured noah device 'plantName' -- Friendly name of the plant """ response = self.session.post(self.get_url('noahDeviceApi/noah/isPlantNoahSystem'), data={ 'plantId': plant_id }) return response.json() def noah_system_status(self, serial_number): """ Returns a dictionary containing the status for the specified Noah Device Keyword arguments: serial_number -- The Serial number of the noah device you want the status of (str) Returns 'msg' 'result' -- True or False 'obj' -- An Object containing the noah device status 'chargePower' -- Battery charging rate in watt e.g. '200Watt' 'workMode' -- Workingmode of the battery (0 = Load First, 1 = Battery First) 'soc' -- Statement of charge (remaining battery %) 'associatedInvSn' -- ??? 'batteryNum' -- Numbers of batterys 'profitToday' -- Today generated profit through noah device 'plantId' -- The ID of the plant 'disChargePower' -- Battery discharging rate in watt e.g. '200Watt' 'eacTotal' -- Total energy exported to the grid in kWh e.g. '20.5kWh' 'eacToday' -- Today energy exported to the grid in kWh e.g. '20.5kWh' 'pac' -- Export to grid rate in watt e.g. '200Watt' 'ppv' -- Solar generation in watt e.g. '200Watt' 'alias' -- Friendly name of the noah device 'profitTotal' -- Total generated profit through noah device 'moneyUnit' -- Unit of currency e.g. '€' 'status' -- Is the noah device online (True or False) """ response = self.session.post(self.get_url('noahDeviceApi/noah/getSystemStatus'), data={ 'deviceSn': serial_number }) return response.json() def noah_info(self, serial_number): """ Returns a dictionary containing the informations for the specified Noah Device Keyword arguments: serial_number -- The Serial number of the noah device you want the informations of (str) Returns 'msg' 'result' -- True or False 'obj' -- An Object containing the noah device informations 'neoList' -- A List containing Objects 'unitList' -- A Object containing currency units e.g. "Euro": "euro", "DOLLAR": "dollar" 'noah' -- A Object containing the folowing 'time_segment' -- A List containing Objects with configured "Operation Mode" NOTE: The keys are generated numerical, the values are generated with folowing syntax "[workingmode (0 = Load First, 1 = Battery First)]_[starttime]_[endtime]_[output power]" 'time_segment': { 'time_segment1': "0_0:0_8:0_150", ([Load First]_[00:00]_[08:00]_[150 watt]) 'time_segment2': "1_8:0_18:0_0", ([Battery First]_[08:00]_[18:00]_[0 watt]) .... } 'batSns' -- A List containing all battery Serial Numbers 'associatedInvSn' -- ??? 'plantId' -- The ID of the plant 'chargingSocHighLimit' -- Configured "Battery Management" charging upper limit 'chargingSocLowLimit' -- Configured "Battery Management" charging lower limit 'defaultPower' -- Configured "System Default Output Power" 'version' -- The Firmware Version of the noah device 'deviceSn' -- The Serial number of the noah device 'formulaMoney' -- Configured "Select Currency" energy cost per kWh e.g. '0.22' 'alias' -- Friendly name of the noah device 'model' -- Model Name of the noah device 'plantName' -- Friendly name of the plant 'tempType' -- ??? 'moneyUnitText' -- Configured "Select Currency" (Value from the unitList) e.G. "euro" 'plantList' -- A List containing Objects containing the folowing 'plantId' -- The ID of the plant 'plantImgName' -- Friendly name of the plant Image 'plantName' -- Friendly name of the plant """ response = self.session.post(self.get_url('noahDeviceApi/noah/getNoahInfoBySn'), data={ 'deviceSn': serial_number }) return response.json() def update_plant_settings(self, plant_id, changed_settings, current_settings = None): """ Applies settings to the plant e.g. ID, Location, Timezone See README for all possible settings options Keyword arguments: plant_id -- The id of the plant you wish to update the settings for changed_settings -- A python dictionary containing the settings to be changed and their value current_settings -- A python dictionary containing the current settings of the plant (use the response from plant_settings), if None - fetched for you Returns: A response from the server stating whether the configuration was successful or not """ #If no existing settings have been provided then get them from the growatt server if current_settings == None: current_settings = self.plant_settings(plant_id) #These are the parameters that the form requires, without these an error is thrown. Pre-populate their values with the current values form_settings = { 'plantCoal': (None, str(current_settings['formulaCoal'])), 'plantSo2': (None, str(current_settings['formulaSo2'])), 'accountName': (None, str(current_settings['userAccount'])), 'plantID': (None, str(current_settings['id'])), 'plantFirm': (None, '0'), #Hardcoded to 0 as I can't work out what value it should have 'plantCountry': (None, str(current_settings['country'])), 'plantType': (None, str(current_settings['plantType'])), 'plantIncome': (None, str(current_settings['formulaMoneyStr'])), 'plantAddress': (None, str(current_settings['plantAddress'])), 'plantTimezone': (None, str(current_settings['timezone'])), 'plantLng': (None, str(current_settings['plant_lng'])), 'plantCity': (None, str(current_settings['city'])), 'plantCo2': (None, str(current_settings['formulaCo2'])), 'plantMoney': (None, str(current_settings['formulaMoneyUnitId'])), 'plantPower': (None, str(current_settings['nominalPower'])), 'plantLat': (None, str(current_settings['plant_lat'])), 'plantDate': (None, str(current_settings['createDateText'])), 'plantName': (None, str(current_settings['plantName'])), } #Overwrite the current value of the setting with the new value for setting, value in changed_settings.items(): form_settings[setting] = (None, str(value)) response = self.session.post(self.get_url('newTwoPlantAPI.do?op=updatePlant'), files = form_settings) return response.json() def update_inverter_setting(self, serial_number, setting_type, default_parameters, parameters): """ Applies settings for specified system based on serial number See README for known working settings Arguments: serial_number -- Serial number (device_sn) of the inverter (str) setting_type -- Setting to be configured (str) default_params -- Default set of parameters for the setting call (dict) parameters -- Parameters to be sent to the system (dict or list of str) (array which will be converted to a dictionary) Returns: JSON response from the server whether the configuration was successful """ settings_parameters = parameters #If we've been passed an array then convert it into a dictionary if isinstance(parameters, list): settings_parameters = {} for index, param in enumerate(parameters, start=1): settings_parameters['param' + str(index)] = param settings_parameters = {**default_parameters, **settings_parameters} response = self.session.post(self.get_url('newTcpsetAPI.do'), params=settings_parameters) return response.json() def update_mix_inverter_setting(self, serial_number, setting_type, parameters): """ Alias for setting inverter parameters on a mix inverter See README for known working settings Arguments: serial_number -- Serial number (device_sn) of the inverter (str) setting_type -- Setting to be configured (str) parameters -- Parameters to be sent to the system (dict or list of str) (array which will be converted to a dictionary) Returns: JSON response from the server whether the configuration was successful """ default_parameters = { 'op': 'mixSetApiNew', 'serialNum': serial_number, 'type': setting_type } return self.update_inverter_setting(serial_number, setting_type, default_parameters, parameters) def update_ac_inverter_setting(self, serial_number, setting_type, parameters): """ Alias for setting inverter parameters on an AC-coupled inverter See README for known working settings Arguments: serial_number -- Serial number (device_sn) of the inverter (str) setting_type -- Setting to be configured (str) parameters -- Parameters to be sent to the system (dict or list of str) (array which will be converted to a dictionary) Returns: JSON response from the server whether the configuration was successful """ default_parameters = { 'op': 'spaSetApi', 'serialNum': serial_number, 'type': setting_type } return self.update_inverter_setting(serial_number, setting_type, default_parameters, parameters) def update_tlx_inverter_time_segment(self, serial_number, segment_id, batt_mode, start_time, end_time, enabled): """ Updates the time segment settings for a TLX hybrid inverter. Arguments: serial_number -- Serial number (device_sn) of the inverter (str) segment_id -- ID of the time segment to be updated (int) batt_mode -- Battery mode (int) start_time -- Start time of the segment (datetime.time) end_time -- End time of the segment (datetime.time) enabled -- Whether the segment is enabled (bool) Returns: JSON response from the server whether the configuration was successful """ params = { 'op': 'tlxSet' } data = { 'serialNum': serial_number, 'type': f'time_segment{segment_id}', 'param1': batt_mode, 'param2': start_time.strftime('%H'), 'param3': start_time.strftime('%M'), 'param4': end_time.strftime('%H'), 'param5': end_time.strftime('%M'), 'param6': '1' if enabled else '0' } response = self.session.post(self.get_url('newTcpsetAPI.do'), params=params, data=data) result = response.json() if not result.get('success', False): raise Exception(f"Failed to update TLX inverter time segment: {result.get('msg', 'Unknown error')}") return result def update_tlx_inverter_setting(self, serial_number, setting_type, parameter): """ Alias for setting parameters on a tlx hybrid inverter See README for known working settings Arguments: serial_number -- Serial number (device_sn) of the inverter (str) setting_type -- Setting to be configured (str) parameter -- Parameter(s) to be sent to the system (str, dict, list of str) (array which will be converted to a dictionary) Returns: JSON response from the server whether the configuration was successful """ default_parameters = { 'op': 'tlxSet', 'serialNum': serial_number, 'type': setting_type } # If parameter is a single value, convert it to a dictionary if not isinstance(parameter, (dict, list)): parameter = {'param1': parameter} elif isinstance(parameter, list): parameter = {f'param{index+1}': param for index, param in enumerate(parameter)} return self.update_inverter_setting(serial_number, setting_type, default_parameters, parameter) def update_noah_settings(self, serial_number, setting_type, parameters): """ Applies settings for specified noah device based on serial number See README for known working settings Arguments: serial_number -- Serial number (device_sn) of the noah (str) setting_type -- Setting to be configured (str) parameters -- Parameters to be sent to the system (dict or list of str) (array which will be converted to a dictionary) Returns: JSON response from the server whether the configuration was successful """ default_parameters = { 'serialNum': serial_number, 'type': setting_type } settings_parameters = parameters #If we've been passed an array then convert it into a dictionary if isinstance(parameters, list): settings_parameters = {} for index, param in enumerate(parameters, start=1): settings_parameters['param' + str(index)] = param settings_parameters = {**default_parameters, **settings_parameters} response = self.session.post(self.get_url('noahDeviceApi/noah/set'), data=settings_parameters) return response.json() PyPi_GrowattServer-1.6.0/setup.py000077500000000000000000000013141472215715700170240ustar00rootroot00000000000000import setuptools import os with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="growattServer", version="1.6.0", author="IndyKoning", author_email="indykoningnl@gmail.com", description="A package to talk to growatt server", license="MIT", long_description=long_description, long_description_content_type="text/markdown", url="https://github.com/indykoning/PyPi_GrowattServer", packages=setuptools.find_packages(), classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ "requests", ], )