using namespace std; #include "spyterm.h" SC_HAS_PROCESS(spyterm); #define PORT_NUM ((unsigned short)6601) spyterm::spyterm(sc_core::sc_module_name name) : sc_module(name), rx("rx", 20) { // Method for the Rx with static sensitivity SC_METHOD(writeMethod); sensitive << rx.data_written_event(); dont_initialize(); connected = false; d.sock = 0; } // Custom destructors are not usually needed for SystemC models, but we use // this to kill the child process running the xterm. spyterm::~spyterm() { cout << "Closing connection" << endl; shutdown(d.sock, SHUT_RDWR); close(d.sock); } // Method handling characters on the Rx buffer // Statically sensitive to characters being written from the UART. When they // arrive, write them to the xterm. Print a time stamp void spyterm::writeMethod() { if (connected == false) { if (!startConnection()) return; } while (rx.num_available() != 0) { // read from uart unsigned char c = rx.read(); socketWrite(c); } } bool spyterm::gethost(const char *address, struct sockaddr_in *in) { long num; struct hostent *h; num = inet_addr(address); if (num > 0) { in->sin_addr.s_addr = num; return false; } h = gethostbyname(address); if (h) { in->sin_addr = *(struct in_addr *)h->h_addr_list[0]; return false; } return true; } bool spyterm::startConnection() { int port = PORT_NUM; int protocol = 0; struct sockaddr_in addr; string hostname = "localhost"; d.hex = 0; d.family = SOCK_STREAM; d.port = port; d.address = hostname.c_str(); if (protocol == 0) { if (gethost(d.address, &addr) != 0) { herror(d.address); return 1; } else protocol = 4; } else if (protocol == 4) { if (gethost(d.address, &addr) != 0) { herror(d.address); return 1; } } if (protocol == 4) { d.addr = (struct sockaddr *)&addr; d.addrlen = sizeof addr; addr.sin_family = AF_INET; addr.sin_port = htons(port); d.sock = socket(AF_INET, d.family, 0); } if (d.sock < 0) { perror("socket"); return 1; } if (d.family == SOCK_STREAM) { if (::connect(d.sock, d.addr, d.addrlen) < 0) { perror("connect"); return 1; } else { connected = true; } } return(connected); } void spyterm::socketWrite(unsigned char ch) { ssize_t size; if (connected && d.sock >= 0) { size = write(d.sock, &ch, 1); if (size < 0) { perror("write()"); connected = false; } } }