summaryrefslogtreecommitdiff
path: root/ofAsterisk/src/Asterisk.cpp
blob: 46957cd9035d3bd758ae30b41e98c3f0b7b10d6c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include "Asterisk.h"


//there is no notification that there is someone in the queue
//but there is a status message you can check periodically...

Asterisk::Asterisk()
{
	udpConnection.Create();
	udpConnection.Bind(5000);
	udpConnection.SetNonBlocking(true);
	cmd("ssh 80.93.22.22 'sudo /usr/sbin/asterisk -rx \"database put GAME passcode 1234\"'");
	state=WAITING; //for acknowledge
	printf("Asterisk: created socket and connected to server\n");
}

void Asterisk::startGame(){
	if (state==IDLE) {
		cmd("ssh 80.93.22.22 'sudo /usr/sbin/asterisk -rx \"devstate change Custom:GAME NOT_INUSE\"'");
		printf("Asterisk: attempting to dequeue\n");
		state=STARTING;
	}
}
void Asterisk::endGame(string score){
	if (state==PLAYING) {
		cmd("ssh 80.93.22.22 'sudo /usr/sbin/asterisk -rx \"database put GAME statuscode "+score+"\"'");
		string emsg="ssh 80.93.22.22 'sudo /usr/sbin/asterisk -rx \"hangup request "+playerCode+"\"'";
		printf("%s\n",emsg.c_str());
		cmd(emsg);
		printf("Asterisk: hanging up %s\n",playerCode.c_str());
		state=WAITING;
	}
}
void Asterisk::cmd(string s) {
	file = popen(s.c_str(), "re");
	filenum=fileno(file);
	fcntl(filenum, F_SETFL, O_NONBLOCK); //doesn't seem to work, still pauses
	//pclose(file); //discard the pipe  THIS IS BLOCKING
}

int Asterisk::update(){
	//capture stdin response from popen
	if (state==WAITING||state==STARTING) {
		char buf[1000];
		ssize_t r = read(filenum, buf, 1000);
		//if (r == -1 && errno == EAGAIN)
		    //no data yet
		//else 
		if (r > 0) {
			pclose(file);
			string msg=string(buf);
			//received data is always a command ACKNOWLEDGEMENT
			if (msg.compare("Changing GAME to NOT_INUSE")==0) {
				printf("player dequeued\n");
				state=PLAYING;
			}
			else if (msg.compare(0,5,"gameQ")==0) {
				//queue status message
			}
			else {
				printf("stdin says: %s\n",buf);
				state=IDLE;
			}
		}
	}
	
	//check udp messages, return new keypresses
	char udpMessage[10000];
	udpConnection.Receive(udpMessage,10000);
	string msg=udpMessage;
	if(msg!=""){
		printf("Asterisk: %s\n",msg.c_str());
		if (msg.length()>3) {
			//printf("status msg: %s\n",msg.c_str());
			if (msg.substr(0,5)=="Local") {
				state=PLAYING;
				playerCode=msg.substr(0,msg.length()-1);
				printf("Asterisk: game started: code %s\n",playerCode.c_str());
				return 1000;
			}
			return 0;
		}
		else {
			return ofToInt(msg);
		}
	}
	else return 0;
}

Asterisk::~Asterisk()
{
	pclose(file);
    //dtor
}