-
Notifications
You must be signed in to change notification settings - Fork 0
/
pycoap-client
executable file
·85 lines (63 loc) · 2.19 KB
/
pycoap-client
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
#!/usr/bin/env python3
import py3coap
from py3coap.errors import HandshakeError
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("uri")
parser.add_argument("payload", nargs="?")
parser.add_argument("--ident")
parser.add_argument("--key")
parser.add_argument("--method", default="PUT")
parser.add_argument("-debug", action="store_true")
class MalformedURI(Exception):
pass
class MissingCredentials(Exception):
pass
def select_method(method):
method = method.upper()
methods = {"GET": py3coap.GET, "PUT": py3coap.PUT, "POST": py3coap.POST}
return methods.get(method, py3coap.GET)
if __name__ == "__main__":
result = None
args = parser.parse_args()
if args.debug:
py3coap.setDebugLevel(1)
fullUri = args.uri
uri = fullUri.split("/")
method = select_method(args.method)
try:
if not (uri[0] == "coap:" or uri[0] == "coaps:"):
raise (MalformedURI())
if not uri[1] == "":
raise (MalformedURI("Missing //"))
if not uri[2].find(":") > 0:
raise (MalformedURI("Missing port"))
dest = "/".join(uri[3:])
if uri[0] == "coap:":
if args.payload != None:
result = py3coap.Request(fullUri, args.payload)
else:
result = py3coap.Request(fullUri)
if uri[0] == "coaps:":
if args.ident == None or args.key == None:
raise MissingCredentials
if args.payload != None:
result = py3coap.Request(
fullUri,
payload=args.payload,
method=method,
ident=args.ident,
key=args.key,
)
else:
result = py3coap.Request(
fullUri, method=py3coap.GET, ident=args.ident, key=args.key
)
if result != None:
print("Response: {}".format(result))
except HandshakeError:
print("Connection timed out")
except MissingCredentials:
print("Error: Missing credentials for DTLS-connection!")
except MalformedURI:
print("Error: Malformed uri {0}".format(args.uri))