The Internet of Things (IoT) has grown rapidly to become the core of many areas of application, leading to the integration of sensors, with IoT devices. However, the number of attacks against these types of devices has grown as fast as the paradigm itself. Certain inherent characteristics of the paradigm, as well as the limited computational capabilities of the devices involved, make it difficult to deploy security measures. This is why it is necessary to design, implement and study new solutions in the field of cybersecurity. In this paper, we propose an architecture that is capable of generating Complex Event Processing (CEP) rules automatically by integrating them with machine learning technologies. While the former is used to automatically detect attack patterns in real time, the latter, through the use of the Principal Component Analysis (PCA) algorithm, allows the characterization of events and the recognition of anomalies. This combination makes it possible to achieve efficient CEP rules at the computational level, with the results showing that the CEP rules obtained using our approach substantially improve upon the performance of the standard CEP rules, which are rules that are not generated by our proposal but can be defined independently by an expert in the field. Our proposal has achieved an F1-score of 0.98 on average, a 76 percent improvement in throughput over standard CEP rules, and a reduction in the network overhead of 86 percent over standard simple events, which are the simple events that are generated when our proposal is not used.