2008年10月28日 星期二

如何在數行內容中,插入/移除字元?

一般我們在編輯文件時,偶爾會需要對數行的內容插入或移除一些字元或符號,此時我們可以以下列的動作來完成:
1. )在vim的一般模式下,按「Ctrl + v」,此時會進入區塊選取模式。
2. )利用游標的方向鍵,選取適當的區塊。
3. )按「Shift + i」,進入插入模式。
4. )進行所需的修改。
5. )修改完後,按「ESC」結束區塊編輯模式。

2008年10月23日 星期四

How to drive usb device with libusb?

想要寫程式控制USB Device,又不想去碰Linux Driver的人有福了!您可以使用libusb來達成您的需求!

1.要透過libusb來操控USB Device,首先您需要安裝libusb。Debian的使用者操作指令如下:
-先尋找適當的usb套件。
$apt-cache search libusb
libftdi0 - Library to control and program the FTDI USB controller
libhid-dev - userspace USB HID development files
libhid0 - userspace USB HID access library
libusb++-0.1-4c2 - userspace C++ USB programming library
libusb++-dev - userspace C++ USB programming library development files
libusb-0.1-4 - userspace USB programming library
libusb-dev - userspace USB programming library development files
python-hid - Python wrapper for USB HID access library
sulu - File Mananger for Samsung Uproar and YEPP

-安裝libusb開發版本(Note:開發版才會有header file可供連結參考)
$apt-get install libusb-dev

2.撰寫程式尋找您要的USB Device。
#include

usb_dev_handle *dev_handle;

// Search device and open it
int devopen(void)
{
struct usb_bus *busses, *bus;
int c, i, a;
struct usb_device *dev;
usb_init();
usb_find_busses();
usb_find_devices();
busses = usb_get_busses();
for (bus = busses; bus; bus = bus->next) {
for (dev = bus->devices; dev; dev = dev->next) {
struct usb_device_descriptor *desc;
desc = &(dev->descriptor);
printf("Vendor/Product ID: %04x:%04x\n", desc->idVendor,
desc->idProduct);
if ((desc->idVendor == 0x1234) && (desc->idProduct == 0x4321)) {
goto a;
}
}
}
if ((bus == NULL) || (dev == NULL))
return -1;
a:
dev_handle = usb_open(dev);

if (dev_handle == NULL) {
printf("USB IO open failed.\n");
return -1;
}
usb_reset(dev_handle);
return 0;
}

// Output interface
// 0x02 is (Output direction | endpoint address).
// 2000 is time out value.
int devwrite(char *buffer, int len)
{
return usb_bulk_write(dev_handle, 0x02, buffer, len, 2000);
}

// Input interface
// 0x86 is (Input direction | endpoint address).
int devread(char *buffer, int len)
{
return usb_bulk_read(dev_handle, 0x86, buffer, len, 2000);
}

int main(void)
{
int result = 0;
char write_buffer[10] = {0};
char read_buffer[10] = {0};

result = devopen();
if (result < 0)
{
printf("Can't open usb device.\n");
} else
{
// send command to usb device.
write_buffer[0] = 0x0B;
write_buffer[1] = 0x01;
write_buffer[2] = 0x02;
result = devwrite(write_buffer, 3);
if (result == 3)
{
// get response from usb device
result = devread(read_buffer, 10);
}
}
return 0;
}

3.編譯上述程式
gcc -g -O0 -o xxx xxx.c -lusb

4.請使用Superuser權限執行它。或者將其檔案屬性進行變更。
chown root xxx
chgrp root xxx
chmod +s xxx

透過上述的機制,您將可以不用撰寫Linux USB Device Driver,即可操作Device Driver。


參考資料:
‧Jollen的Bolg--"libusb 簡介與第一個範例" (http://www.jollen.org/blog/2008/01/libusb_hello_world.html)
‧libusb Developers Guide (http://libusb.sourceforge.net/doc/index.html)
‧testlibusb.c (在libusb的source code中)

感謝Jserv的建議與協助,讓偶有機會做此嘗試。