-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathexample_external_session.py
More file actions
67 lines (48 loc) · 2.22 KB
/
example_external_session.py
File metadata and controls
67 lines (48 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""Example of using python-openevse-http with an external aiohttp.ClientSession.
This demonstrates how to pass your own session to the library, which is useful when:
- You want to manage the session lifecycle yourself
- You need to share a session across multiple API clients
- You want to configure custom session settings (timeouts, connectors, etc.)
"""
import asyncio
import aiohttp
from openevsehttp.__main__ import OpenEVSE
async def example_with_external_session():
"""Demonstrate using an external session."""
# Create your own session with custom settings
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
# Pass the session to OpenEVSE
charger = OpenEVSE("openevse.local", session=session)
# Use the charger normally
await charger.update()
print(f"Status: {charger.status}")
print(f"Current: {charger.charging_current}A")
# The session will be closed when the context manager exits
# but OpenEVSE won't close it (since it's externally managed)
await charger.ws_disconnect()
async def example_without_external_session():
"""Demonstrate without external session (backward compatible)."""
# The library will create and manage its own sessions
charger = OpenEVSE("openevse.local")
# Use the charger normally
await charger.update()
print(f"Status: {charger.status}")
print(f"Current: {charger.charging_current}A")
await charger.ws_disconnect()
async def example_shared_session():
"""Demonstrate sharing a session between multiple clients."""
async with aiohttp.ClientSession() as session:
# Use the same session for multiple chargers
charger1 = OpenEVSE("charger1.local", session=session)
charger2 = OpenEVSE("charger2.local", session=session)
# Both chargers use the same session
await charger1.update()
await charger2.update()
print(f"Charger 1 Status: {charger1.status}")
print(f"Charger 2 Status: {charger2.status}")
await charger1.ws_disconnect()
await charger2.ws_disconnect()
if __name__ == "__main__":
# Run one of the examples
asyncio.run(example_with_external_session())