USB composite device example program, drag-and-drop flash writer.

Dependencies:   SWD USBDevice mbed BaseDAP

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers RamDisk.cpp Source File

RamDisk.cpp

00001 // RamDisk.cpp 2013/9/21
00002 #include "mbed.h"
00003 #include "RamDisk.h"
00004 #include "mydebug.h"
00005 
00006 RamDisk::RamDisk() : _head(NULL), use_size(0)
00007 {
00008     _sectors = 128; // 64KB(512*128)
00009 }
00010 
00011 int RamDisk::read(uint8_t * data, uint32_t block)
00012 {
00013     //DBG("block=%d", block);
00014     SectorData* p = find(block);
00015     if (p) {
00016         memcpy(data, p->data, 512);
00017         return 0;
00018     }
00019     memset(data, 0x00, 512);
00020     return 0;   
00021 }
00022 
00023 static bool is_blank(const uint8_t* data)
00024 {
00025     for(int i = 0; i < 512; i++) {
00026         if (data[i]) {
00027             return false;
00028         }
00029     }
00030     return true;
00031 }
00032 
00033 int RamDisk::write(const uint8_t * data, uint32_t block)
00034 {
00035     SectorData* p = find(block);
00036     if (p) {
00037         DBG("update block=%d", block);
00038         memcpy(p->data, data, 512);
00039         return 0;
00040     }
00041     if (is_blank(data)) {
00042         return 0;
00043     }   
00044     DBG("new block=%d", block);
00045     p = new SectorData;
00046     TEST_ASSERT(p);
00047     p->block = block;
00048     memcpy(p->data, data, 512);
00049     p->next = _head;
00050     _head = p;
00051     use_size += 512;
00052     //DBG("use_size: %d", use_size);
00053     TEST_ASSERT(use_size < (512*16));
00054     return 0;
00055 }
00056 
00057 uint32_t RamDisk::sectors()
00058 {
00059     return _sectors;
00060 }
00061 
00062 SectorData* RamDisk::find(uint16_t block)
00063 {
00064     SectorData* p = _head;
00065     while(p) {
00066         if (p->block == block) {
00067             break;
00068         }
00069         p = p->next;
00070     }
00071     return p;
00072 }
00073 
00074 void RamDisk::exportData(Stream* pc)
00075 {
00076     pc->printf("\n\n\n\n\n");
00077     SectorData* p = _head;
00078     while(p) {
00079         pc->printf("const uint8_t sector_%d[] = {\n", p->block);
00080         for(int i = 0; i < 512; i++) {
00081             pc->printf("0x%02x,", p->data[i]);
00082             if (i%16 == 15) {
00083                 pc->printf("\n");
00084             }
00085         }
00086         pc->printf("};\n");
00087         p = p->next;
00088     }
00089 
00090     pc->printf("const SectorIndex sector_index[] = {\n");
00091     p = _head;
00092     while(p) {
00093         pc->printf("{%d, sector_%d},\n", p->block, p->block); 
00094         p = p->next;
00095     }
00096     pc->printf("{-1, NULL},\n");
00097     pc->printf("};\n");
00098     pc->printf("\n\n\n\n\n");
00099 }