2014年1月9日 星期四

在 linux 下讓 sdk 可以正確偵測 g2


  1. 將手機連線方式改成"數據連線"
  2. 開啟 debug 模式
  3. 跑下面指令
  4. sudo ./adb kill-server
    sudo ./adb start-server
    sudo ./adb devices
    這樣 sdk 就可以正確偵測到 g2 手機了

參考連結

2014年1月6日 星期一

Arduino LCD KeyPad Shield 的測試程式碼

Arduino LCD KeyPad Shield 的測試程式碼

//Sample using LiquidCrystal library
#include <LiquidCrystal.h>
 
/*******************************************************
 
This program will test the LCD panel and the buttons
Mark Bramwell, July 2010
 
********************************************************/
 
// select the pins used on the LCD panel
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
 
// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5
 
// read the buttons
int read_LCD_buttons()
{
 adc_key_in = analogRead(0);      // read the value from the sensor 
 // my buttons when read are centered at these valies: 0, 144, 329, 504, 741
 // we add approx 50 to those values and check to see if we are close
 if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
 // For V1.1 us this threshold
 if (adc_key_in < 50)   return btnRIGHT;  
 if (adc_key_in < 250)  return btnUP; 
 if (adc_key_in < 450)  return btnDOWN; 
 if (adc_key_in < 650)  return btnLEFT; 
 if (adc_key_in < 850)  return btnSELECT;  
 
 // For V1.0 comment the other threshold and use the one below:
/*
 if (adc_key_in < 50)   return btnRIGHT;  
 if (adc_key_in < 195)  return btnUP; 
 if (adc_key_in < 380)  return btnDOWN; 
 if (adc_key_in < 555)  return btnLEFT; 
 if (adc_key_in < 790)  return btnSELECT;   
*/
 
 
 return btnNONE;  // when all others fail, return this...
}
 
void setup()
{
 lcd.begin(16, 2);              // start the library
 lcd.setCursor(0,0);
 lcd.print("Push the buttons"); // print a simple message
}
  
void loop()
{
 lcd.setCursor(9,1);            // move cursor to second line "1" and 9 spaces over
 lcd.print(millis()/1000);      // display seconds elapsed since power-up
 
 
 lcd.setCursor(0,1);            // move to the begining of the second line
 lcd_key = read_LCD_buttons();  // read the buttons
 
 switch (lcd_key)               // depending on which button was pushed, we perform an action
 {
   case btnRIGHT:
     {
     lcd.print("RIGHT ");
     break;
     }
   case btnLEFT:
     {
     lcd.print("LEFT   ");
     break;
     }
   case btnUP:
     {
     lcd.print("UP    ");
     break;
     }
   case btnDOWN:
     {
     lcd.print("DOWN  ");
     break;
     }
   case btnSELECT:
     {
     lcd.print("SELECT");
     break;
     }
     case btnNONE:
     {
     lcd.print("NONE  ");
     break;
     }
 }
 
}


出處:
http://www.dfrobot.com/wiki/index.php/Arduino_LCD_KeyPad_Shield_(SKU:_DFR0009)

2014年1月5日 星期日

cross compile python for arm

這裡是編譯 Python 3.3.3 的方法

1. 建立 config.site,檔案內容如下

ac_cv_file__dev_ptmx=no
ac_cv_file__dev_ptc=no 


2.  在 python 3.3.3 的目錄下依序輸入以下指令。cross compiler 的相關變數你改成你系統的。



CONFIG_SITE=config.site CC=arm-linux-gcc CXX=arm-linux-g++ AR=arm-linux-ar RANLIB=arm-linux-ranlib ./configure --host=arm-linux --build=x86_64-linux-gnu --prefix=/python LDFLAGS="-static -static-libgcc" CPPFLAGS="-static -march=armv4t" --disable-ipv6
make HOSTPYTHON=./hostpython HOSTPGEN=./Parser/hostpgen BLDSHARED="arm-linux-gcc -static" CROSS_COMPILE=arm-linux- CROSS_COMPILE_TARGET=yes HOSTARCH=arm-linux BUILDARCH=x86_64-linux-gnu
 make install HOSTPYTHON=./hostpython BLDSHARED="arm-linux-gcc -static" CROSS_COMPILE=arm-linux- CROSS_COMPILE_TARGET=yes prefix=~/mypython

參考資料:

http://randomsplat.com/id5-cross-compiling-python-for-embedded-linux.html
http://bugs.python.org/msg136962

2014年1月4日 星期六

x86 qemu 使用方式

讓 qemu 指執行 kenel
sudo qemu-system-x86_64 -kernel /boot/vmlinuz-3.8.0-19-generic -m 256
這段指令執行到最後會發生 kernel panic 。因為找不到 root
sudo qemu-system-x86_64 -kernel /boot/vmlinuz-3.8.0-19-generic -initrd /boot/initrd.img-3.8.0-19-generic -append "root=/ram/" -m 256
上面這個指令複雜一些,kenel 會讀取 initrd (用來讀取其他檔案系統的玩意,細節) 。他會執行這個執行檔在 initrd 裡的 /init 這個執行檔,最後會失敗。進入 terminal 模式。你可以打 cat /init 看他做了什麼。


讓 cubie truck 從 sd 卡開機


這裡只是簡單的描述,細節請看 http://docs.cubieboard.org/zh/tutorials/ct1/installation/install_lubuntu_desktop_server_to_sd_card#make_bootable_sd_card

  1. 下載 u-boot,bootfs,rootfs
  2. 清除 sd 卡
    • sudo dd if=/dev/zero of=${card} bs=1024 seek=544 count=128
  3. 把 u-boot 寫進 sd 卡。
    • sudo dd if=u-boot-sunxi-with-spl-ct-20131102.bin of=$card bs=1024 seek=8
  4. 再做磁碟分割,bootfs(第一個磁區) 要 ext2,第二個磁區要 ext4,像這樣(sdd 會隨每個電腦環境不同而有所不同)
    1. Device Boot      Start         End      Blocks   Id  System
      /dev/sdd1            2048      133119       65536   83  Linux
      /dev/sdd2          133120    15278079     7572480   83  Linux
  5. 建立檔案系統並把 bootfs 和rootfs 寫進你剛剛新建的磁區
    1. $mkdir /tmp/sdd1 /tmp/sdd2
      $sudo mount -t ext2 ${card}1 /tmp/sdd1
      $sudo mount -t ext4 ${card}2 /tmp/sdd2
      $sudo tar -C /tmp/sdd1 -xvf bootfs-part1.tar.gz
      $sudo tar -C /tmp/sdd2 -xvf rootfs-part2.tar.gz
      $sync
      $sudo umount /tmp/sdd1
      $sudo umount /tmp/sdd2

2014年1月1日 星期三

在 qemu 底下模擬 Raspberry Pi


1. 安裝 qemu-system-arm

2. 下載 http://xecdesign.com/downloads/linux-qemu/kernel-qemu

3. 執行下面程式碼

qemu-system-arm -kernel kernel-qemu -cpu arm1176 -m 256 -M versatilepb -no-reboot -serial stdio -append "root=/dev/sda2 panic=1 rootfstype=ext4 rw" -hda 2013-09-25-wheezy-raspbian.img

重點就那個 kernel image 和 qemu 的參數,詳情請看參考連結。

參考連結:
http://xecdesign.com/qemu-emulating-raspberry-pi-the-easy-way/

2013年12月31日 星期二

編譯 busybox 並建立一個linux 系統


編譯 busybox 把 arm-none-linux-gnueabi- 換成你的編譯器。然後記得靜態編譯 busybox(在 menuconfig 裡選擇)
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- defconfig
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- menuconfig
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi-
make ARCH=arm CROSS_COMPILE=arm-none-linux-gnueabi- install
編譯完後的檔案會放在 _install。把他做成 img
$ cd _install
$ find . | cpio -o --format=newc > ../rootfs.img

你可以用下面指令測試一下
qemu-system-arm -M versatilepb -m 128M -kernel zImage -initrd rootfs.img -append "root=/dev/ram rdinit=/bin/sh"

建立系統必要的目錄
$ cd _install
$ mkdir proc sys dev etc etc/init.d
$ cd ..




新增一個檔案,_install/etc/init.d/rcS,加入下面的內容
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
/sbin/mdev -s


讓剛剛的檔案可以被執行

chmod +x _install/etc/init.d/rcS
最後的驗收

qemu-system-arm -M versatilepb -m 128M -kernel zImage -initrd rootfs.img.gz -append "root=/dev/ram rdinit=/sbin/init"
參考資料

arm cross compile 常用指令備忘



製作 initramfs image

find . | cpio -H newc -o | gzip -9 > /boot/initrd.img
或是
find . | cpio -H newc -o > rootfs
解壓縮 initramfs image

gunzip -c /boot/initrd.img-2.6.24-19-generic | cpio -i

修改 initrd image

mount -t ext2 -o loop initrd.img temp/

編譯 arm 核心,arm-linux-gnueabi-請換成你用 cross_compiler

make ARCH=arm versatile_defconfigmake ARCH=arm menuconfig
make ARCH=arm CROSS_COMPILE=arm-linux-gnueabi- all

編譯完後,核心路徑在 arch/arm/boot


qemu-system-arm -M versatilepb -m 128M -kernel zImage -no-reboot


第一支程式

#include <stdio.h>
int main() {  printf("Hello World!\n");  while(1);}


編譯第一支程式
arm-linux-gnueabi-gcc -static    test.c   -o test 
製作 rootfs
echo test | cpio -o --format=newc > rootfs
執行第一支程式
qemu-system-arm -M versatilepb -m 128M -kernel zImage -initrd rootfs -append "root=/dev/ram rdinit=/test" -no-reboot
啟動核心後,核心會執行你的程式。

其他:如果你要測試編譯出來的程式,也可以直接用下面指令。
qemu-arm -L /usr/arm-linux-gnueabi/ a.out

參考資料

http://backreference.org/2010/07/04/modifying-initrdinitramfs-files/
http://balau82.wordpress.com/2010/03/22/compiling-linux-kernel-for-qemu-arm-emulator/

2013年12月29日 星期日

簡介 python 的物件生成 ( how to generate an instance in python)

    在開始介紹 python 怎麼產生 instnace 前,先來看一段簡單的程式碼


class MyStr1(str):
    def __init__(self, a='', b=''):
        super(MyStr1, self).__init__()
        self.a = a
        self.b = b


    這段程式碼看起來沒什麼,就繼承自 str 。然後 override __init__ 方法。所以我們可以用下面程式碼產生 instance。


 a = MyStr1("1")

   可是當我們執行下面程式碼時,

 a = MyStr1("1", "2")


    卻會出現

Traceback (most recent call last):
  File "", line 1, in 
TypeError: str() takes at most 1 argument (2 given)

    這到底發生什麼事? 會出現這個錯誤,是因為 str.__new__ 這個方法只接受一個參數,而你給他兩個。

    做個簡單的實驗。執行這兩行 str.__new__(str) 和 str.__new__(str, '1') 程式碼不會出錯。然而 str.__new__(str, '1', '2') 會出現上面的錯誤。所以可以合理懷疑問題真的出在這了。

     接下來來談一個 class 怎麼產生 instance。當 class 要產生 instance 時,他會呼叫 class 的 metaclss 的 __call__ 方法。而 metaclass 的 __call__ 方法大概長這樣:

def __call__(cls, *args, **kwargs):
    obj = cls.__new__(cls, *args, **kwargs)
    obj.__init__(*args, **kwargs)
    return obj

    所以執行 a = MyStr1("1", "2") 時,直譯器會先做 obj = str.__new__(str, *args, **kwargs) ,其中 *args 是 (1, 2, 3),可是因為 str.__new__ 只接受一個參數,因此發生錯誤。

    要怎麼知道直譯器在建立 instance 時,會把類別名稱後面的參數全都丟進 __new__ 和 __init__ 裡呢? 用一段簡單的程式即可說明。



class ClsA(object):
    def __init__(self, *args, **kwargs):
        print 'init: ', args, kwargs

    def __new__(cls, *args, **kwargs):
        print 'new: ', args, kwargs
        return super(ClsA, cls).__new__(cls, *args, **kwargs)

  
a = ClsA('a', 'b', 2)


   上面程式碼,當要建立 ClsA 的程式碼,他會先執行 __new__,而餵給 __new__ 的參數則是 ClsA 後面的參數。之後再把 ClsA 後面的參數餵給 __init__。而這也說明了為什麼一開始的程式碼會有問題。因為建立 instance 時,預設行為是把類別後面的參數全都丟給 __new__ 和 __init__。可是 str.__new__最多只接受一個參數,因此出錯。

    要如何解決第一個程式所遇到的問題呢?
    解法1.
    不要使用預設的 metaclass(type),自訂一個 meta class


class CustomMetaCls(type):
    def __call__(cls, *args, **kwargs):
        if len(args):
            content = args[0]
        else:
            content = ''
        obj = cls.__new__(cls, content)
        obj.__init__(*args, **kwargs)
        return obj

  
class MyStr(str):
    __metaclass__ = CustomMetaCls
 
    def __init__(self, a='', b=''):
        super(MyStr, self).__init__(a)
        self.a = a
        self.b = b


b = MyStr('a', 'b')


    解法2.
    override __new__

class MyStr1(str):
    def __init__(self, a='', b=''):
        super(MyStr1, self).__init__()
        self.a = a
        self.b = b

    def __new__(cls, *args, **kwargs):
        print args, kwargs
        if len(args):
            content = args[0]
        else:
            content = ''
        return str.__new__(cls, content)

2013年12月25日 星期三

docker 原理簡介

    Docker 官網上的簡介,寫了"Docker is an open-source project to easily create lightweight, portable, self-sufficient containers from any application."。不過 containers 是啥呢? 有點難解釋,基本上可以想像成一個 sandbox。不過 docker 還可以在上面跑完整的 linux distributions。

    先看看 Docker 怎麼實作的。他是建立在 lxc 和 aufs 的基礎上。那 lxc 是什麼呢? 官網上講"LXC is a userspace interface for the Linux kernel containment features."。官網上還有這一段話。

Features

Current LXC uses the following kernel features to contain processes:
  • Kernel namespaces (ipc, uts, mount, pid, network and user)
  • Apparmor and SELinux profiles
  • Seccomp policies
  • Chroots (using pivot_root)
  • Kernel capabilities
  • Control groups (cgroups)
    他用到 kernel 許多特性,不過和 container 有關的主要是 kernel namespace 和 control groups。不過能做到 container 主要是靠 kernel namespace。


    namespace 是什麼呢? 以 pid namespace 為例,在每個 namespace 裡,每個 pid 都是唯一的。而不同的 namespace 裡, pid 可以重複。因此在 A namespace 哩,會有一個自以為 pid = 1 的程序,在 B namespace 哩,也會有一個自以為 pid = 1 的程序。如果 A 和 B 繼承自最上層的 namespace (也就是 host 所在的 namespace,叫做 C namespace ),那麼從 C namespace 的觀點來看,前面那兩個自以為是 pid = 1 的程序,其實他的 pid 都不為 1 。這樣可以做到程序隔離的功能,也可以做到虛擬化。 lxc 用到的 namespace 就 ipc, uts, mount, pid, network and user。這篇文章有詳細說明 docker 用到的 namespace 作用。http://blog.dotcloud.com/under-the-hood-linux-kernels-on-dotcloud-part

    這樣要怎麼做到模擬作業系統呢? 一個 linux distributions 就是一個 linux kernel 加上很多其他程式。 namespace 沒辦法跑 kernel。不過那不重要,反正核心都差不多。剩下的程式,就可以把它丟進 namespace 跑,而那些程式在跑的時候,會以為整台電腦都是他的(因為被 namespace) 隔離了。所以他會建立 init(pid = 1) 程序,再做一些其他開機步驟。有 system call 就由 host 的 kernel 來處理。他活在虛擬的世界,還活得很開心。

虛線表示那兩個是同一個。箭頭表示程序間的父子關係。有箭頭的表示子程序。

                       
    如上圖所示, A namespace 的程序無法看到 root namespace 的程序。因此,我們可以在 A namespace 跑 centos 的開機程序,也可跑 ubuntu 的開機程序。在 A namespace 哩,無法察覺 root namespace 存在,他們會以為自己就是 root namespace。

    解決了程序的問題後,還有一個問題,檔案系統。基本上,用原本系統的檔案系統即可做到模擬作業系統,不過 docker 選擇使用 aufs,選用 aufs 還有個好處是可以做版本控制。

    Aufs,全名叫 advanced multi layered unification filesystem。恩,名字不太重要。基本上就分層。以下圖為例:

                                   


       上圖表示至少兩個檔案系統,你可以從 Delete file B 這個往下看,那你看到的檔案系統會是對 Base 加了C(B一加刪,最後看不到)。而從 Add file E 往下看,則看到的檔案系統是對 Base 加了 ADE 這三個檔案。每層只記錄和上一層的差異。要顯示完整的作業系統則把自己到 base 各層 union 起來。

       介紹完 lxc 和 aufs , 來看看 docker 如何整合。



    如上圖所示, docker 把客端作業系統安裝在 aufs 上,你可以 commit 你的修改,他會把你的修改當作一層新的 layer 蓋在上一層。當你要 run 客端作業系統時,他會在你要跑的 image 上面再蓋一層,叫做 container(image 是 read only)。之後 docker 會建立新的 namespace,把 namespace 的 root directory,然後執行 debian 的 init 程序(開機程序),這樣客端作業系統就成功執行了。


如果你想更了解 docker,強烈推薦閱讀  http://blog.dotcloud.com/category/under-the-hood
也可以參考我演講投影片:http://www.slideshare.net/ya790026/docker-33456641

參考資料: