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' """
346 theseven 487
        return self.lib.monitorcommand(struct.pack("IIII", 21, addr, 0, 0), "III", ("rc", 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' """
238 farthen 492
        try:
493
            appheader = struct.unpack("<8sIIIIIIIIII", app[:48])
494
        except struct.error:
427 farthen 495
            raise ArgumentError("The specified app is not an emCORE application")
238 farthen 496
        header = appheader[0]
497
        if header != "emBIexec":
427 farthen 498
            raise ArgumentError("The specified app is not an emCORE application")
238 farthen 499
        baseaddr = appheader[2]
500
        threadnameptr = appheader[8]
501
        nameptr = threadnameptr - baseaddr
502
        name = ""
503
        while True:
504
            char = app[nameptr:nameptr+1]
505
            try:
506
                if ord(char) == 0:
507
                    break
508
            except TypeError:
427 farthen 509
                raise ArgumentError("The specified app is not an emCORE application")
238 farthen 510
            name += char
511
            nameptr += 1
512
        usermem = self.getusermemrange()
513
        if usermem.lower > baseaddr or usermem.upper < baseaddr + len(app):
427 farthen 514
            raise ArgumentError("The baseaddress of the specified emCORE application is out of range of the user memory range on the device. Are you sure that this application is compatible with your device?")
238 farthen 515
        self.write(baseaddr, app)
516
        self.execimage(baseaddr)
517
        return Bunch(baseaddr=baseaddr, name=name)
518
 
395 farthen 519
    @command(timeout = 5000)
171 farthen 520
    def bootflashread(self, memaddr, flashaddr, size):
521
        """ Copies the data in the bootflash at 'flashaddr' of the specified size
522
            to the memory at addr 'memaddr'
523
        """
174 farthen 524
        return self.lib.monitorcommand(struct.pack("IIII", 22, memaddr, flashaddr, size), "III", (None, None, None))
82 benedikt93 525
 
395 farthen 526
    @command(timeout = 30000)
171 farthen 527
    def bootflashwrite(self, memaddr, flashaddr, size):
528
        """ Copies the data in the memory at 'memaddr' of the specified size
529
            to the boot flash at addr 'flashaddr'
530
        """
174 farthen 531
        return self.lib.monitorcommand(struct.pack("IIII", 23, memaddr, flashaddr, size), "III", (None, None, None))
56 benedikt93 532
 
394 farthen 533
    @command()
442 farthen 534
    def execfirmware(self, targetaddr, addr, size):
535
        """ Moves the firmware at 'addr' with size 'size' to 'targetaddr' and passes all control to it. """
536
        self.logger.debug("Moving firmware at 0x%x with the size %d to 0x%x and executing it\n" % (addr, size, targetaddr))
537
        return self.lib.monitorcommand(struct.pack("IIII", 24, targetaddr, addr, size))
56 benedikt93 538
 
395 farthen 539
    @command(timeout = 30000)
171 farthen 540
    def aesencrypt(self, addr, size, keyindex):
541
        """ Encrypts the buffer at 'addr' with the specified size
542
            with the hardware AES key index 'keyindex'
543
        """
544
        return self.lib.monitorcommand(struct.pack("IBBHII", 25, 1, 0, keyindex, addr, size), "III", (None, None, None))
82 benedikt93 545
 
395 farthen 546
    @command(timeout = 30000)
171 farthen 547
    def aesdecrypt(self, addr, size, keyindex):
548
        """ Decrypts the buffer at 'addr' with the specified size
549
            with the hardware AES key index 'keyindex'
550
        """
551
        return self.lib.monitorcommand(struct.pack("IBBHII", 25, 0, 0, keyindex, addr, size), "III", (None, None, None))
82 benedikt93 552
 
395 farthen 553
    @command(timeout = 30000)
171 farthen 554
    def hmac_sha1(self, addr, size, destination):
555
        """ Generates a HMAC-SHA1 hash of the buffer and saves it to 'destination' """
556
        return self.lib.monitorcommand(struct.pack("IIII", 26, addr, size, destination), "III", (None, None, None))
56 benedikt93 557
 
398 farthen 558
    @command(target = 0x47324e49)
227 theseven 559
    def ipodnano2g_getnandinfo(self):
560
        """ Target-specific function: ipodnano2g
561
            Gathers some information about the NAND chip used
562
        """
563
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0001, 0, 0, 0), "IHHHH", ("type", "pagesperblock", "banks", "userblocks", "blocks"))
564
 
398 farthen 565
    @command(timeout = 30000, target = 0x47324e49)
227 theseven 566
    def ipodnano2g_nandread(self, addr, start, count, doecc, checkempty):
567
        """ Target-specific function: ipodnano2g
568
            Reads data from the NAND chip into memory
569
        """
404 farthen 570
        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 571
 
398 farthen 572
    @command(timeout = 30000, target = 0x47324e49)
227 theseven 573
    def ipodnano2g_nandwrite(self, addr, start, count, doecc):
574
        """ Target-specific function: ipodnano2g
575
            Writes data to the NAND chip
576
        """
404 farthen 577
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0003, addr | (0x80000000 if doecc else 0), start, count), "III", (None, None, None))
227 theseven 578
 
398 farthen 579
    @command(timeout = 30000, target = 0x47324e49)
227 theseven 580
    def ipodnano2g_nanderase(self, addr, start, count):
581
        """ Target-specific function: ipodnano2g
582
            Erases blocks on the NAND chip and stores the results to memory
583
        """
584
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0004, addr, start, count), "III", (None, None, None))
585
 
398 farthen 586
    @command(target = 0x4c435049)
346 theseven 587
    def ipodclassic_gethddinfo(self):
588
        """ Target-specific function: ipodclassic
589
            Gather information about the hard disk drive
590
        """
591
        return self.lib.monitorcommand(struct.pack("IIII", 0xffff0001, 0, 0, 0), "IQQII", ("identifyptr", "totalsectors", "virtualsectors", "bbtptr", "bbtsize"))
592
 
398 farthen 593
    @command(timeout = 30000, target = 0x4c435049)
346 theseven 594
    def ipodclassic_hddaccess(self, type, sector, count, addr):
595
        """ Target-specific function: ipodclassic
596
            Access the hard disk, type = 0 (read) / 1 (write)
597
        """
598
        rc = self.lib.monitorcommand(struct.pack("IIQIIII", 0xffff0002, type, sector, count, addr, 0, 0), "III", ("rc", None, None))
599
        if (rc > 0x80000000):
600
            raise DeviceError("HDD access (type=%d, sector=%d, count=%d, addr=0x%08X) failed with RC 0x%08X" % (type, sector, count, addr, rc))
601
 
398 farthen 602
    @command(target = 0x4c435049)
346 theseven 603
    def ipodclassic_writebbt(self, bbt, tempaddr):
604
        """ Target-specific function: ipodclassic
605
            Write hard drive bad block table
606
        """
607
        try:
608
            bbtheader = struct.unpack("<8s2024sQII512I", bbt[:4096])
609
        except struct.error:
427 farthen 610
            raise ArgumentError("The specified file is not an emCORE hard disk BBT")
346 theseven 611
        if bbtheader[0] != "emBIbbth":
427 farthen 612
            raise ArgumentError("The specified file is not an emCORE hard disk BBT")
346 theseven 613
        virtualsectors = bbtheader[2]
614
        bbtsectors = bbtheader[3]
615
        self.write(tempaddr, bbt)
616
        sector = 0
617
        count = 1
618
        offset = 0
619
        for i in range(bbtsectors):
620
            if bbtheader[4][i] == sector + count:
621
                count = count + 1
622
            else:
623
                self.ipodclassic_hddaccess(1, sector, count, tempaddr + offset)
624
                offset = offset + count * 4096
625
                sector = bbtheader[4][i]
626
                count = 1
627
        self.ipodclassic_hddaccess(1, sector, count, tempaddr + offset)
628
 
394 farthen 629
    @command()
379 theseven 630
    def storage_get_info(self, volume):
346 theseven 631
        """ Get information about a storage device """
379 theseven 632
        result = self.lib.monitorcommand(struct.pack("IIII", 27, volume, 0, 0), "IIIIIIII", ("version", None, None, "sectorsize", "numsectors", "vendorptr", "productptr", "revisionptr"))
346 theseven 633
        if result.version != 1:
634
            raise ValueError("Unknown version of storage_info struct: %d" % result.version)
379 theseven 635
        result.vendor = self.readstring(result.vendorptr)
636
        result.product = self.readstring(result.productptr)
637
        result.revision = self.readstring(result.revisionptr)
346 theseven 638
        return result
639
 
395 farthen 640
    @command(timeout = 50000)
346 theseven 641
    def storage_read_sectors_md(self, volume, sector, count, addr):
642
        """ Read sectors from as storage device """
399 farthen 643
        result = self.lib.monitorcommand(struct.pack("IIQIIII", 28, volume, sector, count, addr, 0, 0), "III", ("rc", None, None))
346 theseven 644
        if result.rc > 0x80000000:
645
            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 646
 
395 farthen 647
    @command(timeout = 50000)
346 theseven 648
    def storage_write_sectors_md(self, volume, sector, count, addr):
649
        """ Read sectors from as storage device """
399 farthen 650
        result = self.lib.monitorcommand(struct.pack("IIQIIII", 29, volume, sector, count, addr, 0, 0), "III", ("rc", None, None))
346 theseven 651
        if result.rc > 0x80000000:
652
            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 653
 
395 farthen 654
    @command(timeout = 30000)
346 theseven 655
    def file_open(self, filename, mode):
656
        """ Opens a file and returns the handle """
657
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(filename), 30, mode, 0, 0, filename, 0), "III", ("fd", None, None))
658
        if result.fd > 0x80000000:
659
            raise DeviceError("file_open(filename=\"%s\", mode=0x%X) failed with RC=0x%08X, errno=%d" % (filename, mode, result.fd, self.errno()))
660
        return result.fd
661
 
395 farthen 662
    @command(timeout = 30000)
346 theseven 663
    def file_size(self, fd):
664
        """ Gets the size of a file referenced by a handle """
665
        result = self.lib.monitorcommand(struct.pack("IIII", 31, fd, 0, 0), "III", ("size", None, None))
666
        if result.size > 0x80000000:
667
            raise DeviceError("file_size(fd=%d) failed with RC=0x%08X, errno=%d" % (fd, result.size, self.errno()))
668
        return result.size
394 farthen 669
 
395 farthen 670
    @command(timeout = 30000)
346 theseven 671
    def file_read(self, fd, addr, size):
672
        """ Reads data from a file referenced by a handle """
673
        result = self.lib.monitorcommand(struct.pack("IIII", 32, fd, addr, size), "III", ("rc", None, None))
674
        if result.rc > 0x80000000:
675
            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()))
676
        return result.rc
394 farthen 677
 
395 farthen 678
    @command(timeout = 30000)
346 theseven 679
    def file_write(self, fd, addr, size):
680
        """ Writes data from a file referenced by a handle """
681
        result = self.lib.monitorcommand(struct.pack("IIII", 33, fd, addr, size), "III", ("rc", None, None))
682
        if result.rc > 0x80000000:
683
            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()))
684
        return result.rc
685
 
395 farthen 686
    @command(timeout = 30000)
346 theseven 687
    def file_seek(self, fd, offset, whence):
688
        """ Seeks the file handle to the specified position in the file """
689
        result = self.lib.monitorcommand(struct.pack("IIII", 34, fd, offset, whence), "III", ("rc", None, None))
690
        if result.rc > 0x80000000:
691
            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()))
692
        return result.rc
693
 
395 farthen 694
    @command(timeout = 30000)
346 theseven 695
    def file_truncate(self, fd, length):
696
        """ Truncates a file referenced by a handle to a specified length """
697
        result = self.lib.monitorcommand(struct.pack("IIII", 35, fd, offset, 0), "III", ("rc", None, None))
698
        if result.rc > 0x80000000:
699
            raise DeviceError("file_truncate(fd=%d, length=0x%08X) failed with RC=0x%08X, errno=%d" % (fd, length, result.rc, self.errno()))
700
        return result.rc
701
 
395 farthen 702
    @command(timeout = 30000)
346 theseven 703
    def file_sync(self, fd):
704
        """ Flushes a file handles' buffers """
705
        result = self.lib.monitorcommand(struct.pack("IIII", 36, fd, 0, 0), "III", ("rc", None, None))
706
        if result.rc > 0x80000000:
707
            raise DeviceError("file_sync(fd=%d) failed with RC=0x%08X, errno=%d" % (fd, result.rc, self.errno()))
708
        return result.rc
709
 
395 farthen 710
    @command(timeout = 30000)
346 theseven 711
    def file_close(self, fd):
712
        """ Closes a file handle """
713
        result = self.lib.monitorcommand(struct.pack("IIII", 37, fd, 0, 0), "III", ("rc", None, None))
714
        if result.rc > 0x80000000:
715
            raise DeviceError("file_close(fd=%d) failed with RC=0x%08X, errno=%d" % (fd, result.rc, self.errno()))
716
        return result.rc
717
 
395 farthen 718
    @command(timeout = 30000)
346 theseven 719
    def file_close_all(self):
720
        """ Closes all file handles opened through the debugger """
721
        result = self.lib.monitorcommand(struct.pack("IIII", 38, 0, 0, 0), "III", ("rc", None, None))
722
        if result.rc > 0x80000000:
723
            raise DeviceError("file_close_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
724
        return result.rc
725
 
395 farthen 726
    @command(timeout = 30000)
346 theseven 727
    def file_kill_all(self):
728
        """ Kills all file handles (in the whole system) """
729
        result = self.lib.monitorcommand(struct.pack("IIII", 39, 0, 0, 0), "III", ("rc", None, None))
730
        if result.rc > 0x80000000:
731
            raise DeviceError("file_kill_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
732
        return result.rc
733
 
395 farthen 734
    @command(timeout = 30000)
346 theseven 735
    def file_unlink(self, filename):
736
        """ Removes a file """
737
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(filename), 40, 0, 0, 0, filename, 0), "III", ("rc", None, None))
738
        if result.rc > 0x80000000:
739
            raise DeviceError("file_unlink(filename=\"%s\") failed with RC=0x%08X, errno=%d" % (filename, result.rc, self.errno()))
740
        return result.rc
741
 
395 farthen 742
    @command(timeout = 30000)
346 theseven 743
    def file_rename(self, oldname, newname):
744
        """ Renames a file """
745
        result = self.lib.monitorcommand(struct.pack("IIII248s%dsB" % min(247, len(newname)), 41, 0, 0, 0, oldname, newname, 0), "III", ("rc", None, None))
746
        if result.rc > 0x80000000:
747
            raise DeviceError("file_rename(oldname=\"%s\", newname=\"%s\") failed with RC=0x%08X, errno=%d" % (oldname, newname, result.rc, self.errno()))
748
        return result.rc
749
 
395 farthen 750
    @command(timeout = 30000)
346 theseven 751
    def dir_open(self, dirname):
752
        """ Opens a directory and returns the handle """
753
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(dirname), 42, 0, 0, 0, dirname, 0), "III", ("handle", None, None))
754
        if result.handle == 0:
755
            raise DeviceError("dir_open(dirname=\"%s\") failed with RC=0x%08X, errno=%d" % (dirname, result.handle, self.errno()))
756
        return result.handle
757
 
395 farthen 758
    @command(timeout = 30000)
346 theseven 759
    def dir_read(self, handle):
760
        """ Reads the next entry from a directory """
761
        result = self.lib.monitorcommand(struct.pack("IIII", 43, handle, 0, 0), "III", ("version", "maxpath", "ptr"))
762
        if result.ptr == 0:
763
            raise DeviceError("dir_read(handle=0x%08X) failed with RC=0x%08X, errno=%d" % (handle, result.ptr, self.errno()))
764
        if result.version != 1:
765
            raise ValueError("Unknown version of dirent struct: %d" % result.version)
766
        dirent = self.read(result.ptr, result.maxpath + 16)
767
        ret = Bunch()
768
        (ret.name, ret.attributes, ret.size, ret.startcluster, ret.wrtdate, ret.wrttime) = struct.unpack("%dsIIIHH" % result.maxpath, dirent)
769
        ret.name = ret.name[:ret.name.index('\x00')]
770
        return ret
771
 
395 farthen 772
    @command(timeout = 30000)
346 theseven 773
    def dir_close(self, handle):
774
        """ Closes a directory handle """
775
        result = self.lib.monitorcommand(struct.pack("IIII", 44, handle, 0, 0), "III", ("rc", None, None))
776
        if result.rc > 0x80000000:
777
            raise DeviceError("dir_close(handle=0x%08X) failed with RC=0x%08X, errno=%d" % (handle, result.rc, self.errno()))
778
        return result.rc
779
 
395 farthen 780
    @command(timeout = 30000)
346 theseven 781
    def dir_close_all(self):
782
        """ Closes all directory handles opened through the debugger """
783
        result = self.lib.monitorcommand(struct.pack("IIII", 45, 0, 0, 0), "III", ("rc", None, None))
784
        if result.rc > 0x80000000:
785
            raise DeviceError("dir_close_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
786
        return result.rc
787
 
395 farthen 788
    @command(timeout = 30000)
346 theseven 789
    def dir_kill_all(self):
790
        """ Kills all directory handles (in the whole system) """
791
        result = self.lib.monitorcommand(struct.pack("IIII", 46, 0, 0, 0), "III", ("rc", None, None))
792
        if result.rc > 0x80000000:
793
            raise DeviceError("dir_kill_all() failed with RC=0x%08X, errno=%d" % (result.rc, self.errno()))
794
        return result.rc
795
 
395 farthen 796
    @command(timeout = 30000)
346 theseven 797
    def dir_create(self, dirname):
798
        """ Creates a directory """
799
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(dirname), 47, 0, 0, 0, dirname, 0), "III", ("rc", None, None))
800
        if result.rc > 0x80000000:
801
            raise DeviceError("dir_create(dirname=\"%s\") failed with RC=0x%08X, errno=%d" % (dirname, result.rc, self.errno()))
802
        return result.rc
803
 
395 farthen 804
    @command(timeout = 30000)
346 theseven 805
    def dir_remove(self, dirname):
806
        """ Removes an (empty) directory """
807
        result = self.lib.monitorcommand(struct.pack("IIII%dsB" % len(dirname), 48, 0, 0, 0, dirname, 0), "III", ("rc", None, None))
808
        if result.rc > 0x80000000:
809
            raise DeviceError("dir_remove(dirname=\"%s\") failed with RC=0x%08X, errno=%d" % (dirname, result.rc, self.errno()))
810
        return result.rc
811
 
394 farthen 812
    @command()
346 theseven 813
    def errno(self):
814
        """ Returns the number of the last error that happened """
815
        result = self.lib.monitorcommand(struct.pack("IIII", 49, 0, 0, 0), "III", ("errno", None, None))
816
        return result.errno
817
 
394 farthen 818
    @command()
346 theseven 819
    def disk_mount(self, volume):
820
        """ Mounts a volume """
821
        result = self.lib.monitorcommand(struct.pack("IIII", 50, volume, 0, 0), "III", ("rc", None, None))
822
        if result.rc > 0x80000000:
823
            raise DeviceError("disk_mount(volume=%d) failed with RC=0x%08X, errno=%d" % (volume, result.rc, self.errno()))
824
        return result.rc
825
 
394 farthen 826
    @command()
346 theseven 827
    def disk_unmount(self, volume):
828
        """ Unmounts a volume """
829
        result = self.lib.monitorcommand(struct.pack("IIII", 51, volume, 0, 0), "III", ("rc", None, None))
830
        if result.rc > 0x80000000:
831
            raise DeviceError("disk_unmount(volume=%d) failed with RC=0x%08X, errno=%d" % (volume, result.rc, self.errno()))
832
        return result.rc
833
 
441 farthen 834
    @command()
835
    def malloc(self, size):
836
        """ Allocates 'size' bytes and returns a pointer to the allocated memory """
442 farthen 837
        self.logger.debug("Allocating %d bytes of memory\n" % size)
441 farthen 838
        result = self.lib.monitorcommand(struct.pack("IIII", 52, size, 0, 0), "III", ("ptr", None, None))
442 farthen 839
        self.logger.debug("Allocated %d bytes of memory at 0x%x\n" % (size, result.ptr))
441 farthen 840
        return result.ptr
841
 
842
    @command()
843
    def memalign(self, align, size):
844
        """ Allocates 'size' bytes aligned to 'align' and returns a pointer to the allocated memory """
442 farthen 845
        self.logger.debug("Allocating %d bytes of memory aligned to 0x%x\n" % (size, align))
441 farthen 846
        result = self.lib.monitorcommand(struct.pack("IIII", 53, align, size, 0), "III", ("ptr", None, None))
442 farthen 847
        self.logger.debug("Allocated %d bytes of memory at 0x%x\n" % (size, result.ptr))
441 farthen 848
        return result.ptr
849
 
850
    @command()
851
    def realloc(self, ptr, size):
852
        """ The size of the memory block pointed to by 'ptr' is changed to the 'size' bytes,
853
            expanding or reducing the amount of memory available in the block.
854
            Returns a pointer to the reallocated memory.
855
        """
442 farthen 856
        self.logger.debug("Reallocating 0x%x to have the new size %d\n" % (ptr, size))
441 farthen 857
        result = self.lib.monitorcommand(struct.pack("IIII", 54, ptr, size, 0), "III", ("ptr", None, None))
442 farthen 858
        self.logger.debug("Reallocated memory at 0x%x to 0x%x with the new size %d\n" % (ptr, result.ptr, size))
441 farthen 859
        return result.ptr
860
 
861
    @command()
862
    def reownalloc(self, ptr, owner):
863
        """ Changes the owner of the memory allocation 'ptr' to the thread struct at addr 'owner' """
442 farthen 864
        self.logger.debug("Changing owner of the memory region 0x%x to 0x%x" % (ptr, owner))
441 farthen 865
        return self.lib.monitorcommand(struct.pack("IIII", 55, ptr, owner, 0), "III", (None, None, None))
866
 
867
    @command()
868
    def free(self, ptr):
869
        """ Frees the memory space pointed to by 'ptr' """
442 farthen 870
        self.logger.debug("Freeing the memory region at 0x%x\n" % ptr)
441 farthen 871
        return self.lib.monitorcommand(struct.pack("IIII", 56, addr, 0, 0), "III", (None, None, None))
872
 
346 theseven 873
 
171 farthen 874
class Lib(object):
401 farthen 875
    def __init__(self, logger):
876
        self.logger = logger
877
        self.logger.debug("Initializing Lib object\n")
171 farthen 878
        self.idVendor = 0xFFFF
879
        self.idProduct = 0xE000
176 farthen 880
 
881
        self.headersize = 0x10
882
 
883
        self.connect()
56 benedikt93 884
 
171 farthen 885
    def connect(self):
401 farthen 886
        self.dev = Dev(self.idVendor, self.idProduct, self.logger)
171 farthen 887
        self.connected = True
56 benedikt93 888
 
171 farthen 889
    def monitorcommand(self, cmd, rcvdatatypes=None, rcvstruct=None):
442 farthen 890
        self.logger.debug("Sending monitorcommand [0x%s]\n" % cmd[3::-1].encode("hex"))
269 farthen 891
        writelen = self.dev.cout(cmd)
171 farthen 892
        if rcvdatatypes:
893
            rcvdatatypes = "I" + rcvdatatypes # add the response
894
            data = self.dev.cin(struct.calcsize(rcvdatatypes))
895
            data = struct.unpack(rcvdatatypes, data)
896
            response = data[0]
427 farthen 897
            if libemcoredata.responsecodes[response] == "ok":
401 farthen 898
                self.logger.debug("Response: OK\n")
171 farthen 899
                if rcvstruct:
900
                    datadict = Bunch()
901
                    counter = 1 # start with 1, 0 is the id
902
                    for item in rcvstruct:
903
                        if item != None: # else the data is undefined
904
                            datadict[item] = data[counter]
905
                        counter += 1
906
                    return datadict
907
                else:
908
                    return data
427 farthen 909
            elif libemcoredata.responsecodes[response] == "unsupported":
401 farthen 910
                self.logger.debug("Response: UNSUPPORTED\n")
171 farthen 911
                raise DeviceError("The device does not support this command.")
427 farthen 912
            elif libemcoredata.responsecodes[response] == "invalid":
401 farthen 913
                self.logger.debug("Response: INVALID\n")
171 farthen 914
                raise DeviceError("Invalid command! This should NOT happen!")
427 farthen 915
            elif libemcoredata.responsecodes[response] == "busy":
401 farthen 916
                self.logger.debug("Response: BUSY\n")
171 farthen 917
                raise DeviceError("Device busy")
401 farthen 918
            else:
919
                self.logger.debug("Response: UNKOWN\n")
920
                raise DeviceError("Invalid response! This should NOT happen!")
269 farthen 921
        else:
922
            return writelen
56 benedikt93 923
 
924
 
171 farthen 925
class Dev(object):
401 farthen 926
    def __init__(self, idVendor, idProduct, logger):
171 farthen 927
        self.idVendor = idVendor
928
        self.idProduct = idProduct
67 benedikt93 929
 
401 farthen 930
        self.logger = logger
931
        self.logger.debug("Initializing Dev object\n")
932
 
171 farthen 933
        self.interface = 0
934
        self.timeout = 100
176 farthen 935
 
171 farthen 936
        self.connect()
937
        self.findEndpoints()
938
 
401 farthen 939
        self.logger.debug("Successfully connected to device\n")
342 farthen 940
 
941
        # Device properties
343 farthen 942
        self.packetsizelimit = Bunch()
943
        self.packetsizelimit.cout = None
944
        self.packetsizelimit.cin = None
945
        self.packetsizelimit.dout = None
946
        self.packetsizelimit.din = None
342 farthen 947
 
343 farthen 948
        self.version = Bunch()
342 farthen 949
        self.version.revision = None
950
        self.version.majorv = None
951
        self.version.minorv = None
952
        self.version.patchv = None
953
        self.swtypeid = None
954
        self.hwtypeid = None
955
 
343 farthen 956
        self.usermem = Bunch()
342 farthen 957
        self.usermem.lower = None
958
        self.usermem.upper = None
56 benedikt93 959
 
171 farthen 960
    def __del__(self):
961
        self.disconnect()
56 benedikt93 962
 
171 farthen 963
    def findEndpoints(self):
401 farthen 964
        self.logger.debug("Searching for device endpoints:\n")
171 farthen 965
        epcounter = 0
343 farthen 966
        self.endpoint = Bunch()
171 farthen 967
        for cfg in self.dev:
968
            for intf in cfg:
969
                for ep in intf:
970
                    if epcounter == 0:
401 farthen 971
                        self.logger.debug("Found cout endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 972
                        self.endpoint.cout = ep.bEndpointAddress
171 farthen 973
                    elif epcounter == 1:
401 farthen 974
                        self.logger.debug("Found cin endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 975
                        self.endpoint.cin = ep.bEndpointAddress
171 farthen 976
                    elif epcounter == 2:
401 farthen 977
                        self.logger.debug("Found dout endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 978
                        self.endpoint.dout = ep.bEndpointAddress
171 farthen 979
                    elif epcounter == 3:
401 farthen 980
                        self.logger.debug("Found din endpoint at 0x%x\n" % ep.bEndpointAddress)
343 farthen 981
                        self.endpoint.din = ep.bEndpointAddress
171 farthen 982
                    epcounter += 1
983
        if epcounter <= 3:
984
            raise DeviceError("Not all endpoints found in the descriptor. Only "+str(epcounter)+" found, we need 4")
56 benedikt93 985
 
171 farthen 986
    def connect(self):
427 farthen 987
        self.logger.debug("Looking for emCORE device\n")
171 farthen 988
        self.dev = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
989
        if self.dev is None:
990
            raise DeviceNotFoundError()
401 farthen 991
        self.logger.debug("Device Found!\n")
992
        self.logger.debug("Setting first configuration\n")
171 farthen 993
        self.dev.set_configuration()
56 benedikt93 994
 
171 farthen 995
    def disconnect(self):
996
        pass
102 benedikt93 997
 
171 farthen 998
    def send(self, endpoint, data):
999
        size = self.dev.write(endpoint, data, self.interface, self.timeout)
1000
        if size != len(data):
176 farthen 1001
            raise SendError("Not all data was written!")
171 farthen 1002
        return len
102 benedikt93 1003
 
171 farthen 1004
    def receive(self, endpoint, size):
1005
        read = self.dev.read(endpoint, size, self.interface, self.timeout)
1006
        if len(read) != size:
176 farthen 1007
            raise ReceiveError("Requested size and read size don't match!")
171 farthen 1008
        return read
56 benedikt93 1009
 
171 farthen 1010
    def cout(self, data):
401 farthen 1011
        self.logger.debug("Sending data to cout endpoint with the size " + str(len(data)) + "\n")
343 farthen 1012
        if self.packetsizelimit.cout and len(data) > self.packetsizelimit.cout:
171 farthen 1013
            raise SendError("Packet too big")
343 farthen 1014
        return self.send(self.endpoint.cout, data)
94 benedikt93 1015
 
171 farthen 1016
    def cin(self, size):
401 farthen 1017
        self.logger.debug("Receiving data on the cin endpoint with the size " + str(size) + "\n")
343 farthen 1018
        if self.packetsizelimit.cin and size > self.packetsizelimit.cin:
171 farthen 1019
            raise ReceiveError("Packet too big")
343 farthen 1020
        return self.receive(self.endpoint.cin, size)
94 benedikt93 1021
 
171 farthen 1022
    def dout(self, data):
401 farthen 1023
        self.logger.debug("Sending data to cout endpoint with the size " + str(len(data)) + "\n")
343 farthen 1024
        if self.packetsizelimit.dout and len(data) > self.packetsizelimit.dout:
171 farthen 1025
            raise SendError("Packet too big")
343 farthen 1026
        return self.send(self.endpoint.dout, data)
94 benedikt93 1027
 
171 farthen 1028
    def din(self, size):
401 farthen 1029
        self.logger.debug("Receiving data on the din endpoint with the size " + str(size) + "\n")
343 farthen 1030
        if self.packetsizelimit.din and size > self.packetsizelimit.din:
171 farthen 1031
            raise ReceiveError("Packet too big")
343 farthen 1032
        return self.receive(self.endpoint.din, size)
56 benedikt93 1033
 
96 benedikt93 1034
 
171 farthen 1035
if __name__ == "__main__":
396 farthen 1036
    from misc import Logger
1037
    logger = Logger()
1038
    if sys.argv[1] == "test":
1039
        # Some tests
1040
        import sys
427 farthen 1041
        emcore = Emcore()
1042
        resp = emcore.getversioninfo()
1043
        logger.log("Emcore device version information: " + libemcoredata.swtypes[resp.swtypeid] + " v" + str(resp.majorv) + "." + str(resp.minorv) + 
1044
                         "." + str(resp.patchv) + " r" + str(resp.revision) + " running on " + libemcoredata.hwtypes[resp.hwtypeid] + "\n")
1045
        resp = emcore.getusermemrange()
396 farthen 1046
        logger.log("Usermemrange: "+hex(resp.lower)+" - "+hex(resp.upper)+"\n")
1047
        memaddr = resp.lower
1048
        maxlen = resp.upper - resp.lower
427 farthen 1049
        f = open("./emcore.py", "rb")
1050
        logger.log("Loading test file (emcore.py) to send over USB...\n")
396 farthen 1051
        datastr = f.read()[:maxlen]
1052
        logger.log("Sending data...\n")
427 farthen 1053
        emcore.write(memaddr, datastr)
396 farthen 1054
        logger.log("Encrypting data with the hardware key...\n")
427 farthen 1055
        emcore.aesencrypt(memaddr, len(datastr), 0)
1056
        logger.log("Reading data back and saving it to 'libemcore-test-encrypted.bin'...\n")
1057
        f = open("./libemcore-test-encrypted.bin", "wb")
1058
        f.write(emcore.read(memaddr, len(datastr)))
396 farthen 1059
        logger.log("Decrypting the data again...\n")
427 farthen 1060
        emcore.aesdecrypt(memaddr, len(datastr), 0)
396 farthen 1061
        logger.log("Reading data back from device...\n")
427 farthen 1062
        readdata = emcore.read(memaddr, len(datastr))
396 farthen 1063
        if readdata == datastr:
1064
            logger.log("Data matches!")
1065
        else:
1066
            logger.log("Data does NOT match. Something went wrong")
1067
 
1068
    elif sys.argv[1] == "gendoc":
1069
        # Generates Documentation
1070
        from misc import gendoc
1071
        logger.log("Generating documentation\n")
1072
        cmddict = {}
427 farthen 1073
        for attr, value in Emcore.__dict__.iteritems():
396 farthen 1074
            if getattr(value, 'func', False):
1075
                if getattr(value.func, '_command', False):
1076
                    cmddict[value.func.__name__] = value
441 farthen 1077
        logger.log(gendoc(cmddict))
1078
 
1079
    elif sys.argv[1] == "malloctest":
1080
        emcore = Emcore()
1081
        logger.log("Allocating 200 bytes of memory: ")
1082
        addr = emcore.malloc(200)
1083
        logger.log("0x%x\n" % addr)
1084
        logger.log("Reallocating to 2000 bytes: ")
1085
        addr = emcore.realloc(addr, 2000)
1086
        logger.log("0x%x\n" % addr)
1087
        logger.log("Freeing 0x%x\n" % addr)
1088
        emcore.free(addr)
1089
        logger.log("Allocating 1000 bytes of memory aligned to 100 bytes: ")
1090
        addr = emcore.memalign(100, 1000)
1091
        logger.log("0x%x\n" % addr)
1092
        logger.log("Freeing 0x%x\n" % addr)
1093
        emcore.free(addr)