2010年5月31日 星期一

OPENRISC 4 UART SystemC

Hi all: this is a sample tutorial for "How to write a UART testbench in SystemC". 1.what's "UART" ? You can reference the UART Agenda firstly... or from WiKi Refs: UART Agenda , Serial UART information 2. How and How to work? 2-1. TX/RX (transfer/receiver) this is an asynchronous timing Sequence for UART TX/RX transition. In data (transfer/Receive),we should define our sample and receive rate to catch/push the accurate data. and it depend on our Baud rate and local clk frequency. in this formulation we can calculate out the clock numbers for UART per bit. // Calculate number of clocks per UART bit clocks_per_bit = (int)(clk_freq_hz/uart_baud); Example timing sequence for RX : start_Bit(1) -> star_Bit(0) -> Data_bit(D0) -> Data_bit(D1) ... -> Data_bit(7) -> Stop_Bit(0) -> Stop_Bit(1). 2-2. Baud rate set it define our bit resolution Ex: baud rate for RS232 Display should < %3, if we define our Fclk=12Mhz, smod=1. and we can find a good data resolution rage from XXX to XXX. Black Box Interface *.h (UART_Test_Bench)
class UartSC
  : public sc_core::sc_module
{
public:

  // Constructor
  UartSC (sc_core::sc_module_name  name);

  // The ports
  sc_in < bool >   clk;
  sc_in < bool >   uarttx;
  sc_out < bool >   uartrx;

  // Init function
  void initUart (int clk_freq_hz, int uart_baud) ;
  // Transmit (from ORPSoC) handling function
  void checkTx();

private:
  int clocks_per_bit;
  uint8_t current_char;
  int counter;
  int bits_received;

}; // UartSC ()
define our sensitive type
UartSC::UartSC (sc_core::sc_module_name   name):
  sc_module (name)
{

  SC_METHOD (checkTx);
  dont_initialize();
  sensitive << clk.pos();
  //sensitive << uarttx;
  
}
define our TX method
// Maybe do this with threads instead?!
void 
UartSC::checkTx () {

#ifdef UART_SC_DEBUG
  //printf("Uart TX activity: level is : 0x%x\n", uarttx.read()&1);
#endif
  
  // Check the number of bits received
  if (bits_received==0)
    {
      // Check if tx is low
      if ((uarttx.read()&1) == 0)
 { 
   // Line pulled low, begin receive of new char
   current_char = 0;
   // Start 
   counter = 1;
   bits_received++; // We got the start bit
#ifdef UART_SC_DEBUG
   cout << "UartSC checkTx: got start bit at time " << sc_time_stamp() << endl;
#endif
 }
    }
  else if (bits_received > 0 && bits_received < 9)
    {
      // Check the counter - see if it's time to sample the line
      // We do an extra half-bit delay on first bit read
      if ( ((bits_received==1) && 
     (counter == (clocks_per_bit + (clocks_per_bit/2)))) || 
    ((bits_received > 1) && (counter == clocks_per_bit)) )
 {
   //printf("UartSC checkTx: read bit %d as 0x%x at time", bits_received, uarttx.read()&1);
   //cout << sc_time_stamp() << endl;

   // Shift in the current value of the tx into our char
   current_char |= ((uarttx.read() & 1) << (bits_received-1));
   // Reset the counter
   counter = 1;
   // Increment bit number
   bits_received++;
 }
      else
 counter++;
    }
  else if (bits_received == 9)
    { 
      // Now check for stop bit 1
      if (counter == clocks_per_bit)
 {
   // Check that the value is 1 - this should be the stop bit
   if ((uarttx.read() & 1) != 1)
     {
       printf("UART TX framing error at time\n");
       cout << sc_time_stamp() << endl;

       // Perhaps do something else here to deal with this
       bits_received = 0;
       counter = 0;
     }
   else
     {
       // Print the char
#ifdef UART_SC_DEBUG
       printf("Char received: 0x%2x time: ", current_char);
       cout << sc_time_stamp() << endl;
#endif
       // cout'ing the char didn't work for some systems - jb 090613ol
       //cout << current_char;
       printf("%c",current_char);

       bits_received = 0;
       counter = 0;
     }
 }
      else
 counter++;
    }
}
Ref: http://opencores.org/openrisc,orpsocv21

2010年5月30日 星期日

OPENRISC 4 install

Install GNU toolchain
  • GNU binutils-2.18.50
  • GNU GCC-4.2.2
  • GNU GDB-6.8
  • uClibc-0.9.29
  • Linux-2.6.24
  • BusyBox-1.7.5
安裝 GNU toolchain 4 Linux env 1. 用 script 安裝 The script can be downloaded here. % sh MOF_ORSOC_TCHN_v5c_or32-elf.sh 如果沒有預設路徑, default 會在解壓縮的目錄下. 會產生 or32-build orpsocv2 or32-elf ... 2. 或者是下載以compile好的bin檔 , "Precompiled Toolchains" OpenRISC toolchain including GCC-4.2.2 with uClibc-0.9.29, GDB-6.8 and or1ksim-0.3.0, compiled under Ubuntu x86/i686 (32-bit) 3. 加入環境變數到 ~/.basrc export PATH=$PATH:/home/sean/prj/systemc/or32-elf/bin:/opt/or1ksim/bin Install SystemC 1. SystemC 2. SystemC TLM2.0 3 export Systemc to ~/.basrc export SYSTEMC_HOME=/home/sean/prj/systemc/systemc-2.2.0 export TLM_HOME=/home/sean/prj/systemc/TLM-2009-07-15 you can ref it : how to install Systemc in Cygwin platform Eclipse + SystemC + Cygwin Other Install
  • Icarus Verilog
  • System-Perl
  • Verilog-Perl
  • verilator
for Cycle accurate and event driver simulation Ref: http://opencores.org/openrisc,orpsocv2#overview

2010年5月23日 星期日

iPhone SPI case study

Spi
View more presentations from sean chen.

OpeniBoot 4 iPhone

OpeniBoot flow chart 4 iphone...
OpenIBootStart() < void OpenIBootStart () at openiboot.c:65> :
    setup_openiboot() < int setup_openiboot () at openiboot.c:393> :
        arm_setup()
        mmu_setup()
        tasks_setup()
        setup_devices() < int setup_devices () at openiboot.c:365> :
            miu_setup()
            power_setup()
            clock_setup()
            interrupt_setup()
            gpio_setup()
            timer_setup()
            event_setup()
            wdt_setup()
            usb_shutdown()
            uart_setup()
            i2c_setup()
            dma_setup()
            spi_setup()
        LeaveCriticalSection()
        clock_set_sdiv()
        aes_setup()
        nor_setup()
        syscfg_setup()
        images_setup()
        nvram_setup()
        lcd_setup()
        framebuffer_setup()
        audiohw_init()
    pmu_charge_settings()
    framebuffer_setdisplaytext()
    framebuffer_clear()
    nvram_getvar()
    strcmp()
    bufferPrintf()
    parseNumber()
    menu_setup()
    startUSB() < void startUSB () at openiboot.c:355> :
        usb_setup()
        usb_install_ep_handler()
        controlReceived() < void controlReceived (uint32_t token) at openiboot.c:235> :
            getScrollbackLen()
            usb_send_interrupt()
            usb_send_bulk()
            bufferPrintf()
            bufferFlush()
            usb_receive_bulk()
            usb_receive_interrupt()
        dataReceived() < void dataReceived (uint32_t token) at openiboot.c:290> :
            usb_receive_bulk()
            addToCommandQueue() < void addToCommandQueue (const char *command) at openiboot.c:154> :
                EnterCriticalSection()
                bufferPrintf()
                LeaveCriticalSection()
                malloc()
                strdup()
        controlSent() < void controlSent (uint32_t token) at openiboot.c:322> 
        dataSent() < void dataSent (uint32_t token) at openiboot.c:303> :
            usb_send_bulk()
            bufferPrintf()
            bufferFlush()
        usb_start()
        enumerateHandler() < void enumerateHandler (USBInterface *interface) at openiboot.c:326> :
            usb_add_endpoint()
            memalign()
        startHandler() < void startHandler () at openiboot.c:345> :
            usb_get_speed()
            usb_receive_interrupt()
    camera_setup()
    radio_setup()
    sdio_setup()
    wlan_setup()
    accel_setup()
    als_setup()
    nand_setup()
    fs_setup()
    pmu_set_iboot_stage()
    startScripting()
    DebugPrintf()
    audiohw_postinit()
    EnterCriticalSection()
    free()
    LeaveCriticalSection()
    processCommand() < void processCommand (char *command) at openiboot.c:185> :
        tokenize()
        strcmp()
        EnterCriticalSection()
        parseNumber()
        LeaveCriticalSection()
        free()
        bufferPrintf()

2010年5月21日 星期五

iPhone memory map table

Iphone 1.0.2 kernel memory map.

virt     len         phys     name
000 c0000000.07400000 -> 08000000
001 e0000000.00001000 -> 3cc00000 uart0, S5L8900XSerial, CalloutDevice=/dev/cu.iap, DialinDevice=/dev/tty.iap
002 e0097000.00002000 -> 38e00000 vic
003 e0099000.00001000 -> 3e200000 timer
004 ee79d000.00c00000 -> 0f400000 vram
005 ef39d000.00003000 -> 38e00000 vic, interrupt-controller
006 ef3a0000.00001000 -> 3e400000 gpio, interrupt-controller
007 ef3a1000.00001000 -> 39a00000 power
008 ef3a2000.00001000 -> 39a00000 power, gpio
009 ef3a3000.00001000 -> 3c500000 clkrstgen
010 ef3a4000.00001000 -> 38100000 clkrstgen
011 ef3a5000.00001000 -> 38200000 dmac0, DMA controller
012 ef3a6000.00001000 -> 39900000 dmac1, DMA controller
013 ef3a7000.00001000 -> 38000000 sha1, S5L8900XSHA1
014 ef3a8000.00001000 -> 38400000 usb-otg, S5L8900XUSBWrangler
015 ef3a9000.00003000 -> 38500000 amc
016 ef3ac000.0002c000 -> 22000000 amc
017 ef423000.00001000 -> 38800000 adm, S5L8900XFMC S5L8900XADM
018 ef424000.00001000 -> 38c00000 aes, S5L8900XAES
019 ef425000.00001000 -> 39000000 jpeg
020 ef444000.01000000 -> 3b000000 mbx, 16Mb, PowerVR MBX 3D graphics processor
021 f0444000.00001000 -> 3c300000 spi0, MerlotLCD
022 f0445000.00001000 -> 3c400000 otgphyctrl, USBWrangler
023 f0446000.00001000 -> 3c600000 i2c0, audio0, WM8758Audio, WM875XButtons HID, WM875xOutput, accelerometer LIS302DL, TSL2561 als, PCF50635PMU backlight&RTC&Power
024 f0447000.00001000 -> 3e300000 wdt, watchdog timer s5l8900x
025 f0448000.00001000 -> 3c900000 i2c1, camera0 Micron2020
026 f0449000.00001000 -> 3ca00000 i2s0, audio0, WM8758Audio, WM875XButtons, WM875xOutput
027 f044b000.00001000 -> 3cd00000 i2s1, baseband audio input/output
028 f044c000.00001000 -> 3ce00000 spi1, lcd0 merlot
029 f044d000.00001000 -> 3d200000 spi2, multi-touch z1, firmware based
030 f044e000.00100000 -> 24000000 nor-flash, 1048576 bytes
031 f0560000.00001000 -> 3cc04000 uart1, baseband, CalloutDevice=/dev/cu.baseband, DialinDevice=/dev/tty.baseband
032 f0561000.00001000 -> 3cc0c000 uart3, bluetooth, CalloutDevice=/dev/cu.bluetooth, DialinDevice=/dev/tty.bluetooth
033 f0576000.00001000 -> 3cc00000 uart0, S5L8900XSerial, CalloutDevice=/dev/cu.iap, DialinDevice=/dev/tty.iap
034 f0578000.00001000 -> 3cc10000 uart4, debug,  CalloutDevice=/dev/cu.debug, DialinDevice=/dev/tty.debug
035 f0579000.00140000 -> 18000000 edram, 1310720 bytes, iBEC loaded here
036 f06e2000.00001000 -> 38900000 clcd
037 f06e3000.00001000 -> 39600000 mpvd
038 f06e4000.00070000 -> 39600000 mpvd
039 f0754000.00001000 -> 39800000 h264bpd
040 f0755000.01000000 -> 3b000000 mbx, 16Mb, PowerVR MBX 3D graphics processor
041 f1755000.01000000 -> 3b000000 mbx
042 f278d000.00001000 -> 38d00000 sdio, MRVL868X, airport en0
043 f27e3000.00001000 -> 39700000 camin, H1CameraInterface
044 f27e5000.00c00000 -> 0f400000 vram

not kernel mapped, kexts not loaded ?

physical-addr     name
38a00000.1000  -> flash-controller0, NAND /dev/disk0, bsd minor 0, major 14, block size 2048
38f00000.1000  -> flash-controller0, NAND /dev/disk0, bsd minor 0, major 14, block size 2048
39100000.1000  -> tv-out
39200000.1000  -> tv-out
39300000.1000  -> tv-out
39610000.1000  -> mpvd
39630000.1000  -> mpvd
39641000.1000  -> mpvd
39650000.1000  -> mpvd
39660000.1000  -> mpvd
3e100000.1000  -> prng
3d000000.1000  -> pke
3e500000.1000  -> chipid
20000000.10000 -> vrom, 65536 bytes
24004000.2000  -> diagnostic-data, 8192 bytes
24006000.2000  -> diagnostic-data, 8192 bytes
240fc000.2000  -> nvram, 8192 bytes
240fe000.2000  -> nvram, 8192 bytes
24008000.f4000 -> raw-device, nor-flash, 999424 bytes

Ref: http://code.google.com/p/iphone-elite/wiki/MemoryMap

2010年5月20日 星期四

NDde....

底下是我為了解決RealDDE Crack時的替代方案,可參考底下的連結. Ref: 談談 C#.NET 連結 DDE Server 的設計觀 C# DDE 用戶端(Client) 的範本(含源碼下載與說明) from : Kenming's 軟體設計思維 NDde Source Code Ref: NDde from NDde 主要原因在於RealDDE 會透過API Access 的方式存取 DDE Client, 但是我們並沒有任何 Luck, Event trigger的機制, 導致 sample/(s) 的次數過大時, 會造成 "Exceed Limit" 的狀態. 解決方式: 1. 把 sample ratio 調小 2.更改 DDE Client TimeOut 的時間 $Win32::DDE::Client::Timeout = 1000; -> $Win32::DDE::Client::Timeout = 6000; 3. combine NDde 2 Our Environment.... call "NDde.dll " use Perl Win32 api ... NDde Client 原理
//include lib:
using NDde.Client;

// Create a client that connects to XQFAP|Quote. 
DdeClient client = new DdeClient("XQFAP", "Quote");

// Subscribe to the Disconnected event
client.Disconnected += OnDisconnected;

// Connect to the server. 
client.Connect();

// Syncronous Request Operation
Console.WriteLine("Request: " + client.Request("FITX*1.TF-Price", 60000));

// Asynchronous Request Operation
client.BeginRequest("FITX*1.TF-Price", 1, OnRequestComplete, client);

// Advise Loop
client.StartAdvise("FITX*1.TF-Price", 1, true, 60000);
client.Advise += OnAdvise;

//
        private static void OnRequestComplete(IAsyncResult ar)
        {
            try
            {
                DdeClient client = (DdeClient)ar.AsyncState;
                byte[] data = client.EndRequest(ar);
                Console.WriteLine("OnRequestComplete: " + Encoding.ASCII.GetString(data));
            }
            catch (Exception e)
            {
                Console.WriteLine("OnRequestComplete: " + e.Message);
            }
        }
....

other NDde applications [C#][WinForm]利用程式使用DDE(Dynamic Data Exchange)來打開PDF or ExcelViewer自動列印PDF or Excel檔案 [Office][C#]使用動態資料交換 (DDE) 將 EXCEL 檔案輸出至印表機進行列印

2010年5月19日 星期三

RealDDE 4 FuBon ... update lists

RealDDE 原理 http://funningboy.blogspot.com/2010/05/real-4-fubon-dde.html RealDDE + EntryRule(策略分析) http://funningboy.blogspot.com/2010/05/cdp-from-tsts.html 1. RealDDE 參數說明 my $QU = QUInfo->new(); $QU->QU_SIZ(10); // 定義Queue Size, 盡量不要設太大. $QU->QU_PT_OK_LAT(2); // 定義sample 的時間點, 目前是每兩秒 sample一次 $QU->QU_PT_NO_LAT(1); // 定義如果Queue滿了,要Delay多久在Return $QU->QU_GT_OK_LAT(0); // 定義 Put 到(策略)要Delay 多久, Default 0 $QU->QU_GT_NO_LAT(1); // 定義 Queue Empty時,要Delay多久在Return 2. 加入 Backup機制 如果DDESer Crack, 可以藉由歷史資料回補. 3. Include 轉檔好的 "期交所前日交易資料" 期交所 K 棒轉檔 4 upload 期貨契約 4 期交所 4. 加入 Normal Function Highest('high',Length,D); Lowest('low',Length,D); ...

2010年5月18日 星期二

serializer 1.6G ...

Hi all: this is a sample design for "Serializer 1.6G communication interface", i write it in Hspice based on TSMC 0.35 technology, and used the dynamic charge pump design, that can be locked fatly, used the Differential amplifier to reduce the noise and balance signal level to cable transform. if you like it, just take it, THX Serializer
View more presentations from sean chen.

Design Automation Tool from Behavior Level to Transaction Level for Virtual Bus-Based Platforms

Hi all: this is my thesis in master class(2008), i doing some researches for "High level (CDFG) 2 Low level(systemC) automatic mapped", i think it would useful for TLM designer, if you would like it, just take it THX. Defense
View more presentations from sean chen.

CDP 當沖程式 From TSTS星人

Target: Port TS 2 Our RealDDE Advantages : 1. flexible (NO TS, Met Server...) 2. Faster (Direct Link in Fubon DDE Server) 3. Memory (Memory Size Define by User) 4. replaceable (user can replace the entry rule easily) Disadvantages: 1. Cracker Fubon DDE Server is not stable, we should rerun it by hand. No automatic run. 2. CPU time / Memory if the Memory Size is so Deep, that would influence our performance and throughput. Sample Case: 分成兩大部分, RealDDE, TS->RealDDE(portable) RealDDE: 請參考 http://funningboy.blogspot.com/2010/05/real-4-fubon-dde.html TS->RealDDE(portable): 是用 TSTS星人所寫的 CDP 當沖程式(TS),改寫成我們的Format,且能跟RealDDE做結合. 可參考 TSTS 星人所寫的 CDP當沖程式跟原理. http://ts8.blogspot.com/2009/09/cdp.html?showComment=1273498372696#c4508543946141294345
PS: 回測績效請參考 TSTS星人用 (TS)跑的回測,這邊我們只是做Map的教學, 讓使用者能夠寫策略跟RealDDE做Link. Result:
PS: 本系統不俱自動下單功能,只有提示跟警示功能.

2010年5月17日 星期一

RealDDE 4 Fubon Server...

Target: 利用Real Time 的 DDE 做即時的進場/出場判斷機制. DDE 4 FuBon(富邦) 一些基本的定義,可參考底下的連結. http://funningboy.blogspot.com/2010/02/dde-server-for-stock.html Design Flow: Advantages: 1.利用 Thread 的方式增加系統的效能. 2.Entry Rule 可針對特定的StockID 有不同的進出場方式. 3.利用Queue來增加系統的穩定性,避免Latency 4 Proc, 拖垮系統的效能. CostFunc: Memory(記憶體), CPU Time處理速度...

Sample : 底下用最簡單的 Sample 當例子. Entry Rule : 當連續10筆資料中, 出現 "成交價 大於 買進價 且 成交量 大於等於 100 的次數" 大於 10*2/3=6 次, 就告知可以做買進的動作. 當然你也可以自己定義你的進出場訊號.最後在接回Display, 或者是 Internet 傳送.... Code
use Class::Struct; #use strict; use Win32::DDE::Client; use Win32::DDE; use Data::Dumper; use threads qw(yield); use Thread; use Thread::Queue; use threads::shared; #no warnings 'threads'; # example 4 2330.TW ########################################################## #2330.TW-ID //&#20195;&#30908; #2330.TW-Name //&#21830;&#21697; #2330.TW-Time //&#26178;&#38291; #2330.TW-Bid //&#36023;&#36914; #2330.TW-Ask //&#36067;&#20986; #2330.TW-Price //&#25104;&#20132; #2330.TW-Volume //&#21934;&#37327; #2330.TW-TotalVolume //&#32317;&#37327; #2330.TW-High //&#26368;&#39640; #2330.TW-Low //&#26368;&#20302; #2330.TW-AvgPrice //&#22343;&#20729; ########################################################## # DDE Info definition struct( DDEInfo => { DDE_SER => '$', DDE_HOST => '$', }); my $DDE = DDEInfo->new(); $DDE->DDE_SER('XQFAP'); $DDE->DDE_HOST('Quote'); # Stock info 4 FuBon definition struct( STInfo => { ST_ID => '$', ST_NM => '$', ST_TM => '$', ST_BID=> '$', ST_ASK=> '$', ST_PRC=> '$', ST_VOL=> '$', ST_HIG=> '$', ST_LOW=> '$', }); # Queue Definition 4 DDE 2 Entry struct ( QUInfo => { QU_SIZ => '$', QU_PT_OK_LAT=> '$', QU_PT_NO_LAT=> '$', QU_GT_OK_LAT=> '$', QU_GT_NO_LAT=> '$', }); my $QU = QUInfo->new(); $QU->QU_SIZ(5); $QU->QU_PT_OK_LAT(1); $QU->QU_PT_NO_LAT(2); $QU->QU_GT_OK_LAT(1); $QU->QU_GT_NO_LAT(2); # Buffer Definition 4 Entry struct ( BUFInfo => { BUF_SIZ => '$', }); my $BUF = BUFInfo->new(); $BUF->BUF_SIZ(10); #==============================================# # Create Each Thread 4 StockID #==============================================# open (iStockIDPtr, "../../StockList.csv") die "Open StockList Error\n"; while(<iStockIDPtr>){ chomp; my $StockID = $_; my $q = Thread::Queue->new(); my $thr1 = threads->create(\&GetQueue,$StockID,$q); my $thr2 = threads->create(\&PutQueue,$StockID,$q); } #=============================================# # Run And Display #=============================================# for(;;){ my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time); $year += 1900; $mon += 1; my $MyEndTime = $year."/".$mon."/".$mday."/".$hour."::".$min."::".$sec; print "OK...".$MyEndTime."\n"; sleep 60; } sub PutQueue :locked { my $StockID = $_[0]; my $q = $_[1]; for(;;){ if($q->pending()<=$QU->QU_SIZ()){ my $t= &GetStockInfo($StockID); $q->enqueue($t); yield; sleep $QU->QU_PT_OK_LAT(); } else { yield; sleep $QU->QU_PT_NO_LAT(); } } } sub GetQueue :locked { my $StockID = $_[0]; my $q = $_[1]; for(;;){ if($q->pending()!=0 ){ $t = $q->dequeue; GetEntryInfo($StockID,$t); yield; sleep $QU->QU_GT_OK_LAT(); } else{ yield; sleep $QU->QU_GT_OK_LAT(); } } return $t; } sub GetStockInfo { my $StockID = $_[0]; my $Client = new Win32::DDE::Client ( $DDE->DDE_SER(), $DDE->DDE_HOST() ); die "Unable to initiate conversation" if $Client->Error; my ($ID,$NM,$TM,$BID,$ASK,$PRC,$VOL,$HIG,$LOW) = (-1,-1,-1,-1,-1,-1,-1,-1,-1); defined ( $ID = $Client->Request ($StockID.'-ID')) print "Error ID request\n"; defined ( $NM = $Client->Request ($StockID.'-Name')) print "Error NM request\n"; defined ( $TM = $Client->Request ($StockID.'-Time')) print "Error TM request\n"; defined ( $BID = $Client->Request ($StockID.'-Bid')) print "Error BID request\n"; defined ( $ASK = $Client->Request ($StockID.'-Ask')) print "Error ASK request\n"; defined ( $PRC = $Client->Request ($StockID.'-Price')) print "Error PRC request\n"; defined ( $VOL = $Client->Request ($StockID.'-Volume')) print "Error VOL request\n"; defined ( $HIG = $Client->Request ($StockID.'-High')) print "Error HIG request\n"; defined ( $LOW = $Client->Request ($StockID.'-Low')) print "Error LOW request\n"; my $t = STInfo->new(); $t->ST_ID($ID); $t->ST_NM($NM); $t->ST_TM($TM); $t->ST_BID($BID); $t->ST_ASK($ASK); $t->ST_PRC($PRC); $t->ST_VOL($VOL); $t->ST_HIG($HIG); $t->ST_LOW($LOW); return $t; } sub GetEntryInfo { my $StockID = $_[0]; my $t = $_[1]; my @ArrPtr = @{$BufHsPtr{$StockID}}; if( $#ArrPtr == $BUF->BUF_SIZ() ){ #print Dumper(\@ArrPtr); my $cot =0; for(my $i=0; $i<=$#ArrPtr; $i++){ if( $ArrPtr[$i]->ST_PRC() > $ArrPtr[$i]->ST_BID() && $ArrPtr[$i]->ST_VOL >= 100 ){ $cot++;} } if( $cot >= $#ArrPtr*2/3 ){ print "Found ::".$StockID." count( PRC>BID &&VOL >=100 )\n"; } shift( @{$BufHsPtr{$StockID}} ); } else { push ( @{$BufHsPtr{$StockID}}, $t); } }
code download http://sites.google.com/site/funningboy/perl_code/realtime3.pl?attredirects=0&d=1 PS: 轉碼後,中文註解部分是出現亂碼....

2010年5月8日 星期六

iPlayer ...

sample view http://www.gtkforums.com/about3818.html&highlight= http://blog.timc3.com/2009/02/10/mplayer-disable-lirc/ Sample *.sh id="dMH0bHeiRNg"; mplayer -vc ffflv -ac mp3 -cache 300 -prefer-ipv4 http://youtube.com/get_video.php?video_id=$id\&t=$(curl -s http://www.youtube.com/watch?v=$id | sed -n 's/.*, "t": "\([^"]*\)", .*/\1/p'); http://zetcode.com/tutorials/gtktutorial/gtkdialogs/ http://zetcode.com/tutorials/gtktutorial/chinese/gtklayoutmanagement/ http://stackoverflow.com/questions/2738173/how-do-i-make-the-gtk-code-work GTK apps http://gtk-apps.org/

2010年5月6日 星期四

IPhone Case Study

相信很多人對IPhone要如何 JailBreak感興趣, 底下就大概介紹 IPhone 是如何跟 ITune 溝通. Target : Communication Interface 4 IPhone and Itune
Env : Linux (Ubuntu) Lib : libusb-1.0 定義Usb裝置, configure Address, ID... usbmux 控制 Usb裝置, Create Link, Lock Link, Close Link... usbmuxlib ... libiphone 為iPhone 自己內建OS的Lib ifise 為Access iPhone Root 的proc (取的photo, music...) 透過 AFC 的格式.
Flow: iPhone 首先會跟 ITune 透過TCP protocl 建立連線, iPhone 會送出 ECID SHSH file(exclusive chip identification number), 跟 config( Mode type), usbmuxd 接收到這些訊號後會根據Mode Type 把資料往上送(libiphone), 當然在這之中 Apple 會對傳輸的資料作加密, 解密的動作. lipiphne 會根據收到的Package 回建成iphobe 的Data Based. 最後再透過 ifuse 來存取我們要的Data. Ex : ifuse : Read("/iphone/xxx.jpg"); libiphone : iPhone_Rd(0x00100000); command libusbmuxd : 0x00100000 -> 0x00001000; 編碼(加密 MD5, AES...) libusb : &Read(0x00001000); 傳送加密的data 到Iphone iPhone : 解密後, 再把Data 加密後往上送回libusb. libusb : 在往上送給libusbmuxd做判斷(解密). ... ifuse : 取得xxx.jpg的Path跟Inf Ref: http://www.omnia-repair.com/forum/topic/iphone-jtag Ref: libimobiledevice http://libimobiledevice.org/ eclipse CDT + iphone http://www.gbox.lt/drupal/en/node/44 IPhone Wiki http://theiphonewiki.com/wiki/index.php?title=Main_Page

2010年5月5日 星期三

In This Moment(Maria Brink)

偶然在網路上發現的圖體,主唱的唱法我還滿喜歡的,剛好也可以消一下今天"賠錢"的怨念.... 簡介: In This Moment is an American heavy metal band formed in 2005. They have released two albums to date, both on Century Media Records. The band's sound is recognizable mainly for vocalist Maria Brink's use of a combination of screaming and clean vocals. Ref: http://zh-hk.facebook.com/pages/In-This-Moment/123117872268?v=info

2010年5月4日 星期二

期貨契約 4 期交所

底下是對台指期留倉(未平倉,交易口數與契約金額) 的資料下載, 可以使用底下的程式抓期交所的 Data. 我們是透過 HTML parse 出我們要的Data. Link可參考 http://www.taifex.com.tw/chinese/3/7_12_3.asp 如果是對當日的成交筆數或者是每分K線有興趣可以參考 http://funningboy.blogspot.com/2010/04/k.html 程式碼 :
#!/usr/bin/perl -w
use strict;
use warnings;
use LWP::UserAgent;
use XML::Simple;
use Data::Dumper;
use HTML::TableExtract;

my %GbHsPtr;

GetHtml();
Exp2Exl();

sub GetHtml{
   
    my $ua = LWP::UserAgent->new;
    $ua->agent("MyApp/0.1");

    my $req = HTTP::Request->new(POST => 'http://www.taifex.com.tw/chinese/3/7_12_3.asp');
    my $res = $ua->request($req);
    return unless $res->is_success;
   
    #print $res->content();
    my $html_string = $res->content();
 
 my $te = HTML::TableExtract->new( depth => 4, count => 0);
    $te->parse($html_string);
 
 my $cot=0;
 my ($ID,$NM,$BYER,$TBC,$TBM,$TSC,$TSM,$TBSC,$TBSM,$RBC,$RBM,$RSC,$RSM,$RBSC,$RBSM);
 my ($NID,$NNM);

 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime(time);
    $year += 1900;
      $mon  += 1;
      
      if($mon<10){  $mon="0".$mon}
      if($mday<10){ $mday="0".$mday;}
      
my  $oMyFile = "../rem/".$year."_".$mon."_".$mday.".csv";
open (oMyFilePtr,">$oMyFile") || die "open oMyFile(Rem) Error";

 foreach my $ts ($te->tables) {
    foreach my $row ( $ts->rows ) { 
         my $st = join('.',@{$row});
            $st =~ s/\,//g; $st =~ s/\s+//g; $st=~ s/\./\,/g;
             
            printf oMyFilePtr ($st."\n");
           
          if($cot>=3 && $cot<=$#{$ts->rows}-4){
              ($ID,$NM,$BYER,$TBC,$TBM,$TSC,$TSM,$TBSC,$TBSM,$RBC,$RBM,$RSC,$RSM,$RBSC,$RBSM) = split(',',$st);
               
               if( $ID || $NM ){ ($NID,$NNM)=($ID,$NM); }
               else{             ($ID,$NM) = ($NID,$NNM)}
     
              $GbHsPtr{$NM}{$BYER} = {
                 "TBC" => $TBC,
                 "TBM" => $TBM,
                 "TSC" => $TSC,
                 "TSM" => $TSM,
                 "TBSC" => $TBSC,
                 "TBSM" => $TBSM,
                 "RBC"  => $RBC,
                 "RBM"  => $RBM,
                 "RSC"  => $RSC,
                 "RSM"  => $RSM,
                 "RBSC" => $RBSC,
                 "RBSM" => $RBSM,
                };
              }
              
          $cot++;
         }
      }
#    print Dumper (\%GbHsPtr);
}

sub Exp2Exl {
 
  my ($NM,$BYER,$file,$by);
  my %lt = (
    "&#33274;&#32929;&#26399;&#36008;" => "txf",
    "&#38651;&#23376;&#26399;&#36008;" => "exf",
    "&#37329;&#34701;&#26399;&#36008;" => "fxf",
    "&#23567;&#22411;&#33274;&#25351;" => "mxf",
  );
 
  my %By = (
    "&#33258;&#29151;&#21830;"     => "internal_bank",
    "&#25237;&#20449;"       => "internal_stock",   
    "&#22806;&#36039;&#21450;&#38520;&#36039;" => "external_stock",
    );
 
 my $oMyfile;
    foreach ( keys %GbHsPtr ){
        $NM =$_;
       
        if( defined($lt{$NM})){
            $file = $lt{$NM};
          
          foreach ( keys %{$GbHsPtr{$NM}} ){
              $BYER = $_;
              $by = $By{$BYER};
              
              $oMyfile = "../rem/".$file."/".$by.".csv";
              open(oMyFilePtr,">>$oMyfile") || die "open $oMyfile Error\n";
              
              my $TBC = $GbHsPtr{$NM}{$BYER}{"TBC"};
              my $TBM = $GbHsPtr{$NM}{$BYER}{"TBM"};
        my $TSC = $GbHsPtr{$NM}{$BYER}{"TSC"};
        my $TSM = $GbHsPtr{$NM}{$BYER}{"TSM"};
        my $TBSC = $GbHsPtr{$NM}{$BYER}{"TBSC"}
        my $TBSM = $GbHsPtr{$NM}{$BYER}{"TBSM"};
        my $RBC  = $GbHsPtr{$NM}{$BYER}{"RBC"};
        my $RBM  = $GbHsPtr{$NM}{$BYER}{"RBM"};       
        my $RSC  = $GbHsPtr{$NM}{$BYER}{"RSC"};   
        my $RSM  = $GbHsPtr{$NM}{$BYER}{"RSM"};   
        my $RBSC  = $GbHsPtr{$NM}{$BYER}{"RBSC"};     
        my $RBSM  = $GbHsPtr{$NM}{$BYER}{"RBSM"};   

              printf oMyFilePtr ("$TBC,$TBM,$TSC,$TSM,$TBSC,$TBSM,$RBC,$RBM,$RSC,$RSM,$RBSC,$RBSM\n");
             }
        }
    }
}
 
或者你可以下載打包好的 Path, 會有 code, rem, cur的資料夾 %code : 程式碼 %cur : 每日的 1分K 線 (可以自行定義成 5分K線) %rem : 成交筆數跟未平倉Data 使用步驟 %source fu_ticket.sh Download http://sites.google.com/site/funningboy/perl_code/future_v1.rar?attredirects=0&d=1