root / trunk / code / projects / colonet / ColonetClient / Commands.cpp @ 13
History | View | Annotate | Download (2.25 KB)
1 |
/**
|
---|---|
2 |
*
|
3 |
* @author Jason Knichel
|
4 |
*
|
5 |
* 3/22/07
|
6 |
*/
|
7 |
|
8 |
#include <stdio.h> |
9 |
#include <string.h> |
10 |
#include <ctype.h> |
11 |
#include "includes/Client.h" |
12 |
#include "includes/Commands.h" |
13 |
|
14 |
void Commands::printUsage()
|
15 |
{ |
16 |
printf("\nAvailable commands:\n");
|
17 |
printf("buzzer\n");
|
18 |
printf("lcd\n");
|
19 |
printf("type \"help <command>\" for more information\n\n");
|
20 |
} |
21 |
|
22 |
int Commands::parseCommand(char * command, Server server) |
23 |
{ |
24 |
if (!command)
|
25 |
return -1; |
26 |
|
27 |
if (strlen(command) > MAX_INPUT_LENGTH)
|
28 |
return -1; |
29 |
|
30 |
char tempCommand[MAX_INPUT_LENGTH];
|
31 |
strcpy(tempCommand, command); |
32 |
char tokens[MAX_TOKENS][MAX_TOKEN_SIZE];
|
33 |
int numTokens = 0; |
34 |
if ((numTokens = tokenizeCommand(tempCommand, tokens)) < 1) |
35 |
{ |
36 |
return -1; |
37 |
} |
38 |
|
39 |
if (strcmp(tokens[0], "help") == 0) |
40 |
{ |
41 |
if (numTokens == 1) |
42 |
{ |
43 |
printUsage(); |
44 |
return 0; |
45 |
} |
46 |
|
47 |
if (strcmp(tokens[1], "buzzer") == 0) |
48 |
{ |
49 |
buzzer.printUsage(); |
50 |
} |
51 |
else if (strcmp(tokens[1], "lcd") == 0) |
52 |
{ |
53 |
lcd.printUsage(); |
54 |
} |
55 |
} |
56 |
else if (strcmp(tokens[0], "buzzer") == 0) |
57 |
{ |
58 |
if (buzzer.parseCommand(tokens, numTokens, server) < 0) |
59 |
{ |
60 |
return -1; |
61 |
} |
62 |
} |
63 |
else if (strcmp(tokens[0], "lcd") == 0) |
64 |
{ |
65 |
if (lcd.parseCommand(tokens, numTokens, server) < 0) |
66 |
{ |
67 |
return -1; |
68 |
} |
69 |
} |
70 |
else
|
71 |
{ |
72 |
printf("Invalid command.\n");
|
73 |
} |
74 |
|
75 |
return 0; |
76 |
} |
77 |
|
78 |
int tokenizeCommand(char* command, |
79 |
char tokens[MAX_TOKENS][MAX_TOKEN_SIZE])
|
80 |
{ |
81 |
char* nextToken = command;
|
82 |
char* endToken = NULL; |
83 |
int numTokens = 0; |
84 |
|
85 |
if (!command) {
|
86 |
return -1; |
87 |
} |
88 |
|
89 |
while ((endToken = strstr(nextToken, " "))) { |
90 |
*endToken = '\0';
|
91 |
|
92 |
if (strlen(nextToken) > MAX_TOKEN_SIZE-1) { |
93 |
return -1; |
94 |
} |
95 |
|
96 |
strcpy(tokens[numTokens], nextToken); |
97 |
|
98 |
numTokens++; |
99 |
nextToken = endToken + 1;
|
100 |
|
101 |
while (isspace(*nextToken) && *nextToken != '\0') { |
102 |
nextToken++; |
103 |
} |
104 |
} |
105 |
|
106 |
if (endToken == NULL && *nextToken != '\0') { |
107 |
int nextTokenLen = strlen(nextToken);
|
108 |
if (nextTokenLen > MAX_TOKEN_SIZE-1) { |
109 |
return -1; |
110 |
} |
111 |
if (nextToken[nextTokenLen-1] == '\n') |
112 |
nextToken[nextTokenLen-1] = '\0'; |
113 |
|
114 |
strcpy(tokens[numTokens], nextToken); |
115 |
|
116 |
numTokens++; |
117 |
} |
118 |
|
119 |
return numTokens;
|
120 |
} |