Open access peer-reviewed chapter

Perspective Chapter: Medical Jurisprudence Considerations for Therapeutic Metaverse Immersion

Written By

Sarah Katz

Submitted: 04 June 2025 Reviewed: 10 June 2025 Published: 11 November 2025

DOI: 10.5772/intechopen.1011488

Chapter metrics overview

85 Chapter Downloads

View Full Metrics

Abstract

While metaverse technology has seen increasing use in various healthcare settings, the issues of user data privacy violations and bodily harm due to these devices still pose significant risks. This chapter reviews the existing laws surrounding patient data privacy, as well as details how metaverse technologies, such as augmented and virtual reality applications, could harm users due to neurological disturbances. The chapter weighs the benefits versus the costs of implementing artificial intelligence (AI) to enhance these technologies for more secure handling of user data and bodily welfare. The chapter concludes with a set of Python code for a proposed algorithm, allowing an integrated AI functionality to assess and securely store biometric feedback in metaverse immersive environments for a safer and more customized experience.

Keywords

  • Keywordsartificial intelligence
  • augmented reality
  • virtual reality
  • metaverse
  • healthcare
  • privacy law

1. Introduction

The rising use of metaverse technology, such as augmented reality (AR) and virtual reality (VR), in both healthcare and medical education has led to increased investigations into the potential security and safety ramifications for users [1]. Furthermore, the use of artificial intelligence (AI) to enhance these technologies adds an extra layer of nuance to consider – namely, how AI can be leveraged to protect versus harm user safety and data security.

Thus far, vertigo has emerged as a common risk for users of metaverse technologies in a healthcare context. Vertigo is a common and often debilitating condition that can be caused by both underlying neurological conditions, such as migraine and traumatic brain injury, or environmental factors, such as positional disorientation [2]. While AI can be used to help diagnose the root cause of vertigo, AI-enhancing features in metaverse technologies for medical purposes could also pose a vertigo risk due to a more intensive audiovisual immersion experience. Such immersive experiences could arise from the use of VR headsets and other healthcare wearable technologies [3].

Alongside the risk of bodily harm to the user arises the potential for privacy infringement, particularly in the case of AR – in-app advertisements or even surveillance by the application developers. For healthcare wearable technology specifically, the implementation of transnational laws like the General Data Protection Regulation (GDPR) demonstrates an increased cohesive effort to address these risks across borders. Notwithstanding, while advertisements might be easier to control by regulating what kind of user data developers are permitted to collect, wearable medical devices, such as those used for fitness monitoring, often collect user data as a primary function for wellness tracking [4]. This monitoring could include data on both physical and psychological states, such as insulin levels and stress levels. Thus, the line between patient data security and health can grow more ambiguous in this area [5]. Moreover, the sophistication of AI capabilities, such as machine learning (ML), could entail even greater use of both historical and current user data.

2. Risk of user privacy violation and bodily harm during metaverse immersion

Existing privacy measures tend to center on the Health Insurance Portability and Accountability Act (HIPAA) of 1996, which has been recently expanded to include healthcare technology such as the metaverse and wearable devices used for medical purposes. HIPAA covers three overall categories of individuals or organizations within its scope: 1) health plans, 2) healthcare clearinghouses, and 3) healthcare providers. The first entails medical insurance plans such as Cigna, the second pertains to entities that manage community health records or billing, and the third constitutes clinical providers such as individual physicians and psychologists [6].

Unfortunately, wearable healthcare technology can sometimes fly under the radar, especially if the manufacturing organizations of these technologies are not considered covered entities. This potential gap in oversight could result in the recording of protected health information (PHI), which could then be transmitted from a wearable medical device in an unencrypted manner.

Nonetheless, some legal scholars argue that laws such as GDPR and HIPAA could actually limit the development and dissemination of wearable and other metaverse technologies for healthcare [7]. Therefore, a balance is needed between user privacy and the relevant device’s data monitoring and tracking functionality. Such a balance could allow for AI-equipped metaverse technologies that safeguard user information privacy while continually tracking said data through sophisticated measures like biometric tracking [8]. Device developers could achieve this middle ground by developing an algorithm to ensure that patient data is never transferred to the cloud without explicit user permission.

The second risk of metaverse healthcare technologies involves bodily harm, such as neurological disorientation during immersion with wearable VR headsets [9]. In contrast to the aforementioned privacy risk with therapeutic metaverse devices, biometric tracking could actually be used to help record individual user limits for a safer, customized, and more productive experience.

On the whole, however, the metaverse’s expansion beyond extended reality (XR), such as AR and VR, to include less immersive digital experiences, such as chat platform avatars, means a smart wearable medical device often poses different risks from, for example, an unencrypted connection between a patient and a healthcare provider communicating over the Internet [10]. This means that although an XR device might be regulated by certain data or physical security policies, these laws might differ from those governing general chat-based communication.

3. Metaverse-induced bodily harm as a tort

For metaverse-related incidents resulting in physical harm to a user, tort law – or law pertaining to injury to a person – could apply. To that effect, bodily harm such as VR-induced balance issues, as well as threats made in a virtual space, could both be governed by tort law. While a VR device that ends up damaging the user’s vision due to faulty manufacturing would qualify as negligence, bullying or threats made over a virtual communication session present a grayer area, as psychological harm from such interactions can be difficult to prove [11]. This means that the precise nature of the encounter must be taken into account on a case-by-case basis, and a final verdict determined by a judge, which tends to involve subjectivity.

That said, physical bodily harm tends to be more provable when stemming directly from the use of a device, such as vision loss correlated with VR headset usage. Still, the exact source of liability can be murkier, especially when uncertainty arises regarding whether the human manufacturers or any AI features caused the actual harm [12]. In cases where the point of user injury must be determined for appropriate accountability and liability purposes, an integrated algorithm could further assist in identifying the timing of injury, with biometric tracking – such as irregular eye movement – serving as a control. In this scenario, the algorithm would monitor the amount of time passed between device startup and the initiation of biometric irregularity.

4. Proposed algorithm for preventing privacy infringement and bodily harm during metaverse immersion

Thus, an algorithm to safeguard both user data and physical security would need to be capable of defending against attacks such as evasion and irregular queries during inference, poisoning attacks, Byzantine attacks (nodes intentionally and maliciously sending misinformation to other nodes in the network), and irregular distribution during training [13]. In particular, user privacy protection would have to be implemented during the initial distributed learning stage and model inference at deployment, as well as continuously upheld by an appropriate quality of AI fair governance.

The algorithm would also have to prioritize local, encrypted storage of PHI for safe, reliable tracking of user data. This data could include metrics like heart rate in response to immersion, to customize a tailored user experience going forward.

The appendix of this chapter provides sections of Python code to illustrate a rudimentary foundation for the proposed algorithm, which encompasses user data privacy as well as bodily well-being for VR and AR technologies, respectively. The code aims to help balance user privacy with bodily safety by supplying mechanisms for both biometric tracking and encryption measures. The algorithm presents a theoretical basis for the intended technology ethics component of this study.

5. Conclusion

5.1. Policy considerations

Prioritization of adapting existing data privacy and physical protection measures for metaverse healthcare technology users will require the combined efforts of governing bodies that craft AI and technology governance alongside those setting forth healthcare security policies. Alongside safeguards against bodily harm, such as taking into account the limitations of individual users, policy should also focus on enforcing the confidentiality of user data gathered by the device, ensuring that device developers cannot monitor user activity or information.

Currently, a sample joint initiative in the context of the United States would entail entities such as the US Department of Health and Human Services (HHS) and the Food and Drug Administration (FDA) consulting with the United Nations’ AI Advisory Body and the World Economic Forum for secure metaverse technology development for healthcare.

These governing bodies could use European and US concepts of tort law to help navigate the metaverse security landscape, keeping in mind the need to adapt all behaviors of practitioners and technologies alike to existing healthcare policies for patient protection by HIPAA. These in-place policies could be supplemented by newer regulations set forth by entities like the UN AI Advisory Board to enhance accountability assurance for both human practitioners and manufacturers, as well as best practices for defining such accountability (as with configuring these healthcare devices to track the point of liability that caused harm to the user).

A challenge that could arise when restricting developer visibility into user data during VR device use entails potential overreliance on the user to be capable of interpreting or even remembering to examine the results of their biometric device log reports. Similarly, AR healthcare devices could pose obstacles for users who do not check log reports from their integrated AR application and smart wearable device. These challenges could be overcome with time by healthcare practitioners and metaverse healthcare device manufacturers promoting the importance of patient self-monitoring to track their own limitations and sensitivities during immersion.

Overall, existing law should be applied to, and ideally adapted according to, evolving immersive healthcare technology, which might require a balance of user privacy and biometric data collection for both personal tracking and interpretation by a medical provider for further treatment.

5.2. Future research

Future studies could adopt quantitative methods to investigate whether the majority of extended reality healthcare device users experience issues with data privacy or bodily harm during immersion. Such findings could help guide prioritization for policymaking surrounding both user protection from developer-side surveillance and physical injury. Furthermore, the proposed algorithm presented could be empirically validated to test its integration into immersive healthcare technology. Finally, perhaps as its own study, the many potential psychological effects of cyberbullying in a therapeutic metaverse environment could also be examined.

Appendix

Python code for VR user safety algorithm, focusing on biometric tracking and encryption

from cryptography.fernet import Fernet

import time

import random

import json

from datetime import datetime

# Thresholds

HEART_RATE_THRESHOLD = 10

EYE_MOVEMENT_VARIATION = 10

# Baselines

baseline_heart_rate = 70

baseline_eye_movement = 50

# File paths

KEY_FILE = "/mnt/data/encryption.key"

ENCRYPTED_LOG_FILE = "/mnt/data/encrypted_vr_response_log.json"

# Generate and store encryption key

key = Fernet.generate_key()

with open(KEY_FILE, "wb") as key_file:

key_file.write(key)

fernet = Fernet(key)

# Simulated sensor data functions

def read_heart_rate():

return baseline_heart_rate + random.randint(-5, 20)

def read_eye_movement():

return baseline_eye_movement + random.randint(-20, 20)

# Alert function

def alert_user():

print("ALERT: A notable pattern in physiological response was detected!")

# Log encrypted event

def log_encrypted_event(heart_rate, eye_movement):

event = {

"timestamp": datetime.now().isoformat(),

"heart_rate": heart_rate,

"eye_movement": eye_movement

}

encrypted_data = fernet.encrypt(json.dumps(event).encode())

with open(ENCRYPTED_LOG_FILE, "ab") as file:

file.write(encrypted_data + b"\n")

# Monitor loop with logic for eye movement decrease then increase

previous_eye = baseline_eye_movement

eye_decreased = False

for _ in range(20): # simulate 20 data points

heart_rate = read_heart_rate()

eye_movement = read_eye_movement()

heart_rate_increased = heart_rate > baseline_heart_rate + HEART_RATE_THRESHOLD

if not eye_decreased and eye_movement < previous_eye - EYE_MOVEMENT_VARIATION:

eye_decreased = True

elif eye_decreased and eye_movement > previous_eye + EYE_MOVEMENT_VARIATION:

eye_pattern_detected = True

else:

eye_pattern_detected = False

if heart_rate_increased and eye_decreased and eye_pattern_detected:

alert_user()

log_encrypted_event(heart_rate, eye_movement)

eye_decreased = False # reset to catch future patterns

previous_eye = eye_movement

time.sleep(1)

ENCRYPTED_LOG_FILE

Heart rate and eye movement were used as the sample biometrics in the sample code shown in the appendix of this chapter, based on the aforementioned identification of these metrics as determinants for patient anxiety levels and vertigo, respectively. Upon successful validation of this code, a functional algorithm should be in place for integration into total-immersion (VR) and partial-immersion (AR) metaverse technologies that help ensure user physical and data security.

Python code for AR user safety algorithm, focusing on keyboard haptic feedback and data privacy

from cryptography.fernet import Fernet

import tkinter as tk

from PIL import Image, ImageTk

import time

import random

import json

from datetime import datetime

import threading

# Constants

BASELINE_HEART_RATE = 70

HEART_RATE_THRESHOLD = 10

KEY_FILE = "gui_hr_encryption.key"

LOG_FILE = "gui_encrypted_hr_log.json"

# Generate and save encryption key

key = Fernet.generate_key()

with open(KEY_FILE, "wb") as kf:

kf.write(key)

fernet = Fernet(key)

# Simulated haptic feedback

def simulate_haptic_feedback():

print("Simulated haptic feedback triggered.")

# Simulated heart rate sensor

def read_heart_rate():

return BASELINE_HEART_RATE + random.randint(-5, 25)

# Log encrypted event

def log_encrypted_event(hr):

event = {

"timestamp": datetime.now().isoformat(),

"heart_rate": hr

}

encrypted = fernet.encrypt(json.dumps(event).encode())

with open(LOG_FILE, "ab") as log_file:

log_file.write(encrypted + b"\n")

# GUI application

def start_gui_monitor():

root = tk.Tk()

root.title("Heart Rate Monitor")

root.geometry("500x500")

label = tk.Label(root, text="Monitoring heart rate in response to image…", font=("Arial", 14))

label.pack(pady=10)

# Display placeholder image

img = Image.new("RGB", (400, 300), color="skyblue")

photo = ImageTk.PhotoImage(img)

image_label = tk.Label(root, image=photo)

image_label.image = photo

image_label.pack(pady=20)

alert_text = tk.StringVar()

alert_label = tk.Label(root, textvariable=alert_text, fg="red", font=("Arial", 16))

alert_label.pack(pady=20)

def monitor():

for _ in range(15):

hr = read_heart_rate()

print(f"Heart Rate: {hr}")

if hr > BASELINE_HEART_RATE + HEART_RATE_THRESHOLD:

alert_text.set("ALERT: Heart rate spike detected!")

simulate_haptic_feedback()

log_encrypted_event(hr)

else:

alert_text.set("")

time.sleep(1)

threading.Thread(target=monitor, daemon=True).start()

root.mainloop()

start_gui_monitor()

The same code, adapted for headless environments – devices without a typical graphical user interface, such as a keyboard for haptic (touch-based) feedback rather than a monitor – is shown below:

from cryptography.fernet import Fernet

import tkinter as tk

from PIL import Image, ImageTk

import time

import random

import json

from datetime import datetime

import threading

# Constants

BASELINE_HEART_RATE = 70

HEART_RATE_THRESHOLD = 10

IMAGE_PATH = "/mnt/data/sample_image.jpg" # Simulated image path

KEY_FILE = "/mnt/data/gui_hr_encryption.key"

LOG_FILE = "/mnt/data/gui_encrypted_hr_log.json"

# Generate and save encryption key

key = Fernet.generate_key()

with open(KEY_FILE, "wb") as kf:

kf.write(key)

fernet = Fernet(key)

# Simulated haptic feedback

def simulate_haptic_feedback():

print("Simulated haptic feedback triggered.")

# Simulated heart rate sensor

def read_heart_rate():

return BASELINE_HEART_RATE + random.randint(-5, 25)

# Log encrypted event

def log_encrypted_event(hr):

event = {

"timestamp": datetime.now().isoformat(),

"heart_rate": hr

}

encrypted = fernet.encrypt(json.dumps(event).encode())

with open(LOG_FILE, "ab") as log_file:

log_file.write(encrypted + b"\n")

# GUI application with alert display

def start_gui_monitor():

root = tk.Tk()

root.title("Heart Rate Monitor")

root.geometry("500x500")

label = tk.Label(root, text="Monitoring heart rate in response to image…", font=("Arial", 14))

label.pack(pady=10)

# Load and display image

img = Image.new("RGB", (400, 300), color="skyblue") # Placeholder image

photo = ImageTk.PhotoImage(img)

image_label = tk.Label(root, image=photo)

image_label.image = photo

image_label.pack(pady=20)

alert_text = tk.StringVar()

alert_label = tk.Label(root, textvariable=alert_text, fg="red", font=("Arial", 16))

alert_label.pack(pady=20)

def monitor():

for _ in range(15):

hr = read_heart_rate()

print(f"Heart Rate: {hr}")

if hr > BASELINE_HEART_RATE + HEART_RATE_THRESHOLD:

alert_text.set("ALERT: Heart rate spike detected!")

simulate_haptic_feedback()

log_encrypted_event(hr)

else:

alert_text.set("")

time.sleep(1)

# Run monitoring in a separate thread to keep GUI responsive

threading.Thread(target=monitor, daemon=True).start()

root.mainloop()

start_gui_monitor()

Python code for a VR user safety algorithm, focusing on the time between immersion initiation and irregular biometric activity

import time

import os

import json

from datetime import datetime

from random import uniform # Mock eye-tracking

import psutil # For monitoring AI processes

# === CONFIGURATION ===

DATA_FILE = os.path.expanduser("~/vr_eye_movement_log.json") # Saved only to user directory

AI_KEYWORDS = ['ai_module', 'neural', 'deep_learning'] # Keywords to identify AI software processes

# === MOCKED FUNCTIONS (replace with actual SDK hooks) ===

def get_eye_movement_value():

"""Simulate eye movement value. Replace with actual VR SDK call."""

return uniform(0.0, 10.0)

def get_active_ai_processes():

"""Check for AI-related processes running on the system."""

ai_processes = []

for proc in psutil.process_iter(['pid', 'name', 'cmdline']):

try:

if any(keyword in ' '.join(proc.info['cmdline']).lower() for keyword in AI_KEYWORDS):

ai_processes.append({

'pid': proc.info['pid'],

'name': proc.info['name'],

'cmdline': proc.info['cmdline']

})

except (psutil.NoSuchProcess, psutil.AccessDenied):

continue

return ai_processes

# === MAIN SCRIPT ===

def detect_irregular_eye_movement():

"""Detects increase then decrease in eye movement."""

history = []

while True:

value = get_eye_movement_value()

history.append(value)

if len(history) > 5:

history.pop(0)

if len(history) == 5 and history[0] < history[1] < history[2] and history[2] > history[3] > history[4]:

return {

'timestamp': datetime.now().isoformat(),

'eye_movement_values': history

}

def save_log(log):

"""Save findings locally, visible only to the user."""

with open(DATA_FILE, 'w') as f:

json.dump(log, f, indent=4)

def main():

startup_time = time.time()

print("VR headset startup time recorded.")

print("Monitoring eye movement for irregular patterns…")

detection = detect_irregular_eye_movement()

detection_time = time.time()

ai_status = get_active_ai_processes()

log = {

'startup_time': datetime.fromtimestamp(startup_time).isoformat(),

'irregular_eye_movement_detected_at': detection['timestamp'],

'elapsed_time_sec': round(detection_time - startup_time, 2),

'eye_movement_pattern': detection['eye_movement_values'],

'active_ai_processes': ai_status

}

save_log(log)

print("Irregular eye movement detected. Log saved locally.")

if __name__ == '__main__':

main()

The secure logging functionality ensures only local visibility by storing results in the user’s home directory.

Additionally, the modular design will separate AI detection, logging, and eye-tracking logic.

Finally, the mock inputs in this sample script include placeholders for eye-tracking and AI status detection, which should be replaced with actual APIs in a real VR setup.

Meanwhile, as the OpenVR eye-tracking extension is most configurable for the C++ programming language, the sample code below illustrates the biometric component in C++.

Objective: Monitor the time elapsed between VR headset startup and the onset of irregular eye movements (characterized by an increase followed by a decrease in eye motion), and log the AI software’s activity status at that moment.

  1. OpenXR initialization:

    • Enable the XR_EXT_eye_gaze_interaction extension.

    • Create an OpenXR instance and session.

    • Establish the necessary reference spaces.developer.varjo.comdeveloper-docs.magicleap.cloud

  2. Eye-tracking setup:

    • Verify the availability of eye-tracking support.

    • Initialize eye-tracking by creating an eye-tracker handle.

    • Retrieve eye gaze data using xrLocateEyeGazeEXT. community.khronos.org + 2developer.varjo.com + 2developer.android.com + 2github.com + 6developer.android.com + 6community.khronos.org + 6

  3. Eye movement monitoring:

    • Continuously poll eye-gaze data at a suitable frequency (e.g., 60 Hz).

    • Calculate the magnitude of gaze direction vectors to quantify eye motion.

    • Detect patterns where the eye motion magnitude increases and then decreases, indicating irregular movement.

  4. AI activity logging:

    • Upon detecting irregular eye movements, log the current status of the AI software within the VR application.

  5. Data logging:

    • Record the startup time, the time of irregular eye movement detection, and the AI activity status to a local file accessible only to the user.

Code sample (pre-error handling):

#include <openxr/openxr.h>

#include <openxr/openxr_platform.h>

#include <chrono>

#include <fstream>

#include <vector>

// Function to calculate the magnitude of a 3D vector

float CalculateMagnitude(XrVector3f vector) {

return sqrt(vector.x * vector.x + vector.y * vector.y + vector.z * vector.z);

}

// Function to detect irregular eye movement

bool DetectIrregularMovement(const std::vector<float>& magnitudes) {

if (magnitudes.size() < 5) return false;

return (magnitudes[magnitudes.size() - 5] < magnitudes[magnitudes.size() - 4] &&

magnitudes[magnitudes.size() - 4] < magnitudes[magnitudes.size() - 3] &&

magnitudes[magnitudes.size() - 3] > magnitudes[magnitudes.size() - 2] &&

magnitudes[magnitudes.size() - 2] > magnitudes[magnitudes.size() - 1]);

}

int main() {

// Initialize OpenXR instance and session with eye gaze interaction extension enabled

// [Initialization code here]

// Record startup time

auto startup_time = std::chrono::steady_clock::now();

std::vector<float> eye_motion_magnitudes;

bool irregular_movement_detected = false;

while (!irregular_movement_detected) {

// Poll eye gaze data

XrEyeGazeSampleTimeEXT eyeGazeSample;

// [Code to retrieve eye gaze data and populate eyeGazeSample]

// Calculate magnitude of gaze direction vector

float magnitude = CalculateMagnitude(eyeGazeSample.gazeDirection);

eye_motion_magnitudes.push_back(magnitude);

// Check for irregular movement pattern

if (DetectIrregularMovement(eye_motion_magnitudes)) {

irregular_movement_detected = true;

auto detection_time = std::chrono::steady_clock::now();

auto elapsed_time = std::chrono::duration_cast<std::chrono::seconds>(detection_time - startup_time).count();

// Log AI activity status

// [Code to retrieve AI activity status]

// Save findings to a local file

std::ofstream log_file("eye_movement_log.txt");

log_file << "Startup Time: " << /* startup_time */ "\n";

log_file << "Irregular Movement Detected At: " << /* detection_time */ "\n";

log_file << "Elapsed Time (s): " << elapsed_time << "\n";

log_file << "AI Activity Status: " << /* AI status */ "\n";

log_file.close();

}

// Sleep or wait for the next polling interval

std::this_thread::sleep_for(std::chrono::milliseconds(16)); // Approx. 60 Hz

}

// Cleanup and shutdown

// [Cleanup code here]

return 0;

}

Python code for AR user safety algorithm, focusing on the time between immersion initiation and irregular biometric activity (heart rate)

import time

import os

import json

import psutil

from datetime import datetime

# === CONFIGURATION ===

DATA_FILE = os.path.expanduser("~/pokemon_go_hr_log.json")

AI_KEYWORDS = ['ai', 'neural', 'ml', 'tensorflow', 'torch']

HEART_RATE_THRESHOLD = 100 # Customize based on resting HR

SAMPLING_INTERVAL = 5 # Seconds

# === MOCK FUNCTION (replace with smartwatch API integration) ===

def get_heart_rate():

"""

Fetch the current heart rate from a smartwatch.

Replace this with actual API calls.

"""

import random

return random.randint(60, 130) # Simulated HR for testing

def is_pokemon_go_running():

for proc in psutil.process_iter(['name']):

try:

if "pokemon" in proc.info['name'].lower():

return True

except (psutil.NoSuchProcess, psutil.AccessDenied):

continue

return False

def get_ai_processes():

ai_procs = []

for proc in psutil.process_iter(['pid', 'name', 'cmdline']):

try:

if any(keyword in ' '.join(proc.info['cmdline']).lower() for keyword in AI_KEYWORDS):

ai_procs.append({

'pid': proc.info['pid'],

'name': proc.info['name'],

'cmdline': proc.info['cmdline']

})

except (psutil.NoSuchProcess, psutil.AccessDenied):

continue

return ai_procs

def save_log(log):

with open(DATA_FILE, 'w') as f:

json.dump(log, f, indent=4)

def main():

print("Waiting for Pokémon GO to start…")

while not is_pokemon_go_running():

time.sleep(2)

print("Pokémon GO launched. Monitoring heart rate via smartwatch…")

app_start_time = time.time()

while True:

hr = get_heart_rate()

print(f"Heart Rate: {hr} BPM")

if hr >= HEART_RATE_THRESHOLD:

spike_time = time.time()

ai_status = get_ai_processes()

elapsed = round(spike_time - app_start_time, 2)

log = {

'pokemon_go_start_time': datetime.fromtimestamp(app_start_time).isoformat(),

'heart_rate_spike_time': datetime.fromtimestamp(spike_time).isoformat(),

'elapsed_time_sec': elapsed,

'heart_rate': hr,

'ai_processes': ai_status

}

save_log(log)

print("Heart rate spike detected. Log saved.")

break

time.sleep(SAMPLING_INTERVAL)

if __name__ == '__main__':

main()

The above code assumes an AR mobile application (in this case, Pokemon GO) integration with a smart sensor, such as a Fitbit. The code below shows the integration and configuration process for pairing Fitbit with Pokemon GO.

pip install fitbit requests cherrypy

import time

import os

import json

import psutil

import fitbit

import cherrypy

from datetime import datetime

from fitbit.api import FitbitOauth2Client

# === CONFIGURATION ===

DATA_FILE = os.path.expanduser("~/pokemon_go_hr_log.json")

AI_KEYWORDS = ['ai', 'neural', 'ml', 'tensorflow', 'torch']

HEART_RATE_THRESHOLD = 100

SAMPLING_INTERVAL = 30 # Fitbit intraday API limits to 1/min

CLIENT_ID = 'YOUR_CLIENT_ID'

CLIENT_SECRET = 'YOUR_CLIENT_SECRET'

# === OAuth2 Token Storage ===

TOKENS_FILE = 'fitbit_tokens.json'

def save_tokens(token_dict):

with open(TOKENS_FILE, 'w') as f:

json.dump(token_dict, f)

def load_tokens():

if os.path.exists(TOKENS_FILE):

with open(TOKENS_FILE, 'r') as f:

return json.load(f)

return None

def authorize_fitbit():

server = cherrypy._cpserver.Server()

server.socket_port = 8080

server.socket_host = '0.0.0.0'

class OAuth2CallbackServer:

@cherrypy.expose

def index(self, code):

token = client.fetch_access_token(code)

save_tokens(token)

cherrypy.engine.exit()

tokens = load_tokens()

if tokens:

return fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, access_token=tokens['access_token'],

refresh_token=tokens['refresh_token'], refresh_cb=save_tokens)

client = FitbitOauth2Client(CLIENT_ID, CLIENT_SECRET)

url, _ = client.authorize_token_url(redirect_uri='http://localhost:8080')

print("Go to the following URL and authorize the app:\n", url)

cherrypy.quickstart(OAuth2CallbackServer())

tokens = load_tokens()

return fitbit.Fitbit(CLIENT_ID, CLIENT_SECRET, access_token=tokens['access_token'],

refresh_token=tokens['refresh_token'], refresh_cb=save_tokens)

def is_pokemon_go_running():

for proc in psutil.process_iter(['name']):

try:

if "pokemon" in proc.info['name'].lower():

return True

except (psutil.NoSuchProcess, psutil.AccessDenied):

continue

return False

def get_ai_processes():

ai_procs = []

for proc in psutil.process_iter(['pid', 'name', 'cmdline']):

try:

if any(keyword in ' '.join(proc.info['cmdline']).lower() for keyword in AI_KEYWORDS):

ai_procs.append({

'pid': proc.info['pid'],

'name': proc.info['name'],

'cmdline': proc.info['cmdline']

})

except (psutil.NoSuchProcess, psutil.AccessDenied):

continue

return ai_procs

def save_log(log):

with open(DATA_FILE, 'w') as f:

json.dump(log, f, indent=4)

def main():

print("Authorizing with Fitbit…")

fb = authorize_fitbit()

print("Waiting for Pokémon GO to start…")

while not is_pokemon_go_running():

time.sleep(2)

print("Pokémon GO launched. Monitoring heart rate via Fitbit…")

app_start_time = time.time()

while True:

now = datetime.now()

date_str = now.strftime('%Y-%m-%d')

time_str = now.strftime('%H:%M:%S')

hr_data = fb.intraday_time_series('activities/heart', base_date=date_str, detail_level='1sec')

try:

hr_points = hr_data['activities-heart-intraday']['dataset']

if hr_points:

latest_hr = hr_points[-1]['value']

print(f"Heart rate: {latest_hr}")

if latest_hr >= HEART_RATE_THRESHOLD:

spike_time = time.time()

ai_status = get_ai_processes()

elapsed = round(spike_time - app_start_time, 2)

log = {

'pokemon_go_start_time': datetime.fromtimestamp(app_start_time).isoformat(),

'heart_rate_spike_time': datetime.fromtimestamp(spike_time).isoformat(),

'elapsed_time_sec': elapsed,

'heart_rate': latest_hr,

'ai_processes': ai_status

}

save_log(log)

print("Heart rate spike detected. Log saved.")

break

except Exception as e:

print("Error retrieving heart rate:", e)

time.sleep(SAMPLING_INTERVAL)

if __name__ == '__main__':

main()

References

  1. 1. Diaconu I. Wearable patient monitoring and metaverse-enabled healthcare systems, immersive medical simulation and remote care technologies, and deep learning disease prediction and diagnosis algorithms for Artificial Intelligence-powered individualized. American Journal of Medical Research. 2024;11(1):3954. https://www.ceeol.com/search/article-detail?id=1335015
  2. 2. Alshraideh M, Alkayed Y, Alshraideh A, AlTrabsheh Y, Alshraideh B, Alshraideh H, Alfayoumi B, Alshraideh N. Advancing Vertigo diagnosis with large language models: A multimodal, AI-driven approach to etiology differentiation. Journal of Integrated Science and Technology. 2025;13(4):1079. DOI: 10.62110/sciencein.jist.2025.v13.1079.
  3. 3. Sabry F, Eltaras T, Labda W, Alzoubi K, Malluhi Q, Wu Y. Machine learning for healthcare wearable devices: The big picture. Journal of Healthcare Engineering. 2022; 2022: 125. 4653923. DOI: 10.1155/2022/4653923.
  4. 4. Woll S, Birkenmaier D, Biri G, Nissen R, Lutz L, Schroth M, Ebner-Priemer UW, Giurgiu M. Applying AI in the context of the association between device-based assessment of physical activity and mental health: Systematic review. JMIR mHealth and uHealth. 2025;13:e59660. DOI: 10.2196/59660.
  5. 5. Sivakumar V, et al. Addressing privacy concerns with wearable health monitoring technology Wiley interdisciplinary reviews. data mining and knowledge Discovery/Wiley Interdisciplinary reviews. Data Mining and Knowledge Discovery. 2024;14(3). DOI: 10.1002/widm.1535
  6. 6. Katuska J. Wearing down HIPAA: How wearable technologies Erode privacy protections. The Journal of Corporation Law. 2021;44: University of Iowa School of Law. jcl.law.uiowa.edu/sites/jcl.law.uiowa.edu/files/2021-08/Katuska_Final_Web.pdf
  7. 7. Preston R. Stifling innovation: How Global data protection regulation trends inhibit the growth of healthcare research and start-ups. Emory Law Scholarly Commons. 2023;371.scholarlycommons.law.emory.edu/eilr/vol37/iss1/4
  8. 8. Balasubramaniam S, et al. AI based advancements in biometrics and its applications. 1st edn. 2024. CRC Press.
  9. 9. Zhou S, Gromala D, Wang L. Ethical challenges of virtual reality technology interventions for the vulnerabilities of patients with Chronic Pain: Exploration of technician responsibility. Journal of Medical Internet Research. 2023;25:e49237. DOI: 10.2196/49237.
  10. 10. Pasa B, Bernes A, Gaggioli A, Tuccari E, Zollo F, Vulpiani G, Pignolo L, Scala A, Cerasa A. LawVerse: The legal framework for clinical metaverse content. Journal of Medical Extended Reality. 2025;2(1):1319. DOI: 10.1089/jmxr.2024.0028.
  11. 11. Nicholson A, Udofa K, Collins A. Trespass to the ‘person’ in the metaverse. International Review of Law, Computers & Technology. 2025;122. DOI: 10.1080/13600869.2025.2479891
  12. 12. Mrčela M, Vuletić I.Navigating criminal liability in an era of AI-assisted medicine. Medicine, Law & Society. 2025;18(1). DOI: 10.18690/mls.18.1.93-108.2025.
  13. 13. Wei W, Liu L. Trustworthy distributed AI systems: Robustness, privacy, and governance. ACM Computing Surveys. 2025;57(6):143. 42. DOI: 10.1145/3645102

Written By

Sarah Katz

Submitted: 04 June 2025 Reviewed: 10 June 2025 Published: 11 November 2025