AI-Driven IoT Healthcare System for Real-Time ECG Analysis and Comprehensive Patient Monitoring

This study explores the integration of deep learning and Internet of Things (IoT) technologies to enhance healthcare delivery, with a primary focus on improving electrocardiogram (ECG) analysis and real-time patient monitoring systems. The research presents the development of two innovative deep learning models based on the MIT-BIH dataset, enabling highly accurate ECG analysis. One model is trained for precise R-R peak detection, while the other performs effective classification of ECG signals into five distinct disease categories. The study also introduces an integrated healthcare system that seamlessly captures patients' real-time physiological data, including ECG, SpO 2 , and temperature, using an ESP32 microcontroller and Raspberry Pi. An IoT infrastructure with Node-RED IBM Platform and Message Queuing Telemetry Transport (MQTT) securely transmits the ECG data to the advanced analysis algorithms. The user interface displays patients' vital signs, including heart rate, oxygen saturation, and temperature, providing healthcare professionals with comprehensive real-time insights. By integrating the deep learning models, which achieve approximately 99% accuracy, alongside robust sensor technology and an IoT architecture, this system aims to transform healthcare by enabling highly precise ECG analysis and remote patient monitoring. The findings of this study underscore the potential of the synergistic convergence of deep learning, sensor technology, and IoT to advance healthcare delivery and improve patient outcomes.


Introduction
Cardiovascular diseases remain a leading cause of mortality worldwide, emphasizing the critical need for accurate and efficient electrocardiogram (ECG) interpretation [1].Traditional manual ECG analysis, while valuable, is often hindered by inefficiencies, laborintensive processes, and susceptibility to human error.To address these limitations and enhance patient care, there is a growing interest in leveraging advanced technologies [2], [3].
For training our deep learning models, we utilize the comprehensive MIT-BIH dataset [20].Our IoT infrastructure integrates cutting-edge hardware, including ESP32 microcontrollers, Raspberry Pi devices, and various sensors.We also employ advanced platform and software protocols, specifically Node-RED and MQTT, to support this infrastructure.
By addressing critical challenges in ECG interpretation and patient monitoring, this study aims to significantly impact healthcare delivery.The proposed system has the potential to enhance diagnostic accuracy, enable early detection of cardiac abnormalities, and facilitate personalized and timely interventions [21], [22], [20], [23].
The remainder of the paper is organized as follows.Section 2 describes the system setup and presents the research in general.Section 3 details the methods and materials used in this study, including the creation of the deep learning models, dataset analysis, model training, and the development of the real-time IoT system.Section 4 concludes the study with a summary of the key findings.

System Architecture Setup
The proposed healthcare monitoring system presents an innovative platform that seamlessly integrates multiple components to provide comprehensive patient care.Figure 1 illustrates the system's architecture, which encompasses data acquisition, processing, analysis, and visualization.

Deep learning models
Our system is built around two advanced deep learning models: 1. ECG Peak Detection Model: This model accurately identifies peak values within ECG signals, crucial for evaluating cardiac health and detecting irregularities.

ECG Classification Model: This model categorizes ECG signals into five distinct disease categories,
aiding in the identification of potential cardiac issues.
Online First Both models are trained on extensive datasets and saved in TensorFlow.js format and implemented for seamless integration into the Node-RED environment, enabling real-time analysis.

Data acquisition
The system utilizes a multi-sensor approach to collect comprehensive patient health data: -ECG Sensor (AD8232): Connected to an ESP32 microcontroller for real-time ECG data acquisition.
-SpO2 Sensor (MAX30100A) and temperature sensor (DHT11): Interfaced with a Raspberry Pi to continuously monitor oxygen saturation levels and body temperature.

Data transmission and processing
All collected data is transmitted to a cloud server using the MQTT protocol, ensuring efficient and reliable data transfer.The data is then processed within Node-RED flows for analysis and visualization.This approach allows for scalable and flexible data handling while maintaining the integrity of sensitive health information throughout the transmission process.

Data analysis and visualization
Within the Node-RED environment, the ECG data undergoes two parallel processes: 1. Peak Detection: The first node function applies the peak detection model to identify ECG signal peaks, essential for accurate heart rate calculation.
2. Disease Classification: The second node function utilizes the classification model to categorize ECG data into specific disease classes, crucial for diagnostic purposes.
The results from peak detection, disease classification, SpO2, and temperature data are aggregated to compute vital health metrics, including oxygen saturation, temperature, and heart rate.The system also presents disease classification information alongside the ECG signal with identified peaks.

User interface and remote access
Patient health information and diagnostics are displayed through: 1.An on-site Human Machine Interface (HMI) or LCD display connected to the Raspberry Pi, allowing local medical practitioners to monitor patient health in real-time.
Online First 2. Secure remote access from various devices (computers, mobile phones, or tablets), enabling off-site medical professionals to monitor patient health by logging in through authenticated accounts.
This dual-access approach ensures timely medical intervention, when necessary, while also maintaining the confidentiality and integrity of patient data.

System integration and workflow
The entire system operates as a cohesive unit, with data flowing seamlessly from sensors to analysis models and finally to visualization interfaces.This integrated approach allows for: -Real-time monitoring of critical health parameters -Quick and accurate disease diagnosis -Efficient communication between local and remote healthcare providers By leveraging advanced IoT protocols and cloud computing, our system ensures that vital health data is transmitted, processed, and accessed securely and efficiently.While the focus of this research is not on specific data security mechanisms, the architecture inherently supports the implementation of robust security measures to protect sensitive patient information throughout the data lifecycle.
This comprehensive system setup forms the foundation for our subsequent experimental analysis and evaluation, demonstrating the potential of integrated IoT and AI technologies in revolutionizing healthcare monitoring and diagnosis.

Materials and Methods
This section describes the three layers of the proposed system that have been proposed and adopted:  AI deep learning models. System hardware and software implementation: hosting data and the controller. IoT: Transferring data between the different parts of the system by means of WiFi, MQTT, cloud server, and Node-RED.

ECG signal
ECG interpretation stands at the heart of cardiovascular diagnostics, providing a detailed snapshot of the heart's electrical activity.The distinctive wave forms captured on the ECG graph, namely the P, Q, R, S, and T waves, illustrated in Figure 2, hold pivotal information about the cardiac cycle.The P-wave represents atrial depolarization, signifying the contraction of the atria as they pump blood into the ventricles.Following this, the QRS complex reflects ventricular depolarization, marking the initiation of the main pumping chambers' contraction.The ensuing S-wave denotes the completion of ventricular depolarization.Subsequently, the T-wave represents ventricular depolarization, illustrating the recovery phase as the heart prepares for the next cycle [20], [24].
As explained in Figure 3, the intricate analysis of these waves, their amplitudes, durations, and sequential patterns, enables clinicians to discern abnormalities, identify arrhythmias, and assess overall cardiac health.In the pursuit of more efficient and accurate ECG analysis, this study integrates new techniques, including deep learning, to augment the interpretation process, addressing the inefficiencies and challenges inherent in traditional manual approaches.

Deep learning model for ECG peak detection
This part focuses on a model tailored to pinpoint and localize the peak amplitude values within an ECG signal waveform.The core goal of this model is to precisely identify the maximum amplitude points or peak values found in the ECG wave, as these peaks carry crucial diagnostic importance for evaluating cardiac performance and spotting potential irregularities.

MIT-BIH arrhythmia database analysis
The foundation of any successful machine learning endeavor lies in the quality and appropriateness of the dataset.The MIT-BIH Arrhythmia database serves as the cornerstone of our model development, offering a rich and diverse range of ECG recordings, each meticulously annotated to highlight various cardiac events.This dataset is pivotal in our pursuit to develop a model capable of peak detection in ECG signals, enabling the analysis of critical parameters such as heart rate, QRS complexes, and more.
To better understand the dataset, Figure 4 illustrates the distribution of peak counts per sample, providing insight into the variability and range of ECG signal characteristics captured within the database.Additionally, Figure 5 presents a visualization of ECG signals with detected peaks for both the training and test sets, showcasing how the model interprets and processes the raw data.These visual analyses underscore the dataset's breadth and depth, offering a solid foundation for training a model that can aid in the automatic detection of arrhythmias.
Where  is the output,  are the learnable filters, * denotes the convolution operation,  is the bias term, and  is an activation function typically the Rectified Linear Unit (ReLU) function defined by (2).
3. Max Pooling Layers: These layers downsample the input, focusing on retaining the most essential information while reducing computational complexity.For a max pooling operation with a window size of k we can write the formula given in (3).
Where  is the pooled output and  is the input from the previous layer.
4. Upsampling Layers: Following the convolutional layers, the model employs upsampling layers to reconstruct the original signal dimensions while preserving learned features.For nearest neighbor upsampling by a factor of s given by (4).
Where  is the upsampled output and  is the input from the previous layer.

Convolutional and Sigmoid Layers:
The model concludes with convolutional layers followed by a sigmoid activation function.For the final layer: Where  is the final output, W and  are respectively the weights and bias of the final convolutional layer, and σ is the sigmoid function.
The model is trained to minimize the Mean Squar Error given by (6). Where:   is the number of data points.
  represents the desired values.
  represents the predicted values given by the model.
This architecture allows the model to learn hierarchical features from the ECG signal, compress the information through pooling, reconstruct the signal's dimensions, and output a probability map of peak locations.The use of convolutional layers enables the model to capture local patterns in the ECG signal, while the upsampling layers allow for precise localization of peaks in the original signal domain.
This arrangement allows the model to map the input to the desired output -in this case, peak predictions.The model is trained using the MIT-BIH arrhythmia dataset [25], [26], [27].We divide the dataset into training and testing sets, ensuring robust evaluation.During training, the model learns to identify patterns indicative of peaks in ECG segments.The training process aims to minimize the binary cross-entropy loss between predicted and actual peaks.The choice of this architecture is supported by its success in various time series analysis tasks and its ability to learn hierarchical representations efficiently [21], [28].Additionally, CNNs have demonstrated effectiveness in capturing local dependencies and invariant features, making them wellsuited for peak detection in ECG signals [29][26].This architecture facilitates automatic feature extraction and abstraction, crucial for peak detection in complex ECG waveforms.Figure 6 illustrates the model architecture.

Model training and result
The core of our system's capabilities lies in the intricate process of model training and the subsequent results it yields.To train the model effectively, we employed the MIT-BIH arrhythmia dataset, a wellestablished resource in the field of electrocardiography.Ensuring the robustness of our model, we thoughtfully divided the dataset into training and testing sets.The purpose of this division is to evaluate the model's performance under conditions that simulate real-world scenarios.During the training phase, the model diligently learns to recognize patterns within ECG segments that are indicative of peaks.The objective here is to minimize the binary cross-entropy loss between the model's predicted peaks and the actual peaks present in the ECG data.The end result of this process is a model that possesses the remarkable ability to accurately detect peaks in ECG signals.This capacity is a pivotal step, as it unlocks a multitude of applications within the healthcare domain.One of the immediate applications stemming from our trained peak detection model is heart rate calculation.Precisely identifying the R peaks, which correspond to the heart's contractions, our model enables real-time heart rate calculation.The significance of this functionality is paramount for evaluating a patient's cardiac health, monitoring fluctuations in heart rate, and gaining insights into physiological responses.The model's exceptional performance is evidenced by its impressive accuracy metrics.Upon rigorous evaluation, our peak detection model demonstrates an accuracy of approximately 99.93%, with a validation score of 99.87%.This level of accuracy is a testament to the model's prowess in discerning intricate features within ECG signals.It not only captures the prominent peaks but also detects even the faintest indications of peaks, ensuring a comprehensive analysis as showed in Figure 7. Accuracy is a common evaluation metric in deep learning method, it is calculated as a ratio of correctly predicted instances and its formula is: Where:  TP = True Positives (correct predicted positive cases)  TN = True Negatives (correct predicted negatives cases)  FP = False Positives (incorrectly predicted positive cases)  FN = False Negatives (incorrectly predicted negatives cases).
This remarkable accuracy is a testament to the model's ability to discern intricate features within the ECG signal, capturing even the faintest indications of peaks.It is important to note that our model's accuracy is not solely a result of over-fitting to the training dataset.Rigorous Online First efforts have been made to ensure the model's generalization and robustness.Upon evaluation on novel, unlearned ECG data, the model demonstrates consistent high performance, validating its ability to adapt to variations across different ECG recordings and generalize its peak detection capabilities effectively.One immediate application of accurate peak detection is heart rate calculation.By precisely pinpointing the R peaks, which represent the heart's contractions, the model enables realtime heart rate computation.This capability is crucial for assessing a patient's cardiac condition, monitoring fluctuations in heart rate, and gaining insights into physiological responses.

Deep learning model for ECG classification
Following the high accuracy of our peak detection model, we embark on a new phase of our research: the development of a sophisticated classification model.This expansion in scope enables us to offer a more comprehensive analysis of cardiac health.

Classification database
The dataset employed in this study serves as a valuable resource for the development of deep learning models geared towards the classification of cardiac heartbeat signals.It amalgamates data originating from two well established sources, namely the MIT-BIH arrhythmia dataset [25] and the PTB Diagnostic ECG Database [27], [30].This amalgamation results in a dataset that presents a diverse and comprehensive collection of ECG signals, which are essential for in-depth analysis.With a total of 87,554 samples comprising the training set and 21,892 samples in the test set, this dataset offers a substantial volume of data suitable for both the training and evaluation of deep learning models.Within this dataset, each ECG signal corresponds to a distinct heartbeat pattern, encompassing a wide spectrum of scenarios.It encompasses not only normal heartbeats but also those affected by a variety of arrhythmias and myocardial infarctions.This diversity renders the dataset suitable for a range of tasks, including but not limited to arrhythmia classification and anomaly detection.Notably, the preprocessing and segmentation steps applied to the signals ensure that individual heartbeats are meticulously isolated and prepared for analysis.This preprocessing, in turn, streamlines the development of precise and effective classification models.Researchers and data scientists can harness this dataset to advance the field of cardiac signal analysis, with the ultimate goal of enhancing the diagnosis and monitoring of heart-related conditions.

Data loading
The initial step in the analysis entails the loading of two CSV files, denoted as mitbih-train.csvand mitbihtest.csvinto pandas Data Frames.These CSV files are repositories of ECG data, where each row corresponds to a distinct heartbeat signal.

Data exploration
Following data loading, the code conducts an exploratory analysis to ascertain the dimensions of the training and test datasets.It is revealed that the training set encompasses 87,554 samples, each featuring 188 distinct features.Similarly, the test set contains 21,892 samples, each retaining the same number of features.

Class distribution
To gain insights into the distribution of heartbeat classes within both the training and test datasets, the code quantifies the occurrence of each class, denoted as 0.0, 1.0, 2.0, 3.0, and 4.0.This enumeration is based on the values found in the last column (column 187) of both datasets.Understanding the class distribution is crucial for comprehending the balance, or potential imbalance, present in the dataset.

Data analysis
To enhance the interpretation of class distribution, the code generates a pie chart as a visual representation of the distribution of heartbeat classes within the training dataset.This graphical depiction provides a succinct overview of the proportion of each class, thereby simplifying the identification of any class imbalances as shown in Figure 8.The t-distributed stochastic neighbor embedding (t-SNE) and Principal component analysis (PCA) plots reveal that the five ECG classes in your dataset have significant overlap [31], [32], indicating that the features used don't fully separate the classes in 2D space.While some distinct clusters are visible, particularly for the Normal Beats, the overall overlap suggests that simple models might struggle with classification.This overlap highlights the need for more advanced feature engineering or complex models to improve class separability and achieve better classification performance as illustrated by Figure 9.

Resampling dataset
To rectify class imbalance, the code undertakes a resampling procedure.This process involves the creation of balanced subsets for each class, specifically classes 0, 1, 2, 3, and 4. The balance is achieved through either upsampling or down-sampling.For instance, the majority class (class 0) is downsized to contain 20,000 samples, while the minority classes (classes 1, 2, 3, and 4) are expanded through up-sampling to match this new size.This meticulous resampling guarantees a more equitable distribution of classes, a crucial factor for the subsequent training of machine learning models.Postresampling, the code selects a random sample from each class within the training dataset.

Online First
This selection is performed utilizing the group by function, resulting in the creation of a new data frame labeled "classes".These randomly selected samples, as shown in Figure 11, can serve as valuable resources for further analysis, visualization, and, notably, the acquisition of insights into the unique characteristics of each heartbeat.The dataset, drawn from the Kaggle repository [26], provides researchers and data scientists with an indispensable resource for advancing the field of cardiac signal analysis and enhancing the diagnosis and monitoring of heart related conditions.LSTM layers process the sequential data, capturing temporal dependencies.Dropout is employed to prevent over-fitting.Combining CNN and RNN: The outputs of the CNN and RNN branches are concatenated, resulting in a combined feature vector that captures both spatial and temporal information.Dense Layers and Output: This concatenated feature vector is passed through dense layers with batch normalization, extracting high-level features.A softmax activation function is applied to the final layer to generate class probabilities for each input.Equation ( 1), ( 2) and ( 3) are used respectively for convolution, ReLu activation function and Pooling layer respectively.In addition, relations ( 8) and ( 9) correspond to the flatten and dense layer respectively.
Where  is the flatten vector. Where:   is the probability of class i.  C is the number of classes.
  is the i th element of the dense layer output D.

Model training and result discussion
In the intricate process of model training and evaluation, our focus was on the development and assessment of a robust classification model.Several key components played pivotal roles in this phase.
1) Optimization and loss function: The model was compiled using the Adam optimizer, a popular choice for optimizing neural networks.This optimizer adapts the learning rate during training, which enhances the model's ability to converge to optimal solutions.Additionally, we employed the categorical cross-entropy loss function.This particular choice is well-suited for multi-class classification problems, as it efficiently quantifies the disparity between predicted and actual class labels.
2) Learning rate adaptation: The model's training process benefits from a learning rate scheduler.This scheduler dynamically adjusts the learning rate as training progresses.The adaptation of the learning rate is crucial for ensuring that the model efficiently converges to an optimal solution while avoiding overshooting or getting stuck in local minima.
3) Training data: The model is trained on the provided training data along with their corresponding class labels over a specified number of epochs.This data forms the foundation upon which the model refines its internal parameters and learns to make accurate predictions.
Figure 13 illustrates the convergence of the loss function towards zero and the accuracy towards one, which is as a performant outcome.One notable aspect of the model's evaluation is the utilization of a confusion matrix, which is an insightful tool for assessing the model's classification accuracy for different classes.The confusion matrix for select classes is depicted in Figure 14, offering a more detailed examination of the model's performance.

4) Class-Specific confusion matrices
In Figure 14, we delve into class-specific confusion matrices.These matrices are indispensable for a more granular analysis of the model's performance concerning individual classes.Each subfigure in this set showcases the model's effectiveness in distinguishing the five classes' data, shedding light on its classification accuracy within each category.By analyzing these results, we can gain valuable insights into the strengths and potential weaknesses of the classification model.This comprehensive evaluation equips us with the knowledge required to further refine and optimize our model for more accurate and reliable multi-class classification, which is vital in healthcare applications and beyond.
A confusion matrix is a matrix (n × n) used to describe the performance of a classification model on a set of test data for which the true values are known; it helps to understand the types of errors the model is making.
Where n is the number of classes, each cell (i, j) in the matrix represents the number of instances of class i that were predicted as j.

Embedded health monitoring system setup
In the realm of IoT, the rapid and efficient processing of data is paramount, especially in the context of real-time health monitoring.This chapter presents a detailed account of the comprehensive implementation of a health monitoring platform, harnessing the capabilities of Node-RED and MQTT protocols to optimize ECG data analysis speed and enhance overall system performance.Sensors and Micro-controller integration at the core of our advanced health monitoring system lies the seamless integration of state of-the-art sensors and microcontrollers.Leveraging the capabilities of sensors such as the ECG sensor AD8232, the SpO2 sensor MAX30100A, and the temperature sensor DHT11, we ensure a thorough data collection process for a holistic assessment of patient health.The ECG sensor, seamlessly interfaced with the ESP32 micro-controller, delivers real-time ECG data, providing valuable insights into the patient's cardiac health.Simultaneously, the SpO2 and temperature sensors, connected to the Raspberry Pi, enable continuous monitoring of oxygen saturation and body temperature.This real-time sensor data forms the cornerstone of our healthcare monitoring system, facilitating precise diagnoses and timely interventions.The microcontrollers, acting as central hubs, oversee data collection and transmission, ensuring that critical health information is readily available for analysis and display.Moreover, to enhance portability and flexibility, our system is designed to operate on battery power.The patient data collected from these micro-controllers is transmitted to a cloud server, where it is stored for future use and seamlessly integrated into Node-RED flows through the MQTT protocol.By implementing this embedded system, showed in Figure 15, with battery support, we have created a robust infrastructure for health monitoring that not only enables accurate assessments and proactive healthcare interventions but also enhances the system's portability.The combination of cutting-edge sensors, efficient micro-controllers, cloud-based data storage, and battery support sets the stage for a reliable, scalable, and mobile health monitoring platform.

Real-time ECG analysis
To create a seamless integration of the ECG peak detection model with real time data streaming, an IoT architecture is implemented using Node-RED and MQTT protocols.This architecture allows for the continuous flow of ECG data from the sensor to the model, enabling real-time analysis and visualization.The Node-RED platform provides a visual programming interface that simplifies the creation of complex IoT workflows.MQTT, a lightweight messaging protocol, is used for efficient communication between devices and the cloud server.

Node-RED integration process
The Node-RED workflow consists of three main components: data acquisition, model integration, and visualization.

Data acquisition
ECG signals are collected using the AD8232 sensor and ESP32 microcontroller.The sensor detects electrical Online First signals from the heart and transmits them to the microcontroller.The data is then sent to the Node-RED flow through MQTT messages.

Models integrated into Node-Red
Our health monitoring platform seamlessly incorporates two TensorFlow models into the Node-RED environment.These models, previously trained and finetuned for ECG peak detection and ECG pattern classification, have been converted to TensorFlow.js, allowing for efficient utilization within Node-RED for real-time data analysis and visualization.The received ECG data is processed by the peak detection model, which predicts the location of peaks in the signal.

Peak detection model
The ECG data is processed by the Peak Detection Model, which has been meticulously trained to predict the precise locations of peaks within the ECG signal, providing crucial insights into cardiac activity.Additionally, this model calculates the heart rate, further enhancing the information available to healthcare professionals.

Classification model
Simultaneously, the ECG data is subjected to analysis by our classification Model, a TensorFlow-powered algorithm adept at distinguishing between normal and pathological ECG patterns.This dual-model integration empowers healthcare professionals with comprehensive insights into the patient's cardiac health, all within the Node-RED environment.the flow of this work is illustrated by Figure 16.

Node-RED Sensors integration
The integration process involves creating intuitive and interconnected flows within Node-RED, linking the ECG sensor AD8232, the SpO2 sensor MAX30100A, and the temperature sensor DHT11.Through custom Node-RED nodes and configurations, we establish a cohesive network that effortlessly processes real-time data from these sensors.The ECG sensor provides crucial information about the patient's cardiac activity, the SpO2 sensor contributes data on oxygen saturation levels, and the temperature sensors offers insights into the ambient conditions.These sensor inputs are meticulously woven into Node-RED flows, ensuring a synchronized and coherent stream of health data.Leveraging the MQTT protocol, the integrated sensor data is then efficiently transmitted to the cloud for storage and advanced analysis.The flexibility and visual simplicity of Node-RED make it a powerful tool for orchestrating sensor integration, enabling our health monitoring platform to deliver accurate and timely health insights Figure 17.

Node-RED patient alert
To enhance the user experience and enable immediate response in critical situations, our health monitoring system includes a patient-triggered alert notification flow which is depicted in Figure 18.A dedicated button is incorporated into the system, allowing the patient to initiate an alert when they sense a medical emergency or discomfort.Upon pressing the alert button, Node-RED seamlessly generates a notification, which is then promptly dispatched to the attending medical professionals.This real-time alerting system ensures that healthcare providers receive timely notifications, enabling Online First swift and decisive actions.The integration of this patientinitiated alert feature adds an extra layer of responsiveness to our health monitoring platform, emphasizing patient empowerment and facilitating rapid medical interventions when needed.

Node-RED doctor login account
In our Node-RED dashboard, we have implemented a secure and personalized doctor account system to ensure confidentiality and restricted access.Each authorized doctor is provided with unique login credentials, adding a layer of authentication to prevent unauthorized access as showing in Figure 19.

Visualization
In the visualization component of our health monitoring platform, we provide healthcare professionals with a comprehensive view of critical cardiac information in real-time.Figure 20 shows the corresponding Node-RED flow.

Real-time ECG signal
The real-time ECG signal, received from the sensor via the MQTT protocol, is displayed on the Node-RED dashboard.This continuous stream of data allows for the immediate assessment of the patient's cardiac activity, providing essential information for timely interventions.

Predicted peak markers
The locations of ECG peaks, determined by our Peak Detection Model, are superimposed onto the ECG waveform on the dashboard.These markers offer visual cues, aiding in the interpretation of the ECG signal.

Heart rate display
The heart rate, calculated in real-time based on the positions of ECG peaks, is prominently shown on the dashboard.This vital metric offers healthcare professionals immediate insights into the patient's cardiac rhythm and overall heart health.

QRS complex monitoring
Continuously monitoring the ECG signal, we extract one QRS complex at a time.After applying our Classification Model, each QRS complex is classified, providing valuable information about the specific cardiac pattern.This dynamic display of QRS complexes with their respective classifications equips healthcare providers with the ability to quickly assess the patient's cardiac condition, distinguishing between normal and pathological patterns.

SpO2 monitoring
Data from the SpO2 sensor (MAX30100A) is collected and transmitted to Node-RED, where it is integrated into the dashboard.SpO2 levels are displayed alongside other health metrics, offering a comprehensive view of the patient's well-being.

Patient temperature monitoring
The system employs a precision temperature sensor specifically designed for human patient monitoring.This Online First sensor continuously measures the patient's body temperature with remarkable accuracy.

Temperature and humidity readings
The DHT11 sensor provides temperature and humidity data, which is sent to Node-RED and displayed on the same dashboard.This additional environmental data contributes to a holistic understanding of the patient's condition, aiding in healthcare decision-making.

Patient information and alert system
Each patient is assigned a unique identification (ID) number, which is stored and associated with their vital signs and health data in the system.Alongside the patient ID, the system records the time of each data measurement, ensuring a comprehensive timeline of health events.In the event of critical conditions or abnormalities detected by the monitoring sensors, an alert LED illuminates, providing visual notification to healthcare staff for immediate attention.Additionally, a reset button is incorporated into the system.This comprehensive visualization interface within Node-RED empowers healthcare professionals with real-time insights into the patient's cardiac activity, aiding in rapid decision-making and interventions when necessary.

Node-RED dashboard
The Node-RED dashboard offers a user-friendly interface tailored for healthcare professionals, facilitating the comprehensive monitoring and analysis of patient data.Within the dashboard, healthcare practitioners can observe a multitude of vital parameters in real-time, including the representation of the heartbeat signal, average peaks, and peak detection.Furthermore, it provides visualizations of the QRS complex along with its classification, allowing for a more detailed cardiac assessment.Additionally, essential physiological metrics such as heart rate, oxygen saturation, and patient temperature are prominently displayed.Moreover, environmental factors such as room temperature and humidity are integrated into the interface to provide contextual information.Crucially, the dashboard also features patient identification, timestamp information, and LED alerts for immediate attention to critical events.Lastly, the inclusion of a reset button ensures the interface's functionality and readiness for subsequent use.This comprehensive array of options empowers healthcare practitioners to make informed decisions regarding medical interventions while ensuring seamless monitoring of patient health status.

Comprehensive healthcare system integration
A pivotal aspect of this research entails the seamless integration of cutting-edge sensor technologies and robust IoT infrastructure to construct a comprehensive healthcare system.At its core, micro-controllers act as the nerve center, orchestrating the collection and transmission of vital data from an array of sensors.Notably, the advanced AD8232 sensor captures intricate ECG data, providing invaluable insights into cardiac health.Additionally, the inclusion of SpO2 sensors allows for the continuous monitoring of oxygen saturation levels, while the RTD temperature sensor, alongside the DHT11 sensor, offers precise measurements of patient temperature and environmental factors such as room temperature and humidity.The amalgamation of these sensors serves as the foundation for acquiring comprehensive patient health data in real-time.Leveraging the efficiency of the MQTT protocol, this data is seamlessly transmitted to a secure cloud server.Subsequently, Node-RED, a powerful flow-based development tool, processes this incoming data stream and interfaces with the previously developed deep learning models for ECG analysis and classification.This integration empowers healthcare professionals with accurate and timely diagnostic insights, enhancing patient care outcomes.Furthermore, the visual representation of this processed data is facilitated through a user-friendly dashboard.Here, healthcare practitioners can seamlessly monitor and analyze crucial patient metrics, including ECG waveforms, peak markers, heart rate, SpO2 values, temperature readings, and environmental factors.The comprehensive visualization provided by the dashboard enables healthcare professionals to make informed decisions regarding medical interventions, ultimately improving patient outcomes and advancing healthcare delivery.A final visualization example is showed in Figure 21.

Experimental work
To validate our proposed system, we conducted a series of experiments using a comprehensive setup comprising both hardware and software components as presented in diagram Figure 22.
 ESP32 Microcontroller: The ESP32, showed by Figure 23 served as the primary controller for our system, handling data acquisition from various sensors.It was selected for its versatility, low power consumption, and robust wireless communication capabilities.The ESP32 efficiently managed the initial signal processing tasks, ensuring that data was preprocessed before being transmitted to the Raspberry Pi.  Raspberry Pi 4B: The Raspberry Pi 4B, illustrated by Figure 24, was utilized as the central processing hub in our experimental setup.Equipped with a Quad-core Cortex-A72 processor, it provided the necessary computational power to run deep learning models in realtime.The Raspberry Pi also facilitated data management and communication with external systems via its integrated wireless networking capabilities, including dual-band 802.11acWi-Fi and Bluetooth 5.0.As illustrated in Figure 26, the ADS1115, a 16-bit ADC, digitized the conditioned ECG signal from the AD8232 sensor at a sampling rate of 250 SPS.This highresolution digital data was subsequently transferred to the Raspberry Pi for further processing. A body temperature sensor, as depicted in Figure 27, was incorporated into the system to provide comprehensive health monitoring.The Raspberry Pi processed data from this sensor in conjunction with other vital signs for synchronized patient assessment.To enhance environmental monitoring, a DHT11 sensor, as illustrated in Figure 28, was integrated into the system.This sensor provided real-time temperature and humidity data, which can significantly impact the accuracy and reliability of health measurements.Real-time data from these different devices and sensors was continuously collected and transmitted for immediate processing by our trained deep learning models.Figure 29 presents the complete experimental setup, including the developed HMI.

The estimation time for the real time ECG monitoring
In our real-time ECG monitoring system, we employed the AD8232 ECG sensor for signal conditioning, the ADS1115 ADC converter for high-resolution digital conversion, and the Raspberry Pi 4B, equipped with a Quad-core Cortex-A72 processor and wireless connectivity, for data processing and management.The system's real-time response time was accurately measured using a "Rohde & Schwarz RTM3000" oscilloscope from Germany, providing precise timing information for each component of the process.

Online First
The oscilloscope measurements showed that the ADC conversion on the ADS1115 at 250 SPS takes approximately 4 ms per sample.Data processing, including handling and preprocessing, contributes an additional 1-10 ms, while deep learning inference on the Raspberry Pi 4B requires about 50-150 ms per batch.
The measurements from the RTM3000 oscilloscope revealed that the total response time ranges from 55 ms to 164 ms, with a typical value around 100-150 ms, depending on the model's complexity and preprocessing steps.
When considering physiological parameters identification, including ECG analysis, it's crucial to maintain a balance between response time and accuracy.For most real-time ECG monitoring applications, a response time of 150-250 ms is generally acceptable.This allows for timely detection of critical events while ensuring accurate signal processing and analysis.However, for applications requiring the detection of very rapid changes in cardiac activity, such as certain arrhythmias, aiming for a response time closer to 100 ms or less may be beneficial.It's important to note that reducing response time should not come at the cost of sacrificing the accuracy and reliability of the physiological parameter identification algorithms.

Comparison with our result and related work
The Table 1 illustrate the most advantages and drawbacks between our paper and important related works.

Conclusion
This study has successfully achieved its primary objectives of developing advanced deep learning models for ECG analysis, creating an integrated IoT-based healthcare system, and evaluating its potential clinical impact.The research presents a significant advancement in the field of AI-driven healthcare monitoring, particularly in the domain of real-time ECG analysis and comprehensive patient monitoring.The proposed deep learning models demonstrated exceptional accuracy in R-R peak detection and disease classification, achieving approximately 99% accuracy.This performance surpasses many existing approaches in the field, showcasing the potential of AI in enhancing ECG interpretation.The developed IoT system effectively acquired and analyzed multiple physiological parameters in real-time, including ECG, SpO2, and temperature.This multi-sensor approach provides a more holistic view of patient health, enabling more comprehensive monitoring and potentially more accurate diagnoses.The system's ability to process ECG data in real-time, with a response time ranging from 55 ms to 164 ms, demonstrates its potential for immediate clinical application.This speed is crucial for timely detection of cardiac events and rapid clinical decisionmaking.Furthermore, the implementation of a userfriendly Node-RED dashboard enhances the system's practicality, allowing healthcare professionals to easily monitor and interpret patient data.
The synergistic combination of deep learning and IoT technologies in this system holds significant potential to improve patient outcomes.It offers enhanced diagnostic accuracy, enables early disease detection, and facilitates personalized patient care.The system's ability to continuously monitor and analyze multiple physiological parameters could revolutionize both in-hospital care and remote patient monitoring.
While this study represents a substantial step forward, there are areas for future research and development.These include expanding the system's capabilities to include additional physiological parameters and disease classifications, addressing potential security and privacy challenges associated with IoT-based healthcare systems, conducting large-scale clinical trials to further validate the system's efficacy and impact on patient outcomes, and Online First exploring the integration of this system with existing healthcare infrastructure and electronic health records.This research contributes significantly to the ongoing advancement of healthcare technology, demonstrating the power of integrating AI and IoT for improved patient care.It paves the way for a future where these technologies seamlessly collaborate to enhance medical diagnostics, enable proactive healthcare interventions, and ultimately improve patient lives.As we continue to refine and expand upon this system, we move closer to realizing the full potential of AI-driven, IoT-enabled healthcare monitoring.
Future research should focus on further enhancing the system's capabilities and addressing its current limitations.This may include developing more sophisticated deep learning models capable of detecting a wider range of cardiac abnormalities, integrating additional physiological sensors to provide an even more comprehensive view of patient health, and exploring the use of edge computing to reduce latency and improve realtime performance.Additionally, investigating the longterm impact of such systems on patient outcomes through longitudinal studies will be crucial.Research into improving the system's interpretability and explainability will also be vital, ensuring that healthcare professionals can trust and effectively utilize the AI-driven insights.Finally, exploring the potential of this technology in preventive healthcare and personalized medicine could open new avenues for proactive health management and disease prevention.

Figure 4 .
Figure 4. Dataset distribution of the peak counts.

Figure 7 .
Figure 7. Evolution of test and validation loss during the learning of the phase peak detection model.
The ROC curve for the multi-class classification model visually demonstrates the model's performance across the five classes.Each curve represents one class, showing the trade-off between the true positive rate (sensitivity) and the false positive rate (1-specificity).The AUC (Area Under the Curve) values for each class indicate the model's ability to distinguish between the classes as show in Figure 10.

3. 1 . 3 . 7
Classification model architecture Our classification model architecture is meticulously crafted to accommodate the intricate nature of ECG signals.The proposed model harnesses the power of deep learning techniques, as illustrated in Figure 12, incorporating both Convolutional Neural Networks (CNNs) and Recurrent Neural Networks (RNNs) to capture spatial and sequential features inherent within the ECG data.This synergistic fusion of spatial and sequential analyses enables the model to extract critical information from the entire ECG waveform, facilitating a comprehensive and holistic understanding of the underlying cardiac dynamics.The architecture is divided into two major branches: one for processing ECG signals with CNNs and another for processing them with an RNN.These branches are then combined to form a unified model that predicts the disease class.CNN Branch: The CNN branch processes the ECG data using convolutional layers to capture spatial features.Batch normalization is added to stabilize training and enhance convergence.Max pooling layers help in down-sampling and retaining essential features.The flatten layer transforms the output into a 1D vector.RNN Branch: The RNN branch deals with the temporal aspects of the ECG data.A reshape layer prepares the data for Long-Short-Term-Memory (LSTM) processing.

Figure 13 .
Figure 13.Evolution of test and validation loss during the learning of the classification model.

Figure 14 .
Figure 14.Confusion matrix result for classification model.

Figure 15 .
Figure 15.Hardware implementation of the health monitoring system.

Figure 16 .
Figure 16.Node-RED flow of the deep learning models integration.

Figure 17 .
Figure 17.Node-RED flow of the sensors' integration.

Figure 18 .
Figure 18.Node-RED flow of the patient alert.

Figure 20 .
Figure 20.Node-RED flow of the display block.

Figure 29 .
Figure 29.Schematic representation of the experimental setup used in our study.

Model architecture Accurate peak detection in ECG signals is fundamental for various cardiac analyses. Peaks represent distinctive features of the ECG waveform, including the R-peak. Identifying these peaks enables us to calculate heart rate, evaluate QRS complex duration, and discern
abnormalities, ultimately aiding in clinical diagnosis.Our peak detection model is inspired by convolutional and upsampling neural network architectures.The model's structure is tailored to capture the salient features of the ECG signal and discern its peaks.It consists of several

Table 1 .
Performance comparison of our approach with existing works.

Table 1 (
continued).Performance comparison of our approach with existing works.
 Raspberry Pi 4 ESP32  DHT11 sensor  Body temperature sensor  Python