connectionHub.cpp

00001 /*
00002   TCP/IP 越しにデバイス接続を行うクラス
00003   Satofumi KAMIMURA
00004   $Id$
00005 */
00006 
00007 #include "connectionHub.h"
00008 #include "serialDevice.h"
00009 enum { BufferSize = 4096 };
00010 
00011 
00012 ConnectionHub::ConnectionHub(ConnectionDevice& a, ConnectionDevice& b)
00013   : state(Connected), server(NULL), port_a(&a), port_b(&b) {
00014 }
00015 
00016 
00017 ConnectionHub::ConnectionHub(int port, const char* device, long baudrate)
00018   : state(WaitToConnect),
00019     server(new TcpipServer()), con_device(device), con_baudrate(baudrate),
00020     port_a(NULL), port_b(NULL) {
00021   server->activate(port);
00022 }
00023 
00024 
00025 ConnectionHub::~ConnectionHub(void) {
00026   disconnect();
00027 }
00028 
00029 
00030 void ConnectionHub::disconnect(void) {
00031   state = Closed;
00032 
00033   delete port_a;
00034   port_a = NULL;
00035 
00036   delete port_b;
00037   port_b = NULL;
00038 
00039   delete server;
00040   server = NULL;
00041 }
00042 
00043 
00044 bool ConnectionHub::preUpdate(bool& ret_value) {
00045   if (state == Closed) {
00046     ret_value = false;
00047     return true;
00048   }
00049 
00050   if (state == WaitToConnect) {
00051     TcpipDevice* con = server->accept(0);
00052     if (!con) {
00053       ret_value = true;
00054       return true;
00055     }
00056     port_a = con;
00057     port_b = new SerialDevice;
00058     if (port_b->connect(con_device, con_baudrate) < 0) {
00059       disconnect();
00060     }
00061     state = Connected;
00062     delete server;
00063     server = NULL;
00064   }
00065   return false;
00066 }
00067 
00068 
00069 bool ConnectionHub::update(void) {
00070   bool ret_value = false;
00071   if (preUpdate(ret_value)) {
00072     return ret_value;
00073   }
00074 
00075   // データの送受信
00076   char buffer[BufferSize];
00077   if (!port_a->isConnected() || port_a->size() > 0) {
00078     int n = port_a->recv(buffer, BufferSize);
00079     if (n < 0) {
00080       disconnect();
00081       return false;
00082     }
00083     port_b->send(buffer, n);
00084   }
00085 
00086   if (!port_b->isConnected() || port_b->size() > 0) {
00087     int n = port_b->recv(buffer, BufferSize);
00088     if (n < 0) {
00089       disconnect();
00090       return false;
00091     }
00092     port_a->send(buffer, n);
00093   }
00094   return true;
00095 }
00096 

Generated on Mon Apr 13 22:52:05 2009 by  doxygen 1.5.7.1