Watchdog模式

Watchdog模式

实时系统中使用最多的就是Watchdog模式。
Watchdog是指监视装置的程序,与其他程序在一定距离内进行定时询问或者回电报。Watchdog程序中,如果发现装置的错误或者电报序列的不一致,就会通知发送方。
通知可能是服务的重置或者关闭等。作为插入式的编程技术已是经典。
那么来看一下具体的例子。这个例子中,接受服务的类是Channel,进行监视的则是 Watchdog。
从图1 的类图中可以看出,因为想要变成拥有多个Channel对象的式样,所以要使用多重度来体现。在实际的Java编码中,为了便于理解通常只生成一个。

顺序图的消息传递如图2所示。

Watchdog对象向Channel发送Start()消息从而开始服务。
然后,作为Request(1)发送顺序编号(1)的电报,编号(2)的电报也继续进行。
此外,在Watchdog对象中检测出错误时,从error()向Channel发送Restart()消息,然后重置服务。实际的Java编码如下所示。

Watchdog例的Java编码
                                
    class Channel extends Object{
        PrintPanel pt = new PrintPanel();
        void Start(Watchdog wd){
            pt.Print("Start");
            wd.Request(1); //发送编号1的电报
            wd.Request(2); //发送编号2的电报
        }
        void Restart(Watchdog wd){
            pt.Print("Restart");
            this.Start(wd);
        }
    }
    class Watchdog extends Object{
        Channel channel;
        int seq=0; //用于检查电报顺序编号
        PrintPanel pt = new PrintPanel();
        Watchdog(){
            channel=new Channel();
        }
        void Connect(){
            channel.Start(this);
        }
        void Request(int s){
            if (s != seq+1){
                this.error();
            }
            else{
                seq = s;
                pt.Print("Sequesnce No:"+seq);
            }
        }
        void error(){
            pt.Print("Error");
            seq=0;
            channel.Restart(this);
        }
    }

    class PrintPanel{
        void Print(String s){
        System.out.println(s);
        }
    }
                                
                                
Watchdog例的主要部分
                                
    Watchdog wd;
    wd = new Watchdog();
    wd.Connect();

    发生错误时,wd.error();
                                
                                

在主要部分生成Watchdog对象时,也在Watchdog中生成Channel对象。
因为要开始运行服务,这时生成wd.Connect()之后,向Channel发送Start()消息。这样的话,如图2的顺序图所示,添加Request(1)、Request(2)作为顺序编号后再发送电报。这时的收信人-Watchdog对象用 Start(this)通过引数传递。
收到电报的Watchdog对象只是简单地在Request()中进行顺序编号的检查。而且,主要部分中Watchdog对象发生错误时,通过wd.error()向Channel对象发送Restart()然后进行重置。
这样的话,有监视装置的对象时,就能有效地利用Watchdog模式了。该Watchdog模式在“REAL-TIME UML”Addison -Wesley刊中有介绍。