engine.c (2670B)
1 /* 2 * MySmartUSB MK3 Interface 3 * 4 * @copyright: Copyright (c) 2012, Dominik Schmidt 5 * @author: Dominik Schmidt <das1993@hotmail.com> 6 * @version: 0.0.0 7 * @license: CC-BY-SA 3.0 (http://creativecommons.org/licenses/by-sa/3.0/) 8 * 9 */ 10 #include <stdio.h> 11 #include <option.h> 12 #include <cmd_dispatch.h> 13 #include <dev.h> 14 #include <log.h> 15 #include <engine.h> 16 void print_usage(FILE *stream){ 17 fprintf(stream,"Usage of %s\n",configuration.filename); 18 fprintf(stream,"Global Commands:\n"); 19 struct global_option *glopt=global_options; 20 while(glopt->type!=GLOPT_COUNT){ 21 if(glopt->opt.usage==NULL){ 22 fprintf(stream,"\t%s/%s\n", glopt->opt.short_option, glopt->opt.long_option); 23 } 24 else{ 25 fprintf(stream,"\t%s/%s %s\n", glopt->opt.short_option, glopt->opt.long_option, glopt->opt.usage); 26 } 27 if(glopt->opt.description!=NULL){ 28 fprintf(stream,"\t\t%s\n",glopt->opt.description); 29 } 30 glopt++; 31 } 32 fprintf(stream,"MySmartUSB Commands:\n"); 33 struct command_def *cmdptr=commands; 34 while(cmdptr->name!=NULL){ 35 if(cmdptr->opt.usage==NULL){ 36 fprintf(stream,"\t%s: %s/%s\n", cmdptr->name, cmdptr->opt.short_option, cmdptr->opt.long_option); 37 } 38 else{ 39 fprintf(stream,"\t%s: %s/%s %s\n", cmdptr->name, cmdptr->opt.short_option, cmdptr->opt.long_option, cmdptr->opt.usage); 40 } 41 if(cmdptr->opt.description!=NULL){ 42 fprintf(stream,"\t\t%s\n",cmdptr->opt.description); 43 } 44 cmdptr++; 45 } 46 47 48 } 49 int engine_autorun(int argc, char **argv){ 50 int ret=engine_init(argc,argv); 51 if(ret<-1){ 52 do_log("engine_autorun", "Couldn't initialize engine",LOG_LEVEL_FATAL, LOG_TYPE_NORMAL); 53 } 54 if(ret>=0&&engine_run()<0){ 55 do_log("engine_autorun", "Couldn't run the command",LOG_LEVEL_FATAL, LOG_TYPE_NORMAL); 56 ret=-2; 57 } 58 engine_deinit(); 59 return ret; 60 } 61 int engine_init(int argc, char **argv){ 62 configuration.filename=argv[0]; 63 if(argc<=1){ 64 configuration.print_usage=1; 65 return -1; 66 } 67 68 if(parseArguments(argc-1, &argv[1],&configuration)<0){ 69 do_log("engine_init", "Couldn't parse Arguments",LOG_LEVEL_FATAL, LOG_TYPE_NORMAL); 70 return -2; 71 } 72 73 74 return 0; 75 } 76 77 int engine_run(void){ 78 int fd=openDevice(configuration.device); 79 if(fd<0){ 80 do_log("engine_run","Couldn't open device",LOG_LEVEL_FATAL,LOG_TYPE_NORMAL); 81 return -1; 82 } 83 if(prepareCommandExecution(fd, &configuration)<0){ 84 do_log("engine_run", "CommandExecution Preparation failed", LOG_LEVEL_FATAL, LOG_TYPE_NORMAL); 85 closeDevice(fd); 86 return -2; 87 } 88 processCommands(configuration.cmdlist.data,fd); 89 finishCommandExecution(fd, &configuration); 90 closeDevice(fd); 91 return 0; 92 93 } 94 95 int engine_deinit(void){ 96 if(configuration.print_usage){ 97 print_usage(stderr); 98 } 99 return 0; 100 }