Hatena::ブログ(Diary)

va009039の日記

2013年02月14日(木)

RPC_Serial/main.cpp

RPC::constructの使用例を追加。

#include "mbed.h"
#include "mbed_rpc.h"

Serial pc(USBTX, USBRX);

int i1;
float f2;

void func1(Arguments* arg, Reply* r) {
    pc.printf("obj_name: %s\n", arg->obj_name);
    pc.printf("method_name: %s\n", arg->method_name);
    pc.printf("argc: %d\n", arg->argc);
    for(int n = 0; n < arg->argc; n++) {
        pc.printf("argv[%d]: %s\n", n, arg->argv[n]);
    }
}

void func2(Arguments* arg, Reply* r) {
    r->putData<float>(f2 * i1);
}

void func3(Arguments* arg, Reply* r) {
    i1 = arg->getArg<int>();
    f2 = arg->getArg<float>();
}

class RpcLED : public RPC {
public:
    RpcLED(PinName a0, const char *name=NULL) : RPC(name), o(a0) {}
    
    void write(int a0) {o.write(a0);}
    int read(void) {return o.read();}
    
    virtual const struct rpc_method *get_rpc_methods() {
        static const rpc_method rpc_methods[] = {
            {"write", rpc_method_caller<RpcLED, int, &RpcLED::write>},
            {"read", rpc_method_caller<int, RpcLED, &RpcLED::read>},
            RPC_METHOD_SUPER(RPC)
        };
        return rpc_methods;
    }
private:
    DigitalOut o;
};

int main() {
    // setup the classes that can be created dynamically
    RPC::add_rpc_class<RpcDigitalOut>();
    RPC::add_rpc_class<RpcDigitalIn>();
    RPC::add_rpc_class<RpcDigitalInOut>();
    //RPC::add_rpc_class<RpcAnalogIn>(); // need Reply::putData<unsigned short>()
    //RPC::add_rpc_class<RpcAnalogOut>(); // need Arguments::getArg<unsigned short>()
    RPC::add_rpc_class<RpcPwmOut>();
    RPC::add_rpc_class<RpcSPI>();
    RPC::add_rpc_class<RpcSerial>();
    RPC::add_rpc_class<RpcTimer>();

    //RPC::add_rpc_class<RpcLED>(); // NG 

    RPCVariable<int> _i1(&i1, "i1");    // /i1/write 123  /i1/read
    RPCVariable<float> _f2(&f2, "f2");  // /f2/write 45.6 /f2/read

    RPCFunction _func1(func1, "func1"); // /func1/run
    RPCFunction _func2(func2, "func2"); // /func2/run 
    RPCFunction _func3(func3, "func3"); // /func3/run 123 45.6

    const char* led1_obj_name = RPC::construct<RpcLED, PinName>(LED1);
    pc.printf("LED1 obj_name: %s\n", led1_obj_name);

    const char* led2_obj_name = RPC::construct<RpcLED, PinName, const char*>(LED2, "led2"); // /led2/write 1 
    pc.printf("LED2 obj_name: %s\n", led2_obj_name);
    
    // receive commands, and send back the responses
    char buf[RPC_MAX_STRING], result[RPC_MAX_STRING];
    while(1) {
        pc.gets(buf, sizeof(buf));
        RPC::call(buf, result); 
        pc.printf("%s\n", result);
    }
}