Example #1
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: init_transfer
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void init_transfer(HWND hwnd), takes the parent window HWND.
--
--      RETURNS: void
--
--      NOTES:
--      Intializes a UDP or TCP transfer based on the current settings. Will generate dummy packets if the program is in
--		dummy packet transfer mode, otherwise reads a file and generates packets for the file. Passes the created packets
--		to their respective UDP/TCP functions.
----------------------------------------------------------------------------------------------------------------------*/
void init_transfer(HWND hwnd){

	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);
	int status;
	char msg[MAX_SIZE];
	HANDLE hf;
	DWORD numBytesRead = 0;
	int  totalBytesRead = 0;
	DWORD packetsizes[] = {1024, 4096, 20000, 60000};
	const int packet_size = packetsizes[st->packet_size];
	
	if (st->mode == FILEMODE){
		grab_file(hwnd, &hf);
	}

	activity("Sending data...\n", EB_STATUSBOX);
	WSABUF * wsaBuffers = (LPWSABUF)malloc(sizeof(WSABUF)* MAX_PACKETS);
	
	char * buff = (char*)malloc(sizeof(char)* packet_size);

	int i = 0, buffer_count = 0;
	while (1){
		if (st->mode == FILEMODE){
			status = ReadFile(hf, buff, packet_size, &numBytesRead, NULL);
			if (numBytesRead == 0){
				CloseHandle(hf);
				break;
			}
			wsaBuffers[i].buf = buff;
			wsaBuffers[i++].len = numBytesRead;
			totalBytesRead += numBytesRead;
			buffer_count++;
		}
		else{
			buffer_count = atoi(st->times_to_send);
			
			for (int g = 0; g < packet_size; g++){
				buff[g] = 'p';
			}
			buff[packet_size - 1] = '\0';

			for (int p = 0; p < buffer_count; p++){
				wsaBuffers[p].buf = buff;
				wsaBuffers[p].len = packet_size;
			}
			totalBytesRead = packet_size * buffer_count;
			break;
		}
	}
	
	sprintf_s(msg, "Sending %d bytes in %d packets.\n", totalBytesRead, buffer_count);
	activity(msg, EB_STATUSBOX);

	if(st->protocol == UDP)
		udp_deliver_packets(hwnd, totalBytesRead, packet_size, buffer_count, wsaBuffers);
	else
		tcp_deliver_packets(hwnd, wsaBuffers, st->client_socket, totalBytesRead, packet_size, buffer_count, st->mode);

	free(wsaBuffers);
}
Example #2
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: tcp_deliver_packets
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void tcp_deliver_packets(HWND hwnd, WSABUF * wsaBuffers, SOCKET sock, int totalBytesRead, int packet_size, int buffer_count, int mode)
--
--      RETURNS: void
--
--      NOTES:
--		Takes the parent window HWND, the total bytes to be transferred (totalBytesRead), the current packet size, the amount of packets
--		an an array of WSABUFs each containing a packet of data.
--
--		Delivers TCP packets to the specified host. Intially sends a header containing the int variables passed to the function
--		before sending the actual data. Must be passed an array of WSABUFs, with each WSABUF containing a packet of data.
----------------------------------------------------------------------------------------------------------------------*/
void tcp_deliver_packets(HWND hwnd, WSABUF * wsaBuffers, SOCKET sock, int totalBytesRead, int packet_size, int buffer_count, int mode){
	
	int status;
	char msg[MAX_SIZE];
	DWORD  numBytesSent = 0;

	char flags[HEADER_SIZE];
	memset(flags, '\0', HEADER_SIZE);
	sprintf_s(flags, ";%d,%d,%d,%d;", totalBytesRead, packet_size, buffer_count, mode);
	
	LPWSABUF wsaHeaderBuf = (LPWSABUF)malloc(sizeof(WSABUF));
	wsaHeaderBuf->len = HEADER_SIZE;
	wsaHeaderBuf->buf = flags;

	if ((status = WSASend(sock, wsaHeaderBuf, 1, &numBytesSent, NULL, NULL, NULL)) < 0){
		sprintf_s(msg, "Error %d in TCP WSASend(header) with return of %d\n", WSAGetLastError(), status);
		activity(msg, EB_STATUSBOX);
	}

	startTime = GetTickCount();

	for (int p = 0; p < buffer_count; p++){
		if ((status = WSASend(sock, &wsaBuffers[p], 1, &numBytesSent, NULL, NULL, NULL)) < 0){
			sprintf_s(msg, "Error %d in TCP WSASend(buffer) with return of %d\n", WSAGetLastError(), status);
			activity(msg, EB_STATUSBOX);
			return;
		}
	}

	endTime = GetTickCount();
	seconds = endTime - startTime;
	sprintf_s(msg, "Data transmission completed in %d milliseconds.\n", seconds);
	activity(msg, EB_STATUSBOX);
}
Example #3
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: client_connect
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void client_connect(HWND hwnd), takes the parent window HWND as an argument.
--
--      RETURNS: void
--
--      NOTES:
--      When the client is in TCP mode, will connect the client to the TCP server. Returns messages on failure. After 
--		performing a connect the client is ready to transfer files.
----------------------------------------------------------------------------------------------------------------------*/
void client_connect(HWND hwnd){
	SOCKADDR_IN InternetAddr;
	hostent *hp;
	int iRc;
	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);

	memset((char *)&InternetAddr, 0, sizeof(SOCKADDR_IN));

	InternetAddr.sin_family = AF_INET;
	InternetAddr.sin_port = htons(atoi(st->client_port));
	
	if ((hp = gethostbyname(st->client_send_ip)) == NULL)
	{
		activity("Could not find the specified server address.\n", EB_STATUSBOX);
		return;
	}

	memcpy((char *)&InternetAddr.sin_addr, hp->h_addr, hp->h_length);

	iRc = connect(st->client_socket, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr));
	if (iRc != 0){
		activity("Failed to connect to server.\n", EB_STATUSBOX);
		return;
	}

	setsockopt(st->client_socket, SOL_SOCKET, SO_REUSEADDR, 0, 0);
	SetClassLongPtr(hwnd, 0, (LONG)st);
	activity("Connected to server.\n", EB_STATUSBOX);
	
	return;
}
Example #4
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: udp_deliver_packets
--
--      DATE: Febuary 6 2014
--      REVISIONS: Countless. Most recent, turning it into somewhat reliable UDP.
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void udp_deliver_packets(HWND hwnd, int totalBytesRead, int packet_size, int buffer_count, WSABUF * buffers)
--
--      RETURNS: void
--
--      NOTES:
--      Takes the parent window HWND, the total bytes to be transferred (totalBytesRead), the current packet size, the amount of packets
--		an an array of WSABUFs each containing a packet of data.
--		
--		Delivers the packets over UDP to the specified IP and port, and has some reliability for dropped packets by 
--		incorporating an acknowledgement system as well as a header packet containing the info passed to the function. 
--		If an error occurs in the recvfrom portion of the acknowledgement, consider the transfer dead and restart the program.
--
--		* WILL loop endlessly if the user decides to terminate the server during a transfer. Will continously wait for ACKs.
----------------------------------------------------------------------------------------------------------------------*/
void udp_deliver_packets(HWND hwnd, int totalBytesRead, int packet_size, int buffer_count, WSABUF * buffers){

	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);
	
	int packets_lost = 0;
	int status;
	char msg[MAX_SIZE];
	DWORD  numBytesSent = 0;
	struct sockaddr_in sin;

	char flags[HEADER_SIZE];
	memset(flags, '\0', HEADER_SIZE);
	sprintf_s(flags, ";%d,%d,%d,%d;", totalBytesRead, packet_size, buffer_count, st->mode);

	LPWSABUF wsaHeaderBuf = (LPWSABUF)malloc(sizeof(WSABUF));
	wsaHeaderBuf->len = HEADER_SIZE;
	wsaHeaderBuf->buf = flags;

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(atoi(st->client_port));

	if ((sin.sin_addr.s_addr = inet_addr(st->client_send_ip)) == INADDR_NONE)
	{
		activity("Failed to find address\n", EB_STATUSBOX);
		return;
	}
	
	while (1){ // transferring the header packet
		if ((status = WSASendTo(st->client_socket, wsaHeaderBuf, 1, &numBytesSent, 0, (struct sockaddr *)&sin, sizeof(sin), NULL, NULL)) < 0){
			sprintf_s(msg, "Error %d in TCP WSASend(header) with return of %d\n", WSAGetLastError(), status);
			activity(msg, EB_STATUSBOX);
		}

		if (receive_acknowledge(hwnd) == 1) { break; } 
		packets_lost++;
	}
	
	startTime = GetTickCount();

	for (int p = 0; p < buffer_count; p++){
		while (1){ // transferring the actual data
			if ((status = WSASendTo(st->client_socket, &buffers[p], 1, &numBytesSent, 0, (struct sockaddr *)&sin, sizeof(sin), NULL, NULL)) < 0){
				sprintf_s(msg, "Error %d in sendto(buffer) with return of %d\n", WSAGetLastError(), status);
				activity(msg, EB_STATUSBOX);
				return;
			}

			if (receive_acknowledge(hwnd) == 1){ break; }
			packets_lost++;
		}
	}

	endTime = GetTickCount();
	seconds = endTime - startTime;
	sprintf_s(msg, "Data transmission completed in %d milliseconds.\n", seconds);
	activity(msg, EB_STATUSBOX);
}
Example #5
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{    
    ui->setupUi(this);

    ui->devicelist->show();
#ifdef HYGROMETER
    this->setWindowTitle("Humidity Temperature Sensor");
#else
    this->setWindowTitle("Device Status");
#endif

    connect(ui->devicelist,SIGNAL(activity(QString)),this,SLOT(activity(QString)));
}
Example #6
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: transfer_completion
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: int transfer_completion(HWND hwnd, int mode), takes the parent HWND as an argument and the transfer mode.
--
--      RETURNS: int, returns a positive value over 0, causing the program to deem the transfer as completed.
--
--      NOTES:
--		Called on transfer completion, gets the time the transfer took and saves the data if in FILEMODE, and does nothing
--		with the data if in packet mode.
--
--		Prints info on the transfer and updates the statistics.
----------------------------------------------------------------------------------------------------------------------*/
int transfer_completion(HWND hwnd, int mode){

	char msg[MAX_SIZE];

	if (mode == 0){
		save_file(hwnd, buffer, SocketInfo->totalRecv);
		sprintf_s(msg, "Recieved %d bytes. File transfer completed in %d milliseconds.\n", SocketInfo->totalRecv, seconds);
		activity(msg, EB_STATUSBOX);
		return 3;
	}

	sprintf_s(msg, "Recieved %d bytes. Garbage transfer completed in %d milliseconds.\n", SocketInfo->totalRecv, seconds);
	activity(msg, EB_STATUSBOX);
	return 2; // transfer completed, closing connection
}
Example #7
0
void Kopete::Away::setActive()
{
//	kdDebug(14010) << k_funcinfo << "Found activity on desktop, resetting away timer" << endl;
    d->idleTime.start();

    if(d->autoaway)
    {
        d->autoaway = false;
        emit activity();
        if (d->goAvailable)
        {
            d->autoAwayAccounts.setAutoDelete(false);
            for(Kopete::Account *i=d->autoAwayAccounts.first() ; i; i=d->autoAwayAccounts.current() )
            {
                if(i->isConnected() && i->isAway())
                {
                    i->setOnlineStatus( Kopete::OnlineStatusManager::self()->onlineStatus( i->protocol() ,
                                        Kopete::OnlineStatusManager::Online ) );
                }

                // remove() makes the next entry in the list the current one,
                // that's why we use current() above
                d->autoAwayAccounts.remove();
            }
        }
    }
}
Example #8
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: init_server
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: LPSTR grab_file(HWND hwnd, HANDLE * hf), takes the parent window HWND and a pointer to a file handle as arguments.
--
--      RETURNS: A LPSTR containing the file name. Also sets the *hf to the file specified by the user.
--
--      NOTES:
--		Takes the passed in file point and opens the Common Dialog Box so the user can choose a file to send. Sets the file
--		pointer to the file they have chosen and opens it for reading.
----------------------------------------------------------------------------------------------------------------------*/
LPSTR grab_file(HWND hwnd, HANDLE * hf){
	OPENFILENAME ofn;       
	char szFile[260];       
	
	ZeroMemory(&ofn, sizeof(ofn));
	ofn.lStructSize = sizeof(ofn);
	ofn.hwndOwner = hwnd;
	ofn.lpstrFile = szFile;

	ofn.lpstrFile[0] = '\0';
	ofn.nMaxFile = sizeof(szFile);
	ofn.lpstrFilter = "All\0*.*\0Text\0*.TXT\0";
	ofn.nFilterIndex = 1;
	ofn.lpstrFileTitle = NULL;
	ofn.nMaxFileTitle = 0;
	ofn.lpstrInitialDir = NULL;
	ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

	if (GetOpenFileName(&ofn) == TRUE){
		*hf = CreateFile(ofn.lpstrFile, GENERIC_READ, 0, NULL, 
			OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
		return ofn.lpstrFileTitle;
	}

	activity("Failed to get file handle.\n", EB_STATUSBOX);
	return NULL;
}
Example #9
0
value::Value* Agent::observation(
    const devs::ObservationEvent& event) const
{
    const std::string port = event.getPortName();

    if (port == "KnowledgeBase") {
        std::stringstream out;
        out << *this;
        return new value::String(out.str());
    } else if (port == "Activities") {
        std::stringstream out;
        out << activities();
        return new value::String(out.str());
    } else if ((port.compare(0, 9, "Activity_") == 0) and port.size() > 9) {
        std::string activity(port, 9, std::string::npos);
        const Activity& act(activities().get(activity)->second);
        std::stringstream out;
        out << act.state();
        return new value::String(out.str());
    } else if ((port.compare(0, 6, "Rules_") == 0) and port.size() > 6) {
        std::string rule(port, 6, std::string::npos);
        const Rule& ru(rules().get(rule));
        return new value::Boolean(ru.isAvailable());
    }
    return 0;
}
Example #10
0
/**
 * load a standard m3u playlist into a list of titles that the tools can handle
 */
struct entry_t *loadPlaylist( const char *path ) {
	FILE *fp;
	int cnt;
	struct entry_t *current=NULL;
	char *buff;

	buff=calloc( MAXPATHLEN, sizeof(char) );
	if( !buff ) fail( "Out of memory", "", errno );

	fp=fopen( path, "r" );
	if( !fp ) fail("Couldn't open playlist ", path,  errno);

	while( !feof( fp ) ){
		activity("Loading");
		buff=fgets( buff, MAXPATHLEN, fp );
		if( buff && ( strlen( buff ) > 1 ) && ( buff[0] != '#' ) ){
			current=insertTitle( current, buff );
		}
	}
	fclose( fp );
	current=rewindTitles( current );

	if( _ftverbosity > 2 ) {
		printf("Loaded %s with %i entries.\n", path, cnt );
	}

	return current;
}
Example #11
0
void Progress::MeterDialog::CreateDialogTemplate (::Dialog::Template & tmpl)
{
	::Dialog::TemplateMaker::Button cancelButton (Out::Cancel);
	cancelButton.SetRect (223, 45, 50, 14);
	cancelButton.SetText (L"Cancel");
	cancelButton.Style () << Win::Button::Style::Default;

	::Dialog::TemplateMaker::StaticText caption (CaptionId);
	caption.SetRect (7, 4, 266, 25);
	caption.Style () << Win::Static::Style::Sunken;

	::Dialog::TemplateMaker::StaticText activity (ActivityId);
	activity.SetRect (7, 32, 266, 10);

	::Dialog::TemplateMaker::ProgressBar bar (ProgressBarId);
	bar.SetRect (7, 47, 213, 11);

	::Dialog::TemplateMaker templateMaker;
	templateMaker.SetRect (Win::Rect (0, 0, 280, 66));

	templateMaker.AddItem (&cancelButton);
	templateMaker.AddItem (&caption);
	templateMaker.AddItem (&activity);
	templateMaker.AddItem (&bar);
	templateMaker.Create (tmpl);
}
Example #12
0
int main()
{
    int t, num_acts, start, end;
    std::vector<activity> actlist;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &num_acts);
        for(int i = 0; i < num_acts; i++) {
            scanf("%d%d", &start, &end);
            actlist.push_back(activity(start, end));
        }
        std::sort(actlist.begin(), actlist.end(), comp);
        int max_taken = 1;
        activity last_taken = *(actlist.begin());
        for(std::vector<activity>::iterator it = actlist.begin() + 1; it != actlist.end(); ++it) {
            //printf("%d %d\n", (*it).start, (*it).end);
            if((*it).start >= last_taken.end) {
                max_taken++;
                last_taken = *it;
            }
        }
        printf("%d\n", max_taken);
        actlist.clear();
    }
    return 0;
}
Example #13
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: init_udp_recieve
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: int init_udp_receive(HWND hwnd)
--
--      RETURNS: int, returns values that are dealt with by read_udp. Positive values deem a transfer as over.
--
--      NOTES:
--      Takes a HWND to the parent window.
--
--		Sets up the system to accept a UDP data transfer, reads the packet, acknowledges it and adds it to the main buffer. Once the transfer
--		has been completed a message is printed or the data is saved, based on the specified mode.
----------------------------------------------------------------------------------------------------------------------*/
int init_udp_receive(HWND hwnd){
	DWORD Flags = 0;
	int status;
	char msg[MAX_SIZE];
	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);

	char ack[6] = ";ACK;";

	char * tempBuffer = (char*)malloc(sizeof(char)* SocketInfo->packet_size);
	SocketInfo->DataBuf.len = SocketInfo->packet_size;
	SocketInfo->DataBuf.buf = tempBuffer;

	if ((status = WSARecvFrom(st->server_socket, &SocketInfo->DataBuf, 1, &SocketInfo->BytesRECV, &Flags, NULL, NULL, NULL, NULL)) == SOCKET_ERROR){
		sprintf_s(msg, "Error %d in TCP WSARecv(data) with return of %d\n", WSAGetLastError(), status);
		activity(msg, EB_STATUSBOX);
		return 0;
	}
	acknowledge(hwnd);

	if (SocketInfo->mode == 0){
		SocketInfo->DataBuf.buf[SocketInfo->BytesRECV - 1] = '\0';
		strcat_s(buffer + SocketInfo->totalRecv, SocketInfo->BytesRECV, SocketInfo->DataBuf.buf);
	}

	SocketInfo->packets -= 1;
	SocketInfo->totalRecv += SocketInfo->BytesRECV;

	if (SocketInfo->totalRecv == SocketInfo->total_size || SocketInfo->packets == 0){
		endTime = GetTickCount();
		seconds = endTime - startTime;
		return transfer_completion(hwnd, SocketInfo->mode);
	}
	return -2; // packets remaining
}
Example #14
0
/**
 * This function sets the favourite bit on titles found in the given list
 */
int applyFAVlist( mptitle *root, struct marklist_t *favourites ) {
	struct marklist_t *ptr = NULL;
	mptitle *runner=root;
	int cnt=0;

	do {
		activity( "Favourites " );
		ptr=favourites;

		while( ptr ) {
			if( matchTitle( runner, ptr->dir ) ) {
				addMessage( 3, "[F] %s: %s", ptr->dir, runner->display );
				if( !( runner->flags & MP_FAV ) ) {
					runner->flags|=MP_FAV;
					cnt++;
				}
				ptr=NULL;
			}
			else {
				ptr=ptr->next;
			}
		}

		runner=runner->next;
	} while ( runner != root );

	addMessage( 1, "Marked %i favourites", cnt );

	return cnt;
}
Example #15
0
void GameWidget::mouseReleaseEvent(QMouseEvent *event)
{
    if(selection.size() < 2 or !selection.contains(getGridPos(event->x(), event->y())))
        return; //nothing selected or mouse pointer not in selection

    //backup
    oldscore = score;
    for(int x = 0; x < grid_size; x++)
        for(int y = 0; y < grid_size; y++)
            old_grid[x][y] = grid[x][y];

    foreach(Box pos, selection) {
        if(use_animations)
            old_grid[pos.x][pos.y].scale_step = num_scale_steps-1;

        grid[pos.x][pos.y] = Bubble(); //remove bubbles
    }

    score += selection.size()*selection.size();
    selection.clear();

    emit enableUndo(true);
    emit activity();

    compressBubbles();

#ifndef Q_WS_MAEMO_5
    mouseMoveEvent(event); //draw selection if there's a new set of connected bubbles
#endif
}
Example #16
0
/**
 * load a standard m3u playlist into a list of titles that the tools can handle
 */
mptitle *loadPlaylist( const char *path ) {
	FILE *fp;
	int cnt=0;
	mptitle *current=NULL;
	char *buff;
	char titlePath[MAXPATHLEN];

	fp=fopen( path, "r" );
	if( !fp ) {
		addMessage( 0, "Could not open playlist %s", path );
		return NULL;
	}

	buff=(char*)falloc( MAXPATHLEN, 1 );
	while( !feof( fp ) ) {
		activity( "Loading" );
		if( ( fgets( buff, MAXPATHLEN, fp ) != NULL ) &&
				( strlen( buff ) > 1 ) && ( buff[0] != '#' ) ) {
			strip( titlePath, buff, MAXPATHLEN ); /* remove control chars like CR/LF */
			current=insertTitle( current, titlePath );
			/* turn list into playlist too */
		}
	}
	free( buff );

	fclose( fp );

	addMessage( 2, "Loaded %s with %i entries.", path, cnt );

	return ( current == NULL )?NULL:current->next;
}
Example #17
0
	void Win32Window::Run(const std::function<void()>& gameloop, const std::function<void()>& intloop)
	{
        ShowWindow(handle, SW_SHOW);
        UpdateWindow(handle);

        win32mouse = (Input::Win32Mouse*)mouse;
        activity = gameloop;
        worker = intloop;

        while (true)
        {
            if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
            {
                if (msg.message == WM_QUIT)
                {
                    ZeroMemory(&msg, sizeof(msg));
                    break;
                }
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
            else
            {
                worker();
                activity();
            }
        }
	}
Example #18
0
void debug()
{
	int i;

if(user_level<90)
	return;
getgamedat(0);
getcarddat();

bprintf("\r\nDeck (%d) Current: %d\r\n\r\n",total_decks,cur_card);
for(i=0;i<total_decks*52;i++) {
	if(!(i%11))
		bputs("\r\n");
	bprintf("%3d:%-11s",i,cardstr(card[i])); }

pause();
bprintf("\1n\r\nDealer (%d)\r\n\r\n",dc);
for(i=0;i<dc;i++)
	bprintf("%s ",cardstr(dealer[i]));
bprintf("\1n\r\nNodes (%d) Current: %d\r\n\r\n"
	,total_nodes,curplayer);
for(i=0;i<total_nodes;i++)
	bprintf("%d: node=%d status=%d %s\r\n",i+1,node[i]
		,status[i],activity(status[i]));
}
Example #19
0
QStringList ActivityInfo::getSectionPath()
{
	QStringList path;
	ActivityInfo *activity(this);
	do {
		path.prepend(activity->section());
	} while( ( activity = qobject_cast<ActivityInfo*>(activity->parent()) ) );
	return path;
}
Battery::Battery()
    : mStatus(STATUS_UNKNOWN)
    , mHealth(HEALTH_UNKNOWN)
    , mPresent(false)
    , mACOnline(false)
    , mUSBOnline(false)
    , mCapacity(0)
    , mVoltage(0)
    , mTemperature(0)
    , mVoltageDivisor(1)
{
    QDirIterator it(QStringLiteral("/sys/class/power_supply"));
    while (it.hasNext()) {
	QString path = it.next();
	QString name = it.fileName();

	if (name != QStringLiteral(".") && name != QStringLiteral("..")) {
	    QDir d(path);
	    QFile tfile(d.filePath(QStringLiteral("type")));

	    if (tfile.open(QIODevice::ReadOnly | QIODevice::Text)) {
		QByteArray data = tfile.readLine().trimmed();
		if (data == "Mains") {
		    mPathACOnline = checkFile(d, QStringLiteral("online"));
		}
		else if (data == "USB") {
		    mPathUSBOnline = checkFile(d, QStringLiteral("online"));
		}
		else if (data == "Battery") {
		    mPathBatteryStatus     = checkFile(d, QStringLiteral("status"));
		    mPathBatteryHealth     = checkFile(d, QStringLiteral("health"));
		    mPathBatteryPresent    = checkFile(d, QStringLiteral("present"));
		    mPathBatteryCapacity   = checkFile(d, QStringLiteral("capacity"));
		    mPathBatteryTechnology = checkFile(d, QStringLiteral("technology"));

		    mPathBatteryVoltage = checkFile(d, QStringLiteral("voltage_now"));
		    if (!mPathBatteryVoltage.isEmpty())
			mVoltageDivisor = 1000;
		    else
			mPathBatteryVoltage = checkFile(d, QStringLiteral("batt_volt"));
		    
		    mPathBatteryTemperature = checkFile(d, QStringLiteral("temp"));
		    if (mPathBatteryTemperature.isEmpty())
			mPathBatteryTemperature = checkFile(d, QStringLiteral("batt_temp"));

		}
	    }
	}
    }
    update();

    // Monitor UEvent
    UEventWatcher *watcher = new UEventWatcher();
    connect(watcher, SIGNAL(activity()), SLOT(update()));
    watcher->start();
}
Example #21
0
void TCXParser::activities()
{
	while (_reader.readNextStartElement()) {
		if (_reader.name() == "Activity") {
			_tracks.append(TrackData());
			activity(_tracks.back());
		} else
			_reader.skipCurrentElement();
	}
}
void XRecordKeyboardMonitor::process(xcb_record_enable_context_reply_t *reply)
{
    bool prevActivity = activity();

    xcb_key_press_event_t *events = reinterpret_cast<xcb_key_press_event_t*>
                                    (xcb_record_enable_context_data(reply));
    int nEvents = xcb_record_enable_context_data_length(reply) /
                  sizeof(xcb_key_press_event_t);
    bool wasActivity = prevActivity;
    for (xcb_key_press_event_t *e = events; e < events + nEvents; e++) {
        if (e->response_type != XCB_KEY_PRESS &&
                e->response_type != XCB_KEY_RELEASE)
        {
            continue;
        }

        if (m_ignore[e->detail]) {
            continue;
        }

        bool pressed = (e->response_type == XCB_KEY_PRESS);
        if (m_pressed[e->detail] == pressed) {
            continue;
        }
        m_pressed[e->detail] = pressed;

        int &counter = m_modifier[e->detail] ? m_modifiersPressed :
                       m_keysPressed;
        if (pressed) {
            counter++;
        } else {
            counter--;
        }

        wasActivity = wasActivity || activity();
    }

    if (!prevActivity && activity()) {
        Q_EMIT keyboardActivityStarted();
    } else if (!activity() && wasActivity) {
        Q_EMIT keyboardActivityFinished();
    }
}
Example #23
0
//
// Modify database parameters
//
void KeychainDatabase::setParameters(const DBParameters &params)
{
	StLock<Mutex> _(common());
    makeUnlocked();
	common().mParams = params;
    common().invalidateBlob();		// invalidate old blobs
    activity();				// (also resets the timeout timer)
	secdebug("KCdb", "%p common %p(%s) set params=(%u,%u)",
		this, &common(), dbName(), params.idleTimeout, params.lockOnSleep);
}
Example #24
0
//
// Return the database blob, recalculating it as needed.
//
DbBlob *KeychainDatabase::blob()
{
	StLock<Mutex> _(common());
    if (!validBlob()) {
        makeUnlocked();			// unlock to get master secret
		encode();				// (re)encode blob if needed
    }
    activity();					// reset timeout
	assert(validBlob());		// better have a valid blob now...
    return mBlob;
}
Example #25
0
//
// Given a "blobbed" key for this database, decode it into its real
// key object and (re)populate its ACL.
//
void KeychainDatabase::decodeKey(KeyBlob *blob, CssmKey &key, void * &pubAcl, void * &privAcl)
{
	StLock<Mutex> _(common());

	if(!blob->isClearText())
		makeUnlocked();							// we need our keys

	common().decodeKeyCore(blob, key, pubAcl, privAcl);
	// memory protocol: pubAcl points into blob; privAcl was allocated
	
    activity();
}
Example #26
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: acknowledge
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void acknowledge(HWND hwnd), takes the parent HWND as an argument.
--
--      RETURNS: void
--
--      NOTES:
--      Sends an acknowledgement packet out on the specified client_port/ip. Only called on UDP transfers.
----------------------------------------------------------------------------------------------------------------------*/
void acknowledge(HWND hwnd){

	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);
	struct sockaddr_in sin;
	int status;
	char ack[ACK_SIZE] = ";ACK;";

	memset(&sin, 0, sizeof(sin));
	sin.sin_family = AF_INET;
	sin.sin_port = htons(atoi(st->client_port));

	if ((sin.sin_addr.s_addr = inet_addr(st->client_send_ip)) == INADDR_NONE)
	{
		activity("Failed to find transfer address\n", EB_STATUSBOX);
		return;
	}

	if ((status = sendto(st->client_socket, ack, ACK_SIZE, 0, (const sockaddr *)&sin, sizeof(sin))) < 0){
		activity("Failed to acknowledge, run before it blows up!\n", EB_STATUSBOX);
	}
}
Example #27
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: receive_acknowledge
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: int receive_acknowledge(HWND hwnd), where hwnd is the HWND of the main parent window.
--
--      RETURNS: int, returns 1 if an acknowledgement is received. 
--
--      NOTES:
--      Checks if the packet received after sending a packet is an "ACK" packet. An ACK packet contains the text ";ACK;".
--		*Yes this may be prone to problems, for our purposes it makes it easier. Can easily be changed.
--		*Only used on the UDP side, provides reliability for the client. TCP already does this for us.
----------------------------------------------------------------------------------------------------------------------*/
int receive_acknowledge(HWND hwnd){
	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);
	char ack[6];
	int status, ackrecv;
	
	if ((status = recvfrom(st->server_socket, ack, ACK_SIZE, 0, 0, 0)) == -1){
		activity("Error in acknowledgement, run before it blows up!\n", EB_STATUSBOX);
	}

	ackrecv = (strcmp(ack, ";ACK;") == 0) ? 1 : 0;
	return ackrecv;
}
Example #28
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: socket_event
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void socket_event(HWND hwnd, WPARAM wParam, LPARAM lParam), where wParam is the socket and lParam is the error message.
--		The hwnd is the parent HWND.
--
--      RETURNS: void
--
--      NOTES:
--      Asynchronously responds to socket accept and read events on the server side of the program. Will reallocate the
--		SocketInfo structure whenever a transfer ends.
----------------------------------------------------------------------------------------------------------------------*/
void socket_event(HWND hwnd, WPARAM wParam, LPARAM lParam){

	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);
	char msg[MAX_SIZE];

	if (WSAGETSELECTERROR(lParam))
	{
		sprintf_s(msg, "WSAGETSELECTERROR %d, connection failed.\n", WSAGETSELECTERROR(lParam));
		activity(msg, EB_STATUSBOX);
		closesocket(st->server_socket);
	}
	else
	{
		switch (WSAGETSELECTEVENT(lParam))
		{
		case FD_ACCEPT:
			accept_data(hwnd, wParam);
			break;
		case FD_READ:
			if (st->protocol == TCP){
				if (read_tcp(hwnd, st->server_socket) >= 1){
					if ((SocketInfo = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL){
						activity("GlobalAlloc() failed with error\n", EB_STATUSBOX);
					}
					SocketInfo->header_received = 0; // transmission ends, program waits for a new header
				}
			}
			else{
				if (read_udp(hwnd, st->server_socket) >= 1){
					if ((SocketInfo = (LPSOCKET_INFORMATION)GlobalAlloc(GPTR, sizeof(SOCKET_INFORMATION))) == NULL){
						activity("GlobalAlloc() failed with error\n", EB_STATUSBOX);
					}
					SocketInfo->header_received = 0;
				}
			}
		}
	}
}
Example #29
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: accept_data
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void accept_data(HWND hwnd, WPARAM wParam)
--
--      RETURNS: void
--
--      NOTES:
--      Accepts a new connection over TCP on the listening socket. Called whenever a FD_ACCEPT message is grabbed from WM_SOCKET.
--		The wParam in this instance is the socket that sent out the FD_ACCEPT request. The HWND belongs to the parent window.
----------------------------------------------------------------------------------------------------------------------*/
void accept_data(HWND hwnd, WPARAM wParam){

	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);

	if ((st->server_socket = accept(wParam, NULL, NULL)) == INVALID_SOCKET)
	{
		activity("Failed to accept() connection.\n", EB_STATUSBOX);
		return;
	}

	setsockopt(st->server_socket, SOL_SOCKET, SO_REUSEADDR, 0, 0);
	WSAAsyncSelect(st->server_socket, hwnd, WM_SOCKET, FD_READ | FD_CLOSE);
	SetClassLongPtr(hwnd, 0, (LONG)st);
}
Example #30
0
/*------------------------------------------------------------------------------------------------------------------
--      FUNCTION: init_client
--
--      DATE: Febuary 6 2014
--      REVISIONS: none
--
--      DESIGNER: Ramzi Chennafi
--      PROGRAMMER: Ramzi Chennafi
--
--      INTERFACE: void init_client(HWND hwnd) , takes the parent HWND as an argument.
--
--      RETURNS: void
--
--      NOTES:
--      Intializes the client, the type of intialization depends on the chosen protocol in the settings. Binds whenever
--		the connection is TCP.
----------------------------------------------------------------------------------------------------------------------*/
void init_client(HWND hwnd){
	DWORD Ret;
	SOCKADDR_IN InternetAddr;
	WSADATA wsaData;
	SETTINGS * st = (SETTINGS*)GetClassLongPtr(hwnd, 0);

	if ((Ret = WSAStartup(0x0202, &wsaData)) != 0){
		activity("WSAStartup failed on client.\n", EB_STATUSBOX);
		return;
	}

	switch(st->protocol){
	case TCP:
		st->client_socket = socket(PF_INET, SOCK_STREAM, 0);
		break;
	case UDP:
		st->server_socket = socket(AF_INET, SOCK_DGRAM, 0);
		if ((st->client_socket = socket(AF_INET, SOCK_DGRAM, 0)) == INVALID_SOCKET){
			activity("Failed to create transfer socket.\n", EB_STATUSBOX);
		}
		
		InternetAddr.sin_family = AF_INET;
		InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
		InternetAddr.sin_port = htons(atoi(st->server_port));

		if (bind(st->server_socket, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR){
			activity("bind() failed on receiving socket.\n", EB_STATUSBOX);
		}
		break;
	}

	SetClassLongPtr(hwnd, 0, (LONG)st);

	if(st->client_socket == INVALID_SOCKET){
		activity("Failed to create receiving socket.\n", EB_STATUSBOX);
	}

	if (st->protocol == UDP){
		activity("UDP Client intialized, ready to transfer.\n", EB_STATUSBOX);
		return;
	}

	InternetAddr.sin_family = AF_INET;
	InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	InternetAddr.sin_port = htons(PORT);

	if (bind(st->client_socket, (PSOCKADDR)&InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR){
		activity("bind() failed on client.\n", EB_STATUSBOX);
	}

	activity("TCP Client intialized, ready to connect.\n", EB_STATUSBOX);
}