-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcs_message.py
102 lines (76 loc) · 2.62 KB
/
cs_message.py
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
95
96
97
98
99
100
101
102
import sys
"""
client-server messaging facility
This module provides the ability to send to and receive messages from a
client attached to a serial port. A message is a string of ascii
characters terminated with a new-line, as understood by the TextSerial
interface.
It also provides a diagnostic message tunnel capability. Any message
coming from the client that begins with "D" is intercepted and printed
on stderr (asuming logging in on).
Combined with the dprintf library for the arduino, this enables the
client code to supply diagnostic information as if it was connected to
it's own stderr.
"""
# when True this generates output to stderr, when False does not.
# modify with set_loggin, query with get logging
logging = True
def set_logging(new):
"""
Set logging on True, or off False.
Return the previous value of the logging state.
"""
global logging
old = logging
logging = new
return old
def get_logging():
global logging
return logging
def escape_nl(msg):
"""
It's nice to know if we actually sent a complete line ending in
\n, so escape it for display.
"""
if msg != '' and msg[-1] == "\n":
return msg[:-1] + "\\n"
return msg
def log_msg(msg):
"""
If logging is on, send this message to stderr, making sure to
show if there was a new line. The message is prefixed with "L ", to
indicate that it was a logging message, not a message received from
the client.
Flush the output buffer so we don't lose any of the message.
"""
global logging
if logging:
print("L |{}|".format(escape_nl(msg)), file=sys.stderr, flush=True)
def send_msg_to_client(channel, msg):
"""
Send a message to the client over channel, and log it if
logging on. msg should not end with a new line, as one will be
added by the print. Flush to ensure complete line is sent.
"""
print(msg, file=channel, flush=True)
if logging:
log_msg(msg)
def receive_msg_from_client(channel):
"""
Wait for a message from the client. If a diagnostic 'D' type
message comes in, intercept it, print it on stderr, and wait
for a proper one to arrive.
The message is returned unchanged, terminating new line included.
"""
global logging
while True:
msg = next(channel)
# If message begins with a D, then its a diagnostic message
# from the client, and should be sent to stderr and ignored.
if msg.strip()[:1] == "D":
if logging:
print(escape_nl(msg), file=sys.stderr, flush=True)
continue
else:
break
return msg