Subversion Repositories freemyipod

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
56 benedikt93 1
#!/usr/bin/env python
2
#
3
#
171 farthen 4
#    Copyright 2010 TheSeven, benedikt93, Farthen
56 benedikt93 5
#
6
#
427 farthen 7
#    This file is part of emCORE.
56 benedikt93 8
#
427 farthen 9
#    emCORE is free software: you can redistribute it and/or
56 benedikt93 10
#    modify it under the terms of the GNU General Public License as
11
#    published by the Free Software Foundation, either version 2 of the
12
#    License, or (at your option) any later version.
13
#
427 farthen 14
#    emCORE is distributed in the hope that it will be useful,
56 benedikt93 15
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
16
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
17
#    See the GNU General Public License for more details.
18
#
19
#    You should have received a copy of the GNU General Public License
427 farthen 20
#    along with emCORE.  If not, see <http://www.gnu.org/licenses/>.
56 benedikt93 21
#
22
#
23
 
402 farthen 24
"""
427 farthen 25
    emCORE client library.
26
    Provides functions to communicate with emCORE devices via the USB bus.
402 farthen 27
"""
28
 
56 benedikt93 29
import sys
30
import struct
171 farthen 31
import usb.core
427 farthen 32
import libemcoredata
56 benedikt93 33
 
401 farthen 34
from misc import Logger, Bunch, Error, gethwname
394 farthen 35
from functools import wraps
36
 
171 farthen 37
class ArgumentError(Error):
38
    pass
56 benedikt93 39
 
171 farthen 40
class DeviceNotFoundError(Error):
41
    pass
56 benedikt93 42
 
171 farthen 43
class DeviceError(Error):
44
    pass
56 benedikt93 45
 
171 farthen 46
class SendError(Error):
47
    pass
56 benedikt93 48
 
171 farthen 49
class ReceiveError(Error):
50
    pass
56 benedikt93 51
 
52
 
398 farthen 53
def command(timeout = None, target = None):
394 farthen 54
    """
55
        Decorator for all commands.
56
        It adds the "timeout" variable to all commands.
57
        It also provides the possibility to set the timeout directly in the decorator.
58
        It also includes some dirty hacks to not learn from.
59
    """
60
    time = timeout # dirty hack because otherwise it would raise a scoping problem.
61
                   # The reason is probably because I suck but I can't find any good explanation of this.
62
    def decorator(func):
63
        @wraps(func)
64
        def wrapper(*args, **kwargs):
398 farthen 65
            self = args[0] # little cheat as it expects self being always the first argument
394 farthen 66
            # precommand stuff
398 farthen 67
            if target is not None:
68
                if self.lib.dev.hwtypeid != target:
69
                    raise DeviceError("Wrong device for target-specific command. Expected \'" + gethwname(target) + "\' but got \'" + gethwname(self.lib.dev.hwtypeid) + "\'")
394 farthen 70
            timeout = None
71
            if "timeout" in kwargs.keys():
72
                timeout = kwargs['timeout']
73
            elif time is not None:
74
                timeout = time
75
            if timeout is not None:
76
                oldtimeout = self.lib.dev.timeout
77
                self.lib.dev.timeout = timeout
78
            # function call
79
            ret = func(*args)
80
            # postcommand stuff
81
            if timeout is not None:
82
                self.lib.dev.timeout = oldtimeout
83
            return ret
396 farthen 84
        func._command = True
85
        wrapper.func = func
394 farthen 86
        return wrapper
87
    return decorator
88
 
89
 
427 farthen 90
class Emcore(object):
176 farthen 91
    """
427 farthen 92
        Class for all emcore functions.
394 farthen 93
        They all get the "@command()" decorator.
94
        This decorator has a timeout variable that can be set to change the
95
        device timeout for the duration of the function.
96
        It also adds a "timeout" argument to every function to access this
97
        feature from external. So DON'T EVER use a parameter called 'timeout'
98
        in your commands. Variables are ok.
176 farthen 99
    """
401 farthen 100
    def __init__(self, loglevel = 2, logtarget = "stdout", logfile = "tools.log"):
101
        self.logger = Logger(loglevel, logtarget, logfile)
427 farthen 102
        self.logger.debug("Initializing Emcore object\n")
401 farthen 103
        self.lib = Lib(self.logger)
343 farthen 104
 
105
        self.getversioninfo()
440 farthen 106
        if self.lib.dev.swtypeid != 2:
107
            if self.lib.dev.swtypeid == 1:
108
                raise DeviceError("Connected to emBIOS. emBIOS is not supported by libemcore")
109
            else:
110
                raise DeviceError("Connected to unknown software type. Exiting")
111
 
176 farthen 112
        self.getpacketsizeinfo()
343 farthen 113
        self.getusermemrange()
56 benedikt93 114
 
171 farthen 115
    @staticmethod
116
    def _alignsplit(addr, size, blksize, align):
177 farthen 117
        if size <= blksize: return (size, 0, 0)
171 farthen 118
        end = addr + size
119
        if addr & (align - 1):
120
            bodyaddr = (addr + min(size, blksize)) & ~(align - 1)
121
        else: bodyaddr = addr
122
        headsize = bodyaddr - addr
123
        if (size - headsize) & (align - 1):
124
            tailaddr = (end - min(end - bodyaddr, blksize) + align - 1) & ~(align - 1)
125
        else: tailaddr = end
126
        tailsize = end - tailaddr
127
        return (headsize, tailaddr - bodyaddr, tailsize)
56 benedikt93 128
 
394 farthen 129
    @command()
178 farthen 130
    def _readmem(self, addr, size):
131
        """ Reads the memory from location 'addr' with size 'size'
132
            from the device.
133
        """
134
        resp = self.lib.monitorcommand(struct.pack("IIII", 4, addr, size, 0), "III%ds" % size, (None, None, None, "data"))
135
        return resp.data
394 farthen 136
 
137
    @command()
178 farthen 138
    def _writemem(self, addr, data):
139
        """ Writes the data in 'data' to the location 'addr'
140
            in the memory of the device.
141
        """
142
        return self.lib.monitorcommand(struct.pack("IIII%ds" % len(data), 5, addr, len(data), 0, data), "III", (None, None, None))
143
 
394 farthen 144
    @command()
178 farthen 145
    def _readdma(self, addr, size):
146
        """ Reads the memory from location 'addr' with size 'size'
147
            from the device. This uses DMA and the data in endpoint.
148
        """
149
        self.lib.monitorcommand(struct.pack("IIII", 6, addr, size, 0), "III", (None, None, None))
150
        return struct.unpack("%ds" % size, self.lib.dev.din(size))[0]
151
 
394 farthen 152
    @command()
178 farthen 153
    def _writedma(self, addr, data):
154
        """ Writes the data in 'data' to the location 'addr'
155
            in the memory of the device. This uses DMA and the data out endpoint.
156
        """
157
        self.lib.monitorcommand(struct.pack("IIII", 7, addr, len(data), 0), "III", (None, None, None))
158
        return self.lib.dev.dout(data)
159
 
394 farthen 160
    @command()
171 farthen 161
    def getversioninfo(self):
427 farthen 162
        """ This returns the emCORE version and device information. """
342 farthen 163
        resp = self.lib.monitorcommand(struct.pack("IIII", 1, 0, 0, 0), "IBBBBI", ("revision", "majorv", "minorv", "patchv", "swtypeid", "hwtypeid"))
164
        self.lib.dev.version.revision = resp.revision
165
        self.lib.dev.version.majorv = resp.majorv
166
        self.lib.dev.version.minorv = resp.minorv
167
        self.lib.dev.version.patchv = resp.patchv
401 farthen 168
        self.logger.debug("Device Software Type ID = " + str(resp.swtypeid) + "\n")
342 farthen 169
        self.lib.dev.swtypeid = resp.swtypeid
401 farthen 170
        self.logger.debug("Device Hardware Type ID = " + str(resp.hwtypeid) + "\n")
342 farthen 171
        self.lib.dev.hwtypeid = resp.hwtypeid
172
        return resp
56 benedikt93 173
 
394 farthen 174
    @command()
171 farthen 175
    def getpacketsizeinfo(self):
427 farthen 176
        """ This returns the emCORE max packet size information.
171 farthen 177
            It also sets the properties of the device object accordingly.
178
        """
179
        resp = self.lib.monitorcommand(struct.pack("IIII", 1, 1, 0, 0), "HHII", ("coutmax", "cinmax", "doutmax", "dinmax"))
401 farthen 180
        self.logger.debug("Device cout packet size limit = " + str(resp.coutmax) + "\n")
343 farthen 181
        self.lib.dev.packetsizelimit.cout = resp.coutmax
401 farthen 182
        self.logger.debug("Device cin packet size limit = " + str(resp.cinmax) + "\n")
343 farthen 183
        self.lib.dev.packetsizelimit.cin = resp.cinmax
401 farthen 184
        self.logger.debug("Device din packet size limit = " + str(resp.doutmax) + "\n")
343 farthen 185
        self.lib.dev.packetsizelimit.din = resp.dinmax
401 farthen 186
        self.logger.debug("Device dout packet size limit = " + str(resp.dinmax) + "\n")
343 farthen 187
        self.lib.dev.packetsizelimit.dout = resp.doutmax
171 farthen 188
        return resp
56 benedikt93 189
 
394 farthen 190
    @command()
171 farthen 191
    def getusermemrange(self):
192
        """ This returns the memory range the user has access to. """
342 farthen 193
        resp = self.lib.monitorcommand(struct.pack("IIII", 1, 2, 0, 0), "III", ("lower", "upper", None))
401 farthen 194
        self.logger.debug("Device user memory = 0x%x - 0x%x\n" % (resp.lower, resp.upper))
342 farthen 195
        self.lib.dev.usermem.lower = resp.lower
196
        self.lib.dev.usermem.upper = resp.upper
197
        return resp
56 benedikt93 198
 
394 farthen 199
    @command()
171 farthen 200
    def reset(self, force=False):
201
        """ Reboot the device """
202
        if force:
203
            return self.lib.monitorcommand(struct.pack("IIII", 2, 0, 0, 0))
204
        else:
205
            return self.lib.monitorcommand(struct.pack("IIII", 2, 1, 0, 0), "III", (None, None, None))
56 benedikt93 206
 
394 farthen 207
    @command()
171 farthen 208
    def poweroff(self, force=False):
209
        """ Powers the device off. """
210
        if force:
211
            return self.lib.monitorcommand(struct.pack("IIII", 3, 0, 0, 0))
212
        else:
213
            return self.lib.monitorcommand(struct.pack("IIII", 3, 1, 0, 0), "III", (None, None, None))
56 benedikt93 214
 
394 farthen 215
    @command()
171 farthen 216
    def read(self, addr, size):
217
        """ Reads the memory from location 'addr' with size 'size'
218
            from the device. This cares about too long packages
219
            and decides whether to use DMA or not.
220
        """
343 farthen 221
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
222
        din_maxsize = self.lib.dev.packetsizelimit.din
171 farthen 223
        data = ""
224
        (headsize, bodysize, tailsize) = self._alignsplit(addr, size, cin_maxsize, 16)
225
        if headsize != 0:
178 farthen 226
            data += self._readmem(addr, headsize)
171 farthen 227
            addr += headsize
228
        while bodysize > 0:
229
            if bodysize >= 2 * cin_maxsize:
230
                readsize = min(bodysize, din_maxsize)
178 farthen 231
                data += self._readdma(addr, readsize)
171 farthen 232
            else:
233
                readsize = min(bodysize, cin_maxsize)
178 farthen 234
                data += self._readmem(addr, readsize)
171 farthen 235
            addr += readsize
236
            bodysize -= readsize
237
        if tailsize != 0:
178 farthen 238
            data += self._readmem(addr, tailsize)
171 farthen 239
        return data
56 benedikt93 240
 
394 farthen 241
    @command()
171 farthen 242
    def write(self, addr, data):
243
        """ Writes the data in 'data' to the location 'addr'
244
            in the memory of the device. This cares about too long packages
245
            and decides whether to use DMA or not.
246
        """
343 farthen 247
        cout_maxsize = self.lib.dev.packetsizelimit.cout - self.lib.headersize
248
        dout_maxsize = self.lib.dev.packetsizelimit.dout
171 farthen 249
        (headsize, bodysize, tailsize) = self._alignsplit(addr, len(data), cout_maxsize, 16)
250
        offset = 0
251
        if headsize != 0:
178 farthen 252
            self._writemem(addr, data[offset:offset+headsize])
171 farthen 253
            offset += headsize
254
            addr += headsize
255
        while bodysize > 0:
256
            if bodysize >= 2 * cout_maxsize:
257
                writesize = min(bodysize, dout_maxsize)
178 farthen 258
                self._writedma(addr, data[offset:offset+writesize])
171 farthen 259
            else:
260
                writesize = min(bodysize, cout_maxsize)
178 farthen 261
                self._writemem(addr, data[offset:offset+writesize])
171 farthen 262
            offset += writesize
263
            addr += writesize
264
            bodysize -= writesize
265
        if tailsize != 0:
178 farthen 266
            self._writemem(addr, data[offset:offset+tailsize])
171 farthen 267
        return data
56 benedikt93 268
 
394 farthen 269
    @command()
442 farthen 270
    def upload(self, data):
271
        """ Allocates memory of the size of 'data' and uploads 'data' to that memory region.
272
            Returns the address where 'data' is stored
273
        """
274
        addr = self.malloc(len(data))
275
        self.logger.debug("Uploading %d bytes to 0x%x\n" % (len(data), addr))
276
        self.write(addr, data)
277
        return addr
278
 
279
    @command()
173 farthen 280
    def readstring(self, addr, maxlength = 256):
281
        """ Reads a zero terminated string from memory 
282
            Reads only a maximum of 'maxlength' chars.
283
        """
343 farthen 284
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
173 farthen 285
        string = ""
286
        while (len(string) < maxlength or maxlength < 0):
178 farthen 287
            data = self._readmem(addr, min(maxlength - len(string), cin_maxsize))
173 farthen 288
            length = data.find("\0")
289
            if length >= 0:
290
                string += data[:length]
291
                break
292
            else:
293
                string += data
294
            addr += cin_maxsize
295
        return string
296
 
394 farthen 297
    @command()
171 farthen 298
    def i2cread(self, index, slaveaddr, startaddr, size):
299
        """ Reads data from an i2c slave """
236 farthen 300
        data = ""
301
        for i in range(size):
302
            resp = self.lib.monitorcommand(struct.pack("IBBBBII", 8, index, slaveaddr, startaddr + i, 1, 0, 0), "III1s", (None, None, None, "data"))
303
            data += resp.data
304
        return data
56 benedikt93 305
 
394 farthen 306
    @command()
171 farthen 307
    def i2cwrite(self, index, slaveaddr, startaddr, data):
308
        """ Writes data to an i2c slave """
176 farthen 309
        size = len(data)
310
        if size > 256 or size < 1:
341 farthen 311
            raise ArgumentError("Size must be a number between 1 and 256")
176 farthen 312
        if size == 256:
313
            size = 0
215 theseven 314
        return self.lib.monitorcommand(struct.pack("IBBBBII%ds" % size, 9, index, slaveaddr, startaddr, size, 0, 0, data), "III", (None, None, None))
56 benedikt93 315
 
394 farthen 316
    @command()
176 farthen 317
    def usbcread(self):
318
        """ Reads one packet with the maximal cin size """
343 farthen 319
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
176 farthen 320
        resp = self.lib.monitorcommand(struct.pack("IIII", 10, cin_maxsize, 0, 0), "III%ds" % cin_maxsize, ("validsize", "buffersize", "queuesize", "data"))
321
        resp.data = resp.data[:resp.validsize]
322
        resp.maxsize = cin_maxsize
323
        return resp
56 benedikt93 324
 
394 farthen 325
    @command()
171 farthen 326
    def usbcwrite(self, data):
327
        """ Writes data to the USB console """
343 farthen 328
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
176 farthen 329
        size = len(data)
330
        while len(data) > 0:
331
            writesize = min(cin_maxsize, len(data))
332
            resp = self.lib.monitorcommand(struct.pack("IIII%ds" % writesize, 11, writesize, 0, 0, data[:writesize]), "III", ("validsize", "buffersize", "freesize"))
333
            data = data[resp.validsize:]
334
        return size
56 benedikt93 335
 
394 farthen 336
    @command()
176 farthen 337
    def cread(self, bitmask=0x1):
338
        """ Reads one packet with the maximal cin size from the device consoles
171 farthen 339
            identified with the specified bitmask
340
        """
343 farthen 341
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
217 theseven 342
        resp = self.lib.monitorcommand(struct.pack("IIII", 13, bitmask, cin_maxsize, 0), "III%ds" % cin_maxsize, ("size", None, None))
176 farthen 343
        resp.data = resp.data[size:]
344
        resp.maxsize = cin_maxsize
345
        return resp
394 farthen 346
 
347
    @command()
176 farthen 348
    def cwrite(self, data, bitmask=0x1):
171 farthen 349
        """ Writes data to the device consoles 
350
            identified with the specified bitmask.
351
        """
343 farthen 352
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
176 farthen 353
        size = len(data)
354
        while len(data) > 0:
355
            writesize = min(cin_maxsize, len(data))
217 theseven 356
            resp = self.lib.monitorcommand(struct.pack("IIII%ds" % writesize, 12, bitmask, writesize, 0, data[:writesize]), "III", (None, None, None))
176 farthen 357
            data = data[writesize:]
358
        return size
56 benedikt93 359
 
394 farthen 360
    @command()
171 farthen 361
    def cflush(self, bitmask):
362
        """ Flushes the consoles specified with 'bitmask' """
363
        return self.lib.monitorcommand(struct.pack("IIII", 14, bitmask, 0, 0), "III", (None, None, None))
56 benedikt93 364
 
394 farthen 365
    @command()
173 farthen 366
    def getprocinfo(self):
171 farthen 367
        """ Gets current state of the scheduler """
343 farthen 368
        cin_maxsize = self.lib.dev.packetsizelimit.cin - self.lib.headersize
173 farthen 369
        # Get the size
370
        schedulerstate = self.lockscheduler()
371
        resp = self.lib.monitorcommand(struct.pack("IIII", 15, 0, 0, 0), "III", ("structver", "tablesize", None))
372
        tablesize = resp.tablesize
373
        size = tablesize
374
        structver = resp.structver
375
        offset = 0
376
        data = ""
377
        while size > 0:
378
            if size > cin_maxsize:
379
                readsize = cin_maxsize
380
            else:
381
                readsize = size
382
            resp = self.lib.monitorcommand(struct.pack("IIII", 15, offset, readsize, 0), "III%ds" % readsize, ("structver", "tablesize", None, "data"))
383
            data += resp.data
384
            offset += readsize
385
            size -= readsize
386
        self.lockscheduler(schedulerstate)
387
        threadstructsize = 120
388
        registersize = 32
389
        if len(data) % threadstructsize != 0:
390
            raise DeviceError("The thread struct is not a multiple of "+str(threadsturcsize)+"!")
391
        threadcount = len(data) / threadstructsize
392
        threads = []
393
        id = 0
394
        for thread in range(threadcount):
395
            offset = threadstructsize * thread
396
            threaddata = struct.unpack("<16IIIIIQIIIIIIIBBBB", data[offset:offset+threadstructsize])
397
            info = Bunch()
398
            info.id = id
399
            state = threaddata[17]
427 farthen 400
            info.state = libemcoredata.thread_state[state]
173 farthen 401
            if info.state == "THREAD_FREE":
402
                id += 1
403
                continue
404
            info.regs = Bunch()
405
            for register in range(16):
406
                info.regs["r"+str(register)] = threaddata[register]
407
            info.regs.cpsr = threaddata[16]
408
            info.nameptr = threaddata[18]
409
            if info.nameptr == 0:
410
                info.name = "Thread %d" % info.id
411
            else:
412
                info.name = self.readstring(info.nameptr)
413
            info.cputime_current = threaddata[19]
414
            info.cputime_total = threaddata[20]
415
            info.startusec = threaddata[21]
416
            info.queue_next_ptr = threaddata[22]
417
            info.timeout = threaddata[23]
418
            info.blocked_since = threaddata[24]
419
            info.blocked_by_ptr = threaddata[25]
420
            info.stackaddr = threaddata[26]
421
            info.err_no = threaddata[27]
427 farthen 422
            info.block_type = libemcoredata.thread_block[threaddata[28]]
423
            info.type = libemcoredata.thread_type[threaddata[29]]
173 farthen 424
            info.priority = threaddata[30]
425
            info.cpuload = threaddata[31]
426
            threads.append(info)
427
            id += 1
428
        return threads
56 benedikt93 429
 
394 farthen 430
    @command()
173 farthen 431
    def lockscheduler(self, freeze=True):
171 farthen 432
        """ Freezes/Unfreezes the scheduler """
173 farthen 433
        resp = self.lib.monitorcommand(struct.pack("IIII", 16, 1 if freeze else 0, 0, 0), "III", ("before", None, None))
434
        return True if resp.before == 1 else False
67 benedikt93 435
 
394 farthen 436
    @command()
173 farthen 437
    def unlockscheduler(self):
171 farthen 438
        """ Unfreezes the scheduler """
439
        return self.lib.monitorcommand(struct.pack("IIII", 16, 0, 0, 0), "III", ("before", None, None))
56 benedikt93 440
 
394 farthen 441
    @command()
171 farthen 442
    def suspendthread(self, id, suspend=True):
443
        """ Suspends the thread with the specified id """
173 farthen 444
        resp = self.lib.monitorcommand(struct.pack("IIII", 17, 1 if suspend else 0, id, 0), "III", ("before", None, None))
445
        return True if resp.before == 1 else False
56 benedikt93 446
 
394 farthen 447
    @command()
173 farthen 448
    def resumethread(self, id):
449
        """ Resumes the thread with the specified id """
171 farthen 450
        return self.lib.monitorcommand(struct.pack("IIII", 17, 0, id, 0), "III", ("before", None, None))
56 benedikt93 451
 
394 farthen 452
    @command()
171 farthen 453
    def killthread(self, id):
454
        """ Kills the thread with the specified id """
455
        return self.lib.monitorcommand(struct.pack("IIII", 18, id, 0, 0), "III", ("before", None, None))
56 benedikt93 456
 
394 farthen 457
    @command()
171 farthen 458
    def createthread(self, nameptr, entrypoint, stackptr, stacksize, threadtype, priority, state):
459
        """ Creates a thread with the specified attributes """
460
        if threadtype == "user":
461
            threadtype = 0
462
        elif threadtype == "system":
463
            threadtype = 1
464
        else:
341 farthen 465
            raise ArgumentError("Threadtype must be either 'system' or 'user'")
171 farthen 466
        if priority > 256 or priority < 0:
341 farthen 467
            raise ArgumentError("Priority must be a number between 0 and 256")
171 farthen 468
        if state == "ready":
469
            state = 0
470
        elif state == "suspended":
471
            state = 1
472
        else:
341 farthen 473
            raise ArgumentError("State must be either 'ready' or 'suspended'")
171 farthen 474
        resp = self.lib.monitorcommand(struct.pack("IIIIIIII", 19, nameptr, entrypoint, stackptr, stacksize, threadtype, priority, state), "III", (id, None, None))
475
        if resp.id < 0:
476
            raise DeviceError("The device returned the error code "+str(resp.id))
477
        return resp
56 benedikt93 478
 
394 farthen 479
    @command()
172 farthen 480
    def flushcaches(self):
171 farthen 481
        """ Flushes the CPU instruction and data cache """
482
        return self.lib.monitorcommand(struct.pack("IIII", 20, 0, 0, 0), "III", (None, None, None))
56 benedikt93 483
 
394 farthen 484
    @command()
172 farthen 485
    def execimage(self, addr):
427 farthen 486
        """ Runs the emCORE app at 'addr' """
452 theseven 487
        return self.lib.monitorcommand(struct.pack("IIII", 21, addr, 0, 0), "III", ("thread", None, None))
56 benedikt93 488
 
394 farthen 489
    @command()
238 farthen 490
    def run(self, app):
427 farthen 491
        """ Uploads and runs the emCORE app in the string 'app' """
452 theseven 492
        if app[:8] != "emCOexec":
427 farthen 493
            raise ArgumentError("The specified app is not an emCORE application")
452 theseven 494
        baseaddr = self.malloc(len(app))
238 farthen 495
        self.write(baseaddr, app)
452 theseven 496
        result = self.execimage(baseaddr)
497
        return Bunch(thread=result.thread)
238 farthen 498
 
395 farthen 499
    @command(timeout = 5000)
171 farthen 500
    def bootflashread(self, memaddr, flashaddr, size):
501
        """ Copies the data in the bootflash at 'flashaddr' of the specified size
502
            to the memory at addr 'memaddr'
503
        """
174 farthen 504
        return self.lib.monitorcommand(struct.pack("IIII", 22, memaddr, flashaddr, size), "III", (None, None, None))
82 benedikt93 505
 
395 farthen 506
    @command(timeout = 30000)
171 farthen 507
    def bootflashwrite(self, memaddr, flashaddr, size):
508
        """ Copies the data in the memory at 'memaddr' of the specified size
509
            to the boot flash at addr 'flashaddr'
510
        """
174 farthen 511
        return self.lib.monitorcommand(struct.pack("IIII", 23, memaddr, flashaddr, size), "III", (None, None, None))
56 benedikt93 512
 
394 farthen 513
    @command()
442 farthen 514
    def execfirmware(self, targetaddr, addr, size):
515
        """ Moves the firmware at 'addr' with size 'size' to 'targetaddr' and passes all control to it. """
516
        self.logger.debug("Moving firmware at 0x%x with the size %d to 0x%x and executing it\n" % (addr, size, targetaddr))
517
        return self.lib.monitorcommand(struct.pack("IIII", 24, targetaddr, addr, size))
56 benedikt93 518
 
395 farthen 519
    @command(timeout = 30000)
171 farthen 520
    def aesencrypt(self, addr, size, keyindex):
521
        """ Encrypts the buffer at 'addr' with the specified size
522
            with the hardware AES key index 'keyindex'
523
        """
524
        return self.lib.monitorcommand(struct.pack("IBBHII", 25, 1, 0, keyindex, addr, size), "III", (None, None, None))
82 benedikt93 525
 
395 farthen 526
    @command(timeout = 30000)
171 farthen 527
    def aesdecrypt(self, addr, size, keyindex):
528
        """ Decrypts the buffer at 'addr' with the specified size
529
            with the hardware AES key index 'keyindex'
530
        """
531
        return self.lib.monitorcommand(struct.pack("IBBHII", 25, 0, 0, keyindex, addr, size), "III", (None, None, None))
82 benedikt93 532
 
395 farthen 533
    @command(timeout = 30000)
171 farthen 534
    def hmac_sha1(self, addr, size, destination):
535
        """ Generates a HMAC-SHA1 hash of the buffer and saves it to 'destination' """
536
        return self.lib.monitorcommand(struct.pack("IIII", 26, addr, size, destination), "III", (None, None, None))
56 benedikt93 537
 
398 farthen 538
    @command(target = 0x47324e49)
227 theseven 539
    def ipodnano2g_getnandinfo(self):
540
        """ Target-specific function: ipodnano2g
541
            Gathers some information about the NAND chip used
542
        """
543
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0001, 0, 0, 0), "IHHHH", ("type", "pagesperblock", "banks", "userblocks", "blocks"))
544
 
398 farthen 545
    @command(timeout = 30000, target = 0x47324e49)
227 theseven 546
    def ipodnano2g_nandread(self, addr, start, count, doecc, checkempty):
547
        """ Target-specific function: ipodnano2g
548
            Reads data from the NAND chip into memory
549
        """
404 farthen 550
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0002, addr | (0x80000000 if doecc else 0) | (0x40000000 if checkempty else 0), start, count), "III", (None, None, None))
227 theseven 551
 
398 farthen 552
    @command(timeout = 30000, target = 0x47324e49)
227 theseven 553
    def ipodnano2g_nandwrite(self, addr, start, count, doecc):
554
        """ Target-specific function: ipodnano2g
555
            Writes data to the NAND chip
556
        """
404 farthen 557
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0003, addr | (0x80000000 if doecc else 0), start, count), "III", (None, None, None))
227 theseven 558
 
398 farthen 559
    @command(timeout = 30000, target = 0x47324e49)
227 theseven 560
    def ipodnano2g_nanderase(self, addr, start, count):
561
        """ Target-specific function: ipodnano2g
562
            Erases blocks on the NAND chip and stores the results to memory
563
        """
564
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0004, addr, start, count), "III", (None, None, None))
565
 
398 farthen 566
    @command(target = 0x4c435049)
346 theseven 567
    def ipodclassic_gethddinfo(self):
568
        """ Target-specific function: ipodclassic
569
            Gather information about the hard disk drive
570
        """
571
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0001, 0, 0, 0), "IQQII", ("identifyptr", "totalsectors", "virtualsectors", "bbtptr", "bbtsize"))
572
 
398 farthen 573
    @command(timeout = 30000, target = 0x4c435049)
346 theseven 574
    def ipodclassic_hddaccess(self, type, sector, count, addr):
575
        """ Target-specific function: ipodclassic
576
            Access the hard disk, type = 0 (read) / 1 (write)
577
        """
578
        rc = self.lib.monitorcommand(struct.pack("IIQIIII", 0xffff0002, type, sector, count, addr, 0, 0), "III", ("rc", None, None))
579
        if (rc > 0x80000000):
580
            raise DeviceError("HDD access (type=%d, sector=%d, count=%d, addr=0x%08X) failed with RC 0x%08X" % (type, sector, count, addr, rc))
581
 
398 farthen 582
    @command(target = 0x4c435049)
346 theseven 583
    def ipodclassic_writebbt(self, bbt, tempaddr):
584
        """ Target-specific function: ipodclassic
585
            Write hard drive bad block table
586
        """
587
        try:
588
            bbtheader = struct.unpack("<8s2024sQII512I", bbt[:4096])
589
        except struct.error:
427 farthen 590
            raise ArgumentError("The specified file is not an emCORE hard disk BBT")
346 theseven 591
        if bbtheader[0] != "emBIbbth":
427 farthen 592
            raise ArgumentError("The specified file is not an emCORE hard disk BBT")
346 theseven 593
        virtualsectors = bbtheader[2]
594
        bbtsectors = bbtheader[3]
595
        self.write(tempaddr, bbt)
596
        sector = 0
597
        count = 1
598
        offset = 0
599
        for i in range(bbtsectors):
600
            if bbtheader[4][i] == sector + count:
601
                count = count + 1
602
            else:
603
                self.ipodclassic_hddaccess(1, sector, count, tempaddr + offset)
604
                offset = offset + count * 4096
605
                sector = bbtheader[4][i]
606
                count = 1
607
        self.ipodclassic_hddaccess(1, sector, count, tempaddr + offset)
608
 
394 farthen 609
    @command()
379 theseven 610
    def storage_get_info(self, volume):
346 theseven 611
        """ Get information about a storage device """
379 theseven 612
        result = self.lib.monitorcommand(struct.pack("IIII", 27, volume, 0, 0), "IIIIIIII", ("version", None, None, "sectorsize", "numsectors", "vendorptr", "productptr", "revisionptr"))
346 theseven 613
        if result.version != 1:
614
            raise ValueError("Unknown version of storage_info struct: %d" % result.version)
379 theseven 615
        result.vendor = self.readstring(result.vendorptr)
616
        result.product = self.readstring(result.productptr)
617
        result.revision = self.readstring(result.revisionptr)
346 theseven 618
        return result
619
 
395 farthen 620
    @command(timeout = 50000)
346 theseven 621
    def storage_read_sectors_md(self, volume, sector, count, addr):
622
        """ Read sectors from as storage device """
399 farthen 623
        result = self.lib.monitorcommand(struct.pack("IIQIIII", 28, volume, sector, count, addr, 0, 0), "III", ("rc", None, None))
346 theseven 624
        if result.rc > 0x80000000:
625
            raise DeviceError("storage_read_sectors_md(volume=%d, sector=%d, count=%d, addr=0x%08X) failed with RC 0x%08X" % (volume, sector, count, addr, rc))
394 farthen 626
 
395 farthen 627
    @command(timeout = 50000)
346 theseven 628
    def storage_write_sectors_md(self, volume, sector, count, addr):
629
        """ Read sectors from as storage device """
399 farthen 630
        result = self.lib.monitorcommand(struct.pack("IIQIIII", 29, volume, sector, count, addr, 0, 0), "III", ("rc", None, None))
346 theseven 631
        if result.rc > 0x80000000:
632
            raise DeviceError("storage_read_sectors_md(volume=%d, sector=%d, count=%d, addr=0x%08X) failed with RC 0x%08X" % (volume, sector, count, addr, rc))
394 farthen 633
 
395 farthen 634
    @command(timeout = 30000)
346 theseven 635
    def file_open(self, filename, mode):
636
        """ Opens a file and returns the handle """
637
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(filename), 30, mode, 0, 0, filename, 0), "III", ("fd", None, None))
638
        if result.fd > 0x80000000:
639
            raise DeviceError("file_open(filename=\"%s\", mode=0x%X) failed with RC=0x%08X, errno=%d" % (filename, mode, result.fd, self.errno()))
640
        return result.fd
641
 
395 farthen 642
    @command(timeout = 30000)
346 theseven 643
    def file_size(self, fd):
644
        """ Gets the size of a file referenced by a handle """
645
        result = self.lib.monitorcommand(struct.pack("IIII", 31, fd, 0, 0), "III", ("size", None, None))
646
        if result.size > 0x80000000:
647
            raise DeviceError("file_size(fd=%d) failed with RC=0x%08X, errno=%d" % (fd, result.size, self.errno()))
648
        return result.size
394 farthen 649
 
395 farthen 650
    @command(timeout = 30000)
346 theseven 651
    def file_read(self, fd, addr, size):
652
        """ Reads data from a file referenced by a handle """
653
        result = self.lib.monitorcommand(struct.pack("IIII", 32, fd, addr, size), "III", ("rc", None, None))
654
        if result.rc > 0x80000000:
655
            raise DeviceError("file_read(fd=%d, addr=0x%08X, size=0x%08X) failed with RC=0x%08X, errno=%d" % (fd, addr, size, result.rc, self.errno()))
656
        return result.rc
394 farthen 657
 
395 farthen 658
    @command(timeout = 30000)
346 theseven 659
    def file_write(self, fd, addr, size):
660
        """ Writes data from a file referenced by a handle """
661
        result = self.lib.monitorcommand(struct.pack("IIII", 33, fd, addr, size), "III", ("rc", None, None))
662
        if result.rc > 0x80000000:
663
            raise DeviceError("file_write(fd=%d, addr=0x%08X, size=0x%08X) failed with RC=0x%08X, errno=%d" % (fd, addr, size, result.rc, self.errno()))
664
        return result.rc
665
 
395 farthen 666
    @command(timeout = 30000)
346 theseven 667
    def file_seek(self, fd, offset, whence):
668
        """ Seeks the file handle to the specified position in the file """
669
        result = self.lib.monitorcommand(struct.pack("IIII", 34, fd, offset, whence), "III", ("rc", None, None))
670
        if result.rc > 0x80000000:
671
            raise DeviceError("file_seek(fd=%d, offset=0x%08X, whence=%d) failed with RC=0x%08X, errno=%d" % (fd, offset, whence, result.rc, self.errno()))
672
        return result.rc
673
 
395 farthen 674
    @command(timeout = 30000)
346 theseven 675
    def file_truncate(self, fd, length):
676
        """ Truncates a file referenced by a handle to a specified length """
677
        result = self.lib.monitorcommand(struct.pack("IIII", 35, fd, offset, 0), "III", ("rc", None, None))
678
        if result.rc > 0x80000000:
679
            raise DeviceError("file_truncate(fd=%d, length=0x%08X) failed with RC=0x%08X, errno=%d" % (fd, length, result.rc, self.errno()))
680
        return result.rc
681
 
395 farthen 682
    @command(timeout = 30000)
346 theseven 683
    def file_sync(self, fd):
684
        """ Flushes a file handles' buffers """
685
        result = self.lib.monitorcommand(struct.pack("IIII", 36, fd, 0, 0), "III", ("rc", None, None))
686
        if result.rc > 0x80000000:
687
            raise DeviceError("file_sync(fd=%d) failed with RC=0x%08X, errno=%d" % (fd, result.rc, self.errno()))
688
        return result.rc
689
 
395 farthen 690
    @command(timeout = 30000)
346 theseven 691
    def file_close(self, fd):
692
        """ Closes a file handle """
693
        result = self.lib.monitorcommand(struct.pack("IIII", 37, fd, 0, 0), "III", ("rc", None, None))
694
        if result.rc > 0x80000000:
695
            raise DeviceError("file_close(fd=%d) failed with RC=0x%08X, errno=%d" % (fd, result.rc, self.errno()))
696
        return result.rc
697
 
395 farthen 698
    @command(timeout = 30000)
346 theseven 699
    def file_close_all(self):
700
        """ Closes all file handles opened through the debugger """
701
        result = self.lib.monitorcommand(struct.pack("IIII", 38, 0, 0, 0), "III", ("rc", None, None))
702
        if result.rc > 0x80000000:
703
            raise DeviceError("file_close_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
704
        return result.rc
705
 
395 farthen 706
    @command(timeout = 30000)
346 theseven 707
    def file_kill_all(self):
708
        """ Kills all file handles (in the whole system) """
709
        result = self.lib.monitorcommand(struct.pack("IIII", 39, 0, 0, 0), "III", ("rc", None, None))
710
        if result.rc > 0x80000000:
711
            raise DeviceError("file_kill_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
712
        return result.rc
713
 
395 farthen 714
    @command(timeout = 30000)
346 theseven 715
    def file_unlink(self, filename):
716
        """ Removes a file """
717
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(filename), 40, 0, 0, 0, filename, 0), "III", ("rc", None, None))
718
        if result.rc > 0x80000000:
719
            raise DeviceError("file_unlink(filename=\"%s\") failed with RC=0x%08X, errno=%d" % (filename, result.rc, self.errno()))
720
        return result.rc
721
 
395 farthen 722
    @command(timeout = 30000)
346 theseven 723
    def file_rename(self, oldname, newname):
724
        """ Renames a file """
725
        result = self.lib.monitorcommand(struct.pack("IIII248s%dsB" % min(247, len(newname)), 41, 0, 0, 0, oldname, newname, 0), "III", ("rc", None, None))
726
        if result.rc > 0x80000000:
727
            raise DeviceError("file_rename(oldname=\"%s\", newname=\"%s\") failed with RC=0x%08X, errno=%d" % (oldname, newname, result.rc, self.errno()))
728
        return result.rc
729
 
395 farthen 730
    @command(timeout = 30000)
346 theseven 731
    def dir_open(self, dirname):
732
        """ Opens a directory and returns the handle """
733
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(dirname), 42, 0, 0, 0, dirname, 0), "III", ("handle", None, None))
734
        if result.handle == 0:
735
            raise DeviceError("dir_open(dirname=\"%s\") failed with RC=0x%08X, errno=%d" % (dirname, result.handle, self.errno()))
736
        return result.handle
737
 
395 farthen 738
    @command(timeout = 30000)
346 theseven 739
    def dir_read(self, handle):
740
        """ Reads the next entry from a directory """
741
        result = self.lib.monitorcommand(struct.pack("IIII", 43, handle, 0, 0), "III", ("version", "maxpath", "ptr"))
742
        if result.ptr == 0:
743
            raise DeviceError("dir_read(handle=0x%08X) failed with RC=0x%08X, errno=%d" % (handle, result.ptr, self.errno()))
744
        if result.version != 1:
745
            raise ValueError("Unknown version of dirent struct: %d" % result.version)
746
        dirent = self.read(result.ptr, result.maxpath + 16)
747
        ret = Bunch()
748
        (ret.name, ret.attributes, ret.size, ret.startcluster, ret.wrtdate, ret.wrttime) = struct.unpack("%dsIIIHH" % result.maxpath, dirent)
749
        ret.name = ret.name[:ret.name.index('\x00')]
750
        return ret
751
 
395 farthen 752
    @command(timeout = 30000)
346 theseven 753
    def dir_close(self, handle):
754
        """ Closes a directory handle """
755
        result = self.lib.monitorcommand(struct.pack("IIII", 44, handle, 0, 0), "III", ("rc", None, None))
756
        if result.rc > 0x80000000:
757
            raise DeviceError("dir_close(handle=0x%08X) failed with RC=0x%08X, errno=%d" % (handle, result.rc, self.errno()))
758
        return result.rc
759
 
395 farthen 760
    @command(timeout = 30000)
346 theseven 761
    def dir_close_all(self):
762
        """ Closes all directory handles opened through the debugger """
763
        result = self.lib.monitorcommand(struct.pack("IIII", 45, 0, 0, 0), "III", ("rc", None, None))
764
        if result.rc > 0x80000000:
765
            raise DeviceError("dir_close_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
766
        return result.rc
767
 
395 farthen 768
    @command(timeout = 30000)
346 theseven 769
    def dir_kill_all(self):
770
        """ Kills all directory handles (in the whole system) """
771
        result = self.lib.monitorcommand(struct.pack("IIII", 46, 0, 0, 0), "III", ("rc", None, None))
772
        if result.rc > 0x80000000:
773
            raise DeviceError("dir_kill_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
774
        return result.rc
775
 
395 farthen 776
    @command(timeout = 30000)
346 theseven 777
    def dir_create(self, dirname):
778
        """ Creates a directory """
779
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(dirname), 47, 0, 0, 0, dirname, 0), "III", ("rc", None, None))
780
        if result.rc > 0x80000000:
781
            raise DeviceError("dir_create(dirname=\"%s\") failed with RC=0x%08X, errno=%d" % (dirname, result.rc, self.errno()))
782
        return result.rc
783
 
395 farthen 784
    @command(timeout = 30000)
346 theseven 785
    def dir_remove(self, dirname):
786
        """ Removes an (empty) directory """
787
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(dirname), 48, 0, 0, 0, dirname, 0), "III", ("rc", None, None))
788
        if result.rc > 0x80000000:
789
            raise DeviceError("dir_remove(dirname=\"%s\") failed with RC=0x%08X, errno=%d" % (dirname, result.rc, self.errno()))
790
        return result.rc
791
 
394 farthen 792
    @command()
346 theseven 793
    def errno(self):
794
        """ Returns the number of the last error that happened """
795
        result = self.lib.monitorcommand(struct.pack("IIII", 49, 0, 0, 0), "III", ("errno", None, None))
796
        return result.errno
797
 
394 farthen 798
    @command()
346 theseven 799
    def disk_mount(self, volume):
800
        """ Mounts a volume """
801
        result = self.lib.monitorcommand(struct.pack("IIII", 50, volume, 0, 0), "III", ("rc", None, None))
802
        if result.rc > 0x80000000:
803
            raise DeviceError("disk_mount(volume=%d) failed with RC=0x%08X, errno=%d" % (volume, result.rc, self.errno()))
804
        return result.rc
805
 
394 farthen 806
    @command()
346 theseven 807
    def disk_unmount(self, volume):
808
        """ Unmounts a volume """
809
        result = self.lib.monitorcommand(struct.pack("IIII", 51, volume, 0, 0), "III", ("rc", None, None))
810
        if result.rc > 0x80000000:
811
            raise DeviceError("disk_unmount(volume=%d) failed with RC=0x%08X, errno=%d" % (volume, result.rc, self.errno()))
812
        return result.rc
813
 
441 farthen 814
    @command()
815
    def malloc(self, size):
816
        """ Allocates 'size' bytes and returns a pointer to the allocated memory """
442 farthen 817
        self.logger.debug("Allocating %d bytes of memory\n" % size)
441 farthen 818
        result = self.lib.monitorcommand(struct.pack("IIII", 52, size, 0, 0), "III", ("ptr", None, None))
442 farthen 819
        self.logger.debug("Allocated %d bytes of memory at 0x%x\n" % (size, result.ptr))
441 farthen 820
        return result.ptr
821
 
822
    @command()
823
    def memalign(self, align, size):
824
        """ Allocates 'size' bytes aligned to 'align' and returns a pointer to the allocated memory """
442 farthen 825
        self.logger.debug("Allocating %d bytes of memory aligned to 0x%x\n" % (size, align))
441 farthen 826
        result = self.lib.monitorcommand(struct.pack("IIII", 53, align, size, 0), "III", ("ptr", None, None))
442 farthen 827
        self.logger.debug("Allocated %d bytes of memory at 0x%x\n" % (size, result.ptr))
441 farthen 828
        return result.ptr
829
 
830
    @command()
831
    def realloc(self, ptr, size):
832
        """ The size of the memory block pointed to by 'ptr' is changed to the 'size' bytes,
833
            expanding or reducing the amount of memory available in the block.
834
            Returns a pointer to the reallocated memory.
835
        """
442 farthen 836
        self.logger.debug("Reallocating 0x%x to have the new size %d\n" % (ptr, size))
441 farthen 837
        result = self.lib.monitorcommand(struct.pack("IIII", 54, ptr, size, 0), "III", ("ptr", None, None))
442 farthen 838
        self.logger.debug("Reallocated memory at 0x%x to 0x%x with the new size %d\n" % (ptr, result.ptr, size))
441 farthen 839
        return result.ptr
840
 
841
    @command()
842
    def reownalloc(self, ptr, owner):
843
        """ Changes the owner of the memory allocation 'ptr' to the thread struct at addr 'owner' """
442 farthen 844
        self.logger.debug("Changing owner of the memory region 0x%x to 0x%x" % (ptr, owner))
441 farthen 845
        return self.lib.monitorcommand(struct.pack("IIII", 55, ptr, owner, 0), "III", (None, None, None))
846
 
847
    @command()
848
    def free(self, ptr):
849
        """ Frees the memory space pointed to by 'ptr' """
442 farthen 850
        self.logger.debug("Freeing the memory region at 0x%x\n" % ptr)
441 farthen 851
        return self.lib.monitorcommand(struct.pack("IIII", 56, addr, 0, 0), "III", (None, None, None))
852
 
346 theseven 853
 
171 farthen 854
class Lib(object):
401 farthen 855
    def __init__(self, logger):
856
        self.logger = logger
857
        self.logger.debug("Initializing Lib object\n")
171 farthen 858
        self.idVendor = 0xFFFF
859
        self.idProduct = 0xE000
176 farthen 860
 
861
        self.headersize = 0x10
862
 
863
        self.connect()
56 benedikt93 864
 
171 farthen 865
    def connect(self):
401 farthen 866
        self.dev = Dev(self.idVendor, self.idProduct, self.logger)
171 farthen 867
        self.connected = True
56 benedikt93 868
 
171 farthen 869
    def monitorcommand(self, cmd, rcvdatatypes=None, rcvstruct=None):
442 farthen 870
        self.logger.debug("Sending monitorcommand [0x%s]\n" % cmd[3::-1].encode("hex"))
269 farthen 871
        writelen = self.dev.cout(cmd)
171 farthen 872
        if rcvdatatypes:
873
            rcvdatatypes = "I" + rcvdatatypes # add the response
874
            data = self.dev.cin(struct.calcsize(rcvdatatypes))
875
            data = struct.unpack(rcvdatatypes, data)
876
            response = data[0]
427 farthen 877
            if libemcoredata.responsecodes[response] == "ok":
401 farthen 878
                self.logger.debug("Response: OK\n")
171 farthen 879
                if rcvstruct:
880
                    datadict = Bunch()
881
                    counter = 1 # start with 1, 0 is the id
882
                    for item in rcvstruct:
883
                        if item != None: # else the data is undefined
884
                            datadict[item] = data[counter]
885
                        counter += 1
886
                    return datadict
887
                else:
888
                    return data
427 farthen 889
            elif libemcoredata.responsecodes[response] == "unsupported":
401 farthen 890
                self.logger.debug("Response: UNSUPPORTED\n")
171 farthen 891
                raise DeviceError("The device does not support this command.")
427 farthen 892
            elif libemcoredata.responsecodes[response] == "invalid":
401 farthen 893
                self.logger.debug("Response: INVALID\n")
171 farthen 894
                raise DeviceError("Invalid command! This should NOT happen!")
427 farthen 895
            elif libemcoredata.responsecodes[response] == "busy":
401 farthen 896
                self.logger.debug("Response: BUSY\n")
171 farthen 897
                raise DeviceError("Device busy")
401 farthen 898
            else:
899
                self.logger.debug("Response: UNKOWN\n")
900
                raise DeviceError("Invalid response! This should NOT happen!")
269 farthen 901
        else:
902
            return writelen
56 benedikt93 903
 
904
 
171 farthen 905
class Dev(object):
401 farthen 906
    def __init__(self, idVendor, idProduct, logger):
171 farthen 907
        self.idVendor = idVendor
908
        self.idProduct = idProduct
67 benedikt93 909
 
401 farthen 910
        self.logger = logger
911
        self.logger.debug("Initializing Dev object\n")
912
 
171 farthen 913
        self.interface = 0
914
        self.timeout = 100
176 farthen 915
 
171 farthen 916
        self.connect()
917
        self.findEndpoints()
918
 
401 farthen 919
        self.logger.debug("Successfully connected to device\n")
342 farthen 920
 
921
        # Device properties
343 farthen 922
        self.packetsizelimit = Bunch()
923
        self.packetsizelimit.cout = None
924
        self.packetsizelimit.cin = None
925
        self.packetsizelimit.dout = None
926
        self.packetsizelimit.din = None
342 farthen 927
 
343 farthen 928
        self.version = Bunch()
342 farthen 929
        self.version.revision = None
930
        self.version.majorv = None
931
        self.version.minorv = None
932
        self.version.patchv = None
933
        self.swtypeid = None
934
        self.hwtypeid = None
935
 
343 farthen 936
        self.usermem = Bunch()
342 farthen 937
        self.usermem.lower = None
938
        self.usermem.upper = None
56 benedikt93 939
 
171 farthen 940
    def __del__(self):
941
        self.disconnect()
56 benedikt93 942
 
171 farthen 943
    def findEndpoints(self):
401 farthen 944
        self.logger.debug("Searching for device endpoints:\n")
171 farthen 945
        epcounter = 0
343 farthen 946
        self.endpoint = Bunch()
171 farthen 947
        for cfg in self.dev:
948
            for intf in cfg:
949
                for ep in intf:
950
                    if epcounter == 0:
401 farthen 951
                        self.logger.debug("Found cout endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 952
                        self.endpoint.cout = ep.bEndpointAddress
171 farthen 953
                    elif epcounter == 1:
401 farthen 954
                        self.logger.debug("Found cin endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 955
                        self.endpoint.cin = ep.bEndpointAddress
171 farthen 956
                    elif epcounter == 2:
401 farthen 957
                        self.logger.debug("Found dout endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 958
                        self.endpoint.dout = ep.bEndpointAddress
171 farthen 959
                    elif epcounter == 3:
401 farthen 960
                        self.logger.debug("Found din endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 961
                        self.endpoint.din = ep.bEndpointAddress
171 farthen 962
                    epcounter += 1
963
        if epcounter <= 3:
964
            raise DeviceError("Not all endpoints found in the descriptor. Only "+str(epcounter)+" found, we need 4")
56 benedikt93 965
 
171 farthen 966
    def connect(self):
427 farthen 967
        self.logger.debug("Looking for emCORE device\n")
171 farthen 968
        self.dev = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
969
        if self.dev is None:
970
            raise DeviceNotFoundError()
401 farthen 971
        self.logger.debug("Device Found!\n")
972
        self.logger.debug("Setting first configuration\n")
171 farthen 973
        self.dev.set_configuration()
56 benedikt93 974
 
171 farthen 975
    def disconnect(self):
976
        pass
102 benedikt93 977
 
171 farthen 978
    def send(self, endpoint, data):
979
        size = self.dev.write(endpoint, data, self.interface, self.timeout)
980
        if size != len(data):
176 farthen 981
            raise SendError("Not all data was written!")
171 farthen 982
        return len
102 benedikt93 983
 
171 farthen 984
    def receive(self, endpoint, size):
985
        read = self.dev.read(endpoint, size, self.interface, self.timeout)
986
        if len(read) != size:
176 farthen 987
            raise ReceiveError("Requested size and read size don't match!")
171 farthen 988
        return read
56 benedikt93 989
 
171 farthen 990
    def cout(self, data):
401 farthen 991
        self.logger.debug("Sending data to cout endpoint with the size " + str(len(data)) + "\n")
343 farthen 992
        if self.packetsizelimit.cout and len(data) > self.packetsizelimit.cout:
171 farthen 993
            raise SendError("Packet too big")
343 farthen 994
        return self.send(self.endpoint.cout, data)
94 benedikt93 995
 
171 farthen 996
    def cin(self, size):
401 farthen 997
        self.logger.debug("Receiving data on the cin endpoint with the size " + str(size) + "\n")
343 farthen 998
        if self.packetsizelimit.cin and size > self.packetsizelimit.cin:
171 farthen 999
            raise ReceiveError("Packet too big")
343 farthen 1000
        return self.receive(self.endpoint.cin, size)
94 benedikt93 1001
 
171 farthen 1002
    def dout(self, data):
401 farthen 1003
        self.logger.debug("Sending data to cout endpoint with the size " + str(len(data)) + "\n")
343 farthen 1004
        if self.packetsizelimit.dout and len(data) > self.packetsizelimit.dout:
171 farthen 1005
            raise SendError("Packet too big")
343 farthen 1006
        return self.send(self.endpoint.dout, data)
94 benedikt93 1007
 
171 farthen 1008
    def din(self, size):
401 farthen 1009
        self.logger.debug("Receiving data on the din endpoint with the size " + str(size) + "\n")
343 farthen 1010
        if self.packetsizelimit.din and size > self.packetsizelimit.din:
171 farthen 1011
            raise ReceiveError("Packet too big")
343 farthen 1012
        return self.receive(self.endpoint.din, size)
56 benedikt93 1013
 
96 benedikt93 1014
 
171 farthen 1015
if __name__ == "__main__":
396 farthen 1016
    from misc import Logger
1017
    logger = Logger()
1018
    if sys.argv[1] == "test":
1019
        # Some tests
1020
        import sys
427 farthen 1021
        emcore = Emcore()
1022
        resp = emcore.getversioninfo()
1023
        logger.log("Emcore device version information: " + libemcoredata.swtypes[resp.swtypeid] + " v" + str(resp.majorv) + "." + str(resp.minorv) + 
1024
                         "." + str(resp.patchv) + " r" + str(resp.revision) + " running on " + libemcoredata.hwtypes[resp.hwtypeid] + "\n")
1025
        resp = emcore.getusermemrange()
396 farthen 1026
        logger.log("Usermemrange: "+hex(resp.lower)+" - "+hex(resp.upper)+"\n")
1027
        memaddr = resp.lower
1028
        maxlen = resp.upper - resp.lower
427 farthen 1029
        f = open("./emcore.py", "rb")
1030
        logger.log("Loading test file (emcore.py) to send over USB...\n")
396 farthen 1031
        datastr = f.read()[:maxlen]
1032
        logger.log("Sending data...\n")
427 farthen 1033
        emcore.write(memaddr, datastr)
396 farthen 1034
        logger.log("Encrypting data with the hardware key...\n")
427 farthen 1035
        emcore.aesencrypt(memaddr, len(datastr), 0)
1036
        logger.log("Reading data back and saving it to 'libemcore-test-encrypted.bin'...\n")
1037
        f = open("./libemcore-test-encrypted.bin", "wb")
1038
        f.write(emcore.read(memaddr, len(datastr)))
396 farthen 1039
        logger.log("Decrypting the data again...\n")
427 farthen 1040
        emcore.aesdecrypt(memaddr, len(datastr), 0)
396 farthen 1041
        logger.log("Reading data back from device...\n")
427 farthen 1042
        readdata = emcore.read(memaddr, len(datastr))
396 farthen 1043
        if readdata == datastr:
1044
            logger.log("Data matches!")
1045
        else:
1046
            logger.log("Data does NOT match. Something went wrong")
1047
 
1048
    elif sys.argv[1] == "gendoc":
1049
        # Generates Documentation
1050
        from misc import gendoc
1051
        logger.log("Generating documentation\n")
1052
        cmddict = {}
427 farthen 1053
        for attr, value in Emcore.__dict__.iteritems():
396 farthen 1054
            if getattr(value, 'func', False):
1055
                if getattr(value.func, '_command', False):
1056
                    cmddict[value.func.__name__] = value
441 farthen 1057
        logger.log(gendoc(cmddict))
1058
 
1059
    elif sys.argv[1] == "malloctest":
1060
        emcore = Emcore()
1061
        logger.log("Allocating 200 bytes of memory: ")
1062
        addr = emcore.malloc(200)
1063
        logger.log("0x%x\n" % addr)
1064
        logger.log("Reallocating to 2000 bytes: ")
1065
        addr = emcore.realloc(addr, 2000)
1066
        logger.log("0x%x\n" % addr)
1067
        logger.log("Freeing 0x%x\n" % addr)
1068
        emcore.free(addr)
1069
        logger.log("Allocating 1000 bytes of memory aligned to 100 bytes: ")
1070
        addr = emcore.memalign(100, 1000)
1071
        logger.log("0x%x\n" % addr)
1072
        logger.log("Freeing 0x%x\n" % addr)
1073
        emcore.free(addr)