Example Scripts

Check Battery

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Checking battery level
 5"""
 6
 7import asyncio
 8
 9from idun_guardian_sdk import GuardianClient
10
11
12if __name__ == "__main__":
13    client = GuardianClient()
14
15    battery_level = asyncio.run(client.check_battery())
16    print("Battery Level: %s%%" % battery_level)

check_battery.py

Check Impedance

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Checking impedance
 5"""
 6
 7import asyncio
 8
 9from idun_guardian_sdk import GuardianClient
10
11
12def print_impedance(data):
13    print(f"{data}\tOhm")
14
15
16if __name__ == "__main__":
17    client = GuardianClient(debug=True)
18    asyncio.run(client.stream_impedance(handler=print_impedance))

check_impedance.py

Check Impedance For a Specific Time

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Checking impedance with a sample task running in parallel and stop_impedance command
 5
 6Also demonstrates the connect and disconnect methods (not required to be called)
 7"""
 8
 9import asyncio
10from idun_guardian_sdk import GuardianClient
11
12
13def print_impedance(data):
14    print(f"{data}\tOhm")
15
16
17async def sample_task(seconds):
18    """
19    Replace your function/task here
20    """
21    for i in range(seconds):
22        print(f"Run a sample task for: {i}/{seconds} seconds")
23        await asyncio.sleep(1)
24
25
26async def main():
27    client = GuardianClient(debug=True)
28    await client.connect_device()  # Connect to the device is not required, sdk handles it
29
30    print("Starting impedance task")
31    task = asyncio.create_task(client.stream_impedance(handler=print_impedance))
32
33    try:
34        await sample_task(seconds=15)
35        client.stop_impedance()
36        await task
37        await client.disconnect_device()  # Disconnect to the device is not required to be called, sdk handles it on program exit
38
39    except (KeyboardInterrupt, asyncio.CancelledError):
40        pass
41
42
43if __name__ == "__main__":
44    asyncio.run(main())

check_impedance_start_stop.py

Delete Recording

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Delete a recording
 5"""
 6
 7from idun_guardian_sdk import GuardianClient
 8
 9
10my_api_token = ""
11my_recording_id = ""
12
13
14if __name__ == "__main__":
15
16    client = GuardianClient(api_token=my_api_token)
17    recordings = client.delete_recording(recording_id=my_recording_id)

delete_recording.py

Download Data

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Download EEG data from a recording
 5"""
 6
 7from idun_guardian_sdk import GuardianClient, FileTypes
 8
 9
10my_api_token = ""
11my_recording_id = ""
12
13
14if __name__ == "__main__":
15    client = GuardianClient(api_token=my_api_token)
16    client.download_file(recording_id=my_recording_id, file_type=FileTypes.EEG)

download_data.py

Download Daytime Report

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Generate and Download Daytime Report from a recording
 5"""
 6
 7from idun_guardian_sdk import GuardianClient
 8
 9
10my_api_token = ""
11my_recording_id = ""
12
13
14if __name__ == "__main__":
15    client = GuardianClient(api_token=my_api_token)
16    client.generate_and_download_daytime_report(recording_id=my_recording_id)

download_daytime_report.py

Download Sleep Report

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Generate and Download Sleep Report from a recording
 5"""
 6
 7from idun_guardian_sdk import GuardianClient
 8
 9
10my_api_token = ""
11my_recording_id = ""
12
13
14if __name__ == "__main__":
15    client = GuardianClient(api_token=my_api_token)
16    client.generate_and_download_sleep_report(recording_id=my_recording_id)

download_sleep_report.py

Get Recordings

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Get a list of recordings
 5"""
 6
 7from datetime import datetime
 8
 9from idun_guardian_sdk import GuardianClient
10
11
12my_api_token = ""
13
14
15def to_date(timestamp):
16    """
17    Converts timestamp to formatted date/time
18    """
19    milliseconds = int(timestamp / 1000)
20    dt = datetime.fromtimestamp(milliseconds)
21    formatted_date = dt.strftime("%Y-%m-%dT%H:%M:%S")
22    return formatted_date
23
24
25if __name__ == "__main__":
26
27    client = GuardianClient(api_token=my_api_token)
28    recordings = client.get_recordings(status="COMPLETED", limit=10)
29
30    for recording in recordings["items"]:
31        recording_date = to_date(recording["recordingId"])
32        recordin_id = recording["recordingId"]
33        print(f"Recording Date: {recording_date}. Recoring ID: {recordin_id}")

get_recordings.py

Record Data

Note

The realtime predictions feature is not enabled by default. If you want to test this, get in touch with us.

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4- Start recording data from the Guardian Earbuds
 5"""
 6
 7import asyncio
 8from idun_guardian_sdk import GuardianClient
 9
10RECORDING_TIMER: int = 60 * 60 * 2  # 2 hours of recording
11LED_SLEEP: bool = False
12
13my_api_token = ""
14
15
16# Example callback function
17def print_data(event):
18    print("CB Func:", event.message)
19
20
21if __name__ == "__main__":
22    client = GuardianClient(api_token=my_api_token, debug=True)
23
24    # Subscribe to live insights and/or realtime predictions
25    client.subscribe_live_insights(raw_eeg=True, filtered_eeg=True, handler=print_data)
26    client.subscribe_realtime_predictions(fft=True, jaw_clench=False, handler=print_data)
27
28    # start a recording session
29    asyncio.run(
30        client.start_recording(
31            recording_timer=RECORDING_TIMER, led_sleep=LED_SLEEP, calc_latency=False
32        )
33    )

record_data.py

Record Data and Subscribe to Realtime Insights and Predictions

Note

The realtime predictions feature is not enabled by default. If you want to test this, get in touch with us.

 1"""
 2Sample script for using the Guardian Earbud Client
 3
 4Full example of recording data, generating reports and downloading the files
 5"""
 6
 7import asyncio
 8
 9from idun_guardian_sdk import GuardianClient, FileTypes
10
11
12my_api_token = ""
13RECORDING_TIMER = 60 * 15  # 15 min
14
15
16def print_data(data):
17    print(data.message)
18
19
20if __name__ == "__main__":
21    client = GuardianClient(api_token=my_api_token)
22
23    client.subscribe_live_insights(raw_eeg=True, filtered_eeg=True, handler=print_data)
24    client.subscribe_realtime_predictions(
25        fft=True, jaw_clench=False, quality_score=True, handler=print_data
26    )
27
28    asyncio.run(client.start_recording(recording_timer=RECORDING_TIMER))
29    rec_id = client.get_recording_id()
30
31    print("RecordingId", rec_id)
32    client.update_recording_tags(recording_id=rec_id, tags=["tag1", "tag2"])
33    client.update_recording_display_name(recording_id=rec_id, display_name="todays_recordings")
34    client.download_file(recording_id=rec_id, file_type=FileTypes.EEG)
35    client.generate_and_download_sleep_report(recording_id=rec_id)
36    client.generate_and_download_daytime_report(recording_id=rec_id)

record_data_full_example.py

Stream Data to LSL

Note

This requires pylsl to be installed.

 1import asyncio
 2from pylsl import StreamInfo, StreamOutlet
 3
 4from idun_guardian_sdk import GuardianClient
 5
 6RECORDING_TIMER: int = 60 * 60 * 2  # 2 hours
 7my_api_token = ""
 8
 9
10if __name__ == "__main__":
11    client = GuardianClient(api_token=my_api_token)
12    client.address = asyncio.run(client.search_device())
13
14    info = StreamInfo("IDUN", "EEG", 1, 250, "float32", client.address)
15    lsl_outlet = StreamOutlet(info, 20, 360)
16
17    def lsl_stream_handler(event):
18        message = event.message
19        eeg = message["raw_eeg"]
20        most_recent_ts = eeg[-1]["timestamp"]
21        data = [sample["ch1"] for sample in eeg]
22        lsl_outlet.push_chunk(data, most_recent_ts)
23
24    client.subscribe_live_insights(
25        raw_eeg=True,
26        handler=lsl_stream_handler,
27    )
28
29    asyncio.run(client.start_recording(recording_timer=RECORDING_TIMER))

stream_to_lsl.py

Stream Data to LSL and Check Battery

Note

This requires pylsl to be installed.

 1import asyncio
 2from pylsl import StreamInfo, StreamOutlet
 3
 4from idun_guardian_sdk import GuardianClient
 5
 6RECORDING_TIMER: int = 60 * 60 * 2  # 2 hours
 7my_api_token = ""
 8
 9
10async def stop_task(task):
11    task.cancel()
12    try:
13        await task
14    except asyncio.CancelledError:
15        pass
16
17
18async def read_battery_forever(client):
19    while True:
20        battery = await client.check_battery()
21        print("Battery Level: %s%%" % battery)
22        await asyncio.sleep(1)
23
24
25async def main():
26    client = GuardianClient(api_token=my_api_token, debug=True)
27    client.address = await client.search_device()
28
29    info = StreamInfo("IDUN", "EEG", 1, 250, "float32", client.address)
30    lsl_outlet = StreamOutlet(info, 20, 360)
31
32    def lsl_stream_handler(event):
33        message = event.message
34        eeg = message["raw_eeg"]
35        most_recent_ts = eeg[-1]["timestamp"]
36        data = [sample["ch1"] for sample in eeg]
37        lsl_outlet.push_chunk(data, most_recent_ts)
38
39    client.subscribe_live_insights(
40        raw_eeg=True,
41        handler=lsl_stream_handler,
42    )
43
44    recording_task = asyncio.create_task(client.start_recording(recording_timer=RECORDING_TIMER))
45    battery_task = asyncio.create_task(read_battery_forever(client))
46    await recording_task
47    await stop_task(battery_task)
48
49
50if __name__ == "__main__":
51    asyncio.run(main())

stream_to_lsl_show_battery.py