Examples

Monitoring Example

Simple demonstration of connecting to a known device and printing out telemetry updates.

 1"""Example usage of SolixBLE.
 2
 3.. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
 4
 5"""
 6
 7import asyncio
 8import logging
 9
10from SolixBLE import C300, discover_devices
11
12logging.basicConfig(level=logging.DEBUG)
13
14
15async def main():
16
17    # Find device
18    devices = await discover_devices()
19
20    selected_device = None
21    for device in devices:
22        if device.name is not None and "C300" in device.name:
23            selected_device = device
24            break
25
26    if selected_device is None:
27        print("Device not found!")
28        return
29
30    # Initialize the device
31    device = C300(selected_device)
32    # device = C1000(selected_device)
33
34    # Connect
35    connected = await device.connect()
36
37    if not connected:
38        raise Exception
39
40    # Do nothing, the library will print status updates in debug mode
41    await asyncio.sleep(900)
42
43
44if __name__ == "__main__":
45    asyncio.run(main())

Control Example

Simple demonstration of connecting to a known device and sending commands to control its outputs.

 1"""Example usage of SolixBLE for controlling a C1000.
 2
 3.. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
 4
 5"""
 6
 7import asyncio
 8import logging
 9
10from SolixBLE import C1000, SolixBLEDevice, discover_devices
11from SolixBLE.states import LightStatus
12
13logging.basicConfig(level=logging.DEBUG)
14
15
16async def test_ac_output(device: SolixBLEDevice):
17
18    await asyncio.sleep(10)
19    await device.turn_ac_on()
20
21    await asyncio.sleep(10)
22    await device.turn_ac_off()
23
24
25async def test_light_mode(device: SolixBLEDevice):
26
27    await asyncio.sleep(5)
28    await device.set_light_mode(LightStatus.LOW)
29
30    await asyncio.sleep(5)
31    await device.set_light_mode(LightStatus.MEDIUM)
32
33    await asyncio.sleep(5)
34    await device.set_light_mode(LightStatus.HIGH)
35
36    await asyncio.sleep(5)
37    await device.set_light_mode(LightStatus.SOS)
38
39    await asyncio.sleep(5)
40    await device.set_light_mode(LightStatus.OFF)
41
42
43async def main():
44
45    # Find device
46    devices = await discover_devices()
47
48    selected_device = None
49    for device in devices:
50        if device.name is not None and "C1000" in device.name:
51            selected_device = device
52            break
53
54    if selected_device is None:
55        print("Device not found!")
56        return
57
58    # Initialize the device
59    # device = C300(selected_device)
60    device = C1000(selected_device)
61
62    # Connect
63    connected = await device.connect()
64
65    if not connected:
66        raise Exception
67
68    await test_light_mode(device)
69
70    await asyncio.sleep(300)
71
72
73if __name__ == "__main__":
74    asyncio.run(main())

Complex Example

This is a more advanced demonstration program which prompts the user for the device to connect to, its model, and then prints out the telemetry data on demand and when there is an update. This can be used to add support for new devices, see New devices.

  1"""More advanced usage example of SolixBLE.
  2
  3.. moduleauthor:: Harvey Lelliott (flip-dots) <harveylelliott@duck.com>
  4
  5"""
  6
  7import asyncio
  8import logging
  9import sys
 10
 11# Allows for reading and writing to the console at the same time
 12# pip3 install aioconsole
 13from aioconsole import ainput
 14from bleak import BLEDevice
 15
 16from SolixBLE import (
 17    C300,
 18    C300DC,
 19    C800,
 20    C1000,
 21    C1000G2,
 22    F2000,
 23    F3800,
 24    Generic,
 25    MagGo3in1,
 26    PrimeCharger160w,
 27    PrimeCharger250w,
 28    PrimePowerBank20k,
 29    Solarbank2,
 30    Solarbank3,
 31    SolixBLEDevice,
 32    discover_devices,
 33)
 34
 35MODELS = {
 36    "C300": C300,
 37    "C300DC": C300DC,
 38    "C800": C800,
 39    "C1000": C1000,
 40    "C1000 G2": C1000G2,
 41    "F2000 (767 PowerHouse)": F2000,
 42    "F3800": F3800,
 43    "Solarbank 2": Solarbank2,
 44    "Solarbank 3": Solarbank3,
 45    "PrimeCharger160w": PrimeCharger160w,
 46    "PrimeCharger250w": PrimeCharger250w,
 47    "Prime Power Bank 20k/220w": PrimePowerBank20k,
 48    "MagGo 3-in-1 Wireless Charger": MagGo3in1,
 49    "Unknown": Generic,
 50}
 51
 52
 53async def prompt_debug_mode():
 54    """
 55    Prompt the user to enable/disable debug logging.
 56    """
 57    while True:
 58
 59        print("Show debug info? [Y/N]")
 60        response = input().lower()
 61
 62        if response == "y":
 63            logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
 64            break
 65
 66        elif response == "n":
 67            break
 68
 69
 70async def prompt_select_device(devices: list[BLEDevice]) -> SolixBLEDevice:
 71    """
 72    Prompt the user to select the device and model they want to connect to.
 73
 74    :param devices: List of discovered power stations.
 75    :returns: Selected power station with initialized class.
 76    """
 77
 78    # Get Bluetooth device
 79    print("Which device would you like to connect to?")
 80    for i in range(1, len(devices) + 1):
 81        device = devices[i - 1]
 82        print(f"""{i}. "{device.name}"  ({device.address}) """)
 83    ble_device = devices[int(await ainput("> ")) - 1]
 84
 85    # Get model/class of device
 86    print("What model is this device?")
 87    model_keys = list(MODELS.keys())
 88    model_values = list(MODELS.values())
 89    for i in range(1, len(MODELS) + 1):
 90        print(f"""{i}. "{model_keys[i - 1]}" """)
 91    device_class = model_values[int(await ainput("> ")) - 1]
 92
 93    # Return instantiated device
 94    return device_class(ble_device)
 95
 96
 97async def main():
 98    """
 99    Main program loop.
100
101    This prompts the user for logging mode.
102    Looks for power stations.
103    Asks user to select a power station.
104    Asks user to select the model of the power station.
105    Connects to the power station.
106    Prints status updates of the power station.
107    """
108
109    # Ask user for desired logging mode
110    await prompt_debug_mode()
111
112    # Find power stations
113    devices: list[BLEDevice] = []
114    while not devices:
115
116        print("Looking for power station...")
117        devices = await discover_devices()
118        if not devices:
119            print("No devices found! Trying again...")
120
121    # Ask user to select power station and model
122    device = await prompt_select_device(devices)
123
124    # Register callback
125    def my_callback():
126        """
127        Callback executed by library whenever there is a telemetry update.
128        """
129        print("==== REMOTE STATE CHANGE DETECTED ====")
130        print(device)
131        print("==== END OF STATE CHANGE REPORT ====")
132
133    device.add_callback(my_callback)
134
135    # Connect to device
136    await device.connect()
137
138    # Prompt user for action
139    while True:
140        print("What action would you like to perform?")
141        print("1. Print state")
142        print("2. Exit")
143
144        try:
145            action = int(await ainput("> ")) - 1
146            match action:
147
148                # Print state of device
149                case 0:
150                    print(device)
151
152                # Exit program
153                case 1:
154                    await device.disconnect()
155                    print("Goodbye :)")
156                    return
157
158        except ValueError:
159            pass
160
161
162if __name__ == "__main__":
163    asyncio.run(main())