Skip to main content

HydroQC - Hydro Quebec API wrapper

CI Fixture test coverage PyPI

This is a library to use if you want to build your own solution. If you want a user-friendly implementation for your home automation system please use hydroqc2mqtt which provide a MQTT publisher, docker image and HASS addon.

This is a package to access some functionalities of Hydro Quebec API that are not documented.

We started a discord server for the project where you can come to discuss and find help with the project on our #development channel

Donations

We put a lot of heart and effort in this project, any contribution is greatly appreciated!

Donate

Tested Rates

Each account, contracts and rates are different and we do our best to integrate all available options. Currently the account combinations listed below are supported and tested automaticaly by our CI/CD pipeline. If your account scenario is not currently tested and listed as Needed feel free to reach out to us on our discord #development channel if you want to volunter for testing. We provide a way to setup CI/CD tests in your own account in a way that keep your account info private to you (more details here). Keep in mind that this process is a bit involved technicaly so it is best if you have some working knowledge with Gitlab.

Rate D

Base Rate Rate Option Tester Test result Last run Comment
D - @weimdall Test Result Timestamp
D - @mdallaire1 Test Result Timestamp
D - @devzwf Test Result Timestamp Hilo
D CPC @titilambert Test Result Timestamp

Flex D (DPC)

Base Rate Rate Option Tester Test result Last run Comment
DPC - @mdallaire1 Test Result Timestamp

Dual Energy (DT)

Base Rate Rate Option Tester Test result Last run Comment
DT - @mdallaire1 Test Result Timestamp

Rate M

Base Rate Rate Option Tester Test result Last run Comment
M - @hdenergy Test Result Timestamp HD Énergie
M GDP @hdenergy Test Result Timestamp HD Énergie

Thanks to HD Énergie for sponsoring developpement of the Rate M support.

Other plans

We don't have anyone to test with. Please reach out to us if you have this plan and want to help!

Adding replay fixtures

Replay fixtures let the regular test suite exercise contract scenarios without making live Hydro-Québec requests. To capture a new contract type, use a Hydro-Québec account that has that contract and run the capture command from the repository root:

python -m venv .venv  # skip if the virtual environment already exists
.venv/bin/python -m pip install -e . -r test_requirements.txt
.venv/bin/hydroqc-capture

Install capture_requirements.txt alongside the test dependencies to get the optional Presidio capture/anonymization dependencies and the small French spaCy model. These are not runtime dependencies of HydroQC. Keeping these requirements separate avoids conflicting with test-only packages such as Home Assistant stubs. In a development environment, run:

.venv/bin/python -m pip install -e . -r test_requirements.txt
.venv/bin/python -m pip install -r capture_requirements.txt

The French model is installed with these packages; capture and fixture pseudonymization do not download a model at runtime.

The command prompts for the username and, when needed, the password and MFA code. Once logged in, it lists the contracts available on the account and asks which one to capture. Pass --contract <contract-number> to skip that prompt.

For a contract captured during its winter period, add --winter-period so its fixtures are kept separately from non-winter data:

.venv/bin/hydroqc-capture --contract <contract-number> --winter-period

If the virtual environment is already active, use hydroqc-capture instead of .venv/bin/hydroqc-capture. It captures both the web and mobile API profiles and runs the contract operations discovered by the capture script. At the end it asks whether to keep the saved sessions (tokens and cookies) for the next capture or to purge them.

After a successful capture, the script pseudonymizes the responses and installs them automatically under tests/fixtures/:

tests/fixtures/
  DPC_SUMMER/
    capture-01/
      scenario.json
      common/               # this capture's contract-selection responses
        web/
        mobile/
      contract/             # this capture's rate-specific responses
        web/
        mobile/
  D_CPC_SUMMER/
    capture-01/
      ...

The outer directory is named from the captured rate and option, joined by an underscore when an option exists, then suffixed with _SUMMER or _WINTER (for example, D_CPC_SUMMER or M_GDP_WINTER). Each capture has its own neutral fixture-set name, such as capture-01; its common selection responses stay with that set instead of being shared or overwritten by another capture. After capturing, the command lists existing sets and lets you replace one (with a separate confirmation) or create a new one. New names must be neutral and must not contain personal or contract-identifying information.

The same choice can be made explicitly on the command line. Give a new name to add a separate set, or add --replace-fixture to replace that named set:

.venv/bin/hydroqc-capture --fixture-name capture-02
.venv/bin/hydroqc-capture --fixture-name capture-01 --replace-fixture

An existing set is never replaced implicitly. The --winter-period flag selects the _WINTER suffix and records "winter_period": true in its scenario.json; without the flag, the scenario gets a _SUMMER suffix and the field is false. This works with any rate and option, including G and M: for example, G_SUMMER / G_WINTER or M_GDP_SUMMER / M_GDP_WINTER. The separate folders keep each season's responses apart.

The capture pseudonymizes customer, account, contract, location, and contact details. It preserves consumption readings and their dates, so these are pseudonymized fixtures—not fully anonymized data—and should still be handled carefully. Monetary amounts are synthesized. OAuth token responses are not installed as fixtures. On success, the sensitive raw capture is deleted. Do not use --keep-raw for a normal fixture contribution, and never commit or share a raw capture. If capture fails, it prints the location of the raw files for local diagnosis; remove them securely when finished.

Add one full scenario test for each contract type in tests/scenarios/, using tests/scenarios/test_d_cpc.py as the template. Parameterize the test over web and mobile, load the selected fixture set's common responses followed by its contract responses, and replay the complete authenticated hierarchy through run_webuser_contract_scenario (WebUser → Customer → Account → Contract). Assert the expected rate and option, and assert that the replay transport consumed every recorded response. If a contract type has multiple fixture sets, the scenario test discovers and replays each set. Contract fixtures without the infoCompte responses needed for the authenticated hierarchy must be recaptured before they can run this full scenario.

Run the new scenario without network access, then run all safe local tests:

.venv/bin/python -m pytest -q tests/scenarios/test_<scenario>.py
.venv/bin/python -m pytest -q tests/unit tests/scenarios

Documentation

Code documentation

https://hydroqc.readthedocs.io/

Architecture / concepts

If you need more information about the usage and current integrations of the library please see our website https://hydroqc.ca

E-mail verification (MFA)

Hydro-Québec can ask for a one-time code sent by e-mail after the password round trip. login() returns a LoginStatus instead of a plain boolean:

from hydroqc.consts import LoginStatus
from hydroqc.error import HydroQcMFAInvalidCodeError

status = await webuser.login()
while status is LoginStatus.MFA_REQUIRED:
    code = input("Verification code (empty = send a new one): ")
    if not code.strip():
        await webuser.request_mfa_code()
        continue
    try:
        status = await webuser.submit_mfa_code(code)
    except HydroQcMFAInvalidCodeError:
        print("Code refused, try again.")

if status is not LoginStatus.SUCCESS:
    raise RuntimeError("Login failed")

bool(status) is only true for LoginStatus.SUCCESS, so existing code using if await webuser.login(): keeps working. The code is requested automatically when the step is detected; request_mfa_code() sends a new one. The verification step expires after a few minutes (3 minutes on the current portal): HydroQcMFAExpiredError means the login has to be restarted.

The newer policy first asks how to receive the code: the library always answers e-mail (a text message step is reported as a failure). An account without a registered phone then gets an "add your mobile" page, which is skipped automatically: the login never asks for a phone number.

A silent background login cannot ask for a code and raises HydroQcMFARequiredError instead of failing quietly.

Reusing a session

export_session_state() returns the OAuth tokens plus the Azure AD B2C cookies; import_session_state() restores them. Persisting that state lets a later run skip the password (and a new verification code) while the refresh token or the single sign-on cookie is still valid. The current portal issues 15-minute access tokens and a 24-hour refresh token, so the stored session is normally reusable for about a day; once the refresh token and the single sign-on cookie are both refused, a new interactive login (and a new code) is required:

state = webuser.export_session_state()   # store it somewhere safe
# ... next run ...
webuser = WebUser(username, password, verify_ssl=True)
webuser.import_session_state(state)
if await webuser.try_silent_login() is not LoginStatus.SUCCESS:
    await webuser.login()

Goal

Make it easy to fetch and manipulate data from Hydro-Quebec, especially the winter credit periods

Example folder

An example script that extracts the data available from Hydro-Quebec is available in the examples folder.

Basic setup

This uses python 3.10

  1. Clone the repo

    git clone https://github.com/hydroqc/hydroqc.git
    
  2. Create a virtual-env

    python -m venv env
    . env/bin/activate
    pip install --editable .
    
  3. Enter your hydro account credentials in the examples/hydro.py file (line 6)

  4. Run

    examples/hydro.py
    

TODO

https://gitlab.com/groups/hydroqc/-/issues

Targeted architecture (might change in the future)

classDiagram
    WebUser <-- Customer
    WebUser <-- HydroClient

    Customer <-- Account

    Account <-- Contract

    Contract <-- HydroClient
    Contract <-- Period
    Contract <-- Event
    Contract <-- WinterCreditHelper

    WinterCreditHelper <-- HydroClient


    HydroClient <-- Authenticator

    class HydroClient{

    }
    class WinterCreditHelper{
    }

    class WebUser{
        -HydroClient _hydro_client
        +List~Customer~ customers
        +get_contracts()
    }

    class Customer{
        -HydroClient _hydro_client
        +List~Account~ accounts
    }

    class Account{
        -HydroClient _hydro_client
        +List~Contract~ contracts
    }

    class Config{
        -string config_file_path
    }

    class Contract{
        -HydroClient _hydro_client
        -int customer_id
        -int webuser_id
        +string subscription_type
        +float balance
        +list~Period~ periods
        +list~Event~ events
        +get_winter_credit()
        +fetch_periods()
        +fetch_summary()
    }

    class Period{
    }

    class Event{
    }

Metadata

Release files for Hydro-Quebec-API-Wrapper 4.5.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for Hydro-Quebec-API-Wrapper 4.5.1
File Size Uploaded Provenance Actions
hydro_quebec_api_wrapper-4.5.1.tar.gz 548.8 kB Without provenance Details for hydro_quebec_api_wrapper-4.5.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for Hydro-Quebec-API-Wrapper 4.5.1
File Interpreter ABI Platform Actions
hydro_quebec_api_wrapper-4.5.1-py3-none-any.whl Python 3 none any Details for hydro_quebec_api_wrapper-4.5.1-py3-none-any.whl

Total release size: 651.8 kB

Release files / hydro_quebec_api_wrapper-4.5.1.tar.gz

Download URL hydro_quebec_api_wrapper-4.5.1.tar.gz
Size 548.8 kB
Tags Source
SHA-256 checksum
How to use checksums
78d35b255e7de0424b023b1192a63119fb0eed4fd67b0586d3a6e71daf5778d3
BLAKE2b-256 checksum
How to use checksums
228aecdb827a65ad83f122603cb5d02456ef63b91d1ceb681caccc71eb8c77f8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Release files / hydro_quebec_api_wrapper-4.5.1-py3-none-any.whl

Download URL hydro_quebec_api_wrapper-4.5.1-py3-none-any.whl
Size 103.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
1ce0fc967624dc63205a371a78f9b8d86df4a295cdbf90befa80fe5c96378b1a
BLAKE2b-256 checksum
How to use checksums
e6c59046bf91477ec227978b7ca71c118a3aa74633fa1b8c218e9606bd6bdc63
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Security for Hydro-Quebec-API-Wrapper 4.5.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

4.5.1 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page