File: interactive.py

package info (click to toggle)
galileo 0.5.1-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 392 kB
  • ctags: 578
  • sloc: python: 3,462; xml: 23; makefile: 14
file content (229 lines) | stat: -rw-r--r-- 5,228 bytes parent folder | download | duplicates (2)
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
"""\
This is the implementation of the interactive mode

This is the same idea as ifitbit I wrote for libfitbit some years ago

https://bitbucket.org/benallard/libfitbit/src/tip/python/ifitbit.py?at=default

"""

from __future__ import print_function

try:
    # Override the input from python2 with raw_input
    input = raw_input
except NameError:
    pass

#---------------------------
# The engine

import readline
import traceback
import sys

exit = None

cmds = {}
helps = {}

def command(cmd, help):
    def decorator(fn):
        cmds[cmd] = fn
        helps[cmd] = help
        def wrapped(*args):
            return fn(*args)
        return wrapped
    return decorator


@command('x', "Quit")
def quit():
    print('Bye !')
    global exit
    exit = True


@command('?', 'Print possible commands')
def print_help():
    for cmd in sorted(helps.keys()):
        print('%s\t%s' % (cmd, helps[cmd]))
    print("""Note:
 - You can enter multiple commands separated by ';'
 - To establish a link with the tracker, enter the following command:
      c ; d ; l ; tx 1 ; al
""")

def main(config):
    global exit
    exit = False
    print_help()
    while not exit:
        orders = input('> ').strip()
        if ';' in orders:
            orders = orders.split(';')
        else:
            orders = [orders]
        for order in orders:
            order = order.strip().split(' ')
            try:
                f = cmds[order[0]]
            except KeyError:
                if order[0] == '':
                    continue
                print('Command %s not known' % order[0])
                print_help()
                continue
            try:
                f(*order[1:])
            except TypeError as te:
                print("Wrong number of argument given: %s" % te)
            except Exception as e:
                # We need that to be able to close the connection nicely
                print("BaD bAd BAd", e)
                traceback.print_exc(file=sys.stdout)
                return


#---------------------------
# The commands

from .dongle import FitBitDongle, CM, DM
from .tracker import FitbitClient
from .utils import x2a

import uuid

dongle = None
fitbit = None
trackers = []
tracker = None

@command('c', "Connect")
def connect():
    global dongle
    dongle = FitBitDongle(0)  # No DataRing needed
    if not dongle.setup():
        print("No dongle connected, aborting")
        quit()
    global fitbit
    fitbit = FitbitClient(dongle)
    print('Ok')


def needfitbit(fn):
    def wrapped(*args):
        if dongle is None:
            print("No connection, connect (c) first")
            return
        return fn(*args)
    return wrapped

@command('->', "Send on the control channel")
@needfitbit
def send_ctrl(INS, *payload):
    if payload:
        payload = x2a(' '.join(payload))
    else:
        payload = []
    m = CM(int(INS, 16), payload)
    dongle.ctrl_write(m)

@command('<-', "Receive once on the control channel")
@needfitbit
def receive_ctrl(param='1'):
    if param == '-':
        goOn = True
        while goOn:
            goOn = dongle.ctrl_read() is not None
    else:
        for i in range(int(param)):
            dongle.ctrl_read()

@command('=>', "Send on the control channel")
@needfitbit
def send_data(*payload):
    m = DM(x2a(' '.join(payload)))
    dongle.data_write(m)

@command('<=', "Receive once on the control channel")
@needfitbit
def receive_data(param='1'):
    if param == '-':
        goOn = True
        while goOn:
            goOn = dongle.data_read() is not None
    else:
        for i in range(int(param)):
            dongle.data_read()

@command('d', "Discovery")
@needfitbit
def discovery(UUID="{ADAB0000-6E7D-4601-BDA2-BFFAA68956BA}"):
    UUID = uuid.UUID(UUID)
    global trackers
    trackers = [t for t in fitbit.discover(UUID)]


def needtrackers(fn):
    def wrapped(*args):
        if not trackers:
            print("No trackers, run a discovery (d) first")
            return
        return fn(*args)
    return wrapped

@command('l', "establishLink")
@needtrackers
def establishLink(idx='0'):
    global tracker
    tracker = trackers[int(idx)]
    if fitbit.establishLink(tracker):
        print('Ok')
    else:
        tracker = None

@command('L', "ceaseLink")
@needfitbit
def ceaseLink():
    if not fitbit.ceaseLink():
        print('Bad')
    else:
        print('Ok')

def needtracker(fn):
    def wrapped(*args):
        if tracker is None:
            print("No tracker, establish a Link (l) first")
            return
        return fn(*args)
    return wrapped

@command('tx', "toggle Tx Pipe")
@needfitbit
def toggleTxPipe(on):
    if fitbit.toggleTxPipe(bool(int(on))):
        print('Ok')

@command('al', "initialise airLink")
@needtracker
def initialiseAirLink():
    if fitbit.initializeAirlink(tracker):
        print('Ok')

@command('AL', "terminate airLink")
@needfitbit
def terminateairLink():
    if fitbit.terminateAirlink():
        print('Ok')

@command('D', 'getDump')
@needfitbit
def getDump(type="13"):
    fitbit.getDump(int(type))

@command('R', 'uploadResponse')
@needfitbit
def uploadResponse(*response):
    response = x2a(' '.join(response))
    fitbit.uploadResponse(response)