Create a command line interface

This commit is contained in:
Juhani Krekelä 2019-07-14 23:13:39 +03:00
parent 0443954c26
commit c2d021534f
2 changed files with 30 additions and 22 deletions

View File

@ -407,11 +407,9 @@ void writeallx(int fd, const void *buf, size_t length) {
}
void writeallx_u16(int fd, uint16_t value) {
// Write these little-endian (native for x86) instead of network
// byte order
unsigned char buf[2];
buf[0] = value & 0xff;
buf[1] = value >> 8;
buf[0] = value >> 8;
buf[1] = value & 0xff;
writeallx(fd, buf, sizeof(buf));
}
@ -469,11 +467,11 @@ void read_command(void) {
if (cmd == 'q') {
running = false;
} else if (cmd == 's') {
} else if (cmd == 'r') {
unsigned char mac[6];
readallx(0, mac, sizeof(mac));
send_status_request(mac);
} else if (cmd == 'S') {
} else if (cmd == 's') {
read_status();
} else if (cmd == 'm') {
read_message();

View File

@ -21,7 +21,7 @@ def readall(f, length):
def readall_u16(f):
u16_bytes = readall(f, 2)
return (u16_bytes[1] << 8) | u16_bytes[0]
return (u16_bytes[0] << 8) | u16_bytes[1]
def parse_mac(text):
parts = text.split(':')
@ -48,22 +48,34 @@ def format_status(status):
else:
raise ValueError('Unknown status %i' % status)
def handle_user_command(backend, command):
if command == 's':
mac = parse_mac(input('mac> '))
writeall(backend, b's' + mac)
def send_message(backend, mac, message):
encoded = message.encode('utf-8')
writeall(backend, b'm' + mac + bytes([len(encoded) >> 8, len(encoded) & 0xff]) + encoded)
elif command == 'i':
mac = parse_mac(input('mac> '))
writeall(backend, b'i' + mac)
def send_status_request(backend, mac):
writeall(backend, b'r' + mac)
elif command == 'm':
mac = parse_mac(input('mac> '))
message = input('message> ').encode('utf-8')
writeall(backend, b'm' + mac + bytes([len(message) >> 8, len(message) & 0xff]) + message)
def handle_user_command(backend, line):
if len(line) > 0 and line[0] == '/':
command, _, rest = line.partition(' ')
if command == '/msg':
# Send message to target
mac_str, _, message = rest.partition(' ')
mac = parse_mac(mac_str)
send_message(backend, mac, message)
elif command == '/status':
# Request status
mac = parse_mac(rest)
send_status_request(backend, mac)
else:
# Display usage
print('/msg <MAC> <message>; /status <MAC>')
else:
print('s - request status, m - send message, ^D - quit')
# Display usage
print('/msg <MAC> <message>; /status <MAC>')
def eventloop(proc):
# Create unbuffered version of stdin
@ -107,7 +119,7 @@ def eventloop(proc):
elif event_type == b'A':
# ACK not received (and message send failed)
print('(ack failed)')
print('(ack failed)') #debg
elif event_type == b'm':
# Message received
@ -165,8 +177,6 @@ def main():
print('Own mac: %s' % format_mac(mac))
print('s - request status, m - send message, ^D - quit')
eventloop(proc)
proc.wait()