<repo_name>weimingtom/learn<file_sep>/sys_program/player/src/inc/process_lrc.h
/* ************************************************************************
 *       Filename:  process_lrc.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 09時17分38秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __PTHREAD_LRC_H__
#define __PTHREAD_LRC_H__

extern uint src_segment(char *psrc, char *plines[], char *str);
extern uint line_segment(char *pline, char *pbuf[], char *str);
//extern LRC *build_link(char *lrc_pline[], char *ptitle[], int lines);
extern LRC *build_link(MPLAYER *pm,char *plines[],int lines);
extern LRC *dispose_lrc(MPLAYER *pm, char *name);
extern void show_lyric(LRC *pnode, int longest);
extern void mplayer_show_lyric(MPLAYER *pm, LRC *pnode);
//extern void mplayer_show_lyrtitle(MPLAYER *pm, char *title[]);
extern void mplayer_show_lyrtitle(MPLAYER *pm, char *ptitle, int i);

//void mplayer_show_lyric(MPLAYER *pm, int cur_time);

#endif



<file_sep>/network/1st_day/udp.c
/* ************************************************************************
 *       Filename:  udp.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月31日 16时37分21秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main(int argc, char *argv[])
{
	int sockfd = 0;
	unsigned short port = 8080;
	char *server_ip = "10.221.2.12";

	if(argc > 1)
	{
		server_ip = argv[1];
	}
	if(argc > 2)
	{
		port = atoi(argv[2]);
	}

	//AF_INET : ipv4
	//0: 根据
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);

	//配置服务器地址
	struct sockaddr_in server_addr;
	//memset(&server_addr, 0, sizeof(server_addr));
	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);//服务器的端口
	//服务器的IP
	inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);

	//发送数据
	while(1)
	{
		char msg[256] = "";

		fgets(msg,sizeof(msg),stdin);

		sendto(sockfd, msg, strlen(msg), 0,\
			  (struct sockaddr *)&server_addr, sizeof(server_addr));
	}
	printf("fd = %d\n",sockfd);

	close(sockfd);
	return 0;
}
<file_sep>/work/debug/pc/virtualchar/virtualchar.c
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <asm/uaccess.h>



#define DEVICE_NAME  "virtualchar"
#define MEM_SIZE           0x400  // 1kb
#define VIRTUALCHAR_MAGIC  0x08
#define MEM_CLEAR    _IO(VIRTUALCHAR_MAGIC, 0) // 清零全局内存


static int major = 0;
static struct class *virtualchar_class = NULL;

struct virtualchar_dev
{
	struct cdev cdev;
	unsigned char mem[MEM_SIZE];
};

static struct virtualchar_dev *virtualchar_pdev = NULL; // 设备结构指针

static loff_t virtualchar_llseek(struct file *filp, loff_t offset, int orig)
{
	loff_t ret;

	switch(orig)
	{
		case SEEK_SET: // 从文件开头开始偏移
		{
			if(offset < 0){
				ret = -EINVAL;
				break;
			}
			else if((unsigned int)offset > MEM_SIZE){ // 越界
				ret = -EINVAL;
				break;
			}
			filp->f_pos = offset;
			ret = filp->f_pos;
			break;
		}
		case SEEK_CUR: // 从当前位置开始偏移
		{
			if(filp->f_pos + offset < 0){
				ret = -EINVAL;
				break;
			}
			else if(filp->f_pos + offset > MEM_SIZE){ // 越界
				ret = -EINVAL;
				break;
			}
			filp->f_pos += offset;
			ret = filp->f_pos;
			break;
		}
		case SEEK_END:
		{
			if(offset>0){
				ret = -EINVAL;
				break;
			}
			else if(MEM_SIZE + offset <0){
				ret = -EINVAL;
				break;
			}
			filp->f_pos = MEM_SIZE + offset;
			ret = filp->f_pos;
			break;			
		}
		default:
			ret = -EINVAL;		
	}

	return ret;
}

static int virtualchar_ioctl(struct inode *pinode, struct file *filp, unsigned int cmd, unsigned long arg)
{
	int ret;
	struct virtualchar_dev *pdev = filp->private_data; // 获取设备结构指针
	
	switch(cmd)
	{
		case MEM_CLEAR:
		{	// 清空全局内存
			memset(pdev->mem, 0, MEM_SIZE);
			printk(KERN_INFO "Virtualchar memory is set to zero\n");
			break;
		}
		default:
			ret = -EINVAL; // 其他不支持命令
	}

	return ret;
}

static int virtualchar_open(struct inode *pinode, struct file *filp)
{
	struct virtualchar_dev *pdev =  NULL;

	pdev = container_of(pinode->i_cdev, struct virtualchar_dev, cdev); // 返回设备结构体的首地址
	// 将设备结构指针赋值给文件私有数据指针
	filp->private_data = pdev;	
	return 0;
}

static ssize_t virtualchar_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
	int ret;
	unsigned long count = size;
	unsigned long pos = *ppos;
	struct virtualchar_dev *pdev = filp->private_data;// 获取设备结构指针

	// 分析和获取有效的读长度
	if(pos >= MEM_SIZE){ // 要读的偏移位置越界
		return count? -ENXIO : 0;
	}
	else if(count > MEM_SIZE - pos){ // 要读的字节数过大
		count = MEM_SIZE - pos;
	}

	// 内核空间 -> 用户空间
	if(copy_to_user(buf, (void *)(pdev->mem + pos), count)){
		ret = -EFAULT;
	}
	else {
		*ppos += count;
		ret = count;

		printk(KERN_INFO "read %lu bytes from %lu\n", count, pos);
	}

	return ret;
}

static ssize_t virtualchar_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
	int ret;
	unsigned long count = size;
	unsigned long pos = *ppos;
	struct virtualchar_dev *pdev = filp->private_data;// 获取设备结构指针

	// 分析和获取有效的写长度
	if(pos >= MEM_SIZE){ // 要写的偏移位置越界
		return count? -ENXIO : 0;
	}
	else if(count > MEM_SIZE - pos){ // 要写的字节数过大
		count = MEM_SIZE - pos;
	}

	// 用户空间 -> 内核空间
	if(copy_from_user((void *)(pdev->mem + pos), buf, count)){
		ret = -EFAULT;
	}
	else {
		*ppos += count;
		ret = count;
		printk(KERN_INFO "written %lu bytes from %lu\n", count, pos);
	}

	return ret;
}

static struct file_operations virtualchar_fops = {
	.owner  = THIS_MODULE,
	.llseek = virtualchar_llseek,
	.ioctl  = virtualchar_ioctl,
	.open   = virtualchar_open,
	.read   = virtualchar_read,
	.write  = virtualchar_write,
};

#if 1
void virtualchar_setup_cdev(struct virtualchar_dev *pdev, int minor)
{
	int err, devno;

	devno = MKDEV(major, minor);

	cdev_init(&pdev->cdev, &virtualchar_fops);
	pdev->cdev.owner = THIS_MODULE;
	pdev->cdev.ops = &virtualchar_fops;

	err = cdev_add(&pdev->cdev, devno, 1);
	if(err){
		printk(KERN_NOTICE "Error %d adding globmem\n", err);
	}
}
#else
void virtualchar_setup_cdev(void)
{
	int err, devno;

	devno = MKDEV(major, 0);

	cdev_init(&virtualchar_dev.cdev, &virtualchar_fops);
	virtualchar_dev.cdev.owner = THIS_MODULE;
	virtualchar_dev.cdev.ops = &virtualchar_fops;

	err = cdev_add(&virtualchar_dev.cdev, devno, 1);
	if(err){
		printk(KERN_NOTICE "Error %d adding globmem\n", err);
	}
}
#endif
int __init virtualchar_init(void)
{
	int ret ,i;
	struct device *virtualchar_device;
	dev_t devno = MKDEV(major, 0);
	if(major){
		ret = register_chrdev_region(devno, 2, DEVICE_NAME);
	}
	else{ // 动态获取设备号
		ret = alloc_chrdev_region(&devno, 0, 2, DEVICE_NAME);
		major = MAJOR(devno);
	}

	if(ret < 0){
		printk("register keys_driver failed!\n");
		return ret;		
	}

	/* 动态申请两个设备结构体的内存 */
	virtualchar_pdev = (struct virtualchar_dev *)kmalloc(2*sizeof(struct virtualchar_dev), GFP_KERNEL);
	if(!virtualchar_pdev){ // 申请失败
		ret = -ENOMEM;
		goto malloc_err;
	}
	
	virtualchar_setup_cdev(&virtualchar_pdev[0], 0);
	virtualchar_setup_cdev(&virtualchar_pdev[1], 1);

	// 注册一个类
	virtualchar_class = class_create(THIS_MODULE, DEVICE_NAME);
	if(IS_ERR(virtualchar_class)){
		printk("Err:failed in create keys class!\n");
		ret = PTR_ERR(virtualchar_class);
		goto class_err;	
	}	

	//创建设备节点
	for(i=0;i<2;i++){
		virtualchar_device = device_create(virtualchar_class, NULL, MKDEV(major, i), NULL, "virtualchar%d", i);
		if(IS_ERR(virtualchar_device)){
			printk("Err:failed in create keys device!\n");
			ret = PTR_ERR(virtualchar_device);
			goto device_err;
		}
	}
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	return 0;

	device_err:
	while(i--){
		device_destroy(virtualchar_class, MKDEV(major, i));
	}
	class_destroy(virtualchar_class);
	class_err:
	cdev_del(&virtualchar_pdev[0].cdev);
	cdev_del(&virtualchar_pdev[1].cdev);
	kfree(virtualchar_pdev);

	malloc_err:
	unregister_chrdev_region(devno, 2);
	return ret;
}

void __exit virtualchar_exit(void)
{
	int i;
	//删除设备节点
	for(i=0;i<2;i++)
		device_destroy(virtualchar_class,MKDEV(major, i));
	
	//注销类
	class_destroy(virtualchar_class); 	
	
	// 删除cdev结构
	cdev_del(&(virtualchar_pdev[0].cdev)); 
	cdev_del(&(virtualchar_pdev[1].cdev));
	kfree(virtualchar_pdev); // 释放设备结构体的内存

	// 注销设备号
	unregister_chrdev_region(MKDEV(major, 0), 2);
	printk("%s:%d\n",__FUNCTION__,__LINE__);
}

module_init(virtualchar_init);
module_exit(virtualchar_exit);
MODULE_LICENSE("GPL");
<file_sep>/sys_program/3rd_day/homework/yy/tom.c
/* ************************************************************************
 *       Filename:  jerry.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月17日 16时57分02秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>



int main(int argc, char *argv[])
{
	int ret,fr,fw;
	char tom[] = "Tom: ";
	pid_t pid;
	
	//remove(".rfifo");
	//remove(".wfifo");
	mkfifo(".rfifo",0777);
	mkfifo(".wfifo",0777);
	
	printf("Hello, I am %s\n",tom);	

	fr = open(".rfifo",O_RDONLY);
	if(fr < 0) perror("");
	fw = open(".wfifo",O_WRONLY);

	pid = fork();

	if(pid < 0) perror("");

	else if(pid == 0) //子进程
	{
		int len = 0;
		char buf[128] = "";
		while(1)
		{				
			printf("%s",tom);
			fflush(stdout);

			fgets(buf,sizeof(buf),stdin);
			len = strlen(buf);

			if(len > 1)
			{
				char msg[128] = "";
				
				strcat(msg,tom);
				strcat(msg,buf);
				write(fw, msg, strlen(tom)+len - 1);
			}
		}
	}
	else
	{
		char msg[128] = "";

		while(1)
		{
			memset(msg,0,sizeof(msg));
			read(fr, msg, sizeof(msg)); //FIFO里没数据read会阻塞，如果通信写进程先退出，read将不阻塞，read返回值为0
			
			if(msg[0] == 0)
			{
				kill(pid,1);
				exit(0);
			}
			
			printf("\r%s\n",msg);
			printf("%s",tom);
			fflush(stdout);
		}
	
	}

	return 0;
}



<file_sep>/c/practice/get_samechar.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#if 0
char *get_samechar(char *str)
{
	if(str == NULL)
		return NULL;

	char *p = NULL, *ret = NULL;
	int i = 0, j = 1;
	int len = strlen(str) + 1;// 测出传入字符串长度

	p = (char *)malloc(len);  // 动态分配内存空间，len个字节长度
	bzero(p, len); // 清零

	while(j<len){
		//printf("j = %d\n", j);
		if(str[i] == str[j]){ // 出现连续字符有相同
			p[i] += 2; // 在出现连续相同字符 对应 在字符串中的位置 记录出现的次数，
			j++;
			while(j < len && str[i] == str[j]){ // 判断后面还是不是相同字符
				p[i] += 1; // 记录加1
				j++; // 指向下一个
			}
			i = j;
			j++;
		}
		else{
			i++;
			j++;
		}
	}

	for(i=0,j=1; j<len; j++){
		if(p[i] < p[j])
			i = j;
	}

	if(p[i] != 0) ret = str + i;
	else ret = NULL;
	free(p); // 释放动态分配的内存空间，malloc函数分配的空间在不要时要释放掉

	return ret;
}
#else

char *get_samechar(char *str)
{
	if(str == NULL)
		return NULL;
	int i = 0, j = 1, len = strlen(str);
	int pos = 0, len_new = 0, len_old = 0;

	while(j < len){
		if(str[i] == str[j]){
			len_new += 2;
			j++;
			while(str[j] != 0 && str[i] == str[j]){
				len_new++;
				j++;
			}

			if(len_new > len_old)
				len_old = len_new;

			pos = i;
			i = j + 1;
			j++;
		}
		else{
			i++;
			j++;
		}
	}

	if(len_old != 0)
		return str + pos;
	else
		return NULL;
}
#endif

int main(int argc, char argv[])
{

	char str[64] = "";
	int len = 0;

	printf("输入字符串：");
	// 刷新标准输出，因为在printf函数的缓冲没满，并且打印的
	//字符串后面没有 "\n"，调用这个函数屏幕马上可以看到”输入字符串：“
	fflush(stdout);

	fgets(str, sizeof(str), stdin); // 从标准输入获取输入字符串
	len = strlen(str); // 求出长度
	str[len - 1] = 0;  // 去掉字符串后的换行符

	char *p = get_samechar(str); // 处理

	if(p != NULL){

		printf("##:%s\n", p);
	}

	return 0;
}
<file_sep>/README.md
# learn
echo "# learn" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin <EMAIL>:panddio/learn.git
git push -u origin master
<file_sep>/gtk/4st_week/picture_browse/picture_browse.c
/* ************************************************************************
 *       Filename:  picture_browse.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月11日 14时21分54秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <gtk/gtk.h>
#include "scan_dir.h"
#include "image.h"

gboolean pause_flag = TRUE;
guint timer;	// 定时器id
gdouble upstep;
char buf[6];

typedef struct _Window
{
	GtkWidget *main_window;
	GtkWidget *table;
	GtkWidget *image;
	GtkWidget *button_previous;
	GtkWidget *button_next;
	GtkWidget *button_pause;
	GtkWidget *progress;
}WINDOW;

void itoc(int number, char buf[])
{

	buf[0] = number/1000;
	buf[1] = number%1000/100;
	buf[2] = number%100/10;
	buf[3] = '%';
	buf[4] = '\0';
	buf[5] = number%10;	
	
	if(buf[5] > 5)
	{
		buf[2] += 1;
		if(buf[2] >= 10)
		{
			buf[2] = 0;
			buf[1] += 1;
			
			if(buf[1] >= 10)
			{
				buf[1] = 0;
				
				if(buf[0] > 0) buf[0] = 1;
				else buf[0] += 1;
			}
		}
	}
	
	if (buf[0] == 0) buf[0] = ' ';
	else  buf[0] +=48;
	buf[1] += 48;
	buf[2] += 48;
}

// 定时器的回调函数
static void timer_callback(gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;
	//upstep = gtk_progress_bar_get_fraction(GTK_PROGRESS_BAR(p_temp->progress));	
	gs_index++;	
	upstep += (gdouble)(1.0/(gs_bmp_total));	
	if(gs_index >= gs_bmp_total)
	{
		gs_index = 0;
		upstep = (gdouble)(1.0/(gs_bmp_total));;
	}
	
	printf("gs_index = %d\n", gs_index);
	load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);	
	
	// 设置进度条的新值 
	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_temp->progress), upstep); 
	
	itoc((int)(upstep*1000),buf);
	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(p_temp->progress), buf);
}
// 按钮的回调函数
void deal_switch_image(GtkWidget *button, gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;

	//gdouble upstep = gtk_progress_bar_get_fraction(GTK_PROGRESS_BAR(p_temp->progress)); 
	
	//创建图片控件(这里加这行会出现只能播放一张图片的错误)
	//p_temp->image = gtk_image_new_from_pixbuf(NULL); 
	
	if(button == p_temp->button_previous)// 上一张
	{		
		gs_index--;
		upstep -= (gdouble)(1.0/(gs_bmp_total));
		if(gs_index < 0)
		{	
			gs_index = gs_bmp_total - 1;
			upstep = 1;
		}
		printf("gs_index = %d\n", gs_index);
		printf("p_temp->button_previous\n");
		load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);

	}
	else if(button == p_temp->button_next ) // 下一张
	{	
		gs_index++;	
		upstep += (gdouble)(1.0/(gs_bmp_total));
		
		if(gs_index >= gs_bmp_total)
		{
			gs_index = 0;
			upstep = (gdouble)(1.0/(gs_bmp_total));
		}
		printf("gs_index = %d\n", gs_index);
		printf("p_temp->button_next\n");
		load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);
	}
	else if(button == p_temp->button_pause ) 
	{
		printf("p_temp->button_pause\n");
		
		if(pause_flag)  // 自动播放
		{
			pause_flag = FALSE;
			
			gtk_widget_set_sensitive(p_temp->button_next, FALSE);
			gtk_widget_set_sensitive(p_temp->button_previous, FALSE);
			
			GtkWidget *image = gtk_image_new_from_file("./skin/pause.bmp"); // 图像控件
			gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
			
			//创建定时器
			timer = g_timeout_add(1000, (GSourceFunc)timer_callback, (gpointer)data);
		}
		else
		{
			pause_flag = TRUE;
			
			gtk_widget_set_sensitive(p_temp->button_next, TRUE);
			gtk_widget_set_sensitive(p_temp->button_previous, TRUE);
			
			GtkWidget *image = gtk_image_new_from_file("./skin/play.bmp"); // 图像控件
			gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
			
			//移除定时器
			g_source_remove(timer);		
		}
		
	}
	
	printf("%f\n",(float)upstep);
 
	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_temp->progress), upstep); //设置进度条的新值
	
	itoc((int)(upstep*1000),buf);
	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(p_temp->progress), buf);
	
	//gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->image, 1, 6, 1, 6);	// 把图片控件加入布局
	//gtk_widget_show_all(p_temp->main_window);
}

void show_window(gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;
	upstep = (gdouble)(1.0/(gs_bmp_total));
	// 主窗口
	p_temp->main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);		 	// 创建主窗口
	gtk_window_set_title(GTK_WINDOW(p_temp->main_window), "picture_browse");	 	// 设置窗口标题
	gtk_window_set_position(GTK_WINDOW(p_temp->main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
	gtk_widget_set_size_request(p_temp->main_window, 800, 480);		 	// 设置窗口的最小大小
	gtk_window_set_resizable(GTK_WINDOW(p_temp->main_window), FALSE); 	// 固定窗口的大小
	g_signal_connect(p_temp->main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL); 
	
	// 表格布局
	p_temp->table = gtk_table_new(7, 7, TRUE);	// 表格布局容器 7行 7列
	gtk_container_add(GTK_CONTAINER(p_temp->main_window), p_temp->table); // 容器加入窗口
	
	// 图片控件
	//gs_index = 1;
	p_temp->image = gtk_image_new_from_pixbuf(NULL);		// 创建图片控件
	load_image(p_temp->image, gs_bmp_name[gs_index], 500, 450);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->image, 1, 6, 1, 6);	// 把图片控件加入布局
	
	// 进度条
	GtkWidget *table = gtk_table_new(5, 7, TRUE);  // 表格布局容器，用来存放进度条，限制进度条的宽度
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), table, 0, 7, 0, 1);// 把进度条控件加入布局
	
	p_temp->progress = gtk_progress_bar_new();
	gtk_table_attach_defaults(GTK_TABLE(table), p_temp->progress, 1, 6, 3, 4);// 把进度条控件加入布局
	gtk_progress_bar_set_fraction(GTK_PROGRESS_BAR(p_temp->progress), upstep); //设置开始进度为零
	itoc((int)(upstep*1000),buf);
	gtk_progress_bar_set_text(GTK_PROGRESS_BAR(p_temp->progress), buf);
	//gtk_progress_bar_set_bar_style (p_temp->progress,GTK_PROGRESS_CONTINUOUS);

	// 按钮
#if 1
	p_temp->button_previous = create_button_from_file("./skin/previous.bmp", 70, 60);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_previous, 1, 2, 6, 7);
	g_signal_connect(p_temp->button_previous, "clicked", G_CALLBACK(deal_switch_image), p_temp);
	
	p_temp->button_next = create_button_from_file("./skin/next.bmp", 70, 60);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_next, 5, 6, 6, 7);
	g_signal_connect(p_temp->button_next, "clicked", G_CALLBACK(deal_switch_image), p_temp);
	
	p_temp->button_pause = create_button_from_file("./skin/play.bmp", 70, 60);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_pause, 3, 4, 6, 7);
	g_signal_connect(p_temp->button_pause, "clicked", G_CALLBACK(deal_switch_image), p_temp);
#endif
	chang_background(p_temp->main_window, 800, 480, "./skin/background.bmp");	// 设置窗口背景图
	gtk_widget_show_all(p_temp->main_window);
}

int main(int argc, char* argv[])
{
	WINDOW window;
	
	gtk_init(&argc, &argv);	
	
	get_bmp_name(IMAGE_DIR);
	order_bmp_name();
	//bmp_name_print();//for test
	show_window(&window);
	
	gtk_main();
	return 0;
}

<file_sep>/c/practice/3rd_week/mylink/link.c
/* ************************************************************************
 *       Filename:  link.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月29日 星期三 04時18分53秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "link.h"


/**************************************************
 *函数：insert_link
 *功能：给链表添加新节点，当链表为空时创建链表
 *************************************************/
#if 0
//从链表头插入节点
STU *insert_link(STU *head, STU stu) 
{
	STU *pi = NULL;
	pi = (STU *)malloc(sizeof(STU));

	if(pi != NULL) //成功申请到空间
	{
		*pi = stu;
		pi->next = NULL;


		if(head != NULL)
		{
			pi->next = head;
		}
		head = pi;
	}
	else
	{
		printf("Can not apply for a STU memeory space!\n");
	}

	return head;
}
#elif 1
//从链表尾部插入节点
STU *insert_link(STU *head, STU stu) 
{
	STU *pi = NULL;
	pi = (STU *)malloc(sizeof(STU));

	if(pi != NULL) //成功申请到空间
	{
		*pi = stu;
		pi->next = NULL;

		if(head == NULL)
		{
			head = pi;
		}
		else //链表不为空
		{
			STU *pb = head;

			while(pb->next != NULL)
				pb = pb->next;
			
			pb->next = pi;
		}
	}
	else
	{
		printf("Can not apply for a STU memeory space!\n");
	}

	return head;
}
#elif 0
//按某种顺序插入链表节点
STU *insert_link(STU *head, STU stu)
{
	STU *pi = NULL;
	pi = (STU *)malloc(sizeof(STU));

	if(pi != NULL) //成功申请到空间
	{
		*pi = stu;
		pi->next = NULL;

		if(head == NULL)
		{
			head = pi;
		}
		else //链表不为空
		{
			STU *pb = NULL, *pf =NULL;
			pb = pf = head;

			//按num从小到大插入链表
			while((pi->num > pb->num) && (pb->next != NULL))
			{
				pf = pb;
				pb = pb->next;
			}
			
			if(pi->num <= pb->num)//链表头插入新节点
			{
				if(pb == head)
				{
					pi->next = pb;
					head = pi;
				}
				else //中间插入新节点
				{
					pi->next = pb;
					pf->next = pi;
				}
			}
			else //尾部插入新节点
			{
				pb->next = pi;
			}
		}
	}
	else
	{
		printf("Can not apply for a STU memeory space!\n");
	}

	return head;
}
#endif

/**************************************************
 *函数：delete_link
 *功能：删除链表中指定的节点
 *************************************************/
STU *delete_link(STU *head, int num)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		STU *pb = NULL, *pf = NULL;
		pb = pf =head;

		while((pb->num != num) && (pb->next != NULL))
		{
			pf = pb;
			pb = pb->next;
		}

		if(pb->num == num)
		{
			if(pb == head) //删除的节点是链表头部
			{
				head = pb->next;
			}
			else if(pb->next == NULL) //删除的节点在链表尾部
			{
				pf->next = NULL;
			}
			else//删除的节点在中间
			{
				pf->next = pb->next;
			}
			free(pb);
		}
	}

	return head;
}
/**************************************************
 *函数：delete_head
 *功能：删除链表的头节点
 *************************************************/
STU *delete_head(STU *head)
{
	if(head == NULL)
	{
		printf("Link is empty!\n");
	}
	else
	{
		STU *pb = NULL;
		pb = head;

		head = pb->next; //删除链表头部
		free(pb);
	}

	return head;
}
/**************************************************
 *函数：search_link
 *功能：查询链表中指定的节点，找到返回节点地址，否则返回NULL
 *************************************************/
STU *search_link(STU *head,char *name)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		STU *pb = head;

		while((strcmp(pb->name,name) !=0) && (pb->next != NULL))
			pb = pb->next;

		if(strcmp(pb->name,name) == 0) //找到
		{
			return pb;
		}
	}
	return NULL; //没找到返回NULL指针
}
/**************************************************
 *函数：print_link
 *功能：遍历链表中每个节点，并打印节点的内容
 *************************************************/
void print_link(STU *head)
{

	if(head == NULL)
	{
		printf("Link is not exist!\n"); 
	}
	else
	{
		STU *pb = head;
		
		while(pb != NULL)
		{
			printf("num: %-4d name: %-8s score: %-3d\n",pb->num,pb->name,pb->score);
			pb = pb->next;
		}
	}
}
/**************************************************
 *函数：free_link
 *功能：将整个链表所占的内存空间释放
 *************************************************/
STU *free_link(STU *head)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		STU *pb = head;

		//循环删除链表每个节点的方法：
		//1.判断 head 是否为空
		//2.让 pb 指向和 head 相同的节点
		//3.然后 让 head 指向下个节点
		//4.再把 pb 指向的节点释放掉
		//5.返回步骤 1
		while(head != NULL)
		{
			pb = head;
			head = pb->next;
			free(pb);
		}
	}

	return head;
}
/**************************************************
 *函数：sort_link
 *功能：采用"选择法"将链表按 scort 从大到小排序
 *************************************************/
STU *sort_link(STU *head)
{
	if(head != NULL)
	{
		STU *i, *j, *k, buf;

		for(i=head;i->next != NULL; i=i->next)
		{
			k = i;

			for(j=i->next;j != NULL;j=j->next)
			{
				if(k->score < j->score)
				{
					k = j;	
				}
			}
			
			if(k != i) //不相等，进行交换 i 和 k
			{
				buf = *i;
				buf.next = k->next;
				k->next  = i->next;
				*i = *k;
				*k = buf;
			}
		}
	}
	
	return head;
}
/**************************************************
 *函数：invert_link
 *功能：倒置整个链表
 **************************************************/
STU *invert_link(STU *head)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
		return NULL;
	}
	if( head->next != NULL) //不等与NULL，说明链表节点大于或等于二
	{
		STU *pb = NULL, *pf = NULL, *pn = NULL;

#if 0
		pf = head; //指向链表头
		pb = pn = head->next; //指向链表第二个元素

		while(pn != NULL)
		{
			pn = pn->next;
			pb->next = pf;
			pf = pb;
			pb = pn;
		}
		head->next = NULL;
		head = pf; //
#else
		pb = pf = head;
		pn = head->next;
		printf("akkk\n");
		while(pn != NULL)
		{
			pb = pn;
			pn = pn->next;
			pb->next = pf;
			pf = pb;
		}
		
		head->next = NULL;
		head = pb;
#endif
	}

	return head;
}
<file_sep>/c/practice/3rd_week/encrypt/encrypt.c
/* ************************************************************************
 *       Filename:  encrypt.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月30日 星期四 02時04分32秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include "encrypt.h"
/************************************************************************** 
*函数功能:获取 目的文件 和 源文件 的名字
*参数：src_file_name   源文件名字字符数组首地址。
*      dest_file_name  目的文件的名字字符数组首地址
**************************************************************************/ 
void get_file_name(char * dest_file_name,char * src_file_name)
{
	printf("请输入原文件的名称（30个字符）: ");
	scanf("%s",src_file_name);

	printf("请输入目的文件名（30个字符）： ");
	scanf("%s",dest_file_name);
}
/**************************************************************************
*函数功能:读出文件内容
*参数：file_length    整型指针，此地址中保存文件字节数。
*      src_file_name  文件名字，从此文件中读取内容。
* 返回值:读出字符串的首地址
* 函数中测文件的大小并分配空间，再把文件内容读出到分配的空间中，返回此空间首地址
**************************************************************************/ 
char * read_src_file(unsigned long int *file_length,char *src_file_name)
{
	FILE *fp = NULL;
	char *buf = NULL;

	fp = fopen(src_file_name,"rb");//以只读方式打开一个二进制文件

	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	fseek(fp,0,SEEK_END);
	*file_length = ftell(fp); //获取文件的大小

	buf = (char *)malloc(*file_length); //
	if(buf == NULL)
	{
		printf("malloc() cannot apply for memory!\n");
		goto out;
	}
	rewind(fp); //
	fread(buf,*file_length,1,fp);

	out:
	fclose(fp);
	return buf;
}

/**************************************************************************
*函数功能:加密字符串
*参数：src_file_text  要加密的字符串。length:字符串的长度
*      password       <PASSWORD>
*返回值: 加密后的字符串的首地址
*加密原理字符数组中每个元素加上password
**************************************************************************/ 
char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password)
{
	int i;

	for(i=0;i<length;i++)
	{
		*(src_file_text + i)  += password;
	}

	return src_file_text;
}
/**************************************************************************
*函数功能:解密字符串
*参数：src_file_text  要解密的字符串。length:字符串的长度
*      password       解密密码
*返回值: 解密后的字符串的首地址
*思想;把数组中的每个元素减去password 给自己赋值。
**************************************************************************/ 
char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password)
{
	int i;

	for(i=0;i<length;i++)
	{
		*(src_file_text + i)  -= password;
	}
	return src_file_text;
}
/**************************************************************************
*函数功能:将字符串保存到目的文件中
*参数：text       要保存的字符串首地址
*      file_name  目的文件的名字
*      length     字符串的长度
*思想：传入字符数组的首地址和数组的大小及保存后的文件的名字，即可保存数组到文件中
**************************************************************************/ 
void save_file(char* text,unsigned long int length,char * file_name)
{
	FILE *fp = NULL;

	fp = fopen(file_name,"wb");

	if(fp == NULL)
	{
		printf("Cannot open the file!\n");
		return;
	}

	fwrite(text,length,1,fp); //保存text中的数据到文件
	printf("Data is successfully saved!\n");
	fclose(fp);
}
<file_sep>/sys_program/4th_day/msg.c
/* ************************************************************************
 *       Filename:  msg.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 14时53分41秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <sys/types.h>
#include <stdio.h>
#include <sys/ipc.h>
#include <string.h>

typedef struct _msg
{
	long type;

	char mutex[100];
}MSG;

int main(int argc, char *argv[])
{
	key_t key;
	int id;
	MSG sed;
	MSG sed2;

	sed.type = 10;
	strcpy(sed.mutex, "hello world");

	sed2.type = 1;
	strcpy(sed2.mutex, "I love you");


	key = ftok("./",23);
	id = msgget(key, IPC_CREAT | 0666);

	msgsnd(id,&sed,sizeof(sed)-4 ,0); //参数0，表示msgsnd调用阻塞直到条件满足为止
	msgsnd(id,&sed2,sizeof(sed2)-4 ,0);
	return 0;
}

<file_sep>/c/practice/2nd_week/fun_pointer/fun.h
/* ************************************************************************
 *       Filename:  fun.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月24日 星期五 12時12分43秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __FUN_H__
#define __FUN_H__

extern int add(int a, int b);
extern int sub(int a, int b);
extern int mul(int a, int b);
extern int div(int a, int b);

#endif


<file_sep>/sys_program/7th_day/Makefile
CC = arm-linux-gcc

button:gpio_buttons.c
	$(CC) gpio_buttons.c -o buttons


<file_sep>/c/practice/3rd_week/gps/gps.c
/* ************************************************************************
 *       Filename:  gps.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月28日 星期二 07時11分10秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/



#include <stdio.h>
#include <string.h>

typedef struct gpsinfo
{
	char id[10];
	char time[16];
	char sta;
	char lat[12];
	char ns;
	char lon[12];
	char ew;
	char vel;
	char azi[8];
	char utct[10];
	char mag[6];
	char dir;
	int crc;
}GPS;

typedef struct date
{
	int year;
	int mon;
	int day;
	int hour;
	int min;
	int sec;
}DATE;

void show_time(char *pinfo[])
{
	DATE time;
	
//	printf("%s\n",pinfo);
	sscanf(pinfo[1],"%2d%2d%2d",&time.hour,&time.min,&time.sec);
	time.hour += 8;
	printf("时间：%02d:%02d:%02d\n",time.hour,time.min,time.sec);

	sscanf(pinfo[9],"%2d%2d%2d",&time.day,&time.mon,&time.year);
	printf("日期：%02d年%02d月%01d日\n",time.year,time.mon,time.day);
}

void show_latitude(char *pinfo[])
{
	int du = 0;
	char fen[10];

	sscanf(pinfo[3],"%2d%s",&du,fen);

	printf("纬度：%s纬 %3d度 %s分\n",pinfo[4],du,fen);
}
void show_longitude(char *pinfo[])
{
	int du = 0;
	char fen[10];

	sscanf(pinfo[5],"%3d%s",&du,fen);

	printf("经度：%s经 %3d度 %s分\n",pinfo[6],du,fen);
}
char get_status(char *pinfo[])
{
	char state;

	sscanf(pinfo[2],"%1c",&state);
	//printf("state = %c\n",state);

	return state;
}
int sep_gpsinfo(char *pinfo[],char info[],char *pch)
{
	int i = 0;
	
	pinfo[0] = strtok(info,pch);
	
	while(pinfo[i++] != NULL)
	{
		pinfo[i] = strtok(NULL,pch);
	}
	
	return i;
}

void main()
{
	char *pinfo[13] = {NULL};
	char info[128]="$GPRMC,024813.640,A,3158.4608,N,11848.3737,E,\
					10.05,324.27,150706, , ,A*50";
	char state;

	sep_gpsinfo(pinfo,info,",");

	state = get_status(pinfo);

	if(state == 'A')
	{
		show_time(pinfo);
		show_latitude(pinfo);
		show_longitude(pinfo);
	}
	
}	

	
<file_sep>/work/test/v4l2/Makefile
TOPDIR := $(shell pwd)
GCC := mips-linux-gnu-gcc

CFLAGS := -Os -Wall -mabi=32 -mhard-float -march=mips32r2 -I$(TOPDIR)/include
LDFLAGS := -Wl,-EL
LDLIBS := -L$(TOPDIR)/lib -ljpeg-hw

SOURCES := $(wildcard *.c)

TARGET = cimcapt
all: $(TARGET)

$(TARGET): $(SOURCES)
	$(GCC) $(CFLAGS) $(LDLIBS) $(LDFLAGS) -o $@ $^

INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install: all
	cp $(TARGET) $(INSTALL_DIR) -a

.PHONY: clean
clean:
	rm -rf *.o $(TARGET)
<file_sep>/work/test/cim_test-zmm220/gpio.c

#include <string.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/time.h>
#include "arca.h"

#define LEDR	104
#define LEDG	105


#define GPIO_DIR_IN             0
#define GPIO_DIR_OUT            1
#define GPIO_LEVEL_LOW          0
#define GPIO_LEVEL_HIGH         1

/* ioctl command */
#if 1
#define SETDIRECTION            0x01
#define GETDIRECTION            0x02
#define SETLEVEL                0x03
#define GETLEVEL                0x04
#define SETRISINGEDGE           0x05
#define GETRISINGEDGE           0x06
#define SETFALLINGEDGE          0x07
#define GETFALLINGEDGE          0x08
#define GETEDGEDETECTSTATUS     0x09
#define CLEAREDGEDETECTSTATUS   0x0A

#define NANDREADPAGE		0x0B
#define NANDWRITEPAGE		0x0C
#define NANDREADBLOCK		0x0D
#define NANDWRITEBLOCK		0x0E
#define NANDREASEBLOCK		0x0F
#define NANDSAVEMAC		0x10
#else
#define SETDIRECTION            _IOW ('N', 0x01, struct _MSG)
#define GETDIRECTION            _IOR ('N', 0x02, struct _MSG)
#define SETLEVEL                _IOW ('N', 0x03, struct _MSG)
#define GETLEVEL                _IOR ('N', 0x04, struct _MSG)
#define SETRISINGEDGE           _IOW ('N', 0x05, struct _MSG)
#define GETRISINGEDGE           _IOR ('N', 0x06, struct _MSG)
#define SETFALLINGEDGE          _IOW ('N', 0x07, struct _MSG)
#define GETFALLINGEDGE          _IOR ('N', 0x08, struct _MSG)
#define GETEDGEDETECTSTATUS     _IOR ('N', 0x09, struct _MSG)
#define CLEAREDGEDETECTSTATUS   _IOW ('N', 0x0A, struct _MSG)

#define NANDREADPAGE            _IOR ('N', 0x0B, struct _MSG)
#define NANDWRITEPAGE           _IOW ('N', 0x0C, struct _MSG)
#define NANDREADBLOCK           _IOR ('N', 0x0D, struct _MSG)
#define NANDWRITEBLOCK          _IOW ('N', 0x0E, struct _MSG)
#define NANDREASEBLOCK          _IOW ('N', 0x0F, struct _MSG)
#define NANDSAVEMAC             _IOW ('N', 0x10, struct _MSG)
#define NANDGETBLOCKSTATUS      _IOR ('N', 0x11, struct _MSG)

#define FREEGPIO                _IOW ('N', 0x12, struct _MSG)
#define MAPGPIO                 _IOW ('N', 0x13, struct _MSG)
#endif

static int fd = -1;

struct _MSG
{
	int param0;
        int param1;
//	unsigned char buf[2048];
}Info;


//static int BASELOOPTESTCNT = 30;
/*
void DelayUS(int us)
{
        int i, j, k;

        if (us <= CNT*1000)
        {
                for (i=0; i<us; i++)
                        for(j=0; j<BASELOOPTESTCNT; j++) k++;
        }
        else
        {
                usleep(us);
        }
}
*/
/*
void DelayMS(int ms)
{
        usleep(1000*ms);
}
*/
void __gpio_as_output(int n)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = n;
	Info.param1 = GPIO_DIR_OUT;

	ioctl(fd, SETDIRECTION,&Info);
	
//	return;
}
void __gpio_as_input(int n)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = n;
	Info.param1 = GPIO_DIR_IN;

	ioctl(fd, SETDIRECTION,&Info);
	
//	return;
}


void __gpio_set_pin(int n)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = n;
	Info.param1 = GPIO_LEVEL_HIGH;

	ioctl(fd, SETLEVEL, &Info);
	
//	return;
}

void __gpio_clear_pin(int n)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = n;
	Info.param1 = GPIO_LEVEL_LOW;

	ioctl(fd, SETLEVEL, &Info);
	
//	return;
}

int __gpio_get_pin(int n)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return -1;
	}
	Info.param0 = n;

	ioctl(fd, GETLEVEL,&Info);
	
	return Info.param1;
}

int gpio_open(void)
{
	fd = open("/dev/jzgpio", O_RDWR);
	if(fd<0)
		printf("Error: open dev/jzgpio\n");
	printf("open gpio control ok!\n");
	return fd;
}


int gpio_close(void)
{
	close(fd);
}
#if 0
void Nand_read_onePage(U32 page, U8 *buf)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = page;
	memset(Info.buf, 0, sizeof(Info.buf));
	ioctl(fd, NANDREADPAGE,&Info);
	memcpy(buf, Info.buf, sizeof(Info.buf));
	return;
}

void Nand_write_onePage(U32 page, U8 *buf)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = page;
	memcpy(Info.buf, buf, sizeof(Info.buf));
	ioctl(fd, NANDWRITEPAGE,&Info);
	return;
}

void Nand_read_oneBlock(U32 page, U8 *buf)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
//	ioctl(fd, NANDREADBLOCK,&buf);
	return;
}

void Nand_write_oneBlock(U32 page, U8 *buf)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
//	ioctl(fd, NANDWRITEBLOCK,&buf);
	return;
}

void Nand_erase_oneBlock(U32 block)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	Info.param0 = block;
	ioctl(fd, NANDREASEBLOCK,NULL);
	return;
}

void Nand_save_MAC(U8 *buf)
{
	if(fd<0)
	{
		printf("invalid operation!\n");
		return;
	}
	memcpy(Info.buf, buf,6);
	ioctl(fd, NANDSAVEMAC,&Info);
	return;
}
#endif 
/*
int swi2c_write(uint8_t i2caddr, uint8_t subaddr, uint8_t data);
int swi2c_blkwrite(uint8_t i2caddr, uint8_t subaddr, uint8_t *data, uint32_t blksize);
int swi2c_read(uint8_t i2caddr, uint8_t subaddr, uint8_t *data);
int swi2c_blkread(uint8_t i2caddr, uint8_t subaddr, uint8_t *data, uint32_t blksize);
*/


int CNT=8;
#if 0
int main(int argc, int **argv)
{
	unsigned char buf[100];
	int i;
	int sw = 0;

//	if(argc>=1)
//		CNT=strtoul(argv[1], NULL, 0);
//	if(argc>=2)
//		sw=strtoul(argv[2], NULL, 0);

	fd = open("/dev/gpio", O_RDWR);
	if(fd<0)	
	{
		printf("Error: open dev/gpio\n");
		return 0;
	}

	__gpio_as_output(LEDR);
	__gpio_as_output(LEDG);

	while(1)
	{
		__gpio_set_pin(LEDR);
		__gpio_set_pin(LEDG);
		printf("set pin\n");
		DelayMS(500);
		__gpio_clear_pin(LEDR);
		__gpio_clear_pin(LEDG);
		printf("clear pin\n");
		DelayMS(500);
	}
	
#if 0
	if(sw==0)
	{
	#if 0
		for(i=0; i<CNT; i++) buf[i]=i+10;
		printf("write EEPROM.\n");
		swi2c_blkwrite(0xa0,0, buf, CNT);

		memset(buf, 0, CNT);	
		printf("read EEPROM:\n");
		if(swi2c_blkread(0xa0, 0, buf, CNT)!=0)
			printf("read failed\n");
		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
		printf("\n\n");
	#else
                printf("write EEPROM.\n");
                for(i=0; i<CNT; i++)
			swi2c_write(0xa0,i,i);

                memset(buf, 0, CNT);
                printf("read EEPROM:\n");

                for(i=0; i<CNT; i++)
			if(swi2c_read(0xa0, i, buf+i)!=0)
				printf("read failed\n");
		for(i=0; i<CNT; i++)
                        printf("%02x ",buf[i]);

		memset(buf, 0, CNT);	
		printf("block read EEPROM:\n");
		if(swi2c_blkread(0xa0, 0, buf, CNT)!=0)
			printf("read failed\n");
		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
                printf("\n\n");

	#endif
	}

	if(sw==1)
	{
		memset(buf, 0, CNT);	
		printf("read MI0360:\n");
		if(swi2c_blkread(0xBA, 0, buf, CNT)!=0)
			printf("read failed\n");

		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
		printf("\n");
	}

	if(sw==2)
	{
		memset(buf, 0, CNT);	
		printf("read RTC:\n");
		if(swi2c_blkread(0x65, 0, buf, CNT)!=0)
			printf("read failed\n");
		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
		printf("\n\n");

		memset(buf, 0, CNT);	
		if(swi2c_read(0x65, 0, buf)!=0)
			printf("read failed\n");
		printf("%02x\n",buf[0]);
	}


	if(sw==3)
	{

		memset(buf, 0, CNT);	
		printf("read HVCNT131:\n");
		if(swi2c_blkread(0x22, 0, buf, CNT)!=0)
			printf("read failed\n");
		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
		printf("\n\n");
	}

	if(sw==4)
	{
		memset(buf, 0, CNT);	
		printf("read GC030CNT:\n");
		if(swi2c_blkread(0x42, 0, buf, CNT)!=0)
			printf("read failed\n");
		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
		printf("\n\n");
	}


	if(sw==5)
	{
		memset(buf, 0, CNT);	
		printf("read GC0303:\n");
		if(swi2c_blkread(0x30, 0x90, buf, CNT)!=0)
			printf("read failed\n");
		for(i=0; i<CNT; i++)
			printf("%02x ",buf[i]);
		printf("\n\n");
	}
*/

#endif
	return 0;
}
#endif
<file_sep>/sys_program/5th_day/mutil_pthread.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
	int fd[2];
	pid_t pid;
	pid_t pid_sec;
	char buf[7];
	pipe(fd);
	if((pid = fork())<0)
	{
		printf("fork error!");
		exit(1);
	}
	else if(pid == 0)
	{
		close(fd[0]);
		write(fd[1],"first1",7);
		close(fd[1]);
		exit(0);
	}
	else
	{
		wait(NULL);
		if((pid_sec = fork())<0)
		{
			printf("fork second error!");
			exit(1);
		}
		else if(pid_sec==0)
		{
			close(fd[0]);
			write(fd[1],"Child1",7);
			close(fd[1]);
			exit(0);
		}
		else
		{
			wait(0);
			close(fd[1]);
			read(fd[0],buf,7);
			printf("%s\n",buf);
			wait(0);
			close(fd[1]);
			read(fd[0],buf,7);
			close(fd[0]);
			printf("%s\n",buf);
			exit(0);
		}
	}
	return 0;
}
<file_sep>/work/debug/a8/matrix_keys/matrix_keys.c
#include <linux/module.h>
#include <linux/cdev.h>
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/ioport.h>
#include <linux/slab.h>   // kmalloc() kfree()
#include <linux/delay.h>   // mdelya() msleep()
#include <asm/io.h>
#include <asm/uaccess.h>
#include <plat/gpio-cfg.h>
#include <mach/gpio.h>


#define DEVICE_NAME   "keys_drv"


static int keys_major = 0;
static struct class *keys_class = NULL;
static struct cdev *pcdev = NULL;



static int keys_drv_open(struct inode *pindo, struct file *filp)
{
	printk("%s:%d\n",__FUNCTION__,__LINE__);

	// 引脚设置为输出
	s3c_gpio_cfgpin(S5PV210_GPH3(0), S3C_GPIO_OUTPUT);
	s3c_gpio_cfgpin(S5PV210_GPH3(1), S3C_GPIO_OUTPUT);

	//s3c_gpio_setpin(S5PV210_GPH3(0), 0);
	gpio_set_value(S5PV210_GPH3(0), 0);
	gpio_set_value(S5PV210_GPH3(1), 1);

	s3c_gpio_cfgpin(S5PV210_GPH2(3), S3C_GPIO_INPUT);
	s3c_gpio_cfgpin(S5PV210_GPH2(4), S3C_GPIO_INPUT);
	s3c_gpio_cfgpin(S5PV210_GPH2(5), S3C_GPIO_INPUT);
	s3c_gpio_cfgpin(S5PV210_GPH2(6), S3C_GPIO_INPUT);
	s3c_gpio_cfgpin(S5PV210_GPH2(7), S3C_GPIO_INPUT);

	s3c_gpio_setpull(S5PV210_GPH2(3), S3C_GPIO_PULL_UP);
	s3c_gpio_setpull(S5PV210_GPH2(4), S3C_GPIO_PULL_UP);
	s3c_gpio_setpull(S5PV210_GPH2(5), S3C_GPIO_PULL_UP);
	s3c_gpio_setpull(S5PV210_GPH2(6), S3C_GPIO_PULL_UP);
	s3c_gpio_setpull(S5PV210_GPH2(7), S3C_GPIO_PULL_UP);


	printk("%s:%d\n",__FUNCTION__,__LINE__);
	return 0;
}


static ssize_t keys_drv_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
{
	char data[] = {0};
	int i, keyval;
	int len, ret;

	volatile unsigned char *gph2dat = NULL;
	gph2dat = ioremap(0xe0200c44, 1); // 0xe0200c44 是GPH2DAT 的地址

	for(i=0; i<10; i++){ // 键盘扫描
		gpio_set_value(S5PV210_GPH3(0), 0);
		gpio_set_value(S5PV210_GPH3(1), 1);

		keyval = *gph2dat;
		keyval &= 0xf8;

		if(keyval != 0xf8){ //
			msleep(100);
			//mdelay(100); // 延时消抖
			keyval = *gph2dat;
			keyval &= 0xf8;

			if(keyval != 0xf8){

				switch(keyval){

				case 0xf0: // key2
					data[0] = 2;
					goto out;
					break;

				case 0xe8: // key3
					data[0] = 3;
					goto out;
					break;

				case 0xd8: // key4
					data[0] = 4;
					goto out;
					break;

				case 0xb8: // key5
					data[0] = 5;
					goto out;
					break;

				case 0x78: // key6
					data[0] = 6;
					goto out;
					break;
				}
			}

			// 等待按键释放
			while(keyval != 0xf8){
				keyval = *gph2dat;
				keyval &= 0xf8;
			}
		}

		// 扫描第二行
		gpio_set_value(S5PV210_GPH3(0), 1);
		gpio_set_value(S5PV210_GPH3(1), 0);

		keyval = *gph2dat;
		keyval &= 0xf0;

		if(keyval != 0xf0){ //
			msleep(100);
			//mdelay(100); // 延时消抖
			keyval = *gph2dat;
			keyval &= 0xf0;

			if(keyval != 0xf0){

				switch(keyval){

				case 0xe0: // key8
					data[0] = 8;
					goto out;
					break;

				case 0xd0: // key9
					data[0] = 9;
					goto out;
					break;

				case 0xb0: // key10
					data[0] = 10;
					goto out;
					break;

				case 0x70: // key11
					data[0] = 11;
					goto out;
					break;
				}
			}

			// 等待按键释放
			while(keyval != 0xf0){
				keyval = *gph2dat;
				keyval &= 0xf0;
			}
		}
	}

	out:
	len = min(sizeof(data), count);
	ret = copy_to_user(buf, data, len); // 返回不能被复制的字节数
	return len;
}

static int keys_drv_release(struct inode *pinode, struct file *filp)
{
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	return 0;
}


static struct file_operations keys_drv_fops = {
	.owner   = THIS_MODULE,
	.open    = keys_drv_open,
	.read    = keys_drv_read,
	.release = keys_drv_release,
};

static void keys_setup_cdev(struct cdev *pcdev, int index)
{
	int err;

	dev_t devno = MKDEV(keys_major, index);

	cdev_init(pcdev, &keys_drv_fops);
	pcdev->owner = THIS_MODULE;
	pcdev->ops = &keys_drv_fops;

	err = cdev_add(pcdev, devno, 1);

	if(err){
		printk(KERN_NOTICE "Error %d adding keys cdev %d",err,index);
	}
}

int __init keys_drv_init(void)
{
    int ret;

	dev_t devno = MKDEV(keys_major, 0);

	if(!keys_major){ // 动态获取设备号
		ret = alloc_chrdev_region(&devno, 0, 1, DEVICE_NAME);
		keys_major = MAJOR(devno);
	}
	else{
		ret = register_chrdev_region(devno, 1, DEVICE_NAME);
	}

	if(ret < 0){ // 注册失败
		printk("register keys_driver failed!\n");
		return ret;
	}

	pcdev = kmalloc(sizeof(struct cdev), GFP_KERNEL);
	if(pcdev == NULL){
		printk("kmalloc failed!\n");
		ret = -ENOMEM;
		goto malloc_err;
	}

	memset(pcdev, 0, sizeof(struct cdev));
	keys_setup_cdev(pcdev, 0);

	// 注册一个类
	keys_class = class_create(THIS_MODULE, DEVICE_NAME);
	if(IS_ERR(keys_class)){
		printk("Err:failed in create keys class\n");
		goto class_err;
	}

	//创建一个设备节点
	device_create(keys_class, NULL, devno, NULL, DEVICE_NAME);
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	return 0;

	class_err:
	cdev_del(pcdev);
	kfree(pcdev);

	malloc_err:
	unregister_chrdev_region(devno, 1);
	return ret;
}

void __exit keys_drv_exit(void)
{
	device_destroy(keys_class, MKDEV(keys_major, 0));// 删除设备节点
	class_destroy(keys_class); //注销类
	cdev_del(pcdev); // 注销设备
	kfree(pcdev);    // 回收内存
	unregister_chrdev_region(MKDEV(keys_major, 0), 1);// 注销设备号
	printk("%s:%d\n",__FUNCTION__,__LINE__);
}

module_init(keys_drv_init);
module_exit(keys_drv_exit);
MODULE_LICENSE("GPL");
<file_sep>/sys_program/player/kill.sh

str=`ps | grep mplayer`
echo "$str"

i=1
for arg in `ps | grep ./mplayer`
do
	if [ $i -eq 1 ]
	then
		kill -9 $arg
		echo "mplayer killed!!"
	fi

	i=$[ $i + 1 ]
done

j=1
for arg2 in `ps | grep mplayer`
do
	if [ $j -eq 1 ]
	then
		kill -9 $arg2
		echo "mplayer killed!!"
		exit
	fi

	j=$[ $j + 1 ]
done
<file_sep>/c/practice/3rd_week/gps/Makefile
agps:gps.c
	gcc -o agps gps.c

clean:
	rm agps
<file_sep>/sys_program/2nd_day/am/execl.c
/* ************************************************************************
 *       Filename:  exec.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 11时07分06秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
	execl("/bin/ls","ls","-l","-a","-h",NULL);
	return 0;
}


<file_sep>/gtk/1. base/05_list/list.c
#include <gtk/gtk.h>

// 用户点击"Add List"按钮时的回调函数
void button_add_clicked( GtkWidget *widget, gpointer data )
{
	char *a[2] = {"Mike",  "3 Oz"};
	gtk_clist_append( (GtkCList *)data, a );

	char *b[2] = { "Water",   "6 l" };
	gtk_clist_append( (GtkCList *)data, b );
}

//用户点击"Clear List"  按钮时的回调函数
void button_clear_clicked( GtkWidget *widget, gpointer data )
{
	/* 用gtk_clist_clear函数清除列表。比用
	 * gtk_clist_remove函数逐行清除要快
	 */
	gtk_clist_clear( (GtkCList *)data );
}

// 用户选中某一行时的回调函数
void selection_made( GtkWidget *clist, gint row, gint column,
					GdkEventButton *event, gpointer data )
{
	gtk_widget_queue_draw(clist);	// 人为更新列表，开发板有效
	
	gchar *text;
	
	/* 取得存储在被选中的行和列的单元格上的文本
	 * 当鼠标点击时，我们用text参数接收一个指针
	 */
	gtk_clist_get_text(GTK_CLIST(clist), row, column, &text);
	//打印一些关于选中了哪一行的信息
	g_print("第%d行，第%d列的内容为%s\n", row, column, text);
}

int main( int argc, gchar *argv[] )
{                                  
	gtk_init(&argc, &argv);					// 初始化
	
	// 主窗口
	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);	// 创建窗口
	gtk_widget_set_size_request(GTK_WIDGET(window), 300, 300);	// 设置最小大小
	gtk_window_set_title(GTK_WINDOW(window), "GtkCList Example");	// 设置标题
	gtk_window_set_resizable(GTK_WINDOW(window), FALSE); 			// 固定窗口大小
	g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit),  NULL);
	
	// 表格布局容器
	GtkWidget *table = gtk_table_new(5, 2, TRUE);
	gtk_container_add(GTK_CONTAINER(window), table);

	/* 创建一个滚动窗口构件，将GtkCList组装到里面。
	 * 这样使得内容超出列表时，可以用滚动条浏览
	 * 第一个参数是水平方向的调整对象，第二个参数是垂直方向的调整对象。它们总是设置为NULL。
	 */
	GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL);
	gtk_table_attach_defaults(GTK_TABLE(table), scrolled_window, 0, 2, 0, 4);// 把按钮加入布局
	
	// GTK_POLICY_AUTOMATIC：滚动条根据需要自动出现时
	gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window),
					GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	

	gchar *titles[2] = { "Ingredients", "Amount" };
	// 创建GtkCList构件。本例中，我们使用了两列
	GtkWidget *clist = gtk_clist_new_with_titles(2, titles);
	// 将GtkCList构件添加到滚动窗口构件中
	gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), clist); 
	
	/* 设置某列内容显示的对齐方式
	 * GTK_JUSTIFY_LEFT：  列中的文本左对齐。
	 * GTK_JUSTIFY_RIGHT： 列中的文本右对齐。
	 * GTK_JUSTIFY_CENTER：列中的文本居中对齐。
	 * GTK_JUSTIFY_FILL：  文本使用列中所有可用的空间
	 */
	gtk_clist_set_column_justification(GTK_CLIST(clist), 1, GTK_JUSTIFY_CENTER);
	 
	/* 很重要的一点，我们设置列宽，让文本能容纳在列中。
	 * 注意，列编号是从0开始的, 本例中是0和1
	 */
	gtk_clist_set_column_width(GTK_CLIST(clist), 0, 100);
	
	// 选择某一行时触发selection_made回调函数
	g_signal_connect(clist, "select-row", G_CALLBACK(selection_made), NULL);
	
	
	// 按钮的创建，并放进布局容器里
	GtkWidget *button_add = gtk_button_new_with_label("Add List");
	GtkWidget *button_clear = gtk_button_new_with_label("Clear List");
	gtk_table_attach_defaults(GTK_TABLE(table), button_add, 0, 1, 4, 5);// 把按钮加入布局
	gtk_table_attach_defaults(GTK_TABLE(table), button_clear, 1, 2, 4, 5);// 把按钮加入布局
	
	// 为按钮的点击设置回调函数
	g_signal_connect(button_add, "clicked", G_CALLBACK(button_add_clicked), (gpointer)clist);
	g_signal_connect(button_clear, "clicked", G_CALLBACK(button_clear_clicked), (gpointer)clist);
				
	/* 界面已经完全设置好了，下面可以显示窗口，
	 * 进入gtk_main主循环
	 */
	gtk_widget_show_all(window);
	
	gtk_main();

	return 0;
}<file_sep>/work/camera/bf3703/BF3703_MTK6225_Drv_V3.0/image_sensor.c
/****************************BF3703_BYD_VGA_Sensor***************************
*  Copyright Statement:
*  --------------------
*  This software is protected by Copyright and the information contained
*  herein is confidential. The software may not be copied and the information
*  contained herein may not be used or disclosed except with the written
*  permission of MediaTek Inc. (C) 2010
*
*  BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
*  THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
*  RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
*  AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
*  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
*  NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
*  SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
*  SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
*  THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
*  NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
*  SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
*  BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
*  LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
*  AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
*  OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
*  MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. 
*
*  THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
*  WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
*  LAWS PRINCIPLES.  ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
*  RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
*  THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/

/*****************************************************************************
 *
 * Filename:
 * ---------
 *   image_sensor.c
 *
 * Version:
 * --------
 *   BF3703 MTK 6225 or 6226 DRV V1.0.0
 *
 * Release Date:
 * ------------
 *   2010-07-26
 *
 * Description:
 * ------------
 *   Image sensor driver function
 *
 * Author:
 * BYD Sensor Group
 * -------
 *
 *============================================================================
 *             HISTORY
 * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *------------------------------------------------------------------------------
 *
 *------------------------------------------------------------------------------
 * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *============================================================================

 ****************************************************************************/
#include "drv_comm.h"
#include "IntrCtrl.h"
#include "reg_base.h"
#include "gpio_sw.h"
#include "sccb.h"
#include "isp_if.h"
#include "image_sensor.h"
#include "camera_para.h"
#include "upll_ctrl.h"
#include "med_api.h"

#define BF3703_BYD			{ 128, 0 }

/* Global Valuable */
SensorInfo g_CCT_MainSensor=BF3703_BYD;// must be defined but not referenced by YUV driver
kal_uint8 g_CCT_FirstGrabColor = INPUT_ORDER_CbYCrY1;   // must be defined but not referenced by YUV driver
kal_uint8  start_grab_x_offset=0, start_grab_y_offset=0;
kal_bool   gVGAmode=KAL_TRUE, sensor_night_mode=KAL_FALSE, MPEG4_encode_mode=KAL_FALSE, g_bMJPEG_mode = KAL_FALSE;
kal_uint8  preview_pclk_division=0, capture_pclk_division=0;
kal_uint16 dummy_pixels=0,pre_dummy_pixels=0,cap_dummy_pixels=0,dummy_lines=0, extra_exposure_lines=0;
kal_uint16 exposure_lines=0;

/* MAX/MIN Explosure Lines Used By AE Algorithm */
kal_uint16 MAX_EXPOSURE_LINES=1000;
kal_uint8  MIN_EXPOSURE_LINES=2;
/* Parameter For Engineer mode function */
kal_uint32 FAC_SENSOR_REG;
/* Image Sensor ID */
kal_uint16 sensor_id=0;

kal_bool sensor_cap_state=KAL_FALSE;

#ifndef HW_SCCB

void SCCB_send_byte(kal_uint8 send_byte)
{
	volatile signed char i;
	volatile kal_uint32 j;

	for (i=7;i>=0;i--)
	{	/* data bit 7~0 */
		if (send_byte & (1<<i))
		{
			SET_SCCB_DATA_HIGH;
		}
		else
		{
			SET_SCCB_DATA_LOW;
		}
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SET_SCCB_CLK_HIGH;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SET_SCCB_CLK_LOW;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
	}
	/* don't care bit, 9th bit */
	SET_SCCB_DATA_LOW;
	SET_SCCB_DATA_INPUT;
	SET_SCCB_CLK_HIGH;
	for(j=0;j<SENSOR_I2C_DELAY;j++);
	SET_SCCB_CLK_LOW;
	SET_SCCB_DATA_OUTPUT;
}	/* SCCB_send_byte() */

kal_uint8 SCCB_get_byte(void)
{
	volatile signed char i;
	volatile kal_uint32 j;
	kal_uint8 get_byte=0;

	SET_SCCB_DATA_INPUT;

	for (i=7;i>=0;i--)
	{	/* data bit 7~0 */
		SET_SCCB_CLK_HIGH;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		if (GET_SCCB_DATA_BIT)
			get_byte |= (1<<i);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SET_SCCB_CLK_LOW;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
	}
	/* don't care bit, 9th bit */
	SET_SCCB_DATA_OUTPUT;
	SET_SCCB_DATA_HIGH;
	for(j=0;j<SENSOR_I2C_DELAY;j++);
	SET_SCCB_CLK_HIGH;
	for(j=0;j<SENSOR_I2C_DELAY;j++);
	SET_SCCB_CLK_LOW;

	return get_byte;
}	/* SCCB_get_byte() */

#endif

void write_cmos_sensor(kal_uint32 addr, kal_uint32 para)
{
	volatile kal_uint32 j;
	
	#ifdef HW_SCCB
		SET_SCCB_DATA_LENGTH(3);
		ENABLE_SCCB;
		REG_SCCB_DATA = BF3703_WRITE_ID | SCCB_DATA_REG_ID_ADDRESS;
		REG_SCCB_DATA = addr;
		REG_SCCB_DATA = para;
		while (SCCB_IS_WRITTING) {};
	#else
		I2C_START_TRANSMISSION;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SCCB_send_byte(BF3703_WRITE_ID);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SCCB_send_byte(addr);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SCCB_send_byte(para);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		I2C_STOP_TRANSMISSION;
	#endif /* HW_SCCB */
}	/* write_cmos_sensor() */

kal_uint32 read_cmos_sensor(kal_uint32 addr)
{
	volatile kal_uint32 j;
	kal_uint8 get_byte=0;
	
	#ifdef HW_SCCB
		SET_SCCB_DATA_LENGTH(2);
		ENABLE_SCCB;
		REG_SCCB_DATA = BF3703_WRITE_ID | SCCB_DATA_REG_ID_ADDRESS;
		REG_SCCB_DATA = addr;
		while (SCCB_IS_WRITTING) {};
		ENABLE_SCCB;
		REG_SCCB_DATA = BF3703_READ_ID | SCCB_DATA_REG_ID_ADDRESS;
		REG_SCCB_DATA=0;
		while (SCCB_IS_READING) {};
		get_byte = REG_SCCB_READ_DATA & 0xFF;
	#else
		I2C_START_TRANSMISSION;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SCCB_send_byte(BF3703_WRITE_ID);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SCCB_send_byte(addr);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		I2C_STOP_TRANSMISSION;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		I2C_START_TRANSMISSION;
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		SCCB_send_byte(BF3703_READ_ID);
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		get_byte=SCCB_get_byte();
		for(j=0;j<SENSOR_I2C_DELAY;j++);
		I2C_STOP_TRANSMISSION;
	#endif

	return get_byte;
}	/* read_cmos_sensor() */

void write_BF3703_shutter(kal_uint16 shutter)
{			 
	write_cmos_sensor(0x8c,(shutter&0xFF00)>>8);
	write_cmos_sensor(0x8D,shutter&0xFF);
}	/* write_BF3703_shutter */

kal_uint16 read_BF3703_shutter(void)
{
	kal_uint8 temp_reg1, temp_reg2;
	kal_uint16 shutter;

	temp_reg1=read_cmos_sensor(0x8c);
	temp_reg2=read_cmos_sensor(0x8d);
	
	shutter=((temp_reg1&0xff)<<8)|(temp_reg2);
	exposure_lines=shutter;

	return exposure_lines;
}	/* read_BF3703_shutter */

void set_BF3703_dummy(kal_uint16 pixels, kal_uint16 lines)
{
	write_cmos_sensor(0x2A,((pixels&0x700)>>4));
	write_cmos_sensor(0x2B,(pixels&0xFF));
	write_cmos_sensor(0x92,(lines&0xFF));
	write_cmos_sensor(0x93,((lines&0xFF00)>>8));
}	/* set_BF3703_dummy */



/*************************************************************************
* FUNCTION
*	init_BF3703
*
* DESCRIPTION
*	This function initialize the registers of CMOS sensor and ISP control register.
*
* PARAMETERS
*	None
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_int8 init_BF3703(void)
{
	kal_uint8 I;
	cis_module_power_on(KAL_TRUE);      // Power On CIS Power
	kal_sleep_task(2);
	PWRDN_PIN_LOW;

	/* Sensor Signal Polarity */
	/* Note: Set HSync Polarity to Low means High active */
	SET_CMOS_CLOCK_POLARITY_LOW;
	SET_VSYNC_POLARITY_LOW;
	SET_HSYNC_POLARITY_LOW;    
	kal_sleep_task(2);

	/* YUV Sensor Input Format */
	ENABLE_CAMERA_INDATA_FORMAT;  /* Enable yuv data input */
	SET_CAMERA_INPUT_TYPE(INPUT_YUV422);
	SET_CAMERA_INPUT_ORDER(INPUT_ORDER_CrYCbY1);

	/* Use UPLL to produce 48M clock, then divided by 2 */
	ENABLE_CAMERA_TG_CLK_48M;
	UPLL_Enable(UPLL_OWNER_ISP);    	
	set_isp_driving_current(camera_para.SENSOR.reg[CMMCLK_CURRENT_INDEX].para);

	/* Reset the sensor */
	RESET_PIN_HIGH;
	RESET_PIN_LOW;
	for (I = 0; I < 0x80; I++);
	RESET_PIN_HIGH;
	kal_sleep_task(10);

	sensor_id=(read_cmos_sensor(0xFC)<<8)|read_cmos_sensor(0xFD);
	kal_prompt_trace(MOD_MMI,"------->>>> BF3703 sensor_id==%x",sensor_id);
	
	if(sensor_id != BF3703_SENSOR_ID)
	return -1;
	kal_sleep_task(10);

	write_cmos_sensor(0x11,0x80);
	write_cmos_sensor(0x09,0x00);
	write_cmos_sensor(0x13,0x00);
	write_cmos_sensor(0x01,0x13);
	write_cmos_sensor(0x02,0x25);
	write_cmos_sensor(0x8c,0x02);//01 :devided by 2  02 :devided by 1
	write_cmos_sensor(0x8d,0xfd);//cb: devided by 2  fd :devided by 1
	write_cmos_sensor(0x87,0x1a);
	write_cmos_sensor(0x13,0x07);

	//POLARITY of Signal
	write_cmos_sensor(0x15,0x40);
	write_cmos_sensor(0x3a,0x03);		

	//black level ,对上电偏绿有改善,如果需要请选择使用
	/*
	write_cmos_sensor(0x05,0x1f);
	write_cmos_sensor(0x06,0x60);
	write_cmos_sensor(0x14,0x1f);
	write_cmos_sensor(0x27,0x03);
	write_cmos_sensor(0x06,0xe0);
	*/

	//lens shading
	write_cmos_sensor(0x35,0x68);
	write_cmos_sensor(0x65,0x68);
	write_cmos_sensor(0x66,0x62);
	write_cmos_sensor(0x36,0x05);
	write_cmos_sensor(0x37,0xf6);
	write_cmos_sensor(0x38,0x46);
	write_cmos_sensor(0x9b,0xf6);
	write_cmos_sensor(0x9c,0x46);
	write_cmos_sensor(0xbc,0x01);
	write_cmos_sensor(0xbd,0xf6);
	write_cmos_sensor(0xbe,0x46);

	//AE
	write_cmos_sensor(0x82,0x14);
	write_cmos_sensor(0x83,0x23);
	write_cmos_sensor(0x9a,0x23);//the same as 0x83
	write_cmos_sensor(0x84,0x1a);
	write_cmos_sensor(0x85,0x20);
	write_cmos_sensor(0x89,0x04);//02 :devided by 2  04 :devided by 1
	write_cmos_sensor(0x8a,0x08);//04: devided by 2  05 :devided by 1
	write_cmos_sensor(0x86,0x28);//the same as 0x7b
	write_cmos_sensor(0x96,0xa6);//AE speed
	write_cmos_sensor(0x97,0x0c);//AE speed
	write_cmos_sensor(0x98,0x18);//AE speed
	//AE target
	write_cmos_sensor(0x24,0x7a);//灯箱测试  0x6a
	write_cmos_sensor(0x25,0x8a);//灯箱测试  0x7a
	write_cmos_sensor(0x94,0x0a);//INT_OPEN  
	write_cmos_sensor(0x80,0x55);

	//denoise 
	write_cmos_sensor(0x70,0x6f);//denoise
	write_cmos_sensor(0x72,0x4f);//denoise
	write_cmos_sensor(0x73,0x2f);//denoise
	write_cmos_sensor(0x74,0x27);//denoise
	write_cmos_sensor(0x77,0x90);//去除格子噪声
	write_cmos_sensor(0x7a,0x4e);//denoise in	  low light,0x8e\0x4e\0x0e
	write_cmos_sensor(0x7b,0x28);//the same as 0x86

	//black level
	write_cmos_sensor(0X1F,0x20);//G target
	write_cmos_sensor(0X22,0x20);//R target
	write_cmos_sensor(0X26,0x20);//B target
	//模拟部分参数
	write_cmos_sensor(0X16,0x00);//如果觉得黑色物体不够黑，有点偏红，将0x16写为0x03会有点改善		
	write_cmos_sensor(0xbb,0x20);	// deglitch  对xclk整形
	write_cmos_sensor(0xeb,0x30);
	write_cmos_sensor(0xf5,0x21);
	write_cmos_sensor(0xe1,0x3c);
	write_cmos_sensor(0xbb,0x20);
	write_cmos_sensor(0X2f,0X66);
	write_cmos_sensor(0x06,0xe0);



	//anti black sun spot
	write_cmos_sensor(0x61,0xd3);//0x61[3]=0 black sun disable
	write_cmos_sensor(0x79,0x48);//0x79[7]=0 black sun disable

	//contrast
	write_cmos_sensor(0x56,0x40);

	//Gamma

	write_cmos_sensor(0x3b,0x60);//auto gamma offset adjust in  low light	  
	write_cmos_sensor(0x3c,0x20);//auto gamma offset adjust in  low light	  

	write_cmos_sensor(0x39,0x80);	  
	/*//gamma1
	write_cmos_sensor(0x3f,0xb0);
	write_cmos_sensor(0X40,0X88);
	write_cmos_sensor(0X41,0X74);
	write_cmos_sensor(0X42,0X5E);
	write_cmos_sensor(0X43,0X4c);
	write_cmos_sensor(0X44,0X44);
	write_cmos_sensor(0X45,0X3E);
	write_cmos_sensor(0X46,0X39);
	write_cmos_sensor(0X47,0X35);
	write_cmos_sensor(0X48,0X31);
	write_cmos_sensor(0X49,0X2E);
	write_cmos_sensor(0X4b,0X2B);
	write_cmos_sensor(0X4c,0X29);
	write_cmos_sensor(0X4e,0X25);
	write_cmos_sensor(0X4f,0X22);
	write_cmos_sensor(0X50,0X1F);*/

	/*gamma2	过曝过度好，高亮度
	write_cmos_sensor(0x3f,0xb0);
	write_cmos_sensor(0X40,0X9b);
	write_cmos_sensor(0X41,0X88);
	write_cmos_sensor(0X42,0X6e);
	write_cmos_sensor(0X43,0X59);
	write_cmos_sensor(0X44,0X4d);
	write_cmos_sensor(0X45,0X45);
	write_cmos_sensor(0X46,0X3e);
	write_cmos_sensor(0X47,0X39);
	write_cmos_sensor(0X48,0X35);
	write_cmos_sensor(0X49,0X31);
	write_cmos_sensor(0X4b,0X2e);
	write_cmos_sensor(0X4c,0X2b);
	write_cmos_sensor(0X4e,0X26);
	write_cmos_sensor(0X4f,0X23);
	write_cmos_sensor(0X50,0X1F);
	*/
	/*//gamma3 清晰亮丽 灰阶分布好
	write_cmos_sensor(0X3f,0Xb0);
	write_cmos_sensor(0X40,0X60);
	write_cmos_sensor(0X41,0X60);
	write_cmos_sensor(0X42,0X66);
	write_cmos_sensor(0X43,0X57);
	write_cmos_sensor(0X44,0X4c);
	write_cmos_sensor(0X45,0X43);
	write_cmos_sensor(0X46,0X3c);
	write_cmos_sensor(0X47,0X37);
	write_cmos_sensor(0X48,0X33);
	write_cmos_sensor(0X49,0X2f);
	write_cmos_sensor(0X4b,0X2c);
	write_cmos_sensor(0X4c,0X29);
	write_cmos_sensor(0X4e,0X25);
	write_cmos_sensor(0X4f,0X22);
	write_cmos_sensor(0X50,0X20);*/

	//gamma 4   low noise   
	write_cmos_sensor(0X3f,0Xa8);
	write_cmos_sensor(0X40,0X48);
	write_cmos_sensor(0X41,0X54);
	write_cmos_sensor(0X42,0X4E);
	write_cmos_sensor(0X43,0X44);
	write_cmos_sensor(0X44,0X3E);
	write_cmos_sensor(0X45,0X39);
	write_cmos_sensor(0X46,0X35);
	write_cmos_sensor(0X47,0X31);
	write_cmos_sensor(0X48,0X2E);
	write_cmos_sensor(0X49,0X2B);
	write_cmos_sensor(0X4b,0X29);
	write_cmos_sensor(0X4c,0X27);
	write_cmos_sensor(0X4e,0X23);
	write_cmos_sensor(0X4f,0X20);
	write_cmos_sensor(0X50,0X20);


	//color matrix
	write_cmos_sensor(0x51,0x0d);
	write_cmos_sensor(0x52,0x21);
	write_cmos_sensor(0x53,0x14);
	write_cmos_sensor(0x54,0x15);
	write_cmos_sensor(0x57,0x8d);
	write_cmos_sensor(0x58,0x78);
	write_cmos_sensor(0x59,0x5f);
	write_cmos_sensor(0x5a,0x84);
	write_cmos_sensor(0x5b,0x25);
	write_cmos_sensor(0x5D,0x95);
	write_cmos_sensor(0x5C,0x0e);

	/* 

	// color	艳丽
	write_cmos_sensor(0x51,0x0e);
	write_cmos_sensor(0x52,0x16);
	write_cmos_sensor(0x53,0x07);
	write_cmos_sensor(0x54,0x1a);
	write_cmos_sensor(0x57,0x9d);
	write_cmos_sensor(0x58,0x82);
	write_cmos_sensor(0x59,0x71);
	write_cmos_sensor(0x5a,0x8d);
	write_cmos_sensor(0x5b,0x1c);
	write_cmos_sensor(0x5D,0x95);
	write_cmos_sensor(0x5C,0x0e);
	//  

	//适中
	write_cmos_sensor(0x51,0x08);
	write_cmos_sensor(0x52,0x0E);
	write_cmos_sensor(0x53,0x06);
	write_cmos_sensor(0x54,0x12);
	write_cmos_sensor(0x57,0x82);
	write_cmos_sensor(0x58,0x70);
	write_cmos_sensor(0x59,0x5C);
	write_cmos_sensor(0x5a,0x77);
	write_cmos_sensor(0x5b,0x1B);
	write_cmos_sensor(0x5c,0x0e);//0x5c[3:0] low light color coefficient，smaller ,lower noise
	write_cmos_sensor(0x5d,0x95);


	//color 淡
	write_cmos_sensor(0x51,0x03);
	write_cmos_sensor(0x52,0x0d);
	write_cmos_sensor(0x53,0x0b);
	write_cmos_sensor(0x54,0x14);
	write_cmos_sensor(0x57,0x59);
	write_cmos_sensor(0x58,0x45);
	write_cmos_sensor(0x59,0x41);
	write_cmos_sensor(0x5a,0x5f);
	write_cmos_sensor(0x5b,0x1e);
	write_cmos_sensor(0x5c,0x0e);//0x5c[3:0] low light color coefficient，smaller ,lower noise
	write_cmos_sensor(0x5d,0x95);
	*/

	write_cmos_sensor(0x60,0x20);//color open in low light 
	//AWB
	write_cmos_sensor(0x6a,0x01);//如果肤色偏色，将0x6a写为0x81.
	write_cmos_sensor(0x23,0x66);//Green gain
	write_cmos_sensor(0xa0,0x07);//0xa0写0x03，黑色物体更红；0xa0写0x07，黑色物体更黑；

	write_cmos_sensor(0xa1,0X41);//
	write_cmos_sensor(0xa2,0X0e);
	write_cmos_sensor(0xa3,0X26);
	write_cmos_sensor(0xa4,0X0d);
	//冷色调
	write_cmos_sensor(0xa5,0x28);//The upper limit of red gain 

	/*暖色调
	write_cmos_sensor(0xa5,0x2d);
	*/
	write_cmos_sensor(0xa6,0x04);
	write_cmos_sensor(0xa7,0x80);//BLUE Target
	write_cmos_sensor(0xa8,0x80);//RED Target
	write_cmos_sensor(0xa9,0x28);
	write_cmos_sensor(0xaa,0x28);
	write_cmos_sensor(0xab,0x28);
	write_cmos_sensor(0xac,0x3c);
	write_cmos_sensor(0xad,0xf0);
	write_cmos_sensor(0xc8,0x18);
	write_cmos_sensor(0xc9,0x20);
	write_cmos_sensor(0xca,0x17);
	write_cmos_sensor(0xcb,0x1f);
	write_cmos_sensor(0xaf,0x00);			
	write_cmos_sensor(0xc5,0x18);		
	write_cmos_sensor(0xc6,0x00);
	write_cmos_sensor(0xc7,0x20);		
	write_cmos_sensor(0xae,0x83);//如果照户外偏蓝，将此寄存器0xae写为0x81。
	write_cmos_sensor(0xcc,0x30);
	write_cmos_sensor(0xcd,0x70);
	write_cmos_sensor(0xee,0x4c);// P_TH

	// color saturation
	write_cmos_sensor(0xb0,0xd0);
	write_cmos_sensor(0xb1,0xc0);
	write_cmos_sensor(0xb2,0xb0);

	/* // 饱和度艳丽
	write_cmos_sensor(0xb1,0xd0);
	write_cmos_sensor(0xb2,0xc0);		
	*/
	write_cmos_sensor(0xb3,0x88);

	//anti webcamera banding
	write_cmos_sensor(0x9d,0x4c);

	//switch direction
	write_cmos_sensor(0x1e,0x00);//00:normal  10:IMAGE_V_MIRROR   20:IMAGE_H_MIRROR  30:IMAGE_HV_MIRROR

	return 1;
	
		/* init_cmos_sensor() */
}
/*************************************************************************
* FUNCTION
*	power_off_BF3703
*
* DESCRIPTION
*	This function is to turn off sensor module power.
*
* PARAMETERS
*	None
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/

void power_off_BF3703(void)
{
	cis_module_power_on(KAL_FALSE);      // Power Off CIS Power
	UPLL_Disable(UPLL_OWNER_ISP);
	#ifndef HW_SCCB
	   SET_SCCB_CLK_LOW;
	   SET_SCCB_DATA_LOW;
	#endif
}	/* power_off_BF3703 */

/*************************************************************************
* FUNCTION
*	get_BF3703_id
*
* DESCRIPTION
*	This function return the sensor read/write id of SCCB interface.
*
* PARAMETERS
*	*sensor_write_id : address pointer of sensor write id
*  *sensor_read_id  : address pointer of sensor read id
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void get_BF3703_id(kal_uint8 *sensor_write_id, kal_uint8 *sensor_read_id)
{
	*sensor_write_id=BF3703_WRITE_ID;
	*sensor_read_id=BF3703_READ_ID;
}	/* get_BF3703_id */

/*************************************************************************
* FUNCTION
*	get_BF3703_size
*
* DESCRIPTION
*	This function return the image width and height of image sensor.
*
* PARAMETERS
*	*sensor_width : address pointer of horizontal effect pixels of image sensor
*  *sensor_height : address pointer of vertical effect pixels of image sensor
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void get_BF3703_size(kal_uint16 *sensor_width, kal_uint16 *sensor_height)
{
	*sensor_width=IMAGE_SENSOR_VGA_WIDTH;			/* pixel numbers actually used in one frame */
	*sensor_height=IMAGE_SENSOR_VGA_HEIGHT;		/* line numbers actually used in one frame */
}	/* get_BF3703_size */

/*************************************************************************
* FUNCTION
*	get_BF3703_period
*
* DESCRIPTION
*	This function return the image width and height of image sensor.
*
* PARAMETERS
*	*pixel_number : address pointer of pixel numbers in one period of HSYNC
*  *line_number : address pointer of line numbers in one period of VSYNC
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void get_BF3703_period(kal_uint16 *pixel_number, kal_uint16 *line_number)
{
	*pixel_number=VGA_PERIOD_PIXEL_NUMS;		/* pixel numbers in one period of HSYNC */
	*line_number=VGA_PERIOD_LINE_NUMS;			/* line numbers in one period of VSYNC */
}	/* get_BF3703_period */

void BF3703_preview(image_sensor_exposure_window_struct *image_window, image_sensor_config_struct *sensor_config_data)
{

	sensor_cap_state=KAL_FALSE;
	g_bMJPEG_mode = KAL_FALSE;

	write_cmos_sensor(0x11,0x80);	//MCLK = PCLK

	if((sensor_config_data->isp_op_mode==ISP_MJPEG_PREVIEW_MODE)||(sensor_config_data->isp_op_mode==ISP_MJPEG_ENCODE_MODE))
	{   //MT6225 video mode
		
		MPEG4_encode_mode=KAL_FALSE;
		g_bMJPEG_mode = KAL_TRUE;

		/* config TG of ISP to match the setting of image sensor*/
		SET_TG_OUTPUT_CLK_DIVIDER(3);			
		SET_CMOS_RISING_EDGE(0);
		SET_CMOS_FALLING_EDGE(2);
		ENABLE_CAMERA_PIXEL_CLKIN_ENABLE;
		SET_TG_PIXEL_CLK_DIVIDER(3);
		SET_CMOS_DATA_LATCH(2);

		pre_dummy_pixels=32;
		dummy_lines=32;//anti_flicker 32:devided by 2   103: devided by 1	

	}
	else
	{
		if(sensor_config_data->frame_rate==0x0F)		// MPEG4 Encode Mode
		{
			//MT6226 video mode 
			kal_prompt_trace(MOD_MMI," BF3703  video");
			MPEG4_encode_mode=KAL_TRUE;

			/* config TG of ISP to match the setting of image sensor*/
			SET_TG_OUTPUT_CLK_DIVIDER(3);
			SET_CMOS_RISING_EDGE(0);
			SET_CMOS_FALLING_EDGE(2);
			ENABLE_CAMERA_PIXEL_CLKIN_ENABLE;
			SET_TG_PIXEL_CLK_DIVIDER(3);
			SET_CMOS_DATA_LATCH(2);

			pre_dummy_pixels=32;
			dummy_lines=32;//anti_flicker 32:devided by 2   103: devided by 1	
		}
		else
		{

			kal_prompt_trace(MOD_MMI," BF3703  preview");
			MPEG4_encode_mode=KAL_FALSE;

			/* config TG of ISP to match the setting of image sensor*/
			SET_TG_OUTPUT_CLK_DIVIDER(1);			
			SET_CMOS_RISING_EDGE(0);
			SET_CMOS_FALLING_EDGE(1);
			ENABLE_CAMERA_PIXEL_CLKIN_ENABLE;
			SET_TG_PIXEL_CLK_DIVIDER(1);
			SET_CMOS_DATA_LATCH(1);

			pre_dummy_pixels=32;
			dummy_lines=64;//anti_flicker 32:devided by 2   64: devided by 1	
		}
	}

	preview_pclk_division=((DRV_Reg32(ISP_TG_PHASE_COUNTER_REG)&0xF0)>>4)+1;

	image_window->grab_start_x=IMAGE_SENSOR_VGA_INSERTED_PIXELS;
	image_window->grab_start_y=IMAGE_SENSOR_VGA_INSERTED_LINES+start_grab_y_offset;
	image_window->exposure_window_width=IMAGE_SENSOR_VGA_WIDTH;
	image_window->exposure_window_height=IMAGE_SENSOR_VGA_HEIGHT-1;	
	
	set_BF3703_dummy(pre_dummy_pixels,dummy_lines);
	write_BF3703_shutter(exposure_lines); 

	if (sensor_config_data->isp_op_mode == ISP_MJPEG_ENCODE_MODE) 
	{
	;
	}else 
	{
	// ISP_MJPEG_ENCODE_MODE mode does not invok YUV setting API after preview function
	// If turn on AEC/AGC/AWB in ISP_MJPEG_ENCODE_MODE mode, the AWB setting will be overwriten.
	write_cmos_sensor(0x13, 0x07);	// Turn ON AEC/AGC/AWB
	}
	
	kal_sleep_task(30);
		
}
void BF3703_capture(image_sensor_exposure_window_struct *image_window, image_sensor_config_struct *sensor_config_data)
{
	volatile kal_uint32 shutter=exposure_lines;

	sensor_cap_state=KAL_TRUE;
	
	if(sensor_config_data->enable_shutter_tansfer==KAL_TRUE)
		shutter=sensor_config_data->capture_shutter;
			
	if(!(sensor_config_data->frame_rate==0xF0))	// If not WEBCAM mode.
	{
		kal_prompt_trace(MOD_MMI,"Not WEBCAM MODE");  

	    write_cmos_sensor(0x13,0xE2);  // Turn OffF AGC/AEC
	    
	    shutter=read_BF3703_shutter();
	}
	    	
	if ((image_window->image_target_width<IMAGE_SENSOR_1M_WIDTH)&&
		(image_window->image_target_height<IMAGE_SENSOR_1M_HEIGHT))
	{	/* Less than VGA Mode */
		if (image_window->digital_zoom_factor>=(ISP_DIGITAL_ZOOM_INTERVAL<<1))
		{
			kal_prompt_trace(MOD_MMI,"BF3703 ZOOM ");

			write_cmos_sensor(0x11,0xB0);

			SET_TG_PIXEL_CLK_DIVIDER(7);
			SET_CMOS_DATA_LATCH(4);
			cap_dummy_pixels=VGA_PERIOD_PIXEL_NUMS/4;
			dummy_lines=0;
		}
		else
		{
			if(sensor_config_data->frame_rate==0xF0)	//  WEBCAM  Preview mode.
			{
				write_cmos_sensor(0x11,0x90);

				SET_TG_PIXEL_CLK_DIVIDER(1);
				SET_CMOS_DATA_LATCH(1);

				start_grab_x_offset=0;
				start_grab_y_offset=0;
				cap_dummy_pixels=0;
				dummy_lines=0;
			}
			else
			{
				kal_prompt_trace(MOD_MMI,"BF3703 Capture");

				write_cmos_sensor(0x11,0x90);
			    
				SET_TG_PIXEL_CLK_DIVIDER(3);//3
				SET_CMOS_DATA_LATCH(2);
				cap_dummy_pixels=0;

			}
		}
			
			capture_pclk_division=((DRV_Reg32(ISP_TG_PHASE_COUNTER_REG)&0xF0)>>4)+1;
			
			shutter=(shutter*preview_pclk_division)/capture_pclk_division;
			shutter=(shutter*(VGA_PERIOD_PIXEL_NUMS+pre_dummy_pixels))/(VGA_PERIOD_PIXEL_NUMS+cap_dummy_pixels);
			if(shutter<1)
			shutter=1;
		}

	if ((image_window->image_target_width>=IMAGE_SENSOR_1M_WIDTH)&&
			(image_window->image_target_height>=IMAGE_SENSOR_1M_HEIGHT))
	{

		write_cmos_sensor(0x11,0x90);

		SET_TG_PIXEL_CLK_DIVIDER(3); 
		SET_CMOS_DATA_LATCH(2);

		cap_dummy_pixels=1000;
		capture_pclk_division=((DRV_Reg32(ISP_TG_PHASE_COUNTER_REG)&0xF0)>>4)+1;

		shutter=(shutter*preview_pclk_division)/capture_pclk_division;
		shutter=(shutter*(VGA_PERIOD_PIXEL_NUMS+pre_dummy_pixels))/((VGA_PERIOD_PIXEL_NUMS+cap_dummy_pixels));
		if(shutter<1)
		shutter=1;
	 }
			
	image_window->grab_start_x=IMAGE_SENSOR_VGA_INSERTED_PIXELS;
	image_window->grab_start_y=IMAGE_SENSOR_VGA_INSERTED_LINES;
	image_window->exposure_window_width=IMAGE_SENSOR_VGA_WIDTH;
	image_window->exposure_window_height=IMAGE_SENSOR_VGA_HEIGHT-1; // minus 1 to avoid the last black line


	set_BF3703_dummy(cap_dummy_pixels,dummy_lines);
	write_BF3703_shutter(shutter);
	
}	/* BF3703_capture() */

/*************************************************************************
* FUNCTION
*	write_BF3703_reg
*
* DESCRIPTION
*	This function set the register of BF3703.
*
* PARAMETERS
*	addr : the register index of BF3703
*  para : setting parameter of the specified register of BF3703
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void write_BF3703_reg(kal_uint32 addr, kal_uint32 para)
{
	write_cmos_sensor(addr,para);
}	/* write_BF3703_reg() */

/*************************************************************************
* FUNCTION
*	read_cmos_sensor
*
* DESCRIPTION
*	This function read parameter of specified register from BF3703.
*
* PARAMETERS
*	addr : the register index of BF3703
*
* RETURNS
*	the data that read from BF3703
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 read_BF3703_reg(kal_uint32 addr)
{
	return (read_cmos_sensor(addr));
}	/* read_BF3703_reg() */

/*************************************************************************
* FUNCTION
*	set_BF3703_shutter
*
* DESCRIPTION
*	This function set e-shutter of BF3703 to change exposure time.
*
* PARAMETERS
*	shutter : exposured lines
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void set_BF3703_shutter(kal_uint16 shutter)
{
	exposure_lines=shutter;
	write_BF3703_shutter(shutter); 
}	/* set_BF3703_shutter */

/*************************************************************************
* FUNCTION
*	set_BF3703_gain
*
* DESCRIPTION
*	This function is to set global gain to sensor.
*
* PARAMETERS
*	gain : sensor global gain(base: 0x40)
*
* RETURNS
*	the actually gain set to sensor.
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint16 set_BF3703_gain(kal_uint16 gain)
{
   return gain;
}

/*************************************************************************
* FUNCTION
*	BF3703_night_mode
*
* DESCRIPTION
*	This function night mode of BF3703.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void BF3703_night_mode(kal_bool enable)
{

	if (enable)
	{
		if (g_bMJPEG_mode||MPEG4_encode_mode)
		{
			// this mode is used by MT6225 or MT6226 video Night mode
			write_cmos_sensor(0X85, 0X2a);
			write_cmos_sensor(0X86, 0X30);
			write_cmos_sensor(0x7b, 0x30);		
			write_cmos_sensor(0x8e, 0x07);//Min fps =4	07 分频  0e 不分频
			write_cmos_sensor(0x8f, 0x79);// 79 分频   F2 不分频

		}
		else
		{  
			// this mode is used by camera Night mode
			write_cmos_sensor(0X85, 0X2a);
			write_cmos_sensor(0X86, 0X30);
			write_cmos_sensor(0x7b, 0x30);		
			write_cmos_sensor(0x8e, 0x0E);//Min fps =4  07 分频  0e 不分频
			write_cmos_sensor(0x8f, 0xF2);// 79 分频   F2 不分频     			                                                                                			                
		}

	}
	else
	{
		if (g_bMJPEG_mode||MPEG4_encode_mode)
		{
			// this mode is used by MT6225 or MT6226 video Normal mode
			write_cmos_sensor(0x8e, 0x03);
			write_cmos_sensor(0x8f, 0xbc);
		}
		else
		{  
			// this mode is used by camera  Normal mode 
			write_cmos_sensor(0x8e, 0x07);// MIN FPS=8  03 分频  07 不分频
			write_cmos_sensor(0x8f, 0x79);// bc 分频   79 不分频   			                                                                                			                
		}
	}	
	
}/* BF3703_night_mode */

/*************************************************************************
* FUNCTION
*	set_BF3703_flashlight
*
* DESCRIPTION
*	turn on/off BF3703 flashlight .
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void set_BF3703_flashlight(kal_bool enable)
{
	// Todo
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_zoom
*
* DESCRIPTION
*	BF3703 zoom setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_zoom(kal_uint32 para)
{
	return KAL_FALSE;
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_contrast
*
* DESCRIPTION
*	BF3703 contrast setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_contrast(kal_uint32 para)
{
	// Not Support
	return KAL_FALSE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_brightness
*
* DESCRIPTION
*	BF3703 brightness setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_brightness(kal_uint32 para)
{
	// Not Support
	return KAL_FALSE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_hue
*
* DESCRIPTION
*	BF3703 hue setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_hue(kal_uint32 para)
{
	// Not Support
	return KAL_FALSE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_gamma
*
* DESCRIPTION
*	BF3703 gamma setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_gamma(kal_uint32 para)
{
	return KAL_FALSE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_wb
*
* DESCRIPTION
*	BF3703 wb setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_wb(kal_uint32 para)
{
	kal_uint8  temp_reg;	
	temp_reg=read_cmos_sensor(0x13);

	switch (para)
	{
		case CAM_WB_AUTO:
			kal_prompt_trace(MOD_MMI,"------->>>AWB");
			write_cmos_sensor(0x01,0x15);
			write_cmos_sensor(0x02,0x24);
			write_cmos_sensor(0x13,temp_reg|0x2);   // Enable AWB		
			break;

		case CAM_WB_CLOUD:
			write_cmos_sensor(0x13,temp_reg&~0x2);  // Disable AWB				
			write_cmos_sensor(0x01,0x10);
			write_cmos_sensor(0x02,0x28);			
			break;		

		case CAM_WB_DAYLIGHT:
			write_cmos_sensor(0x13,temp_reg&~0x2);  // Disable AWB				
			write_cmos_sensor(0x01,0x13);
			write_cmos_sensor(0x02,0x26);
			break;		

		case CAM_WB_INCANDESCENCE:
			write_cmos_sensor(0x13,temp_reg&~0x2);  // Disable AWB				
			write_cmos_sensor(0x01,0x1f);
			write_cmos_sensor(0x02,0x15);
			break;		

		case CAM_WB_FLUORESCENT:
			write_cmos_sensor(0x13,temp_reg&~0x2);  // Disable AWB				
			write_cmos_sensor(0x01,0x1a);
			write_cmos_sensor(0x02,0x1e);
			break;		

		case CAM_WB_TUNGSTEN:
			write_cmos_sensor(0x13,temp_reg&~0x2);  // Disable AWB				
			write_cmos_sensor(0x01,0x1a);
			write_cmos_sensor(0x02,0x0d);
			break;

		case CAM_WB_MANUAL:		
		    // TODO
			break;		

		default:
			return KAL_FALSE;	
	}

	return KAL_TRUE;
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_exposure
*
* DESCRIPTION
*	BF3703 exposure setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_exposure(kal_uint32 para)
{
	switch (para)
	{
		case CAM_EV_NEG_4_3:    
            write_cmos_sensor(0x55, 0xF8);		
			break;		
		case CAM_EV_NEG_3_3:
            write_cmos_sensor(0x55, 0xD8);
			break;		
		case CAM_EV_NEG_2_3:
            write_cmos_sensor(0x55, 0xB8);
			break;				
		case CAM_EV_NEG_1_3:
            write_cmos_sensor(0x55, 0x98);
			break;				
		case CAM_EV_ZERO:
            write_cmos_sensor(0x55, 0x00);
			break;				
		case CAM_EV_POS_1_3:
            write_cmos_sensor(0x55, 0x18);
			break;				
		case CAM_EV_POS_2_3:
            write_cmos_sensor(0x55, 0x38);
			break;				
		case CAM_EV_POS_3_3:
            write_cmos_sensor(0x55, 0x58);
			break;				
		case CAM_EV_POS_4_3:	
            write_cmos_sensor(0x55, 0x78);
			break;
		default:
			return KAL_FALSE;    
	}	
	return KAL_TRUE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_effect
*
* DESCRIPTION
*	BF3703 effect setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_effect(kal_uint32 para)
{
    kal_uint32  ret = KAL_TRUE;
    
    kal_prompt_trace(MOD_MMI,"---->>effect");
	
	switch (para)
	{	
		case CAM_EFFECT_ENC_NORMAL:
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x00);		
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;		
		case CAM_EFFECT_ENC_GRAYSCALE:	
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x20);		
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);	
			break;		
		case CAM_EFFECT_ENC_SEPIA:		
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x20);		
			write_cmos_sensor(0x67,0x60);		
			write_cmos_sensor(0x68,0x98);	
			break;		
		case CAM_EFFECT_ENC_COLORINV:	
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x40);		
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);	
			break;		
		case CAM_EFFECT_ENC_SEPIAGREEN:		
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x20);		
			write_cmos_sensor(0x67,0x40);		
			write_cmos_sensor(0x68,0x40);	
			break;					
		case CAM_EFFECT_ENC_SEPIABLUE:	
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x20);		
			write_cmos_sensor(0x67,0xA0);		
			write_cmos_sensor(0x68,0x40);
			break;								
		case CAM_EFFECT_ENC_GRAYINV:	
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x20);		
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);				
			break;								
		case CAM_EFFECT_ENC_COPPERCARVING:
			write_cmos_sensor(0x69,0x00);
			write_cmos_sensor(0x80,0xc5);
			write_cmos_sensor(0x76,0xc0);
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);   	
			break;								
    	case CAM_EFFECT_ENC_BLUECARVING:
			write_cmos_sensor(0x69,0x00);
			write_cmos_sensor(0x80,0xc5);	
			write_cmos_sensor(0x76,0xd0);
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;								
		case CAM_EFFECT_ENC_CONTRAST:	
			write_cmos_sensor(0x80,0x45);		
			write_cmos_sensor(0x76,0x00);
			write_cmos_sensor(0x69,0x00);		
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;							
		case CAM_EFFECT_ENC_EMBOSSMENT:
			write_cmos_sensor(0x69,0x00);
			write_cmos_sensor(0x80,0xc5);	
			write_cmos_sensor(0x77,0x80);
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;
		case CAM_EFFECT_ENC_SKETCH:
			write_cmos_sensor(0x69,0x00);
			write_cmos_sensor(0x80,0xc5);		
			write_cmos_sensor(0x76,0xb0);
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;	
		case CAM_EFFECT_ENC_BLACKBOARD:
			write_cmos_sensor(0x69,0x00);
			write_cmos_sensor(0x80,0xc5);		
			write_cmos_sensor(0x76,0xe0);
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;
		case CAM_EFFECT_ENC_WHITEBOARD:
			write_cmos_sensor(0x69,0x00);
			write_cmos_sensor(0x80,0xc5);		
			write_cmos_sensor(0x76,0xf0);
			write_cmos_sensor(0x67,0x80);		
			write_cmos_sensor(0x68,0x80);
			break;
		case CAM_EFFECT_ENC_JEAN:
		case CAM_EFFECT_ENC_OIL:			
		default:
			ret = KAL_FALSE;
	}

	return ret;
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_banding
*
* DESCRIPTION
*	BF3703 banding setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_banding(kal_uint32 para)
{
	kal_uint8 temp_Reg_80,temp_Reg_2a,temp_Reg_2b;
	kal_uint16 dummy_pixels_banding;

	temp_Reg_80=read_cmos_sensor(0x80);
	temp_Reg_2a=read_cmos_sensor(0x2a);
	temp_Reg_2b=read_cmos_sensor(0x2b);
	dummy_pixels_banding=((temp_Reg_2a&0xF0)<<4)|(temp_Reg_2b);

	kal_prompt_trace(MOD_MMI,"------>>Banding");

	switch (para)
	{
		case CAM_BANDING_50HZ:
			if(g_bMJPEG_mode||MPEG4_encode_mode)   // video , MCLK=12M
			{			
				write_cmos_sensor(0x80,temp_Reg_80); 
				write_cmos_sensor(0x9d,60000/(784+dummy_pixels_banding));
			}
			else
			{
				write_cmos_sensor(0x80,temp_Reg_80);
				write_cmos_sensor(0x9d,120000/(784+dummy_pixels_banding));
			}
				break;                        
		case CAM_BANDING_60HZ:
			if(g_bMJPEG_mode||MPEG4_encode_mode)   //video , MCLK=12M
			{			
				write_cmos_sensor(0x80,temp_Reg_80&0xFE);	
				write_cmos_sensor(0x9e,6000000/(784+dummy_pixels_banding)/120);
			}
			else
			{
				write_cmos_sensor(0x80,temp_Reg_80&0xFE);	
				write_cmos_sensor(0x9e,12000000/(784+dummy_pixels_banding)/120);
			}
			break;
		default:
			return KAL_FALSE;	
		}

	return KAL_TRUE;
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_saturation
*
* DESCRIPTION
*	BF3703 SATURATION setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_saturation(kal_uint32 para)
{
    // Not Support
	return KAL_FALSE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_nightmode
*
* DESCRIPTION
*	BF3703 night mode setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_nightmode(kal_uint32 para)
{
	BF3703_night_mode((kal_bool)para);
	return KAL_TRUE;	
}

/*************************************************************************
* FUNCTION
*	set_BF3703_param_ev
*
* DESCRIPTION
*	BF3703 ev setting.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 set_BF3703_param_ev(kal_uint32 para)
{
	return set_BF3703_param_exposure(para);
}

/*************************************************************************
* FUNCTION
*	BF3703_yuv_sensor_setting
*
* DESCRIPTION
*	This function send command and parameter to yuv sensor module BF3703
*  to configure it
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
kal_uint32 BF3703_yuv_sensor_setting(kal_uint32 cmd, kal_uint32 para)
{
	kal_uint32 ret = KAL_TRUE;
	switch (cmd)
	{
		case CAM_PARAM_ZOOM_FACTOR:
			ret = set_BF3703_param_zoom(para);		
			break;			
		case CAM_PARAM_CONTRAST:
			ret = set_BF3703_param_contrast(para);		
			break;					
		case CAM_PARAM_BRIGHTNESS:
			ret = set_BF3703_param_brightness(para);		
			break;							
		case CAM_PARAM_HUE:
			ret = set_BF3703_param_hue(para);		
			break;							
		case CAM_PARAM_GAMMA:
			ret = set_BF3703_param_gamma(para);		
			break;							
		case CAM_PARAM_WB:
			ret = set_BF3703_param_wb(para);		
			break;
		case CAM_PARAM_EXPOSURE:
			ret = set_BF3703_param_exposure(para);		
			break;							
		case CAM_PARAM_EFFECT:
			ret = set_BF3703_param_effect(para);
			break;		
		case CAM_PARAM_BANDING:
			ret = set_BF3703_param_banding(para);		
			break;		
		case CAM_PARAM_SATURATION:
			ret = set_BF3703_param_saturation(para);				
			break;						
		case CAM_PARAM_NIGHT_MODE:
			ret = set_BF3703_param_nightmode(para);				
			break;						
		case CAM_PARAM_EV_VALUE:
			ret = set_BF3703_param_ev(para);				
			break;				
		default:
			ret = KAL_FALSE;
	}
	return ret;
}

/*************************************************************************
* FUNCTION
*	image_sensor_func_BF3703
*
* DESCRIPTION
*	BF3703 Image Sensor functions struct.
*
* PARAMETERS
*	none
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
image_sensor_func_struct image_sensor_func_BF3703=
{
	init_BF3703,
	get_BF3703_id,
	get_BF3703_size,
	get_BF3703_period,
	BF3703_preview,
	BF3703_capture,
	write_BF3703_reg,
	read_BF3703_reg,
	set_BF3703_shutter,
	BF3703_night_mode,
	power_off_BF3703,
	set_BF3703_gain,
	set_BF3703_flashlight,
	BF3703_yuv_sensor_setting
};	/* image_sensor_func_BF3703 */

/*************************************************************************
* FUNCTION
*	cam_module_func_config
*
* DESCRIPTION
*	This function maps the external camera module function API structure.
*
* PARAMETERS
*
* RETURNS
*	None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void image_sensor_func_config(void)
{
	image_sensor_func=&image_sensor_func_BF3703;
}	/* cam_module_func_config() */

// write camera_para to sensor register
void camera_para_to_sensor(void)
{
}

// update camera_para from sensor register
void sensor_to_camera_para(void)
{
}

//------------------------Engineer mode---------------------------------

void  get_sensor_group_count(kal_int32* sensor_count_ptr)
{
}

void get_sensor_group_info(kal_uint16 group_idx, kal_int8* group_name_ptr, kal_int32* item_count_ptr)
{
}

void get_sensor_item_info(kal_uint16 group_idx,kal_uint16 item_idx, ENG_sensor_info* info_ptr)
{
}

kal_bool set_sensor_item_info(kal_uint16 group_idx, kal_uint16 item_idx, kal_int32 item_value)
{

	return KAL_TRUE;
}
<file_sep>/work/test/v4l2/yuv2bmp.c
/*************************************************************************
	> Filename: capture.c
	>   Author: Qiuwei.wang
	>    Email: <EMAIL> / <EMAIL>
	> Datatime: Mon 28 Nov 2016 06:05:39 PM CST
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "yuv2bmp.h"

/*
 * Functions
 */

static unsigned int yuv2rgb_pixel(int y, int u, int v)
{
	unsigned int rgb_24 = 0;
	unsigned char *pixel = (unsigned char *)&rgb_24;
	int r, g, b;

	r = y + (1.370705 * (v - 128));
	g = y - (0.698001 * (v - 128)) - (0.337633 * (u - 128));
	b = y + (1.732446 * (u - 128));

	if(r > 255) r = 255;
	if(g > 255) g = 255;
	if(b > 255) b = 255;

    if(r < 0) r = 0;
    if(g < 0) g = 0;
    if(b < 0) b = 0;

	pixel[0] = r;
	pixel[1] = g;
	pixel[2] = b;

	return rgb_24;
}

/*
 * YUV422 to RGB24
 */
int yuv2rgb(unsigned char *yuv, unsigned char *rgb, unsigned int width, unsigned height)
{
	unsigned int in = 0, out = 0;
	unsigned int pixel_16;
	unsigned char pixel_24[3];
	unsigned int rgb_24;
	unsigned int y0, u, y1, v;

	for(in = 0; in < width * height * 2; in +=4) {
		pixel_16 = yuv[in + 3] << 24 |
				   yuv[in + 2] << 16 |
				   yuv[in + 1] << 8  |
				   yuv[in + 0];
#if 1
        /* Output data mode:Y U Y V */
		y0 = (pixel_16 & 0x000000ff);
		u  = (pixel_16 & 0x0000ff00) >> 8;
		y1 = (pixel_16 & 0x00ff0000) >> 16;
		v  = (pixel_16 & 0xff000000) >> 24;
#elif 0
        /* Output data mode:Y V Y U */
		y0 = (pixel_16 & 0x000000ff);
		v  = (pixel_16 & 0x0000ff00) >> 8;
		y1 = (pixel_16 & 0x00ff0000) >> 16;
		u  = (pixel_16 & 0xff000000) >> 24;
#else
        /* Output data mode:U Y V Y */
		u  = (pixel_16 & 0x000000ff);
		y0 = (pixel_16 & 0x0000ff00) >> 8;
		v  = (pixel_16 & 0x00ff0000) >> 16;
		y1 = (pixel_16 & 0xff000000) >> 24;
#endif

		rgb_24 = yuv2rgb_pixel(y0, u, v);

		pixel_24[0] = (rgb_24 & 0x000000ff);
		pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
		pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;

		rgb[out++] = pixel_24[0];
		rgb[out++] = pixel_24[1];
		rgb[out++] = pixel_24[2];

		rgb_24 = yuv2rgb_pixel(y1, u, v);

		pixel_24[0] = (rgb_24 & 0x000000ff);
		pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
		pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;

		rgb[out++] = pixel_24[0];
		rgb[out++] = pixel_24[1];
		rgb[out++] = pixel_24[2];
	}

	return 0;
}

int rgb2bmp(char *filename, unsigned int width, unsigned int height,\
        int iBitCount, unsigned char *rgbbuf)
{
    unsigned char *dstbuf;
    unsigned int i, j;
	unsigned long linesize, rgbsize;

    printf("sizeof(BITMAPFILEHEADER) = 0x%02x\n", (unsigned int)sizeof(BITMAPFILEHEADER));
    printf("sizeof(BITMAPINFOHEADER) = 0x%02x\n", (unsigned int)sizeof(BITMAPINFOHEADER));

	if(iBitCount == 24) {
		FILE *fp;
		long ret;
		BITMAPFILEHEADER bmpHeader;
		BITMAPINFO bmpInfo;

		if((fp = fopen(filename, "wb")) == NULL) {
			printf("Can not create BMP file: %s\n", filename);
			return -1;
		}

		rgbsize = width * height * 3;

		bmpHeader.bfType = (WORD)(('M' << 8) | 'B');
		bmpHeader.bfSize = rgbsize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
		bmpHeader.bfReserved1 = 0;
		bmpHeader.bfReserved2 = 0;
		bmpHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

		bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		bmpInfo.bmiHeader.biWidth = width;
		bmpInfo.bmiHeader.biHeight = height;
		bmpInfo.bmiHeader.biPlanes = 1;
		bmpInfo.bmiHeader.biBitCount = iBitCount;
		bmpInfo.bmiHeader.biCompression = 0;
        bmpInfo.bmiHeader.biSizeImage = rgbsize;
		bmpInfo.bmiHeader.biXPelsPerMeter = 0;
		bmpInfo.bmiHeader.biYPelsPerMeter = 0;
		bmpInfo.bmiHeader.biClrUsed = 0;
		bmpInfo.bmiHeader.biClrImportant = 0;

		if((ret = fwrite(&bmpHeader, 1, sizeof(BITMAPFILEHEADER), fp))
				!= sizeof(BITMAPFILEHEADER))
			printf("write BMP file header failed: ret=%ld\n", ret);

		if((ret = fwrite(&(bmpInfo.bmiHeader), 1, sizeof(BITMAPINFOHEADER), fp))
				!= sizeof(BITMAPINFOHEADER))
			printf("write BMP file info failed: ret=%ld\n", ret);

        /* convert rgbbuf */
        dstbuf = (unsigned char *)malloc(rgbsize);
        if(!dstbuf) {
            printf("malloc dstbuf failed !!\n");
            return -1;
        }

        linesize = width * 3; //line size
        for(i = 0, j = height -1; i < height - 1; i++, j--)
            memcpy((dstbuf + (linesize * j)), (rgbbuf + (linesize * i)), linesize);

		if((ret = fwrite(dstbuf, 1, rgbsize, fp)) != rgbsize)
			printf("write BMP file date failed: ret=%ld\n", ret);

        free(dstbuf);
		fclose(fp);
		return 0;
	} else {
        printf("%s: error iBitCount != 24\n", __FUNCTION__);
        return -1;
    }
}
<file_sep>/work/camera/ov7740/ov7740.c
/*
 * V4L2 Driver for camera sensor ov7740
 *
 * Copyright (C) 2012, Ingenic Semiconductor Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * fix by <EMAIL>
 *
 */
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/videodev2.h>
#include <media/v4l2-chip-ident.h>
#include <media/v4l2-subdev.h>
#include <media/soc_camera.h>
#include <media/soc_mediabus.h>
#include <mach/jz_camera.h>

#define REG_CHIP_ID_HIGH		0x0a
#define REG_CHIP_ID_LOW			0x0b
//#define REG_CHIP_REVISION		0x302a
#define CHIP_ID_HIGH			0x77
#define CHIP_ID_LOW			0x42 //0x40

//#define  ov7740_DEFAULT_WIDTH    320
//#define  ov7740_DEFAULT_HEIGHT   240


/* Private v4l2 controls */
#define V4L2_CID_PRIVATE_BALANCE  (V4L2_CID_PRIVATE_BASE + 0)
#define V4L2_CID_PRIVATE_EFFECT  (V4L2_CID_PRIVATE_BASE + 1)

/* In flip, the OV7740 does not need additional settings because the ISP block
 * will auto-detect whether the pixel is in the red line or blue line and make
 * the necessary adjustments.
 */
//#define REG_TC_VFLIP			0x3820
//#define REG_TC_MIRROR			0x3821
//#define OV7740_HFLIP			0x1
//#define OV7740_VFLIP			0x2
//#define OV7740_FLIP_VAL			((unsigned char)0x06)
//#define OV7740_FLIP_MASK		((unsigned char)0x06)

#define REG0C 0x0C /* Register 0C */
#define REG0C_HFLIP_IMG 0x40 /* Horizontal mirror image ON/OFF */
#define REG0C_VFLIP_IMG 0x80 /* Vertical flip image ON/OFF */

 /* whether sensor support high resolution (> vga) preview or not */
#define SUPPORT_HIGH_RESOLUTION_PRE		1

/*
 * Struct
 */
struct regval_list {
	u8 reg_num;
	u8 value;
};

struct mode_list {
	u8 index;
	const struct regval_list *mode_regs;
};

/* Supported resolutions */
enum ov7740_width {
	W_VGA	= 640,
};

enum ov7740_height {
	H_VGA	= 480,
};

struct ov7740_win_size {
	char *name;
	enum ov7740_width width;
	enum ov7740_height height;
	const struct regval_list *regs;
};


struct ov7740_priv {
	struct v4l2_subdev		subdev;
	struct ov7740_camera_info	*info;
	enum v4l2_mbus_pixelcode	cfmt_code;
	struct ov7740_win_size	*win;
	int				model;
	u8				balance_value;
	u8				effect_value;
	u16				flag_vflip:1;
	u16				flag_hflip:1;
};

int cam_t_j = 0, cam_t_i = 0;
unsigned long long cam_t0_buf[10];
unsigned long long cam_t1_buf[10];
static int ov7740_s_power(struct v4l2_subdev *sd, int on);

static inline int ov7740_write_reg(struct i2c_client * client, unsigned char addr, unsigned char value)
{
	return i2c_smbus_write_byte_data(client, addr, value);
}
static inline char ov7740_read_reg(struct i2c_client *client, unsigned char addr)
{
	char ret;
	ret = i2c_smbus_read_byte_data(client, addr);
	if (ret < 0)
		return ret;

	return ret;
}

/*
 * Registers settings
 */

#define ENDMARKER { 0xff, 0xff }

static const struct regval_list ov7740_init_regs[] = {
	//{0x12, 0x80},   //default
	//{0x0a, 0x00},	// read id high
	//{0x0b, 0x00},	// read id low
	{0x13, 0x00},
	{0x11, 0x01},
	{0x12, 0x00},	// i/o control
	//{0x28, 0x02},
	{0x0c, 0x12},
	{0x0d, 0x34},
	{0x17, 0x25},
	{0x18, 0xa0},
	{0x19, 0x03},
	{0x1a, 0xf0},	//
	{0x1b, 0x89},
	{0x22, 0x03},
	{0x33, 0xc4},
	{0x35, 0x05},
	{0x36, 0x3f},	//
	{0xcc, 0x40},
	{0x00, 0x00},
	{0x10, 0xff},
	{0x0f, 0x00},
	{0x13, 0x02},
	ENDMARKER,
};

static const struct regval_list ov7740_vga_regs[] = {
/* Initial registers is for vga format, no setting needed */
    ENDMARKER,
};

static const struct regval_list ov7740_wb_auto_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_wb_incandescence_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_wb_daylight_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_wb_fluorescent_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_wb_cloud_regs[] = {
	ENDMARKER,
};

static const struct mode_list ov7740_balance[] = {
	{0, ov7740_wb_auto_regs}, {1, ov7740_wb_incandescence_regs},
	{2, ov7740_wb_daylight_regs}, {3, ov7740_wb_fluorescent_regs},
	{4, ov7740_wb_cloud_regs},
};


static const struct regval_list ov7740_effect_normal_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_effect_grayscale_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_effect_sepia_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_effect_colorinv_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_effect_sepiabluel_regs[] = {
	ENDMARKER,
};

static const struct mode_list ov7740_effect[] = {
	{0, ov7740_effect_normal_regs}, {1, ov7740_effect_grayscale_regs},
	{2, ov7740_effect_sepia_regs}, {3, ov7740_effect_colorinv_regs},
	{4, ov7740_effect_sepiabluel_regs},
};

#define OV7740_SIZE(n, w, h, r) \
	{.name = n, .width = w , .height = h, .regs = r }

static struct ov7740_win_size ov7740_supported_win_sizes[] = {
	OV7740_SIZE("VGA", W_VGA, H_VGA, ov7740_vga_regs),
};

#define N_WIN_SIZES (ARRAY_SIZE(ov7740_supported_win_sizes))

static const struct regval_list ov7740_yuv422_regs[] = {
	ENDMARKER,
};

static const struct regval_list ov7740_rgb565_regs[] = {
	ENDMARKER,
};

static enum v4l2_mbus_pixelcode ov7740_codes[] = {
	V4L2_MBUS_FMT_YUYV8_2X8,
	//V4L2_MBUS_FMT_YUYV8_1_5X8,
	//V4L2_MBUS_FMT_JZYUYV8_1_5X8,
};

/*
 * Supported balance menus
 */
static const struct v4l2_querymenu ov7740_balance_menus[] = {
	{
		.id		= V4L2_CID_PRIVATE_BALANCE,
		.index		= 0,
		.name		= "auto",
	}, {
		.id		= V4L2_CID_PRIVATE_BALANCE,
		.index		= 1,
		.name		= "incandescent",
	}, {
		.id		= V4L2_CID_PRIVATE_BALANCE,
		.index		= 2,
		.name		= "fluorescent",
	},  {
		.id		= V4L2_CID_PRIVATE_BALANCE,
		.index		= 3,
		.name		= "daylight",
	},  {
		.id		= V4L2_CID_PRIVATE_BALANCE,
		.index		= 4,
		.name		= "cloudy-daylight",
	},

};

/*
 * Supported effect menus
 */
static const struct v4l2_querymenu ov7740_effect_menus[] = {
	{
		.id		= V4L2_CID_PRIVATE_EFFECT,
		.index		= 0,
		.name		= "none",
	}, {
		.id		= V4L2_CID_PRIVATE_EFFECT,
		.index		= 1,
		.name		= "mono",
	}, {
		.id		= V4L2_CID_PRIVATE_EFFECT,
		.index		= 2,
		.name		= "sepia",
	},  {
		.id		= V4L2_CID_PRIVATE_EFFECT,
		.index		= 3,
		.name		= "negative",
	}, {
		.id		= V4L2_CID_PRIVATE_EFFECT,
		.index		= 4,
		.name		= "aqua",
	},
};

/*
 * General functions
 */
static struct ov7740_priv *to_ov7740(const struct i2c_client *client)
{
	return container_of(i2c_get_clientdata(client), struct ov7740_priv,
			    subdev);
}

static int ov7740_write_array(struct i2c_client *client, const struct regval_list *vals)
{
    int ret;
    while ((vals->reg_num != 0xff) || (vals->value != 0xff)) {
        ret = i2c_smbus_write_byte_data(client, vals->reg_num, vals->value);
        dev_vdbg(&client->dev, "array: 0x%02x, 0x%02x", vals->reg_num, vals->value);
        if (ret < 0) {
            dev_err(&client->dev, "array: 0x%02x, 0x%02x write failed",
            vals->reg_num, vals->value);
            return ret;
        }
        vals++;
    }
    return 0;
}

static int ov7740_mask_set(struct i2c_client *client,
			   u8  reg, u8  mask, u8  set)
{
	s32 val = ov7740_read_reg(client, reg);
	if (val < 0)
		return val;

	val &= ~mask;
	val |= set & mask;

	dev_vdbg(&client->dev, "masks: 0x%02x, 0x%02x", reg, val);

	return ov7740_write_reg(client, reg, val);
}

static int ov7740_reset(struct i2c_client *client)
{
    int ret;
    const struct regval_list reset_seq[] = {
        {0x12 ,0x80},
        ENDMARKER,
    };
    ret = ov7740_write_array(client, reset_seq);
    if (ret)
        goto err;
    msleep(5);
err:
    dev_dbg(&client->dev, "%s: (ret %d)", __func__, ret);
    return ret;
}

/*
 * soc_camera_ops functions
 */
static int ov7740_s_stream(struct v4l2_subdev *sd, int enable)
{
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
#if 0

	if (!enable ) {
		dev_info(&client->dev, "stream down\n");
		//ov7740_write_reg(client, 0x3008, 0x42);
		ov7740_write_reg(client, 0x4202, 0x0f);
		return 0;
	}

	dev_info(&client->dev, "stream on\n");
	//ov7740_write_reg(client, 0x3008, 0x02);
	ov7740_write_reg(client, 0x4202, 0x00);
    #endif
	dev_info(&client->dev, "-----%s----", __func__);
	return 0;
}

static int ov7740_g_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
	struct ov7740_priv *priv = to_ov7740(client);
	dev_info(&client->dev, "-----%s----", __func__);

	switch (ctrl->id) {
	case V4L2_CID_VFLIP:
		ctrl->value = priv->flag_vflip;
		break;
	case V4L2_CID_HFLIP:
		ctrl->value = priv->flag_hflip;
		break;
	case V4L2_CID_PRIVATE_BALANCE:
		ctrl->value = priv->balance_value;
		break;
	case V4L2_CID_PRIVATE_EFFECT:
		ctrl->value = priv->effect_value;
		break;
	default:
		break;
	}
	return 0;
}

/* FIXME: Flip function should be update according to specific sensor */
static int ov7740_s_ctrl(struct v4l2_subdev *sd, struct v4l2_control *ctrl)
{
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
	struct ov7740_priv *priv = to_ov7740(client);
	int ret = 0;
	int i = 0;
	u8 value;

	int balance_count = ARRAY_SIZE(ov7740_balance);
	int effect_count = ARRAY_SIZE(ov7740_effect);

	dev_info(&client->dev, "-----%s----", __func__);

	switch (ctrl->id) {
	case V4L2_CID_PRIVATE_BALANCE:
		if(ctrl->value > balance_count)
			return -EINVAL;

		for(i = 0; i < balance_count; i++) {
			if(ctrl->value == ov7740_balance[i].index) {
				ret = ov7740_write_array(client,
						ov7740_balance[ctrl->value].mode_regs);
				priv->balance_value = ctrl->value;
				break;
			}
		}
		break;

	case V4L2_CID_PRIVATE_EFFECT:
		if(ctrl->value > effect_count)
			return -EINVAL;

		for(i = 0; i < effect_count; i++) {
			if(ctrl->value == ov7740_effect[i].index) {
				ret = ov7740_write_array(client,
						ov7740_effect[ctrl->value].mode_regs);
				priv->effect_value = ctrl->value;
				break;
			}
		}
		break;     
        
    case V4L2_CID_VFLIP:
        value = ctrl->value ? REG0C_VFLIP_IMG : 0x00;
        return ov7740_mask_set(client, REG0C, REG0C_VFLIP_IMG, value);
    case V4L2_CID_HFLIP:
        value = ctrl->value ? REG0C_HFLIP_IMG : 0x00;
        return ov7740_mask_set(client, REG0C, REG0C_HFLIP_IMG, value);

	default:
		dev_err(&client->dev, "no V4L2 CID: 0x%x ", ctrl->id);
		return -EINVAL;
	}

	return ret;
}

static int ov7740_g_chip_ident(struct v4l2_subdev *sd,
			       struct v4l2_dbg_chip_ident *id)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	id->ident    = SUPPORT_HIGH_RESOLUTION_PRE;
	id->revision = 0;

	return 0;
}


static int ov7740_querymenu(struct v4l2_subdev *sd,
					struct v4l2_querymenu *qm)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	switch (qm->id) {
	case V4L2_CID_PRIVATE_BALANCE:
		memcpy(qm->name, ov7740_balance_menus[qm->index].name,
				sizeof(qm->name));
		break;

	case V4L2_CID_PRIVATE_EFFECT:
		memcpy(qm->name, ov7740_effect_menus[qm->index].name,
				sizeof(qm->name));
		break;
	}

	return 0;
}

#ifdef CONFIG_VIDEO_ADV_DEBUG
static int ov7740_g_register(struct v4l2_subdev *sd,
			     struct v4l2_dbg_register *reg)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	int ret;

	reg->size = 1;
	if (reg->reg > 0xff)
		return -EINVAL;

	ret = ov7740_read_reg(client, reg->reg);
	if (ret < 0)
		return ret;

	reg->val = ret;

	return 0;
}

static int ov7740_s_register(struct v4l2_subdev *sd,
			     struct v4l2_dbg_register *reg)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);

	if (reg->reg > 0xff ||
	    reg->val > 0xff)
		return -EINVAL;

	return ov7740_write_reg(client, reg->reg, reg->val);
}
#endif

/* Select the nearest higher resolution for capture */
static struct ov7740_win_size *ov7740_select_win(u32 *width, u32 *height)
{
	int i, default_size = ARRAY_SIZE(ov7740_supported_win_sizes) - 1;

	for (i = 0; i < ARRAY_SIZE(ov7740_supported_win_sizes); i++) {
		if ((*width >= ov7740_supported_win_sizes[i].width) &&
		    (*height >= ov7740_supported_win_sizes[i].height)) {
			*width = ov7740_supported_win_sizes[i].width;
			*height = ov7740_supported_win_sizes[i].height;
			return &ov7740_supported_win_sizes[i];
		}
	}

	*width = ov7740_supported_win_sizes[default_size].width;
	*height = ov7740_supported_win_sizes[default_size].height;


	return &ov7740_supported_win_sizes[default_size];
}

static int ov7740_init(struct v4l2_subdev *sd, u32 val)
{
	int ret;
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
	struct ov7740_priv *priv = to_ov7740(client);

	int bala_index = priv->balance_value;
	int effe_index = priv->effect_value;

    ov7740_reset(client);

	/* initialize the sensor with default data */
	ret = ov7740_write_array(client, ov7740_init_regs);
	ret = ov7740_write_array(client, ov7740_balance[bala_index].mode_regs);
	ret = ov7740_write_array(client, ov7740_effect[effe_index].mode_regs);
	if (ret < 0)
		goto err;

	dev_info(&client->dev, "%s: Init default", __func__);
	return 0;

err:
	dev_err(&client->dev, "%s: Error %d", __func__, ret);
	return ret;
}

static int ov7740_g_fmt(struct v4l2_subdev *sd,
			struct v4l2_mbus_framefmt *mf)
{
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
	struct ov7740_priv *priv = to_ov7740(client);
	dev_info(&client->dev, "-----%s----", __func__);

	mf->width = priv->win->width;
	mf->height = priv->win->height;
	mf->code = priv->cfmt_code;

	mf->colorspace = V4L2_COLORSPACE_JPEG;
	mf->field	= V4L2_FIELD_NONE;

	return 0;
}

static int ov7740_s_fmt(struct v4l2_subdev *sd,
			struct v4l2_mbus_framefmt *mf)
{
	/* current do not support set format, use unify format yuv422i */
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
	struct ov7740_priv *priv = to_ov7740(client);
	int ret;
	dev_info(&client->dev, "-----%s----", __func__);

	ov7740_init(sd, 1);

	priv->win = ov7740_select_win(&mf->width, &mf->height);
	/* set size win */
	ret = ov7740_write_array(client, priv->win->regs);
	if (ret < 0) {
		dev_err(&client->dev, "%s: Error\n", __func__);
		return ret;
	}
	return 0;
}

static int ov7740_try_fmt(struct v4l2_subdev *sd,
			  struct v4l2_mbus_framefmt *mf)
{
	const struct ov7740_win_size *win;
	struct i2c_client  *client = v4l2_get_subdevdata(sd);
	/*
	 * select suitable win
	 */
        dev_info(&client->dev, "-----%s----", __func__);
	win = ov7740_select_win(&mf->width, &mf->height);

	if(mf->field == V4L2_FIELD_ANY) {
		mf->field = V4L2_FIELD_NONE;
	} else if (mf->field != V4L2_FIELD_NONE) {
		dev_err(&client->dev, "Field type invalid.\n");
		return -ENODEV;
	}

	switch (mf->code) {
	case V4L2_MBUS_FMT_YUYV8_2X8:
	//case V4L2_MBUS_FMT_YUYV8_1_5X8:
	//case V4L2_MBUS_FMT_JZYUYV8_1_5X8:
		mf->colorspace = V4L2_COLORSPACE_JPEG;
		break;

	default:
		mf->code = V4L2_MBUS_FMT_YUYV8_2X8;
		mf->colorspace = V4L2_COLORSPACE_JPEG;
		break;
	}

	return 0;
}


static int ov7740_enum_fmt(struct v4l2_subdev *sd, unsigned int index,
			   enum v4l2_mbus_pixelcode *code)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	if (index >= ARRAY_SIZE(ov7740_codes))
		return -EINVAL;

	*code = ov7740_codes[index];
	return 0;
}

static int ov7740_g_crop(struct v4l2_subdev *sd, struct v4l2_crop *a)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	return 0;
}

static int ov7740_cropcap(struct v4l2_subdev *sd, struct v4l2_cropcap *a)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	return 0;
}


/*
 * Frame intervals.  Since frame rates are controlled with the clock
 * divider, we can only do 30/n for integer n values.  So no continuous
 * or stepwise options.  Here we just pick a handful of logical values.
 */

static int ov7740_frame_rates[] = { 30, 15, 10, 5, 1 };

static int ov7740_enum_frameintervals(struct v4l2_subdev *sd,
		struct v4l2_frmivalenum *interval)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	if (interval->index >= ARRAY_SIZE(ov7740_frame_rates))
		return -EINVAL;
	interval->type = V4L2_FRMIVAL_TYPE_DISCRETE;
	interval->discrete.numerator = 1;
	interval->discrete.denominator = ov7740_frame_rates[interval->index];
	return 0;
}


/*
 * Frame size enumeration
 */
static int ov7740_enum_framesizes(struct v4l2_subdev *sd,
		struct v4l2_frmsizeenum *fsize)
{
	int i;
	int num_valid = -1;
	__u32 index = fsize->index;
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	dev_info(&client->dev, "-----%s----", __func__);
	for (i = 0; i < N_WIN_SIZES; i++) {
		struct ov7740_win_size *win = &ov7740_supported_win_sizes[index];
		if (index == ++num_valid) {
			fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
			fsize->discrete.width = win->width;
			fsize->discrete.height = win->height;
			return 0;
		}
	}

	return -EINVAL;
}

static int ov7740_video_probe(struct i2c_client *client)
{
	unsigned char retval = 0, retval_high = 0, retval_low = 0;
	struct v4l2_subdev *subdev = i2c_get_clientdata(client);
	int ret = 0;

	struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
	dev_info(&client->dev, "-----%s----", __func__);

	ret = soc_camera_power_on(&client->dev, ssdd);
	if (ret < 0)
		return ret;

	/*
	 * check and show product ID and manufacturer ID
	 */
	 #if 0
	retval = ov7740_write_reg(client, 0x3008, 0x80);
	if(retval) {
		dev_err(&client->dev, "i2c write failed!\n");
		return -1;
	}
    #endif

	retval_high = ov7740_read_reg(client, REG_CHIP_ID_HIGH);
	if (retval_high != CHIP_ID_HIGH) {
		dev_err(&client->dev, "read sensor %s chip_id high %x is error\n",
				client->name, retval_high);
		return -1;
	}

	retval_low = ov7740_read_reg(client, REG_CHIP_ID_LOW);
	if (retval_low != CHIP_ID_LOW) {
		dev_err(&client->dev, "read sensor %s chip_id low %x is error\n",
				client->name, retval_low);
		return -1;
	}

	dev_info(&client->dev, "read sensor %s id high:0x%x,low:%x successed!\n",
			client->name, retval_high, retval_low);

	ret = soc_camera_power_off(&client->dev, ssdd);

	return 0;
}

static int ov7740_s_power(struct v4l2_subdev *sd, int on)
{
	struct i2c_client *client = v4l2_get_subdevdata(sd);
	struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
	struct ov7740_priv *priv = to_ov7740(client);
	int ret;

	int bala_index = priv->balance_value;
	int effe_index = priv->effect_value;
	dev_info(&client->dev, "-----%s----", __func__);


	if (!on)
		return soc_camera_power_off(&client->dev, ssdd);

	ret = soc_camera_power_on(&client->dev, ssdd);

   #if 1 
   return ret;
   #else
	if (ret < 0)
		return ret;


    ov7740_reset(client);

	///* initialize the sensor with default data */
	ret = ov7740_write_array(client, ov7740_init_regs);
	ret = ov7740_write_array(client, ov7740_balance[bala_index].mode_regs);
	ret = ov7740_write_array(client, ov7740_effect[effe_index].mode_regs);
	if (ret < 0)
		goto err;


	dev_info(&client->dev, "%s: Init default", __func__);
	return 0;

err:
	dev_err(&client->dev, "%s: Error %d", __func__, ret);
    
    ov7740_reset(client);
	return ret;
#endif

}

#if 0
static int ov7740_g_mbus_config(struct v4l2_subdev *sd,struct v4l2_mbus_config *cfg)
{
    struct i2c_client *client = v4l2_get_subdevdata(sd);
    struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
    cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
    V4L2_MBUS_VSYNC_ACTIVE_HIGH | V4L2_MBUS_HSYNC_ACTIVE_HIGH |
    V4L2_MBUS_VSYNC_ACTIVE_LOW |
    V4L2_MBUS_DATA_ACTIVE_HIGH;
    cfg->type = V4L2_MBUS_PARALLEL;
    cfg->flags = soc_camera_apply_board_flags(ssdd, cfg);
    return 0;
}
#else
static int ov7740_g_mbus_config(struct v4l2_subdev *sd,
		struct v4l2_mbus_config *cfg)
{

	struct i2c_client *client = v4l2_get_subdevdata(sd);
	struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
	dev_info(&client->dev, "-----%s----", __func__);

	cfg->flags = V4L2_MBUS_PCLK_SAMPLE_RISING | V4L2_MBUS_MASTER |
		    V4L2_MBUS_VSYNC_ACTIVE_HIGH| V4L2_MBUS_HSYNC_ACTIVE_HIGH |
			    V4L2_MBUS_DATA_ACTIVE_HIGH;
	cfg->type = V4L2_MBUS_PARALLEL;

	cfg->flags = soc_camera_apply_board_flags(ssdd, cfg);

	return 0;
}
#endif

static struct v4l2_subdev_core_ops ov7740_subdev_core_ops = {
	.s_power    = ov7740_s_power,
	.g_ctrl		= ov7740_g_ctrl,
	.s_ctrl		= ov7740_s_ctrl,
	.g_chip_ident	= ov7740_g_chip_ident,
	.querymenu  = ov7740_querymenu,
#ifdef CONFIG_VIDEO_ADV_DEBUG
	.g_register	= ov7740_g_register,
	.s_register	= ov7740_s_register,
#endif
};

static struct v4l2_subdev_video_ops ov7740_subdev_video_ops = {
	.s_stream	= ov7740_s_stream,
	.g_mbus_fmt	= ov7740_g_fmt,
	.s_mbus_fmt	= ov7740_s_fmt,
	.try_mbus_fmt	= ov7740_try_fmt,
	.cropcap	= ov7740_cropcap,
	.g_crop		= ov7740_g_crop,
	.enum_mbus_fmt	= ov7740_enum_fmt,
//	.enum_framesizes = ov7740_enum_framesizes,
//	.enum_frameintervals = ov7740_enum_frameintervals,
	.g_mbus_config  = ov7740_g_mbus_config,
};

static struct v4l2_subdev_ops ov7740_subdev_ops = {
	.core	= &ov7740_subdev_core_ops,
	.video	= &ov7740_subdev_video_ops,
};

/*
 * i2c_driver functions
 */

static int ov7740_probe(struct i2c_client *client,
			const struct i2c_device_id *did)
{
	struct ov7740_priv *priv;
	struct soc_camera_subdev_desc *ssdd = soc_camera_i2c_to_desc(client);
	struct i2c_adapter *adapter = to_i2c_adapter(client->dev.parent);
	int ret = 0,default_wight = 640,default_height = 480;

	if (!ssdd) {
		dev_err(&client->dev, "ov7740: missing platform data!\n");
		return -EINVAL;
	}


	if(!i2c_check_functionality(adapter, I2C_FUNC_SMBUS_BYTE
			| I2C_FUNC_SMBUS_BYTE_DATA)) {
		dev_err(&client->dev, "client not i2c capable\n");
		return -ENODEV;
	}

	priv = kzalloc(sizeof(struct ov7740_priv), GFP_KERNEL);
	if (!priv) {
		dev_err(&adapter->dev,
			"Failed to allocate memory for private data!\n");
		return -ENOMEM;
	}


	v4l2_i2c_subdev_init(&priv->subdev, client, &ov7740_subdev_ops);

	priv->win = ov7740_select_win(&default_wight, &default_height);

	priv->cfmt_code  =  V4L2_MBUS_FMT_YUYV8_2X8;


	ret = ov7740_video_probe(client);
	if (ret) {
		kfree(priv);
	}
	return ret;
}

static int ov7740_remove(struct i2c_client *client)
{
	struct ov7740_priv       *priv = to_ov7740(client);

	kfree(priv);
	return 0;
}

static const struct i2c_device_id ov7740_id[] = {
	{ "ov7740",  0 },
	{ }
};


MODULE_DEVICE_TABLE(i2c, ov7740_id);

static struct i2c_driver ov7740_i2c_driver = {
	.driver = {
		.name = "ov7740",
	},
	.probe    = ov7740_probe,
	.remove   = ov7740_remove,
	.id_table = ov7740_id,
};

/*
 * Module functions
 */
static int __init ov7740_module_init(void)
{
	return i2c_add_driver(&ov7740_i2c_driver);
}

static void __exit ov7740_module_exit(void)
{
	i2c_del_driver(&ov7740_i2c_driver);
}

module_init(ov7740_module_init);
module_exit(ov7740_module_exit);

MODULE_DESCRIPTION("camera sensor ov7740 driver");
MODULE_AUTHOR("<NAME>");
MODULE_LICENSE("GPL");
<file_sep>/work/test/cim_test-zmm220/cimsh
#!/bin/sh
make clean
make
cp -f cimtest /mnt/hgfs/wlshare/linuxdevelop/tmp 
<file_sep>/network/6th_day/pcap_test.c
/* ************************************************************************
 *       Filename:  pcap_test.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月09日 16时13分09秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <pcap.h>

#if 0
void my_callback(u_char *user, const struct pcap_pkthdr *hdr, const u_char *msg)
{
	printf("user=%s\n", user);

	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
			msg[6],msg[7],msg[8],msg[9],msg[10],msg[11]);

	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
			msg[0],msg[1],msg[2],msg[3],msg[4],msg[5]);
}

int main(int argc, char *argv[])
{
	char err_buf[100] = "";
	//1.打开网络句柄
	pcap_t *p_fd = pcap_open_live("eth0",2048,0,0,err_buf);

	//2.过滤网络数据
	//2.1编译过滤规则
	//struct bpf_program bpf_p;
	//pcap_compile(p_fd,&bpf_p,"udp port 8000", 0, 0xffffff00);

	//2.2设置过滤规则
	//pcap_setfilter(p_fd, &bpf_p);

	struct pcap_pkthdr p_hdr;
	const u_char *msg = NULL;

	pcap_loop(p_fd, -1, my_callback, (u_char *)"haha");

	pcap_close(p_fd);

	return 0;
}
#elif 0
void my_callback(u_char *msg, const struct pcap_pkthdr *hdr, const u_char *user)
{
	printf("user=%s\n", user);

	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
			msg[6],msg[7],msg[8],msg[9],msg[10],msg[11]);

	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
			msg[0],msg[1],msg[2],msg[3],msg[4],msg[5]);
}

int main(int argc, char *argv[])
{
	char err_buf[100] = "";
	//打开网络句柄
	pcap_t *p_fd = pcap_open_live("eth0",2048,0,0,err_buf);

	struct pcap_pkthdr p_hdr;
	const u_char *msg = NULL;

	pcap_loop(p_fd, -1, my_callback, (u_char *)"haha");

	pcap_close(p_fd);

	return 0;
}
#elif 1

int main(int argc, char *argv[])
{
	char err_buf[100] = "";

	pcap_t *p_fd = pcap_open_live("eth0",2048,0,0,err_buf);

	struct pcap_pkthdr p_hdr;
	const u_char *msg = NULL;
	msg = pcap_next(p_fd, &p_hdr);

	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
			msg[6],msg[7],msg[8],msg[9],msg[10],msg[11]);

	printf("%02x:%02x:%02x:%02x:%02x:%02x\n",\
			msg[0],msg[1],msg[2],msg[3],msg[4],msg[5]);

	pcap_close(p_fd);
	return 0;
}
#elif 0
int main(int argc, char *argv[])
{
	char err_buf[100] = "";
	char *dev = NULL;

	dev = pcap_lookupdev(err_buf);

	printf("dev=%s\n",dev);

	return 0;
}
#endif
<file_sep>/work/camera/bf3703/BF3703_MTK6225_Drv_V3.0/image_sensor.h
/****************************BF3403_BYD_VGA_Sensor***************************
*  Copyright Statement:
*  --------------------
*  This software is protected by Copyright and the information contained
*  herein is confidential. The software may not be copied and the information
*  contained herein may not be used or disclosed except with the written
*  permission of MediaTek Inc. (C) 2005
*
*  BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
*  THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
*  RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER ON
*  AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
*  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
*  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
*  NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
*  SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
*  SUPPLIED WITH THE MEDIATEK SOFTWARE, AND BUYER AGREES TO LOOK ONLY TO SUCH
*  THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
*  NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
*  SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
*  BUYER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND CUMULATIVE
*  LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
*  AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
*  OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY BUYER TO
*  MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. 
*
*  THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
*  WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
*  LAWS PRINCIPLES.  ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
*  RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
*  THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/

/*****************************************************************************
 *
 * Filename:
 * ---------
 *   image_sensor.h
 *
 * Version:
 * --------
 *   BF3703 MTK 6225 or 6226 DRV V1.0.0
 *
 * Release Date:
 * ------------
 *   2010-07-08
 *
 * Description:
 * ------------
 *   CMOS sensor header file
 *
 * Author:
 * -------
 * -------
 *
 *============================================================================
 *             HISTORY
 * Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *------------------------------------------------------------------------------
 *
 *------------------------------------------------------------------------------
 * Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
 *============================================================================
 ****************************************************************************/
#ifndef _IMAGE_SENSOR_H
#define _IMAGE_SENSOR_H

	#include "isp_if.h"
	
	//------------------------Engineer mode---------------------------------
	
	#define FACTORY_START_ADDR 70
	
	typedef enum group_enum {
	   AWB_GAIN=0,
	   PRE_GAIN,
	   SENSOR_DBLC,
	   GAMMA_ENABLE,
	   CMMCLK_CURRENT,
	   FRAME_RATE_LIMITATION,
	   REGISTER_EDITOR,
	   GROUP_TOTAL_NUMS
	} FACTORY_CCT_GROUP_ENUM;
	
	typedef enum register_index {
	   AWB_GAIN_R_INDEX=FACTORY_START_ADDR,
	   AWB_GAIN_B_INDEX,
	   SENSOR_DBLC_INDEX,
	   GAMMA_ENABLE_INDEX,
	   CMMCLK_CURRENT_INDEX,	   
	   FACTORY_END_ADDR
	} FACTORY_REGISTER_INDEX;
	
	typedef enum cct_register_index {
	   GLOBAL_GAIN_INDEX=0,
	   PRE_GAIN_R_INDEX,
	   PRE_GAIN_B_INDEX,
	   CCT_END_ADDR
	} CCT_REGISTER_INDEX;
	
	typedef struct
	{
	   kal_uint8   item_name_ptr[50];         // item name
	   kal_int32	item_value;                // item value
	   kal_bool    is_true_false;             // is this item for enable/disable functions
	   kal_bool	   is_read_only;              // is this item read only
	   kal_bool	   is_need_restart;           // after set this item need restart
	   kal_int32	min;                       // min value of item value	
	   kal_int32	max;                       // max value of item value	
	} ENG_sensor_info;
	
	// API FOR ENGINEER FACTORY MODE
	void  get_sensor_group_count(kal_int32* sensor_count_ptr);
	void  get_sensor_group_info(kal_uint16 group_idx, kal_int8* group_name_ptr, kal_int32* item_count_ptr);
	void  get_sensor_item_info(kal_uint16 group_idx,kal_uint16 item_idx, ENG_sensor_info* info_ptr);
	kal_bool set_sensor_item_info(kal_uint16 group_idx, kal_uint16 item_idx, kal_int32 item_value);
	
	//------------------------Engineer mode---------------------------------
	
	typedef struct {
		kal_uint32	addr;
		kal_uint32	para;
	} sensor_reg_struct;
	
	typedef struct {
		sensor_reg_struct	reg[FACTORY_END_ADDR];
		sensor_reg_struct	cct[CCT_END_ADDR];
	} sensor_data_struct;
	
	// write camera_para to sensor register 
	void camera_para_to_sensor(void);
	// update camera_para from sensor register 
	void sensor_to_camera_para(void);
	// config sensor callback function 
	void image_sensor_func_config(void);
	// Compact Image Sensor Module Power ON/OFF
	void cis_module_power_on(kal_bool on);
	
	/* HW PRODUCE I2C SIGNAL TO CONTROL SENSOR REGISTER */
	//#define HW_SCCB
	
	/* OUTPUT DEBUG INFO. BY UART */
	//#define OUTPUT_DEBUG_INFO

	typedef enum _SENSOR_TYPE {
		CMOS_SENSOR=0,
		CCD_SENSOR
	} SENSOR_TYPE;

	typedef struct {
		kal_uint16		id;
		SENSOR_TYPE		type;
	} SensorInfo;

	/* MAXIMUM EXPLOSURE LINES USED BY AE */
	extern kal_uint16 MAX_EXPOSURE_LINES;
	extern kal_uint8  MIN_EXPOSURE_LINES;
	/* AE CONTROL CRITERION */
	extern kal_uint8  AE_AWB_CAL_PERIOD;
	extern kal_uint8  AE_GAIN_DELAY_PERIOD;
	extern kal_uint8  AE_SHUTTER_DELAY_PERIOD;

	/* DEFINITION USED BY CCT */
	extern SensorInfo	g_CCT_MainSensor;
	extern kal_uint8	g_CCT_FirstGrabColor;

	/* CAMERA PREVIEW FRAME RATE DEFINITION */
	#define CAM_PREVIEW_15FPS
	//	#define CAM_PREVIEW_22FPS
	//	#define CAM_PREVIEW_30FPS

	#define SYSTEM_CLK                           (48*1000*1000)
	/* PIXEL CLOCK USED BY BANDING FILTER CACULATION*/
#if defined(CAM_PREVIEW_15FPS)
	#define PIXEL_CLK							         (SYSTEM_CLK/8)		// 52/8 MHz
#elif defined(CAM_PREVIEW_22FPS)
   #define PIXEL_CLK							         (SYSTEM_CLK/6)		// 52/6 MHz
#elif defined(CAM_PREVIEW_30FPS)
   #define PIXEL_CLK 						      	(SYSTEM_CLK/4)		// 52/4 MHz
#endif
 
	/* MAX/MIN FRAME RATE (FRAMES PER SEC.) */
	#define MAX_FRAME_RATE								15		// Limitation for MPEG4 Encode Only
	#define MIN_FRAME_RATE								12

	/* LINE NUMBERS IN MAX_FRAME_RATE */
	#define MIN_LINES_PER_FRAME						((SYSTEM_CLK/8/MAX_FRAME_RATE)/VGA_PERIOD_PIXEL_NUMS)

	/* SENSOR GLOBAL GAIN AT NIGHT MODE */
	#define SENSOR_NIGHT_MODE_GAIN					0x08

	/* SENSOR PIXEL/LINE NUMBERS IN ONE PERIOD */
	#define VGA_PERIOD_PIXEL_NUMS					784
	#define VGA_PERIOD_LINE_NUMS					510

	/* SENSOR EXPOSURE LINE LIMITATION */
	#define VGA_EXPOSURE_LIMITATION					510
	
	/* 1M RESOLUTION SIZE */
	#define IMAGE_SENSOR_1M_WIDTH					1280
	#define IMAGE_SENSOR_1M_HEIGHT					960

	/* SENSOR VGA SIZE */
	#define IMAGE_SENSOR_VGA_WIDTH					640
	#define IMAGE_SENSOR_VGA_HEIGHT					480

	/* SETUP TIME NEED TO BE INSERTED */
	#define IMAGE_SENSOR_VGA_INSERTED_PIXELS		     133
	#define IMAGE_SENSOR_VGA_INSERTED_LINES		      16
	 

	/* SENSOR READ/WRITE ID */
	#define BF3703_WRITE_ID							0xdc
	#define BF3703_READ_ID							0xdd
	
	/* SENSOR CHIP VERSION */
	#define BF3703_SENSOR_ID						0x3703

	// BB's reset pin high low control MACROs
    #define RESET_PIN_LOW   (REG_ISP_CMOS_SENSOR_MODE_CONFIG &= ~REG_CMOS_SENSOR_RESET_BIT)
    #define RESET_PIN_HIGH  (REG_ISP_CMOS_SENSOR_MODE_CONFIG |= REG_CMOS_SENSOR_RESET_BIT)

    #define PWRDN_PIN_LOW           (REG_ISP_CMOS_SENSOR_MODE_CONFIG &= ~REG_CMOS_SENSOR_POWER_ON_BIT)
    #define PWRDN_PIN_HIGH          (REG_ISP_CMOS_SENSOR_MODE_CONFIG |= REG_CMOS_SENSOR_POWER_ON_BIT)

	
	
#ifdef MCU_104M
	#define SENSOR_I2C_DELAY							0xFF
#else
	#define SENSOR_I2C_DELAY							0x10
#endif

	#define I2C_START_TRANSMISSION \
	{ \
		volatile kal_uint32 j; \
		SET_SCCB_CLK_OUTPUT; \
		SET_SCCB_DATA_OUTPUT; \
		SET_SCCB_CLK_HIGH; \
		SET_SCCB_DATA_HIGH; \
		for(j=0;j<SENSOR_I2C_DELAY;j++);\
		SET_SCCB_DATA_LOW; \
		for(j=0;j<SENSOR_I2C_DELAY;j++);\
		SET_SCCB_CLK_LOW; \
	}
	
	#define I2C_STOP_TRANSMISSION \
	{ \
		volatile kal_uint32 j; \
		SET_SCCB_CLK_OUTPUT; \
		SET_SCCB_DATA_OUTPUT; \
		SET_SCCB_CLK_LOW; \
		SET_SCCB_DATA_LOW; \
		for(j=0;j<SENSOR_I2C_DELAY;j++);\
		SET_SCCB_CLK_HIGH; \
		for(j=0;j<SENSOR_I2C_DELAY;j++);\
		SET_SCCB_DATA_HIGH; \
	}

#endif /* _IMAGE_SENSOR_H */
<file_sep>/network/route/src/inc/common.h
/******************************************************************************
  文 件 名   : common.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月11日
  最近修改   :
  功能描述   : 通用 的头文件
******************************************************************************/
#ifndef __COMMON_H__
#define __COMMON_H__

/*----------------------------------------------*
 * 标准库头文件                                 *
 *----------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <termios.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <netinet/ether.h>
#include <netinet/udp.h>
#include <netinet/tcp.h>
#include <netinet/ip.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <netpacket/packet.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <semaphore.h>


/*----------------------------------------------*
 * 宏定义                                       *
 *----------------------------------------------*/
#define uint    unsigned int
#define uint16  unsigned short
#define ulint   unsigned long
#define uchar   unsigned char

#define TRUE         (1)
#define FALSE        (0)
#define MS           (1000)
#define MAX_PORT     16
#define RULE_LEN     32

#define PASSWD_LEN    9  // 密码最长 8 位 最后以为用于保存 \0
#define ENCRYPT_KEY   (23)
#define ROOT_PASSWD   "<PASSWORD>"


/*----------------------------------------------*
 * 枚举类型定义                                 *
 *----------------------------------------------*/

#undef TRUE
#undef FALSE
typedef enum _boolean
{
	FALSE = 0,
	TRUE  = 1,
}Boolean;

typedef enum _type
{
	MAC  = 0,
	IP   = 1,
	PORT = 2,
	PRO  = 3,
}TYPE_Rule;

typedef enum _status
{
	DOWN = 0,
	UP   = 1,
}STATUS;

/*----------------------------------------------*
 * 结构体类型定义                               *
 *----------------------------------------------*/

typedef struct _firewall
{
	char rule[RULE_LEN];
	struct _firewall *next;
}FIRE_Wall;

typedef struct _arphdr
{
	uint16 ar_hrd;
	uint16 ar_pro;
	uint16 ar_hln;
	uint16 ar_pln;
	uint16 ar_op;

	uchar src_mac[6];
	uchar src_ip[4];
	uchar dst_mac[6];
	uchar dst_ip[4];
}ARP_Hdr;

typedef struct _msg
{
	uchar dst_mac[6];
	uchar src_mac[6];
	uchar dst_ip[4];
	uchar src_ip[4];

	uint16 frame_type;
	uchar  pro_type;
	uint16 s_port;
	uint16 d_port;

	int len;
	int port;
}MSG_Info;

typedef struct _eth_port
{
	char name[20];   //接口名称

	uchar ip[4];     //ip地址
	uchar mac[6];    //mac地址
	uchar netmask[4];//子网掩码
	uchar bc_ip[4];  //广播地址

	STATUS status;
}ETH_Port;

typedef struct _arp_table
{
	unsigned char ip[4];
	unsigned char mac[6];

	struct _arp_table *next;

}ARP_Table;

typedef struct _route
{
	uchar recv[2048];
	char passwd[PASSWD_LEN];

	int raw_fd;   // 原始套接字
	int sockfd;   // 监听套接字
	int connfd;   // 连接套接字
	int port_num; // 接口总数

	STATUS fire_status;

	pthread_t pth_getmsg;
	pthread_t pth_keyeve;
	pthread_mutex_t mutex;

	struct _arp_table *arp_head;
	struct _firewall *ip_head;
	struct _firewall *mac_head;
	struct _firewall *port_head;
	struct _firewall *pro_head;
	struct _eth_port  eth_port[MAX_PORT];

	struct ether_header *eth_hdr;
	struct _arphdr *arp_hdr;
	struct iphdr *ip_hdr;
	struct tcphdr *tcp_hdr;
	struct udphdr *udp_hdr;

	struct sockaddr_in s_addr;
	struct sockaddr_ll sll;
	struct ifreq ethreq;
}TYPE_Route;

#endif

<file_sep>/network/5th_day/arp.c
/* ************************************************************************
 *       Filename:  arp.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月08日 15时05分02秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{
	int i = 0;
	//创建原始套接字
	int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

	unsigned char send_msg[1024] = {
		//-----组MAC----14----
		0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
		0x00,0x0c,0x29,0xe4,0xd3,0xd6,//src_mac: 00:0c:29:e4:d3:d6
		0x08,0x06,                    //类型: 0x0806 ARP协议

		//-----组ARP----28----
		0x00,0x01,0x08,0x00,          //硬件类型1(以太网地址)，协议类型0x0800(IP)
		0x06,0x04,0x00,0x01,          //硬件、协议的地址长度分别为6和4，ARP请求
		0x00,0x0c,0x29,0xe4,0xd3,0xd6,//发送端的mac
		10, 221, 2, 221,              //发送端的IP
		0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac，设置为0)
		10, 221, 2, 255,               //目的IP
	};

	//数据初始化
	struct sockaddr_ll sll;
	struct ifreq ethreq;
	bzero(&sll, sizeof(sll));

	strncpy(ethreq.ifr_name,"eth0", IFNAMSIZ);    //指定网卡名称
	ioctl(sockfd, SIOCGIFINDEX, (char *)&ethreq); //获取网络接口
	sll.sll_ifindex = ethreq.ifr_ifindex;         //将网络接口赋值给原始套接字地址结构

	for(i=1;i<50;i++)
	{
		send_msg[41] = i;
		sendto(sockfd, send_msg, 42, 0, (struct sockaddr *)&sll, sizeof(sll));

		//接收对方的ARP应答
		unsigned char recv_msg[1024] = "";
		recvfrom(sockfd, recv_msg, sizeof(recv_msg), 0, NULL, NULL);

		if(recv_msg[21] == 2) //ARP应答
		{
			unsigned char resp_mac[18] = "";
			unsigned char resp_ip[16] = "";

			//提取mac地址
			sprintf(resp_mac, "%02x:%02x:%02x:%02x:%02x:%02x", \
					recv_msg[22],recv_msg[23],recv_msg[24],recv_msg[25],recv_msg[26],recv_msg[27]);

			//提取ip
			sprintf(resp_ip,"%d.%d.%d.%d",\
				   recv_msg[28],recv_msg[29],recv_msg[30],recv_msg[31]);

			printf("IP:%s -- %s\n",resp_ip,resp_mac);
		}
	}

	close(sockfd);
	return 0;
}
<file_sep>/work/test/cim_test-zmm220/cim.h
#ifndef __CIM_H__
#define __CIM_H__

/*
typedef unsigned int u32;
typedef unsigned char BYTE;
typedef unsigned char u8;
*/
/* timing parameters */
typedef struct
{
	unsigned long mclk_freq;
	unsigned int pclk_active_direction;//o for rising edge, 1 for falling edge
	unsigned int hsync_active_level;
	unsigned int vsync_active_level;
} TIMING_PARAM;

/* image parameters */
typedef struct
{
        unsigned int width;      /* width */
        unsigned int height;     /* height */
        unsigned int bpp;        /* bits per pixel: 8/16/32 */
} IMG_PARAM;

/* image format */
typedef enum {
	NO_FORMAT = 0,
	YUV422_SEP,
	YUV422_PACK,
	RGB565,
	RGB888,
	RAW
} img_format_t;

int cim_open(int id,int width, int height, int bpp);
void cim_close(int id);
int cim_read(unsigned char id,unsigned char *buf, int frame_size);
int set_timing_param(int id,TIMING_PARAM *timing);
void  *cim_mmap(int id, unsigned int size);

#endif /* __CIM_H__ */

<file_sep>/c/lrc/process_lrc.c
/* ************************************************************************
 *       Filename:  process_lrc.c
 *    Description:
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 09時17分27秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (),
 *        Company:
 * ************************************************************************/
#include "common.h"
#include "console.h"
#include "link.h"
#include "file.h"

int src_segment(char *lrc_src, char *plines[], char *str)
{
	int i = 0;

	plines[0] = strtok(lrc_src, str);

	while(plines[i++] != NULL)
	{
		plines[i] = strtok(NULL, str);
	}
	//printf("i=%d\n",i);
	return (i-1);
}

int line_segment(char *pline, char *pbuf[], char *str)
{
	int i = 0;

	pbuf[0] = strtok(pline, str);

	while(pbuf[i++] != NULL)
	{
		pbuf[i] = strtok(NULL, str);
		//printf("%s\n",pbuf[i]);
	}
	//printf("i=%d\n",i);

	return (i-1);
}

LRC *build_link(char *plines[], char *pheader[], int lines)
{
	int i, j;
	int part = 0;
	LRC lyric, *lrc_head = NULL;

	for(i=0;plines[i] != NULL && i<lines;i++)
	{

	#if 0
		char *pbuf[10] = {NULL};

		part = line_segment(plines[i],pbuf, "]"); //切割一行

		for(j=0;j<part;j++)
		{
			int min = 0,sec = 0, msec = 0;

			printf("%s\n",pbuf[j]);
		}
	#elif 1
		if(i<4) //
		{
			char *trash = NULL;
			//char msg[100]; sscanf 按给定格式输出内容放到一个足够大的空间
			//sscanf(plines[i],"%*[^:]%*1s%[^]]",msg[0]);
			trash = strtok(plines[i],":]");
			if(trash != NULL) pheader[i] = strtok(NULL,":]");
		}
		else
		{
			char *pbuf[10] = {NULL};
			char tbuf[10]  = {0};
			int min = 0, sec = 0, msec = 0;
			//float sec;

			part = line_segment(plines[i],pbuf, "]"); //切割一行

			for(j=0;j<part-1;j++)
			{
				if(pbuf[part-1][0] != '[')
				{
					sscanf(pbuf[j],"[%2d:%2d.%2d",&min,&sec,&msec);
					//printf("%2d:%2d.%2d\n",min,sec,msec);

					lyric.time = (min * 60 + sec)*1000 + msec*10; //毫秒
					lyric.psrc = pbuf[part-1];
					lrc_head = insert_link(lrc_head,lyric);
					//printf("%4d  %s\n",lyric.time, lyric.psrc);
				}
			}
		}
	#endif
	}
	return lrc_head;
}

void show_lyric(LRC *pnode, int longest)
{
	char *empty = " ";
	char *pbuf[12];
	int i = 0, offset = 0;
	LRC  *pb = NULL, *pf = NULL;

	pb = pnode;
	pf = pnode->next;

	for(i=4;i>=0;i--)
	{
		if(pb != NULL)
		{
			pbuf[i] = pb->psrc;
			pb = pb->prev;
		}
		else
		{
			pbuf[i] = empty;
		}
	}

	for(i=5;i<12;i++)
	{
		if(pf != NULL)
		{
			pbuf[i] = pf->psrc;
			pf = pf->next;
		}
		else
		{
			pbuf[i] = empty;
		}
	}

	for(i = 0;i < 12;i++) //
	{
		cusor_moveto(60, 17+i); //光标移到 第4+i行，第20列
		printf("%-36s",empty);  //清除上次的显示
		fflush(stdout);
	}

	for(i = 0;i < 12;i++)
	{
		offset = get_showoffset(pbuf[i],longest);
		cusor_moveto(60+offset, 17+i); //光标移到 第10+i行，第50列

		set_fg_color(COLOR_WHITE);
		if(i == 4)
		{
			set_fg_color(COLOR_MAGENTA);
		}
		printf("%-36s",pbuf[i]);

	}
	//cusor_moveto(9, 33);
	fflush(stdout);
}

int get_maxtime(LRC *head)
{
	int maxtime = 0;
	LRC *pb = head;

	while(pb->next != NULL) pb = pb->next;

	maxtime = pb->time;

	return (maxtime + 12 * 1000); //ms
}

int get_timelag(LRC *head)
{
	int maxtime = 0;
	LRC *pb = head;

	while(pb->next != NULL) pb = pb->next;

	maxtime = pb->time;

	return (maxtime + 12 * 1000)/60; //ms
}
<file_sep>/shell/2nd_week/sh
#!/bin/bash

echo $1

if [ $1 -lt 60 ]
then
	echo "E"
elif [ $1 -lt 69 -a $1 -gt 60 ]
then
	echo "D"
elif [ $1 -lt 79 -a $1 -gt 69 ]
then
	echo "C"
fi
<file_sep>/c/practice/binary_search.c
﻿/*=========================================================================
  工程名称：	练习  
  组成文件：	main.c
  功能描述： 	在一个排好序的数据中用二分查找法，找出需要的数据
  程序分析：	首先得从小到大排好序，二分再比较，不等则继续二分，直到高低碰头遍历结束
  维护记录：	2010-09-11 v1.1
=========================================================================*/
#include <stdio.h>

//二分法对以排好序的数据进行查找
int binary_search(int array[],int value,int size)
{
	int low=0,high=size-1,mid;

	while(low<=high)				//只要高低不碰头就继续二分查找
	{
		mid=(low+high)/2;
		if(value==array[mid])		//比较是不是与中间元素相等
			return mid;
		else if(value > array[mid])	//每查找一次，就判断一次所要查找变量所在范围，并继续二分
			low=mid + 1; 				//如果大小中间值，下限移到中间的后一个位，上限不变，往高方向二分
		else
			high=mid - 1; 			    //上限移到中间的前一个位，往低方向二分
	}
	return -1;
}

int main(void)
{
	int value;
	int a[10]={0,1,2,3,4,5,6,7,8,9};
	int n;

	while(1)
	{
		printf("\n请输入你要查找的数字:\n");
		scanf("%d",&value);
		n = binary_search(a,value,10);
		if(n==-1)
			printf("数字没找到!\n");
		else
			printf("查找数据的下标是：%d\n",n);
	}
}
<file_sep>/c/homework/3rd_week/message/msg.h
/* ************************************************************************
 *       Filename:  msg.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月27日 星期一 02時29分22秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/


#ifndef __MSG_H__
#define __MSG_H__

extern void show_number(const char *src);
extern void show_time( char *src1,char *src2);
extern void show_content(const char *src);
extern void show_message(char **src);
extern int msg_deal(char *msg_src, char *msg_done[],char *str);
#endif
<file_sep>/work/test/netlink/netlink_test.c
/*************************************************************************
	> File Name: netlink_test.c
	> Author: 
	> Mail: 
	> Created Time: Thu 01 Sep 2016 12:24:14 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/socket.h>

#define NETLINK_TEST  17
#define MAX_PAYLOAD   1024

struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
struct msghdr msg;
int sock_fd;

int main(int argc, const char *argv[])
{
    sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST);
    memset(&msg, 0, sizeof(struct msghdr));
    memset(&src_addr, 0, sizeof(struct sockaddr_nl));

    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid(); // self pid
    src_addr.nl_groups = 0;
    bind(sock_fd, (struct sockaddr *)&src_addr, sizeof(src_addr));

    memset(&dest_addr, 0, sizeof(struct sockaddr_nl));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0;    // for linux kernel
    dest_addr.nl_groups = 0; // unicast

    nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
    // fill the netlink message header
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
    nlh->nlmsg_pid = getpid();
    nlh->nlmsg_flags = 0;
    // fill in the netlink message payload
    strcpy(NLMSG_DATA(nlh), "This is a test!");

    iov.iov_base = (void *)nlh;
    iov.iov_len = nlh->nlmsg_len;
    msg.msg_name = (void *)&dest_addr;
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;

    sendmsg(sock_fd, &msg, 0);

    // read messsage from kernel
    memset(nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));
    recvmsg(sock_fd, &msg, 0);
    printf("Received message payload: %s\n", NLMSG_DATA(nlh));

    // close netlink socket
    close(sock_fd);
    return 0;
}
<file_sep>/c/mkheader/loader.c
/*************************************************************************
	> Filename: loader.c
	>   Author: 
	>    Email: 
	> Datatime: 2017年02月24日 星期五 22时34分02秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char *argv[])
{
    if (argc > 1) {
        FILE *fp;
        FILE *fp_n;
        char *app_buf;
        uint32_t length;

        fp = fopen("./app", "rb");
        if (fp == NULL) {
            printf("Cannot open file!\n");
            return -1;
        }

        fseek(fp, 0, SEEK_SET);
        fread(&length, sizeof(length), 1, fp);
        printf("read length=%d\n", length);

        app_buf = (char *)malloc(length);
        if (app_buf == NULL) {
            printf("Failed to malloc mem\n");
            return -1;
        }
        bzero(app_buf, length);

        fp_n = fopen("./n_app", "ab+");
        if (fp_n == NULL) {
            printf("Cannot open new file!\n");
            return -1;
        }

        fread(app_buf, length, 1, fp);
        fwrite(app_buf, length, 1, fp_n);

        fclose(fp);
        fclose(fp_n);
        free(app_buf);
    } else {
        int fd;
        int fd_n;
        uint32_t length;
        char *app_buf;

        fd = open("./app", O_RDONLY);
        if (fd < 0) {
            printf("Cannot open app file\n");
            return -1;
        }

        read(fd, (void *)&length, sizeof(length));
        printf("read length=%d\n", length);

        app_buf = (char *)malloc(length);
        if (app_buf == NULL) {
            printf("Failed to malloc mem\n");
            return -1;
        }
        bzero(app_buf, length);
        read(fd, app_buf, length);

        fd_n = open("./n_app", O_RDWR | O_CREAT);
        if (fd_n < 0) {
            printf("Cannot open n_app file\n");
            return -1;
        }

        write(fd_n, app_buf, length);
        fsync(fd_n);
        fchmod(fd_n, 0775);

        close(fd);
        close(fd_n);
        free(app_buf);
    }

    return 0;
}
<file_sep>/sys_program/7th_day/leds.c
/* ************************************************************************
 *       Filename:  leds.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月21日 11时59分31秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "s5pv210-gpio.h"


int main(int argc, char *argv[])
{
	return 0;
}


<file_sep>/sys_program/6th_day/sem.c
/* ************************************************************************
 *       Filename:  sem.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月20日 12时00分54秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t sem1;

void print(char *str)
{
	sem_wait(&sem1);
	while(*str != '\0')
	{
		putchar(*str++);
		fflush(stdout);
		sleep(1);
	}
	putchar('\n');

	sem_post(&sem1);
}

void *fun1(void *arg)
{
	char *buf = "world";

	print(buf);
}

void *fun2(void *arg)
{
	char *buf = "hello";

	print(buf);
}

int main(int argc, char *argv[])
{
	int val = 0;
	pthread_t pth1,pth2;

	sem_init(&sem1,0,1);
	sem_getvalue(&sem1,&val);
	printf("sem_val = %d\n",val);


	pthread_create(&pth1,NULL,fun1,NULL);
	pthread_create(&pth2,NULL,fun2,NULL);

	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);

	val = sem_destroy(&sem1);
	if(val==0)
	{
		printf("delete sem succeed\n");
	}
	return 0;
}
<file_sep>/c/homework/1st_week/petrol.c
/* ************************************************************************
 *       Filename:  petrol.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月20日 星期一 09時36分43秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/


#include <stdio.h>

#define	APRICE (1.50f)
#define BPRICE (1.35f)
#define CPRICE (1.18f)

typedef enum 
{
	agas = 'a',
	bgas = 'b',
	cgas = 'c',
}GAS;

typedef enum
{
	ato = 'f',
	own = 'm',
	ass = 'e',
}SERVER;


float get_gasoline(char service, char gasoline, float kg)
{
	float gas_price;
	float discount;

	switch(service)
	{
		case ato: discount = 0.00f; break;
		case own: discount = 0.05f; break;
		case ass: discount = 0.10f; break;
	}

	switch(gasoline)
	{
		case agas: 
				{
					gas_price = (APRICE * (1-discount)) * kg;
					break;
				}
		case bgas: 
				{
					gas_price = (BPRICE * (1-discount)) * kg;
					break;
				}
		case cgas: 
				{
					gas_price = (CPRICE * (1-discount)) * kg;
					break;
				}	
	}

	return gas_price;
}
int main(int argc, char *argv[])
{
	float price;
	float kg;
	char service,gasoline,temp;

	printf("请选择服务类型，输入：f | m | e\n");
	printf("f--自动服务，无优惠！\n");
	printf("m--自助服务，优惠%5！\n");
	printf("e--协助服务，优惠%10！\n");
	scanf("%c%c",&service,&temp);
//	service = getchar();

	printf("请选择汽油类型，输入：a | b | c\n");
	scanf("%c",&gasoline);
//	gasoline = getchar();
	printf("请输入本次加油量，单位：KG\n");
	scanf("%f",&kg);

	price = get_gasoline(service,gasoline,kg);
	printf("本次加油总价为 %.2f 元\n",price);

	return 0;
}


<file_sep>/work/test/mplay/tcp_server.c
/*************************************************************************
	> File Name: tcp_server.c
	> Author:
	> Mail:
	> Created Time: Mon 17 Oct 2016 10:53:42 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


int create_tcp_server(unsigned short port)
{
	int listen_sock = socket(AF_INET, SOCK_STREAM, 0);
	struct sockaddr_in s_addr;

	bzero(&s_addr, sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(port);
	s_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(listen_sock, (struct sockaddr *)&s_addr, sizeof(s_addr));
	if(ret != 0) {
		perror("bind():");
		return -1;
	}

	listen(listen_sock, 10);

	return listen_sock;
}

int recv_client_data(int listen_sock)
{
	fd_set rfds;
	struct timeval tv = {0, 100*1000};
	static int client = -1;
	int max, ret, index = -1;

	FD_ZERO(&rfds);
	FD_SET(listen_sock, &rfds);

	if(client != -1)
		FD_SET(client, &rfds);

	max = listen_sock > client ? listen_sock : client;
	ret = select(max+1, &rfds, NULL, NULL, &tv);

	if(ret > 0) {
		if(FD_ISSET(listen_sock, &rfds)) {
            struct sockaddr_in c_addr;
            socklen_t addr_len = sizeof(c_addr);
            bzero(&c_addr, addr_len);

			if(client != -1)
				close(client);

			client = accept(listen_sock, (struct sockaddr *)&c_addr, &addr_len);
		}

		if(client != -1 && FD_ISSET(client, &rfds)) {
			ret = read(client, &index, sizeof(index));
			if(ret != sizeof(index)) {
				close(client);
				client = -1;
				index = -1;
			}
		}
	}

	return index;
}
<file_sep>/sys_program/4th_day/rcv.c
/* ************************************************************************
 *       Filename:  rcv.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 15时44分30秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <string.h>
#include <unistd.h>


typedef struct _msg
{
	long type;

	char mutex[100];
}MSG;

int main(int argc, char *argv[])
{
	key_t key;
	int id;
	MSG rcv1, rcv2;

	key = ftok("./", 23);

	id = msgget(key, IPC_CREAT | 0666);

	msgrcv(id, &rcv1,sizeof(rcv1)-4, 10, 0); //0：msgrcv调用阻塞直到接收消息成功为止；成功返回消息长度
	printf("rcv1 = %s\n",rcv1.mutex);

	msgrcv(id, &rcv2,sizeof(rcv2)-4, 1, 0);
	printf("rcv2 = %s\n",rcv2.mutex);

#ifdef P
	printf("this is a test\n");
#endif
	return 0;
}


<file_sep>/gtk/1. base/08_key_event/key_event.c
#include <gtk/gtk.h>	// 头文件
#include <gdk/gdkkeysyms.h>	//键盘头文件

// 键盘按下事件处理函数
gboolean deal_key_press(GtkWidget *widget, GdkEventKey  *event, gpointer data)
{
	
	switch(event->keyval){	// 键盘键值类型
    case GDK_Up:
        g_print("Up\n");
        break;
    case GDK_Left:
        g_print("Left\n");
        break;
    case GDK_Right:
        g_print("Right\n");
        break;
    case GDK_Down:
        g_print("Down\n");
        break;
    }
	
	int key = event->keyval; // 获取键盘键值类型
	g_print("keyval = %d\n", key);
	
	
	return TRUE;
}

int main( int argc, char *argv[] )
{
	gtk_init(&argc, &argv);		// 初始化
	
	// 创建顶层窗口
    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	// 设置窗口的标题
	gtk_window_set_title(GTK_WINDOW(window), "mouse_event");
	// 设置窗口在显示器中的位置为居中
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
	// 设置窗口的最小大小
	gtk_widget_set_size_request(window, 400, 300);
	// "destroy" 和 gtk_main_quit 连接
	g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
	
	// "key-press-event" 与 deal_key_press 连接
	g_signal_connect(window, "key-press-event", G_CALLBACK(deal_key_press), NULL);
	
    gtk_widget_show_all(window);	// 显示窗口全部控件
	
    gtk_main();		// 主事件循环
	
    return 0;
}<file_sep>/sys_program/4th_day/homework/mplayer/image.c
/* ************************************************************************
 *       Filename:  image.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月11日 14时47分17秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <gtk/gtk.h>

// 给创建好的image重新设计一张图片
void load_image(GtkWidget *image, const char *file_path, const int w, const int h )
{
	gtk_image_clear( GTK_IMAGE(image) );        // 清除图像
	GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(file_path, NULL);	// 创建图片资源
	GdkPixbuf *dest_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR); // 指定大小
	gtk_image_set_from_pixbuf(GTK_IMAGE(image), dest_pixbuf); // 图片控件重新设置一张图片(pixbuf)
	g_object_unref(src_pixbuf);		// 释放资源
	g_object_unref(dest_pixbuf);	// 释放资源
}

// 根据图片路径创建一个新按钮，同时指定图片大小
GtkWidget *create_button_from_file(const char *file_path, const int w, const int h)
{
	GtkWidget *temp_image = gtk_image_new_from_pixbuf(NULL);
	load_image(temp_image, file_path, w, h);
	
	GtkWidget *button = gtk_button_new(); 					// 先创建空按钮
	gtk_button_set_image(GTK_BUTTON(button), temp_image);	// 给按钮设置图标
	gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);	// 按钮背景色透明
	
	return button;
}

/* 功能：  设置背景图
 * widget: 主窗口
 * w, h:   图片的大小
 * path：  图片路径
 */
void chang_background(GtkWidget *widget, int w, int h, const gchar *path)
{
	gtk_widget_set_app_paintable(widget, TRUE);		//允许窗口可以绘图
    gtk_widget_realize(widget);	
	
	/* 更改背景图时，图片会重叠
	 * 这时要手动调用下面的函数，让窗口绘图区域失效，产生窗口重绘制事件（即 expose 事件）。
	 */
	gtk_widget_queue_draw(widget);
	
    GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(path, NULL);	// 创建图片资源对象
    // w, h是指定图片的宽度和高度
    GdkPixbuf *dst_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR);

	GdkPixmap *pixmap = NULL;
	
	/* 创建pixmap图像; 
	 * NULL：不需要蒙版; 
	 * 123： 0~255，透明到不透明
	 */
    gdk_pixbuf_render_pixmap_and_mask(dst_pixbuf, &pixmap, NULL, 50);
    // 通过pixmap给widget设置一张背景图，最后一个参数必须为: FASLE
	gdk_window_set_back_pixmap(widget->window, pixmap, FALSE);
    
	// 释放资源
	g_object_unref(src_pixbuf);
    g_object_unref(dst_pixbuf);
    g_object_unref(pixmap);
}

<file_sep>/shell/2nd_week/b.sh
#!/bin/bash

str=" I love linux.I love UNIX too."
str2="$str"
#str2=${str/love/like}

echo "str =$str"
echo "str2=$str2"
exit
str="I love linux, I love GNU too."

echo ${str%,*.}

exit


echo -n "input a string:"
#read -s -p "input a string:" str
read str

echo "$str"

unset color
echo "the shy is ${color:-grey} today"
echo "$color"

echo "the sky is ${color:=grey} today"
echo "$color"

color=yellow

echo "the shy is ${color:?error} today"
echo "$color"


echo "the shy is ${color:+blue} today"
echo "$color"
<file_sep>/c/practice/3rd_week/time/main.c
/* ************************************************************************
 *       Filename:  main.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月28日 星期二 05時13分34秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <time.h>
#include "show_time.h"

void main()
{

	show_time();

}


<file_sep>/work/debug/pc/sync/sync_drv.c
/* ************************************************************************
 *       Filename:  sync_drv.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年11月11日 10时57分49秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <linux/miscdevice.h>
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mm.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/ioctl.h>
#include <linux/cdev.h>
#include <linux/string.h>
#include <linux/list.h>
#include <linux/poll.h>
#include <linux/fcntl.h>
#include <linux/signal.h> //for SIGIO,POLL_IN
#include <linux/timer.h>
#include <linux/jiffies.h>

#define DEVICE_NAME  "sync"

static struct timer_list sync_timer;
static struct fasync_struct *sync_queue;


static void sync_timerhandler(unsigned long arg)
{
	//发送信号到用户空间，通知相关进程
	kill_fasync(&sync_queue, SIGIO, POLL_IN);
	mod_timer(&sync_timer,jiffies + HZ); //更新定时器，不更新的话，定时器处理函数只执行一次
}
	
static int sync_open(struct inode *pinode, struct file *filp)
{
	init_timer(&sync_timer); // 初始化定时器
	sync_timer.data = 0;     // 传递给定时器处理函数的参数
	sync_timer.function = sync_timerhandler; // 定时器处理函数
	sync_timer.expires = jiffies + HZ;
	add_timer(&sync_timer); // 启动定时器
	return 0;
}

static int sync_fasync(int fd, struct file *filp, int mode)
{
	//根据用户空间的需要，获取或设置相应的属性
	return fasync_helper(fd, filp, mode, &sync_queue);
}

static int sync_close(struct inode *pinode, struct file *filp)
{
	del_timer_sync(&sync_timer); // 删除定时器，在定时器时间到前停止一个已注册的定时器
    sync_fasync(-1, filp, 0);    // 将文件从异步通知列表中删除
	return 0;
}

static struct file_operations sync_fops = {
	.owner   = THIS_MODULE,
	.open    = sync_open,
	.fasync  = sync_fasync,
	.release = sync_close,
};

static struct miscdevice sync_misc = { /*杂项字符设备结构体*/
    .minor = MISC_DYNAMIC_MINOR,       /*次设备号 表示自动分配*/
    .name  = DEVICE_NAME,              /*设备名*/
    .fops  = &sync_fops,               /*设备操作*/
};

static __init int sync_init(void)
{
	int ret;

	ret = misc_register(&sync_misc);
	if(ret < 0)
		printk(DEVICE_NAME "can't register\n");
	else
		printk(DEVICE_NAME "register successful\n");
	return ret;
}

static __exit void sync_exit(void)
{
	misc_deregister(&sync_misc);
	printk("unregister success \n");
}

module_init(sync_init);
module_exit(sync_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/yuv2bmp/conver.c
/*
##############################################################################
# Raw Image Player [ImPlayer]                           					 #
# Copyright 2000 <NAME> and <NAME>                             #
# Video Signal Processing Lab, Dept.EE, NTHU                                 #
# Version 1.5  Created 2/1/2000                                              #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 2000 <NAME> and <NAME>, All Rights Reserved.       #
#                                                                            #
# [ImPlayer] may be used and modified free of charge by anyone so long as    #
# this copyright notice and the comments above remain intact. By using this  #
# code you agree to indemnify Yao-Jen Chang from any liability that might    #
# arise from it's use.                                                       #
#                                                                            #
# Comments, feedback, bug reports, improvements are encouraged. Please sent  #
# them to <EMAIL>.                                            #
##############################################################################
*/
/************************************************************************
 *
 *  yuvrgb24.c, colour space conversion for tmndecode (H.263 decoder)
 *  Copyright (C) 1995, 1996  Telenor R&D, Norway
 *        <NAME> <<EMAIL>>
 *  
 *  Contacts: 
 *  <NAME>               <<EMAIL>>, or
 *  <NAME>                  <<EMAIL>>
 *
 *  Telenor Research and Development  http://www.nta.no/brukere/DVC/
 *  P.O.Box 83                        tel.:   +47 63 84 84 00
 *  N-2007 Kjeller, Norway            fax.:   +47 63 81 00 76
 *  
 ************************************************************************/

/*
 * Disclaimer of Warranty
 *
 * These software programs are available to the user without any
 * license fee or royalty on an "as is" basis.  Telenor Research and
 * Development disclaims any and all warranties, whether express,
 * implied, or statuary, including any implied warranties or
 * merchantability or of fitness for a particular purpose.  In no
 * event shall the copyright-holder be liable for any incidental,
 * punitive, or consequential damages of any kind whatsoever arising
 * from the use of these programs.
 *
 * This disclaimer of warranty extends to the user of these programs
 * and user's customers, employees, agents, transferees, successors,
 * and assigns.
 *
 * Telenor Research and Development does not represent or warrant that
 * the programs furnished hereunder are free of infringement of any
 * third-party patents.
 *
 * Commercial implementations of H.263, including shareware, are
 * subject to royalty fees to patent holders.  Many of these patents
 * are general enough such that they are unavoidable regardless of
 * implementation design.
 * */


#include "futil.h"

static unsigned char* clp = NULL;
static int crv_tab[256]={0};
static int cbu_tab[256]={0};
static int cgu_tab[256]={0};
static int cgv_tab[256]={0};
static int tab_76309[256]={0};
static int bilevel_tab_76309[256]={0};
BITMAPINFO  bmi;
static int inited = 0;

static int init_clp() 
{
  int i;
  if(clp == NULL)
  	{
  		clp = (unsigned char*)malloc(1024);
  		if(clp == NULL)
  			{
  				printf("init_clp malloc failed \r\n");
  				return -1;
  			}
  	}else
  		{
  			printf("init_clp always inited \r\n");
  			return 0;
  		}
  clp += 384;

  for (i=-384; i<640; i++)
  {
    clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
  }

  return 0;
}

static void init_dither_tab()
{
  long int crv,cbu,cgu,cgv;
  int i;

  crv = 104597; cbu = 132201;  /* fra matrise i global.h */
  cgu = 25675;  cgv = 53279;

  for (i = 0; i < 256; i++) {
    crv_tab[i] = (i-128) * crv;
    cbu_tab[i] = (i-128) * cbu;
    cgu_tab[i] = (i-128) * cgu;
    cgv_tab[i] = (i-128) * cgv;
    tab_76309[i] = 76309*(i-16);
  }
  bilevel_tab_76309[0] = tab_76309[0];
  for (i = 1; i < 256; i++) {
	  bilevel_tab_76309[i] = tab_76309[255];
  }

}

int  init_conver()
{
  init_dither_tab();
  if(init_clp() < 0)
  	{
  		return -1;
  	}
  bmi.bmiHeader.biSize = (LONG)sizeof(BITMAPINFOHEADER);
  bmi.bmiHeader.biPlanes = 1;
  bmi.bmiHeader.biCompression = 0l;
  bmi.bmiHeader.biSizeImage = 0l;
  bmi.bmiHeader.biXPelsPerMeter = 0l;
  bmi.bmiHeader.biYPelsPerMeter = 0l;
  bmi.bmiHeader.biBitCount = 24;
  inited = 1;
  return 0;
}

/**********************************************************************
 *
 *	Name:	         ConvertYUVtoRGB
 *	Description:     Converts YUV image to RGB (packed mode)
 *
 *	Input:	         pointer to source luma, Cr, Cb, destination,
 *                       image width and height
 *	Returns:
 *	Side effects:
 *
 *	Date: 951208	Author: <EMAIL>
 *
 ***********************************************************************/

void rgb5652rgb888(unsigned short* rgb565,unsigned int* rgb888,unsigned int framesize)
{
	unsigned int i;
	unsigned char r,g,b;
	r=g=b=0;
	for(i=0;i<framesize;i++)
	{
		r=((*((unsigned short*)rgb565 + i))>>11)&0x1f;
		g=((*((unsigned short*)rgb565 + i))>>5)&0x3f;
		b=(*((unsigned short*)rgb565 + i))&0x1f;
		*((unsigned int*)rgb888 + i)=(r<<19)|(g<<10)|(b<<3);
	}
}
/*
yuv422转换RGB565并缩小一半图像的函数
yuv422buf: input width*height picture buffer
rgb565:    output width/2*height/2 picture RGB565 buffer
width:     input picture width
height:    input  picture height
*/
int yuv422rgb565_scale(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height)
{
	int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
	int width4 = width + (4 - (width%4))%4;
	unsigned short R,G,B;
  	unsigned char *pucy,* pucu, * pucv;
	char crgbtmp;
  	if((yuv422buf==NULL)||(rgb565==NULL)){
		return -1;
	}
	if(inited == 0){
		if(init_conver() < 0){
			return -1;
		}
	}
	pucy = yuv422buf;
	pucu = yuv422buf + width * height;
	pucv = yuv422buf + width * height * 3/2;

	width		=	width/2;
	height		=	height/2;

	k	=	width * (height-1);		//Point to the last width_line of rgb565buf,why?
	for (i = 0; i < height; i++){
    		for (j = 0; j < width; j+=4)
		{
			y11 = tab_76309[*pucy++];
        	y12 = tab_76309[*pucy++];
        	u = *pucu++;
        	v = *pucv++;
        	u2g = cgu_tab[u];
        	u2b = cbu_tab[u];
        	v2g = cgv_tab[v];
        	v2r = crv_tab[v];


		     crgbtmp	=	clp[(y11 + v2r)>>16];
		     R 		= 	((crgbtmp >> 3)) & 0x001F;
		     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;
		     crgbtmp	= 	clp[(y11 + u2b)>>16];
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;
			// printf(" ===  R = 0x%04x, G = 0x%04x B =0x%04x    \n",R,G,B);
		     rgb565[k++]	= 	(R | G | B);
			//printf("%d rgb565[%d] = 0x%04x  \n",__LINE__,k,rgb565[k]);
		     crgbtmp	=	clp[(y12 + v2r)>>16];
		     R 		= 	((crgbtmp >> 3)) & 0x001F;

		     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;

		     crgbtmp	= 	clp[(y12 + u2b)>>16];
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;

		     rgb565[k++]	= 	(R | G | B);

//Skip two pixels,because two pixels as a unit.
		     pucy+=2;
		     pucu++;
		     pucv++;

// Let two ALU work at the same time
                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];

			     crgbtmp	=	clp[(y11 + v2r)>>16];
			     R 		= 	((crgbtmp >> 3)) & 0x001F;

			     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];
			     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;

			     crgbtmp	= 	clp[(y11 + u2b)>>16];	
			     B		=	((crgbtmp >> 3)<<11) & 0xF800;
	
			     rgb565[k++]	= 	(R | G | B);      
	
			     crgbtmp	=	clp[(y12 + v2r)>>16];
			     R 		= 	((crgbtmp >> 3)) & 0x001F;
			     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
			     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	
			     crgbtmp	= 	clp[(y12 + u2b)>>16];	
			     B		=	((crgbtmp >> 3)<<11) & 0xF800;
	
			     rgb565[k++]	= 	(R | G | B);      
	
	//Skip two pixels,because two pixels as a unit.
			     pucy+=2;
			     pucu++;
			     pucv++;
	            	}

					k=k - width*2;
					pucy+=width4;				//Skip one width_line Y,U,V
					pucu+=width4/2;
					pucv+=width4/2;
        }

	return 0;
}

/*
yuv422转换RGB565图像的函数
yuv422buf: input width*height picture buffer
rgb565:    output width*height picture RGB565 buffer
width:     input picture width
height:    input  picture height
*/
int yuv422rgb565(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height)
{
	int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
	int width4 = width + (4 - (width%4))%4;
	unsigned short R,G,B;
  	unsigned char *pucy,* pucu, * pucv;
	char crgbtmp;
  	if((yuv422buf==NULL)||(rgb565==NULL)){
		return -1;
	}
	if(inited == 0){
		if(init_conver() < 0){
			return -1;
		}
	}
	pucy = yuv422buf;
	pucu = yuv422buf + width * height;
	pucv = yuv422buf + width * height * 3/2;

	k	=	width * (height-1);		//Point to the last width_line of rgb565buf,why?
	for (i = 0; i < height; i++){
    		for (j = 0; j < width; j+=4)
		{
			y11 = tab_76309[*pucy++];
        	y12 = tab_76309[*pucy++];
        	u = *pucu++;
        	v = *pucv++;
        	u2g = cgu_tab[u];
        	u2b = cbu_tab[u];
        	v2g = cgv_tab[v];
        	v2r = crv_tab[v];


		     crgbtmp	=	clp[(y11 + v2r)>>16];
		     R 		= 	((crgbtmp >> 3)) & 0x001F;
		     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	
		     crgbtmp	= 	clp[(y11 + u2b)>>16];	
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;
		     rgb565[k++]	= 	(R | G | B);      
		     crgbtmp	=	clp[(y12 + v2r)>>16];
		     R 		= 	((crgbtmp >> 3)) & 0x001F;

		     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	

		     crgbtmp	= 	clp[(y12 + u2b)>>16];	
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;

		     rgb565[k++]	= 	(R | G | B);      
		     
                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];

			     crgbtmp	=	clp[(y11 + v2r)>>16];
			     R 		= 	((crgbtmp >> 3)) & 0x001F;
	
			     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
			     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	
	
			     crgbtmp	= 	clp[(y11 + u2b)>>16];	
			     B		=	((crgbtmp >> 3)<<11) & 0xF800;
	
			     rgb565[k++]	= 	(R | G | B);      
	
			     crgbtmp	=	clp[(y12 + v2r)>>16];
			     R 		= 	((crgbtmp >> 3)) & 0x001F;
			     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
			     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	
			     crgbtmp	= 	clp[(y12 + u2b)>>16];	
			     B		=	((crgbtmp >> 3)<<11) & 0xF800;
	
			     rgb565[k++]	= 	(R | G | B);      
	
	            }
					k=k - width*2;
        }

	return 0;
}


#define YCbCrtoR(Y,Cb,Cr) (1000*Y + 1371*(Cr-128))/1000
#define YCbCrtoG(Y,Cb,Cr) (1000*Y - 336*(Cb-128) - 698*(Cr-128))/1000
#define YCbCrtoB(Y,Cb,Cr) (1000*Y + 1732*(Cb-128))/1000
#define min(x1, x2)   (((x1)<(x2))?(x1):(x2))
typedef unsigned char __u8;
typedef unsigned short __u16;
typedef unsigned int __u32;

__u32 Conv_YCbCr_Rgb(__u8 y0, __u8 y1, __u8 cb0, __u8 cr0)
{
	// bit order is
	// YCbCr = [Cr0 Y1 Cb0 Y0], RGB=[R1,G1,B1,R0,G0,B0].

	int r0, g0, b0, r1, g1, b1;
	__u16 rgb0, rgb1;
	__u32 rgb;

#if 1 // 4 frames/s @192MHz, 12MHz ; 6 frames/s @450MHz, 12MHz
	r0 = YCbCrtoR(y0, cb0, cr0);
	g0 = YCbCrtoG(y0, cb0, cr0);
	b0 = YCbCrtoB(y0, cb0, cr0);
	r1 = YCbCrtoR(y1, cb0, cr0);
	g1 = YCbCrtoG(y1, cb0, cr0);
	b1 = YCbCrtoB(y1, cb0, cr0);
#endif

	if (r0>255 ) r0 = 255;
	if (r0<0) r0 = 0;
	if (g0>255 ) g0 = 255;
	if (g0<0) g0 = 0;
	if (b0>255 ) b0 = 255;
	if (b0<0) b0 = 0;

	if (r1>255 ) r1 = 255;
	if (r1<0) r1 = 0;
	if (g1>255 ) g1 = 255;
	if (g1<0) g1 = 0;
	if (b1>255 ) b1 = 255;
	if (b1<0) b1 = 0;

	// 5:6:5 16bit format
	rgb0 = (((__u16)r0>>3)<<11) | (((__u16)g0>>2)<<5) | (((__u16)b0>>3)<<0); //RGB565.
	rgb1 = (((__u16)r1>>3)<<11) | (((__u16)g1>>2)<<5) | (((__u16)b1>>3)<<0); //RGB565.

	rgb = (rgb1<<16) | rgb0;

	return(rgb);
}


/*
yuv422转换RGB888并缩小一半图像的函数
yuv422buf: input width*height picture buffer
rgb888:    output width/2*height/2 picture RGB888 buffer
width:     input picture width
height:    input  picture height
*/
int yuv422rgb888_scale(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height)
{
	int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
	int width4 = width + (4 - (width%4))%4;
	unsigned int R,G,B;
  unsigned char *pucy,* pucu, * pucv;//, * pucraster0;
	char crgbtmp;
  if((yuv422buf==NULL)||(rgb888==NULL))
	{
		return -1;
	}
	if(inited == 0)
	{
			if(init_conver() < 0)
				{
					return -1;
				}
	}
	pucy = yuv422buf;
	pucu = yuv422buf + width * height;
	pucv = yuv422buf + width * height * 3/2;

	width		=	width/2;
	height	=	height/2;

	k	=	width * (height-1);		//Point to the last width_line of rgb565buf,why?
	for (i = 0; i < height; i++)
	{
    for (j = 0; j < width; j+=4)
		{

                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];


		     crgbtmp	=	clp[(y11 + v2r)>>16];
		     R 		= 	crgbtmp ;
		     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
		     G 		= 	crgbtmp ;	
		     crgbtmp	= 	clp[(y11 + u2b)>>16];	
		     B		=	  crgbtmp;
		     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));      
	
		     crgbtmp	=	clp[(y12 + v2r)>>16];
		     R 		= 	crgbtmp ;

		     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
		     G 		= 	crgbtmp ;	

		     crgbtmp	= 	clp[(y12 + u2b)>>16];	
		     B		=	 crgbtmp;

		     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));       
		     
//Skip two pixels,because two pixels as a unit.
		     pucy+=2;
		     pucu++;
		     pucv++;

// Let two ALU work at the same time
                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];

			     crgbtmp	=	clp[(y11 + v2r)>>16];
			     R 		= 	crgbtmp ;
	
			     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
			     G 		= 	crgbtmp;	
	
			     crgbtmp	= 	clp[(y11 + u2b)>>16];	
			     B		=	crgbtmp;
	
			     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));    
	
			     crgbtmp	=	clp[(y12 + v2r)>>16];
			     R 		= 	crgbtmp ;
			     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
			     G 		= 	crgbtmp ;	
			     crgbtmp	= 	clp[(y12 + u2b)>>16];	
			     B		=	crgbtmp ;
	
			     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));         
	
	//Skip two pixels,because two pixels as a unit.
			     pucy+=2;
			     pucu++;
			     pucv++;
	   	}

					k=k - width*2;
					pucy+=width4;				//Skip one width_line Y,U,V
					pucu+=width4/2;
					pucv+=width4/2;
    }

	return 0;
}

/*
yuv422转换RGB888图像的函数
yuv422buf: input width*height picture buffer
rgb888:    output width*height picture RGB888 buffer
width:     input picture width
height:    input  picture height
*/
int yuv422rgb888(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height)
{
	int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
	int width4 = width + (4 - (width%4))%4;
	unsigned int R,G,B;
  unsigned char *pucy,* pucu, * pucv;//, * pucraster0;
	char crgbtmp;
  if((yuv422buf==NULL)||(rgb888==NULL))
	{
		return -1;
	}
	if(inited == 0)
	{
			if(init_conver() < 0)
				{
					return -1;
				}
	}
	pucy = yuv422buf;
	pucu = yuv422buf + width * height;
	pucv = yuv422buf + width * height * 3/2;


	k	=	width * (height-1);		//Point to the last width_line of rgb565buf,why?
	for (i = 0; i < height; i++)
	{
    for (j = 0; j < width; j+=4)
		{

                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];


		     crgbtmp	=	clp[(y11 + v2r)>>16];
		     R 		= 	crgbtmp ;
		     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
		     G 		= 	crgbtmp ;	
		     crgbtmp	= 	clp[(y11 + u2b)>>16];	
		     B		=	  crgbtmp;
		     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));      
	
		     crgbtmp	=	clp[(y12 + v2r)>>16];
		     R 		= 	crgbtmp ;

		     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
		     G 		= 	crgbtmp ;	

		     crgbtmp	= 	clp[(y12 + u2b)>>16];	
		     B		=	 crgbtmp;

		     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));       
		     
// Let two ALU work at the same time
                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];

			     crgbtmp	=	clp[(y11 + v2r)>>16];
			     R 		= 	crgbtmp ;
	
			     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
			     G 		= 	crgbtmp;	
	
			     crgbtmp	= 	clp[(y11 + u2b)>>16];	
			     B		=	crgbtmp;
	
			     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));    
	
			     crgbtmp	=	clp[(y12 + v2r)>>16];
			     R 		= 	crgbtmp ;
			     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
			     G 		= 	crgbtmp ;	
			     crgbtmp	= 	clp[(y12 + u2b)>>16];	
			     B		=	crgbtmp ;
	
			     rgb888[k++]	= 	((R& 0x000000FF) | ((G << 8)& 0x0000FF00) | ((B << 16)& 0x00FF0000));         
	
	   	}

					k=k - width;
    }

	return 0;
}

void FilterRGB(unsigned char *PixelsBuffer, int Width, int Height) {
	int i, j;
	unsigned char p, *p1, *p2, *p3, *p4;
	p1 = (unsigned char *) PixelsBuffer;
	p2 = p1 + 1;
	p3 = p1 + Width;
	p4 = p3 + 1;
	for (i = 0; i < Height - 1; i++) {
		for (j = 0; j < Width - 1; j++) {
			p = (*p1 + *p2++ + *p3++ + *p4++ + 2) / 4;
			*p1++ = p;
		}
		p1++;
		p2++;
		p3++;
		p4++;
	}
}


// convert 24bit rgb888 to 16bit rgb565 color format

static inline unsigned short rgb888torgb565(unsigned char red,unsigned char green, unsigned char blue)
{
	unsigned short  B = (blue >> 3) & 0x001F;
	unsigned short  G = ((green >> 2) << 5) & 0x07E0;
	unsigned short  R = ((red >> 3) << 11) & 0xF800;

	return (unsigned short) (R | G | B);
}

int rgb8882rgb565(unsigned short *rgb565,unsigned char *rgb888,unsigned int imagesize)
{
	unsigned int i,j;
	unsigned short R,G,B;
	for(i = 0; i < imagesize; ++i)
	{
		j = i * 3;
        	R = ((rgb888[j++] >> 3)<<11) & 0xF800;	//
       	G = ((rgb888[j++] >> 2)<<5) & 0x07E0; //
        	B = ((rgb888[j] >> 3)) & 0x001F;		
		rgb565[i] = R | G | B;
	}

	return 0;
}
/*
把rgb565src的图像宽度截取width
rgb565src：输入图像源
rgb565cut：截取后的输出图像数据
width：需要截取的宽度
imagesize：输入图像源的图像大小（这个数据是原始没有缩放的图像长度）
*/
int cut_rgb565(unsigned short *rgb565cut,unsigned short *rgb565src,unsigned int width,unsigned int imagesize)
{
	int i=0,j=0,n=-1,length=0;

	length = imagesize>>2;
	unsigned short *p_input		=	rgb565src;
	unsigned short *p_output	=	rgb565cut;	

  while(i < length)
	{
		if(0==(j%width))
			p_input +=  width;

		*p_output++ = *p_input++;
		 p_input++;
		 j+=2;
		 i++;
	}	

	return 0;
}


void rgb565_rotate90(const unsigned short *input, int width_in, int height_in,unsigned short *output)//, int *width_out, int *height_out)
{
        unsigned short *pIn=(unsigned short *)input;
        unsigned short *pOut=(unsigned short *)output;

        int i,j;

        for(i=0; i<height_in; i++)
        {
                for(j=0; j<width_in; j++)
                {
                        *pOut = *pIn++;
                        pOut = output+height_in*j + i;
                }
        }

//      *width_out = height_in;
//      *height_out = width_in;
}

/*************************
 *Translate the picture Right_Left.
 * ***********************/
void rgb565_folio(unsigned short *rgb565,int width,int height)
{
	printf("rgb565_folio\n");

	unsigned short *p;
	unsigned short *q;
	p = rgb565;
	q = p + width - 1;
	unsigned short ustmp;
	int x,y;

	for(y=1; y <= height; ++y)
	{
		for(x=0; x < width; ++x)
		{
			ustmp	=	*q;
			*q	=	*p;
			*p	=	ustmp;
			 q--;
			 p++;
		}
		p++;
		q=q+width;
	}
}

int  close_conver()
{
	if(clp != NULL)
		{
			clp -= 384;
			free(clp);
			clp=NULL;
		}
		inited = 0;
		return 0;
}
<file_sep>/work/debug/a8/driver.c

#include <linux/module.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <asm/uaccess.h>
#include <plat/gpio-cfg.h>
#include <mach/gpio.h>

#define LED_INPUT	    _IO('i',1)
#define LED_OUTPUT   	_IO('o',2)

static int demo_major = 0;
static struct class *my_class;

static int demo_open(struct inode *pinode, struct file *pfile)
{
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	printk("major:%d,minor:%d\n",imajor(pinode),iminor(pinode));

	return 0;
}
static ssize_t demo_read(struct file *pfile, char __user *buffer, size_t count, loff_t *offset)
{
	char data[] = "this is driver!";
	int ret;
	int len = min(strlen(data),count);
	printk("%s:%d\n",__FUNCTION__,__LINE__);

	ret = copy_to_user(buffer,data,len);
	return len;
}
static ssize_t demo_write(struct file *pfile, const char __user *buffer, size_t count, loff_t *offset)
{
	char data[20];
	int ret;
	int len = min(strlen(data),count);
	printk("%s:%d\n",__FUNCTION__,__LINE__);

	ret = copy_from_user(data,buffer,len);
	printk("%s\n",data);

	if(data[0] == '1'){
		gpio_set_value(S5PV210_GPH0(0), 1); // ΆΤΣ¦Ί―Κύ: gpio_get_value(S5PV210_GPH0(0));
		gpio_set_value(S5PV210_GPH0(1), 1);
		gpio_set_value(S5PV210_GPH0(2), 1);
		gpio_set_value(S5PV210_GPH0(3), 1);
	}
	else{
		gpio_set_value(S5PV210_GPH0(0), 0);
		gpio_set_value(S5PV210_GPH0(1), 0);
		gpio_set_value(S5PV210_GPH0(2), 0);
		gpio_set_value(S5PV210_GPH0(3), 0);
	}
	return len;
}
static int demo_release(struct inode *pinode, struct file *pfile)
{
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	return 0;
}
static long demo_ioctl(struct file *pfile, unsigned int cmd, unsigned long arg)
{
	switch(cmd){
	case LED_INPUT:
		s3c_gpio_cfgpin(S5PV210_GPH0(arg),S3C_GPIO_INPUT);
		break;
	case LED_OUTPUT:
		s3c_gpio_cfgpin(S5PV210_GPH0(arg),S3C_GPIO_OUTPUT);
		break;
	default:
		break;
	}
	
	return 0;
}
static struct file_operations demo_fops = {
	.owner = THIS_MODULE,
	.open = demo_open,
	.read = demo_read,
	.write = demo_write,
	.release = demo_release,
	.unlocked_ioctl = demo_ioctl,
};

int __init demo_module_init(void)
{
	int i;
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	demo_major = register_chrdev(demo_major,"char_dev",&demo_fops);
	my_class = class_create(THIS_MODULE,"demo_class");
	for(i=0;i<6;i++)
		device_create(my_class,NULL,MKDEV(demo_major,i),NULL,"demo_char%d",i);
	return 0;
}
void __exit demo_module_exit(void)
{
	int i;
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	for(i=0;i<6;i++)
		device_destroy(my_class,MKDEV(demo_major,i));
	class_destroy(my_class);
	unregister_chrdev(demo_major,"char_dev");
}
module_init(demo_module_init);
module_exit(demo_module_exit);
MODULE_LICENSE("GPL");

<file_sep>/work/debug/pc/sync/test_sync.c
/* ************************************************************************
 *       Filename:  test_sync.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年11月11日 10时58分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>  
#include <stdlib.h>	
#include <string.h> 
#include <fcntl.h>  
#include <unistd.h>	
#include <sys/stat.h>  
#include <signal.h>	


int flag = 0;

void sync_handler(int signo)
{
	if(signo == SIGIO){
		printf("receive successful!!!\n");
		flag++;
	}
}

#if 0
int main(int argc, char *argv[])
{
	int fd, oflags;

	fd = open("/dev/sync", O_RDWR, 766);

	if(fd < 0){
		printf("cannot' open /dev/sync\n");
		return -1;
	}

	signal(SIGIO, sync_handler);
	fcntl(fd, F_SETOWN, getpid());
	oflags = fcntl(fd, F_GETFL);
	fcntl(fd, F_SETFL, oflags | FASYNC);

	while(1){
		if(flag > 5)
			break;
		usleep(600*1000);
	}

	close(fd);
	return 0;
}
#else
   
int main()   
{   
     struct sigaction action;  
     int async_fd; 
  
     memset(&action, 0, sizeof(action));   
     //信号处理函数
     action.sa_handler = sync_handler;   
     action.sa_flags = 0;       
     //注册信号类型
     sigaction(SIGIO, &action, NULL);   

     async_fd = open("/dev/sync", O_RDONLY);   
     if(async_fd < 0)
     {
          printf("can not open /dev/sync \n");
          return -1;
     }

     //告诉驱动当前进程的PID
     fcntl(async_fd, F_SETOWN, getpid());   
     //设置驱动的FASYNC属性，支持异步通知
     fcntl(async_fd, F_SETFL, fcntl(async_fd, F_GETFL) | FASYNC);   
  
     printf("waiting for receive...\n");

     while(1){
		 if(flag > 5) break;
		 usleep(600*1000); 
	 }
            
     close(async_fd);  
 
     return 0;   
}
#endif<file_sep>/c/practice/1st_week/area_circle/Makefile
area:area_circle.o
	gcc -o area area_circle.o
area_circle.o:area_circle.c
	gcc -c area_circle.c 

.PHONY:clean
clean:
	rm *.o area
<file_sep>/network/3rd_day/tcp_server.c
/* ************************************************************************
 *       Filename:  tcp_server.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月02日 15时19分34秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

void *fun(void *arg)
{
	int confd = (int )arg;
	send(confd, "connect successful!\n", strlen("connect successful!\n"), 0);
	while(1)
	{
		char buf[512]="";
		int recv_len = recv(confd, buf, sizeof(buf),0);
		if(recv_len == 0) break;
		strcat(buf, "\n");
		send(confd, buf, strlen(buf), 0);
	}
	close(confd);
}

int main(int argc, char *argv[])
{
	//1.创建一个用于通信的tcp 监听 套接字
	unsigned short port = 8080;
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);

//	if(argc < 2)
//	{
//		printf("parameter too little\n");
//		exit(-1);
//	}
//	port = atoi(argv[1]);

	//2.让服务器绑定IP和端口
	struct sockaddr_in s_addr;
	bzero(&s_addr, sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(port);
	s_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
	if(ret != 0)
	{
		perror("bind:");
		exit(-1);
	}
	//3.listen创建连接队列
	listen(sockfd, 10);

	while(1)
	{
		struct sockaddr_in c_addr;
		socklen_t c_addr_len = sizeof(c_addr);

		int confd = accept(sockfd, (struct sockaddr *)&c_addr, &c_addr_len);

		pthread_t pthid;
		pthread_create(&pthid, NULL, (void *)fun, (void *)confd);
		pthread_detach(pthid); //线程分离
	}
	close(sockfd);
	return 0;
}




#if 0
int main(int argc, char *argv[])
{
	//1.创建一个用于通信的tcp 监听 套接字
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);

	//2.让服务器绑定IP和端口
	struct sockaddr_in s_addr;
	bzero(&s_addr, sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(8080);
	s_addr.sin_addr.s_addr = htons(INADDR_ANY);

	int ret = bind(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
	if(ret != 0)
	{
		perror("bind:");
		exit(-1);
	}
	//3.listen创建连接队列
	listen(sockfd, 10);

	while(1)
	{
		char ip[16] = "";
		struct sockaddr_in c_addr;
		socklen_t c_addr_len= sizeof(c_addr);
		//4.提取客户端的连接
		int confd = accept(sockfd, (struct sockaddr *)&c_addr, &c_addr_len);

		inet_ntop(AF_INET, &c_addr.sin_addr.s_addr, ip,16);

		while(confd != 0)
		{
			send(confd, "hongbao", strlen("hongbao"), 0);
			//printf("ip:%s  port:%d\n",ip, ntohs(c_addr.sin_port));

			//4.接收
			char buf[128]="";
			int recv_len = recv(confd, buf, sizeof(buf),0);
			if(recv_len == 0) break;
			printf("ip:%s  port:%d recv = %s\n",ip, ntohs(c_addr.sin_port),buf);
		}

		break;
	}
	close(sockfd);
	return 0;
}
#endif
<file_sep>/work/test/cim_test-zmm220/arca.h
/********************************************************************
                                           
 ZEM 200                                          
                                                    
 jz4730.h defines all the constants and others for Jz4730 CPU
                                                      
 Copyright (C) 2003-2006, ZKSoftware Inc.      		
                                                      
********************************************************************/

#ifndef	_JZ4730_H_
#define	_JZ4730_H_

#include <unistd.h>

#define TRUE	1
#define FALSE	0

#define	U8    	unsigned char
#define	U16   	unsigned short
#define	U32   	unsigned int
#define BOOL  	int
#define BYTE  	unsigned char
#define WORD 	unsigned short
#define DWORD	unsigned long
#define LONG	long

#define CONFIG_DEBUG

#ifdef CONFIG_DEBUG
#define DBPRINTF(format, arg...) do { printf(format, ## arg); } while (0)
#else
#define DBPRINTF(format, arg...) 
#endif

#define  AC97_CTL    	 	53   
#define  I2S_CTL		AC97_CTL
#define  RS485_SEND		102
#define  LCDBACkLIGHT		20

#define  IO_GREEN_LED		104
#define  IO_RED_LED		105
#define  IO_LOCK		103
#define  IO_WIEGAND_OUT_D0	100
#define  IO_WIEGAND_OUT_D1	101

#define  WEI_DN			104
#define	 WEI_DP			105
#define  USB_SEL		120
#define	REG8	 volatile unsigned char
#define	REG16	 volatile unsigned short
#define	REG32	 volatile unsigned int
#define	VPchar	 *(REG8 *)
#define	VPshort	 *(REG16 *)
#define	VPint	 *(REG32 *)
#define	Pchar	 (REG8 *)
#define	Pshort	 (REG16 *)
#define	Pint	 (REG32 *)

void CalibrationTimeBaseValue(void);
void DelayUS(int us);
void DelayMS(int ms);
void DelayNS(long ns);

BOOL GPIO_IO_Init(void);
void GPIO_IO_Free(void);
void GPIO_PIN_CTL_SET(int IsWiegandKeyPad, int IsNetSwitch);

void GPIO_AC97_Mute(BOOL Switch);
void GPIO_HY7131_Power(BOOL Switch);
void GPIO_LCD_USB0_Power(BOOL Switch);
void GPIO_RS485_Status(U32 SendMode);
void GPIO_SYS_POWER(void);
void GPIO_WIEGAND_LED(BYTE GPIOPIN, BOOL Light);
void GPIO_KEY_SET(BYTE Value);
int GPIO_KEY_GET(void);

void GPIOSetLevel(BYTE IOPIN, int High);
BOOL GPIOGetLevel(BYTE IOPIN);
BOOL ExCheckGPI(BYTE GPIOPIN);

#endif /* _JZ4730_H_ */

<file_sep>/c/practice/sort/shellsort.c
#include "stdio.h"

void swap(int *a,int *b)
{                            
	int tmp;
	tmp = *a;
	*a = *b;
	*b = tmp;
}

void display(int k[],int n)
{
	int i;

	for(i=0;i<n;i++)                            /*显示原序列之中的元素*/
        printf("%d ",k[i]);
	printf("\n");
}

void shellsort(int k[],int n)
{
	int i, j, flag ,gap = n;

	while(gap > 1)
	{
		gap = gap/2;                /*增量缩小，每次减半*/
		do
		{                        /*子序列应用冒泡排序*/
			flag = 0;
			for(i=0;i<n-gap;i++) //n-gap 是控制上限不让越界
			{
				j = i + gap;	//相邻间隔的前后值进行比较
				if(k[i]>k[j])
				{
					swap(&k[i],&k[j]);
					flag = 1;
				}
			}
			printf("gap = %d:\n",gap);
			display(k,10);
		}while(flag !=0);
	}
}

void shellsort_1(int k[],int n)
{
	int i,flag;

	do
	{                        /*子序列应用冒泡排序*/
		flag = 0;
		for(i=0;i<n-1;i++)
		{
			if(k[i]>k[i+1])	//相邻的前后值进行比较
			{
				swap(&k[i],&k[i+1]);
				flag = 1;
			}
		}
		printf("gap=1:\n");
 		display(k,10);
	}while(flag !=0);
}

int main()
{
    int i,a[10] = {2,5,6,3,7,8,0,9,12,1};            /*初始化序列，a[0]可任意置数*/
    printf("The data array is:\n") ;
    for(i=0;i<10;i++)                            /*显示原序列之中的元素*/
        printf("%d ",a[i]);
	printf("\n\n");
	
    shellsort(a,10);                                /*执行希尔排序*/
   //shellsort_1(a,10);                                /*执行希尔排序*/
   printf("\nThe result of Shell's sorting for the array is:\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);                            /*输出排序后的结果*/
	printf("\n");
	
	return 0;
}

<file_sep>/c/lrc/common.h
#ifndef __COMMON_H__
#define __COMMON_H__

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>


#define  uint   unsigned int
#define  ulint  unsigned long int
#define  uchar  unsigned char

typedef struct lrc
{
	//float time;
	int time;
	char *psrc;
	
	struct lrc *prev;
	struct lrc *next;
}LRC;

#endif<file_sep>/network/route/src/main.c
/******************************************************************************
  文 件 名   : main.c
  版 本 号   : 初稿
  作    者   : 呵呵
  生成日期   : 2015年9月11日
  功能描述   : 主函数
******************************************************************************/
#include "common.h"
#include "route_control.h"
#include "route_pthread.h"



int main(int argc, char *argv[])
{
	TYPE_Route route;       // 定义路由器结构体变量

	route_init(&route);     // 路由器初始化
	create_pthread(&route); // 创建线程

	return 0;
}


<file_sep>/network/route/src/route_firewall.c
/******************************************************************************
  文 件 名   : route_firewall.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 防火墙规则创建和过滤
  函数列表   :
              delete_firewall_rule
              firewall_build_rule
              firewall_filt
              firewall_filt_ip
              firewall_filt_mac
              firewall_filt_port
              firewall_filt_protocol
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"
#include "firewall_link.h"


const char *rules[] = {
	"ip",
	"mac",
	"port",
	"arp",
	"tcp",
	"udp",
	"icmp",
	"igmp",
	"http",
	"tftp",
};

#if 0
/*****************************************************************************
 函 数 名  : firewall_rule_set_help()
 功能描述  : 防火墙规则规则设置帮助
 输入参数  : NULL
 返 回 值  : NULL
 修改日期  : 2015年9月14日
*****************************************************************************/
void firewall_rule_set_help(void)
{
	printf("*************************************************************************\n");
	printf("-               >>>   温馨提示: ()是可选选项  <<<                       *\n");
	printf("-设置 ip 过滤规则，格式:    ip (opt) <ip>   -> ip (src) 192.168.1.1     *\n");
	printf("-设置 mac过滤规则，格式:   mac (opt) <mac>  -> mac (dst) 192.168.1.1    *\n");
	printf("-设置端口过滤规则，格式:  port (opt) <port> -> port (host) 8000         *\n");
	printf("-设置协议过滤规则，格式: <pro> (type) (opt) (type_val) -> udp port 8000 *\n");
	printf("-删除已设置的规则，输入: -d <要删除的规则>                              *\n");
	printf("-查看设置规则帮助，输入: -h                                             *\n");
	printf("-查看已设置的规则，输入: ls                                             *\n");
	printf("-退出防火墙设置，  输入: esc                                            *\n");
	printf("*************************************************************************\n");
}
#endif
/*****************************************************************************
 函 数 名  : firewall_build_rule()
 功能描述  : 建立防火墙规则表
 输入参数  : rt        TYPE_Route 类型结构指针
             rule      待插入的规则
             flag      是否保存到文件标准 1: 保存
 返 回 值  : NULL
 修改日期  : 2015年9月13日
*****************************************************************************/
void firewall_build_rule(TYPE_Route *rt, const char *rule, char flag)
{
	struct _firewall node;

	bzero(node.rule, sizeof(node.rule));
	strcpy(node.rule, rule);

	if(strncmp(rules[0], rule, strlen(rules[0])) == 0){
		rt->ip_head = (FIRE_Wall *)insert_firewall_node(rt->ip_head, node);
	}
	else if(strncmp(rules[1], rule, strlen(rules[1])) == 0){
		rt->mac_head = (FIRE_Wall *)insert_firewall_node(rt->mac_head, node);
	}
	else if(strncmp(rules[2], rule, strlen(rules[2])) == 0){
		rt->port_head = (FIRE_Wall *)insert_firewall_node(rt->port_head, node);
	}
	else{

		int i = 0;
		for(i = 3; i < sizeof(rules)/sizeof(rules[0]); i++)
		{
		   if(strncmp(rules[i], rule, strlen(rules[i])) == 0){
		   	rt->pro_head = (FIRE_Wall *)insert_firewall_node(rt->pro_head, node);
			break;
		   }
		}
	}

	if(flag == 1){
		filrewall_save_rule(rule); //保存规则到文件
	}

}

/*****************************************************************************
 函 数 名  : delete_firewall_rule()
 功能描述  : 删除防火墙规则表
 输入参数  : rt        TYPE_Route 类型结构指针
             rule      待删除的规则
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
void delete_firewall_rule(TYPE_Route *rt, const char *rule)
{
	if(strncmp(rules[0], rule, strlen(rules[0])) == 0){
		rt->ip_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
	}
	else if(strncmp(rules[1], rule, strlen(rules[1])) == 0){
		rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
	}
	else if(strncmp(rules[2], rule, strlen(rules[2])) == 0){
		rt->port_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
	}
	else{

		int i = 0;

		for(i = 3; i < sizeof(rules)/sizeof(rules[0]); i++)
		{
		   if(strncmp(rules[i], rule, strlen(rules[i])) == 0){
			rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, rule);
			break;
		   }
		}
	}
}

/*****************************************************************************
 函 数 名  : firewall_filt_ip()
 功能描述  : 防火墙过滤ip
 输入参数  : rt        TYPE_Route 类型结构指针
             pinfo     MSG_Info 类型结构指针
 返 回 值  : 返回0，说明可以通过ip过滤，返回-1，说明不能通过ip过滤
 修改日期  : 2015年9月13日
*****************************************************************************/
static int firewall_filt_ip(TYPE_Route *rt, MSG_Info *pinfo)
{
	if(rt->ip_head != NULL){

		uchar type[16];
		uchar ip[16];
		uchar src_ip[16] = "";
		uchar dst_ip[16] = "";

		struct _firewall *pnode = NULL;
		pnode = rt->ip_head;

		//提取目的ip
		sprintf(dst_ip,"%d.%d.%d.%d",\
		pinfo->dst_ip[0],pinfo->dst_ip[1],pinfo->dst_ip[2],pinfo->dst_ip[3]);

		//提取源ip
		sprintf(src_ip,"%d.%d.%d.%d",\
		pinfo->src_ip[0],pinfo->src_ip[1],pinfo->src_ip[2],pinfo->src_ip[3]);

		while(pnode != NULL)
		{
			bzero(type, sizeof(type));
			bzero(ip, sizeof(ip));

			sscanf(pnode->rule, "%*s %s %s", type, ip);

			if(strcmp(type, "host") == 0 || strlen(ip) == 0) {

				if(strlen(ip) != 0){
					if(strcmp(src_ip, ip) == 0 || \
					   strcmp(dst_ip, ip) == 0){
						return -1;
					}
				}
				else {
					if(strcmp(src_ip, type) == 0 || \
					   strcmp(dst_ip, type) == 0){
						return -1;
					}
				}
			}
			else if(strcmp(type, "src") == 0) {
				if(strcmp(src_ip, ip) == 0){
					return -1;
				}
			}
			else if(strcmp(type, "dst") == 0) {
				if(strcmp(dst_ip, ip) == 0) {
					return -1;
				}
			}
			else {
				rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->ip_head, pnode->rule);
			}

			pnode = pnode->next;
		}
	}

	return 0;
}

/*****************************************************************************
 函 数 名  : firewall_filt_mac()
 功能描述  : 防火墙过滤mac
 输入参数  : rt        TYPE_Route 类型结构指针
             pinfo     MSG_Info 类型结构指针
 返 回 值  : 返回0，说明可以通过mac过滤，返回-1，说明不能通过mac过滤
 修改日期  : 2015年9月13日
*****************************************************************************/
static int firewall_filt_mac(TYPE_Route *rt, MSG_Info *pinfo)
{
	if(rt->mac_head != NULL){

		uchar type[18];
		uchar mac[18];
		uchar dst_mac[18] = "";
		uchar src_mac[18] = "";

		struct _firewall *pnode = NULL;
		pnode = rt->mac_head;

		//提取目的mac
		sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
			   pinfo->dst_mac[0],pinfo->dst_mac[1],pinfo->dst_mac[2],\
			   pinfo->dst_mac[3],pinfo->dst_mac[4],pinfo->dst_mac[5]);

		//提取源mac
		sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
			pinfo->src_mac[0],pinfo->src_mac[1],pinfo->src_mac[2],\
			pinfo->src_mac[3],pinfo->src_mac[4],pinfo->src_mac[5]);

		while(pnode != NULL)
		{
			bzero(type, sizeof(type));
			bzero(mac, sizeof(mac));

			sscanf(pnode->rule, "%*s %s %s", type, mac);

			if(strcmp(type, "host") == 0 || strlen(mac) == 0) {

				if(strlen(mac) != 0){
					if(strcmp(src_mac, mac) == 0 || \
					   strcmp(src_mac, mac) == 0){
						return -1;
					}
				}
				else {
					if(strcmp(src_mac, type) == 0 || \
					   strcmp(src_mac, type) == 0){
						return -1;
					}
				}
			}
			else if(strcmp(type, "src") == 0) {
				if(strcmp(src_mac, mac) == 0){
					return -1;
				}
			}
			else if(strcmp(type, "dst") == 0) {
				if(strcmp(dst_mac, mac) == 0) {
					return -1;
				}
			}
			else {
				rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->mac_head, pnode->rule);
			}

			pnode = pnode->next;
		}
	}

	return 0;
}

/*****************************************************************************
 函 数 名  : firewall_filt_port()
 功能描述  : 防火墙过滤端口
 输入参数  : rt        TYPE_Route 类型结构指针
             pinfo     MSG_Info 类型结构指针
 返 回 值  : 返回0，说明可以通过端口过滤，返回-1，说明不能通过端口过滤
 修改日期  : 2015年9月13日
*****************************************************************************/
static int firewall_filt_port(TYPE_Route *rt, MSG_Info *pinfo)
{
	if(rt->port_head != NULL){

		uchar type[6];
		uchar port[6];

		uint16 port_val = 0;

		struct _firewall *pnode = NULL;
		pnode = rt->port_head;

		while(pnode != NULL)
		{
			bzero(type, sizeof(type));
			bzero(port, sizeof(port));

			sscanf(pnode->rule, "%*s %s %s", type, port);

			if(strlen(port) != 0)
				port_val = (uint16)atoi(port);
			else
				port_val = (uint16)atoi(type);

			if(strcmp(type, "host") == 0 || strlen(port) == 0) {

				if(port_val == pinfo->s_port || \
				   port_val == pinfo->d_port){
					return -1;
				}
			}
			else if(strcmp(type, "src") == 0) {
				if(port_val == pinfo->s_port){
					return -1;
				}
			}
			else if(strcmp(type, "dst") == 0) {
				if(port_val == pinfo->d_port) {
					return -1;
				}
			}
			else {
				rt->mac_head = (FIRE_Wall *)delete_firewall_node(rt->port_head, pnode->rule);
			}

			pnode = pnode->next;
		}
	}

	return 0;
}

/*****************************************************************************
 函 数 名  : firewall_filt_protocol()
 功能描述  : 防火墙过滤协议类型
 输入参数  : rt        TYPE_Route 类型结构指针
             pinfo     MSG_Info 类型结构指针
 返 回 值  : 返回0，说明可以通过协议过滤，返回-1，说明不能通过协议过滤
 修改日期  : 2015年9月13日
*****************************************************************************/
static int firewall_filt_protocol(TYPE_Route *rt, MSG_Info *pinfo)
{
	if(rt->pro_head != NULL){

		uchar part[4][18];

		struct _firewall *pnode = NULL;
		pnode = rt->pro_head;

		while(pnode != NULL)
		{
			sscanf(pnode->rule, "%s %s %s %s", *(part+0), *(part+1), *(part+2), *(part+3));

			if(strlen(*(part+1)) == 0){

				if(strcmp(*(part+0), "arp") == 0){
					if(pinfo->frame_type == 0x0806){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "icmp") == 0){
					if(pinfo->pro_type == 1){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "igmp") == 0){
					if(pinfo->pro_type == 2){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "tcp") == 0){
					if(pinfo->pro_type == 6){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "udp") == 0){
					if(pinfo->pro_type == 17){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "ftp") == 0){
					if(pinfo->d_port == 21){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "http") == 0){
					if(pinfo->d_port == 80){
						return -1;
					}
				}
				else if(strcmp(*(part+0), "tftp") == 0){
					if(pinfo->d_port == 69){
						return -1;
					}
				}
				else{
					rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
				}
			}

			else {
				if(strcmp(*(part+1), "mac")) {

					uchar dst_mac[18] = "";
					uchar src_mac[18] = "";

					//提取目的mac
					sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
						   pinfo->dst_mac[0],pinfo->dst_mac[1],pinfo->dst_mac[2],\
						   pinfo->dst_mac[3],pinfo->dst_mac[4],pinfo->dst_mac[5]);

					//提取源mac
					sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
						pinfo->src_mac[0],pinfo->src_mac[1],pinfo->src_mac[2],\
						pinfo->src_mac[3],pinfo->src_mac[4],pinfo->src_mac[5]);

					if(strcmp(*(part+2), "host") == 0 || strlen(*(part+3)) == 0) {

						if(strlen(*(part+3)) != 0){
							if(strcmp(src_mac, *(part+3)) == 0 || \
							   strcmp(src_mac, *(part+3)) == 0){
								return -1;
							}
						}
						else {
							if(strcmp(src_mac, *(part+2)) == 0 || \
							   strcmp(src_mac, *(part+2)) == 0){
								return -1;
							}
						}
					}
					else if(strcmp(*(part+2), "src") == 0) {
						if(strcmp(src_mac, *(part+3)) == 0){
							return -1;
						}
					}
					else if(strcmp(*(part+2), "dst") == 0) {
						if(strcmp(dst_mac, *(part+3)) == 0) {
							return -1;
						}
					}
					else {
						rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
					}
				}
				else if(strcmp(*(part+1), "ip")) {

					uchar src_ip[16] = "";
					uchar dst_ip[16] = "";

					//提取目的ip
					sprintf(dst_ip,"%d.%d.%d.%d",\
					pinfo->dst_ip[0],pinfo->dst_ip[1],pinfo->dst_ip[2],pinfo->dst_ip[3]);

					//提取源ip
					sprintf(src_ip,"%d.%d.%d.%d",\
					pinfo->src_ip[0],pinfo->src_ip[1],pinfo->src_ip[2],pinfo->src_ip[3]);

					if(strcmp(*(part+2), "host") == 0 || strlen(*(part+3)) == 0) {

						if(strlen(*(part+3)) != 0){
							if(strcmp(src_ip, *(part+3)) == 0 || \
							   strcmp(dst_ip, *(part+3)) == 0){
								return -1;
							}
						}
						else {
							if(strcmp(src_ip, *(part+2)) == 0 || \
							   strcmp(dst_ip, *(part+2)) == 0){
								return -1;
							}
						}
					}
					else if(strcmp(*(part+2), "src") == 0) {
						if(strcmp(src_ip, *(part+3)) == 0){
							return -1;
						}
					}
					else if(strcmp(*(part+2), "dst") == 0) {
						if(strcmp(dst_ip, *(part+3)) == 0) {
							return -1;
						}
					}
					else {
						rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
					}
				}
				else if(strcmp(*(part+1), "port")) {

					uint16 port_val = 0;
					if(strlen(*(part+3)) != 0)
						port_val = (uint16)atoi(*(part+3));
					else
						port_val = (uint16)atoi(*(part+2));

					if(strcmp(*(part+2), "host") == 0 || strlen(*(part+3)) == 0) {

					if(port_val == pinfo->s_port || \
					   port_val == pinfo->d_port){
						return -1;
						}
					}
					else if(strcmp(*(part+2), "src") == 0) {
						if(port_val == pinfo->s_port){
							return -1;
						}
					}
					else if(strcmp(*(part+2), "dst") == 0) {
						if(port_val == pinfo->d_port) {
							return -1;
						}
					}
					else {
						rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
					}
				}
				else {
					rt->pro_head = (FIRE_Wall *)delete_firewall_node(rt->pro_head, pnode->rule);
				}
			}

			pnode = pnode->next;
		}
	}
}

/*****************************************************************************
 函 数 名  : firewall_filt()
 功能描述  : 防火墙过滤
 输入参数  : rt        TYPE_Route 类型结构指针
             pinfo     MSG_Info 类型结构指针
 返 回 值  : 返回0，说明可以通过ip过滤，返回-1，说明不能通过ip过滤
 修改日期  : 2015年9月13日
*****************************************************************************/
int firewall_filt(TYPE_Route *rt, MSG_Info *pinfo)
{
	int ret = 0;
	rt->eth_hdr = (struct ether_header *)rt->recv;

	memcpy(pinfo->dst_mac, rt->eth_hdr->ether_dhost, ETH_ALEN);
	memcpy(pinfo->src_mac, rt->eth_hdr->ether_shost, ETH_ALEN);

	if(rt->fire_status == UP){
		ret = firewall_filt_mac(rt, pinfo);
		if(ret < 0) return -1;
	}

	pinfo->frame_type = ntohs(rt->eth_hdr->ether_type);

	if(pinfo->frame_type == 0x0800) {
		//recv+14 跳过mac头
		rt->ip_hdr = (struct iphdr *)(rt->recv + 14);

		memcpy(pinfo->src_ip, (uchar *)&rt->ip_hdr->saddr, 4);
		memcpy(pinfo->dst_ip, (uchar *)&rt->ip_hdr->daddr, 4);

		pinfo->pro_type = rt->ip_hdr->protocol;

		switch(pinfo->pro_type)
		{
			case 6:
			{	// rt->ip_hdr->ihl * 4	跳过ip头部
				rt->udp_hdr = (struct udphdr *)(rt->recv + 14 + rt->ip_hdr->ihl * 4);

				pinfo->s_port = ntohs(rt->udp_hdr->source);
				pinfo->d_port = ntohs(rt->udp_hdr->dest);
				break;
			}
			case 17:
			{
				rt->tcp_hdr = (struct tcphdr *)(rt->recv + 14 + rt->ip_hdr->ihl * 4);

				pinfo->s_port = ntohs(rt->tcp_hdr->source);
				pinfo->d_port = ntohs(rt->tcp_hdr->dest);
				break;
			}
		}

		if(rt->fire_status == UP){
			ret = firewall_filt_port(rt, pinfo);
			if(ret < 0) return -1;
		}

	}
	else if(pinfo->frame_type == 0x0806) {
		rt->arp_hdr = (struct _arphdr *)(rt->recv + 14);

		memcpy(pinfo->src_ip, rt->arp_hdr->src_ip, 4);
		memcpy(pinfo->dst_ip, rt->arp_hdr->dst_ip, 4);
	}

	if(rt->fire_status == UP){
		ret = firewall_filt_ip(rt, pinfo);
		if(ret < 0) return -1;

		ret = firewall_filt_protocol(rt, pinfo);
		if(ret < 0) return -1;
	}

	return 0;
}

<file_sep>/work/debug/ingenic/wiegand/wiegand_out.c
/*
 * Copyright (C) 2012 Ingenic Semiconductor Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/miscdevice.h>
#include <linux/spinlock.h>
#include <linux/wakelock.h>
#include <linux/clk.h>
#include <linux/syscalls.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/spinlock.h>
#include <linux/poll.h>
#include <linux/hrtimer.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/wiegand.h>

#ifdef CONFIG_BOARD_4775_ZMM220
#define WIEGANDOUTDRV_LIB_VERSION		"1.0.1 ZMM220"__DATE__	/* DRV LIB VERSION */
#endif

#ifdef CONFIG_BOARD_4775_ZMM210
#define WIEGANDOUTDRV_LIB_VERSION		"1.0.1 ZMM210"__DATE__	/* DRV LIB VERSION */
#endif

#ifdef CONFIG_BOARD_4775_ZMM200
#define WIEGANDOUTDRV_LIB_VERSION		"1.0.1 ZMM200"__DATE__	/* DRV LIB VERSION */
#endif

#ifdef CONFIG_BOARD_X1000_ZLM60
#define WIEGANDOUTDRV_LIB_VERSION		"1.0.1 ZLM60"__DATE__	/* DRV LIB VERSION */
#endif


#define WIEGAND_OUT0_DATA	'0'
#define WIEGAND_OUT1_DATA	'1'

#define PLUSE_WIDTH_STATE	0
#define PLUSE_INTVAL_STATE	1

#define MAX_WIEGAND_DATA_LEN	128

#define DEF_PULSE_WIDTH		100 //us
#define DEF_PULSE_INTERVAL	1000 //us
#define DEF_DATA_LENGTH		26 //bit

struct wiegand_out_dev {
	struct device		*dev;
	struct miscdevice	mdev;
	unsigned int		data0_pin;
	unsigned int		data1_pin;
	unsigned char		wiegand_out_data[MAX_WIEGAND_DATA_LEN];
	int			pos;
	int			data_length;
	int			pulse_width; //us
	int			pulse_intval; //us
	int 			state;
	spinlock_t		lock;
	int			use_count;
	struct hrtimer		timer;
	wait_queue_head_t	wq;
};

static void wiegand_out_data_reset(struct wiegand_out_dev *wiegand_out)
{
	gpio_direction_output(wiegand_out->data0_pin, 1);
	gpio_direction_output(wiegand_out->data1_pin, 1);
}

static void wiegand_out_set_start_state(struct wiegand_out_dev *wiegand_out)
{
	wiegand_out->state = PLUSE_INTVAL_STATE;
}

static void wiegand_out_set_current_state(struct wiegand_out_dev *wiegand_out)
{
	wiegand_out->state = (wiegand_out->state == PLUSE_WIDTH_STATE) ? PLUSE_INTVAL_STATE : PLUSE_WIDTH_STATE;
}

static void wiegand_out_start_pulse_width_timer(struct wiegand_out_dev *wiegand_out)
{
	int us = wiegand_out->pulse_width;
	int s = us / 1000000;
	ktime_t time = ktime_set(s, (us % 1000000) * 1000);
	hrtimer_start(&wiegand_out->timer, time, HRTIMER_MODE_REL);
}

static void wiegand_out_start_pulse_intval_timer(struct wiegand_out_dev *wiegand_out)
{
	int us = wiegand_out->pulse_intval;
	int s = us / 1000000;
	ktime_t time = ktime_set(s, (us % 1000000) * 1000);
	hrtimer_start(&wiegand_out->timer, time, HRTIMER_MODE_REL);
}

static void wiegand_out_start_write(struct wiegand_out_dev *wiegand_out)
{
	wiegand_out->pos = 0;
	wiegand_out_set_start_state(wiegand_out);
	wiegand_out_data_reset(wiegand_out);
	hrtimer_start(&wiegand_out->timer, ktime_set(0, 0), HRTIMER_MODE_REL);
}

static int wiegand_out_check_data(struct wiegand_out_dev *wiegand_out)
{
	int i;

	for (i = 0; i < wiegand_out->data_length; i++) {
		if (wiegand_out->wiegand_out_data[i] != WIEGAND_OUT0_DATA &&
			wiegand_out->wiegand_out_data[i] != WIEGAND_OUT1_DATA)
			return -1;
	}

	return 0;
}

static enum hrtimer_restart wiegand_out_timeout(struct hrtimer *timer)
{
	struct wiegand_out_dev *wiegand_out = container_of(timer, struct wiegand_out_dev, timer);

	wiegand_out_set_current_state(wiegand_out);

	if (wiegand_out->state == PLUSE_WIDTH_STATE) {
		if (wiegand_out->pos == wiegand_out->data_length) {
			if(waitqueue_active(&wiegand_out->wq))
				wake_up_interruptible(&wiegand_out->wq);
			
			return HRTIMER_NORESTART;
		}
		
		if (wiegand_out->wiegand_out_data[wiegand_out->pos] == WIEGAND_OUT0_DATA)
			gpio_direction_output(wiegand_out->data0_pin, 0);
		else
			gpio_direction_output(wiegand_out->data1_pin, 0);
		
		wiegand_out->pos++;
		wiegand_out_start_pulse_width_timer(wiegand_out);
	}
	else {
		gpio_direction_output(wiegand_out->data0_pin, 1);
		gpio_direction_output(wiegand_out->data1_pin, 1);
		wiegand_out_start_pulse_intval_timer(wiegand_out);
	}

	return HRTIMER_NORESTART;
}

static int wiegand_out_open(struct inode *inode, struct file *filp)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);

	spin_lock(&wiegand_out->lock);
	if (wiegand_out->use_count > 0) {
		spin_unlock(&wiegand_out->lock);
		return -EBUSY;
	}
	wiegand_out->use_count++;		
	spin_unlock(&wiegand_out->lock);

	wiegand_out_data_reset(wiegand_out);
	return 0;
}

static int wiegand_out_release(struct inode *inode, struct file *filp)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);

	spin_lock(&wiegand_out->lock);
	wiegand_out->use_count--;		
	spin_unlock(&wiegand_out->lock);

	return 0;
}

static ssize_t wiegand_out_write(struct file *filp, const char __user *buf, size_t size, loff_t *l)
{
	int ret;
	int us;
	int s;
	struct miscdevice *dev = filp->private_data;
	struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);

	if (filp->f_flags & O_NONBLOCK)
		return -EAGAIN;

	if (size > MAX_WIEGAND_DATA_LEN) {
		printk("ERROR: wiegand out data length error, max is %d, please check.\n", MAX_WIEGAND_DATA_LEN);
		return -EFAULT;
	}

	if (copy_from_user(wiegand_out->wiegand_out_data, buf, size))
		return -EFAULT;

	wiegand_out->data_length = size;
	ret = wiegand_out_check_data(wiegand_out);
	if (ret) {
		printk("ERROR: wiegand out data format error, must be '0' or '1', please check.\n");
		return -EFAULT;
	}

	wiegand_out_start_write(wiegand_out);

	us = (wiegand_out->pulse_width + wiegand_out->pulse_intval)
			* wiegand_out->data_length;
	s = us / 1000000;
	ret = interruptible_sleep_on_timeout(&wiegand_out->wq, (s + 2) * HZ);
	if (!ret) {
		printk("wiegand write timeout\n");
		return -EIO;
	}

	return 0;
}

static long wiegand_out_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_out_dev *wiegand_out = container_of(dev, struct wiegand_out_dev, mdev);
	int cs;

	switch (cmd) {
	case WIEGAND_PULSE_WIDTH:
	{
		if(get_user(cs, (unsigned int *)arg))
			return -EINVAL;
		wiegand_out->pulse_width = cs;
		break;
	}

	case WIEGAND_PULSE_INTERVAL:
	{
		if(get_user(cs, (unsigned int *)arg))
			return -EINVAL;
		wiegand_out->pulse_intval = cs;
		break;
	}

	default:
		return -EINVAL;
	}

	return 0;
}

static struct file_operations wiegand_out_misc_fops = {
	.open		= wiegand_out_open,
	.release	= wiegand_out_release,
	.write		= wiegand_out_write,
	.unlocked_ioctl	= wiegand_out_ioctl,
};

static int wiegand_out_probe(struct platform_device *pdev)
{
	int ret = -1;
	struct wiegand_out_dev *wiegand_out;
	struct wiegand_platform_data *pdata;

	printk(" WIEGAND OUT VERSION =  %s  \n",WIEGANDOUTDRV_LIB_VERSION);

	pdata = dev_get_platdata(&pdev->dev);
	if (!pdata) {
		dev_err(&pdev->dev, "Failed to get platform_data %s %d.\n", __FUNCTION__, __LINE__);
		return -ENXIO;
	}

	wiegand_out = kzalloc(sizeof(struct wiegand_out_dev), GFP_KERNEL);
	if (!wiegand_out) {
		printk("%s: alloc mem failed.\n", __FUNCTION__);
		ret = -ENOMEM;
	}
	wiegand_out->data0_pin = pdata->data0_pin;
	wiegand_out->data1_pin = pdata->data1_pin;

	if (gpio_is_valid(wiegand_out->data0_pin)) {
		ret = gpio_request(wiegand_out->data0_pin, "WIEGAND_OUT_DATA0");
		if (ret < 0) {
			printk("ERROR: request wiegand_out_data0 gpio failed.\n");
			goto err_gpio_request0;
		}
	}
	else {
		printk("ERROR: wiegand_out_data0 gpio is invalid.\n");
		goto err_gpio_request0;
	}

	if (gpio_is_valid(wiegand_out->data1_pin)) {
		ret = gpio_request(wiegand_out->data1_pin, "WIEGAND_OUT_DATA1");
		if (ret < 0) {
			printk("ERROR: request wiegand_out_data1 gpio failed.\n");
			goto err_gpio_request1;
		}
	}
	else {
		printk("ERROR: wiegand_out_data1 gpio is invalid.\n");
		goto err_gpio_request1;
	}

	wiegand_out->dev = &pdev->dev;
	wiegand_out->mdev.minor = MISC_DYNAMIC_MINOR;
	wiegand_out->mdev.name =  "dummy";
	wiegand_out->mdev.fops = &wiegand_out_misc_fops;

	wiegand_out_data_reset(wiegand_out);
	wiegand_out->pulse_width = DEF_PULSE_WIDTH;
	wiegand_out->pulse_intval = DEF_PULSE_INTERVAL;
	wiegand_out->data_length = DEF_DATA_LENGTH;

	spin_lock_init(&wiegand_out->lock);
	init_waitqueue_head(&wiegand_out->wq);
	hrtimer_init(&wiegand_out->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
	wiegand_out->timer.function = wiegand_out_timeout;

	ret = misc_register(&wiegand_out->mdev);
	if (ret < 0) {
		dev_err(&pdev->dev, "misc_register failed %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
		goto err_registe_misc;
	}

	platform_set_drvdata(pdev, wiegand_out);
	printk("Weigand out driver register success.\n");

	return 0;

err_registe_misc:
	gpio_free(wiegand_out->data1_pin);
err_gpio_request1:
	gpio_free(wiegand_out->data0_pin);
err_gpio_request0:
	kfree(wiegand_out);
	return ret;
}

static int wiegand_out_remove(struct platform_device *dev)
{
	struct wiegand_out_dev *wiegand_out = platform_get_drvdata(dev);
	misc_deregister(&wiegand_out->mdev);
	gpio_free(wiegand_out->data0_pin);
	gpio_free(wiegand_out->data1_pin);
	kfree(wiegand_out);

	return 0;
}

static struct platform_driver wiegand_out_driver = {
	.probe		= wiegand_out_probe,
	.remove		= wiegand_out_remove,
	.driver		= {
		.name	= "dummy",
	},
};

static int __init wiegand_out_init(void)
{
	return platform_driver_register(&wiegand_out_driver);
}

static void __exit wiegand_out_exit(void)
{
	platform_driver_unregister(&wiegand_out_driver);
}

module_init(wiegand_out_init);
module_exit(wiegand_out_exit);

<file_sep>/sys_program/4th_day/shm.c
/* ************************************************************************
 *       Filename:  shm.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 17时01分32秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <sys/ipc.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <string.h>



int main(int argc, char *argv[])
{
	key_t key;
	char *buf;

	key = ftok("./",66);

	int id = shmget(key,2048,IPC_CREAT | 0666);

	printf("id = %d\n",id);

	buf = (char *)shmat(id,NULL,0);
	bzero(buf,2048);
	strcpy(buf,"I love programming");

	return 0;
}


<file_sep>/work/test/mplay/mplay.c
/*************************************************************************
	> File Name: mplay.c
	> Author:
	> Mail:
	> Created Time: Thu 13 Oct 2016 11:29:59 AM CST
 ************************************************************************/

#include <tinyalsa/asoundlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <linux/input.h>


#define PARENT  SIGUSR1
#define CHILD   SIGUSR2

int exit_flag = 1;
int close_flag = 1;
void play_sample(char *filename, unsigned int device);

/*
 * Functions
 */
void signal_handler(int signo)
{
	switch(signo) {
	case SIGINT:
		printf("recv SIGINT\n");
		close_flag = 1;
		break;

	case SIGCHLD:
		printf("recv SIGCHLD\n");
		waitpid(-1, NULL, WNOHANG); // recycling child process
        exit_flag = 1;
		break;
	}
}

int main(int argc, char *argv[])
{
	pid_t pid = -1;
	int ret = 0;
	int keyfd = 0;
	char *filename = NULL;
	struct input_event event;

	keyfd = open("/dev/input/event0", O_RDONLY);
	if(keyfd < 0) {
		printf("open /dev/input/event0 device failed\n");
		return -1;
	}

	if(argc == 2)
		filename = argv[1];
	else
		filename = "/tmp/paomo.wav";

	//注册父进程 SIGCHLD 信号处理函数，用于非阻塞回收子进程
	//SIGCHLD 将在子进程exit()时发给父进程
	signal(SIGCHLD, signal_handler);

	while(1) {
		bzero(&event, sizeof(struct input_event));
		ret = read(keyfd, &event, sizeof(struct input_event));

		if(ret == sizeof(struct input_event)) {
			if(event.type == EV_KEY) {
				printf("key %d -- %s\n", event.code, !event.value? "Pressed" : "Released");

				if(event.code == KEY_POWER) {
					if(event.value == 0) {
						if(pid != -1) {
							kill(pid, SIGINT);
							pid = -1;
						}

                        if(exit_flag) {
                            pid = fork();
                            if(pid < 0) {
                                perror("fork()");
                                break;
                            }

                            exit_flag = 0; // fork() succeed

                            if(pid == 0) {
                                //close_flag = 0;

                                //注册子进程 SIGINT 信号处理函数
                                //SIGINT 在父进程收到新命令时调用kill(pid, SIGINT)时发出
                                //signal(SIGINT, signal_handler);
                                play_sample(filename, 0);

                                #if 0
                                while(!close_flag) {
                                    printf("child process: wait a common!\n");
                                    sleep(1);
                                }
                                #endif
                                printf("child process %d: exit\n", getpid());
                                exit(0); // child process exit
                            }
                        }
                    }
				}
			}
		}
	}

	close(keyfd);
    return 0;
}
<file_sep>/c/homework/test_typewriting.c
/* ************************************************************************
 *       Filename:  test_typewriting.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月22日 星期三 11時59分14秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>

//#include <windows.h>

#define uint unsigned int
#define LENGHT  40

char mygetch()
{
    struct termios oldt, newt;
    char ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

void show_rule()
{

	printf("\n---------------------\n");
	printf(" 1.按任键开始测试\n");
	printf(" 3.输入屏幕显示字符\n");
	printf(" 4.输入首字母后计时\n");
	printf(" 2.输入过程按Esc退出\n");
	printf(" 5.输入出错以 _ 表示\n");
	printf("----------------------\n");
}
void get_string(char *buf, int n)
{
	char i,ch;

	i = 0;
	srand((uint)time(NULL));
	do
	{
		ch = (char)rand()%128;

		if((ch >= 'a' && ch <= 'z')
	     ||(ch >= 'A' && ch <= 'Z'))
		{
			buf[i] = ch;
			i++;
		}
	}while(i<n);
}

int main()
{
	char i,ch;
	char src[LENGHT],buf[LENGHT];
	int start_time,end_time;
	int count = 0;

	//show_rule();
	//mygetch();
	system("clear");

	while(1)
	{
		show_rule();
		mygetch();

		get_string(src,LENGHT);
		//printf("%s\n",src);
		for(i=0;i<LENGHT;i++)
		{
			printf("%c",src[i]);
		}
		putchar('\n');

		for(i=0;i<LENGHT;i++)
		{
			ch = mygetch();
			if(i == 0)
			{
				start_time = time(NULL);
			}

			if(ch == src[i])
			{
				putchar(ch);
				count++;
			}
			else
			{
				if(ch == 27)
				{
					putchar('\n');
					exit(0);
				}
				putchar('_');
			}
		}
		end_time = time(NULL);
		printf("\n输出完成！\n用时 %ds\n",end_time-start_time);
		printf("正确率%.2f%\n",count/(LENGHT+0.0)*100);
		printf("按Esc键退出，按空格键继续\n");

		getch:
		ch = mygetch();

		switch(ch)
		{
			case ' ': system("clear"); break;
			case  27: exit(0);
			default: goto getch;
		}

	}

	return 0;
}

<file_sep>/sys_program/2nd_day/pm/sighandler.c
/* ************************************************************************
 *       Filename:  sighandler.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 15时48分36秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>

typedef void (* sighandler_t)(int);

void fun1(int signum)
{
	printf("fun1 signal = %d\n",signum);
}

void fun2(int signum)
{
	printf("fun2 signal = %d\n",signum);
}
int main(int argc, char *argv[])
{
	sighandler_t p = NULL;

	p = signal(2,fun1);

	if(p == NULL)
		printf("fun1\n");

	p = signal(2,fun2);

	if(p == fun1)
		printf("fun2\n");

	pause();
	return 0;
}


<file_sep>/network/route/src/print.c
/******************************************************************************
  文 件 名   : print.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 帮助输出
  函数列表   :
              firewall_rule_set_help
              show_help
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"



void show_help(void)
{
	printf("*****************************************************\n");
	printf("-       arp: 查看 ARP 表                            *\n");
	printf("-     clear: 清空屏幕                               *\n");
	printf("-      exit: 关闭路由器                             *\n");
	printf("-      help: 查看帮助信息                           *\n");
	printf("-  ifconfig: 查看网卡信息                           *\n");
	printf("-     reset: 恢复出厂设置                           *\n");
	printf("-   fire on: 开启防火墙                             *\n");
	printf("-  fire off: 关闭防火墙                             *\n");
	printf("-    lsfire: 查看防火墙规则                         *\n");
	printf("-   setfire: 设置防火墙规则                         *\n");
	printf("*****************************************************\n");
}


void firewall_rule_set_help(void)
{
	printf("****************************************************************************\n");
	printf("-                >>>   温馨提示: ()是可选选项  <<<                         *\n");
	printf("-设置 ip 过滤规则，格式:    ip (opt) <ip>   -> ip (src) 192.168.1.1        *\n");
	printf("-设置 mac过滤规则，格式:   mac (opt) <mac>  -> mac (dst) 11:22:33:aa:bb:cc *\n");
	printf("-设置端口过滤规则，格式:  port (opt) <port> -> port (host) 8000            *\n");
	printf("-设置协议过滤规则，格式: <pro> (type) (opt) (type_val) -> udp port 8000    *\n");
	printf("-删除已设置的规则，输入: -d <要删除的规则>                                 *\n");
	printf("-查看设置规则帮助，输入: -h                                                *\n");
	printf("-查看已设置的规则，输入: ls                                                *\n");
	printf("-退出防火墙设置，  输入: esc                                               *\n");
	printf("****************************************************************************\n");
}
<file_sep>/work/shell/envsetup.sh
#!/bin/bash

export WORKPATH=`pwd`
TOP=$WORKPATH
while true;do
	if [ -d $TOP/toolchains ];then
		#echo $TOP
		break
	fi

	if [ x$TOP == x ];then #这里x的作用用于判断$TOP是否为空, if [ X$str = Xabc ], 谨防$str 为空
		echo "no"
		break
	else
		echo "yes"
	fi
	TOP=${TOP%/*}
done

#if [ `uname -m`x = "i686"x ]; then
#	TOOLCHAIN=$TOP/toolchains/mips-gcc472-glibc216-32bit/bin
#else
#	TOOLCHAIN=$TOP/toolchains/mips-gcc472-glibc216/bin
#fi

TOOLCHAIN=$TOP/toolchains/mipsel-gcc472-glibc216-mips32/bin
PATH=$TOOLCHAIN:$PATH
echo "setup PATH=$TOOLCHAIN:\$PATH"

export CROSS_COMPILE='mips-linux-gnu-'


<file_sep>/shell/2nd_week/passwd.sh
#!/bin/bash

IFS.OLD=$IFS

IFS=$'\n'
for entry in `cat /etc/passwd`
do
	echo "value in $entry"
	IFS=:
	for value in $entry
	do
		echo "$value"
	done
done

IFS=$IFS.OLD
<file_sep>/network/route/src/inc/tcp_server.h
/******************************************************************************
  文 件 名   : tcp_server.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月16日
  最近修改   :
  功能描述   : tcp_server.c 的头文件
******************************************************************************/

#ifndef __TCP_SERVER_H__
#define __TCP_SERVER_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */

/*----------------------------------------------*
 * 外部函数原型说明                             *
 *----------------------------------------------*/
extern void tcp_send_arp_table(TYPE_Route *rt, int connfd);
extern void tcp_send_firewall_rules(TYPE_Route *rt, int connfd);
extern void tcp_send_port_info(TYPE_Route *rt, int connfd);
extern void dispose_tcp_cmd(TYPE_Route *rt, int connfd, char cmd[]);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */


#endif /* __TCP_SERVER_H__ */
<file_sep>/work/test/yuv2bmp/yuv2bmp.c
/*************************************************************************
	> Filename: main.c
	>   Author: Qiuwei.wang
	>    Email: <EMAIL> / <EMAIL>
	> Datatime: Time: Tue 27 Sep 2016 11:09:02 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "bmp.h"
#include "srcBuf.h"

/*
 * Macro
 */

#define DEFAULT_WIDTH    640
#define DEFAULT_HEIGHT   480
#define DEFAULT_BPP      16


static const char short_options[] = "b:hx:y:";

static const struct option long_options[] = {
	{ "help",       0,      NULL,           'h' },
	{ "bpp",        1,      NULL,           'b' },
	{ "width",      1,      NULL,           'x' },
	{ "height",     1,      NULL,           'y' },
	{ 0, 0, 0, 0 }
};

/*
 * Functions
 */
static void usage(FILE *fp, int argc, char *argv[])
{
	fprintf(fp,
			 "\nUsage: %s [options]\n"
			 "Options:\n"
			 "-h | --help          Print this message\n"
			 "-b | --bpp           Set image bpp\n"
			 "-x | --width         Set image width\n"
			 "-y | --height        set image height\n"
			 "\n", argv[0]);
}

/*
 * Functions
 */

unsigned int yuv2rgb_pixel(int y, int u, int v)
{
	unsigned int rgb_24 = 0;
	unsigned char *pixel = (unsigned char *)&rgb_24;
	int r, g, b;

	r = y + (1.370705 * (v - 128));
	g = y - (0.698001 * (v - 128)) - (0.337633 * (u - 128));
	b = y + (1.732446 * (u - 128));

	if(r > 255) r = 255;
	if(g > 255) g = 255;
	if(b > 255) b = 255;

	if(r < 0) r = 0;
	if(g < 0) g = 0;
	if(b < 0) b = 0;

	/*
	 * BMP文件内部不压缩图片的格式是BGR
	 */
	pixel[0] = b;
	pixel[1] = g;
	pixel[2] = r;

	return rgb_24;
}

/*
 * YUV422 to RGB
 */
int yuv2rgb(unsigned char *yuv, unsigned char *rgb, unsigned int width, unsigned height)
{
	unsigned int in = 0, out = 0;
	unsigned int pixel_16;
	unsigned char pixel_24[3];
	unsigned int rgb_24;
	unsigned int y0, u, y1, v;

	for(in = 0; in < width * height * 2; in +=4) {
		pixel_16 = yuv[in + 3] << 24 |
				   yuv[in + 2] << 16 |
				   yuv[in + 1] << 8  |
				   yuv[in + 0];
#if 0
		u  = (pixel_16 & 0x000000ff);
		y0 = (pixel_16 & 0x0000ff00) >> 8;
		v  = (pixel_16 & 0x00ff0000) >> 16;
		y1 = (pixel_16 & 0xff000000) >> 24;
#else
		y0 = (pixel_16 & 0x000000ff);
		v  = (pixel_16 & 0x0000ff00) >> 8;
		y1 = (pixel_16 & 0x00ff0000) >> 16;
		u  = (pixel_16 & 0xff000000) >> 24;
#endif

		rgb_24 = yuv2rgb_pixel(y0, u, v);

		pixel_24[0] = (rgb_24 & 0x000000ff);
		pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
		pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;

		rgb[out++] = pixel_24[0];
		rgb[out++] = pixel_24[1];
		rgb[out++] = pixel_24[2];

		rgb_24 = yuv2rgb_pixel(y1, u, v);

		pixel_24[0] = (rgb_24 & 0x000000ff);
		pixel_24[1] = (rgb_24 & 0x0000ff00) >> 8;
		pixel_24[2] = (rgb_24 & 0x00ff0000) >> 16;

		rgb[out++] = pixel_24[0];
		rgb[out++] = pixel_24[1];
		rgb[out++] = pixel_24[2];
	}

	return 0;
}

int writBMPFile(char *filename, unsigned int width, unsigned int height,\
        int iBitCount, unsigned long rgbSize, unsigned char *rgbBuf)
{
    unsigned char *dstBuf = NULL;
    unsigned int i, j, size;

    printf("width = %d, height = %d, rgbSize = %ld\n", width, height, rgbSize);
    printf("sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) = 0x%0x\n", \
            (unsigned int)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)));
    printf("sizeof(BITMAPFILEHEADER) = 0x%02x\n", \
            (unsigned int)sizeof(BITMAPFILEHEADER));
    printf("sizeof(BITMAPINFOHEADER) = 0x%02x\n", \
            (unsigned int)sizeof(BITMAPINFOHEADER));

	if(iBitCount == 24) {
		FILE *fp;
		long count = 0;

		BITMAPFILEHEADER bmpHeader;
		BITMAPINFO bmpInfo;

		if((fp = fopen(filename, "wb")) == NULL) {
			printf("Can not create BMP file: %s\n", filename);
			return -1;
		}

		bmpHeader.bfType = (WORD)(('M' << 8) | 'B');
		bmpHeader.bfSize = rgbSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
		bmpHeader.bfReserved1 = 0;
		bmpHeader.bfReserved2 = 0;
		bmpHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);

		bmpInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
		bmpInfo.bmiHeader.biWidth = width;
		bmpInfo.bmiHeader.biHeight = height;
		bmpInfo.bmiHeader.biPlanes = 1;
		bmpInfo.bmiHeader.biBitCount = iBitCount;
		bmpInfo.bmiHeader.biCompression = 0;
        bmpInfo.bmiHeader.biSizeImage = rgbSize;
		bmpInfo.bmiHeader.biXPelsPerMeter = 0;
		bmpInfo.bmiHeader.biYPelsPerMeter = 0;
		bmpInfo.bmiHeader.biClrUsed = 0;
		bmpInfo.bmiHeader.biClrImportant = 0;

		if((count = fwrite(&bmpHeader, 1, sizeof(BITMAPFILEHEADER), fp))
				!= sizeof(BITMAPFILEHEADER))
			printf("write BMP file header failed: count=%ld\n", count);

		if((count = fwrite(&(bmpInfo.bmiHeader), 1, sizeof(BITMAPINFOHEADER), fp))
				!= sizeof(BITMAPINFOHEADER))
			printf("write BMP file info failed: count=%ld\n", count);

        /* convert rgbbuf */
        dstBuf = (unsigned char *)malloc(rgbSize);
        if(!dstBuf) {
            printf("malloc dstBuf failed !!\n");
            return -1;
        }

        size = width * 3; // line size
        for(i = 0, j = height -1; i < height - 1; i++, j--)
            memcpy((dstBuf + (size * j)), (rgbBuf + (size * i)), size);

		if((count = fwrite(dstBuf, 1, rgbSize, fp)) != rgbSize)
			printf("write BMP file date failed: count=%ld\n", count);

        free(dstBuf);
		fclose(fp);
		return 0;
	} else {
        printf("Err: iBitCount != 24\n");
        return -1;
    }
}

int main(int argc, char *argv[])
{
	unsigned char *rgbBuf = NULL;
    unsigned long rgbSize;
	unsigned int bpp = DEFAULT_BPP;
	unsigned int width = DEFAULT_WIDTH;
	unsigned int height = DEFAULT_HEIGHT;

	while(1) {
		int oc;

		oc = getopt_long(argc, argv, \
						 short_options, long_options, \
						 NULL);
		if(-1 == oc)
			break;

		switch(oc) {
		case 0:
			break;

		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);
			break;

		case 'b':
			bpp = atoi(optarg);
			break;

		case 'x':
			width = atoi(optarg);
			break;

		case 'y':
			height = atoi(optarg);
			break;

		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
			break;
		}
	}

#if 0
    printf("sizeof(unsigned long) = %ld\n", sizeof(unsigned long));
    printf("sizeof(long) = %ld\n", sizeof(long));
    printf("sizeof(int) = %ld\n", sizeof(int));
    printf("sizeof(unsigned short) = %ld\n", sizeof(unsigned short));
#endif

    rgbSize = width * height * 3;

	rgbBuf = (unsigned char *)malloc(rgbSize);
    if(!rgbBuf) {
        printf("malloc rgbBuf failed !!\n");
        return -1;
    }

	yuv2rgb(srcBuf, rgbBuf, width, height);
	writBMPFile("./image/test.bmp", width, height, 24, rgbSize, rgbBuf);
    free(rgbBuf);

    return 0;
}
<file_sep>/c/homework/3rd_week/message/msg.c
#include <stdio.h>
#include <string.h>
#include "msg.h"

void show_number(const char *src)
{
	printf("from: %s\n",src+3);
}

void show_time( char *src1,char *src2)
{
	int i = 0;
	char *pbuf[3] = {NULL};
	char *p = NULL;
	int time[3];
	
	pbuf[0] = strtok(src1,"/");
	
	while(pbuf[i++] != NULL)
	{
		pbuf[i] = strtok(NULL,"/");
	} 	
	
	if(atoi(pbuf[0])>15)
	{
		time[0] = 1900+ atoi(pbuf[0]);
	}
	else
	{
		time[0] = 2000+ atoi(pbuf[0]);
	}
	time[1] = atoi(pbuf[1]);
	time[2] = atoi(pbuf[2]);
	
	printf("date: %d年%d月%d日  ",time[0],time[1],time[2]);
	p = strchr(src2,'+');
	*p = '\0';
	printf("%s\n",src2);
}

void show_content(const char *src)
{
	printf("content: %s\n",src);
}

void show_message(char **src)
{
	show_number(src[1]);
	show_time(src[2],src[3]);
	show_content(src[4]);
}

int msg_deal(char *msg_src, char *msg_done[],char *str)
{
	int i = 0;
	
	msg_done[0] = strtok(msg_src,str);
	
	while(msg_done[i++] != NULL)
	{
		msg_done[i] = strtok(NULL,str);
	} 
	
	return i;
}
<file_sep>/work/shell/smk.sh
#!/bin/bash
#
# Copyright (C) 2016 Ingenic Semiconductor, Inc.
# <NAME> <<EMAIL>, <EMAIL>>

#
# Build config seting
if [ "nand" = "$1" ]; then
UBOOT_BUILD_CONFIG=halley2_v20_zImage_sfc_nand
KERNEL_BUILD_CONFIG=halley2_v20_sfc_nand_defconfig
MOZART_BUILD_CONFIG=halley2_v2.0_43438_ubifs_config
MOZART_TARGET_FILE="appfs.img  updater.img  nv.img"
else
UBOOT_BUILD_CONFIG=halley2_v10_zImage_sfc_nor_config
KERNEL_BUILD_CONFIG=halley2_v10_nor_oss_defconfig
MOZART_BUILD_CONFIG=halley2_v2.0_43438_cramfs_config
MOZART_TARGET_FILE="appfs.cramfs  updater.cramfs  usrdata.jffs2  nv.img"
fi

UBOOT_TARGET_FILE=u-boot-with-spl.bin
KERNEL_IMAGE_PATH=arch/mips/boot/compressed
KERNEL_TARGET_FILE=zImage
MOZART_IMAGE_PATH=output/target

#
# Multithread compiling
MP=8

echoc()
{
    echo -e "\e[0;91m$1\e[0m"
}

usage()
{
    echoc "---------------------------------------------------------------------------"
    echo "\
    usage:
      smk [OPTIONS]
        used to quickly compile the mozart
        support invoke from any location
        image output directory: $OUTPUT_DIR

      OPTIONS:
        -a | --all        ---> make all
        -u | --uboot      ---> make uboot
        -k | --kernel     ---> make kernel
        -m | --mozart     ---> make mozart
        -c | --clean      ---> distclean uboot、kernel、mozart, or all
        -j | --jobs       ---> set multithread compiling
        -s | --setupinfo  ---> get setup informations
        -h | --help       ---> get help message

      eg:
        smk -m       ---> will make mozart
        smk -u -k    ---> will make uboot and kernel
        smk -j 8     ---> will set number of jobs to -j8
        smk -c k     ---> will distclean kernel
        smk -c       ---> will distclean all, include the \$OUTPUT_DIR"
    echoc "---------------------------------------------------------------------------"
    return 0
}

setupinfo()
{
    echoc "---------- smk envsetup ---------------------------------------------------"
    echo " SOURCE_DIR = $SOURCE_DIR"
    echo " TOOLCHAINS = $TOOLCHAINS"
    echo "MKIMAGE_DIR = $MKIMAGE_DIR"
    echo " OUTPUT_DIR = $OUTPUT_DIR"
    echo "export PATH = \$TOOLCHAINS:\$MKIMAGE_DIR:\$PATH"
    echo ""
    echo " UBOOT_BUILD_CONFIG = $UBOOT_BUILD_CONFIG"
    echo "KERNEL_BUILD_CONFIG = $KERNEL_BUILD_CONFIG"
    echo "MOZART_BUILD_CONFIG = $MOZART_BUILD_CONFIG"
    echo ""
    echo " UBOOT_TARGET_FILE = $UBOOT_TARGET_FILE"
    echo "KERNEL_TARGET_FILE = $KERNEL_TARGET_FILE"
    echo "MOZART_TARGET_FILE = $MOZART_TARGET_FILE"
    echoc "---------- If need help: smk -h -------------------------------------------"
}

envsetup()
{
    local dir=$(pwd)
    SOURCE_DIR=$dir

    while true; do
        if [ -d $SOURCE_DIR/mozart -a \
             -d $SOURCE_DIR/u-boot -a \
             -d $SOURCE_DIR/kernel* ]; then
            break
        fi

        if [ x$SOURCE_DIR == x ]; then
            echoc "Error, please read tools/README"
            return -1;
        fi
        SOURCE_DIR=${SOURCE_DIR%/*}
    done

    OUTPUT_DIR=$SOURCE_DIR/out
    MKIMAGE_DIR=$SOURCE_DIR/u-boot/tools
    TOOLCHAINS=$SOURCE_DIR/tools/toolchains/mipsel-gcc472-glibc216-mips32/bin

    if [ -d $TOOLCHAINS ]; then
        export PATH=$TOOLCHAINS:$PATH;
    else
        echoc "TOOLCHAINS is not exist! Please read tools/README"
        return -1
    fi

    if [ -d $MKIMAGE_DIR ]; then
        export PATH=$MKIMAGE_DIR:$PATH
    fi

    if [ ! -d $OUTPUT_DIR ]; then
        mkdir -p $OUTPUT_DIR
        if [ $? -ne 0 ]; then
            echoc "Create $OUTPUT_DIR failed, set OUTPUT_DIR=\$SOURCE_DIR"
            OUTPUT_DIR=$SOURCE_DIR
        fi
    fi

    setupinfo
}
declare -f croot > /dev/null || envsetup

make_uboot()
{
    echoc "\nsmk: compiling u-boot ..."
    cd $SOURCE_DIR/u-boot

    make $UBOOT_BUILD_CONFIG && make -j$MP

    if [ $? -eq 0 ]; then
        cp $UBOOT_TARGET_FILE $OUTPUT_DIR
    else
        echoc "Failed to compile uboot, try 'smk -c u', then 'smk -u'"
        return -1
    fi

    return 0
}

make_kernel()
{
    echoc "\nsmk: compiling kernel ..."
    cd $SOURCE_DIR/kernel*

    make $KERNEL_BUILD_CONFIG && make $KERNEL_TARGET_FILE -j$MP

    if [ $? -eq 0 ]; then
        cp $KERNEL_IMAGE_PATH/$KERNEL_TARGET_FILE $OUTPUT_DIR
    else
        echoc "Failed to compile kernel, try 'smk -c k', then 'smk -k'"
        return -1
    fi

    return 0;
}

make_mozart()
{
    echoc "\nsmk: compiling mozart ..."
    cd $SOURCE_DIR/mozart

    make $MOZART_BUILD_CONFIG && make

    if [ $? -eq 0 ]; then
        cd $MOZART_IMAGE_PATH
        cp $MOZART_TARGET_FILE $OUTPUT_DIR
    else
        echoc "Failed to compile mozart, try 'smk -c m', then 'smk -m'"
        return -1
    fi

    return 0
}

make_clean()
{
    case "$1" in
    u | uboot)
        echoc "smk: clean uboot ..."
        cd $SOURCE_DIR/u-boot && make distclean
        ;;
    k | kernel)
        echoc "smk: clean kernel ..."
        cd $SOURCE_DIR/kernel* && make distclean
        ;;
    m | mozart)
        echoc "smk: clean mozart ..."
        cd $SOURCE_DIR/mozart && make distclean
        ;;
    all|*)
        echoc "smk: clean all ..."

        if [ -d $OUTPUT_DIR -a $OUTPUT_DIR != $SOURCE_DIR ]; then
        rm $OUTPUT_DIR -rf
        fi

        cd $SOURCE_DIR/u-boot && make distclean
        cd $SOURCE_DIR/kernel* && make distclean
        cd $SOURCE_DIR/mozart && make distclean
        break
        ;;
    esac

    return 0
}

set_jobs()
{
    case "$1" in
    [1-9][0-9] | [1-9])
        MP=$1
        echoc "smk: set MP=$MP"
        ;;
    *)
        echoc "Invalid param, eg: smk -j 8"
        return -1
        ;;
    esac

    return 0
}

smk()
{
    local dir=$(pwd)

    if [ $# -eq 0 ]; then
        usage
        return $?
    fi

    if [ ! -d $OUTPUT_DIR ]; then
        mkdir -p $OUTPUT_DIR
        if [ $? -ne 0 ]; then
            echoc "Create $OUTPUT_DIR failed, set OUTPUT_DIR=\$SOURCE_DIR"
            OUTPUT_DIR=$SOURCE_DIR
        fi
    fi

    while [ $# -gt 0 ]
    do
        case $1 in
        -a | --all)
            echoc "smk: compiling all ..."
            make_uboot && make_kernel && make_mozart
            break
            ;;

        -k | --kernel)
            make_kernel || break
            ;;

        -u | --uboot)
            make_uboot || break
            ;;

        -m | --mozart)
            make_mozart || break
            ;;

        -c | --clean)
            shift
            make_clean $1
            break
            ;;

        -j | --jobs)
            shift
            set_jobs $1
            return $?
            ;;

        -s | --setupinfo)
            setupinfo
            return $?
            ;;

        -h | --help)
            usage
            return $?
            ;;

        *)
            echoc "Invalid option '$1', if need help: smk -h"
            return -1
            ;;
        esac
        shift
    done

    cd $dir
    echoc "smk: done !!!"
    return 0
}

# auto complete
_smk()
{
    local cur=${COMP_WORDS[COMP_CWORD]}
    local prev=${COMP_WORDS[COMP_CWORD-1]}
    local penult=${COMP_WORDS[COMP_CWORD-2]}

    [[ "$cur" == "" && "$prev" == "=" ]] && return 0


    local flag_preset="no"
    local flag_separate="no"
    local full_args="--jobs --all --uboot --kernel --mozart --clean --setupinfo --help"

    if [[ "$cur" == * ]]; then
        if (( $COMP_CWORD == 1 )); then
            COMPREPLY=( $( compgen -W "$full_args" -- $cur ) )
        else
            for i in "${COMP_WORDS[@]}"
            do
                [ "$i" == "$cur" ] && break
                case "$i" in
                --all|--clean|--help|--setupinfo|-j) return ;;
                --uboot) flag_separate="yes"; full_args=`echo "$full_args" | sed "s/--uboot//g"` ;;
                --kernel) flag_separate="yes"; full_args=`echo "$full_args" | sed "s/--kernel//g"` ;;
                --mozart) flag_separate="yes"; full_args=`echo "$full_args" | sed "s/--mozart//g"` ;;
                esac
            done
            COMPREPLY=( $( compgen -W "$full_args" -- $cur ) )
        fi
    fi
    return 0
}

complete -F _smk smk
<file_sep>/network/2nd_day/tftp_server.c
/* ************************************************************************
 *       Filename:  tftp_server.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月02日 10时09分55秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

int main(int argc, char *argv[])
{

	return 0;
}



<file_sep>/c/practice/3rd_week/mylink/main.c
#include <stdio.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include "link.h"

#define MAX  6  //队列大小


char mygetch() 
{
    struct termios oldt, newt;
    char ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

void help()
{
	system("clear");
	printf("-----------------------------------\n");
	printf("->help  : 帮助信息                -\n");
	printf("->insert: 插入一个新节点          -\n");
	printf("->print : 遍历整个链表            -\n");
	printf("->search: 查询某个节点            -\n");
	printf("->delete: 查删除某个节点          -\n");
	printf("->free  : 释放整个节点            -\n");
	printf("->sort  : 将链表排序              -\n");
	printf("->invert: 倒置整个链表            -\n");
	printf("->exit  : 退出                    -\n");
	printf("-----------------------------------\n");
}

int main(int argc,char *argv[])
{
	char cmd[128] = "";
	int count = 0;
	STU *head = NULL;
	
	system("clear");
	help();
	while(1)
	{
		printf("cmd: ");
		fflush(stdout);
		scanf("%s",cmd);
		
		if(strcmp(cmd,"help")==0)
		{
			help();
		}
		else if(strcmp(cmd,"insert")==0)
		{
			int num;
			char ch, temp[48];
			STU new;
			
			while(1)
			{
				printf("please input the num, name, score: ");
				//scanf("%d %s %d",&new.num,new.name,&new.score);
				fscanf(stdin,"%d %s %d",&new.num,new.name,&new.score);
				gets(temp);

				if(new.num != num)
				{
					if(count < MAX)
					{
						head = insert_link(head, new);
						count++;
					}
					else
					{
						head = delete_head(head);
						head = insert_link(head, new);
					}
					num = new.num;
					if(head != NULL) //成功插入新节点
					{
						printf("按任意键继续，按‘Esc'结束\n");
						ch = mygetch();
					
						if(ch == 27)//Esc 键的ASCII 码为27
						{
							printf("结束插入！\n");
							break;
						} 
					}
				}
				else
				{
					printf("\n输入无效！\n");
				}
			}
		}
		else if(strcmp(cmd,"print")==0)
		{
			printf("-----print-----\n");
			print_link(head);		
		}
		else if(strcmp(cmd,"search")==0)
		{
			char name[64] = "";
			STU *ret;
			printf("please input search name\n");	
			scanf("%s",name);
			
			ret = search_link(head, name);
			
			if(ret == NULL)
			{
				printf("not found\n");
			}
			else
			{
				printf("num: %-4d name:%-8s score: %-3d\n",ret->num,ret->name,ret->score);
			}
		}
		else if(strcmp(cmd,"delete")==0)
		{
			int num = 0;
			printf("Please input delete num\n");
			scanf("%d",&num);
			head = delete_link(head,num);	
			count--;
			if(count < 0) count = 0;
		}
		else if(strcmp(cmd,"free")==0)
		{
			printf("-----free link-----\n");	
			head = free_link(head);
		}
		else if(strcmp(cmd,"sort")==0)
		{
			printf("-----sort link from score-----\n");	
			sort_link(head);
			print_link(head);
		}
		else if(strcmp(cmd,"invert")==0)
		{
			printf("-----invert link-----\n");	
			head = invert_link(head);
			print_link(head);
		}
		else if(strcmp(cmd,"exit")==0)
		{
			printf("----- exit -----\n");	

			if(head != NULL)
			{
				head = free_link(head);
			}
			break;
		}
		else
		{
			printf("命令不存在！需要帮助，请输入“help”\n");
		}
	}
	return 0;
}
<file_sep>/work/debug/2440/leds/Makefile
ifneq ($(KERNELRELEASE),)
	obj-m := leds_drv.o

else
#	KERNELDIR ?= /lib/modules/$(shell uname -r)/build
	KERNELDIR ?= ~/micro2440/linux/linux-2.6.32.2
	PWD := $(shell pwd)
default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
	rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
	rm -f *.o *~ *.ko  *.mod.c *.mod.o *.symvers *.order
endif

mod:
	sudo insmod ./leds_dev.ko

mt:
	gcc -o test test_leds.c

.PHONY:clc
clc:
	rm test


<file_sep>/work/test/cim_test-zmm220/camera.c
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <time.h>
#include <sys/time.h>
#include <signal.h>
#include "arca.h"
#include "sensor.h"
#include "cim.h"
#include "futil.h"
#include "mt9v136.h"
//#include "mt9v136old62.h"

#define 	IMAGESIZE		(640*480)
#define 	RGB565CUT		(640*480)
#define 	YUVSIZE			(640*480*2)
#define 	RGB24			(640*480)//(320*240*3)
#define 	YUVCUT			(640*240*3)

#define 	PIN 	(1*32+29) //(3*32+2)

#define 	TEST	1

#define    GC0308   1
#define    MT367    2

#if TEST
#define  LCD_DEV	"/dev/fb0"
static int lcd_fd = -1;
static unsigned int fb_width;
static unsigned int fb_height;
static unsigned int fb_depth;
static unsigned int screensize;
static unsigned char *fbmem;
#endif

extern void*fb_mmap(int fd, unsigned int screensize);


int init_camera_gc0308(int width,int height,int bpp)
{
	int ret=0;
	TIMING_PARAM t;
	ret=cim_open(GC0308,width, height, bpp);
	if(ret<0){
		printf(" cim open fail \n ");
		return -1;
	}
	ret = sensor_open_0308();
	if(ret < 0) {
		printf("Open sensor fail!!\n");
		return -1;
	}
	gc0308_init();

	t.mclk_freq = 24000000;
	t.pclk_active_direction = 1;
	t.hsync_active_level = 1;
	t.vsync_active_level = 1;
	
	ret = set_timing_param(GC0308,&t);
	if(ret == 0) {
		printf("set_timing_param fail!!\n");
		return -1;
	}
	printf("Set mclk to %dHz.\n", t.mclk_freq);

	sensor_close_0308();

	printf("GC0308 Init finish!\n");
	return 0;
}

int init_camera_mi367(int width,int height,int bpp)
{	
	int ret = -1;
	TIMING_PARAM t;
	ret=cim_open(MT367,width, height, 16);
	if(ret<0){
		printf("  %s  fail \n ",__func__);
		return -1;
	}	
	ret = sensor_open_mi367();
	if(ret < 0) {
		printf("Open sensor fail!!\n");
		return -1;
	}

	InitMT9V136(width,height,mt9v117regs1);
	InitMT9V136(width,height,wieght_table);

	t.mclk_freq = 48000000;
	t.pclk_active_direction = 0;
	t.hsync_active_level = 1;
	t.vsync_active_level = 0;
	
	set_timing_param(MT367,&t);
	if(ret == 0) {
		printf("set_timing_param fail!!\n");
		return -1;
	}
	printf("Set mclk to %dHz.\n", t.mclk_freq);

	sensor_close_mi367();

	printf("MI367 Init finish!\n");
	
	return 0;
}


int initcamera(unsigned char sensor,int width,int height,int bpp)
{
	int ret = -1 ;
	switch(sensor)
	{
		case GC0308:
			ret = init_camera_gc0308(width,height,bpp);
			
		break;
		
		case  MT367:
			ret = init_camera_mi367(width,height,bpp);
			
		break;
		
	   default:
			printf(" NOT SUPPORT SENSOR \n");
			ret = -1;
		break;
	}
	
	return ret;
}

void close_camera(int id)
{
	cim_close(id);
}

int saveImage(int quality,int width,int height,const char *path, unsigned char *yuv422buf)
{
	int i;
	unsigned char *pframebuf;
	unsigned char *yuv_data[3];
#if TEST
	pframebuf = (unsigned char *)yuv422buf;
	yuv_data[0] = pframebuf;
	yuv_data[2] = pframebuf + width*height;
	yuv_data[1] = pframebuf + width*height*3/2;
	write_JPEG_file(path,quality,width,height,yuv_data);
#endif
	return 0;
}

int grab_image(unsigned int id,int width,int height,unsigned char *buf)
{
	return cim_read(id,buf, width * height * 2);
}


#if TEST
int openlcd(void)
{
	lcd_fd = fb_open(LCD_DEV);
	if(lcd_fd<0)
	{
		printf("open /dev/fb0 fail!!\n");
		return -1;
	}
	printf("openlcd ok lcd_fd =%d\n",lcd_fd);
	fb_stat(lcd_fd,&fb_width,&fb_height,&fb_depth);
	printf("fb: w = %d h = %d depth = %d\n", fb_width, fb_height, fb_depth);
	screensize = fb_width * fb_height *fb_depth/8;
	fbmem = fb_mmap(lcd_fd,screensize);
	if (!fbmem)
	{
		printf("fb_mmap failed!\n");
		return -1;
	}
	return 0;
}

int closelcd(void)
{
	//fb_munmap(fbmem,screensize);
	fb_close(LCD_DEV);
	return 0;
}
#if 0
int fb_pixelAsRow(void *fbmem, int width_cut, int height_cut, int x, int y, unsigned int *rowbuf, int bufsize)
{
    	unsigned int *dst = ((unsigned int *) fbmem + y * width_cut + x);
	memcpy(dst, rowbuf, bufsize);
    	return (0);
}

int displayx(int width, int height,unsigned int width_cut,unsigned int height_cut,unsigned int *rgb888)
{
	unsigned int x,y,k=0;
	for(y = 0; y < height_cut; y++)
	{
		fb_pixelAsRow(fbmem,width_cut,height_cut,0,y,rgb888+y*width,width *4);
	}
}
#endif
#if 1


int displayx(int ox, int oy,unsigned int width_cut,unsigned int height_cut,unsigned short *rgb565cut)
{
	unsigned int x,y,k=0;
	for(y = 0; y < height_cut; y++)
	{
		fb_pixelAsRow(fbmem,fb_width,fb_height,0,y,rgb565cut+y*width_cut,width_cut *2);
	}
}

#endif


#endif

#if TEST
/****************************************************************************************

	flag =  0  save bmp  
	flag =  1  save jpeg
	flag =  2  display to lcd
	
*******************************************************************************************/
int sensor_0308_handle(int width, int higth, unsigned char *yuv422buf,unsigned short *rgb565,int flag)
{
	grab_image(GC0308,width,higth,(unsigned char *)rgb565);
}

/****
	flag =  0  save bmp  
	flag =  1  save jpeg
	flag =  2  display to lcd
****/

int sensor_367_handle(int width, int higth, unsigned char *yuv422buf,unsigned short *rgb565,int flag)
{
	if(grab_image(MT367,width,higth,yuv422buf)>0)
		yuv422rgb565(yuv422buf,rgb565,width,higth);		
}

#define USEGV0308	1
#define USEMI367	0
#define ROTATE		1
int main(int argc,char *argv[])
{
	int ret;
	int width_out, height_out;
	unsigned short *rgb565_0308buf = NULL;
	unsigned char *yuv422_367buf   =NULL;
	unsigned short *rgb565_out=NULL;
	unsigned short *rgb565_367buf=NULL;

	openlcd();	

	int flag=2;

#if USEGV0308
	ret = init_camera_gc0308(640,480,16);
	if (ret) {
		printf("init_camera_gc0308 failed!\n");
		return -1;
	}

	//rgb565_0308buf = cim_mmap(GC0308,640*480*2);
	rgb565_0308buf = malloc(640*480*2);
	if (!rgb565_0308buf) {
		printf("cim_mmap 0308 failed!\n");
		return -1;
	}
#endif

#if USEMI367
	ret = init_camera_mi367(640,480,16);
	if (ret) {
		printf("init_camera_mi367!\n");
		return -1;
	}

	//yuv422_367buf = cim_mmap(MT367,640*480*2);
	yuv422_367buf = malloc(640*480*2);
	if (!yuv422_367buf) {
		printf("cim_mmap 367 buf  failed!\n");
		return -1;
	}

	rgb565_367buf = (unsigned short *)malloc(RGB565CUT);
	if (!rgb565_367buf) {
		printf("malloc failed %s %d\n", __func__, __LINE__);
		return -1;
	}
#endif

#if ROTATE
	rgb565_out = (unsigned short *)malloc(2 * RGB565CUT);
	if (!rgb565_out) {
		printf("malloc failed %s %d\n", __func__, __LINE__);
		return -1;
	}
#endif

	while(1)
	{
#if USEGV0308
		sensor_0308_handle(640,480,NULL,rgb565_0308buf,flag);
#endif
#if USEMI367
		sensor_367_handle(640,480,yuv422_367buf,rgb565_367buf,flag);
#endif
#if ROTATE
		rgb565_rotate90(rgb565_0308buf, 640, 480, rgb565_out, &width_out, &height_out);
		displayx(0, 0, width_out, height_out, rgb565_out);
#else
		displayx(0, 0, 640, 480, rgb565_0308buf);
#endif
	}
#if USEGV0308
	close_camera(GC0308);
#endif
#if USEMI367
	close_camera(MT367);
#endif
	closelcd();
	if (rgb565_out)
		free(rgb565_out);
	if (rgb565_367buf)
		free(rgb565_367buf);
	return 0;
}

#endif  //endif test
<file_sep>/gtk/4st_week/gtk_vbox.c
/* ************************************************************************
 *       Filename:  gtk_hbox.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 11时34分43秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <gtk/gtk.h>


int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	g_signal_connect(window,"destroy", G_CALLBACK(gtk_main_quit),NULL);

	//创建一个垂直容器
	GtkWidget *vbox = gtk_vbox_new(TRUE,10);

	//添加到window
	gtk_container_add(GTK_CONTAINER(window),vbox);

	GtkWidget *button1 = gtk_button_new_with_label("button1");
	//添加button1到hbox
	gtk_container_add(GTK_CONTAINER(vbox),button1);

	GtkWidget *button2 = gtk_button_new_with_label("button2");
	//添加button1到hbox
	gtk_container_add(GTK_CONTAINER(vbox),button2);

	GtkWidget *button3 = gtk_button_new_with_label("button3");
	//添加button1到hbox
	gtk_container_add(GTK_CONTAINER(vbox),button3);

	gtk_widget_show_all(window);

	gtk_main();

	return 0;
}



<file_sep>/network/sockets/TCPEchoClient.c
/*************************************************************************
	> File Name: TCPEchoClient.c
	> Author: 
	> Mail: 
	> Created Time: Fri 06 May 2016 11:12:30 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Practical.h"

int main(int argc, char *argv[])
{
    if(argc < 3 || argc > 4) //Test for correct number of arguments
        DieWithUserMessage("Paramter(s)", "<Server Address/Name> <Echo Word> [<Server Port/Service]");

    char *server = argv[1];  //First arg: server address/name
    char *echoString = argv[2]; //Second arg: string to echo
    char *service = (argc == 4)?argv[3]:"echo"; //Third arg (optional): server port/service


    //Create a connected TCP socket
    int sock  = SetupTCPClientSocket(server, service);
    if(sock < 0)
        DieWithUserMessage("SetupTCPClientSocket() failed","unable to connect");

    size_t echoStringLen = strlen(echoString);
    
    //Send the string to the server
    ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
    if(numBytes < 0)
        DieWithSystemMessage("send() failed");
    else if(numBytes != echoStringLen)
        DieWithUserMessage("send()", "sent unexpected number of bytes");

    //Recevice the same string back from the server
    unsigned int totalBytesRcvd = 0; //Count of total bytes receviced
    fputs("Receviced: ", stdout);
    while(totalBytesRcvd < echoStringLen) {
        char buffer[BUFSIZE];
        numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
        if(numBytes < 0)
            DieWithSystemMessage("recv() failed");
        else if(numBytes == 0)
            DieWithUserMessage("recv()", "connection closed prematurely");

        totalBytesRcvd += numBytes; //Keep tally of total bytes
        buffer[numBytes] = 0;       //Terminate the string
        fputs(buffer, stdout);      //Print the buffer
    }

    fputc('\n',stdout);
    close(sock);
    exit(0);
}
<file_sep>/work/test/v4l2/main.c
/*************************************************************************
	> Filename: main.c
	>   Author: Qiuwei.wang
	>    Email: <EMAIL> / <EMAIL>
	> Datatime: Fri 02 Dec 2016 10:54:24 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

#include "common.h"
#include "capture.h"

/*
 * Macro
 */
#define DEFAULT_DEVICE   "/dev/video0"
#define DEFAULT_WIDTH    640
#define DEFAULT_HEIGHT   480
#define DEFAULT_BPP      16
#define DEFAULT_NBUF     1


static const char short_options[] = "d:hmn:rux:y:";

static const struct option long_options[] = {
	{ "device",     1,      NULL,           'd' },
	{ "help",       0,      NULL,           'h' },
	{ "mmap",       0,      NULL,           'm' },
	{ "nbuf",       1,      NULL,           'n' },
	{ "read",       0,      NULL,           'r' },
	{ "userp",      0,      NULL,           'u' },
	{ "width",      1,      NULL,           'x' },
	{ "height",     1,      NULL,           'y' },
	{ 0, 0, 0, 0 }
};

/*
 * Functions
 */
static void usage(FILE *fp, int argc, char *argv[])
{
	fprintf(fp,
			 "\nUsage: %s [options]\n"
			 "Options:\n"
			 "-d | --device name   Video device name [/dev/video]\n"
			 "-h | --help          Print this message\n"
			 "-m | --mmap          Use memory mapped buffers\n"
			 "-n | --nbuf          Request buffer numbers\n"
			 "-r | --read          Use read() calls\n"
			 "-u | --userp         Use application allocated buffers\n"
			 "-x | --width         Capture width\n"
			 "-y | --height        Capture height\n"
			 "\n", argv[0]);
}

int main(int argc, char *argv[])
{
	struct capture_t capt;

	capt.dev_name = DEFAULT_DEVICE;
	capt.width    = DEFAULT_WIDTH;
	capt.height   = DEFAULT_HEIGHT;
	capt.bpp      = DEFAULT_BPP;
	capt.nbuf     = DEFAULT_NBUF;
	capt.io       = IO_METHOD_MMAP;

	while(1) {
		int oc;

		oc = getopt_long(argc, argv, \
						 short_options, long_options, \
						 NULL);
		if(-1 == oc)
			break;

		switch(oc) {
		case 0:
			break;

		case 'd':
			capt.dev_name = optarg;
			break;

		case 'h':
			usage(stdout, argc, argv);
			exit(EXIT_SUCCESS);
			break;

		case 'm':
			capt.io = IO_METHOD_MMAP;
			break;

		case 'r':
			capt.io = IO_METHOD_READ;
			break;

		case 'u':
			capt.io = IO_METHOD_USERPTR;
			break;

		case 'n':
			capt.nbuf = atoi(optarg);
			break;

		case 'x':
			capt.width = atoi(optarg);
			break;

		case 'y':
			capt.height = atoi(optarg);
			break;

		default:
			usage(stderr, argc, argv);
			exit(EXIT_FAILURE);
			break;
		}
	}

	open_device(&capt);
	init_device(&capt);

	test_framerate(&capt);

	start_capturing(&capt);
	main_loop(&capt);
	stop_capturing(&capt);

	free_device(&capt);
	close_device(&capt);

	return 0;
}
<file_sep>/network/5th_day/checksum.c
unsigned short checksum(unsigned short *buf, int nword)
{
	unsigned long sum;
	for(sum = 0; nword > 0; nword--)
	{
		sum += htons(*buf);
		buf++;
	}
	sum = (sum>>16) + (sum&0xffff);
	sum += (sum>>16);
	return ~sum;
}
<file_sep>/sys_program/4th_day/homework/mplayer/mplayer.c
/* ************************************************************************
 *       Filename:  mplayer.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 12时25分03秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include "interface.h"

void *fun(void *arg)
{
	int i = (int)arg;

	printf("pid = %d\n",i);

	sleep(6);
	kill((int)arg,2);
}

int main(int argc, char* argv[])
{
	WINDOW window;	
	pid_t pid;
	pthread_t pth;
	
	mkfifo("cmd_fifo",0777);
	fd = open("cmd_fifo",O_RDWR);	
		
	pid = fork();
	
	if(pid < 0)
	{
		perror("");
		exit(-1);
	}
	else if(pid == 0) //
	{
		printf("start mplayer now!\n");	
		//write(fd, "pause\n", strlen("pause\n")); //
		//启动mplayer
		execlp("mplayer",
		       "mplayer",
			   "-slave", "-quiet","-idle",
			   "-input", "file=./cmd_fifo",
			   "./media/sad_or_happy.mp3", NULL);
	}
	else
	{	
		//pthread_create(&pth,NULL,fun,(void *)pid); //创建一个新进程
		
		write(fd, "pause\n", strlen("pause\n")); //
		gtk_init(&argc, &argv);		
		show_window(&window);	
		gtk_main();				
	}
	
	return 0;
}
<file_sep>/work/test/gpioset/gpioset.c
/*************************************************************************
	> File Name: gpioset.c
	> Author:
	> Mail:
	> Created Time: Tue 24 May 2016 04:36:11 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>


/*#define DEBUG*/
#define GPIO_SET_OUTPUT  1
#define GPIO_SET_INPUT   0
#define GPIO_SET_LOW     0
#define GPIO_SET_HIGH    1

// Functions declaration
static void print_help(void);
static int gpio_export(int pin);
static int gpio_unexport(int pin);
static int gpio_direction(int pin, int dir);
static int gpio_read(int pin);

static void print_help(void)
{
    printf("Usage: gpioset gpionum I/O/H/L/R\n");
    printf("Usage:\n");
    printf("    I -> set gpio input\n");
    printf("    O -> set gpio output\n");
    printf("    H -> set gpio output 1\n");
    printf("    L -> set gpio output 0\n");
    printf("    R -> read gpio value\n");
    printf("   eg: gpioset 52 I\n");
}

static int gpio_export(int gpionum)
{
    char buffer[64];
    int len, fd;

    fd = open("/sys/class/gpio/export", O_WRONLY);
    if(fd < 0) {
        printf("Failed to open export for writing!\n");
        return -1;
    }

    len = snprintf(buffer, sizeof(buffer),"%d", gpionum);
    if(write(fd, buffer, len) < 0) {
        printf("Failed to export gpio%d!\n", gpionum);
        return -1;
    }

    close(fd);
    return 0;
}

static int gpio_unexport(int gpionum)
{
    char buffer[64];
    int len, fd;

    fd = open("/sys/class/gpio/unexport", O_WRONLY);
    if(fd < 0) {
        printf("Failed to open upexport for writing!\n");
        return -1;
    }

    len = snprintf(buffer, sizeof(buffer),"%d", gpionum);
    if(write(fd, buffer, len) < 0) {
        printf("Failed to upexport gpio%d!\n", gpionum);
        return -1;
    }

    close(fd);
    return 0;
}

//dir: 0 -> in, 1-> out
static int gpio_direction(int gpionum, int dir)
{
    static const char dir_str[] = "in\0out";
    char path[64];
    int fd;

    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/direction", gpionum);
    fd = open(path, O_WRONLY);
    if(fd < 0) {
        printf("Failed to open gpio direction for writing!\n");
        return -1;
    }

    if(write(fd, &dir_str[dir == 0?0:3], dir == 0?2:3) < 0) {
        printf("Failed to set gpio%d direction!\n", gpionum);
        return -1;
    }

    close(fd);
    return 0;
}

//value: 0 -> LOW, 1 -> HIGH
static int gpio_write(int gpionum, int value)
{
    char path[64];
    char value_str[3] = "01";
    int fd;

    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpionum);
    fd = open(path, O_WRONLY);
    if(fd < 0) {
        printf("Failed to open gpio value for reading!\n");
        return -1;
    }

    if(write(fd, &value_str[value == 0?0:1], 1) < 0) {
        printf("Failed to write gpio%d value!\n", gpionum);
        return -1;
    }

    close(fd);
    return 0;
}

static int gpio_read(int gpionum)
{
    char path[64];
    char value_str[3] = {0};
    int fd, i;

    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpionum);
    printf("path: %s\n",path);
    fd = open(path, O_RDONLY);
    if(fd < 0) {
        printf("Failed to open gpio value for reading!\n");
        return -1;
    }
    for(i = 0; i < 2; i++) {
        if(read(fd, value_str, sizeof(value_str)) < 0) {
            printf("Failed to read gpio%d value!\n", gpionum);
            return -1;
        }
    }
#ifdef DEBUG
    printf("### read value = %s\n", value_str);
    for(i = 0; i < 3; i++) {
        printf("value_str[%d] = %d\t",i, value_str[i]);
    }
    printf("\n");
#endif
    close(fd);
    return atoi(value_str);
}

int main(int argc, char *argv[])
{
    // Test for correct number of arguments
    if(argc != 3) {
        print_help();
        return -1;
    }

    int gpionum = atoi(argv[1]);
    if(gpionum < 0 || gpionum > 101) { // For Ingenic x1000 soc
        printf("### gpionum: %d is invalid ###\n", gpionum);
        return -1;
    }

    int ret = gpio_export(gpionum);
    if(ret < 0)
        return -1;

    char opt;
    memcpy(&opt, argv[2], 1);

    switch(opt) {
    case 'I': // Set gpio direction as input
        gpio_direction(gpionum, GPIO_SET_INPUT);
        break;
    case 'O': // Set gpio dirextion as output
        gpio_direction(gpionum, GPIO_SET_OUTPUT);
        break;
    case 'H': // Set gpio output 1
        ret = gpio_direction(gpionum, GPIO_SET_OUTPUT);
        if(ret != -1)
            gpio_write(gpionum, GPIO_SET_HIGH);
        break;
    case 'L': // Set gpio output 0
        ret = gpio_direction(gpionum, GPIO_SET_OUTPUT);
        if(ret != -1)
            gpio_write(gpionum, GPIO_SET_LOW);
        break;
    case 'R': // Read gpio value
        ret = gpio_read(gpionum);
        if(ret != -1)
            printf("### read gpio%d ret = %d ###\n", gpionum, ret);
        break;
    default:
        print_help(); // Show help when entry a wrong argument
    }

    printf("### Successful opetation! ###\n");
    gpio_unexport(gpionum);
    return 0;
}
<file_sep>/work/shell/s11mount
#!/bin/sh

# mount rootfs
#mount -t jffs2  /dev/mtdblock3 /mnt/rootfs

#if [ $? -ne 0 ]; then
if [ ! -d "rootfs" ]; then
    exit 1
fi

libs="ld-2.16.so
ld.so.1
libc-2.16.so
libcrypto.so
libcrypto.so.1.0.0
libc.so.6
libdl-2.16.so
libdl.so.2
libm-2.16.so
libm.so.6
libnss_dns-2.16.so
libnss_dns.so.2
libnss_files-2.16.so
libnss_files.so.2
libpthread-2.16.so
libpthread.so.0
libresolv-2.16.so
libresolv.so.2
librt-2.16.so
librt.so.1

libnl-3.so
libnl-3.so.200
libnl-3.so.200.19.0
libnl-genl-3.so
libnl-genl-3.so.200
libnl-genl-3.so.200.19.0
libssl.so
libssl.so.1.0.0"

# copy libs
ROOTFS=./rootfs
mkdir lib usr/lib sbin -p

for lib in $libs
do
    if [ -f $ROOTFS/lib/$lib ]; then
        cp $ROOTFS/lib/$lib lib/ -a
    elif [ -f $ROOTFS/usr/lib/$lib ]; then
        cp $ROOTFS/usr/lib/$lib usr/lib/ -a
    else
        echo "$lib dose not exist ..."
    fi
done

cp $ROOTFS/sbin/wifi_connect.sh sbin/
cp $ROOTFS/usr/sbin/wpa_supplicant sbin/
<file_sep>/network/route/src/inc/route_firewall.h
/******************************************************************************
  文 件 名   : route_firewall.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月14日
  最近修改   :
  功能描述   : route_firewall.c 的头文件
******************************************************************************/
#ifndef __ROUTE_FIREWALL_H__
#define __ROUTE_FIREWALL_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
 * 内部函数原型说明                             *
 *----------------------------------------------*/

//static Boolean check_input_rules();
static int firewall_filt_ip(TYPE_Route *rt, MSG_Info *pinfo);
static int firewall_filt_mac(TYPE_Route *rt, MSG_Info *pinfo);
static int firewall_filt_port(TYPE_Route *rt, MSG_Info *pinfo);
static int firewall_filt_protocol(TYPE_Route *rt, MSG_Info *pinfo);

/*----------------------------------------------*
 * 外部函数原型说明                             *
 *----------------------------------------------*/
extern void firewall_rule_set_help(void);
extern void firewall_build_rule(TYPE_Route *rt, const char *rule, char flag);
extern void delete_firewall_rule(TYPE_Route *rt, const char *rule);
extern int firewall_filt(TYPE_Route *rt, MSG_Info *pinfo);


#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */

/*****************************************************************************
                      >>>  防火墙规则输入格式  <<<
ip src 10.221.2.1
ip dst 10.221.2.1
ip host 10.221.2.1

mac src 01:02:03:04:05:06
mac dst 01:02:03:04:05:06
mac host 01:02:03:04:05:06

port src 8000
port dst 8000
port 8000

tcp ip src 10.221.2.1
tcp port dst 8000
tcp port 8000

arp
tcp 
udp 
icmp
igmp
http
tftp
*****************************************************************************/

#endif /* __ROUTE_FIREWALL_H__ */
<file_sep>/work/debug/a8/buttons/buttons_dev.c
#include <linux/module.h>
#include <linux/ioport.h>	/* resource */
#include <linux/irq.h>	    /* IRQ_EINT(23) */
#include <linux/gpio.h>	    /* S5PV210_GPH3(0) */
#include <linux/platform_device.h> /* platform_device_register() */
#include <linux/gpio_keys.h>  /* gpio_keys_button */
#include <linux/input.h>


static struct gpio_keys_button s5pv210_gpio_buttons[] = {
	// KEY2
	{
		.code    = KEY_UP,
		.gpio    = S5PV210_GPH2(3),
		.desc    = "key-up",
		.type    = EV_KEY,
	},
	// KEY4
	{
		.code    = KEY_DOWN,
		.gpio    = S5PV210_GPH2(5),
		.desc    = "key-down",
		.type    = EV_KEY,
	},
	// KEY6
	{
		.code    = KEY_LEFT,
		.gpio    = S5PV210_GPH2(7),
		.desc    = "key-left",
		.type    = EV_KEY,
	},
	// KEY5
	{
		.code    = KEY_RIGHT,
		.gpio    = S5PV210_GPH2(6),
		.desc    = "key-right",
		.type    = EV_KEY,
	},
};

static struct resource s5pv210_gpio_resource[] = {
	[0] = {
		.start = S5PV210_GPH3(0),
		.end = S5PV210_GPH3(0),
		.name = "GPH3_0",
		.flags = IORESOURCE_IO,
	},
	[1] = {
		.start = S5PV210_GPH0(3),
		.end = S5PV210_GPH0(3),
		.name = "GPH0_3",
		.flags = IORESOURCE_IO,	
	}
};

static struct gpio_keys_platform_data s5pv210_buttons_info = {
	.buttons  = s5pv210_gpio_buttons,
	.nbuttons = ARRAY_SIZE(s5pv210_gpio_buttons),
};


static void	s5pv210_buttons_device_release(struct device *pdev)
{
	printk(KERN_WARNING "%s\n",__FUNCTION__);	
	return;
}


static struct platform_device s5pv210_buttons_dev = {
	.name  = "s5pv210_buttons",
	.id    = -1,
	.num_resources = ARRAY_SIZE(s5pv210_gpio_resource),
	.resource = s5pv210_gpio_resource,
	.dev = {
		.platform_data = &s5pv210_buttons_info,
		.release       = s5pv210_buttons_device_release,
	},
};

static int __init s5pv210_buttons_device_init(void)
{
	return platform_device_register(&s5pv210_buttons_dev);
}

static void __exit s5pv210_buttons_device_exit(void)
{
	platform_device_unregister(&s5pv210_buttons_dev);
	return;
}

module_init(s5pv210_buttons_device_init);
module_exit(s5pv210_buttons_device_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/v4l2/capture.c
/*************************************************************************
	> Filename: capture.c
	>   Author: Qiuwei.wang
	>    Email: <EMAIL> / <EMAIL>
	> Datatime: Mon 28 Nov 2016 06:05:39 PM CST
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <getopt.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <malloc.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <asm/types.h>          /* for videodev2.h */
#include <linux/videodev2.h>

#include "common.h"
#include "yuv2bmp.h"
#include "capture.h"


/*
 * Functions
 */
static void init_read(struct capture_t *capt)
{
	capt->pbuf = calloc(1, sizeof(struct buffer));

	if(capt->pbuf) {
		fprintf(stderr, "Out of memory\n");
		exit(EXIT_FAILURE);
	}

	capt->pbuf[0].length = capt->sizeimage;
	capt->pbuf[0].start  = malloc(capt->sizeimage);

	if(!capt->pbuf[0].start) {
		fprintf(stderr, "Out of memory\n");
		exit(EXIT_FAILURE);
	}
}

static void init_mmap(struct capture_t *capt)
{
	int i;
	struct v4l2_requestbuffers req;

	CLEAR(req);
	req.count  = capt->nbuf;
	req.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	req.memory = V4L2_MEMORY_MMAP;

	/* Request buffer */
	if(-1 == xioctl(capt->fd, VIDIOC_REQBUFS, &req)) {
		if(EINVAL == errno) {
			fprintf(stderr, "%s does not support "
					"memory mapping\n", capt->dev_name);
			exit(EXIT_FAILURE);
		} else
			errno_exit("VIDIOC_REQBUFS");
	}

	if (req.count < 1) {
		fprintf(stderr, "Insufficient buffer memory on %s\n",
				capt->dev_name);
		exit(EXIT_FAILURE);
	}

	capt->pbuf = calloc(req.count, sizeof(struct buffer));
	if(!capt->pbuf) {
		fprintf(stderr, "Out of memory\n");
		exit(EXIT_FAILURE);
	}

	/* Update the value of nbuf */
	capt->nbuf = req.count;

	for(i = 0; i < req.count; i++) {
		struct v4l2_buffer buf;

		CLEAR(buf);
		buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		buf.memory = V4L2_MEMORY_MMAP;
		buf.index  = i;

		/* Get address and length of the frame buffer */
		if(-1 == xioctl(capt->fd, VIDIOC_QUERYBUF, &buf))
			errno_exit("VIDIOC_QUERYBUF");

		/* memory map */
		capt->pbuf[i].length = buf.length;
		capt->pbuf[i].start  = mmap(NULL,
								    buf.length,
								    PROT_READ | PROT_WRITE,
								    MAP_SHARED,
								    capt->fd, buf.m.offset);

		if(MAP_FAILED == capt->pbuf[i].start)
			errno_exit("mmap");
	}
}

static void init_userp(struct capture_t *capt)
{
	int i;
	unsigned int page_size;
	unsigned int buffer_size;
	struct v4l2_requestbuffers req;

	page_size = getpagesize();
	buffer_size = (capt->sizeimage + page_size - 1) & ~(page_size - 1);

	CLEAR(req);
	req.count  = capt->nbuf;
	req.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	req.memory = V4L2_MEMORY_USERPTR;

	/* Request buffer */
	if(-1 == xioctl(capt->fd, VIDIOC_REQBUFS, &req)) {
		if(EINVAL == errno) {
			fprintf(stderr, "%s does not support "
					"user pointer i/o\n", capt->dev_name);
			exit(EXIT_FAILURE);
		} else
			errno_exit("VIDIOC_REQBUFS");
	}

	if (req.count < 1) {
		fprintf(stderr, "Insufficient buffer memory on %s\n",
				capt->dev_name);
		exit(EXIT_FAILURE);
	}

	capt->pbuf = calloc(req.count, sizeof(struct buffer));
	if(!capt->pbuf) {
		fprintf(stderr, "Out of memory\n");
		exit(EXIT_FAILURE);
	}

	/* Update the value of nbuf */
	capt->nbuf = req.count;

	for(i = 0; i < capt->nbuf; i++) {
		capt->pbuf[i].length = buffer_size;
		capt->pbuf[i].start  = JZMalloc(128, buffer_size);

		if(!capt->pbuf[i].start) {
			fprintf(stderr, "Out of memory\n");
			exit(EXIT_FAILURE);
		}
	}
}

void process_image(struct capture_t *capt, int index)
{
	unsigned char *rgbbuf = NULL;
	unsigned char *yuvbuf = NULL;

	yuvbuf = (unsigned char *)capt->pbuf[index].start;
	rgbbuf = (unsigned char *)malloc(capt->width * capt->height * 3);
	if(!rgbbuf) {
		fprintf(stderr, "malloc rgbbuf failed!!\n");
		errno_exit("malloc");
	}

	yuv2rgb(yuvbuf, rgbbuf, capt->width, capt->height);
	rgb2bmp("test.bmp", capt->width, capt->height, 24, rgbbuf);

	free(rgbbuf);
}

int read_frame(struct capture_t *capt)
{
	struct v4l2_buffer buf;
	unsigned int i;

	switch(capt->io) {
	case IO_METHOD_READ:
		if(-1 == read(capt->fd, capt->pbuf[0].start, capt->pbuf[0].length)) {
			switch(errno) {
			case EAGAIN:
				fprintf(stderr, "Read frame error: %d, %s\n", \
						errno, strerror(errno));
				return FALSE;

			case EIO:
			default:
				errno_exit("read");
			}
		}

		process_image(capt, 0);
		break;

	case IO_METHOD_MMAP:
		CLEAR(buf);
		buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		buf.memory = V4L2_MEMORY_MMAP;

		if(-1 == xioctl(capt->fd, VIDIOC_DQBUF, &buf)) {
			switch(errno) {
			case EAGAIN:
				fprintf(stderr, "Read frame error: %d, %s\n", \
						errno, strerror(errno));
				return FALSE;

			case EIO:
			default:
				errno_exit("VIDIOC_DQBUF");
			}
		}

		assert(buf.index < capt->nbuf);
		process_image(capt, buf.index);

		if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
			errno_exit("VIDIOC_QBUF");

		break;

	case IO_METHOD_USERPTR:
		CLEAR(buf);
		buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		buf.memory = V4L2_MEMORY_USERPTR;

		if(-1 == xioctl(capt->fd, VIDIOC_DQBUF, &buf)) {
			switch(errno) {
			case EAGAIN:
				fprintf(stderr, "Read frame error: %d, %s\n", \
						errno, strerror(errno));
				return FALSE;

			case EIO:
			default:
				errno_exit("VIDIOC_DQBUF");
			}
		}

		unsigned int page_size   = getpagesize();
		unsigned int buffer_size = (buf.length + page_size - 1) & ~(page_size - 1);
		for(i = 0; i < capt->nbuf; i++) {
			if((unsigned long)(capt->pbuf[i].start) == buf.m.userptr && \
			   (unsigned long)(capt->pbuf[i].length) == buffer_size)
				break;
		}

		assert(i < capt->nbuf);
		process_image(capt, i);

		if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
			errno_exit("VIDIOC_QBUF");

		break;
	}

	return TRUE;
}

void start_capturing(struct capture_t *capt)
{
	int i;
	enum v4l2_buf_type type;

	switch(capt->io) {
	case IO_METHOD_READ:
		/* Nothing to do */
		break;

	case IO_METHOD_MMAP:
		/* Add to buffer queue */
		for(i = 0; i < capt->nbuf; i++) {
			struct v4l2_buffer buf;

			CLEAR(buf);
			buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
			buf.memory = V4L2_MEMORY_MMAP;
			buf.index  = i;

			if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
				errno_exit("VIDIOC_QBUF");
		}

		type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		if(-1 == xioctl(capt->fd, VIDIOC_STREAMON, &type))
			errno_exit("VIDIOC_STREAMON");

		break;

	case IO_METHOD_USERPTR:
		/* Add to buffer queue */
		for(i = 0; i < capt->nbuf; i++) {
			struct v4l2_buffer buf;

			CLEAR(buf);
			buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
			buf.memory = V4L2_MEMORY_USERPTR;
			buf.index  = i;
			buf.length = capt->pbuf[i].length;
			buf.m.userptr = (unsigned long)capt->pbuf[i].start;

			if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
				errno_exit("VIDIOC_QBUF");
		}

		type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		if(-1 == xioctl(capt->fd, VIDIOC_STREAMON, &type))
			errno_exit("VIDIOC_STREAMON");

		break;
	}
}

void stop_capturing(struct capture_t *capt)
{
    enum v4l2_buf_type type;

	switch(capt->io) {
	case IO_METHOD_READ:
		/* Nothing to do */
		break;

	case IO_METHOD_MMAP:
	case IO_METHOD_USERPTR:
		type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		if(-1 == xioctl(capt->fd, VIDIOC_STREAMOFF, &type))
			errno_exit("VIDIOC_STREAMOFF");

		break;
	}
}

void test_framerate(struct capture_t *capt)
{
	fd_set fds;
	struct timeval tv;
	struct timeval start_tv;
	struct timeval end_tv;
	struct v4l2_buffer buf;
	int ret = 0;
	int count = 0;
	int costtime = 0;

	fprintf(stdout, "Start to test frame rate ...\n");
	start_capturing(capt);
	gettimeofday(&start_tv, NULL);

	while(1) {
		FD_ZERO(&fds);
		FD_SET(capt->fd, &fds);

		/* Select time */
		tv.tv_sec  = 2;
		tv.tv_usec = 0;

		ret = select(capt->fd + 1, &fds, NULL, NULL, &tv);
		if(ret < 0) {
			if(EINTR == errno)
				continue;
			errno_exit("select");
		} else if(0 == ret) {
			fprintf(stderr, "Select timeout\n");
			exit(EXIT_FAILURE);
		}

		CLEAR(buf);
		buf.type   = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		buf.memory = V4L2_MEMORY_MMAP;

		if(-1 == xioctl(capt->fd, VIDIOC_DQBUF, &buf)) {
			switch(errno) {
			case EAGAIN:
			case EIO:
			default:
				errno_exit("VIDIOC_DQBUF");
			}
		}

		assert(buf.index < capt->nbuf);

		if(-1 == xioctl(capt->fd, VIDIOC_QBUF, &buf))
			errno_exit("VIDIOC_QBUF");

		count++;
		if(count == 60)
			break;
	}

	gettimeofday(&end_tv, NULL);
	costtime = (end_tv.tv_sec - start_tv.tv_sec) * 1000000 + \
			   (end_tv.tv_usec - start_tv.tv_usec);

	fprintf(stdout, "%s: get %d frame = %dus, fps = %f\n", \
			capt->dev_name, count, costtime, 1000000.0 * count/costtime);

	stop_capturing(capt);
}

void open_device(struct capture_t *capt)
{
	struct stat st;

	if(-1 == stat(capt->dev_name, &st)) {
		fprintf(stderr, "Cannot identify '%s': %d, %s\n",
				capt->dev_name, errno, strerror(errno));
		exit(EXIT_FAILURE);
	}

	if(!S_ISCHR(st.st_mode)) {
		fprintf(stderr, "%s is no device\n", capt->dev_name);
		exit(EXIT_FAILURE);
	}

	capt->fd = open(capt->dev_name, O_RDWR | O_NONBLOCK, 0);

	if(capt->fd < 0) {
		fprintf(stderr, "Cannot open '%s': %d, %s\n",
				capt->dev_name, errno, strerror(errno));
		exit(EXIT_FAILURE);
	}
}

void close_device(struct capture_t *capt)
{
	if(-1 == close(capt->fd))
		errno_exit("close");

	capt->fd = -1;
	free(capt->pbuf);
}

void init_device(struct capture_t *capt)
{
	unsigned int min;
	struct v4l2_capability cap;
	struct v4l2_cropcap cropcap;
	struct v4l2_crop crop;
	struct v4l2_format fmt;

	if(-1 == xioctl(capt->fd, VIDIOC_QUERYCAP, &cap)) {
		if(EINVAL == errno) {
			fprintf(stderr, "%s is no V4L2 device\n",
					capt->dev_name);
			exit(EXIT_FAILURE);
		} else
			errno_exit("VIDIOC_QUERYCAP");
	}

	if(!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
		fprintf(stderr, "%s is no video capture device\n",
				capt->dev_name);
		exit(EXIT_FAILURE);
	}

	switch(capt->io) {
	case IO_METHOD_READ:
		if(!(cap.capabilities & V4L2_CAP_READWRITE)) {
			fprintf(stderr, "%s does not support read i/o\n",
					capt->dev_name);
			exit(EXIT_FAILURE);
		}

		break;

	case IO_METHOD_MMAP:
	case IO_METHOD_USERPTR:
		if(!(cap.capabilities & V4L2_CAP_STREAMING)) {
			fprintf(stderr, "%s does not support streaming i/o\n",
					capt->dev_name);
			exit(EXIT_FAILURE);
		}

		break;
	}

	/* Select video input, video standard and tune here */
	CLEAR(cropcap);

	cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	if(0 == xioctl(capt->fd, VIDIOC_CROPCAP, &cropcap)) {
		crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
		crop.c = cropcap.defrect; /* reset to default */

		if(-1 == xioctl(capt->fd, VIDIOC_S_CROP, &crop)) {
			switch(errno) {
			case EINVAL:
				/* Cropping not supported. */
				break;
			default:
				/* Errors ignored. */
				break;
			}
		}
	} else {
		/* Errors ignored */
	}

	CLEAR(fmt);
	fmt.type                = V4L2_BUF_TYPE_VIDEO_CAPTURE;
	fmt.fmt.pix.width       = capt->width;
	fmt.fmt.pix.height      = capt->height;
	fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;
	fmt.fmt.pix.field       = V4L2_FIELD_NONE; //V4L2_FIELD_INTERLACED;

	if(-1 == xioctl(capt->fd, VIDIOC_S_FMT, &fmt))
		errno_exit ("VIDIOC_S_FMT");

	/* Note VIDIOC_S_FMT may change width and height */
	min = fmt.fmt.pix.width * 2;
	if(fmt.fmt.pix.bytesperline < min)
		fmt.fmt.pix.bytesperline = min;

	min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
	if(fmt.fmt.pix.sizeimage < min)
		fmt.fmt.pix.sizeimage = min;

	/* Save image size */
	capt->sizeimage = min;

	capt->width  = fmt.fmt.pix.width;
	capt->height = fmt.fmt.pix.height;

	fprintf(stdout, "==> %s L%d: sizeimage = 0x%x, width = %d, height = %d\n", \
			__FUNCTION__, __LINE__, capt->sizeimage, capt->width, capt->height);

	switch(capt->io) {
	case IO_METHOD_READ:
		init_read(capt);
		break;

	case IO_METHOD_MMAP:
		init_mmap(capt);
		break;

	case IO_METHOD_USERPTR:
		init_userp(capt);
		break;
	}
}

void free_device(struct capture_t *capt)
{
	int i;

	switch(capt->io) {
	case IO_METHOD_READ:
		free(capt->pbuf[0].start);
		break;

	case IO_METHOD_MMAP:
		for(i = 0; i < capt->nbuf; i++) {
			if(-1 == munmap(capt->pbuf[i].start, \
							capt->pbuf[i].length))
				errno_exit("munmap");
		}

		break;

	case IO_METHOD_USERPTR:
		jz47_free_alloc_mem();
		break;
	}
}

void main_loop(struct capture_t *capt)
{
	fd_set fds;
	struct timeval tv;
	int ret;
	int count = 5;

	while(count--) {
		FD_ZERO(&fds);
		FD_SET(capt->fd, &fds);

		/* Select time */
		tv.tv_sec  = 2;
		tv.tv_usec = 0;

		ret = select(capt->fd + 1, &fds, NULL, NULL, &tv);
		if(ret < 0) {
			if(EINTR == errno)
				continue;
			errno_exit("select");
		} else if(0 == ret) {
			fprintf(stderr, "Select timeout\n");
			exit(EXIT_FAILURE);
		}

		if(read_frame(capt))
			break;
	}
}
<file_sep>/work/debug/a8/touchscreen/Makefile
# If KERNELRELEASE is 2.6.35.7, we've been invoked from the 
# kernel build system and can use its language. 
ifeq ($(KERNELRELEASE),2.6.35.7)

#if you want use param to make,as follow:
#use£şmake t=XXX
TARGET=$(t)
ifneq ($(TARGET),)
obj-m := $(TARGET).o
else
#if have only one *.c file and get one *.ko file
#obj-m := virtualchar.o 

#if have many *.c file and get many *.ko
obj-m := goodix_dev.o goodix_touch_v2.1.o

#if have many *.c file and get one *.ko
#note: The object file name of the next two line must be consistent
#obj-m := ZZZ.o 
#ZZZ-objs := XXX.o YYY.o ... 
endif

else

#if not define KERNELDIR in enviroment,you need define KERNELDIR by yourself 
ifeq ($(KERNELDIR),)
KERNELDIR = /home/edu/a8/2.6.35.7_tools/unsp210_linux_2.6.35/
endif	

$(PWD) := $(shell pwd)

default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules	
	rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
	
clean:
	rm -rf *.ko 

# app test need 
test:
	arm-linux-gcc -o $@ test.c
testclean:
	rm -fr test	
	
endif 
<file_sep>/work/debug/pc/sync/Makefile
ifneq ($(KERNELRELEASE),)
	obj-m := sync_drv.o

else
	KERNELDIR ?= /lib/modules/$(shell uname -r)/build
#	KERNELDIR ?= /work/linux/linux-2.6.32.2
	PWD := $(shell pwd)
default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
	rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
	rm -f *.o *~ *.ko  *.mod.c *.mod.o *.symvers *.order
endif

ins:
	sudo insmod ./sync_drv.ko
del:
	sudo rmmod sync_drv
	
CC := gcc
mt:
	$(CC) -o test test_sync.c

.PHONY:clc
clc:
	rm test


<file_sep>/work/test/pwm-beeper/Makefile
GCC := mips-linux-gnu-gcc

CFLAGS := -EL -mabi=32 -mhard-float -march=mips32r2 -Os
LDFLAGS:= -Wl,-EL
LDLIBS :=

SOURCES := $(wildcard *.c)

TARGET = beeper
all: $(TARGET)

$(TARGET): $(SOURCES)
	$(GCC) $(CFLAGS) $(LDFLAGS) -o $@ $^

INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install:
	cp $(TARGET) $(INSTALL_DIR) -a

.PHONY: clean
clean:
	rm -rf *.o $(TARGET)
<file_sep>/gtk/1. base/01_button/button.c
#include <gtk/gtk.h>	// 头文件

// 回调函数
void callback(GtkButton *button, gpointer data)
{
	const char *str = gtk_button_get_label( button ); // 获得按钮的文本内容
	printf("str = %s\n", str);
}

int main(int argc, char *argv[]) 
{ 
	gtk_init(&argc, &argv); 	// 初始化

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);    // 创建窗口
	gtk_window_set_title(GTK_WINDOW(window), "button");// 设置标题 
	g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); 			
	gtk_container_set_border_width(GTK_CONTAINER(window), 10);       // 设置窗口边框的宽度
	gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); // 窗口居中

	GtkWidget *hbox = gtk_hbox_new(TRUE, 10); 		// 水平布局容器
	gtk_container_add(GTK_CONTAINER(window), hbox); // 把横向盒状容器放入窗口

	// 普通按钮
	GtkWidget *normal_button = gtk_button_new_with_label("normal button");
	gtk_button_set_label(GTK_BUTTON(normal_button), "change");	// 设置按钮的文本内容
	g_signal_connect(normal_button, "pressed", G_CALLBACK(callback), NULL);
	gtk_container_add(GTK_CONTAINER(hbox), normal_button);     // 把按钮放入横向容器里

	// 带图标按钮
	GtkWidget *button = gtk_button_new(); // 先创建空按钮
	GtkWidget *image = gtk_image_new_from_file("1.png"); // 图像控件
	gtk_button_set_image(GTK_BUTTON(button), image);
	gtk_container_add(GTK_CONTAINER(hbox), button);     // 把按钮放入横向容器里
	gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_HALF);	// 按钮背景色透明
	
	// 按钮使能设置，默认为使能TRUE，非使能FALSE
	//gtk_widget_set_sensitive(button, FALSE);

	gtk_widget_show_all(window);	// 显示窗口控件

	gtk_main(); 	// 主事件循环

    return 0; 
}
<file_sep>/c/practice/3rd_week/encrypt/main.c
/* ************************************************************************
 *       Filename:  encrypt.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月30日 星期四 01時59分46秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include "encrypt.h"

char mygetch() 
{
    struct termios oldt, newt;
    char ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

void print_help()
{
	printf("输入 1：加密文件\n");
	printf("输入 2：解密文件\n");
	printf("输入 3：退出程序\n");
}

void main()
{
	char ch, *buf = NULL;
	char dest_file_name[30] = "";
	char src_file_name[30] = "";
	long unsigned int length = 0,password = 0;;
	
	while(1)
	{
		print_help(); //显示提示
		
		do
		{
			ch = mygetch();
		}while(ch != '1' && ch != '2' && ch != '3');
		
		switch(ch)
		{
			#if 0
			case '1':
			{
				get_file_name(dest_file_name,src_file_name); //获取加密文件名和目的文件名
				buf = read_src_file(&length,src_file_name);  //读取待加密文件内容
				printf("Please input your poassword: ");
				scanf("%lu",&password);  //获取加密密码
				buf = file_text_encrypt(buf,length,password); //进行加密
				save_file(buf,length,dest_file_name);
				break;
			}
			case '2':
			{
				get_file_name(dest_file_name,src_file_name); //获取解密文件名和目的文件名
				buf = read_src_file(&length,src_file_name);  //读取待解密文件内容
				printf("Please input your poassword: ");
				scanf("%lu",&password);  //获取解密密码
				buf = file_text_decrypt(buf,length,password); //进行解密	
				save_file(buf,length,dest_file_name);
				break;
			}
			case '3': free(buf); exit(0);
			#elif 1
			case '3': free(buf); exit(0);			
			case '1':	
			case '2':
			{
				get_file_name(dest_file_name,src_file_name); //获取源文件名和目的文件名
				buf = read_src_file(&length,src_file_name);  //读取待操作的文件内容
				printf("Please input your poassword: ");
				scanf("%lu",&password);  //获取密码
				if(ch == '1')
				{
					buf = file_text_encrypt(buf,length,password); //进行加密
					save_file(buf,length,dest_file_name);
					break;
				}
				else
				{
					buf = file_text_decrypt(buf,length,password); //进行解密	
					save_file(buf,length,dest_file_name);
					break;					
				}
			}
			#endif
		}
	}
}


<file_sep>/c/practice/3rd_week/link/Makefile
link: main.c link.c
	gcc -o link main.c link.c -Wall
clean:
	rm link
<file_sep>/network/6th_day/Makefile
all:pcap libnet

pcap:
	gcc -o pcap pcap_test.c -lpcap

libnet:
	gcc -o libnet libnet_test.c -lnet


.PHONY:clean
clean:
	rm pcap libnet
<file_sep>/gtk/4st_week/picture_browse/scan_dir.h
/* ************************************************************************
 *       Filename:  scan_dir.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月11日 14时38分20秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __SCAN_DIR_H__
#define __SCAN_DIR_H__

#define IMAGE_WIDTH				400
#define IMAGE_HEIGTH			300
#define IMAGE_DIR				"./image/"

extern int gs_index;
extern int gs_bmp_total;	//图片总数
extern char *gs_bmp_name[50];//存放图片目录和文件名地址的指针数组


void save_bmp_name(char *path, char *bmp);
void get_bmp_name(char *path);
int conver_bmp_name(char *bmp_pathname);
void order_bmp_name(void);
void bmp_name_print(void);

#endif


<file_sep>/c/homework/3rd_week/mystring.c
/* ************************************************************************
 *       Filename:  mystring.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月24日 星期五 03時39分01秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟 
 *        Company:  
 * ************************************************************************/
#include<math.h>
#include<string.h>
#include"mystring.h"

void mystrinv(char *src)
{
	char *head = NULL;
	char *trail= NULL;
	char ch;
	int i = 0;

	while(src[i++]);
	head = src;
	trail= head + i -2;

	while(trail > head)
	{
		ch = *head;
		*head = *trail;
		*trail= ch;
		head++;
		trail--;
	}
}

int mystrlen(char *src)
{
	int i= 0;

	while(src[i++]);

	return i-1;
}

int mystrcpy(char *obj, char *src)
{
	int i = 0;

	while(src[i])
	{
		obj[i] = src[i];
		i++;
	}

	obj[i] = '\0';

	return i;
}

int mystrcmp(char *src1, char *src2)
{
	int i = 0;

	while(src1[i++])
	{
		if(src1[i]>src2[i])
		{
			return 1;
		}
		else if(src1[i]<src2[i])
		{
			return -1;
		}
	}

	return 0;
}
int strchange(char *src)
{
	int i = 0;
	int len = 0, res = 0;
	len = strlen(src);

	for(i=0;i<len;i++)
	{
		res += pow(10,len-i-1) * (src[i]-48);
	}

	return res;
}
<file_sep>/work/test/cim_test-zmm220/futil.c
#include "futil.h"


#ifndef WIN32
DWORD GetTickCount(void)
{
	struct timeval tv;
	struct timezone tz;
	gettimeofday(&tv, &tz);
	return (tv.tv_sec*1000 + tv.tv_usec/1000);
}
#endif

int WriteBitmap(const BYTE *buffer, int Width, int Height, const char *file)
{
	char Buffer[0x500];
	BITMAPFILEHEADER *bmpfheader=(BITMAPFILEHEADER *)Buffer;
	BITMAPINFO *bmpinfo=(BITMAPINFO *)(((char*)bmpfheader)+14);
	int i,w;
	FILE *f;
	memset(bmpfheader,0,0x500);
	bmpfheader->bfType =19778;
	w = ((Width+3)/4)*4*Height+sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+255*sizeof(RGBQUAD);
	memcpy((void*)(((char*)bmpfheader)+2), &w, 4);
	//bmpfheader->bfOffBits;
	w= sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFO)+255*sizeof(RGBQUAD);
	memcpy((void*)(((char*)bmpfheader)+10), &w, 4);
	bmpinfo->bmiHeader.biWidth=Width;
	bmpinfo->bmiHeader.biHeight=Height;
	bmpinfo->bmiHeader.biBitCount=8;
	bmpinfo->bmiHeader.biClrUsed=0;
	bmpinfo->bmiHeader.biSize=sizeof(bmpinfo->bmiHeader);
	bmpinfo->bmiHeader.biPlanes=1;
	bmpinfo->bmiHeader.biSizeImage=((Width+3)/4)*4*Height;
	f=fopen(file, "wb");
	if(f)
	{
		for(i=1;i<256;i++)
		{
			bmpinfo->bmiColors[i].rgbBlue=i;
			bmpinfo->bmiColors[i].rgbGreen=i;
			bmpinfo->bmiColors[i].rgbRed=i;
		}
		fwrite(Buffer, sizeof(BITMAPFILEHEADER)+sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD), 1, f);

		w = ((Width+3)/4)*4;
		buffer+=Width*(Height-1);
		for(i=0; i<Height; i++)
		{
			fwrite(buffer, Width, 1, f);
			if(w-Width)
				fwrite(buffer, w-Width, 1, f);
			buffer-=Width;
		}
		fclose(f);
		return Width*Height;
	}
	return 0;
}

BYTE *LoadFile(const char *FileName)
{
	BYTE *data=NULL;
	FILE *f=fopen(FileName, "rb"); 
	long s;
	if(!f) return 0;
	fseek(f,0,SEEK_END);
	s=ftell(f);
	if(s>0)
	{
		fseek(f,0,SEEK_SET);
		data=(BYTE*)malloc(s);
		if (1>(long)fread(data, s, 1, f))
		{
			free(data);
			data=NULL;
		}
	}
	fclose(f);
	return data;
}

int SaveToFile(const char *fileName, void *buffer, int size)
{
	FILE *f=fopen(fileName, "wb");
	if(f==NULL)
	{
		logMsg("Open file %s to write fail.\n", fileName);
		return 0;
	}
	fwrite(buffer, size, 1, f);
	fclose(f);
	return 1;
}

static FILE *logf=NULL;
static unsigned int startTick=0;

int logClose()
{
	if(logf) 
	{
		fprintf(logf, "%ld:\tEnd Log.\n", GetTickCount()-startTick);
		fclose(logf);
		logf=NULL;
	}
	return 0;
}

int logMsg(char *fmt, ...)
{
	static int lastEnd=0;
	unsigned int theTick=GetTickCount();
	va_list argptr;
	va_start(argptr, fmt);
//	return 0;
	if(logf==NULL)
	{
		logf=fopen("log.txt", "w");
	}
	if(logf==NULL) return 0;
	if(startTick==0)
	{
		startTick=theTick;
		fprintf(logf, "%d:\tStart Log.\n", startTick);
		lastEnd=1;
	}
	if(lastEnd)
		fprintf(logf, "%d:\t",theTick-startTick);
	lastEnd=(fmt[strlen(fmt)-1]=='\n')?1:0;
	vfprintf(logf, fmt, argptr);
	vprintf(fmt, argptr);
	return 1;
}


int ReadBitmap(BYTE *p, BYTE *buffer, int *Width, int *Height)
{
	BITMAPFILEHEADER *bmpfheader=(BITMAPFILEHEADER *)p;
	BITMAPINFO *bmpinfo=(BITMAPINFO *)(p+14);
	int i,w;
	if(!p) return 0;

	*Width = bmpinfo->bmiHeader.biWidth;
	*Height=bmpinfo->bmiHeader.biHeight;
	if((bmpfheader->bfType ==19778) && (bmpinfo->bmiHeader.biCompression==0) &&
		(bmpinfo->bmiHeader.biBitCount==8))
	{
		if(bmpinfo->bmiHeader.biClrUsed==0) bmpinfo->bmiHeader.biClrUsed=256;
		if(bmpinfo->bmiHeader.biClrUsed!=256) return 0;
		p+=0x436;
		w = ((*Width+3)/4)*4;
		p+=w*(*Height-1);
		if(buffer)
			for(i=0; i<(int)*Height; i++)
			{
				memcpy(buffer, p, *Width);
				buffer+=*Width;
				p-=w;
			}
	}
	return *Width**Height;
}

int LoadBitmapFile(const char *FileName, BYTE *buffer, int *Width, int *Height)
{
	unsigned char *p=LoadFile(FileName);
	int res=ReadBitmap(p, buffer, Width, Height);
	free(p);
	return res;
}

void msleep(int msec)
{
	struct timeval delay;
	delay.tv_sec =msec /1000;
	delay.tv_usec =(msec%1000)*1000;
	select(0, NULL, NULL, NULL, &delay);
}

int dumpData(const unsigned char *data, int dataSize, const char *title)
{
	static char Hex[17]="0123456789ABCDEF";
	int i, linec=0;
	char line[20];
	printf("Dump %s: Size=%d\n", title? title: "Data", dataSize);
	for(i=0; i<dataSize;i++)
	{
		char HexData[3];
		HexData[0]=Hex[data[i]>>4]; HexData[1]=Hex[data[i]&0x0F]; HexData[2]=0;
		if(linec==0) printf("  ");
		printf("%s ", HexData);
		if(data[i]>=0x20 && data[i]<0x7F)
			line[linec]=data[i];
		else
			line[linec]='.';
		if(++linec>=16)
		{
			line[linec]=0;
			printf("  %s\n", line);
			linec=0;
		}
	}
	if(linec)
	{
		for(i=0;i<16-linec;i++) printf("   ");
		line[linec]=0;
		printf("  %s\n",line);
	}
	return 0;
}
<file_sep>/c/mkheader/mkheader.c
/*************************************************************************
	> Filename: god.c
	>   Author: 
	>    Email: 
	> Datatime: 2017年02月24日 星期五 22时23分04秒
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int main(int argc, char *argv[])
{
    FILE *fp;
    uint32_t length;
    char *buf;

    //fp = fopen("./app", "rb+");
    fp = fopen(argv[1], "rb+");
    if (fp == NULL) {
        printf("Cannot open the file!\n");
        return -1;
    }

    fseek(fp, 0, SEEK_END);
    length = ftell(fp);

    printf("write length=%d\n", length);
    buf = (char *)malloc(length + 4);
    if (buf == NULL) {
        printf("Failed to malloc mem\n");
        return 0;
    }
    bzero(buf, length + 4);

    *(uint32_t *)buf = length;

    fseek(fp, 0, SEEK_SET);
    fread(buf+4, length, 1, fp);

    fseek(fp, 0, SEEK_SET);
    fwrite(buf, length + 4, 1, fp);

    fclose(fp);
    return 0;
}
<file_sep>/work/shell/timer.sh
#!/bin/sh

for i in $(seq 1 2)
do
	sleep 20s
	echo "20s later..."
done

echo "reboot system now..."
reboot
<file_sep>/sys_program/4th_day/homework/mplayer/interface.c
/* ************************************************************************
 *       Filename:  interface.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 20时42分13秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <string.h>
#include "interface.h"
#include "image.h"

int fd; //保存管道文件描述符
int playing = FALSE;

// 按钮的回调函数
void deal_switch_image(GtkWidget *button, gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;
		
	if(button == p_temp->button_previous)   // 快退
	{		
		write(fd, "seek -10\n", strlen("seek -10\n"));
	}
	else if(button == p_temp->button_next ) // 快进
	{	
		write(fd, "seek -10\n", strlen("seek 10\n"));
	}
	else if(button == p_temp->button_pause ) // 赞同或播放
	{
		printf("p_temp->button_pause\n");
		
		if(playing)  // 正在播放，则暂停
		{
			write(fd, "pause\n", strlen("pause\n"));
			playing = FALSE;
					
			GtkWidget *image = gtk_image_new_from_file("./skin/pause.bmp"); // 图像控件
			gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
			
		}
		else //否则，开启播放
		{
			write(fd, "pause\n", strlen("pause\n"));
			playing = TRUE;
					
			GtkWidget *image = gtk_image_new_from_file("./skin/play.bmp"); // 图像控件
			gtk_button_set_image(GTK_BUTTON(p_temp->button_pause), image);
					
		}
		
	}
	
}

void show_window(gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;
	
	// 主窗口
	p_temp->main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);		 	// 创建主窗口
	gtk_window_set_title(GTK_WINDOW(p_temp->main_window), "picture_browse");	 	// 设置窗口标题
	gtk_window_set_position(GTK_WINDOW(p_temp->main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
	gtk_widget_set_size_request(p_temp->main_window, 500, 250);		 	// 设置窗口的最小大小
	gtk_window_set_resizable(GTK_WINDOW(p_temp->main_window), FALSE); 	// 固定窗口的大小
	g_signal_connect(p_temp->main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL); 
	
	// 表格布局
	p_temp->table = gtk_table_new(5, 7, TRUE);	// 表格布局容器 5行 7列
	gtk_container_add(GTK_CONTAINER(p_temp->main_window), p_temp->table); // 容器加入窗口

	// 按钮
#if 1
	p_temp->button_previous = create_button_from_file("./skin/previous.bmp", 70, 60);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_previous, 1, 2, 2, 3);
	g_signal_connect(p_temp->button_previous, "clicked", G_CALLBACK(deal_switch_image), p_temp);
	
	p_temp->button_next = create_button_from_file("./skin/next.bmp", 70, 60);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_next, 5, 6, 2, 3);
	g_signal_connect(p_temp->button_next, "clicked", G_CALLBACK(deal_switch_image), p_temp);
	
	p_temp->button_pause = create_button_from_file("./skin/play.bmp", 70, 60);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_pause, 3, 4, 2, 3);
	g_signal_connect(p_temp->button_pause, "clicked", G_CALLBACK(deal_switch_image), p_temp);
#endif
	chang_background(p_temp->main_window, 500, 250, "./skin/background.bmp");	// 设置窗口背景图
	gtk_widget_show_all(p_temp->main_window);
}
<file_sep>/work/shell/abc.sh
#!/bin/sh

/usr/fs/etc/init.d/S04bsa.sh stop
iwconfig wlan0 txpower off
ifconfig wlan0 down
<file_sep>/sys_program/player/src/gtk_callback.c
#include <gtk/gtk.h>
#include <glade/glade.h>
#include <string.h>
#include "common.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"
#include "mplayer_ui.h"
#include "gtk_callback.h"


// 鼠标移动事件(点击鼠标任何键)的处理函数
gboolean motion_event_callback(GtkWidget *widget, GdkEventMotion *event, gpointer data)
{
	// 获得移动鼠标的坐标值
	gint x = event->x;
	gint seek_sec = 0;
	char cmd[32] = "seek ";
	char buf[8] = {0};
	MPLAYER *pm = (MPLAYER*)data;

	if(pm->playflag == playing) pm->playflag = stop;

	seek_sec = x * song.end_time/400;          //毫秒
	seek_sec = (seek_sec - song.cur_time)/1000;//秒
	
	printf("seek_sec = %d\n",seek_sec);
	
	gcvt(seek_sec,5,buf);
	strcat(cmd, buf);
	strcat(cmd,"\n");
	printf("cmd = %s\n",cmd);
	send_cmd(cmd,pm);

	pm->playflag == playing;
	//gint j = event->y;
	//printf("motion_x = %d, motion_y = %d\n", i, j);
	return TRUE;
}

void search_entry_callback(GtkWidget *widget, gpointer entry)
{	
	MPLAYER *pm = (MPLAYER*)entry;
	const gchar *text;
	int i = 0;
	char *p = NULL;
	
	text = (gchar *)gtk_entry_get_text(GTK_ENTRY(pm->ui.hbox_left.entry_search));
	//printf("Entry contents: %s\n",text);

	for(i=0; i<song.count; i++)
	{
		if((p=strstr(song.psong_list[i],text)) != NULL)
		{
			printf("entry >> song_name = %s\n",song.psong_list[i]);
			
			sungtk_clist_set_row_color(musiclist, i, "green");
			
			song.search[i] = 1;
			song.search_flag = 1;
			p = NULL;
		}
	}
}

void keys_board_callback(GtkWidget *widget, GdkEventKey  *event, gpointer data)
{

	printf("Entry keys_board_callback!!!!\n");
	if(event->keyval == 65288) //backspace
	{
		MPLAYER *pm = (MPLAYER*)data;
		const gchar *text;
		char *p = NULL;
		int i = 0;

		text = (gchar *)gtk_entry_get_text(GTK_ENTRY(pm->ui.hbox_left.entry_search));
		//printf("Entry contents: %s\n",text);

		if(text != NULL)
		{
			for(i=0; i<song.count; i++)
			{
				if((p=strstr(song.psong_list[i],text)) != NULL)
				{
					printf("entry >> song_name = %s\n",song.psong_list[i]);
					
					//gdk_threads_enter();
					sungtk_clist_set_row_color(musiclist, i, "green");
					//gdk_threads_leave();
					
					song.search[i] = 1;
					song.search_flag = 1;
					p = NULL;
				}
			}
		}
	}
}

void playmode_button_callback(GtkButton *button, gpointer data)
{
	MPLAYER *pm = (MPLAYER*)data;

	switch(pm->playmode)
	{
		case list_loop:
		{
			pm->playmode = sequence;
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_sequence.png",20,20);
			break;
		}
		
		case sequence:
		{
			pm->playmode = loop;
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_loop.png",20,20);
			break;
		}
		
		case loop:
		{
			pm->playmode = randm;
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_random.png",20,20);
			break;
		}
		
		case randm:
		{
			pm->playmode = list_loop;
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_list_loop.png",20,20);
			break;
		}
	}
}

void musiclist_buttons_callback(GtkButton *button, gpointer data)
{
	MPLAYER *pm = (MPLAYER*)data;

	if(button == pm->ui.hbox_left.bmusic_list)
	{
		//int i = 0;
		//for(i=0;song.psong_list[i] != NULL && i< song.count;i++)
		//{
			//sungtk_clist_append(musiclist, song.psong_list[i]);
			//printf("%s\n",ps->psong_list[i]);
		//}
		
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list),     FALSE);
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_collect),  TRUE);
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_recently), TRUE);
	}
	
	else if(button == pm->ui.hbox_left.bmusic_collect)
	{
		//gtk_clist_clear();
		
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list),     TRUE);
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_collect),  FALSE);
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_recently), TRUE);
	}
	
	else if(button == pm->ui.hbox_left.bmusic_recently)
	{
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list),     TRUE);
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_collect),  TRUE);
		gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_recently), FALSE);
	}
}


void music_buttons_callback(GtkButton *button, gpointer data)
{
	MPLAYER *pm = (MPLAYER*)data;


	if(button == pm->ui.hbox_right.button_pause)
	{
		if(pm->playflag == playing)// 正在播放，则暂停
		{  
			//printf("pause\n");
			pm->playflag = stop;
			
			send_cmd("pause\n", pm);	
			
			gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_backward), FALSE);
			gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_forward), FALSE);			
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_pause), "./image/style/play.png",70,70);			
		}
		else //否则，开启播放
		{ 
			//printf("playing\n");
			pm->playflag = playing;
			
			send_cmd("pause\n", pm);	
			gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_backward), TRUE);
			gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_right.button_forward), TRUE);					
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_pause), "./image/style/pause.png",70,70);				
		}
	}

	else if(button == pm->ui.hbox_right.button_forward)
	{
		//printf("button_forward\n");
		send_cmd("seek 10\n", pm);	
	}
	
	else if(button == pm->ui.hbox_right.button_backward)
	{
		//printf("button_backward\n");
		send_cmd("seek -10\n", pm);
	}

	else if(button == pm->ui.hbox_right.button_next)
	{
		//printf("button_next\n");
		set_keyflag(next);
		set_playing_song(pm, 1);
		
		#if 0
		song.old= song.now;
		song.now++;
		if(song.now >= song.count)
		{
			song.now = 0;
		}
		#endif
		//set_songname(song.now);
		//strcpy(song.name, song.psong_list[song.now]);
		//playing_song(pm, song.now);
	}
	
	else if(button == pm->ui.hbox_right.button_back)
	{
		//printf("button_back\n");	
		set_keyflag(back);
		set_playing_song(pm, -1);
		#if 0
		song.old= song.now;
		song.now--;
		if(song.now < 0)
		{
			song.now = song.count - 1;
		}
		#endif
		
		//set_songname(song.now);
		//playing_song(pm, song.now);
	}

	else if(button == pm->ui.hbox_right.button_volume)
	{
		if(pm->soundflag == beam)//判断如果不是静音状态 则设置成静音状态
		{
			//printf("mute\n");
			pm->soundflag = mute;
			
			send_cmd("mute 1\n", pm);
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_volume), "./image/style/mute.png",50,50);			
		}
		else
		{
			//printf("beam\n");
			pm->soundflag = beam;
			send_cmd("mute 0\n", pm);
			sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_volume), "./image/style/beam.png",50,50);			
		}
	}
}


gboolean callback_list_release(GtkWidget *widget, GdkEventButton *event, gpointer data)  
{  
	int i;
    int row = (int)data; 	
    printf("row = %d\n", row);  

	printf(">>list 111---song.old = %d\n",song.old);
	song.old = song.now;
	song.now = row;

	printf(">>list 222---song.old = %d\n",song.old);

	if(song.search_flag == 1)
	{
		song.search_flag = 0;

		for(i=0;i< song.count;i++)
		{
			if(song.search[i] == 1)
			{
				song.search[i] = 0;

				//gdk_threads_enter();
				sungtk_clist_set_row_color(musiclist, i, "black");
				//gdk_threads_leave();
			}
		}
	}

	set_keyflag(clist);
	set_songname(song.now);
#if 0
    const char *text = sungtk_clist_get_row_data(musiclist, row);  
    printf("text = %s\n", text);  

	song.now = row;
	printf("new = %d\n",song.now);
	strcpy(song.name,text);
	printf("song_name= %s\n",song.name);
#endif
    return TRUE;  
} 
<file_sep>/c/homework/2nd_week/typewriting.c
/* ************************************************************************
 *       Filename:  test_typewriting.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月22日 星期三 11時59分14秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <termios.h>
#include <unistd.h>

//#include <windows.h>

#define uint unsigned int
#define LENGHT  40

char mygetch() 
{
    struct termios oldt, newt;
    char ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

void show_rule()
{

	printf("\n---------------------\n");
	printf(" 1.按任键开始测试\n");
	printf(" 3.输入屏幕显示字符\n");
	printf(" 4.输入首字母后计时\n");
	printf(" 2.输入过程按Esc退出\n");
	printf(" 5.输入出错以 _ 表示\n");
	printf("----------------------\n");
}
void get_string(char *buf, int n, int mode)
{
	char i,ch;
	
	i = 0;
	srand((uint)time(NULL));
	do
	{
		ch = (char)rand()%128;

		if((mode & 0x01 && ch >= 'a' && ch <= 'z')
	     ||(mode & 0x02 && ch >= 'A' && ch <= 'Z'))
		{
			buf[i] = ch;
			printf("%c",ch);
			i++;
		}
	
	}while(i<n);
	putchar('\n');
}
void typewriting(char *src,int num)
{
	char i,ch;
	int count = 0;
	int start_time,end_time;

	putchar('\n');

	for(i=0;i<num;i++)
	{	
		ch = mygetch();
		if(i == 0)
		{
			start_time = time(NULL);
		}

		if(ch == src[i])
		{
			putchar(ch);
			count++;
		}
		else
		{
			if(ch == 27)//判断是不是按下Esc键 
			{
				putchar('\n');
				exit(0);
			}
			putchar('_');
		}
	}
	end_time = time(NULL);
	printf("\n输出完成！\n用时 %ds\n",end_time-start_time);
	printf("正确率%.2f%\n",count/(num+0.0)*100);
	printf("按Esc键退出，按空格键继续\n");

	getch:
	ch = mygetch();

	switch(ch)
	{
		case ' ': system("clear"); break;
		case  27: exit(0);
		default: goto getch;
	}
}
int main()
{
	char src[LENGHT];
	int mode;
	//show_rule();
	//mygetch();
	system("clear");

	while(1)
	{
		show_rule();
		mygetch();
	   
		printf(">>>>请选择打字测试模式，输入：1 | 2 | 3\n");
		printf("1---全小写字符串\n");
		printf("2---全大写字符串\n");
		printf("3---大小写字符串\n");
		//scanf("%d",&mode);
		do
		{
			mode  = mygetch();
		}while(mode != '1' && mode != '2' && mode !='3');

		get_string(src,LENGHT,mode-48);

		typewriting(src,LENGHT);

	}

	return 0;
}

<file_sep>/gtk/4st_week/gtk_hbox.c
/* ************************************************************************
 *       Filename:  gtk_hbox.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 11时34分43秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <gtk/gtk.h>


int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	g_signal_connect(window,"destroy", G_CALLBACK(gtk_main_quit),NULL);

	//创建一个水平容器
	GtkWidget *hbox = gtk_hbox_new(TRUE,10);

	//添加到window
	gtk_container_add(GTK_CONTAINER(window),hbox);

	GtkWidget *button1 = gtk_button_new_with_label("button1");
	//添加button1到hbox
	gtk_container_add(GTK_CONTAINER(hbox),button1);

	GtkWidget *button2 = gtk_button_new_with_label("button2");
	//添加button1到hbox
	gtk_container_add(GTK_CONTAINER(hbox),button2);

	GtkWidget *button3 = gtk_button_new_with_label("button3");
	//添加button1到hbox
	gtk_container_add(GTK_CONTAINER(hbox),button3);

	gtk_widget_show_all(window);

	gtk_main();

	return 0;
}


<file_sep>/c/practice/1st_week/area_circle/area_circle.c
/* ************************************************************************
 *       Filename:  area_circle.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月16日 星期四 11時46分42秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/



#include <stdio.h>


#define	PI 3.14
int main(int argc, char *argv[])
{
	float r = 0;
	float area = 0;
	printf("please input circle's radius\n");
	scanf("%f",&r);
	area =  PI * r * r;
	printf("area=%8.3f\n",area);
	return 0;
}
<file_sep>/c/practice/3rd_week/struct/Makefile
sort:sort.c

.POHONY:clean
clean:
	rm sort
<file_sep>/network/3rd_day/broadcast.c
/* ************************************************************************
 *       Filename:  broadcast.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月02日 10时39分25秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>



int main(int argc, char *argv[])
{
	int sockfd = 0;
	char buf[1024] ="";
	unsigned short port = 8080;
	struct sockaddr_in send_addr;

	bzero(&send_addr, sizeof(send_addr));
	send_addr.sin_family  = AF_INET;
	send_addr.sin_port = htons(port);

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);

	if(sockfd < 0)
	{
		perror("socket failed!\n");
		close(sockfd);
		exit(-1);
	}

	if(argc > 1)
	{
		send_addr.sin_addr.s_addr = inet_addr(argv[1]);
	}
	else
	{
		printf("hava not a server IP\n");
		exit(-1);
	}

	int yes = 1;
	setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));
	strcpy(buf, "boardcast sucess, Dawei");

	int len = sendto(sockfd, buf, strlen(buf), 0,\
			        (struct sockaddr *)&send_addr, sizeof(send_addr));
	if(len < 0)
	{
		printf("send error\n");
	}
	close(sockfd);
	return 0;
}
<file_sep>/work/test/cim_test-zmm220/mt9v136725.h
#ifndef _MT9V136_H
#define _MT9V136_H

#define END_ 0xff

unsigned char mt9v136regs0[]=
{
//0xC8,0x16,0x00,0x83, 
//0xC8,0x18,0x00,0x9D, 
0xC8,0x1A,0x00,0x03,//0x18, 
0xC8,0x1C,0x00,0x03,//0x14, 
0x00,0x40,0x80,0x02,
			//delay = 30
0xC8,0x1E,0x00,0x04, 
0xC8,0x20,0x00,0x03, 
0xC9,0x16,0x01,0x09, 
0xC9,0x18,0x06,0x2C, 
0xC8,0x50,0x03,0x42, 
0xC8,0xF4,0x00,0x04, 
0xC8,0xF8,0x00,0x82, 
			//delay = 30
0x00,0x30,0x04,0x04, 
0x00,0x30,0x04,0x04, 
0x30,0x1A,0x10,0xD0, 
0x31,0xC0,0x14,0x04, 
0x3E,0xD8,0x87,0x9C, 
0x30,0x42,0x20,0xE1, 
0x30,0xD4,0x80,0x20, 
0x30,0xC0,0x00,0x26, 
0x30,0x1A,0x10,0xD4,
0xA8,0x02,0x00,0xD3, 
0xC8,0x78,0x00,0xA0, 
0xC8,0x76,0x01,0x40, 
0xBC,0x04,0x00,0xFC, 
0xBC,0x38,0x00,0x7f, 
0xBC,0x3A,0x00,0xbf,	
0xBC,0x3C,0x00,0xbf, 
0xBC,0x04,0x00,0xFc,	
0xC9,0x1A,0x00,0x0F, 
0xC9,0x1C,0x00,0x06, 
0xC8,0xFC,0x00,0x0C, 
0xC8,0xFE,0x00,0x30, 
0xC9,0x12,0x00,0x0C, 
0xC9,0x14,0x00,0x4B, 
0xC9,0x16,0x01,0x09, 
0xC9,0x18,0x06,0x2C, 
0xC9,0x07,0xA8,0x01, 
0xC9,0x0A,0x14,0x14, 
0xC9,0x0C,0x14,0x14, 
0xC9,0x0E,0x32,0x32, 
0xC9,0x10,0x32,0x32, 
0xC9,0x1E,0x01,0xF4, 
0xC9,0x20,0x27,0x10,
0xC9,0x00,0x80,0x4a, 
0xC9,0x04,0x08,0x02,  
0xC9,0x06,0x02,0xa8,  
0xC9,0x08,0x07,0x7f,  
0xBC,0x06,0x01,0x5E, 
0xC8,0xE6,0x80,0x80, 
0xC8,0x3E,0x00,0x01, 
0x32,0x80,0x00,0xAA, 
0xC9,0x16,0x01,0x09, 
0xC9,0x18,0x06,0x2C, 
0xC8,0xCE,0x33,0xA1, 
0xC8,0xD0,0xEC,0x08, 
0xC8,0xD2,0xFF,0xC0, 
0xC8,0xDE,0x00,0x33, 
0x00,0x40,0x80,0x02, 
			//delay = 30
0x09,0x82,0x00,0x01, 
0x09,0x8A,0x70,0x00, 
0xF0,0x00,0x72,0xCF, 
0xF0,0x02,0xFF,0x00, 
0xF0,0x04,0x3E,0xD0, 
0xF0,0x06,0x92,0x00, 
0xF0,0x08,0x71,0xCF, 
0xF0,0x0A,0xFF,0xFF, 
0xF0,0x0C,0xF2,0x18, 
0xF0,0x0E,0xB1,0x10, 
0xF0,0x10,0x92,0x05, 
0xF0,0x12,0xB1,0x11, 
0xF0,0x14,0x92,0x04, 
0xF0,0x16,0xB1,0x12, 
0xF0,0x18,0x70,0xCF, 
0xF0,0x1A,0xFF,0x00, 
0xF0,0x1C,0x30,0xC0, 
0xF0,0x1E,0x90,0x00, 
0xF0,0x20,0x7F,0xE0, 
0xF0,0x22,0xB1,0x13, 
0xF0,0x24,0x70,0xCF, 
0xF0,0x26,0xFF,0xFF, 
0xF0,0x28,0xE7,0x1C, 
0xF0,0x2A,0x88,0x36, 
0xF0,0x2C,0x09,0x0F, 
0xF0,0x2E,0x00,0xB3, 
0xF0,0x30,0x69,0x13, 
0xF0,0x32,0xE1,0x80, 
0xF0,0x34,0xD8,0x08, 
0xF0,0x36,0x20,0xCA, 
0xF0,0x38,0x03,0x22, 
0xF0,0x3A,0x71,0xCF, 
0xF0,0x3C,0xFF,0xFF, 
0xF0,0x3E,0xE5,0x68, 
0xF0,0x40,0x91,0x35, 
0xF0,0x42,0x22,0x0A, 
0xF0,0x44,0x1F,0x80, 
0xF0,0x46,0xFF,0xFF, 
0xF0,0x48,0xF2,0x18, 
0xF0,0x4A,0x29,0x05, 
0xF0,0x4C,0x00,0x3E, 
0xF0,0x4E,0x12,0x22, 
0xF0,0x50,0x11,0x01, 
0xF0,0x52,0x21,0x04, 
0xF0,0x54,0x0F,0x81, 
0xF0,0x56,0x00,0x00, 
0xF0,0x58,0xFF,0xF0, 
0xF0,0x5A,0x21,0x8C, 
0xF0,0x5C,0xF0,0x10, 
0xF0,0x5E,0x1A,0x22, 
0xF0,0x60,0x10,0x44, 
0xF0,0x62,0x12,0x20, 
0xF0,0x64,0x11,0x02, 
0xF0,0x66,0xF7,0x87, 
0xF0,0x68,0x22,0x4F, 
0xF0,0x6A,0x03,0x83, 
0xF0,0x6C,0x1A,0x20, 
0xF0,0x6E,0x10,0xC4, 
0xF0,0x70,0xF0,0x09, 
0xF0,0x72,0xBA,0xAE, 
0xF0,0x74,0x7B,0x50, 
0xF0,0x76,0x1A,0x20, 
0xF0,0x78,0x10,0x84, 
0xF0,0x7A,0x21,0x45, 
0xF0,0x7C,0x01,0xC1, 
0xF0,0x7E,0x1A,0x22, 
0xF0,0x80,0x10,0x44, 
0xF0,0x82,0x70,0xCF, 
0xF0,0x84,0xFF,0x00, 
0xF0,0x86,0x3E,0xD0, 
0xF0,0x88,0xB0,0x60, 
0xF0,0x8A,0xB0,0x25, 
0xF0,0x8C,0x7E,0xE0, 
0xF0,0x8E,0x78,0xE0, 
0xF0,0x90,0x71,0xCF, 
0xF0,0x92,0xFF,0xFF, 
0xF0,0x94,0xF2,0x18, 
0xF0,0x96,0x91,0x12, 
0xF0,0x98,0x72,0xCF, 
0xF0,0x9A,0xFF,0xFF, 
0xF0,0x9C,0xE7,0x1C, 
0xF0,0x9E,0x8A,0x57, 
0xF0,0xA0,0x20,0x04, 
0xF0,0xA2,0x0F,0x80, 
0xF0,0xA4,0x00,0x00, 
0xF0,0xA6,0xFF,0xF0, 
0xF0,0xA8,0xE2,0x80, 
0xF0,0xAA,0x20,0xC5, 
0xF0,0xAC,0x01,0x61, 
0xF0,0xAE,0x20,0xC5, 
0xF0,0xB0,0x03,0x22, 
0xF0,0xB2,0xB1,0x12, 
0xF0,0xB4,0x71,0xCF, 
0xF0,0xB6,0xFF,0x00, 
0xF0,0xB8,0x3E,0xD0, 
0xF0,0xBA,0xB1,0x04, 
0xF0,0xBC,0x7E,0xE0, 
0xF0,0xBE,0x78,0xE0, 
0xF0,0xC0,0x70,0xCF, 
0xF0,0xC2,0xFF,0xFF, 
0xF0,0xC4,0xE7,0x1C, 
0xF0,0xC6,0x88,0x57, 
0xF0,0xC8,0x71,0xCF, 
0xF0,0xCA,0xFF,0xFF, 
0xF0,0xCC,0xF2,0x18, 
0xF0,0xCE,0x91,0x13, 
0xF0,0xD0,0xEA,0x84, 
0xF0,0xD2,0xB8,0xA9, 
0xF0,0xD4,0x78,0x10, 
0xF0,0xD6,0xF0,0x03, 
0xF0,0xD8,0xB8,0x89, 
0xF0,0xDA,0xB8,0x8C, 
0xF0,0xDC,0xB1,0x13, 
0xF0,0xDE,0x71,0xCF, 
0xF0,0xE0,0xFF,0x00, 
0xF0,0xE2,0x30,0xC0, 
0xF0,0xE4,0xB1,0x00, 
0xF0,0xE6,0x7E,0xE0, 
0xF0,0xE8,0xC0,0xF1, 
0xF0,0xEA,0x09,0x1E, 
0xF0,0xEC,0x03,0xC0, 
0xF0,0xEE,0xC1,0xA1, 
0xF0,0xF0,0x75,0x08, 
0xF0,0xF2,0x76,0x28, 
0xF0,0xF4,0x77,0x48, 
0xF0,0xF6,0xC2,0x40, 
0xF0,0xF8,0xD8,0x20, 
0xF0,0xFA,0x71,0xCF, 
0xF0,0xFC,0x00,0x03, 
0xF0,0xFE,0x20,0x67, 
0xF1,0x00,0xDA,0x02, 
0xF1,0x02,0x08,0xAE, 
0xF1,0x04,0x03,0xA0, 
0xF1,0x06,0x73,0xC9, 
0xF1,0x08,0x0E,0x25, 
0xF1,0x0A,0x13,0xC0, 
0xF1,0x0C,0x0B,0x5E, 
0xF1,0x0E,0x01,0x60, 
0xF1,0x10,0xD8,0x06, 
0xF1,0x12,0xFF,0xBC, 
0xF1,0x14,0x0C,0xCE, 
0xF1,0x16,0x01,0x00, 
0xF1,0x18,0xD8,0x00, 
0xF1,0x1A,0xB8,0x9E, 
0xF1,0x1C,0x0E,0x5A, 
0xF1,0x1E,0x03,0x20, 
0xF1,0x20,0xD9,0x01, 
0xF1,0x22,0xD8,0x00, 
0xF1,0x24,0xB8,0x9E, 
0xF1,0x26,0x0E,0xB6, 
0xF1,0x28,0x03,0x20, 
0xF1,0x2A,0xD9,0x01, 
0xF1,0x2C,0x8D,0x14, 
0xF1,0x2E,0x08,0x17, 
0xF1,0x30,0x01,0x91, 
0xF1,0x32,0x8D,0x16, 
0xF1,0x34,0xE8,0x07, 
0xF1,0x36,0x0B,0x36, 
0xF1,0x38,0x01,0x60, 
0xF1,0x3A,0xD8,0x07, 
0xF1,0x3C,0x0B,0x52, 
0xF1,0x3E,0x01,0x60, 
0xF1,0x40,0xD8,0x11, 
0xF1,0x42,0x8D,0x14, 
0xF1,0x44,0xE0,0x87, 
0xF1,0x46,0xD8,0x00, 
0xF1,0x48,0x20,0xCA, 
0xF1,0x4A,0x02,0x62, 
0xF1,0x4C,0x00,0xC9, 
0xF1,0x4E,0x03,0xE0, 
0xF1,0x50,0xC0,0xA1, 
0xF1,0x52,0x78,0xE0, 
0xF1,0x54,0xC0,0xF1, 
0xF1,0x56,0x08,0xB2, 
0xF1,0x58,0x03,0xC0, 
0xF1,0x5A,0x76,0xCF, 
0xF1,0x5C,0xFF,0xFF, 
0xF1,0x5E,0xE5,0x40, 
0xF1,0x60,0x75,0xCF, 
0xF1,0x62,0xFF,0xFF, 
0xF1,0x64,0xE5,0x68, 
0xF1,0x66,0x95,0x17, 
0xF1,0x68,0x96,0x40, 
0xF1,0x6A,0x77,0xCF, 
0xF1,0x6C,0xFF,0xFF, 
0xF1,0x6E,0xE5,0x42, 
0xF1,0x70,0x95,0x38, 
0xF1,0x72,0x0A,0x0D, 
0xF1,0x74,0x00,0x01, 
0xF1,0x76,0x97,0x40, 
0xF1,0x78,0x0A,0x11, 
0xF1,0x7A,0x00,0x40, 
0xF1,0x7C,0x0B,0x0A, 
0xF1,0x7E,0x01,0x00, 
0xF1,0x80,0x95,0x17, 
0xF1,0x82,0xB6,0x00, 
0xF1,0x84,0x95,0x18, 
0xF1,0x86,0xB7,0x00, 
0xF1,0x88,0x76,0xCF, 
0xF1,0x8A,0xFF,0xFF, 
0xF1,0x8C,0xE5,0x44, 
0xF1,0x8E,0x96,0x20, 
0xF1,0x90,0x95,0x15, 
0xF1,0x92,0x08,0x13, 
0xF1,0x94,0x00,0x40, 
0xF1,0x96,0x0E,0x1E, 
0xF1,0x98,0x01,0x20, 
0xF1,0x9A,0xD9,0x00, 
0xF1,0x9C,0x95,0x15, 
0xF1,0x9E,0xB6,0x00, 
0xF1,0xA0,0xFF,0xA1, 
0xF1,0xA2,0x75,0xCF, 
0xF1,0xA4,0xFF,0xFF, 
0xF1,0xA6,0xE7,0x1C, 
0xF1,0xA8,0x77,0xCF, 
0xF1,0xAA,0xFF,0xFF, 
0xF1,0xAC,0xE5,0x46, 
0xF1,0xAE,0x97,0x40, 
0xF1,0xB0,0x8D,0x16, 
0xF1,0xB2,0x76,0xCF, 
0xF1,0xB4,0xFF,0xFF, 
0xF1,0xB6,0xE5,0x48, 
0xF1,0xB8,0x8D,0x37, 
0xF1,0xBA,0x08,0x0D, 
0xF1,0xBC,0x00,0x81, 
0xF1,0xBE,0x96,0x40, 
0xF1,0xC0,0x09,0x15, 
0xF1,0xC2,0x00,0x80, 
0xF1,0xC4,0x0F,0xD6, 
0xF1,0xC6,0x01,0x00, 
0xF1,0xC8,0x8D,0x16, 
0xF1,0xCA,0xB7,0x00, 
0xF1,0xCC,0x8D,0x17, 
0xF1,0xCE,0xB6,0x00, 
0xF1,0xD0,0xFF,0xB0, 
0xF1,0xD2,0xFF,0xBC, 
0xF1,0xD4,0x00,0x41, 
0xF1,0xD6,0x03,0xC0, 
0xF1,0xD8,0xC0,0xF1, 
0xF1,0xDA,0x0D,0x9E, 
0xF1,0xDC,0x01,0x00, 
0xF1,0xDE,0xE8,0x04, 
0xF1,0xE0,0xFF,0x88, 
0xF1,0xE2,0xF0,0x0A, 
0xF1,0xE4,0x0D,0x6A, 
0xF1,0xE6,0x01,0x00, 
0xF1,0xE8,0x0D,0x8E, 
0xF1,0xEA,0x01,0x00, 
0xF1,0xEC,0xE8,0x7E, 
0xF1,0xEE,0xFF,0x85, 
0xF1,0xF0,0x0D,0x72, 
0xF1,0xF2,0x01,0x00, 
0xF1,0xF4,0xFF,0x8C, 
0xF1,0xF6,0xFF,0xA7, 
0xF1,0xF8,0xFF,0xB2, 
0xF1,0xFA,0xD8,0x00, 
0xF1,0xFC,0x73,0xCF, 
0xF1,0xFE,0xFF,0xFF, 
0xF2,0x00,0xF2,0x40, 
0xF2,0x02,0x23,0x15, 
0xF2,0x04,0x00,0x01, 
0xF2,0x06,0x81,0x41, 
0xF2,0x08,0xE0,0x02, 
0xF2,0x0A,0x81,0x20, 
0xF2,0x0C,0x08,0xF7, 
0xF2,0x0E,0x81,0x34, 
0xF2,0x10,0xA1,0x40, 
0xF2,0x12,0xD8,0x00, 
0xF2,0x14,0xC0,0xD1, 
0xF2,0x16,0x7E,0xE0, 
0xF2,0x18,0x53,0x51, 
0xF2,0x1A,0x30,0x34, 
0xF2,0x1C,0x20,0x6F, 
0xF2,0x1E,0x6E,0x5F, 
0xF2,0x20,0x73,0x74, 
0xF2,0x22,0x61,0x72, 
0xF2,0x24,0x74,0x5F, 
0xF2,0x26,0x73,0x74, 
0xF2,0x28,0x72,0x65, 
0xF2,0x2A,0x61,0x6D, 
0xF2,0x2C,0x69,0x6E, 
0xF2,0x2E,0x67,0x20, 
0xF2,0x30,0x25,0x64, 
0xF2,0x32,0x20,0x25, 
0xF2,0x34,0x64,0x0A,
0xF2,0x36,0x00,0x00, 
0xF2,0x38,0x00,0x00, 
0xF2,0x3A,0x00,0x00, 
0xF2,0x3C,0x00,0x00, 
0xF2,0x3E,0x00,0x00, 
0xF2,0x40,0xFF,0xFF, 
0xF2,0x42,0xE8,0x28, 
0xF2,0x44,0xFF,0xFF, 
0xF2,0x46,0xF0,0xE8, 
0xF2,0x48,0xFF,0xFF, 
0xF2,0x4A,0xE8,0x08, 
0xF2,0x4C,0xFF,0xFF, 
0xF2,0x4E,0xF1,0x54, 
0x09,0x8E,0x00,0x00, 
0xE0,0x00,0x05,0xD8, 
0xE0,0x02,0x04,0x03, 
0x00,0x40,0xFF,0xF8, 
			//delay = 30
0x00,0x40,0xFF,0xF9, 
			//delay = 30
0x32,0x10,0x00,0xB0, 
0x09,0x8e,0x48,0x26, 
0xc8,0x26,0x01,0x00, 
0xc8,0x6c,0x00,0x80, 
0xc8,0x6e,0x00,0x80, 
0xc8,0x70,0x00,0x20, 
0xc8,0x72,0x28,/*0x01*/0x80, 
0xa8,0x0e,0xa8,0x08, 
0x30,0x32,0x01,0x00, 
0x30,0x34,0x01,0x00, 
0x30,0x36,0x01,0x00, 
0x30,0x38,0x01,0x00, 
0xc8,0x22,0x00,0xe0, 
0x00,0x40,0x80,0x02, 
0x00,0x40,0x80,0x04, 
0xc8,0x68,0x02,0x38, 
0xa8,0x0e,0x2a,0x06, 
0xa8,0x12,0x04,0x00, 
0xa4,0x04,0x01,0x01, 
0xC8,0xF4,0x00,0x04, 
0xC8,0xF6,0x00,0x00, 
0xC8,0xF8,0x00,0x82, 
0xC8,0xFA,0x00,0x5E, 
0x00,0x40,0x80,0x04, 
0x32,0x6c,0x10,0x03, 
0x09,0x8E,0x48,0x8A, 
0xC8,0x8A,0x02,0x14, 
0xC8,0x8C,0xFE,0xDE, 
0xC8,0x8E,0x00,0x0D, 
0xC8,0x90,0xFF,0xCB, 
0xC8,0x92,0x01,0x4D, 
0xC8,0x94,0xFF,0xE8, 
0xC8,0x96,0xFF,0xC6, 
0xC8,0x98,0xFF,0x2B, 
0xC8,0x9A,0x02,0x0F, 
0xC8,0x9C,0x00,0x1E, 
0xC8,0x9E,0x00,0x44, 
0xC8,0xA0,0xFF,0xB7, 
0xC8,0xA2,0x00,0x9F, 
0xC8,0xA4,0xFF,0xAA, 
0xC8,0xA6,0x00,0x05, 
0xC8,0xA8,0xFF,0xD3, 
0xC8,0xAA,0x00,0x28, 
0xC8,0xAC,0x00,0x36, 
0xC8,0xAE,0x00,0x67, 
0xC8,0xB0,0xFF,0x63, 
0xC8,0xB2,0x00,0x12, 
0xC8,0xB4,0xFF,0xD9, 
0xC8,0xCA,0x03,0x01, 
0xC8,0xCC,0x00,0x00, 
0xC8,0xCE,0x00,0x00, 
0xC8,0xD0,0x00,0x80, 
0xC8,0xD2,0x1B,0x80, 
0xC8,0xD4,0x16,0x80, 
0xC8,0xD6,0x01,0xAC, 
0xC8,0xD8,0x00,0x3C, 
0xC8,0xDA,0x00,0x00, 
0xC8,0xDC,0x00,0x3C, 
0xC8,0xDE,0x00,0x57, 
0xAC,0x32,0x2E,0x7f,  
0xAC,0x34,0x1B,0x83, 
0x09,0x8E,0xBC,0x0C, 
0xBC,0x02,0x00,0x07, 
0xBC,0x0C,0x00,0x03, 
0xBC,0x08,0x02,0x01, 
0xBC,0x0E,0x0a,0x20, 
0xBC,0x10,0x4f,0x71, 
0xBC,0x12,0x8d,0xa3, 
0xBC,0x14,0xb3,0xc0,
0xBC,0x16,0xcc,0xd5, 
0xBC,0x18,0xdd,0xe4, 
0xBC,0x1A,0xeb,0xf0, 
0xBC,0x1C,0xf6,0xfb, 
0xBC,0x1E,0xFf,0x00, 
//0xc8,0x1c,0x00,0x14, 
0x00,0x40,0x80,0x02, 
0x36,0x40,0x03,0x70,	
0x36,0x42,0x30,0xE8,	
0x36,0x44,0x0A,0xCF,	
0x36,0x46,0x62,0xCC,	
0x36,0x48,0xA4,0x2F,	
0x36,0x4A,0x02,0xD0,	
0x36,0x4C,0xB9,0xAB,	
0x36,0x4E,0x1B,0x0F,	
0x36,0x50,0x1F,0x2B,	
0x36,0x52,0x99,0x0F,	
0x36,0x54,0x02,0xD0,	
0x36,0x56,0xBD,0x89,	
0x36,0x58,0x4F,0x2E,	
0x36,0x5A,0x81,0x2A,	
0x36,0x5C,0xAF,0xCE,	
0x36,0x5E,0x03,0x90,	
0x36,0x60,0x9E,0xC9,	
0x36,0x62,0x16,0xCF,	
0x36,0x64,0x11,0x0D,	
0x36,0x66,0xBF,0xCF,	
0x36,0x80,0x0B,0x8C,	
0x36,0x82,0x94,0x6E,	
0x36,0x84,0xB1,0x4D,	
0x36,0x86,0x51,0xCE,	
0x36,0x88,0x0E,0xEF,	
0x36,0x8A,0x51,0x0A,	
0x36,0x8C,0x85,0x2E,	
0x36,0x8E,0x13,0xAB,	
0x36,0x90,0x20,0xEE,	
0x36,0x92,0x5F,0x6D,	
0x36,0x94,0x07,0xEC,	
0x36,0x96,0xDB,0x4D,	
0x36,0x98,0x03,0xAE,	
0x36,0x9A,0x1F,0xAE,	
0x36,0x9C,0xE3,0xCD,	
0x36,0x9E,0x00,0xED,	
0x36,0xA0,0xC4,0x0D,	
0x36,0xA2,0x46,0xCB,	
0x36,0xA4,0x1F,0x4E,	
0x36,0xA6,0x28,0xAB,	
0x36,0xC0,0x7E,0xED,	
0x36,0xC2,0x09,0x8D,	
0x36,0xC4,0x89,0xF1,	
0x36,0xC6,0x95,0xEE,	
0x36,0xC8,0x47,0xCF,	
0x36,0xCA,0x2B,0xCE,	
0x36,0xCC,0xC7,0x08,	
0x36,0xCE,0x8E,0xD1,	
0x36,0xD0,0x06,0x0D,	
0x36,0xD2,0x21,0xF0,	
0x36,0xD4,0x6D,0x0D,	
0x36,0xD6,0xC7,0x2E,	
0x36,0xD8,0x93,0x71,	
0x36,0xDA,0x05,0xF0,	
0x36,0xDC,0x73,0xD0,	
0x36,0xDE,0x3D,0x8D,	
0x36,0xE0,0x12,0x0D,	
0x36,0xE2,0x89,0xD1,	
0x36,0xE4,0xEB,0xCD,	
0x36,0xE6,0x29,0xD0,	
0x37,0x00,0xA6,0x6E,	
0x37,0x02,0x65,0xCF,	
0x37,0x04,0x02,0x51,	
0x37,0x06,0xC2,0x6F,	
0x37,0x08,0xC2,0xB1,	
0x37,0x0A,0xD9,0x2C,	
0x37,0x0C,0x39,0x8F,	
0x37,0x0E,0x64,0x0E,	
0x37,0x10,0xC3,0xCF,	
0x37,0x12,0x20,0x0E,	
0x37,0x14,0x22,0x4B,	
0x37,0x16,0x1E,0x8F,	
0x37,0x18,0x97,0x30,	
0x37,0x1A,0xA1,0x6F,	
0x37,0x1C,0x33,0x11,	
0x37,0x1E,0xB8,0xAD,	
0x37,0x20,0x4B,0x8F,	
0x37,0x22,0x57,0x8F,	
0x37,0x24,0xCE,0x6F,	
0x37,0x26,0xF4,0xCF,	
0x37,0x40,0x95,0xAE,	
0x37,0x42,0x97,0xAF,	
0x37,0x44,0x71,0xAC,	
0x37,0x46,0x15,0x8D,	
0x37,0x48,0x1F,0x72,	
0x37,0x4A,0x9A,0x4F,	
0x37,0x4C,0xCA,0x6D,	
0x37,0x4E,0x02,0xD1,	
0x37,0x50,0x17,0x8F,	
0x37,0x52,0xF1,0x2F,	
0x37,0x54,0xDC,0xCE,	
0x37,0x56,0x07,0x10,	
0x37,0x58,0x05,0xB2,	
0x37,0x5A,0xDB,0x11,	
0x37,0x5C,0xC6,0x32,	
0x37,0x5E,0x8B,0xCE,	
0x37,0x60,0x99,0x2F,	
0x37,0x62,0x07,0x90,	
0x37,0x64,0x63,0xCD,	
0x37,0x66,0x39,0xD0,	
0x37,0x82,0x00,0xD8,	
0x37,0x84,0x01,0x3C,	
0x32,0x10,0x02,0xb8,	
0x09,0x8E,0x48,0x60, 
0xc8,0x60,0x01,0x00, 
0xc8,0x61,0x00,0x00, 
0x09,0x8E,0x48,0x61, 
0x00,0x40,0x80,0x02, 
0x09,0x8E,0x48,0x02, 
0xc8,0x02,0x00,0x10, 
0xc8,0x06,0x02,0x97, 
0xc8,0x04,0x01,0xf3, 
0xc8,0x14,0x01,0xe3, 
0xc8,0x0e,0x02,0x0d, 
0xc8,0x48,0x00,0x00, 
0xc8,0x4a,0x00,0x00, 
0xc8,0x4c,0x02,0x80, 
0xc8,0x4e,0x01,0xe0, 
0xc8,0x54,0x02,0x80, 
0xc8,0x56,0x01,0xe0, 
0xc8,0x50,0x03,0x42, 
0xc8,0xf0,0x02,0x7f, 
0xc8,0xf2,0x01,0xdf, 
0xc8,0xf4,0x00,0x04, 
0xc8,0xf6,0x00,0x04, 
0xc8,0xf8,0x00,0x7e, 
0xc8,0xfa,0x00,0x5e, 
0xdc,0x00,0x28,0x00, 
0xc8,0x28,0x00,0x02,
		       //delay = 10
0xc9,0x05,0x02,0x00, 
0xc9,0x08,0x03,0x00, 
		       //delay = 10 
//0x09,0x8e,0x48,0x18, 
//0x09,0x90,0x00,0x9b,  //open streaming


0x09,0x8E,0x48,0x48,  //VGA streaming
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4A,
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4C,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x4E,
0x09,0x90,0x01,0xE0,
0x09,0x8E,0x48,0x54,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x56,
0x09,0x90,0x01,0xe0,
0x09,0x8E,0xC8,0x50,
0x09,0x90,0x03,0x00,
0x09,0x8E,0x48,0xF0,
0x09,0x90,0x02,0x7F,
0x09,0x8E,0x48,0xF2,
0x09,0x90,0x01,0xdF,
0x09,0x8E,0x48,0xF4,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF6,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF8,
0x09,0x90,0x00,0x7e,
0x09,0x8E,0x48,0xFA,
0x09,0x90,0x00,0x5e,
0x09,0x8E,0xDC,0x00,
0x09,0x90,0x28,0x00,
0x09,0x8e,0x48,0x16,
0x09,0x90,0x00,0x83,
0xdc,0x00,0x28,0x31,
0x00,0x40,0x80,0x02,
										//delay = 10 //VGA streaming

0x09,0x8E,0x48,0x28,
0xc8,0x28,0x00,0x02, //mirror
0xdc,0x00,0x28,0x31, 
0x00,0x40,0x80,0x02, 
										//delay = 30  //normal[flip section]

0x09,0x8E,0x48,0x69,  //brightness
0x09,0x90,0x38,0x00, 

0x09,0x8E,0x48,0x60,  //Hue
0x09,0x90,0x01,0x00,
0x09,0x8E,0x48,0x61,
0x09,0x90,0x00,0x00,
0x00,0x40,0x80,0x02,

0x09,0x8E,0x49,0x05,  //sharpness
0x09,0x90,0x02,0x00,
0x09,0x8E,0x49,0x08,
0x09,0x90,0x02,0x00,
//modify by seven 2011-6-7
//Disable auto exposure
#if 0
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x00,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
0x30,0x12,0x01,0x2C,
#endif
//Enable auto exposure
#if 1
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x1F,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
#endif

0xC8,0x16,0x00,0xBD,
0xC8,0x18,0x00,0xE3,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,

END_,END_,END_,END_
};


unsigned char mt9v136regs1[]=
{
0xC8,0x16,0x00,0xBD, 
0xC8,0x18,0x00,0xE3, 
0xC8,0x1A,0x00,0x06,//0x18, 
0xC8,0x1C,0x00,0x05,//0x14, 
0x00,0x40,0x80,0x02,
			//delay = 30
0xC8,0x1E,0x00,0x04, 
0xC8,0x20,0x00,0x03, 
0xC9,0x16,0x01,0x09, 
0xC9,0x18,0x06,0x2C, 
0xC8,0x50,0x03,0x42, 
0xC8,0xF4,0x00,0x04, 
0xC8,0xF8,0x00,0x82, 
			//delay = 30
0x00,0x30,0x04,0x04, 
0x00,0x30,0x04,0x04, 
0x30,0x1A,0x10,0xD0, 
0x31,0xC0,0x14,0x04, 
0x3E,0xD8,0x87,0x9C, 
0x30,0x42,0x20,0xE1, 
0x30,0xD4,0x80,0x20, 
0x30,0xC0,0x00,0x26, 
0x30,0x1A,0x10,0xD4,
0xA8,0x02,0x00,0xD3, 
0xC8,0x78,0x00,0xA0, 
0xC8,0x76,0x01,0x40, 
0xBC,0x04,0x00,0xFC, 
0xBC,0x38,0x00,0x7f, 
0xBC,0x3A,0x00,0xbf,	
0xBC,0x3C,0x00,0xbf, 
0xBC,0x04,0x00,0xFc,	
0xC9,0x1A,0x00,0x0F, 
0xC9,0x1C,0x00,0x06, 
0xC8,0xFC,0x00,0x0C, 
0xC8,0xFE,0x00,0x30, 
0xC9,0x12,0x00,0x0C, 
0xC9,0x14,0x00,0x4B, 
0xC9,0x16,0x01,0x09, 
0xC9,0x18,0x06,0x2C, 
0xC9,0x07,0xA8,0x01, 
0xC9,0x0A,0x14,0x14, 
0xC9,0x0C,0x14,0x14, 
0xC9,0x0E,0x32,0x32, 
0xC9,0x10,0x32,0x32, 
0xC9,0x1E,0x01,0xF4, 
0xC9,0x20,0x27,0x10,
0xC9,0x00,0x80,0x4a, 
0xC9,0x04,0x08,0x02,  
0xC9,0x06,0x02,0xa8,  
0xC9,0x08,0x07,0x7f,  
0xBC,0x06,0x01,0x5E, 
0xC8,0xE6,0x80,0x80, 
0xC8,0x3E,0x00,0x01, 
0x32,0x80,0x00,0xAA, 
0xC9,0x16,0x01,0x09, 
0xC9,0x18,0x06,0x2C, 
0xC8,0xCE,0x33,0xA1, 
0xC8,0xD0,0xEC,0x08, 
0xC8,0xD2,0xFF,0xC0, 
0xC8,0xDE,0x00,0x33, 
0x00,0x40,0x80,0x02, 
			//delay = 30
0x09,0x82,0x00,0x01, 
0x09,0x8A,0x70,0x00, 
0xF0,0x00,0x72,0xCF, 
0xF0,0x02,0xFF,0x00, 
0xF0,0x04,0x3E,0xD0, 
0xF0,0x06,0x92,0x00, 
0xF0,0x08,0x71,0xCF, 
0xF0,0x0A,0xFF,0xFF, 
0xF0,0x0C,0xF2,0x18, 
0xF0,0x0E,0xB1,0x10, 
0xF0,0x10,0x92,0x05, 
0xF0,0x12,0xB1,0x11, 
0xF0,0x14,0x92,0x04, 
0xF0,0x16,0xB1,0x12, 
0xF0,0x18,0x70,0xCF, 
0xF0,0x1A,0xFF,0x00, 
0xF0,0x1C,0x30,0xC0, 
0xF0,0x1E,0x90,0x00, 
0xF0,0x20,0x7F,0xE0, 
0xF0,0x22,0xB1,0x13, 
0xF0,0x24,0x70,0xCF, 
0xF0,0x26,0xFF,0xFF, 
0xF0,0x28,0xE7,0x1C, 
0xF0,0x2A,0x88,0x36, 
0xF0,0x2C,0x09,0x0F, 
0xF0,0x2E,0x00,0xB3, 
0xF0,0x30,0x69,0x13, 
0xF0,0x32,0xE1,0x80, 
0xF0,0x34,0xD8,0x08, 
0xF0,0x36,0x20,0xCA, 
0xF0,0x38,0x03,0x22, 
0xF0,0x3A,0x71,0xCF, 
0xF0,0x3C,0xFF,0xFF, 
0xF0,0x3E,0xE5,0x68, 
0xF0,0x40,0x91,0x35, 
0xF0,0x42,0x22,0x0A, 
0xF0,0x44,0x1F,0x80, 
0xF0,0x46,0xFF,0xFF, 
0xF0,0x48,0xF2,0x18, 
0xF0,0x4A,0x29,0x05, 
0xF0,0x4C,0x00,0x3E, 
0xF0,0x4E,0x12,0x22, 
0xF0,0x50,0x11,0x01, 
0xF0,0x52,0x21,0x04, 
0xF0,0x54,0x0F,0x81, 
0xF0,0x56,0x00,0x00, 
0xF0,0x58,0xFF,0xF0, 
0xF0,0x5A,0x21,0x8C, 
0xF0,0x5C,0xF0,0x10, 
0xF0,0x5E,0x1A,0x22, 
0xF0,0x60,0x10,0x44, 
0xF0,0x62,0x12,0x20, 
0xF0,0x64,0x11,0x02, 
0xF0,0x66,0xF7,0x87, 
0xF0,0x68,0x22,0x4F, 
0xF0,0x6A,0x03,0x83, 
0xF0,0x6C,0x1A,0x20, 
0xF0,0x6E,0x10,0xC4, 
0xF0,0x70,0xF0,0x09, 
0xF0,0x72,0xBA,0xAE, 
0xF0,0x74,0x7B,0x50, 
0xF0,0x76,0x1A,0x20, 
0xF0,0x78,0x10,0x84, 
0xF0,0x7A,0x21,0x45, 
0xF0,0x7C,0x01,0xC1, 
0xF0,0x7E,0x1A,0x22, 
0xF0,0x80,0x10,0x44, 
0xF0,0x82,0x70,0xCF, 
0xF0,0x84,0xFF,0x00, 
0xF0,0x86,0x3E,0xD0, 
0xF0,0x88,0xB0,0x60, 
0xF0,0x8A,0xB0,0x25, 
0xF0,0x8C,0x7E,0xE0, 
0xF0,0x8E,0x78,0xE0, 
0xF0,0x90,0x71,0xCF, 
0xF0,0x92,0xFF,0xFF, 
0xF0,0x94,0xF2,0x18, 
0xF0,0x96,0x91,0x12, 
0xF0,0x98,0x72,0xCF, 
0xF0,0x9A,0xFF,0xFF, 
0xF0,0x9C,0xE7,0x1C, 
0xF0,0x9E,0x8A,0x57, 
0xF0,0xA0,0x20,0x04, 
0xF0,0xA2,0x0F,0x80, 
0xF0,0xA4,0x00,0x00, 
0xF0,0xA6,0xFF,0xF0, 
0xF0,0xA8,0xE2,0x80, 
0xF0,0xAA,0x20,0xC5, 
0xF0,0xAC,0x01,0x61, 
0xF0,0xAE,0x20,0xC5, 
0xF0,0xB0,0x03,0x22, 
0xF0,0xB2,0xB1,0x12, 
0xF0,0xB4,0x71,0xCF, 
0xF0,0xB6,0xFF,0x00, 
0xF0,0xB8,0x3E,0xD0, 
0xF0,0xBA,0xB1,0x04, 
0xF0,0xBC,0x7E,0xE0, 
0xF0,0xBE,0x78,0xE0, 
0xF0,0xC0,0x70,0xCF, 
0xF0,0xC2,0xFF,0xFF, 
0xF0,0xC4,0xE7,0x1C, 
0xF0,0xC6,0x88,0x57, 
0xF0,0xC8,0x71,0xCF, 
0xF0,0xCA,0xFF,0xFF, 
0xF0,0xCC,0xF2,0x18, 
0xF0,0xCE,0x91,0x13, 
0xF0,0xD0,0xEA,0x84, 
0xF0,0xD2,0xB8,0xA9, 
0xF0,0xD4,0x78,0x10, 
0xF0,0xD6,0xF0,0x03, 
0xF0,0xD8,0xB8,0x89, 
0xF0,0xDA,0xB8,0x8C, 
0xF0,0xDC,0xB1,0x13, 
0xF0,0xDE,0x71,0xCF, 
0xF0,0xE0,0xFF,0x00, 
0xF0,0xE2,0x30,0xC0, 
0xF0,0xE4,0xB1,0x00, 
0xF0,0xE6,0x7E,0xE0, 
0xF0,0xE8,0xC0,0xF1, 
0xF0,0xEA,0x09,0x1E, 
0xF0,0xEC,0x03,0xC0, 
0xF0,0xEE,0xC1,0xA1, 
0xF0,0xF0,0x75,0x08, 
0xF0,0xF2,0x76,0x28, 
0xF0,0xF4,0x77,0x48, 
0xF0,0xF6,0xC2,0x40, 
0xF0,0xF8,0xD8,0x20, 
0xF0,0xFA,0x71,0xCF, 
0xF0,0xFC,0x00,0x03, 
0xF0,0xFE,0x20,0x67, 
0xF1,0x00,0xDA,0x02, 
0xF1,0x02,0x08,0xAE, 
0xF1,0x04,0x03,0xA0, 
0xF1,0x06,0x73,0xC9, 
0xF1,0x08,0x0E,0x25, 
0xF1,0x0A,0x13,0xC0, 
0xF1,0x0C,0x0B,0x5E, 
0xF1,0x0E,0x01,0x60, 
0xF1,0x10,0xD8,0x06, 
0xF1,0x12,0xFF,0xBC, 
0xF1,0x14,0x0C,0xCE, 
0xF1,0x16,0x01,0x00, 
0xF1,0x18,0xD8,0x00, 
0xF1,0x1A,0xB8,0x9E, 
0xF1,0x1C,0x0E,0x5A, 
0xF1,0x1E,0x03,0x20, 
0xF1,0x20,0xD9,0x01, 
0xF1,0x22,0xD8,0x00, 
0xF1,0x24,0xB8,0x9E, 
0xF1,0x26,0x0E,0xB6, 
0xF1,0x28,0x03,0x20, 
0xF1,0x2A,0xD9,0x01, 
0xF1,0x2C,0x8D,0x14, 
0xF1,0x2E,0x08,0x17, 
0xF1,0x30,0x01,0x91, 
0xF1,0x32,0x8D,0x16, 
0xF1,0x34,0xE8,0x07, 
0xF1,0x36,0x0B,0x36, 
0xF1,0x38,0x01,0x60, 
0xF1,0x3A,0xD8,0x07, 
0xF1,0x3C,0x0B,0x52, 
0xF1,0x3E,0x01,0x60, 
0xF1,0x40,0xD8,0x11, 
0xF1,0x42,0x8D,0x14, 
0xF1,0x44,0xE0,0x87, 
0xF1,0x46,0xD8,0x00, 
0xF1,0x48,0x20,0xCA, 
0xF1,0x4A,0x02,0x62, 
0xF1,0x4C,0x00,0xC9, 
0xF1,0x4E,0x03,0xE0, 
0xF1,0x50,0xC0,0xA1, 
0xF1,0x52,0x78,0xE0, 
0xF1,0x54,0xC0,0xF1, 
0xF1,0x56,0x08,0xB2, 
0xF1,0x58,0x03,0xC0, 
0xF1,0x5A,0x76,0xCF, 
0xF1,0x5C,0xFF,0xFF, 
0xF1,0x5E,0xE5,0x40, 
0xF1,0x60,0x75,0xCF, 
0xF1,0x62,0xFF,0xFF, 
0xF1,0x64,0xE5,0x68, 
0xF1,0x66,0x95,0x17, 
0xF1,0x68,0x96,0x40, 
0xF1,0x6A,0x77,0xCF, 
0xF1,0x6C,0xFF,0xFF, 
0xF1,0x6E,0xE5,0x42, 
0xF1,0x70,0x95,0x38, 
0xF1,0x72,0x0A,0x0D, 
0xF1,0x74,0x00,0x01, 
0xF1,0x76,0x97,0x40, 
0xF1,0x78,0x0A,0x11, 
0xF1,0x7A,0x00,0x40, 
0xF1,0x7C,0x0B,0x0A, 
0xF1,0x7E,0x01,0x00, 
0xF1,0x80,0x95,0x17, 
0xF1,0x82,0xB6,0x00, 
0xF1,0x84,0x95,0x18, 
0xF1,0x86,0xB7,0x00, 
0xF1,0x88,0x76,0xCF, 
0xF1,0x8A,0xFF,0xFF, 
0xF1,0x8C,0xE5,0x44, 
0xF1,0x8E,0x96,0x20, 
0xF1,0x90,0x95,0x15, 
0xF1,0x92,0x08,0x13, 
0xF1,0x94,0x00,0x40, 
0xF1,0x96,0x0E,0x1E, 
0xF1,0x98,0x01,0x20, 
0xF1,0x9A,0xD9,0x00, 
0xF1,0x9C,0x95,0x15, 
0xF1,0x9E,0xB6,0x00, 
0xF1,0xA0,0xFF,0xA1, 
0xF1,0xA2,0x75,0xCF, 
0xF1,0xA4,0xFF,0xFF, 
0xF1,0xA6,0xE7,0x1C, 
0xF1,0xA8,0x77,0xCF, 
0xF1,0xAA,0xFF,0xFF, 
0xF1,0xAC,0xE5,0x46, 
0xF1,0xAE,0x97,0x40, 
0xF1,0xB0,0x8D,0x16, 
0xF1,0xB2,0x76,0xCF, 
0xF1,0xB4,0xFF,0xFF, 
0xF1,0xB6,0xE5,0x48, 
0xF1,0xB8,0x8D,0x37, 
0xF1,0xBA,0x08,0x0D, 
0xF1,0xBC,0x00,0x81, 
0xF1,0xBE,0x96,0x40, 
0xF1,0xC0,0x09,0x15, 
0xF1,0xC2,0x00,0x80, 
0xF1,0xC4,0x0F,0xD6, 
0xF1,0xC6,0x01,0x00, 
0xF1,0xC8,0x8D,0x16, 
0xF1,0xCA,0xB7,0x00, 
0xF1,0xCC,0x8D,0x17, 
0xF1,0xCE,0xB6,0x00, 
0xF1,0xD0,0xFF,0xB0, 
0xF1,0xD2,0xFF,0xBC, 
0xF1,0xD4,0x00,0x41, 
0xF1,0xD6,0x03,0xC0, 
0xF1,0xD8,0xC0,0xF1, 
0xF1,0xDA,0x0D,0x9E, 
0xF1,0xDC,0x01,0x00, 
0xF1,0xDE,0xE8,0x04, 
0xF1,0xE0,0xFF,0x88, 
0xF1,0xE2,0xF0,0x0A, 
0xF1,0xE4,0x0D,0x6A, 
0xF1,0xE6,0x01,0x00, 
0xF1,0xE8,0x0D,0x8E, 
0xF1,0xEA,0x01,0x00, 
0xF1,0xEC,0xE8,0x7E, 
0xF1,0xEE,0xFF,0x85, 
0xF1,0xF0,0x0D,0x72, 
0xF1,0xF2,0x01,0x00, 
0xF1,0xF4,0xFF,0x8C, 
0xF1,0xF6,0xFF,0xA7, 
0xF1,0xF8,0xFF,0xB2, 
0xF1,0xFA,0xD8,0x00, 
0xF1,0xFC,0x73,0xCF, 
0xF1,0xFE,0xFF,0xFF, 
0xF2,0x00,0xF2,0x40, 
0xF2,0x02,0x23,0x15, 
0xF2,0x04,0x00,0x01, 
0xF2,0x06,0x81,0x41, 
0xF2,0x08,0xE0,0x02, 
0xF2,0x0A,0x81,0x20, 
0xF2,0x0C,0x08,0xF7, 
0xF2,0x0E,0x81,0x34, 
0xF2,0x10,0xA1,0x40, 
0xF2,0x12,0xD8,0x00, 
0xF2,0x14,0xC0,0xD1, 
0xF2,0x16,0x7E,0xE0, 
0xF2,0x18,0x53,0x51, 
0xF2,0x1A,0x30,0x34, 
0xF2,0x1C,0x20,0x6F, 
0xF2,0x1E,0x6E,0x5F, 
0xF2,0x20,0x73,0x74, 
0xF2,0x22,0x61,0x72, 
0xF2,0x24,0x74,0x5F, 
0xF2,0x26,0x73,0x74, 
0xF2,0x28,0x72,0x65, 
0xF2,0x2A,0x61,0x6D, 
0xF2,0x2C,0x69,0x6E, 
0xF2,0x2E,0x67,0x20, 
0xF2,0x30,0x25,0x64, 
0xF2,0x32,0x20,0x25, 
0xF2,0x34,0x64,0x0A,
0xF2,0x36,0x00,0x00, 
0xF2,0x38,0x00,0x00, 
0xF2,0x3A,0x00,0x00, 
0xF2,0x3C,0x00,0x00, 
0xF2,0x3E,0x00,0x00, 
0xF2,0x40,0xFF,0xFF, 
0xF2,0x42,0xE8,0x28, 
0xF2,0x44,0xFF,0xFF, 
0xF2,0x46,0xF0,0xE8, 
0xF2,0x48,0xFF,0xFF, 
0xF2,0x4A,0xE8,0x08, 
0xF2,0x4C,0xFF,0xFF, 
0xF2,0x4E,0xF1,0x54, 
0x09,0x8E,0x00,0x00, 
0xE0,0x00,0x05,0xD8, 
0xE0,0x02,0x04,0x03, 
0x00,0x40,0xFF,0xF8, 
			//delay = 30
0x00,0x40,0xFF,0xF9, 
			//delay = 30
0x32,0x10,0x00,0xB0, 
0x09,0x8e,0x48,0x26, 
0xc8,0x26,0x01,0x00, 
0xc8,0x6c,0x00,0x80, 
0xc8,0x6e,0x00,0x80, 
0xc8,0x70,0x00,0x20, 
0xc8,0x72,0x08,/*0x01*/0x00, 
0xa8,0x0e,0xa8,0x08, 
0x30,0x32,0x01,0x00, 
0x30,0x34,0x01,0x00, 
0x30,0x36,0x01,0x00, 
0x30,0x38,0x01,0x00, 
0xc8,0x22,0x00,0xe0, 
0x00,0x40,0x80,0x02, 
0x00,0x40,0x80,0x04, 
0xc8,0x68,0x02,0x38, 
0xa8,0x0e,0x2a,0x06, 
0xa8,0x12,0x04,0x00, 
0xa4,0x04,0x01,0x01, 
#if 0
0xC8,0xF4,0x00,0x04,//0x00,0x04, 	//AE
0xC8,0xF6,0x00,0x00,//0x00,0x00, 
0xC8,0xF8,0x00,0x82,//0x00,0x82, 
0xC8,0xFA,0x00,0x5E,//0x00,0x5E, 
#else
0xC8,0xF4,0x00,0x00, 	//AE
0xC8,0xF6,0x00,0x00, 
0xC8,0xF8,0x02,0x80, 
0xC8,0xFA,0x01,0xE0, 
#endif
0x00,0x40,0x80,0x04, 
0x32,0x6c,0x10,0x03, 
0x09,0x8E,0x48,0x8A, 
0xC8,0x8A,0x02,0x14, 
0xC8,0x8C,0xFE,0xDE, 
0xC8,0x8E,0x00,0x0D, 
0xC8,0x90,0xFF,0xCB, 
0xC8,0x92,0x01,0x4D, 
0xC8,0x94,0xFF,0xE8, 
0xC8,0x96,0xFF,0xC6, 
0xC8,0x98,0xFF,0x2B, 
0xC8,0x9A,0x02,0x0F, 
0xC8,0x9C,0x00,0x1E, 
0xC8,0x9E,0x00,0x44, 
0xC8,0xA0,0xFF,0xB7, 
0xC8,0xA2,0x00,0x9F, 
0xC8,0xA4,0xFF,0xAA, 
0xC8,0xA6,0x00,0x05, 
0xC8,0xA8,0xFF,0xD3, 
0xC8,0xAA,0x00,0x28, 
0xC8,0xAC,0x00,0x36, 
0xC8,0xAE,0x00,0x67, 
0xC8,0xB0,0xFF,0x63, 
0xC8,0xB2,0x00,0x12, 
0xC8,0xB4,0xFF,0xD9, 
0xC8,0xCA,0x03,0x01, 
0xC8,0xCC,0x00,0x00, 
0xC8,0xCE,0x00,0x00, 
0xC8,0xD0,0x00,0x80, 
0xC8,0xD2,0x1B,0x80, 
0xC8,0xD4,0x16,0x80, 
0xC8,0xD6,0x01,0xAC, 
0xC8,0xD8,0x00,0x3C, 
0xC8,0xDA,0x00,0x00, 
0xC8,0xDC,0x00,0x3C, 
0xC8,0xDE,0x00,0x57, 
0xAC,0x32,0x2E,0x7f,  
0xAC,0x34,0x1B,0x83, 
0x09,0x8E,0xBC,0x0C, 
0xBC,0x02,0x00,0x07, 
0xBC,0x0C,0x00,0x03, 
0xBC,0x08,0x02,0x01, 
0xBC,0x0E,0x0a,0x20, 
0xBC,0x10,0x4f,0x71, 
0xBC,0x12,0x8d,0xa3, 
0xBC,0x14,0xb3,0xc0,
0xBC,0x16,0xcc,0xd5, 
0xBC,0x18,0xdd,0xe4, 
0xBC,0x1A,0xeb,0xf0, 
0xBC,0x1C,0xf6,0xfb, 
0xBC,0x1E,0xFf,0x00, 
//0xc8,0x1c,0x00,0x14, 
0x00,0x40,0x80,0x02, 
0x36,0x40,0x03,0x70,	
0x36,0x42,0x30,0xE8,	
0x36,0x44,0x0A,0xCF,	
0x36,0x46,0x62,0xCC,	
0x36,0x48,0xA4,0x2F,	
0x36,0x4A,0x02,0xD0,	
0x36,0x4C,0xB9,0xAB,	
0x36,0x4E,0x1B,0x0F,	
0x36,0x50,0x1F,0x2B,	
0x36,0x52,0x99,0x0F,	
0x36,0x54,0x02,0xD0,	
0x36,0x56,0xBD,0x89,	
0x36,0x58,0x4F,0x2E,	
0x36,0x5A,0x81,0x2A,	
0x36,0x5C,0xAF,0xCE,	
0x36,0x5E,0x03,0x90,	
0x36,0x60,0x9E,0xC9,	
0x36,0x62,0x16,0xCF,	
0x36,0x64,0x11,0x0D,	
0x36,0x66,0xBF,0xCF,	
0x36,0x80,0x0B,0x8C,	
0x36,0x82,0x94,0x6E,	
0x36,0x84,0xB1,0x4D,	
0x36,0x86,0x51,0xCE,	
0x36,0x88,0x0E,0xEF,	
0x36,0x8A,0x51,0x0A,	
0x36,0x8C,0x85,0x2E,	
0x36,0x8E,0x13,0xAB,	
0x36,0x90,0x20,0xEE,	
0x36,0x92,0x5F,0x6D,	
0x36,0x94,0x07,0xEC,	
0x36,0x96,0xDB,0x4D,	
0x36,0x98,0x03,0xAE,	
0x36,0x9A,0x1F,0xAE,	
0x36,0x9C,0xE3,0xCD,	
0x36,0x9E,0x00,0xED,	
0x36,0xA0,0xC4,0x0D,	
0x36,0xA2,0x46,0xCB,	
0x36,0xA4,0x1F,0x4E,	
0x36,0xA6,0x28,0xAB,	
0x36,0xC0,0x7E,0xED,	
0x36,0xC2,0x09,0x8D,	
0x36,0xC4,0x89,0xF1,	
0x36,0xC6,0x95,0xEE,	
0x36,0xC8,0x47,0xCF,	
0x36,0xCA,0x2B,0xCE,	
0x36,0xCC,0xC7,0x08,	
0x36,0xCE,0x8E,0xD1,	
0x36,0xD0,0x06,0x0D,	
0x36,0xD2,0x21,0xF0,	
0x36,0xD4,0x6D,0x0D,	
0x36,0xD6,0xC7,0x2E,	
0x36,0xD8,0x93,0x71,	
0x36,0xDA,0x05,0xF0,	
0x36,0xDC,0x73,0xD0,	
0x36,0xDE,0x3D,0x8D,	
0x36,0xE0,0x12,0x0D,	
0x36,0xE2,0x89,0xD1,	
0x36,0xE4,0xEB,0xCD,	
0x36,0xE6,0x29,0xD0,	
0x37,0x00,0xA6,0x6E,	
0x37,0x02,0x65,0xCF,	
0x37,0x04,0x02,0x51,	
0x37,0x06,0xC2,0x6F,	
0x37,0x08,0xC2,0xB1,	
0x37,0x0A,0xD9,0x2C,	
0x37,0x0C,0x39,0x8F,	
0x37,0x0E,0x64,0x0E,	
0x37,0x10,0xC3,0xCF,	
0x37,0x12,0x20,0x0E,	
0x37,0x14,0x22,0x4B,	
0x37,0x16,0x1E,0x8F,	
0x37,0x18,0x97,0x30,	
0x37,0x1A,0xA1,0x6F,	
0x37,0x1C,0x33,0x11,	
0x37,0x1E,0xB8,0xAD,	
0x37,0x20,0x4B,0x8F,	
0x37,0x22,0x57,0x8F,	
0x37,0x24,0xCE,0x6F,	
0x37,0x26,0xF4,0xCF,	
0x37,0x40,0x95,0xAE,	
0x37,0x42,0x97,0xAF,	
0x37,0x44,0x71,0xAC,	
0x37,0x46,0x15,0x8D,	
0x37,0x48,0x1F,0x72,	
0x37,0x4A,0x9A,0x4F,	
0x37,0x4C,0xCA,0x6D,	
0x37,0x4E,0x02,0xD1,	
0x37,0x50,0x17,0x8F,	
0x37,0x52,0xF1,0x2F,	
0x37,0x54,0xDC,0xCE,	
0x37,0x56,0x07,0x10,	
0x37,0x58,0x05,0xB2,	
0x37,0x5A,0xDB,0x11,	
0x37,0x5C,0xC6,0x32,	
0x37,0x5E,0x8B,0xCE,	
0x37,0x60,0x99,0x2F,	
0x37,0x62,0x07,0x90,	
0x37,0x64,0x63,0xCD,	
0x37,0x66,0x39,0xD0,	
0x37,0x82,0x00,0xD8,	
0x37,0x84,0x01,0x3C,	
0x32,0x10,0x02,0xb8,	
0x09,0x8E,0x48,0x60, 
0xc8,0x60,0x01,0x00, 
0xc8,0x61,0x00,0x00, 
0x09,0x8E,0x48,0x61, 
0x00,0x40,0x80,0x02, 
0x09,0x8E,0x48,0x02, 
0xc8,0x02,0x00,0x10, 
0xc8,0x06,0x02,0x97, 
0xc8,0x04,0x01,0xf3, 
0xc8,0x14,0x01,0xe3, 
0xc8,0x0e,0x02,0x0d, 
0xc8,0x48,0x00,0x00, 
0xc8,0x4a,0x00,0x00, 
0xc8,0x4c,0x02,0x80, 
0xc8,0x4e,0x01,0xe0, 
0xc8,0x54,0x02,0x80, 
0xc8,0x56,0x01,0xe0, 
0xc8,0x50,0x03,0x42, 
0xc8,0xf0,0x02,0x7f, 
0xc8,0xf2,0x01,0xdf, 
0xc8,0xf4,0x00,0x04, 
0xc8,0xf6,0x00,0x04, 
0xc8,0xf8,0x00,0x7e, 
0xc8,0xfa,0x00,0x5e, 
0xdc,0x00,0x28,0x00, 
0xc8,0x28,0x00,0x00, 
		       //delay = 10
0xc9,0x05,0x02,0x00, 
0xc9,0x08,0x03,0x00, 
		       //delay = 10 
//0x09,0x8e,0x48,0x18, 
//0x09,0x90,0x00,0x9b,  //open streaming


0x09,0x8E,0x48,0x48,  //VGA streaming
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4A,
0x09,0x90,0x00,0x00,
0x09,0x8E,0x48,0x4C,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x4E,
0x09,0x90,0x01,0xE0,
0x09,0x8E,0x48,0x54,
0x09,0x90,0x02,0x80,
0x09,0x8E,0x48,0x56,
0x09,0x90,0x01,0xe0,
0x09,0x8E,0xC8,0x50,
0x09,0x90,0x03,0x00,
0x09,0x8E,0x48,0xF0,
0x09,0x90,0x02,0x7F,
0x09,0x8E,0x48,0xF2,
0x09,0x90,0x01,0xdF,
0x09,0x8E,0x48,0xF4,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF6,
0x09,0x90,0x00,0x04,
0x09,0x8E,0x48,0xF8,
0x09,0x90,0x00,0x7e,
0x09,0x8E,0x48,0xFA,
0x09,0x90,0x00,0x5e,
0x09,0x8E,0xDC,0x00,
0x09,0x90,0x28,0x00,
0x09,0x8e,0x48,0x16,
0x09,0x90,0x00,0x83,
0xdc,0x00,0x28,0x31,
0x00,0x40,0x80,0x02,
										//delay = 10 //VGA streaming

0x09,0x8E,0x48,0x28,
0xc8,0x28,0x00,0x00, 
0xdc,0x00,0x28,0x31, 
0x00,0x40,0x80,0x02, 
										//delay = 30  //normal[flip section]

0x09,0x8E,0x48,0x69,  //brightness
0x09,0x90,0x38,0x00, 

0x09,0x8E,0x48,0x60,  //Hue
0x09,0x90,0x01,0x00,
0x09,0x8E,0x48,0x61,
0x09,0x90,0x00,0x00,
0x00,0x40,0x80,0x02,

0x09,0x8E,0x49,0x05,  //sharpness
0x09,0x90,0x02,0x00,
0x09,0x8E,0x49,0x08,
0x09,0x90,0x02,0x00,

//Disable auto exposure
#if 1
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x00,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
0x30,0x12,0x01,0x2C,
#endif

//Enable auto exposure
#if 0
0x09,0x8E,0x28,0x04,
0xA8,0x04,0x00,0x1F,
0xDC,0x00,0x00,0x28,
0x00,0x40,0x80,0x02,
#endif
0xA8,0x12,0x01,0x00,
//0xC8,0x1A,0x00,0x06,
//0xC8,0x1C,0x00,0x05,

END_,END_,END_,END_
};

#if 0
unsigned char wieght_table[]=
{
#define	AG	0x0
#define	CG	0x40
#define CCG	0x64
	0xA4,0x07,AG,  AG,
	0xA4,0x08,AG,  AG,
	0xA4,0x09,AG,  AG,
	0xA4,0x0A,AG,  AG,
	0xA4,0x0B,AG,  AG,
	0xA4,0x0C,AG,  AG,
	0xA4,0x0D,CG,CG,
	0xA4,0x0E,CG, CG,
	0xA4,0x0F,CG,CG,
	0xA4,0x10,AG,  AG,
	0xA4,0x11,AG,  AG,
	0xA4,0x12,CG,CG,
	0xA4,0x13,CCG,CCG,
	0xA4,0x14,CG,CG,
	0xA4,0x15,AG,  AG,
	0xA4,0x16,AG,  AG,
	0xA4,0x17,CG,CG,
	0xA4,0x18,CG,CG,
	0xA4,0x19,CG,CG,
	0xA4,0x1A,AG,  AG,
	0xA4,0x1B,AG,  AG,
	0xA4,0x1C,AG,  AG,
	0xA4,0x1D,AG,  AG,
	0xA4,0x1E,AG,  AG,
	0xA4,0x1F,AG,  0x04,
	END_,END_,END_ ,END_

};

int InitMT9V136(int width, int height, unsigned char *regs);
void Set_MT9V136_Exposure(int val);
void Set_MT9V136_Gain(int val);
int sensor_set_addr(int sensor_fd, unsigned int addr);
void Set_MT9V136_AutoExposure(int enable);
int Get_MT9V136_Brightness(void);
#endif
#endif
<file_sep>/c/homework/2nd_week/guess_number.c
/* ************************************************************************
 *       Filename:  guess_number.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月20日 星期一 07時04分30秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟
 *        Company:  
 * ************************************************************************/
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <math.h>

#define uint unsigned int

char mygetch() 
{
    struct termios oldt, newt;
    char ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

void get_charnumber(int number,int n,char *buf)
{
	char i;
	int temp = 0;
	int divisor;

	temp = number%(int)pow(10,n);

	if(temp < pow(10,n-1))
	{
		buf[n-1] = 0+48;
		for(i=n-2;i>=0;i--)
		{
			divisor =(int)pow(10,i);
			buf[i] = temp/divisor+48;
			temp %=divisor;
		}
	}
	else
	{
		for(i=n-1;i>=0;i--)
		{
			divisor =(int)pow(10,i);
			buf[i] = temp/divisor+48;
			temp %=divisor;
		}
	}
}

void guess_number()
{
	char *buf,*src;
	char ch,i;
	int count=0,right=0;
	int num, n;

	printf("请输入挑战数字位数(1~10):");
	scanf("%d",&n);
	
	srand((uint)time(NULL));
	do
	{	
		num = rand();
	}while(num < pow(10,n-1));

	src = (char *)malloc(sizeof(char)*n);
	get_charnumber(num,n,src);

	printf(">>>请选择难度级别:\n");
    printf("1--简单，10次机会\n");
	printf("2--中度，7 次机会\n");
	printf("3--困难，5 次机会\n");

	do
	{
		ch = mygetch();
	}while(ch != '1' && ch != '2' && ch != '3');

	switch(ch)
	{
		case '1': count = 10; break;
		case '2': count =  7; break;
		case '3': count =  5; break;
	}
	
	buf = (char *)malloc(sizeof(char)*n);
	printf("\n请输入一个%d位数字：",n);
	scanf("%s",buf);
	//printf("%s\n",buf);
	//printf("%s\n",src);
	do
	{
		right = 0;

		for(i=0;i<n;i++)
		{
			if(buf[i] == src[i])
			{
				printf("第%d位数字正确\n",i+1);	
				right++;
			}
			else if(buf[i] < src[i])
			{
				printf("第%d位数字小于正确数字\n",i+1);
			}
			else
			{
				printf("第%d位数字大于正确数字\n",i+1);
			}
		}

		if(right == n)
		{
			printf("你输入的数字全部正确，游戏成功\n");
			goto leave;
		}
		
		count--;
		if(count>0)
		{
			printf("\n你还有%d次机会，请再输入一个%d位数:",count,n);
			scanf("%s",buf);
		}
		else
		{
			printf("\n在规定次数没能猜中数字，游戏失败\n");
		}				
	}while(count>0);

leave:
	getchar();
	free(buf);
}

void show_rule()
{
	printf("---------------------------\n");
	printf("         猜字游戏规则      \n");
	printf("1、系统会产生一个整型随机数\n");
	printf("2、选择合适难度级别进行游戏\n");
	printf("3、输入你认为正确的整型数字\n");
	printf("4、系统根据输入数据给你提示\n");
	printf("5、规定的次数内猜对游戏成功\n");
	printf("---------------------------\n");								
}

int main()
{
	char ch = 0;

	while(1)
	{
	
		printf("\n>>>>>欢迎进行猜字游戏<<<<<\n");
		printf("-----按1  进入游戏\n");
		printf("-----按2  查看规则\n");
		printf("-----按0  退出游戏\n");

		ch = mygetch();

		switch(ch)
		{
			case '1':
					{
						guess_number();
						break;
					}
			case '2':
					{
						show_rule();
						break;
					}
			case '0': goto exit;	
		
		}
	}

exit:
	return 0;
}


<file_sep>/c/practice/3rd_week/string/Makefile
mystring:main.c mystring.c
	gcc -o mystring main.c mystring.c -lm

.PHONY:clean
clean:
	rm -rf mystring
<file_sep>/work/test/cim_test-zmm220/conver.c
/*
##############################################################################
# Raw Image Player [ImPlayer]                           					 #
# Copyright 2000 <NAME> and <NAME>                             #
# Video Signal Processing Lab, Dept.EE, NTHU                                 #
# Version 1.5  Created 2/1/2000                                              #
##############################################################################
# COPYRIGHT NOTICE                                                           #
# Copyright 2000 <NAME> and <NAME>, All Rights Reserved.       #
#                                                                            #
# [ImPlayer] may be used and modified free of charge by anyone so long as    #
# this copyright notice and the comments above remain intact. By using this  #
# code you agree to indemnify Yao-Jen Chang from any liability that might    #
# arise from it's use.                                                       #
#                                                                            #
# Comments, feedback, bug reports, improvements are encouraged. Please sent  #
# them to <EMAIL>.                                            #
##############################################################################
*/
/************************************************************************
 *
 *  yuvrgb24.c, colour space conversion for tmndecode (H.263 decoder)
 *  Copyright (C) 1995, 1996  Telenor R&D, Norway
 *        <NAME> <<EMAIL>>
 *  
 *  Contacts: 
 *  <NAME>               <<EMAIL>>, or
 *  <NAME>                  <<EMAIL>>
 *
 *  Telenor Research and Development  http://www.nta.no/brukere/DVC/
 *  P.O.Box 83                        tel.:   +47 63 84 84 00
 *  N-2007 Kjeller, Norway            fax.:   +47 63 81 00 76
 *  
 ************************************************************************/

/*
 * Disclaimer of Warranty
 *
 * These software programs are available to the user without any
 * license fee or royalty on an "as is" basis.  Telenor Research and
 * Development disclaims any and all warranties, whether express,
 * implied, or statuary, including any implied warranties or
 * merchantability or of fitness for a particular purpose.  In no
 * event shall the copyright-holder be liable for any incidental,
 * punitive, or consequential damages of any kind whatsoever arising
 * from the use of these programs.
 *
 * This disclaimer of warranty extends to the user of these programs
 * and user's customers, employees, agents, transferees, successors,
 * and assigns.
 *
 * Telenor Research and Development does not represent or warrant that
 * the programs furnished hereunder are free of infringement of any
 * third-party patents.
 *
 * Commercial implementations of H.263, including shareware, are
 * subject to royalty fees to patent holders.  Many of these patents
 * are general enough such that they are unavoidable regardless of
 * implementation design.
 * */


#include "futil.h"

static unsigned char* clp;
//modify by seven 2011-06-10
/*
static long int crv_tab[256];
static long int cbu_tab[256];
static long int cgu_tab[256];
static long int cgu_tab[256];
*/
static int crv_tab[256];
static int cbu_tab[256];
//static int cgu_tab[256];
static int cgu_tab[256];
static int cgv_tab[256];
//static long int tab_76309[256];
static int tab_76309[256];
static int bilevel_tab_76309[256];
BITMAPINFO  bmi;

static void init_clp() 
{
  int i;
  unsigned char clpbuf[1024]={0};
  clp = clpbuf;
  clp += 384;

  for (i=-384; i<640; i++)
    clp[i] = (i<0) ? 0 : ((i>255) ? 255 : i);
}

static void init_dither_tab()
{
  long int crv,cbu,cgu,cgv;
  int i;   
  
  crv = 104597; cbu = 132201;  /* fra matrise i global.h */
  cgu = 25675;  cgv = 53279;
  
  for (i = 0; i < 256; i++) {
    crv_tab[i] = (i-128) * crv;
    cbu_tab[i] = (i-128) * cbu;
    cgu_tab[i] = (i-128) * cgu;
    cgv_tab[i] = (i-128) * cgv;
    tab_76309[i] = 76309*(i-16);
  }
  bilevel_tab_76309[0] = tab_76309[0];
  for (i = 1; i < 256; i++) {
	  bilevel_tab_76309[i] = tab_76309[255];
  }

}

void init_player()
{
  init_dither_tab();
  init_clp();
  bmi.bmiHeader.biSize = (LONG)sizeof(BITMAPINFOHEADER);
  bmi.bmiHeader.biPlanes = 1;
  bmi.bmiHeader.biCompression = 0l;
  bmi.bmiHeader.biSizeImage = 0l;
  bmi.bmiHeader.biXPelsPerMeter = 0l;
  bmi.bmiHeader.biYPelsPerMeter = 0l;
  bmi.bmiHeader.biBitCount = 24;
}
           
/**********************************************************************
 *
 *	Name:	         ConvertYUVtoRGB	
 *	Description:     Converts YUV image to RGB (packed mode)
 *	
 *	Input:	         pointer to source luma, Cr, Cb, destination,
 *                       image width and height
 *	Returns:       
 *	Side effects:
 *
 *	Date: 951208	Author: <EMAIL>
 *
 ***********************************************************************/

void rgb5652rgb888(unsigned short* rgb565,unsigned int* rgb888,unsigned int framesize)
{
	unsigned int i;
	unsigned char r,g,b;
	r=g=b=0;
	for(i=0;i<framesize;i++)
	{
		r=((*((unsigned short*)rgb565 + i))>>11)&0x1f;
		g=((*((unsigned short*)rgb565 + i))>>5)&0x3f;
		b=(*((unsigned short*)rgb565 + i))&0x1f;
		*((unsigned int*)rgb888 + i)=(r<<19)|(g<<10)|(b<<3);
	}
}

//modify by seven 2011-06-02
int yuv422rgb565(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height)
{
	int i, j, k, u, v, u2g, u2b, v2g, v2r, y11, y12;
	int width4 = width + (4 - (width%4))%4;
	unsigned short R,G,B;
  	unsigned char *pucy,* pucu, * pucv;//, * pucraster0;
	char crgbtmp;

	pucy = yuv422buf;
	pucu = yuv422buf + width * height;
	pucv = yuv422buf + width * height * 3/2;

	width		=	width/2;
	height	=	height/2;

	init_player();		//Luck~

//	pucraster0 = rgb565 + (((width4/2) * (height-1)))*3;
	k	=	width * (height-1);		//Point to the last width_line of rgb565buf,why?
	#if 0
	for (i = 0; i<256;i++) {
		if (i%12==0)
			printf("\n");
		printf("tab_=[%d]\t",tab_76309[i]);
	}
	for (i = 0; i<256;i++) {
		if (i%12==0)
			printf("\n");	
		printf("cgu=[%d]\t",cgu_tab[i]);		
	}
	for (i = 0; i<256;i++) {
		if (i%12==0)
			printf("\n");	
		printf("cbu=[%d]\t",cbu_tab[i]);		
	}
	for (i = 0; i<256;i++) {
		if (i%12==0)
			printf("\n");	
		printf("cgv=[%d]\t",cgv_tab[i]);		
	}
	for (i = 0; i<256;i++) {
		
		if (i%12==0)
			printf("\n");	
		printf("crv=[%d]\t",crv_tab[i]);
	}	

	#endif
	
	for (i = 0; i < height; i++)
	{
            for (j = 0; j < width; j+=4)
		{

                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];

		
//modify by seven 2011-06-12
/*
                *pucraster0++ = clp[(y11 + u2b)>>16];			//B
                *pucraster0++ = clp[(y11 - u2g - v2g)>>16];		//G
                *pucraster0++ = clp[(y11 + v2r)>>16];			//R
*/
		     crgbtmp	=	clp[(y11 + v2r)>>16];
//		     R		=	((crgbtmp >> 3)<<11) & 0xF800;
		     R 		= 	((crgbtmp >> 3)) & 0x001F;
		     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	

		     crgbtmp	= 	clp[(y11 + u2b)>>16];	
//		     B 		= 	((crgbtmp >> 3)) & 0x001F;
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;

		     rgb565[k++]	= 	(R | G | B);      

//modify by seven 2011-06-12
/*
                *pucraster0++ = clp[(y12 + u2b)>>16];
                *pucraster0++ = clp[(y12 - u2g - v2g)>>16];
                *pucraster0++ = clp[(y12 + v2r)>>16];
*/
	
		     crgbtmp	=	clp[(y12 + v2r)>>16];
//		     R		=	((crgbtmp >> 3)<<11) & 0xF800;
		     R 		= 	((crgbtmp >> 3)) & 0x001F;

		     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	

		     crgbtmp	= 	clp[(y12 + u2b)>>16];	
//		     B 		= 	((crgbtmp >> 3)) & 0x001F;
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;

		     rgb565[k++]	= 	(R | G | B);      


//Skip two pixels,because two pixels as a unit.
		     pucy+=2;
		     pucu++;
		     pucv++;

//modify by seven 2011-06-10 Let two ALU work at the same time
                y11 = tab_76309[*pucy++];
                y12 = tab_76309[*pucy++];
                u = *pucu++;
                v = *pucv++;
                u2g = cgu_tab[u];
                u2b = cbu_tab[u];
                v2g = cgv_tab[v];
                v2r = crv_tab[v];
//modify by seven 2011-06-12
/*
                *pucraster0++ = clp[(y11 + u2b)>>16];			//R
                *pucraster0++ = clp[(y11 - u2g - v2g)>>16];		//G
                *pucraster0++ = clp[(y11 + v2r)>>16];			//B
*/
		     crgbtmp	=	clp[(y11 + v2r)>>16];
		     R 		= 	((crgbtmp >> 3)) & 0x001F;

		     crgbtmp 	= 	clp[(y11 - u2g - v2g)>>16];	
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	

		     crgbtmp	= 	clp[(y11 + u2b)>>16];	
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;

		     rgb565[k++]	= 	(R | G | B);      

//modify by seven 2011-06-12
/*
                *pucraster0++ = clp[(y12 + u2b)>>16];
                *pucraster0++ = clp[(y12 - u2g - v2g)>>16];
                *pucraster0++ = clp[(y12 + v2r)>>16];
*/	
		     crgbtmp	=	clp[(y12 + v2r)>>16];
		     R 		= 	((crgbtmp >> 3)) & 0x001F;


		     crgbtmp 	= 	clp[(y12 - u2g - v2g)>>16];	
		     G 		= 	((crgbtmp >> 2)<<5) & 0x07E0;	

		     crgbtmp	= 	clp[(y12 + u2b)>>16];	
		     B		=	((crgbtmp >> 3)<<11) & 0xF800;


		     rgb565[k++]	= 	(R | G | B);      

//Skip two pixels,because two pixels as a unit.
		     pucy+=2;
		     pucu++;
		     pucv++;
            	}

//modify by seven 2011-06-12
//          pucraster0 = pucraster0 - width4*3;	//Back two lines to start store new datas.

		k=k - width*2;
		pucy+=width4;				//Skip one width_line Y,U,V
		pucu+=width4/2;
		pucv+=width4/2;
        }

	return 0;
}

//modify by seven 2011-06-02
// convert 24bit rgb888 to 16bit rgb565 color format

static inline unsigned short rgb888torgb565(unsigned char red,unsigned char green, unsigned char blue)
{
	unsigned short  B = (blue >> 3) & 0x001F;
	unsigned short  G = ((green >> 2) << 5) & 0x07E0;
	unsigned short  R = ((red >> 3) << 11) & 0xF800;

	return (unsigned short) (R | G | B);
}

//modify by seven 2011-06-02
int rgb8882rgb565(unsigned short *rgb565,unsigned char *rgb888,unsigned int imagesize)
{
	unsigned int i,j;
	unsigned short R,G,B;
	for(i = 0; i < imagesize; ++i)
	{
		j = i * 3;
        	R = ((rgb888[j++] >> 3)<<11) & 0xF800;	//
       	G = ((rgb888[j++] >> 2)<<5) & 0x07E0; //
        	B = ((rgb888[j] >> 3)) & 0x001F;		
		rgb565[i] = R | G | B;
	}

	return 0;
}
//modify by seven 2011-06-02
int cut_rgb565(unsigned short *rgb565cut,unsigned short *rgb565src,unsigned int width,unsigned int imagesize)
{
	int i=0,j=0,n=-1,length=0;

	length = imagesize>>2;
	unsigned short *p_input		=	rgb565src;
	unsigned short *p_output	=	rgb565cut;	

      while(i < length)
	{
		if(0==(j%width))
			p_input +=  width;

		*p_output++ = *p_input++;
		 p_input++;
		 j+=2;
		 i++;
	}	

	return 0;
}

//modify by seven 2011-0612
void rgb565_rotate90(
const unsigned short *input, int width_in, int height_in,
        unsigned short *output, int *width_out, int *height_out)
{
        unsigned short *pIn=(unsigned short *)input;
        unsigned short *pOut=(unsigned short *)output;

        int i,j;

        for(i=0; i<height_in; i++)
        {
                for(j=0; j<width_in; j++)
                {
                        *pOut = *pIn++;
                        pOut = output+height_in*j + i;
                }
        }

	*width_out = height_in;
      *height_out = width_in;
}

//modify by seven 2011-06-22
/*************************
 *Translate the picture Right_Left.
 * ***********************/
void rgb565_folio(unsigned short *rgb565,int width,int height)
{
	printf("rgb565_folio\n");

	unsigned short *p;
	unsigned short *q;
	p = rgb565;
	q = p + width - 1;
	unsigned short ustmp;
	int x,y;

	for(y=1; y <= height; ++y)
	{
		for(x=0; x < width; ++x)
		{
			ustmp	=	*q;
			*q	=	*p;
			*p	=	ustmp;
			 q--;
			 p++;
		}
		p++;
		q=q+width;
	}
}
<file_sep>/c/mkheader/app.c
/* ************************************************************************
 *       Filename:  studer_score.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月20日 星期一 11時04分43秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#include <termios.h>

#if 1
void main()
{
    int *p = malloc(100);

    printf("This is a test!\n");

    printf("sizeof(p)=%lu, sizeof(*p)=%lu\n", sizeof(p), sizeof(*p));
}
#elif 0
/************************************************************************/
/* 把所有的奇数放到所有偶数的前面                                        /
/************************************************************************/
void reverseString(char *p)
{
	//char *ptr=p;
	if( *p == '\0' || *(p + 1) == '\0' )
	{
		return ;
	}
	else
	{
		reverseString(p+1);
		if(*p%2 == 0)
		{
			while( *(p + 1) != '\0' )
			{
		//	if (*p%2 == 0)
			{
				*p = *(p + 1) ^ *p;
				*(p + 1) = *p ^ *(p + 1);
				*p = *p ^ *(p + 1);

			}/*
				*p = *(p+1) + *p;
				*(p+1) = *p - *(p+1);
				*p = *p - *(p+1);*/
				p++;
			}
		}
		//reverseString(p + 1);
	}

	return ;
}

int main(int argc, char *argv[])
{
	//int i;
	char str[] = "1234567";
	reverseString(str);
	//for(i = 0; i < 4; i++)
	    printf("%s",str);

	return 0;
}
#elif 0
#define PASSWD_FILE  ".passwd"
#define PASSWD_LEN    9

void firewall_get_passwd(char passwd[])
{
	FILE *fp = NULL;
	char str[PASSWD_LEN] = "";
	int i, len;

	fp = fopen(PASSWD_FILE, "rb");
	if(fp == NULL) {
		//文件不存在，则创建，然后退出
		fp = fopen(PASSWD_FILE, "wb");
		fclose(fp);
		return;
	}

	len = fread(str, 1, PASSWD_LEN, fp); //fread 返回实际读的块数
	len--;
	str[len] = 0; // 去掉 \n

	for(i=0; i<len; i++) {
		str[i] -= 22;
	}	
	
	strcpy(passwd, str);
	
	fclose(fp);
}

void firewall_save_passwd(char passwd[])
{
	FILE *fp = NULL;
	int i, len;

	len = strlen(passwd);
	
	for(i=0; i<len; i++) {
		passwd[i] += 22;
	}

	if(len >= PASSWD_LEN) {
		len = PASSWD_LEN-1;
		passwd[len] = 0;
	}
	strcat(passwd,"\n");
	
	fp = fopen(PASSWD_FILE, "wb");
	if(fp != NULL) {
		fwrite(passwd, 1, len+1, fp);
		fclose(fp);
	}	
}

char getch() 
{
    struct termios oldt, newt;
    char ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}
void get_passwd(char *pwd, int len)
{
	char ch;
	char i =0;
	while(i<len)
	{
		ch = getch();
		if(ch == 10){
			pwd[i] = 0;
			break;
		} 
		pwd[i++] = ch;

		putchar('*');
	}
}
void main()
{
#if 0	
	char passwd[PASSWD_LEN] = "";
	
	get_passwd(passwd, PASSWD_LEN);
	printf("\n-1-  %s\n",passwd);

	firewall_save_passwd(passwd);
	bzero(passwd, PASSWD_LEN);
	
	firewall_get_passwd(passwd);
	printf("-2-  %s\n",passwd);
#elif 1
	char str[50] = "";
	char ip[16] = "10.221.2.221";
	char mac[18] = "00:0c:67:fa:c6:1d";
	
	sprintf(str,"%12s\n%-18s\n", ip, mac);
	
	printf("%s", str);
	// char ch = getch();
	// printf("%d\n",ch);
	// putchar('*');
	// printf("entry:");
	// ch = getch();
	//gets(str);
#endif
}
#elif 0
void main(int argc)
{
	int ii = 1555444;
	char buf[20];

	sprintf(buf,"%d",ii);
	printf("%s\n",buf);
	
	printf("argc = %d\n",argc);
	
}
#elif 0

char *read_firewall_rule_file(const char *file_name)
{
	FILE *fp = NULL;
	char *buf = NULL;
	int file_length = 0;
	
	fp = fopen(file_name, "rb");
	if(fp == NULL){
		printf("Cannot open the flie!\n");
		return;
	}
	
	fseek(fp,0,SEEK_END);
	file_length = ftell(fp); 	
	buf = (char *)malloc(file_length); //
	
	if(buf == NULL){
		printf("malloc() cannot apply for memory!\n");
		goto out;
	}
	rewind(fp); //
	fread(buf,file_length,1,fp);
	
	out:
	fclose(fp);
	return buf;
}

void main()
{
	char *pbuf = NULL;
	char *p = NULL;
	
	pbuf = read_firewall_rule_file("mac_rule");
	
	printf("buf >>\n%s<<\n", pbuf);
	
	p = strtok(pbuf,"\n");
	while(p != NULL){
		printf("%s $$$len=%d\n",p, strlen(p));
		p = strtok(NULL,"\n");
	}
	free(pbuf);
}
#elif 0
void main()
{
	FILE *fp = NULL;
	char rule[32] = "";
	int i = 0;
	fp = fopen("mac_rule", "ab");
	
	for(i=0;i<3;i++)
	{
		fgets(rule, 32, stdin);
		rule[strlen(rule) - 1] = 0;
		strcat(rule,"\n");
		fwrite(rule,1, strlen(rule), fp);
	}
}
#elif 0

void main()
{
	printf("\033[35;4mhello\033[47;34m world\033[0m\n");
}

#elif 0
char *read_src_file(int *file_length, char *lrc_src)
{
	FILE *fp = NULL;
	char *buf = NULL;
	
	//unsigned long int file_length = 0;
	
	fp = fopen(lrc_src,"rb");//以只读方式打开一个二进制文件
	
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	fseek(fp,0,SEEK_END);
	*file_length = ftell(fp); //获取文件的大小
	
	buf = (char *)malloc(*file_length); //
	rewind(fp); //
	fread(buf,*file_length,1,fp);
	
	fclose(fp);
	return buf;
}
int src_segment(char *psrc, char *pbuf[], char *str)
{
	int i = 0;
	
	pbuf[0] = strtok(psrc, str);
	
	while(pbuf[i++] != NULL)
	{
		pbuf[i] = strtok(NULL, str);
	} 
	//printf("i=%d\n",i);
	return (i-1);
}
int check_lines(int file_length, char *lrc_src)
{
	int lines = 0;
	int i = 0;
	char *p = NULL;
	
	p = lrc_src;
	
	#if 1
	for(i = 0;i < file_length;i++)
	{
		if(p[i]=='\n')  lines++;
	}
	#elif 0 //这种方法不行，因为strchr函数和strstr函数遇到 '\0' 就返回
	while(p != NULL)
	{
		p = strchr(p,'\n');
		lines++;
	}
	#endif
	return lines;
}
void main()
{
	FILE *fp =NULL;
	char *buf = NULL, *pbuf[100] = {NULL};
	int file_length = 0, i = 0, n = 0;
	int lines = 0;
	system("ls ./lrc2/music | grep .mp3 >./lrc2/.msgbuf");
	
	fp = fopen("lrc2/.msgbuf","rb");
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	buf = read_src_file(&file_length,"lrc2/.msgbuf");
	lines = check_lines(file_length,buf);
	printf("%d\n",lines);
	
	n = src_segment(buf, pbuf, "\r\n");
	printf("n = %d\n",n);
	for(i=0;i<n-1;i++)
	{
		printf("%s\n",pbuf[i]);
	}
}
#elif 0

int get_chrnumber(char *pbuf, int len)
{
	int i = 0,count = 0;
	
	for(i=0;i<len;i++)
	{
		if(pbuf[i] > 0 && pbuf[i] <127) count++;
	}
	return count;
}

int main()
{
	char str1[100]=" dd笑gh声 喜!!?%欢你  更  迷人g";
	int len = strlen(str1);
	int count = 0;
	
	system("dir >./test.txt");
	count = get_chrnumber(str1,len);
	printf("len=%d\n",len);
	printf("%d\n",count);
	return 0;
}
#elif 0
int main()
{
	char str1[20]="hello \r\nr $#$ world";
	char ch='\n';
	char str2[20]="$#$";
	char *result;
	
	result=strchr(str1,ch);		
	printf("%s\n",result);
	printf("%d\n",result-str1);
	
	result=strstr(str1,str2);		
	printf("%s\n",result);
	printf("%d\n",result-str1);
	return 0;
}
#elif 0 

void main()
{
	char buf[1000] = "这是个测试";
	int count = 0;
	FILE *fp = NULL;

	fp = fopen("love.lrc","rb");

		printf("%s\n",buf);
	if(fp = NULL)
	{
	//	puts("error\n");
		return;
	}
	while(1)
	{
		fgets(buf,100,fp);
		if(feof(fp) != 0)
			break;
		printf("%s\n",buf);
		count++;	
	}

	printf("count=%d\n",count);
	free(fp);
}
#elif 0
void main()
{
	char *p = "hello";
	char *q = "world";
	char **pp;

	pp = (char **)malloc(20);
	
	pp[0]= p;
	pp[1] = q;

	printf("%s %s\n",pp[0],pp[1]);
}
#elif 0
int main()
{
	struct A
	{
		char e;
		short f;
	};
	
	struct B
	{
		int a;
		char b;
		struct A c;
		char d;
	}cc;
	
	printf("%u %u\n",&cc.c.e,&cc.d);

}
#elif 0
struct A
{
	int a;
	double b;
	float c;
};
struct
{
	char e[2];
	int f;
	double g;
	short h;
	struct A i;
}B;

void main()
{
	printf("%d\n",sizeof(B));
}
#elif 0
typedef struct stu
{
	int num;
	char name[20];
	float score;
}STU;
void main()
{
	STU stu[3];
	int i=0;
	float temp = 0;
	float ave = 0.0f;
	for(i=0;i<3;i++)
	{
		printf("请输入%d位学生的学号、姓名、成绩：\n",i+1);
		scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].score);
	}

	for(i=0;i<3;i++)
	{
		ave +=stu[i].score;
		//printf("num=%d, name=%s, score=%.1f\n",stu[i].num,stu[i].name,stu[i].score);
	}
	ave /=3;
	printf("平均成绩%.1f\n",ave);
	temp = stu[0].score>stu[1].score?(stu[0].score>stu[2].score?stu[0].score:stu[2].score) 
	     : (stu[1].score>stu[2].score?stu[1].score:stu[2].score);
	printf("最大成绩为%.1f\n",temp);
}

#elif 0
void main()
{
	char buf[128] = "abcfff#degghgf#ghi";
	char buf1[123] = "";
	char m[10] = "",s[10] = "";
	int aminute=0,second=0;

	sscanf(buf,"%*[^#]#%[^#]",buf1); //当buf第一个字符是'#'时，这样取会出错
	printf("buf1=%s\n",buf1);
	
	sscanf("thj[i:简单爱]","%*[^:]%*1s%[^]]",buf1);
	printf("buf1=%s\n",buf1);

	//sscanf("[02:06.85]","%*[[]%2d%*1s%2d",&aminute,&second);
	sscanf("[02:06.85]","[%2d:%2d",&aminute,&second);
	printf("aminute=%d,second=%d\n",aminute,second);
	
	sscanf("[12:16.85]","%*[[]%2d%*[:]%2d",&aminute,&second);
	printf("aminute=%d,second=%d\n",aminute,second);
	
	sscanf("[02:06.85]","%*[[]%2s%*1s%2s",m,s);
	printf("m=%s,s=%s\n",m,s);
}

#elif 0

void main()
{
	char buf[128] = "12345678";
	int a=0,b=0;

	sscanf(buf,"%*2d%2d%*2d%2d",&a,&b);

	printf("a=%d,b=%d\n",a,b);
}

#elif 0

void main()
{
	char dst[40] = "szsunplusedu.com";
	char *p = NULL;

	p = dst;

#elif 0
	while(1)
	{
		p = strchr(p, 'u');

		if(p != NULL)
		{
			*p = '#';
		}
		else
		{
			break;
		}
	}

	printf("%s\n",dst);
}
#elif 0

#define MIN(a,b) ((a)<(b)?(a):(b))
void main()
{
	int a[3]={2,6,8};
	int b = 3;
	int *p  = a;	
	printf("%d\n",MIN(*p++,b));
}
#elif 0
int main(int argc, char *argv[])
{
	float a[5][3]={{80,75,56},{59,65,71},{59,63,70},{85,75,90},{76,77,45}};
	int i,j ,person_low[5]={0};
	float s=0,lesson_aver[5]={0};

	for(j=0;j<5;j++)
	{
		for(i=0;i<3;i++)
		{
			s += a[j][i];
			
			if(a[j][i]<60)
			{
				person_low[j]++;
			}
		
		}
		lesson_aver[j] = s/3;
		s = 0;
	}

	for(i=0;i<5;i++)
	{
		printf("第%d个人的各科平均成绩为：%.2f,不及格有%d科\n",i,lesson_aver[i],person_low[i]);
	}
	return 0;
}
#elif 0

typedef struct game
{
	//struct game *head;
	char *topic;
	char *key;
	struct game *next;
}GAME;

int main(int argc, char *argv[])
{
	GAME one,two,*p;
	char ch[100]={0};

	one.topic = "这是个测试";
	one.key = "12";

	two.topic = "这依然是测试";
	two.key = "13";
	printf("%d\n",sizeof("哈共和斤斤计较哈哈"));
	one.next = &two;
	two.next = &one;
	p = &one;

	do
	{
		sleep(2);
		printf("%s  %s\n",p->topic,p->key);
		p = p->next;
	}while(p != NULL);

	printf("%s %s\n",one.topic,one.key);
	return 0;
}
#elif 0

void main()
{
	int a = 0x01020304;
	int *p = NULL;
	int *cp= NULL;
	char ch = 97;
	cp =&ch;
	cp = (char *)cp;//cp 还是指向int型，有cp定义类型决定
	p = &a;
	printf("%d\n",*(char *)cp);
	printf("0x%x\n",*(short int *)cp);

//	printf("0x%x\n",*((short int *)((char *)p+1)));

}

#elif 0

int sum(int n)
{
	int temp = 0;
	int i;
	if(n==1)
	{
		return 1;
	}
	else if(n>1)
	{
		for(i=1;i<=n;i++)
		{
			temp +=i;
		}
	//	temp +=sum(n-1);
	//	return temp;
		return temp+sum(n-1);
	}
	//return temp;
}
void main()
{
	int n = 0;
	n= sum(6);

	printf("%d\n",n);
}


#elif 0

void main()
{
	int num[5] = { 1,2,3,4,5};
	//int *p[5] = {&num[0],&num[1],&num[2],&num[3],&num[4]};
	int *p[5] = { &num[0]};
	//printf("%d\n",*p[2]);
	printf("%d\n",*(p[0]+2));

	char *str[100] = {"hehe1","hehe2","hehe3","hehe4"};
	char i;

	i = 0;
	while(str[i] != NULL)
	{
		printf("%s\t",str[i]);
		i++;
	}
	putchar('\n');
}
#elif 0
int f(char *s)
{
	char *p=s;
	while(*p!='\0') 
	{
		p++;
	}
	return(p-s);
}

int bic(int d, int m)
{

	char temp_1[32],temp_2[32];
	int i=0,j=0;

	memset(temp_1,'\0',sizeof(temp_1));
	while(d!=0)
	{
		temp_1[i++]=d%2;
		//printf("%c  ",temp_1[i-1]+'0');
		d=d/2;
	}

	memset(temp_2,'\0',sizeof(temp_2));
	i=0;
	while(m!=0)
	{
		temp_2[i++]=m%2;
		m=m/2;
	}


	for(i=0;i<32;i++)
	{
		if(temp_2[i]==1)
		{
			temp_1[i]=0;
		}
		
	}
	d=0;
	for(i=0;i<32;i++)
	{
		d+= temp_1[i]*pow(2,i);
	}
	
	return d;
}

main()
{
	int t;
	t = bic(30,5);
	printf("%d\n", t);

	printf("%d\n",f("FUJIAN"));	
	
}

#elif 0
int main()
{
	char buf[]="I am a good programer, am i? hello, world.";
	//			?i am ,programer good a am i

	char * p[50],ch,*str;
	int i=0,j=0,word_num=0;
	printf("***%s***\n",buf);
	str=(char *)malloc(strlen(buf)+1);
	p[i]=strtok(buf," ");//按空格切割字符串
	while(p[i]!=NULL)
	{
		i++;
		p[i]=strtok(NULL," ");
	}
	word_num=i;
	for(i=0; i< word_num; i++)//把所有单词中有标点符号的处理完
	{
		if(ispunct( *(p[i]+strlen(p[i])-1)) != 0) //检查参数是否为标点符号或特殊符号，是，返回TRUE
		{
			ch=*(p[i]+strlen(p[i])-1);
			for(j=strlen(p[i]);j>1 ;j--)
			{
				*(p[i]+j-1)=*(p[i]+j-2);
			}
			*p[i]=ch;
		}
	}
	i=word_num;
	strcpy(str,p[i-1]);
	for(i=word_num-2; i>=0  ;i--)//从后向前把所有字符串追加进来，以空格分开
	{
		strcat(str," ");
		strcat(str,p[i]);			
	}

	strcpy(buf,str);
	printf("***%s***\n",buf);
	free(str);
	return 0;
}
#elif 0
int lenght(char *p)
{
	int len=0;
	len = strlen(p);
	return len;
}
void main()
{
	int aa = 0;
	long bb = 0;
	
	scanf("%2d%ld",&aa,&bb);
	printf("add = %ld\n", aa+bb);
	
	char a[5]={'a','b','c','d','e'};
	//char a[]="abcde";
	printf("%d\n",lenght(a));
}
#endif
<file_sep>/network/2nd_day/tftp_client.c
/******************************************************************************
  文 件 名   : tftp_client.c
  版 本 号   : 
  作    者   : 
  生成日期   : 2015年9月1日
  最近修改   :
  功能描述   : TFTP 客户端
******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>


int main(int argc, char *argv[])
{
	FILE *fp = NULL;
	char *p  = NULL;
	char file_name[128] = "a.txt";
	char server_ip[16]  = "10.221.2.12";
	char cmd[128]  = "", msg[1024] = "";
	int sockfd = 0, cmd_len = 0, msg_len = 0, ask = 0;
	unsigned short port = 69; // TFTP服务器的固定端口


	if(argc > 1)
	{
		strcpy(server_ip, argv[1]);
	}
	if(argc > 2)
	{
		bzero(file_name, sizeof(file_name));
		strcpy(file_name, argv[2]);
	}

	//创建一个套接字
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);

	//配置服务器的地址
	struct sockaddr_in server_addr;
	socklen_t server_len = sizeof(server_addr);
	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);//服务器的端口
	inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);//服务器的IP

	//printf("file_name = %s\n",file_name);

	cmd_len = sprintf(cmd, "%c%c%s%c%s%c", 0, 1, file_name, 0, "octet", 0);
	sendto(sockfd, cmd, cmd_len, 0,\
		  (struct sockaddr *)&server_addr, sizeof(server_addr));

	p = msg; //
	fp = fopen(file_name, "wb");

	while(1)
	{
	  	bzero(msg, sizeof(msg));
		//bzero(&server_addr, sizeof(server_addr));
		msg_len = recvfrom(sockfd, msg, sizeof(msg), 0, (struct sockaddr *)&server_addr, &server_len);

		if(*(p+1) == 3) //数据确认
		{
			//printf("ask_no = %d&&&&&&&&&\n",*(p+3));
			if(ask != *(p+3))
			{
				ask = *(p+3);
				//把接收的数据写入文件
				fwrite((p+4), msg_len - 4, 1, fp);
			}

			if(msg_len < 516)
			{
				fclose(fp);
				break;
			}

			*(p+1) = 4; //数据确认操作码

			//发送确认信号
			sendto(sockfd, msg, 4, 0,\
				  (struct sockaddr *)&server_addr, sizeof(server_addr));
		}
	}

	//fclose(fp);
	close(sockfd);
	return 0;
}
<file_sep>/sys_program/player/src/inc/gtk_callback.h
#ifndef __GTK_CALLBACK_H__
#define __GTK_CALLBACK_H__

extern gboolean motion_event_callback(GtkWidget *widget, GdkEventMotion *event, gpointer data);
extern void search_entry_callback(GtkWidget *widget, gpointer entry);
extern void keys_board_callback(GtkWidget *widget, GdkEventKey  *event, gpointer data);
extern void playmode_button_callback(GtkButton *button, gpointer data);
extern void musiclist_buttons_callback(GtkButton *button, gpointer data);
extern void music_buttons_callback(GtkButton *button, gpointer data);
extern gboolean callback_list_release(GtkWidget *widget, GdkEventButton *event, gpointer data);
#endif<file_sep>/network/route/src/inc/firewall_file.h
/******************************************************************************
  文 件 名   : firewall_file.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : firewall_file.c 的头文件
******************************************************************************/
#ifndef __FIREWALL_FILE_H__
#define __FIREWALL_FILE_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */

/*----------------------------------------------*
 * 内部函数原型说明                             *
 *----------------------------------------------*/
static char *firewall_read_rule_file(const char *file_name);
static char getch();

/*----------------------------------------------*
 * 外部函数原型说明                             *
 *----------------------------------------------*/
extern void firewall_save_all_rules(TYPE_Route *rt);
extern void filrewall_save_rule(const char *rule);
extern void firewall_config(TYPE_Route *rt);
extern void firewall_get_passwd(TYPE_Route *rt);
extern void firewall_save_passwd(char passwd[]);
extern void get_passwd(char passwd[], int max_len);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */


#endif /* __FIREWALL_FILE_H__ */
<file_sep>/c/homework/3rd_week/operation/operation.c
/* ************************************************************************
 *       Filename:  operation.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月27日 星期一 11時04分01秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <string.h>
#include "fun.h"

char *cmp[] = { "add", "sub", "mul", "div"};
int (*fp[])(int a,int b) = { add, sub, mul, div};

void main()
{
	int i = 0;
	int a = 0,b = 0, res = 0;
	char buf[10] = {0};

	printf("请输入计算指令，例如：\n");
	printf("add 15 25 //计算15+25的值，并返回结果\n");
	printf("sub 15 25 //计算15-25的值，并返回结果\n");
	printf("mul 15 25 //计算15*25的值，并返回结果\n");
	printf("div 15 25 //计算15/25的值，并返回结果\n");
	scanf("%s %d %d",buf,&a,&b);
	
	while(1)
	{
		for(i=0;i<sizeof(fp)/sizeof(fp[0]);i++)
		{
			if(strcmp(buf,cmp[i])==0)
			{
				res = fp[i](a,b);
				printf("计算结果为：%d\n",res);
			}
		}
	}
}


<file_sep>/c/lrc/process_lrc.h
/* ************************************************************************
 *       Filename:  process_lrc.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 09時17分38秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __PROCESS_LRC_H__
#define __PROCESS_LRC_H__

int src_segment(char *lrc_src, char *plines[], char *str);
int line_segment(char *pline, char *pbuf[], char *str);
LRC *build_link(char *lrc_pline[], char *pheader[], int lines);
void show_lyric(LRC *pnode, int longest);
int get_showoffset(char *pbuf,int longest);
int get_maxtime(LRC *head);
int get_timelag(LRC *head);

#endif



<file_sep>/network/5th_day/bk_filch.c
/* ************************************************************************
 *       Filename:  rarp.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月09日 11时23分33秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <net/if.h>
#include <netinet/ether.h>
#include <netinet/in.h>
#include "gb2312_ucs2.h"

void get_feiQ_msg(unsigned char const *src)
{
	char *p = NULL;
	int i = 0, colon = 0;
	unsigned char msg[1024] = "";
	unsigned char buf[1024] = "";
	unsigned short udp_len = 0;
	unsigned char utf8[1024] = "";

	udp_len = (src[4]*256+src[5]);
	printf("udp_len=%d\n",udp_len);

	memcpy(buf,src+8,udp_len-8);
	for(i=0;i<udp_len-8;i++)
	{
		printf("%c",buf[i]);
	}
	printf("\n");
	p = buf;
	for(i=0;i<udp_len-8;i++)
	{
		if(buf[i] == ':') colon++;
		if(colon == 5) break;
		p++;
	}

	if(colon == 5)
	{
		memcpy(msg,p+1,udp_len-8-(i+1));
		gb2312_to_utf8(msg, utf8);
		printf("msg=%s\n",utf8);
	}

	//udp_len = ntohs((unsigned short *)(src+4));
}
unsigned short get_src_port(unsigned char const *src)
{
	//unsigned char port[4] = "";

	//sprintf(port,"%d%d",src[0],src[1]);

	printf("%d %d ****\n",src[2],src[3]);

	return (src[0]*256+src[1]);
}

unsigned char get_IP_type(unsigned char const *src)
{
	unsigned char type[1] = "";
	//提取数据包类型
	sprintf(type,"%c",src[9]);

	if(type[0] == 6)
		printf("TCP 数据包\n");
	else if(type[0] == 17)
		printf("UDP 数据包\n");
	//printf("IP_TYPE:%d\n", type[0]);

	return type[0];
}
unsigned char get_ip_headlen(unsigned char const *src)
{
	unsigned char temp = 0;
	temp = src[0] & 0x0f;

	printf("headlen=%d\n",temp);
	return temp;
}
void get_ip(unsigned char const *src)
{
	unsigned char dst_ip[16] = "";
	unsigned char src_ip[16] = "";

	//提取目的ip
	sprintf(dst_ip,"%d.%d.%d.%d",\
			src[16],src[17],src[18],src[19]);

	//提取源ip
	sprintf(src_ip,"%d.%d.%d.%d",\
			src[12],src[13],src[14],src[15]);

	printf("IP:%s >> %s\n", src_ip, dst_ip);
}

void get_ARP_ip(unsigned char const *src)
{
	unsigned char dst_ip[16] = "";
	unsigned char src_ip[16] = "";

	//提取目的ip
	sprintf(dst_ip,"%d.%d.%d.%d",\
			src[24],src[25],src[26],src[27]);

	//提取源ip
	sprintf(src_ip,"%d.%d.%d.%d",\
			src[14],src[15],src[16],src[17]);

	printf("ARP_IP:%s >> %s\n", src_ip, dst_ip);
}

void get_mac(unsigned char const *src)
{
	unsigned char dst_mac[18] = "";
	unsigned char src_mac[18] = "";

	//提取目的mac
	sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
			src[0],src[1],src[2],src[3],src[4],src[5]);
	//提取源mac
	sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
			src[6],src[7],src[8],src[9],src[10],src[11]);

	printf("MAC:%s >> %s\n", src_mac, dst_mac);
}

unsigned short get_type(unsigned char const *src, unsigned char *type)
{
	//提取数据包类型
	sprintf(type,"%02x%02x",src[12],src[13]);

	printf("TYPE:%s\n", type);
	//printf("TYPE:%c%c%c%c\n", type[0],type[1],type[2],type[3]);
}

int main(int argc, char *argv[])
{
	unsigned char type[4]    = "";
	unsigned char recv[2048] = "";
	unsigned char ip_type = 0;
	unsigned short dport  = 0;

	//创建原始套接字
	int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

	//组arp的应答包
	unsigned char send_msg[1024] = {
		//-----组MAC----14----
		0x74,0x27,0xea,0xb3,0x66,0xca,//dst_mac: 柱琦 XP mac
		//0x00,0x0c,0x29,0xe4,0xd3,0xd6,//src_mac: me VM mac
		0x00,0x0c,0x29,0x98,0xcc,0x6c,//IP = .62 mac
		0x08,0x06,                    //类型: 0x0806 ARP协议

		//-----组ARP----28----
		0x00,0x01,0x08,0x00,          //硬件类型1(以太网地址)，协议类型0x0800(IP)
		0x06,0x04,0x00,0x02,          //硬件、协议的地址长度分别为6和4，ARP应答
		//0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
		//0x00,0x0c,0x29,0xe4,0xd3,0xd6,//发送端的mac，把10.221.2.11的mac伪装成自己的
		0x00,0x0c,0x29,0x98,0xcc,0x6c,//
		10, 221, 2, 12,               //发送端的IP
		0x74,0x27,0xea,0xb3,0x66,0xca,//目的mac
		10, 221, 2, 6,                //目的IP
	};

	//数据初始化
	struct sockaddr_ll sll;
	struct ifreq ethreq;

	strncpy(ethreq.ifr_name,"eth0", IFNAMSIZ);//指定网卡名称
	//将网络接口赋值给原始套接字地址结构
	ioctl(sockfd, SIOCGIFINDEX, (char *)&ethreq);
	bzero(&sll, sizeof(sll));
	sll.sll_ifindex = ethreq.ifr_ifindex;

	while(1)
	{
		sendto(sockfd, send_msg, 42, 0, (struct sockaddr *)&sll, sizeof(sll));
		recvfrom(sockfd, recv, sizeof(recv), 0, NULL, NULL);

		get_type(recv, type);

		if(strcmp(type, "0800") == 0)//ip
		{
			get_ip(recv+14);
			get_ip_headlen(recv+14);

			ip_type = get_IP_type(recv+14);

			if(ip_type == 17) //UDP
			{
				dport = get_src_port(recv+14+20);
				if(dport == 2425)
				{
					printf("#######$$$$$$$$$\n");
					get_feiQ_msg(recv+14+20);
				}

			}
		}

		usleep(1000);
	}
	return 0;
}
<file_sep>/sys_program/2nd_day/am/execle.c
/* ************************************************************************
 *       Filename:  excele.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 12时03分24秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>



int main(int argc, char *argv[])
{
	char *env[] = {"USER=ME","COMGSI = sunplusapp.com"};

	execle("./getenv","getenv",NULL,env);
	return 0;
}


<file_sep>/sys_program/4th_day/r_shm.c
/* ************************************************************************
 *       Filename:  r_shm.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 17时27分33秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdbool.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/stat.h>


int main(int argc, char *argv[])
{
    int i = 20000;
	key_t key;
	char *buf;

	key = ftok("./",66);

    while(i--) {
	int id = shmget(key,2048,IPC_CREAT | 0666);

	//printf("id = %d\n",id);

	buf = (char *)shmat(id,NULL,0);

    if((long)buf < 0) {
        printf("shmat failed: %s", strerror(errno));
        break;
    }
    else
        printf("i: %08d,  buf = %s\n",i, buf);
    }

	shmdt(buf);//将共享内存和当前进程分离

	return 0;
}




<file_sep>/network/route/go.sh
#!/bin/bash

clear
echo "compiling the route project..."
rm route
make

if [ -e route ]
then
	echo "running..."
	sudo ./route
fi
<file_sep>/sys_program/6th_day/pdt_csm.c
/* ************************************************************************
 *       Filename:  sem_syn.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月20日 14时38分35秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t semp, semc;
int totol_num = 3;


void *producter(void *arg)
{
	while(1)
	{
		sem_wait(&semp);

		sleep(1);
		totol_num++;
		printf("push into  >>totol_num = %d\n",totol_num);

		sem_post(&semc);
	}
}

void *consumer(void *arg)
{
	while(1)
	{
		sem_wait(&semc);

		sleep(2);
		totol_num--;
		printf("pop out    >>totol_num = %d\n",totol_num);

		sem_post(&semp);
	}
}

int main(int argc, char *argv[])
{
	pthread_t pth1,pth2;

	sem_init(&semp,0,7);
	sem_init(&semc,0,3);

	pthread_create(&pth1,NULL,producter,NULL);
	pthread_create(&pth2,NULL,consumer,NULL);

	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);

	sem_destroy(&semp);
	sem_destroy(&semc);

	return 0;
}
<file_sep>/work/test/cim_test-zmm220/gc0308.c
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include "gc0308.h"


#define IOCTL_READ_REG                          0 
#define IOCTL_WRITE_REG                         1 
#define IOCTL_READ_EEPROM                       2 
#define IOCTL_WRITE_EEPROM                      3 
#define IOCTL_SET_ADDR                          4 
#define IOCTL_SET_CLK                           5 

#define GC0308_CHIPID	0x00

/*exp reg */
#define GC0308_EXP_H        0x03
#define GC0308_EXP_L        0x04

/* windows regs*/
#define GC0308_ROW_H        0x05
#define GC0308_ROW_L        0x06
#define GC0308_COL_H        0x08
#define GC0308_COL_L        0x07
#define GC0308_WINH_H       0x09
#define GC0308_WINH_L       0x0A
#define GC0308_WINW_H       0x0B
#define GC0308_WINW_L       0x0C

#define GC0308_CISCTL_MODE2 0x0E
#define GC0308_CISCTL_MODE1 0x0F

#define GC0308_SCTRA 0x28

#define GC0308ID	0x42
//static pbusparam bus;
 
static  int sensor_0308_fd = -1;
static  int m_sensitivity;
static  int m_sensor_opt;

static int m_image_reverse;
static int m_image_symmetry=1;
static int exposH;

#define SIZE 12
static struct IO_MSG {
	unsigned int write_size;
	unsigned int read_size;
	unsigned char reg_buf[SIZE];
} reg_msg ;

#define SENC0308  "/dev/sensor-gc0308"
int sensor_open_0308(void)
{
	sensor_0308_fd=open(SENC0308,O_RDWR);

	if(sensor_0308_fd < 0)
	{
		perror("sensor_open()");
		return -1;
	}
	
	printf("%s open ok. \n", SENC0308);
	
	return sensor_0308_fd;
}

int sensor_close_0308()
{
	close(sensor_0308_fd);
}

static int sensor_set_addr(unsigned int addr)
{
	if (ioctl(sensor_0308_fd, IOCTL_SET_ADDR, (unsigned int)&addr) < 0) {
		printf("ioctl: set gc0308 address failed!addr=%x\n",addr);
		return -1;
	}
	return 0;
}

static unsigned char read_reg(int sensor_fd, unsigned char reg)
{
	unsigned char read_val;
	reg_msg.write_size=1;
	reg_msg.read_size=1;
	reg_msg.reg_buf[0]=reg;
	if (ioctl(sensor_fd, IOCTL_READ_REG, (void *)&reg_msg) < 0) {
		printf("warning: read_reg failed!\n");
		return 0;
	}
	read_val = reg_msg.reg_buf[0];
	return read_val;
}

static int write_reg(int sensor_fd, unsigned char reg, unsigned char val)
{
	reg_msg.write_size=2;
	reg_msg.read_size=0;
	reg_msg.reg_buf[0]=reg;
	reg_msg.reg_buf[1]=val;
	if (ioctl(sensor_fd, IOCTL_WRITE_REG, (unsigned long *)&reg_msg) < 0) {
		printf("warning: write_reg failed!\n");
		return 0;
	}

	return 1;
}

int gc0308_set_clk(int sensor_fd,unsigned int clk)
{
	if(sensor_fd==-1)
	{
		printf("%s m_sensor_fd is -1\n", __FUNCTION__);
		return -1;
	}

	if (ioctl(sensor_fd, IOCTL_SET_CLK, (unsigned int)&clk) < 0)
	{
		printf("%s ioctl: set clock failed!\n", __FUNCTION__);
		return -1;
	}
	return 0;
}


static void set_EXPOS_GC308(int exposH)
{
	//int value=read_reg(m_sensor_fd, 0xd0);
	//write_reg(m_sensor_fd, 0xd0, value | 0x20);
	write_reg(sensor_0308_fd, GC0308_EXP_H, (exposH>>8)&0xff);
	write_reg(sensor_0308_fd, GC0308_EXP_L, exposH&0xff);
}


static void set_BackgroundRGB_GC308(int RBlackLevel, int BBlackLevel, int GBlackLevel, int RBlackFactor, int GBlackFactor, int BBlackFactor)
{
	write_reg(sensor_0308_fd, 0x85, RBlackLevel);
	write_reg(sensor_0308_fd, 0x86, BBlackLevel);
	write_reg(sensor_0308_fd, 0x87, GBlackLevel);
	write_reg(sensor_0308_fd, 0x88, RBlackFactor);
	write_reg(sensor_0308_fd, 0x89, GBlackFactor);
	write_reg(sensor_0308_fd, 0x8a, BBlackFactor);
}

static void set_Contrast_GC308(int contrast)
{
	write_reg(sensor_0308_fd, 0xb3, contrast);
	write_reg(sensor_0308_fd, 0xb4, 0x80);
}

static void set_RGBGain_GCC308(int GGain, int G1Gain, int RGain, int BGain, int G2Gain)
{
	if(GGain > 0)
		write_reg(sensor_0308_fd, 0x50, GGain);//Global_Gain
	if(G1Gain > 0)
		write_reg(sensor_0308_fd, 0x53, G1Gain);//Gain_G1
	if(RGain > 0)
		write_reg(sensor_0308_fd, 0x54, RGain);//Gain_R
	if(BGain > 0)
		write_reg(sensor_0308_fd, 0x55, BGain);//Gain_B
	if(G2Gain > 0)
		write_reg(sensor_0308_fd, 0x56, G2Gain);//Gain_G2
}

static void select_page_gc308(int page)
{
	write_reg(sensor_0308_fd, 0xFE, page);
}

static void set_window_GC308(int l, int t, int w, int h)
{
	/* Set the row start address */
	write_reg(sensor_0308_fd,GC0308_ROW_H, (t >> 8) & 0xff);
	write_reg(sensor_0308_fd,GC0308_ROW_L, t & 0xff);

	/* Set the column start address */
	write_reg(sensor_0308_fd,GC0308_COL_H, (l >> 8) & 0xff);
	write_reg(sensor_0308_fd,GC0308_COL_L, l & 0xff);

	/* Set the image window width*/
	write_reg(sensor_0308_fd,GC0308_WINW_H, ((w+8)>> 8) & 0xff);
	write_reg(sensor_0308_fd,GC0308_WINW_L, (w+8) & 0xff);

	/* Set the image window height*/
	write_reg(sensor_0308_fd,GC0308_WINH_H, ((h+8) >> 8) & 0xff);
	write_reg(sensor_0308_fd,GC0308_WINH_L, (h+8) & 0xff);
}

/* VCLK = MCLK/div */
static void set_sensor_clock_gc308(int div)
{
	/* ABLC enable */
	int FrequencyNumber=div&0x0F;
	int FrequencyDiv=(div>>4)&0x0F;
	switch (FrequencyNumber+FrequencyDiv) {
	case 2:
	case 3:
	case 4:
	case 5:
	case 6:
	case 7:
	case 8:
		write_reg(sensor_0308_fd,GC0308_SCTRA, (FrequencyNumber+FrequencyDiv-1)<<4 | FrequencyDiv);       // DCF=MCLK
		break;
	default:
		write_reg(sensor_0308_fd,GC0308_SCTRA, 0x00);       // DCF=MCLK
		break;
	}
}

static void set_vertical_GC308(int vertical)
{
	int value=0;
	value=read_reg(sensor_0308_fd, 0x14);
	if(vertical)
		write_reg(sensor_0308_fd, 0x14, value | 0x02);
	else
		write_reg(sensor_0308_fd, 0x14, value & (~0x02));
}

//设置图像是否需要左右镜像处理
static void set_symmetry_GC308(int symmetry)
{
	int value=read_reg(sensor_0308_fd, 0x14);
	if(symmetry==1)
		write_reg(sensor_0308_fd, 0x14, value | 0x01);//图像需要垂直翻转
	else
		write_reg(sensor_0308_fd, 0x14, value & (~0x01));//图像不需要垂直翻转
}

static void sensor_power_on_GC308(void)
{
	unsigned char value;
	value = read_reg(sensor_0308_fd, 0x24);
	write_reg(sensor_0308_fd, 0x24, value & 0xe0);
	value = read_reg(sensor_0308_fd, 0x25);
	write_reg(sensor_0308_fd, 0x25, value | 0x0F);
}

static void sensor_power_down_GC308(void)
{
	unsigned char value;
	value = read_reg(sensor_0308_fd, 0x25);
	write_reg(sensor_0308_fd, 0x25, value & (~0x0F));
}


static int sensorid_read(int sensorfd,unsigned char regs)
{
	return read_reg(sensorfd,regs);
}


void __gc0308_init(unsigned int (*regs)[2])
{
	int i=0;

	while (1)
	{		
		if ((_END_==regs[i][0])&&(_END_==regs[i][1])){
				break;
		}	
		
		write_reg(sensor_0308_fd,regs[i][0],regs[i][1]);	
		
		i++;		
	}
}

static int sensor_init_GC308(int left, int top, int width, int height)
{    
    int ret;
	#if 1
	gc0308_set_clk(sensor_0308_fd,100000);
	sleep(1);
	sensor_set_addr(GC0308ID);	     //IIC ADDR
	select_page_gc308(0);
	#endif
	//
	ret = read_reg(sensor_0308_fd,0x00);
	if(0x9b == ret){
		printf("Found Sensor-Gc0308...\n");
	}
	else{
		printf("That Should Be GC0308.Something-Unlucky-Happen.SensorID = 0x%x\n",ret);
		exit(1);
	}
	
	__gc0308_init(gc0308reg);
	
	set_window_GC308(left, top, width, height);

	return 0;
}




int gc0308_init(void)
{
    return sensor_init_GC308(0,0,640,480);    
}

<file_sep>/network/5th_day/raw_udp.c
/* ************************************************************************
 *       Filename:  raw_udp.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月08日 17时41分48秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netpacket/packet.h>
#include <netinet/udp.h>
#include <netinet/ip.h>
#include <net/if.h>
#include <net/ethernet.h>

typedef struct _raw_upd
{
	int raw_fd;

	unsigned char src_mac[6];
	unsigned char dst_mac[6];

	unsigned char src_ip[4];
	unsigned char dst_ip[4];

	struct sockaddr_ll sll;
	struct ifreq ethreq;
}UDP;

unsigned short checksum(unsigned short *buf, int nword)
{
	unsigned long sum;
	for(sum = 0; nword > 0; nword--)
	{
		sum += htons(*buf);
		buf++;
	}
	sum = (sum>>16) + (sum&0xffff);
	sum += (sum>>16);
	return ~sum;
}

char send_msg(unsigned char msg_buf[], int raw_fd, struct sockaddr_ll sll)
{
	int msg_len = 0;

	msg_len = strlen(msg_buf);
	msg_len--;
	msg_buf[msg_len] = 0; //去掉 \n

	if(msg_len%2 != 0) //数据个数不是偶数
	{
		msg_buf[msg_len] = 0;
		msg_len++; //
		msg_buf[msg_len] = 0;
	}
	printf("msg_len=%d\n",msg_len);

	//2.封装mac头
	unsigned char packet[2048] = "";
	unsigned char src_mac[6] = {0x00,0x0c,0x29,0xe4,0xd3,0xd6};
	unsigned char dst_mac[6] = {0xec,0xa8,0x6b,0xac,0xcf,0xf9};

	struct ether_header *eth_hdr = NULL;
	eth_hdr = (struct ether_header *)packet;
	memcpy(eth_hdr->ether_shost, src_mac, 6);
	memcpy(eth_hdr->ether_dhost, dst_mac, 6);
	eth_hdr->ether_type = htons(0x0800); //

	//3.封装ip头
	struct iphdr *ip_hdr = NULL;
	ip_hdr = (struct iphdr *)(packet+14);
	ip_hdr->ihl = 5;
	ip_hdr->version = 4;
	ip_hdr->tos = 0;       //服务类型
	ip_hdr->ttl = 128;     //生存时间
	ip_hdr->tot_len = htons(20+8+msg_len);//
	ip_hdr->protocol = 17; //UDP协议
	ip_hdr->saddr = inet_addr("10.221.2.221");
	ip_hdr->daddr = inet_addr("10.221.2.12");
	ip_hdr->check = htons(0);

	//4.封装UDP头部
	struct udphdr *udp_hdr = NULL;
	udp_hdr = (struct udphdr *)(packet+14+20);
	udp_hdr->source = htons(8000); //源端口
	udp_hdr->dest = htons(8080);   //目的端口
	udp_hdr->len  = htons(8+msg_len);
	udp_hdr->check = htons(0);

	//5.udp的数据
	memcpy(packet+14+20+8, msg_buf, msg_len);

	//6.ip首部校验和
	ip_hdr->check = htons(checksum((unsigned short *)(packet+14),20/2));

	//7.udp伪头部，用于计算校验和
	unsigned char fake[1024] = {
	10, 221, 2, 221, //源ip
	10, 221, 2,  12, //目的ip
	 0,  17, 0,   0, //最后两位是UDP的长度
	};

	*(unsigned short *)(fake+10) = htons(8+msg_len); //UDP的长度
	memcpy(fake+12, packet+14+20, 8+msg_len);
	udp_hdr->check = htons(checksum((unsigned short *)(fake),(12+8+msg_len)/2));//udp头部校验和

	sendto(raw_fd, packet, 14+20+8+msg_len, 0, (struct sockaddr *)&sll, sizeof(sll));

}

int main(int argc, char *argv[])
{

	//创建原始套接字
	int raw_fd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));

	//数据初始化
	struct sockaddr_ll sll;
	struct ifreq ethreq;
	bzero(&sll, sizeof(sll));

	strncpy(ethreq.ifr_name,"eth0", IFNAMSIZ);   //指定网卡名称
	ioctl(raw_fd, SIOCGIFINDEX, (char *)&ethreq);//获取网络接口
	sll.sll_ifindex = ethreq.ifr_ifindex;

	while(1)
	{
		unsigned char msg_buf[1024] = "";
		printf("please input the message you want to send:\n");
		fgets(msg_buf, sizeof(msg_buf),stdin);
		send_msg(msg_buf, raw_fd, sll);
	}
	return 0;
}
<file_sep>/sys_program/6th_day/sem_have_name2.c
/* ************************************************************************
 *       Filename:  sem_have_name.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月20日 15时13分17秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/stat.h>


void print(sem_t *psem1,sem_t *psem2)
{
	int i = 0;


	while(1)
	{
		sem_wait(psem2);
		printf("i = %d\n",i);
		i++;
		sem_post(psem1);
	}
}

int main(int argc, char *argv[])
{
	sem_t *ptr1,*ptr2;

	ptr1 = sem_open("sem_name1",O_CREAT,0777,1);
	if(ptr1 == SEM_FAILED)
	{
		printf("Failed:sem_name1\n");
	}

	ptr2 = sem_open("sem_name2",O_CREAT,0777,0);
	if(ptr2 == SEM_FAILED)
	{
		printf("Failed:sem_name2\n");
	}
	print(ptr1,ptr2);
	return 0;
}
<file_sep>/work/shell/mktag.sh
#!/bin/sh

function echoc() {
	echo -e "\e[0;91m$1\e[0m"
}

function useage() {
	echoc "Useage:"
	echoc "\t./mktag TAG_NAME"
	exit 1
}

if [ $# -ne 1 ]; then
	echo $#
        useage
fi


TAG_NAME=$1
export TAG_NAME

echoc "tag: $TAG_NAME"

./repo forall -c 'echo $REPO_PATH;echo $TAG_NAME;git tag $TAG_NAME;git push $REPO_REMOTE $TAG_NAME'
<file_sep>/c/practice/2nd_week/libtest/mytest.c
/* ************************************************************************
 *       Filename:  mytest.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月22日 星期三 10時28分13秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include "mylib.h"


int main(int argc, char *argv[])
{
	int a = 10, b = 20;
	int max_num,min_num;

	max_num = max(a,b);
	min_num = min(a,b);
	printf("max=%d\n",max_num);
	printf("min=%d\n",min_num);
	return 0;
}


<file_sep>/work/test/cim_test-zmm220/mt9v136.c
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
//#include"mt9v136.h"

#define u16 unsigned short

#define IOCTL_READ_REG      0
#define IOCTL_WRITE_REG     1
#define JZ_CIM	1

typedef struct
{
        u16 reg;
        u16 val;
}S_CFG_16;

#define IOCTL_READ_EEPROM   2 /* read  sensor eeprom */
#define IOCTL_WRITE_EEPROM  3 /* write sensor eeprom */
#define IOCTL_SET_ADDR	    4
#define IOCTL_SET_CLK		  5 /* set i2c clock */


static int sensor_367_fd = -1;
#define I2C_MT9V136_CLOCK    100000
#define I2C_MT9V136_ADDR     0Xba
#define SIZE 12

static struct IO_MSG {
	unsigned int write_size;
	unsigned int read_size;
	unsigned char reg_buf[SIZE];
} reg_msg ;

static int MT9V136_set_addr(unsigned int addr)
{
	if (ioctl(sensor_367_fd, IOCTL_SET_ADDR, (unsigned int)&addr) < 0) {
		printf("ioctl: set address failed!\n");
		return -1;
	}
	return 0;
}

static int MT9V136_set_clk(int fd,unsigned int clk)
{
	if(fd==-1)
	{
		printf("%s m_sensor_fd is -1\n", __FUNCTION__);
		return -1;
	}

	if (ioctl(fd, IOCTL_SET_CLK, (unsigned int)&clk) < 0)
	{
		printf("%s ioctl: set clock failed!\n", __FUNCTION__);
		return -1;
	}
	return 0;
}

u16 read_reg_(u16 r)
{
	u16 read_val;
	reg_msg.write_size=2;
	reg_msg.read_size=2;
	reg_msg.reg_buf[0]=r>>8;
	reg_msg.reg_buf[1]=(0xff&r);
	if (ioctl(sensor_367_fd, IOCTL_READ_REG, (void *)&reg_msg) < 0) {
		printf("warning: read_reg failed!\n");
		return -1;
	}
	read_val = (reg_msg.reg_buf[0]<<8)|reg_msg.reg_buf[1];
	return read_val;
}

u16 write_reg_(u16 r,u16 v)
{
	reg_msg.write_size=4;
	reg_msg.reg_buf[0]=r>>8;
	reg_msg.reg_buf[1]=(0xff&r);
	reg_msg.reg_buf[2]=v>>8;
	reg_msg.reg_buf[3]=(0xff&v);	
	if (ioctl(sensor_367_fd, IOCTL_WRITE_REG, (unsigned long *)&reg_msg) < 0) {
		printf("warning: write_reg failed!\n");
		return -1;
	}
	return 0;
}

#define END_	0xff
void InitMT9V136(int width,int height,unsigned char *regs)
{
	u16	addr_,val_, ret;
	int i=0;
	u16 j=0;
	
	MT9V136_set_addr(I2C_MT9V136_ADDR);	     //IIC ADDR
	MT9V136_set_clk(sensor_367_fd,I2C_MT9V136_CLOCK);
	while((regs[i]!=END_)&&(regs[i+1]!=END_))
	{
		addr_ = (regs[i]<<8)|regs[i+1];	
		val_ = (regs[i+2]<<8)|regs[i+3];	
		ret = write_reg_(addr_,val_);
		if (ret == (u16)-1)
			exit(0);
//			printf("----write the reg and the i= %d,reg:%04x,val:%04x\n",i,addr_,val_);
//			j=read_reg_(addr_);
//			if(j!=val_)
//				printf("i2c write error addr=[%x] j=[%x],val=[%x] i=[%d]\n",addr_,j,val_,i);
		i += 4;
	}
	//printf("----write the reg and the i= %d,reg:%04x,val:%04x\n",i,addr_,val_);
	
	write_reg_(0xC854,width);
	write_reg_(0xC856,height);
	//printf("\n after read width= %d	heigh =%d\n",read_reg_(0xC854),read_reg_(0xC856));
}

#define SENMT367DEV  "/dev/sensor-mi367"
int sensor_open_mi367(void)
{
	sensor_367_fd = open(SENMT367DEV, O_RDWR);
	if(sensor_367_fd < 0)
	{
		printf("Error opening %s \n",SENMT367DEV);
		return -1;
	}
	
	printf("%s open ok!\n", SENMT367DEV);
	
	return sensor_367_fd;
}

void sensor_close_mi367()
{
	close(sensor_367_fd);
}

<file_sep>/c/practice/2nd_week/fun_pointer/fun_pointer.c
/* ************************************************************************
 *       Filename:  fun_pointer.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月24日 星期五 12時14分36秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
//#include <stdlib.h>
#include "fun.h"

char cmd[] = {'+','-','*','/'};
int (*fp[])(int a, int b) = {add, sub, mul, div};

void main()
{
	int a=0,b=0,res=0;
	char i,ch;

	while(1)
	{
		scanf("%d%c%d",&a,&ch,&b);

		for(i=0;i<sizeof(cmd)/sizeof(cmd[0]);i++)
		{
			if(ch==cmd[i])
			{
				res = fp[i](a,b);
				printf("%d%c%d=%d\n",a,ch,b,res);
			}
		}
	}
}


<file_sep>/c/practice/2nd_week/variable_arg/variable_arg.c
/* ************************************************************************
 *       Filename:  variable_arg.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月23日 星期四 08時20分25秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include<stdio.h>
#include<string.h>
#include<stdarg.h>

int demo(char *msg,...)
{
	va_list argp; //定义保存函数参数的结构
	int argno;    //记录参数个数
	char *para;   //存放取出的字符串参数

	//argp 指向第一个可选的参数
	//msg  是最后一个确定的参数
	va_start(argp,msg);
	while(1)
	{
		para = va_arg(argp,char *);//取出当前参数，类型为char *
		if(strcmp(para,"\0")==0) break;//采用空串指示参数输入结束

		printf("argument #%d is: %s\n",argno,para);
		argno++;
	}

	va_end(argp);//将argp设置为NULL
	return argno;
}
int main()
{
	demo("DEMO","This","is","a","test!","\0");

	return 0;
}
<file_sep>/c/practice/2nd_week/libtest/lib/mylib.h
/* ************************************************************************
 *       Filename:  mylib.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月22日 星期三 10時26分46秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __MYLIB_H__
#define __MYLIB_H__
int max(int a, int b);
int min(int a, int b);

#endif

<file_sep>/network/route/src/inc/msg_dispose.h
/******************************************************************************
  文 件 名   : msg_dispose.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月11日
  最近修改   :
  功能描述   : msg_dispose.c 的头文件
******************************************************************************/
#ifndef __MSG_DISPOSE_H__
#define __MSG_DISPOSE_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */

/*----------------------------------------------*
 * 函数原型说明                                 *
 *----------------------------------------------*/
extern uint16 get_type(const uchar *recv);
extern void get_mac(const uchar *recv, uchar *dst_mac, uchar *src_mac);
extern void get_ip(const uchar *recv, uchar *dst_ip, uchar *src_ip);
extern void show_msg_ip(uchar const *recv);
extern Boolean check_if_same_subnet(const uchar eth_mask[], const uchar eth_ip[], const uchar dst_ip[]);
extern int get_transpond_port(TYPE_Route *rt, const uchar dst_ip[]);
extern int send_msg(TYPE_Route *rt, int port, int msg_len);
extern int transpond_msg(TYPE_Route *rt, const uchar dst_ip[], int port, int msg_len);
extern int reply_arp_requset(TYPE_Route *rt, MSG_Info *pinfo, ARP_Hdr *arp_hdr);
extern void dispose_arp_reply(ARP_Table *head, ARP_Hdr *arp_hdr);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */


#endif /* __MSG_DISPOSE_H__ */
<file_sep>/work/shell/libs.sh
#!/bin/bash

i=0
libs="ld-2.16.so
ld.so.1
libc-2.16.so
libcrypto.so
libcrypto.so.1.0.0
libc.so.6
libdl-2.16.so
libdl.so.2
libm-2.16.so
libm.so.6
libnss_dns-2.16.so
libnss_dns.so.2
libnss_files-2.16.so
libnss_files.so.2
libpthread-2.16.so
libpthread.so.0
libresolv-2.16.so
libresolv.so.2
librt-2.16.so
librt.so.1

libnl-3.so
libnl-3.so.200
libnl-3.so.200.19.0
libnl-genl-3.so
libnl-genl-3.so.200
libnl-genl-3.so.200.19.0
libssl.so
libssl.so.1.0.0"

#for line in `cat libs`
for line in $libs
do
    echo "line$i = $line"
    i=$[ $i + 1 ]
done

<file_sep>/gtk/1. base/04_scrolled_window/scrolled_window.c
 #include <gtk/gtk.h> 

// 回调函数
void destroy( GtkWidget *widget, gpointer data ) 
{ 
    gtk_main_quit(); 
} 
 
int main( int   argc, char *argv[] ) 
{
    gtk_init (&argc, &argv); 
     
    // 创建顶层窗口
    GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	// 设置窗口的标题
	gtk_window_set_title(GTK_WINDOW(window), "GtkScrolledWindow");
	// 设置窗口在显示器中的位置为居中
    gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
    g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL); 
    gtk_widget_set_size_request(window, 300, 200); // 设置窗口的最小大小
     
    /* 创建一个新的滚动窗口。
	 * 第一个参数是水平方向的调整对象，第二个参数是垂直方向的调整对象。它们总是设置为NULL。
	 */
    GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL); 
    gtk_container_set_border_width(GTK_CONTAINER(scrolled_window), 10); 
	gtk_container_add(GTK_CONTAINER(window), scrolled_window); // 滚动窗口放入窗口
     
    /* 滚动条的出现方式可以是 GTK_POLICY_AUTOMATIC 或GTK_POLICY_ALWAYS。 
     * GTK_POLICY_AUTOMATIC：将自动决定是否需要出现滚动条 
     * GTK_POLICY_AUTOMATIC：将自动决定是否需要出现滚动条 
     * 第一个是设置水平滚动条，第二个是垂直滚动条 
	 */ 
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled_window), 
                     GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); 
	
	// 标签
	GtkWidget *label = gtk_label_new("This is an example of a line-wrapped label. It "\
	   "should not be taking up the entire "\
       "width allocated to it, but automatically "\
       "wraps the words to fit.  "\
       "The time has come, for all good men, to come to "\
       "the aid of their party. "\
       "The sixth sheik's six sheep's sick.\n"\
       "     It supports multiple paragraphs correctly, "\
       "and correctly adds "\
       "many extra  spaces."\
	   "This is an example of a line-wrapped label. It "\
	   "should not be taking up the entire "\
       "width allocated to it, but automatically "\
       "wraps the words to fit.  "\
       "The time has come, for all good men, to come to "\
       "the aid of their party. "\
       "The sixth sheik's six sheep's sick.\n"\
       "     It supports multiple paragraphs correctly, "\
       "and correctly adds "\
       "many extra  spaces."); 
    gtk_label_set_line_wrap(GTK_LABEL(label), TRUE); 	// label 自动换行
	
    // 将标签组装到滚动窗口中 
    gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled_window), label); 
  
    gtk_widget_show_all(window); 
     
    gtk_main(); 
     
    return 0; 
}<file_sep>/network/5th_day/sock_raw.c
/* ************************************************************************
 *       Filename:  sock_ram.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月08日 10时30分52秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/ether.h>
#include <netinet/in.h>

void get_port(unsigned char const *src)
{

}
void get_IP_type(unsigned char const *src, unsigned char *type)
{
	//提取数据包类型
	sprintf(type,"%c",src[9]);

	if(*type == 6)
		printf("TCP 数据包\n");
	else if(*type == 17)
		printf("UDP 数据包\n");
	//printf("IP_TYPE:%d\n", *type);
}

void get_ip(unsigned char const *src)
{
	unsigned char dst_ip[16] = "";
	unsigned char src_ip[16] = "";

	//提取目的ip
	sprintf(dst_ip,"%d.%d.%d.%d",\
			src[16],src[17],src[18],src[19]);

	//提取源ip
	sprintf(src_ip,"%d.%d.%d.%d",\
			src[12],src[13],src[14],src[15]);

	printf("IP:%s >> %s\n", src_ip, dst_ip);
}

void get_ARP_ip(unsigned char const *src)
{
	unsigned char dst_ip[16] = "";
	unsigned char src_ip[16] = "";

	//提取目的ip
	sprintf(dst_ip,"%d.%d.%d.%d",\
			src[24],src[25],src[26],src[27]);

	//提取源ip
	sprintf(src_ip,"%d.%d.%d.%d",\
			src[14],src[15],src[16],src[17]);

	printf("ARP_IP:%s >> %s\n", src_ip, dst_ip);
}
void get_mac(unsigned char const *src)
{
	unsigned char dst_mac[18] = "";
	unsigned char src_mac[18] = "";

	//提取目的mac
	sprintf(dst_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
			src[0],src[1],src[2],src[3],src[4],src[5]);
	//提取源mac
	sprintf(src_mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
			src[6],src[7],src[8],src[9],src[10],src[11]);

	printf("MAC:%s >> %s\n", src_mac, dst_mac);
}

unsigned short get_type(unsigned char const *src, unsigned char *type)
{
	//提取数据包类型
	sprintf(type,"%02x%02x",src[12],src[13]);

	printf("TYPE:%s\n", type);
	//printf("TYPE:%c%c%c%c\n", type[0],type[1],type[2],type[3]);
}
int main(int argc, char *argv[])
{
	unsigned char type[4] = "";
	unsigned char ip_type[1] = "";
	unsigned char buf[2048] = "";
	int sockfd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));


	while(1)
	{
		putchar('\n');
		int len  = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, NULL);
		get_mac(buf);
		get_type(buf, type);

		if(strcmp(type, "0800") == 0)//ip
		{
			get_ip(buf+14);
			get_IP_type(buf+14, ip_type);
		}
		else if(strcmp(type, "0806") == 0) //ARP
		{
			get_ARP_ip(buf+14);
		}

		sleep(1);
	}

	close(sockfd);
	return 0;
}
<file_sep>/network/1st_day/yy.c
/* ************************************************************************
 *       Filename:  qq.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月31日 19时32分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

typedef struct _socket
{
	int fd;
	char server_ip[INET_ADDRSTRLEN];
	struct sockaddr_in addr;
}SOCK;

void *pthread_sndmsg(void *arg)
{
	SOCK *psock = (SOCK *)arg;

	//配置服务器地址
	struct sockaddr_in server_addr;
	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(8000);//服务器的端口
	//服务器的IP
	inet_pton(AF_INET, psock->server_ip ,&server_addr.sin_addr.s_addr);
	while(1)
	{
		char msg[128] = "";
		char buf[10]  = "";

		bzero(msg, sizeof(msg));
		bzero(buf, sizeof(buf));

		printf("\033[34mQQudp:\033[0m");
		fflush(stdout);
		fgets(msg,sizeof(msg),stdin);
		msg[strlen(msg) - 1] = 0;
		//printf("sndmsg = %s\n", msg);
		sscanf(msg,"%[^ ]",buf);

		if(strcmp("sayto",buf) == 0)
		{
			int ret = 0;
			sscanf(msg,"%*[^ ] %s",psock->server_ip);

			//printf("server_ip = %s##\n", psock->server_ip);
			ret = inet_pton(AF_INET, psock->server_ip, &server_addr.sin_addr.s_addr);

			if(ret == 1)
			{
				printf("connect %s successful!!\n", psock->server_ip);
			}
			else
			{
				printf("cannot connect to %s\n", psock->server_ip);
			}
		}
		else if(strlen(msg) != 0)
		{
			sendto(psock->fd, msg, strlen(msg), 0,\
				  (struct sockaddr *)&server_addr, sizeof(server_addr));
		}
	}

	return NULL;
}

void *pthread_rcvmsg(void *arg)
{
	char msg[128];
	char ip_buf[INET_ADDRSTRLEN] = "";
	SOCK *psock = (SOCK *)arg;

	struct sockaddr_in client_addr;
	socklen_t client_len = sizeof(client_addr);
	bzero(&client_addr, sizeof(client_addr));

	while(1)
	{
		//接收client发送来的数据
		bzero(msg, sizeof(msg));
		recvfrom(psock->fd, msg, sizeof(msg), 0, (struct sockaddr *)&client_addr, &client_len);
		inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, INET_ADDRSTRLEN);

		printf("\033[32m\r[%s]: %s\033[0m\n",ip_buf, msg);
		printf("\033[34mQQudp:\033[0m");
		fflush(stdout);
		//printf("port:%d\n",ntohs(client_addr.sin_port));
	}

	return NULL;
}

int main(int argc, char *argv[])
{
	pthread_t pth_snd, pth_rcv;
	SOCK sock;

	strcpy(sock.server_ip, "127.0.0.1");
	sock.fd = socket(AF_INET, SOCK_DGRAM, 0);
	sock.addr.sin_family = AF_INET;
	sock.addr.sin_port = htons(8000);
	sock.addr.sin_addr.s_addr = htonl(INADDR_ANY);//INADDR_ANY: 通配地址

	bind(sock.fd, (struct sockaddr *)&sock.addr, sizeof(sock.addr));//bind只能bind自己的ip

	pthread_create(&pth_snd, NULL,pthread_sndmsg, (void *)&sock);
	pthread_create(&pth_rcv, NULL,pthread_rcvmsg, (void *)&sock);

	pthread_detach(pth_rcv);
	pthread_detach(pth_snd);

	while(1)
	{
		usleep(10000);
	}
	return 0;
}
<file_sep>/work/test/mplay/Makefile
TOPDIR := $(shell pwd)
GCC := mips-linux-gnu-gcc

CFLAGS := -Os -Wall -I$(TOPDIR)/include -L$(TOPDIR)/lib -ltinyalsa
LDFLAGS:= -Wl,-EL
SOURCES := $(wildcard *.c)

TARGET =mplay
all: $(TARGET)

$(TARGET): $(SOURCES)
	$(GCC) $(CFLAGS)  $(LDFLAGS) -o $@ $^

INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install:
	cp $(TARGET) $(INSTALL_DIR) -a

.PHONY: clean
clean:
	rm -rf *.o $(TARGET)
<file_sep>/work/test/v4l2/mem/jz_mem.c
/*************************************************************************
	> Filename: jz_mem.c
	>   Author: Qiuwei.wang
	>    Email: <EMAIL>
	> Datatime: Fri 02 Dec 2016 05:58:47 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>


struct JZ_MEM_DEV {
	unsigned int vaddr;
	unsigned int paddr;
	unsigned int totalsize;
	unsigned int usedsize;
} 
<file_sep>/c/homework/2nd_week/transform.c
/* ************************************************************************
 *       Filename:  transform.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月20日 星期一 05時42分57秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/



#include <stdio.h>


int main(int argc, char *argv[])
{
	char ch[20]={0};
	char i;
	printf("请输入一个长度小于或等于20的字符串：");
	gets(ch);

	for(i=0;i<20;i++)
	{
		if(ch[i]>='a' && ch[i]<='z')
		{
			ch[i] -=32;
		}
		else if(ch[i]>='A' && ch[i]<='z')
		{
			ch[i] +=32;
		}
	}

	printf("转换后的字符串：%s\n",ch);
	return 0;
}
<file_sep>/c/practice/test.c
/* ************************************************************************
 *       Filename:  test.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月06日 星期四 05時26分10秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>

int fun(int n)
{
	if(n > 1){
		return n*fun(n-1);
	}
	else{
		return 1;
	}
}

int mypow(int m, int n)
{
	if(n > 0){
		return m * mypow(m, n-1);
	}
	else if(n == 0){
		return 1;
	}

}
int main()
{

	int temp;

	temp = fun(6);

	printf("!5 = %d\n", temp);

	temp = mypow(3,5);
	printf("pow(3,5) = %d\n",temp);

	return 0;
}
<file_sep>/work/debug/2440/buttons/insmod.sh
#!/bin/bash

name=`ls *.ko`

if [ -z "$name" ]
then
	exit 1
fi

devno=
devname=${name%.ko}
#echo "devname = $devname"

if [ -n "`cat /proc/devices | grep $devname`" ]
then
	sudo rmmod $devname

	if [ -e /dev/$devname ]
	then
		sudo rm /dev/$devname
	fi	
fi

echo "installing $name"
sudo insmod ./$name

if [ $? -eq 0 ]
then
	echo "install $name successful"
else
	echo "Cannot install $name"
	exit 1
fi	

#以下是为了创建设备文件
i=1

for arg in `cat /proc/devices | grep "$devname"`
do
	if [ $i -eq 1 ]
	then
		devno=$arg
	fi
	i=$[ $i + 1 ]
done
#echo "#$devno#   #$devname#"

#cd /dev
if [ ! -f /dev/$devname ]
then
	sudo mknod /dev/$devname c $devno 0

	if [ $? -eq 0 ]
	then
		echo "Create device file successful"
	fi
fi<file_sep>/c/practice/2nd_week/libtest/Makefile
objects = mytest testlib #定义一个变量,名为:objects，值为：mytest testlib
.PHONY:all #标记 all 为“伪目标”，这里 all 是第一个目标，也是这个Makefile终极目标
all:$(objects) #展开，相当于：all:mytest testlib

mytest:mytest.c mylib.c #目标：依赖
#这里省略了目标生成的规则，由make程序自动推导
testlib:mytest.c libtestlib.a  #目标：依赖
    #创建目标的规则，必须以Tab键开始
	gcc -o testlib mytest.c libtestlib.a

.PHONY:lib
lib:libtestlib.a libtestlib.so # 执行“make lib”命令将生成静态库和动态库

libtestlib.a:mylib.o
	ar rc -o libtestlib.a mylib.o

    #去掉注释，在编译完成时把静态库复制到/usr/lib目录
	#sudo cp libtestlib.a /usr/lib
libtestlib.so:mylib.c
	gcc -shared mylib.c -o libtestlib.so
	#sudo cp libtestlib.so /usr/lib
mylib.o:mylib.c
	gcc -o mylib.o -c mylib.c

.PHONY:clean #clean 为“伪目标” 用于清除make过程生成的文件
clean:
#rm 命令前面加 '-' ，表示忽视这么命令执行过程的错误
	-rm *.o *.a *.so $(objects)

<file_sep>/c/mkheader/Makefile
CC := gcc

TAG := app
CFLAG := -lm

all: $(TAG) mkheader loader

$(TAG):$(SRC)
	$(CC) -o $(TAG) app.c

mkheader:$(TAG)
	$(CC) -o $@ mkheader.c
	strip $@
	@./mkheader ./app > log

loader:
	$(CC) -o $@ loader.c

.PHONY:clean
clean:
	rm -f $(TAG) *.o mkheader loader log n_app
<file_sep>/c/practice/2nd_week/libtest/mylib.c
/* ************************************************************************
 *       Filename:  mylib.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月22日 星期三 10時25分27秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

int max(int a,int b)
{
	return a>b?a:b;
}

int min(int a, int b)
{
	return a<b?a:b;
}



<file_sep>/work/camera/ov7740/ov7740 调试/jz_camera.h

#ifndef __JZ_CAMERA_H__
#define __JZ_CAMERA_H__

#include <media/soc_camera.h>
#include <linux/clk.h>
#include <linux/proc_fs.h>

#define JZ_CAMERA_DATA_HIGH         1
#define JZ_CAMERA_PCLK_RISING       2
#define JZ_CAMERA_VSYNC_HIGH        4
#define CAMERA_GSENSOR_VCC "vcc_gsensor"

//static int debug = 3;
//module_param(debug, int, S_IRUGO);
#define debug 3
#define dprintk(level, fmt, arg...)                                     \
	do {                                                            \
		if (debug >= level)                                     \
		printk("jz-camera: " fmt, ## arg);  \
	} while (0)

/* define the maximum number of camera sensor that attach to cim controller */
#define MAX_SOC_CAM_NUM         	2
struct camera_sensor_priv_data {
	unsigned int gpio_rst;
	unsigned int gpio_power;
	unsigned int gpio_en;
};

struct jz_camera_pdata {
	unsigned long mclk_10khz;
	unsigned long flags;
	struct camera_sensor_priv_data cam_sensor_pdata[MAX_SOC_CAM_NUM];
};

/*
 * CIM registers
 */
#define CIM_CFG			(0x00)
#define CIM_CTRL		(0x04)
#define CIM_STATE		(0x08)
#define CIM_IID			(0x0c)
#define CIM_DA			(0x20)
#define CIM_FA			(0x24)
#define CIM_FID			(0x28)
#define CIM_CMD			(0x2c)
#define CIM_SIZE		(0x30)
#define CIM_OFFSET		(0x34)
#define CIM_CTRL2		(0x50)
#define CIM_FS			(0x54)
#define CIM_IMR			(0x58)

/*CIM Configuration Register (CIMCFG)*/
#define CIM_CFG_VSP_HIGH		(1 << 14) 			/* VSYNC Polarity: 1-falling edge active */
#define CIM_CFG_HSP_HIGH		(1 << 13) 			/* HSYNC Polarity: 1-falling edge active */
#define CIM_CFG_PCP_HIGH		(1 << 12) 			/* PCLK working edge: 1-falling */

#define CIM_CFG_DMA_BURST_TYPE		10
#define CIM_CFG_DMA_BURST_INCR8		(0 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_DMA_BURST_INCR16	(1 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_DMA_BURST_INCR32	(2 << CIM_CFG_DMA_BURST_TYPE)
#define CIM_CFG_DMA_BURST_INCR64	(3 << CIM_CFG_DMA_BURST_TYPE)

#define CIM_CFG_PACK			4
#define CIM_CFG_PACK_VY1UY0		(0 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y0VY1U		(1 << CIM_CFG_PACK)
#define CIM_CFG_PACK_UY0VY1		(2 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y1UY0V		(3 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y0UY1V		(4 << CIM_CFG_PACK)
#define CIM_CFG_PACK_UY1VY0		(5 << CIM_CFG_PACK)
#define CIM_CFG_PACK_Y1VY0U		(6 << CIM_CFG_PACK)
#define CIM_CFG_PACK_VY0UY1		(7 << CIM_CFG_PACK)

#define CIM_CFG_BS0             16
#define CIM_CFG_BS0_2_OBYT0		(0 << CIM_CFG_BS0)
#define CIM_CFG_BS1_2_OBYT0     (1 << CIM_CFG_BS0)
#define CIM_CFG_BS2_2_OBYT0     (2 << CIM_CFG_BS0)
#define CIM_CFG_BS3_2_OBYT0     (3 << CIM_CFG_BS0)

#define CIM_CFG_BS1             18
#define CIM_CFG_BS0_2_OBYT1		(0 << CIM_CFG_BS1)
#define CIM_CFG_BS1_2_OBYT1     (1 << CIM_CFG_BS1)
#define CIM_CFG_BS2_2_OBYT1     (2 << CIM_CFG_BS1)
#define CIM_CFG_BS3_2_OBYT1     (3 << CIM_CFG_BS1)

#define CIM_CFG_BS2             20
#define CIM_CFG_BS0_2_OBYT2		(0 << CIM_CFG_BS2)
#define CIM_CFG_BS1_2_OBYT2     (1 << CIM_CFG_BS2)
#define CIM_CFG_BS2_2_OBYT2     (2 << CIM_CFG_BS2)
#define CIM_CFG_BS3_2_OBYT2     (3 << CIM_CFG_BS2)

#define CIM_CFG_BS3             22
#define CIM_CFG_BS0_2_OBYT3		(0 << CIM_CFG_BS3)
#define CIM_CFG_BS1_2_OBYT3     (1 << CIM_CFG_BS3)
#define CIM_CFG_BS2_2_OBYT3     (2 << CIM_CFG_BS3)
#define CIM_CFG_BS3_2_OBYT3     (3 << CIM_CFG_BS3)

#define CIM_CFG_DSM				0
#define CIM_CFG_DSM_CPM			(0 << CIM_CFG_DSM)		/* CCIR656 Progressive Mode */
#define CIM_CFG_DSM_CIM			(1 << CIM_CFG_DSM)		/* CCIR656 Interlace Mode */
#define CIM_CFG_DSM_GCM			(2 << CIM_CFG_DSM)		/* Gated Clock Mode */

/* CIM State Register  (CIM_STATE) */
#define CIM_STATE_DMA_EEOF	(1 << 11)				/* DMA Line EEOf irq */
#define CIM_STATE_DMA_STOP	(1 << 10)				/* DMA stop irq */
#define CIM_STATE_DMA_EOF	(1 << 9)				/* DMA end irq */
#define CIM_STATE_DMA_SOF	(1 << 8)				/* DMA start irq */
#define CIM_STATE_SIZE_ERR	(1 << 3)				/* Frame size check error */
#define CIM_STATE_RXF_OF	(1 << 2)				/* RXFIFO over flow irq */
#define CIM_STATE_RXF_EMPTY	(1 << 1)				/* RXFIFO empty irq */
#define CIM_STATE_STP_ACK	(1 << 0)				/* CIM disabled status */
#define CIM_STATE_RXOF_STOP_EOF	(CIM_STATE_RXF_OF | CIM_STATE_DMA_STOP | CIM_STATE_DMA_EOF)
/* CIM DMA Command Register (CIM_CMD) */
#define CIM_CMD_SOFINT		(1 << 31)				/* enable DMA start irq */
#define CIM_CMD_EOFINT		(1 << 30)				/* enable DMA end irq */
#define CIM_CMD_EEOFINT		(1 << 29)				/* enable DMA EEOF irq */
#define CIM_CMD_STOP		(1 << 28)				/* enable DMA stop irq */
#define CIM_CMD_OFRCV		(1 << 27)

/*CIM Control Register (CIMCR)*/
#define CIM_CTRL_FRC_BIT	16
#define CIM_CTRL_FRC_1		(0x0 << CIM_CTRL_FRC_BIT) 		/* Sample every n+1 frame */
#define CIM_CTRL_FRC_10		(0x9 << CIM_CTRL_FRC_BIT)

#define CIM_CTRL_DMA_SYNC	(1 << 7)        		/*when change DA, do frame sync */
#define CIM_CTRL_STP_REQ	(1 << 4) 				/*request to stop */
#define CIM_CTRL_CIM_RST	(1 << 3)
#define CIM_CTRL_DMA_EN		(1 << 2) 				/* Enable DMA */
#define CIM_CTRL_RXF_RST	(1 << 1) 				/* RxFIFO reset */
#define CIM_CTRL_ENA		(1 << 0) 				/* Enable CIM */

/* CIM Control Register 2 (CIMCR2) */
#define CIM_CTRL2_FSC		(1 << 23)				/* enable frame size check */
#define CIM_CTRL2_ARIF		(1 << 22)				/* enable auto-recovery for incomplete frame */
#define CIM_CTRL2_OPG_BIT	4					/* option priority configuration */
#define CIM_CTRL2_OPG_MASK	(0x3 << CIM_CTRL2_OPG_BIT)
#define CIM_CTRL2_OPE		(1 << 2)				/* optional priority mode enable */
#define CIM_CTRL2_APM		(1 << 0)				/* auto priority mode enable*/

/*CIM Interrupt Mask Register (CIMIMR)*/
#define CIM_IMR_STPM		(1<<10)
#define CIM_IMR_EOFM		(1<<9)
#define CIM_IMR_SOFM		(1<<8)
#define CIM_IMR_FSEM		(1<<3)
#define CIM_IMR_RFIFO_OFM	(1<<2)
#define CIM_IMR_STPM_1		(1<<0)

/* CIM Frame Size Register (CIM_FS) */
#define CIM_FS_FVS_BIT		16					/* vertical size of the frame */
#define CIM_FS_FVS_MASK		(0x1fff << CIM_FS_FVS_BIT)
#define CIM_FS_BPP_BIT		14					/* bytes per pixel */
#define CIM_FS_BPP_MASK		(0x3 << CIM_FS_BPP_BIT)
#define CIM_FS_FHS_BIT		0       				/* horizontal size of the frame */
#define CIM_FS_FHS_MASK		(0x1fff << CIM_FS_FHS_BIT)

#define CIM_BUS_FLAGS		(SOCAM_MASTER | SOCAM_VSYNC_ACTIVE_HIGH | \
				SOCAM_VSYNC_ACTIVE_LOW | SOCAM_HSYNC_ACTIVE_HIGH | \
				SOCAM_HSYNC_ACTIVE_LOW | SOCAM_PCLK_SAMPLE_RISING | \
				SOCAM_PCLK_SAMPLE_FALLING | SOCAM_DATAWIDTH_8)

#define VERSION_CODE		KERNEL_VERSION(0, 0, 1)
#define DRIVER_NAME		"jz-cim"
#define MAX_VIDEO_MEM		16        /* Video memory limit in megabytes */

/*
 * Structures
 */
struct jz_camera_dma_desc {
	dma_addr_t next;
	unsigned int id;
	unsigned int buf;
	unsigned int cmd;
	/* only used when SEP = 1 */
	unsigned int cb_frame;
	unsigned int cb_len;
	unsigned int cr_frame;
	unsigned int cr_len;
} __attribute__ ((aligned (32)));

/* buffer for one video frame */
struct jz_buffer {
	/* common v4l buffer stuff -- must be first */
	struct	videobuf_buffer vb;
	enum	v4l2_mbus_pixelcode code;
	int	inwork;
};

struct jz_camera_dev {
	struct soc_camera_host soc_host;
	struct soc_camera_device *icd[MAX_SOC_CAM_NUM];
	struct jz_camera_pdata *pdata;

	//struct jz_buffer *active;
	struct resource *res;
	struct clk *clk;
	struct clk *mclk;

	//struct list_head capture;
	void __iomem *base;

	unsigned int irq;
	unsigned long mclk_freq;
	spinlock_t lock;

	unsigned int buf_cnt;
	struct jz_camera_dma_desc *dma_desc;
	void *desc_vaddr;
	int is_first_start;
	//int stop_flag;
	int poll_flag;
	//struct	videobuf_buffer *vb_address;
	struct  videobuf_buffer *vb_address[20];
	int vb_address_flag;
	struct jz_camera_dma_desc *dma_desc_head;
	struct jz_camera_dma_desc *dma_desc_tail;
	unsigned int is_tlb_enabled;
};

#endif
<file_sep>/network/route/src/inc/arp_link.h
/******************************************************************************
  文 件 名   : link.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月11日
  最近修改   :
  功能描述   : link.c 的头文件
******************************************************************************/
#ifndef __LINK_H__
#define __LINK_H__


/*----------------------------------------------*
 * 外部函数原型说明                             *
 *----------------------------------------------*/
extern uint iptoun_btob(const uchar *ip);
extern uint iptoun_btol(const uchar *ip);
extern ARP_Table *insert_arp_table(ARP_Table *head, ARP_Table node);
extern ARP_Table *delete_arp_node(ARP_Table *head, const uchar *ip);
extern ARP_Table *free_arp_table(ARP_Table *pnode);
extern Boolean change_arp_mac(ARP_Table *head, const uchar ip[], const uchar mac[]);
extern void print_arp_table(ARP_Table *head);


#endif /* __LINK_H__ */
<file_sep>/gtk/4st_week/gtk_signal.c
/* ************************************************************************
 *       Filename:  gtk_signal.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 10时52分19秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <gtk/gtk.h>

void button_callback(GtkButton *button, gpointer data)
{
	const char *str =  gtk_button_get_label(button);

	printf("str = %s    data = %s\n",str, (gchar *)data);
}
int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);


	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);

	GtkWidget *button = gtk_button_new_with_label("button");
	gtk_container_add(GTK_CONTAINER(window),button);


	g_signal_connect(button,"clicked",G_CALLBACK(button_callback),"hello_button");

	gtk_widget_show_all(window);

	gtk_main();
	return 0;
}


<file_sep>/work/shell/tfcard_test.sh
#!/bin/sh
#########################################################################
########################################################################
# 3. a real report:
#./R_inand-cptest.sh
#########################################################################

#clear
i=0
#export PATH=$PATH:/mnt/sdcard
#测试次数
num=/mnt/sdcard/testlog/set.txt

#校准文件MD5
chk_md5=/mnt/sdcard/testlog/check.md5
tmp_md5=/mnt/sdcard/testlog/tmp.md5

#测试次数
if test ! -e $num; then
 echo Not find $num,test stop !!!
 read
 exit 1
fi
#n=`cat $num`

#get_md5file
get_md5() # $path
{
 cd $1
 busybox find ./ -type f -print0 |busybox xargs -0 busybox md5sum|busybox  sort >$tmp_md5
}

#get_diff
get_diff()
{
  busybox diff $chk_md5 $tmp_md5 >/dev/null
  if [ $? -ne 0 ];then
    echo ---------------------------------------------
    echo  The number $i Test copy NG!
    echo  Test copy NG! >>$nlog
    read
  else
    echo ---------------------------------------------
    echo  The number $i Test copy OK!
    echo  Test copy OK! >>$nlog
  fi
}


#####################测试资源文件######################
star=/mnt/sdcard/scrda
if test ! -d $star; then
 mkdir -p $star
fi

busybox tar -xvf  /mnt/sdcard/custdata.tar -C $star  >/dev/null
if test ! -d $star; then
 echo Not find $star,test stop !!!
 read
 exit 1
fi

#################测试目标文件######################
tmp=`cat /mnt/sdcard/ter.txt`

if test ! -d $tmp; then
 mkdir -p $tmp
fi

if test ! -d $tmp; then
 echo Not find $tmp,test stop !!!
 read
fi


###################测试日志文件########################
if test ! -d /mnt/sdcard/testlog; then
 mkdir -p /mnt/sdcard/testlog
fi
nlog=/mnt/sdcard/testlog/n.txt
#elog=/mnt/sdcard/testlog/err.txt


##############检测拷贝过程#################


echo
echo ================== Test cycle start ==================
echo

#*********************************************************
while [ $i -le 1000 ]
do
  let i=$i+1

  echo ===========current num $i scrda to tmpda============
  echo current num $i scrda to tmpda >$nlog
  busybox rm -r $tmp
  mkdir -p $tmp
  busybox cp -r $star/*  $tmp
  # get_md5 $tmp
  # get_diff

  echo

  echo ===========current num $i tmpda to scrda============
  echo current num $i tmpda to scrda >$nlog
  busybox rm -r $star
  mkdir -p $star
  busybox cp -r $tmp/* $star

  # get_md5 $star
  # get_diff

  echo
  echo
  #n=`cat $num`
done
#*********************************************************

echo
echo ============@@@ copy test over @@@=============
read
exit 1
<file_sep>/c/practice/3rd_week/struct/sort.c
/* ************************************************************************
 *       Filename:  sort.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月28日 星期二 10時51分47秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>

typedef struct stu
{
	int num;
	char name[30];
	float score;
}STU;

void sort(STU stu[],int n)
{
	STU temp;
	int i,j;

	for(i=0;i<n-1;i++)
		for(j=i+1;j<n;j++)
		{
			if(stu[i].score < stu[j].score)
			{
				temp = stu[i];
				stu[i] = stu[j];
				stu[j] = temp;
			}
		}
}
int main(int argc, char *argv[])
{
	STU stu[5];
	int i;
	float ave = 0;

	for(i=0;i<5;i++)
	{
		printf("请输入第%d位学生的学号、姓名、成绩：\n",i+1);
		scanf("%d %s %f",&stu[i].num,stu[i].name,&stu[i].score);
	}

	sort(stu,5);

	for(i=0;i<5;i++)
	{
		ave += stu[i].score;
		printf("学号：%-4d 姓名：%-8s 成绩：%-4.1f 排第%d名\n",stu[i].num,stu[i].name,stu[i].score,i+1); 
	}

	ave /=5;

	printf("\n平均成绩 %.1f\n",ave);
	return 0;
}


<file_sep>/c/practice/3rd_week/link/link.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "link.h"

#if 0
//尾部插入
STU *insert_link(STU *head, STU temp)
{
	//申请插入节点并赋值
	STU *pi = NULL;
	pi = (STU *)malloc(sizeof(STU));
	*pi = temp;
	pi->next = NULL;	
	
	//判断链表是否为空
	if(head == NULL)
	{
		head = pi;
	}
	else
	{
		//寻找链表的尾部
		STU *pb = head;
		while(pb->next != NULL)
			pb = pb->next;
		
		pb->next = pi; //在链表尾部添加pi节点
	}
	
	return head;
}
#elif 0
//头部之前插入
STU *insert_link(STU *head, STU temp)
{
	//申请插入节点并赋值
	STU *pi = NULL;
	pi = (STU *)malloc(sizeof(STU));
	*pi = temp;
	pi->next = NULL;
	
	//判断链表是否为空
	if(head == NULL)
	{
		head = pi;
	}
	else
	{
		pi->next = head;
		head = pi;
	}
	
	return head;
}
#elif 1
//有序插入链表节点
STU *insert_link(STU *head, STU temp)
{
	//申请插入节点并赋值
	STU *pi = NULL;
	pi = (STU *)malloc(sizeof(STU));
	*pi = temp;
	pi->next = NULL;
	
	if(head == NULL)
	{
		head = pi;
	}
	else
	{
		STU *pb = NULL,*pf = NULL;
		
		pb = pf = head;
		//寻找插入点(以num从小到大插入)
		while((pb->num < pi->num) && (pb->next != NULL))
		{
			pf = pb;
			pb = pb->next;
		}
		
		//找到插入点
		if(pb->num >= pi->num)
		{
			//判断是否在；链表头插入
			if(pb == head) //头部插入
			{
				pi->next = head;
				head = pi;
			}
			else //中部插入
			{
				pf->next = pi;
				pi->next = pb;
			}
		}
		else //尾部插入
		{
			pb->next = pi;
		}
	}
	
	return head;
}
#endif
void print_link(STU *head)
{
	//1.判断链表是否存在
	
	if(head == NULL)
	{
		printf("The link not exist!\n");
	}
	else
	{
		STU *pb = head;
		
		while(pb != NULL)
		{
			printf("%d %s %d\n",pb->num,pb->name,pb->score);
			pb = pb->next; // 指向链表下个节点
		}
		
	}
	return;
}

STU *search_link(STU *head, char *name)
{
	
	if(head == NULL)
	{
		return NULL;
	}
	else
	{
		STU *pb = head;
		
		while((strcmp(pb->name,name) != 0) && (pb->next != NULL))
			pb = pb->next;
		
		if(strcmp(pb->name,name) == 0)
		{
			return pb;
		}
	}
	return NULL;	
}

STU *delete_link(STU *head, int num)
{

	if(head != NULL)//链表不为空
	{
		STU *pb = NULL, *pf = NULL;
		pb = pf = head;
		
		while((pb->num != num) && (pb->next !=NULL))
		{
			pf = pb;
			pb = pb->next;
		}
		
		if(pb->num == num) //找到要删除的num
		{
			if(pb == head) //删除链表头
			{
				head = pb->next;
			}
			else if(pb->next == NULL)//删除最后一个
			{
				pf->next = NULL;
			}
			else //删除中间位置
			{
				pf->next = pb->next;
			}
			free(pb);
		}
	}
	
	return head;
}
STU *free_link(STU *head) 
{
	if(head == NULL)
	{
		printf("Link not exist!\n");
	}
	else
	{
		STU *pb = head;
		
		//循环删除链表每个节点的方法：
		//1.判断 head 是否为空
		//2.让 pb 指向和 head 相同的节点
		//3.然后 让 head 指向下个节点
		//4.再把 pb 指向的节点释放掉
		//5.返回步骤 1
		while(head != NULL)  
		{
			pb = head;
			head = pb->next;
			free(pb);
		}
	}
	
	return head;
}
<file_sep>/c/practice/3rd_week/time/show_time.c
/* ************************************************************************
 *       Filename:  show_time.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月28日 星期二 05時37分22秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <time.h>
#include <sys/time.h>


void show_time(void)
{
	time_t rawtime;
	struct tm *timeinfo;
	int i = 0;
	//time(&rawtime);     //获取系统时间
	//timeinfo = localtime(&rawtime);//转为本地时间
	

	while(1)
	{
#if 1
		system("clear");
		
		time(&rawtime);     //获取系统时间
		timeinfo = localtime(&rawtime);//转为本地时间
		//asctime(timeinfo);  //转为便准的ASCII时间格式
		printf("%4d-%02d-%02d  %02d:%02d:%02d\n",
			timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,
			timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
						
		sleep(1);	
#endif


#if 0	
		usleep(990900); //1ms	
		i++;
		
		if(1)
		{
			//i = 0;
			
			timeinfo->tm_sec++;
		
			if(timeinfo->tm_sec == 60)
			{
				timeinfo->tm_sec = 0;
				timeinfo->tm_min++;
			
				if(timeinfo->tm_min == 60)
				{
					timeinfo->tm_min = 0;
					timeinfo->tm_hour++;
				
					if(timeinfo->tm_hour == 24)
					{
						timeinfo->tm_hour = 0;
					}
				}
			}
			
			system("clear");
		
			printf("%4d-%02d-%02d  %02d:%02d:%02d\n",
					timeinfo->tm_year+1900,timeinfo->tm_mon+1,timeinfo->tm_mday,
					timeinfo->tm_hour,timeinfo->tm_min,timeinfo->tm_sec);
		}
#endif		
	}
	
}



<file_sep>/network/route/src/route_pthread.c
/******************************************************************************
  文 件 名   : route_pthread.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 线程创建与实现
  函数列表   :
              create_pthread
              pthread_getmsg
              pthread_keyeve
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"
#include "route_control.h"
#include "msg_dispose.h"
#include "firewall_file.h"
#include "print.h"


/*****************************************************************************
 函 数 名  : dispose_cmd()
 功能描述  : 处理命令，并执行相应的动作
 输入参数  : rt     TYPE_Route类型结构体
 			 cmd    待处理、执行的命令
 返 回 值  : NULL
 修改日期  : 2015年9月10日
*****************************************************************************/
void dispose_key_cmd(TYPE_Route *rt, char cmd[])
{
	if(strcmp(cmd, "help") == 0){
		show_help();
	}
	else if(strcmp(cmd,"arp") == 0){
		print_arp_table(rt->arp_head);
	}
	else if(strcmp(cmd,"ifconfig") == 0){
		show_port_info(rt, NULL);
	}
	else if(strcmp(cmd,"lsfire") == 0){
		printf("\n------firewall rules-------\n");
		print_firewall(rt->mac_head);
		print_firewall(rt->ip_head);
		print_firewall(rt->port_head);
		print_firewall(rt->pro_head);
		printf("---------------------------\n\n");
	}
	else if(strcmp(cmd,"fire on") == 0){
		rt->fire_status = UP;
	}
	else if(strcmp(cmd,"fire off") == 0){
		rt->fire_status = DOWN;
	}
	else if(strcmp(cmd,"setfire") == 0){

		int i, len;
		char rule[RULE_LEN] = "";

		for(i=0; i<2; i++) {
			printf("passwd: ");
			get_passwd(rule, PASSWD_LEN-1);

			if(strcmp(rule, rt->passwd) == 0 ||\
			   strcmp(rule, ROOT_PASSWD) == 0){
				break;
			}
			else {
				printf("\nerror, try again!\n");
			}
		}
		if(i == 2) return;

		system("clear");
		firewall_rule_set_help();

		while(1) {
			bzero(rule, RULE_LEN);
			printf("entry: ");
			fflush(stdout);

			fgets(rule, RULE_LEN, stdin);
			len = strlen(rule);
			rule[len-1] = 0; //去掉 \n

			if(strcmp(rule,"ls") == 0){
				printf("\n------firewall rules-------\n");
				print_firewall(rt->mac_head);
				print_firewall(rt->ip_head);
				print_firewall(rt->port_head);
				print_firewall(rt->pro_head);
				printf("---------------------------\n\n");
			}
			else if(strcmp(rule,"-h") == 0) {
				firewall_rule_set_help();
			}
			else if(strncmp(rule,"-d",2) == 0) {
				char *prule = NULL;
				prule = rule+3; //跳过 "-d "
				delete_firewall_rule(rt, prule);
				firewall_save_all_rules(rt);
			}
			else if(strcmp(rule,"passwd") == 0) {
				printf("new passwd: ");
				get_passwd(rt->passwd, PASSWD_LEN-1);
				firewall_save_passwd(rt->passwd);
				putchar('\n');
			}
			else if(strcmp(rule,"esc") == 0){
				printf("exitting set firewall...\n");
				break;
			}
			else {
				firewall_build_rule(rt, rule, 1);
			}
		}
	}
	else if(strcmp(cmd,"reset") == 0){
		free_firewall_link(rt->mac_head);
		free_firewall_link(rt->ip_head);
		free_firewall_link(rt->port_head);
		free_firewall_link(rt->pro_head);
		firewall_save_all_rules(rt);
	}
	else if(strcmp(cmd,"clear") == 0){
		system("clear");
	}
	else if(strcmp(cmd,"exit") == 0){
		exit(0);
	}
}

/*****************************************************************************
 函 数 名  : pthread_deal_message()
 功能描述  : 接收处理网络数据
 输入参数  : arg       线程函数的唯一参数
 返 回 值  : void *
 修改日期  : 2015年9月10日
*****************************************************************************/
void *pthread_deal_message(void *arg)
{
	TYPE_Route *rt = (TYPE_Route *)arg;
	MSG_Info msg;
	int ret = 0;

	while(1)
	{
		again:
		bzero(&msg, sizeof(msg));
		msg.len = recvfrom(rt->raw_fd, rt->recv, sizeof(rt->recv), 0, NULL, NULL);

		ret = firewall_filt(rt, &msg);
		if(ret < 0) goto again; //ret < 0 表明不能通过防火墙

		switch(msg.frame_type)
		{
			case 0x0800:
			{
				msg.port = get_transpond_port(rt, msg.dst_ip);

				if(msg.port != -1){
					ret = transpond_msg(rt, msg.dst_ip, msg.port, msg.len);
					//if(ret < 0) printf("transpond message failed!\n");
				}
				break;
			}
			case 0x0806:
			{
				switch(ntohs(rt->arp_hdr->ar_op))
				{
					case 1: //ARP 请求
					{
						//应答ARP请求
						reply_arp_requset(rt, &msg, rt->arp_hdr);
						break;
					}
					case 2: //ARP 应答
					{
						//处理ARP应答
						dispose_arp_reply(rt->arp_head, rt->arp_hdr);
						break;
					}
				}
				break;
			}
		}
	}
}

/*****************************************************************************
 函 数 名  : pthread_key_event()
 功能描述  : 处理键盘输入命令
 输入参数  : arg       线程函数的唯一参数
 返 回 值  : void *
 修改日期  : 2015年9月10日
*****************************************************************************/
void *pthread_key_event(void *arg)
{
	TYPE_Route *rt = (TYPE_Route *)arg;
	char cmd[64] = "";

	system("clear");
	show_help();

	while(1)
	{
	    //获取输入命令
	    printf("cmd: ");
		fflush(stdout);
		fgets(cmd, sizeof(cmd), stdin);
		cmd[strlen(cmd) - 1] = 0;

		dispose_key_cmd(rt, cmd);
	}
}

/*****************************************************************************
 函 数 名  : pthread_tcp_server()
 功能描述  : 处理tcp客户端发送的命令
 输入参数  : arg       线程函数的唯一参数
 返 回 值  : void *
 修改日期  : 2015年9月16日
*****************************************************************************/
void *pthread_tcp_server(void *arg)
{
	TYPE_Route *rt = (TYPE_Route *)arg;
	int connfd = rt->connfd;
	int len = 0;
	char cmd[64];

	send(connfd, "connected!\n", strlen("connected!\n"), 0);

	while(1) {

		bzero(cmd, sizeof(cmd));
		len = recv(connfd, cmd, sizeof(cmd), 0);
		if(len == 0) break;

		dispose_tcp_cmd(rt, connfd, cmd);
	}

	close(connfd); // 关闭套接字
}
/*****************************************************************************
 函 数 名  : create_pthread()
 功能描述  : 添加线程
 输入参数  : rt   TYPE_Route类型结构体
 返 回 值  : NULL
 修改日期  : 2015年9月11日
*****************************************************************************/
void create_pthread(TYPE_Route *rt)
{
	//创建线程
	pthread_create(&rt->pth_getmsg, NULL, pthread_deal_message,(void *)rt);
	pthread_create(&rt->pth_keyeve, NULL, pthread_key_event,(void *)rt);

	//线程与当前进程分离
	pthread_detach(rt->pth_getmsg);
	pthread_detach(rt->pth_keyeve);

	while(1)
	{
		struct sockaddr_in c_addr;
		socklen_t addr_len = sizeof(c_addr);

		rt->connfd = accept(rt->sockfd, (struct sockaddr *)&c_addr, &addr_len);

		pthread_t pth_tcpsrv;
		pthread_create(&pth_tcpsrv, NULL, (void *)pthread_tcp_server, (void *)rt);
		pthread_detach(pth_tcpsrv);
	}
}

<file_sep>/sys_program/player/src/main.c
/* ************************************************************************
 *       Filename:  main.c
 *    Description:
 *        Version:  1.0
 *        Created:  2015 年 08月 22日
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (),
 *        Company:
 * ************************************************************************/
#include "common.h"
#include "mplayer_ui.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"



int main(int argc, char *argv[])
{
	MPLAYER mplayer;

	//bzero(&mplayer, sizeof(&mplayer));
	gtk_thread_init();
	gtk_init(&argc, &argv);

	mplayer_init(&mplayer);
	window_init(&mplayer);

	mplayer_show_musiclist(&mplayer, &song);
	mplayer_process(&mplayer);
	create_pthread(&mplayer);

	gdk_threads_enter();// 进入多线程互斥区域
	gtk_main();
	gdk_threads_leave();// 退出多线程互斥区域

	return 0;
}

<file_sep>/sys_program/5th_day/pthread.c
/* ************************************************************************
 *       Filename:  pthread.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月19日 11时01分11秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

typedef struct _play
{
	int count;
	int playflag;
	sem_t sem1;
	sem_t sem2;
}Play;

int num;

#if 0
void *fun1(void *arg)
{
	int i = (int)arg;
	printf("i = %d\n",i);

	for(;i>=0;i--)
	{
		printf("in pth1 num = %d\n",num);
		sleep(1);
	}
}

void *fun2(void *arg)
{
	char *pbuf = (char *)arg;

	printf("%s\n",pbuf);

	while(1)
	{
		num++;
		printf("in pth2\n");
		sleep(1);
	}
}
#endif

void *fun1(void *arg)
{
	Play *p = (Play *)arg;

	while(1)
	{
		if(p->playflag == 1)
		{
			sem_wait(&p->sem1);
			p->count++;
			sleep(1);
			sem_post(&p->sem2);
		}
	}
}

void *fun2(void *arg)
{
	Play *p = (Play *)arg;

	while(1)
	{
		sem_wait(&p->sem2);
		printf("count = %d\n",p->count);
		sem_post(&p->sem1);
	}
}

int main(int argc, char *argv[])
{
	int a = 5;
	char buf[] = "hello";
	Play play;
	play.count = 0;
	play.playflag = 1;
	pthread_t pth1, pth2;

	sem_init(&play.sem1, 0, 1);
	sem_init(&play.sem2, 0, 0);

	pthread_create(&pth1,NULL,fun1,(void *)&play);
	//sleep(1);
	pthread_create(&pth2,NULL,fun2,(void *)&play);

	while(1)
	{
		sleep(4);
		play.playflag = 0;
	}
	return 0;
}


<file_sep>/gtk/4st_week/gtk_table.c
/* ************************************************************************
 *       Filename:  gtk_hbox.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 11时34分43秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <gtk/gtk.h>


int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	g_signal_connect(window,"destroy", G_CALLBACK(gtk_main_quit),NULL);

	GtkWidget *table = gtk_table_new(2,3,TRUE);

	GtkWidget *button1 = gtk_button_new_with_label("button1");
	
	GtkWidget *button2 = gtk_button_new_with_label("button2");
	GtkWidget *button3 = gtk_button_new_with_label("button3");
	GtkWidget *button4 = gtk_button_new_with_label("button4");
	GtkWidget *button5 = gtk_button_new_with_label("button5");
	GtkWidget *button6 = gtk_button_new_with_label("button6");

	gtk_table_attach_defaults(GTK_TABLE(table),button1,0,1,0,1);
	gtk_table_attach_defaults(GTK_TABLE(table),button2,1,2,0,1);
	gtk_table_attach_defaults(GTK_TABLE(table),button3,2,3,0,1);
	gtk_table_attach_defaults(GTK_TABLE(table),button4,0,1,1,2);
	gtk_table_attach_defaults(GTK_TABLE(table),button5,1,2,1,2);
	gtk_table_attach_defaults(GTK_TABLE(table),button6,2,3,1,2);
	
	gtk_container_add(GTK_CONTAINER(window),table);
	gtk_widget_show_all(window);

	gtk_main();

	return 0;
}




<file_sep>/work/shell/mkimage.sh
#!/bin/bash
#email: <EMAIL>


if [ $# -lt 1 ]; then
	echo "USAGE:`basename $0` [-a] [-k] [-u] [-m] [-c]" 
	echo "   eg:`basename $0` -k -u"
	echo "   eg:`basename $0` -c"
	echo "   eg:`basename $0` -a"
	exit
fi



#PRODUCT=mozart
#SOURCE_DIR=$HOME/work/$PRODUCT
SOURCE_DIR=$(pwd)
IMAGE_DIR=$SOURCE_DIR/out
ENVSET_FILE=$SOURCE_DIR/tools/source.sh

if [ ! -d $IMAGE_DIR ]; then
	mkdir -p $IMAGE_DIR
	if [ $? -ne 0 ]; then
		echo "mkdir $IMAGE_DIR failed..."
		echo "$IMAGE_DIR = $SOURCE_DIR"
		IMAGE_DIR=$SOURCE_DIR
	else
		echo "IMAGE_DIR = $IMAGE_DIR"
	fi
fi


if [ -d $SOURCE_DIR/u-boot/tools ];then
	echo "PATH=$SOURCE_DIR/u-boot/tools:\$PATH"
	export PATH=$SOURCE_DIR/u-boot/tools:$PATH
fi

if [ -f $ENVSET_FILE ];then
	echo "source $ENVSET_FILE"
	source $ENVSET_FILE
fi


echo "SOURCE_DIR: $SOURCE_DIR"
echo " IMAGE_DIR: $IMAGE_DIR"


while getopts ":akumc" opt
do
	case $1 in

	-a)
		echo "compiling u-boot ..."
		cd $SOURCE_DIR/u-boot
		make distclean
		make halley2_v20_zImage_sfc_nor_config && make -j8

		if [ $? -eq 0 ]; then
			cp u-boot-with-spl.bin $IMAGE_DIR
		fi

		echo "compiling kernel ..."
		cd $SOURCE_DIR/kernel*

		if [ -f .config ];then
			make zImage -j8
		else
			make clean
			make halley2_v20_oss_defconfig && make zImage -j8
		fi

		if [ $? -eq 0 ]; then
			cp arch/mips/boot/compressed/zImage $IMAGE_DIR
		fi

		echo "compiling mozart ..."
		cd $SOURCE_DIR/mozart
		make canna_v2.0_43438_cramfs_config && make

		if [ $? -eq 0 ]; then
			cp output/target/appfs.cramfs $IMAGE_DIR
			cp output/target/updater.cramfs $IMAGE_DIR
			cp output/target/usrdata.jffs2 $IMAGE_DIR
		fi
		echo "make all ..."
		;;
	-k)
		echo "compiling kernel ..."
		cd $SOURCE_DIR/kernel*

		if [ -f .config ];then
			make zImage -j8
		else
			make clean;
			make halley2_v20_oss_defconfig && make zImage -j8
		fi

		if [ $? -eq 0 ]; then
			cp arch/mips/boot/compressed/zImage $IMAGE_DIR
		fi
		;;
	-u)
		echo "compiling u-boot ..."
		cd $SOURCE_DIR/u-boot
		make distclean
		make halley2_v20_zImage_sfc_nor_config && make -j8

		if [ $? -eq 0 ]; then
			cp u-boot-with-spl.bin $IMAGE_DIR
		fi
		;;
	-m)
		echo "compiling mozart ..."
		cd $SOURCE_DIR/mozart

		if [ -f output/mozart/usr/include/mozart_config.h ];then
			make
		else
			make canna_v2.0_43438_cramfs_config && make
		fi

		if [ $? -eq 0 ]; then
			cp output/target/appfs.cramfs $IMAGE_DIR
			cp output/target/updater.cramfs $IMAGE_DIR
			cp output/target/usrdata.jffs2 $IMAGE_DIR
		fi
		;;
	-c)
		echo "make distclean ..."
		if [ -d $IMAGE_DIR ];then
			rm $IMAGE_DIR -rf
		fi

		cd $SOURCE_DIR/u-boot && make distclean
		cd $SOURCE_DIR/kernel* && make distclean
		cd $SOURCE_DIR/mozart && make distclean
		return $?
		;;
	\?)
		 echo "Invalid option : `basename $0` [-a] [-k] [-u] [-m] [-c]"
		;;
	esac
done
<file_sep>/network/route/src/firewall_link.c
/******************************************************************************
  文 件 名   : firewall_link.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 创建防火墙链表
  函数列表   :
              delete_firewall_node
              free_firewall_link
              insert_firewall_node
              print_firewall
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"


/*****************************************************************************
 函 数 名  : insert_firewall_node()
 功能描述  : 插入一条防火墙规则表
 输入参数  : head   链表头
             node   待插入节点
 返 回 值  : 链表头指针
 修改日期  : 2015年9月13日
*****************************************************************************/
FIRE_Wall *insert_firewall_node(FIRE_Wall *head, FIRE_Wall node)
{
	FIRE_Wall *pi = NULL;
	pi = (FIRE_Wall *)malloc(sizeof(FIRE_Wall));

	if(pi != NULL){ //成功申请到空间

		*pi = node;
		pi->next = NULL;

		if(head != NULL){

			FIRE_Wall *pb = NULL;
			pb = head;

			while((strcmp(pb->rule, pi->rule)) != 0 && (pb->next!= NULL))
				pb = pb->next;

			if(strcmp(pb->rule, pi->rule) != 0){
				pi->next = head;
			}
		}
		head = pi;
	}
	else{
		printf("Can not apply for a FIRE_Wall memeory space!\n");
	}

	return head;
}

/*****************************************************************************
 函 数 名  : delete_firewall_node()
 功能描述  : 查找ARP表,并删除链表中的指定节点
 输入参数  : head     链表头
             rule     从链表查找删除的规则
 返 回 值  : 链表头指针
 修改日期  : 2015年9月13日
*****************************************************************************/
FIRE_Wall *delete_firewall_node(FIRE_Wall *head, const char *rule)
{
	if(head == NULL) {
		printf("Link is not exist!\n");
	}
	else
	{
		FIRE_Wall *pb = NULL, *pf = NULL;
		pb = pf =head;

		while((strcmp(pb->rule, rule) !=0) && (pb->next != NULL))
		{
			pf = pb;
			pb = pb->next;
		}

		if(strcmp(pb->rule, rule) == 0)
		{
			if(pb == head) {//删除的节点是链表头部
				head = pb->next;
			}
			else if(pb->next == NULL) { //删除的节点在链表尾部
				pf->next = NULL;
			}
			else { //删除的节点在中间
				pf->next = pb->next;
			}

			free(pb);
		}
		else {
			printf("haved not set this firewall rule!\n");
		}
	}

	return head;
}

/*****************************************************************************
 函 数 名  : print_firewall()
 功能描述  : 打印整个防火墙规则表
 输入参数  : head   链表头
 返 回 值  : 链表头指针
 修改日期  : 2015年9月13日
*****************************************************************************/
void print_firewall(FIRE_Wall *head)
{

	if(head != NULL){

		FIRE_Wall *pb = head;

		while(pb != NULL)
		{
			printf("%s\n", pb->rule);
			pb = pb->next;
		}
	}
}

/*****************************************************************************
 函 数 名  : free_firewall_link()
 功能描述  : 释放整个防火墙规则表
 输入参数  : head   链表头
 返 回 值  : 链表头指针
 修改日期  : 2015年9月13日
*****************************************************************************/
FIRE_Wall *free_firewall_link(FIRE_Wall *head)
{
	if(head != NULL){
		FIRE_Wall *pb = head;

		//循环删除链表每个节点的方法：
		//1.判断 head 是否为空
		//2.让 pb 指向和 head 相同的节点
		//3.然后 让 head 指向下个节点
		//4.再把 pb 指向的节点释放掉
		//5.返回步骤 1
		while(head != NULL)
		{
			pb = head;
			head = pb->next;
			free(pb);
		}
	}

	return head;
}

<file_sep>/work/rootfs/sbin/wifi_connect.sh
#!/bin/sh

INTERFACE=wlan0
WPA_CONF=/etc/wpa_supplicant.conf

# wpa_supplicant config file
if [ ! -f "$WPA_CONF" ]; then
	echo "No configuration file"
	exit 0
fi

ifconfig $INTERFACE up
wpa_supplicant -Dnl80211 -i$INTERFACE -c$WPA_CONF -B
usleep 1300000
udhcpc -i $INTERFACE -q

exit 0

<file_sep>/sys_program/player/src/file.c
/* ************************************************************************
 *       Filename:  file.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 05時35分04秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include "common.h"
#include "process_lrc.h"
#include "file.h"

/**************************************************************************
*函数功能:读出文件内容
*参数：file_length    整型指针，此地址中保存文件字节数。
*      lrc_src  文件名字，从此文件中读取内容。
* 返回值:读出字符串的首地址
* 函数中测文件的大小并分配空间，再把文件内容读出到分配的空间中，返回此空间首地址
**************************************************************************/ 
char *read_src_file(ulint *file_length, char *lrc_src)
{
	FILE *fp = NULL;
	char *buf = NULL;	
	
	fp = fopen(lrc_src,"rb");//以只读方式打开一个二进制文件
	
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return NULL;
	}
	fseek(fp,0,SEEK_END);
	*file_length = ftell(fp); //获取文件的大小
	
	buf = (char *)malloc(*file_length+1); //
	
	if(buf == NULL)
	{
		printf("malloc() cannot apply for memory!\n");
		goto out;
	}
	
	bzero(buf, *file_length+1);
	
	rewind(fp); //
	fread(buf,*file_length,1,fp);
	
	out:
	fclose(fp);
	return buf;
}
#if 1
char *get_musiclist(char ***plist, int *plines)
{
	FILE *fp =NULL;
	char *buf = NULL;	
	ulint list_length = 0;
	//uint lines = 0;
	int part = 0;
	system("ls ./music | grep .mp3 >./music/musiclist");
	
	fp = fopen("music/musiclist","rb");
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return NULL;
	}
	buf = read_src_file(&list_length,"music/musiclist");	
	*plines = check_lines(list_length, buf);
	
	*plist = (char **)malloc((*plines  + 1) * sizeof(char **));  //动态分配空间存储每行的首地址
	
	if(*plist == NULL)
	{
		goto out;
		return NULL; 
	}

	bzero(*plist, *plines+1);
	
	part = src_segment(buf, *plist, "\r\n");	              //按行分割
	plist[*plines ] = NULL; 
	
#if 0 //
   int i, len;
	for(i=0;i<part;i++)
	{
		len = strlen(*(*(plist) + i));
		*(*(*(plist) + i) + len -4) = '\0';
		//printf("%s\n",plist[i]);
	}	
#endif	
	out:
	fclose(fp);
	return buf;
}
#else
char **get_musiclist()
{
	FILE *fp =NULL;
	char *buf = NULL, **plist = NULL;	
	ulint list_length = 0;
	uint lines = 0;
	int part = 0;
	system("ls ./music | grep .mp3 >./music/musiclist");
	
	fp = fopen("music/musiclist","rb");
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	buf = read_src_file(&list_length,"music/musiclist");	
	lines = check_lines(list_length, buf);
	
	plist = (char **)malloc((lines + 1) * sizeof(char **));  //动态分配空间存储每行的首地址
	
	if(plist == NULL) return NULL; 
	
	part = src_segment(buf, plist, "\r\n");	         //按行分割
	plist[lines] = NULL; 
	
#if 1
   int i, len;
	for(i=0;i<part-1;i++)
	{
		len = strlen(*(*(plist) + i));
		//printf("len =%d\n",len);
		*(*(*(plist) + i) + len -1) = '\0';
		//printf("%s\n",plist[i]);
	}	
#endif
	fclose(fp);
	return plist;
}
#endif
int check_lines(ulint file_length, char *src)
{
	uint lines = 0;
	ulint i = 0;
	char *p = NULL;
	
	p = src;
	
	#if 1
	for(i = 0;i < file_length;i++)
	{
		if(p[i]=='\n')  lines++;
	}
	#elif 0 //这种方法不行，因为strchr函数和strstr函数遇到 '\0' 就返回
	while(p != NULL)
	{
		p = strchr(p,'\n');
		lines++;
	}
	#endif
	return lines;
}

int get_longestline(int lines, char *plines[])
{
	int longestline = 0, temp = 0, i = 0;
	
	for(i=0;i<lines;i++)
	{
		temp = strlen(plines[i]);
		
		if(temp > longestline) longestline = i;
	}
	return longestline;
}

int get_chrnumber(char *pbuf, int len)
{
	int i = 0,count = 0;
	
	for(i=0;i<len;i++)
	{
		if(pbuf[i] > 0 && pbuf[i] <127) count++;
	}
	return count;
}
int get_longestlength(LRC *lrc_head)
{
	int longest = 0, temp = 0, chrnum = 0;
	
	if(lrc_head != NULL)
	{
		LRC *pb = NULL, *pf = NULL;
		pb = lrc_head;
		
		while(pb != NULL)
		{
			temp = strlen(pb->src);
			if(temp > longest) 
			{
				pf = pb;
				longest = temp;
			}		
			//printf("len=%d  %s\n",temp,pb->src);
			pb = pb->next;
		}
		
		temp = strlen(pf->src);
		chrnum = get_chrnumber(pf->src,temp);
		longest += chrnum/2;
	}

	return longest;
}

int get_showoffset(char *pbuf, int longest)
{
	int len = 0, offset = 0;
	int count = 0;
	
	len = strlen(pbuf);
	count = get_chrnumber(pbuf, len);
	len += count/2;
	
	offset = (longest - len)/3;
	//printf("longest=%d len=%d offset=%d  %s\n",longest,len,offset,pbuf);
	if(offset < 0) offset = 0; //一定要加此判断
	return offset;
}
char get_songname(char *desr, char *src)
{
	char *p = NULL;
	char buf[256];

	bzero(buf,sizeof(buf));
	
	if((p = strstr(src, ".mp3")) != NULL)
	{
		sscanf(src,"%[^.mp3]",buf);
		strcat(buf,".mp3");
		strcpy(desr,buf);
		return 0;
	}
	return -1;
}

char get_lrcname(char *src)
{
	char *p = NULL;

	if((p = strstr(src, ".mp3")) != NULL)
	{
		*p = '\0';
		strcat(src,".lrc");
		return 0;
	}	

	return -1;
}

char *transfer_space(char src[])
{
	int i = 0, j = 0, len = 0;
	int space = 0;
	char *pbuf = NULL;
	
	len = strlen(src);
	
	while(src[i])
	{
		if(src[i] == ' ')
		{
			space++;
		}
		i++;
	}

	pbuf = (char *)malloc(sizeof(char) * (len + space + 2));

	if(pbuf == NULL) 
	{
		printf("transfer_space >> malloc failed\n");
		return NULL;
	}
	
	i = 0;
	while(src[i])
	{
		if(src[i] == ' ')
		{
			pbuf[j] = '\\';
			j++;
		}

		pbuf[j] = src[i];
		j++;
		i++;
	}	
	pbuf[j] = '\0';
	return pbuf;
}

void delete_dot(char *plist[])
{
	int i = 0,len = 0;
	
	for(i=0;plist[i] != NULL;i++)
	{
		len = strlen(plist[i]);
		plist[i][len-1] = '\0';
	}
}
void recover_dot(char *plist[])
{
	int i = 0,len = 0;
	
	for(i=0;plist[i] != NULL;i++)
	{
		len = strlen(plist[i]);
		plist[i][len] = '.';
	}
}

void recover_line_dot(char *plist[],int line_num)
{
	int len = 0;
	
	len = strlen(plist[line_num]);
	plist[line_num][len] = '.';

}

<file_sep>/work/test/socket/socket_client.c
/*************************************************************************
	> File Name: socket_client.c
	> Author: 
	> Mail: 
	> Created Time: Tue 17 May 2016 11:34:19 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

int main(int argc, char ** argv) {
    int sockfd, n;
    int my;
    char buf[100];
    struct sockaddr_in servaddr;

    if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("create socket error\n");
        exit(1);

    }

    bzero(&servaddr, sizeof(struct sockaddr_in));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(atoi(argv[2]));

    if(inet_pton(AF_INET, argv[1], &servaddr.sin_addr) < 0) {
        printf("inet_pton error\n");
        exit(1);

    }

    if((my = connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) < 0) {
        printf("connect error\n");
        exit(1);

    }

    struct sockaddr_in serv, guest;
    int serv_len = sizeof(serv);
    int guest_len = sizeof(guest);
    char serv_ip[20], guest_ip[20];

    getsockname(sockfd, (struct sockaddr *)&guest, &guest_len);
    getpeername(sockfd, (struct sockaddr *)&serv, &serv_len);

    inet_ntop(AF_INET, &guest.sin_addr, guest_ip, sizeof(guest_ip));
    inet_ntop(AF_INET, &serv.sin_addr, serv_ip, sizeof(serv_ip));

    printf("host %s:%d, guest %s:%d\n", serv_ip, ntohs(serv.sin_port), guest_ip, ntohs(guest.sin_port));

    n = read(sockfd, buf, 100);
    buf[n] = '\0';

    printf("%s\n", buf);
    getchar();
    close(sockfd);
    exit(0);
}
<file_sep>/sys_program/4th_day/homework/mplayer/interface.h
/* ************************************************************************
 *       Filename:  interface.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 20时42分29秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __INTERFACE_H__
#define __INTERFACE_H__

#include <gtk/gtk.h>

typedef struct _Window
{
	GtkWidget *main_window;
	GtkWidget *table;
	GtkWidget *image;
	GtkWidget *button_previous;
	GtkWidget *button_next;
	GtkWidget *button_pause;
	//GtkWidget *progress;
}WINDOW;

extern int fd;
extern int playing;


void show_window(gpointer data);

#endif
<file_sep>/sys_program/player/src/mplayer_ui.c
/* ************************************************************************
 *       Filename:  gtk_button.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 10时14分55秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include "common.h"
#include "file.h"
#include "mplayer_pthread.h"
#include "gtk_callback.h"
#include "mplayer_ui.h"


//MPLAYER mplayer; 
SunGtkCList *musiclist = NULL;  
  
static void show_boot_animation(MPLAYER *pm)
{
	int i;
	char ch[2] = "a"; 
	char path[] = "./image/jpg/";	
	char jpg[] = ".JPG";
	char buf[64];

	for(i=0; i<18;i++)
	{
		bzero(buf, sizeof(buf));
		ch[0] += i;
		strcat(buf, path);
		strcat(buf, ch);
		strcat(buf, jpg);

		printf("jpg path = %s####\n",buf);
		sungtk_background_set_picture(pm->ui.main_window,buf,800, 480);
		gtk_widget_show_all(pm->ui.main_window);
		ch[0] = 'a';
		sleep(1);
	}
}

static int hbox_left_init(MPLAYER *pm, GtkBuilder *builder)
{
	pm->ui.hbox_left.bmusic_list     = GTK_BUTTON(gtk_builder_get_object(builder, "bmusic_list"));
	pm->ui.hbox_left.bmusic_collect  = GTK_BUTTON(gtk_builder_get_object(builder, "bmusic_collect"));
	pm->ui.hbox_left.bmusic_recently = GTK_BUTTON(gtk_builder_get_object(builder, "bmusic_recently"));

	gtk_widget_set_sensitive(GTK_WIDGET(pm->ui.hbox_left.bmusic_list), FALSE);
	g_signal_connect(pm->ui.hbox_left.bmusic_list,    "clicked", G_CALLBACK(musiclist_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_left.bmusic_collect, "clicked", G_CALLBACK(musiclist_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_left.bmusic_recently,"clicked", G_CALLBACK(musiclist_buttons_callback), pm);
	
	pm->ui.hbox_left.eventbox_musiclist  = (GtkEventBox *)(gtk_builder_get_object(builder, "eventbox_musiclist"));
	gtk_event_box_set_visible_window(pm->ui.hbox_left.eventbox_musiclist, FALSE); //???

	//
	pm->ui.hbox_left.button_search= GTK_BUTTON(gtk_builder_get_object(builder, "button_search"));
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_left.button_search), "./image/style/find.png",20,20);
	g_signal_connect(GTK_WIDGET(pm->ui.hbox_left.button_search), "clicked", G_CALLBACK(search_entry_callback), pm);
	
	pm->ui.hbox_left.table_search = GTK_TABLE(gtk_builder_get_object(builder, "table_search"));
	pm->ui.hbox_left.entry_search = GTK_ENTRY(gtk_entry_new());                         //б?		
	gtk_entry_set_max_length(GTK_ENTRY(pm->ui.hbox_left.entry_search), 30); //б????	
	gtk_table_attach_defaults(pm->ui.hbox_left.table_search,GTK_WIDGET(pm->ui.hbox_left.entry_search),0,1,0,1); //
	g_signal_connect(GTK_WIDGET(pm->ui.hbox_left.entry_search), "activate",G_CALLBACK(search_entry_callback), pm);
	
	pm->ui.hbox_left.table_musiclist = GTK_TABLE(gtk_builder_get_object(builder, "table_musiclist"));

	//б
	musiclist = sungtk_clist_new();  
    sungtk_clist_set_row_height(musiclist, 25);  
    sungtk_clist_set_col_width(musiclist, 200);  
    sungtk_clist_set_text_size(musiclist, 12);  
    sungtk_clist_set_select_row_signal(musiclist, "button-release-event", callback_list_release);  
    gtk_table_attach_defaults(pm->ui.hbox_left.table_musiclist, musiclist->fixed, 1, 4, 1, 5);  
      
    //sungtk_clist_append(musiclist, "aaaaaaaaaaa");  
    //sungtk_clist_append(musiclist, "bbbbbbbbbb");  
      
    //sungtk_clist_set_row_color(musiclist, 0, "red");

	return 0;
}

static int hbox_right_init(MPLAYER *pm, GtkBuilder *builder)
{
#if 1 
	pm->ui.hbox_right.button_pause   = GTK_BUTTON(gtk_builder_get_object(builder, "button_pause"));
	pm->ui.hbox_right.button_back    = GTK_BUTTON(gtk_builder_get_object(builder, "button_back"));
	pm->ui.hbox_right.button_next    = GTK_BUTTON(gtk_builder_get_object(builder, "button_next"));
	pm->ui.hbox_right.button_backward= GTK_BUTTON(gtk_builder_get_object(builder, "button_backward"));
	pm->ui.hbox_right.button_forward = GTK_BUTTON(gtk_builder_get_object(builder, "button_forward"));
	pm->ui.hbox_right.button_volume  = GTK_BUTTON(gtk_builder_get_object(builder, "button_volume"));
	pm->ui.hbox_right.button_playmode= GTK_BUTTON(gtk_builder_get_object(builder, "button_playmode"));
		
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_back),     "./image/style/back.png",70,70);	
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_pause),    "./image/style/pause.png",70,70);
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_next),     "./image/style/next.png",70,70);	
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_backward), "./image/style/backward.png",60,60);
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_forward),  "./image/style/forward.png",60,60);
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_volume),   "./image/style/beam.png",50,50);
	sungtk_button_inset_image(GTK_WIDGET(pm->ui.hbox_right.button_playmode), "./image/style/playmode_list_loop.png",20,20);
	
	g_signal_connect(pm->ui.hbox_right.button_pause,    "clicked", G_CALLBACK(music_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_right.button_back,     "clicked", G_CALLBACK(music_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_right.button_next,     "clicked", G_CALLBACK(music_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_right.button_backward, "clicked", G_CALLBACK(music_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_right.button_forward,  "clicked", G_CALLBACK(music_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_right.button_volume,   "clicked", G_CALLBACK(music_buttons_callback), pm);
	g_signal_connect(pm->ui.hbox_right.button_playmode, "clicked", G_CALLBACK(playmode_button_callback), pm);
#endif	

#if 1 //label
	pm->ui.hbox_right.label_title1 = GTK_LABEL(gtk_builder_get_object(builder, "label_title1"));
	pm->ui.hbox_right.label_title2 = GTK_LABEL(gtk_builder_get_object(builder, "label_title2"));
	pm->ui.hbox_right.label_title3 = GTK_LABEL(gtk_builder_get_object(builder, "label_title3"));
	
	pm->ui.hbox_right.label_lrc1 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc1"));
	pm->ui.hbox_right.label_lrc2 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc2"));
	pm->ui.hbox_right.label_lrc3 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc3"));
	pm->ui.hbox_right.label_lrc4 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc4"));
	pm->ui.hbox_right.label_lrc5 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc5"));
	pm->ui.hbox_right.label_lrc6 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc6"));
	pm->ui.hbox_right.label_lrc7 = GTK_LABEL(gtk_builder_get_object(builder, "label_lrc7"));	

	sungtk_widget_set_font_color(GTK_WIDGET(pm->ui.hbox_right.label_lrc2),"yellow", FALSE);
	//char pbuf[] = "heheheh";
	gtk_label_set_text(pm->ui.hbox_right.label_title1, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_title2, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_title3, "");
	
	gtk_label_set_text(pm->ui.hbox_right.label_lrc1, "");
	gtk_label_set_text(pm->ui.hbox_right.label_lrc2, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_lrc3, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_lrc4, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_lrc5, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_lrc6, "");	
	gtk_label_set_text(pm->ui.hbox_right.label_lrc7, "");	

	//sungtk_widget_set_font_color(GTK_WIDGET(pm->ui.hbox_right.label_lrc4),"MedSpringGreen", FALSE);
		
	pm->ui.hbox_right.label_cur_time = GTK_LABEL(gtk_builder_get_object(builder, "label_cur_time"));
	pm->ui.hbox_right.label_end_time = GTK_LABEL(gtk_builder_get_object(builder, "label_end_time"));	
#endif	

	pm->ui.hbox_right.progress_bar    = GTK_PROGRESS_BAR(gtk_builder_get_object(builder, "progress_bar"));
	pm->ui.hbox_right.eventbox_bar    = (GtkEventBox *)(gtk_builder_get_object(builder, "eventbox_bar"));
	pm->ui.hbox_right.eventbox_volume = (GtkEventBox *)(gtk_builder_get_object(builder, "eventbox_volume"));
	gtk_event_box_set_visible_window(pm->ui.hbox_right.eventbox_bar,   FALSE);
	gtk_event_box_set_visible_window(pm->ui.hbox_right.eventbox_volume,FALSE);

	//???
	gtk_widget_add_events(GTK_WIDGET(pm->ui.hbox_right.eventbox_bar), GDK_BUTTON_MOTION_MASK);
	// "motion-notify-event"  motion_event_callback ????
	g_signal_connect(GTK_WIDGET(pm->ui.hbox_right.eventbox_bar), "motion-notify-event", G_CALLBACK(motion_event_callback), pm);


	pm->ui.hbox_right.image_logo = GTK_IMAGE(gtk_builder_get_object(builder, "image_logo"));
	sungtk_image_load_picture(GTK_WIDGET(pm->ui.hbox_right.image_logo), "./image/style/picture.png", 140, 140);	
	
	return 0;
}

void window_init(MPLAYER *pm)
{
	//创建GtkBuilder对象，GtkBuilder在<gtk/gtk.h>声明
	//读取Mplayer.glade文件的信息，保存在builder中 	
	GtkBuilder *builder = gtk_builder_new(); //创建GtkBuilder对象，GtkBuilder在<gtk/gtk.h>声明
	if(!gtk_builder_add_from_file(builder,"Mplayer.glade", NULL)) //读取Mplayer.glade文件的信息，保存在builder中   
	{  
		printf("connot Mplayer.glade file!");  
	} 
	 

	//获取窗口指针，注意"main_window"要和glade里面的标签名词匹配
	pm->ui.main_window = GTK_WIDGET(gtk_builder_get_object(builder,"main_window"));
	
 	gtk_window_set_title(GTK_WINDOW(pm->ui.main_window), "Mplayer");	            // 设置窗口标题
	gtk_window_set_position(GTK_WINDOW(pm->ui.main_window), GTK_WIN_POS_CENTER);    // 设置窗口在显示器中的位置为居中
	gtk_widget_set_size_request(pm->ui.main_window, 800, 480);		 	             // 设置窗口的最小大小
	gtk_window_set_resizable(GTK_WINDOW(pm->ui.main_window), FALSE); 	            // 固定窗口的大小
	//gtk_window_set_decorated(GTK_WINDOW(pm->ui.main_window), FALSE); // 设置无边框
	g_signal_connect(pm->ui.main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL); 
	

	//show_boot_animation(pm);
	sungtk_background_set_picture(pm->ui.main_window,"./image/background/11.jpg",800, 480);
	
	hbox_left_init(pm, builder);  //
	hbox_right_init(pm, builder); //
	
	gtk_widget_show_all(pm->ui.main_window);
}

void mplayer_ui_show(int argc, char *argv[], MPLAYER *pm)
{
	
	pm->playflag  = stop; //暂停
	pm->soundflag = beam; //播音
	
	gtk_init(&argc, &argv);
	window_init(pm);
	gtk_main();
}
<file_sep>/work/test/cim_test-zmm220/yuv2jpg.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <jpeglib.h>
#include <jerror.h>

#define uint8 unsigned char

//write_JPEG_file (char * filename, int quality,int image_width,int image_height)
void write_JPEG_file (char * filename, int quality,int image_width,int image_height, unsigned char **yuv_data)
{

	struct jpeg_compress_struct cinfo;

	struct jpeg_error_mgr jerr;

	FILE * outfile;     /* target file */
//	JSAMPROW row_pointer[1];   /* pointer to JSAMPLE row[s] */
//	int row_stride;     /* physical row width in image buffer */
  	JSAMPIMAGE   buffer;

	int band,i,buf_width[3],buf_height[3];
	int mem_size,max_line, counter;
	uint8 *pSrc, *pDst;
	cinfo.err = jpeg_std_error(&jerr);

	jpeg_create_compress(&cinfo);

	if ((outfile = fopen(filename, "wb")) == NULL) {
	fprintf(stderr, "can't open %s\n", filename);
	exit(1);
	}
	jpeg_stdio_dest(&cinfo, outfile);

	cinfo.image_width = image_width;   /* image width and height, in pixels */
	cinfo.image_height = image_height;
	cinfo.input_components = 3;     /* # of color components per pixel */
	cinfo.in_color_space = JCS_RGB;   /* colorspace of input image */

	jpeg_set_defaults(&cinfo);

	jpeg_set_quality(&cinfo, quality, TRUE );

	//////////////////////////////
	cinfo.raw_data_in = TRUE;
	cinfo.jpeg_color_space = JCS_YCbCr;
	cinfo.comp_info[0].h_samp_factor = 2;
	cinfo.comp_info[0].v_samp_factor = 1;
	/////////////////////////

	jpeg_start_compress(&cinfo, TRUE);

	buffer = (JSAMPIMAGE) (*cinfo.mem->alloc_small) ((j_common_ptr) &cinfo,
			JPOOL_IMAGE, 3*sizeof(JSAMPARRAY));   
	for(band=0; band<3; band++)
	{
  		buf_width[band] = cinfo.comp_info[band].width_in_blocks * DCTSIZE;
		buf_height[band] = cinfo.comp_info[band].v_samp_factor * DCTSIZE;
		buffer[band] = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo,
			JPOOL_IMAGE, buf_width[band], buf_height[band]);
	}   
    
	max_line = cinfo.max_v_samp_factor*DCTSIZE;   
	for(counter=0; cinfo.next_scanline < cinfo.image_height; counter++)
	{     
		//buffer image copy.
		for(band=0; band<3; band++)
		{
			mem_size = buf_width[band];
			pDst = (uint8 *) buffer[band][0];
			//    	pSrc = (uint8 *) yuv.data[band] + //yuv.data[band]分别表示YUV起始地址
			pSrc = (uint8 *) yuv_data[band] + //yuv.data[band]分别表示YUV起始地址
				counter*buf_height[band] * buf_width[band];
    
			for(i=0; i<buf_height[band]; i++)
			{
				memcpy(pDst, pSrc, mem_size);
				pSrc += buf_width[band];
				pDst += buf_width[band];
			}
		}
		jpeg_write_raw_data(&cinfo, buffer, max_line);
	}

	jpeg_finish_compress(&cinfo);

	fclose(outfile);

	jpeg_destroy_compress(&cinfo);

}


//int main()
//{
//	return 0;
//}
<file_sep>/c/practice/1st_week/math/mymath.c
/* ************************************************************************
 *       Filename:  sum.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月16日 星期四 02時11分45秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <string.h>
int sum(int a,int b)
{
	return a+b;
}

int abs(int n)
{
	return n>0?n:~n;
}

void Bubbing_Methed(char *p)
{
	int length = 0;
	length = strlen(p);
	printf("%d\n",length);

}
<file_sep>/sys_program/4th_day/homework/chat/chat.c
/* ************************************************************************
 *       Filename:  chat.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月18日 17时47分59秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/msg.h>
#include <unistd.h>
#include <fcntl.h>

#if defined   (P)
char name[] = "Peter";
#elif defined (L)
char name[] = "Lucy";
#elif defined (B)
char name[] = "Bob";
#endif

typedef struct _msg
{
	long type;
	char msg[256];
}MSG;

int main(int argc, char *argv[])
{
	key_t key;
	pid_t pid;
	MSG snd,rcv;
	int id;

	key = ftok("./",23);                //获取key 值
	id = msgget(key, IPC_CREAT | 0666); //打开或创建消息队列
	if(id == -1)  //出错退出
	{
		perror("");
		exit(-1);
	}

	printf("Hi, I am %s\n",name);

	pid = fork(); //创建子进程
	if(pid < 0)   //出错退出
	{
		perror("");
		exit(-1);
	}
	else if(pid == 0) //子进程
	{
		int len = 0, i;
		char buf[256] = "";

		while(1)
		{
			printf("%s: ",name);
			fflush(stdout);

			fgets(buf,sizeof(buf),stdin);
			len = strlen(buf);

			if(len > 3)
			{
				char msg[256] = "";
				buf[len-1] = '\0';

				for(i=0;i < len-1;i++)
				{
					if(buf[i] == 'P' || buf[i] == 'L' || buf[i] == 'B' && buf[i+1] == ' ')
					{
						if(buf[i] == name[0]) //判断是不是给自己发信息
						{
							break; //给自己发信息直接退出，不写入消息队列
						}
						snd.type = buf[i];
						buf[i] = ':';

						strcat(msg,name);
						strcat(msg, buf+i);
						strcpy(snd.msg, msg);

						msgsnd(id, &snd, sizeof(snd) - sizeof(long) , 0);
						break;
					}
				}
			}
		}
	}
	else //父进程
	{

		while(1)
		{
			bzero(rcv.msg, sizeof(rcv.msg));

		#if defined   (P)
			msgrcv(id, &rcv,sizeof(rcv) - sizeof(long), (long)('P'), 0);
		#elif defined (L)
			msgrcv(id, &rcv,sizeof(rcv) - sizeof(long), (long)('L'), 0);
		#elif defined (B)
			msgrcv(id, &rcv,sizeof(rcv) - sizeof(long), (long)('B'), 0);
		#endif
			printf("\r%s\n",rcv.msg);
			printf("%s: ",name);
			fflush(stdout);
		}
	}
	//printf("name = %s\n",name);
	return 0;
}
<file_sep>/work/debug/ingenic/wiegand/wiegand_in.c
/*
 * Copyright (C) 2012 Ingenic Semiconductor Co., Ltd.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 */
#include <linux/errno.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/miscdevice.h>
#include <linux/spinlock.h>
#include <linux/wakelock.h>
#include <linux/clk.h>
#include <linux/syscalls.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/gpio.h>
#include <linux/spinlock.h>
#include <linux/poll.h>
#include <linux/hrtimer.h>
#include <linux/wait.h>
#include <linux/time.h>
#include <linux/kernel.h>
#include <linux/wiegand.h>
#include <linux/module.h>

#define WIEGANDINDRV_LIB_VERSION		"1.0.1 ZLM60"__DATE__	/* DRV LIB VERSION */

#define DEF_PULSE_WIDTH		100 //us
#define DEF_PULSE_INTERVAL	1000 //us
#define DEF_DATA_LENGTH		26 //bit
#define DEVIATION		100 //us

struct wiegand_in_dev {
	struct device		*dev;
	struct miscdevice	mdev;
	unsigned int		data0_pin;
	unsigned int		data1_pin;
	unsigned int		current_data[2];
	unsigned int		wiegand_in_data[2];
	int			data_length;
	int			recvd_length;
	int			pulse_width;
	int			pulse_intval;
	int			error;
	spinlock_t		lock;
	int			use_count;
	struct hrtimer		timer;
	wait_queue_head_t	wq;
	struct timeval 		latest;
	struct timeval 		now;
};

static void wiegand_in_data_reset(struct wiegand_in_dev *wiegand_in)
{
	wiegand_in->recvd_length = -1;
	wiegand_in->current_data[0] = 0;
	wiegand_in->current_data[1] = 0;
	wiegand_in->wiegand_in_data[0] = 0;
	wiegand_in->wiegand_in_data[1] = 0;
	wiegand_in->error = 0;
}

static int wiegand_in_open(struct inode *inode, struct file *filp)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);

	spin_lock(&wiegand_in->lock);
	if (wiegand_in->use_count > 0) {
		spin_unlock(&wiegand_in->lock);
		return -EBUSY;
	}
	wiegand_in->use_count++;
	spin_unlock(&wiegand_in->lock);

	wiegand_in_data_reset(wiegand_in);
	enable_irq(gpio_to_irq(wiegand_in->data0_pin));
	enable_irq(gpio_to_irq(wiegand_in->data1_pin));
	return 0;
}

static int wiegand_in_release(struct inode *inode, struct file *filp)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);

	disable_irq(gpio_to_irq(wiegand_in->data0_pin));
	disable_irq(gpio_to_irq(wiegand_in->data1_pin));
	spin_lock(&wiegand_in->lock);
	wiegand_in->use_count--;
	spin_unlock(&wiegand_in->lock);

	return 0;
}

static ssize_t wiegand_in_read(struct file *filp, char *buf, size_t size, loff_t *l)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);

	if (filp->f_flags & O_NONBLOCK)
		return -EAGAIN;

	if (wait_event_interruptible(wiegand_in->wq,
		(wiegand_in->wiegand_in_data[0] > 0) || (wiegand_in->error)))
		return -ERESTARTSYS;

	if(wiegand_in->wiegand_in_data[0] > 0) {
		if(copy_to_user(buf, wiegand_in->wiegand_in_data,
			sizeof(wiegand_in->wiegand_in_data)))
			return -EFAULT;
		wiegand_in->wiegand_in_data[0] = 0;
		wiegand_in->wiegand_in_data[1] = 0;

		return sizeof(wiegand_in->wiegand_in_data);
	}
	wiegand_in->error = 0;

	return 0;
}

static unsigned int wiegand_in_poll(struct file *filp, poll_table *wait)
{
	unsigned int mask = 0;

	struct miscdevice *dev = filp->private_data;
	struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
	poll_wait(filp, &wiegand_in->wq, wait);

	if( wiegand_in->wiegand_in_data[0] )
		mask |= POLLIN | POLLRDNORM;

	return mask;
}

static long wiegand_in_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	struct miscdevice *dev = filp->private_data;
	struct wiegand_in_dev *wiegand_in = container_of(dev, struct wiegand_in_dev, mdev);
	int cs;

	switch (cmd) {
	case WIEGAND_PULSE_WIDTH:
	{
		if(get_user(cs, (unsigned int *)arg))
			return -EINVAL;
		wiegand_in->pulse_width = cs;
		break;
	}

	case WIEGAND_PULSE_INTERVAL:
	{
		if(get_user(cs, (unsigned int *)arg))
			return -EINVAL;
		wiegand_in->pulse_intval = cs;
		break;
	}

	case WIEGAND_FORMAT:
	{
		if(get_user(cs, (unsigned int *)arg))
			return -EINVAL;
		wiegand_in->data_length = cs;
		break;
	}

	case WIEGAND_READ:
	{
		if(wiegand_in->wiegand_in_data[0]) {
			if( copy_to_user((unsigned int *)arg,
				wiegand_in->wiegand_in_data, sizeof(wiegand_in->wiegand_in_data)))
				return -EFAULT;
			wiegand_in->wiegand_in_data[0] = 0;
			wiegand_in->wiegand_in_data[1] = 0;
		}
		break;
	}

	case WIEGAND_STATUS:
	{
		if(wiegand_in->wiegand_in_data[0] == 0)
			cs = 0;
		else
			cs = 1;
		if(put_user(cs, (unsigned int *)arg))
			return -EINVAL;
		break;
	}

	default:
		return -EINVAL;
	}

	return 0;
}

static struct file_operations wiegand_in_misc_fops = {
	.open		= wiegand_in_open,
	.release	= wiegand_in_release,
	.read		= wiegand_in_read,
	.unlocked_ioctl	= wiegand_in_ioctl,
	.poll    	= wiegand_in_poll,
};

static void wiegand_in_check_data(struct wiegand_in_dev *wiegand_in)
{
	if (wiegand_in->recvd_length == wiegand_in->data_length - 1) {
		memcpy(wiegand_in->wiegand_in_data, wiegand_in->current_data, sizeof(wiegand_in->current_data));
		wiegand_in->recvd_length = -1;
		wiegand_in->current_data[0] = 0;
		wiegand_in->current_data[1] = 0;
		wake_up_interruptible(&wiegand_in->wq);
	} else {
		printk("recvd data error: received length = %d, required length = %d\n",
			wiegand_in->recvd_length, wiegand_in->data_length);
		wiegand_in_data_reset(wiegand_in);
		wiegand_in->error = 1;
		wake_up_interruptible(&wiegand_in->wq);
	}
}

static enum hrtimer_restart wiegand_in_timeout(struct hrtimer * timer)
{
	struct wiegand_in_dev *wiegand_in = container_of(timer, struct wiegand_in_dev, timer);
	wiegand_in_check_data(wiegand_in);
	return HRTIMER_NORESTART;
}

static void wiegand_in_reset_timer(struct wiegand_in_dev *wiegand_in)
{
	int us = (wiegand_in->pulse_width + wiegand_in->pulse_intval)
		* wiegand_in->data_length;
	int s = us / 1000000;
	ktime_t time = ktime_set(s, (us % 1000000) * 1000);
	hrtimer_start(&wiegand_in->timer, time, HRTIMER_MODE_REL);
}

static int wiegand_in_check_irq(struct wiegand_in_dev *wiegand_in)
{
	int diff;

	if (wiegand_in->recvd_length < 0) {
		do_gettimeofday(&wiegand_in->latest);
		return 0;
	}

	/* Check how much time we have used already */
	do_gettimeofday(&wiegand_in->now);
	diff = wiegand_in->now.tv_usec - wiegand_in->latest.tv_usec;

	/* check fake interrupt */
	if (diff < wiegand_in->pulse_width )//+ wiegand_in->pulse_intval - DEVIATION)
		return -1;
	/*
	 * if intarval is greater than DEVIATION,
	 * then cheet it as beginning of another scan
	 * and discard current data
	 */
	else if (diff > wiegand_in->pulse_width + wiegand_in->pulse_intval
					+ ((wiegand_in->pulse_width + wiegand_in->pulse_intval)<<1)) {
		hrtimer_cancel(&wiegand_in->timer);
		wiegand_in_data_reset(wiegand_in);
		return -1;
	}

	wiegand_in->latest.tv_sec = wiegand_in->now.tv_sec;
	wiegand_in->latest.tv_usec = wiegand_in->now.tv_usec;
	return 0;
}

static irqreturn_t wiegand_in_interrupt(int irq, void *dev_id)
{
	struct wiegand_in_dev *wiegand_in = (struct wiegand_in_dev *)dev_id;

	if (wiegand_in_check_irq(wiegand_in))
		return IRQ_HANDLED;

	if (wiegand_in->recvd_length < 0)
		wiegand_in_reset_timer(wiegand_in);

	wiegand_in->recvd_length++;
	wiegand_in->current_data[1] <<= 1;
	wiegand_in->current_data[1] |= ((wiegand_in->current_data[0] >> 31) & 0x01);
	wiegand_in->current_data[0] <<= 1;
	if (irq == gpio_to_irq(wiegand_in->data1_pin))
		wiegand_in->current_data[0] |= 1;
	return IRQ_HANDLED;
}

static int wiegand_in_probe(struct platform_device *pdev)
{
	int ret;
	struct wiegand_in_dev *wiegand_in;
	struct wiegand_platform_data *pdata;

	printk(" WIEGAND IN VERSION =  %s  \n",WIEGANDINDRV_LIB_VERSION);

	pdata = dev_get_platdata(&pdev->dev);
	if (!pdata) {
		dev_err(&pdev->dev, "Failed to get platform_data %s %d.\n", __FUNCTION__, __LINE__);
		return -ENXIO;
	}

	wiegand_in = kzalloc(sizeof(struct wiegand_in_dev), GFP_KERNEL);
	if (!wiegand_in) {
		printk("%s: alloc mem failed.\n", __FUNCTION__);
		ret = -ENOMEM;
	}

#if 1
	wiegand_in->data0_pin = pdata->data1_pin;
	wiegand_in->data1_pin = pdata->data0_pin;
#else
	wiegand_in->data0_pin = pdata->data0_pin;
	wiegand_in->data1_pin = pdata->data1_pin;
#endif

	if (gpio_is_valid(wiegand_in->data0_pin)) {
		ret = gpio_request(wiegand_in->data0_pin, "WIEGAND_IN_DATA0");
		gpio_direction_input(wiegand_in->data0_pin);
		if (ret < 0) {
			printk("ERROR: request wiegand_in_data0 gpio failed.\n");
			goto err_gpio_request0;
		}
	}
	else {
		printk("ERROR: wiegand_in_data0 gpio is invalid.\n");
		goto err_gpio_request0;
	}
	if (gpio_is_valid(wiegand_in->data1_pin)) {
		ret = gpio_request(wiegand_in->data1_pin, "WIEGAND_IN_DATA1");
		gpio_direction_input(wiegand_in->data1_pin);
		if (ret < 0) {
			printk("ERROR: request wiegand_in_data1 gpio failed.\n");
			goto err_gpio_request1;
		}
	}
	else {
		printk("ERROR: wiegand_in_data1 gpio is invalid.\n");
		goto err_gpio_request1;
	}

	ret = request_irq(gpio_to_irq(wiegand_in->data0_pin),
		wiegand_in_interrupt,
		IRQF_DISABLED |
		IRQF_TRIGGER_FALLING,
		"wiegand_in_data0", wiegand_in);
	if (ret < 0) {
		printk("ERROR: request wiegand_in_data0 irq failed.\n");
		goto err_request_irq0;
	}
	disable_irq(gpio_to_irq(wiegand_in->data0_pin));
	ret = request_irq(gpio_to_irq(wiegand_in->data1_pin),
		wiegand_in_interrupt,
		IRQF_DISABLED |
		IRQF_TRIGGER_FALLING,
		"wiegand_in_data1", wiegand_in);
	if (ret < 0) {
		printk("ERROR: request wiegand_in_data1 irq failed.\n");
		goto err_request_irq1;
	}
	disable_irq(gpio_to_irq(wiegand_in->data1_pin));

	wiegand_in->dev = &pdev->dev;
	wiegand_in->mdev.minor = MISC_DYNAMIC_MINOR;
	wiegand_in->mdev.name =  "wiegand_in";
	wiegand_in->mdev.fops = &wiegand_in_misc_fops;

	wiegand_in_data_reset(wiegand_in);
	wiegand_in->pulse_width = DEF_PULSE_WIDTH;
	wiegand_in->pulse_intval = DEF_PULSE_INTERVAL;
	wiegand_in->data_length = DEF_DATA_LENGTH;

	spin_lock_init(&wiegand_in->lock);
	init_waitqueue_head(&wiegand_in->wq);
	hrtimer_init(&wiegand_in->timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
	wiegand_in->timer.function = wiegand_in_timeout;

	ret = misc_register(&wiegand_in->mdev);
	if (ret < 0) {
		dev_err(&pdev->dev, "misc_register failed %s %s %d\n", __FILE__, __FUNCTION__, __LINE__);
		goto err_registe_misc;
	}

	platform_set_drvdata(pdev, wiegand_in);
	printk("Weigand in driver register success.\n");

	return 0;

err_registe_misc:
	free_irq(gpio_to_irq(wiegand_in->data1_pin), NULL);
err_request_irq1:
	free_irq(gpio_to_irq(wiegand_in->data0_pin), NULL);
err_request_irq0:
	gpio_free(wiegand_in->data1_pin);
err_gpio_request1:
	gpio_free(wiegand_in->data0_pin);
err_gpio_request0:
	kfree(wiegand_in);
	return ret;
}

static int wiegand_in_remove(struct platform_device *dev)
{
	struct wiegand_in_dev *wiegand_in = platform_get_drvdata(dev);
	misc_deregister(&wiegand_in->mdev);
	free_irq(gpio_to_irq(wiegand_in->data0_pin), wiegand_in);
	free_irq(gpio_to_irq(wiegand_in->data1_pin), wiegand_in);
	gpio_free(wiegand_in->data0_pin);
	gpio_free(wiegand_in->data1_pin);
	kfree(wiegand_in);

	return 0;
}

static struct platform_driver wiegand_in_driver = {
	.probe		= wiegand_in_probe,
	.remove		= wiegand_in_remove,
	.driver		= {
		.name	= "wiegand_in",
	},
};

static int __init wiegand_in_init(void)
{
	return platform_driver_register(&wiegand_in_driver);
}

static void __exit wiegand_in_exit(void)
{
	platform_driver_unregister(&wiegand_in_driver);
}

module_init(wiegand_in_init);
module_exit(wiegand_in_exit);
MODULE_LICENSE("GPL");

<file_sep>/sys_program/player/src/inc/include.h
/* ************************************************************************
 *       Filename:  include.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月25日 08时02分50秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __INCLUDE_H__
#define __INCLUDE_H__







#endif
<file_sep>/c/lrc/file.h
/* ************************************************************************
 *       Filename:  file.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 05時35分49秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __FILE_H__
#define __FILE_H__

#include "common.h"

char * read_src_file(ulint *file_length, char *lrc_src);
//char **get_musiclist();
char *get_musiclist(char ***plist);
void delete_dot(char *plist[]);
void recover_dot(char *plist[]);
int check_lines(ulint file_length, char *lrc_src);
int get_longestline(int lines, char *plines[]);
int get_longestlength(LRC *lrc_head);
int get_showoffset(char *pbuf, int longest);
int get_chrnumber(char *pbuf, int len);
#endif
<file_sep>/network/1st_day/test.c
/* ************************************************************************
 *       Filename:  test.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月11日 14时42分35秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define uchar    unsigned char
#define uint     unsigned int
#define uint16   unsigned short
#define TRUE    (1)
#define FALSE   (0)

const char *rules[] = {
	"ip",
	"mac",
	"port",
	"arp",
	"tcp",
	"udp",
	"icmp",
	"igmp",
	"http",
	"tftp",
};

unsigned int iptoun_btol(unsigned char *ip)
{
	unsigned int ip_val = 0;

	ip_val = ip[0]<<24 | ip[1]<<16 | ip[2]<<8 | ip[3]; //如果把 “|” 换成 “+”，得到的结果是0

	return ip_val;
}
unsigned int iptoun_btob(unsigned char *ip)
{
	unsigned int ip_val = 0;

	//ip_val = ip[3]<<24 | ip[2]<<16 | ip[1]<<8 | ip[0];
	ip_val = *(unsigned int *)ip;
	return ip_val;
}

char check_if_same_subnet(uchar eth_mask[], uchar eth_ip[], uchar dst_ip[])
{
	if(((*(uint *)eth_ip) & (*(uint *)eth_mask)) ==\
		((*(uint *)dst_ip) & (*(uint *)eth_mask)))
		return TRUE;

	else
		return FALSE;
}
#if 1
int main(int argc, char *argv[])
{
	uchar buf[64] = "";
	int len =0;
	char tt[] = "5557";
	len = atoi(tt);
	printf("##%d\n",len);
	fgets(buf, 64, stdin);
	len = strlen(buf);

	buf[len] = 0;

	printf("%d\n", buf[0]);
}
#elif 0
int main(int argc, char *argv[])
{
	uchar ip[16] = "10.221.2.12";
	uchar part[4][6];
	bzero(part, sizeof(part));
	sscanf(ip, "%s.%s.%s.%s", *(part+0), *(part+1), *(part+2), *(part+3));

	printf("%s #%s #%s #%s\n",*(part+0), *(part+1), *(part+2), *(part+3));
#if 0
	int p[4];

	sscanf("10.221..12", "%d.%d.%d.%d", (int *)&p[0],(int *)&p[1],(int *)&p[2],(int *)&p[3]);
	printf("%d %d %d %d\n",p[0],p[1],p[2],p[3]);
#endif
	return 0;
}
#elif 0
int main(int argc, char *argv[])
{
	uchar part[2][18];
	uchar type[16];
	uchar port[16];
	uchar ip[4] = {10,221,2,12};
	uchar src_ip[16] = "";
	uchar dst_ip[16] = "";
	uint16 port_val = 0;
	uint16 temp = 8000;
	char rule[30] = "ip 10.221.2.12";

	//提取源ip
	sprintf(src_ip,"%d.%d.%d.%d",\
	ip[0],ip[1],ip[2],ip[3]);

	sscanf(rule, "%*s %s %s", *(part+0), *(part+1));

	int len = strlen(*(part+1));
	printf("len = %d\n",len);
	if(strcmp(src_ip, *(part+1)) == 0) printf("****OK\n");
#if 0
	sscanf(rule, "%*s %s %s", type, port);
	port_val = (uint16)atoi(port);

	if(port_val == temp) printf("***OK\n");
	return 0;
#endif
}
#elif 0
typedef struct _arphdr
{
	uint16 ar_hrd;
	uint16 ar_pro;
	uchar ar_hln;
	uchar ar_pln;
	uint16 ar_op;

	uchar src_mac[6];
	uchar src_ip[4];
	uchar dst_mac[6];
	uchar dst_ip[4];
}ARP_Hdr;

int main(int argc, char *argv[])
{
	uchar msg[256] = {
		//-----组mac----14----
		0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
		0x00,0x00,0x00,0x00,0x00,0x00,//src_mac:
		0x08,0x06,                    //类型: 0x0806 ARP协议

		//-----组ARP----28----
		0x00,0x01,0x08,0x00,          //硬件类型1(以太网地址)，协议类型:0x800(IP)
		0x06,0x04,0x00,0x01,          //硬件、协议的地址长度分别为6和4，ARP请求
		0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
		0, 0, 0, 0,                   //发送端的ip
		0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac，设置为0)
		10, 221, 2, 221,              //目的ip
	};
	unsigned char p[4] = "";
	ARP_Hdr *arp = NULL;
	arp = (ARP_Hdr *)(msg+14);

	if(ntohs(arp->ar_op) == 1) printf("arp request\n");
	else if(arp->ar_op == 2) printf("arp reply\n");

	printf("dst_ip:%d\n",iptoun_btol(arp->dst_ip));

	unsigned char ip[4] = {10,221,2,221};



	sscanf("10.221.2.12", "%d.%d.%d.%d", (int *)&p[0],(int *)&p[1],(int *)&p[2],(int *)&p[3]);
	printf("%d %d %d %d\n",p[0],p[1],p[2],p[3]);

	printf("iptoun_btol -- ip=%d\n",iptoun_btol(ip));

	printf("rules count=%d\n", sizeof(rules)/sizeof(rules[0]));
	return 0;
}
#elif 0
int main(int argc, char *argv[])
{
	unsigned char ip[4] = {10,221,2,221};
	unsigned char ip2[4] = {192,221,2,1};
	unsigned char mask[4] = {255,255,255,0};
	unsigned int ip_val = 0, ip_val2 = 0, mask_val = 0;
	uchar ty[2] = {0x08,0x00};
	unsigned short type = 0;

	type = ntohs(*(uint16 *)(ty));

	printf("type=%d, %d\n", type, 0x0800);
	(*(uint *)ip) = ((*(uint *)ip) & (*(uint *)mask));
	printf("%d.%d.%d.%d\n",ip[0],ip[1],ip[2],ip[3]);

	char flag = check_if_same_subnet(mask,ip,ip2);
	if(flag == TRUE) printf("OK####\n");
	else printf("NO*****\n");

	//printf("%s\n",((*(uint *)ip) & (*(uint *)mask)));
#if 0
	printf("IP:%s\n",(char*)inet_ntoa(ip));

	ip_val = ntohl(*(unsigned int *)ip);
	printf("ntohl-- ip_val=%d\n",ip_val);

	ip_val = iptoun_btol(ip);
	printf("iptoun_btol-- ip_val=%d\n",ip_val);

	ip_val = htonl(*(unsigned int *)ip);
	printf("htonl-- ip_val=%d\n",ip_val);

	ip_val = iptoun_btob(ip);
	printf("iptoun_btob -1- ip_val=%u\n",ip_val);

	ip_val2 = iptoun_btob(ip2);
	printf("iptoun_btob -2- ip_val=%u\n",ip_val2);
	printf("iptoun_btob -2- ip_val=%u\n",*(unsigned int *)ip2);

	if(ip_val2 > ip_val) printf("good\n");

	ip_val = ntohl(ip_val2);
	printf("iptoun_btol -2- ip_val=%d\n",ip_val);
#endif
	return 0;
}
#endif

<file_sep>/network/sockets/GetAddrInfo.c
/*************************************************************************
	> File Name: GetAddrInfo.c
	> Author: 
	> Mail: 
	> Created Time: Fri 06 May 2016 09:20:10 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include "Practical.h"

int main(int argc, char *argv[])
{

    if(argc != 3)
        DieWithUserMessage("Parameter(s)","<Address/Name> <Port/Service");

    char *addrString = argv[1];
    char *portString = argv[2];

    //Tell the system what kind(s) of address info we want
    struct addrinfo addrCriterial;
    memset(&addrCriterial, 0, sizeof(addrCriterial));
    addrCriterial.ai_family = AF_UNSPEC;
    addrCriterial.ai_socktype = SOCK_STREAM;
    addrCriterial.ai_protocol = IPPROTO_TCP;

    //Get address(es) associated with the specified name/Service
    struct addrinfo *addrList;
    int rtnVal = getaddrinfo(addrString, portString, &addrCriterial, &addrList);
    if(rtnVal != 0)
        DieWithUserMessage("getaddrinfo() failed",gai_strerror(rtnVal));

    //Display returned addresses
    struct addrinfo *addr;
    for(addr = addrList; addr != NULL; addr = addr->ai_next) {
        PrintSocketAddress(addr->ai_addr, stdout);
        fputc('\n', stdout);
    }

    freeaddrinfo(addrList); //Free addrinfo allocated in getaddrinfo()
    exit(0);
}
<file_sep>/c/homework/3rd_week/atoi/myatoi.c
/* ************************************************************************
 *       Filename:  myatoi.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月27日 星期一 02時24分00秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <math.h>

int myatoi(char *src)
{
	int i = 0;
	int len = 0, res = 0;
	len = strlen(src);

	for(i=0;i<len;i++)
	{
		res += pow(10,len-i-1) * (src[i]-48);
	}

	return res;
}

void main()
{
	char c[]="12345";
	
	printf("%d\n",myatoi(c));
}
<file_sep>/network/6th_day/libnet_test.c
/* ************************************************************************
 *       Filename:  libnet_test.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月10日 10时13分29秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libnet.h>


int main(int argc, char *argv[])
{
	char msg[1024] = "1_lbt6_56#128#7427EAB366CA#0#0#0#4000#9:666666:szb05:SZ-B05:32:";
	char buf[1024] = "";
	char err_buf[100] = "";
	unsigned char dst_mac[6] = {0xec,0xa8,0x6b,0xac,0xcf,0xf9};
	unsigned char src_mac[6] = {0x00,0x0c,0x29,0xe4,0xd3,0xd6};
	char *dst_ip_str = "10.221.2.12";
	char *src_ip_str = "10.221.2.221";

	unsigned long dst_ip, src_ip;
	libnet_t *plib_hdr = NULL;
	libnet_ptag_t ptag1 = 0, ptag2 = 0, ptag3 = 0;

	fgets(buf, sizeof(buf), stdin);
	int len = strlen(buf);
	buf[--len] = 0;
	strcat(msg,buf);
	len = strlen(msg);

	plib_hdr = libnet_init(LIBNET_LINK_ADV, "eth0", err_buf);
	if(NULL == plib_hdr)
	{
		perror("");
		exit(-1);
	}
	src_ip = libnet_name2addr4(plib_hdr, src_ip_str, LIBNET_RESOLVE);
	dst_ip = libnet_name2addr4(plib_hdr, dst_ip_str, LIBNET_RESOLVE);

	ptag1 = libnet_build_udp(2425, 2425, 8+len, 0, msg, len, plib_hdr, 0);
	ptag2 = libnet_build_ipv4(20+8+len,0,0,0,128,17,0,src_ip,dst_ip,NULL,0,plib_hdr,0);
	ptag3 = libnet_build_ethernet((u_int8_t *)dst_mac,(u_int8_t *)src_mac,ETHERTYPE_IP,NULL,0,plib_hdr,0);

	libnet_write(plib_hdr);
	libnet_destroy(plib_hdr);

	return 0;
}
<file_sep>/sys_program/4th_day/homework/mplayer/Makefile
CC := gcc
SRC := $(shell ls *.c)
#OBJ := $(patsubst %.c,%.o,$(SRC))
OBJ := $(SRC:%.c=%.o)
TAG := elf
CFLAGS = `pkg-config --cflags --libs gtk+-2.0`	

$(TAG):$(OBJ)
	$(CC) -o $@ $^ $(CFLAGS) -lpthread
%.o:%.c
	$(CC) -o $@ -c $< $(CFLAGS) -lpthread


.PHONY:clean
clean:
	rm -f $(TAG) *.o *~
<file_sep>/network/1st_day/Makefile
all:qq yy

qq:qq.c
	gcc -o qq qq.c -lpthread
yy:qq.c
	gcc -o yy qq.c -lpthread

.PHONY:clean
clean:
	rm qq yy
<file_sep>/c/homework/3rd_week/message/main.c
/* ************************************************************************
 *       Filename:  message.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月27日 星期一 11時55分11秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "msg.h"
void main()
{
	char msg_src[]={"+CMGR:REC UNREAD,+8613466630259,98/10/01,18:22:11+00,ABCdefGHI"};
	char *msg_done[5] = {NULL};
	
	msg_deal(msg_src,msg_done,",");
	show_message(msg_done);
}


<file_sep>/sys_program/1st_day/cp/Makefile
CC := gcc
SRC := $(shell ls *.c)
OBJ := $(patsubst %.c,%.o,$(SRC))
#OBJ := $(SRC:%.c=%.o)

TAG := cp
CFLAG := -lm

$(TAG):$(OBJ)
	$(CC) -o $@ $^ $(CFLAG)
%.o:%.c
	$(CC) -o $@ -c $< $(CFLAG)


.PHONY:clean
clean:
	rm -f $(TAG) $(OBJ)
<file_sep>/network/1st_day/udp_server.c
/* ************************************************************************
 *       Filename:  udp_server.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月31日 17时33分36秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>


int main(int argc, char *argv[])
{
	//创建一个通信socket
	int sockfd = socket(AF_INET, SOCK_DGRAM, 0);

	//作为一个服务器应该有一个固定的ip、port
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(8030);
	//INADDR_ANY: 通配地址
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	//bind只能bind自己的ip
	bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));

	//定义保存接收信息的源地址信息
	char buf[128];
	char ip_buf[INET_ADDRSTRLEN] = ""; //INET_ADDRSTRLEN = 16
	struct sockaddr_in client_addr;
	socklen_t client_len = sizeof(client_addr);
	bzero(&client_addr, sizeof(client_addr));

	//接收client发送来的数据
	recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&client_addr, &client_len);

	inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, INET_ADDRSTRLEN);
	printf("ipaddr:%s\n",ip_buf);
	//printf("ipaddr:%d\n",ntohl(client_addr.sin_addr.s_addr));
	printf("port  :%d\n",ntohs(client_addr.sin_port));
	printf("buf = %s\n",buf);
	return 0;
}
<file_sep>/network/4th_day/webserver.c
/* ************************************************************************
 *       Filename:  webserver.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月06日 11时36分46秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

char const err[] = "HTTP/1.1 404 Not Fount\n\
					Server:Apache Tomcat/5.0.12\n\
					Content-Type:text/html\n\
					Content-Length:43\n\
					<HTML><BODY>File not Fount</BODY></HTML>";

char const *ack[] ={"HTTP/1.1 200 OK\r\n",
				    "Server:Apache Tomcat/5.0.12\r\n",
				    "Content-Type:text/html\r\n",
				    "Content-Length:",
					"\r\n"
				   };

void *server_fun(void *arg)
{
	FILE *fp = NULL;
	int connfd = (int)arg;
	int len = 0;
	char msg[512] = "";
	char html[256]= "";
	char path[256]= "./html/";

	bzero(msg, sizeof(msg));
	len = recv(connfd, msg, sizeof(msg),0);
	sscanf(msg,"GET /%[^ ]",html);
	//printf("html = ###%s###\n",html);
	//printf("msg = %s\n", msg);

	strcat(path,html);
	printf("path = %s\n",path);
	fp = fopen(path,"rb");
	if(fp == NULL)
	{
		printf("Not fount file\n");
		send(connfd, err, sizeof(err), 0);
		close(connfd);
		pthread_exit(NULL);//退出线程
	}

	//fseek(fp,0,SEEK_END);
	//len = ftell(fp); //获取文件的大小
	//sprintf(msg, "%s%d%s", ack[4],len,"\r\n");
	//printf("msg = %s\n",msg);

	send(connfd,ack[0],strlen(ack[0]),0);
	//send(connfd,ack[1],strlen(ack[1]),0);
	send(connfd,ack[2],strlen(ack[2]),0);
	//send(connfd,ack[3],strlen(ack[3]),0);
	send(connfd,ack[4],strlen(ack[4]),0); //要加上这一句，否则网页的图片无法显示

	while(1)
	{
		bzero(msg,sizeof(msg));
		len = fread(msg, 1, 512, fp);

		if(len == 0) break;
		send(connfd, msg, len, 0);
		//printf("_len=%d\n",len);
	}

	fclose(fp);
	close(connfd);
	return NULL;
}

int main(int argc, char *argv[])
{
	unsigned short port = 8000;

	//创建一个监听套接字
	int sockfd  = socket(AF_INET, SOCK_STREAM, 0);

	if(argc > 1)
	{
		port = atoi(argv[1]);
	}

	//让服务器绑定IP和端口
	struct sockaddr_in addr;
	bzero(&addr, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port   = htons(port);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));
	if(ret != 0)
	{
		perror("bind:");
		exit(-1);
	}

	listen(sockfd, 10);//创建监听队列

	struct sockaddr_in c_addr;
	socklen_t c_addr_len = sizeof(c_addr);

	while(1)
	{
		int connfd = accept(sockfd, (struct sockaddr *)&c_addr, &c_addr_len);
		pthread_t pth;
		pthread_create(&pth, NULL, (void *)server_fun, (void *)connfd);
		pthread_detach(pth);
	}

	close(sockfd);
	return 0;
}


<file_sep>/sys_program/player/src/inc/common.h
#ifndef __COMMON_H__
#define __COMMON_H__

#include <gtk/gtk.h>
#include <glade/glade.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include "sungtk_interface.h"



#define  uint   unsigned int
#define  ulint  unsigned long int
#define  uchar  unsigned char


#define  FIFO   "cmd_fifo"
#define  MS     (1000)


typedef enum
{
	sequence  = 0,  //列表顺序播放
	list_loop = 1,  //列表循环
	loop      = 2,  //单曲循环
	randm     = 3,  //随机播放
}PLAY_MODE;

typedef enum
{
	stop    = 0,
	playing = 1,
//	end     = 2,
}PLAY_STATUS;

typedef enum
{
	mute = 0, //静音
	beam = 1, //播音
}SOUND_STATUS;

typedef enum
{
	quiet = 0,
	init  = 1,
	back  = 2,
	next  = 3,
	clist = 4,
}KEY_STATUS;

typedef struct _lrc
{
	//float time;
	int time;
	char src[256];

	struct _lrc *prev;
	struct _lrc *next;
}LRC;

typedef struct _song
{
	char *song_src;
	char **psong_list;
	char *search;
	char search_flag;
	char name[168];

	char *lrc_src;
	char *plines[128]; //指向 歌词的每一行
//	char *lrc_title[4];

	int lrc_lines;    //存放歌词的行数
	int now;          //指向当前播放的歌曲
	int old;
	int count;        //歌的数量

	int   cur_time;  //歌曲播放当前时间
	int   end_time;  //歌曲播放结束时间
	int   endflag;   //歌曲播放结束标志
	float rate;      //歌曲播放进度

	ulint lrc_length;

	sem_t sem_setsong;
	sem_t sem_keyflag;

	LRC *lrc_head;
	LRC *pnode;

	KEY_STATUS keyflag;
}SONG;

typedef struct _hbox_left
{
	GtkButton *bmusic_list;
	GtkButton *bmusic_collect;
	GtkButton *bmusic_recently;

	GtkEntry  *entry_search;
	GtkButton *button_search;
	GtkTable  *table_search;
	GtkScrolledWindow *scrollbar_musiclist;
	GtkCList *music_clist;
	GtkTable *table_musiclist;
	GtkEventBox *eventbox_musiclist;
}HBOX_LEFT;

typedef struct _hbox_right
{
	GtkImage *image_logo;

	GtkButton *button_back;
	GtkButton *button_next;
	GtkButton *button_pause;
	GtkButton *button_backward;
	GtkButton *button_forward;
	GtkButton *button_playmode;

	GtkImage *image_back;
	GtkImage *image_next;
	GtkImage *image_pause;
	GtkImage *image_backward;
	GtkImage *image_forward;

	GtkLabel *label_title1;
	GtkLabel *label_title2;
	GtkLabel *label_title3;

	GtkLabel *label_lrc1;
	GtkLabel *label_lrc2;
	GtkLabel *label_lrc3;
	GtkLabel *label_lrc4;
	GtkLabel *label_lrc5;
	GtkLabel *label_lrc6;
	GtkLabel *label_lrc7;

	GtkLabel *label_cur_time;
	GtkLabel *label_end_time;

	GtkProgressBar *progress_bar;
	GtkEventBox *eventbox_bar;

	GtkHScale *hscale_volume;
	GtkButton *button_volume;
	GtkEventBox *eventbox_volume;
}HBOX_RIGHT;

typedef struct _window
{
	GtkWidget *main_window;
	//GtkImage *image;

	HBOX_LEFT  hbox_left;
	HBOX_RIGHT hbox_right;
}WINDOW;

typedef struct _mplayer
{
	WINDOW ui;

//	char msg[128]; //接收mplayer信息
	int fd_pipe;   //命名管道
	int fd[2];     //无名管道
	pid_t pid;     //启动mplayer的子进程pid

	pthread_t pth_showlrc;
	pthread_t pth_rcvmsg;
	pthread_t pth_sendcmd;

	pthread_mutex_t mutex;

	PLAY_STATUS  playflag; //播放状态
	PLAY_MODE    playmode; //播放模式
	SOUND_STATUS soundflag;
//	SunGtkCList *musiclist;
}MPLAYER;
#endif
<file_sep>/network/route/src/msg_dispose.c
/******************************************************************************
  文 件 名   : msg_dispose.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 处理网络数据
  函数列表   :
              get_ip
              get_mac
              check_if_same_subnet
              dispose_arp_reply
              get_transpond_port
              get_type
              reply_arp_requset
              send_msg
              show_msg_ip
              transpond_msg
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"
#include "arp_link.h"


/*****************************************************************************
 函 数 名  : get_mac()
 功能描述  : 提取目的mac、源mac
 输入参数  : recv      接收网络数据包的缓存
 			 dst_mac   存储目的mac的首地址  传入NULL 则不提取
 			 src_mac   存储源mac的首地址    传入NULL 则不提取
 返 回 值  : NULL
 修改日期  : 2015年9月12日
*****************************************************************************/
void get_mac(uchar *recv, uchar *dst_mac, uchar *src_mac)
{
	if(dst_mac != NULL){
		memcpy(dst_mac, recv, 6);
	}

	if(src_mac != NULL){
		memcpy(src_mac, recv+6, 6);
	}
}

/*****************************************************************************
 函 数 名  : get_type()
 功能描述  : 获取协议类型
 输入参数  : recv     接收网络数据包的缓存
 返 回 值  : 返回协议类型(无符号短整型整数)
 修改日期  : 2015年9月11日
*****************************************************************************/
uint16 get_type(const uchar *recv)
{
	uint16 type = 0;

	type = ntohs(*(uint16 *)(recv+12));

	return type;
}

/*****************************************************************************
 函 数 名  : get_ip()
 功能描述  : 提取目的ip、源ip
 输入参数  : recv     接收网络数据包的缓存
 			 dst_ip   存储目的ip的首地址  传入NULL 则不提取
 			 src_ip   存储源ip的首地址    传入NULL 则不提取
 返 回 值  : NULL
 修改日期  : 2015年9月12日
*****************************************************************************/
void get_ip(const uchar *recv, uchar *dst_ip, uchar *src_ip)
{
	if(src_ip != NULL){
		//提取源ip
		memcpy(src_ip, recv+12, 4);
	}

	if(dst_ip != NULL){
		//提取目的ip
		memcpy(dst_ip, recv+16, 4);
	}
}

/*****************************************************************************
 函 数 名  : show_msg_ip()
 功能描述  : 提取目的ip、源ip
 输入参数  : recv     接收网络数据包的缓存
 返 回 值  : NULL
 修改日期  : 2015年9月11日
*****************************************************************************/
void show_msg_ip(const uchar *recv)
{
	unsigned char dst_ip[16] = "";
	unsigned char src_ip[16] = "";

	//提取源ip
	sprintf(src_ip,"%d.%d.%d.%d",\
			recv[12],recv[13],recv[14],recv[15]);

	//提取目的ip
	sprintf(dst_ip,"%d.%d.%d.%d",\
			recv[16],recv[17],recv[18],recv[19]);

	printf("IP:%s >> %s\n", src_ip, dst_ip);
}

/*****************************************************************************
 函 数 名  : check_if_same_subnet()
 功能描述  : 检测目的ip跟网卡是否在同一网段
 输入参数  : eth_mask     网卡子网掩码
             eth_ip       网卡ip
             dst_ip       目的ip
 返 回 值  : 布尔型
 修改日期  : 2015年9月12日
*****************************************************************************/
Boolean check_if_same_subnet(const uchar eth_mask[], const uchar eth_ip[],const uchar dst_ip[])
{
	if(((*(uint *)eth_ip) & (*(uint *)eth_mask)) ==\
		((*(uint *)dst_ip) & (*(uint *)eth_mask)))
		return TRUE;

	else
		return FALSE;
}

/*****************************************************************************
 函 数 名  : get_transpond_port()
 功能描述  : 获取数据转发的接口
 输入参数  : rt        TYPE_Route 类型结构指针
 			 dst_ip    目的ip
 返 回 值  : 返回网卡的编号
 修改日期  : 2015年9月12日
*****************************************************************************/
int get_transpond_port(TYPE_Route *rt, const uchar dst_ip[])
{
	int i = 0;
	Boolean flag = FALSE;

	for(i=0; i < rt->port_num; i++)
	{
		flag = check_if_same_subnet(rt->eth_port[i].netmask, rt->eth_port[i].ip, dst_ip);

		if(flag == TRUE) return i;
	}

	return -1;
}

/*****************************************************************************
 函 数 名  : send_msg()
 功能描述  : 获取ip数据包的转发接口
 输入参数  : rt        TYPE_Route 类型结构指针
 			 port      网络接口的编号
 			 msg_len   发送数据长度
 返 回 值  :
 修改日期  : 2015年9月12日
*****************************************************************************/
int send_msg(TYPE_Route *rt, int port, int msg_len)
{
	int send_len = 0;

	strncpy(rt->ethreq.ifr_name,rt->eth_port[port].name, IFNAMSIZ);
	ioctl(rt->raw_fd, SIOCGIFINDEX, (char *)&rt->ethreq);
	bzero(&rt->sll, sizeof(rt->sll));
	rt->sll.sll_ifindex = rt->ethreq.ifr_ifindex;

	send_len = sendto(rt->raw_fd, rt->recv, msg_len, 0, (struct sockaddr *)&rt->sll, sizeof(rt->sll));

	return send_len;
}
/*****************************************************************************
 函 数 名  : transpond_msg()
 功能描述  : 获取ip数据包的转发接口
 输入参数  : rt        TYPE_Route 类型结构指针
 			 dst_ip    目的ip
 			 port      网络接口的编号
 			 msg_len   发送数据包的长度
 返 回 值  : 无法获取目的mac时，返回-1，否则返回实际发送的长度
 修改日期  : 2015年9月12日
*****************************************************************************/
int transpond_msg(TYPE_Route *rt, const uchar dst_ip[], int port, int msg_len)
{
	ARP_Table *pnode = NULL;

	if(rt->arp_head == NULL){ //如果ARP表为空，则建立ARP表
		build_arp_table(rt);
	}

	pnode = (ARP_Table *)search_arp_table(rt->arp_head, dst_ip);

	if(pnode == NULL){ //在arp表中没有找到目的ip
		Boolean flag = broadcast(rt, dst_ip); //广播获取目的mac

		if(flag == FALSE) { //广播没有获取到目的mac

			return -1;
		}
		pnode = (ARP_Table *)search_arp_table(rt->arp_head, dst_ip);
	}

//	uchar dst_mac[6] = "";
//	uchar src_mac[6] = "";
//
//	memcpy(dst_mac, pnode->mac, 6);
//	memcpy(src_mac, rt->eth_port[port].mac, 6);

	memcpy(rt->recv,   pnode->mac, 6); //修改ip数据包的目的mac地址
	memcpy(rt->recv+6, rt->eth_port[port].mac, 6); //修改ip数据包的源mac地址


	int send_len = send_msg(rt, port, msg_len);

	return send_len;
}

/*****************************************************************************
 函 数 名  : reply_arp_requset()
 功能描述  : 应答arp请求
 输入参数  : rt        TYPE_Route 类型结构指针
 			 pinfo     MSG_Info 类型指针
 			 ARP_Hdr   ARP_Hdr 类型指针
 返 回 值  : 返回发送的长度，出错返回-1
 修改日期  : 2015年9月12日
*****************************************************************************/
int reply_arp_requset(TYPE_Route *rt, MSG_Info *pinfo, ARP_Hdr *arp_hdr)
{
	int port = 0;

	memcpy(pinfo->dst_ip, arp_hdr->dst_ip, 6);
	port = get_transpond_port(rt, pinfo->dst_ip);

	if(port != -1)
	{
		//获取ARP请求端的ip和mac地址
		memcpy(pinfo->src_mac, arp_hdr->src_mac, 6);
		memcpy(pinfo->src_ip,  arp_hdr->src_ip, 4);

		//组ARP应答包
		memcpy(rt->recv, pinfo->src_mac, 6); //
		memcpy(rt->recv+6, rt->eth_port[port].mac, 6);

		arp_hdr->ar_op = htons(2); // -> 运算符优先级高于 &

		memcpy(arp_hdr->src_mac, rt->eth_port[port].mac, 6);
		memcpy(arp_hdr->src_ip, pinfo->dst_ip, 4);

		memcpy(arp_hdr->dst_mac, pinfo->src_mac,6);
		memcpy(arp_hdr->dst_ip,  pinfo->src_ip, 4);


		int send_len = send_msg(rt, port, pinfo->len);

		return send_len;
	}

	return -1;
}

/*****************************************************************************
 函 数 名  : dispose_arp_reply()
 功能描述  : 处理arp请求
 输入参数  : rt        TYPE_Route 类型结构指针
 			 ARP_Hdr   ARP_Hdr 类型指针
 返 回 值  : NULL
 修改日期  : 2015年9月12日
*****************************************************************************/
void dispose_arp_reply(ARP_Table *head, ARP_Hdr *arp_hdr)
{
	ARP_Table *pnode = NULL, node;

	memcpy(node.ip,  arp_hdr->src_ip, 4);
	memcpy(node.mac, arp_hdr->src_mac,6);

	pnode = (ARP_Table *)search_arp_table(head, node.ip);

	if(pnode != NULL) {
		change_arp_mac(head, node.ip, node.mac);
	}
	else {
		head = (ARP_Table *)insert_arp_table(head, node);
	}
}
<file_sep>/shell/4st_week/test
#!/bin/bash

cd $HOME

if [ ! -d "test" ]
then
	echo "test directory is not exist!"
	read -p "input 'y' to create or 'n' to leave: " answer

	case $answer in
	y | Y) mkdir test
		   echo "create test directory succeed";;
	n | N) exit;;
	*) echo "input error!"
	   exit;;
	esac
fi

echo "cd test"
cd test

count=1
read -p "please input a file name: " filename

until [ ! -f "$filename" ]
do
	read -p "$filename is exist, input again: " filename
	count=$[ $count + 1 ]

	if [ $count -eq 3 ]
	then
		echo "exit!"
		exit
	fi
done

if test touch "$filename"
then
	echo "create $filename file succeed"
fi
<file_sep>/sys_program/player/src/process_lrc.c
/* ************************************************************************
 *       Filename:  process_lrc.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 09時17分27秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include "common.h"
#include "console.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"
#include "gb2312_ucs2.h"
#include "link.h"
#include "file.h"
#include "process_lrc.h"


uint src_segment(char *src, char *plines[], char *str)
{
	uint i = 0;
	
	plines[0] = strtok(src, str);
	
	while(plines[i++] != NULL)
	{
		plines[i] = strtok(NULL, str);
	} 
	//printf("i=%d\n",i);
	return (i-1);
}

uint line_segment(char *pline, char *pbuf[], char *str)
{
	uint i = 0;
	
	pbuf[0] = strtok(pline, str);
	
	while(pbuf[i++] != NULL)
	{
		pbuf[i] = strtok(NULL, str);
		//printf("%s\n",pbuf[i]);
	} 
	//printf("i=%d\n",i);	
	
	return (i-1);
}

LRC *build_link(MPLAYER *pm,char *plines[],int lines)
{
	int i, j;
	uint part = 0;
	LRC lyric, *lrc_head = NULL;
	
	for(i=0;plines[i] != NULL && i<lines; i++)
	{	

	#if 0
		char *pbuf[10] = {NULL};
		
		part = line_segment(plines[i],pbuf, "]"); //切割一行
			
		for(j=0;j<part;j++)
		{
			int min = 0,sec = 0, msec = 0;
			
			printf("%s\n",pbuf[j]);
		}
	#elif 1				
		if(i<4) //
		{	
			char *ptitle = NULL;
			//char msg[100]; sscanf ???????
			//sscanf(plines[i],"%*[^:]%*1s%[^]]",msg[0]); 
			ptitle = strtok(plines[i],":]");
			if(ptitle != NULL) ptitle = strtok(NULL,":]");

			if(ptitle != NULL)
			{
				//printf("##$@#$ %s***\n",ptitle);
				//mplayer_show_lyrtitle(pm, ptitle, i);
			}
			
			#if 0			
			char *trash = NULL;
			int len = 0;

			if(plines[i] != NULL)
			{
				trash = strtok(plines[i],":]");
				if(trash != NULL)
				{
					trash = strtok(NULL,":]");
					if(trash != NULL)
					{						
						//printf("$$$$$$$$$$$$$$$$$$$$$$$\n");
						len = strlen(trash);
						
						if(len == 0) song.lrc_title[i] = NULL;
						else
						{
							char utf8[96] = {0};
							
							song.lrc_title[i] = (char *)malloc(len + 1);
							
							bzero(song.lrc_title[i], len + 1);
							gb2312_to_utf8(trash, utf8);
							
							strcpy(song.lrc_title[i], utf8);
							printf("lrc_title[%d] = %s\n",i, song.lrc_title[i]);
						}
					}
					else
					{
						song.lrc_title[i] = NULL;
					}
				}
			}
			#endif
		}
		else
		{ 	
			char *pbuf[10] = {NULL};
			int min = 0, sec = 0, msec = 0;
			//float sec;
			
			part = line_segment(plines[i],pbuf, "]"); //切割一行	
			
			for(j=0;j<part-1;j++)
			{				
				if(pbuf[part-1][0] != '[')
				{
					char utf8[256] = {0};
					sscanf(pbuf[j],"[%2d:%2d.%2d",&min,&sec,&msec);
					//printf("%2d:%2d.%2d\n",min,sec,msec);
				
					lyric.time = (min * 60 + sec)*1000 + msec*10;
					
					gb2312_to_utf8(pbuf[part-1], utf8);
					strcpy(lyric.src, utf8);				
					lrc_head = insert_link(lrc_head,lyric);
					//printf("%4d  %s\n",lyric.time, lyric.src);					
				}
			}				
		}
	#endif
	}
	return lrc_head;
}

LRC *dispose_lrc(MPLAYER *pm,char *name)
{
	song.lrc_src  = NULL;
	song.lrc_head = NULL;
	
	song.lrc_src = (char *)read_src_file(&song.lrc_length, name);
	if(song.lrc_src != NULL)
	{	
		song.lrc_lines = src_segment(song.lrc_src, song.plines, "\r\n");
		song.lrc_head  = (LRC *)build_link(pm, song.plines, song.lrc_lines);	
		song.pnode = song.lrc_head;	
		//print_link(song.lrc_head); 
	}

	free(song.lrc_src);
	return song.lrc_head;
}

void show_lyric(LRC *pnode, int longest)
{
	char *empty = " ";
	char *pbuf[12];
	int i = 0, offset = 0;
	LRC  *pb = NULL, *pf = NULL;
	
	pb = pnode;
	pf = pnode->next;
	
	for(i=3;i>=0;i--)
	{
		if(pb != NULL)
		{
			pbuf[i] = pb->src;
			pb = pb->prev;
		}
		else
		{
			pbuf[i] = empty;
		}
	}
	
	for(i=4;i<12;i++)
	{
		if(pf != NULL)
		{
			pbuf[i] = pf->src;
			pf = pf->next;
		}
		else
		{
			pbuf[i] = empty;
		}
	}

	for(i = 0;i < 12;i++) //
	{
		cusor_moveto(55, 20+i); //光标移到 第4+i行，第20列		
		printf("%-40s",empty); //清除上次的显示
		fflush(stdout);
	}	

	for(i = 0;i < 12;i++)
	{
		offset = get_showoffset(pbuf[i],longest);
		cusor_moveto(55+offset, 20+i); //光标移到 第10+i行，第50列
		
		set_fg_color(COLOR_WHITE);
		if(i == 3)
		{
			set_fg_color(COLOR_MAGENTA);
		}
		printf("%-40s",pbuf[i]);
		fflush(stdout);
	}
	cusor_moveto(9, 36);
	//fflush(stdout);	
}

void mplayer_show_lyric(MPLAYER *pm, LRC *pnode)
{
	char *empty = " ";
	char *pbuf[3] = {NULL};
	int i = 0;
	LRC  *pb = NULL, *pf = NULL;
	
	pb = pnode;
	pf = pnode->next;
	//printf(">>%d ms --- %s\n",song.pnode->time, song.pnode->src);
	
	for(i=0;i>=0;i--)
	{
		if(pb != NULL)
		{
			pbuf[i] = pb->src;
			pb = pb->prev;
		}
		else
		{
			pbuf[i] = empty;
		}
	}
	
	for(i=1;i<3;i++)
	{
		if(pf != NULL)
		{
			pbuf[i] = pf->src;
			pf = pf->next;
		}
		else
		{
			pbuf[i] = empty;
		}
	}

	set_lrc_lable(pm, pbuf);

}

void mplayer_show_lyrtitle(MPLAYER *pm, char *ptitle, int i)
{
	//char *msg[] = { ": ", "?: ", ": "};
	char utf8[168];
	//char buf[168];

	
	if(i < 3)
	{	
		//bzero(buf, sizeof(buf));
		//strcat(buf, msg[i]);
		//strcat(buf, ptitle);
		bzero(utf8, sizeof(utf8));
		gb2312_to_utf8(ptitle, utf8);
		printf("##$@#$ %s***\n",utf8);
		
		switch(i)
		{
			case 0:
			{
				set_lable(pm->ui.hbox_right.label_title1, utf8);
				break;
			}
			case 2:
			{
				set_lable(pm->ui.hbox_right.label_title2, utf8);
				break;
			}
			case 3:
			{
				set_lable(pm->ui.hbox_right.label_title3, utf8);
				break;
			}
		}
	}
}

<file_sep>/network/route/src/inc/route_control.h
/******************************************************************************
  文 件 名   : route_control.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月11日
  最近修改   :
  功能描述   : route_control.c 的头文件
******************************************************************************/
#ifndef __ROUTE_CONTROL_H__
#define __ROUTE_CONTROL_H__


/*----------------------------------------------*
 * 外部函数原型说明                             *
 *----------------------------------------------*/
extern void route_init(TYPE_Route *rt);
extern void show_port_info(TYPE_Route *rt, char *port_name);
extern void get_ethernet_port(TYPE_Route *rt);
extern void build_arp_table(TYPE_Route *rt);
extern Boolean broadcast(TYPE_Route *rt, const uchar ip[]);


#endif /* __ROUTE_CONTROL_H__ */
<file_sep>/work/test/pwm-led/pwm-led.c
/*************************************************************************
	>File Name: pwm-led.c
	>   Author: <NAME>
	>     Mail: <EMAIL> / <EMAIL>
	> Datatime: Thu 03 Nov 2016 07:45:42 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

/*
 * Macro
 */
#define JZ_GENERIC_PWM          0
#define DEFAULT_MAX_BRIGHTNESS  255
#define DEFAULT_DELAY_US        40000
#define DEFAULT_LED            "led_state"

/*
 * Variables
 */
const float duty[] = {
    0.00, 0.01, 0.02, 0.03,
    0.04, 0.05, 0.06, 0.07,
    0.09, 0.10, 0.11, 0.13,
    0.15, 0.17, 0.19, 0.21,
    0.23, 0.25, 0.27, 0.29,
    0.31, 0.33, 0.35, 0.38,
    0.41, 0.44, 0.47, 0.50,
    0.53, 0.56, 0.59, 0.62,
    0.66, 0.70, 0.74, 0.79,
    0.84, 0.89, 0.94, 1.00,
};

/*
 * Function
 */
void print_usage()
{
    printf("Usage:\n \
        pwm-led [OPTIONS]\n \
            a pwm-leds test demo\n\n \
        OPTIONS:\n \
            -l   ----> select led name\n \
            -m   ----> select pwd output method\n \
            -n   ----> set cycle times\n \
            -t   ----> set delay_us value\n \
            -h   ----> get help message\n\n \
        eg:\n \
        pwm-led -l xxx       ----> select /sys/class/leds/xxx\n \
        pwm-led -m 1 -t 500  ----> select method 1,and set delay_us = 500us\r\n");
}

int main(int argc, char *argv[])
{
    int fd;
    int len, oc;
    int i = 0, n = 10;
    int max_brightness = DEFAULT_MAX_BRIGHTNESS;
    int method = 0, delay_us = DEFAULT_DELAY_US;
    float val;
    char *arg = NULL, tmp[8] = "0";
#if (JZ_GENERIC_PWM == 1)
    char led[68] = "/sys/class/jz-pwm/";
#else
    char led[68] = "/sys/class/leds/";
#endif

    while(1) {
        oc = getopt(argc, argv, "hl:m:n:t:");
        if(oc == -1)
            break;

        switch(oc) {
        case 'l':
            arg = optarg;
            break;

        case 'm':
            method = atoi(optarg);
            break;

        case 'n':
            n = atoi(optarg);
            break;

        case 't':
            delay_us = atoi(optarg);
            break;

        case 'h':
        default:
            print_usage();
            return 1;
        }
    }

    if(arg != NULL) {
        strcat(led, arg);
        printf("LED name: %s\n", arg);
    } else {
        strcat(led, DEFAULT_LED);
        printf("LED name: %s\n", DEFAULT_LED);
    }

    len = strlen(led);

#if (JZ_GENERIC_PWM == 1)
    strncpy(led + len, "/max_dutyratio", sizeof("/max_dutyratio"));
#else
    strncpy(led + len, "/max_brightness", sizeof("/max_brightness"));
#endif
    fd = open(led, O_RDONLY);
    if(fd != -1) {
        if(read(fd, tmp, sizeof(tmp)) > 0)
            max_brightness = atoi(tmp);
        close(fd);
    }

    printf("        method = %d\n", method);
    printf("      delay_us = %d\n", delay_us);
    printf("max_brightness = %d\n", max_brightness);

#if (JZ_GENERIC_PWM == 1)
    strncpy(led + len, "/dutyratio", sizeof("/dutyratio"));
#else
    strncpy(led + len, "/brightness", sizeof("/brightness"));
#endif
    fd = open(led, O_WRONLY);
    if(fd < 0) {
        printf("Failed to open: %s\n", led);
        return -1;
    }

    while(n--) {
        if(method == 0) {
            for(i = 0; i < sizeof(duty)/sizeof(float); i++) {
                val = max_brightness * duty[i];
                len = snprintf(tmp, sizeof(tmp), "%d", (int)val);

                if(write(fd, tmp, len) < 0) {
                    printf("%d: write failed\n", __LINE__);
                    continue;
                }

                usleep(delay_us);
            }

            for(i = sizeof(duty)/sizeof(float) - 1; i >= 0; i--) {
                val = max_brightness * duty[i];
                len = snprintf(tmp, sizeof(tmp), "%d", (int)val);

                if(write(fd, tmp, len) < 0) {
                    printf("%d: write failed\n", __LINE__);
                    continue;
                }

                usleep(delay_us);
            }
        } else {
            for(val = 0; val < max_brightness; val++) {
                len = snprintf(tmp, sizeof(tmp), "%d", (int)val);

                if(write(fd, tmp, len) < 0) {
                    printf("%d: write failed\n", __LINE__);
                    continue;
                }

                usleep(delay_us);
            }

            for(val = max_brightness; val >= 0; val--) {
                len = snprintf(tmp, sizeof(tmp), "%d", (int)val);

                if(write(fd, tmp, len) < 0) {
                    printf("%d: write failed\n", __LINE__);
                    continue;
                }

                usleep(delay_us);
            }
        }
    }

    close(fd);
    return 0;
}
<file_sep>/network/4th_day/Makefile
webserver:webserver.c
	gcc -o webserver webserver.c -lpthread

.PHONY:clean
clean:
	rm webserver
<file_sep>/sys_program/1st_day/fork.c
/* ************************************************************************
 *       Filename:  fork.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月13日 15时34分25秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int gnum = 0;

int main(int argc, char *argv[])
{
	int num = 0;
	pid_t pid;

	pid = fork();

	if(pid < 0)  perror("error");

	else if(pid == 0)
	{
		while(1)
		{
			printf("gnum = %d   num = %d\n",gnum,num);
			printf("in son process\n");
			sleep(1);
		}
	}
	else
	{
		while(1)
		{
			gnum++;
			num++;

			printf("in father process\n");
			sleep(1);
		}
	}
	return 0;
}
<file_sep>/c/practice/sort/selectsort.c
#include "stdio.h"

void swap(int *a,int *b)
{                            
	int tmp;
	tmp = *a;
	*a = *b;
	*b = tmp;
}

void selectsort(int data[],int n)    /*选择排序*/
{
	int i,j,k,max;
	//int temp;

	for(i=0;i<n-1;i++)// “ i ” 就是起始值
	{
		k = i;
		for(j=i+1;j<n;j++)          
		{
			if(data[j] < data[k])
				k = j;//k is the always the smaller data location
		}
		
		if(k != i)//move the smallest data to the first location
		{
			swap(&data[i], &data[k]);		
		}	
	}
	

}

int main()
{
    int i,a[10] = {2,5,6,3,7,8,0,9,12,1};        
    printf("The data array is:\n") ;
    for(i=0;i<10;i++)                        /*显示原序列之中的元素*/
        printf("%d ",a[i]);

    selectsort(a,10);                         /*执行选择排序*/
	printf("\nThe result of selection sorting for the array is:\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);                        /*输出排序后的结果*/
	printf("\n");
	
	return 0;
}

<file_sep>/work/camera/ov7740/jz-ov7740/jz_camera_v13.c
/*
 * V4L2 Driver for Ingenic jz camera (CIM) host
 *
 * Copyright (C) 2014, Ingenic Semiconductor Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 * This program is support Continuous physical address mapping,
 * not support sg mode now.
 */
#include <linux/clk.h>
#include <linux/device.h>
#include <linux/types.h>
#include <linux/dma-mapping.h>
#include <linux/mutex.h>
#include <linux/version.h>
#include <linux/platform_device.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/device.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/slab.h>
#include <linux/videodev2.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-common.h>
#include <media/v4l2-dev.h>
#include <media/videobuf-dma-contig.h>
#include <media/soc_camera.h>
#include <media/soc_mediabus.h>
#include <asm/dma.h>
/*kzalloc*/
#include <mach/jz_camera.h>

#include <linux/regulator/consumer.h>

#define CIM_DUMP_REG
#define PRINT_CIM_REG
struct regulator *regul;
#ifdef CIM_DUMP_REG
static void cim_dump_reg(struct jz_camera_dev *pcdev)
{
	if(pcdev == NULL) {
		printk("===>>%s,%d pcdev is NULL!\n",__func__,__LINE__);
		return;
	}
#define STRING  "\t=\t0x%08x\n"
	printk("REG_CIM_CFG" STRING, readl(pcdev->base + CIM_CFG));
	printk("REG_CIM_CTRL" STRING, readl(pcdev->base + CIM_CTRL));
	printk("REG_CIM_CTRL2" STRING, readl(pcdev->base + CIM_CTRL2));
	printk("REG_CIM_STATE" STRING, readl(pcdev->base + CIM_STATE));

	printk("REG_CIM_IMR" STRING, readl(pcdev->base + CIM_IMR));
	printk("REG_CIM_IID" STRING, readl(pcdev->base + CIM_IID));
	printk("REG_CIM_DA" STRING, readl(pcdev->base + CIM_DA));
	printk("REG_CIM_FA" STRING, readl(pcdev->base + CIM_FA));

	printk("REG_CIM_FID" STRING, readl(pcdev->base + CIM_FID));
	printk("REG_CIM_CMD" STRING, readl(pcdev->base + CIM_CMD));
	printk("REG_CIM_WSIZE" STRING, readl(pcdev->base + CIM_SIZE));
	printk("REG_CIM_WOFFSET" STRING, readl(pcdev->base + CIM_OFFSET));

	printk("REG_CIM_FS" STRING, readl(pcdev->base + CIM_FS));
	printk("REG_CIM_YFA" STRING, readl(pcdev->base + CIM_YFA));
	printk("REG_CIM_YCMD" STRING, readl(pcdev->base + CIM_YCMD));
	printk("REG_CIM_CBFA" STRING, readl(pcdev->base + CIM_CBFA));

	printk("REG_CIM_CBCMD" STRING, readl(pcdev->base + CIM_CBCMD));
	printk("REG_CIM_CRFA" STRING, readl(pcdev->base + CIM_CRFA));
	printk("REG_CIM_CRCMD" STRING, readl(pcdev->base + CIM_CRCMD));
	printk("REG_CIM_TC" STRING, readl(pcdev->base + CIM_TC));

	printk("REG_CIM_TINX" STRING, readl(pcdev->base + CIM_TINX));
	printk("REG_CIM_TCNT" STRING, readl(pcdev->base + CIM_TCNT));
}
#endif

static unsigned int get_paddr(unsigned int vaddr)
{
	unsigned int addr = vaddr & (PAGE_SIZE-1);
	pgd_t *pgdir;
	pmd_t *pmdir;
	pte_t *pte;
	pgdir = pgd_offset(current->mm, vaddr);
	if(pgd_none(*pgdir) || pgd_bad(*pgdir))
		return 0;
	pmdir = pmd_offset((pud_t *)pgdir, vaddr);
	if(pmd_none(*pmdir) || pmd_bad(*pmdir))
		return 0;
	pte = pte_offset(pmdir,vaddr);
	if (pte_present(*pte)) {
		return addr | (pte_pfn(*pte) << PAGE_SHIFT);
	}
	return 0;
}

static int is_cim_enable(struct jz_camera_dev *pcdev)
{
	unsigned int regval = 0;

	regval = readl(pcdev->base + CIM_CTRL);
	return  (regval & 0x1);
}
static int is_cim_disabled(struct jz_camera_dev *pcdev)
{
	unsigned int regval = 0;

	regval = readl(pcdev->base + CIM_CTRL);
	return  ((regval & 0x1) == 0x0);
}

void cim_disable_without_dma(struct jz_camera_dev *pcdev)
{
	unsigned long temp = 0;

	/* clear status register */
	writel(0, pcdev->base + CIM_STATE);

	/* disable cim */
	temp = readl(pcdev->base + CIM_CTRL);
	temp &= (~CIM_CTRL_ENA);
	writel(temp, pcdev->base + CIM_CTRL);

	/* reset rx fifo */
	temp = readl(pcdev->base + CIM_CTRL);
	temp |= CIM_CTRL_RXF_RST;
	writel(temp, pcdev->base + CIM_CTRL);

	/* stop resetting RXFIFO */
	temp = readl(pcdev->base + CIM_CTRL);
	temp &= (~CIM_CTRL_RXF_RST);
	writel(temp, pcdev->base + CIM_CTRL);
}

static int jz_camera_querycap(struct soc_camera_host *ici, struct v4l2_capability *cap)
{
	strlcpy(cap->card, "jz-Camera", sizeof(cap->card));
	cap->version = VERSION_CODE;
	cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;

	return 0;
}

unsigned long jiff_temp;
static unsigned int jz_camera_poll(struct file *file, poll_table *pt)
{
	struct soc_camera_device *icd = file->private_data;
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;
	struct jz_buffer *buf;
	unsigned long temp = 0;
	unsigned int regval;

	if(!pcdev->poll_flag)
		pcdev->poll_flag = 1;

	buf = list_entry(icd->vb_vidq.stream.next, struct jz_buffer, vb.stream);

	if(pcdev->is_first_start) {
		writel(0, pcdev->base + CIM_STATE);

		/* please enable dma first, enable cim ctrl later.
		 * if enable cim ctrl first, RXFIFO can easily overflow.
		 */
		regval = (unsigned int)(pcdev->dma_desc);
		writel(regval, pcdev->base + CIM_DA);

		/*enable dma*/
		temp = readl(pcdev->base + CIM_CTRL);
		temp |= CIM_CTRL_DMA_EN;
		writel(temp, pcdev->base + CIM_CTRL);

		/* clear rx fifo */
		temp = readl(pcdev->base + CIM_CTRL);
		temp |= CIM_CTRL_RXF_RST;
		writel(temp, pcdev->base + CIM_CTRL);

		temp = readl(pcdev->base + CIM_CTRL);
		temp &= ~CIM_CTRL_RXF_RST;
		writel(temp, pcdev->base + CIM_CTRL);

		/* enable cim */
		temp = readl(pcdev->base + CIM_CTRL);
		temp |= CIM_CTRL_ENA;
		writel(temp, pcdev->base + CIM_CTRL);

		pcdev->is_first_start = 0;
	}

	jiff_temp = jiffies;
	poll_wait(file, &buf->vb.done, pt);

	if (buf->vb.state == VIDEOBUF_DONE ||
			buf->vb.state == VIDEOBUF_ERROR) {
		return POLLIN | POLLRDNORM;
	}

	return 0;
}
static int jz_camera_alloc_desc(struct jz_camera_dev *pcdev, struct v4l2_requestbuffers *p)
{
	struct jz_camera_dma_desc *dma_desc_paddr;
	struct jz_camera_dma_desc *dma_desc;

	pcdev->buf_cnt = p->count;
	pcdev->desc_vaddr = dma_alloc_coherent(pcdev->soc_host.v4l2_dev.dev,
			sizeof(*pcdev->dma_desc) * pcdev->buf_cnt,
			(dma_addr_t *)&pcdev->dma_desc, GFP_KERNEL);

	dma_desc_paddr = (struct jz_camera_dma_desc *) pcdev->dma_desc;
	dma_desc = (struct jz_camera_dma_desc *) pcdev->desc_vaddr;

#if 0
	int i = 0;
	printk("pcdev->desc_vaddr = 0x%p, pcdev->dma_desc = 0x%p\n",pcdev->desc_vaddr, (dma_addr_t *)pcdev->dma_desc);
	for(i = 0; i < pcdev->buf_cnt; i++){
		printk("pcdev->desc_vaddr[%d] = 0x%p\n", i, &dma_desc[i]);
	}
	for(i = 0; i < pcdev->buf_cnt; i++){
		printk("dma_desc_paddr[%d] = 0x%p\n", i, &dma_desc_paddr[i]);
	}
#endif

	if (!pcdev->dma_desc)
		return -ENOMEM;

	return 0;
}

static int jz_camera_reqbufs(struct soc_camera_device *icd, struct v4l2_requestbuffers *p) {
	int i;
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;

	for (i = 0; i < p->count; i++) {
		struct jz_buffer *buf = container_of(icd->vb_vidq.bufs[i],
				struct jz_buffer, vb);
		buf->inwork = 0;
		INIT_LIST_HEAD(&buf->vb.queue);
	}

	if(jz_camera_alloc_desc(pcdev, p))
		return -ENOMEM;

	return 0;
}
static int jz_videobuf_setup(struct videobuf_queue *vq, unsigned int *count,
		unsigned int *size) {
	struct soc_camera_device *icd = vq->priv_data;
	int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width,
			icd->current_fmt->host_fmt);

	if (bytes_per_line < 0)
		return bytes_per_line;

	*size = bytes_per_line * icd->user_height;

	if (!*count)
		*count = 32;

	if (*size * *count > MAX_VIDEO_MEM * 1024 * 1024)
		*count = (MAX_VIDEO_MEM * 1024 * 1024) / *size;

	dprintk(7, "count=%d, size=%d\n", *count, *size);

	return 0;
}

static void free_buffer(struct videobuf_queue *vq, struct jz_buffer *buf) {
	struct videobuf_buffer *vb = &buf->vb;
	struct soc_camera_device *icd = vq->priv_data;
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;

	BUG_ON(in_interrupt());

	dprintk(7, "%s (vb=0x%p) 0x%08lx %d\n", __func__,
			vb, vb->baddr, vb->bsize);
	/*
	 * This waits until this buffer is out of danger, i.e., until it is no
	 * longer in STATE_QUEUED or STATE_ACTIVE
	 */

	videobuf_waiton(vq, vb, 0, 0);
	videobuf_dma_contig_free(vq, vb);

	vb->state = VIDEOBUF_NEEDS_INIT;

	if(pcdev->poll_flag)
		pcdev->poll_flag = 0;

	if(pcdev->vb_address_flag)
		pcdev->vb_address_flag = 0;
}

static int jz_init_dma(struct videobuf_queue *vq, struct videobuf_buffer *vbuf) {
	struct soc_camera_device *icd = vq->priv_data;
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;
	struct jz_camera_dma_desc *dma_desc;
	dma_addr_t dma_address;

	dma_desc = (struct jz_camera_dma_desc *) pcdev->desc_vaddr;


	if (vbuf->memory == V4L2_MEMORY_USERPTR)
		dma_address = icd->vb_vidq.bufs[0]->baddr;
	else if(vbuf->memory == V4L2_MEMORY_MMAP)
		dma_address = videobuf_to_dma_contig(vbuf);

	if(!dma_address) {
		dprintk(3, "Failed to setup DMA address\n");
		return -ENOMEM;
	}

	dma_desc[vbuf->i].id = vbuf->i;

	if (vbuf->memory == V4L2_MEMORY_USERPTR)
		dma_desc[vbuf->i].buf = get_paddr(dma_address);
	else if (vbuf->memory == V4L2_MEMORY_MMAP)
		dma_desc[vbuf->i].buf = dma_address;

	if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_YUYV) {
		dma_desc[vbuf->i].cmd = icd->sizeimage >> 2 |
			CIM_CMD_EOFINT | CIM_CMD_OFRCV;
	}else if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_SBGGR8) {
		dma_desc[vbuf->i].cmd = icd->sizeimage >> 2 |
			CIM_CMD_EOFINT | CIM_CMD_OFRCV;
	} else {
		printk("current fourcc is not support, use default fourcc!\n");
		dma_desc[vbuf->i].cmd = (icd->sizeimage * 8 / 12) >> 2 |
			CIM_CMD_EOFINT | CIM_CMD_OFRCV;

		dma_desc[vbuf->i].cb_len = (icd->user_width >> 1) *
			(icd->user_height >> 1) >> 2;

		dma_desc[vbuf->i].cr_len = (icd->user_width >> 1) *
			(icd->user_height >> 1) >> 2;
	}

	if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_YUV420) {
		dma_desc[vbuf->i].cb_frame = dma_desc[vbuf->i].buf + icd->sizeimage * 8 / 12;
		dma_desc[vbuf->i].cr_frame = dma_desc[vbuf->i].cb_frame + (icd->sizeimage / 6);
	} else if(icd->current_fmt->host_fmt->fourcc == V4L2_PIX_FMT_JZ420B) {
		dma_desc[vbuf->i].cb_frame = dma_desc[vbuf->i].buf + icd->sizeimage;
		dma_desc[vbuf->i].cr_frame = dma_desc[vbuf->i].cb_frame + 64;
	}

	if(vbuf->i == 0) {
		pcdev->dma_desc_head = (struct jz_camera_dma_desc *)(pcdev->desc_vaddr);
	}

	if(vbuf->i == (pcdev->buf_cnt - 1)) {
		//dma_desc[vbuf->i].next = (dma_addr_t) (pcdev->dma_desc);
		dma_desc[vbuf->i].next = 0;
		dma_desc[vbuf->i].cmd |= CIM_CMD_STOP;
		dma_desc[vbuf->i].cmd &= (~CIM_CMD_EOFINT);

		pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc[vbuf->i]);
	} else {
		dma_desc[vbuf->i].next = (dma_addr_t) (&pcdev->dma_desc[vbuf->i + 1]);
	}

	dprintk(7, "cim dma desc[vbuf->i] address is: 0x%x\n", dma_desc[vbuf->i].buf);

	return 0;
}
static int jz_videobuf_prepare(struct videobuf_queue *vq,
		struct videobuf_buffer *vb, enum v4l2_field field)
{
	struct soc_camera_device *icd = vq->priv_data;
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;
	struct device *dev = pcdev->soc_host.v4l2_dev.dev;
	struct jz_buffer *buf = container_of(vb, struct jz_buffer, vb);
	int bytes_per_line = soc_mbus_bytes_per_line(icd->user_width, icd->current_fmt->host_fmt);
	int ret;

	if (bytes_per_line < 0)
		return bytes_per_line;

	dprintk(7, "%s (vb=0x%p) 0x%08lx %d\n", __func__,
			vb, vb->baddr, vb->bsize);

	/* Added list head initialization on alloc */
	WARN_ON(!list_empty(&vb->queue));

	BUG_ON(NULL == icd->current_fmt);

	/*
	 * I think, in buf_prepare you only have to protect global data,
	 * the actual buffer is yours
	 */
	buf->inwork = 1;

	if (buf->code != icd->current_fmt->code ||
			vb->width   != icd->user_width ||
			vb->height  != icd->user_height ||
			vb->field   != field) {
		buf->code	= icd->current_fmt->code;
		vb->width	= icd->user_width;
		vb->height	= icd->user_height;
		vb->field	= field;
		vb->state	= VIDEOBUF_NEEDS_INIT;
	}

	vb->size = bytes_per_line * vb->height;
	if (0 != vb->baddr && vb->bsize < vb->size) {
		ret = -EINVAL;
		goto out;
	}
	if (vb->state == VIDEOBUF_NEEDS_INIT) {
		jz_init_dma(vq, vb);
		if(ret) {
			dev_err(dev, "%s:DMA initialization for Y/RGB failed\n", __func__);
			goto fail;
		}
		vb->state = VIDEOBUF_PREPARED;
	}

	buf->inwork = 0;

	return 0;
fail:
	free_buffer(vq, buf);
out:
	buf->inwork = 0;
	return ret;
}

static void jz_videobuf_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
	struct soc_camera_device *icd = vq->priv_data;
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;
	struct jz_camera_dma_desc *dma_desc_vaddr;
	int i = 0;
	unsigned int regval = 0;
	struct jz_camera_dma_desc *dma_desc_paddr;

	dma_desc_vaddr = (struct jz_camera_dma_desc *) pcdev->desc_vaddr;

	vb->state = VIDEOBUF_ACTIVE;

	/* judged vb->i */
	if((vb->i > pcdev->buf_cnt) || (vb->i < 0)) {
		printk("Warning: %s, %d, vb->i > pcdev->buf_cnt || vb->i < 0, please check vb->i !!!\n",
				 __func__, vb->i);
		return;
	}

	/* set pcdev->vb_address */
	if(!pcdev->vb_address_flag) {
		pcdev->vb_address_flag = 1;
		for(i = 0; i < pcdev->buf_cnt; i++)
			pcdev->vb_address[i] = (struct  videobuf_buffer *)vq->bufs[i];
	}

	/* has select */
	if(pcdev->poll_flag) {
		if(pcdev->dma_desc_head != pcdev->dma_desc_tail) {
			dma_desc_vaddr[vb->i].cmd |= CIM_CMD_STOP;
			dma_desc_vaddr[vb->i].cmd &= (~CIM_CMD_EOFINT);

			pcdev->dma_desc_tail->next = (dma_addr_t) (&pcdev->dma_desc[vb->i]);
			pcdev->dma_desc_tail->cmd &= (~CIM_CMD_STOP);
			pcdev->dma_desc_tail->cmd |=  CIM_CMD_EOFINT;
			pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
		} else {
			if(is_cim_disabled(pcdev)) {
				dma_desc_vaddr[vb->i].cmd |= CIM_CMD_STOP;
				dma_desc_vaddr[vb->i].cmd &= (~CIM_CMD_EOFINT);

				pcdev->dma_desc_head = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
				pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);

				dma_desc_paddr = (struct jz_camera_dma_desc *) pcdev->dma_desc;

				/* Configure register CIMDA */
				regval = (unsigned int) (&dma_desc_paddr[vb->i]);
				writel(regval, pcdev->base + CIM_DA);

				/* clear state register */
				writel(0, pcdev->base + CIM_STATE);

				/* Reset RXFIFO */
				regval = readl(pcdev->base + CIM_CTRL);
				regval |= CIM_CTRL_DMA_EN | CIM_CTRL_RXF_RST;
				regval &= (~CIM_CTRL_ENA);
				writel(regval, pcdev->base + CIM_CTRL);

				/* stop resetting RXFIFO */
				regval = readl(pcdev->base + CIM_CTRL);
				regval |= CIM_CTRL_DMA_EN;
				regval &= ((~CIM_CTRL_RXF_RST) & (~CIM_CTRL_ENA));
				writel(regval, pcdev->base + CIM_CTRL);

				/* enable CIM */
				regval = readl(pcdev->base + CIM_CTRL);
				regval |= CIM_CTRL_DMA_EN | CIM_CTRL_ENA;
				regval &= (~CIM_CTRL_RXF_RST);
				writel(regval, pcdev->base + CIM_CTRL);
			} else {
				dma_desc_vaddr[vb->i].cmd &= (~CIM_CMD_EOFINT);
				dma_desc_vaddr[vb->i].cmd |= CIM_CMD_STOP;

				pcdev->dma_desc_tail->next = (dma_addr_t) (&pcdev->dma_desc[vb->i]);
				pcdev->dma_desc_tail->cmd &= (~CIM_CMD_STOP);
				pcdev->dma_desc_tail->cmd |= CIM_CMD_EOFINT;
				pcdev->dma_desc_tail = (struct jz_camera_dma_desc *)(&dma_desc_vaddr[vb->i]);
			}
		}
	}

}

static void jz_videobuf_release(struct videobuf_queue *vq,
		struct videobuf_buffer *vb) {

	struct jz_buffer *buf = container_of(vb, struct jz_buffer, vb);

	dprintk(7, "%s (vb=0x%p) 0x%08lx %d\n", __func__,
			vb, vb->baddr, vb->bsize);

	switch (vb->state) {
		case VIDEOBUF_ACTIVE:
			dprintk(7, "%s (active)\n", __func__);
			break;
		case VIDEOBUF_QUEUED:
			dprintk(7, "%s (queued)\n", __func__);
			break;
		case VIDEOBUF_PREPARED:
			dprintk(7, "%s (prepared)\n", __func__);
			break;

		case VIDEOBUF_DONE:
			dprintk(7, "%s (DONE)\n", __func__);
			break;
		case VIDEOBUF_IDLE:
			dprintk(7, "%s (IDLE)\n", __func__);
			break;

		case VIDEOBUF_ERROR:
			dprintk(7, "%s (ERROR)\n", __func__);
			break;
		case VIDEOBUF_NEEDS_INIT:
			dprintk(7, "%s (INIT)\n", __func__);
			break;
		default:
			dprintk(7, "%s (unknown)\n", __func__);
			break;
	}

	free_buffer(vq, buf);
}

static int test_platform_param(struct jz_camera_dev *pcdev,
			       unsigned char buswidth, unsigned long *flags)
{
	/*
	 * Platform specified synchronization and pixel clock polarities are
	 * only a recommendation and are only used during probing. The PXA270
	 * quick capture interface supports both.
	 */
	*flags = V4L2_MBUS_MASTER |
		V4L2_MBUS_HSYNC_ACTIVE_HIGH |
		V4L2_MBUS_HSYNC_ACTIVE_LOW |
		V4L2_MBUS_VSYNC_ACTIVE_HIGH |
		V4L2_MBUS_VSYNC_ACTIVE_LOW |
		V4L2_MBUS_DATA_ACTIVE_HIGH |
		V4L2_MBUS_PCLK_SAMPLE_RISING |
		V4L2_MBUS_PCLK_SAMPLE_FALLING;

	/* If requested data width is supported by the platform, use it */
	//if ((1 << (buswidth - 1)) & pcdev->width_flags)
	//	return 0;
	return 0;

//	return -EINVAL;
}
static struct videobuf_queue_ops jz_videobuf_ops = {
	.buf_setup      = jz_videobuf_setup,
	.buf_prepare    = jz_videobuf_prepare,
	.buf_queue      = jz_videobuf_queue,
	.buf_release    = jz_videobuf_release,
};
static void jz_camera_init_videobuf(struct videobuf_queue *q, struct soc_camera_device *icd) {
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;

	videobuf_queue_dma_contig_init(q, &jz_videobuf_ops, icd->parent,
			&pcdev->lock, V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_FIELD_NONE,
			sizeof(struct jz_buffer), icd, &ici->host_lock);
}

static int jz_camera_try_fmt(struct soc_camera_device *icd, struct v4l2_format *f) {
	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
	const struct soc_camera_format_xlate *xlate;
	struct v4l2_pix_format *pix = &f->fmt.pix;
	struct v4l2_mbus_framefmt mf;
	__u32 pixfmt = pix->pixelformat;
	int ret;
	/* TODO: limit to jz hardware capabilities */

	xlate = soc_camera_xlate_by_fourcc(icd, pix->pixelformat);
	if (!xlate) {
		printk("Format %x not found\n", pix->pixelformat);
		return -EINVAL;
	}

	v4l_bound_align_image(&pix->width, 48, 2048, 1,
			&pix->height, 32, 2048, 0,
			pixfmt == V4L2_PIX_FMT_YUV422P ? 4 : 0);


	mf.width	= pix->width;
	mf.height	= pix->height;
	mf.field	= pix->field;
	mf.colorspace	= pix->colorspace;
	mf.code		= xlate->code;


	/* limit to sensor capabilities */
	ret = v4l2_subdev_call(sd, video, try_mbus_fmt, &mf);
	if (ret < 0)
		return ret;

	pix->width	= mf.width;
	pix->height	= mf.height;
	pix->field	= mf.field;
	pix->colorspace	= mf.colorspace;

	return 0;
}

static int jz_camera_set_fmt(struct soc_camera_device *icd, struct v4l2_format *f) {
	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
	const struct soc_camera_format_xlate *xlate;
	struct v4l2_pix_format *pix = &f->fmt.pix;
	struct v4l2_mbus_framefmt mf;
	int ret, buswidth;
	xlate = soc_camera_xlate_by_fourcc(icd, pix->pixelformat);
	if (!xlate) {
		dprintk(4, "Format %x not found\n", pix->pixelformat);
		return -EINVAL;
	}

	buswidth = xlate->host_fmt->bits_per_sample;
	if (buswidth > 8) {
		dprintk(4, "bits-per-sample %d for format %x unsupported\n",
				buswidth, pix->pixelformat);
		return -EINVAL;
	}

	mf.width        = pix->width;
	mf.height       = pix->height;
	mf.field        = pix->field;
	mf.colorspace   = pix->colorspace;
	mf.code         = xlate->code;

	ret = v4l2_subdev_call(sd, video, s_mbus_fmt, &mf);
	if (ret < 0)
		return ret;

	if (mf.code != xlate->code)
		return -EINVAL;

	pix->width              = mf.width;
	pix->height             = mf.height;
	pix->field              = mf.field;
	pix->colorspace         = mf.colorspace;

	icd->current_fmt        = xlate;

	return ret;
}

static int jz_camera_set_crop(struct soc_camera_device *icd, const struct v4l2_crop *a) {
	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);

	return v4l2_subdev_call(sd, video, s_crop, a);
}

static int jz_camera_set_bus_param(struct soc_camera_device *icd) {
	struct v4l2_subdev *sd = soc_camera_to_subdev(icd);
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;
	struct v4l2_mbus_config cfg = {.type = V4L2_MBUS_PARALLEL,};
	u32 pixfmt = icd->current_fmt->host_fmt->fourcc;
	unsigned long common_flags;
	unsigned long bus_flags = 0;
	unsigned long cfg_reg = 0;
	unsigned long ctrl_reg = 0;
	unsigned long ctrl2_reg = 0;
	unsigned long fs_reg = 0;
	unsigned long temp = 0;
	int ret;

	ret = test_platform_param(pcdev, icd->current_fmt->host_fmt->bits_per_sample,
			&bus_flags);

	ret = v4l2_subdev_call(sd, video, g_mbus_config, &cfg);
	if (!ret) {
		common_flags = soc_mbus_config_compatible(&cfg,
				bus_flags);
		if (!common_flags) {
			dev_warn(icd->parent,
					"Flags incompatible: camera 0x%x, host 0x%lx\n",
					cfg.flags, bus_flags);
			return -EINVAL;
		}
	} else if (ret != -ENOIOCTLCMD) {
		return ret;
	} else {
		common_flags = bus_flags;
	}

	/* Make choises, based on platform preferences */

	if ((common_flags & V4L2_MBUS_VSYNC_ACTIVE_HIGH) &&
	    (common_flags & V4L2_MBUS_VSYNC_ACTIVE_LOW)) {
		if (pcdev->pdata->flags & JZ_CAMERA_VSYNC_HIGH)
		{
        		dev_warn(icd->parent, "================>V4L2_MBUS_VSYNC_ACTIVE_HIGH\n");
			common_flags &= ~V4L2_MBUS_VSYNC_ACTIVE_HIGH;
		}
		else
		{
            dev_warn(icd->parent, "================>V4L2_MBUS_VSYNC_ACTIVE_LOW\n");
			common_flags &= ~V4L2_MBUS_VSYNC_ACTIVE_LOW;
		}
	}
    else
    {
        dev_warn(icd->parent, "================>V4L2_MBUS_VSYNC_ACTIVE_NONE\n");
    }

	if ((common_flags & V4L2_MBUS_PCLK_SAMPLE_RISING) &&
	    (common_flags & V4L2_MBUS_PCLK_SAMPLE_FALLING)) {
		if (pcdev->pdata->flags & JZ_CAMERA_PCLK_RISING)
			common_flags &= ~V4L2_MBUS_PCLK_SAMPLE_FALLING;
		else
			common_flags &= ~V4L2_MBUS_PCLK_SAMPLE_RISING;
	}

	if ((common_flags & V4L2_MBUS_DATA_ACTIVE_HIGH) &&
	    (common_flags & V4L2_MBUS_DATA_ACTIVE_LOW)) {
		if (pcdev->pdata->flags & JZ_CAMERA_DATA_HIGH)
			common_flags &= ~V4L2_MBUS_DATA_ACTIVE_LOW;
		else
			common_flags &= ~V4L2_MBUS_DATA_ACTIVE_HIGH;
	}

	cfg.flags = common_flags;
	ret = v4l2_subdev_call(sd, video, s_mbus_config, &cfg);
	if (ret < 0 && ret != -ENOIOCTLCMD) {
		dev_dbg(icd->parent, "camera s_mbus_config(0x%lx) returned %d\n",
			common_flags, ret);
		return ret;
	}

	/*PCLK Polarity Set*/
	cfg_reg = (common_flags & V4L2_MBUS_PCLK_SAMPLE_RISING) ?
		cfg_reg | CIM_CFG_PCP_HIGH : cfg_reg & (~CIM_CFG_PCP_HIGH);

	/*VSYNC Polarity Set*/
	cfg_reg = (common_flags & V4L2_MBUS_VSYNC_ACTIVE_LOW) ?
		cfg_reg | CIM_CFG_VSP_HIGH : cfg_reg & (~CIM_CFG_VSP_HIGH);

    dev_warn(icd->parent, "================>vsync active %s\n", (cfg_reg&CIM_CFG_VSP_HIGH)?"falling":"rigsing");

	/*HSYNC Polarity Set*/
	cfg_reg = (common_flags & V4L2_MBUS_HSYNC_ACTIVE_LOW) ?
		cfg_reg | CIM_CFG_HSP_HIGH : cfg_reg & (~CIM_CFG_HSP_HIGH);

    dev_warn(icd->parent, "================>hsync active %s\n", (cfg_reg&CIM_CFG_HSP_HIGH)?"falling":"rigsing");

	cfg_reg |= CIM_CFG_DMA_BURST_INCR32 | CIM_CFG_DF_YUV422
		| CIM_CFG_DSM_GCM | CIM_CFG_PACK_Y0UY1V;

	ctrl_reg |= CIM_CTRL_DMA_SYNC | CIM_CTRL_FRC_1;

	ctrl2_reg |= CIM_CTRL2_APM | CIM_CTRL2_EME | CIM_CTRL2_OPE |
		(1 << CIM_CTRL2_OPG_BIT) | CIM_CTRL2_FSC | CIM_CTRL2_ARIF;

	fs_reg = (icd->user_width -1) << CIM_FS_FHS_BIT | (icd->user_height -1)
		<< CIM_FS_FVS_BIT | 1 << CIM_FS_BPP_BIT;

	if((pixfmt == V4L2_PIX_FMT_YUV420) || (pixfmt == V4L2_PIX_FMT_JZ420B)) {
		ctrl2_reg |= CIM_CTRL2_CSC_YUV420;
		cfg_reg |= CIM_CFG_SEP | CIM_CFG_ORDER_YUYV;
	}

	if(pixfmt == V4L2_PIX_FMT_JZ420B)
		ctrl_reg |= CIM_CTRL_MBEN;

	if(pixfmt == V4L2_PIX_FMT_SBGGR8) {
		fs_reg = (icd->user_width -1) << CIM_FS_FHS_BIT | (icd->user_height -1)
			<< CIM_FS_FVS_BIT | 0 << CIM_FS_BPP_BIT;
		ctrl2_reg |= CIM_CTRL2_CSC_BYPASS;
	}

	/*BS0 BS1 BS2 BS3 must be 00,01,02,03 when pack is b100*/

	if(cfg_reg & CIM_CFG_PACK_Y0UY1V)
		cfg_reg |= CIM_CFG_BS1_2_OBYT1 | CIM_CFG_BS2_2_OBYT2 | CIM_CFG_BS3_2_OBYT3;

	writel(cfg_reg, pcdev->base + CIM_CFG);
	writel(ctrl_reg, pcdev->base + CIM_CTRL);
	writel(ctrl2_reg, pcdev->base + CIM_CTRL2);
	writel(fs_reg, pcdev->base + CIM_FS);

#ifdef PRINT_CIM_REG
	cim_dump_reg(pcdev);
#endif
	/* enable end of frame interrupt */
	temp = readl(pcdev->base + CIM_IMR);
	temp &= (~CIM_IMR_EOFM);
	writel(temp, pcdev->base + CIM_IMR);

	/* enable stop of frame interrupt */
	temp = readl(pcdev->base + CIM_IMR);
	temp &= (~CIM_IMR_STPM);
	writel(temp, pcdev->base + CIM_IMR);

	/* enable rx overflow interrupt */
	temp = readl(pcdev->base + CIM_IMR);
	temp &= (~CIM_IMR_RFIFO_OFM);
	writel(temp, pcdev->base + CIM_IMR);

	temp = readl(pcdev->base + CIM_IMR);
	temp &= (~CIM_IMR_STPM_1);
	writel(temp, pcdev->base + CIM_IMR);

	return 0;
}
static void jz_camera_activate(struct jz_camera_dev *pcdev) {
	int ret = -1;


	dprintk(7, "Activate device\n");
	if(pcdev->clk) {
		ret = clk_enable(pcdev->clk);
	}
	if(pcdev->mclk) {
		ret = clk_set_rate(pcdev->mclk, pcdev->mclk_freq);
		ret = clk_enable(pcdev->mclk);
	}
	if(regul)
		regulator_enable(regul);
	if(ret) {
		printk("enable clock failed!\n");
	}

	msleep(10);
}
static void jz_camera_deactivate(struct jz_camera_dev *pcdev) {
	unsigned long temp = 0;

	if(pcdev->clk) {
		clk_disable(pcdev->clk);
	}
	if(pcdev->mclk) {
		clk_disable(pcdev->mclk);
	}
	if(regul)
		regulator_disable(regul);

	/* clear status register */
	writel(0, pcdev->base + CIM_STATE);

	/* disable end of frame interrupt */
	temp = readl(pcdev->base + CIM_IMR);
	temp |= CIM_IMR_EOFM;
	writel(temp, pcdev->base + CIM_IMR);

	/* disable rx overflow interrupt */
	temp = readl(pcdev->base + CIM_IMR);
	temp |= CIM_IMR_RFIFO_OFM;
	writel(temp, pcdev->base + CIM_IMR);

	/* disable dma */
	temp = readl(pcdev->base + CIM_CTRL);
	temp &= ~CIM_CTRL_DMA_EN;
	writel(temp, pcdev->base + CIM_CTRL);

	/* clear rx fifo */
	temp = readl(pcdev->base + CIM_CTRL);
	temp |= CIM_CTRL_RXF_RST;
	writel(temp, pcdev->base + CIM_CTRL);

	temp = readl(pcdev->base + CIM_CTRL);
	temp &= ~CIM_CTRL_RXF_RST;
	writel(temp, pcdev->base + CIM_CTRL);

	/* disable cim */
	temp = readl(pcdev->base + CIM_CTRL);
	temp &= ~CIM_CTRL_ENA;
	writel(temp, pcdev->base + CIM_CTRL);

	if(pcdev && pcdev->desc_vaddr) {
		dma_free_coherent(pcdev->soc_host.v4l2_dev.dev,
				sizeof(*pcdev->dma_desc) * pcdev->buf_cnt,
				pcdev->desc_vaddr, (dma_addr_t )pcdev->dma_desc);

		pcdev->desc_vaddr = NULL;
	}
	dprintk(7, "Deactivate device\n");
}

static int jz_camera_add_device(struct soc_camera_device *icd) {
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;

	int icd_index = icd->devnum;

	if (pcdev->icd[icd_index])
		return -EBUSY;

	printk("jz Camera driver attached to camera %d\n",
			icd->devnum);

	pcdev->icd[icd_index] = icd;
	pcdev->is_first_start = 1;

	/* disable tlb when open camera every time */
	pcdev->is_tlb_enabled = 0;

	jz_camera_activate(pcdev);

	return 0;
}
static void jz_camera_remove_device(struct soc_camera_device *icd) {
	struct soc_camera_host *ici = to_soc_camera_host(icd->parent);
	struct jz_camera_dev *pcdev = ici->priv;

	int icd_index = icd->devnum;

	BUG_ON(icd != pcdev->icd[icd_index]);

	jz_camera_deactivate(pcdev);
	dprintk(6, "jz Camera driver detached from camera %d\n",
			icd->devnum);

	pcdev->icd[icd_index] = NULL;
}

static void jz_camera_wakeup(struct jz_camera_dev *pcdev,
		struct videobuf_buffer *vb) {

	vb->state = VIDEOBUF_DONE;
	do_gettimeofday(&vb->ts);

	vb->field_count++;
	wake_up(&vb->done);

	dprintk(7, "after wake up cost %d ms\n", jiffies_to_msecs(jiffies - jiff_temp));
}

static irqreturn_t jz_camera_irq_handler(int irq, void *data) {
	struct jz_camera_dev *pcdev = (struct jz_camera_dev *)data;
	unsigned long status = 0, temp = 0;
	unsigned long flags = 0;
	int index = 0, regval = 0;
	struct jz_camera_dma_desc *dma_desc_paddr;
	//cim_dump_reg(pcdev);
	for (index = 0; index < ARRAY_SIZE(pcdev->icd); index++) {
		if (pcdev->icd[index]) {
			break;
		}
	}

	if(index == MAX_SOC_CAM_NUM)
		return IRQ_HANDLED;

	/* judged pcdev->dma_desc_head->id */
	if((pcdev->dma_desc_head->id > pcdev->buf_cnt) || (pcdev->dma_desc_head->id < 0)) {
		printk("Warning: %s, %d, pcdev->dma_desc_head->id >pcdev->buf_cnt || pcdev->dma_desc_head->id < 0, please check pcdev->dma_desc_head->id !!!\n",
				 __func__, pcdev->dma_desc_head->id);
		return IRQ_NONE;
	}

	spin_lock_irqsave(&pcdev->lock, flags);

	/* read interrupt status register */
	status = readl(pcdev->base + CIM_STATE);
	if (!status) {
		printk("status is NULL! \n");
		spin_unlock_irqrestore(&pcdev->lock, flags);

		return IRQ_NONE;
	}

	if(!(status & CIM_STATE_RXOF_STOP_EOF)) {
		/* other irq */
		printk("irq_handle status is 0x%lx, not judged in irq_handle\n", status);

		spin_unlock_irqrestore(&pcdev->lock, flags);
		return IRQ_HANDLED;
	}

	if (status & CIM_STATE_RXF_OF) {
		printk("RX FIFO OverFlow interrupt!\n");

		/* clear rx overflow interrupt */
		temp = readl(pcdev->base + CIM_STATE);
		temp &= ~CIM_STATE_RXF_OF;
		writel(temp, pcdev->base + CIM_STATE);

		/* disable cim */
		temp = readl(pcdev->base + CIM_CTRL);
		temp &= ~CIM_CTRL_ENA;
		writel(temp, pcdev->base + CIM_CTRL);

		/* clear rx fifo */
		temp = readl(pcdev->base + CIM_CTRL);
		temp |= CIM_CTRL_RXF_RST;
		writel(temp, pcdev->base + CIM_CTRL);

		temp = readl(pcdev->base + CIM_CTRL);
		temp &= ~CIM_CTRL_RXF_RST;
		writel(temp, pcdev->base + CIM_CTRL);

		/* clear status register */
		writel(0, pcdev->base + CIM_STATE);

		/* enable cim */
		temp = readl(pcdev->base + CIM_CTRL);
		temp |= CIM_CTRL_ENA;
		writel(temp, pcdev->base + CIM_CTRL);

		spin_unlock_irqrestore(&pcdev->lock, flags);
		return IRQ_HANDLED;
	}

	if(status & CIM_STATE_DMA_STOP) {
		/* clear dma interrupt status */
		temp = readl(pcdev->base + CIM_STATE);
		temp &= (~CIM_STATE_DMA_STOP);
		writel(temp, pcdev->base + CIM_STATE);

		jz_camera_wakeup(pcdev, (pcdev->vb_address[pcdev->dma_desc_head->id]));

		if(pcdev->dma_desc_head == pcdev->dma_desc_tail) {
			if(is_cim_enable(pcdev)) {
				cim_disable_without_dma(pcdev);
			} else {
				printk("@@@@@@ not complate!\n");
			}
		} else {
			pcdev->dma_desc_head =
				(struct jz_camera_dma_desc *)UNCAC_ADDR(phys_to_virt(pcdev->dma_desc_head->next));

			/* Configure register CIMDA */
			dma_desc_paddr = (struct jz_camera_dma_desc *) pcdev->dma_desc;
			regval = (unsigned int) (&dma_desc_paddr[pcdev->dma_desc_head->id]);
			writel(regval, pcdev->base + CIM_DA);
		}

		spin_unlock_irqrestore(&pcdev->lock, flags);

		return IRQ_HANDLED;
	}

	if(status & CIM_STATE_DMA_EOF) {
		/* clear dma interrupt status */
		temp = readl(pcdev->base + CIM_STATE);
		temp &= (~CIM_STATE_DMA_EOF);
		writel(temp, pcdev->base + CIM_STATE);

		jz_camera_wakeup(pcdev, (struct videobuf_buffer *)(pcdev->vb_address[pcdev->dma_desc_head->id]));
		if(pcdev->dma_desc_head != pcdev->dma_desc_tail) {
			pcdev->dma_desc_head =
				(struct jz_camera_dma_desc *)UNCAC_ADDR(phys_to_virt(pcdev->dma_desc_head->next));
		}

		spin_unlock_irqrestore(&pcdev->lock, flags);

		return IRQ_HANDLED;
	}
	spin_unlock_irqrestore(&pcdev->lock, flags);

	return IRQ_HANDLED;
}
/* initial camera sensor reset and power gpio */
static int camera_sensor_gpio_init(struct platform_device *pdev) {
	int ret, i, cnt = 0;
	struct jz_camera_pdata *pdata = pdev->dev.platform_data;
	char gpio_name[20];

	if(!pdata) {
		dev_err(&pdev->dev, "%s:have not cim platform data\n", __func__);
		return -1;
	}


	for (i = 0; i < ARRAY_SIZE(pdata->cam_sensor_pdata); i++) {
		if (pdata->cam_sensor_pdata[i].gpio_en){
			sprintf(gpio_name, "cim_enable%d", i);
			printk("cim_enable%d,%d\n", i,pdata->cam_sensor_pdata[i].gpio_rst);
			ret = gpio_request(pdata->cam_sensor_pdata[i].gpio_en, gpio_name);
			if (ret){
				dev_err(&pdev->dev, "%s:request cim%d vdd en gpio fail\n",
						__func__, i);
				goto err_request_gpio;
			}
			gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_en, 0);
		cnt++;
		}
	}
	for (i = 0; i < ARRAY_SIZE(pdata->cam_sensor_pdata); i++) {
		if(pdata->cam_sensor_pdata[i].gpio_rst) {
			sprintf(gpio_name, "sensor_rst%d", i);
			printk("sensor_rst%d,%d\n", i,pdata->cam_sensor_pdata[i].gpio_rst);
			ret = gpio_request(pdata->cam_sensor_pdata[i].gpio_rst,
					gpio_name);
			if(ret) {
				dev_err(&pdev->dev, "%s:request cim%d reset gpio fail\n",
						__func__, i);
				goto err_request_gpio;
			}
			gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_rst, 0);
			cnt++;
		}

		if(pdata->cam_sensor_pdata[i].gpio_power) {
			sprintf(gpio_name, "sensor_en%d", i);
			printk("sensor_en%d,%d\n", i,pdata->cam_sensor_pdata[i].gpio_power);
			ret = gpio_request(pdata->cam_sensor_pdata[i].gpio_power,
					gpio_name);
			if(ret) {
				dev_err(&pdev->dev, "%s:request cim%d en gpio fail\n",
						__func__, i);
				goto err_request_gpio;
			}
//			gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_power, 1);
			gpio_direction_output(pdata->cam_sensor_pdata[i].gpio_power, 0);
			cnt++;
		}
	}

	return 0;

err_request_gpio:
	for (i = 0; i < cnt / 2; i++) {
		gpio_free(pdata->cam_sensor_pdata[i].gpio_rst);
		gpio_free(pdata->cam_sensor_pdata[i].gpio_power);
	}

	if ((cnt % 2) != 0) {
		gpio_free(pdata->cam_sensor_pdata[i].gpio_rst);
	}

	return ret;
}

static struct soc_camera_host_ops jz_soc_camera_host_ops = {
	.owner = THIS_MODULE,
	.add = jz_camera_add_device,
	.remove = jz_camera_remove_device,
	.set_bus_param = jz_camera_set_bus_param,
	.set_crop = jz_camera_set_crop,
	.set_fmt = jz_camera_set_fmt,
	.try_fmt = jz_camera_try_fmt,
	.init_videobuf = jz_camera_init_videobuf,
	.reqbufs = jz_camera_reqbufs,
	.poll = jz_camera_poll,
	.querycap = jz_camera_querycap,
	//.num_controls = 0,
};

static int __init jz_camera_probe(struct platform_device *pdev) {
	int err = 0;
	unsigned int irq;
	struct resource *res;
	void __iomem *base;
	struct jz_camera_dev *pcdev;

	/* malloc */
	pcdev = kzalloc(sizeof(*pcdev), GFP_KERNEL);
	if (!pcdev) {
		dprintk(3, "Could not allocate pcdev\n");
		err = -ENOMEM;
		goto err_kzalloc;
	}

	/* resource */
	res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
	if(!res) {
		dprintk(3, "Could not get resource!\n");
		err = -ENODEV;
		goto err_get_resource;
	}

	/* irq */
	irq = platform_get_irq(pdev, 0);
	if (irq <= 0) {
		dprintk(3, "Could not get irq!\n");
		err = -ENODEV;
		goto err_get_irq;
	}
	/*get cim1 clk*/
	pcdev->clk = clk_get(&pdev->dev, "cim");
	if (IS_ERR(pcdev->clk)) {
		err = PTR_ERR(pcdev->clk);
		dev_err(&pdev->dev, "%s:can't get clk %s\n", __func__, "cim");
		goto err_clk_get_cim1;
	}

	/*get cgu_cimmclk1 clk*/
	pcdev->mclk = clk_get(&pdev->dev, "cgu_cim");
	if (IS_ERR(pcdev->mclk)) {
		err = PTR_ERR(pcdev->mclk);
		dev_err(&pdev->dev, "%s:can't get clk %s\n",
				__func__, "cgu_cimmclk");
		goto err_clk_get_cgu_cimmclk1;
	}

	regul = regulator_get(NULL, CAMERA_GSENSOR_VCC);
	if(IS_ERR(regul)) {
		dprintk(3, "get regulator fail !, if you need regulator, please check this place!\n");
		err = -ENODEV;
		regul = NULL;
//		goto exit_put_clk_cim;
	}else {
		regulator_enable(regul);
	}

	pcdev->pdata = pdev->dev.platform_data;
	if (pcdev->pdata)
		pcdev->mclk_freq = pcdev->pdata->mclk_10khz * 10000;

	if (!pcdev->mclk_freq) {
		dprintk(4, "mclk_10khz == 0! Please, fix your platform data."
				"Using default 24MHz\n");
		pcdev->mclk_freq = 24000000;
	}
	if (clk_get_rate(pcdev->mclk) >= pcdev->mclk_freq) {
		clk_set_rate(pcdev->mclk, pcdev->mclk_freq);
	} else {
		clk_set_rate(pcdev->mclk, pcdev->mclk_freq);
	}


	/* Request the regions. */
	if (!request_mem_region(res->start, resource_size(res), DRIVER_NAME)) {
		err = -EBUSY;
		goto err_request_mem_region;
	}
	base = ioremap(res->start, resource_size(res));
	if (!base) {
		err = -ENOMEM;
		goto err_ioremap;
	}

	spin_lock_init(&pcdev->lock);

	pcdev->res = res;
	pcdev->irq = irq;
	pcdev->base = base;

	/* request irq */
	err = request_irq(pcdev->irq, jz_camera_irq_handler, IRQF_DISABLED,
			dev_name(&pdev->dev), pcdev);
	if(err) {
		dprintk(3, "request irq failed!\n");
		goto err_request_irq;
	}

	/* request sensor reset and power gpio */
	err = camera_sensor_gpio_init(pdev);
	if(err) {
		dump_stack();
		goto err_camera_sensor_gpio_init;
	}

	pcdev->soc_host.drv_name        = DRIVER_NAME;
	pcdev->soc_host.ops             = &jz_soc_camera_host_ops;
	pcdev->soc_host.priv            = pcdev;
	pcdev->soc_host.v4l2_dev.dev    = &pdev->dev;
	//pcdev->soc_host.nr              = pdev->id;
	pcdev->soc_host.nr              = 0; /* use one cim0 or cim1 */
	pcdev->poll_flag		= 0;
	pcdev->vb_address_flag		= 0;

	err = soc_camera_host_register(&pcdev->soc_host);
	if (err)
		goto err_soc_camera_host_register;

	if (!IS_ERR(regul))
		    regulator_disable(regul);

	dprintk(6, "jz Camera driver loaded!\n");

	return 0;

err_soc_camera_host_register:
err_camera_sensor_gpio_init:
	free_irq(pcdev->irq, pcdev);
err_request_irq:
	iounmap(base);
err_ioremap:
	release_mem_region(res->start, resource_size(res));
err_request_mem_region:
	clk_put(pcdev->mclk);
err_clk_get_cgu_cimmclk1:
	clk_put(pcdev->clk);
err_clk_get_cim1:
err_get_irq:
err_get_resource:
	kfree(pcdev);
err_kzalloc:
	return err;

}

static int __exit jz_camera_remove(struct platform_device *pdev)
{
	struct soc_camera_host *soc_host = to_soc_camera_host(&pdev->dev);
	struct jz_camera_dev *pcdev = container_of(soc_host,
					struct jz_camera_dev, soc_host);
	struct resource *res;

	free_irq(pcdev->irq, pcdev);

	clk_put(pcdev->clk);
	clk_put(pcdev->mclk);

	soc_camera_host_unregister(soc_host);

	iounmap(pcdev->base);

	res = pcdev->res;
	release_mem_region(res->start, resource_size(res));

	kfree(pcdev);

	dprintk(6, "jz Camera driver unloaded\n");

	return 0;
}

static struct platform_driver jz_camera_driver = {
	.remove		= __exit_p(jz_camera_remove),
	.driver		= {
		.name	= DRIVER_NAME,
		.owner	= THIS_MODULE,
	},
};

static int __init jz_camera_init(void) {
	/*
	 * platform_driver_probe() can save memory,
	 * but this Driver can bind to one device only.
	 */
	return platform_driver_probe(&jz_camera_driver, jz_camera_probe);
}

static void __exit jz_camera_exit(void) {
	return platform_driver_unregister(&jz_camera_driver);
}

late_initcall(jz_camera_init);
module_exit(jz_camera_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("yefei <<EMAIL>>");
MODULE_DESCRIPTION("jz Soc Camera Host Driver");
MODULE_ALIAS("a jz-cim platform");
<file_sep>/work/test/fb_test/Makefile
GCC := mips-linux-gnu-gcc

CFLAGS := -EL -mabi=32 -mhard-float -march=mips32r2 -Os
LDFLAGS:= -Wl,-EL
LDLIBS :=

SOURCES := $(wildcard *.c)

TARGET = fb_test
all: $(TARGET)

$(TARGET): $(SOURCES)
	$(GCC) $(CFLAGS) $(LDFLAGS) -o $@ $^

.PHONY:install clean distclean
INSTALL_DIR := ~/work/mozart-new/mozart/rootfs/updater/usr/bin/
install:fb_test
	cp $(TARGET) $(INSTALL_DIR)

clean:
	rm $(TARGET) *.o -rf

distclean:
	rm $(TARGET) $(INSTALL_DIR)/$(TARGET) *.o -rf
<file_sep>/work/test/cim_test-zmm220/Makefile
#CC=gcc
#ifeq ($(MAKERULES),)
#include ../../Rules.make
#else
#include $(MAKERULES)
#endif
CC=mipsel-linux-gcc
#CC=arm-marvell-linux-gnueabi-gcc
#CFLAGS+=-Iinclude/ -DDEBUG_BUILD -DCONFIG_IPM \
	-I/home/work/300/rel/host/include\
	-g -Waggregate-return -Wmissing-noreturn -W -Wall -mcpu=iwmmxt -mtune=iwmmxt -mabi=aapcs-linux
#	-I/home/work/300/rel/host/include -L/home/work/300/rel/host/lib -L/home/work/300/rel/target/rootfs/lib -g -Waggregate-return -Wmissing-noreturn -W -Wall -mcpu=iwmmxt -mtune=iwmmxt -mabi=aapcs-linux
CFLAGS+=-O2 -W
#LFLAGS+= -I/opt/zem800/arm-marvell-linux-gnueabi/include -L/opt/zem800/arm-marvell-linux-gnueabi/lib -ljpeg
LFLAGS+= -ljpeg

.PHONY: all compile clean clean-local

all: compile

compile: cimtest 
	echo "built successfully"

OBJECTS=mt9v136.c cim.c gpio.c camera.c conver.c fvjpg.c futil.c yuv2jpg.c gc0308.c
cimtest:$(OBJECTS)
	$(CC) $(CFLAGS) $(LFLAGS) -o $@ $^

clean: clean-local

clean-local:
	-rm -f *.o  cimtest
<file_sep>/work/test/yuv2bmp/Makefile
LFLAGS =

yuv2bmp:
	gcc $(LFLAGS) -o yuv2bmp yuv2bmp.c

clean:
	rm -rf yuv2bmp *.o
<file_sep>/sys_program/2nd_day/pm/alarm.c
/* ************************************************************************
 *       Filename:  alarm.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 15时20分17秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>


int main(int argc, char *argv[])
{
	int ret = 0;
	ret = alarm(6);
	printf("ret 1 = %d\n",ret);

	sleep(4);

	ret = alarm(5);

	printf("ret 2 = %d\n",ret);

	while(1)
	{
		printf("alarm\n");
		sleep(1);
	}
	return 0;
}


<file_sep>/c/practice/3rd_week/encrypt/Makefile
encrypt:main.c encrypt.c
	gcc -o encrypt main.c encrypt.c

clean:
	rm encrypt
<file_sep>/c/practice/3rd_week/encrypt/encrypt.h
/* ************************************************************************
 *       Filename:  encrypt.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月30日 星期四 02時04分56秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __ENCRYPT_H__
#define __ENCRYPT_H__

void get_file_name(char * dest_file_name,char * src_file_name);
char * read_src_file(unsigned long int *file_length,char *src_file_name);
char * file_text_encrypt(char * src_file_text,unsigned long int length,unsigned int password);
char * file_text_decrypt(char * src_file_text,unsigned long int length,unsigned int password);
void save_file(char* text,unsigned long int length,char * file_name);

#endif

<file_sep>/network/route/src/inc/firewall_link.h
/******************************************************************************
  文 件 名   : firewall_link.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月13日
  最近修改   :
  功能描述   : firewall_link.c 的头文件
******************************************************************************/

#ifndef __FIREWALL_LINK_H__
#define __FIREWALL_LINK_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */

/*----------------------------------------------*
 * 函数原型说明                                 *
 *----------------------------------------------*/
extern FIRE_Wall *delete_firewall_node(FIRE_Wall *head, const char *rule);
extern FIRE_Wall *free_firewall_link(FIRE_Wall *head);
extern FIRE_Wall *insert_firewall_node(FIRE_Wall *head, FIRE_Wall node);
extern void print_firewall(FIRE_Wall *head);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */


#endif /* __FIREWALL_LINK_H__ */
<file_sep>/c/homework/1st_week/perversion.c
/* ************************************************************************
 *       Filename:  perversion.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月17日 星期五 06時34分20秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟
 *        Company:  
 * ************************************************************************/


#include <stdio.h>
#include <malloc.h>
#include <math.h>

#if 0
int main(int argc, char *argv[])
{
	int count = 0;
	int number = 0;
	int *buf = NULL;
	char i;

	printf("Please input a integer number:\n");
	scanf("%d",&number);

	count = printf("%d\n",number) - 1;
	//printf("count = %d\n",count);
	buf = (int *)malloc((sizeof(int) * count));

	perversion(number, buf, count);

	for(i=0;i<count;i++)
	{
		printf("%d",buf[i]);
	}
	putchar('\n');
	return 0;
}

void perversion(int number, int *buf, int count)
{
	int i;
	int divisor;

	for(i=count-1;i>=0;i--)
	{
		divisor = (int)pow(10,i);
		buf[i]  = number/divisor;
		number %= divisor;
	}
}
#else

void perversion(int number, char *buf, int count)
{
	int i;
	int divisor;

	for(i=count-1;i>=0;i--)
	{
		divisor = (int)pow(10,i);
		buf[i]  = number/divisor;
		number %= divisor;
	}
}

int main(int argc, char *argv[])
{
	int count = 0;
	int number = 0;
    char *buf = NULL;
	char i;

	printf("Please input a integer number:\n");
	scanf("%d",&number);

	#if 0 //三种方法计算 count 的值
 	count = printf("%d\n",number) - 1;
	#elif 1
	while((number/pow(10,count))>=1)
	{
		count++;
	}
	#else
	count =(int)log10(number) + 1;
	#endif

	//printf("count = %d\n",count);
	buf = (char *)malloc((sizeof(char) * count));

	if(count>1)
	{
		perversion(number, buf, count);
		for(i=0;i<count;i++)
		{
			printf("%d",buf[i]);
		}
		putchar('\n');
	}
	else
	{
		printf("%d\n",number);
	}

	free(buf);
	return 0;
}
#endif
<file_sep>/work/debug/pc/timer/timer_drv.c
/* ************************************************************************
 *       Filename:  timer.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月07日 19时28分40秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <linux/timer.h> /*包括timer.h头文件*/
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/miscdevice.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <asm/atomic.h>

#define DEVICE_NAME "timer_drv"

struct timer_dev
{
	struct cdev timer_cdev;	
	struct timer_list s_timer;
	atomic_t counter;
};

struct timer_dev *p_tdev = NULL;
//dev_t devno; //设备号
//static int majno = 0; //主设备号



//定时器到达expires 时间后，这个函数被调用
static void this_timer_handle(unsigned long arg) 
{
	mod_timer(&p_tdev->s_timer,jiffies + HZ); //更新定时器
	atomic_inc(&p_tdev->counter); //使counter自增
	printk(KERN_NOTICE "current jiffies is %ld\n",jiffies);
}

int this_timer_release(struct inode *inode, struct file *filp)
{
	del_timer(&p_tdev->s_timer);
	return 0;
}

static int timer_open(struct inode *inode, struct file *filp)
{
	//初始化定时器，主要对定时器的下一定时器的地址和此定时器所在结构体进行初始化
	init_timer(&p_tdev->s_timer);
	p_tdev->s_timer.function = this_timer_handle; //设置定时器超时后调度的超时处理函数
	//设置定时器超时的时间，jiffies为当前滴答数，HZ为一秒的滴答数
	p_tdev->s_timer.expires = jiffies + HZ;

	add_timer(&p_tdev->s_timer);    //把定时器添加到定时器链表中
	atomic_set(&p_tdev->counter,0); //计数清零

	return 0;
}

static ssize_t timer_read(struct file *filp,char __user *buf, size_t count,loff_t *ppos)
{
	int counter;
	counter = atomic_read(&p_tdev->counter); //
	if(put_user(counter,(int*)buf))
		return -EFAULT;
	else
		return(sizeof(unsigned int));
}

static struct file_operations timer_fops =
{
	.owner = THIS_MODULE,
	.open = timer_open,
	.read = timer_read,
	.release = this_timer_release,

};

static void timer_setup_cdev(struct timer_dev *dev, int index)
{
	int err;
	//dev_t devno = MKDEV(majno,0);

	cdev_init(&dev->timer_cdev,&timer_fops);
	dev->timer_cdev.owner = THIS_MODULE;
	dev->timer_cdev.ops = &timer_fops;

	//err = cdev_add(&dev->timer_cdev,devno,1);
	err = cdev_add(&dev->timer_cdev,10,1);

	if(err)
	{
		printk(KERN_NOTICE "Error %d adding timer %d",err,index);
	}
}

static struct miscdevice misc =
{
     .minor = MISC_DYNAMIC_MINOR, //表示动态分配次设备号
     .name = DEVICE_NAME,
     .fops = &timer_fops,
};

static int __init timerdrv_init(void)
{
	int ret;

	ret = misc_register(&misc);

	if(ret<0)
	{
        printk(KERN_INFO " can't register timer_drv\n");
        return ret;
	}

	p_tdev = kmalloc(sizeof(struct timer_dev), GFP_KERNEL);

	if(!p_tdev)
	{
		ret = -ENOMEM;
		goto fail_malloc;
	}

	memset(p_tdev, 0, sizeof(struct timer_dev));

	timer_setup_cdev(p_tdev,0);

	printk(KERN_INFO "timer_drv initialized\n");
    return 0;

	fail_malloc:
	misc_deregister(&misc);
	return -1;
}

static void __exit timerdrv_exit(void)
{
	cdev_del(&p_tdev->timer_cdev);//注销cdev
	kfree(p_tdev); //回收设备结构的内存

    misc_deregister(&misc);
    printk(KERN_INFO "timer_drv exited!\n");
}


#if 0
static void timer_setup_cdev(struct timer_dev *dev, int index)
{
	int err;
	dev_t devno = MKDEV(majno,0);

	cdev_init(&dev->timer_cdev,&timer_fops);
	dev->timer_cdev.owner = THIS_MODULE;
	dev->timer_cdev.ops = &timer_fops;

	err = cdev_add(&dev->timer_cdev,devno,1);

	if(err)
	{
		printk(KERN_NOTICE "Error %d adding timer %d",err,index);
	}
}

static int __init timerdev_init(void)
{
	int ret;

	dev_t devno = MKDEV(majno,0);

	if(!majno) //动态申请主设备号
	{
		ret = alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
		majno = MAJOR(devno);
	}
	else
	{
		ret = register_chrdev_region(devno,1,DEVICE_NAME);	
	}
	
	if(ret < 0) return ret;//失败
	
	
	p_tdev = kmalloc(sizeof(struct timer_dev), GFP_KERNEL);
	
	if(!p_tdev)
	{
		ret = -ENOMEM;
		goto fail_malloc;
	}
	
	memset(p_tdev, 0, sizeof(struct timer_dev));
	
	timer_setup_cdev(p_tdev,0);
	
	//注册一个类
	timer_class = class_create(THIS_MODULE, DEVICE_NAME);//要包含#include <linux/device.h>

	if(IS_ERR(timer_class))
	{
		printk("Err:failed in create leds class\n");
		goto fail_add_class;
	}
	//创建一个设备节点
	//device_create(timer_class, NULL, MKDEV(majno, 0), NULL, DEVICE_NAME);
	device_create(timer_class, NULL, devno, NULL, DEVICE_NAME);
	return 0;
	
	fail_malloc:
	unregister_chrdev_region(devno,1);
	return -1;
	
	fail_add_class:
	cdev_del(&p_tdev->timer_cdev);
	kfree(p_tdev);
	unregister_chrdev_region(devno,1);
	return -1;		
}
#endif

module_init(timerdrv_init);
module_exit(timerdrv_exit);

/* 描述驱动程序的一些信息，不是必须的 */
MODULE_AUTHOR("Dawei");                 // 驱动程序的作者
MODULE_DESCRIPTION("A Timer Driver");   // 一些描述信息
MODULE_LICENSE("GPL");                  // 遵循的协议
<file_sep>/sys_program/5th_day/cancel.c
/* ************************************************************************
 *       Filename:  cancel.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月19日 14时42分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_t pth1,pth2;

void up_fun1(void *arg)
{
	printf("push fun1\n");
}

void up_fun2(void *arg)
{
	printf("push fun2\n");
}
void up_fun3(void *arg)
{
	printf("push fun3\n");
}
void *fun1(void *arg)
{
	int i=0;

	//pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);

	pthread_cleanup_push(up_fun1,NULL);
	pthread_cleanup_push(up_fun2,NULL);
	pthread_cleanup_push(up_fun3,NULL);
	pthread_cleanup_pop(0);
	//for(i=0;i<20;i++)
	while(1)
	{
		printf("in pth1\n");
		sleep(1);
		//pthread_testcancel();//
		i++;
		if(i == 2)
		{
			return 0;
		}
	}

	pthread_cleanup_pop(0);
	pthread_cleanup_pop(1);

	return;
}

void *fun2(void *arg)
{
	int i=0;

	for(i=0;i<10;i++)
	{
		printf("in pth2\n");
		sleep(1);

		if(i==5)
		{
			pthread_exit(NULL);
		}

		if(i==2)
		{
			pthread_cancel(pth1);
		}
	}

	return;
}

int main(int argc, char *argv[])
{

	pthread_create(&pth1,NULL,fun1,NULL);
	//pthread_create(&pth2,NULL,fun2,NULL);

	sleep(5);
	pthread_cancel(pth1);

	pthread_join(pth1,NULL);
	//pthread_join(pth2,NULL);


	return 0;
}


<file_sep>/work/debug/a8/buttons/buttons_drv.c
#include <linux/module.h>	/* module_init */
#include <linux/fs.h>	/* file_operations */
#include <linux/device.h>	/* class device */
#include <asm/io.h>	/* writel() */
#include <plat/gpio-cfg.h>	/* s3c_gpio_cfgpin */
#include <mach/gpio.h>	/* gpio_set_value */
#include <linux/uaccess.h> /* copy_to_user() */
#include <linux/interrupt.h> /* request_irq() */
#include <linux/irq.h> /* IRQ_TYPE_EDGE_FALLING() */
#include <linux/delay.h> /* mdelay() */
#include <linux/kfifo.h> /* kfifo */
#include <linux/poll.h> /* poll */
#include <linux/kthread.h> /* kthread */
#include <linux/miscdevice.h> /* struct miscdevice */
#include <linux/cdev.h> /* cdev_init */
#include <linux/proc_fs.h>	/* proc_dir_entry */
#include <linux/platform_device.h> /* platform_driver_register() */
#include <linux/ioport.h>	/* resource */
#include <linux/input.h>
#include <linux/gpio_keys.h> 



#define DEVICE_NAME   "s5pv210_buttons"
#define DOWN          0    //按键按下
#define UP            1    //按键松开

#define GPH2_7  _IO('g',7)
#define GPH2_6	_IO('g',6)
#define GPH2_5	_IO('g',5)
#define GPH2_4	_IO('g',4)



static struct task_struct *kthread_ops = NULL;
static struct input_dev *input_buttons = NULL;
static struct workqueue_struct *buttons_workqueue = NULL;
static struct work_struct buttons_work;
static struct kfifo buttons_fifo;
static struct completion buttons_compet;
static struct timer_list buttons_timer;

static spinlock_t buttons_spinlock;
static atomic_t open_flag = ATOMIC_INIT(0);

struct gpio_buttons {
	u8 status; /* up=0, down=1 */
	u8 type;   /* short=0, long=1 */
	u32 code;
};

struct gpio_buttons button = {
	.status = 0,
	.type   = 0,
	.code   = 0,
};

static struct gpio_keys_platform_data *pbuttons = NULL;

static int nbuttons = 0; // 记录按键个数
static int key_id   = 0; // 记录哪个按键被按下


static struct gpio_keys_button s5pv210_gpio_buttons[] = {
	// KEY2
	{
		.code    = KEY_UP,
		.gpio    = S5PV210_GPH2(3),
		.desc    = "key-up",
		.type    = EV_KEY,
	},
	// KEY4
	{
		.code    = KEY_DOWN,
		.gpio    = S5PV210_GPH2(5),
		.desc    = "key-down",
		.type    = EV_KEY,
	},
	// KEY6
	{
		.code    = KEY_LEFT,
		.gpio    = S5PV210_GPH2(7),
		.desc    = "key-left",
		.type    = EV_KEY,
	},
	// KEY5
	{
		.code    = KEY_RIGHT,
		.gpio    = S5PV210_GPH2(6),
		.desc    = "key-right",
		.type    = EV_KEY,
	},
};

static struct resource s5pv210_gpio_resource[] = {
	[0] = {
		.start = S5PV210_GPH3(0),
		.end = S5PV210_GPH3(0),
		.name = "GPH3_0",
		.flags = IORESOURCE_IO,
	},
	[1] = {
		.start = S5PV210_GPH0(3),
		.end = S5PV210_GPH0(3),
		.name = "GPH0_3",
		.flags = IORESOURCE_IO,
	}
};

static struct gpio_keys_platform_data s5pv210_buttons_info = {
	.buttons  = s5pv210_gpio_buttons,
	.nbuttons = ARRAY_SIZE(s5pv210_gpio_buttons),
};


static void	s5pv210_buttons_release(struct device *pdev)
{
	printk(KERN_WARNING "%s\n",__FUNCTION__);
	return;
}


static struct platform_device s5pv210_buttons_dev = {
	.name  = "s5pv210_buttons",
	.id    = -1,
	.num_resources = ARRAY_SIZE(s5pv210_gpio_resource),
	.resource = s5pv210_gpio_resource,
	.dev = {
		.platform_data = &s5pv210_buttons_info,
		.release       = s5pv210_buttons_release,
	},
};

static int input_buttons_open(struct input_dev *dev)
{
	int i;
	printk(KERN_WARNING "%s\n",__FUNCTION__);

	if(atomic_read(&open_flag) == 0){
		for(i=0;i<nbuttons;i++)
			enable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
	}
	atomic_inc(&open_flag);
	return 0;
}

static void input_buttons_close(struct input_dev *dev)
{
	int i;
	printk(KERN_WARNING "%s\n",__FUNCTION__);
	del_timer_sync(&buttons_timer);

	atomic_dec(&open_flag);
	if(atomic_read(&open_flag) == 0){
		for(i=0;i<nbuttons;i++)
			disable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
	}
}

static void buttons_timerhandler(unsigned long data)
{
	int ret = 0;
	unsigned long irqflag;

	printk(KERN_WARNING "[msg]:  %s\n",__FUNCTION__);
	spin_lock_irqsave(&buttons_spinlock, irqflag);
	button.type = 1;	 // 等0，表示短按，等1，表示长按
	ret = kfifo_in(&buttons_fifo,&button, sizeof(button));
	spin_unlock_irqrestore(&buttons_spinlock, irqflag);

	if(ret != sizeof(button))
		printk(KERN_WARNING "kfifo_in fail!\n");

	mod_timer(&buttons_timer,jiffies+20);/* 5ms*20=100ms */
}

static void buttons_workhandler(struct work_struct *work)
{
	int ret;
	unsigned long irqflag;

	if(button.status == 0){
		s3c_gpio_cfgpin(pbuttons->buttons[key_id].gpio, S3C_GPIO_INPUT);	// 配置引脚为输入，S3C_GPIO_INPUT 可以替换成S3C_GPIO_SFN(0x1)
		mdelay(30);	// 延时消抖
		ret = gpio_get_value(pbuttons->buttons[key_id].gpio);
		s3c_gpio_cfgpin(pbuttons->buttons[key_id].gpio, S3C_GPIO_SFN(0xf)); // S3C_GPIO_SFN(0xf)复用功能选择，0xf对应引脚中断功能,

		if( ret != 0)
			return;
		if(kfifo_is_full(&buttons_fifo))
			return;

		spin_lock_irqsave(&buttons_spinlock, irqflag);
		button.status = 1;
		button.type = 0;	 // 等0，表示短按，等1，表示长按
		button.code = pbuttons->buttons[key_id].code;
		kfifo_in(&buttons_fifo,&button, sizeof(button));
		spin_unlock_irqrestore(&buttons_spinlock, irqflag);

		if(!timer_pending(&buttons_timer)){	      // 查看定时器是否正被调度
			buttons_timer.expires = jiffies+1*HZ; // 设置定时器的定时时间为1秒
			add_timer(&buttons_timer);	          // 注册定时器
		}
	}
	else { // 按键抬起 不用去抖动
		del_timer_sync(&buttons_timer); // 删除定时器，在定时器时间到前停止一个已注册的定时器

		if(kfifo_is_full(&buttons_fifo))
			return;

		spin_lock_irqsave(&buttons_spinlock, irqflag);
		button.status = 0;
		button.code = pbuttons->buttons[key_id].code;
		kfifo_in(&buttons_fifo,&button, sizeof(button));
		spin_unlock_irqrestore(&buttons_spinlock, irqflag);
	}

}

static irqreturn_t s5pv210_buttons_irqhandler(int irq, void *dev_id)
{
	//printk(KERN_WARNING "%s\n",__FUNCTION__);

	key_id = (int)dev_id;
	queue_work(buttons_workqueue, &buttons_work);

	return IRQ_HANDLED;
}

static int kthread_ops_buttons(void *data)
{
	int ret;
	unsigned long irqflag;
	struct gpio_buttons buttons_read;

	for(;;)
	{
		if(kthread_should_stop()) break; // 是否终止
		if(!kfifo_is_empty(&buttons_fifo)){
			spin_lock_irqsave(&buttons_spinlock, irqflag);
			ret = kfifo_out(&buttons_fifo, &buttons_read, sizeof(buttons_read));
			spin_unlock_irqrestore(&buttons_spinlock, irqflag);

			if(ret == sizeof(buttons_read)){
				input_report_key(input_buttons, buttons_read.code, buttons_read.status); //
				input_sync(input_buttons);
				//printk(KERN_WARNING "%s\n",__FUNCTION__);
			}
		}
		schedule_timeout(HZ); // 让出CPU，并告诉内核不要超过HZ时间不调‘我’
	}
	complete_and_exit(&buttons_compet, 0);
	return 0;
}


static __devinit int s5pv210_buttons_probe(struct platform_device *pdev)
{
	int ret, i;

	printk(KERN_WARNING "%s\n",__FUNCTION__);

	// 初始化按键公共端接口输出低电平
	s3c_gpio_cfgpin(pdev->resource[0].start, S3C_GPIO_OUTPUT);
	gpio_set_value(pdev->resource[0].start, 0);

	ret = kfifo_alloc(&buttons_fifo, 128, GFP_KERNEL);
	if(ret)  goto out;

	buttons_workqueue = create_workqueue("buttons_workqueue");	// 创建工作队列
	INIT_WORK(&buttons_work,buttons_workhandler); // 初始化工作(工作和工作函数建立关联)

	spin_lock_init(&buttons_spinlock); // 初始化自旋锁
	init_timer(&buttons_timer);
	buttons_timer.data = 0;	 // 设置传给回调函数的参数为0
	buttons_timer.function = buttons_timerhandler; // 设置定时器到时回调函数

	pbuttons = pdev->dev.platform_data;
	nbuttons = pbuttons->nbuttons; // 获取按键个数

	for(i=0;i<nbuttons;i++){

		s3c_gpio_setpull(pbuttons->buttons[i].gpio, S3C_GPIO_PULL_UP); // 设置引脚上拉使能

		// 注册中断
		ret = request_irq(gpio_to_irq(pbuttons->buttons[i].gpio), s5pv210_buttons_irqhandler,\
						 IRQ_TYPE_EDGE_BOTH, pbuttons->buttons[i].desc, (void *)i);
		disable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
		if(ret){       //返回非0，中断申请失败
			while(i--) //释放注册成功的中断
				free_irq(gpio_to_irq(pbuttons->buttons[i].gpio), (void *)i);
			goto request_irq_err;
		}
	}

	//input 子系统
	input_buttons = input_allocate_device(); // 给input设备分配空间
	if(IS_ERR(input_buttons)){
		ret = PTR_ERR(input_buttons);
		goto input_allocate_err;
	}
	input_buttons->name = DEVICE_NAME;
	input_buttons->phys = "inputkey";
	input_buttons->id.bustype = BUS_HOST;
	input_buttons->id.vendor = 0x0001;
	input_buttons->evbit[0] = BIT(EV_KEY)|BIT(EV_REP)|BIT(EV_SYN); // 支持事件类型: 按键+重复按键+同步事件
	for(i=0;i<nbuttons;i++){
		set_bit(pbuttons->buttons[i].type, input_buttons->evbit);
		set_bit(pbuttons->buttons[i].code, input_buttons->keybit);
		//input_buttons->keybit[BIT_WORD(pbuttons->buttons[i].code)] |= BIT_MASK(pbuttons->buttons[i].code);
	}
	input_buttons->open  = input_buttons_open;  // 在input_register_device成功后被调用
	input_buttons->close = input_buttons_close; // 在input_unregister_device成功后被调用

	ret = input_register_device(input_buttons); // 注册input子系统
	if(ret) goto input_register_err;

	// completion是一种轻量级的机制，它允许一个线程告诉另一个线程工作已经完成
	init_completion(&buttons_compet);// 可以利用宏静态创建completion: DECLARE_COMPLETION(my_completion);

	// 创建内核线程
	kthread_ops = kthread_create(kthread_ops_buttons, NULL, "buttons_ops");
	if(IS_ERR(kthread_ops)){
		complete(&buttons_compet);
		ret = PTR_ERR(kthread_ops);
		goto kthread_create_err;
	}
	wake_up_process(kthread_ops); // 启动内核进程

	printk(KERN_WARNING "%s\n",__FUNCTION__);
	return 0;

	// 出错退出处理
	kthread_create_err:
	input_unregister_device(input_buttons);

	input_register_err:
	input_free_device(input_buttons);

	input_allocate_err:
	for(i=0; i<nbuttons; i++){
		free_irq(gpio_to_irq(pbuttons->buttons[i].gpio), (void *)i);
	}
	request_irq_err:
	destroy_workqueue(buttons_workqueue);
	out:
	kfifo_free(&buttons_fifo);
	return ret;
}

static __devexit int s5pv210_buttons_remove(struct platform_device *pdev)
{
	int i;
	kthread_stop(kthread_ops);
	wait_for_completion(&buttons_compet);
	destroy_workqueue(buttons_workqueue);
	input_unregister_device(input_buttons);
	input_free_device(input_buttons);
	kfifo_free(&buttons_fifo);

	for(i=0; i<nbuttons; i++){
		disable_irq(gpio_to_irq(pbuttons->buttons[i].gpio));
		free_irq(gpio_to_irq(pbuttons->buttons[i].gpio), (void *)i);
	}

	printk(KERN_WARNING "%s\n",__FUNCTION__);
	return 0;
}

static struct platform_driver s5pv210_buttons_drv = {
	.probe  = s5pv210_buttons_probe,  // 匹配后的回调函数
	.remove = s5pv210_buttons_remove, // 在设备注销时或是驱动注销时调用
	.driver = {
		.owner = THIS_MODULE,
		.name  = "s5pv210_buttons",
	},
};

static __init int s5pv210_buttons_driver_init(void)
{
	int ret;

	ret = platform_device_register(&s5pv210_buttons_dev);
	if(ret){
		printk(KERN_ERR "%s: register device failed\n", __FUNCTION__);
		goto fail0;
	}

	ret = platform_driver_register(&s5pv210_buttons_drv);
	if(ret){
		printk(KERN_ERR "%s: register driver failed\n", __FUNCTION__);
		goto fail1;
	}

	return 0;
	fail1:
	platform_device_unregister(&s5pv210_buttons_dev);
	fail0:
	return ret;
}

static __exit void s5pv210_buttons_driver_exit(void)
{
	platform_driver_unregister(&s5pv210_buttons_drv);
	platform_device_unregister(&s5pv210_buttons_dev);
	printk(KERN_WARNING "%s\n",__FUNCTION__);
	return;
}

module_init(s5pv210_buttons_driver_init);
module_exit(s5pv210_buttons_driver_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/test.c
/* ************************************************************************
 *       Filename:  test.c
 *    Description:
 *        Version:  1.0
 *        Created:  12/03/2015 04:55:09 PM
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  <NAME> (),
 *        Company:
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>


#if 1

int main(int argc, char argv[])
{
    unsigned long length = 0;
    FILE *fp = NULL;
    char *buf = NULL;

    fp = fopen("./qrcode_app", "rb+");
    if(fp==NULL) {
        printf("Cannot open the file\n");
        return -1;
    }

    fseek(fp, 0, SEEK_END);
    length = ftell(fp);

    printf("file length: %lu\n", length);
    fseek(fp, 0, SEEK_SET);
    fwrite(&length, sizeof(length), 1, fp);

    unsigned long r_len = 0;
    fseek(fp, 0, SEEK_SET);
    fread(&r_len, sizeof(length), 1, fp);
    printf("read length: %lu\n", r_len);

    fclose(fp);
    return 0;
}
#elif 0
int test(char *src, char *dst)
{
    if (src == NULL || dst == NULL)
        return -1;
    int count = 0;
    char *p=NULL;
    p = strtok(src, dst);
    while(p != NULL) {
        count++;
        p = strtok(NULL, src);
    }

    return count;
}

void main()
{
    char *src = "dd23kjdi32kkj23,  423";
    char *buf = src;
    char *dst = "23";
    int count = 0;
    char *p[100];

    printf("src=%s, dst=%s\n", src, dst);
    printf("count=%d\n", count);
    //p[count] = strtok(buf, dst);
    while((p[count] = strtok(buf, "23")) != NULL) {
        count++;
        //p[count] = strtok(buf, dst);
    }
    printf("count=%d\n", count);
}
#elif 0
#include <pwd.h>
static void do_sth(int cnt)
{
    printf("This is a test program: %d!\n", cnt);
}

static void dump_compile_info(void)
{
	time_t timep;
	struct passwd *pwd;
	char hostname[16] = "Unknown";

	time(&timep);
	pwd = getpwuid(getuid());
	gethostname(hostname, 16);
	printf("mozart compiled at %s on %s@%s\n", asctime(gmtime(&timep)), pwd->pw_name, hostname);
}

int main(int argc, char *argv[])
{
    int cnt = 0;
    daemon(0, 1);
    while(1) {
        do_sth(cnt);
        cnt++;
        sleep(1);
        if (cnt > 20)
            break;
    }

    dump_compile_info();
    return 0;
}
#elif 0
struct cim_framebuf {
	unsigned char id;
	unsigned char busy;
	unsigned char *pfree;
	unsigned char *vaddr;
	unsigned char *paddr;
	struct cim_framebuf *next;
};

struct jz_cim_dev {
	unsigned int nbuf;
	unsigned int frame_size;
	unsigned char read_flag;
	unsigned char dma_started;
	struct cim_framebuf *framebuf_head;
	struct cim_framebuf *framebuf_index;
};

struct jz_cim_dev *cim = NULL;

static struct cim_framebuf *cim_insert_link(struct cim_framebuf *head, struct cim_framebuf *in)
{
	struct cim_framebuf *pi, *pb;

	if(in != NULL) {
		pi = in;

		if(head == NULL) {
			head = pi;
			head->next = head;
		} else {
			pb = head;

			while(pb->next != head)
				pb = pb->next;

			pi->next = head;
			pb->next = pi;
		}
	}

	return head;
}

static struct cim_framebuf *cim_free_link(struct cim_framebuf *head)
{
	struct cim_framebuf *pb, *pn;

	if(head != NULL) {
		pb = head;
		pn = head->next;

		while(pn != head) {
			free(pb->pfree);
			free(pb);

			pb = pn;
			pn = pn->next;
		}

		/* Last node */
		free(pb->pfree);
		free(pb);
	}

	return NULL;
}

void cim_print_link(struct cim_framebuf *head)
{
	struct cim_framebuf *pb;
	if(head != NULL) {
		pb = head;
		printf("pb->id = %d\n", pb->id);
		printf("cim->framebuf vaddr = 0x%08x\n", pb->vaddr);
		printf("cim->framebuf paddr = 0x%08x\n", pb->paddr);

		while(pb->next != head) {
			pb = pb->next;
			printf("pb->id = %d\n", pb->id);
			printf("cim->framebuf vaddr = 0x%08x\n", pb->vaddr);
			printf("cim->framebuf paddr = 0x%08x\n", pb->paddr);
		}
	}
}

static int cim_fb_malloc(struct jz_cim_dev *cim)
{
	int i;
	struct cim_framebuf *in;

	for(i = 0; i < cim->nbuf; i++) {
		in = (struct cim_framebuf *)malloc(sizeof(struct cim_framebuf));
		if(!in) {
			printf("Can nor apply a framebuf memory space!\n");
			return -1;
		}

		in->vaddr = (unsigned char *)malloc(cim->frame_size + 0x3f);
		if(!in->vaddr) {
			printf("malloc framebuf failed\n");
			return -1;
		}

		memset(in->vaddr, 0, cim->frame_size);
		in->id = i;
		in->pfree = in->vaddr;
		in->paddr = in->vaddr + 0x01;

		printf("cim->framebuf vaddr = 0x%08x\n", in->vaddr);
		printf("cim->framebuf paddr = 0x%08x\n", in->paddr);
		cim->framebuf_head = cim_insert_link(cim->framebuf_head, in);
	}

	cim->framebuf_index = cim->framebuf_head;

	return 0;
}

static void cim_fb_free(struct jz_cim_dev *cim)
{
	cim->framebuf_head = cim_free_link(cim->framebuf_head);
}

int main(int argc, char *argv[])
{
	int count;
	cim = (struct jz_cim_dev *)malloc(sizeof(struct jz_cim_dev));
	if(!cim) {
		printf("%s -- malloc cim dev failed\n", __FUNCTION__);
		return -1;
	}

	memset(cim, 0, sizeof(struct jz_cim_dev));

	cim->nbuf = 1;
	cim->frame_size = 640 * 480 * 2;

	cim_fb_malloc(cim);

	count = 4;
	while(count--)
		cim_print_link(cim->framebuf_head);

	cim->nbuf = 3;
	cim_fb_free(cim);
	cim_fb_malloc(cim);
	printf("====================================\n");
	count = 25;
	while(count--) {
		printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n");
		printf("cim framebuf id = %d\n", cim->framebuf_index->id);
		printf("cim->framebuf vaddr = 0x%08x\n", cim->framebuf_index->vaddr);
		printf("cim->framebuf paddr = 0x%08x\n", cim->framebuf_index->paddr);
		cim->framebuf_index = cim->framebuf_index->next;
		printf("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&\n");
	}

	return 0;
}
#elif 0

struct img_param_t {
	unsigned int width;      /* width */
	unsigned int height;     /* height */
	unsigned int bpp;        /* bits per pixel: 8/16/32 */
};

struct timing_param_t {
	unsigned long mclk_freq;
	unsigned int pclk_active_level;  //0 for rising edge, 1 for falling edge
	unsigned int hsync_active_level;
	unsigned int vsync_active_level;
};

struct pix_buffer_t {
	int read_flag;
	void *pbuf;              /* point to a frame_size buffer */
};

struct get_frame_t {
	unsigned int nbuf;       /* buffer number */
	unsigned int frame_size; /* frame image size */
	struct pix_buffer_t pix[0];
};

struct jz_cim_dev {
    unsigned int frame_size;
    unsigned char read_flag;
    unsigned char dma_started;
    unsigned char *pframebuf;
    unsigned char *framebuf_vaddr;
    unsigned char *framebuf_paddr;
    void *desc_vaddr;
    struct cim_dma_desc *dma_desc_paddr;
    struct img_param_t img;
    struct timing_param_t timing;
    struct get_frame_t *frame;
};

int main(int argc, char *argv[])
{

    printf("sizeof(long) = %lu\n", sizeof(long));
    printf("sizeof(void *) = %lu\n", sizeof(void *));
    printf("sizeof(struct img_param_t) = %lu\n", sizeof(struct img_param_t));
    printf("sizeof(struct timing_param_t) = %lu\n", sizeof(struct timing_param_t));
    printf("sizeof(struct pix_buffer_t) = %lu\n", sizeof(struct pix_buffer_t));
    printf("sizeof(struct get_frame_t) = %lu\n", sizeof(struct get_frame_t));
    printf("sizeof(struct jz_cim_dev) = %lu\n", sizeof(struct jz_cim_dev));

    return 0;
}

#elif 0
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
typedef unsigned char u8;
typedef unsigned long u32;

struct regval_list {
	u8 reg_num;
	u8 value;
};

struct mode_list {
	u8 index;
	const struct regval_list *mode_regs;
};

/* Supported resolutions */
enum gc2155_width {
	W_QVGA	= 320,
	W_VGA	= 640,
	W_720P  = 1280,
};

enum gc2155_height {
	H_QVGA	= 240,
	H_VGA	= 480,
	H_720P  = 720,
};

struct gc2155_win_size {
	char *name;
	enum gc2155_width width;
	enum gc2155_height height;
	const struct regval_list *regs;
};

#define GC2155_SIZE(n, w, h, r) \
	{.name = n, .width = w , .height = h, .regs = r }

static const struct gc2155_win_size gc2155_supported_win_sizes[] = {
	GC2155_SIZE("QVGA", W_QVGA, H_QVGA, NULL),
	GC2155_SIZE("VGA", W_VGA, H_VGA, NULL),
	GC2155_SIZE("720P", W_720P, H_720P, NULL),
};

/* Select the nearest higher resolution for capture */
static const struct gc2155_win_size *gc2155_select_win(u32 *width, u32 *height)
{
	int i, default_size = ARRAY_SIZE(gc2155_supported_win_sizes);

	for (i = 0; i < default_size; i++) {
		if (gc2155_supported_win_sizes[i].width  >= *width &&
		    gc2155_supported_win_sizes[i].height >= *height) {
			*width = gc2155_supported_win_sizes[i].width;
			*height = gc2155_supported_win_sizes[i].height;
			return &gc2155_supported_win_sizes[i];
		}
	}

	*width = gc2155_supported_win_sizes[default_size-1].width;
	*height = gc2155_supported_win_sizes[default_size-1].height;
	return &gc2155_supported_win_sizes[default_size-1];
}

void fun1(int val)
{
	printf("val = %d\n", val);
	val = val + 100;

	printf("val = %d\n", val);

	if(val)
		goto error;

error:
	printf("%s: Error\n", __FUNCTION__);

}
void fun2(int val)
{
	if(val)
		goto error;

error:
	printf("%s: Error\n", __FUNCTION__);

}

void main(void)
{
	u32 width = 340, height = 500;

	struct gc2155_win_size *win = NULL;

	win = (struct gc2155_win_size *)malloc(sizeof(struct gc2155_win_size));

	//win->width = 320;
	//win->height = 240;

	printf("win->width: %d  win->height: %d\n", win->width, win->height);
	win = gc2155_select_win(&width, &height);
	printf("width: %d  height: %d\n", width, height);
	printf("win->width: %d  win->height: %d\n", win->width, win->height);
	fun1(1);
	fun2(2);
}
#elif 0
int main()
{
    int i;
    int val = 0x12345678;
    char buf[4] = "";

    *(int *)buf = val;

    for(i = 0; i <4; i++) {
        printf("buf[%d] = %d\n", i, buf[i]);
    }
}

#elif 0
int main(int argc, char *argv[])
{
	unsigned int val = 0;
	printf("## argc[1] = %s\n", argv[1]);

	val = atoi(argv[1]);
	printf("## atoi(): val = 0x%08x \n",val);

	sscanf(argv[1],"%x", &val);
	printf("## sscanf(): val = 0x%08x \n", val);
	return 0;
}
#elif 0
int main(int argc, char *argv[])
{
	int opt;
	int option_index = 0;
	char *optstring = "a:b:c:d";

	static struct option long_options[] = {
		{"reqarg", required_argument, NULL, 'r'},
		{"nonarg",no_argument, NULL, 'n'},
		{"optarg", optional_argument, NULL, 'o'},
		{0,0,0,0},
	};

	while((opt = getopt_long(argc, argv, optstring, long_options, &option_index)) != -1) {
		printf("opt = %c\n", opt);
		printf("optarg = %s\n", optarg);
		printf("optind = %d\n",optind);
		printf("argv[optind - 1] = %s\n", argv[optind -1]);
		printf("option_index = %d\n", option_index);
	}

	return 0;
}
#elif 0

extern char *optarg;
extern int optind, opterr, optopt;

int main(int argc, char *argv[])
{
    int opt;
    char *optstring = "a:b:c:d";

     while ((opt = getopt(argc, argv, optstring)) != -1)
     {
         printf("opt = %c\n", opt);
         printf("optarg = %s\n", optarg);
         printf("optind = %d\n", optind);
         printf("argv[optind - 1] = %s\n\n",  argv[optind - 1]);
    }

    return 0;
}

#elif 0

//#define DEBUG
#ifdef DEBUG
#define debug(fmt, arg...) \
		printf("jz-cim: "fmt, ##arg)
#else
#define debug(fmt, arg...)
#endif

#if 0
#ifdef DEBUG
#define _DEBUG 1
#define debug(fmt, arg...) \
    do {                   \
        if(_DEBUG)         \
		    printf("jz-cim: "fmt, ##arg); \
    }while(0)
#else
#define _DEBUG 0
#define debug(fmt, arg...)       \
    do {                         \
        if(_DEBUG)               \
		    printf("jz-cim: "fmt, ##arg); \
    }while(0)
#endif
#endif

int  main(int argc, char *argv[])
{
	int i = 100;
    debug("=== Hello world --%d ===\n", i);
    return 0;
}
#elif 0
typedef struct {
    int a;
    short s[2];
}MSG;

void main() {
    MSG *mp, m = {4, 1, 256};
    char *fp, *tp;

    mp = (MSG *)malloc(sizeof(MSG));
    for(fp=(char *)mp->s, tp=(char *)m.s; fp < (char *)(mp + 1);) {
        //*fp++ = *tp++;
        *fp = *tp;
        printf("*fp = %d  *tp = %d\n", *fp, *tp);
        fp++;
        tp++;
    }
}
#elif 0

#if 0
The passwd structure is defined in<pwd.h>asfollows:
struct passwd {
	char*pw_name; /*user name */
	char*pw_passwd; /*<PASSWORD> */
	uid_t pw_uid; /*user id */
	gid_t pw_gid; /*group id */
	char*pw_gecos; /*real name */
	char*pw_dir; /*home directory */
	char*pw_shell; /*shell program */
};
#endif
#include <time.h>
#include <pwd.h>
#include <sys/types.h>
int main()
{
	time_t timep;
	struct tm *lct, *gmt;
	struct passwd *pwd;
	char hostname[64] = "Unknown";

	time(&timep);
	lct = localtime(&timep);
	gmt = gmtime(&timep);

	pwd = getpwuid(getuid());
	gethostname(hostname, 16);

	printf("system localtime: %s\n", asctime(lct));
	printf("system gmtime: %s\n", asctime(gmt));
	printf("hostname: %s\n", hostname);
	printf("pw_name: %s\n", pwd->pw_name);
	printf("pw_passwd: %s\n", pwd->pw_passwd);
	printf("pw_uid: %d\n", pwd->pw_uid);

	return 0;
}

#elif 0
int main()
{
    if(daemon(1,0) != 0) {
        perror("daemon");
        return -1;
    }
    int i;
    for(i = 0; i < 5; i++) {
        printf("this is a test\n");
    }

    return 0;
}
#elif 0
int fun(int a)
{
	return a != 0;
}
void main()
{
	printf("ret = %d\n",fun(1));
}
#elif 0
#define A
#define B
int main()
{

#ifndef A
#ifdef B
	printf("defined B\n");
#endif
#endif

#ifdef A
	printf("defined A\n");
#endif
	return 0;
}
#endif

<file_sep>/gtk/4st_week/gtk_awindow.c
/* ************************************************************************
 *       Filename:  gtk_awimdow.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 09时35分14秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	//设置窗口标题
	gtk_window_set_title(GTK_WINDOW(window),"Hello GTK");
	
	//设置窗口的位置
	gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);

	//设置窗口的大小
	gtk_widget_set_size_request(window, 400, 300);
	
	//设置窗口是否可以改变大小
	gtk_window_set_resizable(GTK_WINDOW(window),FALSE);

	g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);

	gtk_widget_show_all(window);
	//隐藏窗口


	gtk_main();

	return 0;
}



<file_sep>/gtk/4st_week/picture_browse/scan_dir.c
/* ************************************************************************
 *       Filename:  scan_dir.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月11日 14时34分04秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>


int  gs_index = 0; //指向当前显示的图片
int  gs_bmp_total = 0;	//图片总数
char *gs_bmp_name[50] = {""};//存放图片目录和文件名地址的指针数组


//=================================================================================
// 函数介绍：	保存图片的目录和名字的地址到指针数组里
// 输入参数：	图片的路径：path
// 				图片的名字：bmp
// 返回值：		无
//=================================================================================
void save_bmp_name(char *path, char *bmp)
{
	gs_bmp_name[gs_bmp_total] = (char *)malloc(strlen(bmp)+1+strlen(path));
	bzero(gs_bmp_name[gs_bmp_total], strlen(bmp)+1); //将申请的内存清零
	strcpy(gs_bmp_name[gs_bmp_total], path);
	strcat(gs_bmp_name[gs_bmp_total], bmp);
	gs_bmp_total++;
}
//=================================================================================
// 函数介绍：	获取并保存图片的名字
// 输入参数：	图片的路径：path
// 返回值：		无
//=================================================================================
void get_bmp_name(char *path)
{
	DIR *dir;
	struct dirent *ptr;
	
	dir = opendir(path);
	while((ptr = readdir(dir)) != NULL)
	{
		//存图片名
		if(strstr(ptr->d_name, ".bmp"))
		{
			//printf("ptr->d_name = %s\n", ptr->d_name);
			save_bmp_name(path, ptr->d_name);
		}
	}
	closedir(dir);
}
//=================================================================================
// 函数介绍：	转换图片的名字为数字
// 输入参数：	图片的路径+图片名：bmp_pathname
// 返回值：		图片的编号
//=================================================================================
int conver_bmp_name(char *bmp_pathname)
{
	int num = 0;
	
	sscanf(bmp_pathname, "./image/%d", &num);
	//printf("num=%d\n", num);
	return num;
}
//=================================================================================
// 函数介绍：	根据图片的名字排序
// 输入参数：	无
// 返回值：		无
//=================================================================================
void order_bmp_name(void)
{
	char *tmp = NULL;
	int j, k;
	
	for(j=0;j<gs_bmp_total-1;j++)
	{
		for(k=j+1; k<gs_bmp_total; k++)
		{
			if(conver_bmp_name(gs_bmp_name[j]) > conver_bmp_name(gs_bmp_name[k]))
			{
				tmp = gs_bmp_name[k];
				gs_bmp_name[k] = gs_bmp_name[j];
				gs_bmp_name[j]= tmp;
			}
		}
	}
	
}
//=================================================================================
// 函数介绍：	打印图片的名字
// 输入参数：	无
// 返回值：		无
//=================================================================================
void bmp_name_print(void)
{
	int i;
	
	printf("gs_bmp_total = %d\n", gs_bmp_total);
	for(i=0;i<gs_bmp_total;i++)
	{
		printf("bmp_name = %s\n", gs_bmp_name[i]);
	}
}<file_sep>/c/practice/3rd_week/string/mystring.h
/* ************************************************************************
 *       Filename:  mystring.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月24日 星期五 06時44分57秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __MYSTRING_H__
#define __MYSTRING_H__

extern void mystrinv(char *src);
extern int  mystrlen(const char *src);
extern int  mystrcpy(char *obj, const char *src);
extern int  mystrcmp(const char *src1, const char *src2);
extern int  strchange(const char *src);

#endif


<file_sep>/c/practice/recursion.c
#include <stdio.h>



float fun(int n)
{
	float res = 0.0;
	int temp = 0, i = n;
	
	if(n==1) return 1;
	
	while(i>0)
	{
		temp += i;
		i--;
	}
	
	res = 1.0/temp;
	
	return (res + fun(n-1));	
}

void main(void)
{
	float res = 0.0;
	
	
	res = fun(11);
	
	printf("res = %f\n",res);
}<file_sep>/network/sockets/Makefile


CC := gcc
EXC :=


.PHONY:all
all:


.PHONY:clean
clean:

<file_sep>/sys_program/7th_day/gpio_buttons.c
/* ************************************************************************
 *       Filename:  gpio_buttons.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月21日 14时16分42秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "s5pv210-gpio.h"

static open_dev(const char *devname)
{
	int fd;

	fd = open(devname,O_RDWR);

	if(fd < 0)
	{
		perror("open_dev");
		_exit(-1);
	}
	return fd;
}
int main(int argc,char *argv[])
{
	int fd_row = 0;
	int fd_col = 0;
	int key_ret = 0, key_tmp = 0;
	fd_row = open_dev("/dev/gpH3");
	ioctl(fd_row,GPIO_SET_PIN_OUT,0x0);
	ioctl(fd_row,GPIO_CLR_PIN,0x0);

	fd_col = open_dev("/dev/gpH2");
	ioctl(fd_col,GPIO_SET_PIN_IN,0x3);
	ioctl(fd_col,GPIO_SET_PIN_IN,0x4);
	ioctl(fd_col,GPIO_SET_PIN_IN,0x5);
	ioctl(fd_col,GPIO_SET_PIN_IN,0x6);
	ioctl(fd_col,GPIO_SET_PIN_IN,0x7);

	ioctl(fd_col,GPIO_SET_PULL_UP,0x3);
	ioctl(fd_col,GPIO_SET_PULL_UP,0x4);
	ioctl(fd_col,GPIO_SET_PULL_UP,0x5);
	ioctl(fd_col,GPIO_SET_PULL_UP,0x6);
	ioctl(fd_col,GPIO_SET_PULL_UP,0x7);

	while(1)
	{
		read(fd_col, &key_tmp, sizeof(key_tmp));
		key_tmp &= 0xf8;

		if(key_tmp != 0xf8)
		{
			switch(key_tmp)
			{
				case 0xf0:
					key_ret = 2;
					printf("key2 pressed\n");
					break;
				case 0xe8:
					key_ret = 3;
					printf("key3 pressed\n");
					break;
				case 0xd8:
					key_ret = 4;
					printf("key4 pressed\n");
					break;
				case 0xb8:
					key_ret = 5;
					printf("key5 pressed\n");
					break;
				case 0x78:
					key_ret = 6;
					printf("key6 pressed\n");
					break;
			}

			do
			{
				read(fd_col, &key_tmp, sizeof(key_tmp));
				key_tmp &= 0xf8;
			}while(key_tmp != 0xf8);
		}
		else
		{
			printf("Err: key_ret = %d\n",key_tmp);
		}
	}

	return 0;
}
<file_sep>/network/route/tcp/tcp_client.c
/*****************************************************************************
 函 数 名  : getch()
 功能描述  : 获取一个字符
 输入参数  : NULL 
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
static char getch() 
{
    struct termios oldt, newt;
    char ch;
	
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
	
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
	
    return ch;
}

/*****************************************************************************
 函 数 名  : get_passwd()
 功能描述  : 获取密码
 输入参数  : pwd      保存获取密码的指针
 返 回 值  : max_len  密码的最大长度    
 修改日期  : 2015年9月15日
*****************************************************************************/
void get_passwd(char passwd[], int max_len)
{
	char ch;
	char i = 0;
	
	while(i < max_len)
	{
		ch = getch();
		if(ch == 10){       // 回车键
			passwd[i] = 0;
			break;
		}
		else if(ch ==127) { // 回格键
			//i--;
			//if(i<0) i = 0;
			continue;
		}
		passwd[i++] = ch;
		putchar('*');
	}
	
	passwd[max_len] = 0;
}

int tcp_receive_msg(int sockfd, char recv[])
{
	int len = 0;

	while(1) {
		len = recv(sockfd, recv, sizeof(recv), 0);
		if((strcmp(recv, "#end#") == 0) || (len == 0)){
			return len;
		}

		printf("%s", recv);
	}
}

void tcp_send_cmd(char cmd[], int sockfd)
{
	int len  = 0;
	char recv[1024] = "";	
	
	if(strcmp(cmd, "help") == 0){
		send(sockfd, cmd, strlen(cmd), 0);	
		tcp_receive_msg(sockfd, recv);					
	}
	else if(strcmp(cmd,"arp") == 0){
		send(sockfd, cmd, strlen(cmd), 0);
		tcp_receive_msg(sockfd, recv);
	}
	else if(strcmp(cmd,"ifconfig") == 0){
		send(sockfd, cmd, strlen(cmd), 0);
		tcp_receive_msg(sockfd, recv);
	}
	else if(strcmp(cmd,"lsfire") == 0){	
		send(sockfd, cmd, strlen(cmd), 0);
		tcp_receive_msg(sockfd, recv);		
	}
	else if(strcmp(cmd,"setfire") == 0){
		
		int i;
		char passwd[PASSWD_LEN] = "";
		
		send(sockfd, cmd, strlen(cmd), 0);		
		for(i=0; i<2; i++) {		
			tcp_receive_msg(sockfd, recv);
			
			get_passwd(passwd, PASSWD_LEN-1);
			send(sockfd, passwd, strlen(passwd), 0);
	
			tcp_receive_msg(sockfd, recv);	
			if(strcmp(recv, "passed") == 0) break;		
		}
		
		if(i == 2) return;
		
		tcp_receive_msg(sockfd, recv);	
	
		while(1) {			
			bzero(cmd, RULE_LEN);

			tcp_receive_msg(sockfd, recv);
							
			fgets(cmd, RULE_LEN, stdin);	
			len = strlen(cmd);
			rule[len-1] = 0; //去掉 \n	
			
			if(strcmp(cmd,"ls") == 0){
				send(sockfd, cmd, strlen(cmd), 0);
				tcp_receive_msg(sockfd, recv);
			}
			else if(strcmp(cmd,"-h") == 0) {
				send(sockfd, cmd, strlen(cmd), 0);
				tcp_receive_msg(sockfd, recv);			
			}	
			else if(strncmp(cmd,"-d",2) == 0) {
				char *prule = NULL;
				prule = cmd+3; //跳过 "-d "
				send(sockfd, cmd, strlen(cmd), 0);
			}
			else if(strcmp(cmd,"passwd") == 0) {
				send(sockfd, cmd, strlen(cmd), 0);
				tcp_receive_msg(sockfd, recv);								
				get_passwd(passwd, PASSWD_LEN-1);
				send(sockfd, passwd, strlen(passwd), 0);				
			}
			else if(strcmp(cmd,"esc") == 0){
				send(sockfd, cmd, strlen(cmd), 0);
				tcp_receive_msg(sockfd, recv);	
				break;
			}
			else {			
				send(sockfd, cmd, strlen(cmd), 0);
			}
		}		
	}	

	out:
	pthread_mutex_unlock(&rt->mutex);// 解锁
}
<file_sep>/sys_program/2nd_day/am/atexit.c
/* ************************************************************************
 *       Filename:  atexit.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 09时59分51秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>

void fun1(void)
{
	printf("in fun1 atexit\n");
}

void fun2(void)
{
	printf("in fun2 atexit\n");
}
void fun3(void)
{
	printf("in fun3 atexit\n");
}

int main(int argc, int *argvp[])
{
	atexit(fun1);
	atexit(fun2);
	atexit(fun3);

	sleep(3);
	return 0;
}


<file_sep>/network/sockets/DieWithMessage.c
/*************************************************************************
	> File Name: DieWithMessage.c
	> Author: 
	> Mail: 
	> Created Time: Wed 04 May 2016 03:52:24 PM CST
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>

void DieWithUserMessage(const char *msg, const char *detail) {
  fputs(msg, stderr);
  fputs(": ", stderr);
  fputs(detail, stderr);
  fputc('\n', stderr);
  exit(1);
}

void DieWithSystemMessage(const char *msg) {
  perror(msg);
  exit(1);
}
<file_sep>/work/camera/bf3703/bf3703/bf3703_camera.h
/*
 * linux/drivers/misc/camera_source/bf3703/camera.h -- Ingenic CIM driver
 *
 * Copyright (C) 2005-2010, Ingenic Semiconductor Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 */

#ifndef bf3703_CAMERA_H
#define bf3703_CAMERA_H


#include <linux/jz_cim_core.h>
#include <linux/jz_sensor.h>

/*
struct private_info
{
	int cur_rwidth;
	int cur_rheight;
	int cur_mode;

	int cur_focus_mode;
};
*/

struct bf3703_sensor
{
	struct i2c_client      		 *client;
//	struct private_info		 pinfo;
	struct camera_sensor_desc	 desc;
};

#endif
<file_sep>/shell/top.sh
#!/bin/bash

HEADFLAGD="-n 20"
PSFLAGS=aux
SLEEPFLAGS=2
SORTFLAGS=`-k3nr -k1,1 -k2n`

HEADER="`ps $PSFLAGS | head -n 1`"

while true
do
	clear
	uptime
	echo "$HEADER"
	ps $HEADER |
		sed -e ld |
			sort $SORTFLAGS |
				head $HEADFLAGD

	sleep $SLEEPFLAGS
done
<file_sep>/work/test/cim_test-zmm220/futil.h
#ifndef _FUTIL_H_
#define _FUTIL_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <stddef.h>
#include <time.h>
#include <sys/time.h>
#include "bmp.h"

DWORD GetTickCount(void);

int WriteBitmap(const BYTE *buffer, int Width, int Height, const char *file);

BYTE *LoadFile(const char *FileName);

int SaveToFile(const char *fileName, void *buffer, int size);

int logClose();

int logMsg(char *fmt, ...);


int ReadBitmap(BYTE *p, BYTE *buffer, int *Width, int *Height);

int LoadBitmapFile(const char *FileName, BYTE *buffer, int *Width, int *Height);

void msleep(int msec);

int dumpData(const unsigned char *data, int dataSize, const char *title);

#endif
<file_sep>/work/debug/a8/delmod.sh
#!/bin/sh

name=`ls *.ko`

if [ -z "$name" ]
then
	exit 1
fi

devname=${name%.ko}
devno=
#echo "devname=$devname"

if [ -z "`cat /proc/devices | grep $devname`" ]
then
	echo "$devname haven't installed!"
	exit 1	
fi

#echo "$devno  $devname"

if [ -e /dev/$devname ]
then
	rm /dev/$devname

	if [ $? -eq 0 ]
	then
		echo "remove /dev/$devname successful"
	fi
fi

rmmod $devname

if [ $? -eq 0 ]
then 
	echo "uninstall $devname successful"
fi
<file_sep>/c/practice/3rd_week/time/Makefile
atime:main.c show_time.c
	gcc -o atime main.c show_time.c

.PHONY:clean
clean:
	rm atime
<file_sep>/network/3rd_day/multicast.c
/* ************************************************************************
 *       Filename:  multicast.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月02日 11时44分58秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


int main(int argc, char *argv[])
{
	char group[INET_ADDRSTRLEN] = "172.16.31.10";
	char msg[512] = "";
	int sockfd;
	struct sockaddr_in addr;
	struct ip_mreq mreq;//定义一个多播组

	sockfd = socket(AF_INET, SOCK_DGRAM, 0);
	addr.sin_family = AF_INET;
	addr.sin_port = htons(8080);
	addr.sin_addr.s_addr = htonl(INADDR_ANY);
	bind(sockfd, (struct sockaddr *)&addr, sizeof(addr));

	mreq.imr_multiaddr.s_addr = inet_addr(group); //设置多播组IP
	mreq.imr_interface.s_addr = htonl(INADDR_ANY);//向多播组添加一个IP
	setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));

	while(1)
	{
		bzero(msg, sizeof(msg));
		recvfrom(sockfd, msg, sizeof(msg), 0, NULL, NULL);
		printf("msg = %s\n",msg);
	}
	close(sockfd);
	return 0;
}

<file_sep>/sys_program/1st_day/cp/cp.c
/* ************************************************************************
 *       Filename:  systemcall.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月13日 10时16分10秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>

#if 1
int main(int argc, char *argv[])
{
	int fd, ft, ret;
	char *pbuf = NULL, ch;
	unsigned long filelen = 0;

	fd = open(argv[1],O_RDWR);

	if(fd < 0) 
	{
		perror("error:\n");
		return -1;
	}

	while(read(fd,&ch,sizeof(ch)) == 1) filelen++;
	
	pbuf = (char *)malloc(filelen);
	if(pbuf == NULL) 
	{
		printf("Err:failed to malloc!\n");
		return -1;
	}

	close(fd);
	fd = open(argv[1],O_RDWR);
	ret = read(fd,pbuf,filelen);
	
	ft = open(argv[2],O_RDWR | O_CREAT,0777);
	write(ft,pbuf,filelen);

	printf("filelen = %lu\n",filelen);
	printf("ret     = %d\n",ret);

	close(fd);
	close(ft);
	free(pbuf);
	return 0;
}
#endif<file_sep>/network/route/src/route_control.c
/******************************************************************************
  文 件 名   : route_control.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 数据发送
  函数列表   :
              broadcast
              build_arp_table
              get_ethernet_port
              route_init
              show_port_info
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"
#include "arp_link.h"
#include "firewall_file.h"
#include "route_control.h"

/*****************************************************************************
 函 数 名  : route_init()
 功能描述  : 初始化
 输入参数  : 无
 返 回 值  : NULL
 修改日期  : 2015年9月10日
*****************************************************************************/
void route_init(TYPE_Route *rt)
{
	//创建原始套接字
	rt->raw_fd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));

	//创建监听套接字
	rt->sockfd = socket(AF_INET, SOCK_STREAM, 0);

	//让服务器绑定端口和ip
	bzero(&rt->s_addr, sizeof(rt->s_addr));
	rt->s_addr.sin_family = AF_INET;
	rt->s_addr.sin_port = htons(8080);
	rt->s_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(rt->sockfd, (struct sockaddr *)&rt->s_addr, sizeof(rt->s_addr));

	if(ret != 0)
	{
		perror("bind:");
		exit(-1);
	}
	//listen 创建链接队列
	listen(rt->sockfd, 5);

	rt->fire_status = UP; // 初始化防火墙的状态: 开启

	//初始化链表头指针
	rt->arp_head  = NULL;
	rt->mac_head  = NULL;
	rt->ip_head   = NULL;
	rt->port_head = NULL;
	rt->pro_head  = NULL;

	pthread_mutex_init(&rt->mutex, NULL); // 初始化互斥锁
	get_ethernet_port(rt);   // 获取网卡接口信息
	build_arp_table(rt);     // 创建ARP表
	firewall_config(rt);     // 读取规则文件，配置防火墙
	firewall_get_passwd(rt); // 获取保存在文件的防火墙密码
}

#if 0
/*****************************************************************************
 函 数 名  : show_help()
 功能描述  : 输入帮助提示
 输入参数  : 无
 返 回 值  : void
 修改日期  : 2015年9月10日
*****************************************************************************/
void show_help(void)
{
	printf("***************************************************\n");
	printf("-      help: 查看帮助信息                         *\n");
	printf("-       arp: 查看 ARP 表                          *\n");
	printf("-  ifconfig: 查看网卡信息                         *\n");
	printf("-   fire on: 开启防火墙                           *\n");
	printf("-  fire off: 关闭防火墙                           *\n");
	printf("-    lsfire: 查看防火墙规则                       *\n");
	printf("-   setfire: 设置防火墙规则                       *\n");
	printf("***************************************************\n");
}
#endif

/*****************************************************************************
 函 数 名  : get_ethernet_port()
 功能描述  : 获取网络接口信息
 输入参数  : 无
 返 回 值  : NULL
 修改日期  : 2015年9月10日
*****************************************************************************/
void get_ethernet_port(TYPE_Route *rt)
{
	struct ifreq buf[MAX_PORT];    /* ifreq结构数组 */
	struct ifconf ifc;             /* ifconf结构 */

	 /* 初始化ifconf结构 */
    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = (caddr_t) buf;

	/* 获得接口列表 */
    if (ioctl(rt->raw_fd, SIOCGIFCONF, (char *)&ifc) == -1)
	{
        perror("SIOCGIFCONF ioctl");
        return ;
    }

	rt->port_num= ifc.ifc_len / sizeof(struct ifreq); /* 接口数量 */
    printf("port_num=%d\n\n", rt->port_num);

	char buff[20]="";
	int ip;
	int if_len = rt->port_num;

	while(if_len-- > 0) /* 遍历每个接口 */
	{
        sprintf(rt->eth_port[if_len].name, "%s", buf[if_len].ifr_name); /* 接口名称 */

		/* 获得接口标志 */
        if(!(ioctl(rt->raw_fd, SIOCGIFFLAGS, (char *) &buf[if_len])))
		{
            /* 接口状态 */
            if(buf[if_len].ifr_flags & IFF_UP)
			{
				rt->eth_port[if_len].status = UP;
            }
            else
			{
				rt->eth_port[if_len].status = DOWN;
            }
        }
		else
		{
            char str[256];
            sprintf(str, "SIOCGIFFLAGS ioctl %s", buf[if_len].ifr_name);
            perror(str);
        }

        /* IP地址 */
        if(!(ioctl(rt->raw_fd, SIOCGIFADDR, (char *)&buf[if_len])))
		{
			bzero(buff,sizeof(buff));
			sprintf(buff, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
			inet_pton(AF_INET, buff, &ip);
			memcpy(rt->eth_port[if_len].ip, &ip, 4);
		}
		else
		{
            char str[256];
            sprintf(str, "SIOCGIFADDR ioctl %s", buf[if_len].ifr_name);
            perror(str);
        }

        /* 子网掩码 */
        if(!(ioctl(rt->raw_fd, SIOCGIFNETMASK, (char *)&buf[if_len])))
		{
			bzero(buff,sizeof(buff));
			sprintf(buff, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
			inet_pton(AF_INET, buff, &ip);
			memcpy(rt->eth_port[if_len].netmask, &ip, 4);
        }
		else
		{
            char str[256];
            sprintf(str, "SIOCGIFADDR ioctl %s", buf[if_len].ifr_name);
            perror(str);
        }

        /* 广播地址 */
        if(!(ioctl(rt->raw_fd, SIOCGIFBRDADDR, (char *)&buf[if_len])))
		{
            //printf("bc_ip:%s\n",(char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
			bzero(buff,sizeof(buff));
			sprintf(buff, "%s", (char*)inet_ntoa(((struct sockaddr_in*)(&buf[if_len].ifr_addr))->sin_addr));
			inet_pton(AF_INET, buff, &ip);
			memcpy(rt->eth_port[if_len].bc_ip, &ip, 4);
        }
		else
		{
            char str[256];
            sprintf(str, "SIOCGIFADDR ioctl %s", buf[if_len].ifr_name);
            perror(str);
        }

        /*MAC地址 */
		if(!(ioctl(rt->raw_fd, SIOCGIFHWADDR, (char *) &buf[if_len])))
		{
			memcpy(rt->eth_port[if_len].mac, (unsigned char *)buf[if_len].ifr_hwaddr.sa_data, 6);
		}
		else
		{
            char str[256];
            sprintf(str, "SIOCGIFHWADDR ioctl %s", buf[if_len].ifr_name);
            perror(str);
        }
    }//–while end
}

/*****************************************************************************
 函 数 名  : show_port_info()
 功能描述  : 打印网络接口信息
 输入参数  : rt            TYPE_Route 类型指针
 			 port_name     网络接口名称，当为NULL时，打印所有接口信息
 返 回 值  : NULL
 修改日期  : 2015年9月10日
*****************************************************************************/
void show_port_info(TYPE_Route *rt, char *port_name)
{
	int i = 0;

	if(port_name != NULL)
	{
		for(i=0;i<rt->port_num;i++)
		{
			if(strcmp(port_name, rt->eth_port[i].name) == 0)
			{
				printf("___________%s___________\n", rt->eth_port[i].name);

				if(rt->eth_port[i].status == UP) printf("UP\n");
				else printf("DOWN\n");

				//ip
				printf("     ip: %d.%d.%d.%d\n",\
					   rt->eth_port[i].ip[0],rt->eth_port[i].ip[1],\
					   rt->eth_port[i].ip[2],rt->eth_port[i].ip[3]);
				//mac
				printf("    mac: %02x:%02x:%02x:%02x:%02x:%02x\n",\
					   rt->eth_port[i].mac[0],rt->eth_port[i].mac[1],\
					   rt->eth_port[i].mac[2],rt->eth_port[i].mac[3],\
					   rt->eth_port[i].mac[4],rt->eth_port[i].mac[5]);

				//netmask
				printf("netmask: %d.%d.%d.%d\n",\
					   rt->eth_port[i].netmask[0],rt->eth_port[i].netmask[1],\
					   rt->eth_port[i].netmask[2],rt->eth_port[i].netmask[3]);

				//broadcast ip
				printf("  bc_ip: %d.%d.%d.%d\n",\
					   rt->eth_port[i].bc_ip[0],rt->eth_port[i].bc_ip[1],\
					   rt->eth_port[i].bc_ip[2],rt->eth_port[i].bc_ip[3]);
				printf("__________________________\n");
			}
		}
	}
	else
	{
		for(i=0;i<rt->port_num;i++)
		{
			printf("___________%s___________\n", rt->eth_port[i].name);

			if(rt->eth_port[i].status == UP) printf("UP\n");
			else printf("DOWN\n");

			//ip
			printf("     ip: %d.%d.%d.%d\n",\
				   rt->eth_port[i].ip[0],rt->eth_port[i].ip[1],\
				   rt->eth_port[i].ip[2],rt->eth_port[i].ip[3]);
			//mac
			printf("    mac: %02x:%02x:%02x:%02x:%02x:%02x\n",\
				   rt->eth_port[i].mac[0],rt->eth_port[i].mac[1],\
				   rt->eth_port[i].mac[2],rt->eth_port[i].mac[3],\
				   rt->eth_port[i].mac[4],rt->eth_port[i].mac[5]);

			//netmask
			printf("netmask: %d.%d.%d.%d\n",\
				   rt->eth_port[i].netmask[0],rt->eth_port[i].netmask[1],\
				   rt->eth_port[i].netmask[2],rt->eth_port[i].netmask[3]);

			//broadcast ip
			printf("  bc_ip: %d.%d.%d.%d\n",\
				   rt->eth_port[i].bc_ip[0],rt->eth_port[i].bc_ip[1],\
				   rt->eth_port[i].bc_ip[2],rt->eth_port[i].bc_ip[3]);

			printf("__________________________\n");
		}
	}
}

/*****************************************************************************
 函 数 名  : build_arp_table()
 功能描述  : 建立ARP表
 输入参数  : 无
 返 回 值  : void
 修改日期  : 2015年9月10日
*****************************************************************************/
void build_arp_table(TYPE_Route *rt)
{
	int i = 0, port_num = 0;
	uchar recv[2024] = "";
	uchar arp[256] = {
		//-----组mac----14----
		0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
		0x00,0x00,0x00,0x00,0x00,0x00,//src_mac:
		0x08,0x06,                    //类型: 0x0806 ARP协议

		//-----组ARP----28----
		0x00,0x01,0x08,0x00,          //硬件类型1(以太网地址)，协议类型:0x800(IP)
		0x06,0x04,0x00,0x01,          //硬件、协议的地址长度分别为6和4，ARP请求
		0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
		0, 0, 0, 0,                   //发送端的ip
		0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac，设置为0)
		0, 0, 0, 0,                   //目的ip
	};

	if(rt->arp_head != NULL){
		free_arp_table(rt->arp_head);
		rt->arp_head = NULL;
	}

	while(port_num < rt->port_num)
	{
		memcpy(arp+6, rt->eth_port[port_num].mac, 6);
		memcpy(arp+22,rt->eth_port[port_num].mac, 6);
		memcpy(arp+28,rt->eth_port[port_num].ip,  4);
		memcpy(arp+38,rt->eth_port[port_num].ip,  4);

		strncpy(rt->ethreq.ifr_name,rt->eth_port[port_num].name, IFNAMSIZ);
		ioctl(rt->raw_fd, SIOCGIFINDEX, (char *)&rt->ethreq);
		bzero(&rt->sll, sizeof(rt->sll));
		rt->sll.sll_ifindex = rt->ethreq.ifr_ifindex;

		for(i=0;i<255;i++)
		{
			arp[41] = i;

			//发送ARP请求
			sendto(rt->raw_fd, arp, 42, 0, (struct sockaddr *)&rt->sll, sizeof(rt->sll));

			//接收对方的ARP应答
			recvfrom(rt->raw_fd, recv, sizeof(recv), 0, NULL, NULL);

			if(recv[21] == 2) //接收到ARP应答数据包
			{
				ARP_Table node;

				memcpy(node.ip,  recv + 28, 4); //提取ip
				memcpy(node.mac, recv + 22, 6); //提取mac

				rt->arp_head = (ARP_Table *)insert_arp_table(rt->arp_head, node);
			}
		}

		port_num++;
	}

	//print_arp_table(rt->arp_head);
}

Boolean broadcast(TYPE_Route *rt, const uchar ip[])
{
	int i = 0, port_num = 0;
	uchar recv[2024] = "";
	uchar arp[256] = {
		//-----组mac----14----
		0xff,0xff,0xff,0xff,0xff,0xff,//dst_mac: ff:ff:ff:ff:ff:ff
		0x00,0x00,0x00,0x00,0x00,0x00,//src_mac:
		0x08,0x06,                    //类型: 0x0806 ARP协议

		//-----组ARP----28----
		0x00,0x01,0x08,0x00,          //硬件类型1(以太网地址)，协议类型:0x800(IP)
		0x06,0x04,0x00,0x01,          //硬件、协议的地址长度分别为6和4，ARP请求
		0x00,0x00,0x00,0x00,0x00,0x00,//发送端的mac
		0, 0, 0, 0,                   //发送端的ip
		0x00,0x00,0x00,0x00,0x00,0x00,//目的mac(获取对方的mac，设置为0)
		0, 0, 0, 0,                   //目的ip
	};

	while(port_num < rt->port_num)
	{
		memcpy(arp+6, rt->eth_port[port_num].mac, 6);
		memcpy(arp+22,rt->eth_port[port_num].mac, 6);
		memcpy(arp+28,rt->eth_port[port_num].ip,  4);
		memcpy(arp+38,ip,  4);

		strncpy(rt->ethreq.ifr_name,rt->eth_port[port_num].name, IFNAMSIZ);
		ioctl(rt->raw_fd, SIOCGIFINDEX, (char *)&rt->ethreq);
		bzero(&rt->sll, sizeof(rt->sll));
		rt->sll.sll_ifindex = rt->ethreq.ifr_ifindex;

		for(i=0;i<5;i++) //广播五次
		{
			//发送ARP请求
			sendto(rt->raw_fd, arp, 42, 0, (struct sockaddr *)&rt->sll, sizeof(rt->sll));

			//接收对方的ARP应答
			recvfrom(rt->raw_fd, recv, sizeof(recv), 0, NULL, NULL);

			if(recv[21] == 2) //接收到ARP应答数据包
			{
				if(iptoun_btol(recv + 28) == iptoun_btol(ip))
				{
					ARP_Table node;

					memcpy(node.ip,  recv + 28, 4); //提取ip
					memcpy(node.mac, recv + 22, 6); //提取mac

					rt->arp_head = (ARP_Table *)insert_arp_table(rt->arp_head, node);
					return TRUE;
				}
			}
		}

		port_num++;
	}

	return FALSE;
}
<file_sep>/network/5th_day/Makefile
all:filch feiQ udp sock_raw arp

filch:
	gcc -o filch filch.c gb2312_ucs2.c

feiQ:
	gcc raw_feiQ.c gb2312_ucs2.c -o feiQ

udp:
	gcc raw_udp.c -o udp

sock_raw:sock_raw.c
	gcc -o sock_raw sock_raw.c

arp:
	gcc -o arp arp.c

.PHONY:clean
clean:
	rm sock_raw feiQ udp filch
<file_sep>/work/test/yuv2bmp/conver.h
#ifndef __CONVER_H__
#define __CONVER_H__

int  init_conver();
void rgb5652rgb888(unsigned short* rgb565,unsigned int* rgb888,unsigned int framesize);

int yuv422rgb565_scale(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height);
int yuv422rgb565(unsigned char *yuv422buf,unsigned short *rgb565,int width,int height);
int yuv422rgb888_scale(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height);
int yuv422rgb888(unsigned char *yuv422buf,unsigned int *rgb888,int width,int height);

int rgb8882rgb565(unsigned short *rgb565,unsigned char *rgb888,unsigned int imagesize);

int cut_rgb565(unsigned short *rgb565cut,unsigned short *rgb565src,unsigned int width,unsigned int imagesize);

void rgb565_rotate90(const unsigned short *input, int width_in, int height_in,unsigned short *output);//, int *width_out, int *height_out);

/*************************
 *Translate the picture Right_Left.
 * ***********************/
void rgb565_folio(unsigned short *rgb565,int width,int height);

int  close_conver();
#endif



<file_sep>/c/practice/mate_bracket.c
/* ************************************************************************
 *       Filename:  mate_bracket.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年11月17日 20时31分35秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int  mate_bracket(char *str)
{
	char *p = NULL;
	int i = 0, j = 0, len = strlen(str);

	p = (char *)malloc(len + 1);
	memset(p, 0, len+1);

	for(i=0;i<len;i++)
	{
		if(str[i] == '(' || str[i] == '[' 
		|| str[i] == '{' || str[i] == '<')
		{
			p[j] = str[i];
			j++;
			continue;
		}

		switch(str[i])
		{
			case ')':
				j--;
				if(j < 0 || p[j] != '(')
					return 0;
				break;	

			case ']':
				j--;
				if(j < 0 || p[j] != '[')
					return 0;
				break;

			case '}':

				j--;
				if(j < 0 || p[j] != '{')
					return 0;
				break;
			case '>':
				j--;
				if(j < 0 || p[j] != '<')
					return 0;
				break;
		}
	}

	free(p);
	if(j != 0)
		return 0;
	else
		return 1;

}


int main(int argc, char *argv[])
{
	char exp[128] = {0};
	int ret, len;

	fgets(exp, sizeof(exp),stdin);
	len = strlen(exp);
	exp[len - 1] = 0;


	ret = mate_bracket(exp);

	printf("ret = %d\n",ret);

	return 0;
}


<file_sep>/work/camera/bf3703/bf3703/bf3703_camera.c
#include <asm/jzsoc.h>
#include <linux/i2c.h>
#include "bf3703_camera.h"
#include "bf3703_set.h"
#include "bf3703_set_mode.h"
#include <asm/jzsoc.h>

#define bf3703_DEBUG
#ifdef bf3703_DEBUG
#define dprintk(x...)   do{printk("bf3703---\t");printk(x);printk("\n");}while(0)
#else
#define dprintk(x...)
#endif

/* gpio init */
#define GPIO_CAMERA_RST         	(32*4+18) /*GPE18*/ 
#define GPIO_CAMERA_PDN   		(32*4+19) /*GPE19*/
#define GPIO_CIM_PDN            (32 * 4 + 24 )   // GPE24

struct bf3703_sensor bf3703;

void bf3703_reset(void)
{
    printk("bf3703_reset\n");
	__gpio_as_output(GPIO_CAMERA_RST);
	mdelay(50);
	__gpio_clear_pin(GPIO_CAMERA_RST);
	mdelay(50);
	__gpio_set_pin(GPIO_CAMERA_RST);
	mdelay(50);
}

void bf3703_power_down(void)
{
    printk("bf3703_power_down\n");
    __gpio_as_output(GPIO_CIM_PDN);
    __gpio_clear_pin(GPIO_CIM_PDN);
	mdelay(100);
    //-----------------
	__gpio_as_output(GPIO_CAMERA_PDN);
	__gpio_set_pin(GPIO_CAMERA_PDN);
    mdelay(100);
}

void bf3703_power_up(void)
{
    printk("bf3703_power_up \n");
	//bf3703_power_on later
	__gpio_as_output(GPIO_CAMERA_PDN);
	__gpio_set_pin(GPIO_CAMERA_PDN);
	mdelay(100);

   __gpio_as_output(GPIO_CIM_PDN);
   __gpio_clear_pin(GPIO_CIM_PDN);
   mdelay(100);
}

#if 0
void bf3703_reset(void)
{
    printk("bf3703_reset\n");
	__gpio_as_output(GPIO_CAMERA_RST);
	mdelay(50);
	__gpio_clear_pin(GPIO_CAMERA_RST);
	mdelay(50);
	__gpio_set_pin(GPIO_CAMERA_RST);
	mdelay(50);
}
#endif

int bf3703_set_balance(balance_flag_t balance_flag,int arg)
{
	dprintk("bf3703_set_balance");
	switch(balance_flag)
	{
		case WHITE_BALANCE_AUTO:
			bf3703_set_wb_auto_mode(bf3703.client);
			dprintk("wb_auto ");
			break;
		case WHITE_BALANCE_DAYLIGHT ://ri guang
			bf3703_set_wb_sunny_mode(bf3703.client);
			dprintk("wb_daylight ");
			break;
		case WHITE_BALANCE_CLOUDY_DAYLIGHT ://ying tian
			bf3703_set_wb_cloudy_mode(bf3703.client);
			dprintk("wb_cloudy daylight ");
			break;
		case WHITE_BALANCE_INCANDESCENT :
			bf3703_set_wb_office_mode(bf3703.client);
			dprintk("wb_incandenscent ");
			break;
	}
	return 0;
}

void bf3703_set_effect_whiteboard(struct i2c_client *client);
int bf3703_set_effect(effect_flag_t effect_flag,int arg)
{
	dprintk("bf3703_set_effect");
	switch(effect_flag)
	{
		case EFFECT_NONE:
			bf3703_set_effect_normal(bf3703.client);
			dprintk("effect_none");
			break;
		case EFFECT_MONO :
			bf3703_set_effect_blackwhite(bf3703.client);  
			dprintk("effect_mono ");
			break;
		case EFFECT_NEGATIVE :
			bf3703_set_effect_negative(bf3703.client);
			dprintk("effect_negative ");
			break;
		case EFFECT_SOLARIZE ://bao guang
			dprintk("effect_solarize ");
			break;
		case EFFECT_SEPIA :
			bf3703_set_effect_sepia(bf3703.client);
			dprintk("effect_sepia ");
			break;
		case EFFECT_POSTERIZE ://se diao fen li
			dprintk("effect_posterize ");
			break;
		case EFFECT_WHITEBOARD :
			dprintk("effect_whiteboard ");
			break;
		case EFFECT_BLACKBOARD :
			bf3703_set_effect_whiteboard(bf3703.client);
			dprintk("effect_blackboard ");
			break;
		case EFFECT_AQUA ://qian lv se
			bf3703_set_effect_greenish(bf3703.client);
			dprintk("effect_aqua  ");
			break;
		case EFFECT_PASTEL:
			dprintk("effect_pastel");
			break;
		case EFFECT_MOSAIC:
			dprintk("effect_mosaic");
			break;
		case EFFECT_RESIZE:
			dprintk("effect_resize");
			break;
	}
	return 0;
}

int bf3703_set_antibanding(antibanding_flag_t antibanding_flag,int arg)
{
	dprintk("bf3703_set_antibanding");
	switch(antibanding_flag)
	{
		case ANTIBANDING_AUTO :
			bf3703_ab_auto(bf3703.client);
			dprintk("ANTIBANDING_AUTO ");
			break;
		case ANTIBANDING_50HZ :
			bf3703_ab_50hz(bf3703.client);
			dprintk("ANTIBANDING_50HZ ");
			break;
		case ANTIBANDING_60HZ :
			bf3703_ab_60hz(bf3703.client);
			dprintk("ANTIBANDING_60HZ ");
			break;
		case ANTIBANDING_OFF :
			bf3703_ab_off(bf3703.client);
			dprintk("ANTIBANDING_OFF ");
			break;
	}
	return 0;
}


int bf3703_set_flash_mode(flash_mode_flag_t flash_mode_flag,int arg)
{
	return 0;
}

int bf3703_set_scene_mode(scene_mode_flag_t scene_mode_flag,int arg)
{
	return 0;
}

int bf3703_set_focus_mode(focus_mode_flag_t flash_mode_flag,int arg)
{
	return 0;
}


int bf3703_set_fps(int fps)
{
	dprintk("set fps : %d",fps);
	return 0;
}

int bf3703_set_luma_adaptation(int arg)
{
	dprintk("luma_adaptation : %d",arg);
	return 0;
}

int bf3703_set_parameter(int cmd, int mode, int arg)
{
	switch(cmd)
	{
		case CPCMD_SET_BALANCE :
			bf3703_set_balance(mode,arg);
			break;
		case CPCMD_SET_EFFECT :
			bf3703_set_effect(mode,arg);
			break;
		case CPCMD_SET_ANTIBANDING :
			bf3703_set_antibanding(mode,arg);
			break;
		case CPCMD_SET_FLASH_MODE :
			bf3703_set_flash_mode(mode,arg);
			break;
		case CPCMD_SET_SCENE_MODE :
			bf3703_set_scene_mode(mode,arg);
			break;
		case CPCMD_SET_PIXEL_FORMAT :
			break;
		case CPCMD_SET_FOCUS_MODE :
			bf3703_set_focus_mode(mode,arg);
			break;
		case CPCMD_SET_PREVIEW_FPS:
			bf3703_set_fps(arg);
			break;
		case CPCMD_SET_NIGHTSHOT_MODE:
			break;
		case CPCMD_SET_LUMA_ADAPTATION:
			bf3703_set_luma_adaptation(arg);
			break;
	}
	return 0;
}

int bf3703_set_power(int state)
{
	switch (state)
	{
		case 0:           
			/* hardware power up first */
			bf3703_power_up();
			/* software power up later if it implemented */
			break;
		case 1:
			bf3703_power_down();
			break;
		case 2:
			break;
		default:
			printk("%s : EINVAL! \n",__FUNCTION__);
	}
	return 0;
}

int bf3703_sensor_init(void)
{
	//bf3703_reset();
	bf3703_init_setting(bf3703.client);
	return 0;
}

int bf3703_sensor_probe(void)
{
	int sensor_id = 0;

	bf3703_power_up();
	bf3703_reset();
	sensor_id = (sensor_read_reg(bf3703.client,0xFC)<<8)|sensor_read_reg(bf3703.client,0xFD);	
	bf3703_power_down();

	if(sensor_id == 0x3703)
		return 0; 
	return -1;
}

/* sensor_set_function use for init preview or capture.there may be some difference between preview and capture.
 * so we divided it into two sequences.param: function indicated which function
 * 0: preview
 * 1: capture
 * 2: recording
 */
int bf3703_set_function(int function)
{
	switch (function)
	{
		case 0:
			preview_set(bf3703.client);
            printk("preview set %s \n",__func__);
			break;
		case 1:
			capture_set(bf3703.client);
            printk("capture set %s \n",__func__);
			break;
		case 2:		
			break;
	}
	return 0;
}

int bf3703_set_resolution(int width,int height,int bpp,pixel_format_flag_t fmt,camera_mode_t mode)
{
	size_switch(bf3703.client,width,height,mode);
	return 0;         
}

static ssize_t bf3703_write_store(struct device *dev,
				   struct device_attribute *attr,
				   const char *buf, size_t count)
{
	//uint32_t reg,val;
	//sscanf(buf,"%x,%x",&reg,&val);
	//printk("write reg : %x | value : %x\n",reg&0xffff,val&0xff);
	//sensor_write_reg16(bf3703.client,reg&0xffff,val&0xff);

	return count;
}

static ssize_t bf3703_read_store(struct device *dev,
				   struct device_attribute *attr,
				   const char *buf, size_t count)
{
	//uint32_t reg;
	//sscanf(buf,"%x",&reg);
	//printk("read reg 0x%x = 0x%x\n",reg&0xffff,sensor_read_reg16(bf3703.client,reg&0xffff));

	return count;
}


static DEVICE_ATTR(write, 0664, NULL, bf3703_write_store);
static DEVICE_ATTR(read, 0664, NULL, bf3703_read_store);

//static struct attribute *bf3703_attributes[] = {
	//&dev_attr_write.attr,
	//&dev_attr_read.attr,
	//NULL
//};

//static const struct attribute_group bf3703_attr_group = {
//	.attrs = bf3703_attributes,
//};

static int bf3703_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
	bf3703.client = client;

	//sysfs_create_group(&client->dev.kobj, &bf3703_attr_group);
	sensor_set_i2c_speed(client,400000);
	return camera_sensor_register(&bf3703.desc);
}

struct camera_sensor_ops bf3703_sensor_ops = {
	.sensor_init = bf3703_sensor_init,
	.camera_sensor_probe = bf3703_sensor_probe,
	.sensor_set_function = bf3703_set_function,
	.sensor_set_resolution = bf3703_set_resolution, 
	.sensor_set_parameter = bf3703_set_parameter, 
	.sensor_set_power = bf3703_set_power,
};

struct resolution_info bf3703_resolution_table[] = {	
	{640,480,16,PIXEL_FORMAT_YUV422I},	//
	{352,288,16,PIXEL_FORMAT_YUV422I},
	{320,240,16,PIXEL_FORMAT_YUV422I},	//
	{176,144,16,PIXEL_FORMAT_YUV422I},
};

struct bf3703_sensor bf3703 = {
	.desc = {
		.name = "bf3703",
		.wait_frames = 0,

		.ops = &bf3703_sensor_ops,

		.resolution_table = bf3703_resolution_table,
		.resolution_table_nr=ARRAY_SIZE(bf3703_resolution_table),

		.capture_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},
		.max_capture_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},

		.preview_parm = {640,480, 16,PIXEL_FORMAT_YUV422I}, 
		.max_preview_parm = {640,480, 16,PIXEL_FORMAT_YUV422I},

		.cfg_info = {
			.configure_register= 0x0
				|CIM_CFG_PACK_3			/* pack mode : 4 3 2 1 */
				|CIM_CFG_BYPASS			/* Bypass Mode */	
				|CIM_CFG_VSP             	/* VSYNC Polarity:1-falling edge active */
                	//      |CIM_CFG_HSP 
		//		|CIM_CFG_PCP             	/* PCLK working edge:1-falling */
				|CIM_CFG_DSM_GCM,		/* Gated Clock Mode */
		},

		.flags = {
			.effect_flag = 0
				|EFFECT_NONE
				|EFFECT_MONO
				|EFFECT_SEPIA
				|EFFECT_NEGATIVE 
				|EFFECT_AQUA,
			.balance_flag = 0
				| WHITE_BALANCE_AUTO 
				| WHITE_BALANCE_DAYLIGHT 
				| WHITE_BALANCE_CLOUDY_DAYLIGHT 
				| WHITE_BALANCE_INCANDESCENT,
			.antibanding_flag = ~0x0,
			.flash_mode_flag = 0,
			.scene_mode_flag = 0,
			.pixel_format_flag = 0,
			.focus_mode_flag = 0,
		},
	},
};

static const struct i2c_device_id bf3703_id[] = {
	{ "bf3703", 0 },
	{ }	/* Terminating entry */
};
MODULE_DEVICE_TABLE(i2c, bf3703_id);

static struct i2c_driver bf3703_driver = {
	.probe		= bf3703_i2c_probe,
	.id_table	= bf3703_id,
	.driver	= {
		.name = "bf3703",
	},
};

static int __init bf3703_i2c_register(void)
{
	return i2c_add_driver(&bf3703_driver);
}

module_init(bf3703_i2c_register);
<file_sep>/sys_program/2nd_day/am/vfork.c
/* ************************************************************************
 *       Filename:  vfork.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 10时28分00秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  王秋伟, 
 *        Company:  
 * ************************************************************************/
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


int gnum = 0;

int main(int argc, char *argv[])
{
	pid_t pid;
	int num = 1;

	//pid = fork();
	pid = vfork();

	if(pid < 0) perror("");

	else if(pid == 0)
	{
		int i;

		for(i=0;i<3;i++)
		{
			printf("in son process\n");
			gnum++;
			num++;
			sleep(1);
		}
		printf("in #son process\n");
		execl("/bin/ls","ls","-l","-h",NULL); //当调用exec函数后，用vfork创建的子进程也会有自己的地址空间，
											  //并且exec启动的程序会把，该地址空间的数据段、代码段和堆栈段覆盖掉
											  //所以就导致后面的printf打印不出信息
											  //当遇到exec函数，用vfork创建子进程的父进程将不再等待子进程执行完
											  //所以这里会先看到父进程for循环中打印出一条信息，然后再有 ls 执行的打印信息

		printf("in son# process\n"); //加了execl函数后，并没有把这条信息打印到屏幕

		//exit(2);// 退出子进程，并返回2，会刷新缓冲区
		//return 0;//加了这句，会弹栈，因为这里的子进程跟父进程共用同一地址空间，
		           //导致父进程找不到栈原来的内容，则出错，
				   //比如这里，返回后，父进程中访问num的值为0，而实际在子进程return前num ！= 0
	}
	else
	{
		int i;
		int status = 0;

		for(i=0;i<3;i++)
		{
			printf("in father process\n");
			printf("gnum = %d  num = %d\n",gnum,num);
			sleep(1);
		}
				
		//wait(&status);
		waitpid(-1,&status,0); // 这里跟 wait(&status) 一样

		if(WIFEXITED(status) != 0) //判断返回状态 ，存在status的低8位
		{
			printf("return = %d\n",WEXITSTATUS(status)); //取返回值，存在status的8~16位
		}
	}

	return 0;
}
<file_sep>/c/practice/bitree/bitree.c
/* ************************************************************************
 *       Filename:  bitree.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月06日 18时35分22秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct _BiTNode
{
	char data; //节点数据域
	struct _BiTNode *lchild, *rchild;  /*指向左孩子和右孩子*/
}BiTNode, *pBiTNode; 


/*创建一棵二叉树*/
//不管是先序或中序或后序创建二叉树，对遍历二叉树不影响
CreatBiTree(pBiTNode *T) // T为二级指针
{
	char ch;
	
	ch = getchar();
	getchar();
	
	printf("get = %c\n",ch);
	if(ch == ' ')
	{
		*T = NULL;
	}
	else
	{
		*T = (BiTNode *)malloc(sizeof(BiTNode));/*创建一个结点*/
		bzero(*T, sizeof(BiTNode));
		
		// * 运算符的优先级比 -> 运算符低
		(*T)->data = ch; //这条语句放这里是先序创建二叉树, 
		CreatBiTree(&((*T)->lchild)); // 递归创建左子树
		//(*T)->data = ch;
		CreatBiTree(&((*T)->rchild)); // 递归创建右子树
		//(*T)->data = ch;
	}
}

/*遍历二叉树*/
//先序
PreOrderTraverse(pBiTNode T,int level)
{
	if(T) 
	{	/*递归结束条件，T为空*/
		printf("level: %d  node: %c\n",level, T->data);
		PreOrderTraverse(T->lchild, level+1);
		PreOrderTraverse(T->rchild, level+1);
	}
}
//中序
MiOrderTraverse(pBiTNode T,int level)
{
	if(T) 
	{	/*递归结束条件，T为空*/	
		MiOrderTraverse(T->lchild, level+1);
		printf("level: %d  node: %c\n",level, T->data);
		MiOrderTraverse(T->rchild, level+1);
	}
}
//后序
PostOrderTraverse(pBiTNode T,int level)
{
	if(T) 
	{	/*递归结束条件，T为空*/	
		PostOrderTraverse(T->lchild, level+1);		
		PostOrderTraverse(T->rchild, level+1);
		printf("level: %d  node: %c\n",level, T->data);
	}
}

//统计二叉树叶子节点数
int CountLeaf(pBiTNode T)
{
	static int count = 0;
	
	if(T)
	{
		count = CountLeaf(T->lchild);
		if(T->lchild == NULL && T->rchild == NULL)
		{
			count++;
		}
		count = CountLeaf(T->rchild);
	}
	return count;
}

//求二叉树的深度
int TreeDepth(pBiTNode T)
{
	static int count = 0;
	
	if(T)
	{
		count++;
		count = TreeDepth(T->lchild);
		count = TreeDepth(T->rchild);
	}
	return count;
}

int main(int argc, char *argv[])
{
	int level = 1;
	int Node_num = 0,Depth_num = 0;
	pBiTNode T = NULL;  /*最开始T指向空*/

	CreatBiTree(&T);  			//创建二叉树，先画出树形图，根据图进行输入创建
	printf("\n先序遍历：\n");
	PreOrderTraverse(T,level); 	//遍历二叉树，找到包含D字符结点位于二叉树中的层数
	printf("\n中序遍历：\n");
	MiOrderTraverse(T,level); 	//遍历二叉树，找到包含D字符结点位于二叉树中的层数
	printf("\n后序遍历：\n");
	PostOrderTraverse(T,level); 	//遍历二叉树，找到包含D字符结点位于二叉树中的层数

	Node_num = CountLeaf(T);
	Depth_num = TreeDepth(T);
	printf("\nNode_num = %d, Depth_num = %d\n",Node_num,Depth_num);
	return 0;
}


<file_sep>/c/lrc/main.c
/* ************************************************************************
 *       Filename:  main.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 05時36分37秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include "common.h"
#include "process_lrc.h"
#include "start_mplayer.h"
#include "interface.h"
#include "file.h"
#include "link.h"


int main(int argc, char *argv[])
{
	char *lrc_src = NULL, **plines = NULL, *pheader[4] = {NULL};
	char *list_src = NULL, **plist = NULL;
	char playing = 0;    //播放标志，1 为正在播放
	int lines = 0, longestlength = 0, i = 0;
	int time = 0, maxtime = 0, timelag = 0;
	ulint lrc_length = 0;
	LRC *lrc_head = NULL, *pnode = NULL;
	struct timeval start_time,end_time;


	show_interface(); //
	list_src = get_musiclist(&plist);
	show_musiclist(plist);

	while(1)
	{
#if 1
		if(!playing)
		{

			mplayer_play("./music/喜欢你.mp3");
			lrc_src = read_src_file(&lrc_length, "lyric/喜欢你.lrc"); //读出歌词文件的内容到lrc_src指向的地址空间
			lines = check_lines(lrc_length, lrc_src);         //检测歌词有几行
			plines = (char **)malloc(lines*sizeof(char **));  //动态分配空间存储每行的首地址

			if(plines == NULL) goto out;                      //如果分配空间失败，退出程序

			src_segment(lrc_src, plines, "\r\n");	          //按行分割歌词

			lrc_head = build_link(plines, pheader, lines);    //按时间建立链表
			longestlength = get_longestlength(lrc_head);
			pnode = lrc_head;
			//print_link(lrc_head);
			show_lrcheader(pheader);

			maxtime = get_maxtime(lrc_head);
			timelag = maxtime/60;

			gettimeofday(&start_time,0);  //开始计时

			playing = 1; //
		}

		gettimeofday(&end_time,0);
		time = 1000000*(end_time.tv_sec - start_time.tv_sec) + end_time.tv_usec - start_time.tv_usec;
		time = (int)time/1000;  //除以1000则进行毫秒计时

		if(pnode != NULL && time >= pnode->time) //
		{
			show_lyric(pnode,longestlength);
			pnode = pnode->next;
		}

		show_progressbar(time,timelag);
		show_time(time, maxtime);

		if(pnode == NULL)
		{
			sleep(12);
			playing = 0;
			move = 1;    //在interface.c里定义，用于记录进度条的进度

			lrc_head = free_link(lrc_head);
			free(lrc_src);

		}
#endif
	}

	free(lrc_src);
	free_link(lrc_head);
	out:
	return 0;
}

<file_sep>/work/camera/bf3703/bf3703/bf3703_set.c
#include <linux/jz_cim_core.h>
#include <linux/jz_sensor.h>
#include <linux/i2c.h>
#include <asm/jzsoc.h>

//#define bf3703_DEBUG
#undef bf3703_DEBUG
#ifdef bf3703_DEBUG
#define dprintk(x...)   do{printk("bf3703-\t");printk(x);printk("\n");}while(0)
#else
#define dprintk(x...)
#endif

//for test
void retry_write_reg(struct i2c_client *client ,int addr, int value)
{
    int num = 0;
    sensor_write_reg(client,addr,value);
    while(sensor_read_reg(client,addr) != value)
    {
        num++;
        //printk("this is %d to retry_write_reg, addr is %d \n",num,addr);
        sensor_write_reg(client,addr,value);
        if(num > 10)
            break;
    }
}
//end


void preview_set(struct i2c_client *client)                   
{
	
}    //===preview setting end===

void set_size_640x480(struct i2c_client *client,int mode)
{
#if 1
		retry_write_reg(client,0x17,0x00);
		retry_write_reg(client,0x18,0xa0);
		retry_write_reg(client,0x19,0x00);
		retry_write_reg(client,0x1a,0x78);
		retry_write_reg(client,0x03,0x00);
		retry_write_reg(client,0x12,0x00);
		retry_write_reg(client,0x8e,0x05); 
		retry_write_reg(client,0x8f,0xfb);

       // frame
	//	retry_write_reg(client,0x0b,0x00);
#endif

	dprintk("VGA 640x480");
}  

void set_size_352x288(struct i2c_client *client,int mode)
{
#if 1
		retry_write_reg(client,0x17,0x36);
	    retry_write_reg(client,0x18,0x8e);
		retry_write_reg(client,0x19,0x1b);
		retry_write_reg(client,0x1a,0x63);
		retry_write_reg(client,0x03,0xf0);
		retry_write_reg(client,0x12,0x00);

		retry_write_reg(client,0x8e,0x03); 
		retry_write_reg(client,0x8f,0xfc);


       // frame
	//	retry_write_reg(client,0x0b,0x00);
#endif

	dprintk("CIF 352x288");
}  

void set_size_320x240(struct i2c_client *client,int mode)
{
	retry_write_reg(client,0x17,0x00);
	retry_write_reg(client,0x18,0xa0);
	retry_write_reg(client,0x19,0x00);
	retry_write_reg(client,0x1a,0x78);
	retry_write_reg(client,0x03,0x00);
	sensor_write_reg(client,0x12,0x10);	

	dprintk("QVGA 320x320");
}  

void set_size_176x144(struct i2c_client *client,int mode)
{

	sensor_write_reg(client,0x17,0x36);
	sensor_write_reg(client,0x18,0x8e);
	sensor_write_reg(client,0x19,0x1b);
	sensor_write_reg(client,0x1a,0x63);
	sensor_write_reg(client,0x03,0xf0);
	sensor_write_reg(client,0x12,0x10);

	dprintk("QCIF 176x144");
} 

void size_switch(struct i2c_client *client,int width,int height,int setmode)
{
	dprintk("%dx%d - mode(%d)",width,height,setmode);

	//return;
	if(width == 640 && height == 480)
	{
		set_size_640x480(client,setmode);
	} 
	else if(width == 352 && height == 288)
	{
		set_size_352x288(client,setmode);
	} 
	else if(width == 320 && height == 240)
	{
		set_size_320x240(client,setmode);
	}  
	else if(width == 176 && height == 144)
	{
		set_size_176x144(client,setmode);
	}  
	else
		return;
	//	mdelay(500);
}

void bf3703_reset(void);
void bf3703_init_setting(struct i2c_client *client)
{
	//SOFE RESET
	//retry_write_reg16(client,0x12,0x80);
	bf3703_reset();
	mdelay(10);	
	retry_write_reg(client,0x11,0x80);

	//retry_write_reg(client,0x11,0x80);//modify by huawu
	retry_write_reg(client,0x20,0x40);
	retry_write_reg(client,0x09,0xc0);
	//retry_write_reg(client,0x12,0x00); 
	retry_write_reg(client,0x13,0x00);
	retry_write_reg(client,0x01,0x13);
	retry_write_reg(client,0x01,0x13);//retry 01
	retry_write_reg(client,0x02,0x25);
	retry_write_reg(client,0x8c,0x02); 
	retry_write_reg(client,0x8d,0xfd);
	retry_write_reg(client,0x87,0x1a);
	retry_write_reg(client,0x13,0x07); 
	//POLARITY of Signal 
	retry_write_reg(client,0x15,0x00);
	retry_write_reg(client,0x3a,0x03);
	//black level ,对上电偏绿有改善,如果需要请使用
	/*                                             
	retry_write_reg(client,0x05,0x1f); 
	retry_write_reg(client,0x06,0x60); 
	retry_write_reg(client,0x14,0x1f); 
	retry_write_reg(client,0x06,0xe0); 
	*/
	/*
	retry_write_reg(client,0x17,0x00);
	retry_write_reg(client,0x18,0xa0);
	retry_write_reg(client,0x19,0x00);
	retry_write_reg(client,0x1a,0x78);
	retry_write_reg(client,0x03,0x00);
	*/
	//lens shading 
	retry_write_reg(client,0x35,0x68);
	retry_write_reg(client,0x65,0x68);
	retry_write_reg(client,0x66,0x62); 
	retry_write_reg(client,0x36,0x05); 
	retry_write_reg(client,0x37,0xf6); 
	retry_write_reg(client,0x38,0x46); 
	retry_write_reg(client,0x9b,0xf6); 
	retry_write_reg(client,0x9c,0x46); 
	retry_write_reg(client,0xbc,0x01); 
	retry_write_reg(client,0xbd,0xf6); 
	retry_write_reg(client,0xbe,0x46); 
	//AE 
	retry_write_reg(client,0x82,0x14); 
	retry_write_reg(client,0x83,0x23); 
	retry_write_reg(client,0x9a,0x23); 
	retry_write_reg(client,0x84,0x1a); 
	retry_write_reg(client,0x85,0x20); 
	retry_write_reg(client,0x89,0x04); 
	retry_write_reg(client,0x8a,0x08); 
	retry_write_reg(client,0x86,0x28); 
	retry_write_reg(client,0x96,0xa6); 
	retry_write_reg(client,0x97,0x0c); 
	retry_write_reg(client,0x98,0x18); 
	//AE target
	retry_write_reg(client,0x24,0x7a); 
	retry_write_reg(client,0x25,0x8a); 
	retry_write_reg(client,0x94,0x0a); 
	retry_write_reg(client,0x80,0x55); 
	//denoise 
	retry_write_reg(client,0x70,0x6f); 
	retry_write_reg(client,0x72,0x4f); 
	retry_write_reg(client,0x73,0x2f); 
	retry_write_reg(client,0x74,0x27); 
	retry_write_reg(client,0x7a,0x4e); 
	retry_write_reg(client,0x7b,0x28); 
	//black level  
	retry_write_reg(client,0X1F,0x20); 
	retry_write_reg(client,0X22,0x20); 
	retry_write_reg(client,0X26,0x20); 
	//模拟部分参数 
	retry_write_reg(client,0X16,0x00); 
	retry_write_reg(client,0xbb,0x20); 
	retry_write_reg(client,0xeb,0x30); 
	retry_write_reg(client,0xf5,0x21); 
	retry_write_reg(client,0xe1,0x3c); 
	retry_write_reg(client,0xbb,0x20); 
	retry_write_reg(client,0X2f,0X66); 
	retry_write_reg(client,0x06,0xe0); 
	 //anti black sun spot  
	retry_write_reg(client,0x61,0xd3); 
	retry_write_reg(client,0x79,0x48); 
     //Gamma  
	retry_write_reg(client,0x3b,0x60); 
	retry_write_reg(client,0x3c,0x20); 
	retry_write_reg(client,0x56,0x40); 
	retry_write_reg(client,0x39,0x80); 
	//gamma1 

	retry_write_reg(client,0x3f,0xa8); 
	retry_write_reg(client,0X40,0X48); 
	retry_write_reg(client,0X41,0X54); 
	retry_write_reg(client,0X42,0X4E); 
	retry_write_reg(client,0X43,0X44); 
	retry_write_reg(client,0X44,0X3e); 
	retry_write_reg(client,0X45,0X39); 
	retry_write_reg(client,0X46,0X35); 
	retry_write_reg(client,0X47,0X31); 
	retry_write_reg(client,0X48,0X2e); 
	retry_write_reg(client,0X49,0X2b); 
	retry_write_reg(client,0X4b,0X29); 
	retry_write_reg(client,0X4c,0X27); 
	retry_write_reg(client,0X4e,0X23); 
	retry_write_reg(client,0X4f,0X20); 
	retry_write_reg(client,0X50,0X20); 

	/*				
	//gamma2  高亮度 
	retry_write_reg(client,0x3f,0xc8); 
	retry_write_reg(client,0X40,0X9b); 
	retry_write_reg(client,0X41,0X88); 
	retry_write_reg(client,0X42,0X6e); 
	retry_write_reg(client,0X43,0X59); 
	retry_write_reg(client,0X44,0X4d); 
	retry_write_reg(client,0X45,0X45); 
	retry_write_reg(client,0X46,0X3e); 
	retry_write_reg(client,0X47,0X39); 
	retry_write_reg(client,0X48,0X35); 
	retry_write_reg(client,0X49,0X31); 
	retry_write_reg(client,0X4b,0X2e); 
	retry_write_reg(client,0X4c,0X2b); 
	retry_write_reg(client,0X4e,0X26); 
	retry_write_reg(client,0X4f,0X23); 
	retry_write_reg(client,0X50,0X1F); 

*/
	/*
	//gamma3 清晰亮丽
	retry_write_reg(client,0X3f,0Xa0); 
	retry_write_reg(client,0X40,0X60); 
	retry_write_reg(client,0X41,0X60); 
	retry_write_reg(client,0X42,0X66); 
	retry_write_reg(client,0X43,0X57); 
	retry_write_reg(client,0X44,0X4c); 
	retry_write_reg(client,0X45,0X43); 
	retry_write_reg(client,0X46,0X3c); 
	retry_write_reg(client,0X47,0X37); 
	retry_write_reg(client,0X48,0X32); 
	retry_write_reg(client,0X49,0X2f); 
	retry_write_reg(client,0X4b,0X2c); 
	retry_write_reg(client,0X4c,0X29); 
	retry_write_reg(client,0X4e,0X25); 
	retry_write_reg(client,0X4f,0X22); 
	retry_write_reg(client,0X50,0X20); 
	
	//gamma 4 	low noise	 
	retry_write_reg(client,0X3f,0Xa0); 
	retry_write_reg(client,0X40,0X48); 
	retry_write_reg(client,0X41,0X54); 
	retry_write_reg(client,0X42,0X4E); 
	retry_write_reg(client,0X43,0X44); 
	retry_write_reg(client,0X44,0X3E); 
	retry_write_reg(client,0X45,0X39); 
	retry_write_reg(client,0X46,0X34); 
	retry_write_reg(client,0X47,0X30); 
	retry_write_reg(client,0X48,0X2D); 
	retry_write_reg(client,0X49,0X2A); 
	retry_write_reg(client,0X4b,0X28); 
	retry_write_reg(client,0X4c,0X26); 
	retry_write_reg(client,0X4e,0X22); 
	retry_write_reg(client,0X4f,0X20); 
	retry_write_reg(client,0X50,0X1E); 
	*/
	
	//color matrix	
	//艳丽
	retry_write_reg(client,0x51,0x0d); 
	retry_write_reg(client,0x52,0x21); 
	retry_write_reg(client,0x53,0x14); 
	retry_write_reg(client,0x54,0x15); 
	retry_write_reg(client,0x57,0x8d); 
	retry_write_reg(client,0x58,0x78); 
	retry_write_reg(client,0x59,0x5f); 
	retry_write_reg(client,0x5a,0x84); 
	retry_write_reg(client,0x5b,0x25); 
	retry_write_reg(client,0x5c,0x0e); 
	retry_write_reg(client,0x5d,0x95); 

	 /* 
	 //适中
	retry_write_reg(client,0x51,0x06); 
	retry_write_reg(client,0x52,0x16); 
	retry_write_reg(client,0x53,0x10); 
	retry_write_reg(client,0x54,0x11); 
	retry_write_reg(client,0x57,0x62); 
	retry_write_reg(client,0x58,0x51); 
	retry_write_reg(client,0x59,0x49); 
	retry_write_reg(client,0x5a,0x65); 
	retry_write_reg(client,0x5b,0x1c); 
	retry_write_reg(client,0x5c,0x0e); 
	retry_write_reg(client,0x5d,0x95); 
	*/  
	  /*
	  //淡
	retry_write_reg(client,0x51,0x03); 
	retry_write_reg(client,0x52,0x0d); 
	retry_write_reg(client,0x53,0x0b); 
	retry_write_reg(client,0x54,0x14); 
	retry_write_reg(client,0x57,0x59); 
	retry_write_reg(client,0x58,0x45); 
	retry_write_reg(client,0x59,0x41); 
	retry_write_reg(client,0x5a,0x5f); 
	retry_write_reg(client,0x5b,0x1e); 
	retry_write_reg(client,0x5c,0x0e); 
	retry_write_reg(client,0x5d,0x95); 
	*/
	
	retry_write_reg(client,0x60,0x20); 
	//AWB	  
	retry_write_reg(client,0x6a,0x81); //01
	retry_write_reg(client,0x23,0x66); //Green gain
	retry_write_reg(client,0xa0,0x03); //07

	retry_write_reg(client,0xa1,0X41); 
	retry_write_reg(client,0xa2,0X0e); 
	retry_write_reg(client,0xa3,0X26); 
	retry_write_reg(client,0xa4,0X0d); 
	retry_write_reg(client,0xa5,0x28); 
	retry_write_reg(client,0xa6,0x04); 
	retry_write_reg(client,0xa7,0x80); 
	retry_write_reg(client,0xa8,0x80); 
	retry_write_reg(client,0xa9,0x28); 
	retry_write_reg(client,0xaa,0x28); 
	retry_write_reg(client,0xab,0x28); 
	retry_write_reg(client,0xac,0x3c); 
	retry_write_reg(client,0xad,0xf0); 
	retry_write_reg(client,0xc8,0x18); 
	retry_write_reg(client,0xc9,0x20); 
	retry_write_reg(client,0xca,0x17); 
	retry_write_reg(client,0xcb,0x1f); 
	retry_write_reg(client,0xaf,0x00); 
	retry_write_reg(client,0xc5,0x18); 
	retry_write_reg(client,0xc6,0x00); 
	retry_write_reg(client,0xc7,0x20); 
	retry_write_reg(client,0xae,0x81); //83
	retry_write_reg(client,0xcc,0x30);
	retry_write_reg(client,0xcd,0x70); 
	retry_write_reg(client,0xee,0x4c); 

	retry_write_reg(client,0xae,0x81); //83 retry ae
	// color saturation

	retry_write_reg(client,0xb0,0xd0); 
	retry_write_reg(client,0xb1,0xc0); 
	retry_write_reg(client,0xb2,0xb0); 
	retry_write_reg(client,0xb3,0x88); 

	//retry_write_reg(client,0x8e,0x05); //0x07,8帧//0x03,10
	//retry_write_reg(client,0x8f,0xfb); //0x79//0xfc,10
	retry_write_reg(client,0x9d,0x99); 

	//switch  
//	retry_write_reg(client,0x1e,0x00); //00,10,20,30
	retry_write_reg(client,0x1e,0x20); //00,10,20,30  //modify by huawu
	
}

uint32_t stop_ae(struct i2c_client *client)
{
	
	return 0;
}

void capture_set(struct i2c_client *client)
{
	
}

<file_sep>/work/debug/pc/timer/test_timer.c
/* ************************************************************************
 *       Filename:  test_timer.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月08日 10时43分53秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>

void main()
{
	int fd = 0;
	int counter = 0;
	int old_counter = 0;
	
	fd = open("/dev/timer_drv",O_RDONLY);
	
	if(fd != -1)
	{
		while(1)
		{
			read(fd,&counter,sizeof(unsigned int));
			if(counter != old_counter)
			{
				old_counter = counter;
				printf("seconds open /dev/timer_dev: %d\n",counter);
			}				
		}
	}
	else
	{
		printf("Device open failure!\n");
	}
}


<file_sep>/work/test/fibonacci/fibonacci.c

long long fibonacci(long i)
{
    long long fib1 = 1;
    long long fib2 = 1;
    long long temp;
    while(i > 2) {
	temp = fib2;
	fib2 = fib2 + fib1;
	fib1 = temp;
	i--;
    }

    return fib2;
}

int main(int argc, char *argv[])
{
    (void)fibonacci(30000000);
    return 0;
}
<file_sep>/work/debug/pc/snull/snull.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/in.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/skbuff.h>
#include <linux/in6.h>
#include <asm/checksum.h>
#include "snull.h"

static int lockup = 0;
module_param(lockup, int, 0);
static int timeout = SNULL_TIMEOUT;
module_param(timeout, int, 0);
struct net_device snull_devs[2];

int snull_open(struct net_device *dev)
{
    //将硬件（MAC）从硬件设备复制到dev->dev_addr
    memcpy(dev->dev_addr, "\0SNUL0", ETH_ALEN);
    if(dev == snull_devs[1])
        dev->dev_addr[ETH_ALEN - 1]++; /* \0SNUL1 */

    netif_start_queue(dev);//启动接口的传输队列，允许接口接受传输包
    return 0;
}

int snull_release(struct net_device *dev)
{
    netif_stop_queue(dev);//在接口被关闭时，必须调用该函数，但该函数也可以用来临时停止传输。
    return 0;
}

int snull_config(struct net_device *dev, struct ifmap *map)
{
    if(dev->flags & IFF_UP)
        return -EBUSY;
    if(map->base_addr != dev->base_addr) {
        printk(KERN_WARNING "snull: Can't change I/O address\n");
        return -EOPNOTSUPP;
    }

    if(map->irq != dev->irq)
        dev->irq = map->irq;

    return 0;
}

void snull_rx(struct net_device *dev, int len, unsigned char *buf)
{
    struct sk_buff *skb;
    struct snull_priv *prvi = netdev_priv(dev);

    skb = dev_alloc_skb(len + 2);//分配一个保存数据包的缓冲区
    if(!skb) {
        printk("snull rx: low on mem - packet dropped\n");
        priv->stats.rx_dropped++;
        return;
    }

    skb_reserve(skb, 2);
    memcpy(skb_put(skb, len), buf, len);//skb_put函数刷新缓冲区内的数据末尾指针，并且返回新创建数据区的指针
    skb->dev = dev;
    skb->protocol = eth_type_trans(skb, dev);
    skb->ip_summed = CHECKSUM_UNNECESSARY;
    priv->stats.rx_packets++;
    priv->stats.rx_bytes += len;
    netif_rx(skb);//将套接字缓冲区传递给上层软件处理
    return;
}

void snull_interrupt(int irq, void *dev_id, struct pt_regs *regs)
{
    int statusword;
    struct net_device *dev = (struct net_device *)dev_id;
    struct snull_priv *priv = netdev_priv(dev);

    if(!dev)
        return;
    spin_lock(&priv->lock);
    statusword = priv->status;
    priv->status = 0;

    if(statusword & SNULL_RX_INTR)
        snull_rx(dev, priv->rx_packetlen, priv->rx_packetdata);

    if(statusword & SNULL_TX_INTR) {
        priv->stats.tx_packets++;
        priv->stats.tx_bytes += priv->tx_packetlen;
        dev_kfree_skb(priv->skb);
    }
    spin_unlock(&priv->lock);

    return;
}

void snull_tx_timeout(struct net_device *dev)
{
    struct snull_priv = netdev_priv(dev);
    printk(KERN_INFO"Transmit timeout at %ld, latency %ld\n", jiffies,jiffies - dev->trans_start);

    priv->status = SNULL_TX_INTR;
    snull_interrupt(0, dev, NULL); // 模拟一个传输中断
    priv->stats.tx_errors++;
    netif_wake_queue(dev);
    return;
}

void snull_hw_tx(char *buf, int len, struct net_device *dev)
{
    struct iphdr *ih;
    struct net_device *dest;
    struct snull_priv *priv = netdev_priv(dev);
    unsigned long *saddr, *daddr;

    if(len < sizeof(struct ethhdr) + sizeof(struct ipdhr)){
        printk("snull: Hmm... packet too short (%i octets)\n", len);
        return;
    }

    ih = (struct iphdr *)(buf + sizeof(struct iphdr));
    saddr = &ih->saddr;
    daddr = &ih->daddr;

    ((u8 *)saddr)[2] ^= 1;
    ((u8 *)daddr)[2] ^= 1;

    ih->check = 0;
    /* 重新计算ip校验和，正常情况下还应该重新计算tcp头校验和，icmp头检验和.. */
    ih->check = ip_fast_csum((u8 *)ih, ih->ihl);

    if(dev == snull_devs[0])
        printk(KERN_INFO"%08x:%05i --> %08x:%05i\n",
               ntohl(ih->saddr),ntohs(((struct tcphdr *)(ih+1))->source),
               ntohl(ih->daddr),ntohs(((struct tcphdr *)(ih+1))->dest));
    else
        printk(KERN_INFO"%08x:%05i <-- %08x:%05i\n",
               ntohl(ih->daddr),ntohs(((struct tcphdr *)(ih+1))->dest),
               ntohl(ih->saddr),ntohs(((struct tcphdr *)(ih+1))->source));

    dest = snull_devs[dev == snull_devs[0] ? 1 : 0];
    priv->status = SNULL_RX_INTR;
    priv->rx_packetlen = len;
    priv->rx_packetdata = buf;
    snull_interrupt(0, dest, NULL); // 产生中断--->接收

    priv->status = SNULL_TX_INTR;
    priv->tx_packetlen = len;
    priv->tx_packetdata = buf;

    if (lockup && ((priv->stats.tx_packets + 1) % lockup) == 0) {
        netif_stop_queue(dev);
        printk(KERN_INFO"Simulate lockup at %ld, txp %ld\n", jiffies,(unsigned long) priv->stats.tx_packets);
    }
    else
        snull_interrupt(0, dev, NULL);// 产生中断--->发送

    return;
}

int snull_tx(struct sk_buff *skb, struct net_device *dev)
{
    int len;
    chat *data, shortpkt[ETH_ZLEN];
    struct snull_priv *priv = netdev_priv(dev);

    data = skb->data;
    len =skb->len;
    if(len < ETH_ZLEN) {
        memset(shortpkt, 0, ETH_ZLEN);
        memcpy(shortpkt, skb->data, len);
        data = shortpkt;
    }

    dev->trans_start = jiffies; //保存时间
    priv->sbk = skb;            //记住skb，以便释放
    snull_hw_tx(data, len, dev);//硬件相关的传输函数

    return 0;
}

int snull_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
{
    return 0;
}

struct net_device_stats *snull_stats(struct net_device *dev)
{
    struct snull_priv = netdev_priv(dev);
    return &priv->stats;
}

int snull_rebuild_header(struct sk_buff *skb)
{
    struct ethhdr *eth = (struct ethhdr *)skb->data;
    struct net_device *dev = skb->dev;

    memcpy(eth->h_source, dev->dev_addr, dev->addr_len);
    memcpy(eth->h_dest, dev->dev_addr, dev->addr_len);
    eth->h_dest[ETH_ALEN - 1] ^= 0x01;
    return 0;
}

int snull_header(struct sk_buff *skb, struct net_device *dev,
                 unsigned short type, const void *daddr, const void *saddr,
                 unsigned int len)
{
    struct ethhdr *eth = (struct ethhdr *)skb_push(skb, ETH_HLEN);

    eth->h_proto = htons(type);
    memcpy(eth->h_source, saddr?saddr:dev->dev_addr, dev->addr_len);
    memcpy(eth->h_dest, daddr?daddr:dev->dev_addr, dev->addr_len);
    eth->h_dest[ETH_ALEN - 1] ^= 0x01;

    return (dev->hard_harder_len);
}

int snull_change_mtu(struct net_device *dev, int new_mtu)
{
    unsigned long flags;
    struct snull_priv *priv = netdev_priv(dev);
    spinlock_t *lock = &priv->lock;

    if((new_mtu < 68) || (new_mtu > 1500)) //以太网的MTU是1500个octet（ETH_DATA_LEN）
        return -EINVAL;
    spin_lock_irqsave(lock, flags);
    dev->mtu = new_mtu;
    spin_unlock_irqsave(lock, flags);
    return 0;
}

//以下两个结构是相关接口函数的初始化
static const struct net_device_ops snull_dev_ops = {
    .ndo_open       = snull_open,
    .ndo_stop       = snull_release,
    .ndo_set_config = snull_config,
    .ndo_start_xmit = snull_tx,
    .ndo_do_ioctl   = snull_ioctl,
    .ndo_get_stats  = snull_stats,
    .ndo_change_mtu = snull_change_mtu,
    .ndo_tx_timeout = snull_tx_timeout,
};

static const struct header_ops snull_header_ops = {
    .creat   = snull_header,
    .rebuild = snull_rebuild_header,
    .cache   = NULL,
};

static void snull_init_netdev(struct net_device *dev)
{
    struct snull_priv *priv = NULL;

    ether_setup(dev);//对某些成员作一些初始化
    dev->netdev_ops = &snull_dev_ops;
    dev->header_ops = &snull_header_ops;
    dev->watchdog_timeo = timeout;
    dev->flags |= IFF_NOARP;    //禁止ARP
    dev->features |= NETIF_F_NO_CSUM;

    priv = netdev_priv(dev);//priv是net_device中的一个成员，它与net_device一起被分配，当需要访问私有成员priv时使用该函数
    memset(priv, 0, sizeof(struct snull_priv));
    priv->dev = dev;
    spin_lock_init(&priv->lock);
    return;
}

static __init int snull_init(void)
{
    int ret, i;

    snull_devs[0] = alloc_netdev(sizeof(struct snull_priv), "sn%d", snull_init_netdev);
    snull_devs[1] = alloc_netdev(sizeof(struct snull_priv), "sn%d", snull_init_netdev);

    if(snull_devs[0] == NULL || snull_devs[1] == NULL) {
        for(i = 0; i < 2; i++) {
            if(snull_devs[i] != NULL)
                free_netdev(snull_devs[i]);    //将net_device结构返还给系统
        }
        goto fail0;
    }

    for(i = 0; i < 2; i++) {
        //注册设备，必须在初始化一切事情后再注册
        ret = register_netdev(snull_devs[i]);
        if(ret) {
            printk("snull: error %i registering device \"%s\"\n",result, snull_devs[i]->name);
            break;
        }
    }

    if(i != 2) {
         while(i >= 0)
            unregister_netdev(snull_devs[i]);    //从系统中删除接口
         goto fail1
    }

    return 0;
fail1:
    free_netdev(snull_devs[0]);
    free_netdev(snull_devs[1]);
fail0:
    return -ENODEV;
}

static __exit void snull_exit(void)
{
    int i;
    for(i=0; i<2;i++) {
        if(snull_devs[i]) {
            unregister_netdev(snull_devs[i]); //从系统中删除接口
            free_netdev(snull_devs[i]); //将net_device结构返还给系统
        }
    }
    return;
}

module_init(snull_init);
module_exit(snull_exit);

MODULE_VERSION("snull_v1.0");
MODULE_LICENSE("GPL");<file_sep>/work/debug/pc/snull/snull.h
#ifndef __SNULL_H__
#define __SNULL_H__

#define u8  unsigned short
#define u32 unsigned long

#define SNULL_RX_INTR 0x0001
#define SNULL_TX_INTR 0x0002
#define SNULL_TIMEOUT 5

struct snull_prib {
    int status;
    int rx_packetlen;
    int tx_packetlen;
    unsigned short *rx_packetdata;
    unsigned short *tx_packetdata;

    spinlock_t lock;
    struct sk_buff *skb;
    struct net_device *dev;
    struct net_device_stats stats;
};

#endif
<file_sep>/gtk/4st_week/gtk_entry.c
/* ************************************************************************
 *       Filename:  entry.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 14时28分21秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <gtk/gtk.h>


void entry_callback(GtkWidget *widget, gpointer entry)
{
	const gchar *entry_text;

	entry_text = (gchar *)gtk_entry_get_text(GTK_ENTRY(entry));
	printf("Entry contents: %s\n",entry_text);	
}

int main(int argc, char *argv[])
{
	gtk_init(&argc,&argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title(GTK_WINDOW(window),"GTK entry");

	GtkWidget *vbox1 = gtk_vbox_new(TRUE, 5); //创建一个垂直布局容器
	gtk_container_add(GTK_CONTAINER(window), vbox1);
	
	GtkWidget *hbox1 = gtk_hbox_new(TRUE, 0); //创建一个水平布局容器
	gtk_container_add(GTK_CONTAINER(vbox1), hbox1); //加入垂直布局里面
	
	GtkWidget *label = gtk_label_new("text: ");
	gtk_container_add(GTK_CONTAINER(hbox1), label); //加入垂直布局里面
	
	GtkWidget *entry = gtk_entry_new(); //创建行编辑	
	gtk_entry_set_max_length(GTK_ENTRY(entry), 100);//设置行编辑显示最大字符的长度
	//gtk_entry_set_text(GTK_ENTRY(entry), "hello world");//设置显示内容
	gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE); //密码模式
	gtk_container_add(GTK_CONTAINER(hbox1), entry); //加入水平布局里面

	g_signal_connect(entry, "activate",G_CALLBACK(entry_callback), entry);

	GtkWidget *vbox2 = gtk_vbox_new(TRUE, 5); //创建一个垂直布局容器
	gtk_container_add(GTK_CONTAINER(window), vbox2);
	
	GtkWidget *hbox2 = gtk_hbox_new(TRUE, 0); //创建一个水平布局容器
	

	GtkWidget *button1 = gtk_button_new_with_label("button 1");
	gtk_container_add(GTK_CONTAINER(hbox2), button1);

	GtkWidget *button2 = gtk_button_new_with_label("button 2");
	gtk_container_add(GTK_CONTAINER(hbox2), button2);
	gtk_container_add(GTK_CONTAINER(vbox2), hbox2);
	
	GtkWidget *button_close = gtk_button_new_with_label("close");	
	g_signal_connect(button_close,"clicked", G_CALLBACK(gtk_main_quit),NULL);
	gtk_container_add(GTK_CONTAINER(vbox2), button_close);

	gtk_widget_show_all(window);

	gtk_main();
	return 0;
}


<file_sep>/network/1st_day/qq.c
/* ************************************************************************
 *       Filename:  qq.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月31日 19时32分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

void *pthread_sndmsg(void *arg)
{
	int snd_fd = 0;
	unsigned short port = 8000;
	char server_ip[INET_ADDRSTRLEN] = "127.0.0.1";

	snd_fd = socket(AF_INET, SOCK_DGRAM, 0);

	//配置服务器地址
	struct sockaddr_in server_addr;
	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);//服务器的端口
	inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);//服务器的IP

	while(1)
	{
		char msg[128] = "";
		char buf[10]  = "";

		bzero(msg, sizeof(msg));
		bzero(buf, sizeof(buf));

		printf("\033[34mQQudp:\033[0m");
		fflush(stdout);
		fgets(msg,sizeof(msg),stdin);
		msg[strlen(msg) - 1] = 0;
		//printf("sndmsg = %s\n", msg);
		sscanf(msg,"%[^ ]",buf);

		if(strcmp("sayto",buf) == 0)
		{
			int ret = 0;
			sscanf(msg,"%*[^ ] %s",server_ip);
			//printf("server_ip = %s##\n", server_ip);
			ret = inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);

			if(ret == 1)
			{
				printf("connect %s successful!!\n",server_ip);
			}
			else
			{
				printf("cannot connect to %s\n",server_ip);
			}
		}
		else if(strlen(msg) != 0)
		{
			sendto(snd_fd, msg, strlen(msg), 0,\
				  (struct sockaddr *)&server_addr, sizeof(server_addr));
		}
	}

	return NULL;
}

void *pthread_rcvmsg(void *arg)
{
	char msg[128];
	char ip_buf[INET_ADDRSTRLEN] = "";
	//创建一个通信socket
	int rvc_fd = socket(AF_INET, SOCK_DGRAM, 0);

	//作为一个服务器应该有一个固定的ip、port
	struct sockaddr_in addr;
	addr.sin_family = AF_INET;
	addr.sin_port = htons(8000);
	//INADDR_ANY: 通配地址
	addr.sin_addr.s_addr = htonl(INADDR_ANY);

	//bind只能bind自己的ip
	bind(rvc_fd, (struct sockaddr *)&addr, sizeof(addr));

	struct sockaddr_in client_addr;
	socklen_t client_len = sizeof(client_addr);
	bzero(&client_addr, sizeof(client_addr));

	while(1)
	{
		//接收client发送来的数据
		bzero(msg, sizeof(msg));
		recvfrom(rvc_fd, msg, sizeof(msg), 0, (struct sockaddr *)&client_addr, &client_len);
		inet_ntop(AF_INET, &client_addr.sin_addr.s_addr, ip_buf, INET_ADDRSTRLEN);

		printf("\033[32m\r[%s]: %s\033[0m\n",ip_buf, msg);
		printf("\033[34mQQudp:\033[0m");
		fflush(stdout);
		//printf("port:%d\n",ntohs(client_addr.sin_port));
	}

	return NULL;
}

int main(int argc, char *argv[])
{
	pthread_t pth_snd, pth_rcv;

	pthread_create(&pth_snd, NULL,pthread_sndmsg, NULL);
	pthread_create(&pth_rcv, NULL,pthread_rcvmsg, NULL);

	pthread_detach(pth_rcv);
	pthread_detach(pth_snd);

	while(1)
	{
		sleep(10);
	}
	return 0;
}
<file_sep>/work/test/timer/timer.c
/*************************************************************************
	> Filename: timer.c
	>   Author:
	>    Email: <EMAIL> / <EMAIL>
	> Datatime: Wed 04 Jan 2017 02:22:26 PM CST
 ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#include <signal.h>
#include <pthread.h>
#include <errno.h>
#include <time.h>

#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/epoll.h>
#include <sys/syscall.h>
#include <sys/time.h>
#include <sys/timerfd.h>


#if 1
/*
 * POSIX Timer
 */
static int counter = 0;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void print_time(void)
{
    struct timeval tv;

    gettimeofday(&tv, NULL);
    printf("Current time: %ld.%ld\n",tv.tv_sec, tv.tv_usec);
}

void timer_thread(union sigval sgv)
{
    pthread_mutex_lock(&mutex);
    if (++counter >= 8)
        pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);

    pid_t tid = (pid_t)syscall(SYS_gettid);
    printf("Timer %d in PID:[%d], TID:[%d]\n", *((int *)(sgv.sival_ptr)), getpid(), tid);
    print_time();
}

int main(int argc, char *argv[])
{
    timer_t timerid1, timerid2;
    struct sigevent evp1, evp2;
    struct itimerspec its1, its2;

    /*
     * create timer
     */
    bzero(&evp1, sizeof(evp1));
    evp1.sigev_notify = SIGEV_THREAD;
    evp1.sigev_value.sival_ptr = &timerid1;
    evp1.sigev_notify_function = timer_thread;
    evp1.sigev_notify_attributes = NULL;
    if (timer_create(CLOCK_MONOTONIC, &evp1, &timerid1) < 0) {
        printf("Failed to create timer1: %s", strerror(errno));
        return -1;
    }

    bzero(&evp2, sizeof(evp2));
    evp2.sigev_notify = SIGEV_THREAD;
    evp2.sigev_value.sival_ptr = &timerid2;
    evp2.sigev_notify_function = timer_thread;
    evp2.sigev_notify_attributes = NULL;
    if (timer_create(CLOCK_MONOTONIC, &evp2, &timerid2) < 0) {
        printf("Failed to create timer2: %s", strerror(errno));
        return -1;
    }

    /*
     * start timer
     */
    its1.it_interval.tv_sec = 2;
    its1.it_interval.tv_nsec = 0;
    its1.it_value.tv_sec = 3;
    its1.it_value.tv_nsec = 0;
    if (timer_settime(timerid1, 0, &its1, NULL) < 0) {
        printf("Failed to set timer1: %s\n", strerror(errno));
        return -1;
    }

    its2.it_interval.tv_sec = 1;
    its2.it_interval.tv_nsec = 0;
    its2.it_value.tv_sec = 5;
    its2.it_value.tv_nsec = 0;
    if (timer_settime(timerid2, 0, &its2, NULL) < 0) {
        printf("Failed to set timer2: %s\n", strerror(errno));
        return -1;
    }

    print_time();
    while(counter < 8)
        pthread_cond_wait(&cond, &mutex);

    return 0;
}
#elif 0
/*
 * setitimer
 */
static int cnt = 0;

void print_time(void)
{
    struct timeval tv;

    gettimeofday(&tv, NULL);
    printf("Current time: %ld.%ld, cnt = %d\n",tv.tv_sec, tv.tv_usec, cnt);
}

void sighandler(int signo)
{
    switch(signo) {
    case SIGALRM:
        printf("Timer fired, signo: %s\n", "SIGALRM");
        break;
    case SIGVTALRM:
        printf("Timer fired, signo: %s\n", "SIGVTALRM");
        break;
    case SIGPROF:
        printf("Timer fired, signo: %s\n", "SIGPROF");
        break;
    }

    cnt++;
    print_time();
}

int main(int argc, char *argv[])
{
    struct sigaction act;
    struct itimerval val;

    /*
     * init sigaction
     */
    act.sa_handler = sighandler;
    act.sa_flags = 0;                           //见注 3)
    //act.sa_flags = SA_RESETHAND | SA_NODEFER; //见注 2)
    //sigaddset(&act.sa_mask, SIGQUIT);         //见注 1)
    sigemptyset(&act.sa_mask);
    sigaction(SIGPROF, &act, NULL);

    /*
     * init timer
     */
    val.it_value.tv_sec = 5;
    val.it_value.tv_usec = 0;
    val.it_interval.tv_sec = 3;
    val.it_interval.tv_usec = 0;
    setitimer(ITIMER_PROF, &val, NULL);

    print_time();

    while(cnt < 4)
        usleep(100);

    return 0;
}

/**
 * 注：
 * 1) 如果在信号SIGINT(Ctrl + c)的信号处理函数show_handler执行过程中，本进程收到信号SIGQUIT(Crt+\)，将阻塞该信号，直到show_handler执行结束才会处理信号SIGQUIT。
 *
 * 2) SA_NODEFER  :一般情况下，当信号处理函数运行时，内核将阻塞<该给定信号:SIGINT>。但是如果设置了SA_NODEFER标记，那么在该信号处理函数运行时，内核将不会阻塞该
 *                 信号。SA_NODEFER是这个标记的正式的POSIX名字(还有一个名字SA_NOMASK，为了软件的可移植性，一般不用这个名字)
 *
 *    SA_RESETHAND:当调用信号处理函数时，将信号的处理函数重置为缺省值。 SA_RESETHAND是这个标记的正式的POSIX名字(还有一个名字SA_ONESHOT，为了软件的可移植性，一般不用这个名字)
 *
 * 3) 如果不需要重置该给定信号的处理函数为缺省值；并且不需要阻塞该给定信号(无须设置sa_flags标志)，那么必须将sa_flags清零，否则运行将会产生段错误。但是sa_flags清零后可能会造成信号丢失！
 */
#endif
<file_sep>/work/test/cim_test-zmm220/sensor.h
/*************************************************
                                           
 ZEM 200                                          
                                                    
 sensor.h 
                                                      
 Copyright (C) 2003-2006, ZKSoftware Inc.      		
                                                      
*************************************************/

#ifndef	_SENSOR_H_
#define	_SENSOR_H_

#define CMOS_WIDTH 	640
#define CMOS_HEIGHT 	480

void InitSensor(int LeftLine, int TopLine, int Width, int Height, int FPReaderOpt);
void FreeSensor(void);
int CaptureSensor(char *Buffer);

#endif

<file_sep>/gtk/4st_week/gtk_button.c
/* ************************************************************************
 *       Filename:  gtk_button.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 10时14分55秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <gtk/gtk.h>

int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);

	gtk_container_set_border_width(GTK_CONTAINER(window),15);

	GtkWidget *button = gtk_button_new_with_label("button");

	const char *str =  gtk_button_get_label(GTK_BUTTON(button));

	printf("str =  %s\n",str);

	gtk_container_add(GTK_CONTAINER(window),button);


	gtk_widget_show_all(window);

	gtk_main();

	return 0;

}


<file_sep>/network/sockets/UDPEchoClient.c
/*************************************************************************
	> File Name: UDPEchoClient.c
	> Author: 
	> Mail: 
	> Created Time: Mon 16 May 2016 04:50:18 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Practical.h"

int main(int argc, char *argv[])
{
    if(argc < 3 || argc > 4)
        DieWithUserMessage("Parameter(s)",
            "<Server Address/Name> <Echo Word> [<Server Port/Service]");

    char *server = argv[1];
    char *echoString = argv[2];

    size_t echoStringLen = strlen(echoString);
    if(echoStringLen > MAXSTRINGLENGTH) //Check input length
        DieWithUserMessage(echoString, "string too long");

    //Thrid arg(optional): server port/service
    char *servPort = argv[3];

    //Tell the system what kind(s) of address info we want
    struct addrinfo addrCriteria;
    memset(&addrCriteria, 0, sizeof(addrCriteria));
    addrCriteria.ai_family = AF_UNSPEC;
    addrCriteria.ai_socktype = SOCK_DGRAM;  //Only datagram sockets
    addrCriteria.ai_protocol = IPPROTO_UDP; //Onlu UDP protocol

   //Get address(es)
   struct addrinfo *servAddr;
   int rtnVal = getaddrinfo(server, servPort, &addrCriteria, &servAddr);
   if(rtnVal != 0)
       DieWithUserMessage("getaddrinfo() failed", gai_strerror(rtnVal));

   //Create a datagram/UDP socket
   int sock = socket(servAddr->ai_family, servAddr->ai_socktype, servAddr->ai_protocol);

   if(sock < 0)
       DieWithSystemMessage("socket() failed");

   //Send the string to server
   ssize_t numBytes = sendto(sock, echoString, echoStringLen, 0,
           servAddr->ai_addr, servAddr->ai_addrlen);

   if(numBytes < 0)
       DieWithSystemMessage("sendto() failed");
   else if(numBytes != echoStringLen)
       DieWithUserMessage("sendto() error", "sent unexpected number of bytes");

   //Receive a response
   struct sockaddr_storage fromAddr; //Source address of server
   socklen_t fromAddrLen = sizeof(fromAddr);
   char buffer[MAXSTRINGLENGTH + 1] = {0};
   numBytes = recvfrom(sock, buffer, MAXSTRINGLENGTH, 0,
                (struct sockaddr *)&fromAddr, &fromAddrLen);

   if(numBytes < 0)
       DieWithSystemMessage("recvfrom() failed");
   else if(numBytes != echoStringLen)
       DieWithUserMessage("recvfrom() error", "received unexpected number of bytes");

   //Verify reception from expected source
   if(!SockAddrsEqual(servAddr->ai_addr, (struct sockaddr *)&fromAddr))
       DieWithUserMessage("recvfrom()","received a packet from unknown source");

   freeaddrinfo(servAddr);
   buffer[MAXSTRINGLENGTH] = '\n';
   printf("Received: %s\n", buffer);

   close(sock);
   return 0;
}
<file_sep>/shell/2nd_week/with_param_option2
#!/bin/bash

while getopts :ab:cd opt
do
	case "$opt" in
	a) echo "-a option";;
	b) echo "-b option,with parameter value $OPTARG";;
	c) echo "-c option";;
	d) echo "-d option";;
	*) echo "Unknown option: $opt";;
	esac
done
shift $[ $OPIND + 2 ]
count=1

for param in $@
do
	echo "Parameter #$count: $param"
	count=$[ $count + 1 ]
done

<file_sep>/gtk/4st_week/gtk_login.c
/* ************************************************************************
 *       Filename:  login.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 14时27分03秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <gtk/gtk.h>

#define PSW  "123456"

char psw[50] = "";

/* 功能：  设置背景图
 * widget: 主窗口
 * w, h:   图片的大小
 * path：  图片路径
 */
static void chang_background(GtkWidget *widget, int w, int h, const gchar *path)
{
	gtk_widget_set_app_paintable(widget, TRUE);		//允许窗口可以绘图
    gtk_widget_realize(widget);	
	
	/* 更改背景图时，图片会重叠
	 * 这时要手动调用下面的函数，让窗口绘图区域失效，产生窗口重绘制事件（即 expose 事件）。
	 */
	gtk_widget_queue_draw(widget);
	
    GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(path, NULL);	// 创建图片资源对象
    // w, h是指定图片的宽度和高度
    GdkPixbuf *dst_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR);

	GdkPixmap *pixmap = NULL;
	
	/* 创建pixmap图像; 
	 * NULL：不需要蒙版; 
	 * 123： 0~255，透明到不透明
	 */
    gdk_pixbuf_render_pixmap_and_mask(dst_pixbuf, &pixmap, NULL, 50);
    // 通过pixmap给widget设置一张背景图，最后一个参数必须为: FASLE
	gdk_window_set_back_pixmap(widget->window, pixmap, FALSE);
    
	// 释放资源
	g_object_unref(src_pixbuf);
    g_object_unref(dst_pixbuf);
    g_object_unref(pixmap);
}

void entry_callback(GtkWidget *widget, gpointer entry)
{
	const gchar *entry_text;

	entry_text = (gchar *)gtk_entry_get_text(GTK_ENTRY(entry));
	printf("Entry contents: %s\n",entry_text);
	
	if(strcmp(entry_text, PSW) == 0)
	{
		printf("Entry password right!\n");
	}
	else
	{
		char empty[] = "";
		gtk_entry_set_text(GTK_ENTRY(entry), empty);//设置显示内容
		
		printf("Entry password wrong!\n");
	}
}
void num_callback(GtkButton *button, gpointer entry)
{
	const char *button_label = gtk_button_get_label(button);
	
	gtk_entry_append_text(GTK_ENTRY(entry), button_label);
	
	//strcat(psw,button_label);
	//gtk_entry_set_text(GTK_ENTRY(entry), psw);//设置显示内容
}

void button_callback(GtkButton *button, gpointer entry)
{
	const char *button_label = gtk_button_get_label(button);
	
	gint len = GTK_ENTRY(entry)->text_length;
	
	if(strcmp(button_label,"<-") == 0)
	{
		gtk_editable_delete_text(GTK_EDITABLE(entry), len-1,len);
	}
	else if(strcmp(button_label,"sure") == 0)
	{
		const char *databuf = gtk_entry_get_text(GTK_ENTRY(entry));
		
		if(strcmp(databuf,PSW) == 0)
		{
			printf("Entry password right!\n");
		}
		else
		{
			char empty[] = "";
			gtk_entry_set_text(GTK_ENTRY(entry), empty);//设置显示内容
			
			printf("Entry password wrong!\n");
		}
	}
}
int main(int argc, char *argv[])
{
	int i, j, num = 0;


	
	gtk_init(&argc,&argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title(GTK_WINDOW(window),"GTK entry");

	gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);//设置窗口的位置
	gtk_widget_set_size_request(window, 500, 300);	               //设置窗口的大小	
	gtk_window_set_resizable(GTK_WINDOW(window),FALSE);            //设置窗口是否可以改变大小

	g_signal_connect(window,"destroy",G_CALLBACK(gtk_main_quit),NULL);	
	
	GtkWidget *table = gtk_table_new(4,6,TRUE); //创建一个三行六列的表格容器

	GtkWidget *entry = gtk_entry_new();                    //创建行编辑	
	gtk_entry_set_max_length(GTK_ENTRY(entry), 100);       //设置行编辑显示最大字符的长度
	//gtk_entry_set_text(GTK_ENTRY(entry), "hello world"); //设置显示内容
	gtk_entry_set_visibility(GTK_ENTRY(entry), FALSE);     //密码模式
	
	//创建一个标签
	GtkWidget *label = gtk_label_new("password: ");
	gtk_table_attach_defaults(GTK_TABLE(table),label,0,1,0,1);
	gtk_table_attach_defaults(GTK_TABLE(table),entry,1,6,0,1); //
	for(i=2;i<4;i++)
	{
		for(j=0;j<5;j++)
		{
			char pnum[3] = "";
			sprintf(pnum,"%d",num);
			GtkWidget *button = gtk_button_new_with_label(pnum);
			num++;
			gtk_widget_set_size_request(button, 60, 35); 
			gtk_table_attach_defaults(GTK_TABLE(table),button,j,j+1,i,i+1);			 
			g_signal_connect(button, "pressed", G_CALLBACK(num_callback), entry); 
		}
	}
#if 0		
	GtkWidget *button0 = gtk_button_new_with_label("0");
	GtkWidget *button1 = gtk_button_new_with_label("1");		
	GtkWidget *button2 = gtk_button_new_with_label("2");
	GtkWidget *button3 = gtk_button_new_with_label("3");
	GtkWidget *button4 = gtk_button_new_with_label("4");
	GtkWidget *button5 = gtk_button_new_with_label("5");
	GtkWidget *button6 = gtk_button_new_with_label("6");
	GtkWidget *button7 = gtk_button_new_with_label("7");
	GtkWidget *button8 = gtk_button_new_with_label("8");
	GtkWidget *button9 = gtk_button_new_with_label("9");
	
	GtkWidget *sure   = gtk_button_new_with_label("sure");
	GtkWidget *delete = gtk_button_new_with_label("<-");
	
	gtk_table_attach_defaults(GTK_TABLE(table),button0,0,1,2,3);
	gtk_table_attach_defaults(GTK_TABLE(table),button1,1,2,2,3);
	gtk_table_attach_defaults(GTK_TABLE(table),button2,2,3,2,3);
	gtk_table_attach_defaults(GTK_TABLE(table),button3,3,4,2,3);
	gtk_table_attach_defaults(GTK_TABLE(table),button4,4,5,2,3);
	gtk_table_attach_defaults(GTK_TABLE(table),delete, 5,6,2,3);
	
	gtk_table_attach_defaults(GTK_TABLE(table),button5,0,1,3,4);
	gtk_table_attach_defaults(GTK_TABLE(table),button6,1,2,3,4);
	gtk_table_attach_defaults(GTK_TABLE(table),button7,2,3,3,4);
	gtk_table_attach_defaults(GTK_TABLE(table),button8,3,4,3,4);
	gtk_table_attach_defaults(GTK_TABLE(table),button9,4,5,3,4);
	gtk_table_attach_defaults(GTK_TABLE(table),sure,5,6,3,4);


	//6.设置button的大小   	
	gtk_widget_set_size_request(button0,60, 35);  
	gtk_widget_set_size_request(button1,60, 35); 
	gtk_widget_set_size_request(button2,60, 35); 
	gtk_widget_set_size_request(button3,60, 35); 
	gtk_widget_set_size_request(button4,60, 35); 
	gtk_widget_set_size_request(button5,60, 35); 
	gtk_widget_set_size_request(button6,60, 35); 
	gtk_widget_set_size_request(button7,60, 35); 
	gtk_widget_set_size_request(button8,60, 35); 
	gtk_widget_set_size_request(button9,60, 35); 
	gtk_widget_set_size_request(sure,60, 30); 
	gtk_widget_set_size_request(delete,60, 30);  

	//7.注册信号函数，把entry传给回调函数deal_num()   
    g_signal_connect(button0, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button1, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button2, "pressed", G_CALLBACK(num_callback), entry);
    g_signal_connect(button3, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button4, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button5, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button6, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button7, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button8, "pressed", G_CALLBACK(num_callback), entry);  
    g_signal_connect(button9, "pressed", G_CALLBACK(num_callback), entry);
#endif 	
	GtkWidget *sure   = gtk_button_new_with_label("sure");
	GtkWidget *delete = gtk_button_new_with_label("<-");
	
	gtk_widget_set_size_request(sure,60, 30); 
	gtk_widget_set_size_request(delete,60, 30);  
	
	gtk_table_attach_defaults(GTK_TABLE(table),delete, 5,6,2,3);
	gtk_table_attach_defaults(GTK_TABLE(table),sure, 5,6,3,4);
	
    g_signal_connect(delete, "pressed", G_CALLBACK(button_callback), entry);  
    g_signal_connect(sure, "pressed", G_CALLBACK(button_callback), entry);
	g_signal_connect(entry, "activate",G_CALLBACK(entry_callback), entry);

	GtkWidget *fixed= gtk_fixed_new();
	gtk_fixed_put(GTK_FIXED(fixed),table,50,100);
	gtk_container_add(GTK_CONTAINER(window),fixed);
	
	chang_background(window, 500, 300, "image.jpg");	// 设置窗口背景图
	gtk_widget_show_all(window);

	gtk_main();

	return 0;
}


<file_sep>/c/homework/2nd_week/super_macro.c
/* ************************************************************************
 *       Filename:  super_macro.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月22日 星期三 06時51分27秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/


#include <stdio.h>

#define SUPER(x,op,y)  (op=='+'?(x)+(y):op=='-'?(x)-(y):op=='*'?(x)*(y):op=='/'?(x)/(y):op=='%'?(x)%(y):0)
int main(int argc, char *argv[])
{
	int m=25,k=4;

	printf("m=%d,k=%d\n",m,k);
	printf("m+k=%d\n",SUPER(m,'+',k));
	printf("m-k=%d\n",SUPER(m,'-',k));
	printf("m*k=%d\n",SUPER(m,'*',k));
	printf("m/k=%d\n",SUPER(m,'/',k));
	printf("m%k=%d\n",SUPER(m,'%',k));
	return 0;
}


<file_sep>/sys_program/player/src/inc/file.h
/* ************************************************************************
 *       Filename:  file.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 05時35分49秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __FILE_H__
#define __FILE_H__

//#include "common.h"

extern char *read_src_file(ulint *file_length,char *lrc_src);
//char **get_musiclist();
extern char *get_musiclist(char ***plist, int *plines);
extern int check_lines(ulint file_length, char *psrc);
extern int get_longestline(int lines, char *plines[]);
extern int get_longestlength(LRC *lrc_head);
extern int get_showoffset(char *pbuf, int longest);
extern int get_chrnumber(char *pbuf, int len);
extern char get_songname(char *desr, char *src);
extern char get_lrcname(char *src);
extern char *transfer_space(char src[]);
extern void delete_dot(char *plist[]);
extern void recover_dot(char *plist[]);
extern void recover_line_dot(char *plist[],int line_num);
#endif<file_sep>/sys_program/3rd_day/dup.c
/* ************************************************************************
 *       Filename:  dup.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月17日 11时10分56秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(int argc, char *argv[])
{
	int fd;
	int fd2;
	fd = open("a.txt",O_CREAT | O_RDWR,0777);

	close(1);

	fd2 = dup(fd);

	printf("fd2 = %d\n",fd2);
	return 0;
}


<file_sep>/work/test/Makefile
CC := gcc
#CC := mips-linux-gnu-gcc
SRC=test.c
TAG=test

all: $(TAG)
$(TAG):test.c
	$(CC) -o $(TAG) $(SRC)

.PHONY:clean
clean:
	rm -rf $(TAG)
<file_sep>/sys_program/6th_day/sem_syn.c
/* ************************************************************************
 *       Filename:  sem_syn.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月20日 14时38分35秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>

sem_t sem1, sem2;
char ch = 'a';

void print(char *str)
{
	sem_wait(&sem1);
	while(*str != '\0')
	{
		putchar(*str++);
		fflush(stdout);
		sleep(1);
	}
	putchar('\n');

	sem_post(&sem1);
}

void *fun1(void *arg)
{
	while(1)
	{
		sem_wait(&sem1);
		ch++;
		sleep(1);
		sem_post(&sem2);
	}

}

void *fun2(void *arg)
{
	while(1)
	{
		sem_wait(&sem2);
		printf("%c",ch);
		fflush(stdout);
		sem_post(&sem1);
	}

}

int main(int argc, char *argv[])
{
	int val = 0;
	pthread_t pth1,pth2;

	sem_init(&sem1,0,0);
	sem_init(&sem2,0,1);


	pthread_create(&pth1,NULL,fun1,NULL);
	pthread_create(&pth2,NULL,fun2,NULL);

	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);

	val = sem_destroy(&sem1);

	if(val==0)
	{
		printf("delete sem succeed\n");
	}
	return 0;
}
<file_sep>/c/homework/3rd_week/operation/Makefile
operation:operation.c fun.c

.PHONY:clean
clean:
	rm operation
<file_sep>/work/debug/2440/ts/s3c2440_ts.c
/* ************************************************************************
 *       Filename:  s3c2440_ts.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年10月30日 20时43分30秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <linux/kernel.h>  /* 提供prink等内核特有属性 */  
#include <linux/module.h>  /* 提供如MODULE_LICENSE()、EXPORT_SYMBOL() */  
#include <linux/init.h>    /* 设置段，如_init、_exit，设置初始化优先级，如__initcall */  
#include <linux/wait.h>    /* 等待队列wait_queue */  
#include <linux/interrupt.h> /* 中断方式，如IRQF_SHARED */  
#include <linux/fs.h>       /* file_operations操作接口等 */  
#include <linux/clk.h>      /* 时钟控制接口，如struct clk */ 
#include <linux/input.h>    /* 内核输入子系统操作接口 */  
#include <linux/slab.h>     /* kzalloc内存分配函数 */  
#include <linux/time.h>     /* do_gettimeofday时间函数 */  
#include <linux/timer.h>    /* timer定时器 */ 
#include <linux/miscdevice.h> /* 杂项设备 */ 
#include <linux/sched.h>
#include <linux/irq.h>
#include <asm/io.h>        /* 提供readl、writel */  
#include <asm/irq.h>       /* 提供中断号，中断类型等，如IRQ_ADC中断号 */  
#include <asm/uaccess.h>   /* 提供copy_to_user等存储接口 */
#include <plat/regs-adc.h> /* 提供控制器的寄存器操作，如S3C2410_ADCCON */  
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/regs-irq.h>

#define __IRQT_FALEDGE IRQ_TYPE_EDGE_FALLING
#define __IRQT_RISEDGE IRQ_TYPE_EDGE_RISING
#define __IRQT_LOWLVL  IRQ_TYPE_LEVEL_LOW
#define __IRQT_HIGHLVL IRQ_TYPE_LEVEL_HIGH
#define IRQT_NOEDGE   (0)
#define IRQT_RISING   (__IRQT_RISEDGE)
#define IRQT_FALLING  (__IRQT_FALEDGE)
#define IRQT_BOTHEDGE (__IRQT_RISEDGE|__IRQT_FALEDGE)
#define IRQT_LOW      (__IRQT_LOWLVL)
#define IRQT_HIGH     (__IRQT_HIGHLVL)
#define IRQT_PROBE    IRQ_TYPE_PROBE

#define CONFIG_S3C2440_TOUCHSCREEN__DEBUG  1
#define DEVICE_NAME   "s3c2440ts"


// 定义一个宏WAIT4INT，用于对ADCTSC触摸屏控制寄存器进行操作
#define WAIT4INT(x)  (((x)<<8) | S3C2410_ADCTSC_YM_SEN | S3C2410_ADCTSC_YP_SEN | \
						S3C2410_ADCTSC_XP_SEN | S3C2410_ADCTSC_XY_PST(3))

// 定义一个宏AUTOPST，用于设置ADCTSC触摸屏控制寄存器为自动转换模式
#define AUTOPST  (S3C2410_ADCTSC_YM_SEN | S3C2410_ADCTSC_YP_SEN | S3C2410_ADCTSC_XP_SEN | \
				  S3C2410_ADCTSC_AUTO_PST | S3C2410_ADCTSC_XY_PST(0))

struct ts_event 
{
	short pressure;	/* 是否按下     */	
	short xp;		/*触摸屏x坐标值 */	
	short yp;		/*触摸屏y坐标值 */
};

struct s3c2440_ts 
{
	struct input_dev *input;/* 输入子系统设备结构体 */  
	struct timer_list timer;/* 定时器，用于ADC转换操作 */  
	struct ts_event tc;	    /* ADC转换的值的保存位置，也用于上报input子系统的数据 */  
	int pendown; 		    /* 判断是否有按下 */  
	int count;		        /* 用于驱动去抖的计数 */  
	int shift;			    /* 用于驱动去抖的基数 */	
};

struct s3c2440_ts *pts = NULL;

static void __iomem *base_addr;
static struct clk *adc_clock;
static struct semaphore adc_lock;

static void touch_timer_callback(unsigned long data)
{
	unsigned long data0;
	unsigned long data1;

	// 禁止中断，处理完数据再打开中断
	set_irq_type(IRQ_TC, IRQT_NOEDGE);
	set_irq_type(IRQ_ADC,IRQT_NOEDGE);

	// 读取ADCDAT0和ADCDAT1寄存器，提取ADC转换的x，y坐标值
	data0 = readl(base_addr + S3C2410_ADCDAT0);
	data1 = readl(base_addr + S3C2410_ADCDAT1);

	// 判断ADCDAT0和ADCDAT1中的[15]位，[15]位为等待中断模式下用于判断笔尖是否有抬起或落下，0=落下
	pts->pendown = (!(data0 &S3C2410_ADCDAT0_UPDOWN)) && (!(data1 & S3C2410_ADCDAT0_UPDOWN));

	// 当触摸屏处于被按下状态，执行下面代码
	if(pts->pendown){
		/* count不为0，说明正在转换，xp和yp往右移动shift(2)位是为了去抖 
		 * 需要结合stylus_action中断函数来看，当count=4时，才能认为转换结束， 
		 * 即最后所得的xp和yp是累加了4次的，最终上报时需要除以4，因此这里预先 
		 * 右移2位，相当于除以4 
		 */ 
		if(pts->count != 0){
			pts->tc.xp >>= pts->shift; // pts->tc.xp = pts->tc.xp >> pts->shift
			pts->tc.yp >>= pts->shift;

			// 终端打印调试信息  
			#ifdef CONFIG_S3C2440_TOUCHSCREEN__DEBUG  
			{  
				struct timeval tv;  
				do_gettimeofday(&tv);  
				printk(KERN_INFO"T: %06d, X: %03x, Y: %03x\n", (int)tv.tv_usec, pts->tc.xp, pts->tc.yp);  
			}  
			#endif

			// 报告X、Y的绝对坐标值
			input_report_abs(pts->input, ABS_X, pts->tc.xp);
			input_report_abs(pts->input, ABS_Y, pts->tc.yp);
			input_report_abs(pts->input, ABS_PRESSURE, pts->tc.pressure);// 报告触摸屏的状态，1表明触摸屏被按下
			input_report_key(pts->input, BTN_TOUCH,pts->pendown);// 报告按键事件，键值为1(代表触摸屏对应的按键被按下)
			input_sync(pts->input);// 等待接收方受到数据后回复确认，用于同步
		}

		// count=0执行这里面的代码，ADC还没有开始转换
		pts->tc.xp = 0;
		pts->tc.yp = 0;
		pts->tc.xp = 0;
		pts->tc.pressure= 0;
		pts->count = 0;

    	// 因为触摸屏是按下状态，ADC还没有转换，需要启动ADC开始转换 
        // 本句代码是设置触摸屏为自动转换模式 
        writel(S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST, base_addr + S3C2410_ADCTSC);	

		// 启动ADC转换
		writel(readl(base_addr +S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START, base_addr + S3C2410_ADCCON);	

	}
	else {
		// 执行到这里说明按键没有被按下或按键抬起，count清0
		pts->count = 0;

		input_report_key(pts->input, BTN_TOUCH, 0);   // 报告按键事件，给0值说明按键抬起	
		input_report_abs(pts->input, ABS_PRESSURE, 0);// 报告按键事件，给0值说明按键抬起
		input_sync(pts->input); 

		writel(WAIT4INT(0), base_addr +S3C2410_ADCTSC);// 将触摸屏重新设置为等待中断状态，等待触摸屏被按下

		del_timer_sync(&pts->timer); // 删除定时器，在定时器时间到前停止一个已注册的定时器
		up(&adc_lock);               // 触摸屏抬起了，可以释放信号量了 
	}

	// 使能中断触发条件，IRQT_BOTHEDGE为使能上升沿和下降沿触发  
	set_irq_type(IRQ_TC, IRQT_BOTHEDGE);  
	set_irq_type(IRQ_ADC,IRQT_BOTHEDGE); 	

}

// ADC中断服务程序，ADC启动转换后被执行
static irqreturn_t stylus_action(int irq, void *dev_id)
{
	unsigned long data0;
	unsigned long data1;

#ifdef CONFIG_S3C2440_TOUCHSCREEN__DEBUG  
	printk(KERN_ERR "%s() No.%dline:\n\r",__FUNCTION__,__LINE__);  
#endif

	// 获取触摸屏的x，y坐标值
	data0 = readl(base_addr + S3C2410_ADCDAT0);
	data1 = readl(base_addr + S3C2410_ADCDAT1);

	pts->tc.xp += data0 & S3C2410_ADCDAT0_XPDATA_MASK;
	pts->tc.yp += data1 & S3C2410_ADCDAT1_YPDATA_MASK;
	pts->tc.pressure = 1;
	pts->count++;
	
	// 如果count小于4，需要重启设置自动转换模式，并进行ADC转换，用于去抖
	if((pts->count) < (1 << pts->shift)){
		writel(S3C2410_ADCTSC_PULL_UP_DISABLE | AUTOPST, base_addr + S3C2410_ADCTSC);
		writel(readl(base_addr + S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START, base_addr + S3C2410_ADCCON);
	}
	else {
		// pts->count=4，启动定时器去执行touch_timer_callback函数上报按键和触摸事件
		mod_timer(&pts->timer, jiffies + HZ/100);

		// 检测触摸屏抬起的中断信号
		writel(WAIT4INT(1),base_addr + S3C2410_ADCTSC);
	}

	return IRQ_HANDLED;
}

// 触摸屏中断服务程序，触摸屏按下或抬起时触发执行
static irqreturn_t stylus_updown(int irq, void *dev_id)
{
	unsigned long data0;
	unsigned long data1;

	// 由于是中断程序，所以不能使用down和down_interruptible，会导致睡眠
	if(down_trylock(&adc_lock) == 0){
		// 读取ADCDAT0和ADCDAT1，用于判断触摸屏是否被按下
		data0 = readl(base_addr + S3C2410_ADCDAT0);
		data1 = readl(base_addr + S3C2410_ADCDAT1);

		pts->pendown = (!(data0 & S3C2410_ADCDAT0_UPDOWN)) && (!(data1 & S3C2410_ADCDAT1_UPDOWN));
		if(pts->pendown){
			// 启动ADC转换，设置ADCCON寄存器的bit[0]为1，bit[0]在启动ADC转换后自动清零
			writel(readl(base_addr + S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START, base_addr + S3C2410_ADCCON);
		}
	}
	
	return IRQ_RETVAL(IRQ_HANDLED);
}


static void adc_init(void) 
{
    // S3C2410_ADCCON_PRSCEN设置ADCCON的位[14]=1为使能A/D预分频器 
    // S3C2410_ADCCON_PRSCVL设置ADCCON的位[13:6]=32表示设置的分频值， 
    // ADC的转换频率需要在2.5MHZ以下，我们使用的ADC输入时钟为PCLK=50MHZ，50MHZ/(49+1)=1MHZ，满足条件  
	writel(S3C2410_ADCCON_PRSCEN |S3C2410_ADCCON_PRSCVL(49), base_addr + S3C2410_ADCCON);

    // 初始化ADC启动或延时寄存器，ADC转换启动延时值设置为0xffff  
    writel(0xffff, base_addr + S3C2410_ADCDLY);	

   /* 初始化ADC触摸屏控制寄存器ADCTSC， 
    * WAIT4INT(0)在上面定义，引脚YM、YP、XM、XP的使能位在ADCTSC的[7:4]位， 
    * 设置触摸屏的工作状态在[1:0]位，WAIT4INT(0)=11010011， 
    * 1101代表笔尖按下时发生触摸屏中断信号IRQ_TS给CPU，0011表示XP上拉使能， 
    * 使用正常ADC转换，转换的方式为等待中断模式 
    */  
    writel(WAIT4INT(0), base_addr + S3C2410_ADCTSC); 	
}

static __init int s3c2440_ts_init(void)
{
	int ret;
	struct input_dev *input_dev;

	pts = kzalloc(sizeof(struct s3c2440_ts), GFP_KERNEL);

	input_dev = input_allocate_device(); //给输入设备申请空间
	if(!pts || !input_dev){
		goto fail1;
	}
	
	adc_clock = clk_get(NULL, "adc");    //获得adc的时钟源
	if(!adc_clock){
		printk(KERN_ERR "failed to get adc clock source\n");  
		ret =  -ENOENT;  
		goto fail1;
	}
	clk_enable(adc_clock); // 使能adc时钟源，ADC转换需要输入时钟

    // 使用ioremap获得操作ADC控制器的虚拟地址 
    // S3C2410_PA_ADC=ADCCON，是ADC控制器的基地址，寄存器组的长度=0x1c   
    base_addr = ioremap(S3C2410_PA_ADC, 0x1c); 	

    if (base_addr == NULL) {  
        printk(KERN_ERR "Failed to remapregister block\n");  
        ret = -ENOMEM;  
        goto fail2;  
    } 	

	adc_init();              // 初始化ADC控制寄存器和ADC触摸屏控制寄存器
	sema_init(&adc_lock, 1); // 初始化信号量的值为1
	pts->shift = 2;          // 设置驱动去抖基数

	// 申请ADC中断，AD转换完成后触发。这里使用共享中断IRQF_SHARED是因为该中断号在ADC驱动中也使用了， 
	// 最后一个参数用于区分共享中断，如果设为NULL，中断申请失败 
	ret = request_irq(IRQ_ADC, stylus_action, IRQF_SHARED | IRQF_SAMPLE_RANDOM, DEVICE_NAME, (void *)pts);
	if(ret){
		ret = -EBUSY;
		goto fail3;
	}

	// 申请触摸屏中断，对触摸屏按下或提笔时触发  
	ret = request_irq(IRQ_TC, stylus_updown, IRQF_SAMPLE_RANDOM, DEVICE_NAME, (void *)pts);
	if(ret){
		ret = -EBUSY;
		goto fail4;
	}
	// 设置中断触发条件，IRQT_BOTHEDGE为使能上升沿和下降沿触发	
	set_irq_type(IRQ_TC, IRQT_BOTHEDGE);  
	set_irq_type(IRQ_ADC,IRQT_BOTHEDGE);

	// 初始化定时器 
	init_timer(&pts->timer);  
	pts->timer.data = 1;  
	pts->timer.function = touch_timer_callback;

	/* 设置触摸屏输入设备的标志，注册输入设备成功进入根文件系统，可以cat /proc/bus/input/devices查看其内容*/
	input_dev->name 	  = DEVICE_NAME;
	input_dev->phys 	  = "s3c2440ts/input0";
	input_dev->id.bustype = BUS_HOST;  /*总线类型 */	 
	input_dev->id.vendor  = 0x1;	   /*经销商ID */  
	input_dev->id.product = 0x2;	   /*产品ID */	
	input_dev->id.version = 0x0100;    /*版本ID */ 

	// evbit字段用于描述支持的事件，这里支持同步事件、按键事件、绝对坐标事件
	input_dev->evbit[0] = BIT_MASK(EV_SYN) |BIT_MASK(EV_KEY) | BIT_MASK(EV_ABS);
	input_dev->keybit[BIT_WORD(BTN_TOUCH)] = BIT_MASK(BTN_TOUCH); // keybit字段用于描述按键的类型，BTN_TOUCH表示触摸屏的点击
	
	//对于触摸屏来说，使用的是绝对坐标系统。这里设置该坐标系统中X和Y坐标的最小值和最大值(0-1023范围) 
	//ABS_X和ABS_Y就表示X坐标和Y坐标，ABS_PRESSURE就表示触摸屏是按下还是抬起状态  
	input_set_abs_params(input_dev, ABS_X, 0,0x3FF, 0, 0);	
	input_set_abs_params(input_dev, ABS_Y, 0,0x3FF, 0, 0);	
	input_set_abs_params(input_dev, ABS_PRESSURE, 0, 1, 0, 0); 

	pts->input = input_dev;
	ret = input_register_device(pts->input); // 注册输入子系统
	if(ret) 
		goto fail5;

	return 0;

fail5:
	free_irq(IRQ_TC, (void *)pts);
	disable_irq(IRQ_TC);
fail4:
	free_irq(IRQ_ADC, (void *)pts);
	disable_irq(IRQ_ADC);
fail3:
	iounmap(base_addr);
fail2:
	clk_disable(adc_clock); // 禁止ADC的时钟源     
	clk_put(adc_clock); 
fail1:
	input_free_device(input_dev);
	kfree(pts);
	return ret;
}

static __exit void s3c2440_ts_exit(void)
{
	// 屏蔽并释放中断
	disable_irq(IRQ_TC);
	disable_irq(IRQ_ADC);
	free_irq(IRQ_TC, (void *)pts);
	free_irq(IRQ_ADC, (void *)pts);

	// 注销定时器
	del_timer_sync(&pts->timer);

	// 屏蔽和禁止adc时钟
	if(adc_clock) {
		clk_disable(adc_clock);
		clk_put(adc_clock);
		adc_clock = NULL;
	}

	// 注销触摸屏输入子系统
	input_unregister_device(pts->input);

	// 释放虚拟地址
	iounmap(base_addr);

	// 释放触摸屏设备结构体
	kfree(pts);
}

module_init(s3c2440_ts_init);
module_exit(s3c2440_ts_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/2440/lcd/s3c24xx_fb.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/dma-mapping.h>
#include <linux/fb.h>
#include <linux/clk.h>
#include <linux/interrupt.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <asm/div64.h>
#include <mach/regs-lcd.h>
#include <mach/regs-gpio.h>
#include <mach/fb.h>
#include <linux/pm.h>


#define DEVICE_NAME   "s3cfb"
#define PALETTE_BUFF_CLEAR (0x80000000) //用做清空调色板(颜色表)

struct fb_var
{
	int lcd_irq_no;           /*保存LCD中断号*/
	struct clk *lcd_clock;    /*保存从平台时钟队列中获取的LCD时钟*/
	struct resource *lcd_mem; /*LCD的IO空间*/
	void __iomem *lcd_base;   /*LCD的IO空间映射到虚拟地址*/
	struct device *dev;
	struct s3c2410fb_hw regs; /*表示5个LCD配置寄存器，s3c2410fb_hw定义在mach-s3c2410/include/mach/fb.h中*/

	/*定义一个数组来充当调色板。据数据手册描述，TFT屏色位模式为8BPP时，调色板(颜色表)的长度
	为256，调色板起始地址为0x4D000400*/
	u32 palette_buffer[256];
	u32 pseudo_pal[16];
	unsigned intpalette_ready; /*标识调色板是否准备好了*/	
};

static struct file_operations lcd_fb_fops = {



};

//该函数实现修改GPIO端口的值，第三个参数mask的
//作用是将要设置的寄存器值先清零
static inline void modify_gpio(void __iomem *reg,
			       unsigned long set, unsigned long mask)
{
	unsigned long tmp;

	tmp = readl(reg) & ~mask;
	writel(tmp | set, reg);
}

static void s3cfb_init_registers(struct fb_info *fbinfo) // LCD 相关寄存器的初始化
{
	unsigned long flags;
	void __iomem *tpal;
	void __iomem *lpcsel;	
	struct fb_var *fbvar = fbinfo->par;
	struct s3c2410fb_mach_info *mach_info = fbvar->dev->platform_data;

	//获得临时调色板寄存器基地址，S3C2410_TPAL宏定义在mach-s3c2410/include/mach/regs-lcd.h中
	//注意对于lpcsel这是一个针对三星TFT屏的一个专用寄存器，如果用的不是三星的TFT屏应该不用管它
	tpal   = fbvar->lcd_base + S3C2410_TPAL;
	lpcsel = fbvar->lcd_base + S3C2410_LPCSEL;

	//*在修改下面寄存器值之前先屏蔽中断，将中断状态保存到flags中
	local_irq_save(flags);

	//把IO端口C和D配置成LCD模式
	modify_gpio(S3C2410_GPCUP,  mach_info->gpcup,  mach_info->gpcup_mask);
	modify_gpio(S3C2410_GPCCON, mach_info->gpccon, mach_info->gpccon_mask);
	modify_gpio(S3C2410_GPDUP,  mach_info->gpdup,  mach_info->gpdup_mask);
	modify_gpio(S3C2410_GPDCON, mach_info->gpdcon, mach_info->gpdcon_mask);	

	
	local_irq_restore(flags);//恢复被屏蔽的中断
	
	writel(0x00,tpal); //临时调色板寄存器使能禁止
	writel(mach_info->lpcsel,lpcsel); //它是三星TFT屏的一个寄存器，这里可以不管
	return 0;	
	
}

static void s3cfb_check_var(struct fb_info *fbinfo)
{
	unsigned int i;

	//从lcd_fb_probe探测函数设置的平台数据中再获得LCD相关信息的数据
	struct fb_var_screeninfo *var = &fbinfo->var;//fb_info中的LCD可变参数
	struct fb_var *fbvar = fbinfo->par; //在lcd_fb_probe探测函数中设置的私有结构体数据
	struct s3c2410fb_mach_info *mach_info = fbvar->dev->platform_data; //从LCD平台设备资源 取出LCD的配置结构体数据
	struct s3c2410fb_display *display = NULL;
	struct s3c2410fb_display *default_display = mach_info->displays + mach_info->default_display;
	int type = default_display->type; //LCD的类型

	//验证X/Y解析度
	if (var->yres == default_display->yres &&
		var->xres == default_display->xres &&
		var->bits_per_pixel == default_display->bpp)
	{
		display =default_display;
	}
	else
	{
		for (i =0;i <mach_info->num_displays;i++)
		{
			if (type == mach_info->displays[i].type &&
				var->yres == mach_info->displays[i].yres &&
				var->xres == mach_info->displays[i].xres &&
				var->bits_per_pixel == mach_info->displays[i].bpp)
			{
				display = mach_info->displays + i;
				break;
			}
		}
	}

	if (!display)
		return -EINVAL;

	//配置LCD配置寄存器1中的5-6位(配置成TFT类型)和配置LCD配置寄存器5
	fbvar->regs.lcdcon1 = display->type;
	fbvar->regs.lcdcon5 = display->lcdcon5;

	//设置屏幕的虚拟解析像素和高度宽度
	var->xres_virtual = display->xres;
	var->yres_virtual = display->yres;
	var->height = display->height;
	var->width = display->width;

	//设置时钟像素，行、帧切换值，水平同步、垂直同步长度值
	var->pixclock = display->pixclock;
	var->left_margin = display->left_margin;
	var->right_margin = display->right_margin;
	var->upper_margin = display->upper_margin;
	var->lower_margin = display->lower_margin;
	var->vsync_len = display->vsync_len;
	var->hsync_len = display->hsync_len;

	//设置透明度
	var->transp.offset = 0;
	var->transp.length = 0;

	//根据色位模式(BPP)来设置可变参数中R、G、B的颜色位域
	//对于这些参数值的设置请参考CPU数据
	switch (var->bits_per_pixel)
	{
		case 1:
		case 2:
		case 4:
			var->red.offset = 0;
			var->red.length = var->bits_per_pixel;
			var->green      = var->red;
			var->blue       = var->red;
			break;
		case 8:/* 8 bpp 332 */
			if (display->type != S3C2410_LCDCON1_TFT)
			{
				var->red.length   = 3;
				var->red.offset   = 5;
				var->green.length = 3;
				var->green.offset = 2;
				var->blue.length  = 2;
				var->blue.offset  = 0;
			}
			else
			{
				var->red.offset   = 0;
				var->red.length   = 8;
				var->green        = var->red;
				var->blue         = var->red;
			}
			break;
	case 12:/* 12 bpp 444 */
		var->red.length     = 4;
		var->red.offset     = 8;
		var->green.length   = 4;
		var->green.offset   = 4;
		var->blue.length    = 4;
		var->blue.offset    = 0;
		break;
	case 16:/* 16 bpp */
		if (display->lcdcon5 &S3C2410_LCDCON5_FRM565)
		{
			/* 565 format */
			var->red.offset   = 11;
			var->green.offset = 5; 
			var->blue.offset  = 0;
			var->red.length   = 5;
			var->green.length = 6;
			var->blue.length  = 5;
		} 
		else 
		{
			/* 5551 format */
			var->red.offset    = 11;
			var->green.offset  = 6;
			var->blue.offset   = 1;
			var->red.length    = 5;
			var->green.length  = 5;
			var->blue.length   = 5;
		}
		break;
	case 32:/* 24 bpp 888 and 8 dummy */
		var->red.length    = 8;
		var->red.offset    = 16;
		var->green.length  = 8;
		var->green.offset  = 8;
		var->blue.length   = 8;
		var->blue.offset   = 0;
		break;
	}

	return 0;
}

//申请帧缓冲设备fb_info的显示缓冲区空间
static int __init s3cfb_map_video_memory(struct fb_info *fbinfo)
{
	dma_addr_t map_dma; //用于保存DMA缓冲区总线地址
	struct fb_var *fbvar = fbinfo->par;//获得在lcd_fb_probe探测函数中设置的私有结构体数据
	unsigned map_size = PAGE_ALIGN(fbinfo->fix.smem_len);//获得FrameBuffer缓存的大小, PAGE_ALIGN定义在mm.h中

	//分配的一个写合并DMA缓存区设置为LCD屏幕的虚拟地址
	//dma_alloc_writecombine定义在arch/arm/mm/dma-mapping.c中
	fbinfo->screen_base = dma_alloc_writecombine(fbvar->dev, map_size, &map_dma, GFP_KERNEL);
	if(fbinfo->screen_base)
	{
		//设置这片DMA缓存区的内容为空
		memset(fbinfo->sreen_base, 0x00, map_size);
		
		//将DMA缓冲区总线地址设成fb_info不可变参数中framebuffer缓存的开始位置
		fbinfo->fix.smem_start = map_dma;
	}

	return fbinfo->screen_base ? 0 : -ENOMEM;
}

//释放帧缓冲设备fb_info的显示缓冲区空间
static int inline s3cfb_unmap_video_memory(struct fb_info *fbinfo)
{
	struct fb_var *fbvar = fbinfo->par;
	unsigned map_size = PAGE_ALIGN(fbinfo->fix.smem_len);
	
	//释放写合并DMA缓存区，跟申请DMA的地方想对应
	dma_free_writecombine(fbvar->dev,map_size,fbinfo->screen_base,fbinfo->fix.smem_start);
}


static void s3cfb_write_palette(struct fb_var *fbvar)
{
	unsigned int i;
	void __iomem *regs = fbvar->lcd_base;
	fbvar->palette_ready =0;

	for(i = 0 ; i <256 ; i++)
	{
	    unsigned long ent = fbvar->palette_buffer[i];
		if(ent == PALETTE_BUFF_CLEAR)
			continue;
		writel(ent, regs + S3C2410_TFTPAL(i));
		if(readw(regs + S3C2410_TFTPAL(i)) == ent)
			fbvar->palette_buffer[i] =PALETTE_BUFF_CLEAR;
		else
			fbvar->palette_ready = 1;				
	}
}

static irqreturn_t lcd_fb_irq(void *dev_id)
{
	struct fb_var *fbvar = dev_id;
	void __iomem *lcd_irq_base;
	unsigned long lcdirq;
	
	lcd_irq_base = fbvar->lcd_base + S3C2410_LCDINTBASE;//LCD中断寄存器基地址
	lcdirq = readl(lcd_irq_base + S3C24XX_LCDINTPND);   //读取LCD中断挂起寄存器的值
	
	//判断是否为中断挂起状态
	if(lcdirq & S3C2410_LCDINT_FRSYNC)
	{
		//填充调色板
		if (fbvar->palette_ready)
			s3cfb_write_palette(fbvar);

		//清除帧中断请求标志
		writel(S3C2410_LCDINT_FRSYNC, lcd_irq_base + S3C24XX_LCDINTPND);
		writel(S3C2410_LCDINT_FRSYNC, lcd_irq_base + S3C24XX_LCDSRCPND);
	}
		
	return IRQ_HANDLED;
}

static void s3cfb_lcd_enable(struct fb_var *fbvar, int enable)
{
	unsigned long flags;

	//在修改下面寄存器值之前先屏蔽中断，将中断状态保存到flags中
	local_irq_save(flags);
	
	if(enable)
	{
		fbvar->regs.lcdcon1 |= S3C2410_LCDCON1_ENVID;
	}
	else
	{
		fbvar->regs.lcdcon1 &= ~S3C2410_LCDCON1_ENVID;
	}
	writel(fbvar->regs.lcdcon1, fbvar->lcd_base + S3C2410_LCDCON1);

	//恢复被屏蔽的中断
	local_irq_restore(flags);
}

//有两个地方会调用到：一个是设备注销时，一个是驱动注销时
static __devexit int lcd_fb_remove(struct platform_device *pdev)
{
	struct fb_info *fbinfo = platform_get_drvdata(pdev);
	struct fb_var *fbvar = fbinfo->par;


	//从系统中注销帧缓冲设备
	unregister_framebuffer(fbinfo);

	//停止LCD控制器的工作
	s3cfb_lcd_enable(fbvar,0);
	msleep(1); // 延迟一段时间，因为停止LCD控制器需要一点时间

	//释放帧缓冲设备fb_info的显示缓冲区空间
	s3cfb_unmap_video_memory(fbinfo);

	//将LCD平台数据清空和释放fb_info空间资源
	platform_set_drvdata(pdev, NULL);
	framebuffer_release(fbinfo);

	//释放中断资源
	free_irq(fbvar->lcd_irq_no,fbvar);

	//释放时钟资源
	if (fbvar->lcd_clock)
	{
		clk_disable(fbvar->lcd_clock);
		clk_put(fbvar->lcd_clock);
		fbvar->lcd_clock = NULL;
	}

	//释放LCD IO空间映射的虚拟内存空间
	iounmap(fbvar->lcd_base);
	
	//释放申请的LCD IO端口所占用的IO空间
	release_resource(fbvar->lcd_mem); 

	return 0;
	
}

static __devinit int lcd_fb_probe(struct platform_device *pdev)
{
	int ret, i;

	struct resource *res; //保存从LCD平台设备中获取的LCD资源
	struct fb_info *fbinfo;//FrameBuffer驱动所对应的fb_info结构
	struct s3c2410fb_mach_info *mach_info;//保存从内核中获取的平台设备数据
	struct fb_var *fbvar; //上面定义的驱动程序全局变量结构体
	struct s3c2410fb_display *display; //LCD屏的配置信息结构体，该结构体定义在mach-s3c2410/include/mach/fb.h中

	//获取LCD硬件相关信息数据，在mach-s3c2440.c中
    //s3c24xx_fb_set_platdata()函数将LCD的硬件相关信息保存到LCD平台数据中 
	mach_info = pdev->dev.platform_data;
	if(mach_info == NULL)
	{
		/*判断获取数据是否成功*/
		dev_err(&pdev->dev, "no platform data for lcd\n");
		return -EINVAL;
	}	
	//获得在mach-s3c2440.c中定义的FrameBuffer平台设备的LCD配置信息
	display = mach_info->displays + mach_info->default_display;
	
	//申请一段大小为sizeof(fb_info)+sizeof(fb_var)的空间，fb_var是这个设备的私有数据结构
	//并初始化fb_info->par = &fb_var, fb_info->device = &pdev->dev,
	//目的是在其他接口函数中通过fb_info结构取出这些成员
	//返回这段空间的首地址
	fbinfo = framebuffer_alloc(sizeof(fb_var), &pdev->dev);
	if(!fbinfo)
	{
		dev_err(&pdev->dev, "framebuffer alloc of registers failed\n");
		ret = -ENOMEM;
		goto err_noirq;
	}
	//重新将LCD平台设备数据设置为fbinfo，好在后面的一些函数中来使用
	platform_set_drvdata(pdev, fbinfo);

	//fbinfo->par 在framebuffer_alloc()函数中赋值，指向了fb_var私有数据结构
	//这里从fbinfo->par获取到fb_var私有数据结构的地址，进行成员的初始化
	fbvar = fbinfo->par;
	fbvar->dev = &pdev->dev;//保存pdev->dev到私有数据结构，这样在其他函数可以通过fbva私有数据结构取出LCD平台设备资源

	//从LCD平台设备资源中获取LCD中断号,platform_get_irq定义在platform_device.h中
	fbvar->lcd_irq_no =platform_get_irq(pdev, 0);
	if(fbvar->lcd_irq_no <0)
	{
		/*判断获取中断号是否成功*/
		dev_err(&pdev->dev, "no lcd irq for platform\n");
		return -ENOENT;
	}

	//获取LCD平台设备所使用的IO端口资源，注意这个IORESOURCE_MEM
	//标志和LCD平台设备定义中的一致
	res =platform_get_resource(pdev,IORESOURCE_MEM,0);
	if(res == NULL)
	{
		/*判断获取资源是否成功*/
		dev_err(&pdev->dev, "failed to get memory region resource\n");
		return -ENOENT;
	}

	//申请LCD IO端口所占用的IO空间(注意理解IO空间和内存空间的
	//区别),request_mem_region定义在ioport.h中
	fbvar->lcd_mem =request_mem_region(res->start, res->end - res->start + 1,pdev->name);
	if(fbvar->lcd_mem == NULL)	
	{
		/*判断申请IO空间是否成功*/
		dev_err(&pdev->dev, "failed to reserve memory region\n");
		return -ENOENT;
	}

	//从平台时钟队列中获取LCD的时钟，这里为什么要取得这个时钟，
	//从LCD屏的时序图上看，各种控制信号的延迟都跟LCD的时钟有关
	fbvar->lcd_clock =clk_get(NULL, "lcd");
	if(!fbvar->lcd_clock)
	{
		/*判断获取时钟是否成功*/
		dev_err(&pdev->dev, "failed to find lcd clock source\n"); 
		ret = -ENOENT;
		goto err_nomap;
	}

	//时钟获取后要使能后才可以使用，clk_enable定义在arch/arm/plat-s3c/clock.c中
	clk_enable(fbvar->lcd_clock);	

	//申请LCD中断服务，上面获取的中断号lcd_fb_irq，使用快速中断方式:IRQF_DISABLED
	ret =request_irq(fbvar->lcd_irq_no, lcd_fb_irq, IRQF_DISABLED, pdev->name, fbvar)
	if(ret)
	{
		/*判断申请中断服务是否成功*/
		dev_err(&pdev->dev, "IRQ%d error %d\n",fbvar->lcd_irq_no,ret);
		ret = -EBUSY;
		goto err_noclk;		
	}
	/*以上是对要使用的资源进行了获取和设置。下面就开始初始化填充fb_info结构体*/

	/*首先初始化fb_info中代表LCD固定参数的结构体fb_fix_screeninfo*/
	/*像素值与显示内存的映射关系有5种，定义在fb.h中。现在采用FB_TYPE_PACKED_PIXELS方式，
	在该方式下，像素值与内存直接对应，比如在显示内存某单元写入一个"1"时，该单元对应的像
	素值也将是"1"，这使得应用层把显示内存映射到用户空间变得非常方便。Linux中当LCD为TFT
	屏时，显示驱动管理显示内存就是基于这种方式*/
	strcpy(fbinfo->fix.id, DEVICE_NAME); // 字符串形式的标识符
	fbinfo.fix.type = FB_TYPE_PACKED_PIXELS;
	fbinfo->fix.type_aux  = 0;//以下这些根据fb_fix_screeninfo定义中的描述，当没有硬件是都设为0
	fbinfo->fix.xpanstep  = 0;
	fbinfo->fix.ypanstep  = 0;
	fbinfo->fix.ywrapstep = 0;
	fbinfo->fix.accel     = FB_ACCEL_NONE;	
	//接着，再初始化fb_info中代表LCD可变参数的结构体fb_var_screeninfo
	fbinfo->var.nonstd			= 0;
	fbinfo->var.activate		= FB_ACTIVATE_NOW;
	fbinfo->var.accel_flags 	= 0;
	fbinfo->var.vmode			= FB_VMODE_NONINTERLACED;
	fbinfo->var.xres			= display->xres;
	fbinfo->var.yres			= display->yres;
	fbinfo->var.bits_per_pixel	= display->bpp;
	//指定对底层硬件操作的函数指针, 因内容较多故其定义在第3步中再讲
	fbinfo->fbops				= &lcd_fb_fops;
	fbinfo->flags				= FBINFO_FLAG_DEFAULT;
	fbinfo->pseudo_palette	    = &fbvar->pseudo_pal;

	//初始化色调色板(颜色表)为空
	for(i=0;i<256;i++)
		fbvar->palette_buffer[i] = PALETTE_BUFF_CLEAR;

	for ( i = 0 ; i < mach_info->num_displays; i++ )
	{
	    //计算FrameBuffer缓存的最大大小，这里右移3位(即除以8)
		//是因为色位模式BPP是以位为单位
		unsigned long smem_len = (mach_info->displays[i].xres * \
								  mach_info->displays[i].xres * \
								  mach_info->displays[i].bpp) >> 3;

		if(fbinfo->fix.smem_len < smem_len)
			fbinfo->fix.smem_len = smem_len;	
	}

	msleep(1); //初始化LCD控制器之前要延迟一段时间
	
	
	s3cfb_init_registers(fbinfo);//初始化完fb_info后，开始对LCD各寄存器进行初始化
	s3cfb_check_var(fbinfo);     //初始化完寄存器后，开始检查fb_info中的可变参数
	ret = s3cfb_map_video_memory(fbinfo);//申请帧缓冲设备fb_info的显示缓冲区空间
	if (ret)
	{
		dev_err(&pdev->dev, "failed to allocate video RAM: %d\n",ret);
		ret = -ENOMEM;
		goto err_nofb;
	}

	//最后，注册这个帧缓冲设备fb_info到系统中, 
	//register_framebuffer定义在fb.h中在fbmem.c中
	ret =register_framebuffer(fbinfo);
	if (ret <0)
	{
		dev_err(&pdev->dev, "failed to register framebuffer device: %d\n",ret);
		goto err_video_nomem;
	}

	//对设备文件系统的支持创建frambuffer设备文件，
	//device_create_file定义在linux/device.h中
	ret =device_create_file(&pdev->dev, &dev_attr_debug);
	if (ret)
	{
		dev_err(&pdev->dev, "failed to add debug attribute\n");
	} 
	printk(KERN_WARNING "%s\n",__FUNCTION__);
	return 0;

	//以下是出错处理
err_video_nomem:	
	s3cfb_unmap_video_memory(fbinfo);	
err_nofb:
	platform_set_drvdata(pdev, NULL);
	framebuffer_release(fbinfo);	
err_noirq:
	free_irq(fbvar->lcd_irq_no, fbvar);
err_noclk:
	clk_disable(fbvar->lcd_clock);
	clk_put(fbvar->lcd_clock);
err_nomap:
	iounmap(fbvar->lcd_base);
err_nomem:
	release_resource(fbvar->lcd_mem);
	kfree(fbvar->lcd_mem);

	return ret;
}


static struct platform_driver lcd_fb_driver = {
	.probe  = lcd_fb_probe,


	.driver = {
		.name  = "s3c2410-lcd",
		.owner = THIS_MODULE,
	}

};

static __init int lcd_fb_init(void)
{   
	// Linux中，帧缓冲设备被看做是平台设备
	platform_driver_register(&lcd_fb_driver);
}

static __exit void lcd_fb_exit(void)
{
	// 注销设备
	platform_driver_unregister(&lcd_fb_driver);
}

module_init(lcd_fb_init);
module_exit(lcd_fb_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/2440/adc/adc_drv.c
/* ************************************************************************
 *       Filename:  adc_drv.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年10月30日 16时00分23秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <linux/kernel.h>  /* 提供prink等内核特有属性 */  
#include <linux/module.h>  /* 提供如MODULE_LICENSE()、EXPORT_SYMBOL() */  
#include <linux/init.h>    /* 设置段，如_init、_exit，设置初始化优先级，如__initcall */  
#include <linux/wait.h>    /* 等待队列wait_queue */  
#include <linux/interrupt.h> /* 中断方式，如IRQF_SHARED */  
#include <linux/fs.h>      /* file_operations操作接口等 */  
#include <linux/clk.h>     /* 时钟控制接口，如struct clk */  
#include <linux/miscdevice.h> /* 杂项设备 */  
#include <linux/sched.h>
#include <asm/io.h>        /* 提供readl、writel */  
#include <asm/irq.h>       /* 提供中断号，中断类型等，如IRQ_ADC中断号 */  
#include <asm/uaccess.h>   /* 提供copy_to_user等存储接口 */
#include <mach/hardware.h>
#include <mach/regs-gpio.h>
#include <mach/regs-irq.h>
#include <plat/regs-adc.h> /* 提供控制器的寄存器操作，如S3C2410_ADCCON */  


#define DEVICE_NAME   "adc"

 
static struct clk *adc_clock;   // 定义adc时钟，通过adc_clock接口获得adc输入时钟，adc转换器需要  
static void __iomem *base_addr; //定义虚拟地址访问硬件寄存器，__iomem只是用于表示指针将指向I/O内存  
static wait_queue_head_t adc_waitqueue; //定义一个等待队列adc_waitqueue，对ADC资源进行阻塞访问  

   
/* 定义并初始化信号量adc_lock，用于控制共享中断IRQ_ADC资源的使用 */  
DECLARE_MUTEX(adc_lock);  
EXPORT_SYMBOL(adc_lock);

static volatile int read_ok = 0; //定义等待队列的条件，当read_ok=1时，ADC转换完毕，数据可读 
static volatile int adc_data;    //定义ADC转换的数据内容


/*ADC中断服务程序，获取ADC转换后的数据 */  
static irqreturn_t adc_irq_callback(int irq, void *dev_id)
{
	// 仅当read_ok=0时才进行转换，防止多次中断
	if(!read_ok){
	    // 读取ADCCON[9:0]的值，0x3ff为只获取[9:0]位，ADCCON为转换后的数据 
        adc_data = readl(base_addr + S3C2410_ADCDAT0) & 0x3ff;  
  
        read_ok = 1; // 设置标识为1，唤醒读等待进程可以拷贝数据给用户空间了   
      	wake_up_interruptible(&adc_waitqueue);	
	}

	return IRQ_HANDLED;
}

static int adc_drv_open(struct inode *pinode, struct file *filp)
{
	int ret;

	// 由于IRQ_ADC为共享中断，因此中断类型选择IRQF_SHARED，最后一个参数需要设置NULL以外的值
	ret = request_irq(IRQ_ADC, adc_irq_callback, IRQF_SHARED, DEVICE_NAME, (void *)1);
    if(ret) {
        printk(KERN_ERR "Could notallocate ts IRQ_ADC !\n");
        return -EBUSY;
    }

    return ret;
}

static void adc_run(void)
{
	volatile unsigned int adccon;

	/* ADCCON的位[14]=1为使能A/D预分频器，位[13:6]=32表示设置的分频值，ADC的转换频率需要在2.5MHZ以下
     * 我们使用的ADC输入时钟为PCLK=50MHZ，50MHZ/32<2.5MHZ，满足条件
     * 位[5:3]=000，表示模拟输入通道选择AIN0
     */
	adccon = (1 << 14) | (32 << 6);
	writel(adccon, base_addr + S3C2410_ADCCON);

	// 位[0]=1表示使能ADC转换，当转换完毕后此位被ADC控制器自动清0
	adccon = readl(base_addr + S3C2410_ADCCON) | S3C2410_ADCCON_ENABLE_START;
	writel(adccon, base_addr + S3C2410_ADCCON);
}

static ssize_t adc_drv_read(struct file *filp, char __user *buf, size_t count, loff_t *ppos)
{
	int err;

    // 获取信号量，如果被占用，睡眠等待持有者调用up唤醒
    // 这样做的原因是，有可能其他进程抢占执行或是触摸屏驱动抢占执行
   	down_interruptible(&adc_lock);

    adc_run(); // 启动adc转换，调用中断处理函数adc_irq

	// 如果read_ok为假，则睡眠等待条件为真，由中断处理函数唤醒
    wait_event_interruptible(adc_waitqueue, read_ok);

	read_ok = 0; // 执行到此说明中断处理程序获得了ADC转换后的值，清除为0等待下一次的读

	// 将转换后的数据adc_data提交给用户
	err = copy_to_user(buf, (char *)&adc_data, min(sizeof(adc_data), count));

    up(&adc_lock); // 释放信号量，并唤醒因adc_lock而睡眠的进程

	return err ? -EFAULT : min(sizeof(adc_data), count);
}

static int adc_drv_close(struct inode *pinode, struct file *filp)
{
	// 释放中断
    free_irq(IRQ_ADC, (void *)1);

	return 0;
}


static struct file_operations adc_fops = { //字符设备操作接口
	.owner  = THIS_MODULE,
	.open   = adc_drv_open,
	.read   = adc_drv_read,
	.release= adc_drv_close,
};

static struct miscdevice adc_misc = {
	.minor = MISC_DYNAMIC_MINOR, // 动态获取次设备号
	.name  = DEVICE_NAME,        // 杂项设备名称
	.fops  = &adc_fops,          // 杂项设备子系统接口，指向adc_fops操作接口
};

static __init int adc_drv_init(void)
{
	int ret;

	// 获得adc的时钟源，通过arch/arm/mach-s3c2410/clock.c获得提供的时钟源为PCLK
	adc_clock = clk_get(NULL, "adc");
	if(!adc_clock){
		printk(KERN_ERR "failed to get adcclock source\n"); 
		return -ENOENT;
	}

    // 使能adc时钟源，ADC转换需要输入时钟
    clk_enable(adc_clock);  	

    // 使用ioremap获得操作ADC控制器的虚拟地址 
    // S3C2410_PA_ADC=ADCCON，是ADC控制器的基地址，寄存器组的长度=0x1c   
    base_addr = ioremap(S3C2410_PA_ADC, 0x1c);  
    if (base_addr == NULL){  
        printk(KERN_ERR "Failed to remapregister block\n");  
        ret = -ENOMEM;  
        goto fail1;  
    }	

	// 初始化等待队列
	init_waitqueue_head(&adc_waitqueue);  

	// 注册杂项设备
	ret = misc_register(&adc_misc);
	if(ret<0){
		printk(KERN_INFO " can't register adc_drv\n"); 
		goto fail2;
	}

fail2:
	iounmap(base_addr);
fail1:
	clk_disable(adc_clock); // 禁止ADC的时钟源 
    clk_put(adc_clock); 
	return ret;
}

static __exit void adc_drv_exit(void)
{
    /* 释放虚拟地址 */
    iounmap(base_addr);

    /* 禁止ADC的时钟源 */
    if (adc_clock)
    {
        clk_disable(adc_clock);
        clk_put(adc_clock);
        adc_clock = NULL;
    }

	misc_deregister(&adc_misc);
}

module_init(adc_drv_init);
module_exit(adc_drv_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/test/timer/Makefile
#GCC := gcc

GCC := mips-linux-gnu-gcc
CFLAGS := -EL -mabi=32 -mhard-float -march=mips32r2 -Os
LDFLAGS:= -Wl,-EL
LDLIBS := -lrt -lpthread

SOURCES := $(wildcard *.c)

TARGET = timer
all: $(TARGET)

$(TARGET): $(SOURCES)
	$(GCC) -o $@ $^ $(CFLAGS) $(LDFLAGS) $(LDLIBS)

INSTALL_DIR = ~/work/sz-halley2/out/product/yak/system/usr/bin
install:
	cp $(TARGET) $(INSTALL_DIR) -a

.PHONY: clean
clean:
	rm -rf *.o $(TARGET)
<file_sep>/c/lrc/link.c
/* ************************************************************************
 *       Filename:  link.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月01日 星期六 10時18分27秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include "common.h"

LRC *insert_link(LRC *head, LRC slrc)
{
	LRC *pi = NULL;
	pi = (LRC *)malloc(sizeof(LRC));

	if(pi != NULL) //成功申请到空间
	{
		*pi = slrc;
		pi->next = NULL;

		if(head == NULL)
		{
			head = pi;
		}
		else //链表不为空
		{
			LRC *pb = NULL, *pf =NULL;
			pb = pf = head;

			//按num从小到大插入链表
			while((pi->time > pb->time) && (pb->next != NULL))
			{
				pf = pb;
				pb = pb->next;
			}

			if(pi->time <= pb->time)//链表头插入新节点
			{
				if(pb == head)
				{
					pi->next = pb;
					pb->prev = pi;
					head = pi;
				}
				else //中间插入新节点
				{
					pb->prev = pi;
					pi->prev = pf;

					pi->next = pb;
					pf->next = pi;
				}
			}
			else //尾部插入新节点
			{
				pb->next = pi;
				pi->prev = pb;
			}
		}
	}
	else
	{
		printf("Can not apply for a LRC memeory space!\n");
	}

	return head;
}

/**************************************************
 *函数：free_link
 *功能：将整个链表所占的内存空间释放
 *************************************************/
LRC *free_link(LRC *head)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		LRC *pb = head;

		//循环删除链表每个节点的方法：
		//1.判断 head 是否为空
		//2.让 pb 指向和 head 相同的节点
		//3.然后 让 head 指向下个节点
		//4.再把 pb 指向的节点释放掉
		//5.返回步骤 1
		while(head != NULL)
		{
			pb = head;
			head = pb->next;
			free(pb);
		}
	}

	return head;
}

/**************************************************
 *函数：print_link
 *功能：遍历链表中每个节点，并打印节点的内容
 *************************************************/
void print_link(LRC *head)
{

	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		LRC *pb = head;

		while(pb != NULL)
		{
			//printf("%.2f  %s\n",pb->time,pb->psrc);
			printf("%d  %s\n",pb->time,pb->psrc);
			pb = pb->next;
		}
	}
}
<file_sep>/network/route/src/arp_link.c
/******************************************************************************
  文 件 名   : arp_link.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 链表创建、查找、打印、释放等
  函数列表   :
              iptoun_btob
              iptoun_btol
              insert_arp_table
              search_arp_table
              delete_arp_node
              free_arp_table
              change_arp_mac
              print_arp_table
  修改历史   :
  1.日    期   : 2015年9月10日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"



/*****************************************************************************
 函 数 名  : iptoun_btol()
 功能描述  : 将存在ip[]的ip地址(大端)转化为32无符号整数(小端)，相当ntohl()函数
 输入参数  : ip[]
 返 回 值  : 返回32无符号整数的ip地址(小端)
 修改日期  : 2015年9月10日
*****************************************************************************/
uint iptoun_btol(const uchar *ip)
{
	uint ip_val = 0;

	ip_val = ip[0]<<24 | ip[1]<<16 | ip[2]<<8 | ip[3];

	return ip_val;
}

/*****************************************************************************
 函 数 名  : iptoun_btob()
 功能描述  : 将存在ip[]的ip地址(大端)转化为32无符号整数(大端)
 输入参数  : ip[]
 返 回 值  : 返回32无符号整数的ip地址(大端)
 修改日期  : 2015年9月10日
*****************************************************************************/
uint iptoun_btob(const uchar *ip)
{
	uint ip_val = 0;

	ip_val = ip[3]<<24 | ip[2]<<16 | ip[1]<<8 | ip[0];
	//ip_val = *(uint *)ip;

	return ip_val;
}

/*****************************************************************************
 函 数 名  : insert_arp_table()
 功能描述  : 建立ARP表
 输入参数  : head   链表头
             node   待插入节点
 返 回 值  : 链表头指针
 修改日期  : 2015年9月10日
*****************************************************************************/
ARP_Table *insert_arp_table(ARP_Table *head, ARP_Table node)
{
	ARP_Table *pi = NULL;
	pi = (ARP_Table *)malloc(sizeof(ARP_Table));

	//bzero(pi, 0, sizeof(ARP_Table));

	if(pi != NULL) //成功申请到空间
	{
		*pi = node;
		pi->next = NULL;

		int ip_val = iptoun_btol(node.ip);

		if(head == NULL)
		{
			head = pi;
		}
		else //链表不为空
		{
			ARP_Table *pb = NULL, *pf =NULL;
			pb = pf = head;

			//按从小到大插入链表
			while((ip_val > iptoun_btol(pb->ip)) && (pb->next != NULL))
			{
				pf = pb;
				pb = pb->next;
			}

			if(ip_val <= iptoun_btol(pb->ip))//链表头插入新节点
			{
				if(pb == head)
				{
					pi->next = pb;
					head = pi;
				}
				else //中间插入新节点
				{
					pi->next = pb;
					pf->next = pi;
				}
			}
			else //尾部插入新节点
			{
				pb->next = pi;
			}
		}
	}
	else
	{
		printf("Can not apply for a ARP_Table node memeory space!\n");
	}

	return head;
}

/*****************************************************************************
 函 数 名  : search_arp_table()
 功能描述  : 查找ARP表
 输入参数  : head   链表头
             ip     从链表查找的ip
 返 回 值  : 链表头指针
 修改日期  : 2015年9月10日
*****************************************************************************/
ARP_Table *search_arp_table(ARP_Table *head, const uchar *ip)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		ARP_Table *pb = head;
		uint ip_val;

		ip_val = iptoun_btol(ip);

		while((ip_val != iptoun_btol(pb->ip)) && (pb->next != NULL))
			pb = pb->next;

		if(ip_val == iptoun_btol(pb->ip)) //在ARP表找到匹配的ip
		{
			return pb;
		}
	}
	return NULL; //没找到匹配的ip返回NULL
}

/*****************************************************************************
 函 数 名  : delete_arp_node()
 功能描述  : 查找ARP表,并删除链表中的指定节点
 输入参数  : head   链表头
             ip     从链表查找的ip
 返 回 值  : 链表头指针
 修改日期  : 2015年9月10日
*****************************************************************************/
ARP_Table *delete_arp_node(ARP_Table *head, const uchar *ip)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		ARP_Table *pb = NULL, *pf = NULL;
		pb = pf =head;
		uint ip_val = iptoun_btol(ip);

		while((ip_val != iptoun_btol(pb->ip)) && (pb->next != NULL))
		{
			pf = pb;
			pb = pb->next;
		}

		if(ip_val == iptoun_btol(pb->ip))
		{
			if(pb == head) //删除的节点再链表头
				head = pb->next;

			else if(pb->next == NULL) //删除的节点在表尾
				pf->next = NULL;

			else //删除的节点再中间
				pf->next = pb->next;

			free(pb);
		}
	}

	return head;
}

/*****************************************************************************
 函 数 名  : free_arp_table()
 功能描述  : 释放整个ARP表
 输入参数  : head   链表头
 返 回 值  : 链表头指针
 修改日期  : 2015年9月10日
*****************************************************************************/
ARP_Table *free_arp_table(ARP_Table *head)
{
	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		ARP_Table *pb = head;

		//释放整个链表的方法:
		//1、判断head是否为空
		//2、让pb指向和head相同的节点
		//3、然后head指向下一个节点
		//4、再释放pb指向的节点
		//5、返回步骤1
		while(head != NULL)
		{
			pb = head;
			head = pb->next;
			free(pb);
		}
	}

	return head;
}

/*****************************************************************************
 函 数 名  : change_arp_mac()
 功能描述  : 查找整个ARP表，修改ip对应的mac
 输入参数  : head   链表头
 			 ip     要修改mac对应的ip
 			 mac    新的mac
 返 回 值  : Boolean 类型值，成功返回:TRUE
 修改日期  : 2015年9月12日
*****************************************************************************/
Boolean change_arp_mac(ARP_Table *head, const uchar ip[], const uchar mac[])
{
	if(head == NULL){
		printf("Link is not exist!\n");
	}
	else {

		ARP_Table *pnode = NULL;

		pnode = search_arp_table(head, ip);

		if(pnode != NULL){
			memcpy(pnode->mac, mac, 6);

			return TRUE;
		}
	}

	return FALSE;
}

/*****************************************************************************
 函 数 名  : print_arp_table()
 功能描述  : 打印整个ARP表
 输入参数  : head   链表头
 返 回 值  : 链表头指针
 修改日期  : 2015年9月10日
*****************************************************************************/
void print_arp_table(ARP_Table *head)
{

	if(head == NULL)
	{
		printf("Link is not exist!\n");
	}
	else
	{
		uchar ip[16] ="";
		uchar mac[18]="";
		ARP_Table *pb = head;

		printf("_____IP________________MAC_______\n");
		while(pb != NULL)
		{
			bzero(ip, 16);
			bzero(mac,18);

			sprintf(ip,"%d.%d.%d.%d",\
				    pb->ip[0],pb->ip[1],pb->ip[2],pb->ip[3]);

			sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
				    pb->mac[0],pb->mac[1],pb->mac[2],pb->mac[3],pb->mac[4],pb->mac[5]);

			printf("%-12s -- %s\n", ip,mac);

			pb = pb->next;
		}
		printf("_________________________________\n");
	}
}

<file_sep>/sys_program/player/src/inc/link.h
/* ************************************************************************
 *       Filename:  link.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 05時39分46秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __LINK_H__
#define __LINK_H__

#include "common.h"

LRC *insert_link(LRC *head, LRC slrc);
LRC *free_link(LRC *head);
void print_link(LRC *head);
LRC *search_link(LRC *head,int time);

#endif



<file_sep>/work/test/sndkit/sound.c
/*************************************************************************
	> File Name: sound.c
	> Author: 
	> Mail: 
	> Created Time: Tue 06 Sep 2016 05:26:44 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/ioctl.h>
#include <linux/soundcard.h>

#define LENGTH    8      /* 存储秒数 */
#define RATE      16000  /* 采样频率 */
#define BITS      16     /* 量化位数 */
#define CHANNELS  1      /* 声道数目 */

/********以下是wave格式文件的文件头格式说明******/
/*------------------------------------------------
|             RIFF WAVE Chunk                  |
|             ID = 'RIFF'                     |
|             RiffType = 'WAVE'                |
------------------------------------------------
|             Format Chunk                     |
|             ID = 'fmt '                      |
------------------------------------------------
|             Fact Chunk(optional)             |
|             ID = 'fact'                      |
------------------------------------------------
|             Data Chunk                       |
|             ID = 'data'                      |
------------------------------------------------*/
/**********以上是wave文件格式头格式说明***********/
/*wave 文件一共有四个Chunk组成，其中第三个Chunk可以省略，每个Chunk有标示（ID）,大小（size,就是本Chunk的内容部分长度）,内容三部分组成*/
typedef struct waveheader
{
	/****RIFF WAVE CHUNK*/
	unsigned char a[4];//四个字节存放'R','I','F','F'
	long int b;        //整个文件的长度-8;每个Chunk的size字段，都是表示除了本Chunk的ID和SIZE字段外的长度;
	unsigned char c[4];//四个字节存放'W','A','V','E'
	/****Format CHUNK*/
	unsigned char d[4];//四个字节存放'f','m','t',''
	long int e;       //16后没有附加消息，18后有附加消息；一般为16，其他格式转来的话为18
	short int f;       //编码方式，一般为0x0001;
	short int g;       //声道数目，1单声道，2双声道;
	long int h;        //采样频率;
	long int i;        //每秒所需字节数;
	short int j;       //每个采样需要多少字节，若声道是双，则两个一起考虑;
	short int k;       //即量化位数
	/***Data Chunk**/
        unsigned char p[4];//四个字节存放'd','a','t','a'
	long int q;        //语音数据部分长度，不包括文件头的任何部分
} waveheader;//定义WAVE文件的文件头结构体

waveheader *get_waveheader(int bits, int rates, int channels, unsigned long size)
{
    waveheader *header = malloc(sizeof(*header));

	header->a[0] = 'R';
	header->a[1] = 'I';
	header->a[2] = 'F';
	header->a[3] = 'F';
	header->b = size - 8;
	header->c[0] = 'W';
	header->c[1] = 'A';
	header->c[2] = 'V';
	header->c[3] = 'E';
	header->d[0] = 'f';
	header->d[1] = 'm';
	header->d[2] = 't';
	header->d[3] = ' ';
	header->e = 16;
	header->f = 1;
	header->g = channels;
	header->h = rates;
	header->i = size / (rates * channels * bits / 8);
	header->j = channels * bits / 8;
	header->k = bits;
	header->p[0] = 'd';
	header->p[1] = 'a';
	header->p[2] = 't';
	header->p[3] = 'a';
	header->q = size;

    return header;
}

int main(int argc, char *argv[])
{
    unsigned char *buf = NULL, *pbuf = NULL;
    unsigned int size = 0, cnt = 0;
    int len;
    int fd;     /* 声音设备的文件描述符 */
    int arg;    /* 用于ioctl调用的参数 */
    int status; /* 系统调用的返回值 */

    if (argc > 2) {
        printf("Too many arguments!\n");
        exit(1);
    }

    if (argc == 2) {
        /* 打开声音设备 */
        fd = open("/dev/mixer3", O_RDWR);
        if (fd < 0) {
            perror("open of /dev/mixer3 failed");
            exit(1);
        }

        arg = atoi(argv[1]);
        /* set dmix gain */
        status = ioctl(fd, SOUND_MIXER_WRITE_MIC, &arg);
        if(status < 0)
            perror("SOUND_MIXER_WRITE_MIC ioctl failed");

        int vol = 0, left = 0, right = 0;
        /* get dmic gain */
        status = ioctl(fd, SOUND_MIXER_READ_IGAIN, &vol);
        left = vol & 0xff;
        right = vol >> 8;
        printf("left gain id %d %%, right gain is %d %%\n", left, right);
        close(fd);
    }

    /* 打开声音设备 */
    fd = open("/dev/dsp3", O_RDONLY);
    if (fd < 0) {
        perror("open of /dev/dsp3 failed");
        exit(1);
    }

    /* 设置采样时的量化位数 */
    arg = BITS;
    status = ioctl(fd, SNDCTL_DSP_SETFMT, &arg);
    if (status < 0)
        perror("SOUND_PCM_WRITE_BITS ioctl failed");
    if (arg != BITS)
        perror("unable to set sample size");

    /* 设置采样时的声道数目 */
    arg = CHANNELS;
    status = ioctl(fd, SNDCTL_DSP_CHANNELS, &arg);
    if (status < 0)
        perror("SOUND_PCM_WRITE_CHANNELS ioctl failed");
    if (arg != CHANNELS)
        perror("unable to set number of channels");

    /* 设置采样时的采样频率 */
    arg = RATE;
    status = ioctl(fd, SNDCTL_DSP_SPEED, &arg);
    if (status < 0)
        perror("SOUND_PCM_WRITE_WRITE ioctl failed");

    /* 用于保存数字音频数据的内存缓冲区 */
    size = LENGTH * RATE * CHANNELS * BITS/8;
    buf = (unsigned char *)malloc(size);
    if(buf == NULL) {
        printf("malloc data buffer failed!\n");
        exit(1);
    }

    printf("Say something now...\n");
    len = read(fd, buf, size);
    if(len != size) {
        perror("read wrong number of bytes");
        exit(1);
    }

    /* make the wav file header */
    waveheader *header = get_waveheader(BITS, RATE, CHANNELS, len);

    /* creat wav file */
    int wav_fd = open("/tmp/record.wav", O_WRONLY | O_CREAT, 0777);

    /* write wav file header */
    write(wav_fd, header, sizeof(*header));
    free(header);
    header = NULL;

    pbuf = buf;
    /* write pcm data */
    while(len > 0) {
        cnt = len > 10240 ? 10240 : len;
        cnt = write(wav_fd, pbuf, cnt);
        if(cnt < 0) {
            printf("write error, retry.\n");
            exit(1);
        }
        len -= cnt;
        pbuf += cnt;
    }

    free(buf);
    close(fd);
    close(wav_fd);
    printf("record done, output file: /tmp/recorder.wav\n");
    return 0;
}
<file_sep>/sys_program/2nd_day/am/system.c
/* ************************************************************************
 *       Filename:  system.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 19时09分10秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>


int main(int argc, char *argv[])
{
	pid_t pid;
	char cmd[128] = "";

	while(1)
	{
		//printf("Please input a cmd: ");
		//fgets(cmd,sizeof(cmd),stdin);
		//printf("%d\n",strlen(cmd));
		//cmd[strlen(cmd)-1] = '\0'; //把获取的字符后面的\n转化成 '\0'

		pid =  fork(); //创建子进程

		if(pid == 0) //子进程
		{
			int len = 0;
			printf("Please input a cmd: ");
			fgets(cmd,sizeof(cmd),stdin);

			len = strlen(cmd);
			//printf("%d\n",len);
			if(len > 1)
			{
				cmd[len-1] = '\0'; //把获取的字符后面的\n转化成 '\0'
			}
			else
			{
				exit(0);
			}

			//printf("in son process\n");
			execl("/bin/sh","sh","-c",cmd,NULL);
			exit(1);
		}
		wait(NULL);
	}

	return 0;
}
<file_sep>/work/test/v4l2/include/capture.h
/*************************************************************************
	> Filename: capture.h
	>   Author: Qiuwei.wang
	>    Email: <EMAIL>
	> Datatime: Fri 02 Dec 2016 10:07:17 AM CST
 ************************************************************************/

#ifndef _CAPTURE_H
#define _CAPTURE_H

/*
 * Struct
 */
typedef enum {
	IO_METHOD_READ,
	IO_METHOD_MMAP,
	IO_METHOD_USERPTR,
} io_method;

struct buffer {
	void *start;
	size_t length;
};

struct capture_t {
	char *dev_name;
	int fd;
	unsigned int width;
	unsigned int height;
	unsigned int bpp;
	unsigned int sizeimage;
	unsigned int nbuf;
	unsigned int count;

	io_method io;
	struct buffer *pbuf;
};

/*
 * Extern functions
 */
int read_frame(struct capture_t *capt);
void process_image(struct capture_t *capt, int index);
void start_capturing(struct capture_t *capt);
void stop_capturing(struct capture_t *capt);
void test_framerate(struct capture_t *capt);
void open_device(struct capture_t *capt);
void close_device(struct capture_t *capt);
void init_device(struct capture_t *capt);
void free_device(struct capture_t *capt);
void main_loop(struct capture_t *capt);

#endif
<file_sep>/network/route/tcp/main.c
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>



int main(int argc, char *argv[])
{
	char cmd[] = 
	char ip[16] = "192.168.1.221";
	unsigned short port = 8080;

	if(argc > 1) {
		strcpy(ip, argv[1]);
	}
	//1.创建一个用于通信的tcp套接字
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	
	//2.连接制定的服务器
	struct sockaddr_in s_addr;
	bzero(&s_addr, sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(8080);
	s_addr.sin_addr.s_addr = inet_addr(ip);
	//3.连接
	int ret = connect(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
	if(ret != 0)
	{
		perror("connect:");
		exit(-1);
	}

	while(1)
	{
		printf("cmd: ");
		fflush(stdout);

		cmd[strlen(cmd)- 1] = 0; // 去掉 \n

		
	}
	return 0;
}

<file_sep>/network/route/src/firewall_file.c
/******************************************************************************
  文 件 名   : firewall_file.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月15日
  最近修改   :
  功能描述   : 将防火墙规则写入文件或从文件读出
  函数列表   :
              filrewall_save_rule
              firewall_config
              firewall_read_rule_file
              firewall_save_all_rules
              firewall_get_passwd
              firewall_save_passwd
  修改历史   :
  1.日    期   : 2015年9月15日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"
#include "route_firewall.h"

/*----------------------------------------------*
 * 宏定义                                       *
 *----------------------------------------------*/
#define RULE_FILE    ".firewall_rule"
#define PASSWD_FILE  ".passwd"

/*****************************************************************************
 函 数 名  : firewall_save_all_rules()
 功能描述  : 把防火墙规则链表的所有规则保存到文件
 输入参数  : rt       TYPE_Route 类型结构指针
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
void firewall_save_all_rules(TYPE_Route *rt)
{
	FILE *fp = NULL;
	FIRE_Wall *pnode = NULL;
	FIRE_Wall *pbuf[4] = {rt->mac_head,rt->ip_head,rt->port_head,rt->pro_head};
	char rule[RULE_LEN] = "";
	int i = 0;
	
	fp = fopen(RULE_FILE, "wb");

	if(fp != NULL){
		for(i=0; i<4; i++)
		{
			pnode = pbuf[i];

			while(pnode != NULL)
			{
				strcpy(rule, pnode->rule);
				strcat(rule,"\n");
				fwrite(rule, 1, strlen(rule), fp);

				pnode = pnode->next;
			}		
		}
		
		fclose(fp);
	}		
}

/*****************************************************************************
 函 数 名  : filrewall_save_rule()
 功能描述  : 把新加的防火墙规则保存到文件
 输入参数  : rule     要保存的规则
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
void filrewall_save_rule(const char *rule)
{
	FILE *fp = NULL;	

	fp = fopen(RULE_FILE, "ab");
	if(fp != NULL){
		char buf[RULE_LEN] = "";

		strcpy(buf, rule);
		strcat(buf, "\n");

		fwrite(buf, 1, strlen(buf), fp);
		fclose(fp);
	}
}

/*****************************************************************************
 函 数 名  : firewall_read_rule_file()
 功能描述  : 读出防火墙规则文件的内容
 输入参数  : file_name       文件名
 返 回 值  : 返回指向文件内容的首部的指针
 修改日期  : 2015年9月15日
*****************************************************************************/
static char *firewall_read_rule_file(const char *file_name)
{
	FILE *fp = NULL;
	char *buf = NULL;
	ulint file_length = 0;

	fp = fopen(file_name, "rb");
	if(fp == NULL){
		//printf("Cannot open the flie!\n");
		//Z文件不存在，则创建，然后返回
		fp = fopen(file_name, "wb");
		fclose(fp);
		return;
	}

	fseek(fp,0,SEEK_END);
	file_length = ftell(fp);
	buf = (char *)malloc(file_length); //动态分配内存

	if(buf == NULL){
		printf("malloc() cannot apply for memory!\n");
		goto out;
	}
	rewind(fp); //
	fread(buf,file_length,1,fp);

	out:
	fclose(fp);
	return buf;
}

/*****************************************************************************
 函 数 名  : firewall_config()
 功能描述  : 读出防火墙规则文件的内容，建立过滤规则链表
 输入参数  : rt       TYPE_Route 类型结构指针
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
void firewall_config(TYPE_Route *rt)
{
	char *p_src = NULL;
	char *p_rule= NULL;

	p_src = (char *)firewall_read_rule_file(RULE_FILE);

	p_rule = strtok(p_src, "\n");
	while(p_rule != NULL){
		firewall_build_rule(rt, p_rule, 0);
		p_rule = strtok(NULL, "\n");
	}

	free(p_src);
}

/*****************************************************************************
 函 数 名  : firewall_get_passwd()
 功能描述  : 从文件获取防火墙的密码
 输入参数  : rt       TYPE_Route 类型结构指针
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
void firewall_get_passwd(TYPE_Route *rt)
{
	FILE *fp = NULL;
	char str[PASSWD_LEN] = "";
	int i, len;

	fp = fopen(PASSWD_FILE, "rb");
	if(fp == NULL) {
		//文件不存在，则创建，然后退出
		fp = fopen(PASSWD_FILE, "wb");
		fclose(fp);
		return;
	}

	len = fread(str, 1, PASSWD_LEN, fp); //fread 返回实际读的块数
	len--;
	str[len] = 0; // 去掉 \n

	for(i=0; i<len; i++) {
		str[i] -= ENCRYPT_KEY;
	}

	strcpy(rt->passwd, str);

	fclose(fp);
}

/*****************************************************************************
 函 数 名  : firewall_save_passwd()
 功能描述  : 防火墙的密码加密后保存到文件
 输入参数  : passwd       要保存的密码
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
void firewall_save_passwd(char passwd[])
{
	FILE *fp = NULL;
	int i, len;

	len = strlen(passwd);

	for(i=0; i<len; i++) {
		passwd[i] += ENCRYPT_KEY;
	}

	if(len >= PASSWD_LEN) {
		len = PASSWD_LEN-1;
		passwd[len] = 0;
	}
	strcat(passwd,"\n");

	fp = fopen(PASSWD_FILE, "wb");
	if(fp != NULL) {
		fwrite(passwd, 1, len+1, fp);
		fclose(fp);
	}
}

/*****************************************************************************
 函 数 名  : getch()
 功能描述  : 获取一个字符
 输入参数  : NULL
 返 回 值  : NULL
 修改日期  : 2015年9月15日
*****************************************************************************/
static char getch()
{
    struct termios oldt, newt;
    char ch;

    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );

    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );

    return ch;
}

/*****************************************************************************
 函 数 名  : get_passwd()
 功能描述  : 获取密码
 输入参数  : pwd      保存获取密码的指针
 返 回 值  : max_len  密码的最大长度
 修改日期  : 2015年9月15日
*****************************************************************************/
void get_passwd(char passwd[], int max_len)
{
	char ch = 0, i = 0;
	char buf[PASSWD_LEN];

	while(i < max_len)
	{
		ch = getch();
		if(ch == 10){       // 回车键
			passwd[i] = 0;
			break;
		}
		else if(ch ==127) { // 回格键
			//i--;
			//if(i<0) i = 0;
			continue;
		}
		passwd[i++] = ch;
		putchar('*');
	}

	passwd[max_len] = 0;
}
<file_sep>/work/test/v4l2/include/common.h
/*************************************************************************
	> Filename: common.h
	>   Author: Qiuwei.wang
	>    Email: <EMAIL> / <EMAIL>
	> Datatime: Fri 02 Dec 2016 02:24:29 PM CST
 ************************************************************************/

#ifndef _COMMON_H
#define _COMMON_H

#define TRUE   1
#define FALSE  0
#define CLEAR(x) memset (&(x), 0, sizeof (x))

#define errno_exit(str)     \
	do {                    \
		fprintf(stderr, "%s error %d, %s\n",  \
			str, errno, strerror(errno));     \
		exit(EXIT_FAILURE); \
	} while(0)

#define xioctl(fd, request, arg)  \
	({                             \
		int ret;                  \
		do {                      \
			ret = ioctl(fd, request, arg);    \
		} while(-1 == ret && EINTR == errno); \
                                              \
		ret; \
	})


/*
 * Extern functions
 */
void *JZMalloc(int align, int size);
void jz47_free_alloc_mem();
unsigned int get_phy_addr(unsigned int vaddr);

#endif
<file_sep>/network/5th_day/raw_test.c
int main(int argc,char *argv[])
{
  //1.创建一个原始套接字
  int raw_fd = socket(PF_PACKET,SOCK_RAW,htons(ETH_P_ALL));
  unsigned char msg[2048]="";
  //1.封装mac头
  unsigned char dst_mac[6]={0x00,0x0c,0x29,0xef,0x4d,0x3d};
  unsigned char src_mac[6]={0x00,0x0c,0x29,0xf5,0xc6,0x39};
  struct ether_header *eth_hdr = NULL;
  eth_hdr = (struct ether_header *)msg;
  memcpy(eth_hdr->ether_dhost,6);
  memcpy(eth_hdr->ether_shost,6);
  ether_hdr->ether_type = htons(0x0800);

  //2.封装ip头
  struct iphdr *ip_hdr =NULL;
  ip_hdr = (struct iphdr *)(msg+14);
  ip_hdr->version =4;
  ip_hdr->ihl=5;
  ip_hdr->tos=0;
  ip_hdr->tot_len = htons(20+ip_data_len);//两个字节的 要htons
  ip_hdr->saddr = inet_addr("10.221.2.16");
  ip_hdr->daddr = inet_addr("");
  ip_hdr->check = htons(0);//????????
  //2.封装udp头部
  struct udphdr *udp_hdr;
  udp_hdr = (struct udphdr *)(msg+14+20);
  udp_hdr->source = htons(8000);
  udp_hdr->dest = htons(8000);
  udp_hdr->len = htons(8+udp_data_len);
  udp_hdr->check=htons(0);//??

  //3.udp数据
  memcpy(msg +14 +20+8,"hehe",strlen("hehe"));
  //4.ip首部校验
  ip->check = htons(checksum(msg+14),20/2);
  //5.0 udp校验
  unsigned char wei_udp[1024]={
        10.221.2.66//源ip
		10.221.2.16//目的ip
		0,17,0,0//长度需要对其赋值&
  }
  *(unsigned short *)(wei_udp+10) = htons(8+strlen("hehe"));//&
  memcpy(wei_udp+12,msg+12+20,8+strlen("hehe"));
  udp_hdr->check = htons(checksum(wei_udp,(12+8+strlen("hehe"))/2));

  sendto();

}
<file_sep>/network/route/Makefile
DIR_INC := ./src/inc
DIR_SRC := ./src
DIR_OBJ := ./obj
DIR_BIN := ./bin

SRC = $(wildcard ${DIR_SRC}/*.c)
OBJ = $(patsubst %.c,${DIR_OBJ}/%.o,$(notdir ${SRC}))

TARGET = route

#BIN_TARGET = ${DIR_BIN}/${TARGET} # 目标存放在 bin目录
BIN_TARGET = ./${TARGET}  # 目标存放在当前目录

CC = gcc
INCFAG = -I$(DIR_INC)
CFLAGES = -lpthread

$(shell test -e obj || mkdir obj)

$(BIN_TARGET):$(OBJ)
	$(CC) $(OBJ)  -o $@ $(CFLAGES)

$(DIR_OBJ)/%.o:$(DIR_SRC)/%.c
	$(CC) $(INCFAG) -c  $< -o $@ $(CFLAGES)

.PHONY:clean
clean:
#	find $(DIR_OBJ) -name *.o -exec rm -rf {}\ ;
	rm ${DIR_OBJ}/* ${TARGET}
<file_sep>/c/practice/3rd_week/mylink/link.h
#ifndef __LINK_H__
#define __LINK_H__

typedef struct student
{
	int num;
	char name[64];
	int score;
	
	struct student *next;
}STU;

/*******************************************/
extern STU *insert_link(STU *head, STU temp);
extern void print_link(STU *head);
extern STU *search_link(STU *head, char *name);
extern STU *delete_link(STU *head, int num);
extern STU *delete_head(STU *head);
extern STU *free_link(STU *head);
extern STU *sort_link(STU *head);
extern STU *invert_link(STU *head);
#endif
<file_sep>/work/test/socket/socket_server.c
/*************************************************************************
	> File Name: socket_server.c
	> Author: 
	> Mail: 
	> Created Time: Tue 17 May 2016 11:28:50 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>


int main(int argc, char ** argv) {
    int listenfd;
    struct sockaddr_in servaddr;
    pid_t pid;
    char temp[100];
    int n = 0;

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(atoi(argv[1]));
    bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    listen(listenfd, n);
    for(;;) {
        struct sockaddr_in local;
        int connfd = accept(listenfd, (struct sockaddr *)NULL, NULL);
        if((pid = fork()) == 0) {
            struct sockaddr_in serv, guest;
            char serv_ip[20];
            char guest_ip[20];
            int serv_len = sizeof(serv);
            int guest_len = sizeof(guest);
            getsockname(connfd, (struct sockaddr *)&serv, &serv_len);
            getpeername(connfd, (struct sockaddr *)&guest, &guest_len);
            inet_ntop(AF_INET, &serv.sin_addr, serv_ip, sizeof(serv_ip));
            inet_ntop(AF_INET, &guest.sin_addr, guest_ip, sizeof(guest_ip));
            printf("host %s:%d guest %s:%d\n", serv_ip, ntohs(serv.sin_port), guest_ip, ntohs(guest.sin_port));
            char buf[] = "hello world";
            write(connfd, buf, strlen(buf));
            close(connfd);
            exit(0);

        }
        close(connfd);
    }
}
<file_sep>/sys_program/2nd_day/am/Makefile
elf:vfork.c
	gcc -o elf vfork.c


.PHONY:clean
clean:
	rm elf
<file_sep>/work/test/mplay/wavsound.c
/*************************************************************************
	> File Name: wavsound.c
	> Author:
	> Mail:
	> Created Time: Fri 14 Oct 2016 02:26:26 PM CST
 ************************************************************************/

#include <tinyalsa/asoundlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>

/*
 * Macro
 */
#define	ID_RIFF		0x46464952
#define	ID_WAVE		0x45564157
#define	ID_FMT		0x20746d66
#define	ID_DATA		0x61746164
#define FORMAT_PCM  1

/*
 * Struct
 */
struct riff_wave_header {
    uint32_t riff_id;
    uint32_t riff_sz;
    uint32_t wave_id;
};

struct chunk_header {
    uint32_t id;
    uint32_t sz;
};

struct chunk_fmt {
    uint16_t audio_format;
    uint16_t num_channels;
    uint32_t sample_rate;
    uint32_t byte_rate;
    uint16_t block_align;
    uint16_t bits_per_sample;
};

struct wav_header {
	uint32_t  riff_id;
	uint32_t  riff_sz;
	uint32_t  riff_fmt;
	uint32_t  fmt_id;
	uint32_t  fmt_sz;
	uint16_t  audio_format;
	uint16_t  num_channels;
	uint32_t  sample_rate;
	uint32_t  byte_rate;
	uint16_t  block_align;
	uint16_t  bits_per_sample;
	uint32_t  data_id;
	uint32_t  data_sz;
};

extern int close_flag;

void play_sample(char *filename, unsigned int device)
{
	char *buffer = NULL;
	int size, num_read;
	static FILE *file = NULL;
	struct pcm *pcm;
	struct pcm_config config;
	struct wav_header header;

	printf("entry: %s\n", __FUNCTION__);

	bzero(&config, sizeof(struct pcm_config));

	file = fopen(filename, "rb");
	if(!file) {
		printf("Unable to open file '%s'\n", filename);
		return;
	}

	fread(&header, sizeof(struct wav_header), 1, file);

	if((header.riff_id != ID_RIFF) || (header.riff_fmt != ID_WAVE) ||
	   (header.fmt_id != ID_FMT) || (header.audio_format != FORMAT_PCM) ||
	   (header.fmt_sz != 16)) {
		printf("Error: '%s' is not a PCM riff/wave file\n", filename);
		fclose(file);
		return;
	}

	config.channels = header.num_channels;
	config.rate = header.sample_rate;
	config.period_size = 1024;
	config.period_count = 4;

	if(header.bits_per_sample == 32)
		config.format = PCM_FORMAT_S32_LE;
	else if(header.bits_per_sample == 16)
		config.format = PCM_FORMAT_S16_LE;
	config.start_threshold = 0;
	config.stop_threshold = 0;
	config.silence_threshold = 0;

	pcm = pcm_open(0, device, PCM_OUT, &config);
	if(!pcm || !pcm_is_ready(pcm)) {
		printf("Unable to open PCM device %u (%s)\n", device, pcm_get_error(pcm));
		return;
	}

	size = pcm_frames_to_bytes(pcm, pcm_get_buffer_size(pcm));
	buffer = malloc(size);
	if(!buffer) {
		printf("Unable to allocate %d bytes\n", size);
		pcm_close(pcm);
		return;
	}

	printf("Playing sample: %u ch, %u hz, %u bit\n", header.num_channels,
			header.sample_rate, header.bits_per_sample);

	do {
		num_read = fread(buffer, 1, size, file);
		if(num_read > 0) {
			if(pcm_write(pcm, buffer, num_read)) {
				printf("Error playing sample\n");
				break;
			}
		}
	} while(num_read > 0);

	printf("pcm_write over...\n");
	fclose(file);
	free(buffer);
	pcm_close(pcm);
}
<file_sep>/network/3rd_day/tcp_client.c
/* ************************************************************************
 *       Filename:  tcp_client.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年09月02日 14时38分49秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
	//1.创建一个用于通信的tcp套接字
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);

	//2.连接制定的服务器
	struct sockaddr_in s_addr;
	bzero(&s_addr, sizeof(s_addr));
	s_addr.sin_family = AF_INET;
	s_addr.sin_port = htons(8080);
	s_addr.sin_addr.s_addr = inet_addr("10.221.2.12");
	//连接
	int ret = connect(sockfd, (struct sockaddr *)&s_addr, sizeof(s_addr));
	if(ret != 0)
	{
		perror("connect:");
		exit(-1);
	}
	//3.给服务器发送数据
	send(sockfd, "hehe", strlen("hehe"), 0);

	//4.接收服务器的应答
	char buf[128]="";
	recv(sockfd, buf, sizeof(buf),0);

	//5.关闭tcp套接字
	close(sockfd);
	return 0;
}


<file_sep>/c/practice/3rd_week/string/main.c
#include <stdio.h>
#include <string.h>
#include "mystring.h"

void main()
{
	char a[]="jkdjgse";
	char b[20]="hjakh";
	char c[]="12345";
	int num = 0;

	mystrinv(a);
	printf("a=%s\n",a);
	printf("%d\n",mystrcmp(a,b));

	num = strchange(c);
	printf("num=%d\n",num);

	mystrcpy(b,a);
	printf("b=%s\n",b);
}
<file_sep>/work/shell/test.sh
#!/bin/bash

UBOOT_BUILD_CONFIG=halley2_v10_xImage_sfc_nor
KERNEL_BUILD_CONFIG=halley2_nor_v10_linux_defconfig
KERNEL_TARGET_IMAGE=xImage

echo "$KERNEL_BUILD_CONFIG, $KERNEL_TARGET_IMAGE, $UBOOT_BUILD_CONFIG"

tmp=${1#-j}
echo "$tmp"

x="xx87+ jdlj"
echo $x | grep -o '[0-9]\+'

case "$2" in
	[1-9][0-9]*)
		echo "$2 is number"
		;;
	*)
		;;
	esac

if [ -n "$(echo $2 | sed -n "/^[0-9]\+$/p")" ];then
  echo "$2 is number."
else
  echo 'no.'
fi
<file_sep>/sys_program/player/src/inc/mplayer_pthread.h
/* ************************************************************************
 *       Filename:  mplayer_process.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月23日 18时05分21秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __MPLAYER_PTHREAD_H__
#define __MPLAYER_PTHREAD_H__

extern SONG song;

extern void mplayer_init(MPLAYER *pm);
extern void gtk_thread_init(void);
extern void get_song_msg(MPLAYER *pm);
extern int  mplayer_process(MPLAYER *pm);
extern void create_pthread(MPLAYER *pm);
#endif<file_sep>/c/practice/check_samechar.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int check_samechar(char *str)
{
	char ch[127] = {0};
	int i = 0;

	if(str == NULL) return 0;

	while(str[i] != 0){
		if(ch[str[i]] == 0){
			ch[str[i]] = str[i];
		}
		else return 1;
		i++;
	}

	return 0;
}

int main(int argc, char *argv[])
{
	char str[64] = "";
	int len = 0;

	printf("输入字符串：");
	// 刷新标准输出，因为在printf函数的缓冲没满，并且打印的
	// 字符串后面没有 "\n"，调用这个函数屏幕马上可以看到”输入字符串：“
	fflush(stdout);

	fgets(str, sizeof(str), stdin); // 从标准输入获取输入字符串
	len = strlen(str); // 求出长度
	str[len - 1] = 0;  // 去掉字符串后的换行符

	int flag = check_samechar(str); // 处理

	if(flag == 1)
		printf("##:%s\n", str);

	return 0;
}
<file_sep>/c/lrc/Makefile
CC := gcc
SRC := $(shell ls *.c)
#OBJ := $(patsubst %.c,%.o,$(SRC))
OBJ := $(SRC: %.c=%.o)
TAG := lrc

$(TAG):$(OBJ)
	$(CC) -o $@ $^ 
%.o:%.c
	$(CC) -o $@ -c $<


.PHONY:clean
clean:
	rm -f $(TAG) *.o
<file_sep>/c/practice/3rd_week/time/show_time.h
#ifndef __SHOW_TIME_H__
#define __SHOW_TIME_H__

extern void show_time(void);
#endif
<file_sep>/sys_program/1st_day/wait.c
/* ************************************************************************
 *       Filename:  wait.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月13日 17时03分10秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>


int main(int argc, char *argv[])
{
	pid_t pid;

	pid = fork();

	if(pid < 0) perror("error\n");

	else if (pid == 0)
	{
		int i = 0;

		for(i = 0;i<5;i++)
		{
			printf("in son process");

			sleep(1);
		}

		exit(2); //退出时会刷新缓冲区
		//_exit(2);//退出时 不会 刷新缓冲区
		//return 2; //这里return 2 跟 exit(2) 效果一样
	}
	else
	{
		int status = 0;
		int i;

		//wait(&status);
		waitpid(-1,&status,0);

		if(WIFEXITED(status) != 0) //判断返回状态 ，存在status的低8位
		{
			printf("return = %d\n",WEXITSTATUS(status)); //取返回值，存在status的8~16位
		}
		for(i=0;i<5;i++)
		{
			printf("in father process\n");
			sleep(1);
		}
	}

	return 0;
}
<file_sep>/work/notes/notes.c
配置：
source build/envsetup.sh

编译uboot:
cd bootable/bootloader/uboot
make aw808_wisesquare_an51_msc0


cat build/smk.sh | grep  aw808
build/smk.sh --preset=aw808_v11_wisesquare_iwop -j32

======================================================================
m200 watch:
版级代码所在目录:
qiuweiwang@sw1:~/4.3/kernel/arch/mips/xburst/soc-m200/chip-m200/watch$

该目录下的common目录下的keyboard_gpio.c


/4.3/kernel/drivers/input/keyboard/gpio_keys.c
======================================================================

out/host/linux-x86/bin/mkbootimg --kernel kernel-3.10.14/arch/mips/boot/compressed/zImage  --ramdisk out/target/product/aw808/ramdisk.img --output out/target/product/aw808/boot.img

./out/host/linux-x86/bin/mkbootimg  --kernel ./kernel/arch/mips/boot/compressed/zImage --ramdisk ./out/target/product/aw808_iwop/ramdisk.img  --output ./out/target/product/aw808_iwop/boot.img

out/host/linux-x86/bin/mkbootimg --kernel kernel-3.10.14/arch/mips/boot/compressed/zImage --ramdisk out/target/product/aw808/ramdisk.img --output out/target/product/aw808/boot.img

/5.1/kernel-3.10.14/arch/mips/xburst/soc-m200/chip-m200/watch/common$ vi i2c_bus.c
======================================================================
烧录kernel:
adb push boot.img /data
cat boot.img > /dev/block/mmcblk0p1 

======================================================================
从历史命令中查看与sshfs相关的
history | grep sshfs
sshfs qiuweiwang@192.168.3.11:/home/qiuweiwang/ /home/qwwang/server

======================================================================
setenv bootargs mem=256M mem=768M@0x30000000 console=ttyS3,57600n8 ip=off root=/dev/mmcblk0p5 bk_root=/dev/mmcblk0p7 rw rootdelay=2 keep_bootcon


qwwang@qiuweiwang:/$ /etc/init.d/xinetd start
 * Starting internet superserver xinetd                                  [ OK ]

sudo /etc/init.d/tftpd-hpa start
ps -aux | grep 6847
sudo chmnod 777 /var/lib/tftpboot/
======================================================================
在内核中， sysfs 属性一般是由 __ATTR 系列的宏来声明的，如对设备的使用 DEVICE_ATTR ，对总线使用 BUS_ATTR ，对驱动使用 DRIVER_ATTR ，对类别(class)使用 CLASS_ATTR, 这四个高级的宏来自于 <include/linux/device.h>, 都是以更低层的来自 <include/linux/sysfs.h> 中的 __ATTR/__ATRR_RO 宏实现。这几个东东的区别就是，DEVICE_ATTR对应的文件在/sys/devices/目录中对应的device下面。而其他几个分别在driver，bus，class中对应的目录下

在documentation/driver-model/Device.txt中有对DEVICE_ATTR的详细介绍，这儿主要说明使用方法。

先看看DEVICE_ATTR的原型：
DEVICE_ATTR(_name, _mode, _show, _store)
_name：名称，也就是将在sys fs中生成的文件名称。
_mode：上述文件的访问权限，与普通文件相同，UGO的格式。
_show：显示函数，cat该文件时，此函数被调用。
_store：写函数，echo内容到该文件时，此函数被调用。

在终端查看到接口，当我们将数据 echo 到接口中时，在上层实际上完成了一次 write 操作，对应到 kernel ，调用了驱动中的 “store”。同理，当我们cat 一个 接口时则会调用 “show” 。

======================================================================
struct mmc_host是mmc core层与host层的接口，mmc_host.ops是控制host完成用户请求的接口函数集，其类型是struct mmc_host_ops，该结构体定义在include/linux/mmc/host.h文件中：

[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
 83structmmc_host_ops {  

 88   int (*enable)(struct mmc_host *host);  
 89   int (*disable)(struct mmc_host *host);  
 
 98   void    (*post_req)(structmmc_host *host, struct mmc_request *req,  
 99                int err);  
100   void    (*pre_req)(struct mmc_host*host, struct mmc_request *req,  
101               bool is_first_req);  
102   void    (*request)(struct mmc_host*host, struct mmc_request *req);  
103   /* 
104    * Avoid calling these three functions too often or in a "fastpath", 
105    * since underlaying controller might implement them in an expensive 
106    * and/or slow way. 
107    * 
108    * Also note that these functions might sleep, so don't call them 
109    * in the atomic contexts! 
110    * 
111    * Return values for the get_ro callback should be: 
112    *   0 for a read/write card 
113    *   1 for a read-only card 
114    *   -ENOSYS when not supported(equal to NULL callback) 
115    *   or a negative errno value whensomething bad happened 
116    * 
117    * Return values for the get_cd callback should be: 
118    *   0 for a absent card 
119    *   1 for a present card 
120    *   -ENOSYS when not supported(equal to NULL callback) 
121    *   or a negative errno value whensomething bad happened 
122    */  
123   void    (*set_ios)(struct mmc_host*host, struct mmc_ios *ios);  
124   int (*get_ro)(struct mmc_host *host);  
125   int (*get_cd)(struct mmc_host *host);  
126  
127   void    (*enable_sdio_irq)(structmmc_host *host, int enable);  
128  
129   /* optional callback for HC quirks */  
130   void    (*init_card)(struct mmc_host*host, struct mmc_card *card);  
131  
132   int (*start_signal_voltage_switch)(struct mmc_host *host, struct mmc_ios*ios);  
133  
134   /* Check if the card is pulling dat[0:3] low */  
135   int (*card_busy)(struct mmc_host *host);  
136  
137   /* The tuning command opcode value is different for SD and eMMC cards */  
138   int (*execute_tuning)(struct mmc_host *host, u32 opcode);  
139   int (*select_drive_strength)(unsigned int max_dtr, int host_drv, intcard_drv);  
140   void    (*hw_reset)(struct mmc_host*host);  
141   void    (*card_event)(structmmc_host *host);  
142};  


request函数用于处理用户的请求。

set_ios函数用于设置SDI的控制参数，如时钟、总线宽度等等。

get_ro函数用于探测SD卡是否有写保护。

get_cd函数用于探测卡是否已插入插槽。

enable_sdio_irq函数用于启动或禁用SDI中断。

需要注意的是，为什么没有对MMC/SD进行读写的read和write函数呢？这是因为Linux块设备的读写操作是通过request函数完成的。

--------------------------------------------------------------------------
jz4775mmc 驱动

0) 两大招
grep -rn "xxx" ./
find ./ -name "xxx"

1) arch/mips/xburst/soc-4775/common/platform.c

179:    int jz_device_register(struct platform_device *pdev,void *pdata)
		{
			pdev->dev.platform_data = pdata;

			return platform_device_register(pdev);
		}
		
274:#define DEF_MSC(NO)		\
275:	static struct resource jz_msc##NO##_resources[] = {..}
287:    struct platform_device jz_msc##NO##_device = {..}

297:  DEF_MSC(0); 
	  这个宏展开 => static struct resource jz_msc0_resources[] = {..}  and 
			        static struct resource jz_msc0_device = {...}
			   
298:  DEF_MSC(1); // 同DEF_MSC(0)
299:  DEF_MSC(2); // 同DEF_MSC(0)


2) arch/mips/xburst/soc-4775/board/zmm220/zmm220-mmc.c

47:   struct jzmmc_platform_data inand_pdata = {..}
72:   struct jzmmc_platform_data tf_pdata = {..}
96:   struct jzmmc_platform_data tf_pdata = {..}
116:  struct jzmmc_platform_data sdio_pdata = {..}

3) arch/mips/xburst/soc-4775/board/zmm220/zmm220-misc.c:
>>> 以下注册设备
628:	jz_device_register(&jz_msc0_device, &inand_pdata); // MSC0 接的是存储
631:	jz_device_register(&jz_msc1_device, &sdio_pdata);  
634:	jz_device_register(&jz_msc2_device, &tf_pdata);    // 可能是wifi模块
638:	jz_device_register(&jz_msc0_device, &tf_pdata);
641:	jz_device_register(&jz_msc2_device, &sdio_pdata);

4) drivers/mmc/host/jz4775_mmc.c

1864:   static struct platform_driver jzmmc_driver = {..}

1877:   static int __init jzmmc_init(void)
		{
			return platform_driver_probe(&jzmmc_driver, jzmmc_probe);
		}
	
5) drivers/mmc/host/jz4775_mmc.c

1684:
static int __init jzmmc_probe(struct platform_device *pdev)
{
	...
	struct jzmmc_host *host = NULL;
	struct mmc_host *mmc;
	...

	mmc = mmc_alloc_host(sizeof(struct jzmmc_host), &pdev->dev); // 原型在core/host.c函数展开如下
		  {
		  	 /* 建立数据结构 */
			 struct mmc_host *host;
			 /*申请 sizeof(struct mmc_host) + sizeof(struct jzmmc_host) 大小空间
			  *struct mmc_host 
			  *{    ..
			  *		unsigned long  private[0] ____cacheline_aligned; //后面有这个长度为零的数组
			  *}
			  */这样 private 的位置正好是 struct jzmmc_host 的首地址
			 host = kzalloc(sizeof(struct mmc_host) + extra, GFP_KERNEL); 

			/* 建立kobject */
			 host->parent = dev;
			 host->class_dev.parent = dev;
			 host->class_dev.class = &mmc_host_class;
			 device_initialize(&host->class_dev);

			/* 初始化等待队列，工作队列 */
			 init_waitqueue_head(&host->wq);
			 INIT_DELAYED_WORK(&host->detect, mmc_rescan); // 初始化延时工作，指定工作函数
			                                               //注意这里的工作队列的延时时间delay为0，
			                                               //因为系统启动的时候不考虑插拔卡
			                                               //目的在系统初始化的时候就扫描查看是否存在卡
			/* 配置控制器 */
			 host->max_hw_segs = 1;
			 host->max_seg_size = PAGE_CACHE_SIZE;

			 host->max_req_size = PAGE_CACHE_SIZE;
			 host->max_blk_size = 512;
			 host->max_blk_count = PAGE_CACHE_SIZE / 512;

			 return host;	  
		  }
	
	host = mmc_priv(mmc); // host = mmc->private，即指向了struct jzmmc_host 结构
	...
	mmc_set_drvdata(pdev, host); //pdev->dev->p->driver_data = host，保存驱动的数据结构
	
	ret = jzmmc_msc_init(host); // 初始化 msc
	
	ret = jzmmc_gpio_init(host);// 初始化连接的IO口，申请中断等
	
	jzmmc_host_init(host, mmc); 
	{
		struct jzmmc_platform_data *pdata = host->pdata;
		
		mmc->ops = &jzmmc_ops; // !!!!

		...

		host->mmc = mmc;
		
		setup_timer(&host->request_timer, jzmmc_request_timeout,
				(unsigned long)host); // 设置mmc host 的定时器
				
		mmc_add_host(mmc); 
		{
			...
			device_add(&host->class_dev);
			...
 			mmc_start_host(host);
 			{
 				mmc_power_off(host);
				mmc_detect_change(host, 0);
 			}
		}
	}
	
	return 0;
	...
}

6) drivers/mmc/host/jz4775_mmc.c

struct mmc_host是mmc core层与host层的接口，mmc_host.ops是控制host完成用户请求的接口函数集，其类型是struct mmc_host_ops，该结构体定义在include/linux/mmc/host.h文件中。

1392:
static const struct mmc_host_ops jzmmc_ops = {
	.request		= jzmmc_request,
	.set_ios		= jzmmc_set_ios,
	.get_ro			= jzmmc_get_read_only,
	.get_cd			= jzmmc_get_card_detect,
	.enable_sdio_irq	= jzmmc_enable_sdio_irq,
};

request ：用于处理用户的请求。
set_ios ：用于设置SDI的控制参数，如时钟、总线宽度等等。
get_ro  ：用于探测SD卡是否有写保护。
get_cd  ：用于探测卡是否已插入插槽。
enable_sdio_irq ：用于启动或禁用SDI中断。

为什么没有对MMC/SD进行读写的read和write函数呢？这是因为Linux块设备的读写操作是通过request函数完成的。

934:
static void jzmmc_request(struct mmc_host *mmc, struct mmc_request *mrq)
{
	...
	
	jzmmc_command_start(host, host->cmd);  //实现命令的传输
	if (host->data)
		jzmmc_data_start(host, host->data);//实现数据的传输
	if (unlikely(test_and_clear_bit(JZMMC_CARD_NEED_INIT, &host->flags)))
		host->cmdat_def &= ~CMDAT_INIT;
}
======================================================================
/data/misc/bluetooth # cat bt_addr
su
echo 1 > /sys/power/wake_lock 

time busybox wget -P /data ftp://qwwang:123456@192.168.3.11//home/qwwang/test.mp3
======================================================================
gitk filename
git reset --hard 00c18a2d0c9b36aae147ad28e320842b3d7fe3de(哈希值)
kernel/sound/oss$ gitk --all &
kernel/arch/mips/xburst/soc-m200/chip-m200/watch/acrab$ gitk sound.c
kernel/arch/mips/xburst/soc-m200/chip-m200/watch/common$ gitk sound.c
======================================================================
zlm60 编译：
代码获取：
repo init -u ssh://wangqiuwei@192.168.3.11:29418/mirror/linux-x1000/manifest.git

platform/
source tools/build/source.sh
make

development/device/device.mk :
U-BOOT-CONFIG := zlm60_v10_uImage_spi_nand
KERNEL-CONFIG := zlm60_linux_spinand_ubi_defconfig

out/target/product/zlm60/image/

>> 编译 system.ubifs :
cd out/target/product/zlm60  &&
./mkfs.ubifs -d system -e 0x1f000 -c 2048 -m 0x800 -o image/system.ubifs


解决在启动时不接串口会进入uboot命令行的问题，修改uboot如下：
include/configs/zlm60.h: 499 行添加
/*
* UART configuration
*/
#define	UART2_RXD_PORT  GPIO_PC(31)

arch/mips/cpu/xburst/x1000/soc.c: 76 行添加
gpio_enable_pull(GPIO_PC(31));
======================================================================
需要说明的是网卡芯片也有“软硬”之分，特别是对与主板板载(LOM)的网卡芯片来说更是如此，这是怎么回事呢?大家知道，以太网接口可分为协议层和物理层。
　　
　　协议层是由一个叫MAC(Media Access Layer，媒体访问层)控制器的单一模块实现。
　　
　　物理层由两部分组成，即PHY(Physical Layer，物理层)和传输器。
　　
　　常见的网卡芯片都是把MAC和PHY集成在一个芯片中，但目前很多主板的南桥芯片已包含了以太网MAC控制功能，只是未提供物理层接口，因此，需外接PHY芯片以提供以太网的接入通道。这类PHY网络芯片就是俗称的“软网卡芯片”，常见的PHY功能的芯片有RTL8201BL、VT6103等等。
　　
　　“软网卡”一般将网络控制芯片的运算部分交由处理器或南桥芯片处理，以简化线路设计，从而降低成本，但其多少会更多占用系统资源.
======================================================================
4.3/kernel/sound/oss:
grep  -nr "attibute_dac_l_gain"  ./

5.1/kernel-3.10.14/sound/soc/ingenic/icodec$:
grep  -nr "2c"  ./ 
grep  -nr "DLV_REG_GCR_DACL"  ./
gedit icdc_d1.c +472

5.1/kernel-3.10.14/:
grep  -nr "SOC_DOUBLE_R_TLV"  ./include/   | grep define
gedit ./include/sound/soc.h +123
======================================================================
0x00000000-0x00200000 : "NAND BOOT partition"   0    16
0x00200000-0x00500000 : "NAND KERNEL partition" 16   24
0x00500000-0x01900000 : "NAND ROOTFS partition" 40   160
0x01900000-0x08000000 : "NAND YAFFS partition"  200  1024-200

>>>
nerase 0 1024
fconfig 192.168.1.12 jdi.cfg
nprog 0 u-boot-nand.bin
fconfig 192.168.1.12 jdiyaffs.cfg
nprog 512 lconfig-normal.bin
fconfig 192.168.1.12 jdi.cfg
nprog 704 linuxlogo240x400.bin
nprog 1024 uImage_ZEM565-20120201

fconfig 192.168.1.12 jdiyaffs.cfg
nprog 2560 rootfsyaffs220151020
nprog 12800 mtdyaffs2tft300-20151022
======================================================================
error while loading shared libraries: libudev.so.0: cannot open shared object file: No such file or directory

locate udev.so
ln -s /lib/i386-linux-gnu/libudev.so.1 ./libudev.so.0
======================================================================
wiegand driver

device 资源定义和注册:
arch/mips/xburst/soc-x1000/chip-x1000/zlm60/common/board_base.c

driver 注册和实现：
driver/misc/wiegand_in.c
======================================================================	    
dd if=/dev/zero of=/dev/mtdblock5 bs=1024 count=3000
3072000 bytes (2.9MB) copied, 3.737917 seconds, 802.6KB/s

dd if=/dev/zero of=/dev/mtdblock5 bs=1M count=4
4194304 bytes (4.0MB) copied, 3.361232 seconds, 1.2MB/s

dd if=/dev/urandom of=/dev/mtdblock5 bs=1M count=4
4194304 bytes (4.0MB) copied, 6.387169 seconds, 641.3KB/s

dd if=/dev/urandom of=/dev/mtdblock5 bs=1024 count=3000
3072000 bytes (2.9MB) copied, 6.199825 seconds, 483.9KB/s
----------------------------------------------------------------------
dd if=/dev/zero of=/data/tt bs=16k count=6000 conv=fsync
98304000 bytes (93.8MB) copied, 17.804461 seconds, 5.3MB/s

dd if=/dev/zero of=/data/tt bs=16k count=6000 
98304000 bytes (93.8MB) copied, 5.389757 seconds, 17.4MB/s

dd if=/data/tt of=/dev/null bs=16k count=6000
98304000 bytes (93.8MB) copied, 4.672038 seconds, 20.1MB/s
----------------------------------------------------------------------
dd if=/dev/zero of=/data/mtdblock5 bs=16k count=6000 conv=fsync
98304000 bytes (93.8MB) copied, 17.743677 seconds, 5.3MB/s

dd if=/dev/zero of=/data/mtdblock5 bs=16k count=6000
98304000 bytes (93.8MB) copied, 5.501961 seconds, 17.0MB/s
======================================================================
linux sfcnand 驱动：
1) 设备资源

>> arch/mips/xburst/soc-x1000/common/platform.c:786
#ifdef CONFIG_JZ_SFC
static struct resource jz_sfc_resources[] = {
	[0] = {
		.flags = IORESOURCE_MEM, // SFC's registers map base address 0x13440000
		.start = SFC_IOBASE,
		.end = SFC_IOBASE + 0x10000 - 1,
	},
	[1] = {
		.flags = IORESOURCE_IRQ,
		.start = IRQ_SFC, //  SFC's IRQ
	},
	[2] = {
		.start = CONFIG_SFC_SPEED,
		.flags = IORESOURCE_BUS,
	}
};

struct platform_device jz_sfc_device = {
	.name = "jz-sfc",
	.id = 0,
	.resource = jz_sfc_resources,
	.num_resources = ARRAY_SIZE(jz_sfc_resources),
};
#endif

>> arch/mips/xburst/soc-x1000/common/board_base.c:19
struct jz_platform_device
{
	struct platform_device *pdevices;
	void *pdata;
	int size;
};

>> arch/mips/xburst/soc-x1000/common/board_base.c:54
定义 platform 设备资源数组
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE)  \
	{ .pdevices = DEVICE,   \
		.pdata = DATA, .size = SIZE,}

#ifdef	CONFIG_JZ_SFC
	DEF_DEVICE(&jz_sfc_device,&sfc_info_cfg, sizeof(struct jz_sfc_info)),
	展开如下：
	{
		.pdevices = &jz_sfc_device,
		.pdata    = &sfc_info_cfg,
		.size     = sizeof(struct jz_sfc_info),
	},
#endif
		
};

>> arch/mips/xburst/soc-x1000/include/mach/jzssi.h:187
struct jz_sfc_info {
	u8	chnl;				              /* the chanel of SSI controller */
	u16	bus_num;			             /* spi_master.bus_num */
	unsigned is_pllclk:1;			   /* source clock: 1---pllclk;0---exclk */
	unsigned long	board_size;  /* spi_master.num_chipselect */
	u32	 num_chipselect;
	u32	 allow_cs_same;
	void  *board_info;
	u32  board_info_size;
};

>> arch/mips/xburst/soc-x1000/common/spi_bus.c:485
#elif defined(CONFIG_JZ_SFCNAND)
struct jz_sfc_info sfc_info_cfg = {
	.chnl = 0,
	.bus_num = 0,
	.num_chipselect = 1,
	.board_info = &jz_spi_nand_data,
};
#endif

>> arch/mips/xburst/soc-x1000/common/spi_bus.c:210
struct jz_spi_nand_platform_data jz_spi_nand_data = {
	.jz_spi_support = jz_spi_nand_support_table,  // 程序所支持的nand，spi_bus.c:110
	.num_spi_flash	= ARRAY_SIZE(jz_spi_nand_support_table), // 
	.mtd_partition  = jz_mtd_spinand_partition, // nand 的分区情况，spi_bus.c:76
	.num_partitions = ARRAY_SIZE(jz_mtd_spinand_partition),   // 
};

jz_spi_nand_support_table=((struct jz_spi_nand_platform_data *)(flash->pdata->board_info))->jz_spi_support;
>> arch/mips/xburst/soc-x1000/common/board_base.c:281
注册设备资源：
static int __init board_base_init(void)
{
 	。。。
	pdevices_array_size = ARRAY_SIZE(platform_devices_array);
	for(i = 0; i < pdevices_array_size; i++) {
		if(platform_devices_array[i].size)
			platform_device_add_data(platform_devices_array[i].pdevices,
					platform_devices_array[i].pdata, platform_devices_array[i].size);
		platform_device_register(platform_devices_array[i].pdevices);
	}
	。。。
}
		
>> 执行以下函数之后
platform_device_add_data(platform_devices_array[i].pdevices,
	platform_devices_array[i].pdata, platform_devices_array[i].size);		

最终结果：		
platform_devices_array[i].pdevices->dev.platform_data = &sfc_info_cfg。


2) 驱动分析

>> drivers/mtd/nand/jz_sfcnand.c:1166
static int __init jz_sfc_probe(struct platform_device *pdev)
{
	struct jz_sfc_nand *flash; // 非常重要的结构！
	const char *jz_probe_types[] = {"cmdlinepart",NULL};
	struct jz_spi_support *spi_flash; // 存放nand flash 信息，比如：id 、块大小 、页大小 、Busytime等等

	int err = 0,ret = 0;
	struct nand_chip *chip;  // nand 操作的函数指针
	struct mtd_partition *mtd_sfcnand_partition;
	int num_partitions;
	struct jz_spi_nand_platform_data *param;
	int nand_magic= 0;

	chip = kzalloc(sizeof(struct nand_chip),GFP_KERNEL); // 分配 nand _ship 空间
	if(!chip)
		return -ENOMEM;
	
	flash = kzalloc(sizeof(struct jz_sfc_nand), GFP_KERNEL); // 分配 jz_sfc_nand 空间
	if (!flash) {
		kfree(chip);
		return -ENOMEM;
	}
	
	flash->dev = &pdev->dev;  // 保存 platform_device 中的struct device 结构指针
	flash->pdata = pdev->dev.platform_data; // 保存指向备的私有数据结构的指针， = &sfc_info_cfg  
	
	flash->threshold = THRESHOLD; // ？
	ret=sfc_nand_plat_resource_init(flash,pdev);  // 获取设备资源，初始化 jz_sfc_nand 部分成员
	if(ret) // 非0 则sfc_nand_plat_resource_init() 执行过程出错
	{
		....  // 出错处理
	}
	
	flash->chnl= flash->pdata->chnl; //the chanel of SSI controller， 这里是 0
	flash->tx_addr_plus = 0;
	flash->rx_addr_plus = 0;
	flash->use_dma = 0; // 
	err=0;
	
	/* find and map our resources */
	/* SFC controller initializations for SFC */
	jz_sfc_init_setup(flash); //  SFC controller initializations
	platform_set_drvdata(pdev, flash);
	init_completion(&flash->done);   // 初始化 jz_sfc_nand 中的完成量 struct completion done = 0
	spin_lock_init(&flash->lock_rxtx); //初始化 jz_sfc_nand 中的 spinlock_t		lock_rxtx;
	spin_lock_init(&flash->lock_status); // 初始化 jz_sfc_nand 中的 spinlock_t  lock_status
	
	err = request_irq(flash->irq, jz_sfc_irq, 0, pdev->name, flash); // flash->irq 在sfc_nand_plat_resource_init() 获得
	
	flash->column_cmdaddr_bits=24; // 
	
	jz_get_sfcnand_param(&param,flash,&nand_magic); // 获取烧录工具传下的参数
	if(nand_magic==0x6e616e64){   //如果0x6e616e64 则使用烧录工具传下来的一套参数
		(flash->pdata)->board_info = (void *)param;
	}else{
		param=(flash->pdata)->board_info; // 使用驱动定义的参数
	}
	
	mtd_sfcnand_partition=param->mtd_partition; // nand flash 的分区信息
	num_partitions=param->num_partitions;           // nand flash 的分区数量
	
	
	spi_flash = jz_sfc_nand_probe(flash);  // 匹配具体的 nand flash，并返回存放nand flash 信息的结构指针
	
	// 初始化jz_sfc_nand 中的 struct mtd_info mtd
	flash->mtd.name = "sfc_nand";
	flash->mtd.owner = THIS_MODULE;
	flash->mtd.type = MTD_NANDFLASH;
	flash->mtd.flags |= MTD_CAP_NANDFLASH;
	flash->mtd.erasesize = spi_flash->block_size;
	flash->mtd.writesize = spi_flash->page_size;
	flash->mtd.size = spi_flash->size;
	flash->mtd.oobsize = spi_flash->oobsize;
	flash->mtd.writebufsize = flash->mtd.writesize;
	flash->column_cmdaddr_bits = spi_flash->column_cmdaddr_bits;
	flash->tRD = spi_flash->tRD_maxbusy;
	flash->tPROG = spi_flash->tPROG_maxbusy;
	flash->tBERS = spi_flash->tBERS_maxbusy;
	flash->mtd.bitflip_threshold = flash->mtd.ecc_strength = 1;
	
	// 初始化 struct nand_chip chip
	chip->select_chip = NULL;
	chip->badblockbits = 8;
	chip->scan_bbt = nand_default_bbt;
	chip->block_bad = jz_sfcnand_block_bad_check;
	chip->block_markbad = jz_sfc_nandflash_block_markbad;
	//chip->ecc.layout= &gd5f_ecc_layout_128; // for erase ops
	chip->bbt_erase_shift = chip->phys_erase_shift = ffs(flash->mtd.erasesize) - 1;
	if (!(chip->options & NAND_OWN_BUFFERS))
		    chip->buffers = kmalloc(sizeof(*chip->buffers), GFP_KERNEL);

	/* Set the bad block position */
	if (flash->mtd.writesize > 512 || (chip->options & NAND_BUSWIDTH_16))
	chip->badblockpos = NAND_LARGE_BADBLOCK_POS;
	else
		    chip->badblockpos = NAND_SMALL_BADBLOCK_POS;
		    
	flash->mtd.priv = chip; //  初始化mtd 的私有数据指针

	flash->mtd._erase = jz_sfcnand_erase;
	flash->mtd._read = jz_sfcnand_read;
	flash->mtd._write = jz_sfcnand_write;
	flash->mtd._read_oob = jz_sfcnand_read_oob;
	flash->mtd._write_oob = jz_sfcnand_write_oob;
	flash->mtd._block_isbad = jz_sfcnand_block_isbab;
	flash->mtd._block_markbad = jz_sfcnand_block_markbad;
	
	chip->scan_bbt(&flash->mtd);  // ？
	// 注册mtd 设备
	ret = mtd_device_parse_register(&flash->mtd,jz_probe_types,NULL, mtd_sfcnand_partition, num_partitions);
	if (ret) {
		kfree(flash);
		return -ENODEV;
	}
}

x-loader sfcnand 驱动分析：
#define  SFC_SEND_COMMAND(sfc, a, b, c, d, e, f, g)   do{                       \
        ((struct jz_sfc *)sfc)->cmd = a;                                        \
        ((struct jz_sfc *)sfc)->len = b;                                        \
        ((struct jz_sfc *)sfc)->addr = c;                                       \
        ((struct jz_sfc *)sfc)->addr_len = d;                                   \
        ((struct jz_sfc *)sfc)->addr_plus = 0;                                  \
        ((struct jz_sfc *)sfc)->dummy_byte = e;                                 \
        ((struct jz_sfc *)sfc)->daten = f;                                      \
        SFC_MODE_GENERATE(sfc, a);                                              \
        sfc_send_cmd(sfc, g);                                                   \
} while(0)


git checkout --track ing/sz-master
======================================================================
uboot 的 spl（second program loader）
>> arch/mips/cpu/xburst/x1000/start.S：172
	j	board_init_f // 跳到board_init_f 函数，C代码

>> arch/mips/cpu/xburst/x1000/soc.c ：58
void board_init_f(ulong dummy)
{
	....
	gpio_init();
	enable_uart_clk();
	timer_init();
#ifndef CONFIG_FPGA
#ifdef CONFIG_SPL_CORE_VOLTAGE
	debug("Set core voltage:%dmv\n", CONFIG_SPL_CORE_VOLTAGE);
	spl_regulator_set_voltage(REGULATOR_CORE, CONFIG_SPL_CORE_VOLTAGE);
#endif
#ifdef CONFIG_SPL_MEM_VOLTAGE
	debug("Set mem voltage:%dmv\n", CONFIG_SPL_MEM_VOLTAGE);
	spl_regulator_set_voltage(REGULATOR_MEM, CONFIG_SPL_MEM_VOLTAGE);
#endif
#endif

	clk_prepare();
	pll_init(); // 锁相环
	clk_init(); // 时钟
	sdram_init(); // 内存
	board_init_r(NULL, 0); // 调用board_init_r
}

>> common/spl/spl.c：149
void board_init_r(gd_t *dummy1, ulong dummy2)
{	// 这个函数主要判断是从 nand、mmc、onenand、nor等设备加载uboot代码到初始化好的内存中
	....
	switch (boot_device) {
	             ....
	#ifdef CONFIG_SPL_SPI_NAND
	case BOOT_DEVICE_SPI_NAND:
		spl_spi_nand_load_image();
		break;
	#endif
	#ifdef CONFIG_SPL_SFC_NOR
	case BOOT_DEVICE_SFC_NOR:
		spl_sfc_nor_load_image();
		break;
	#endif
	#ifdef CONFIG_SPL_SFC_NAND
	case BOOT_DEVICE_SFC_NAND:
		spl_sfc_nand_load_image();
		break;
	#endif
		.....
	}
	
	jump_to_image_no_args(&spl_image);
}

mips-linux-gnu-objcopy --remove-section=.dynsym --gap-fill=0xff --pad-to=16384 \
			-I binary -O binary spl/u-boot-spl.bin spl/u-boot-spl-pad.bin
选项说明：
--remove-section=.dynsym：从输出文件中去除掉由sectionname指定的section，可以多次指定，不当会导致输出文件不可用
--gap-fill=0xff：在section之间的空隙中填充0xff	
--pad-to=16384	
-I binary：指定输入的文件，这里是 spl/u-boot-spl.bin
-O binary：指定输出的文件，这里是 spl/u-boot-spl-pad.bin

// 连接spl/u-boot-spl-pad.bin和u-boot.bin，生存最终烧录文件 u-boot-with-spl.bin
cat spl/u-boot-spl-pad.bin u-boot.bin > u-boot-with-spl.bin 
rm spl/u-boot-spl-pad.bin
======================================================================
网卡在物理上具有载波侦听的功能，当网络连接完成或者网络链接断开时，网卡芯片硬件会自动设置寄存器标志位来标识。

如网线链接断开的时候，会将LinkSts清位；重新链接网线，则硬件自动将此位置位。

这样，在网卡驱动中读写该位信息就可一判断网络是否链接通路。

网卡驱动程序通过netif_carrier_on/netif_carrier_off/netif_carrier_ok来和内核网络子系统传递信息。

1】netif_carrier_on【作用】告诉内核子系统网络链接完整。

2】netif_carrier_off【作用】告诉内核子系统网络断开。

3】netif_carrier_ok【作用】查询网络断开还是链接。

以上函数主要是改变net_device dev的state状态来告知内核链路状态的变化。
======================================================================
ubuntu下安装卸载 VMWare Player / WorkStation （.bundle文件）

比如下载下来的VMware Player文件名为
VMware-Player-3.1.0-261024.i386.bundle

在终端中转到文件放置的目录，执行
sudo sh VMware-Player-3.1.0-261024.i386.bundle

安装就开始了。

卸载方法：
在终端中输入
sudo vmware-installer -u vmware-player

就能卸载

卸载Workstation的方法相同，输入
sudo vmware-installer -u vmware-workstation
======================================================================
UBIFS 出错：
[    3.817188] VFS: Mounted root (ubifs filesystem) on device 0:9.
[    3.824409] Freeing unused kernel memory: 220K (80539000 - 80570000)
Starting mount /data parttion
[    3.944590] UBIFS: background thread "ubifs_bgt1_0" started, PID 53
[    4.009158] UBIFS error (pid 52): ubifs_check_node: bad CRC: calculated 0xe94bab05, read 0x869acbe8
[    4.018555] UBIFS error (pid 52): ubifs_check_node: bad node at LEB 253:82976

网上的一些见解：
UBIFS本身的机制导致它会出现这种错误，可以到http://www.linux-mtd.infradead.org/faq/ubifs.html，详细了解这个文件系统的特性和它的不足之处。
以下是我对你问题的一点理解。
1.你的根文件系统是UBIFS，可写读的。
2.在你运行Linux系统时，系统的一些服务，如日志等，可能会频繁的读写你的存储器。UBIFS对掉电的容忍性我觉得是比较差的，在异常掉电或重启后，下次重启后可能导致到UBIFS文件系统记录节点CRC和实际计算的不一致，导致你的根文件系统挂载不了。
所以我有了以下直观认识：
1.UBIFS挂载速度快，存储器寿命高。
2.UBIFS对异常掉电的容忍性差，容易出现CRC错误。

所以我以下建议：
1.将你的根文件系统设置为只读，另外建立一个可读写扩展文件系统系统分区，用于其他用途。
2.如果你坚持保留根文件系统分区为可读写，则每次通过linux命令执行关机操作，尽量避免直接切断电源。
3.或者向freescale官方咨询答案，到时候大家一起讨论共享。

针对你说的不能烧写和扩展文件系统，我有以下建议给你。
1.修改你的内核NAND flash分区，增加一个扩展文件系统分区。
2.然后通过ubifs文件系统工具将你的文件打包成ubifs固有的格式（为什么？）。
3.因为上面已经将文件打包成ubifs格式了，所以直接在uboot或类似uboot的引导程序中通过nand的命令如 nand erase、nand write等将打包后的文件直接写入对应的扩展分区中。
4.修改根文件系统，在初始化脚本中mount该扩展文件系统到根文件系统下即可

以上的正确性需要再验证
======================================================================
//没bug的分支
git checkout remotes/ingenic/ingenic-master-3.10.14
gitk pm_p0.c //相关文件

/work/m200/5.1/kernel-3.10.14/drivers/char/voice_wakeup
voice_wakeup_firmware.hex  复制出来覆盖 Indroid5.1-master 分支的

//要测试的分支
git checkout remotes/ingenic/Indroid5.1-master


//跟踪 4.3 的 remotes/ing/ingenic-master 分支关于深休的修改
remotes/ing/ingenic-master
======================================================================
MII_BMSR
phy_write(phy, MII_BMCR, ctl);
val = phy_read(phy, MII_BMCR);

======================================================================
测试Audio:
1) 播放，可查看音频文件格式信息：
aplay att.wav

2) 转化音频格式：
mpg123
mpg123 -r 8000 --8bit -m -n 50  -w road_8Khz_single_mono.wav road.mp3 
mpg123 -r 22050 --8bit -k 1000 -n 2000 -w 22Khz.wav paomo.mp3

3) 重要的概念：
通道数(channel)：该参数为1表示单声道，2则是立体声。
桢(frame)：桢记录了一个声音单元，一个时间点上所抓取的样本，其长度为样本长度与通道数的乘积。
采样率(rate)：每秒钟采样次数，该次数是针对桢而言。
周期(period)：音频设备一次处理所需要的桢数，对于音频设备的数据访问以及音频数据的存储，都是以此为单位。
======================================================================
efuse:

ret = jz_efuse_write(efuse->wr_info->seg_id, efuse->wr_info->data_length, efuse->wr_info->buf);


unsigned int  buf[32] = {0,1,2,3,4,5};
jz_efuse_write(USER_ID, 32, buf);
printk("===========================\n");
jz_efuse_read(USER_ID, 32, buf);
printk("PROTECT_SEG: byte1 = %u, byte2 = %u byte3 = %u, byte4 = %u\n", buf[0], buf[1],buf[2], buf[3]);
======================================================================
halley2
input: gpio-keys as /devices/platform/gpio-keys/input/input1
-----------------------------------------------------------------------------------------------
如何查看 /dev/input/eventx 对应的相关设备信息：
cat /proc/bus/input/devices
I: Bus=0019 Vendor=0000 Product=0000 Version=0000
N: Name="matrix-keypad"
P: Phys=
S: Sysfs=/devices/platform/matrix-keypad.0/input/input0
U: Uniq=
H: Handlers=event0 
B: PROP=0
B: EV=100013
B: KEY=40000800 1480 0 0 ffc
B: MSC=10

I: Bus=0019 Vendor=0001 Product=0001 Version=0100
N: Name="gpio-keys"
P: Phys=gpio-keys/input0
S: Sysfs=/devices/platform/gpio-keys/input/input1
U: Uniq=
H: Handlers=event1 
B: PROP=0
B: EV=3
B: KEY=200 0 0 0

在上面的H:中可以看到对应的eventx
-----------------------------------------------------------------------------------------------
/etc/mdev.conf

mdev.conf写的不对

加入下面的就可以：
# Move input devices to input directory
event.*	0:0	0660	@(mkdir -p input&&mv $MDEV input)
mice	0:0	0660	@(mkdir -p input&&mv $MDEV input)
mouse.*	0:0	0660	@(mkdir -p input&&mv $MDEV input)

关于 halley2 找不到/dev/input/event文件的解决方法，修改kernel的 halley2_nor 的配置文件，过程如下：
1) make halley2_nor_v10_linux_defconfig
2) make menuconfig
       A) 使能 Event interface
       Device Drivers  ---->
            Input device support  ---->
                    <*> Event interface

        B) 去掉支持 ext4 文件系统
        File systems  --->
                < >The Extended 4 (ext4) support
        说明： 去掉支持 ext4 文件系统的原因使编译的 uImage 小于3M，否则大于3M kernel 无法启动，因为uboot 只加载3M大小到内存。
3) make uImage
4) 烧录启动即可， ls /dev :

arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/keyboard_gpio.c
arch/mips/xburst/soc-x1000/chip-x1000/halley2/halley2_v10/board.h


sudo apt-get install automake autoconf m4 libtool gettext
sudo apt-get install libncurses5-dev libslang2-dev libselinux1-dev debhelper lsb-release pkg-config po-debconf

objdump -t path-to-library.a | grep -e __isoc99_sscanf

======================================================================
halley 2 摄像头测试：

development/testsuit/camera_process/jpg_api
libjpeg.so
out/target/product/halley2/system/lib

platform/development/testsuit/grab_source/jpeg


./cimutils -I 0 -P -v -l -w 640 -h 480
./cimutils -I 0 -P -w 640 -h 480
./cimutils -I 0 -C -v -x 640 -y 480

======================================================================
halley2 蓝牙：
启动： bt_enable
hciconfig -a
hcitool scan
obex_test -b 30:45:1C:FC:03:11 1
======================================================================
linux下查看so文件的函数列表 :

方法一：
nm查看共享库so文件中导出函数列表

查看so文件中的导出函数表；
nm -D xxx.so
列出所有导出的函数，包括 xxx.so 静态链接的库中的那些导出函数。

方法二：
objdump -tT xxx.so
======================================================================
halley2_43438_cramfs_config: unconfig mozart_prepare product_canna_v2.0_ap6212_config \
		wifi_ap6212_config bt_ap6212_config bt_hci_dev_ttyS0_config \
		lcd_disable_config webrtc_aec_disable_config \
		audio_dev_x1000_config dmr_enable_config dms_disable_config \
		airplay_enable_config localplayer_enable_config song_supplyer_ximalaya_config \
		mplayer_float_config vr_speech_config vr_wakeup_key_shortpress_config \
		lapsule_enable_config adb_enable_config \
		rootfs_cramfs_config usrdata_jffs2_config flash_spi_gd25q128c_config
	@echo "Config complete sdk with cramfs for halley2 ap6212 board"
CONFIG_JZ_HIBERNATE

/home/qwwang/work/audio/org.x1000/mozart/output/host/usr/sbin/mkfs.cramfs /home/qwwang/work/audio/org.x1000/mozart/output/fs/appfs /home/qwwang/work/audio/org.x1000/mozart/output/target/appfs.cramfs  >> /home/qwwang/work/audio/org.x1000/mozart/output/target/fakeroot.fs
======================================================================
audio_recorder.cpp
webrtc_watch_aec.cpp

hardware/ingenic/audio/audio-alsa$ mm -B

out/target/product/aw808/system/lib/hw/audio.primary.watch.so

root@watch:/ # ps | grep me
media     118   1     69212  7284  ffffffff 76e82674 S /system/bin/mediaserver

logcat
logcat -v time 
======================================================================
adb shell 出现如下错误：
error: insufficient permissions for device

解决方法;
kill -9 <adb 进程id>
sudo adb shell
======================================================================
HUAWEI MU709s-6:
hardware/mobiled/src/modem/configure.cpp
kernel/drivers/usb/serial/option.c

编译：mobiled
cd hardware/mobiled
mm -B

代码提交：
git push ing HEAD:refs/for/分支

======================================================================
halley2 mozart:
源码获取：
repo init -u ssh://username@192.168.3.11:29418/mirror/sdk-x1000-v1.6/linux/manifest -b sz-master-mozart


 >> 重启adb
./usr/fs/etc/init.d/S99adbd.sh start


1. 打开/关闭无线网卡电源
iwconfig wlan0 txpower on
iwconfig wlan0 txpower off && ifconfig wlan0 down

linux以命令行下配置连接wlan无线网卡：
工作的大体思路如下：
用iwconfig开启无线网卡的电源，并查找区域内的无线网络
连接到相应的无线网络
通过ifconfig启用无线网卡，并获取IP（如果使用DHCP的话）
注意：
假设无线被识别为wlan0，如果您的网卡没有被识别为wlan0，可以在操作时做相应的修改。
具体过程
1. 打开无线网卡电源
iwconfig wlan0 txpower on
2. 列出区域内的无线网络
iwlist wlan0 scan
3. 假设要连接到网络MyHome（即essid为MyHome的网络），那么输入命令
iwconfig wlan0 essid "MyHome"
如果网络是加密的，密码是<PASSWORD>，那么就输入命令
iwconfig wlan0 essid "MyHome" key 0123-4567-89
4. 如果正常的话，输入
iwconfig wlan0
就可以看到连接正常的各项参数了。 5. 启用无线网卡
ifconfig wlan0 up
6. 如果是用DHCP获取IP的，那么用dhclient或dhcpcd获取ip
dhclient wlan0
或
dhcpcd wlan0
7. 现在无线网卡应该可以正常使用了
注意：一定要把NetworkManager服务停掉
======================================================================
X1000 SLCD Controller
SLCD Pins Description:
SLCD_DC: Command/Data Select Signal.     I/O: Output
SLCD_WR: Data Sample Signal.             I/O: Output
SLCD_RD: Smart LCD read signal.          I/O: Output
SLCD_CE: Smart LCD chip select.          I/O: Output
SLCD_TE: Smart LCD tearing effect signal I/O: Input
SLCD_DAT: The data of SLCD               I/O: Output

-----------------------------------------------
>>>> lcd-truly_tftp240240 屏:
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/lcd/lcd-truly_tftp240240_2_e.c:

struct lcd_platform_data truly_tft240240_pdata = {
	.reset    = truly_tft240240_power_reset,
	.power_on = truly_tft240240_power_on,
};

/* LCD Panel Device */
struct platform_device truly_tft240240_device = {
	.name		= "truly_tft240240_slcd",
	.dev		= {
		.platform_data	= &truly_tft240240_pdata,
	},
};

arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:

static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE)  \
	{ .pdevices = DEVICE,   \
		.pdata = DATA, .size = SIZE,}	

		。
		。
#ifdef CONFIG_LCD_TRULY_TFT240240_2_E
	DEF_DEVICE(&truly_tft240240_device, 0, 0),
#endif
		。
		。
}

>>>> 注册设备：
static int __init board_base_init(void)
{
	int pdevices_array_size, i;

	pdevices_array_size = ARRAY_SIZE(platform_devices_array);
	for(i = 0; i < pdevices_array_size; i++) {
		if(platform_devices_array[i].size)
			platform_device_add_data(platform_devices_array[i].pdevices,
					platform_devices_array[i].pdata, platform_devices_array[i].size);
		platform_device_register(platform_devices_array[i].pdevices);
	}
	。
	。
	return 0;
}

>>>> 对应的驱动：
drivers/video/backlight/truly_tft240240_2_e.c:
static struct platform_driver truly_tft240240_driver = {
	.driver		= {
		.name	= "truly_tft240240_slcd",
		.owner	= THIS_MODULE,
	},
	.probe		= truly_tft240240_probe,
	.remove		= truly_tft240240_remove,
	.suspend	= truly_tft240240_suspend,
	.resume		= truly_tft240240_resume,
};

static int __init truly_tft240240_init(void)
{
	return platform_driver_register(&truly_tft240240_driver);
}

-----------------------------------------------
>>>>>>> fb

arch/mips/xburst/soc-x1000/common/platform.c:
#ifdef CONFIG_FB_JZ_V13
static u64 jz_fb_dmamask = ~(u64) 0;
static struct resource jz_fb_resources[] = {
	[0] = {
		.start = LCDC_IOBASE,
		.end = LCDC_IOBASE + 0x1800 - 1,
		.flags = IORESOURCE_MEM,
	},
	[1] = {
		.start = IRQ_LCD,
		.end = IRQ_LCD,
		.flags = IORESOURCE_IRQ,
	},
};

struct platform_device jz_fb_device = {
	.name = "jz-fb",
	.id = -1,
	.dev = {
		.dma_mask = &jz_fb_dmamask,
		.coherent_dma_mask = 0xffffffff,
	},
	.num_resources = ARRAY_SIZE(jz_fb_resources),
	.resource = jz_fb_resources,
};
#endif

arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE)  \
	{ .pdevices = DEVICE,   \
		.pdata = DATA, .size = SIZE,}	

		。
		。
#ifdef CONFIG_FB_JZ_V13
	DEF_DEVICE(&jz_fb_device, &jzfb_pdata, sizeof(struct jzfb_platform_data)),
#endif
		。
		。
}

>>>> 设备注册过程同上

>>>> 对应的 fb 驱动：
drivers/video/jz_fb_v13/jz_fb.c:
	。。。。
	
static struct platform_driver jzfb_driver = {
	.probe = jzfb_probe,
	.remove = jzfb_remove,
	.shutdown = jzfb_shutdown,
	.driver = {
		   .name = "jz-fb",
#ifdef CONFIG_PM
		   .pm = &jzfb_pm_ops,
#endif

		   },
};

static int __init jzfb_init(void)
{
	platform_driver_register(&jzfb_driver);
	return 0;
}
	。。。。

-----------------------------------------------
>>>>>>>>  backlight
arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/lcd/lcd-truly_tftp240240_2_e.c:
static struct platform_pwm_backlight_data backlight_data = {
	.pwm_id		= 0,
	.max_brightness	= 255,
	.dft_brightness	= 80,
	.pwm_period_ns	= 30000,
	.init		= backlight_init,
	.exit		= backlight_exit,
	.notify		= backlight_notify,
};

struct platform_device backlight_device = {
	.name		= "pwm-backlight",
	.dev		= {
		.platform_data	= &backlight_data,
	},
};

arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE)  \
	{ .pdevices = DEVICE,   \
		.pdata = DATA, .size = SIZE,}	

		。
		。
#ifdef CONFIG_BACKLIGHT_PWM
	DEF_DEVICE(&backlight_device, 0, 0),
#endif
		。
		。
}

>>>> 设备注册过程同上

>>>> 对应的 backlight 驱动：
drivers/video/backlight/pwm_bl.c:
static struct platform_driver pwm_backlight_driver = {
	.driver		= {
		.name	= "pwm-backlight",
		.owner	= THIS_MODULE,
	},
	.probe		= pwm_backlight_probe,
	.remove		= pwm_backlight_remove,
	.suspend	= pwm_backlight_suspend,
	.resume		= pwm_backlight_resume,
};

static int __init pwm_backlight_init(void)
{
	return platform_driver_register(&pwm_backlight_driver);
}

======================================================================
LED 子系统

LED GPIO 的定义：
arch/mips/xburst/soc-x1000/chip-x1000/canna/common/misc.c：
static struct gpio_led gpio_leds[] = {
	{
		.name = "led-bt",   //名称，将在/sys/class/leds/目录下出现，代表一个LED
		.gpio = GPIO_PA(8), //LED 对应的GPIO
		.active_low = true, //是否对.default_state状态进行翻转，比如GPIO输出0.LED亮，而LEDS_GPIO_DEFSTATE_OFF正好等于0
		.default_state = LEDS_GPIO_DEFSTATE_OFF,
		.retain_state_suspended = true,
		.default_trigger = NULL, //触发模式：timer、ide-disk、heartbeat、backlight、gpio、default-on等
	},	
}

static struct gpio_led_platform_data gpio_led_info = {
        .leds = gpio_leds,
        .num_leds = ARRAY_SIZE(gpio_leds),
};

struct platform_device jz_leds_gpio = {
        .name = "leds-gpio",
        .id = -1,
        .dev = {
                .platform_data  = &gpio_led_info,
        },
};

struct gpio_led_platform_data {
	int 		num_leds;
	const struct gpio_led *leds;

#define GPIO_LED_NO_BLINK_LOW	0	/* No blink GPIO state low */
#define GPIO_LED_NO_BLINK_HIGH	1	/* No blink GPIO state high */
#define GPIO_LED_BLINK		2	/* Please, blink */
	int		(*gpio_blink_set)(unsigned gpio, int state,
					unsigned long *delay_on,
					unsigned long *delay_off);
};
----------------------------------------
LED 子系统的驱动：
drivers/leds/

主要文件:
# LED Core
obj-$(CONFIG_NEW_LEDS)                   +=led-core.o
obj-$(CONFIG_LEDS_CLASS)                 += led-class.o
obj-$(CONFIG_LEDS_TRIGGERS)              +=led-triggers.o
   
# LED PlatformDrivers  
obj-$(CONFIG_LEDS_GPIO)                  += leds-gpio.o
   
# LED Triggers
obj-$(CONFIG_LEDS_TRIGGER_TIMER)         +=ledtrig-timer.o
obj-$(CONFIG_LEDS_TRIGGER_IDE_DISK)      +=ledtrig-ide-disk.o
obj-$(CONFIG_LEDS_TRIGGER_HEARTBEAT)     +=ledtrig-heartbeat.o
obj-$(CONFIG_LEDS_TRIGGER_BACKLIGHT)     +=ledtrig-backlight.o
obj-$(CONFIG_LEDS_TRIGGER_GPIO)          +=ledtrig-gpio.o
obj-$(CONFIG_LEDS_TRIGGER_DEFAULT_ON)    += ledtrig-default-on.o


drivers/leds/leds-gpio.c:
static struct platform_driver gpio_led_driver = {
	.probe		= gpio_led_probe,
	.remove		= __devexit_p(gpio_led_remove),
	.driver		= {
		.name	= "leds-gpio",
		.owner	= THIS_MODULE,
		.of_match_table = of_gpio_leds_match,
	},
};

static int __init gpio_led_init(void)
{
	return platform_driver_register(&gpio_led_driver);
}

probe 函数主要流程：
static int __devinit gpio_led_probe(struct platform_device *pdev)
{
	struct gpio_led_platform_data *pdata = pdev->dev.platform_data;
	struct gpio_leds_priv *priv;
	int i, ret = 0;

	if (pdata && pdata->num_leds) {
		priv = kzalloc(sizeof_gpio_leds_priv(pdata->num_leds),
				GFP_KERNEL);
		if (!priv)
			return -ENOMEM;

		priv->num_leds = pdata->num_leds;
		for (i = 0; i < priv->num_leds; i++) {
			//create_gpio_led，注册GPIO LED
			ret = create_gpio_led(&pdata->leds[i],
					      &priv->leds[i],
					      &pdev->dev, pdata->gpio_blink_set);
			if (ret < 0) {
				/* On failure: unwind the led creations */
				for (i = i - 1; i >= 0; i--)
					delete_gpio_led(&priv->leds[i]);
				kfree(priv);
				return ret;
			}
		}
	} else {
		priv = gpio_leds_create_of(pdev);
		if (!priv)
			return -ENODEV;
	}

	platform_set_drvdata(pdev, priv);

}

create_gpio_led 函数主要流程：
static int __devinit create_gpio_led(const struct gpio_led *template,
	struct gpio_led_data *led_dat, struct device *parent,
	int (*blink_set)(unsigned, int, unsigned long *, unsigned long *))
{
	int ret, state;

	led_dat->gpio = -1;

	/* skip leds that aren't available */
	if (!gpio_is_valid(template->gpio)) {
		printk(KERN_INFO "Skipping unavailable LED gpio %d (%s)\n",
				template->gpio, template->name);
		return 0;
	}

	ret = gpio_request(template->gpio, template->name);
	if (ret < 0)
		return ret;

	// 初始化每个LED对应的 struct gpio_led_data 结构
	led_dat->cdev.name = template->name;
	led_dat->cdev.default_trigger = template->default_trigger;
	led_dat->gpio = template->gpio;
	led_dat->can_sleep = gpio_cansleep(template->gpio);
	led_dat->active_low = template->active_low;
	led_dat->blinking = 0;

	if (blink_set) { //blink_set = NULL, if语句不会执行
		led_dat->platform_gpio_blink_set = blink_set;
		led_dat->cdev.blink_set = gpio_blink_set;
	}
	
	led_dat->cdev.brightness_set = gpio_led_set; // 设定 LED 
	if (template->default_state == LEDS_GPIO_DEFSTATE_KEEP)
		state = !!gpio_get_value(led_dat->gpio) ^ led_dat->active_low;
	else
		state = (template->default_state == LEDS_GPIO_DEFSTATE_ON);

	led_dat->cdev.brightness = state ? LED_FULL : LED_OFF;
	if (!template->retain_state_suspended)
		led_dat->cdev.flags |= LED_CORE_SUSPENDRESUME;

	ret = gpio_direction_output(led_dat->gpio, led_dat->active_low ^ state); //设置GPIO LED 初始状态
	if (ret < 0)
		goto err;
		
	INIT_WORK(&led_dat->work, gpio_led_work);

	ret = led_classdev_register(parent, &led_dat->cdev); //创建classdev设备，也即leds类中实例化一个对象
	if (ret < 0)
		goto err;

	return 0;
err:
	gpio_free(led_dat->gpio);
	return ret;
}

led_classdev_register 函数主要流程：
1.加到leds_list链表中，
2.初始化blinktimer，
3.指定blink_timer的function和data，
4.设置trigger，
5.然后一个新的led设备就注册好了，就可以使用了。
int led_classdev_register(struct device *parent, struct led_classdev *led_cdev)
{
	led_cdev->dev = device_create(leds_class, parent, 0, led_cdev,
				      "%s", led_cdev->name);
	if (IS_ERR(led_cdev->dev))
		return PTR_ERR(led_cdev->dev);

#ifdef CONFIG_LEDS_TRIGGERS
	init_rwsem(&led_cdev->trigger_lock);
#endif
	/* add to the list of leds */
	down_write(&leds_list_lock);
	list_add_tail(&led_cdev->node, &leds_list);
	up_write(&leds_list_lock);

	if (!led_cdev->max_brightness)
		led_cdev->max_brightness = LED_FULL;

	led_update_brightness(led_cdev);

	init_timer(&led_cdev->blink_timer);
	led_cdev->blink_timer.function = led_timer_function;
	led_cdev->blink_timer.data = (unsigned long)led_cdev;

#ifdef CONFIG_LEDS_TRIGGERS
	led_trigger_set_default(led_cdev);
#endif

	printk(KERN_DEBUG "Registered led device: %s\n",
			led_cdev->name);

	return 0;
}

/*
 * PWM LED driver data - see drivers/leds/leds-pwm.c
 */
#ifndef __LINUX_LEDS_PWM_H
#define __LINUX_LEDS_PWM_H

struct led_pwm {
	const char	*name;
	const char	*default_trigger;
	unsigned	pwm_id;
	u8 		active_low;
	unsigned 	max_brightness;
	unsigned	pwm_period_ns;
};

struct led_pwm_platform_data {
	int			num_leds;
	struct led_pwm	*leds;
};

#endif
======================================================================
wifi 网络测试方法:
1. 使能wlan0
2. 增加网络热点
在文件中 增加新的内容/data/misc/wifi/wpa_supplicant.conf 如下
ctrl_interface=/data/misc/wifi/sockets
update_config=1
device_name=aw808
manufacturer=Ingenic
model_name=WATCH-RDK
model_number=WATCH-RDK
serial_number=
device_type=10-0050F204-5
config_methods=physical_display virtual_push_button
external_sim=1
#----------------------以下是新增加的热点密码及优先级 ----------------------
network={
    ssid="sw1"
    psk="#sz@sw1^"
    key_mgmt=WPA-PSK
    priority=27
}
3. reboot 或手动重启wpa_supplicant 服务
4. busybox ifconfig  即可看到分配的IP地址 

wpa_supplicant -Dnl80211 -iwlan0 -cwpa_supplicant.conf
udhcpc -i wlan0
======================================================================
ack的解决思路是：1)缺省就搜索子目录；2)对常用编程语言，ack里面写好了对应哪些文件扩展名，比如perl是.pl, .pm和.pod，那么你只要指定按perl这个语言搜就行了。于是上述命令可以简化为:
ack --perl pattern

如果只想排除perl类型的文件，则可以用:
ack --noperl pattern

你可以--type-add TYPE=.ext[,ext2[,...]]或者--type-set TYPE=.ext[,ext2[,...]]来临时定制文件类型（如果要长期使用，可以修改~/.ackrc。

同时，也许你已经注意到了，其实ack也可以用来替代那一大堆find命令，用来搜索指定类型的文件本身(而不是文件内容)，ack当然也支持，只需要添加-f 选项就行了:
ack -f --perl
----------------------------------------------------------------------
glark

与ack关注点不一样的是，glark跟关注文件里面的内容，举两个例子说一下:

% glark --and=2 printStackTrace catch *.java
这表示在java代码中搜索printStackTrace和catch这两个词，要求这两个词出现的位置相差不超过2行；

 
% glark --or catch throw *.java
这表示要求搜出包含catch或者throw的行；

% glark --and=5 cout --or double float *.c
这表示要求某行包含double或者float，然后在其上下5行内有cout出现。
======================================================================
#define PXPIN		0x00   /* PIN Level Register */
#define PXINT		0x10   /* Port Interrupt Register */
#define PXINTS		0x14   /* Port Interrupt Set Register */
#define PXINTC		0x18   /* Port Interrupt Clear Register */
#define PXMSK		0x20   /* Port Interrupt Mask Reg */
#define PXMSKS		0x24   /* Port Interrupt Mask Set Reg */
#define PXMSKC		0x28   /* Port Interrupt Mask Clear Reg */
#define PXPAT1		0x30   /* Port Pattern 1 Set Reg. */
#define PXPAT1S		0x34   /* Port Pattern 1 Set Reg. */
#define PXPAT1C		0x38   /* Port Pattern 1 Clear Reg. */
#define PXPAT0		0x40   /* Port Pattern 0 Register */
#define PXPAT0S		0x44   /* Port Pattern 0 Set Register */
#define PXPAT0C		0x48   /* Port Pattern 0 Clear Register */
#define PXFLG		0x50   /* Port Flag Register */
#define PXFLGC		0x58   /* Port Flag clear Register */
#define PXOENS		0x64   /* Port Output Disable Set Register */
#define PXOENC		0x68   /* Port Output Disable Clear Register */
#define PXPEN		0x70   /* Port Pull Disable Register */
#define PXPENS		0x74   /* Port Pull Disable Set Register */
#define PXPENC		0x78   /* Port Pull Disable Clear Register */
#define PXDSS		0x84   /* Port Drive Strength set Register */
#define PXDSC		0x88   /* Port Drive Strength clear Register */
#define PZGID2LD	0xF0   /* GPIOZ Group ID to load */

#define GPIO_BASE   0xb0010000

#define GPIO_PXPIN(n)   (GPIO_BASE + (PXPIN + (n)*0x100)) /* PIN Level Register */
#define GPIO_PXINT(n)   (GPIO_BASE + (PXINT + (n)*0x100)) /* Port Interrupt Register */
#define GPIO_PXINTS(n)  (GPIO_BASE + (PXINTS + (n)*0x100)) /* Port Interrupt Set Register */
#define GPIO_PXINTC(n)  (GPIO_BASE + (PXINTC + (n)*0x100)) /* Port Interrupt Clear Register */
#define GPIO_PXMSK(n)   (GPIO_BASE + (PXMSK + (n)*0x100)) /* Port Interrupt Mask Register */
#define GPIO_PXMSKS(n)  (GPIO_BASE + (PXMSKS + (n)*0x100)) /* Port Interrupt Mask Set Reg */
#define GPIO_PXMSKC(n)  (GPIO_BASE + (PXMSKC + (n)*0x100)) /* Port Interrupt Mask Clear Reg */
#define GPIO_PXPAT1(n)  (GPIO_BASE + (PXPAT1 + (n)*0x100)) /* Port Pattern 1 Register */
#define GPIO_PXPAT1S(n) (GPIO_BASE + (PXPAT1S + (n)*0x100)) /* Port Pattern 1 Set Reg. */
#define GPIO_PXPAT1C(n) (GPIO_BASE + (PXPAT1C + (n)*0x100)) /* Port Pattern 1 Clear Reg. */
#define GPIO_PXPAT0(n)  (GPIO_BASE + (PXPAT0 + (n)*0x100)) /* Port Pattern 0 Register */
#define GPIO_PXPAT0S(n) (GPIO_BASE + (PXPAT0S + (n)*0x100)) /* Port Pattern 0 Set Register */
#define GPIO_PXPAT0C(n) (GPIO_BASE + (PXPAT0C + (n)*0x100)) /* Port Pattern 0 Clear Register */
#define GPIO_PXFLG(n)   (GPIO_BASE + (PXFLG + (n)*0x100)) /* Port Flag Register */
#define GPIO_PXFLGC(n)  (GPIO_BASE + (PXFLGC + (n)*0x100)) /* Port Flag clear Register */
#define GPIO_PXPE(n)    (GPIO_BASE + (PXPE + (n)*0x100)) /* Port Pull Disable Register */
#define GPIO_PXPES(n)   (GPIO_BASE + (PXPES + (n)*0x100)) /* Port Pull Disable Set Register */
#define GPIO_PXPEC(n)   (GPIO_BASE + (PXPEC + (n)*0x100)) /* Port Pull Disable Clear Register */

#define GPIO_PA(n)      (0*32 + n)
#define GPIO_PB(n)      (1*32 + n)
#define GPIO_PC(n)      (2*32 + n)
#define GPIO_PD(n)      (3*32 + n)

static void gpio_direction_output(unsigned int gpio, unsigned int value)
{
	unsigned int port = gpio/32;
	unsigned int pin = gpio%32;

    *(volatile unsigned int *)GPIO_PXINTC(port) = 1 << pin;
    *(volatile unsigned int *)GPIO_PXMSKS(port) = 1 << pin;
    *(volatile unsigned int *)GPIO_PXPAT1C(port) = 1 << pin;

    if(value)
        *(volatile unsigned int *)GPIO_PXPAT0S(port) = 1 << pin;
    else
        *(volatile unsigned int *)GPIO_PXPAT0C(port) = 1 << pin;
}

void dump_gpio_status (unsigned int port, unsigned int pin)
{
    unsigned pxpin =  *(volatile unsigned int *) (GPIO_BASE + port * 0x100 );
    unsigned pxint =  *(volatile unsigned int *) (GPIO_BASE + port * 0x100  + 0x10);
    unsigned pxmsk  =  *(volatile unsigned int *) (GPIO_BASE + port * 0x100  + 0x20);
    unsigned pxpat1 =  *(volatile unsigned int *) (GPIO_BASE + port * 0x100  + 0x30);
    unsigned pxpat0 =  *(volatile unsigned int *) (GPIO_BASE + port * 0x100  + 0x40);
    //unsigned pxpen =  *(volatile unsigned int *) (GPIO_BASE + port * 0x100  + 0x70);

    int int_f, mask_f, pat0_f, pat1_f, pen_f;
    int_f = pxint & (1<<pin);
    mask_f = pxmsk & (1<<pin);
    pat0_f = pxpat0 & (1<<pin);
    pat1_f = pxpat1 & (1<<pin); 

    if (!int_f && mask_f && !pat1_f && !pat0_f)
        printf(">>> port: %d, pin: %d -- output 0 <<<\n", port, pin);
    else if (!int_f && mask_f && !pat1_f && pat0_f)
        printf(">>> port: %d, pin: %d -- output 1 <<<\n", port, pin);
    else
        printf(">>> port: %d, pin: %d -- unkown status <<<\n", port, pin);
}
======================================================================
sz-mozart 摄像头 cim_core

设备：
1) arch/mips/xburst/soc-x1000/include/mach/platform.h:
#define CIM_PORTA							\
	{ .name = "cim",    .port = GPIO_PORT_A,  .func = GPIO_FUNC_2, .pins = 0xfff << 8, }

2) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:

struct jz_gpio_func_def platform_devio_array[] = {
	.
	.
#if defined(CONFIG_VIDEO_JZ_CIM_HOST) || defined (CONFIG_JZ_CIM_CORE)
	CIM_PORTA,
#endif
	.	
}


#if defined(CONFIG_VIDEO_JZ_CIM_HOST) || defined(CONFIG_JZ_CIM_CORE)
static struct resource jz_cim_resources[] = {
	[0] = {
		.flags = IORESOURCE_MEM,
		.start = CIM_IOBASE,
		.end = CIM_IOBASE + 0x10000 - 1,
	},
	[1] = {
		.flags = IORESOURCE_IRQ,
		.start = IRQ_CIM,
	}
};

struct platform_device jz_cim_device = {
	.name = "jz-cim",
	.id = 0,
	.resource = jz_cim_resources,
	.num_resources = ARRAY_SIZE(jz_cim_resources),
};
#endif

3) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c:
static struct jz_platform_device platform_devices_array[] __initdata = {
#define DEF_DEVICE(DEVICE, DATA, SIZE)  \
	{ .pdevices = DEVICE,   \
		.pdata = DATA, .size = SIZE,}
		
#ifdef CONFIG_JZ_CIM_CORE
    DEF_DEVICE(&jz_cim_device, 0, 0),
#endif
		
}

sensor-gc2155:
1) arch/mips/xburst/soc-x1000/chip-x1000/halley2/halley2_v20/board.h
#ifdef CONFIG_JZ_CAMERA_SENSOR
#define FRONT_CAMERA_INDEX  0
#define BACK_CAMERA_INDEX   1

#define CAMERA_SENSOR_RESET GPIO_PD(5)
#define CAMERA_FRONT_SENSOR_PWDN  GPIO_PD(4)
#define CAMERA_VDD_EN  GPIO_PD(3)
#endif

2) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/i2c_bus.c
#ifdef CONFIG_JZ_CAMERA_SENSOR
static int sensor_gc2155_early_init(void)
{
    int ret = -1;

    if (!gpio_is_valid(CAMERA_VDD_EN)) {
        pr_err("%s %d: GPIO CAMERA_VDD_EN is invalid\n", __func__, __LINE__);
        return -1;
    }

    ret = gpio_request(CAMERA_VDD_EN, "gc2155_vdd_en");
    if (ret < 0) {
        pr_err("%s %d: CAMERA_VDD_EN request failed\n", __func__, __LINE__);
        return -1;
    }

    if (!gpio_is_valid(CAMERA_FRONT_SENSOR_PWDN)) {
        pr_err("%s %d: GPIO CAMERA_FRONT_SENSOR_PWDN is invalid\n", __func__, __LINE__);
        return -1;
    }

    ret = gpio_request(CAMERA_FRONT_SENSOR_PWDN, "gc2155_front_power_pwdn");
    if (ret < 0) {
        pr_err("%s %d: CAMERA_FRONT_SENSOR_PWDN request failed\n", __func__, __LINE__);
        return -1;
    }

    if (!gpio_is_valid(CAMERA_SENSOR_RESET)) {
        pr_err("%s %d: GPIO CAMERA_SENSOR_RESET is invalid\n", __func__, __LINE__);
        return -1;
    }

    ret = gpio_request(CAMERA_SENSOR_RESET, "gc2155_sensor_reset");
    if (ret < 0) {
        pr_err("%s %d: CAMERA_SENSOR_RESET request failed\n", __func__, __LINE__);
        return -1;
    }

    return 0;
}

static void sensor_gc2155_reset(void)
{
    gpio_direction_output(CAMERA_VDD_EN, 1);

    gpio_direction_output(CAMERA_SENSOR_RESET, 0);
    mdelay(250);
    gpio_direction_output(CAMERA_SENSOR_RESET, 1);
    mdelay(250);
}

static void sensor_gc2155_power_on(int value)
{
    gpio_direction_output(CAMERA_VDD_EN, value);

    /* enable or disable the camera */
    gpio_direction_output(CAMERA_FRONT_SENSOR_PWDN, value ? 0 : 1);
    mdelay(150);
}

static struct cim_sensor_plat_data gc2155_pdata = {
    .name = "sensor-gc2155",
    .gpio_en = CAMERA_VDD_EN,
    .init = sensor_gc2155_early_init,
    .reset = sensor_gc2155_reset,
    .power_on = sensor_gc2155_power_on,
};
#endif

#if (defined(CONFIG_SOFT_I2C0_GPIO_V12_JZ) || defined(CONFIG_I2C0_V12_JZ))
struct i2c_board_info jz_i2c0_devs[] __initdata = {
	....
#ifdef CONFIG_JZ_CAMERA_SENSOR
    {
        I2C_BOARD_INFO("sensor", 0x3c),
        .platform_data  = &gc2155_pdata,
    },
#endif
};
int jz_i2c0_devs_size = ARRAY_SIZE(jz_i2c0_devs);
#endif

3) arch/mips/xburst/soc-x1000/chip-x1000/halley2/common/board_base.c
static int __init board_base_init(void)
{
	int pdevices_array_size, i;

	。。。。

#if (defined(CONFIG_SOFT_I2C0_GPIO_V12_JZ) || defined(CONFIG_I2C0_V12_JZ))
	i2c_register_board_info(0, jz_i2c0_devs, jz_i2c0_devs_size);
#endif
	return 0;
}

驱动：
1) drivers/char/jz_cim_core.c:

======================================================================
sz-halley2 camera

sensor-ov7740
1) 
#ifdef CONFIG_VIDEO_JZ_CIM_HOST_V13
#define FRONT_CAMERA_INDEX  0
#define BACK_CAMERA_INDEX   1

#define CAMERA_SENSOR_RESET GPIO_PD(5)
#define CAMERA_FRONT_SENSOR_PWDN  GPIO_PD(4)
#define CAMERA_VDD_EN  GPIO_PD(3)
#endif


struct soc_camera_desc icdesc_front = {
	.host_desc = {
		.bus_id = CIM0,
		.board_info	= &jz_i2c0_devs[FRONT_CAMERA_INDEX],
		.i2c_adapter_id	= 0,
	},
	.subdev_desc = {
		.power = front_camera_sensor_power,
		.reset = camera_sensor_reset_front,
		.drv_priv = &ov772x_priv_front,
	},
};


3) 摄像头初始化时，没有将数据写入I2C，一般问题会出现在哪里？
SENSOR的各路电源是否接好，
CMCLK是否正确
RESET sensor
I2C总线上拉电阻是否匹配正确，
访问sensor时使用的 device ID是否正确， (注意7位地址和8位地址)
I2C的时钟CLK速率是否太高，
两次I2C连续读写之间是否有spec规定的delay时间
CAMERA POWER UP 时序是否符合 SPEC。

4) 编写测试代码过程中常见的问题

● 摄像头寄存器的配置

因为摄像头有很多寄存器，可能一下无法理解里面所有的配置含义，所以开始时希望得到一份可用的配置。但往往从别人的测试代码中拿到配置后，仍然无法使用。我这里列出几个可能的原因：
（a）摄像头中的图像输出格式和你在camera控制器中设置的不一致，同一个摄像头可以设置多种输入格式，如：YCbYCr或CbYCrY。
（b）图像输出的一些时序和你的camera控制器设置不一致，摄像头可以设置一些时序，如：图像数据在CAMPCLK的上升沿有效还是下降沿有效。
（c）注意输出图像的格式和Framebuffer控制器的匹配，如字节顺序等问题
（d）图像属性设置，比如宽高是否超范围或是否为4/8 整数倍。
（e）查看图像，RGB格式的数据，可以直接丢到LCD显示，验证图像效果。YUV可以用专门的YUV工具查看，或者用Photoshop查看。
（f）camera控制器中，隔行，逐行的控制位设置。 


5) Camera 测试
a)照相：cimutils -I 0 -C -v -x 320 -y 240、 cimutils -I 0 -C -v -x 640 -y 480
b)预览：cimutils -I 0 -P -w 320 -h 240
c)预览并照相：/cimutils -I 0 -P -v -l -w 320 -h 240
d)获取帮助：cimutils --help
======================================================================
VIM Ack基本使用
常用参数：
-i         忽略大小写
-v        显示不匹配行
-w        强制匹配整个单词
-l         打印匹配的文件名
-L        打印不匹配的文件名
-m       在每个文件中最多匹配多少行就停止搜索
-c        显示匹配的总行数

然后在Vim中输入 :Ack test_blah 便可以在当前项目代码中搜索 "test_blah" 了
常用快捷键如下：
?           帮助，显示所有快捷键
Enter/o     打开文件
O           打开文件并关闭Quickfix
go          预览文件，焦点仍然在Quickfix
t           新标签页打开文件
q           关闭Quickfix


可以在 ~/.vimrc 中为 :Ack 设置一个快捷键：
map <c-u> :Ack<space>
以后在普通模式下输入 Ctrl+U 便可以自动输入 :Ack 了

配置个热键：
    参考 http://vim.wikia.com/wiki/Word_under_cursor_for_command
    :map <F8> "zyw:exe "Ack ".@z.""<CR>
不配热键也可以：
:Ack <Ctrl + R + W> 就能把光标下的当前单词放进VIM命令行了


" 映射成<Ctrl-TAB>打开下一个TAB, <Alt-1>打开第一个TAB, <Alt-2>打开第二个, ...

if has("gui_running") 
     :map <silent> <C-S> :if expand("%") == ""<CR>:browse confirm w<CR>:else<CR>:confirm w<CR>:endif<CR> 
     noremap <M-1> 1gt 
     noremap <M-2> 2gt 
     noremap <M-3> 3gt 
     noremap <M-4> 4gt 
     noremap <M-5> 5gt 
     noremap <M-6> 6gt 
     noremap <M-7> 7gt 
     noremap <M-8> 8gt 
     noremap <M-9> 9gt 
     noremap <M-0> 10gt 
     noremap <C-TAB> gt 
     noremap <C-F4> <ESC>:bd<CR> 
     noremap qt <ESC>:bd<CR> 
     au BufEnter * simalt ~x "maximum the initial window 
else 
     colorscheme desert"torte 
endif

1.NERDTree与右边编辑区的Tabbar切换focus为 ctrl+w+h   ctr+w+l
2.也可以直接ctr+w 多次切换
3.Tabbar切换tab esc+[Number]
4.关闭tab :bd 回车清除内容，再回车关闭tab
5.关闭所有tab :qa! 
6.NERDTree与右边编辑区的Tabbar切换focus为 ctrl+h   ctr+l
7.Tabbar切换 ctrl+tab 上一下，下一个tab的切换，直接鼠标双击切换tab，直接跳转到[Number]的tab上，还没有找到。。。
8.关闭同上

ctags:
找到 tag：1/3 或更多

在跳转到一个函数或者一个变量的定义处时，经常有多处地方定义了相同名字，需要定位正确的定义地方。
:ts 或 tselect 查看有相同地方的定义
:tn或tnext   查找下一个定义地方。
:tp   查找上一个地方。
:tfirst  到第一个匹配
:tlast 到最后一个匹配
:tags 查看到达当前位置所经过的标签路径
ta xxx 跳转到标签 xxx 定义的地方
:stag xxx 在分割窗口中查看包含 xxx 的文件
======================================================================
获取31服务器上的Manhhatan/halley2代码:
repo init -u ssh://wangqiuwei@192.168.3.11:29418/mirror/Manhhatan/halley2/platform/manifest.git -b ingenic-linux-kernel3.10.14-halley2-v2.0-20160905 -m boards/halley2.xml

----------------------------------------------------------------------
获取31服务器上的mozart代码:
repo init -u ssh://wangqiuwei@192.168.3.11:29418/mirror/sdk-x1000-v1.6/linux/manifest -b sz-master-mozart
repo init -u ssh://wangqiuwei@192.168.3.11:29418/mirror/sdk-x1000-v1.6/linux/manifest -b speaker-master-x1000
repo init -u ssh://wangqiuwei@192.168.3.11:29418/mirror/sdk-x1000-v1.6/linux/manifest -b speaker-master-x1000 -m master.xml

网盘下载：
链接: http://pan.baidu.com/s/1c0Dae0g 密码: <PASSWORD>

kernel:
./git/config:
[core]
	repositoryformatversion = 0
	filemode = true
[remote "ing"]
	url = ssh://wangqiuwei@192.168.3.11:29418/mirror/sdk-x1000-v1.6/android/kernel/kernel-3.0.8
	review = https://review.ingenic.cn/
	projectname = android/kernel/kernel-3.0.8
	fetch = +refs/heads/*:refs/remotes/ing/*
[remote "bj"]
    url = ssh://qwwang_sz@192.168.1.26:29418/android/kernel/kernel-3.0.8
	review = https://review.ingenic.cn/
	projectname = android/kernel/kernel-3.0.8
	fetch = +refs/heads/*:refs/remotes/ing/*
	push = HEAD:refs/for/speaker-master-x1000

uboot:
.git/config:
[core]
	repositoryformatversion = 0
	filemode = true
[remote "ing"]
	url = ssh://wangqiuwei@192.168.3.11:29418/mirror/sdk-x1000-v1.6/bootloader/u-boot
	review = https://review.ingenic.cn/
	projectname = bootloader/u-boot
	fetch = +refs/heads/*:refs/remotes/ing/*

[remote "bj"]
    url = ssh://qwwang_sz@192.168.1.26:29418/bootloader/u-boot
	review = https://review.ingenic.cn/
	projectname = bootloader/u-boot
	fetch = +refs/heads/*:refs/remotes/ing/*
    push = HEAD:refs/for/speaker-master-x1000
----------------------------------------------------------------------
#define CONFIG_BOOTCOMMAND          "bootx sfc 0x80f00000 0xd00000" 这一行（大概在159行），

   0xd00000 这个值没有修改正确，计算方法：updater分区大小 + appfs 分区起始地址
   
----------------------------------------------------------------------
grep 设置默认跳过的目录和文件的方法:
修改:~/.profile,添加如下一行:
export GREP_OPTIONS="--exclude-dir=\.git --exclude=.tags* --exclude=tags"
----------------------------------------------------------------------
Makefile有三个非常有用的变量。分别是$@，$^，$<代表的意义分别是：
$@--目标文件，$^--所有的依赖文件，$<--第一个依赖文件。

======================================================================
应用层：
open("/dev/dsp3", O_RDONLY);
驱动：
xb_snd_dsp_open
xb_snd_dsp_ioctl

应用层：
open("/dev/mixer3", O_RDONLY);
驱动：
xb_snd_mixer_open
xb_snd_mixer_ioctl
======================================================================
交叉编译opencv

报错解决：
Linking CXX shared library ../../lib/libopencv_core.so
/opt/toolchains/mips-gcc472-glibc216/bin/../lib/gcc/mips-linux-gnu/4.7.2/../../../../mips-linux-gnu/bin/ld: ../../3rdparty/lib/libzlib.a(gzclose.c.obj): relocation R_MIPS_26 against `gzclose_w' can not be used when making a shared object; recompile with -fPIC
../../3rdparty/lib/libzlib.a: error adding symbols: Bad value
collect2: error: ld returned 1 exit status
make[2]: *** [lib/libopencv_core.so] 错误 1

解决方法，修改build/CmakeCache.txt， 如下：

1) CMAKE_CXX_FLAGS:STRING=-fPIC，大概163行
2) CMAKE_C_FLAGS:STRING=-fPIC ， 大概183行

运行运用找不到库的问题：
error while loading shared libraries: ../../lib/libopencv_core.so的解决方法

readelf -d libopencv_highgui.so

Dynamic section at offset 0x50580 contains 30 entries:
  Tag Type Name/Value
 0x00000001 (NEEDED) Shared library: [../../lib/libopencv_core.so]
 0x00000001 (NEEDED) Shared library: [../../lib/libopencv_imgproc.so]
 0x00000001 (NEEDED) Shared library: [libstdc++.so.6]
 0x00000001 (NEEDED) Shared library: [libm.so.6]
 0x00000001 (NEEDED) Shared library: [libgcc_s.so.1]
 0x00000001 (NEEDED) Shared library: [libc.so.6]
 0x0000000c (INIT) 0xa410
 0x0000000d (FINI) 0x49ed4
 0x00000019 (INIT_ARRAY) 0x50000
 0x0000001b (INIT_ARRAYSZ) 12 (bytes)
 0x0000001a (FINI_ARRAY) 0x5000c
......

解决方法：
1) vi toolchain.cmake, 内容如下：
set(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_SYSTEM_PROCESSOR mips)
set(CMAKE_C_COMPILER mipsel-linux-gcc)
set(CMAKE_CXX_COMPILER mipsel-linux-g++)
set(CMAKE_FIND_ROOT_PATH "/opt/toolchains/mipsel-buildroot-linux-gnu/usr")
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

2) cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake ../opencv-2.4.13/
3) ccmake .
======================================================================
/*#define CONFIG_LCD*/

#define CONFIG_GPIO_PWR_WAKE		GPIO_PB(31)
#define CONFIG_GPIO_PWR_WAKE_ENLEVEL	0

#ifdef CONFIG_LCD
#define LCD_BPP     5
#define SOC_X1000
#define CONFIG_JZ_PWM
#define CONFIG_GPIO_LCD_PWM     GPIO_PC(25)
#define CONFIG_LCD_GPIO_FUNC1_SLCD

#define CONFIG_JZ_LCD_V13
#define CONFIG_SYS_WHITE_ON_BLACK
#define CONFIG_SYS_PWM_PERIOD       10000 /* Pwm period in ns */
#define CONFIG_SYS_PWM_CHN          0     /* Pwm channel ok */
#define CONFIG_SYS_PWM_FULL         255
#define CONFIG_SYS_BACKLIGHT_LEVEL  80    /* Backlight brightness is (80 / 256) */

#define CONFIG_SYS_CONSOLE_INFO_QUIET
#define CONFIG_SYS_CONSOLE_IS_IN_ENV

#define CONFIG_VIDEO_TRULY_TFT240240_2_E

#ifdef CONFIG_VIDEO_TRULY_TFT240240_2_E
#define CONFIG_GPIO_LCD_RD  GPIO_PB(16)
#define CONFIG_GPIO_LCD_RST GPIO_PD(0)
#define CONFIG_GPIO_LCD_CS  GPIO_PB(18)
#define CONFIG_GPIO_LCD_BL  GPIO_PD(1)
#endif	/* CONFIG_VIDEO_TRULY_TFT240240_2_E */

/*#define CONFIG_LCD_LOGO*/
/*#define CONFIG_RLE_LCD_LOGO*/
/*#define CONFIG_LCD_INFO_BELOW_LOGO*/  /*display the console info on lcd panel for debugg*/
#ifdef CONFIG_RLE_LCD_LOGO
#define CONFIG_CMD_BATTERYDET           /*detect battery and show charge logo*/
#define CONFIG_CMD_LOGO_RLE             /*display the logo using rle command*/
#endif

#endif /* CONFIG_LCD */
======================================================================
#ifndef CONFIG_LCD_DK_ST7789H2
#define SLCDC_PORTAB_8BIT						\
	{ .name = "slcd", .port = GPIO_PORT_A, .func = GPIO_FUNC_1, .pins = 0xff, }, \
	{ .name = "slcd", .port = GPIO_PORT_B, .func = GPIO_FUNC_1, .pins = 0x1a << 16, } 
#else
#define SLCDC_PORTAB_8BIT						\
	{ .name = "slcd", .port = GPIO_PORT_A, .func = GPIO_FUNC_1, .pins = 0xff, }, \
	{ .name = "slcd", .port = GPIO_PORT_B, .func = GPIO_FUNC_1, .pins = 0x12 << 16, } 
#endif
======================================================================
tar.xz 文件压缩与解压:

1) xz压缩文件方法或命令:
xz -z 要压缩的文件
如果要保留被压缩的文件加上参数 -k ，如果要设置压缩率加入参数 -0 到 -9调节压缩率。如果不设置，默认压缩等级是6.

2) xz解压文件方法或命令:
xz -d 要解压的文件
同样使用 -k 参数来保留被解压缩的文件。

3)创建或解压tar.xz文件的方法:
习惯了 tar czvf 或 tar xzvf 的人可能碰到 tar.xz也会想用单一命令搞定解压或压缩。
其实不行 tar里面没有征对 xz格式的参数, 比如 z是针对 gzip，j是针对 bzip2。

创建tar.xz文件：只要先 tar cvf xxx.tar xxx/ 这样创建xxx.tar文件先，然后使用 xz -z xxx.tar 来将 xxx.tar压缩成为 xxx.tar.xz
解压tar.xz文件：先 xz -d xxx.tar.xz 将 xxx.tar.xz解压成 xxx.tar 然后，再用 tar xvf xxx.tar来解包
======================================================================
根文件系统，网络已经连接，并且 网关、DNS 已经配置可以 ping通 域名的IP， 无法 ping通 域名的解决方法：
问题原因：
因为缺少几个必要的库和配置文件：/etc/nsswitch.conf, /lib/libnss_dns*, /lib/libnss_files*, and /lib/libresolv*
实测： /etc/nsswitch.conf 可以没有
======================================================================
配置编译strace
1) 配置：
./configure ARCH=mips CROSS_COMPILE=mips-linux-gnu- --prefix=`pwd` --host=mipsel-linux CC=mips-linux-gnu-gcc LD=mips-linux-gnu-ld CFLAGS="-EL -mabi=32 -mhard-float -march=mips32r2 -Os"

2) 编译：
make LDLIBS="-Wl -EL -W1 -start-group -lc -lnss_file -lnss_dns -lresolv -W1 -end-group"

3) 去掉符号信息
mips-linux-gnu-strip strace
======================================================================
shell 判断字符串为空
主要有以下几种方法：

echo “$str”|awk '{print length($0)}'
expr length “$str”
echo “$str”|wc -c
但是第三种得出的值会多1，可能是把结束符也计算在内了

判断字符串为空的方法有三种：
if [ "$str" =  "" ]
if [ x"$str" = x ]
if [ -z "$str" ] （-n 为非空）
注意：变量都要带双引号，否则有些命令会报错，养成好习惯吧！

test或[ ]的注意事项
1、在中括号 [] 内的每个组件都需要有空白键来分隔
2、在中括号内的变量，最好都以双引号括号起来
3、在中括号内的常数，最好都以单或双引号括号起来
======================================================================
printk("### %s: %s -- %d ###\n",__FILE__, __FUNCTION__, __LINE__);

# echo 250 > brightness 
[   97.473346] ### drivers/leds/led-class.c: led_brightness_store -- 51 ###
[   97.480682] ### brightness = 250, period = 30000, max = 255 duty = 29411 pwm->flags = 6 ###
[   97.489358] ### drivers/leds/leds-pwm.c: __led_pwm_set -- 46 111
[   97.495550] ### drivers/pwm/core.c: pwm_config -- 407 ###
[   97.501156] ### drivers/pwm/pwm-jz.c: jz_pwm_config -- 100  pwm_id = 4 ###
[   97.508240] ### tcu_device->pwm_flag = 6 ###
[   97.512665] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_as_timer_config -- 266 ###
[   97.520931] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_set_start_state -- 141 ###
[   97.529196] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_set_pwm_shutdown -- 130 ###
[   97.537534] ### arch/mips/xburst/soc-x1000/common/tcu.c: set_tcu_full_half_value -- 122 ###
[   97.546157] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_select_division_ratio -- 153 ###
[   97.554961] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_pwm_output_enable -- 76 ###
[   97.563317] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_select_clk -- 170 ###
[   97.571134] ### drivers/pwm/pwm-jz.c: jz_pwm_config -- 156 OK
[   97.577054] ### drivers/leds/leds-pwm.c: __led_pwm_set -- 54 enable
[   97.583528] ### drivers/pwm/pwm-jz.c: jz_pwm_disable -- 176 ###
[   97.589643] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_disable -- 357 ###
[   97.597175] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_shutdown_counter -- 97 ###
[   97.605437] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_pwm_output_disable -- 90 ###
[   97.613880] ### drivers/pwm/core.c: pwm_enable -- 440 aaa
[   97.619456] ### drivers/pwm/pwm-jz.c: jz_pwm_enable -- 165 ###
[   97.625467] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_enable -- 338 ###
[   97.632925] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_pwm_output_enable -- 76 ###
[   97.641277] ### arch/mips/xburst/soc-x1000/common/tcu.c: tcu_enable -- 346 ###
--------------------------------------------------------------------------------------------
tcu_as_timer_config() {
	tcu_set_start_state() {
		stop conuting up;
		The clock supplies to timer x is supplied;
		set TCSRx = 0;

		tcu_set_pwm_shutdown() {
			set TCSRx.SD;
		}
	}

	set TCNTx = 0; //Timer counter regiter
	
	set_tcu_full_half_value() {
		set TDFRx = period;
		set TDHRx = duty;
	}

	tcu_select_division_ratio() {
		tmp = regr(TCSRx);
		regw((tmp | CSR_DIVx), TCSRx)
	}

	tcu_pwm_output_enable(id) {
		if (id > 4) {
			pr_err("TCU %d is not support PWM output\n", id);
			dump_stack();
			return -ENXIO;
		}
		tmp = regr(CH_TCSR(id));
		regw((tmp | TCSR_PWM_EN), CH_TCSR(id));
	}

	tcu_select_clk(int id, int clock) {
		int tmp;

		tmp = regr(CH_TCSR(id));
		switch (clock) {
		case EXT_EN:  regw((tmp | CSR_EXT_EN), CH_TCSR(id)); break;
		case RTC_EN:  regw((tmp | CSR_RTC_EN), CH_TCSR(id)); break;
		case PCLK_EN: regw((tmp | CSR_PCK_EN), CH_TCSR(id)); break;
		case CLK_MASK:
			regw((tmp & (~CSR_CLK_MSK)), CH_TCSR(id));
		}
	}
}

pwm-beeper ===>>
#if defined(CONFIG_INPUT_PWM_BEEPER) && defined(PWM_BEEPER_PORT)
struct platform_device pwm_beeper_device = {
    .name   = "pwm-beeper",
    .dev    = {
        .platform_data = (unsigned long *)PWM_BEEPER_PORT,
    },
};
#endif
	/* tcu->half_num = tcu->full_num, indicated duty = 0 */
	if (tcu->half_num == tcu->full_num) {
		if (tcu->io_func != (tcu->init_level ? GPIO_OUTPUT1 : GPIO_OUTPUT0)) {
			tcu->io_func = tcu->init_level ? GPIO_OUTPUT1 : GPIO_OUTPUT0;
			jzgpio_set_func(tcu->gpio_def->port, tcu->io_func, tcu->gpio_def->pins);
			pr_debug("%s -- line = %d, tcu->io_func = %s\n", __FUNCTION__, __LINE__, \
				tcu->io_func == GPIO_OUTPUT1 ? "GPIO_OUTPUT1" : "GPIO_OUTPUT0");
		}
	} else if (tcu->half_num == 0) {  /* tcu->half_num = 0, indicated duty = 100% */
		if (tcu->io_func != (tcu->init_level ? GPIO_OUTPUT0 : GPIO_OUTPUT1)) {
			tcu->io_func = tcu->init_level ? GPIO_OUTPUT0 : GPIO_OUTPUT1;
			jzgpio_set_func(tcu->gpio_def->port, tcu->io_func, tcu->gpio_def->pins);
			pr_debug("%s -- line = %d, tcu->io_func = %s\n", __FUNCTION__, __LINE__, \
				tcu->io_func == GPIO_OUTPUT0 ? "GPIO_OUTPUT0" : "GPIO_OUTPUT1");
		}
	} else {
		if (tcu->io_func != tcu->gpio_def->func) {
			tcu->io_func = tcu->gpio_def->func;
			jzgpio_set_func(tcu->gpio_def->port, tcu->io_func, tcu->gpio_def->pins);
		}
	}
======================================================================
#include <soc/cpm.h>
#include <soc/base.h>
 
#define CPM_CLKGR_CIM          (1 << 22)

unsigned int reg_clkgr = cpm_inl(CPM_CLKGR);
unsigned int gate = CPM_CLKGR_CIM;
reg_clkgr |= gate;
cpm_outl(reg_clkgr, CPM_CLKGR);
printk("CPM_CLKGR  = 0x%08x\n", cpm_inl(CPM_CLKGR));

======================================================================
解压cpio文件
cpio -idmv < filename.cpio
同样可以解压img文件：
cpio -idmv < filename.img
cpio 备份命令
备份：cpio -covB > [file|device] 将数据备份到文件或设备上
还原：cpio -icduv < [file|device} 将数据还原到系统中
常用参数：
-o   ：将数据copy到文件或设备上
-i    ：将数据从文件或设备上还原到系统中
-t    ：查看cpio建立的文件或设备内容
-c   ：一种比较新的portable format方式存储
-v   ：在屏幕上显示备份过程中的文件名
-B   ：让预设的blocks可以增加到5120bytes，默认是512bytes，这样可以使备份速度加快
-d   ：自动建立目录，这样还原时才不会出现找不到路径的问题
-u   ：更新，用较新的文件覆盖旧的文件
cpio常与find 配合使用


先解开 root-nand.cpio
mkdir root-nand
cd root-nand
sudo cpio -idm < ../root-nand.cpio
cp -a ../recovery sbin/
重新打包
find ./ -print | cpio -H newc -ov > ../root-nand.cpio
======================================================================
ov5640 sysclock registers:
0x3034:
	Bit[7]:   Debug mode
	Bit[6:4]: PLL charge pump control
	Bit[3:0]:
			  MIPI bit mode
			  0x8: 8-bit mode
			  0xA: 10-bit mode
			  Others: Debug mode

0x3035:
	Bit[7:4]: System clock divider
			  Slow down all clocks
	Bit[3:0]: Scale divider for MIPI
			  MIPI PCLK/SERCLK can be slowed down

0x3036:
	Bit[7:0]: PLL multiplier (4~252)
			  Can be any integer from 4~127
			  and only even integers from 128~252
			  
0x3067:
	Bit[7:5]: Debug mode
	Bit[4]:   PLL root divider
			  0: Bypass
			  1: Divided by 2
	Bit[3:0]: PLL pre-divider
			  1,2,3,4,6,8

0x3108:
	Pad Clock Divider for SCCB Clock
	Bit[7:6]: Debug mode
	Bit[5:4]: PCLK root divider
			  00: PCLK = pll_clki
			  01: PCLK = pll_clki/2
			  10: PCLK = pll_clki/4
			  11: PCLK = pll_clki/8
	Bit[3:2]: sclk2x root divider
			  00: SCLK2x = pll_clki
			  01: SCLK2x = pll_clki/2
			  10: SCLK2x = pll_clki/4
			  11: SCLK2x = pll_clki/8
	Bit[1:0]: SCLK root divider
			  00: SCLK = pll_clki
			  01: SCLK = pll_clki/2
			  10: SCLK = pll_clki/4
			  11: sclk = pll_clki/8
======================================================================
linux spi应用程序编写步骤:
第一：open
第二：ioctl ，ioctl有九种cmd，分别对应不同的arg
a、设置或获取SPI工作模式
SPI_IOC_RD_MODE     //读 模式 
SPI_IOC_WR_MODE     //写 模式 
以上两种cmd对用arg是spi_device.mode
spi_device.mode有以下几种类型
#define SPI_MODE_0 (0|0) //SCLK空闲时为低电平，串行同步时钟的前沿（上升）数据被采样
#define SPI_MODE_1 (0|SPI_CPHA)//SCLK空闲时为高电平，串行同步时钟的前沿（下降）数据被采样
#define SPI_MODE_2 (SPI_CPOL|0)//SCLK空闲时为低电平，串行同步时钟的后沿（上升）数据被采样
#define SPI_MODE_3 (SPI_CPOL|SPI_CPHA)//SCLK空闲时为高电平，串行同步时钟的后沿（下降）数据被采样
#define SPI_CS_HIGH 0x04//片选为高
#define SPI_LSB_FIRST 0x08//低位数据先传输
#define SPI_3WIRE 0x10//三线式，输入输出数据线为一条线
#define SPI_LOOP 0x20//回环模式
#define SPI_NO_CS 0x40//没有片选信号
#define SPI_READY 0x80//
用法：
mode = SPI_MODE_0 | SPI_CS_HIGH | SPI_LSB_FIRST | SPI_LOOP
ioctl(fd, SPI_IOC_WR_MODE, &mode)；
注意：前面四种是对SCK时钟信号空闲时的电平，和采样时刻的选择，四个只能选择其中一种，后面的五种可以用或的形式选择任意几个，使用方法如上

b、设置或获取SPI读写是从高位还是低位开始
SPI_IOC_RD_LSB_FIRST    //读 LSB 
SPI_IOC_WR_LSB_FIRST    //写 LSB 
以上两种cmd对用arg是spi_device.mode
用法：同上，但是mode类型只有SPI_LSB_FIRST一种

c、设置或获取SPI读写数据位数
SPI_IOC_RD_BITS_PER_WORD    //读 每字多少位 
SPI_IOC_WR_BITS_PER_WORD    //写 每字多少位
以上两种cmd对用arg是spi_device.bits_per_word
用法：
bits = 8；
ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);

d、设置或获取SPI读写的最大频率
SPI_IOC_RD_MAX_SPEED_HZ //读 最大速率 
SPI_IOC_WR_MAX_SPEED_HZ //写 最大速率 
以上两种cmd对用arg是spi_device.max_speed_hz
用法：
speed = 50*1000；
ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);

e、传输数据
SPI_IOC_MESSAGE(n)      //传输n个数据包 
以上一种cmd对用arg是spi_ioc_transfer
用法：全双工传输数据
struct spi_ioc_transfer tr = {
    .tx_buf = (unsigned long)tx,
    .rx_buf = (unsigned long)rx,
    .len = ARRAY_SIZE(tx),
    .delay_usecs = delay,
    .speed_hz = speed,
    .bits_per_word = bits,
};
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);

第三：read或write
用法：和大多数的设备read函数一样的用法，但是每次读或者写的大小不能大于4096Byte。
char* buf[n];
read(fd,buf,sizeof(buf));或者write(fd,buf,sizeof(buf));

第四：close
======================================================================
Linux下Beyond Compare4的破解使用 
1.官网下载最新版 Beyond Compare 4 并安装

http://www.scootersoftware.com/download.php
2.安装后进入到bcompare目录下，输入命令破解

进入目录：
cd /usr/lib/beyondcompare/

更改权限：
sudo chmod 755 BCompare

输入破解命令:
sudo sed -i "<KEY>" BCompare

3.此时BCompare文件已被破解，打开软件会提示Trial Mode Error！表示成功，输入Team ZWT生成的密钥即可注册成功

提供Team ZWT生成密钥一枚：
--- BEGIN LICENSE KEY ---
<KEY>
--- END LICENSE KEY -----
======================================================================
0x400     1K
0x1000    4K
0x10000   64K
0x80000   512K/0.5M
0x100000  1M
======================================================================
config WKUP_PIN_RST
	depends on MACH_XBURST
	bool "support reset chip by press the WKUP pin judge time"
	default n

config JUDGE_TIME
	int "judge time lenght in second"
	range 1 16
	default 5
	depends on WKUP_PIN_RST
======================================================================
建 repo管理的 git库
服务器：
01) cd review_site/git/mirror/
02) mkdir lrc
03) git clone qwwang@192.168.3.11:/home/qwwang/work/github/tt/lrc --mirror
04) mkdir manifest
05) cp ../QRcode/manifest/default.xml manifest/
06) cd manifest && vim default.xml, 修改 default.xml 为:
<?xml version="1.0" encoding="UTF-8"?>
<manifest>
  <remote  name="linux"
           fetch="."
           review="https://review.ingenic.cn/" />
  <default revision="master"
           remote="linux"
           sync-j="1" />

   <project path="lrc" name="lrc" />
</manifest>
07) git init; git add .; git commit -m "init"
08) cd ..; git clone manifest/ --mirror
09) git clone qwwang@192.168.3.11:/home/qwwang/work/github/tt/route --mirror
10) cd manifest && vim default.xml, 添加一行: <project path="route" name="route" />
11) git add .; git commit -m "add route"; git push, 如果出错继续执行下面步骤
    a) cp default.xml ../; cd ..
    b) rm manifest/ -rf
    c) git clone manifest.git/
    d) cp default.xml manifest/; cd manifest/
    e) git add .; git commit -m "add route"; git push origin

客户机：
1) mkdir test; cd test
2) repo init -u ssh://wangqiuwei@192.168.3.11:29418/mirror/lrc/manifest
3) repo sync

建单独的git库
服务器：
1)git init --bare test （test为新建库的名称）

客户机：
1)git clone ssh://wangqiuwei@192.168.3.11:29418/test

Gerrit 添加一个已经有的git工程到gerrit服务器
1) ssh -p 29418 user@localhost gerrit create-project --name demo-project
2) git push ssh://user@localhost:29418/demo-project *:*

添加用户方法
服务器：
添加用户 "aaa": htpasswd etc/passwords aaa
======================================================================
ISP(Image Signal Processing 中文译为“图形信号处理”

BF3703
0x03 VHREF
VREF and HREF control.
Bit[7:6]: VREF end low 2 Bits(high 8 Bit at VSTOP[7:0])
Bit[5:4]: VREF start low 2 Bits(high 8 Bit at VSTART[7:0])
Bit[3:2]: HREF end 2 LSB(high 8 MSB at register HSTOP)
Bit[1:0]: HREF start 2 LSB(high 8 MSB at register HSTART)

0x17 HSTART
Output Format-Horizontal Frame(HREF column)start high
8-Bit(low 2Bits are at VHREF[1:0])

0x18 HSTOP
Output Format-Horizontal Frame(HREF column)end high
8-Bit(low 2 Bits are at VHREF[3:2])

0x19 VSTART 
Output Format-Vertical Frame(row)start high 8-Bit(low 2 Bits are at VHREF[5:4])

0x1a VSTOP
Output Format-Vertical Frame(row)end high 8-Bit(low 2 Bits are at VHREF[7:6])
======================================================================
获取文件大小的方法：
stat -c%s filename
======================================================================
sed 是stream editor的简称，也就是流编辑器。它一次处理一行内容，处理时，把当前处理的行存储在临时缓冲区中，
称为“模式空间”（pattern space），接着用sed命令处理缓冲区中的内容，处理完成后，把缓冲区的内容送往屏幕。接
着处理下一行，这样不断重复，直到文件末尾。文件内容并没有 改变，除非你使用重定向存储输出。

sed 命令行格式为：
  sed [-nefri] ‘command’ 输入文本

常用选项：
  -n ∶ 使用安静(silent)模式。在一般 sed 的用法中，所有来自 STDIN的资料一般都会被列出到萤幕上。
       但如果加上 -n 参数后，则只有经过 sed 特殊处理的那一行(或者动作)才会被列出来。
  -e ∶ 直接在指令列模式上进行 sed 的动作编辑；
  -f ∶ 直接将 sed 的动作写在一个档案内， -f filename 则可以执行 filename 内的sed 动作；
  -r ∶ sed 的动作支援的是延伸型正规表示法的语法。(预设是基础正规表示法语法)
  -i ∶ 直接修改读取的档案内容，而不是由萤幕输出。       

常用命令：
  a ∶ 新增，a 的后面可以接字串，而这些字串会在新的一行出现(目前的下一行)
  c ∶ 取代，c 的后面可以接字串，这些字串可以取代 n1,n2 之间的行！
  d ∶ 删除，因为是删除啊，所以 d 后面通常不接任何咚咚；
  i ∶ 插入，i 的后面可以接字串，而这些字串会在新的一行出现(目前的上一行)
  p ∶ 列印，亦即将某个选择的资料印出。通常 p 会与参数 sed -n 一起运作～
  s ∶ 取代，可以直接进行取代的工作哩！通常这个 s 的动作可以搭配正规表示法！例如 1,20s/old/new/g 就是啦！

sed -i 's/.\/$(LOADER_NAME)[ ]\+[0-9a-z]\+[ ]\+[0-9]\+/.\/$(LOADER_NAME) $(APP_OFFSET) $(APP_SIZE)/' $(APP_SCRIPT); \

======================================================================
git clone ssh://wangqiuwei@192.168.3.11:29418/linux-recovery
======================================================================
安装 libffi
sed -e '/^includesdir/ s/$(libdir).*$/$(includedir)/' \
    -i include/Makefile.in && sed -e '/^includedir/ s/=.*$/=@includedir@/' \
    -e 's/^Cflags: -I${includedir}/Cflags:/' \
    -i libffi.pc.in        &&./configure --prefix=/usr --disable-static && make
======================================================================
sudo autoreconf -ivf  

<file_sep>/sys_program/2nd_day/pm/raise.c
/* ************************************************************************
 *       Filename:  raise.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 15时28分59秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <signal.h>
#include <sys/types.h>


int main(int argc, char *argv[])
{
	sleep(3);
	printf("raise\n");
	raise(2);
	return 0;
}


<file_sep>/network/route/src/inc/route_pthread.h
/******************************************************************************
  文 件 名   : route_pthread.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月11日
  最近修改   :
  功能描述   : route_pthread.c 的头文件
******************************************************************************/

#ifndef __ROUTE_PTHREAD_H__
#define __ROUTE_PTHREAD_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */

/*----------------------------------------------*
 * 函数原型说明                                 *
 *----------------------------------------------*/
extern void create_pthread(TYPE_Route *rt);
extern void dispose_key_cmd(TYPE_Route *rt, char cmd[]);
extern void *pthread_deal_message(void *arg);
extern void *pthread_key_event(void *arg);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */


#endif /* __ROUTE_PTHREAD_H__ */
<file_sep>/work/test/gpioset/Makefile
CC := mipsel-linux-gcc
TAG := gpioset gpior
INSTALL_DIR := ../../mozart/rootfs/updater/usr/bin/

all:$(TAG)

.PHONY:gpioset
gpioset:gpioset.c
	$(CC) -o gpioset gpioset.c

.PHONY:gpior
gpior:
	$(CC) -o gpior gpior.c

.PHONY:install
install:gpioset gpior
	cp $(TAG) $(INSTALL_DIR)

.PHONY:clean
clean:
	rm $(TAG) *.o -rf
<file_sep>/shell/mount_nfs.sh
#!/bin/sh

#auto get ip
#udhcpc

#config ip netmask gw
ifconfig eth0 10.221.2.112 netmask 255.255.255.0
route add default gw 10.221.2.254

serverip=10.221.2.221
serverpath=/home/edu
localpath=/mnt

echo "usage:./mount_nfs serverip serverpath localpath"
if [ -z $serverip ]; then
	echo "serverip is NULL"
	exit 1
fi
if [ -z $serverpath ]; then
	echo "serverpath is NULL"
	exit 1
fi
if [ -z $localpath ]; then
	localpath=/mnt/nfs
	echo "localpath default /mnt/nfs"
fi

mount -o nolock,wsize=1024,rsize=1024 $serverip:$serverpath $localpath


if [ $? = 0 ]; then
	echo "nfs mount succeed!!"
	echo "if you want to umount the serverpath"
	echo "please input umount like this: umount /mnt"
else
	echo "nfs mount failed,please check and try again!!"
fi
<file_sep>/sys_program/2nd_day/pm/signal_set.c
/* ************************************************************************
 *       Filename:  signal_set.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 17时01分27秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <signal.h>
#include <stdio.h>



int main(int argc, char *argv[])
{
	sigset_t set;
	int ret = 0;

	sigemptyset(&set);

	ret = sigismember(&set,SIGINT);

	if(ret == 0)
		printf("SIG is not a member of sigpromask \nret = %d\n",ret);

	sigaddset(&set,SIGINT);
	sigaddset(&set,SIGQUIT);

	ret = sigismember(&set,SIGINT);

	if(ret == 1)
		printf("SIG is a member of sigpromask \nret = %d\n",ret);

	return 0;
}


<file_sep>/sys_program/6th_day/mutex.c
/* ************************************************************************
 *       Filename:  mutex.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月20日 10时34分16秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t mutex;
//PTHREAD_MUTEX_INITIALIZER;


void print(char *str)
{
	pthread_mutex_lock(&mutex);

	while(*str != '\0')
	{
		putchar(*str++);
		fflush(stdout);
		sleep(1);
	}
	putchar('\n');

	pthread_mutex_unlock(&mutex);
}

void *fun1(void *arg)
{
	char *buf = "world";

	print(buf);
}

void *fun2(void *arg)
{
	char *buf = "hello";

	print(buf);
}

int main(int argc, char *argv[])
{
	pthread_t pth1,pth2;

	pthread_mutex_init(&mutex,NULL);

	pthread_create(&pth1,NULL,fun1,NULL);
	pthread_create(&pth2,NULL,fun2,NULL);

	pthread_join(pth1,NULL);
	pthread_join(pth2,NULL);

	pthread_mutex_destroy(&mutex);
	return 0;
}
<file_sep>/work/test/gpioset/gpior.c
/*************************************************************************
	> File Name: gpio.c
	> Author:
	> Mail:
	> Created Time: Wed 25 May 2016 10:50:56 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>

/*#define DEBUG*/
#define GPIO_SET_OUTPUT  1
#define GPIO_SET_INPUT   0
#define GPIO_SET_LOW     0
#define GPIO_SET_HIGH    1

static void print_help(void)
{
    printf("Usage: gpior gpionum \n");
    printf("Usage:\n");
    printf("   eg: gpior 52\n");
}

static int gpio_read(int gpionum)
{
    char path[64];
    char value_str[3] = {0};
    int fd, i;

    snprintf(path, sizeof(path), "/sys/class/gpio/gpio%d/value", gpionum);
    printf("path: %s\n",path);
    fd = open(path, O_RDONLY);
    if(fd < 0) {
        printf("Failed to open gpio value for reading!\n");
        return -1;
    }

    for(i = 0; i < 2; i++) {
        if(read(fd, value_str, sizeof(value_str)) < 0) {
          printf("Failed to read gpio%d value!\n", gpionum);
          return -1;
        }
    }
#ifdef DEBUG
    printf("### read value = %s\n", value_str);
    for(i = 0; i < 3; i++) {
        printf("value_str[%d] = %d\t",i, value_str[i]);
    }
    printf("\n");
#endif
    close(fd);
    return atoi(value_str);
}

int main(int argc, char *argv[])
{
    // Test for correct number of arguments
    if(argc != 2) {
        print_help();
        return -1;
    }

    int gpionum = atoi(argv[1]);
    if(gpionum < 0 || gpionum > 101) { // For Ingenic x1000 soc
        printf("### gpionum: %d is invalid ###\n", gpionum);
        return -1;
    }
     int ret = gpio_read(gpionum);
     if(ret != -1)
         printf("### read gpio%d ret = %d ###\n", gpionum, ret);
     return 0;
}
<file_sep>/work/debug/2440/buttons/buttons_drv.c
/* ************************************************************************
 *       Filename:  buttons_drv.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月16日 18时40分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/platform_device.h>
#include <linux/cdev.h>
#include <linux/miscdevice.h>
#include <linux/sched.h>
#include <linux/gpio.h>
#include <linux/timer.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <mach/regs-gpio.h>
#include <mach/hardware.h>

#define DEVICE_NAME          "buttons_drv"
#define TIME_DELAY_20MS      (HZ/50)         //按键按下去抖延时
#define TIME_DELAY_50MS      (HZ/20)         //按键松开去抖延时
#define KEY_DOWN             0               //按键按下
#define KEY_UP               1               //按键松开
#define KEY_UNCERTAIN        2               //按键不确定
#define KEY_COUNT            6

static volatile int ev_press = 0;             //按键按下状态标志
static volatile int key_status[KEY_COUNT];    //记录按键的状态
static struct timer_list key_timers[KEY_COUNT];//定义6个按键去抖定时器
static DECLARE_WAIT_QUEUE_HEAD(buttons_waitq);//定义并初始化等待队列

static int majno = 0; //主设备号
static struct cdev *p_cdev = NULL;
static struct class *keys_class = NULL;

struct key_irq_desc
{
	int irqno;   //中断号
	int pin;     //引脚
	int pin_cfg; //引脚配置
	char *name;  //中断设备名称
};

static struct key_irq_desc keys_irq[] =
{
    {IRQ_EINT8 , S3C2410_GPG(0) ,  S3C2410_GPG0_EINT8  , "KEY0"},
    {IRQ_EINT11, S3C2410_GPG(3) ,  S3C2410_GPG3_EINT11 , "KEY1"},
    {IRQ_EINT13, S3C2410_GPG(5) ,  S3C2410_GPG5_EINT13 , "KEY2"},
    {IRQ_EINT14, S3C2410_GPG(6) ,  S3C2410_GPG6_EINT14 , "KEY3"},
    {IRQ_EINT15, S3C2410_GPG(7) ,  S3C2410_GPG7_EINT15 , "KEY4"},
    {IRQ_EINT19, S3C2410_GPG(11),  S3C2410_GPG11_EINT19, "KEY5"},
};


static irqreturn_t key_interrupt(int irq, void *dev_id)
{
	//获取哪个按键被按下
	int key_id = (int)dev_id;

	if(key_status[key_id] == KEY_UP)
	{
		key_status[key_id] = KEY_UNCERTAIN; //设置当前按键状态为不确定

		//设置去抖延时时间为20MS，并启动定时器
		key_timers[key_id].expires = jiffies + TIME_DELAY_20MS;
		add_timer(&key_timers[key_id]); //定时器到时之后会调用定时器的回调函数进一步处理
	}

	return IRQ_RETVAL(IRQ_HANDLED);
}

static void timer_callback(unsigned long arg)
{
	//获取哪个按键被按下
	int key_id = arg;
	int status = s3c2410_gpio_getpin(keys_irq[key_id].pin); //获取按键状态

	if( !status ) //低电平， 按键按下
	{
		if(key_status[key_id] == KEY_UNCERTAIN)
		{
			key_status[key_id] = KEY_DOWN;

			s3c2410_gpio_setpin(keys_irq[key_id].pin, 1);
			ev_press = 1; //确定有按键被按下
			wake_up_interruptible(&buttons_waitq);//唤醒等待队列
		}

		//设置按键抬起去抖延时
		key_timers[key_id].expires = jiffies + TIME_DELAY_50MS;
		add_timer(&key_timers[key_id]);
	}
}

static int buttons_open(struct inode *inode, struct file *file)
{
	int i, ret;

	for(i=0;i<KEY_COUNT;i++)
	{
		//配置I/O的模式为中断
		s3c2410_gpio_cfgpin(keys_irq[i].pin, keys_irq[i].pin_cfg);

		//配置下降沿触发中断
		set_irq_type(keys_irq[i].pin, IRQ_TYPE_EDGE_FALLING);

		ret = request_irq(keys_irq[i].irqno, key_interrupt, IRQF_DISABLED, keys_irq[i].name, (void *)i);

		if(ret)	break; //申请中断成功返回 0

		key_status[i] = KEY_UP;

		//初始化并设置各个按键的去抖定时器
		key_timers[i].function = timer_callback;  //注册定时器的到时处理函数
		key_timers[i].data = i;                   //传递给到时处理函数的参数
		init_timer(&key_timers[i]);                //初始化定时器
	}

	if(ret) //中断申请失败
	{
		i--;

		for(; i >= 0; i--)
		{   //释放注册成功的中断
			disable_irq(keys_irq[i].irqno);
			free_irq(keys_irq[i].irqno, (void *)i);
		}

		return -EBUSY;
	}

	return 0;
}

static ssize_t buttons_read(struct file *filp,char __user *buf, size_t count,loff_t *ppos)
{
	unsigned long ret;

	if(!ev_press) //没有按键被按下
	{
		if(filp->f_flags & O_NONBLOCK)
		{
			//若应用程序采用非阻塞方式读取，则返回
			return -EAGAIN; //提示用户再尝试读
		}
		else
		{
			//以阻塞方式读取且按键没被按下，则让等待队列进入休眠
			wait_event_interruptible(buttons_waitq, ev_press);
		}
	}

	ev_press = 0; //已有按键按下，重置此标志

	ret = copy_to_user(buf, (void *)key_status, min(sizeof(key_status), count));

	memset((void *)key_status, 0, sizeof(key_status));

	return ret ? -EFAULT :  min(sizeof(key_status), count); //返回用户成功读取的字节数
}

static int buttons_close(struct inode *inode,struct file *file)
{
	int i;

	//释放定时器和中断
	for(i=0; i < KEY_COUNT; i++)
	{
		del_timer(&key_timers[i]);

		disable_irq(keys_irq[i].irqno);
		free_irq(keys_irq[i].irqno, (void *)i);
	}
	return 0;
}

static unsigned int buttons_poll(struct file *file, struct poll_table_struct *wait)
{
	unsigned int mask = 0;

	//添加 等待队列 到 等待队列表中
	poll_wait(file, &buttons_waitq, wait);

	if(ev_press) //按键被按下
	{
		mask |= POLLIN | POLLRDNORM; //表示数据可以获取
	}

	return mask;
}

static struct file_operations buttons_fops =
{
	.owner   = THIS_MODULE,
	.open    = buttons_open,
	.read    = buttons_read,
	.release = buttons_close,
	.poll    = buttons_poll,
};

static void buttons_setup_cdev(struct cdev *dev,int index)
{
	int err;
	dev_t devno = MKDEV(majno, index);

	cdev_init(dev, &buttons_fops);

	dev->owner = THIS_MODULE;
	dev->ops = &buttons_fops;

	err = cdev_add(dev, devno, 1);

	if(err)
	{
		printk(KERN_NOTICE "Error %d adding keys cdev %d",err,index);
	}
}

static int __init buttons_init(void)
{
	int ret;
	dev_t devno = MKDEV(majno,0);

	//初始化硬件I/O

	if(!majno)
	{
		ret = alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
		majno = MAJOR(devno);
	}
	else
	{
		ret = register_chrdev_region(devno,1,DEVICE_NAME);
	}

	if(ret < 0)
	{
		return ret;
	}

	p_cdev = kmalloc(sizeof(struct cdev), GFP_KERNEL);

	if(!p_cdev)
	{
		ret = -ENOMEM;
		goto fail_malloc;
	}

	memset(p_cdev, 0, sizeof(struct cdev));

	buttons_setup_cdev(p_cdev,0);

	//注册一个类
	keys_class = class_create(THIS_MODULE, DEVICE_NAME);//要添加#include <linux/device.h>

	if(IS_ERR(keys_class))
	{
		printk("Err:failed in create keys class\n");
		goto fail_add_class;
	}
	//创建一个设备节点
	device_create(keys_class,NULL,MKDEV(devno,0),NULL,DEVICE_NAME);
	return 0;

	fail_malloc:
	unregister_chrdev_region(devno,1);
	return -1;

	fail_add_class:
	cdev_del(p_cdev);
	kfree(p_cdev);
	unregister_chrdev_region(devno,1);
	return -1;
}
/*
 * 设备的注销函数，在设备从内核卸载时调用
 *
 */
static void __exit buttons_exit(void)
{
	device_destroy(keys_class,MKDEV(majno,0));  //删除设备节点
	class_destroy(keys_class); //注销类
	cdev_del(p_cdev);
	kfree(p_cdev);  //回收设备结构的内存
	unregister_chrdev_region(MKDEV(majno,0),1); //释放设备号
}

module_init(buttons_init);
module_exit(buttons_exit);

/* 描述驱动程序的一些信息，不是必须的 */
MODULE_AUTHOR("Dawei");                 // 驱动程序的作者
MODULE_DESCRIPTION("A buttons Driver");   // 一些描述信息
MODULE_LICENSE("GPL");                  // 遵循的协议
<file_sep>/c/practice/3rd_week/link/main.c
#include <stdio.h>
#include <string.h>
#include "link.h"

void help()
{
	printf("-----------------------------------\n");
	printf("->help  : 帮助信息                  \n");
	printf("->insert: 插入一个新节点             \n");
	printf("->print : 遍历整个链表               \n");
	printf("->search: 查询某个节点               \n");
	printf("->delete: 查删除某个节点             \n");
	printf("->free  : 释放整个节点               \n");
	printf("->exit  : 退出                      \n");
	printf("-----------------------------------\n");
}

int main(int argc,char *argv[])
{
	char cmd[128] = "";
	STU *head = NULL;
	
	while(1)
	{
		scanf("%s",cmd);
		
		if(strcmp(cmd,"help")==0)
		{
			help();
		}
		else if(strcmp(cmd,"insert")==0)
		{
			STU temp;
			printf("please input the num,name,score:\n");
			scanf("%d %s %d",&temp.num,temp.name,&temp.score);
			head = insert_link(head, temp);
		}
		else if(strcmp(cmd,"print")==0)
		{
			printf("-----print-----\n");
			print_link(head);		
		}
		else if(strcmp(cmd,"search")==0)
		{
			char name[64] = "";
			STU *ret;
			printf("please input search name\n");	
			scanf("%s",name);
			
			ret = search_link(head, name);
			
			if(ret == NULL)
			{
				printf("not found\n");
			}
			else
			{
				printf("%d %s %d\n",ret->num,ret->name,ret->score);
			}
		}
		else if(strcmp(cmd,"delete")==0)
		{
			int num = 0;
			printf("Please input delete num\n");
			scanf("%d",&num);
			head = delete_link(head,num);	
		}
		else if(strcmp(cmd,"free")==0)
		{
			printf("-----free link-----\n");	
			head = free_link(head);
		}
		else if(strcmp(cmd,"exit")==0)
		{
			printf("----- exit -----\n");	
			head = free_link(head);
			break;
		}
	}
	return 0;
}
<file_sep>/c/homework/3rd_week/atoi/Makefile
atoi:myatoi.c
	gcc -o atoi myatoi.c -lm

.PHONY:clean
clean:
	rm atoi
<file_sep>/work/test/cim_test-zmm220/fvjpg.c
/*
 * $Id: fv.c
 * $Desp: draw jpeg to framebuffer
 * $Author: rockins
 * $Date: Wed Jan  3 20:15:49 CST 2007
 */

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
//#include <jpeglib.h>
//#include <jerror.h>
#include <string.h>

#define	FB_DEV	"/dev/fb0"

/***************** function declaration ******************/
void            usage(char *msg);
unsigned short  RGB888toRGB565(unsigned char red,
							   unsigned char green, unsigned char blue);
int             fb_open(char *fb_device);
int             fb_close(int fd);
int             fb_stat(int fd, int *width, int *height, int *depth);
void           *fb_mmap(int fd, unsigned int screensize);
int             fb_munmap(void *start, size_t length);
int             fb_pixel(void *fbmem, int width, int height,
						 int x, int y, unsigned short color);
#define TRUE	1
/************ function implementation ********************/
//int main(int argc, char **argv)

	/*
	 * declaration for jpeg decompression
	 */
	static struct jpeg_decompress_struct cinfo;
	static struct jpeg_error_mgr jerr;
	static FILE           *infile,*fp;
	static unsigned char  *buffer;

	/*
	 * declaration for framebuffer device
	 */
	static int             fbdev;
	static char           *fb_device;
	static unsigned char  *fbmem;
	static unsigned int    screensize;
	static unsigned int    fb_width;
	static unsigned int    fb_height;
	static unsigned int    fb_depth;
	static unsigned int    x;
	static unsigned int    y;
	static int flag=0;

void openDev(void)
{
	#if 0
	if ((fp = fopen("/mnt/sdcard/main", "rb")) != NULL) {
		printf("sdcard ok\n");
		fclose(fp);
		//return 1;
		flag=1;
	}
	#endif
#if 0
        /*
         * open input jpeg file
         */
        if(!flag)
        {
        //      if ((infile = fopen(argv[1], "rb")) == NULL) {
                if ((infile = fopen(path, "rb")) == NULL) {
                        printf("can't open jpg file\n");
                //      exit(-1);
                        return -1;
                }
        }
        else
        {
                if ((infile = fopen("warning2.jpg", "rb")) == NULL) {
                        printf("can't open jpg file\n");
                        exit(-1);
                }
        }
#endif

	/*
	 * open framebuffer device
	 */
	if ((fb_device = getenv("FRAMEBUFFER")) == NULL)
	{
		fb_device = FB_DEV;
		printf("fb_device=/dev/fb0\n");
	}

	printf("fd_device:%s\n",fb_device);

	fbdev = fb_open(fb_device);

	/*
	 * get status of framebuffer device
	 */
	fb_stat(fbdev, &fb_width, &fb_height, &fb_depth);

	/*
	 * map framebuffer device to shared memory
	 */
	screensize = fb_width * fb_height * fb_depth / 8;
	fbmem = fb_mmap(fbdev, screensize);
	printf("open framebuffer ok\n");

}

#if 0
int showimage(char *path)
{

                if ((infile = fopen(path, "rb")) == NULL) {
                        printf("can't open jpg file\n");
                //      exit(-1);
                        return -1;
                }
	/*
	 * init jpeg decompress object error handler
	 */
	cinfo.err = jpeg_std_error(&jerr);
	jpeg_create_decompress(&cinfo);

	/*
	 * bind jpeg decompress object to infile
	 */
	jpeg_stdio_src(&cinfo, infile);


	/*
	 * read jpeg header
	 */
	jpeg_read_header(&cinfo, TRUE);

	/*
	 * decompress process.
	 * note: after jpeg_start_decompress() is called
	 * the dimension infomation will be known,
	 * so allocate memory buffer for scanline immediately
	 */
	jpeg_start_decompress(&cinfo);
	if ((cinfo.output_width > fb_width) ||
		(cinfo.output_height > fb_height)) {
		printf("fb_width=%d\n",fb_width);
		printf("fb_height=%d\n",fb_height);
		printf("too large JPEG file,cannot display\n");
		return (-1);
	}

	buffer = (unsigned char *) malloc(cinfo.output_width *
									  cinfo.output_components);
	y = 0;
//	printf("fb_depth %d\n",fb_depth);
	while (cinfo.output_scanline < cinfo.output_height) 
	{
		jpeg_read_scanlines(&cinfo, &buffer, 1);

		if (fb_depth == 16) 
		{
			unsigned short  color;
			for (x = 0; x < cinfo.output_width; x++) 
			{
				color = RGB888toRGB565(buffer[x * 3], buffer[x * 3 + 1], buffer[x * 3 + 2]);
				fb_pixel(fbmem, fb_width, fb_height, x, y, color);
			}
		} 
		else if (fb_depth == 24) 
		{
			memcpy((unsigned char *) fbmem + y * fb_width * 3, buffer, cinfo.output_width * cinfo.output_components);
		}
		y++;					// next scanline
	}
	/*
	 * finish decompress, destroy decompress object
	 */
	jpeg_finish_decompress(&cinfo);
	jpeg_destroy_decompress(&cinfo);

	fclose(infile);

}
#endif
void showimg(unsigned char *buf,int x, int y, int w, int h)
{
//	printf("show img ...\n");
	int i;
	for(i=0;i<h;i++)
		memcpy((unsigned char *) fbmem + ((y+i)*fb_width+x)*2 , buf+i*w*2, w*2);
}

void closeDev(void)
{

	/*
	 * release memory buffer
	 */
	free(buffer);

	/*
	 * close jpeg inputing file
	 */
//	fclose(infile);

	/*
	 * unmap framebuffer's shared memory
	 */
	fb_munmap(fbmem, screensize);

	/*
	 * close framebuffer device
	 */
	fb_close(fbdev);
//	return (0);
}

void
usage(char *msg)
{
	fprintf(stderr, "%s\n", msg);
	printf("Usage: fv some-jpeg-file.jpg\n");
}

/*
 * convert 24bit RGB888 to 16bit RGB565 color format
 */
unsigned short
RGB888toRGB565(unsigned char red,unsigned char green, unsigned char blue)
{
	unsigned short  B = (blue >> 3) & 0x001F;
	unsigned short  G = ((green >> 2) << 5) & 0x07E0;
	unsigned short  R = ((red >> 3) << 11) & 0xF800;

	return (unsigned short) (R | G | B);
}

void RGB565toRGB888(unsigned short rgb565, unsigned char *rgb)
{
	rgb[0] = (rgb565&0xF800)>>11;
	rgb[1] = (rgb565&0x0E70)>>5;
	rgb[2] = (rgb565&0x001F);
	
	return;
}
/*
 * open framebuffer device.
 * return positive file descriptor if success,
 * else return -1.
 */
int
fb_open(char *fb_device)
{
	int             fd;

	if ((fd = open(fb_device, O_RDWR)) < 0) {
		perror(__func__);
		return (-1);
	}
	return (fd);
}

/*
 * get framebuffer's width,height,and depth.
 * return 0 if success, else return -1.
 */
int
fb_stat(int fd, int *width, int *height, int *depth)
{
	struct fb_fix_screeninfo fb_finfo;
	struct fb_var_screeninfo fb_vinfo;

	if (ioctl(fd, FBIOGET_FSCREENINFO, &fb_finfo)) {
		perror(__func__);
		return (-1);
	}

	if (ioctl(fd, FBIOGET_VSCREENINFO, &fb_vinfo)) {
		perror(__func__);
		return (-1);
	}

	*width = fb_vinfo.xres;
	*height = fb_vinfo.yres;
	*depth = fb_vinfo.bits_per_pixel;

	return (0);
}

/*
 * map shared memory to framebuffer device.
 * return maped memory if success,
 * else return -1, as mmap dose.
 */
void           *
fb_mmap(int fd, unsigned int screensize)
{
	caddr_t         fbmem;

	if ((fbmem = mmap(0, screensize, PROT_READ | PROT_WRITE,
					  MAP_SHARED, fd, 0)) == MAP_FAILED) {
		perror(__func__);
		return NULL;
	}

	return (fbmem);
}

/*
 * unmap map memory for framebuffer device.
 */
int
fb_munmap(void *start, size_t length)
{
	return (munmap(start, length));
}

/*
 * close framebuffer device
 */
int
fb_close(int fd)
{
	return (close(fd));
}

/*
 * display a pixel on the framebuffer device.
 * fbmem is the starting memory of framebuffer,
 * width and height are dimension of framebuffer,
 * x and y are the coordinates to display,
 * color is the pixel's color value.
 * return 0 if success, otherwise return -1.
 */
int
fb_pixel(void *fbmem, int width, int height,
		 int x, int y, unsigned short color)
{
	if ((x > width) || (y > height))
		return (-1);

	unsigned short *dst = ((unsigned short *) fbmem + y * width + x);

	*dst = color;
	return (0);
}

//modify by seven 2011-06-11
#if 1
int fb_pixelAsRow(void *fbmem, int width, int height,
                 int x, int y, unsigned short *rowbuf, int bufsize)
{
        if ((x > width) || (y > height))
                return (-1);

        unsigned short *dst = ((unsigned short *) fbmem + y * width + x);

	memcpy(dst, rowbuf, bufsize);

        return (0);
}
#endif


/*
int main(int argc, char **argv)
{
	char name[50];
	int i;

	for(i=0;i<10;i++)
	{
		sprintf(name,"image%d.jpg",i);
		showimage(name);
	}
	return 0;
}
*/
<file_sep>/sys_program/2nd_day/pm/pause.c
/* ************************************************************************
 *       Filename:  pause.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 15时38分33秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <signal.h>


int main(int argc, char *argv[])
{
	sleep(3);
	printf("pause\n");
	pause();
	return 0;
}


<file_sep>/work/camera/bf3703/bf3703/bf3703_set_mode.c
#include <asm/jzsoc.h>
#include <linux/jz_sensor.h>
#include <linux/i2c.h>
#include "bf3703_set.h"

#define bf3703_DEBUG
#ifdef bf3703_DEBUG
#define dprintk(x...)   do{printk("cm3511---\t");printk(x);printk("\n");}while(0)
#else
#define dprintk(x...)
#endif


void night_enable(struct i2c_client *client)
{
	
}

void de_night_disable(struct i2c_client *client)
{
	
}

void bf3703_night_select(struct i2c_client *client,int enable)
{
}
/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/






/*----------------------------------set white balance------------------------------------------------*/

void bf3703_set_wb_auto_mode(struct i2c_client *client)
{
	retry_write_reg(client,0x01,0x15);
	retry_write_reg(client,0x02,0x24);
	retry_write_reg(client,0x13,0x07);   // Enable AWB
}

void bf3703_set_wb_sunny_mode(struct i2c_client *client)
{
	retry_write_reg(client,0x13,0x05);   // Disable AWB
	retry_write_reg(client,0x01,0x13);
	retry_write_reg(client,0x02,0x26);	
}

void bf3703_set_wb_cloudy_mode(struct i2c_client *client)
{ 
	retry_write_reg(client,0x13,0x05);   // Disable AWB
	retry_write_reg(client,0x01,0x10);
	retry_write_reg(client,0x02,0x28);
}

void bf3703_set_wb_office_mode(struct i2c_client *client)
{ 
	retry_write_reg(client,0x13,0x05);   // Disable AWB
	retry_write_reg(client,0x01,0x1f);
	retry_write_reg(client,0x02,0x15);
}

void bf3703_set_wb_home_mode(struct i2c_client *client)
{
	
}

/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/





/*---------------------------------------set banding------------------------------------------------*/

void bf3703_ab_auto(struct i2c_client *client)
{
}

void bf3703_ab_50hz(struct i2c_client *client)
{
	retry_write_reg(client,0x9d,0x99); 

}


void bf3703_ab_60hz(struct i2c_client *client)
{
	retry_write_reg(client,0x9e,0x80); 

}


void bf3703_ab_off(struct i2c_client *client)
{
}
/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/





/*---------------------------------------set effect------------------------------------------------*/

void bf3703_set_effect_normal(struct i2c_client *client)
{
	retry_write_reg(client,0x80,0x45);		
	retry_write_reg(client,0x76,0x00);
	retry_write_reg(client,0x69,0x00);		
	retry_write_reg(client,0x67,0x80);		
	retry_write_reg(client,0x68,0x80);
}

void bf3703_set_effect_sepia(struct i2c_client *client)
{
	retry_write_reg(client,0x80,0x45);
	retry_write_reg(client,0x76,0x00);
	retry_write_reg(client,0x69,0x20);		
	retry_write_reg(client,0x67,0x60);		
	retry_write_reg(client,0x68,0x98);
}

void bf3703_set_effect_whiteboard(struct i2c_client *client)
{
 	retry_write_reg(client,0x69,0x00);
	retry_write_reg(client,0x80,0xc5);		
	retry_write_reg(client,0x76,0xf0);			
	retry_write_reg(client,0x67,0x80);		
	retry_write_reg(client,0x68,0x80);
}


void bf3703_set_effect_bluish(struct i2c_client *client)
{
 	
}

void bf3703_set_effect_greenish(struct i2c_client *client)
{
	retry_write_reg(client,0x80,0x45);
	retry_write_reg(client,0x76,0x00);
	retry_write_reg(client,0x69,0x20);		
	retry_write_reg(client,0x67,0x40);		
	retry_write_reg(client,0x68,0x40);
}

void bf3703_set_effect_reddish(struct i2c_client *client)
{
}

void bf3703_set_effect_yellowish(struct i2c_client *client)
{
}

void bf3703_set_effect_blackwhite(struct i2c_client *client)
{
	retry_write_reg(client,0x80,0x45);		
	retry_write_reg(client,0x76,0x00);
	retry_write_reg(client,0x69,0x20);		
	retry_write_reg(client,0x67,0x80);		
	retry_write_reg(client,0x68,0x80);
}

void bf3703_set_effect_negative(struct i2c_client *client)
{
	retry_write_reg(client,0x80,0x45);		
	retry_write_reg(client,0x76,0x00);
	retry_write_reg(client,0x69,0x40);		
	retry_write_reg(client,0x67,0x80);		
	retry_write_reg(client,0x68,0x80);

}

/*--------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------*/





<file_sep>/sys_program/4th_day/homework/chat/Makefile
.PHONY:all
all:peter lucy bob

peter:chat.c
	gcc chat.c -o peter -DP
	
lucy:chat.c
	gcc chat.c -o lucy -DL
	
bob:chat.c
	gcc chat.c -o bob -DB
	
.PHONY:clean
clean:
	rm peter lucy bob<file_sep>/work/shell/mksystem_img.sh
#!/bin/bash

if [ $# -gt 0 ]; then
    TARGET_DEVICE=$1
fi

if [ x"$TARGET_DEVICE" = x ]; then
    TARGET_DEVICE="halley2"
fi

echo "TARGET_DEVICE = $TARGET_DEVICE"
./out/host/tools/mkfs.jffs2 -e 0x8000 -p 0xc80000 -d ./out/product/$TARGET_DEVICE/system/ -o ./out/product/$TARGET_DEVICE/image/system.jffs2
<file_sep>/work/debug/a8/touchscreen/goodix_dev.c
/*
 * Copyright (c) 2012 sunplusapp
 * this program is free software; you can redistribute it and/or modify it
 *
 * this is a demo about how to create i2c_board_info dynamically; it just like
 * i2c_register_device
 *
 * Date and Edition:		2012-11-18  v1.0
 * Date and Edition:		2013-01-05  v1.1
 * Author:				<<EMAIL>>
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/i2c.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/irq.h>


static struct i2c_board_info goodix_info = {
	/**/
	I2C_BOARD_INFO("Goodix-TS",0x55),
};

static struct i2c_client *dev_test_client;
static struct i2c_client *goodix_client;

static __init int goodix_device_init(void)
{
	struct i2c_adapter *i2c_adap;
	/**/
	i2c_adap = i2c_get_adapter(0);
	goodix_client = i2c_new_device(i2c_adap, &goodix_info);
	i2c_put_adapter(i2c_adap);
	printk("%s:%d\n",__FUNCTION__,__LINE__);
	return 0;
}

static __exit void goodix_device_exit(void)
{
	i2c_unregister_device(dev_test_client);
}

module_init(goodix_device_init);
module_exit(goodix_device_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("sunplusedu");
<file_sep>/sys_program/player/src/inc/mplayer_control.h
/* ************************************************************************
 *       Filename:  mplayer_control.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月24日 10时05分21秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __MPLAYER_CONTROL_H__
#define __MPLAYER_CONTROL_H__

extern void send_cmd(char cmd[],MPLAYER *pm);
extern void mplayer_show_musiclist(MPLAYER *pm, SONG *ps);
//extern void mplayer_show_musiclist(MPLAYER *pm);
extern void playing_song(MPLAYER *pm, int new_song);
extern void set_playing_song(MPLAYER *pm, int step);
extern void set_lable(GtkLabel *label, char *src);
extern void set_keyflag(KEY_STATUS status);
extern void set_songname(int song_num);
extern void set_lrc_lable(MPLAYER *pm, char *pbuf[]);
extern void clear_lrc_lable(MPLAYER *pm);

#endif


<file_sep>/c/homework/2nd_week/Makefile
execute = guess_number transform year typewriting
sources = guess_number.c transform.c year.c	typewriting.c
objects = guess_number.o transform.o year.o typewriting.o

.PHONY:all
all:$(subst .c,,$(sources))
#$(patsubst %.c,%,$(sources))
#$(sources:.c=)

typewriting:typewriting.c
	gcc -o typewriting typewriting.c -w
guess_number:guess_number.c
	@echo "making guess_number.c"
	gcc -o guess_number guess_number.c -lm -w
transform:transform.c

year:year.c

.PHONY:clean
clean:
	rm $(execute)
<file_sep>/c/practice/1st_week/math/mymath.h
/* ************************************************************************
 *       Filename:  mymath.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月16日 星期四 02時22分12秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#ifndef __MYMATH_H__
#define __MYMATH_H__


int sum(int a,int b);
int abs(int n);
extern void Bubbing_Methed(char *p);

#endif


<file_sep>/c/practice/sort/insertsort.c
#include "stdio.h"

//从小到大进行排序
insertsort(int k[],int n)         	/*直接插入排序*/
{
    int i,j;
	int temp;

    for(i=1;i<n;i++)
    {
        temp = k[i];				//将要比较的值先绶存起来留出一个空位，方便移动
        j = i - 1;
        while(j>=0 && k[j]>temp)    //比较直到出现比temp大的值，或向前找到头
        {
			k[j+1] = k[j];			//将前面的值往后移
			j--;
		}
        k[j+1] = temp;             	//插在a[j]的后面
    }
}

int main()
{
    int i,a[10] = {2,5,6,3,7,8,0,9,12,1};        /*初始化序列，a[0]可任意置数*/
    printf("The data array is:\n") ;
    for(i=0;i<10;i++)                       	 /*输出排序前的数据*/
        printf("%d ",a[i]);

    insertsort(a,10);                            /*插入排序*/
	
    printf("\nThe result of insertion sorting for the array is:\n");
    for(i=0;i<10;i++)
        printf("%d ",a[i]);                      /*输出排序后的数据*/
	printf("\n");
	return 0;
}<file_sep>/c/lrc/file.c
/* ************************************************************************
 *       Filename:  file.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月31日 星期五 05時35分04秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include "common.h"

/**************************************************************************
*函数功能:读出文件内容
*参数：file_length    整型指针，此地址中保存文件字节数。
*      lrc_src  文件名字，从此文件中读取内容。
* 返回值:读出字符串的首地址
* 函数中测文件的大小并分配空间，再把文件内容读出到分配的空间中，返回此空间首地址
**************************************************************************/ 
char *read_src_file(ulint *file_length, char *lrc_src)
{
	FILE *fp = NULL;
	char *buf = NULL;
	
	//unsigned long int file_length = 0;
	
	fp = fopen(lrc_src,"rb");//以只读方式打开一个二进制文件
	
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	fseek(fp,0,SEEK_END);
	*file_length = ftell(fp); //获取文件的大小
	
	buf = (char *)malloc(*file_length); //
	
	if(buf == NULL)
	{
		printf("malloc() cannot apply for memory!\n");
		goto out;
	}
	rewind(fp); //
	fread(buf,*file_length,1,fp);
	
	out:
	fclose(fp);
	return buf;
}
#if 1
char *get_musiclist(char ***plist)
{
	FILE *fp =NULL;
	char *buf = NULL;	
	ulint list_length = 0;
	uint lines = 0;
	int part = 0;
	system("ls ./music | grep .mp3 >./music/musiclist");
	
	fp = fopen("music/musiclist","rb");
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	buf = read_src_file(&list_length,"music/musiclist");	
	lines = check_lines(list_length, buf);
	
	*plist = (char **)malloc((lines + 1) * sizeof(char **));  //动态分配空间存储每行的首地址
	
	if(*plist == NULL) return NULL; 
	
	part = src_segment(buf, *plist, "\r\n");	         //按行分割
	plist[lines] = NULL; 
	
#if 1
   int i, len;
	for(i=0;i<part-1;i++)
	{
		len = strlen(*(*(plist) + i));
		*(*(*(plist) + i) + len -4) = '\0';
		//printf("%s\n",plist[i]);
	}	
#endif	

	return buf;
}
#else
char **get_musiclist()
{
	FILE *fp =NULL;
	char *buf = NULL, **plist = NULL;	
	ulint list_length = 0;
	uint lines = 0;
	int part = 0;
	system("ls ./music | grep .mp3 >./music/musiclist");
	
	fp = fopen("music/musiclist","rb");
	if(fp == NULL)
	{
		printf("Cannot open the flie!\n");
		return;
	}
	buf = read_src_file(&list_length,"music/musiclist");	
	lines = check_lines(list_length, buf);
	
	plist = (char **)malloc((lines + 1) * sizeof(char **));  //动态分配空间存储每行的首地址
	
	if(plist == NULL) return NULL; 
	
	part = src_segment(buf, plist, "\r\n");	         //按行分割
	plist[lines] = NULL; 
	
#if 1
   int i, len;
	for(i=0;i<part-1;i++)
	{
		len = strlen(*(*(plist) + i));
		//printf("len =%d\n",len);
		*(*(*(plist) + i) + len -1) = '\0';
		//printf("%s\n",plist[i]);
	}	
#endif

	return plist;
}
#endif
void delete_dot(char *plist[])
{
	int i = 0,len = 0;
	
	for(i=0;plist[i] != NULL;i++)
	{
		len = strlen(plist[i]);
		plist[i][len-4] = '\0'; //减4目的是跳过歌名中的 mp3 字样
	}
}
void recover_dot(char *plist[])
{
	int i = 0,len = 0;
	
	for(i=0;plist[i] != NULL;i++)
	{
		len = strlen(plist[i]);
		plist[i][len] = '.';
	}
}
int check_lines(ulint file_length, char *lrc_src)
{
	uint lines = 0;
	ulint i = 0;
	char *p = NULL;
	
	p = lrc_src;
	
	#if 1
	for(i = 0;i < file_length;i++)
	{
		if(p[i]=='\n')  lines++;
	}
	#elif 0 //这种方法不行，因为strchr函数和strstr函数遇到 '\0' 就返回
	while(p != NULL)
	{
		p = strchr(p,'\n');
		lines++;
	}
	#endif
	return lines;
}

int get_longestline(int lines, char *plines[])
{
	int longestline = 0, temp = 0, i = 0;
	
	for(i=0;i<lines;i++)
	{
		temp = strlen(plines[i]);
		
		if(temp > longestline) longestline = i;
	}
	return longestline;
}

int get_longestlength(LRC *lrc_head)
{
	int longest = 0, temp = 0, chrnum = 0;
	
	if(lrc_head != NULL)
	{
		LRC *pb = NULL, *pf = NULL;
		pb = lrc_head;
		
		while(pb != NULL)
		{
			temp = strlen(pb->psrc);
			if(temp > longest) 
			{
				pf = pb;
				longest = temp;
			}		
			//printf("len=%d  %s\n",temp,pb->psrc);
			pb = pb->next;
		}
		
		temp = strlen(pf->psrc);
		chrnum = get_chrnumber(pf->psrc,temp);
		longest += chrnum/2;
	}

	return longest;
}

int get_showoffset(char *pbuf, int longest)
{
	int len = 0, offset = 0, temp = 0;
	int count = 0;
	
	len = strlen(pbuf);
	count = get_chrnumber(pbuf, len);
	len += count/2;
	
	offset = (longest - len)/3;
	//printf("longest=%d len=%d offset=%d  %s\n",longest,len,offset,pbuf);
	if(offset < 0) offset = 0; //一定要加此判断
	return offset;
}

int get_chrnumber(char *pbuf, int len)
{
	int i = 0,count = 0;
	
	for(i=0;i<len;i++)
	{
		if(pbuf[i] > 0 && pbuf[i] <127) count++;
	}
	return count;
}
<file_sep>/work/debug/pc/timer/Makefile
ifneq ($(KERNELRELEASE),)
	obj-m := timer_drv.o

else
	KERNELDIR ?= /lib/modules/$(shell uname -r)/build
#	KERNELDIR ?= /work/linux/linux-2.6.32.2
	PWD := $(shell pwd)
default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
	rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
	rm -f *.o *~ *.ko  *.mod.c *.mod.o *.symvers *.order
endif

ins:
	sudo insmod ./timer_dev.ko
del:
	sudo rmmod timer_dev
	
CC := gcc
mt:
	$(CC) -o test test_timer.c

.PHONY:clc
clc:
	rm test


<file_sep>/work/debug/2440/keys/tiny6410_buttons.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/poll.h>
#include <linux/irq.h>  // #define S3C_EINT(x) ((x) + S3C_IRQ_EINT_BASE)   #define IRQ_EINT(x) S3C_EINT(x)
#include<linux/mm.h>
#include<linux/sched.h>
#include<asm/system.h>
#include <asm/irq.h>
#include <asm/io.h>
#include <linux/interrupt.h>
#include <asm/uaccess.h>
#include <mach/hardware.h>
#include <linux/platform_device.h>
#include <linux/cdev.h>
#include <linux/miscdevice.h>
#include <mach/map.h>
#include <mach/regs-clock.h>
#include <mach/regs-gpio.h>
#include <plat/gpio-cfg.h>
#include <mach/gpio-bank-n.h>
#include <mach/gpio-bank-l.h>  //#define S3C64XX_GPLDAT (S3C64XX_GPL_BASE + 0x08)

#define DEVICE_NAME "buttons"
 
struct fasync_struct *async_queue; /*异步结构体指针，用于读*/
 
struct button_irq_desc{
    int irq;
    int number;
    char *name;
};

static struct button_irq_desc button_irqs[] = {
    {IRQ_EINT(0),  0, "KEY0"},
    {IRQ_EINT(1),  1, "KEY1"},
    {IRQ_EINT(2),  2, "KEY2"},
    {IRQ_EINT(3),  3, "KEY3"},
    {IRQ_EINT(4),  4, "KEY4"},
    {IRQ_EINT(5),  5, "KEY5"},
    {IRQ_EINT(19), 6, "KEY6"},
    {IRQ_EINT(20), 7, "KEY7"},
};
static volatile char key_values[] = {'0', '0', '0', '0', '0', '0', '0', '0'};
 
static DECLARE_WAIT_QUEUE_HEAD(button_waitq); /*定义一个新的等待队列的头*/
static volatile int ev_press = 0;             /*判断是否有按键按下的标志位*/
 
static irqreturn_t buttons_interrupt(int irq, void *dev_id) /*中断处理函数*/
{                                                   /*(void *)&button_irqs[i]申请中断时传进来的参数*/
    struct button_irq_desc *button_irqs = (struct button_irq_desc *)dev_id;
    int down;
    int number;
    unsigned tmp;
    udelay(0);
    number = button_irqs->number;
    switch(number) {
        case 0: case 1: case 2: case 3: case 4: case 5:
            tmp = readl(S3C64XX_GPNDAT);  //  
            down = !(tmp & (1<<number));
            break;
        case 6: case 7:
            tmp = readl(S3C64XX_GPLDAT); /*（返回）从映射的I/O空间读取32位4字节的数值 */
            down = !(tmp & (1 << (number + 5)));
            break;
        default:
            down = 0;
    }
     if (down != (key_values[number] & 1)) {
        key_values[number] = '0' + down;
        ev_press = 1;
        wake_up_interruptible(&button_waitq);   /*唤醒阻塞（睡眠）的读等待队列*/

        /*产生异步读信号通知相关进程 把要发送的SIGIO 信号发送出去*/
        if(async_queue){
               kill_fasync(&async_queue, SIGIO, POLL_IN);
         #ifdef DEBUG
               printk("<0>%s kill SIGIO\n", __func__);
         #endif
        }
    }
    /*  //means that we did have a valid interrupt and handled it
     *  #define IRQ_RETVAL(x) ((x) != IRQ_NONE )   //这个宏只是返回0或非0
     */
    return IRQ_RETVAL(IRQ_HANDLED);
}
 
static int s3c64xx_buttons_open(struct inode *inode, struct file *file)
{
    int i;
    int err = 0;
    for (i = 0; i < sizeof(button_irqs)/sizeof(button_irqs[0]); i++) {
        if (button_irqs[i].irq < 0) {
            continue;
        }                 /*中断号            处理函数           双延触发*/
        err = request_irq(button_irqs[i].irq, buttons_interrupt, IRQ_TYPE_EDGE_BOTH,    /*申请中断*/
                button_irqs[i].name, (void *)&button_irqs[i]);
                /*在proc/interrupts中显示中断拥有者   void *dev_id*/
        if (err)
            break;
    }
    if (err) {  /*出错处理 把之前分配的中断释放掉*/
        i--;
        for (; i >= 0; i--) {
            if (button_irqs[i].irq < 0){
                continue;
            }
            disable_irq(button_irqs[i].irq);
            free_irq(button_irqs[i].irq, (void *)&button_irqs[i]);
        }
        return -EBUSY;
    }
    ev_press = 1;
    return 0;
}

static int s3c64xx_buttons_close(struct inode *inode, struct file *file)
{
    int i;
    for (i = 0; i < sizeof(button_irqs)/sizeof(button_irqs[0]); i++) {
        if (button_irqs[i].irq < 0) {
            continue;
        }
        free_irq(button_irqs[i].irq, (void *)&button_irqs[i]);
    }
    return 0;
}

static int s3c64xx_buttons_read(struct file *filp, char __user *buff, size_t count, loff_t *offp)
{
    unsigned long err;
    if (!ev_press) {
        if (filp->f_flags & O_NONBLOCK)
            return -EAGAIN;
        else{
            /*这个宏：使调用进程在等待队上睡眠，一直到修改了给定条件为止*/
            wait_event_interruptible(button_waitq, ev_press);  /*直到ev_press 为 1*/
        }
    }
    ev_press = 0;
    err = copy_to_user((void *)buff, (const void *)(&key_values), min(sizeof(key_values), count));
    return err ? -EFAULT : min(sizeof(key_values), count);
}
 
static unsigned int s3c64xx_buttons_poll( struct file *file, struct poll_table_struct *wait)
{
    unsigned int mask = 0;
    poll_wait(file, &button_waitq, wait);
	if (ev_press){
		mask |= POLLIN | POLLRDNORM; //有键按下 标示数据可以读取
    }
    ev_press = 0;
    return mask;
}
 
/*增加支持异步通知的函数 在release 函数中调用 */
static int misc_key_fasync(int fd, struct file *filp, int mode)
{
    /*将文件从异步通知列表（相关进程列表）中删除*/
     return fasync_helper(fd, filp, mode, &async_queue);
}

/*文件释放函数*/
int misc_key_release(struct inode *inode, struct file *filp)
{
    /*将文件从异步通知列表中删除*/
    misc_key_fasync(-1, filp, 0);
    return 0;
}
 
static struct file_operations dev_fops = {
    .owner   = THIS_MODULE,
    .open    = s3c64xx_buttons_open,
    .release = s3c64xx_buttons_close,
    .read    = s3c64xx_buttons_read,
    .poll    = s3c64xx_buttons_poll,
    .fasync = misc_key_fasync, /*不要忘了在这里也要加上 与内核联系的接口*/
    .release = misc_key_release,
};

static struct miscdevice misc = { /*杂项字符设备结构体*/
    .minor = MISC_DYNAMIC_MINOR,  /*次设备号 表示自动分配*/
    .name  = DEVICE_NAME,         /*设备名*/
    .fops  = &dev_fops,           /*设备操作*/
};
 
static int __init dev_init(void)
{
    int ret;
    ret = misc_register(&misc);             /*注册一个混杂设备 在加载模块时会自动创建设备文件， 为主设备号为10的字符设备*/
    printk(DEVICE_NAME"\tinitialized\n");   /*无需mknod指令创建设备文件。因为misc_register()会调用class_device_create()或者device_create()*/
    return ret;
}

static void __exit dev_exit(void)
{
    misc_deregister(&misc);                 /*注销混杂设备 自动删除设备文件*/
}
 
module_init(dev_init);
module_exit(dev_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("FriendlyARM Inc.");<file_sep>/shell/2nd_week/for.sh
#!/bin/bash

for file in $HOME/share/*.c ../homework/*
do
	if [ -d "$file" ]
	then
		echo "$file is a directory"
	elif [ -f "$file" ]
	then
		echo "$file is a file"
	fi
done >output.txt

for ((i=0;i<4;i++))
do
	echo "the number is $i"
done

for state in Shanghai Beijing Guangzhou Zhanjiang "New York"
do
	echo "$state is the next place to go"
done | sort
<file_sep>/c/lrc/interface.h
/* ************************************************************************
 *       Filename:  interface.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月03日 星期一 03時39分16秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __INTERFACE_H__
#define __INTERFACE_H__

extern char move;

void show_musicbar();
void show_interface();
void show_pattern(const char *src[], int lines, int SROW, int COL);
void show_musiclist(char *plist[]);
void show_progressbar(int time, int timelag);
void show_lrcheader(char *pheader[]);
void show_time(int time, int maxtime);

#endif
<file_sep>/c/lrc/interface.c
/* ************************************************************************
 *       Filename:  interface.c
 *    Description:
 *        Version:  1.0
 *        Created:  2015年08月03日 星期一 03時39分07秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (),
 *        Company:
 * ************************************************************************/
#include "common.h"
#include "console.h"
#include "file.h"
#include "interface.h"

const char *logo[6] = {"．．＿＿＿＿．╭╮╭╮．＿＿＿＿",
					   "．．＿．．．╭－┴┴－★╮．．．",
					   "．．＿．．．│◎　　︵│＿．．．",
					   "．．．． ※※※╰○－－○╯※※※．",
					   "．．．．．．★ 欢迎光临 ★．．．",
					   "．．．．．．★ 无限透明 ★．．．",
					  };

const char *wave1[7]	= { "．．．．．．．．．★︵＿＿＿︵★．．．．．．．．",
							"．．．．．．．．．／●　　　●＼．．．．．．．．",
							"．．．．．．．．．︴≡　﹏　≡  ︴．．．．．．．．",
							"．．．．．．．．．＼＿＿＿＿ ／．．．．．．．．．",
							"．．．．．╭╧╮ ╭╧╮ ╭╧╮  ╭╧╮ ╭╧╮  ╭╧╮  ╭╧╮ ．．．",
							"．．．．．│我 |來  │幫  │你  │灌  水│  │哩．．．．",
							"．．．．．╘∞╛╘∞╛ ╘∞╛ ╘∞╛ ╘∞╛ ╘∞╛  ╘∞╛．．．",
					  };


void show_interface()
{
	int i = 0;

	system("clear");
	set_fg_color(COLOR_GREEN);
	printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
	printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
	printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
	//fflush(stdout);

	for(i=0;i<33;i++)
	{
		cusor_moveto(110, i+2); //
		printf("‖");
	}
	cusor_moveto(0, 34); //
	printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
	printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·");
	printf("═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");

	set_fg_color(COLOR_WHITE);

	show_musicbar();
	show_pattern(logo, 6, 2, 1);
	//show_pattern(wave, 7, 2, 58);
}

void show_musicbar()
{
	int i = 0;

	cusor_moveto(0, 9);
	set_fg_color(COLOR_GREEN);

	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");

	printf("·       >>  歌曲清单  <<      ·\n");

	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═");
	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");

	for(i=0;i<20;i++)
	{
		cusor_moveto(31, 12+i);
		printf("‖         ");
	}

	for(i=2;i<9;i++)
	{
		cusor_moveto(31, i);
		printf("|");
	}

	cusor_moveto(0, 32);
	printf("·═·═·═·═·═·═·═·═·═·═·═·═·═·═·═·\n");
	printf("·                             ·\n");

	set_fg_color(COLOR_RED);
	cusor_moveto(3, 33);
	printf("搜索：");
#if 0
	printf("■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n");
	printf("☆        >>  歌曲清单  <<     ★\n");
	printf("■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n");

	for(i=0;i<20;i++)
	{
		printf("                              □\n");
		printf("                              ■\n");
	}
	printf("■□■□■□■□■□■□■□■□■□■□■□■□■□■□■□■\n");
	printf("· 搜索：                      ·\n");
x
	for(i=32;i<110;i ++)
	{
		cusor_moveto(i, 9);
		printf("-");
		//printf("☆★");
	}
#endif
	fflush(stdout);
	set_fg_color(COLOR_WHITE);
	cusor_hide(); //隐藏光标
	//cusor_moveto(9, 33);
}

void show_pattern(const char *src[], int lines, int SROW, int COL)
{
	int i;

	for(i=0;i<lines;i++)
	{
		cusor_moveto(COL, SROW + i);
		printf("%s",src[i]);
	}
	fflush(stdout);
}

void show_musiclist(char *plist[])
{
	int i = 0;

	set_fg_color(COLOR_BLUE);
	for(i=0;plist[i] != NULL && i<20;i++)
	{
		cusor_moveto(0, 12+i);
		printf("%d. %s",i+1,plist[i]);
	}

	set_fg_color(COLOR_GREEN);
	for(i=0;i<20;i++)
	{
		cusor_moveto(31, 12+i);	//为了防止歌名覆盖了原来的界面
		printf("‖         ");
	}
	fflush(stdout);
	set_fg_color(COLOR_WHITE);
}

void show_lrcheader(char *pheader[])
{
	cusor_moveto(40, 3); //
	printf("歌名：%s\n",pheader[0]);
	cusor_moveto(40, 4); //
	printf("演唱：%s\n",pheader[1]);
	cusor_moveto(40, 5); //
	printf("作者：%s\n",pheader[2]);
	cusor_moveto(41, 14); //
	printf("○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○○");//
}
/*************************************************************************
*  函数名称：show_progressbar
*  功能说明：显示进度条
*  参数说明：time     歌曲从播放到当前的时间
*          timelag  进度条前进的时间间隔
*  函数返回：无
*************************************************************************/
char move = 1;
void show_progressbar(int time, int timelag)
{
	char *p = " ";
	if(time/(timelag * move) > 0 && move <= 61)
	{
		cusor_moveto(40+move, 14); //
		set_fg_color(COLOR_MAGENTA);
		printf("●");
		move++;
	}

	if(time%2 == 0)
	{
		set_fg_color(COLOR_GREEN);
	}
	else if(time%3 == 0)
	{
		set_fg_color(COLOR_RED);
	}
	else if(time%5 == 0)
	{
		set_fg_color(COLOR_CYAN);
	}
	else
	{
		set_fg_color(COLOR_YELLOW);
	}

	cusor_moveto(40+move, 14); //
	printf("●");
	set_fg_color(COLOR_WHITE);

	fflush(stdout);
}
/*************************************************************************
*  函数名称：show_time
*  功能说明：显示进度条
*  参数说明：time     歌曲从播放到当前的时间
*  函数返回：无
*************************************************************************/


void show_time(int time, int maxtime)
{
	int min = 0,sec = 0,time_left = 0;

	time_left = maxtime - time;

	if(time_left < 0) time_left = 0;

	min = time_left/1000/60; //单位：秒
	sec = time_left/1000%60;


	if(time_left%1000 > 500)
	{
		 sec += 1;
	}
	//cusor_moveto(55, 6); //
	//printf("%02d:%02d\n",min,sec);

	cusor_moveto(40, 6); //
	printf("时间：%02d:%02d\n",min,sec);

}
<file_sep>/work/test/pwm-beeper/pwm-beeper.c
/*************************************************************************
	> File Name: pwm-beeper.c
	>    Author: <NAME>
	>      Mail: <EMAIL>
	>  Datatime: Wed 09 Nov 2016 03:35:40 PM CST
 ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/input.h>

#define DEFAULT_DEV  "event0"


int main(int argc, char *argv[])
{
    int fd;
    int i;
    char dev[32] = "/dev/input/";
    struct input_event event;

    if(argc > 1)
        strcat(dev, argv[1]);
    else
        strcat(dev, DEFAULT_DEV);


    fd = open(dev, O_RDWR);
    if(fd < 0) {
        printf("Open %s failed\n", dev);
        return 1;
    }

    event.type = EV_SND;
    event.code = SND_TONE;
    event.value = 0;

    for(i = 1; i < 10; i++) {
        event.value = i * 100;
        printf("event0.value = %d\n", event.value);
        write(fd, &event,sizeof(event));
        //sleep(1);
    }

    event.value = 1004000;
    write(fd, &event, sizeof(event));

    while(1)
        sleep(1);
    close(fd);
    return 0;
}
<file_sep>/sys_program/3rd_day/wfifo.c
/* ************************************************************************
 *       Filename:  fifo.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月17日 14时26分03秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>


int main(int argc, char *argv[])
{
	int ret, fd;
	char buf[100] = "hello world";

	ret = mkfifo("./myfifo",0777);

	if(ret < 0)  perror("");

	printf("creat myfifo\n");
	fd = open ("./myfifo",O_WRONLY | O_NONBLOCK);
	printf("open success!  fd = %d\n",fd);

	while(1)
	{
		write(fd,buf,strlen(buf));
		printf("write\n");
		sleep(1);
	}
	return 0;
}
<file_sep>/c/homework/2nd_week/year.c
/* ************************************************************************
 *       Filename:  year.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年07月16日 星期四 09時17分41秒 HKT
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>

int months[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
int main(int argc, char *argv[])
{
	char i = 0;
	int countday = 0;
	int year = 0, month = 0, day = 0;
	
	printf("-----------------------------------------\n");

	again:
	printf("Please input the year, month, day.\n");
	scanf("%d %d %d",&year,&month,&day);

	if(year<0 || month<0 ||month >12 || day<0)
	{
		printf("error! input again!\n");
		goto again;
	}
	else
	{
		switch(month)
		{
			case  1:
			case  3:
			case  5:
			case  7:
			case  8:
			case 10:
			case 12:
					checkday1:
					if(day>31)
					{
						printf("Please input a day between 1 to 31!\n");
						scanf("%d",&day);
						goto checkday1;
					}
					break;

			case  4:
			case  6:
			case  9:
			case 11:
					checkday2:
					if(day>30)
					{
						printf("Please input a day between 1 to 30\n");
						scanf("%d",&day);
						goto checkday2;
					}
					break;
		}
	}



	if((year%4 == 0 && year%100 != 0) || (year%400 == 0))
	{
		printf("%d is a leap year!\n",year);
		months[1] = 29;
		if((month == 2) && (day > 29))
		{
			printf("Please input a day between 1 to 29!\n");
			scanf("%d",&day);
		}
	}
	else
	{

		printf("%d is not a leap year!\n",year);
		months[1] = 28;
		if((month == 2) && (day > 28)) 
		{		
			printf("Please input a day between 1 to 28!\n");
			scanf("%d",&day);
		}
	}
	
	for(i=0;i<month-1;i++)
	{
		countday += months[i];
	}

	countday += day;
	
	printf("The day you input is the %d'th day of %d.\n",countday,year);
	printf("-------------- %d.%d.%d ----------------\n",year,month,day);
	return 0;
}


<file_sep>/sys_program/3rd_day/homework/expr/expr.c
/* ************************************************************************
 *       Filename:  expr.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月17日 19时28分44秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char *argv[])
{
	pid_t pid;
	int fd[2];
	char cmd[128] = "";
	char buf[64] = "";
	
	if(pipe(fd) < 0)
	{
		perror("");
	}
		
	while(1)
	{	
		pid = vfork();
		
		if(pid < 0) perror("");
		
		else if(pid == 0)
		{
			int len = 0;
			printf("Please input a cmd: ");		
			fgets(cmd,sizeof(cmd),stdin);
			
			len = strlen(cmd);
						
			if(len > 1) 
				cmd[len-1] = '\0'; //把获取的字符后面的\n转化成 '\0'
			else  
				exit(0);
			
			dup2(fd[1], 1); //			
	
			execl("/bin/sh","sh","-c",cmd,NULL);
			//_exit(1);
		}
		else //
		{
			read(fd[0],buf,sizeof(buf));
			printf("%s",buf);
			//wait(NULL);
		}	
	}
	
	return 0;
}



<file_sep>/work/debug/a8/gpio_i2c/bma150_i2c.c
#include <linux/module.h>
#include <linux/ioport.h>	/* resource */
#include <linux/irq.h>	/* IRQ_EINT(23) */
#include <linux/gpio.h>	/* S5PV210_GPH3(0) */
#include <linux/platform_device.h> /* platform_device_register() */
#include <linux/gpio_keys.h>
#include <linux/input.h>
#include <linux/miscdevice.h>
#include <linux/delay.h>


#define BMA150_ADDR			0x38
#define BMA150_WRITE			0x00
#define BMA150_READ			0x01

#define clk_out()		s3c_gpio_cfgpin(S5PV210_GPD1(5),S3C_GPIO_OUTPUT)
#define dat_out()		s3c_gpio_cfgpin(S5PV210_GPD1(4),S3C_GPIO_OUTPUT)
#define dat_in()		s3c_gpio_cfgpin(S5PV210_GPD1(4),S3C_GPIO_INPUT)
#define clk_clear()	gpio_set_value(S5PV210_GPD1(5), 0)
#define clk_set()		gpio_set_value(S5PV210_GPD1(5), 1)
#define dat_clear()	gpio_set_value(S5PV210_GPD1(4), 0)
#define dat_set()		gpio_set_value(S5PV210_GPD1(4), 1)
#define get_data_in()	gpio_get_value(S5PV210_GPD1(4))
#define demo_i2c_delay()		udelay(50)

static void demo_i2c_send_byte(unsigned char data)
{
	signed char i;

	dat_out();
	clk_clear();
	for(i=7;i>=0;i--){
		if(data&(1<<i))
			dat_set();
		else
			dat_clear();
		demo_i2c_delay();
		clk_set();
		demo_i2c_delay();/* 对方读取数据 */
		clk_clear();
	}
}
static unsigned char demo_i2c_receive_byte(void)
{
	signed char i;
	unsigned char data = 0;

	dat_in();
	clk_clear();
	for(i=7;i>=0;i--){
		demo_i2c_delay();
		clk_set();
		demo_i2c_delay();
	//	data = data<<1;
		data |= get_data_in()<<i;
		clk_clear();
	}
	return data;
}
static void demo_i2c_send_ack(unsigned char ack)
{
	dat_out();
	clk_clear();
	if(ack)
		dat_set();
	else
		dat_clear();
	demo_i2c_delay();
	clk_set();
	demo_i2c_delay();/* 对方读取应答 */
	clk_clear();
}
static unsigned char demo_i2c_receive_ack(void)
{
	unsigned char ack = 0;

	dat_in();
	clk_clear();
	demo_i2c_delay();
	clk_set();
	demo_i2c_delay();
	ack = get_data_in();
	clk_clear();
	return ack;
}
static void demo_i2c_start(void)
{
	dat_out();
	dat_set();
	clk_set();
	demo_i2c_delay();
	dat_clear();
	demo_i2c_delay();
	clk_clear();	
}
static void demo_i2c_stop(void)
{
	dat_out();
	dat_clear();
	clk_set();
	demo_i2c_delay();
	dat_set();
	demo_i2c_delay();
	clk_clear();	
}

static void demo_i2c_init(void)
{
	clk_out();
	dat_out();
	clk_clear();
	dat_clear();
}
static void demo_i2c_send(unsigned char reg,unsigned char *buff,int len)
{
	int i = 0;
	demo_i2c_start();
	demo_i2c_send_byte((BMA150_ADDR<<1)|BMA150_WRITE);/* 发送地址 */
	demo_i2c_receive_ack();
	demo_i2c_send_byte(reg);
	demo_i2c_receive_ack();
	
	while(len--){
		demo_i2c_send_byte(buff[i++]);
		demo_i2c_receive_ack();
	}
	demo_i2c_stop();
}
static void demo_i2c_receive(unsigned char reg,unsigned char *buff,int len)
{
	int i = 0;
	demo_i2c_start();
	demo_i2c_send_byte((BMA150_ADDR<<1)|BMA150_WRITE);/* 发送地址 */
	demo_i2c_receive_ack();
	demo_i2c_send_byte(reg);
	demo_i2c_receive_ack();
	demo_i2c_stop();
	
	demo_i2c_start();
	demo_i2c_send_byte((BMA150_ADDR<<1)|BMA150_READ);/* 发送地址 */
	demo_i2c_receive_ack();
	while(len--){
		buff[i++] = demo_i2c_receive_byte();
		if(len == 0)
			demo_i2c_send_ack(1);
		else
			demo_i2c_send_ack(0);
	}
	demo_i2c_stop();
}
static int demo_bma150_open(struct inode *pinode, struct file *pfile)
{
	unsigned char chip_id;
	demo_i2c_receive(0x00,&chip_id,1);
	printk("%s,%d,id = %d\n",__FUNCTION__,__LINE__,chip_id);
	
	return 0;
}
static ssize_t demo_bma150_read(struct file *pfile, char __user *buffer, size_t count, loff_t *offset)
{
	unsigned char data[6];
	signed short x,y,z;
	
	demo_i2c_receive(0x02,data,6);
	x = (data[0]>>6)|(data[1]<<2);
	y = (data[2]>>6)|(data[3]<<2);
	z = (data[4]>>6)|(data[5]<<2);
	
	x = (signed short)(x<<6)>>6;/* 符号位扩展 */
	y = (signed short)(y<<6)>>6;
	z = (signed short)(z<<6)>>6;
	printk("x=%d,y=%d,z=%d\n",x,y,z);
	return 1;
}
static struct file_operations bma150_fops = {
	.owner = THIS_MODULE,
	.open = demo_bma150_open,
	.read = demo_bma150_read,
};
static struct miscdevice bma150_ops = {
	.minor = MISC_DYNAMIC_MINOR,
	.name = "bma150_dev",
	.fops = &bma150_fops,
};
static int __init demo_bma150_init(void)
{
	printk("%s,%d\n",__FUNCTION__,__LINE__);
	demo_i2c_init();
	return misc_register(&bma150_ops);
}
static void __exit demo_bma150_exit(void)
{
	printk("%s,%d\n",__FUNCTION__,__LINE__);
	misc_deregister(&bma150_ops);
}

module_init(demo_bma150_init);
module_exit(demo_bma150_exit);
MODULE_LICENSE("GPL");
<file_sep>/work/debug/ingenic/pe10/test_pe10.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#define PE10_IOC_MAGIC     'p'
#define PE10_SET_ON_TIMER  _IO(PE10_IOC_MAGIC, 1) 
#define PE10_SET_OFF_TIMER _IO(PE10_IOC_MAGIC, 2)

int main(int argc, char *argv[])
{
	char cmd[64] = {0};
	char *pcmd[5] = {NULL};
	int fd = 0, arg = 0, i = 0;
	
	fd = open("/dev/pe10_gpio", O_RDWR);
	if(fd <0){
		printf("open '/dev/pe10_gpio' failed\n");
		return -1;
	}
	
	while(1) {
		bzero(cmd, sizeof(cmd));
		
		printf("\033[31mCMD: \033[0m");
		fflush(stdout);
		fgets(cmd, sizeof(cmd), stdin);
		cmd[strlen(cmd) - 1] = 0;
		
		if(strlen(cmd) == 0)
			continue;
		i = 0;
		pcmd[i++] = strtok(cmd, " ");
		if(pcmd[0] != NULL) {
			pcmd[i++] = strtok(NULL, " ");
		}
		
		if(strcmp(pcmd[0], "on") == 0) {
			if(pcmd[1] != NULL) {
				arg = atoi(pcmd[1]);
				printf("set on time as %d\n", arg);
				ioctl(fd, PE10_SET_ON_TIMER, arg);	
			}
			else
				printf("set on time : on <value>\n");
		}
		else if(strcmp(pcmd[0], "off") == 0) {
			if(pcmd[1] != NULL) {
				arg = atoi(pcmd[1]);
				printf("set off time as %d\n", arg);
				ioctl(fd, PE10_SET_OFF_TIMER, arg);
			}
			else
				printf("set off time: off <value>\n");
		}
		else if(strcmp(pcmd[0], "help") == 0) {
			printf("\033[34mset on time : on <value>\033[0m\n");
			printf("\033[34mset off time: off <value>\033[0m\n");
			printf("\033[34msetting exit: q\n");		
		}
		else if(strcmp(pcmd[0], "q") == 0) {
			break;
		}
		else {
			printf("wrong cmd, input 'help' to get help.\n");
		}
	}
	
	close(fd);
	return 0;
}

<file_sep>/java/Test.java
/*
public class Test {
	void max(int a , int b) {
		System.out.println( a > b ? a : b );
	}
	
	void max(short a , short b) {
		System.out.println("short");
		System.out.println( a > b ? a : b );
	}
	
	void max(float a, float b) {
		System.out.println( a > b ? a : b );
	}
	
	public static void main(String[] args) {
		Test t = new Test();
		t.max(3, 4);
		//short a = 3;
		//short b = 4;
		t.max((short)3, (short)4);
	}
}*/
public class Test {
	public static void main(String[] args) {
		
		int i,j;
		int a[][]={{1,2},{3,4,5},{6},{7,8,9,0,}};
		String s[][];
		s = new String[3][];
		s[0] = new String[2];
		s[1] = new String[3];
		s[2] = new String[4];
		
		for(i=0;i < a.length;i++) {
			for(j=0; j < a[i].length;j++) {
				System.out.print("a["+i+"]["+j+"] = "+a[i][j]+"  ");
			}
			System.out.println();
		}
		
		for(i=0;i < s.length;i++) {
			for(j=0; j < s[i].length;j++) {
				s[i][j] = new String("ÎÒµÄÎ»ÖÃÊÇ£º"+i+","+j+"  ");
			}
		}

		for(i=0;i < s.length;i++) {
			for(j=0; j < s[i].length;j++) {
				System.out.print(s[i][j]+"  ");
			}
			System.out.println();
		}
	}
}<file_sep>/gtk/1. base/02_image/demo.c
#include <gtk/gtk.h>

typedef struct _Window
{
	GtkWidget *main_window;
	GtkWidget *table;
	GtkWidget *image;
	GtkWidget *button_previous;
	GtkWidget *button_next;
}WINDOW;

// 给创建好的image重新设计一张图片
void load_image(GtkWidget *image, const char *file_path, const int w, const int h )
{
	gtk_image_clear( GTK_IMAGE(image) );        // 清除图像
	GdkPixbuf *src_pixbuf = gdk_pixbuf_new_from_file(file_path, NULL);	// 创建图片资源
	GdkPixbuf *dest_pixbuf = gdk_pixbuf_scale_simple(src_pixbuf, w, h, GDK_INTERP_BILINEAR); // 指定大小
	gtk_image_set_from_pixbuf(GTK_IMAGE(image), dest_pixbuf); // 图片控件重新设置一张图片(pixbuf)
	g_object_unref(src_pixbuf);		// 释放资源
	g_object_unref(dest_pixbuf);	// 释放资源
}

// 根据图片路径创建一个新按钮，同时指定图片大小
GtkWidget *create_button_from_file(const char *file_path, const int w, const int h)
{
	GtkWidget *temp_image = gtk_image_new_from_pixbuf(NULL);
	load_image(temp_image, file_path, w, h);
	
	GtkWidget *button = gtk_button_new(); 					// 先创建空按钮
	gtk_button_set_image(GTK_BUTTON(button), temp_image);	// 给按钮设置图标
	gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);	// 按钮背景色透明
	
	return button;
}

// 按钮的回调函数
void deal_switch_image(GtkWidget *button, gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;
	
	if(button == p_temp->button_previous){		// 上一张
		printf("p_temp->button_previous\n");
	}else if(button == p_temp->button_next ){	// 下一张
		printf("p_temp->button_next\n");
	}
}

void window_demo(gpointer data)
{
	WINDOW *p_temp = (WINDOW *)data;
	
	// 主窗口
	p_temp->main_window = gtk_window_new(GTK_WINDOW_TOPLEVEL);		 	// 创建主窗口
	gtk_window_set_title(GTK_WINDOW(p_temp->main_window), "image");	 	// 设置窗口标题
	gtk_window_set_position(GTK_WINDOW(p_temp->main_window), GTK_WIN_POS_CENTER); // 设置窗口在显示器中的位置为居中
	gtk_widget_set_size_request(p_temp->main_window, 800, 480);		 	// 设置窗口的最小大小
	gtk_window_set_resizable(GTK_WINDOW(p_temp->main_window), FALSE); 	// 固定窗口的大小
	g_signal_connect(p_temp->main_window, "destroy", G_CALLBACK(gtk_main_quit), NULL); 
	
	// 表格布局
	p_temp->table = gtk_table_new(7, 7, TRUE);	 					      // 表格布局容器
	gtk_container_add(GTK_CONTAINER(p_temp->main_window), p_temp->table); // 容器加入窗口
	
	// 图片控件
	p_temp->image = gtk_image_new_from_pixbuf(NULL);		// 创建图片控件
	load_image(p_temp->image, "./image/1.jpg", 500, 450);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->image, 1, 6, 1, 6);	// 把图片控件加入布局

	
	// 按钮
	p_temp->button_previous = create_button_from_file("./image/previous.bmp", 80, 80);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_previous, 1, 2, 6, 7);
	g_signal_connect(p_temp->button_previous, "clicked", G_CALLBACK(deal_switch_image), p_temp);
	
	p_temp->button_next = create_button_from_file("./image/next.bmp", 80, 80);
	gtk_table_attach_defaults(GTK_TABLE(p_temp->table), p_temp->button_next, 5, 6, 6, 7);
	g_signal_connect(p_temp->button_next, "clicked", G_CALLBACK(deal_switch_image), p_temp);
	
	gtk_widget_show_all(p_temp->main_window);
	
}

int main(int argc, char *argv[])
{
	gtk_init(&argc, &argv);		// 初始化
	
	WINDOW window;
	window_demo(&window);

	gtk_main();			// 主事件循环

	return 0;
}<file_sep>/work/test/cim_test-zmm220/cim.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fb.h>
#include <asm/mman.h>
#include <sys/mman.h>
#include <string.h>

#include "cim.h"
#include "arca.h"


#define CIM0308DEV  	"/dev/cim0"
#define CIM367DEV      "/dev/cim1"

#define    GC0308   1
#define    MT367    2


/*
 * IOCTL_XXX commands
 */
#define IOCTL_READ_REG      0 /* read sensor registers */
#define IOCTL_WRITE_REG     1 /* write sensor registers */
#define IOCTL_READ_EEPROM   2 /* read  sensor eeprom */
#define IOCTL_WRITE_EEPROM  3 /* write sensor eeprom */
#define IOCTL_SET_IMG_FORMAT	8	//arg type:enum imgformat
#define IOCTL_SET_TIMING_PARAM	9	// arg type: timing_param_t *
#define IOCTL_SET_IMG_PARAM	10	// arg type: img_param_t *
#define IOCTL_CIM_READ_REG	211	


static int cim0308_fd=-1;
static int cim367_fd=-1;


int set_timing_param(int id,TIMING_PARAM *timing)
{
	printf(" %s  %d \n",__func__,__LINE__);
	switch(id)
	{
	case GC0308:	
		if (ioctl(cim0308_fd, IOCTL_SET_TIMING_PARAM, (unsigned long)timing) < 0){
			printf("set_timing_param failed!\n");
			return 0;
		}
		break;
		
	case MT367:		
		if (ioctl(cim367_fd, IOCTL_SET_TIMING_PARAM, (unsigned long)timing) < 0){
			printf("set_timing_param failed!\n");
			return 0;
		}
		break;
	default:
		return 0;
	}
	
	return 1;
	
}

int set_img_format(int fd, img_format_t format)
{
	if (ioctl(fd, IOCTL_SET_IMG_FORMAT, &format) < 0) {
		printf("set_img_format failed!\n");
		return 0;
	}
	return 1;
}

int set_img_param(int fd,IMG_PARAM *img)
{
	printf(" %s  %d \n",__func__,__LINE__);
	if (ioctl(fd, IOCTL_SET_IMG_PARAM, (unsigned long)img) < 0) {
		printf("set_img_param failed!\n");
		return 0;
	}
	return 1;
}

int cim_open(int id,int width, int height, int bpp)
{
	IMG_PARAM param;
	printf(" %s  %d \n",__func__,__LINE__);
	switch(id)
	{
		case GC0308:
		{
			if(cim0308_fd>0) cim_close(GC0308);
			cim0308_fd = open(CIM0308DEV, O_RDWR);
			if(cim0308_fd < 0)
			{
				printf("Error opening %s \n",CIM0308DEV);
				return -1;
			}
			printf("open %s  success \n",CIM0308DEV);

			if (set_img_format(cim0308_fd, RGB565) == 0)
				return -1;

			param.width = width;
			param.height = height;
			param.bpp = bpp;
			
			if (set_img_param(cim0308_fd,&param) == 0)
				return -1;

			return cim0308_fd;
		}
		case MT367:
		{
			if(cim367_fd>0) cim_close(MT367);
			cim367_fd = open(CIM367DEV, O_RDWR);
			if(cim367_fd < 0)
			{
				printf("Error opening %s \n",CIM367DEV);
				return -1;
			}

			if (set_img_format(cim367_fd, YUV422_SEP) == 0)
				return -1;

			param.width = width;
			param.height = height;
			param.bpp = bpp;

			if (set_img_param(cim367_fd,&param) == 0)
				return -1;
			
			return cim367_fd;
		}
			
	}
	return -1;
}


/* Read a frame of image */
int cim_read(unsigned char id,unsigned char *buf, int frame_size)
{		
	switch(id)
	{
		case GC0308:
			return read(cim0308_fd, buf, frame_size);
		case MT367:
			return read(cim367_fd, buf, frame_size);
		default:
			return 0;
	}
}


void cim_close(int id)
{
	switch(id)
	{
		case GC0308:
			close(cim0308_fd);
			cim0308_fd = -1;
		 break;
		case MT367:
			close(cim367_fd);
			cim367_fd = -1;
		break;
		default:
			break;
	}

}

void  *cim_mmap(int id, unsigned int size)
{
	caddr_t  mem;
	switch(id){
	case GC0308:
		if ((mem = mmap(0, size, PROT_READ | PROT_WRITE,
						  MAP_SHARED, cim0308_fd, 0)) == MAP_FAILED) {
			perror(__func__);
			return NULL;
		}
		
		break;
		
	case MT367:
		if ((mem = mmap(0, size, PROT_READ | PROT_WRITE,
						  MAP_SHARED, cim367_fd, 0)) == MAP_FAILED) {
			perror(__func__);
			return NULL;
		}
		
		break;
		
	default:
			return NULL;
	 }
	
	return (mem);
}


<file_sep>/network/2nd_day/tftp_pull.c
/******************************************************************************
  文 件 名   : tftp_client.c
  版 本 号   : 
  作    者   : 
  生成日期   : 2015年9月1日
  最近修改   :
  功能描述   : TFTP 客户端
******************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>

typedef enum _mode
{
	pull = 0,
	push = 1,
}MODE;

int main(int argc, char *argv[])
{
	fd_set rfds;
	MODE flag;
	struct timeval tv;
	FILE *fp = NULL;
	char file_name[128] = "";
	char server_ip[16]  = "10.221.2.12";
	unsigned char cmd[128]  = "", msg[1024] = "";
	int sockfd = 0, ask = 0, ret = 0;
	int cmd_len = 0, msg_len = 0, snd_len = 0;
	unsigned short port = 69; // TFTP服务器的固定端口

	if(argc < 2)
	{
		printf("parameter too little!\n");
		printf("please run again: ./elf  pull/push  filename\n");
		exit(-1);
	}
	strcpy(file_name, argv[2]);
	printf("file_name = %s\n",file_name);

	//创建一个套接字
	sockfd = socket(AF_INET, SOCK_DGRAM, 0);

	//配置服务器的地址
	struct sockaddr_in server_addr;
	socklen_t server_len = sizeof(server_addr);
	bzero(&server_addr, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(port);//服务器的端口
	inet_pton(AF_INET, server_ip ,&server_addr.sin_addr.s_addr);//服务器的IP

	if(strcmp("pull", argv[1]) == 0) //下载
	{
		flag = pull;
		printf("pull>>>\n");
		cmd_len = sprintf(cmd, "%c%c%s%c%s%c", 0, 1, file_name, 0, "octet", 0); //octet: 二进制模式；netascii: 文本模式
		sendto(sockfd, cmd, cmd_len, 0,\
		      (struct sockaddr *)&server_addr, sizeof(server_addr));

		fp = fopen(file_name, "wb");
		if(fp == NULL)
		{
			printf("%s is not exist!!\n", file_name);
			exit(-1);
		}
	}
	else if(strcmp("push", argv[1]) == 0) //上传
	{
		flag = push;
		printf("push>>>\n");
		cmd_len = sprintf(cmd, "%c%c%s%c%s%c", 0, 2, file_name, 0, "octet", 0);
		sendto(sockfd, cmd, cmd_len, 0,\
		      (struct sockaddr *)&server_addr, sizeof(server_addr));

		fp = fopen(file_name, "rb");
		if(fp == NULL)
		{
			printf("%s is not exist!!\n", file_name);
			exit(-1);
		}
	}
	else
	{
		printf("Err: argv[1] != pull/push\n");
		exit(-1);
	}

	while(1)
	{
		bzero(msg, sizeof(msg));
		bzero(&server_addr, sizeof(server_addr));

		FD_ZERO(&rfds);
		FD_SET(sockfd, &rfds);

		/* Wait up to one second. */
		tv.tv_sec  = 1;
		tv.tv_usec = 0;

		ret = select(FD_SETSIZE, &rfds, NULL, NULL, &tv);

		if(ret < 0) perror("");

		if(FD_ISSET(sockfd, &rfds))
		{
			msg_len = recvfrom(sockfd, msg, sizeof(msg), 0, \
							  (struct sockaddr *)&server_addr, &server_len);
		}
		else
		{
			printf("time out, continue!\n");
			continue;
		}

		if(flag == pull) //下载
		{
			if(msg[1] == 3) //数据确认
			{
				//printf("ask_no = %d&&&&&&&&&\n",msg[3]);
				if(ask != msg[3])
				{
					ask = msg[3];
					//把接收的数据写入文件
					fwrite((msg+4), msg_len - 4, 1, fp);
				}

				if(msg_len < 516)
				{
					//fclose(fp);
					break;
				}

				msg[1] = 4; //数据确认操作码

				//发送确认信号
				sendto(sockfd, msg, 4, 0,\
					  (struct sockaddr *)&server_addr, sizeof(server_addr));
				printf("ask_no = %d&&&&&&&&&\n",msg[3]);
			}
		}
		else if(flag == push)
		{
			if(msg_len == 4)
			{
				//bzero(msg, sizeof(msg));
				msg_len = fread((msg+4), 1, 512, fp);//用fread((msg+4), 512, 1, fp);只能读到一个字节
				//printf("read_len = %d\n",msg_len);
				if(msg_len == 0)
				{
					printf("push %s finish!\n",file_name);
					break;
				}

				ask++;
				msg[0] = 0;
				msg[1] = 3;
				msg[2] = ask/256;
				msg[3] = ask%256;

				printf("msg[1]=%d msg[2~3]=%d\n",msg[1], msg[2] * 256 + msg[3]);
				//发送数据
				snd_len = sendto(sockfd, msg, msg_len+4, 0,\
								(struct sockaddr *)&server_addr, sizeof(server_addr));

				if(snd_len != msg_len+4)
				{
					printf("Err: send msg to server error!\n");
				}
			}
		}
	}
	fclose(fp);
	close(sockfd);
	return 0;
}
<file_sep>/sys_program/3rd_day/pipe.c
/* ************************************************************************
 *       Filename:  pipe.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月17日 10时18分41秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


int main(int argc, char *argv[])
{
	int fd[2];
	char buf[100] = "Hello world";
	pid_t pid;

	if(pipe(fd) < 0)
	{
		perror("");
	}
	printf("fd[0] = %d  fd[1] = %d\n",fd[0],fd[1]);

	pid = fork();

	if(pid <0 )
	{
		perror("");
	}
	else if(pid == 0)
	{
		write(fd[1],buf,strlen(buf));
		exit(1);
	}
	else
	{
		wait(NULL);

		memset(buf,0,sizeof(buf));
		read(fd[0],buf,sizeof(buf));

		printf("buf = %s\n",buf);
	}
	return 0;
}
<file_sep>/sys_program/player/src/inc/mplayer_ui.h
#ifndef __MPLAYER_UI_H__
#define __MPLAYER_UI_H__

//extern MPLAYER mplayer;
extern SunGtkCList *musiclist;

extern void window_init(MPLAYER *pm);
extern void mplayer_ui_show(int argc, char *argv[], MPLAYER *pm);

#endif
<file_sep>/c/practice/sort/quicksort.c
#include <stdio.h>

void swap(int *a,int *b)
{                            /*序列中元素位置的交换*/
	int tmp;
	tmp = *a;
	*a = *b;
	*b = tmp;
}

void print(int k[])
{
	int i;
	static int cont = 0;

	cont++;
	printf("\n第 %d 次:   ",cont);
	for(i=0;i<10;i++)
	{
		printf("%d ",k[i]);
	}
	printf("\n");

}
void quicksort(int k[], int start_num, int end_num)
{                            /*快速排序*/
	int i, j;
	
	if(start_num < end_num)
	{
		i = start_num;
		j = end_num + 1;
		
		while(1)
		{
			do{
				i++;
			}while( !(k[i] >= k[start_num] || i == end_num));  //从第一个开始求出第一个大于基准值的元素位置i
			
			do{
				j--;
			}while( !(k[j] <= k[start_num] || j == start_num)); //从最后开始求出第一个小于基准值的元素位置j
			
			if(i < j) swap(&k[i], &k[j]);
			else break;
		}
		
		swap(&k[start_num], &k[j]);
		quicksort(k, start_num, j-1);   /*递归排序基准元素前面的子序列*/
		quicksort(k, j+1, end_num);     /*递归排序基准元素后面的子序列*/
	}

}

int main()
{
    int k[10]={2,5,6,3,7,8,1,9,12,0} , i;
    printf("The data array is\n") ;
    for(i=0;i<10;i++)                        	/*显示原序列之中的元素*/
        printf("%d ",k[i]);
	printf("\n");

    quicksort(k,0,9);                        	/*快速排序*/
    printf("\nThe result of quick sorting for the array is\n");
    for(i=0;i<10;i++)                        	 /*显示排序后的结果*/
        printf("%d ",k[i]);
	printf("\n");

	return 0;
}


<file_sep>/work/test/pwm-led/pwm-led.sh
#!/bin/sh

cd /sys/class/leds/led_state/

val=`cat brightness`

for i in $(seq $val 254)
do
    echo $i
    echo $i > brightness
    usleep 20000
done

for i in $(seq 254 0)
do
    echo $i
    echo $i > brightness
    usleep 20000
done
<file_sep>/work/test/netlink/Makefile
ifneq ($(KERNELRELEASE),)
	obj-m := netlink_kernel.o

else
	CC=mips-linux-gnu-gcc
	KERNELDIR ?= ~/work/sz-halley2/kernel
	PWD := $(shell pwd)
default:
	$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
	rm -rf *.o *.mod.c *.order *.symvers .*.cmd .tmp*
clean:
	rm -f *.o *~ *.ko  *.mod.c *.mod.o *.symvers *.order
endif

<file_sep>/network/sockets/UDPEchoServer.c
/*************************************************************************
	> File Name: UDPEchoServer.c
	> Author: 
	> Mail: 
	> Created Time: Mon 16 May 2016 06:09:10 PM CST
 ************************************************************************/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include "Practical.h"

int main(int argc, char *argv[])
{
   if(argc != 2)
       DieWithUserMessage("Parameter(s)", "<Server Port/Service>");

   char *service = argv[1];


}

<file_sep>/c/practice/3rd_week/mylink/Makefile
link: main.c link.c
	gcc -o link main.c link.c
clean:
	rm link
<file_sep>/gtk/1. base/06_timeout/timeout.c
﻿#include <gtk/gtk.h>
#include <stdlib.h> 
#include <string.h>

guint timer;	// 定时器id

/* 功能: 		设置控件字体大小
 * widget: 		需要改变字体的控件
 * size: 		字体大小
 * is_button: 	TRUE代表控件为按钮，FALSE为其它控件
 */
void set_widget_font_size(GtkWidget *widget, int size, int is_button)
{
	GtkWidget *labelChild;  
	PangoFontDescription *font;  
	gint fontSize = size;  
  
	font = pango_font_description_from_string("Sans");//"Sans"字体名   
	pango_font_description_set_size(font, fontSize*PANGO_SCALE);//设置字体大小   
	
	if(is_button){
		labelChild = gtk_bin_get_child(GTK_BIN(widget));//取出GtkButton里的label  
	}else{
		labelChild = widget;
	}
	
	//设置label的字体，这样这个GtkButton上面显示的字体就变了
	gtk_widget_modify_font(GTK_WIDGET(labelChild), font);
	pango_font_description_free(font);
}

/* 功能:  定时器处理函数
 * label: 主要用于显示数字
 */
gboolean deal_time( GtkWidget* label ) 
{
	char buf[5] = "";
	static int num = 10;
	num--;
	sprintf(buf, "%d", num);
	gtk_label_set_text(GTK_LABEL(label), buf);
	
	if(0 == num){
		num = 11;
		//g_source_remove(timer); // 移除定时器 
	}
	
	return TRUE;
}

int main( int argc, char *argv[])
{
	gtk_init(&argc, &argv);
	
	/////////////////主窗口操作
	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title(GTK_WINDOW(window), "倒计时");
	gtk_container_set_border_width(GTK_CONTAINER(window), 0);
	//设置窗口默认大小，设置一个最小大小
	gtk_window_set_default_size(GTK_WINDOW(window), 320, 400);
	//设置窗口在显示器中的位置为居中。
	gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
	g_signal_connect( G_OBJECT(window), "destroy",
		G_CALLBACK(gtk_main_quit), NULL ); //按关闭按钮可以把程序中断
	
	// 倒计时显示区域
	GtkWidget *label = gtk_label_new("10");		// label的创建
	set_widget_font_size(label, 230, FALSE);	// 设置label的字体大小
	gtk_container_add(GTK_CONTAINER(window), label);
	
	// 定时器的创建
	timer = g_timeout_add(500, (GSourceFunc)deal_time, (gpointer)label);
	
	gtk_widget_show_all(window); // 显示所有部件
	
	gtk_main();
	
	return 0;
}<file_sep>/sys_program/player/src/mplayer_pthread.c
/* ************************************************************************
 *       Filename:  mplayer_process.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月23日 18时05分21秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include "common.h"
#include "file.h"
#include "link.h"
#include "process_lrc.h"
#include "mplayer_control.h"
#include "mplayer_pthread.h"


SONG song;


void mplayer_init(MPLAYER *pm)
{
	FILE *fp = NULL;
	int i = 0, ret = 0;
	char buf[128];

	song.song_src = (char *)get_musiclist(&song.psong_list, &song.count);
	if(song.count > 0)
	{
		song.search = NULL;
		song.search = (char *)malloc(song.count + 1);
		if(song.search == NULL) perror("");	
		bzero(song.search, song.count+1);
	}
	
	pm->playflag  = playing;  //暂停
	pm->playmode  = list_loop;//列表顺序播放模式 
	pm->soundflag = beam;     //播音

	bzero(song.name, sizeof(song.name));
	fp = fopen(".song", "r");
	if(fp != NULL)
	{
		fread(buf, sizeof(buf), 1, fp);
		
		if(get_songname(song.name,buf) == 0)
		{
			printf("get_songname = %s\n",song.name);
			for(i = 0;i < song.count; i++)
			{
				if(strcmp(song.name,song.psong_list[i]) == 0)
				{
					song.now = i;
					song.old = i;				
					break;
				}
			}
			if(i == song.count) 
			{
				song.now = 0;   
				song.old = 0;
				strcpy(song.name, song.psong_list[0]);
			}
		}
	}
	else
	{
		song.now = 6;  
		song.old = 6;
		strcpy(song.name, song.psong_list[6]);
	}
	song.keyflag = init;
	song.endflag = FALSE;
	
	//?
	ret = pipe(pm->fd);   
	if(ret < 0) perror("pipe");

	unlink("./.cmd_fifo");      //
	mkfifo("./.cmd_fifo",0666); //
	pm->fd_pipe = open("./.cmd_fifo", O_RDWR);	
	//write(pm->fd_pipe, "pause\n", strlen("pause\n"));//
	
	//??
	sem_init(&song.sem_keyflag, 0, 1);
	sem_init(&song.sem_setsong, 0, 1);

	//?
	pthread_mutex_init(&pm->mutex, NULL);
}

int mplayer_process(MPLAYER *pm)
{		
	pm->pid = fork();//
	
	if(pm->pid < 0)
	{
		perror("fork:");
		return(-1);
	}	
	
	if(pm->pid == 0)
	{
		//char buf[256] = "./music/";
		//printf("in son process  >> song_name = %s\n",song.name);
		//strcat(buf,song.name);		
		 
		if( dup2(pm->fd[1], 1) < 0) perror("dup2");//??

		printf("start mplayer now!\n");
		
		//启动mplayer		
		execlp("mplayer",		      
		       "mplayer",			  
	           "-slave", "-quiet","-idle",			  
		       "-input", "file=./.cmd_fifo",			   
		       "./music/login.wav", NULL);
		exit(0);		
	}

	return 0;
}

void gtk_thread_init(void)
{
	if( FALSE == g_thread_supported() )	
	{  
		g_thread_init(NULL);
	}
	gdk_threads_init();
}

void *pthread_show_lrc(void *agr)
{
	MPLAYER *pm = (MPLAYER *)agr;
	LRC *pb = NULL;
	char buf[256];
	char lrc_path[]  = "./music/lyric/";
	
	while(1)
    {  	
		usleep(500*MS);

		if(pm->playflag == playing)
		{
			if(song.keyflag != quiet)
			{   	
				set_keyflag(quiet);
				free_link(song.lrc_head);
				
				bzero(buf,sizeof(buf));
				strcat(buf,lrc_path);
		    	strcat(buf,song.name);			
				get_lrcname(buf);			
				
				dispose_lrc(pm, buf);		
				playing_song(pm, song.now);

				song.cur_time = 0;
				song.end_time = 0;
				song.endflag  = FALSE;
			}

			if(song.pnode != NULL && song.cur_time >= song.pnode->time) //
			{
				pb = NULL;
				pb = (LRC *)search_link(song.pnode, song.pnode->time); //song.pnode???????
				mplayer_show_lyric(pm, pb);

				if(pb != NULL) song.pnode = song.pnode->next;
			}

			if((song.rate/100.0) >= 0.99) //
			{
				song.endflag = TRUE;
				set_playing_song(pm, 1);
				set_keyflag(init);
				song.rate = 0;
			}

		}
	}
}

void *pthread_send_cmd(void *agr)
{
	MPLAYER *pm = (MPLAYER *)agr;
	char *cmd[]={ "get_percent_pos\n", "get_time_pos\n","get_time_length\n", "get_file_name\n", "get_meta_artist\n"};
	int i = 0;

	while(1)
	{
		for(i=0; i < 5; i++)
		{
			if((pm->playflag == playing) && (song.endflag == FALSE))
			{
				send_cmd(cmd[i], pm);
				usleep(100*MS);
			}
		}
	}
}

void *pthread_rcv_msg(void *agr)
{
	MPLAYER *pm = (MPLAYER *)agr;
	float temp = 0.0;
	char msg[256];
	char *p = NULL, buf[16];

	while(1)
	{
		usleep(80*MS);

		if(pm->playflag == playing)
		{
			bzero(msg,sizeof(msg));
			read(pm->fd[0], msg, sizeof(msg));

			//printf(">>>>>pthread_rcv_msg  = %s\n",msg);
			if((p = strstr(msg, "ANS_PERCENT_POSITION=")) != NULL)
		    {
		   		sscanf(p,"ANS_PERCENT_POSITION=%f",&song.rate);
				gdk_threads_enter();
				gtk_progress_bar_set_fraction(pm->ui.hbox_right.progress_bar, song.rate/100.0);
				gdk_threads_leave();			    }

			if((p = strstr(msg,"ANS_TIME_POSITION=")) != NULL)
		    {
		  	    sscanf(msg,"ANS_TIME_POSITION=%f\n",&temp);

				bzero(buf,sizeof(buf));
				sprintf(buf,"%02d:%02d", (int)temp/60, (int)temp%60);

				set_lable(pm->ui.hbox_right.label_cur_time, buf);
				song.cur_time = (int)(temp * 1000);
				//printf("music cur_time = %d ms\n",song.cur_time);
		    }

		    if((p = strstr(msg,"ANS_LENGTH=")) !=NULL)
		    {
		    	sscanf(p,"ANS_LENGTH=%f",&temp);

				bzero(buf,sizeof(buf));
				sprintf(buf,"%02d:%02d", (int)temp/60, (int)temp%60);

				set_lable(pm->ui.hbox_right.label_end_time, buf);
				song.end_time = (int)(temp * 1000);
				//printf("music end_time = %d ms\n",song.end_time);
		    }

			#if 1
			if((p = strstr(msg, "ANS_FILENAME=")) != NULL)
			{
				char buf[128] = {0};

				sscanf(p,"ANS_FILENAME='%[^']",buf);

				set_lable(pm->ui.hbox_right.label_title1, buf);
			}

			if((p = strstr(msg, "ANS_META_ARTIST=")) != NULL)
			{
				char buf[128]  = {0};
				char utf8[128] = {0};

				sscanf(p,"ANS_META_ARTIST='%[^']",buf);
				gb2312_to_utf8(buf, utf8);
				set_lable(pm->ui.hbox_right.label_title2, utf8);
			}
			#endif
		}
	}
}

void create_pthread(MPLAYER *pm)
{
	pthread_create(&pm->pth_sendcmd,NULL,pthread_send_cmd,(void *)pm);
	pthread_create(&pm->pth_rcvmsg, NULL,pthread_rcv_msg, (void *)pm);
	pthread_create(&pm->pth_showlrc,NULL,pthread_show_lrc,(void *)pm);

	pthread_detach(pm->pth_showlrc);
	pthread_detach(pm->pth_rcvmsg);
	pthread_detach(pm->pth_sendcmd);
}

<file_sep>/c/practice/2nd_week/fun_pointer/Makefile
fun_pointer:fun_pointer.c fun.c

.PHONY:clean
clean:
	rm fun_pointer
<file_sep>/gtk/2. configure/03. vim_gtk自动补全/readme.txt
1) 把文件夹《vim_configure》拷贝到虚拟机任意目录
2) 进入此文件夹，sudo运行copy_con.sh脚本<file_sep>/gtk/4st_week/gtk_calculator.c
/* ************************************************************************
 *       Filename:  gtk_calculator.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月10日 19时59分35秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <gtk/gtk.h>


int main(int argc, char *argv[])
{
	gtk_init(&argc,&argv);

	GtkWidget *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	gtk_window_set_title(GTK_WINDOW(window),"GTK entry");

	gtk_window_set_position(GTK_WINDOW(window),GTK_WIN_POS_CENTER);//设置窗口的位置
	gtk_widget_set_size_request(window, 500, 300);	               //设置窗口的大小	
	gtk_window_set_resizable(GTK_WINDOW(window),FALSE);            //设置窗口是否可以改变大小

	GtkWidget *entry = gtk_entry_new();                //创建行编辑	
	gtk_entry_set_max_length(GTK_ENTRY(entry), 100);   //设置行编辑显示最大字符的长度
	gtk_entry_set_text(GTK_ENTRY(entry), "1+2=3");     //设置显示内容
	gtk_entry_set_editable(GTK_EDITABLE(entry),FALSE); //设置行编辑不予许编辑，只能显示
	
	<file_sep>/work/test/fb_test/fb_test.c
/*************************************************************************
	> File Name: fb_test.c
	> Author: 
	> Mail: 
	> Created Time: Mon 30 May 2016 04:06:45 PM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>

#define RED_COLOR565     0x0f100
#define GREEN_COLOR565   0x007e0
#define BLUE_COLOR565    0x0001f

#define RED_COLOR888     0xff0000
#define GREEN_COLOR888   0x00ff00
#define BLUE_COLOR888    0x0000ff

int main()
{
    int fd = 0;
    int x = 0, y = 0;
    int div = 0;
    char *fbp = NULL;
    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;
    struct fb_cmap cmapinfo;
    long int screensize = 0;
    long int location = 0;

    //Open the file for reading and writing
    fd = open("/dev/fb0", O_RDWR);
    if(fd < 0) {
        printf("ERROR: cannot open framebuffer device. %d\n", fd);
        exit(1);
    }
    printf("The framebuffer device was opened successfully!\n");

    //Get fixed screen infomation
    if(ioctl(fd, FBIOGET_FSCREENINFO, &finfo)) { //
        printf("ERROR: cannot get fixed infomation!\n ");
        exit(2);
    }

    printf(finfo.id);
    printf("\ntype: 0x%x\n", finfo.type);
    printf("visual: %d\n", finfo.visual);
    printf("line_length: %d\n", finfo.line_length);
    printf("smem_start: 0x%x, smem_len: %d\n", finfo.smem_start, finfo.smem_len);
    printf("mmio_start: 0x%x, mmio_len: %d\n", finfo.mmio_start, finfo.mmio_len);

    // Get variable screen infomation
    if(ioctl(fd, FBIOGET_VSCREENINFO, &vinfo)) {
        printf("ERROR: cannot get variable infomation!\n");
        exit(3);
    }
    printf("%d x %d, %dbpp\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel);
    //Figure out the size of the screen in bytes
    screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel/8;

    //Map the device to memory
    fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if((int)fbp == -1) {
        printf("ERROR: failed to map framebuffer device to memory!\n");
        exit(4);
    }

    printf("The framebuffer device was mapped to memory successfully!\n");

    //Figure out where in memory to put the pixel
#if 0
    int r, b, g;
    b = 0x10;  //blue:0000 0010
    g = 0x100; //green: 0000 0100
    r = 0x100; //red: 0000 0100
    //vinfo.xoffset = (240-160)/2;
    //vinfo.yoffset = (240-160)/2;

    for(y = 80; y < 160; y++) {
        for(x = 80; x < 160; x++) {
            location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
                (y + vinfo.yoffset) * finfo.line_length;

        #if 0
            if(vinfo.bits_per_pixel == 32) {
                *(fbp + location) = b;
                *(fbp + location + 1) = g;
                *(fbp + location + 2) = r;
                *(fbp + location + 3) = 0;
            } else { //16bpp: r:g:b = 5:6:6
                unsigned short int t = r << 11 | g << 5 | b;
                *((unsigned short int *)(fbp + location)) = t;
            }
        #else
            /* 简单处理,假定是32位或者是16位 565模式*/
            if (vinfo.bits_per_pixel == 32) {
                *(fbp + location) = 100;    // Some blue
                *(fbp + location + 1) = 15+(x-100)/2; // A little green
                *(fbp + location + 2) = 200-(y-100)/5;// A lot of red
                *(fbp + location + 3) = 0xff;         // No transparency
            } else { //assume 16bpp
                unsigned short b = 10;
                unsigned short g = (x-100)/6;
                unsigned short r = 31-(y-100)/16; // A lot of red
                unsigned short t = r << 11 | g << 5 | b;
                *((unsigned short *)(fbp + location)) = t;
            }
        #endif
        }
    }
#else

    switch(vinfo.bits_per_pixel) {
    case 16:
		div = vinfo.yres/3;
		for(y = 0; y < vinfo.yres; y++) {
			for(x = 0; x < vinfo.xres; x++) {
				location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
					(y + vinfo.yoffset) * finfo.line_length;

				switch(y/div) {
				case 0: //Red screen
					*((unsigned short *)(fbp + location)) = RED_COLOR565;
					break;
				case 1: //Green screen
					*((unsigned short *)(fbp + location)) = GREEN_COLOR565;
					break;
				case 2: //Blue screen
					*((unsigned short *)(fbp + location)) = BLUE_COLOR565;
					break;
				}
			}
		}
        break;
    case 32:
        div = vinfo.yres/3;
		for(y = 0; y < vinfo.yres; y++) {
			for(x = 0; x < vinfo.xres; x++) {
				location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
					(y + vinfo.yoffset) * finfo.line_length;

                switch(y/div) {
				case 0: //Red screen
					*((unsigned int *)(fbp + location)) = RED_COLOR888 - ((y%div)/(div/4) * 0x20 << 16);
					break;
				case 1: //Green screen
					*((unsigned int *)(fbp + location)) = GREEN_COLOR888 - ((y%div)/(div/4) * 0x20 << 8);
					break;
				case 2: //Blue screen
					*((unsigned int *)(fbp + location)) = BLUE_COLOR888 - ((y%div)/(div/4) * 0x20 << 0);
					break;
				}
            }
        }
        break;
    default:
        printf("WARNNING: bpp if not %d\n", vinfo.bits_per_pixel);
    }
#endif
    munmap(fbp, screensize);
    close(fd);
    return 0;
}

<file_sep>/network/route/src/inc/print.h
/******************************************************************************
  文 件 名   : print.h
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月14日
  最近修改   :
  功能描述   : print.c 的头文件
******************************************************************************/
#ifndef __PRINT_H__
#define __PRINT_H__


#ifdef __cplusplus
#if __cplusplus
extern "C"{
#endif
#endif /* __cplusplus */
/*----------------------------------------------*
 * 外部函数原型说明                             *
 *----------------------------------------------*/

extern void firewall_rule_set_help(void);
extern void show_help(void);

#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif /* __cplusplus */


#endif /* __PRINT_H__ */
<file_sep>/gtk/4st_week/picture_browse/image.h
/* ************************************************************************
 *       Filename:  image.h
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月11日 14时47分43秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#ifndef __IMAGE_H__
#define __IMAGE_H__

void load_image(GtkWidget *image, const char *file_path, const int w, const int h );
GtkWidget *create_button_from_file(const char *file_path, const int w, const int h);
void chang_background(GtkWidget *widget, int w, int h, const gchar *path);

#endif
<file_sep>/network/route/src/tcp_server.c
/******************************************************************************
  文 件 名   : tcp_server.c
  版 本 号   : 初稿
  作    者   : if
  生成日期   : 2015年9月16日
  最近修改   :
  功能描述   : tcp 服务器 调用函数
  函数列表   :            
              tcp_send_arp_table
              tcp_send_firewall_rules
              tcp_send_port_info
              dispose_tcp_cmd
  修改历史   :
  1.日    期   : 2015年9月16日
    作    者   : if
    修改内容   : 创建文件

******************************************************************************/
#include "common.h"


/*****************************************************************************
 函 数 名  : tcp_send_arp_table()
 功能描述  : 给TCP客户端发送ARP表的信息
 输入参数  : rt       TYPE_Route类型结构体 
 			 connfd   监听套接字
 返 回 值  : NULL
 修改日期  : 2015年9月16日
*****************************************************************************/
void tcp_send_arp_table(TYPE_Route *rt, int connfd)
{
	uchar ip[16] = "";
	uchar mac[18]= "";
	uchar msg[50]= "";
	ARP_Table *pb = NULL;
	
	pb = rt->arp_head;

	send(connfd, "_____IP________________MAC_______\n", \
		 strlen("_____IP________________MAC_______\n"), 0);
	
	while(pb != NULL) {
		//bzero(ip,  sizeof(ip));
		//bzero(mac, sizeof(mac));
		//bzero(msg, sizeof(msg));
		
		sprintf(ip,"%d.%d.%d.%d",\
				pb->ip[0],pb->ip[1],pb->ip[2],pb->ip[3]);
		
		sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",\
				pb->mac[0],pb->mac[1],pb->mac[2],pb->mac[3],pb->mac[4],pb->mac[5]);
	
		sprintf(msg, "-%-12s -- %s\n", ip, mac);
		send(connfd, msg, strlen(msg), 0);
		
		pb = pb->next;
	}

	send(connfd, "_________________________________\n", \
		 strlen("_________________________________\n"), 0);
	send(connfd, "#end#", strlen("#end#"), 0);
}

/*****************************************************************************
 函 数 名  : tcp_send_firewall_rules()
 功能描述  : 给TCP客户端发送防火墙的设定规则
 输入参数  : rt       TYPE_Route类型结构体 
 			 connfd   监听套接字
 返 回 值  : NULL
 修改日期  : 2015年9月16日
*****************************************************************************/
void tcp_send_firewall_rules(TYPE_Route *rt, int connfd)
{
	FIRE_Wall *pnode = NULL;
	FIRE_Wall *pbuf[4] = {rt->mac_head,rt->ip_head,rt->port_head,rt->pro_head};
	char rule[RULE_LEN] = "";
	int i = 0;

	send(connfd,"\n------firewall rules-------\n", \
		 strlen("\n------firewall rules-------\n"), 0);
	
	for(i=0; i<4; i++) {
		pnode = pbuf[i];
	
		while(pnode != NULL) {
			strcpy(rule, pnode->rule);
			strcat(rule,"\n");
			
			send(connfd, rule, strlen(rule), 0);			
			pnode = pnode->next;
		}		
	}

	send(connfd,"---------------------------\n\n", \
		 strlen("---------------------------\n\n"), 0);
	send(connfd, "#end#", strlen("#end#"), 0);
}

/*****************************************************************************
 函 数 名  : tcp_send_port_info()
 功能描述  : 给TCP客户端发送接口信息
 输入参数  : rt       TYPE_Route类型结构体 
 			 connfd   监听套接字
 返 回 值  : NULL
 修改日期  : 2015年9月16日
*****************************************************************************/
void tcp_send_port_info(TYPE_Route *rt, int connfd)
{
	int i = 0;
	char name[64];
	char ip[16];
	char mask[16];
	char b_ip[16];
	char mac[18];
	char msg[200];

	for(i=0;i<rt->port_num;i++)
	{
		
		sprintf(name, "___________%s___________", rt->eth_port[i].name);
	
		//ip
		sprintf(ip, "%d.%d.%d.%d",\
			   rt->eth_port[i].ip[0],rt->eth_port[i].ip[1],\
			   rt->eth_port[i].ip[2],rt->eth_port[i].ip[3]);
		//mac
		sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x",\
			   rt->eth_port[i].mac[0],rt->eth_port[i].mac[1],\
			   rt->eth_port[i].mac[2],rt->eth_port[i].mac[3],\
			   rt->eth_port[i].mac[4],rt->eth_port[i].mac[5]);
		//netmask
		printf(mask, "%d.%d.%d.%d",\
			   rt->eth_port[i].netmask[0],rt->eth_port[i].netmask[1],\
			   rt->eth_port[i].netmask[2],rt->eth_port[i].netmask[3]);
		//broadcast ip
		sprintf(b_ip, "%d.%d.%d.%d",\
			   rt->eth_port[i].bc_ip[0],rt->eth_port[i].bc_ip[1],\
			   rt->eth_port[i].bc_ip[2],rt->eth_port[i].bc_ip[3]);
		
		sprintf(msg, "%s\n%s\n%s\n%s\n%s\n", name, ip, mac, mask, b_ip);

		send(connfd, msg, strlen(msg), 0);
		send(connfd, "__________________________\n", \
			 strlen("__________________________\n"), 0);
		send(connfd, "#end#", strlen("#end#"), 0);
	}
		

}

/*****************************************************************************
 函 数 名  : dispose_cmd()
 功能描述  : 处理命令，并执行相应的动作
 输入参数  : rt     TYPE_Route类型结构体 
 			 cmd    待处理、执行的命令
 返 回 值  : NULL
 修改日期  : 2015年9月16日
*****************************************************************************/
void dispose_tcp_cmd(TYPE_Route *rt, int connfd, char cmd[])
{
	pthread_mutex_lock(&rt->mutex); // 上锁
	
	if(strcmp(cmd, "help") == 0){

		char route_help[] = {
		"***************************************************\n\
		 -      help: 查看帮助信息                         *\n\
		 -       arp: 查看 ARP 表                          *\n\
		 -  ifconfig: 查看网卡信息                         *\n\
		 -   fire on: 开启防火墙                           *\n\
		 -  fire off: 关闭防火墙                           *\n\
		 -    lsfire: 查看防火墙规则                       *\n\
		 -   setfire: 设置防火墙规则                       *\n\
		 ***************************************************\n"			
		};

		send(connfd, route_help, strlen(route_help), 0);
		send(connfd, "#end#", strlen("#end#"), 0);
	}
	else if(strcmp(cmd,"arp") == 0){
		tcp_send_arp_table(rt, connfd);
	}
	else if(strcmp(cmd,"ifconfig") == 0){
		tcp_send_port_info(rt, connfd);
	}
	else if(strcmp(cmd,"lsfire") == 0){	
		tcp_send_firewall_rules(rt, connfd);
	}
	else if(strcmp(cmd,"setfire") == 0){
		
		int i, len;
		char rule[RULE_LEN] = "";
		char passwd[PASSWD_LEN] = "";

		for(i=0; i<2; i++) {	
			send(connfd, "passwd: ", strlen("passwd: "), 0);
			send(connfd, "#end#", strlen("#end#"), 0);
			len = recv(connfd, passwd, sizeof(passwd), 0);
			if(len == 0) goto out;
			
			if(strcmp(passwd, rt->passwd) == 0){
			    send(connfd, "passed", strlen("passed"), 0);
			    send(connfd, "#end#", strlen("#end#"), 0);
				break;
			}
			else {
				send(connfd, "\nerror, try again!\n", strlen("\nerror, try again!\n"), 0);
				send(connfd, "#end#", strlen("#end#"), 0);
			}
		}		
		if(i == 2) goto out;
		
		char fire_help[] = {
			"*************************************************************************\n\
			 -				>>>   温馨提示: ()是可选选项  <<<						 *\n\
			 -设置 ip 过滤规则，格式:	ip (opt) <ip>	-> ip (src) 192.168.1.1 	 *\n\
			 -设置 mac过滤规则，格式:   mac (opt) <mac>	-> mac (dst) 192.168.1.1	 *\n\
			 -设置端口过滤规则，格式:  port (opt) <port> -> port (host) 8000 		 *\n\
			 -设置协议过滤规则，格式: <pro> (type) (opt) (type_val) -> udp port 8000 *\n\
			 -删除已设置的规则，输入: -d <要删除的规则>								 *\n\
			 -查看设置规则帮助，输入: -h 											 *\n\
			 -查看已设置的规则，输入: ls 											 *\n\
			 -退出防火墙设置，  输入: esc											 *\n\
			 *************************************************************************\n"
		};
		send(connfd, fire_help, strlen(fire_help), 0);
		send(connfd, "#end#", strlen("#end#"), 0);
			
		while(1) {			
			bzero(rule, RULE_LEN);
			send(connfd, "entry: ", strlen("entry: "), 0);
			send(connfd, "#end#", strlen("#end#"), 0);
			len = recv(connfd, rule, RULE_LEN, 0);		
			if(len == 0) goto out;			

			if(strcmp(rule,"ls") == 0){
				tcp_send_firewall_rules(rt, connfd);
			}
			else if(strcmp(rule,"-h") == 0) {
				send(connfd, fire_help, strlen(fire_help), 0);
				send(connfd, "#end#", strlen("#end#"), 0);
			}	
			else if(strncmp(rule,"-d",2) == 0) {
				char *prule = NULL;
				prule = rule+3; //跳过 "-d "
				delete_firewall_rule(rt, prule);
				firewall_save_all_rules(rt);
			}
			else if(strcmp(rule,"passwd") == 0) {
				send(connfd, "new passwd: ", strlen("new passwd: "), 0);
				send(connfd, "#end#", strlen("#end#"), 0);
				len = recv(connfd, passwd, sizeof(passwd), 0);				
				if(len == 0) goto out;
				
				get_passwd(rt->passwd, PASSWD_LEN-1);
				firewall_save_passwd(rt->passwd);
			}
			else if(strcmp(rule,"esc") == 0){
				send(connfd, "exitting set firewall...\n", 
					 strlen("exitting set firewall...\n"), 0);
				send(connfd, "#end#", strlen("#end#"), 0);
				break;
			}
			else {			
				firewall_build_rule(rt, rule, 1);
			}
		}		
	}	

	out:
	pthread_mutex_unlock(&rt->mutex);// 解锁
}

<file_sep>/network/2nd_day/Makefile
tftp_client:tftp_client.c
	gcc -o tftp_client tftp_client.c

.PHONY:clean
clean:
	rm tftp_client
<file_sep>/sys_program/2nd_day/pm/sigpromask.c
/* ************************************************************************
 *       Filename:  sigpromask.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月14日 17时22分34秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>



int main(int argc, char *argv[])
{
	sigset_t set;
	int i = 0;

	sigemptyset(&set);
	sigaddset(&set,SIGINT);

	while(1)
	{
		sigprocmask(SIG_BLOCK, &set, NULL);

		for(i=0;i<5;i++)
		{
			printf("SIGINT signal is blocked\n");
			sleep(1);
		}

		sigprocmask(SIG_UNBLOCK, &set, NULL);

		for(i=0;i<5;i++)
		{
			printf("SIGINT signal unblocked\n");
			sleep(1);
		}
	}
	return 0;
}


<file_sep>/work/debug/ingenic/pe10/pe10_drv.c
#include <linux/module.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/sysctl.h>
#include <linux/proc_fs.h>
#include <linux/delay.h>
#include <linux/gpio_keys.h>
#include <linux/gpio.h>
#include <linux/miscdevice.h> /* struct miscdevice */
#include <jz_notifier.h>

#define PE10_PORT    (GPIO_PE(10))
#define DEVICE_NAME  "pe10_gpio"

#define PE10_IOC_MAGIC     'p'
#define PE10_SET_ON_TIMER  _IO(PE10_IOC_MAGIC, 1) 
#define PE10_SET_OFF_TIMER _IO(PE10_IOC_MAGIC, 2) 



static int flag = 0;
static int on_time = 180 * HZ;
static int off_time = 3 * HZ;

static struct timer_list pe10_timer;

static void pe10_timer_handle(unsigned long arg)
{
	if(flag == 0) {	
		flag = 1;
		gpio_direction_output(PE10_PORT, 0); 
		mod_timer(&pe10_timer,jiffies+off_time);
		printk(KERN_WARNING "[msg]:  output 0 %s\n",__FUNCTION__);
	}
	else {
		flag = 0;
		gpio_direction_output(PE10_PORT, 1); 
		mod_timer(&pe10_timer,jiffies+on_time);	
		printk(KERN_WARNING "[msg]:  output 1 %s\n",__FUNCTION__);
	}

	//printk(KERN_WARNING "[msg]:  %s\n",__FUNCTION__);
}

static int pe10_drv_open(struct inode *inode, struct file *filp)
{
	//pe10_timer.expires = jiffies+on_time;  // 设置定时器的定时时间为on_time秒		
	//add_timer(&pe10_timer);			 // 注册定时器 
	printk(KERN_WARNING "[msg]:  %s\n",__FUNCTION__);
	return 0;
}

static long pe10_drv_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	int ret = 0;
	
	printk(KERN_WARNING "[msg]:  %s\n",__FUNCTION__);
	
	switch(cmd) {
		case PE10_SET_ON_TIMER:
			if(arg < 1 || arg > 2000)
				ret = EINVAL;
			else {
				on_time = arg * HZ;
				mod_timer(&pe10_timer,jiffies+on_time);
			}
			break;
		case PE10_SET_OFF_TIMER:
			if(arg < 1 || arg > 60)
				ret = EINVAL;
			else {
				off_time = arg * HZ;
				mod_timer(&pe10_timer,jiffies+off_time);
			}
			break;
		default:
			ret = -EINVAL;
	}

	return ret;
}

static int pe10_drv_release(struct inode *inode, struct file *filp)
{	
	//del_timer(&pe10_timer);	
	printk(KERN_WARNING "[msg]:  %s\n",__FUNCTION__);
	return 0;
}

static struct file_operations pe10_fops = {
	.owner   = THIS_MODULE,
	.open    = pe10_drv_open,
	.release = pe10_drv_release,
	.unlocked_ioctl = pe10_drv_ioctl,
};

static struct miscdevice pe10_misc = {
	.minor = MISC_DYNAMIC_MINOR,	
	.name  = DEVICE_NAME,
	.fops  = &pe10_fops,
};

static __init int pe10_drv_init(void)
{
	int ret;

	ret = misc_register(&pe10_misc);	
	
	init_timer(&pe10_timer); 
	pe10_timer.data = 0;                
	pe10_timer.function = pe10_timer_handle;

	// GPIO 申请及初始化
	ret = gpio_request(PE10_PORT, "PE10_DRV PORT");	
	if (ret < 0)  {		
		printk("Failed to request GPIO:%d, ERRNO:%d\n",(int)PE10_PORT, ret);		
		goto err1;	
	}
	gpio_direction_output(PE10_PORT, 1); 
	
	pe10_timer.expires = jiffies+on_time; 	
	add_timer(&pe10_timer);			    
	printk (DEVICE_NAME"\tinitialized\n");
	return 0;
	
err1:
	misc_deregister(&pe10_misc);
	return ret;
}

static __exit void pe10_drv_exit(void)
{
	del_timer_sync(&pe10_timer);
	misc_deregister(&pe10_misc);
	printk(KERN_WARNING "[msg]:  %s\n",__FUNCTION__);
}

module_init(pe10_drv_init);
module_exit(pe10_drv_exit);
MODULE_LICENSE("GPL");

<file_sep>/work/debug/2440/leds/leds_drv.c
/* ************************************************************************
 *       Filename:  leds_drv.c
 *    Description:  
 *        Version:  1.0
 *        Created:  2015年08月09日 22时26分14秒
 *       Revision:  none
 *       Compiler:  gcc
 *         Author:  YOUR NAME (), 
 *        Company:  
 * ************************************************************************/
#include <linux/kernel.h> 
#include <linux/module.h> 
#include <linux/init.h> 
#include <linux/fs.h> 
#include <linux/delay.h> 
#include <linux/ioctl.h> 
#include <linux/cdev.h> 
#include <linux/gpio.h>
#include <linux/device.h>
#include <asm/irq.h> 
#include <mach/regs-gpio.h> 
#include <mach/hardware.h>

#define DEVICE_NAME "leds_drv"

#define LED_ON   0
#define LED_OFF  1


static int majno = 0; //
static struct cdev *p_cdev = NULL;
static struct class *leds_class = NULL;

static unsigned long led_table[] = {
	S3C2410_GPB(5), 
	S3C2410_GPB(6), 
	S3C2410_GPB(7), 
	S3C2410_GPB(8), 
};

static unsigned int led_cfg_table[] =
{
	S3C2410_GPIO_OUTPUT, 
	S3C2410_GPIO_OUTPUT,
	S3C2410_GPIO_OUTPUT,
	S3C2410_GPIO_OUTPUT,
	//S3C2410_GPB5_OUTP,
	//S3C2410_GPB6_OUTP, 
	//S3C2410_GPB7_OUTP, 
	//S3C2410_GPB8_OUTP, 	
};

static int leds_open(struct inode *inode, struct file *filp)
{
	int i;
	
	for(i=0;i<4;i++)
	{
		s3c2410_gpio_cfgpin(led_table[i], led_cfg_table[i]); //要添加#include <linux/gpio.h>
	}
	
	return 0;
}

static int leds_ioctl(struct inode * inode, struct file *file, unsigned int cmd, unsigned long arg)
{
	
	if(arg >= 4)
	{
		return -EINVAL;
	}
	
	switch(cmd)
	{
		case LED_ON:
		{
			s3c2410_gpio_setpin(led_table[arg], 0);
			return 0;
		}
		case LED_OFF:
		{
			s3c2410_gpio_setpin(led_table[arg], 1);
			return 0;
		}
		default:
			return -EINVAL;
	}
}


static struct file_operations leds_fops = 
{
	.owner = THIS_MODULE,
	.open  = leds_open,
	.ioctl = leds_ioctl,
};

static void leds_setup_cdev(struct cdev *dev,int index)
{
	int err;
	dev_t devno = MKDEV(majno, index);
	
	cdev_init(dev, &leds_fops);
	
	dev->owner = THIS_MODULE;
	dev->ops = &leds_fops;	
	
	err = cdev_add(dev, devno, 1);
	
	if(err)
	{
		printk(KERN_NOTICE "Error %d adding leds cdev %d",err,index);
	}	
}
/*
 * 设备初始化函数，在设备加载到内核时调用
 */
static int __init leds_drv_init(void)
{
	int ret;
	dev_t devno = MKDEV(majno,0);
	
	if(!majno)
	{
		ret = alloc_chrdev_region(&devno,0,1,DEVICE_NAME);
		majno = MAJOR(devno);
	}
	else
	{
		ret = register_chrdev_region(devno,1,DEVICE_NAME);
	}
	
	if(ret < 0)
	{
		return ret;
	}
	
	p_cdev = kmalloc(sizeof(struct cdev), GFP_KERNEL);
	
	if(!p_cdev)
	{
		ret = -ENOMEM;
		goto fail_malloc;
	}
	
	memset(p_cdev, 0, sizeof(struct cdev));
	
	leds_setup_cdev(p_cdev,0);

	//注册一个类
	leds_class = class_create(THIS_MODULE, DEVICE_NAME);//要添加#include <linux/device.h>

	if(IS_ERR(leds_class))
	{
		printk("Err:failed in create leds class\n");
		goto fail_add_class;
	}
	//创建一个设备节点
	device_create(leds_class,NULL,MKDEV(devno,0),NULL,DEVICE_NAME);	
	return 0;

	fail_malloc:
	unregister_chrdev_region(devno,1);
	return -1;

	fail_add_class:
	cdev_del(p_cdev);
	kfree(p_cdev);
	unregister_chrdev_region(devno,1);
	return -1;
}

/*
 * 设备的注销函数，在设备从内核卸载时调用
 *
 */
static void __exit leds_drv_exit(void)
{
	cdev_del(p_cdev);
	kfree(p_cdev);  //回收设备结构的内存
	
	device_destroy(leds_class,MKDEV(majno,0));  //删除设备节点
	class_destroy(leds_class); //注销类	
	unregister_chrdev_region(MKDEV(majno,0),1); //释放设备号	
}

module_init(leds_drv_init);
module_exit(leds_drv_exit);

/* 描述驱动程序的一些信息，不是必须的 */
MODULE_AUTHOR("Dawei");                 // 驱动程序的作者
MODULE_DESCRIPTION("A Leds Driver");    // 一些描述信息
MODULE_LICENSE("GPL");                  // 遵循的协议
<file_sep>/c/homework/3rd_week/message/Makefile
msg:main.c msg.c 

.PHONY:clean
clean:
	rm msg
<file_sep>/work/camera/bf3703/BF3703.c
#include "bf3703.h"
#include "twi_s.h"
#include "system_gpio.h"


#define BF3703_ADDRESS		    0x6e
#define BF3703_IMG_WIDTH            640
#define BF3703_IMG_HEIGHT           480
#define BF3703_IMG_WIDTH_WITH_DATA  (0+BF3703_IMG_WIDTH)
#define BF3703_IMG_HEIGHT_WITH_DATA (0+BF3703_IMG_HEIGHT)
#define BF3703_IMG_SIZE             (BF3703_IMG_WIDTH*BF3703_IMG_HEIGHT)
#define BF3703_IMG_SIZE_WITH_DATA   (BF3703_IMG_WIDTH_WITH_DATA*BF3703_IMG_HEIGHT_WITH_DATA)


#define RegTable_size(table) (sizeof(table)/sizeof(table[0]))

typedef struct sensor_conf{
	u8 reg;
	u8 value;
	u8 delay_ms;
}sensor_conf;

static  const struct sensor_conf BF3703_reg[] =
{
  {0x15,0x22},//VSYNC = VSYNC_DAT		0x15[5] = 1	  
  {0x09,0x01},//0x01 ,standby
  {0x12,0x01},//0x01	VGA RAW Bayer RGB mode
  {0x3a,0x00},//0x00 
  //{0x1e,0x10},//Vertically flip
  {0xf1,0x28},
  {0x13,0x00},//关闭AEC和AGC
  {0x01,0x00},
  {0x02,0x00},
  //{0x8c,0x01},
  //{0x8d,0x32},
  {0x8c,0x00},
  {0x8d,0x2D},//曝光时间约3ms
  {0x87,0x20},//模拟增益设置到32
  //{0x13,0x05},
  {0x05,0x1f},
  {0x06,0x60},
  {0x14,0x20},
  {0x27,0x03},
  {0x06,0xe0},
  {0x11,0x40},//MCLK=XCLK
  {0x2a,0x00},//0x2a和0x2b是设置dummy pix。设置为16，是为了把每一行的pix设置到800。
  {0x2b,0x10},//这样一来，MCLK为24MHz时，每一行的时间就为1/15ms，方便计算。
  {0x9e,0x4c},
  {0x9e,0x3f},
  {0x92,225},//0x92和0x93,设置VSYNC后插入行。，这里设置为225行，也就是15ms
  {0x93,0x00},
  {0xe3,0x2D},//0x92和0x93,设置VSYNC前插入行。这里保持与初次设置的曝光时间一样。
  {0xe4,0x00},
  {0xeb,0x30},
  {0xbb,0x20},
  {0Xf5,0x21},
  {0Xe1,0X3c},
  {0X16,0x03},
  {0X2f,0Xf6},
  {0x33,0x20},
  {0x34,0x08},
  {0x35,0x56},
  {0x65,0x58},
  {0x66,0x52},
  {0x36,0x05},
  {0x37,0xc0},
  {0x38,0x46},
  {0x9b,0xf6},
  {0x9c,0x46},
  {0xbc,0x01},
  {0xbd,0xf6},
  {0xbe,0x46},
  {0x82,0x14},
  {0x83,0x23},
  {0x9a,0x23},
  {0x70,0x6f},
  {0x72,0x2f},
  {0x73,0x2f},
  {0x74,0x29},
  {0x77,0x90},
  {0x7a,0x26},
  {0x7b,0x30},
  {0x84,0x1a},
  {0x85,0x20},
  {0x89,0x02},
  {0x8a,0x64},
  {0x86,0x30},
  {0x96,0xa6},
  {0x97,0x0c},
  {0x98,0x18},
  {0x80,0x54},
  {0x24,0x88},
  {0x25,0x78},
  {0x69,0x20},
  {0x94,0x0a},
  {0X1F,0x20},
  {0X22,0x20},
  {0X26,0x20},
  {0x56,0x40},
  {0x61,0xd3},
  {0x79,0x48},
  {0x3b,0x60},
  {0x3c,0x28},
  {0x39,0x80},
  {0x3f,0xc0},
  {0x40,0X60},
  {0x41,0X60},
  {0x42,0X66},
  {0x43,0X57},
  {0x44,0X4c},
  {0x45,0X43},
  {0x46,0X3c},
  {0x47,0X37},
  {0x48,0X33},
  {0x49,0X2f},
  {0x4b,0X2c},
  {0x4c,0X29},
  {0x4e,0X25},
  {0x4f,0X22},
  {0x50,0X20},
  {0x6a,0x00},
  {0x23,0x00},
  {0xa0,0x03},
  {0x06,0xe0},
  {0x8e,0x01},
  {0x8f,0xfe},//{0xb6,0x20},//{0xb7,0x20},//{0xb8,0x20},{0xb9,0xc0}
  //{0xb9,0x80}
};

//设置图像传感器曝光时间
void BF3703_SetExposure(u16 exposure)
{
    u8 reg_val=0;
    
    // Integration time MSB 0x8c, stores the higher 8 bits of exposure time.
    // Integration time LSB 0x8d, stores the lower 8 bits of exposure time.
    reg_val=(u8)(exposure>>8);
    TWI_Write(TWI1, 0x6e, 0x8c, 1, &reg_val, 1);
    reg_val=(u8)(exposure&0xff);
    TWI_Write(TWI1, 0x6e, 0x8d, 1, &reg_val, 1);
}

void BF3703_SetAnalogGain(u16 gain)		  //set global gain register
{
  u8 reg_val=0;

  reg_val=(u8)MIN(0x3F,MAX(0x00,gain)); // Limit the value between 0 ~ 63
  TWI_Write(TWI1, 0x6e, 0x87, 1, &reg_val, 1);
}

//设置图像传感器帧率
void BF3703_SetDummyLine(u16 dummy_lines)
{
    u8 reg_val=0;

    // Dummy lines insert before active line MSB 0xe4, stores the higher 8 bits of dummy lines.
    // Dummy lines insert before active line LSB 0xe3, stores the lower 8 bits of dummy lines.
    reg_val=(u8)(dummy_lines>>8);
    TWI_Write(TWI1, 0x6e, 0xe4, 1, &reg_val, 1);
    reg_val=(u8)(dummy_lines&0xff);
    TWI_Write(TWI1, 0x6e, 0xe3, 1, &reg_val, 1);
}

u32 BF3703_GetExposure(void)		   
{
    u8 string[2]={0};
    u16 reg_val=0;
    
    TWI_Read(TWI1, 0x6e, 0x8c, 1, &(string[0]), 1);
    TWI_Read(TWI1, 0x6e, 0x8d, 1, &(string[1]), 1);
         
	reg_val =  string[1]; 			//lsb 8bit
	reg_val |= ((string[0]<<8));	//hsb 	     
	return (u32)reg_val;
}

u32 BF3703_GetAnalogGain(void)
{
	u8 reg_val=0;
    
    TWI_Read(TWI1, 0x6e, 0x87, 1, &reg_val, 1);   
	return (u32)reg_val;
}

//u32 BF3703_GetCurrentBin(void)
//{
//	u8 reg_val=0;
//    
//    TWI_Read(TWI1, 0x6e, 0x88, 1, &reg_val, 1);   
//	return (u32)reg_val;
//}

u32 BF3703_GetCurrentBin(u8* p_data)
{
	u32 BIN_NUM=256;
	u32 GREY_LEVEL=256;
	u32 IMG_STEP=4;
	u32 HIST_STEP=GREY_LEVEL/BIN_NUM;
	u32 width=0;
	u32 height=0;
	u32 w_offset=0;
	u32 h_offset=0;
	u32 w_start=0;
	u32 w_end=0;
	u32 h_start=0;
	u32 h_end=0;
	u8* data_addr=p_data; 
	u32 hist_temp[256]={0};
	u32 sum=0;
	u32 pix_num=0;
	u32 i=0,j=0;
	
	width=BF3703_IMG_WIDTH;
	height=BF3703_IMG_HEIGHT;
	w_offset=0;
	h_offset=0;
	w_start=0;
	w_end=width;
	h_start=0;
	h_end=height;
	
	// 1. 先创建一个256级的histogram，并对原图像下采样1/4 * 1/4 统计。
	memset(hist_temp,0,GREY_LEVEL*sizeof(u32));
	for(j=h_start;j<h_end;j+=IMG_STEP)
		for(i=w_start;i<w_end;i+=IMG_STEP)
			hist_temp[data_addr[i+j*width]]++;
	
	// 计算当前256级别下的Bin值
	for(i=0;i<GREY_LEVEL;i++)
	{
		sum+=(hist_temp[i]*i);	// 计算total sum的直方图。
		pix_num+=hist_temp[i];	// 计算pixel计入计算的总数。
	}
	sum=(sum/pix_num);
	
//	// 计算64级别下的Bin值
//	sum=(sum>>2);//((sum/GREY_LEVEL)*BIN_NUM)
	
	// 返回量程为256的图像bin值
	return sum;	
}

u32 BF3703_GetCurrentBin_80Per(u8* p_data)
{
	u32 BIN_NUM=256;
	u32 GREY_LEVEL=256;
	u32 IMG_STEP=4;
	u32 HIST_STEP=GREY_LEVEL/BIN_NUM;
	u32 width=0;
	u32 height=0;
	u32 w_offset=0;
	u32 h_offset=0;
	u32 w_start=0;
	u32 w_end=0;
	u32 h_start=0;
	u32 h_end=0;
	u8* data_addr=p_data; 
	u32 hist_temp[256]={0};
	u32 sum=0;
	u32 pix_num=0;
	u32 i=0,j=0;
	
	width=BF3703_IMG_WIDTH;
	height=BF3703_IMG_HEIGHT;
	w_offset=width*(20-19)/20;
	h_offset=height*(20-19)/20;
	w_start=w_offset;
	w_end=width-w_offset;
	h_start=h_offset;
	h_end=height-h_offset;
	
	// 1. 先创建一个256级的histogram，并对原图像下采样1/4 * 1/4 统计。
	memset(hist_temp,0,GREY_LEVEL*sizeof(u32));
	for(j=h_start;j<h_end;j+=IMG_STEP)
		for(i=w_start;i<w_end;i+=IMG_STEP)
			hist_temp[data_addr[i+j*width]]++;
	
	// 计算当前256级别下的Bin值
	for(i=0;i<GREY_LEVEL;i++)
	{
		sum+=(hist_temp[i]*i);	// 计算total sum的直方图。
		pix_num+=hist_temp[i];	// 计算pixel计入计算的总数。
	}
	sum=(sum/pix_num);
	
//	// 计算64级别下的Bin值
//	sum=(sum>>2);//((sum/GREY_LEVEL)*BIN_NUM)
	
	// 返回量程为256的图像bin值
	return sum;
}

void BF3703_AE_Enable(void)
{
  u8 reg_val=0;
  
  reg_val = 0x05;
  TWI_Write(TWI1, 0x6e, 0x13, 1, &reg_val, 1);
}

void BF3703_AE_Disable(void)
{
  u8 reg_val=0;
  
  reg_val = 0x00;
  TWI_Write(TWI1, 0x6e, 0x13, 1, &reg_val, 1);
}

void BF3703_ExitStandby(void)
{
//    u8 reg_val=0;
//    u32 delay=0;
  
//  // Software Power Down
//  reg_val = 0x01;
//  TWI_Write(TWI1, 0x6e, 0x09, 1, &reg_val, 1);
    // Hardware Power Down
    PIO_Clear(&Pin_ISI_PWDN);// 1:pwdn mode
}

void BF3703_EnterStandby(void)
{
//  u8 reg_val=0;
//  u32 delay=0;
//  // Software Power Up  
//    reg_val = 0x11;
//    TWI_Write(TWI1, 0x6e, 0x09, 1, &reg_val, 1);
    // Hardware Power Up  
    PIO_Set(&Pin_ISI_PWDN);// 0:normal mode
}

/*********************************************************************************
Function:       BF3703_GetHistogram()
Description:    Fetch Histogram based on the image info area and loaded into a
				existing histo array
Input:          u32 	bin_num
         		u8* 	pImgData
Output:			u32*	_hist
Return:         None
Create Date:	2014/09/09
Last Update:	None
**********************************************************************************/
void BF3703_GetHistogram(u32* _hist, u32 bin_num, u8* pImgData)
{
	u32 BIN_NUM=bin_num;
	u32 GREY_LEVEL=256;
	u32 IMG_STEP=4;
	u32 HIST_STEP=GREY_LEVEL/BIN_NUM;
	u32 width=BF3703_IMG_WIDTH;
	u32 height=BF3703_IMG_HEIGHT;
	u8* data_addr=pImgData; 
	u32 hist_temp[256]={0};
	u32 temp=0;
	u32 i=0,j=0;
	
	// 1. 先创建一个256级的histogram，并对原图像下采样1/4 * 1/4 统计。
	memset(hist_temp,0,GREY_LEVEL*sizeof(u32));
	for(j=0;j<height;j+=IMG_STEP)
		for(i=0;i<width;i+=IMG_STEP)
			hist_temp[data_addr[i+j*width]]++;
	// 2. 将256级的临时histogram降入64级
	for(i=0;i<BIN_NUM;i++)
	{
		temp=0;
		for(j=0;j<HIST_STEP;j++)
			temp+=hist_temp[i*HIST_STEP+j];
		// 每4个256级的元素，组成一个64级元素
		_hist[i]=temp;
	}
	return;
}

void BF3703_Init(void)
{
  uint32_t i;
  uint8_t tmp_val;// read for check 
  volatile uint32_t delay;//need use volatile？

  for (i = 0; i < RegTable_size(BF3703_reg); i++)  
  {
    //TWI_Write(Twi *pTwi, uint8_t address, uint32_t iaddress, uint8_t isize, uint8_t *pData, uint32_t num)
    TWI_Write(TWI1, 0x6e, BF3703_reg[i].reg, 1, (u8*)&(BF3703_reg[i].value), 1);
  } 	
}

void BF3703_WriteRegister(u8 reg_addr,u8 reg_val)
{
  TWI_Write(TWI1, 0x6e, reg_addr, 1, &reg_val, 1);
}

void BF3703_Reset(void)
{
  u8 reg_val=0;
  u32 delay=0;
  
  reg_val = 0x10;
  TWI_Write(TWI1, 0x6e, 0x12, 1, &reg_val, 1);
}
