A wireless sensor network comprised of numerous sensors randomly distributed within a specific region, which aimed at detecting and collecting information within that region. Although they cannot be recharged or replaced, but sensor devices can detect, store, and transport data and energy, Data communication is another potential use of case for sensor devices. Since energy resources are limited in sensors, wireless sensor networks are constantly developing energy-efficient protocols to extend their ability to last long. Developing the routing protocol is extremely essential in order to maximize the longevity of the network by optimizing its energy efficiency. The key essential role play by Wireless sensor networks (WSNs) in the monitoring of the environment, which gains special focus on attaining energy efficiency and guaranteeing the secure transferring of data as key objectives in their design. Attacks that are network-based there has been gains increased focus, as the complexity of computer networks continues to grows. This, in turn, has prompted research activities that are focused at developing Intrusion Detection Systems that are more resistant to vulnerabilities. This research aims to develop an automated intrusion detection system (IDS) that enhances energy efficiency in wireless sensor networks (WSNs) using LD2FA and Particle Swarm Optimization. The Learning Dynamic Deterministic Finite Automata (LD2FA) that has been presented which is capable of dynamically adapting to the nature of the network. It offers insights into the examination of nodes, packets, and routes in order to efficiently discover and eliminate intrusions. Data transmission that is more energy-efficient as a consequence is accomplished via the use of improved routing. The essential goal of the LD2FA-PSO approach is to optimize routing patterns in order to ensure that transfer of data is as energy-efficient as possible. DFA strengthen the intrusion detection system's which has the ability to recognize and to eliminate variety of network security threats, which includes denial of service attacks, worms, viruses, and malware, while PSO refines the routing process and picks the most effective data transfer channels.