One of the most challenging problems related to the operation of smart microgrids is the optimal home energy management scheme with multiple and conflicting objectives. Moreover, there is a noticeable increase in homes equipped with renewable energy sources (RESs), where the coordination of loads and generation can achieve extra savings and minimize peak loads. In this paper, a solar-powered smart home with optimal energy management is designed in an affordable and secure manner, allowing the owner to control the home from remote and local sites using their smartphones and PCs. The Raspberry Pi 4 B is used as the brain of the proposed smart home automation management system (HAMS). It is used to collect the data from the existing sensors and store them, and then take the decision. The home is monitored using a graphical interface that monitors room temperature, humidity, smoke, and lighting through a set of sensors, as well as PIR sensors to monitor the people movement. This action enables remote control of all home appliances in a safe and emission-free manner. This target is reached using Cayenne, which is an IoT platform, in addition to building some codes related to some appliances and sensors not supported in Cayenne from scratch. Convenience for people with disabilities is considered by using the Amazon Echo Dot (Alexa) to control home appliances and the charging point by voice, implementing the associated code for connecting the Raspberry pi with Alexa from scratch, and simulating the system on LabVIEW. To reach the optimal operation and reduce the operating costs, an optimization framework for the home energy management system (HEMS) is proposed. The operating costs for the day amounted to approximately 16.039 €. There is a decrease in the operating costs by about 23.13%. The consumption decreased after using the smart HAMS by 18.161 kWh. The results of the optimization also show that the least area that can be used to install solar panels to produce the desired energy with the lowest cost is about 118.1039 m2, which is about 23.62% of the total surface area of the home in which the study was conducted. The obtained results prove the effectiveness of the proposed system in terms of automation, security, safety, and low operating costs.