树莓派——智能家居工厂模式实现四个场景灯的控制

万事开头难,上篇的第一步已经成功迈出,此时工厂模式的优势就体现出来了,可以通过简单的更改名字即可实现不同场景的灯的开关,修改部分如下:

#include "contrlDevices.h"
#include 

int OuttingLightOpen(int pin)
{

        digitalWrite(pin,LOW);

}

int OuttingLightClose(int pin)
{

        digitalWrite(pin,HIGH);

}

int OuttingLightInit(int pin)
{

        pinMode(pin,OUTPUT);
        digitalWrite(pin,HIGH);

}

struct Devices OuttingLight = {

        .devicesName = "OuttingLight",
        .pin = 28,
        .open = OuttingLightOpen,
        .close = OuttingLightClose,
        .deviceInit = OuttingLightInit


};
struct Devices *addOuttingLightToDeviceLink(struct Devices *phead)
{
        if(phead == NULL){
                return &OuttingLight;
        }else{
                OuttingLight.next = phead;
                phead = &OuttingLight;
        }
}

如上,对比上一篇的room,只需要在outting.c文件内把room改成outting就好了,再更改以下输出引脚号,最后把该设备的成链函数放到contrlDevices.h头文件内即可

树莓派——智能家居工厂模式实现四个场景灯的控制_第1张图片

这是四个灯的

在main函数里边:

#include 
#include "contrlDevices.h"
#include 
struct Devices *findDeviceByName(char *name,struct Devices *phead)
{
        struct Devices *tmp=phead;
        if(phead == NULL){
                return NULL;
        }else{
                while(tmp != NULL){
                        if(strcmp(tmp->devicesName,name)==0){
                                return tmp;

                        }
                        tmp = tmp->next;
                }
                return NULL;
        }

}

int main()
{
        char name[128];//定义一个数组存放用户输入的名字
        if(wiringPiSetup() ==-1){
                return -1;
        }
        
    struct Devices *pdeviceHead = NULL;
//把设备插入链表
    pdeviceHead = addroomLightToDeviceLink(pdeviceHead);
    pdeviceHead = addOuttingLightToDeviceLink(pdeviceHead);
    pdeviceHead = addLivingroomLightToDeviceLink(pdeviceHead);
    pdeviceHead = addswimmingLightToDeviceLink(pdeviceHead);
    
        
    while(1){
    printf("please input Device:   \n");
    scanf("%s",name);
    struct Devices *tmp = findDeviceByName(name,pdeviceHead);
        if(tmp != NULL){
                tmp->deviceInit(tmp->pin);
                tmp->open(tmp->pin);
                }
        }

        return 0;
}
                          

如上,用树莓派基于工厂模式完成了四个场景灯的控制

你可能感兴趣的:(树莓派,智能家居)