-
Notifications
You must be signed in to change notification settings - Fork 61
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
New provider: National Grid #45
Comments
Do you see requests to opower.com when going to your utility website? If yes, it's up to you or the community to add some code in this library to convert the login credentials to an opower access token. Existing utility implementations might help you. |
Some network calls I saw when logging into national grid: scope openid https://login.nationalgridus.com/opower-uwp/opower profile offline_access |
Nice find!! Let me see if I can line this up with any of the existing providers… |
Page source also has these urls: https://ngbk.opower.com |
I won't realistically be able to get to this for a few days but I can take a stab at this potentially some time within the next week if it's not already in progress. Just happened to come across this library trying to figure out the same problem, so this directly relates to my interests haha |
This seems like it would be very similar to ConEd but maybe we should split it up like Exelon because of the different subdomains. |
Here’s what I found for PSEG LI GAS: initial login endpoint (questionable?) initial login form payload: Get opower access_token: the response will include the access_token the token seems to require a code, I see it in the payload of the request, just not sure where it comes from. There also looks to be many opower subdomains as indicated above, that is only relevant once we have the access_token |
This is also one of the calls they make to create the "Green Button Report" https://ngli.opower.com/ei/edge/apis/DataBrowser-v1/cws/utilities/ngli/customers/<customer_id>/usage_export/download?format=csv it starts a download of a csv with all account data, however even though the browser is logged in it gives:
so perhaps the call should explicitly pass the user information too. |
I need help here. |
Looks like a user on another project built a login to an Azure app exactly like we need to do here! also, adding the following blob for reference |
Ngrid uses a standard Azure AD B2C provider accountNumber: "" //account-specific
authority: "https://login.nationalgrid.com/loginnationalgridus.onmicrosoft.com/B2C_1A_NationalGrid_convert_merge_signin"
clientId: "36488660-e86a-4a0d-8316-3df49af8d06d"
coreJsUrl:"https://ngny.opower.com/ei/x/embedded-api/core.js?auth-mode=oauth&locale=en_US"
customerType: "Residential"
envurl: "https://myaccount.nationalgrid.com/s/opower-widget"
fuelType: "ELEC"
isOpowerSessionForCurrentUser: false
region: "UNY" //region-specific. UNY is 'upstate new york'
scope: "https://login.nationalgridus.com/opower-uwp/opower"
servicePostalCode: "" //account-specific
source: "CSS"
tenant: "loginnationalgridus" edit: looks like they use two different client ids for authentication (i.e. login page) ( |
|
Several notes, most of which can be summed up by "read up on the links above, as well as authentication & authorization flows with OIDC"-
|
Hey, all. After recently getting a National Grid "smart meter" installed, I've been going down the path of trying to integrate the data into Home Assistant, eventually arriving here. I've been digging in a bit myself to see if I can get anything working, but think I may need some help. Based on the discussion so far, and from my experience, it seems like the National Grid auth flow is somewhat troublesome to get working correctly with this project. However, one potential solution that occurred to me would be to instead try to leverage the It would be more roundabout to setup initially, but theoretically, if a user were to log into the site using their browser and manually grab the
I'm curious to hear if this is feasible in the context of this project. I have successfully modified the code to roughly work like this, but the main bumps I'm hitting are:
Below is my python src/demo.py --utility nationalgrid --username="anything" password="abcdef" --start_date 2024-04-01 --end_date 2024-04-07 --aggregate_type day where You'll also need to modify the """National Grid"""
from typing import Optional
import aiohttp
from ..exceptions import InvalidAuth
from .base import UtilityBase
import logging
class NationalGrid(UtilityBase):
"""National Grid utility class."""
@staticmethod
def name() -> str:
return "National Grid"
@staticmethod
def subdomain() -> str:
return "ngny"
@staticmethod
def timezone() -> str:
return "America/New_York"
@staticmethod
def uses_refresh_token() -> bool:
"""Check if utility uses refresh token for authorization."""
return True
@staticmethod
async def async_login(
session: aiohttp.ClientSession,
username: str,
password: str,
optional_mfa_secret: Optional[str],
) -> Optional[str]:
#
logging.debug("LOGIN");
token_url = "https://login.nationalgrid.com/login.nationalgridus.com/b2c_1a_nationalgrid_convert_merge_signin/oauth2/v2.0/token"
async with session.post(
token_url,
data={
"grant_type": "refresh_token",
"refresh_token": password
}
) as response:
if response.status == 200:
data = await response.json()
access_token = data.get("access_token")
return access_token
else:
# If login fails, raise an exception
raise InvalidAuth("Invalid username or password") |
Sorry, I haven't had time to put everything together into a PR for opower. But it's not hard to get through the initial user OAuth, here's how I did it for my region. import re
import requests
import json
def authSession():
username=""
password=""
session = requests.Session()
session.verify = False
session.cookies.set("USRW","r=nyupstate&ct=home",domain=".nationalgridus.com")
session.headers['User-Agent']='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36'
req = session.get("https://myaccount.nationalgrid.com/services/auth/sso/NGP_SignIn_NY_Upstate_Home")
sets = re.search("var SETTINGS = ({.*?});",req.text,re.DOTALL)
settings = json.loads(sets.group(1))
# var f = r.hosts.tenant + "/" + r.api + "?tx=" + r.transId + "&p=" + r.hosts.policy
url = f"https://login.nationalgrid.com/{settings['hosts']['tenant']}/{settings['api']}?tx={settings['transId']}&p={settings['hosts']['policy']}"
headers = {'X-CSRF-TOKEN':settings['csrf']}
authed=session.post(url,headers=headers,data=[("signInName",username),("password",password),("Signin-forgotPassword","FORGOT_PASSWORD_FALSE"),("request_type","RESPONSE")])
completed = f"https://login.nationalgrid.com/{settings['hosts']['tenant']}/api/{settings['api']}/confirmed?tx={settings['transId']}&p={settings['hosts']['policy']}&csrf_token={settings['csrf']}"
res = session.get(completed)
breakpoint()
r = res.text
session.close()
return r |
That's great to hear @X-sam! Let me know if I can help in any way. Like I said, I'm a little out of my area of expertise here, but happy to contribute if I'm able. |
Don't forget about me, what can I do to help? |
Are there any updates on this? I'm going to take a look this week, but am interested if any further developments have been made here. |
Nothing really, I believe we have all the components here but couldn't seem to put the pieces together. |
|
I've submitted a pull request for a different utility company that uses Azure B2C OAuth: https://github.com/tronikos/opower/pull/87/files Might help here if you can replace values for those specific to National Grid |
Thanks for that @SplicedNZ, worked for this as well. #91 should cover National Grid in the Upstate NY region. |
Can people from other regions try this out? I expect you will need to update the opower subdomain (ngny) and judging from the posts above, at least the POLICY (B2C_1A_UWP_NationalGrid_convert_merge_signin). |
You need to clone the repo, setup a python development environment, copy the existing nationalgridnyupstate.py to a new file, rename the file and class to match your region, update constants in the file and try it out with:
Whenever you make changes to the file you need to rerun both of these commands to test your changes. Once it's working, submit a PR. |
Similar to home-assistant/core#122658 and now that #91 is merged, do we need to bump opower in HA? |
Bumping in home-assistant/core#124475 |
Happy to give it a go, where might I find some context for that?
…On Fri, Aug 23, 2024, 6:41 AM tronikos ***@***.***> wrote:
Bumping in home-assistant/core#124475
<home-assistant/core#124475>
@X-sam <https://github.com/X-sam> could you create a virtual integration?
I think a single National Grid virtual integration should be fine. I don't
think we really need one for each region.
—
Reply to this email directly, view it on GitHub
<#45 (comment)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ABSQJ56DM554DQBURPEJI43ZS4GT3AVCNFSM6AAAAAA4RVII56VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDGMBWHAYTKNBSGU>
.
You are receiving this because you were mentioned.Message ID:
***@***.***>
|
You need a total of 3 PRs similar to: |
To be clear, one virtual integration for National Grid, but we still need a utility for each region breaking out and changing the subdomains. Right? |
Right. People from other regions need to send a PR with a utility class with the right domain and constants. |
Shall I just run through the list and make all 6? |
Is the only difference in the domain? If everything else is the same, can we just have a single class and after the login use the appropriate domain based on the result of some endpoint? |
Small tiny little issue here, changing the subdomain successfully logs me in and adds the integration to HA, but no entities come up. |
For many utilities there are no entities. Are there any statistics? You use the statistics in the energy dashboard. See documentation with screenshots. |
Hi, I created a Nat Grid integration for NGMA. I have tested and it is working well with my energy data. No sensors, but usage and costs show in the energy dashboard. @tronikos would you please review and add to Pypi? |
Let's gooooo!
I'd love to jump onboard! This library looks good...
There's a lot of articles talking about national Grid and Opower relations but I can't seem to find a login page. Can you direct me in the right direction?
The text was updated successfully, but these errors were encountered: