Process status messages

This commit is contained in:
Juhani Krekelä 2019-07-13 20:51:15 +03:00
parent ac1fbb9bd0
commit eb2842efeb
2 changed files with 41 additions and 32 deletions

View File

@ -413,10 +413,11 @@ void readallx(int fd, unsigned char *buf, size_t length) {
}
}
void writeallx(int fd, unsigned char *buf, size_t length) {
void writeallx(int fd, const void *buf, size_t length) {
const unsigned char *cbuf = buf;
size_t completed = 0;
while (completed < length) {
ssize_t res = write(fd, &buf[completed], length - completed);
ssize_t res = write(fd, &cbuf[completed], length - completed);
if (res == -1) {
err(1, "write");
}
@ -658,36 +659,18 @@ void handle_status(const unsigned char source_mac[6], const unsigned char *data,
return;
}
char mac[18];
format_mac(source_mac, mac);
// Type of event: Status
writeallx(1, "s", 1);
if (printf("%s status: ", mac) == -1) {
err(1, "printf");
}
// MAC
writeallx(1, source_mac, 6);
if (status == EMS_UNAVAILABLE) {
if (printf("(unavailable) ") == -1) {
err(1, "printf");
}
} else if (status == EMS_OFFLINE) {
if (printf("(offline) ") == -1) {
err(1, "printf");
}
}
// Status
writeallx(1, &status, 1);
for (size_t i = 0; i < (size_t)nick_length; i++) {
if (putchar(nick[i]) == EOF) {
err(1, "putchar");
}
}
if (putchar('\n') == EOF) {
err(1, "putchar");
}
if (fflush(stdout) == EOF) {
err(1, "fflush");
}
// Nick
writeallx(1, &nick_length, 1);
writeallx(1, nick, nick_length);
}
void handle_msgid(const unsigned char source_mac[6], const unsigned char *data, size_t data_length) {

View File

@ -97,6 +97,16 @@ def parse_mac(text):
def format_mac(mac):
return ':'.join(mac[i:i+1].hex() for i in range(len(mac)))
def format_status(status):
if status == 0:
return 'available'
elif status == 1:
return 'unavailable'
elif status == 2:
return 'offline'
else:
raise ValueError('Unknown status %i' % status)
class PollBasedThread(threading.Thread):
def run(self):
while True:
@ -170,9 +180,25 @@ class Backend(PollBasedThread):
raise Exception('Unreachable')
elif fd == self.proc.stdout.fileno() and event & select.POLLIN:
data = self.proc.stdout.read(1024)
sys.stdout.buffer.write(data)
sys.stdout.flush()
event_type = readall(self.proc.stdout, 1)
if event_type == b's':
# Status
source_mac = readall(self.proc.stdout, 6)
status, = readall(self.proc.stdout, 1)
nick_length, = readall(self.proc.stdout, 1)
nick = readall(self.proc.stdout, nick_length,)
print('%s (%s) ~%s' % (format_mac(source_mac), format_status(status), nick.decode('utf-8')))
else:
# Not sth we handle yet
data = self.proc.stdout.read(1023)
if data is None:
data = b'[!] ' + event_type
else:
data = b'[!] ' + event_type + data
sys.stdout.buffer.write(data)
sys.stdout.flush()
elif fd == self.proc.stdout.fileno() and event & select.POLLHUP:
print('Backend exited')