/
hologram_network.py
75 lines (61 loc) · 2.53 KB
/
hologram_network.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
#!/usr/bin/env python3
# hologram_network.py - Hologram Python SDK command line interface (CLI) for connect/disconnect interfaces.
#
# Author: Hologram <support@hologram.io>
#
# Copyright 2016 - Hologram (Konekt, Inc.)
#
# LICENSE: Distributed under the terms of the MIT License
from Hologram.CustomCloud import CustomCloud
from Exceptions.HologramError import HologramError
from .hologram_util import VAction
import psutil
help_connect = '''This subcommand establishes a cellular connection.\n
'''
help_disconnect = '''This subcommand brings down a cellular connection.\n
'''
def run_network_connect(args):
cloud = CustomCloud(None, network='cellular')
cloud.network.disable_at_sockets_mode()
res = cloud.network.connect()
if res:
print('PPP session started')
else:
print('Failed to start PPP')
def run_network_disconnect(args):
print('Checking for existing PPP sessions')
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name'])
except:
raise HologramError('Failed to check for existing PPP sessions')
if 'pppd' in pinfo['name']:
print('Found existing PPP session on pid: %s' % pinfo['pid'])
print('Killing pid %s now' % pinfo['pid'])
process = psutil.Process(pinfo['pid'])
process.terminate()
process.wait()
_run_handlers = {
'network_connect': run_network_connect,
'network_disconnect': run_network_disconnect
}
# EFFECTS: Parses the CLI arguments as options to the hologram modem subcommand.
def parse_hologram_network_args(parser):
# Create a subparser
subparsers = parser.add_subparsers(title='subcommands',
dest='network subcommand',
required=True)
# Connect
parser_connect = subparsers.add_parser('connect', help=help_connect)
parser_connect.set_defaults(command_selected='network_connect')
parser_connect.add_argument('-v', nargs='?', action=VAction, dest='verbose', required=False)
# Disconnect
parser_disconnect = subparsers.add_parser('disconnect', help=help_disconnect)
parser_disconnect.set_defaults(command_selected='network_disconnect')
parser_disconnect.add_argument('-v', nargs='?', action=VAction, dest='verbose', required=False)
# EFFECTS: Runs the hologram modem interfaces.
def run_hologram_network(args):
if args['command_selected'] not in _run_handlers:
raise Exception('Internal CLI error: Invalid command_selected value')
else:
_run_handlers[args['command_selected']](args)