code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * shell_dump.c */ #include "private.h" #include "lub/dump.h" /*--------------------------------------------------------- */ void clish_shell_dump(clish_shell_t * this) { clish_view_t *v; clish_ptype_t *t; clish_var_t *var; lub_bintree_iterator_t iter; lub_dump_printf("shell(%p)\n", this); lub_dump_printf("OVERVIEW:\n%s", this->overview); lub_dump_indent(); v = lub_bintree_findfirst(&this->view_tree); /* iterate the tree of views */ for (lub_bintree_iterator_init(&iter, &this->view_tree, v); v; v = lub_bintree_iterator_next(&iter)) { clish_view_dump(v); } /* iterate the tree of types */ t = lub_bintree_findfirst(&this->ptype_tree); for (lub_bintree_iterator_init(&iter, &this->ptype_tree, t); t; t = lub_bintree_iterator_next(&iter)) { clish_ptype_dump(t); } /* iterate the tree of vars */ var = lub_bintree_findfirst(&this->var_tree); for (lub_bintree_iterator_init(&iter, &this->var_tree, var); var; var = lub_bintree_iterator_next(&iter)) { clish_var_dump(var); } lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_dump.c
C
bsd
1,103
/* * shell_startup.c */ #include "private.h" #include <assert.h> #include "tinyrl/tinyrl.h" #include "lub/string.h" /*----------------------------------------------------------------------- */ int clish_shell_timeout_fn(tinyrl_t *tinyrl) { clish_context_t *context = tinyrl__get_context(tinyrl); clish_shell_t *this = context->shell; /* Idle timeout */ if (!this->wdog_active) { tinyrl_crlf(tinyrl); fprintf(stderr, "Warning: Idle timeout. The session will be closed.\n"); /* Return -1 to close session on timeout */ return -1; } /* Watchdog timeout */ clish_shell_wdog(this); this->wdog_active = BOOL_FALSE; tinyrl__set_timeout(tinyrl, this->idle_timeout); return 0; } /*----------------------------------------------------------------------- */ int clish_shell_keypress_fn(tinyrl_t *tinyrl, int key) { clish_context_t *context = tinyrl__get_context(tinyrl); clish_shell_t *this = context->shell; if (this->wdog_active) { this->wdog_active = BOOL_FALSE; tinyrl__set_timeout(tinyrl, this->idle_timeout); } return 0; } /*----------------------------------------------------------- */ int clish_shell_wdog(clish_shell_t *this) { clish_context_t context; assert(this->wdog); context.shell = this; context.cmd = this->wdog; context.pargv = NULL; /* Call watchdog script */ return clish_shell_execute(&context, NULL); } /*----------------------------------------------------------- */ void clish_shell__set_wdog_timeout(clish_shell_t *this, unsigned int timeout) { assert(this); this->wdog_timeout = timeout; } /*----------------------------------------------------------- */ unsigned int clish_shell__get_wdog_timeout(const clish_shell_t *this) { assert(this); return this->wdog_timeout; }
zzysjtu-klish
clish/shell/shell_wdog.c
C
bsd
1,740
/* * shell_pwd.c */ #include <stdlib.h> #include <assert.h> #include "lub/string.h" #include "private.h" /*--------------------------------------------------------- */ void clish_shell__init_pwd(clish_shell_pwd_t *pwd) { pwd->line = NULL; pwd->view = NULL; /* initialise the tree of vars */ lub_bintree_init(&pwd->viewid, clish_var_bt_offset(), clish_var_bt_compare, clish_var_bt_getkey); } /*--------------------------------------------------------- */ void clish_shell__fini_pwd(clish_shell_pwd_t *pwd) { clish_var_t *var; lub_string_free(pwd->line); pwd->view = NULL; /* delete each VAR held */ while ((var = lub_bintree_findfirst(&pwd->viewid))) { lub_bintree_remove(&pwd->viewid, var); clish_var_delete(var); } } /*--------------------------------------------------------- */ void clish_shell__set_pwd(clish_shell_t *this, const char *line, clish_view_t *view, char *viewid, clish_context_t *context) { clish_shell_pwd_t **tmp; size_t new_size = 0; unsigned int i; unsigned int index = clish_view__get_depth(view); clish_shell_pwd_t *newpwd; /* Create new element */ newpwd = malloc(sizeof(*newpwd)); assert(newpwd); clish_shell__init_pwd(newpwd); /* Resize the pwd vector */ if (index >= this->pwdc) { new_size = (index + 1) * sizeof(clish_shell_pwd_t *); tmp = realloc(this->pwdv, new_size); assert(tmp); this->pwdv = tmp; /* Initialize new elements */ for (i = this->pwdc; i <= index; i++) { clish_shell_pwd_t *pwd = malloc(sizeof(*pwd)); assert(pwd); clish_shell__init_pwd(pwd); this->pwdv[i] = pwd; } this->pwdc = index + 1; } /* Fill the new pwd entry */ newpwd->line = line ? lub_string_dup(line) : NULL; newpwd->view = view; clish_shell__expand_viewid(viewid, &newpwd->viewid, context); clish_shell__fini_pwd(this->pwdv[index]); free(this->pwdv[index]); this->pwdv[index] = newpwd; this->depth = index; } /*--------------------------------------------------------- */ char *clish_shell__get_pwd_line(const clish_shell_t *this, unsigned int index) { if (index >= this->pwdc) return NULL; return this->pwdv[index]->line; } /*--------------------------------------------------------- */ char *clish_shell__get_pwd_full(const clish_shell_t * this, unsigned depth) { char *pwd = NULL; unsigned i; for (i = 1; i <= depth; i++) { const char *str = clish_shell__get_pwd_line(this, i); /* Cannot get full path */ if (!str) { lub_string_free(pwd); return NULL; } if (pwd) lub_string_cat(&pwd, " "); lub_string_cat(&pwd, "\""); lub_string_cat(&pwd, str); lub_string_cat(&pwd, "\""); } return pwd; } /*--------------------------------------------------------- */ clish_view_t *clish_shell__get_pwd_view(const clish_shell_t * this, unsigned int index) { if (index >= this->pwdc) return NULL; return this->pwdv[index]->view; } /*--------------------------------------------------------- */ konf_client_t *clish_shell__get_client(const clish_shell_t * this) { return this->client; } /*--------------------------------------------------------- */ void clish_shell__set_lockfile(clish_shell_t * this, const char * path) { if (!this) return; lub_string_free(this->lockfile); this->lockfile = NULL; if (path) this->lockfile = lub_string_dup(path); } /*--------------------------------------------------------- */ char * clish_shell__get_lockfile(clish_shell_t * this) { if (!this) return NULL; return this->lockfile; } /*--------------------------------------------------------- */ int clish_shell__set_socket(clish_shell_t * this, const char * path) { if (!this || !path) return -1; konf_client_free(this->client); this->client = konf_client_new(path); return 0; }
zzysjtu-klish
clish/shell/shell_pwd.c
C
bsd
3,713
/* * shell_tinyrl.c * * This is a specialisation of the tinyrl_t class which maps the readline * functionality to the CLISH environment. */ #include "private.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <errno.h> #include <ctype.h> #include "tinyrl/tinyrl.h" #include "tinyrl/history.h" #include "lub/string.h" /*-------------------------------------------------------- */ static void clish_shell_renew_prompt(clish_shell_t *this) { clish_context_t prompt_context; char *prompt = NULL; const clish_view_t *view; char *str = NULL; /* Create appropriate context */ memset(&prompt_context, 0, sizeof(prompt_context)); prompt_context.shell = this; /* Obtain the prompt */ view = clish_shell__get_view(this); assert(view); lub_string_cat(&str, "${_PROMPT_PREFIX}"); lub_string_cat(&str, clish_view__get_prompt(view)); lub_string_cat(&str, "${_PROMPT_SUFFIX}"); prompt = clish_shell_expand(str, SHELL_VAR_NONE, &prompt_context); assert(prompt); lub_string_free(str); tinyrl__set_prompt(this->tinyrl, prompt); lub_string_free(prompt); } /*-------------------------------------------------------- */ static bool_t clish_shell_tinyrl_key_help(tinyrl_t * this, int key) { bool_t result = BOOL_TRUE; if (tinyrl_is_quoting(this)) { /* if we are in the middle of a quote then simply enter a space */ result = tinyrl_insert_text(this, "?"); } else { /* get the context */ clish_context_t *context = tinyrl__get_context(this); tinyrl_crlf(this); clish_shell_help(context->shell, tinyrl__get_line(this)); tinyrl_crlf(this); tinyrl_reset_line_state(this); } /* keep the compiler happy */ key = key; return result; } /*lint +e818 */ /*-------------------------------------------------------- */ /* * Expand the current line with any history substitutions */ static clish_pargv_status_t clish_shell_tinyrl_expand(tinyrl_t * this) { clish_pargv_status_t status = CLISH_LINE_OK; int rtn; char *buffer; /* first of all perform any history substitutions */ rtn = tinyrl_history_expand(tinyrl__get_history(this), tinyrl__get_line(this), &buffer); switch (rtn) { case -1: /* error in expansion */ status = CLISH_BAD_HISTORY; break; case 0: /*no expansion */ break; case 1: /* expansion occured correctly */ tinyrl_replace_line(this, buffer, 1); break; case 2: /* just display line */ tinyrl_printf(this, "\n%s", buffer); free(buffer); buffer = NULL; break; default: break; } free(buffer); return status; } /*-------------------------------------------------------- */ /* * This is a CLISH specific completion function. * If the current prefix is not a recognised prefix then * an error is flagged. * If it is a recognisable prefix then possible completions are displayed * or a unique completion is inserted. */ static tinyrl_match_e clish_shell_tinyrl_complete(tinyrl_t * this) { /* context_t *context = tinyrl__get_context(this); */ tinyrl_match_e status; /* first of all perform any history expansion */ (void)clish_shell_tinyrl_expand(this); /* perform normal completion */ status = tinyrl_complete(this); switch (status) { case TINYRL_NO_MATCH: if (BOOL_FALSE == tinyrl_is_completion_error_over(this)) { /* The user hasn't even entered a valid prefix! */ /* tinyrl_crlf(this); clish_shell_help(context->shell, tinyrl__get_line(this)); tinyrl_crlf(this); tinyrl_reset_line_state(this); */ } break; default: /* the default completion function will have prompted for completions as * necessary */ break; } return status; } /*--------------------------------------------------------- */ static bool_t clish_shell_tinyrl_key_space(tinyrl_t * this, int key) { bool_t result = BOOL_FALSE; tinyrl_match_e status; clish_context_t *context = tinyrl__get_context(this); const char *line = tinyrl__get_line(this); clish_pargv_status_t arg_status; const clish_command_t *cmd = NULL; clish_pargv_t *pargv = NULL; if(tinyrl_is_empty(this)) { /* ignore space at the begining of the line, don't display commands */ return BOOL_TRUE; } else if (tinyrl_is_quoting(this)) { /* if we are in the middle of a quote then simply enter a space */ result = BOOL_TRUE; } else { /* Find out if current line is legal. It can be * fully completed or partially completed. */ arg_status = clish_shell_parse(context->shell, line, &cmd, &pargv); if (pargv) clish_pargv_delete(pargv); switch (arg_status) { case CLISH_LINE_OK: case CLISH_LINE_PARTIAL: if (' ' != line[strlen(line) - 1]) result = BOOL_TRUE; break; default: break; } /* If current line is illegal try to make auto-comletion. */ if (!result) { /* perform word completion */ status = clish_shell_tinyrl_complete(this); switch (status) { case TINYRL_NO_MATCH: case TINYRL_AMBIGUOUS: /* ambiguous result signal an issue */ break; case TINYRL_COMPLETED_AMBIGUOUS: /* perform word completion again in case we just did case modification the first time */ status = clish_shell_tinyrl_complete(this); if (status == TINYRL_MATCH_WITH_EXTENSIONS) { /* all is well with the world just enter a space */ result = BOOL_TRUE; } break; case TINYRL_MATCH: case TINYRL_MATCH_WITH_EXTENSIONS: case TINYRL_COMPLETED_MATCH: /* all is well with the world just enter a space */ result = BOOL_TRUE; break; } } } if (result) result = tinyrl_insert_text(this, " "); /* keep compiler happy */ key = key; return result; } /*-------------------------------------------------------- */ static bool_t clish_shell_tinyrl_key_enter(tinyrl_t *this, int key) { clish_context_t *context = tinyrl__get_context(this); const clish_command_t *cmd = NULL; const char *line = tinyrl__get_line(this); bool_t result = BOOL_FALSE; char *errmsg = NULL; /* Inc line counter */ if (context->shell->current_file) context->shell->current_file->line++; /* Renew prompt */ clish_shell_renew_prompt(context->shell); /* nothing to pass simply move down the screen */ if (!*line) { tinyrl_multi_crlf(this); tinyrl_done(this); return BOOL_TRUE; } /* try and parse the command */ cmd = clish_shell_resolve_command(context->shell, line); if (!cmd) { tinyrl_match_e status = clish_shell_tinyrl_complete(this); switch (status) { case TINYRL_MATCH: case TINYRL_MATCH_WITH_EXTENSIONS: case TINYRL_COMPLETED_MATCH: /* re-fetch the line as it may have changed * due to auto-completion */ line = tinyrl__get_line(this); /* get the command to parse? */ cmd = clish_shell_resolve_command(context->shell, line); /* * We have had a match but it is not a command * so add a space so as not to confuse the user */ if (!cmd) result = tinyrl_insert_text(this, " "); break; default: /* failed to get a unique match... */ if (!tinyrl__get_isatty(this)) { /* batch mode */ tinyrl_multi_crlf(this); errmsg = "Unknown command"; } break; } } if (cmd) { clish_pargv_status_t arg_status; tinyrl_multi_crlf(this); /* we've got a command so check the syntax */ arg_status = clish_shell_parse(context->shell, line, &context->cmd, &context->pargv); switch (arg_status) { case CLISH_LINE_OK: tinyrl_done(this); result = BOOL_TRUE; break; case CLISH_BAD_HISTORY: errmsg = "Bad history entry"; break; case CLISH_BAD_CMD: errmsg = "Illegal command line"; break; case CLISH_BAD_PARAM: errmsg = "Illegal parameter"; break; case CLISH_LINE_PARTIAL: errmsg = "The command is not completed"; break; default: errmsg = "Unknown problem"; break; } } /* If error then print message */ if (errmsg) { if (tinyrl__get_isatty(this) || !context->shell->current_file) { fprintf(stderr, "Syntax error: %s\n", errmsg); tinyrl_reset_line_state(this); } else { char *fname = "stdin"; if (context->shell->current_file->fname) fname = context->shell->current_file->fname; fprintf(stderr, "Syntax error on line %s:%u \"%s\": " "%s\n", fname, context->shell->current_file->line, line, errmsg); } } /* keep the compiler happy */ key = key; return result; } /*-------------------------------------------------------- */ /* This is the completion function provided for CLISH */ tinyrl_completion_func_t clish_shell_tinyrl_completion; char **clish_shell_tinyrl_completion(tinyrl_t * tinyrl, const char *line, unsigned start, unsigned end) { lub_argv_t *matches; clish_context_t *context = tinyrl__get_context(tinyrl); clish_shell_t *this = context->shell; clish_shell_iterator_t iter; const clish_command_t *cmd = NULL; char *text; char **result = NULL; if (tinyrl_is_quoting(tinyrl)) return result; matches = lub_argv_new(NULL, 0); text = lub_string_dupn(line, end); /* Don't bother to resort to filename completion */ tinyrl_completion_over(tinyrl); /* Search for COMMAND completions */ clish_shell_iterator_init(&iter, CLISH_NSPACE_COMPLETION); while ((cmd = clish_shell_find_next_completion(this, text, &iter))) lub_argv_add(matches, clish_command__get_suffix(cmd)); /* Try and resolve a command */ cmd = clish_shell_resolve_command(this, text); /* Search for PARAM completion */ if (cmd) clish_shell_param_generator(this, matches, cmd, text, start); lub_string_free(text); /* Matches were found */ if (lub_argv__get_count(matches) > 0) { unsigned i; char *subst = lub_string_dup(lub_argv__get_arg(matches, 0)); /* Find out substitution */ for (i = 1; i < lub_argv__get_count(matches); i++) { char *p = subst; const char *match = lub_argv__get_arg(matches, i); size_t match_len = strlen(p); /* identify the common prefix */ while ((tolower(*p) == tolower(*match)) && match_len--) { p++; match++; } /* Terminate the prefix string */ *p = '\0'; } result = lub_argv__get_argv(matches, subst); lub_string_free(subst); } lub_argv_delete(matches); return result; } /*-------------------------------------------------------- */ static void clish_shell_tinyrl_init(tinyrl_t * this) { bool_t status; /* bind the '?' key to the help function */ status = tinyrl_bind_key(this, '?', clish_shell_tinyrl_key_help); assert(status); /* bind the <RET> key to the help function */ status = tinyrl_bind_key(this, '\r', clish_shell_tinyrl_key_enter); assert(status); status = tinyrl_bind_key(this, '\n', clish_shell_tinyrl_key_enter); assert(status); /* bind the <SPACE> key to auto-complete if necessary */ status = tinyrl_bind_key(this, ' ', clish_shell_tinyrl_key_space); assert(status); /* Assign timeout callback */ tinyrl__set_timeout_fn(this, clish_shell_timeout_fn); /* Assign keypress callback */ tinyrl__set_keypress_fn(this, clish_shell_keypress_fn); } /*-------------------------------------------------------- */ /* * Create an instance of the specialised class */ tinyrl_t *clish_shell_tinyrl_new(FILE * istream, FILE * ostream, unsigned stifle) { /* call the parent constructor */ tinyrl_t *this = tinyrl_new(istream, ostream, stifle, clish_shell_tinyrl_completion); /* now call our own constructor */ if (this) clish_shell_tinyrl_init(this); return this; } /*-------------------------------------------------------- */ void clish_shell_tinyrl_fini(tinyrl_t * this) { /* nothing to do... yet */ this = this; } /*-------------------------------------------------------- */ void clish_shell_tinyrl_delete(tinyrl_t * this) { /* call our destructor */ clish_shell_tinyrl_fini(this); /* and call the parent destructor */ tinyrl_delete(this); } /*-------------------------------------------------------- */ int clish_shell_execline(clish_shell_t *this, const char *line, char **out) { char *str; clish_context_t context; tinyrl_history_t *history; int lerror = 0; assert(this); this->state = SHELL_STATE_OK; if (!line && !tinyrl__get_istream(this->tinyrl)) { this->state = SHELL_STATE_SYSTEM_ERROR; return -1; } /* Renew prompt */ clish_shell_renew_prompt(this); /* Set up the context for tinyrl */ context.cmd = NULL; context.pargv = NULL; context.shell = this; /* Push the specified line or interactive line */ if (line) str = tinyrl_forceline(this->tinyrl, &context, line); else str = tinyrl_readline(this->tinyrl, &context); lerror = errno; if (!str) { switch (lerror) { case ENOENT: this->state = SHELL_STATE_EOF; break; case ENOEXEC: this->state = SHELL_STATE_SYNTAX_ERROR; break; default: this->state = SHELL_STATE_SYSTEM_ERROR; break; }; return -1; } /* Deal with the history list */ if (tinyrl__get_isatty(this->tinyrl)) { history = tinyrl__get_history(this->tinyrl); tinyrl_history_add(history, str); } /* Let the client know the command line has been entered */ if (this->client_hooks->cmd_line_fn) this->client_hooks->cmd_line_fn(&context, str); free(str); /* Execute the provided command */ if (context.cmd && context.pargv) { int res; if ((res = clish_shell_execute(&context, out))) { this->state = SHELL_STATE_SCRIPT_ERROR; if (context.pargv) clish_pargv_delete(context.pargv); return res; } } if (context.pargv) clish_pargv_delete(context.pargv); return 0; } /*-------------------------------------------------------- */ int clish_shell_forceline(clish_shell_t *this, const char *line, char **out) { return clish_shell_execline(this, line, out); } /*-------------------------------------------------------- */ int clish_shell_readline(clish_shell_t *this, char **out) { return clish_shell_execline(this, NULL, out); } /*-------------------------------------------------------- */ FILE * clish_shell__get_istream(const clish_shell_t * this) { return tinyrl__get_istream(this->tinyrl); } /*-------------------------------------------------------- */ FILE * clish_shell__get_ostream(const clish_shell_t * this) { return tinyrl__get_ostream(this->tinyrl); } /*-------------------------------------------------------- */ void clish_shell__set_interactive(clish_shell_t * this, bool_t interactive) { assert(this); this->interactive = interactive; } /*-------------------------------------------------------- */ bool_t clish_shell__get_interactive(const clish_shell_t * this) { assert(this); return this->interactive; } /*-------------------------------------------------------- */ bool_t clish_shell__get_utf8(const clish_shell_t * this) { assert(this); return tinyrl__get_utf8(this->tinyrl); } /*-------------------------------------------------------- */ void clish_shell__set_utf8(clish_shell_t * this, bool_t utf8) { assert(this); tinyrl__set_utf8(this->tinyrl, utf8); } /*-------------------------------------------------------- */ void clish_shell__set_timeout(clish_shell_t *this, int timeout) { assert(this); this->idle_timeout = timeout; } /*--------------------------------------------------------- */ tinyrl_t *clish_shell__get_tinyrl(const clish_shell_t * this) { return this->tinyrl; } /*----------------------------------------------------------*/ int clish_shell__save_history(const clish_shell_t *this, const char *fname) { return tinyrl__save_history(this->tinyrl, fname); } /*----------------------------------------------------------*/ int clish_shell__restore_history(clish_shell_t *this, const char *fname) { return tinyrl__restore_history(this->tinyrl, fname); } /*----------------------------------------------------------*/ void clish_shell__stifle_history(clish_shell_t *this, unsigned int stifle) { tinyrl__stifle_history(this->tinyrl, stifle); } /*-------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_tinyrl.c
C
bsd
15,681
/* * ------------------------------------------------------ * shell_expat.c * * This file implements the means to read an XML encoded file * and populate the CLI tree based on the contents. It implements * the clish_xml API using the expat XML parser * * expat is not your typicall XML parser. It does not work * by creating a full in-memory XML tree, but by calling specific * callbacks (element handlers) regularly while parsing. It's up * to the user to create the corresponding XML tree if needed * (obviously, this is what we're doing, as we really need the XML * tree in klish). * * The code below do that. It transforms the output of expat * to a DOM representation of the underlying XML file. This is * a bit overkill, and maybe a later implementation will help to * cut the work to something simpler, but the current klish * implementation requires this. * ------------------------------------------------------ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #if defined(HAVE_LIB_EXPAT) #include <string.h> #include <stdlib.h> #include <sys/fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <expat.h> #include "xmlapi.h" /** DOM_like XML node * * @struct clish_xmlnode_s */ struct clish_xmlnode_s { char *name; clish_xmlnode_t *parent; /**< parent node */ clish_xmlnode_t *children; /**< list of children */ clish_xmlnode_t *next; /**< next sibling */ clish_xmlnode_t *attributes; /**< attributes are nodes too */ char *content; /**< !NULL for text and attributes nodes */ clish_xmlnodetype_t type; /**< node type */ int depth; /**< node depth */ clish_xmldoc_t *doc; }; /** DOM-like XML document * * @struct clish_xmldoc_s */ struct clish_xmldoc_s { clish_xmlnode_t *root; /**< list of root elements */ clish_xmlnode_t *current; /**< current element */ char *filename; /**< current filename */ }; /* * Expat need these functions to be able to build a DOM-like tree that * will be usable by klish. */ /** Put a element at the and of an element list * * @param first first element of the list * @param node element to add * @return new first element of the list */ static clish_xmlnode_t *clish_expat_list_push_back(clish_xmlnode_t *first, clish_xmlnode_t *node) { clish_xmlnode_t *cur = first; clish_xmlnode_t *prev = NULL; while (cur) { prev = cur; cur = cur->next; } if (prev) { prev->next = node; return first; } return node; } /** Generic add_attr() function * * @param first first attribute in the attribute list * @param n attribute name * @param v attribute value * @return the new first attribute in the attribute list */ static clish_xmlnode_t *clish_expat_add_attr(clish_xmlnode_t *first, const char *n, const char *v) { clish_xmlnode_t *node; node = malloc(sizeof(clish_xmlnode_t)); if (!node) return first; node->name = strdup(n); node->content = strdup(v); node->children = NULL; node->attributes = NULL; node->next = NULL; node->type = CLISH_XMLNODE_ATTR; node->depth = 0; return clish_expat_list_push_back(first, node); } /** Run through an expat attribute list, and create a DOM-like attribute list * * @param node parent node * @param attr NULL-terminated attribute liste * * Each attribute uses two slots in the expat attribute list. The first one is * used to store the name, the second one is used to store the value. */ static void clish_expat_add_attrlist(clish_xmlnode_t *node, const char **attr) { int i; for (i = 0; attr[i]; i += 2) { node->attributes = clish_expat_add_attr(node->attributes, attr[i], attr[i+1]); } } /** Generic make_node() function * * @param parent XML parent node * @param type XML node type * @param n node name (can be NULL, strdup'ed) * @param v node content (can be NULL, strdup'ed) * @param attr attribute list * @return a new node or NULL on error */ static clish_xmlnode_t *clish_expat_make_node(clish_xmlnode_t *parent, clish_xmlnodetype_t type, const char *n, const char *v, const char **attr) { clish_xmlnode_t *node; node = malloc(sizeof(clish_xmlnode_t)); if (!node) return NULL; node->name = n ? strdup(n) : NULL; node->content = v ? strdup(v) : NULL; node->children = NULL; node->attributes = NULL; node->next = NULL; node->parent = parent; node->doc = parent ? parent->doc : NULL; node->depth = parent ? parent->depth + 1 : 0; node->type = type; if (attr) clish_expat_add_attrlist(node, attr); if (parent) parent->children = clish_expat_list_push_back(parent->children, node); return node; } /** Add a new XML root * * @param doc XML document * @param el root node name * @param attr expat attribute list * @return a new root element */ static clish_xmlnode_t *clish_expat_add_root(clish_xmldoc_t *doc, const char *el, const char **attr) { clish_xmlnode_t *node; node = clish_expat_make_node(NULL, CLISH_XMLNODE_ELM, el, NULL, attr); if (!node) return doc->root; doc->root = clish_expat_list_push_back(doc->root, node); return node; } /** Add a new XML element as a child * * @param cur parent XML element * @param el element name * @param attr expat attribute list * @return a new XMl element */ static clish_xmlnode_t *clish_expat_add_child(clish_xmlnode_t *cur, const char *el, const char **attr) { clish_xmlnode_t *node; node = clish_expat_make_node(cur, CLISH_XMLNODE_ELM, el, NULL, attr); if (!node) return cur; return node; } /** Expat handler: element content * * @param data user data * @param s content (not nul-termainated) * @param len content length */ static void clish_expat_chardata_handler(void *data, const char *s, int len) { clish_xmldoc_t *doc = data; if (doc->current) { char *content = strndup(s, len); clish_expat_make_node(doc->current, CLISH_XMLNODE_TEXT, NULL, content, NULL); /* * the previous call is a bit too generic, and strdup() content * so we need to free out own version of content. */ free(content); } } /** Expat handler: start XML element * * @param data user data * @param el element name (nul-terminated) * @param attr expat attribute list */ static void clish_expat_element_start(void *data, const char *el, const char **attr) { clish_xmldoc_t *doc = data; if (!doc->current) { doc->current = clish_expat_add_root(doc, el, attr); } else { doc->current = clish_expat_add_child(doc->current, el, attr); } } /** Expat handler: end XML element * * @param data user data * @param el element name */ static void clish_expat_element_end(void *data, const char *el) { clish_xmldoc_t *doc = data; if (doc->current) { doc->current = doc->current->parent; } } /** Free a node, its children and its attributes * * @param node node to free */ static void clish_expat_free_node(clish_xmlnode_t *cur) { clish_xmlnode_t *node; clish_xmlnode_t *first; if (cur->attributes) { first = cur->attributes; while (first) { node = first; first = first->next; clish_expat_free_node(node); } } if (cur->children) { first = cur->children; while (first) { node = first; first = first->next; clish_expat_free_node(node); } } if (cur->name) free(cur->name); if (cur->content) free(cur->content); free(cur); } /* * Public interface */ clish_xmldoc_t *clish_xmldoc_read(const char *filename) { clish_xmldoc_t *doc; struct stat sb; int fd; char *buffer; XML_Parser parser; doc = malloc(sizeof(clish_xmldoc_t)); if (!doc) return NULL; memset(doc, 0, sizeof(clish_xmldoc_t)); doc->filename = strdup(filename); parser = XML_ParserCreate(NULL); if (!parser) goto error_parser_create; XML_SetUserData(parser, doc); XML_SetCharacterDataHandler(parser, clish_expat_chardata_handler); XML_SetElementHandler(parser, clish_expat_element_start, clish_expat_element_end); fd = open(filename, O_RDONLY); if (fd < 0) goto error_open; fstat(fd, &sb); buffer = malloc(sb.st_size+1); read(fd, buffer, sb.st_size); buffer[sb.st_size] = 0; close(fd); if (!XML_Parse(parser, buffer, sb.st_size, 1)) goto error_parse; XML_ParserFree(parser); free(buffer); return doc; error_parse: free(buffer); error_open: XML_ParserFree(parser); error_parser_create: clish_xmldoc_release(doc); return NULL; } void clish_xmldoc_release(clish_xmldoc_t *doc) { if (doc) { clish_xmlnode_t *node; while (doc->root) { node = doc->root; doc->root = node->next; clish_expat_free_node(node); } if (doc->filename) free(doc->filename); free(doc); } } int clish_xmldoc_is_valid(clish_xmldoc_t *doc) { return doc && doc->root; } int clish_xmldoc_error_caps(clish_xmldoc_t *doc) { return CLISH_XMLERR_NOCAPS; } int clish_xmldoc_get_err_line(clish_xmldoc_t *doc) { return -1; } int clish_xmldoc_get_err_col(clish_xmldoc_t *doc) { return -1; } const char *clish_xmldoc_get_err_msg(clish_xmldoc_t *doc) { return ""; } int clish_xmlnode_get_type(clish_xmlnode_t *node) { if (node) return node->type; return CLISH_XMLNODE_UNKNOWN; } clish_xmlnode_t *clish_xmldoc_get_root(clish_xmldoc_t *doc) { if (doc) return doc->root; return NULL; } clish_xmlnode_t *clish_xmlnode_parent(clish_xmlnode_t *node) { if (node) return node->parent; return NULL; } clish_xmlnode_t *clish_xmlnode_next_child(clish_xmlnode_t *parent, clish_xmlnode_t *curchild) { if (curchild) return curchild->next; if (parent) return parent->children; return NULL; } char *clish_xmlnode_fetch_attr(clish_xmlnode_t *node, const char *attrname) { if (node) { clish_xmlnode_t *n = node->attributes; while (n) { if (strcmp(n->name, attrname) == 0) return n->content; n = n->next; } } return NULL; } int clish_xmlnode_get_content(clish_xmlnode_t *node, char *content, unsigned int *contentlen) { int minlen = 1; if (node && content && contentlen) { clish_xmlnode_t *children = node->children; while (children) { if (children->type == CLISH_XMLNODE_TEXT && children->content) minlen += strlen(children->content); children = children->next; } if (minlen >= *contentlen) { *contentlen = minlen + 1; return -E2BIG; } children = node->children; *content = 0; while (children) { if (children->type == CLISH_XMLNODE_TEXT && children->content) strcat(content, children->content); children = children->next; } return 0; } return -EINVAL; } int clish_xmlnode_get_name(clish_xmlnode_t *node, char *name, unsigned int *namelen) { if (node && name && namelen) { if (strlen(node->name) >= *namelen) { *namelen = strlen(node->name) + 1; return -E2BIG; } sprintf(name, "%s", node->name); return 0; } return -EINVAL; } void clish_xmlnode_print(clish_xmlnode_t *node, FILE *out) { if (node) { int i; clish_xmlnode_t *a; for (i=0; i<node->depth; ++i) { fprintf(out, " "); } fprintf(out, "<%s", node->name); a = node->attributes; while (a) { fprintf(out, " %s='%s'", a->name, a->content); a = a->next; } fprintf(out, ">..."); } } void clish_xml_release(void *p) { /* nothing to release */ } #endif /* HAVE_LIB_EXPAT */
zzysjtu-klish
clish/shell/shell_expat.c
C
bsd
11,106
/* * shell_new.c */ #include "private.h" #include <assert.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "lub/string.h" #include "lub/db.h" /*-------------------------------------------------------- */ static void clish_shell_init(clish_shell_t * this, const clish_shell_hooks_t * hooks, void *cookie, FILE * istream, FILE * ostream, bool_t stop_on_error) { clish_ptype_t *tmp_ptype = NULL; /* initialise the tree of views */ lub_bintree_init(&this->view_tree, clish_view_bt_offset(), clish_view_bt_compare, clish_view_bt_getkey); /* initialise the tree of ptypes */ lub_bintree_init(&this->ptype_tree, clish_ptype_bt_offset(), clish_ptype_bt_compare, clish_ptype_bt_getkey); /* initialise the tree of vars */ lub_bintree_init(&this->var_tree, clish_var_bt_offset(), clish_var_bt_compare, clish_var_bt_getkey); assert((NULL != hooks) && (NULL != hooks->script_fn)); /* set up defaults */ this->client_hooks = hooks; this->client_cookie = cookie; this->global = NULL; this->startup = NULL; this->idle_timeout = 0; /* No idle timeout by default */ this->wdog = NULL; this->wdog_timeout = 0; /* No watchdog timeout by default */ this->wdog_active = BOOL_FALSE; this->state = SHELL_STATE_INITIALISING; this->overview = NULL; this->tinyrl = clish_shell_tinyrl_new(istream, ostream, 0); this->current_file = NULL; this->pwdv = NULL; this->pwdc = 0; this->depth = -1; /* Current depth is undefined */ this->client = NULL; this->lockfile = lub_string_dup(CLISH_LOCK_PATH); this->default_shebang = lub_string_dup("/bin/sh"); this->fifo_name = NULL; this->interactive = BOOL_TRUE; /* The interactive shell by default. */ this->log = BOOL_FALSE; /* Disable logging by default */ this->user = lub_db_getpwuid(getuid()); /* Get user information */ /* Create internal ptypes and params */ /* Current depth */ tmp_ptype = clish_shell_find_create_ptype(this, "__DEPTH", "Depth", "[0-9]+", CLISH_PTYPE_REGEXP, CLISH_PTYPE_NONE); assert(tmp_ptype); this->param_depth = clish_param_new("_cur_depth", "Current depth", tmp_ptype); clish_param__set_hidden(this->param_depth, BOOL_TRUE); /* Current pwd */ tmp_ptype = clish_shell_find_create_ptype(this, "__PWD", "Path", ".+", CLISH_PTYPE_REGEXP, CLISH_PTYPE_NONE); assert(tmp_ptype); this->param_pwd = clish_param_new("_cur_pwd", "Current path", tmp_ptype); clish_param__set_hidden(this->param_pwd, BOOL_TRUE); /* Args */ tmp_ptype = clish_shell_find_create_ptype(this, "internal_ARGS", "Arguments", "[^\\\\]+", CLISH_PTYPE_REGEXP, CLISH_PTYPE_NONE); assert(tmp_ptype); /* Push non-NULL istream */ if (istream) clish_shell_push_fd(this, istream, stop_on_error); } /*--------------------------------------------------------- */ static void clish_shell_fini(clish_shell_t * this) { clish_view_t *view; clish_ptype_t *ptype; clish_var_t *var; unsigned i; /* delete each VIEW held */ while ((view = lub_bintree_findfirst(&this->view_tree))) { lub_bintree_remove(&this->view_tree, view); clish_view_delete(view); } /* delete each PTYPE held */ while ((ptype = lub_bintree_findfirst(&this->ptype_tree))) { lub_bintree_remove(&this->ptype_tree, ptype); clish_ptype_delete(ptype); } /* delete each VAR held */ while ((var = lub_bintree_findfirst(&this->var_tree))) { lub_bintree_remove(&this->var_tree, var); clish_var_delete(var); } /* free the textual details */ lub_string_free(this->overview); /* Remove the startup command */ if (this->startup) clish_command_delete(this->startup); /* Remove the watchdog command */ if (this->wdog) clish_command_delete(this->wdog); /* clean up the file stack */ while (!clish_shell_pop_file(this)); /* delete the tinyrl object */ clish_shell_tinyrl_delete(this->tinyrl); /* finalize each of the pwd strings */ for (i = 0; i < this->pwdc; i++) { clish_shell__fini_pwd(this->pwdv[i]); free(this->pwdv[i]); } /* free the pwd vector */ free(this->pwdv); konf_client_free(this->client); /* Free internal params */ clish_param_delete(this->param_depth); clish_param_delete(this->param_pwd); lub_string_free(this->lockfile); lub_string_free(this->default_shebang); free(this->user); if (this->fifo_name) { unlink(this->fifo_name); lub_string_free(this->fifo_name); } } /*-------------------------------------------------------- */ clish_shell_t *clish_shell_new(const clish_shell_hooks_t * hooks, void *cookie, FILE * istream, FILE * ostream, bool_t stop_on_error) { clish_shell_t *this = malloc(sizeof(clish_shell_t)); if (this) { clish_shell_init(this, hooks, cookie, istream, ostream, stop_on_error); if (hooks->init_fn) { /* now call the client initialisation */ if (BOOL_TRUE != hooks->init_fn(this)) this->state = SHELL_STATE_CLOSING; } } return this; } /*--------------------------------------------------------- */ void clish_shell_delete(clish_shell_t * this) { /* now call the client finalisation */ if (this->client_hooks->fini_fn) this->client_hooks->fini_fn(this); clish_shell_fini(this); free(this); } /*--------------------------------------------------------- */ struct passwd *clish_shell__get_user(clish_shell_t * this) { return this->user; } /*-------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_new.c
C
bsd
5,314
/* * ------------------------------------------------------ * shell_roxml.c * * This file implements the means to read an XML encoded file * and populate the CLI tree based on the contents. It implements * the clish_xml API using roxml * ------------------------------------------------------ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #if defined(HAVE_LIB_ROXML) #include <errno.h> #include <roxml.h> #include "xmlapi.h" /* dummy stuff ; really a node_t */ struct clish_xmldoc_s { int dummy; }; /* dummy stuff ; really a node_t */ struct clish_xmlnode_s { int dummy; }; static inline node_t *xmldoc_to_node(clish_xmldoc_t *doc) { return (node_t*)doc; } static inline node_t *xmlnode_to_node(clish_xmlnode_t *node) { return (node_t*)node; } static inline clish_xmldoc_t *node_to_xmldoc(node_t *node) { return (clish_xmldoc_t*)node; } static inline clish_xmlnode_t *node_to_xmlnode(node_t *node) { return (clish_xmlnode_t*)node; } /* * public interface */ clish_xmldoc_t *clish_xmldoc_read(const char *filename) { node_t *doc = roxml_load_doc((char*)filename); return node_to_xmldoc(doc); } void clish_xmldoc_release(clish_xmldoc_t *doc) { if (doc) { node_t *node = xmldoc_to_node(doc); roxml_release(RELEASE_ALL); roxml_close(node); } } int clish_xmldoc_is_valid(clish_xmldoc_t *doc) { return doc != NULL; } int clish_xmldoc_error_caps(clish_xmldoc_t *doc) { return CLISH_XMLERR_NOCAPS; } int clish_xmldoc_get_err_line(clish_xmldoc_t *doc) { return -1; } int clish_xmldoc_get_err_col(clish_xmldoc_t *doc) { return -1; } const char *clish_xmldoc_get_err_msg(clish_xmldoc_t *doc) { return ""; } int clish_xmlnode_get_type(clish_xmlnode_t *node) { if (node) { int type = roxml_get_type(xmlnode_to_node(node)); switch (type) { case ROXML_ELM_NODE: return CLISH_XMLNODE_ELM; case ROXML_TXT_NODE: return CLISH_XMLNODE_TEXT; case ROXML_CMT_NODE: return CLISH_XMLNODE_COMMENT; case ROXML_PI_NODE: return CLISH_XMLNODE_PI; case ROXML_ATTR_NODE: return CLISH_XMLNODE_ATTR; default: break; } } return CLISH_XMLNODE_UNKNOWN; } clish_xmlnode_t *clish_xmldoc_get_root(clish_xmldoc_t *doc) { if (doc) { node_t *root = roxml_get_root(xmldoc_to_node(doc)); return node_to_xmlnode(root); } return NULL; } clish_xmlnode_t *clish_xmlnode_parent(clish_xmlnode_t *node) { if (node) { node_t *roxn = xmlnode_to_node(node); node_t *root = roxml_get_root(roxn); if (roxn != root) return node_to_xmlnode(roxml_get_parent(roxn)); } return NULL; } clish_xmlnode_t *clish_xmlnode_next_child(clish_xmlnode_t *parent, clish_xmlnode_t *curchild) { node_t *roxc; if (!parent) return NULL; roxc = xmlnode_to_node(curchild); if (roxc) { return node_to_xmlnode(roxml_get_next_sibling(roxc)); } else { node_t *roxp = xmlnode_to_node(parent); node_t *child = NULL; int count; count = roxml_get_chld_nb(roxp); if (count) child = roxml_get_chld(roxp, NULL, 0); return node_to_xmlnode(child); } return NULL; } static int i_is_needle(char *src, const char *needle) { int nlen = strlen(needle); int slen = strlen(src); if (slen >= nlen) { if (strncmp(src, needle, nlen) == 0) return 1; } return 0; } /* warning: dst == src is valid */ static void i_decode_and_copy(char *dst, char *src) { while (*src) { if (*src == '&') { if (i_is_needle(src, "&lt;")) { *dst++ = '<'; src += 4; } else if (i_is_needle(src, "&gt;")) { *dst++ = '>'; src += 4; } else if (i_is_needle(src, "&amp;")) { *dst++ = '&'; src += 5; } else { *dst++ = *src++; } } else { *dst++ = *src++; } } *dst++ = 0; } char *clish_xmlnode_fetch_attr(clish_xmlnode_t *node, const char *attrname) { node_t *roxn; node_t *attr; char *content; if (!node || !attrname) return NULL; roxn = xmlnode_to_node(node); attr = roxml_get_attr(roxn, (char*)attrname, 0); content = roxml_get_content(attr, NULL, 0, NULL); if (content) { i_decode_and_copy(content, content); } return content; } static int i_get_content(node_t *n, char *v, unsigned int *vl) { char *c; int len; c = roxml_get_content(n, NULL, 0, NULL); if (c) { len = strlen(c) + 1; if (len <= *vl) { i_decode_and_copy(v, c); roxml_release(c); return 0; } else { *vl = len; roxml_release(c); return -E2BIG; } } *vl = (unsigned int)-1; return -ENOMEM; } int clish_xmlnode_get_content(clish_xmlnode_t *node, char *content, unsigned int *contentlen) { if (content && contentlen && *contentlen) *content = 0; if (!node || !content || !contentlen) return -EINVAL; if (*contentlen <= 1) return -EINVAL; *content = 0; return i_get_content(xmlnode_to_node(node), content, contentlen); } static int i_get_name(node_t *n, char *v, unsigned int *vl) { char *c; int len; c = roxml_get_name(n, NULL, 0); if (c) { len = strlen(c) + 1; if (len <= *vl) { sprintf(v, "%s", c); roxml_release(c); return 0; } else { *vl = len; roxml_release(c); return -E2BIG; } } *vl = (unsigned int)-1; return -ENOMEM; } int clish_xmlnode_get_name(clish_xmlnode_t *node, char *name, unsigned int *namelen) { if (name && namelen && *namelen) *name = 0; if (!node || !name || !namelen) return -EINVAL; if (*namelen <= 1) return -EINVAL; *name = 0; return i_get_name(xmlnode_to_node(node), name, namelen); } void clish_xmlnode_print(clish_xmlnode_t *node, FILE *out) { node_t *roxn; char *name; roxn = xmlnode_to_node(node); name = roxml_get_name(roxn, NULL, 0); if (name) { fprintf(out, "<%s", name); roxml_release(name); if (roxml_get_attr_nb(roxn)) { int attr_count = roxml_get_attr_nb(roxn); int attr_pos; for (attr_pos = 0; attr_pos < attr_count; ++attr_pos) { node_t *attr = roxml_get_attr(roxn, NULL, attr_pos); char *n = roxml_get_name(attr, NULL, 0); char *v = roxml_get_content(attr, NULL, 0, NULL); if (n && v) { fprintf(out, " %s='%s'", n, v); } if (v) roxml_release(v); if (n) roxml_release(n); } } fprintf(out, ">"); } } void clish_xml_release(void *p) { if (p) { roxml_release(p); } } #endif /* HAVE_LIB_ROXML */
zzysjtu-klish
clish/shell/shell_roxml.c
C
bsd
6,217
/* * shell.h - private interface to the shell class */ #include "lub/bintree.h" #include "tinyrl/tinyrl.h" #include "clish/shell.h" #include "clish/pargv.h" #include "clish/var.h" #include "clish/action.h" /*------------------------------------- * PRIVATE TYPES *------------------------------------- */ /*-------------------------------------------------------- */ /* * iterate around commands */ typedef struct { const char *last_cmd; clish_nspace_visibility_t field; } clish_shell_iterator_t; /* this is used to maintain a stack of file handles */ typedef struct clish_shell_file_s clish_shell_file_t; struct clish_shell_file_s { clish_shell_file_t *next; FILE *file; char *fname; unsigned int line; bool_t stop_on_error; /* stop on error for file input */ }; typedef struct { char *line; clish_view_t *view; lub_bintree_t viewid; } clish_shell_pwd_t; struct clish_shell_s { lub_bintree_t view_tree; /* Maintain a tree of views */ lub_bintree_t ptype_tree; /* Maintain a tree of ptypes */ lub_bintree_t var_tree; /* Maintain a tree of global variables */ const clish_shell_hooks_t *client_hooks; /* Client callback hooks */ void *client_cookie; /* Client callback cookie */ clish_view_t *global; /* Reference to the global view. */ clish_command_t *startup; /* This is the startup command */ unsigned int idle_timeout; /* This is the idle timeout */ clish_command_t *wdog; /* This is the watchdog command */ unsigned int wdog_timeout; /* This is the watchdog timeout */ bool_t wdog_active; /* If watchdog is active now */ clish_shell_state_t state; /* The current state */ char *overview; /* Overview text for this shell */ tinyrl_t *tinyrl; /* Tiny readline instance */ clish_shell_file_t *current_file; /* file currently in use for input */ clish_shell_pwd_t **pwdv; /* Levels for the config file structure */ unsigned int pwdc; int depth; konf_client_t *client; char *lockfile; char *default_shebang; char *fifo_name; /* The name of temporary fifo file. */ bool_t interactive; /* Is shell interactive. */ bool_t log; /* If command logging is enabled */ struct passwd *user; /* Current user information */ /* Static params for var expanding. The refactoring is needed. */ clish_param_t *param_depth; clish_param_t *param_pwd; }; /** * Initialise a command iterator structure */ void clish_shell_iterator_init(clish_shell_iterator_t * iter, clish_nspace_visibility_t field); /** * get the next command which is an extension of the specified line */ const clish_command_t *clish_shell_find_next_completion(const clish_shell_t * instance, const char *line, clish_shell_iterator_t * iter); /** * Pop the current file handle from the stack of file handles, shutting * the file down and freeing any associated memory. The next file handle * in the stack becomes associated with the input stream for this shell. * * \return * BOOL_TRUE - the current file handle has been replaced. * BOOL_FALSE - there is only one handle on the stack which cannot be replaced. */ int clish_shell_pop_file(clish_shell_t * instance); clish_view_t *clish_shell_find_view(clish_shell_t * instance, const char *name); void clish_shell_insert_view(clish_shell_t * instance, clish_view_t * view); clish_pargv_status_t clish_shell_parse(clish_shell_t * instance, const char *line, const clish_command_t ** cmd, clish_pargv_t ** pargv); clish_pargv_status_t clish_shell_parse_pargv(clish_pargv_t *pargv, const clish_command_t *cmd, void *context, clish_paramv_t *paramv, const lub_argv_t *argv, unsigned *idx, clish_pargv_t *last, unsigned need_index); char *clish_shell_word_generator(clish_shell_t * instance, const char *line, unsigned offset, unsigned state); const clish_command_t *clish_shell_resolve_command(const clish_shell_t * instance, const char *line); const clish_command_t *clish_shell_resolve_prefix(const clish_shell_t * instance, const char *line); void clish_shell_insert_ptype(clish_shell_t * instance, clish_ptype_t * ptype); void clish_shell_tinyrl_history(clish_shell_t * instance, unsigned int *limit); tinyrl_t *clish_shell_tinyrl_new(FILE * instream, FILE * outstream, unsigned stifle); void clish_shell_tinyrl_delete(tinyrl_t * instance); void clish_shell_param_generator(clish_shell_t * instance, lub_argv_t *matches, const clish_command_t * cmd, const char *line, unsigned offset); char **clish_shell_tinyrl_completion(tinyrl_t * tinyrl, const char *line, unsigned start, unsigned end); void clish_shell__expand_viewid(const char *viewid, lub_bintree_t *tree, clish_context_t *context); void clish_shell__init_pwd(clish_shell_pwd_t *pwd); void clish_shell__fini_pwd(clish_shell_pwd_t *pwd); int clish_shell_timeout_fn(tinyrl_t *tinyrl); int clish_shell_keypress_fn(tinyrl_t *tinyrl, int key);
zzysjtu-klish
clish/shell/private.h
C
bsd
4,777
/* * xmlapi.h * * private klish file: internal XML API */ #ifndef clish_xmlapi_included_h #define clish_xmlapi_included_h #include <stdlib.h> #include <errno.h> #include <stdio.h> /* need for FILE */ /* * XML document (opaque type) * The real type is defined by the selected external API */ typedef struct clish_xmldoc_s clish_xmldoc_t; /* * XML node (opaque type) * The real type is defined by the selected external API */ typedef struct clish_xmlnode_s clish_xmlnode_t; /* * read an XML document */ clish_xmldoc_t *clish_xmldoc_read(const char *filename); /* * release a previously opened XML document */ void clish_xmldoc_release(clish_xmldoc_t *doc); /* * check if a doc is valid (i.e. it loaded successfully) */ int clish_xmldoc_is_valid(clish_xmldoc_t *doc); /* * XML implementation error capabilitiess * The real capabilities is or'ed using the following * constants */ typedef enum { CLISH_XMLERR_NOCAPS = 0, CLISH_XMLERR_LINE = 0x10, CLISH_XMLERR_COL = 0x20, CLISH_XMLERR_DESC = 0x40 } clish_xmlerrcaps_t; /* * does this specific implementation define any error? * -> get the capabilities */ int clish_xmldoc_error_caps(clish_xmldoc_t *doc); typedef enum { CLISH_XMLNODE_DOC, CLISH_XMLNODE_ELM, CLISH_XMLNODE_TEXT, CLISH_XMLNODE_ATTR, CLISH_XMLNODE_COMMENT, CLISH_XMLNODE_PI, CLISH_XMLNODE_DECL, CLISH_XMLNODE_UNKNOWN, } clish_xmlnodetype_t; /* * get error description, when available */ int clish_xmldoc_get_err_line(clish_xmldoc_t *doc); int clish_xmldoc_get_err_col(clish_xmldoc_t *doc); const char *clish_xmldoc_get_err_msg(clish_xmldoc_t *doc); /* * get the node type */ int clish_xmlnode_get_type(clish_xmlnode_t *node); /* * get the document root */ clish_xmlnode_t *clish_xmldoc_get_root(clish_xmldoc_t *doc); /* * get the next child or NULL. If curchild is NULL, * then the function returns the first child. */ clish_xmlnode_t *clish_xmlnode_next_child( clish_xmlnode_t *parent, clish_xmlnode_t *curchild); /* * get the parent node. * returns NULL if node is the document root node. */ clish_xmlnode_t *clish_xmlnode_parent(clish_xmlnode_t *node); /* * get the node name. * neither name not namelen shall be NULL. *namelen is the length of the * name buffer. If it's too small, we return -E2BIG and set *namelen to * the minimum length value. * returns < 0 on error. On error, name shall not be modified. */ int clish_xmlnode_get_name( clish_xmlnode_t *node, char *name, unsigned int *namelen); /* * get the node name * dynamically allocate the buffer (it must be freed once you don't need it * anymore) that will contain all the content of the node. * return NULL on error. */ static inline char* clish_xmlnode_get_all_name(clish_xmlnode_t *node) { char *name = NULL; unsigned int nlen = 2048; int result; do { name = (char*)realloc(name, nlen); result = clish_xmlnode_get_name(node, name, &nlen); } while (result == -E2BIG); if (result < 0) { free(name); return NULL; } return name; } /* * get the node content. * neither content not contentlen shall be NULL. *contentlen is the length * of the content buffer. If it's too small, we return -E2BIG and set * *contentlen to the minimum length value (including space for the \0 * character) so that two subsequent calls to this functions are going * to succeed if the forst one failed because of a too small buffer. * returns < 0 on error. On error, content shall not be modified. */ int clish_xmlnode_get_content( clish_xmlnode_t *node, char *content, unsigned int *contentlen); /* * get the node content * dynamically allocate the buffer (it must be freed once you don't need it * anymore) that will contain all the content of the node. * return NULL on error. */ static inline char* clish_xmlnode_get_all_content(clish_xmlnode_t *node) { char *content = NULL; unsigned int clen = 2048; int result; do { content = (char*)realloc(content, clen); result = clish_xmlnode_get_content(node, content, &clen); } while (result == -E2BIG); if (result < 0) { free(content); return NULL; } return content; } /* * get an attribute by name. May return NULL if the * attribute is not found * Special: allocate memory (to free with clish_xml_release()) */ char *clish_xmlnode_fetch_attr( clish_xmlnode_t *node, const char *attrname); /* * Free a pointer allocated by the XML backend */ void clish_xml_release(void *p); /* * print an XML node to the out file */ void clish_xmlnode_print(clish_xmlnode_t *node, FILE *out); #endif /* clish_xmlapi_included_h */
zzysjtu-klish
clish/shell/xmlapi.h
C
bsd
4,583
/* * shell_help.c */ #include "private.h" #include "clish/types.h" #include "lub/string.h" #include <stdio.h> #include <string.h> #include <ctype.h> /*--------------------------------------------------------- */ /* * Provide a detailed list of the possible command completions */ static void available_commands(clish_shell_t *this, clish_help_t *help, const char *line, size_t *max_width) { const clish_command_t *cmd; clish_shell_iterator_t iter; if (max_width) *max_width = 0; /* Search for COMMAND completions */ clish_shell_iterator_init(&iter, CLISH_NSPACE_HELP); while ((cmd = clish_shell_find_next_completion(this, line, &iter))) { size_t width; const char *name = clish_command__get_suffix(cmd); if (max_width) { width = strlen(name); if (width > *max_width) *max_width = width; } lub_argv_add(help->name, name); lub_argv_add(help->help, clish_command__get_text(cmd)); lub_argv_add(help->detail, clish_command__get_detail(cmd)); } } /*--------------------------------------------------------- */ static int available_params(clish_shell_t *this, clish_help_t *help, const clish_command_t *cmd, const char *line, size_t *max_width) { unsigned index = lub_argv_wordcount(line); unsigned idx = lub_argv_wordcount(clish_command__get_name(cmd)); lub_argv_t *argv; clish_pargv_t *completion, *pargv; unsigned i; unsigned cnt = 0; clish_pargv_status_t status = CLISH_LINE_OK; clish_context_t context; /* Empty line */ if (0 == index) return -1; if (line[strlen(line) - 1] != ' ') index--; argv = lub_argv_new(line, 0); /* get the parameter definition */ completion = clish_pargv_new(); pargv = clish_pargv_new(); context.shell = this; context.cmd = cmd; context.pargv = pargv; status = clish_shell_parse_pargv(pargv, cmd, &context, clish_command__get_paramv(cmd), argv, &idx, completion, index); clish_pargv_delete(pargv); cnt = clish_pargv__get_count(completion); /* Calculate the longest name */ for (i = 0; i < cnt; i++) { const clish_param_t *param; const char *name; unsigned clen = 0; param = clish_pargv__get_param(completion, i); if (CLISH_PARAM_SUBCOMMAND == clish_param__get_mode(param)) name = clish_param__get_value(param); else name = clish_ptype__get_text(clish_param__get_ptype(param)); if (name) clen = strlen(name); if (max_width && (clen > *max_width)) *max_width = clen; clish_param_help(param, help); } clish_pargv_delete(completion); lub_argv_delete(argv); /* It's a completed command */ if (CLISH_LINE_OK == status) return 0; /* Incompleted command */ return -1; } /*--------------------------------------------------------- */ void clish_shell_help(clish_shell_t *this, const char *line) { clish_help_t help; size_t max_width = 0; const clish_command_t *cmd; int i; help.name = lub_argv_new(NULL, 0); help.help = lub_argv_new(NULL, 0); help.detail = lub_argv_new(NULL, 0); /* Get COMMAND completions */ available_commands(this, &help, line, &max_width); /* Resolve a command */ cmd = clish_shell_resolve_command(this, line); /* Search for PARAM completion */ if (cmd) { size_t width = 0; int status; status = available_params(this, &help, cmd, line, &width); if (width > max_width) max_width = width; /* Add <cr> if command is completed */ if (!status) { lub_argv_add(help.name, "<cr>"); lub_argv_add(help.help, NULL); lub_argv_add(help.detail, NULL); } } if (lub_argv__get_count(help.name) == 0) goto end; /* Print help messages */ for (i = 0; i < lub_argv__get_count(help.name); i++) { fprintf(stderr, " %-*s %s\n", (int)max_width, lub_argv__get_arg(help.name, i), lub_argv__get_arg(help.help, i) ? lub_argv__get_arg(help.help, i) : ""); } /* Print details */ if ((lub_argv__get_count(help.name) == 1) && (SHELL_STATE_HELPING == this->state)) { const char *detail = lub_argv__get_arg(help.detail, 0); if (detail) fprintf(stderr, "%s\n", detail); } /* update the state */ if (this->state == SHELL_STATE_HELPING) this->state = SHELL_STATE_OK; else this->state = SHELL_STATE_HELPING; end: lub_argv_delete(help.name); lub_argv_delete(help.help); lub_argv_delete(help.detail); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_help.c
C
bsd
4,274
#include <stdlib.h> #include <assert.h> #include "lub/string.h" #include "private.h" /*----------------------------------------------------------- */ static int clish_shell_push(clish_shell_t * this, FILE * file, const char *fname, bool_t stop_on_error) { /* Allocate a control node */ clish_shell_file_t *node = malloc(sizeof(clish_shell_file_t)); assert(this); assert(node); /* intialise the node */ node->file = file; if (fname) node->fname = lub_string_dup(fname); else node->fname = NULL; node->line = 0; node->stop_on_error = stop_on_error; node->next = this->current_file; /* put the node at the top of the file stack */ this->current_file = node; /* now switch the terminal's input stream */ tinyrl__set_istream(this->tinyrl, file); return 0; } /*----------------------------------------------------------- */ int clish_shell_push_file(clish_shell_t * this, const char * fname, bool_t stop_on_error) { FILE *file; int res; assert(this); if (!fname) return -1; file = fopen(fname, "r"); if (!file) return -1; res = clish_shell_push(this, file, fname, stop_on_error); if (res) fclose(file); return res; } /*----------------------------------------------------------- */ int clish_shell_push_fd(clish_shell_t *this, FILE *file, bool_t stop_on_error) { return clish_shell_push(this, file, NULL, stop_on_error); } /*----------------------------------------------------------- */ int clish_shell_pop_file(clish_shell_t *this) { int result = -1; clish_shell_file_t *node = this->current_file; if (!node) return -1; /* remove the current file from the stack... */ this->current_file = node->next; /* and close the current file... */ fclose(node->file); if (node->next) { /* now switch the terminal's input stream */ tinyrl__set_istream(this->tinyrl, node->next->file); result = 0; } /* and free up the memory */ if (node->fname) lub_string_free(node->fname); free(node); return result; } /*----------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_file.c
C
bsd
2,031
/* * shell_parse.c */ #include <string.h> #include <assert.h> #include "lub/string.h" #include "lub/system.h" #include "private.h" /*----------------------------------------------------------- */ clish_pargv_status_t clish_shell_parse( clish_shell_t *this, const char *line, const clish_command_t **ret_cmd, clish_pargv_t **pargv) { clish_pargv_status_t result = CLISH_BAD_CMD; clish_context_t context; const clish_command_t *cmd; lub_argv_t *argv = NULL; unsigned int idx; *ret_cmd = cmd = clish_shell_resolve_command(this, line); if (!cmd) return result; /* Now construct the parameters for the command */ *pargv = clish_pargv_new(); context.shell = this; context.cmd = cmd; context.pargv = *pargv; idx = lub_argv_wordcount(clish_command__get_name(cmd)); argv = lub_argv_new(line, 0); result = clish_shell_parse_pargv(*pargv, cmd, &context, clish_command__get_paramv(cmd), argv, &idx, NULL, 0); lub_argv_delete(argv); if (CLISH_LINE_OK != result) { clish_pargv_delete(*pargv); *pargv = NULL; } if (*pargv) { char str[100]; char * tmp; /* Variable __cur_depth */ int depth = clish_shell__get_depth(this); snprintf(str, sizeof(str) - 1, "%u", depth); clish_pargv_insert(*pargv, this->param_depth, str); /* Variable __cur_pwd */ tmp = clish_shell__get_pwd_full(this, depth); if (tmp) { clish_pargv_insert(*pargv, this->param_pwd, tmp); lub_string_free(tmp); } } return result; } /*--------------------------------------------------------- */ static bool_t line_test(const clish_param_t *param, void *context) { char *str = NULL; char *teststr = NULL; bool_t res; if (!param) return BOOL_FALSE; teststr = clish_param__get_test(param); if (!teststr) return BOOL_TRUE; str = clish_shell_expand(teststr, SHELL_VAR_ACTION, context); if (!str) return BOOL_FALSE; res = lub_system_line_test(str); lub_string_free(str); return res; } /*--------------------------------------------------------- */ clish_pargv_status_t clish_shell_parse_pargv(clish_pargv_t *pargv, const clish_command_t *cmd, void *context, clish_paramv_t *paramv, const lub_argv_t *argv, unsigned *idx, clish_pargv_t *last, unsigned need_index) { unsigned argc = lub_argv__get_count(argv); unsigned index = 0; unsigned nopt_index = 0; clish_param_t *nopt_param = NULL; unsigned i; clish_pargv_status_t retval; unsigned paramc = clish_paramv__get_count(paramv); int up_level = 0; /* Is it a first level of param nesting? */ assert(pargv); assert(cmd); /* Check is it a first level of PARAM nesting. */ if (paramv == clish_command__get_paramv(cmd)) up_level = 1; while (index < paramc) { const char *arg = NULL; clish_param_t *param = clish_paramv__get_param(paramv,index); clish_param_t *cparam = NULL; int is_switch = 0; /* Use real arg or PARAM's default value as argument */ if (*idx < argc) arg = lub_argv__get_arg(argv, *idx); /* Is parameter in "switch" mode? */ if (CLISH_PARAM_SWITCH == clish_param__get_mode(param)) is_switch = 1; /* Check the 'test' conditions */ if (param && !line_test(param, context)) { index++; continue; } /* Add param for help and completion */ if (last && (*idx == need_index) && (NULL == clish_pargv_find_arg(pargv, clish_param__get_name(param)))) { if (is_switch) { unsigned rec_paramc = clish_param__get_param_count(param); for (i = 0; i < rec_paramc; i++) { cparam = clish_param__get_param(param, i); if (!cparam) break; if (!line_test(cparam, context)) continue; if (CLISH_PARAM_SUBCOMMAND == clish_param__get_mode(cparam)) { const char *pname = clish_param__get_value(cparam); if (!arg || (arg && (pname == lub_string_nocasestr(pname, arg)))) clish_pargv_insert(last, cparam, arg); } else { clish_pargv_insert(last, cparam, arg); } } } else { if (CLISH_PARAM_SUBCOMMAND == clish_param__get_mode(param)) { const char *pname = clish_param__get_value(param); if (!arg || (arg && (pname == lub_string_nocasestr(pname, arg)))) clish_pargv_insert(last, param, arg); } else { clish_pargv_insert(last, param, arg); } } } /* Set parameter value */ if (param) { char *validated = NULL; clish_paramv_t *rec_paramv = clish_param__get_paramv(param); unsigned rec_paramc = clish_param__get_param_count(param); /* Save the index of last non-option parameter * to restore index if the optional parameters * will be used. */ if (!clish_param__get_optional(param)) { nopt_param = param; nopt_index = index; } /* Validate the current parameter. */ if (clish_pargv_find_arg(pargv, clish_param__get_name(param))) { /* Duplicated parameter */ validated = NULL; } else if (is_switch) { for (i = 0; i < rec_paramc; i++) { cparam = clish_param__get_param(param, i); if (!cparam) break; if (!line_test(cparam, context)) continue; if ((validated = arg ? clish_param_validate(cparam, arg) : NULL)) { rec_paramv = clish_param__get_paramv(cparam); rec_paramc = clish_param__get_param_count(cparam); break; } } } else { validated = arg ? clish_param_validate(param, arg) : NULL; } if (validated) { /* add (or update) this parameter */ if (is_switch) { clish_pargv_insert(pargv, param, clish_param__get_name(cparam)); clish_pargv_insert(pargv, cparam, validated); } else { clish_pargv_insert(pargv, param, validated); } lub_string_free(validated); /* Next command line argument */ /* Don't change idx if this is the last unfinished optional argument. */ if (!(clish_param__get_optional(param) && (*idx == need_index) && (need_index == (argc - 1)))) { (*idx)++; /* Walk through the nested parameters */ if (rec_paramc) { retval = clish_shell_parse_pargv(pargv, cmd, context, rec_paramv, argv, idx, last, need_index); if (CLISH_LINE_OK != retval) return retval; } } /* Choose the next parameter */ if (clish_param__get_optional(param) && !clish_param__get_order(param)) { if (nopt_param) index = nopt_index + 1; else index = 0; } else { /* Save non-option position in case of ordered optional param */ nopt_param = param; nopt_index = index; index++; } } else { /* Choose the next parameter if current * is not validated. */ if (clish_param__get_optional(param)) index++; else { if (!arg) break; else return CLISH_BAD_PARAM; } } } else { return CLISH_BAD_PARAM; } } /* Check for non-optional parameters without values */ if ((*idx >= argc) && (index < paramc)) { unsigned j = index; const clish_param_t *param; while (j < paramc) { param = clish_paramv__get_param(paramv, j++); if (BOOL_TRUE != clish_param__get_optional(param)) return CLISH_LINE_PARTIAL; } } /* If the number of arguments is bigger than number of * params than it's a args. So generate the args entry * in the list of completions. */ if (last && up_level && clish_command__get_args(cmd) && (clish_pargv__get_count(last) == 0) && (*idx <= argc) && (index >= paramc)) { clish_pargv_insert(last, clish_command__get_args(cmd), ""); } /* * if we've satisfied all the parameters we can now construct * an 'args' parameter if one exists */ if (up_level && (*idx < argc) && (index >= paramc)) { const char *arg = lub_argv__get_arg(argv, *idx); const clish_param_t *param = clish_command__get_args(cmd); char *args = NULL; if (!param) return CLISH_BAD_CMD; /* * put all the argument into a single string */ while (NULL != arg) { bool_t quoted = lub_argv__get_quoted(argv, *idx); if (BOOL_TRUE == quoted) { lub_string_cat(&args, "\""); } /* place the current argument in the string */ lub_string_cat(&args, arg); if (BOOL_TRUE == quoted) { lub_string_cat(&args, "\""); } (*idx)++; arg = lub_argv__get_arg(argv, *idx); if (NULL != arg) { /* add a space if there are more arguments */ lub_string_cat(&args, " "); } } /* add (or update) this parameter */ clish_pargv_insert(pargv, param, args); lub_string_free(args); } return CLISH_LINE_OK; } /*----------------------------------------------------------- */ clish_shell_state_t clish_shell__get_state(const clish_shell_t *this) { return this->state; } /*----------------------------------------------------------- */ void clish_shell__set_state(clish_shell_t *this, clish_shell_state_t state) { assert(this); this->state = state; } /*----------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_parse.c
C
bsd
8,900
/* * ------------------------------------------------------ * shell_xml.c * * This file implements the means to read an XML encoded file and populate the * CLI tree based on the contents. * ------------------------------------------------------ */ #include "private.h" #include "xmlapi.h" #include "lub/string.h" #include "lub/ctype.h" #include "lub/system.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include <errno.h> #include <sys/types.h> #include <dirent.h> typedef void (PROCESS_FN) (clish_shell_t * instance, clish_xmlnode_t * element, void *parent); /* Define a control block for handling the decode of an XML file */ typedef struct clish_xml_cb_s clish_xml_cb_t; struct clish_xml_cb_s { const char *element; PROCESS_FN *handler; }; /* forward declare the handler functions */ static PROCESS_FN process_clish_module, process_startup, process_view, process_command, process_param, process_action, process_ptype, process_overview, process_detail, process_namespace, process_config, process_var, process_wdog; static clish_xml_cb_t xml_elements[] = { {"CLISH_MODULE", process_clish_module}, {"STARTUP", process_startup}, {"VIEW", process_view}, {"COMMAND", process_command}, {"PARAM", process_param}, {"ACTION", process_action}, {"PTYPE", process_ptype}, {"OVERVIEW", process_overview}, {"DETAIL", process_detail}, {"NAMESPACE", process_namespace}, {"CONFIG", process_config}, {"VAR", process_var}, {"WATCHDOG", process_wdog}, {NULL, NULL} }; /* * if CLISH_PATH is unset in the environment then this is the value used. */ const char *default_path = "/etc/clish;~/.clish"; /*-------------------------------------------------------- */ void clish_shell_load_scheme(clish_shell_t *this, const char *xml_path) { const char *path = xml_path; char *buffer; char *dirname; char *saveptr; /* use the default path */ if (!path) path = default_path; /* take a copy of the path */ buffer = lub_system_tilde_expand(path); /* now loop though each directory */ for (dirname = strtok_r(buffer, ";", &saveptr); dirname; dirname = strtok_r(NULL, ";", &saveptr)) { DIR *dir; struct dirent *entry; /* search this directory for any XML files */ dir = opendir(dirname); if (NULL == dir) { #ifdef DEBUG tinyrl_printf(this->tinyrl, "*** Failed to open '%s' directory\n", dirname); #endif continue; } for (entry = readdir(dir); entry; entry = readdir(dir)) { const char *extension = strrchr(entry->d_name, '.'); /* check the filename */ if ((NULL != extension) && (0 == strcmp(".xml", extension))) { char *filename = NULL; /* build the filename */ lub_string_cat(&filename, dirname); lub_string_cat(&filename, "/"); lub_string_cat(&filename, entry->d_name); /* load this file */ (void)clish_shell_xml_read(this, filename); /* release the resource */ lub_string_free(filename); } } /* all done for this directory */ closedir(dir); } /* tidy up */ lub_string_free(buffer); #ifdef DEBUG clish_shell_dump(this); #endif } /* * ------------------------------------------------------ * This function reads an element from the XML stream and processes it. * ------------------------------------------------------ */ static void process_node(clish_shell_t * shell, clish_xmlnode_t * node, void *parent) { switch (clish_xmlnode_get_type(node)) { case CLISH_XMLNODE_ELM: { clish_xml_cb_t * cb; char name[128]; unsigned int namelen = sizeof(name); if (clish_xmlnode_get_name(node, name, &namelen) == 0) { for (cb = &xml_elements[0]; cb->element; cb++) { if (0 == strcmp(name, cb->element)) { #ifdef DEBUG fprintf(stderr, "NODE:"); clish_xmlnode_print(node, stderr); fprintf(stderr, "\n"); #endif /* process the elements at this level */ cb->handler(shell, node, parent); break; } } } break; } case CLISH_XMLNODE_DOC: case CLISH_XMLNODE_TEXT: case CLISH_XMLNODE_ATTR: case CLISH_XMLNODE_PI: case CLISH_XMLNODE_COMMENT: case CLISH_XMLNODE_DECL: case CLISH_XMLNODE_UNKNOWN: default: break; } } /* ------------------------------------------------------ */ static void process_children(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_xmlnode_t *node = NULL; while ((node = clish_xmlnode_next_child(element, node)) != NULL) { /* Now deal with all the contained elements */ process_node(shell, node, parent); } } /* ------------------------------------------------------ */ static void process_clish_module(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { // create the global view if (!shell->global) shell->global = clish_shell_find_create_view(shell, "global", ""); process_children(shell, element, shell->global); } /* ------------------------------------------------------ */ static void process_view(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_view_t *view; int allowed = 1; char *name = clish_xmlnode_fetch_attr(element, "name"); char *prompt = clish_xmlnode_fetch_attr(element, "prompt"); char *depth = clish_xmlnode_fetch_attr(element, "depth"); char *restore = clish_xmlnode_fetch_attr(element, "restore"); char *access = clish_xmlnode_fetch_attr(element, "access"); /* Check permissions */ if (access) { allowed = 0; if (shell->client_hooks->access_fn) allowed = shell->client_hooks->access_fn(shell, access); } if (!allowed) goto process_view_end; assert(name); /* re-use a view if it already exists */ view = clish_shell_find_create_view(shell, name, prompt); if (depth && (lub_ctype_isdigit(*depth))) { unsigned res = atoi(depth); clish_view__set_depth(view, res); } if (restore) { if (!lub_string_nocasecmp(restore, "depth")) clish_view__set_restore(view, CLISH_RESTORE_DEPTH); else if (!lub_string_nocasecmp(restore, "view")) clish_view__set_restore(view, CLISH_RESTORE_VIEW); else clish_view__set_restore(view, CLISH_RESTORE_NONE); } process_children(shell, element, view); process_view_end: clish_xml_release(name); clish_xml_release(prompt); clish_xml_release(depth); clish_xml_release(restore); clish_xml_release(access); } /* ------------------------------------------------------ */ static void process_ptype(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_ptype_method_e method; clish_ptype_preprocess_e preprocess; clish_ptype_t *ptype; char *name = clish_xmlnode_fetch_attr(element, "name"); char *help = clish_xmlnode_fetch_attr(element, "help"); char *pattern = clish_xmlnode_fetch_attr(element, "pattern"); char *method_name = clish_xmlnode_fetch_attr(element, "method"); char *preprocess_name = clish_xmlnode_fetch_attr(element, "preprocess"); assert(name); assert(pattern); method = clish_ptype_method_resolve(method_name); preprocess = clish_ptype_preprocess_resolve(preprocess_name); ptype = clish_shell_find_create_ptype(shell, name, help, pattern, method, preprocess); assert(ptype); clish_xml_release(name); clish_xml_release(help); clish_xml_release(pattern); clish_xml_release(method_name); clish_xml_release(preprocess_name); } /* ------------------------------------------------------ */ static void process_overview(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { char *content = NULL; unsigned int content_len = 2048; int result; /* * the code below faithfully assume that we'll be able fully store * the content of the node. If it's really, really big, we may have * an issue (but then, if it's that big, how the hell does it * already fits in allocated memory?) * Ergo, it -should- be safe. */ do { content = (char*)realloc(content, content_len); result = clish_xmlnode_get_content(element, content, &content_len); } while (result == -E2BIG); if (result == 0 && content) { /* set the overview text for this view */ assert(NULL == shell->overview); /* store the overview */ shell->overview = lub_string_dup(content); } if (content) free(content); } /* ------------------------------------------------------ */ static void process_command(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_view_t *v = (clish_view_t *) parent; clish_command_t *cmd = NULL; clish_command_t *old; char *alias_name = NULL; clish_view_t *alias_view = NULL; int allowed = 1; char *access = clish_xmlnode_fetch_attr(element, "access"); char *name = clish_xmlnode_fetch_attr(element, "name"); char *help = clish_xmlnode_fetch_attr(element, "help"); char *view = clish_xmlnode_fetch_attr(element, "view"); char *viewid = clish_xmlnode_fetch_attr(element, "viewid"); char *escape_chars = clish_xmlnode_fetch_attr(element, "escape_chars"); char *args_name = clish_xmlnode_fetch_attr(element, "args"); char *args_help = clish_xmlnode_fetch_attr(element, "args_help"); char *lock = clish_xmlnode_fetch_attr(element, "lock"); char *interrupt = clish_xmlnode_fetch_attr(element, "interrupt"); char *ref = clish_xmlnode_fetch_attr(element, "ref"); /* Check permissions */ if (access) { allowed = 0; if (shell->client_hooks->access_fn) allowed = shell->client_hooks->access_fn(shell, access); } if (!allowed) goto process_command_end; assert(name); /* check this command doesn't already exist */ old = clish_view_find_command(v, name, BOOL_FALSE); if (old) { /* flag the duplication then ignore further definition */ printf("DUPLICATE COMMAND: %s\n", clish_command__get_name(old)); goto process_command_end; } assert(help); /* Reference 'ref' field */ if (ref) { char *saveptr; const char *delim = "@"; char *view_name = NULL; char *cmdn = NULL; char *str = lub_string_dup(ref); cmdn = strtok_r(str, delim, &saveptr); if (!cmdn) { printf("EMPTY REFERENCE COMMAND: %s\n", name); lub_string_free(str); goto process_command_end; } alias_name = lub_string_dup(cmdn); view_name = strtok_r(NULL, delim, &saveptr); if (!view_name) alias_view = v; else alias_view = clish_shell_find_create_view(shell, view_name, NULL); lub_string_free(str); } /* create a command */ cmd = clish_view_new_command(v, name, help); assert(cmd); clish_command__set_pview(cmd, v); /* define some specialist escape characters */ if (escape_chars) clish_command__set_escape_chars(cmd, escape_chars); if (args_name) { /* define a "rest of line" argument */ clish_param_t *param; clish_ptype_t *tmp = NULL; assert(args_help); tmp = clish_shell_find_ptype(shell, "internal_ARGS"); assert(tmp); param = clish_param_new(args_name, args_help, tmp); clish_command__set_args(cmd, param); } /* define the view which this command changes to */ if (view) { clish_view_t *next = clish_shell_find_create_view(shell, view, NULL); /* reference the next view */ clish_command__set_view(cmd, next); } /* define the view id which this command changes to */ if (viewid) clish_command__set_viewid(cmd, viewid); /* lock field */ if (lock && lub_string_nocasecmp(lock, "false") == 0) clish_command__set_lock(cmd, BOOL_FALSE); else clish_command__set_lock(cmd, BOOL_TRUE); /* interrupt field */ if (interrupt && lub_string_nocasecmp(interrupt, "true") == 0) clish_command__set_interrupt(cmd, BOOL_TRUE); else clish_command__set_interrupt(cmd, BOOL_FALSE); /* Set alias */ if (alias_name) { assert(!((alias_view == v) && (!strcmp(alias_name, name)))); clish_command__set_alias(cmd, alias_name); assert(alias_view); clish_command__set_alias_view(cmd, alias_view); lub_string_free(alias_name); } process_children(shell, element, cmd); process_command_end: clish_xml_release(access); clish_xml_release(name); clish_xml_release(help); clish_xml_release(view); clish_xml_release(viewid); clish_xml_release(escape_chars); clish_xml_release(args_name); clish_xml_release(args_help); clish_xml_release(lock); clish_xml_release(interrupt); clish_xml_release(ref); } /* ------------------------------------------------------ */ static void process_startup(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_view_t *v = (clish_view_t *) parent; clish_command_t *cmd = NULL; char *view = clish_xmlnode_fetch_attr(element, "view"); char *viewid = clish_xmlnode_fetch_attr(element, "viewid"); char *default_shebang = clish_xmlnode_fetch_attr(element, "default_shebang"); char *timeout = clish_xmlnode_fetch_attr(element, "timeout"); char *lock = clish_xmlnode_fetch_attr(element, "lock"); char *interrupt = clish_xmlnode_fetch_attr(element, "interrupt"); assert(!shell->startup); assert(view); /* create a command with NULL help */ cmd = clish_view_new_command(v, "startup", NULL); clish_command__set_lock(cmd, BOOL_FALSE); /* define the view which this command changes to */ clish_view_t *next = clish_shell_find_create_view(shell, view, NULL); /* reference the next view */ clish_command__set_view(cmd, next); /* define the view id which this command changes to */ if (viewid) clish_command__set_viewid(cmd, viewid); if (default_shebang) clish_shell__set_default_shebang(shell, default_shebang); if (timeout) clish_shell__set_timeout(shell, atoi(timeout)); /* lock field */ if (lock && lub_string_nocasecmp(lock, "false") == 0) clish_command__set_lock(cmd, BOOL_FALSE); else clish_command__set_lock(cmd, BOOL_TRUE); /* interrupt field */ if (interrupt && lub_string_nocasecmp(interrupt, "true") == 0) clish_command__set_interrupt(cmd, BOOL_TRUE); else clish_command__set_interrupt(cmd, BOOL_FALSE); /* remember this command */ shell->startup = cmd; clish_xml_release(view); clish_xml_release(viewid); clish_xml_release(default_shebang); clish_xml_release(timeout); clish_xml_release(lock); clish_xml_release(interrupt); process_children(shell, element, cmd); } /* ------------------------------------------------------ */ static void process_param(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_command_t *cmd = NULL; clish_param_t *p_param = NULL; clish_xmlnode_t *pelement; char *pname; pelement = clish_xmlnode_parent(element); pname = clish_xmlnode_get_all_name(pelement); if (pname && lub_string_nocasecmp(pname, "PARAM") == 0) p_param = (clish_param_t *)parent; else cmd = (clish_command_t *)parent; if (pname) free(pname); if (cmd || p_param) { char *name = clish_xmlnode_fetch_attr(element, "name"); char *help = clish_xmlnode_fetch_attr(element, "help"); char *ptype = clish_xmlnode_fetch_attr(element, "ptype"); char *prefix = clish_xmlnode_fetch_attr(element, "prefix"); char *defval = clish_xmlnode_fetch_attr(element, "default"); char *mode = clish_xmlnode_fetch_attr(element, "mode"); char *optional = clish_xmlnode_fetch_attr(element, "optional"); char *order = clish_xmlnode_fetch_attr(element, "order"); char *value = clish_xmlnode_fetch_attr(element, "value"); char *hidden = clish_xmlnode_fetch_attr(element, "hidden"); char *test = clish_xmlnode_fetch_attr(element, "test"); char *completion = clish_xmlnode_fetch_attr(element, "completion"); clish_param_t *param; clish_ptype_t *tmp = NULL; assert((!cmd) || (cmd != shell->startup)); /* create a command */ assert(name); assert(help); assert(ptype); if (*ptype) { tmp = clish_shell_find_create_ptype(shell, ptype, NULL, NULL, CLISH_PTYPE_REGEXP, CLISH_PTYPE_NONE); assert(tmp); } param = clish_param_new(name, help, tmp); /* If prefix is set clish will emulate old optional * command syntax over newer optional command mechanism. * It will create nested PARAM. */ if (prefix) { const char *ptype_name = "__SUBCOMMAND"; clish_param_t *opt_param = NULL; /* Create a ptype for prefix-named subcommand that * will contain the nested optional parameter. The * name of ptype is hardcoded. It's not good but * it's only the service ptype. */ tmp = (clish_ptype_t *)lub_bintree_find( &shell->ptype_tree, ptype_name); if (!tmp) tmp = clish_shell_find_create_ptype(shell, ptype_name, "Option", "[^\\\\]+", CLISH_PTYPE_REGEXP, CLISH_PTYPE_NONE); assert(tmp); opt_param = clish_param_new(prefix, help, tmp); clish_param__set_mode(opt_param, CLISH_PARAM_SUBCOMMAND); clish_param__set_optional(opt_param, BOOL_TRUE); if (test) clish_param__set_test(opt_param, test); /* add the parameter to the command */ if (cmd) clish_command_insert_param(cmd, opt_param); /* add the parameter to the param */ if (p_param) clish_param_insert_param(p_param, opt_param); /* Unset cmd and set parent param to opt_param */ cmd = NULL; p_param = opt_param; } if (defval) clish_param__set_default(param, defval); if (hidden && lub_string_nocasecmp(hidden, "true") == 0) clish_param__set_hidden(param, BOOL_TRUE); else clish_param__set_hidden(param, BOOL_FALSE); if (mode) { if (lub_string_nocasecmp(mode, "switch") == 0) { clish_param__set_mode(param, CLISH_PARAM_SWITCH); /* Force hidden attribute */ clish_param__set_hidden(param, BOOL_TRUE); } else if (lub_string_nocasecmp(mode, "subcommand") == 0) clish_param__set_mode(param, CLISH_PARAM_SUBCOMMAND); else clish_param__set_mode(param, CLISH_PARAM_COMMON); } if (optional && lub_string_nocasecmp(optional, "true") == 0) clish_param__set_optional(param, BOOL_TRUE); else clish_param__set_optional(param, BOOL_FALSE); if (order && lub_string_nocasecmp(order, "true") == 0) clish_param__set_order(param, BOOL_TRUE); else clish_param__set_order(param, BOOL_FALSE); if (value) { clish_param__set_value(param, value); /* Force mode to subcommand */ clish_param__set_mode(param, CLISH_PARAM_SUBCOMMAND); } if (test && !prefix) clish_param__set_test(param, test); if (completion) clish_param__set_completion(param, completion); /* add the parameter to the command */ if (cmd) clish_command_insert_param(cmd, param); /* add the parameter to the param */ if (p_param) clish_param_insert_param(p_param, param); clish_xml_release(name); clish_xml_release(help); clish_xml_release(ptype); clish_xml_release(prefix); clish_xml_release(defval); clish_xml_release(mode); clish_xml_release(optional); clish_xml_release(order); clish_xml_release(value); clish_xml_release(hidden); clish_xml_release(test); clish_xml_release(completion); process_children(shell, element, param); } } /* ------------------------------------------------------ */ static void process_action(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_action_t *action = NULL; char *builtin = clish_xmlnode_fetch_attr(element, "builtin"); char *shebang = clish_xmlnode_fetch_attr(element, "shebang"); clish_xmlnode_t *pelement = clish_xmlnode_parent(element); char *pname = clish_xmlnode_get_all_name(pelement); char *text; if (pname && lub_string_nocasecmp(pname, "VAR") == 0) action = clish_var__get_action((clish_var_t *)parent); else action = clish_command__get_action((clish_command_t *)parent); assert(action); if (pname) free(pname); text = clish_xmlnode_get_all_content(element); if (text && *text) { /* store the action */ clish_action__set_script(action, text); } if (text) free(text); if (builtin) clish_action__set_builtin(action, builtin); if (shebang) clish_action__set_shebang(action, shebang); clish_xml_release(builtin); clish_xml_release(shebang); } /* ------------------------------------------------------ */ static void process_detail(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_command_t *cmd = (clish_command_t *) parent; /* read the following text element */ char *text = clish_xmlnode_get_all_content(element); if (text && *text) { /* store the action */ clish_command__set_detail(cmd, text); } if (text) free(text); } /* ------------------------------------------------------ */ static void process_namespace(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_view_t *v = (clish_view_t *) parent; clish_nspace_t *nspace = NULL; char *view = clish_xmlnode_fetch_attr(element, "ref"); char *prefix = clish_xmlnode_fetch_attr(element, "prefix"); char *prefix_help = clish_xmlnode_fetch_attr(element, "prefix_help"); char *help = clish_xmlnode_fetch_attr(element, "help"); char *completion = clish_xmlnode_fetch_attr(element, "completion"); char *context_help = clish_xmlnode_fetch_attr(element, "context_help"); char *inherit = clish_xmlnode_fetch_attr(element, "inherit"); char *access = clish_xmlnode_fetch_attr(element, "access"); int allowed = 1; if (access) { allowed = 0; if (shell->client_hooks->access_fn) allowed = shell->client_hooks->access_fn(shell, access); } if (!allowed) goto process_namespace_end; assert(view); clish_view_t *ref_view = clish_shell_find_create_view(shell, view, NULL); assert(ref_view); /* Don't include itself without prefix */ if ((ref_view == v) && !prefix) goto process_namespace_end; nspace = clish_nspace_new(ref_view); assert(nspace); clish_view_insert_nspace(v, nspace); if (prefix) { clish_nspace__set_prefix(nspace, prefix); if (prefix_help) clish_nspace_create_prefix_cmd(nspace, "prefix", prefix_help); else clish_nspace_create_prefix_cmd(nspace, "prefix", "Prefix for the imported commands."); } if (help && lub_string_nocasecmp(help, "true") == 0) clish_nspace__set_help(nspace, BOOL_TRUE); else clish_nspace__set_help(nspace, BOOL_FALSE); if (completion && lub_string_nocasecmp(completion, "false") == 0) clish_nspace__set_completion(nspace, BOOL_FALSE); else clish_nspace__set_completion(nspace, BOOL_TRUE); if (context_help && lub_string_nocasecmp(context_help, "true") == 0) clish_nspace__set_context_help(nspace, BOOL_TRUE); else clish_nspace__set_context_help(nspace, BOOL_FALSE); if (inherit && lub_string_nocasecmp(inherit, "false") == 0) clish_nspace__set_inherit(nspace, BOOL_FALSE); else clish_nspace__set_inherit(nspace, BOOL_TRUE); process_namespace_end: clish_xml_release(view); clish_xml_release(prefix); clish_xml_release(prefix_help); clish_xml_release(help); clish_xml_release(completion); clish_xml_release(context_help); clish_xml_release(inherit); clish_xml_release(access); } /* ------------------------------------------------------ */ static void process_config(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_command_t *cmd = (clish_command_t *)parent; clish_config_t *config; if (!cmd) return; config = clish_command__get_config(cmd); /* read the following text element */ char *operation = clish_xmlnode_fetch_attr(element, "operation"); char *priority = clish_xmlnode_fetch_attr(element, "priority"); char *pattern = clish_xmlnode_fetch_attr(element, "pattern"); char *file = clish_xmlnode_fetch_attr(element, "file"); char *splitter = clish_xmlnode_fetch_attr(element, "splitter"); char *seq = clish_xmlnode_fetch_attr(element, "sequence"); char *unique = clish_xmlnode_fetch_attr(element, "unique"); char *depth = clish_xmlnode_fetch_attr(element, "depth"); if (operation && !lub_string_nocasecmp(operation, "unset")) clish_config__set_op(config, CLISH_CONFIG_UNSET); else if (operation && !lub_string_nocasecmp(operation, "none")) clish_config__set_op(config, CLISH_CONFIG_NONE); else if (operation && !lub_string_nocasecmp(operation, "dump")) clish_config__set_op(config, CLISH_CONFIG_DUMP); else { clish_config__set_op(config, CLISH_CONFIG_SET); /* The priority if no clearly specified */ clish_config__set_priority(config, 0x7f00); } if (priority) { long val = 0; char *endptr; unsigned short pri; val = strtol(priority, &endptr, 0); if (endptr == priority) pri = 0; else if (val > 0xffff) pri = 0xffff; else if (val < 0) pri = 0; else pri = (unsigned short)val; clish_config__set_priority(config, pri); } if (pattern) clish_config__set_pattern(config, pattern); else clish_config__set_pattern(config, "^${__cmd}"); if (file) clish_config__set_file(config, file); if (splitter && lub_string_nocasecmp(splitter, "false") == 0) clish_config__set_splitter(config, BOOL_FALSE); else clish_config__set_splitter(config, BOOL_TRUE); if (unique && lub_string_nocasecmp(unique, "false") == 0) clish_config__set_unique(config, BOOL_FALSE); else clish_config__set_unique(config, BOOL_TRUE); if (seq) clish_config__set_seq(config, seq); else /* The entries without sequence cannot be non-unique */ clish_config__set_unique(config, BOOL_TRUE); if (depth) clish_config__set_depth(config, depth); clish_xml_release(operation); clish_xml_release(priority); clish_xml_release(pattern); clish_xml_release(file); clish_xml_release(splitter); clish_xml_release(seq); clish_xml_release(unique); clish_xml_release(depth); } /* ------------------------------------------------------ */ static void process_var(clish_shell_t * shell, clish_xmlnode_t * element, void *parent) { clish_var_t *var = NULL; char *name = clish_xmlnode_fetch_attr(element, "name"); char *dynamic = clish_xmlnode_fetch_attr(element, "dynamic"); char *value = clish_xmlnode_fetch_attr(element, "value"); assert(name); /* Check if this var doesn't already exist */ var = (clish_var_t *)lub_bintree_find(&shell->var_tree, name); if (var) { printf("DUPLICATE VAR: %s\n", name); assert(!var); } /* Create var instance */ var = clish_var_new(name); lub_bintree_insert(&shell->var_tree, var); if (dynamic && lub_string_nocasecmp(dynamic, "true") == 0) clish_var__set_dynamic(var, BOOL_TRUE); if (value) clish_var__set_value(var, value); clish_xml_release(name); clish_xml_release(dynamic); clish_xml_release(value); process_children(shell, element, var); } /* ------------------------------------------------------ */ static void process_wdog(clish_shell_t *shell, clish_xmlnode_t *element, void *parent) { clish_view_t *v = (clish_view_t *)parent; clish_command_t *cmd = NULL; assert(!shell->wdog); /* create a command with NULL help */ cmd = clish_view_new_command(v, "watchdog", NULL); clish_command__set_lock(cmd, BOOL_FALSE); /* Remember this command */ shell->wdog = cmd; process_children(shell, element, cmd); } /* ------------------------------------------------------ */ int clish_shell_xml_read(clish_shell_t * shell, const char *filename) { int ret = -1; clish_xmldoc_t *doc; doc = clish_xmldoc_read(filename); if (clish_xmldoc_is_valid(doc)) { clish_xmlnode_t *root = clish_xmldoc_get_root(doc); process_node(shell, root, NULL); ret = 0; } else { int errcaps = clish_xmldoc_error_caps(doc); printf("Unable to open file '%s'", filename); if ((errcaps & CLISH_XMLERR_LINE) == CLISH_XMLERR_LINE) printf(", at line %d", clish_xmldoc_get_err_line(doc)); if ((errcaps & CLISH_XMLERR_COL) == CLISH_XMLERR_COL) printf(", at column %d", clish_xmldoc_get_err_col(doc)); if ((errcaps & CLISH_XMLERR_DESC) == CLISH_XMLERR_DESC) printf(", message is %s", clish_xmldoc_get_err_msg(doc)); printf("\n"); } clish_xmldoc_release(doc); return ret; } /* ------------------------------------------------------ */
zzysjtu-klish
clish/shell/shell_xml.c
C
bsd
27,396
/* * shell_var.c */ #include <stdlib.h> #include <assert.h> #include <string.h> #include <ctype.h> #include "lub/string.h" #include "private.h" /*----------------------------------------------------------- */ /* * search the current viewid string for a variable */ void clish_shell__expand_viewid(const char *viewid, lub_bintree_t *tree, clish_context_t *context) { char *expanded; char *q, *saveptr; expanded = clish_shell_expand(viewid, SHELL_VAR_NONE, context); if (!expanded) return; for (q = strtok_r(expanded, ";", &saveptr); q; q = strtok_r(NULL, ";", &saveptr)) { char *value; clish_var_t *var; value = strchr(q, '='); if (!value) continue; *value = '\0'; value++; /* Create var instance */ var = clish_var_new(q); lub_bintree_insert(tree, var); clish_var__set_value(var, value); } lub_string_free(expanded); } /*----------------------------------------------------------- */ /* * expand context dependent fixed-name variables */ static char *find_context_var(const char *name, clish_context_t *this) { char *result = NULL; clish_shell_t *shell = this->shell; if (!lub_string_nocasecmp(name, "_width")) { char tmp[5]; snprintf(tmp, sizeof(tmp), "%u", tinyrl__get_width(shell->tinyrl)); tmp[sizeof(tmp) - 1] = '\0'; result = strdup(tmp); } else if (!lub_string_nocasecmp(name, "_height")) { char tmp[5]; snprintf(tmp, sizeof(tmp), "%u", tinyrl__get_height(shell->tinyrl)); tmp[sizeof(tmp) - 1] = '\0'; result = strdup(tmp); } else if (!lub_string_nocasecmp(name, "_watchdog_timeout")) { char tmp[5]; snprintf(tmp, sizeof(tmp), "%u", shell->wdog_timeout); tmp[sizeof(tmp) - 1] = '\0'; result = strdup(tmp); } else if (!this->cmd) { /* The vars dependent on command */ return NULL; } else if (!lub_string_nocasecmp(name, "_full_cmd")) { result = lub_string_dup(clish_command__get_name(this->cmd)); } else if (!lub_string_nocasecmp(name, "_cmd")) { result = lub_string_dup(clish_command__get_name( clish_command__get_cmd(this->cmd))); } else if (!lub_string_nocasecmp(name, "_orig_cmd")) { result = lub_string_dup(clish_command__get_name( clish_command__get_orig(this->cmd))); } else if (!lub_string_nocasecmp(name, "_line")) { result = clish_shell__get_line(this); } else if (!lub_string_nocasecmp(name, "_full_line")) { result = clish_shell__get_full_line(this); } else if (!lub_string_nocasecmp(name, "_params")) { if (this->pargv) result = clish_shell__get_params(this); } else if (!lub_string_nocasecmp(name, "_interactive")) { if (clish_shell__get_interactive(this->shell)) result = strdup("1"); else result = strdup("0"); } else if (!lub_string_nocasecmp(name, "_isatty")) { if (tinyrl__get_isatty(this->shell->tinyrl)) result = strdup("1"); else result = strdup("0"); } else if (lub_string_nocasestr(name, "_prefix") == name) { int idx = 0; int pnum = 0; pnum = lub_argv_wordcount(clish_command__get_name(this->cmd)) - lub_argv_wordcount(clish_command__get_name( clish_command__get_cmd(this->cmd))); idx = atoi(name + strlen("_prefix")); if (idx < pnum) { lub_argv_t *argv = lub_argv_new( clish_command__get_name(this->cmd), 0); result = lub_string_dup(lub_argv__get_arg(argv, idx)); lub_argv_delete(argv); } } return result; } /*--------------------------------------------------------- */ static char *find_var(const char *name, lub_bintree_t *tree, clish_context_t *context) { clish_var_t *var = lub_bintree_find(tree, name); char *value; bool_t dynamic; char *res = NULL; if (!var) return NULL; /* Try to get saved value for static var */ dynamic = clish_var__get_dynamic(var); if (!dynamic) { char *saved = clish_var__get_saved(var); if (saved) return lub_string_dup(saved); } /* Try to expand value field */ value = clish_var__get_value(var); if (value) res = clish_shell_expand(value, SHELL_VAR_NONE, context); /* Try to execute ACTION */ if (!res) { char *out = NULL; clish_action_t *action = clish_var__get_action(var); if (clish_shell_exec_action(action, context, &out)) { lub_string_free(out); return NULL; } res = out; } /* Save value for static var */ if (!dynamic && res) clish_var__set_saved(var, res); return res; } /*--------------------------------------------------------- */ static char *find_global_var(const char *name, clish_context_t *context) { return find_var(name, &context->shell->var_tree, context); } /*--------------------------------------------------------- */ static char *find_viewid_var(const char *name, clish_context_t *context) { int depth = clish_shell__get_depth(context->shell); if (depth < 0) return NULL; return find_var(name, &context->shell->pwdv[depth]->viewid, context); } static char * chardiff(const char *syms, const char *minus) { char *dst = malloc(strlen(syms) + 1); char *p = dst; const char *src; for (src = syms; *src; src++) { if (!strchr(minus, *src)) *(p++) = *src; } *p = '\0'; return dst; } /*--------------------------------------------------------- */ /* * return the next segment of text from the provided string * segments are delimited by variables within the string. */ static char *expand_nextsegment(const char **string, const char *escape_chars, clish_context_t *this) { const char *p = *string; char *result = NULL; size_t len = 0; if (!p) return NULL; if (*p && (p[0] == '$') && (p[1] == '{')) { /* start of a variable */ const char *tmp; p += 2; tmp = p; /* * find the end of the variable */ while (*p && p++[0] != '}') len++; /* ignore non-terminated variables */ if (p[-1] == '}') { bool_t valid = BOOL_FALSE; char *text, *q; char *saveptr; /* get the variable text */ text = lub_string_dupn(tmp, len); /* * tokenise this INTO ':' separated words * and either expand or duplicate into the result string. * Only return a result if at least * of the words is an expandable variable */ for (q = strtok_r(text, ":", &saveptr); q; q = strtok_r(NULL, ":", &saveptr)) { char *var; int mod_quote = 0; /* quote modifier */ int mod_esc = 0; /* internal escape modifier */ int mod_esc_chars = 1; /* escaping */ int mod_esc_dec = 0; /* remove internal chars from escaping */ char *space; char *all_esc = NULL; /* Search for modifiers */ while (*q && !isalpha(*q)) { if ('#' == *q) { mod_quote = 1; mod_esc = 1; } else if ('\\' == *q) { mod_esc = 1; } else if ('!' == *q) { mod_quote = 1; mod_esc = 1; mod_esc_chars = 0; } else if ('~' == *q) { mod_esc = 1; mod_esc_chars = 0; } else if (('_' == *q) && ('_' == *(q+1))) { mod_esc_dec = 1; q++; break; } else break; q++; } /* Get clean variable value */ var = clish_shell_expand_var(q, this); if (!var) { lub_string_cat(&result, q); continue; } valid = BOOL_TRUE; /* Quoting */ if (mod_quote) space = strchr(var, ' '); if (mod_quote && space) lub_string_cat(&result, "\""); /* Escape special chars */ if (escape_chars && mod_esc_chars) { /* Remove internal esc from escape chars */ if (mod_esc_dec) all_esc = chardiff(escape_chars, lub_string_esc_quoted); else all_esc = lub_string_dup(escape_chars); } /* Internal escaping */ if (mod_esc) lub_string_cat(&all_esc, lub_string_esc_quoted); /* Real escaping */ if (all_esc) { char *tstr = lub_string_encode(var, all_esc); lub_string_free(var); var = tstr; lub_string_free(all_esc); } /* copy the expansion or the raw word */ lub_string_cat(&result, var); /* Quoting */ if (mod_quote && space) lub_string_cat(&result, "\""); lub_string_free(var); } if (!valid) { /* not a valid variable expansion */ lub_string_free(result); result = lub_string_dup(""); } /* finished with the variable text */ lub_string_free(text); } } else { /* find the start of a variable */ while (*p) { if ((p[0] == '$') && (p[1] == '{')) break; len++; p++; } if (len > 0) result = lub_string_dupn(*string, len); } /* move the string pointer on for next time... */ *string = p; return result; } /*--------------------------------------------------------- */ /* * This function builds a dynamic string based on that provided * subtituting each occurance of a "${FRED}" type variable sub-string * with the appropriate value. */ char *clish_shell_expand(const char *str, clish_shell_var_t vtype, clish_context_t *context) { char *seg, *result = NULL; const char *escape_chars = NULL; const clish_command_t *cmd = context->cmd; /* Escape special characters */ if (SHELL_VAR_REGEX == vtype) { if (cmd) escape_chars = clish_command__get_regex_chars(cmd); if (!escape_chars) escape_chars = lub_string_esc_regex; } else if (SHELL_VAR_ACTION == vtype) { if (cmd) escape_chars = clish_command__get_escape_chars(cmd); if (!escape_chars) escape_chars = lub_string_esc_default; } /* read each segment and extend the result */ while ((seg = expand_nextsegment(&str, escape_chars, context))) { lub_string_cat(&result, seg); lub_string_free(seg); } return result; } /*--------------------------------------------------------- */ char *clish_shell__get_params(clish_context_t *context) { clish_pargv_t *pargv = context->pargv; char *line = NULL; unsigned i, cnt; const clish_param_t *param; const clish_parg_t *parg; char *request = NULL; if (!pargv) return NULL; cnt = clish_pargv__get_count(pargv); for (i = 0; i < cnt; i++) { param = clish_pargv__get_param(pargv, i); if (clish_param__get_hidden(param)) continue; parg = clish_pargv__get_parg(pargv, i); if (request) lub_string_cat(&request, " "); lub_string_cat(&request, "${!"); lub_string_cat(&request, clish_parg__get_name(parg)); lub_string_cat(&request, "}"); } line = clish_shell_expand(request, SHELL_VAR_NONE, context); lub_string_free(request); return line; } /*--------------------------------------------------------- */ static char *internal_get_line(clish_context_t *context, int cmd_type) { const clish_command_t *cmd = context->cmd; clish_pargv_t *pargv = context->pargv; char *line = NULL; char *params = NULL; if (0 == cmd_type) /* __cmd */ lub_string_cat(&line, clish_command__get_name( clish_command__get_cmd(cmd))); else /* __full_cmd */ lub_string_cat(&line, clish_command__get_name(cmd)); if (!pargv) return line; params = clish_shell__get_params(context); if (params) { lub_string_cat(&line, " "); lub_string_cat(&line, params); } lub_string_free(params); return line; } /*--------------------------------------------------------- */ char *clish_shell__get_line(clish_context_t *context) { return internal_get_line(context, 0); /* __cmd */ } /*--------------------------------------------------------- */ char *clish_shell__get_full_line(clish_context_t *context) { return internal_get_line(context, 1); /* __full_cmd */ } /*--------------------------------------------------------- */ char *clish_shell_expand_var(const char *name, clish_context_t *context) { clish_shell_t *this; const clish_command_t *cmd; clish_pargv_t *pargv; const char *tmp = NULL; char *string = NULL; assert(name); if (!context) return NULL; this = context->shell; cmd = context->cmd; pargv = context->pargv; /* try and substitute a parameter value */ if (pargv) { const clish_parg_t *parg = clish_pargv_find_arg(pargv, name); if (parg) tmp = clish_parg__get_value(parg); } /* try and substitute the param's default */ if (!tmp && cmd) tmp = clish_paramv_find_default( clish_command__get_paramv(cmd), name); /* try and substitute a viewId variable */ if (!tmp && this) tmp = string = find_viewid_var(name, context); /* try and substitute context fixed variable */ if (!tmp) tmp = string = find_context_var(name, context); /* try and substitute a global var value */ if (!tmp && this) tmp = string = find_global_var(name, context); /* get the contents of an environment variable */ if (!tmp) tmp = getenv(name); if (string) return string; return lub_string_dup(tmp); } /*----------------------------------------------------------- */
zzysjtu-klish
clish/shell/shell_var.c
C
bsd
12,418
/* * clish_script_callback.c * * Callback hook to action a shell script. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <assert.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "lub/string.h" #include "konf/buf.h" #include "internal.h" /*--------------------------------------------------------- */ int clish_script_callback(clish_context_t *context, clish_action_t *action, const char *script, char **out) { clish_shell_t *this = context->shell; const char * shebang = NULL; pid_t cpid = -1; int res; const char *fifo_name; FILE *rpipe, *wpipe; char *command = NULL; bool_t is_sh = BOOL_FALSE; /* Signal vars */ struct sigaction sig_old_int; struct sigaction sig_old_quit; struct sigaction sig_new; sigset_t sig_set; assert(this); if (!script) /* Nothing to do */ return BOOL_TRUE; /* Find out shebang */ if (action) shebang = clish_action__get_shebang(action); if (!shebang) shebang = clish_shell__get_default_shebang(this); assert(shebang); if (0 == lub_string_nocasecmp(shebang, "/bin/sh")) is_sh = BOOL_TRUE; #ifdef DEBUG fprintf(stderr, "SHEBANG: #!%s\n", shebang); fprintf(stderr, "SCRIPT: %s\n", script); #endif /* DEBUG */ /* If /bin/sh we don't need FIFO */ if (!is_sh) { /* Get FIFO */ fifo_name = clish_shell__get_fifo(this); if (!fifo_name) { fprintf(stderr, "System error. Can't create temporary FIFO.\n" "The ACTION will be not executed.\n"); return BOOL_FALSE; } /* Create process to write to FIFO */ cpid = fork(); if (cpid == -1) { fprintf(stderr, "System error. Can't fork the write process.\n" "The ACTION will be not executed.\n"); return BOOL_FALSE; } /* Child: write to FIFO */ if (cpid == 0) { wpipe = fopen(fifo_name, "w"); if (!wpipe) _exit(-1); fwrite(script, strlen(script) + 1, 1, wpipe); fclose(wpipe); _exit(0); } } /* Parent */ /* Prepare command */ if (!is_sh) { lub_string_cat(&command, shebang); lub_string_cat(&command, " "); lub_string_cat(&command, fifo_name); } else { lub_string_cat(&command, script); } /* If the stdout of script is needed */ if (out) { konf_buf_t *buf; /* Ignore SIGINT and SIGQUIT */ sigemptyset(&sig_set); sig_new.sa_flags = 0; sig_new.sa_mask = sig_set; sig_new.sa_handler = SIG_IGN; sigaction(SIGINT, &sig_new, &sig_old_int); sigaction(SIGQUIT, &sig_new, &sig_old_quit); /* Execute shebang with FIFO as argument */ rpipe = popen(command, "r"); if (!rpipe) { fprintf(stderr, "System error. Can't fork the script.\n" "The ACTION will be not executed.\n"); lub_string_free(command); if (!is_sh) { kill(cpid, SIGTERM); waitpid(cpid, NULL, 0); } /* Restore SIGINT and SIGQUIT */ sigaction(SIGINT, &sig_old_int, NULL); sigaction(SIGQUIT, &sig_old_quit, NULL); return BOOL_FALSE; } /* Read the result of script execution */ buf = konf_buf_new(fileno(rpipe)); while (konf_buf_read(buf) > 0); *out = konf_buf__dup_line(buf); konf_buf_delete(buf); /* Wait for the writing process */ if (!is_sh) { kill(cpid, SIGTERM); waitpid(cpid, NULL, 0); } /* Wait for script */ res = pclose(rpipe); /* Restore SIGINT and SIGQUIT */ sigaction(SIGINT, &sig_old_int, NULL); sigaction(SIGQUIT, &sig_old_quit, NULL); } else { res = system(command); /* Wait for the writing process */ if (!is_sh) { kill(cpid, SIGTERM); waitpid(cpid, NULL, 0); } } lub_string_free(command); #ifdef DEBUG fprintf(stderr, "RETCODE: %d\n", WEXITSTATUS(res)); #endif /* DEBUG */ return WEXITSTATUS(res); } /*--------------------------------------------------------- */ int clish_dryrun_callback(clish_context_t *context, clish_action_t *action, const char *script, char ** out) { #ifdef DEBUG fprintf(stderr, "DRY-RUN: %s\n", script); #endif /* DEBUG */ if (out) *out = NULL; return 0; } /*--------------------------------------------------------- */
zzysjtu-klish
clish/callback_script.c
C
bsd
4,052
/* * command.h */ #ifndef _clish_command_h #define _clish_command_h typedef struct clish_command_s clish_command_t; #include "lub/bintree.h" #include "lub/argv.h" #include "clish/types.h" #include "clish/pargv.h" #include "clish/view.h" #include "clish/param.h" #include "clish/action.h" #include "clish/config.h" /*===================================== * COMMAND INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ clish_command_t *clish_command_new(const char *name, const char *help); clish_command_t *clish_command_new_link(const char *name, const char *help, const clish_command_t * ref); clish_command_t * clish_command_alias_to_link(clish_command_t * instance); int clish_command_bt_compare(const void *clientnode, const void *clientkey); void clish_command_bt_getkey(const void *clientnode, lub_bintree_key_t * key); size_t clish_command_bt_offset(void); clish_command_t *clish_command_choose_longest(clish_command_t * cmd1, clish_command_t * cmd2); int clish_command_diff(const clish_command_t * cmd1, const clish_command_t * cmd2); /*----------------- * methods *----------------- */ void clish_command_delete(clish_command_t *instance); void clish_command_insert_param(clish_command_t *instance, clish_param_t *param); int clish_command_help(const clish_command_t *instance); void clish_command_dump(const clish_command_t *instance); /*----------------- * attributes *----------------- */ const char *clish_command__get_name(const clish_command_t * instance); const char *clish_command__get_suffix(const clish_command_t * instance); const char *clish_command__get_text(const clish_command_t * instance); const char *clish_command__get_detail(const clish_command_t * instance); const char *clish_command__get_escape_chars(const clish_command_t * instance); const char *clish_command__get_regex_chars(const clish_command_t * instance); const clish_param_t *clish_command__get_args(const clish_command_t * instance); clish_action_t *clish_command__get_action(const clish_command_t *instance); clish_view_t *clish_command__get_view(const clish_command_t * instance); char *clish_command__get_viewid(const clish_command_t *instance); unsigned int clish_command__get_param_count(const clish_command_t * instance); const clish_param_t *clish_command__get_param(const clish_command_t * instance, unsigned index); clish_paramv_t *clish_command__get_paramv(const clish_command_t * instance); void clish_command__set_escape_chars(clish_command_t * instance, const char *escape_chars); void clish_command__set_regex_chars(clish_command_t * instance, const char *escape_chars); void clish_command__set_args(clish_command_t * instance, clish_param_t * args); void clish_command__set_detail(clish_command_t * instance, const char *detail); void clish_command__set_view(clish_command_t * instance, clish_view_t * view); void clish_command__force_view(clish_command_t * instance, clish_view_t * view); void clish_command__set_viewid(clish_command_t * instance, const char *viewid); void clish_command__force_viewid(clish_command_t * instance, const char *viewid); void clish_command__set_pview(clish_command_t * instance, clish_view_t * view); clish_view_t *clish_command__get_pview(const clish_command_t * instance); unsigned clish_command__get_depth(const clish_command_t * instance); clish_config_t *clish_command__get_config(const clish_command_t *instance); clish_view_restore_t clish_command__get_restore(const clish_command_t * instance); const clish_command_t * clish_command__get_orig(const clish_command_t * instance); const clish_command_t * clish_command__get_cmd(const clish_command_t * instance); bool_t clish_command__get_lock(const clish_command_t * instance); void clish_command__set_lock(clish_command_t * instance, bool_t lock); void clish_command__set_alias(clish_command_t * instance, const char * alias); const char * clish_command__get_alias(const clish_command_t * instance); void clish_command__set_alias_view(clish_command_t * instance, clish_view_t * alias_view); clish_view_t * clish_command__get_alias_view(const clish_command_t * instance); void clish_command__set_dynamic(clish_command_t * instance, bool_t dynamic); bool_t clish_command__get_dynamic(const clish_command_t * instance); bool_t clish_command__get_interrupt(const clish_command_t * instance); void clish_command__set_interrupt(clish_command_t * instance, bool_t interrupt); #endif /* _clish_command_h */
zzysjtu-klish
clish/command.h
C
bsd
4,478
/* * ptype.c */ #include "private.h" #include "lub/string.h" #include "lub/ctype.h" #include "lub/argv.h" #include <stdlib.h> #include <string.h> #include <assert.h> #include <limits.h> #include <stdio.h> /*--------------------------------------------------------- * PRIVATE METHODS *--------------------------------------------------------- */ static char *clish_ptype_select__get_name(const clish_ptype_t * this, unsigned index) { char *result = NULL; const char *arg = lub_argv__get_arg(this->u.select.items, index); if (arg) { size_t name_len = strlen(arg); const char *lbrk = strchr(arg, '('); if (lbrk) name_len = (size_t) (lbrk - arg); result = lub_string_dupn(arg, name_len); } return result; } /*--------------------------------------------------------- */ static char *clish_ptype_select__get_value(const clish_ptype_t * this, unsigned index) { char *result = NULL; const char *arg = lub_argv__get_arg(this->u.select.items, index); if (arg) { const char *lbrk = strchr(arg, '('); const char *rbrk = strchr(arg, ')'); const char *value = arg; size_t value_len = strlen(arg); if (lbrk) { value = lbrk + 1; if (rbrk) value_len = (size_t) (rbrk - value); } result = lub_string_dupn(value, value_len); } return result; } /*--------------------------------------------------------- */ static void clish_ptype__set_range(clish_ptype_t * this) { char tmp[80]; /* now set up the range values */ switch (this->method) { /*------------------------------------------------- */ case CLISH_PTYPE_REGEXP: /* * nothing more to do */ break; /*------------------------------------------------- */ case CLISH_PTYPE_INTEGER: /* * Setup the integer range */ sprintf(tmp, "%d..%d", this->u.integer.min, this->u.integer.max); this->range = lub_string_dup(tmp); break; /*------------------------------------------------- */ case CLISH_PTYPE_UNSIGNEDINTEGER: /* * Setup the unsigned integer range */ sprintf(tmp, "%u..%u", (unsigned int)this->u.integer.min, (unsigned int)this->u.integer.max); this->range = lub_string_dup(tmp); break; /*------------------------------------------------- */ case CLISH_PTYPE_SELECT: { /* * Setup the selection values to the help text */ unsigned i; for (i = 0; i < lub_argv__get_count(this->u.select.items); i++) { char *p = tmp; char *name = clish_ptype_select__get_name(this, i); if (i > 0) p += sprintf(p, "/"); p += sprintf(p, "%s", name); lub_string_cat(&this->range, tmp); lub_string_free(name); } break; } /*------------------------------------------------- */ } } /*--------------------------------------------------------- * PUBLIC META FUNCTIONS *--------------------------------------------------------- */ int clish_ptype_bt_compare(const void *clientnode, const void *clientkey) { const clish_ptype_t *this = clientnode; const char *key = clientkey; return strcmp(this->name, key); } /*-------------------------------------------------------- */ void clish_ptype_bt_getkey(const void *clientnode, lub_bintree_key_t * key) { const clish_ptype_t *this = clientnode; /* fill out the opaque key */ strcpy((char *)key, this->name); } /*--------------------------------------------------------- */ size_t clish_ptype_bt_offset(void) { return offsetof(clish_ptype_t, bt_node); } /*--------------------------------------------------------- */ static const char *method_names[] = { "regexp", "integer", "unsignedInteger", "select" }; /*--------------------------------------------------------- */ const char *clish_ptype_method__get_name(clish_ptype_method_e method) { int max_method = sizeof(method_names) / sizeof(char *); if (method >= max_method) return NULL; return method_names[method]; } /*--------------------------------------------------------- */ clish_ptype_method_e clish_ptype_method_resolve(const char *name) { clish_ptype_method_e result = CLISH_PTYPE_REGEXP; if (NULL != name) { unsigned i; for (i = 0; i < CLISH_PTYPE_SELECT + 1; i++) { if (0 == strcmp(name, method_names[i])) { result = (clish_ptype_method_e) i; break; } } /* error for incorrect type spec */ assert(i <= CLISH_PTYPE_SELECT); } return result; } /*--------------------------------------------------------- */ static const char *preprocess_names[] = { "none", "toupper", "tolower" }; /*--------------------------------------------------------- */ const char *clish_ptype_preprocess__get_name( clish_ptype_preprocess_e preprocess) { return preprocess_names[preprocess]; } /*--------------------------------------------------------- */ clish_ptype_preprocess_e clish_ptype_preprocess_resolve(const char *name) { clish_ptype_preprocess_e result = CLISH_PTYPE_NONE; if (name) { unsigned i; for (i = 0; i < CLISH_PTYPE_TOLOWER + 1; i++) { if (0 == strcmp(name, preprocess_names[i])) { result = (clish_ptype_preprocess_e) i; break; } } /* error for incorrect type spec */ assert((clish_ptype_preprocess_e) i <= CLISH_PTYPE_TOLOWER); } return result; } /*--------------------------------------------------------- * PUBLIC METHODS *--------------------------------------------------------- */ /*--------------------------------------------------------- */ void clish_ptype_word_generator(clish_ptype_t * this, lub_argv_t *matches, const char *text) { char *result = NULL; unsigned i = 0; /* Another ptypes has no completions */ if (this->method != CLISH_PTYPE_SELECT) return; /* First of all simply try to validate the result */ result = clish_ptype_validate(this, text); if (result) { lub_argv_add(matches, result); lub_string_free(result); return; } /* Iterate possible completion */ while ((result = clish_ptype_select__get_name(this, i++))) { /* get the next item and check if it is a completion */ if (result == lub_string_nocasestr(result, text)) lub_argv_add(matches, result); lub_string_free(result); } } /*--------------------------------------------------------- */ static char *clish_ptype_validate_or_translate(const clish_ptype_t * this, const char *text, bool_t translate) { char *result = lub_string_dup(text); assert(this->pattern); switch (this->preprocess) { /*----------------------------------------- */ case CLISH_PTYPE_NONE: break; /*----------------------------------------- */ case CLISH_PTYPE_TOUPPER: { char *p = result; while (*p) { /*lint -e155 Ignoring { }'ed sequence within an expression, 0 assumed * MACRO implementation uses braces to prevent multiple increments * when called. */ *p = lub_ctype_toupper(*p); p++; } break; } /*----------------------------------------- */ case CLISH_PTYPE_TOLOWER: { char *p = result; while (*p) { *p = lub_ctype_tolower(*p); p++; } break; } /*----------------------------------------- */ } /* * now validate according the specified method */ switch (this->method) { /*------------------------------------------------- */ case CLISH_PTYPE_REGEXP: /* test the regular expression against the string */ /*lint -e64 Type mismatch (arg. no. 4) */ /* * lint seems to equate regmatch_t[] as being of type regmatch_t ! */ if (0 != regexec(&this->u.regexp, result, 0, NULL, 0)) { lub_string_free(result); result = NULL; } /*lint +e64 */ break; /*------------------------------------------------- */ case CLISH_PTYPE_INTEGER: { /* first of all check that this is a number */ bool_t ok = BOOL_TRUE; const char *p = result; if (*p == '-') p++; while (*p) { if (!lub_ctype_isdigit(*p++)) { ok = BOOL_FALSE; break; } } if (BOOL_TRUE == ok) { /* convert and check the range */ int value = atoi(result); if ((value < this->u.integer.min) || (value > this->u.integer.max)) { lub_string_free(result); result = NULL; } } else { lub_string_free(result); result = NULL; } break; } /*------------------------------------------------- */ case CLISH_PTYPE_UNSIGNEDINTEGER: { /* first of all check that this is a number */ bool_t ok = BOOL_TRUE; const char *p = result; while (*p) { if (!lub_ctype_isdigit(*p++)) { ok = BOOL_FALSE; break; } } if (BOOL_TRUE == ok) { /* convert and check the range */ unsigned int value = (unsigned int)atoi(result); if ((value < (unsigned)this->u.integer.min) || (value > (unsigned)this->u.integer.max)) { lub_string_free(result); result = NULL; } } else { lub_string_free(result); result = NULL; } break; } /*------------------------------------------------- */ case CLISH_PTYPE_SELECT: { unsigned i; for (i = 0; i < lub_argv__get_count(this->u.select.items); i++) { char *name = clish_ptype_select__get_name(this, i); char *value = clish_ptype_select__get_value(this, i); int tmp = lub_string_nocasecmp(result, name); lub_string_free((BOOL_TRUE == translate) ? name : value); if (0 == tmp) { lub_string_free(result); result = ((BOOL_TRUE == translate) ? value : name); break; } else { lub_string_free((BOOL_TRUE == translate) ? value : name); } } if (i == lub_argv__get_count(this->u.select.items)) { /* failed to find a match */ lub_string_free(result); result = NULL; } break; } /*------------------------------------------------- */ } return (char *)result; } /*--------------------------------------------------------- */ static void clish_ptype_init(clish_ptype_t * this, const char *name, const char *text, const char *pattern, clish_ptype_method_e method, clish_ptype_preprocess_e preprocess) { assert(name); this->name = lub_string_dup(name); this->text = NULL; this->pattern = NULL; this->preprocess = preprocess; this->range = NULL; /* Be a good binary tree citizen */ lub_bintree_node_init(&this->bt_node); if (pattern) { /* set the pattern for this type */ clish_ptype__set_pattern(this, pattern, method); } else { /* The method is regexp by default */ this->method = CLISH_PTYPE_REGEXP; } /* set the help text for this type */ if (text) clish_ptype__set_text(this, text); } /*--------------------------------------------------------- */ char *clish_ptype_validate(const clish_ptype_t * this, const char *text) { return clish_ptype_validate_or_translate(this, text, BOOL_FALSE); } /*--------------------------------------------------------- */ char *clish_ptype_translate(const clish_ptype_t * this, const char *text) { return clish_ptype_validate_or_translate(this, text, BOOL_TRUE); } /*--------------------------------------------------------- */ clish_ptype_t *clish_ptype_new(const char *name, const char *help, const char *pattern, clish_ptype_method_e method, clish_ptype_preprocess_e preprocess) { clish_ptype_t *this = malloc(sizeof(clish_ptype_t)); if (this) clish_ptype_init(this, name, help, pattern, method, preprocess); return this; } /*--------------------------------------------------------- */ static void clish_ptype_fini(clish_ptype_t * this) { if (this->pattern) { switch (this->method) { case CLISH_PTYPE_REGEXP: regfree(&this->u.regexp); break; case CLISH_PTYPE_INTEGER: case CLISH_PTYPE_UNSIGNEDINTEGER: break; case CLISH_PTYPE_SELECT: lub_argv_delete(this->u.select.items); break; } } lub_string_free(this->name); this->name = NULL; lub_string_free(this->text); this->text = NULL; lub_string_free(this->pattern); this->pattern = NULL; lub_string_free(this->range); this->range = NULL; } /*--------------------------------------------------------- */ void clish_ptype_delete(clish_ptype_t * this) { clish_ptype_fini(this); free(this); } /*--------------------------------------------------------- */ const char *clish_ptype__get_name(const clish_ptype_t * this) { return (const char *)this->name; } /*--------------------------------------------------------- */ const char *clish_ptype__get_text(const clish_ptype_t * this) { return (const char *)this->text; } /*--------------------------------------------------------- */ void clish_ptype__set_pattern(clish_ptype_t * this, const char *pattern, clish_ptype_method_e method) { assert(NULL == this->pattern); this->method = method; switch (this->method) { /*------------------------------------------------- */ case CLISH_PTYPE_REGEXP: { int result; /* only the expression is allowed */ lub_string_cat(&this->pattern, "^"); lub_string_cat(&this->pattern, pattern); lub_string_cat(&this->pattern, "$"); /* compile the regular expression for later use */ result = regcomp(&this->u.regexp, this->pattern, REG_NOSUB | REG_EXTENDED); assert(0 == result); break; } /*------------------------------------------------- */ case CLISH_PTYPE_INTEGER: /* default the range to that of an integer */ this->u.integer.min = INT_MIN; this->u.integer.max = INT_MAX; this->pattern = lub_string_dup(pattern); /* now try and read the specified range */ sscanf(this->pattern, "%d..%d", &this->u.integer.min, &this->u.integer.max); break; /*------------------------------------------------- */ case CLISH_PTYPE_UNSIGNEDINTEGER: /* default the range to that of an unsigned integer */ this->u.integer.min = 0; this->u.integer.max = (int)UINT_MAX; this->pattern = lub_string_dup(pattern); /* now try and read the specified range */ sscanf(this->pattern, "%u..%u", (unsigned int *)&this->u.integer.min, (unsigned int *)&this->u.integer.max); break; /*------------------------------------------------- */ case CLISH_PTYPE_SELECT: this->pattern = lub_string_dup(pattern); /* store a vector of item descriptors */ this->u.select.items = lub_argv_new(this->pattern, 0); break; /*------------------------------------------------- */ } /* now set up the range details */ clish_ptype__set_range(this); } /*--------------------------------------------------------- */ void clish_ptype__set_text(clish_ptype_t * this, const char *text) { assert(!this->text); this->text = lub_string_dup(text); } /*--------------------------------------------------------- */ void clish_ptype__set_preprocess(clish_ptype_t * this, clish_ptype_preprocess_e preprocess) { assert(!this->preprocess); this->preprocess = preprocess; } /*--------------------------------------------------------- */ const char *clish_ptype__get_range(const clish_ptype_t * this) { return (const char *)this->range; } /*--------------------------------------------------------- */
zzysjtu-klish
clish/ptype/ptype.c
C
bsd
14,572
/* * ptype_dump.c */ #include "private.h" #include "lub/dump.h" /*--------------------------------------------------------- */ void clish_ptype_dump(clish_ptype_t * this) { lub_dump_printf("ptype(%p)\n", this); lub_dump_indent(); lub_dump_printf("name : %s\n", clish_ptype__get_name(this)); lub_dump_printf("text : %s\n", clish_ptype__get_text(this)); lub_dump_printf("pattern : %s\n", this->pattern); lub_dump_printf("method : %s\n", clish_ptype_method__get_name(this->method)); lub_dump_printf("postprocess: %s\n", clish_ptype_preprocess__get_name(this->preprocess)); lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/ptype/ptype_dump.c
C
bsd
689
/* * ptype.h */ #include "clish/pargv.h" #include "lub/bintree.h" #include "lub/argv.h" #include <sys/types.h> #include <regex.h> typedef struct clish_ptype_integer_s clish_ptype_integer_t; struct clish_ptype_integer_s { int min; int max; }; typedef struct clish_ptype_select_s clish_ptype_select_t; struct clish_ptype_select_s { lub_argv_t *items; }; struct clish_ptype_s { lub_bintree_node_t bt_node; char *name; char *text; char *pattern; char *range; clish_ptype_method_e method; clish_ptype_preprocess_e preprocess; unsigned last_name; /* index used for auto-completion */ union { regex_t regexp; clish_ptype_integer_t integer; clish_ptype_select_t select; } u; };
zzysjtu-klish
clish/ptype/private.h
C
bsd
695
/* * pargv.h */ #include "clish/pargv.h" #include "clish/param.h" /*--------------------------------------------------------- */ struct clish_parg_s { const clish_param_t *param; char *value; }; struct clish_pargv_s { unsigned pargc; clish_parg_t **pargv; }; /*--------------------------------------------------------- */
zzysjtu-klish
clish/pargv/private.h
C
bsd
329
/* * pargv_dump.c */ #include "private.h" #include "lub/dump.h" /*--------------------------------------------------------- */ void clish_parg_dump(const clish_parg_t * this) { lub_dump_printf("parg(%p)\n", this); lub_dump_indent(); lub_dump_printf("name : %s\n", clish_parg__get_name(this)); lub_dump_printf("ptype: %s\n", clish_ptype__get_name(clish_parg__get_ptype(this))); lub_dump_printf("value: %s\n", clish_parg__get_value(this)); lub_dump_undent(); } /*--------------------------------------------------------- */ void clish_pargv_dump(const clish_pargv_t * this) { unsigned i; lub_dump_printf("pargv(%p)\n", this); lub_dump_indent(); for (i = 0; i < this->pargc; i++) { /* get the appropriate parameter definition */ clish_parg_dump(this->pargv[i]); } lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/pargv/pargv_dump.c
C
bsd
869
/* * pargv.c */ #include "private.h" #include "lub/string.h" #include "lub/argv.h" #include "lub/system.h" #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> /*--------------------------------------------------------- */ /* * Search for the specified parameter and return its value */ static clish_parg_t *find_parg(clish_pargv_t * this, const char *name) { unsigned i; clish_parg_t *result = NULL; if (!this || !name) return NULL; /* scan the parameters in this instance */ for (i = 0; i < this->pargc; i++) { clish_parg_t *parg = this->pargv[i]; const char *pname = clish_param__get_name(parg->param); if (0 == strcmp(pname, name)) { result = parg; break; } } return result; } /*--------------------------------------------------------- */ int clish_pargv_insert(clish_pargv_t * this, const clish_param_t * param, const char *value) { if (!this || !param) return -1; clish_parg_t *parg = find_parg(this, clish_param__get_name(param)); if (parg) { /* release the current value */ lub_string_free(parg->value); } else { size_t new_size = ((this->pargc + 1) * sizeof(clish_parg_t *)); clish_parg_t **tmp; /* resize the parameter vector */ tmp = realloc(this->pargv, new_size); this->pargv = tmp; /* insert reference to the parameter */ parg = malloc(sizeof(*parg)); this->pargv[this->pargc++] = parg; parg->param = param; } parg->value = NULL; if (value) parg->value = lub_string_dup(value); return 0; } /*--------------------------------------------------------- */ clish_pargv_t *clish_pargv_new(void) { clish_pargv_t *this; this = malloc(sizeof(clish_pargv_t)); this->pargc = 0; this->pargv = NULL; return this; } /*--------------------------------------------------------- */ static void clish_pargv_fini(clish_pargv_t * this) { unsigned i; /* cleanup time */ for (i = 0; i < this->pargc; i++) { lub_string_free(this->pargv[i]->value); this->pargv[i]->value = NULL; free(this->pargv[i]); } free(this->pargv); } /*--------------------------------------------------------- */ void clish_pargv_delete(clish_pargv_t * this) { if (!this) return; clish_pargv_fini(this); free(this); } /*--------------------------------------------------------- */ unsigned clish_pargv__get_count(clish_pargv_t * this) { if (!this) return 0; return this->pargc; } /*--------------------------------------------------------- */ clish_parg_t *clish_pargv__get_parg(clish_pargv_t * this, unsigned index) { if (!this) return NULL; if (index > this->pargc) return NULL; return this->pargv[index]; } /*--------------------------------------------------------- */ const clish_param_t *clish_pargv__get_param(clish_pargv_t * this, unsigned index) { clish_parg_t *tmp; if (!this) return NULL; if (index >= this->pargc) return NULL; tmp = this->pargv[index]; return tmp->param; } /*--------------------------------------------------------- */ const char *clish_parg__get_value(const clish_parg_t * this) { if (!this) return NULL; return this->value; } /*--------------------------------------------------------- */ const char *clish_parg__get_name(const clish_parg_t * this) { if (!this) return NULL; return clish_param__get_name(this->param); } /*--------------------------------------------------------- */ const clish_ptype_t *clish_parg__get_ptype(const clish_parg_t * this) { if (!this) return NULL; return clish_param__get_ptype(this->param); } /*--------------------------------------------------------- */ const clish_parg_t *clish_pargv_find_arg(clish_pargv_t * this, const char *name) { if (!this) return NULL; return find_parg(this, name); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/pargv/pargv.c
C
bsd
3,760
/* * command.c * * This file provides the implementation of a command definition */ #include "private.h" #include "clish/types.h" #include "lub/bintree.h" #include "lub/string.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <stdio.h> /*--------------------------------------------------------- * PRIVATE METHODS *--------------------------------------------------------- */ static void clish_command_init(clish_command_t *this, const char *name, const char *text) { /* initialise the node part */ this->name = lub_string_dup(name); this->text = lub_string_dup(text); /* Be a good binary tree citizen */ lub_bintree_node_init(&this->bt_node); /* set up defaults */ this->link = NULL; this->alias = NULL; this->alias_view = NULL; this->paramv = clish_paramv_new(); this->viewid = NULL; this->view = NULL; this->action = clish_action_new(); this->config = clish_config_new(); this->detail = NULL; this->escape_chars = NULL; this->regex_chars = NULL; this->args = NULL; this->pview = NULL; this->lock = BOOL_TRUE; this->interrupt = BOOL_FALSE; this->dynamic = BOOL_FALSE; } /*--------------------------------------------------------- */ static void clish_command_fini(clish_command_t * this) { lub_string_free(this->name); lub_string_free(this->text); /* Link need not full cleanup */ if (this->link) return; /* finalize each of the parameter instances */ clish_paramv_delete(this->paramv); lub_string_free(this->alias); lub_string_free(this->viewid); clish_action_delete(this->action); clish_config_delete(this->config); lub_string_free(this->detail); lub_string_free(this->escape_chars); lub_string_free(this->regex_chars); if (this->args) clish_param_delete(this->args); } /*--------------------------------------------------------- * PUBLIC META FUNCTIONS *--------------------------------------------------------- */ size_t clish_command_bt_offset(void) { return offsetof(clish_command_t, bt_node); } /*--------------------------------------------------------- */ int clish_command_bt_compare(const void *clientnode, const void *clientkey) { const clish_command_t *this = clientnode; const char *key = clientkey; return lub_string_nocasecmp(this->name, key); } /*--------------------------------------------------------- */ void clish_command_bt_getkey(const void *clientnode, lub_bintree_key_t * key) { const clish_command_t *this = clientnode; /* fill out the opaque key */ strcpy((char *)key, this->name); } /*--------------------------------------------------------- */ clish_command_t *clish_command_new(const char *name, const char *help) { clish_command_t *this = malloc(sizeof(clish_command_t)); if (this) clish_command_init(this, name, help); return this; } /*--------------------------------------------------------- */ clish_command_t *clish_command_new_link(const char *name, const char *help, const clish_command_t * ref) { if (!ref) return NULL; clish_command_t *this = malloc(sizeof(clish_command_t)); assert(this); /* Copy all fields to the new command-link */ *this = *ref; /* Initialise the name (other than original name) */ this->name = lub_string_dup(name); /* Initialise the name (other than original name) */ this->text = lub_string_dup(help); /* Be a good binary tree citizen */ lub_bintree_node_init(&this->bt_node); /* It a link to command so set the link flag */ this->link = ref; return this; } /*--------------------------------------------------------- */ clish_command_t * clish_command_alias_to_link(clish_command_t * this) { clish_command_t * ref; clish_command_t tmp; if (!this || !this->alias) return this; assert(this->alias_view); ref = clish_view_find_command(this->alias_view, this->alias, BOOL_FALSE); if (!ref) return this; memcpy(&tmp, this, sizeof(tmp)); *this = *ref; memcpy(&this->bt_node, &tmp.bt_node, sizeof(tmp.bt_node)); this->name = lub_string_dup(tmp.name); this->text = lub_string_dup(tmp.text); this->link = ref; clish_command_fini(&tmp); return this; } /*--------------------------------------------------------- * PUBLIC METHODS *--------------------------------------------------------- */ void clish_command_delete(clish_command_t * this) { clish_command_fini(this); free(this); } /*--------------------------------------------------------- */ void clish_command_insert_param(clish_command_t * this, clish_param_t * param) { clish_paramv_insert(this->paramv, param); } /*--------------------------------------------------------- */ int clish_command_help(const clish_command_t *this) { return 0; } /*--------------------------------------------------------- */ clish_command_t *clish_command_choose_longest(clish_command_t * cmd1, clish_command_t * cmd2) { unsigned len1 = (cmd1 ? strlen(clish_command__get_name(cmd1)) : 0); unsigned len2 = (cmd2 ? strlen(clish_command__get_name(cmd2)) : 0); if (len2 < len1) { return cmd1; } else if (len1 < len2) { return cmd2; } else { /* let local view override */ return cmd1; } } /*--------------------------------------------------------- */ int clish_command_diff(const clish_command_t * cmd1, const clish_command_t * cmd2) { if (NULL == cmd1) { if (NULL != cmd2) return 1; else return 0; } if (NULL == cmd2) return -1; return lub_string_nocasecmp(clish_command__get_name(cmd1), clish_command__get_name(cmd2)); } /*--------------------------------------------------------- * PUBLIC ATTRIBUTES *--------------------------------------------------------- */ const char *clish_command__get_name(const clish_command_t * this) { if (!this) return NULL; return this->name; } /*--------------------------------------------------------- */ const char *clish_command__get_text(const clish_command_t * this) { return this->text; } /*--------------------------------------------------------- */ const char *clish_command__get_detail(const clish_command_t * this) { return this->detail; } /*--------------------------------------------------------- */ void clish_command__set_detail(clish_command_t * this, const char *detail) { assert(NULL == this->detail); this->detail = lub_string_dup(detail); } /*--------------------------------------------------------- */ clish_action_t *clish_command__get_action(const clish_command_t *this) { return this->action; } /*--------------------------------------------------------- */ clish_config_t *clish_command__get_config(const clish_command_t *this) { return this->config; } /*--------------------------------------------------------- */ void clish_command__set_view(clish_command_t * this, clish_view_t * view) { assert(NULL == this->view); clish_command__force_view(this, view); } /*--------------------------------------------------------- */ void clish_command__force_view(clish_command_t * this, clish_view_t * view) { this->view = view; } /*--------------------------------------------------------- */ clish_view_t *clish_command__get_view(const clish_command_t * this) { return this->view; } /*--------------------------------------------------------- */ void clish_command__set_viewid(clish_command_t * this, const char *viewid) { assert(NULL == this->viewid); clish_command__force_viewid(this, viewid); } /*--------------------------------------------------------- */ void clish_command__force_viewid(clish_command_t * this, const char *viewid) { this->viewid = lub_string_dup(viewid); } /*--------------------------------------------------------- */ char *clish_command__get_viewid(const clish_command_t * this) { return this->viewid; } /*--------------------------------------------------------- */ const clish_param_t *clish_command__get_param(const clish_command_t * this, unsigned index) { return clish_paramv__get_param(this->paramv, index); } /*--------------------------------------------------------- */ const char *clish_command__get_suffix(const clish_command_t * this) { return lub_string_suffix(this->name); } /*--------------------------------------------------------- */ void clish_command__set_escape_chars(clish_command_t * this, const char *escape_chars) { assert(!this->escape_chars); this->escape_chars = lub_string_dup(escape_chars); } /*--------------------------------------------------------- */ const char *clish_command__get_escape_chars(const clish_command_t * this) { return this->escape_chars; } /*--------------------------------------------------------- */ void clish_command__set_regex_chars(clish_command_t *this, const char *escape_chars) { assert(!this->regex_chars); this->regex_chars = lub_string_dup(escape_chars); } /*--------------------------------------------------------- */ const char *clish_command__get_regex_chars(const clish_command_t *this) { return this->regex_chars; } /*--------------------------------------------------------- */ void clish_command__set_args(clish_command_t * this, clish_param_t * args) { assert(NULL == this->args); this->args = args; } /*--------------------------------------------------------- */ const clish_param_t *clish_command__get_args(const clish_command_t * this) { return this->args; } /*--------------------------------------------------------- */ unsigned int clish_command__get_param_count(const clish_command_t * this) { return clish_paramv__get_count(this->paramv); } /*--------------------------------------------------------- */ clish_paramv_t *clish_command__get_paramv(const clish_command_t * this) { return this->paramv; } /*--------------------------------------------------------- */ void clish_command__set_pview(clish_command_t * this, clish_view_t * view) { this->pview = view; } /*--------------------------------------------------------- */ clish_view_t *clish_command__get_pview(const clish_command_t * this) { return this->pview; } /*--------------------------------------------------------- */ unsigned clish_command__get_depth(const clish_command_t * this) { if (!this->pview) return 0; return clish_view__get_depth(this->pview); } /*--------------------------------------------------------- */ clish_view_restore_t clish_command__get_restore(const clish_command_t * this) { if (!this->pview) return CLISH_RESTORE_NONE; return clish_view__get_restore(this->pview); } /*--------------------------------------------------------- */ const clish_command_t * clish_command__get_orig(const clish_command_t * this) { if (this->link) return clish_command__get_orig(this->link); return this; } /*--------------------------------------------------------- */ bool_t clish_command__get_lock(const clish_command_t * this) { return this->lock; } /*--------------------------------------------------------- */ void clish_command__set_lock(clish_command_t * this, bool_t lock) { this->lock = lock; } /*--------------------------------------------------------- */ void clish_command__set_alias(clish_command_t * this, const char * alias) { assert(!this->alias); this->alias = lub_string_dup(alias); } /*--------------------------------------------------------- */ const char * clish_command__get_alias(const clish_command_t * this) { return this->alias; } /*--------------------------------------------------------- */ void clish_command__set_alias_view(clish_command_t * this, clish_view_t * alias_view) { this->alias_view = alias_view; } /*--------------------------------------------------------- */ clish_view_t * clish_command__get_alias_view(const clish_command_t * this) { return this->alias_view; } /*--------------------------------------------------------- */ void clish_command__set_dynamic(clish_command_t * this, bool_t dynamic) { this->dynamic = dynamic; } /*--------------------------------------------------------- */ bool_t clish_command__get_dynamic(const clish_command_t * this) { return this->dynamic; } /*--------------------------------------------------------- */ const clish_command_t * clish_command__get_cmd(const clish_command_t * this) { if (!this->dynamic) return this; if (this->link) return clish_command__get_cmd(this->link); return NULL; } /*--------------------------------------------------------- */ bool_t clish_command__get_interrupt(const clish_command_t * this) { return this->interrupt; } /*--------------------------------------------------------- */ void clish_command__set_interrupt(clish_command_t * this, bool_t interrupt) { this->interrupt = interrupt; }
zzysjtu-klish
clish/command/command.c
C
bsd
12,432
/* * command_dump.c */ #include "lub/dump.h" #include "private.h" /*--------------------------------------------------------- */ void clish_command_dump(const clish_command_t * this) { unsigned i; lub_dump_printf("command(%p)\n", this); lub_dump_indent(); lub_dump_printf("name : %s\n", this->name); lub_dump_printf("text : %s\n", this->text); lub_dump_printf("link : %s\n", this->link ? clish_command__get_name(this->link) : "(null)"); lub_dump_printf("alias : %s\n", this->alias); lub_dump_printf("alias_view : %s\n", this->alias_view ? clish_view__get_name(this->alias_view) : "(null)"); lub_dump_printf("paramc : %d\n", clish_paramv__get_count(this->paramv)); lub_dump_printf("detail : %s\n", this->detail ? this->detail : "(null)"); clish_action_dump(this->action); clish_config_dump(this->config); /* Get each parameter to dump their details */ for (i = 0; i < clish_paramv__get_count(this->paramv); i++) { clish_param_dump(clish_command__get_param(this, i)); } lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/command/command_dump.c
C
bsd
1,123
/* * command.h */ #include "clish/command.h" /*--------------------------------------------------------- * PRIVATE TYPES *--------------------------------------------------------- */ struct clish_command_s { lub_bintree_node_t bt_node; char *name; char *text; clish_paramv_t *paramv; clish_action_t *action; clish_config_t *config; clish_view_t *view; char *viewid; char *detail; char *escape_chars; char *regex_chars; clish_param_t *args; const struct clish_command_s *link; clish_view_t *alias_view; char *alias; clish_view_t *pview; bool_t lock; bool_t interrupt; bool_t dynamic; /* Is command dynamically created */ };
zzysjtu-klish
clish/command/private.h
C
bsd
648
/* * private.h */ #ifndef _clish_private_h #define _clish_private_h #include "lub/c_decl.h" #endif /* _clish_private_h */
zzysjtu-klish
clish/private.h
C
bsd
127
/* * action.h */ #ifndef _clish_action_h #define _clish_action_h typedef struct clish_action_s clish_action_t; #include "lub/bintree.h" /*===================================== * ACTION INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ clish_action_t *clish_action_new(void); /*----------------- * methods *----------------- */ void clish_action_delete(clish_action_t *instance); void clish_action_dump(const clish_action_t *instance); /*----------------- * attributes *----------------- */ void clish_action__set_script(clish_action_t *instance, const char *script); char *clish_action__get_script(const clish_action_t *instance); void clish_action__set_builtin(clish_action_t *instance, const char *builtin); const char *clish_action__get_builtin(const clish_action_t *instance); void clish_action__set_shebang(clish_action_t *instance, const char *shebang); const char *clish_action__get_shebang(const clish_action_t *instance); #endif /* _clish_action_h */
zzysjtu-klish
clish/action.h
C
bsd
1,040
/* * param.h */ /** \ingroup clish \defgroup clish_param param @{ \brief This class represents an instance of a parameter type. Parameter instances are assocated with a command line and used to validate the the arguments which a user is inputing for a command. */ #ifndef _clish_param_h #define _clish_param_h typedef struct clish_paramv_s clish_paramv_t; typedef struct clish_param_s clish_param_t; #include "clish/types.h" #include "clish/ptype.h" #include "clish/pargv.h" #include "clish/var.h" /** * The means by which the param is interpreted. */ typedef enum { /** * A common parameter. */ CLISH_PARAM_COMMON, /** * A swich parameter. * Choose the only one of nested parameters. */ CLISH_PARAM_SWITCH, /** * A subcomand. * Identified by it's name. */ CLISH_PARAM_SUBCOMMAND } clish_param_mode_e; /*===================================== * PARAM INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ clish_param_t *clish_param_new(const char *name, const char *text, clish_ptype_t *ptype); /*----------------- * methods *----------------- */ void clish_param_delete(clish_param_t * instance); void clish_param_help(const clish_param_t * instance, clish_help_t *help); void clish_param_help_arrow(const clish_param_t * instance, size_t offset); char *clish_param_validate(const clish_param_t * instance, const char *text); void clish_param_dump(const clish_param_t * instance); void clish_param_insert_param(clish_param_t * instance, clish_param_t * param); /*----------------- * attributes *----------------- */ const char *clish_param__get_name(const clish_param_t * instance); const char *clish_param__get_text(const clish_param_t * instance); const char *clish_param__get_range(const clish_param_t * instance); const char *clish_param__get_default(const clish_param_t * instance); clish_ptype_t *clish_param__get_ptype(const clish_param_t * instance); void clish_param__set_default(clish_param_t * instance, const char *defval); void clish_param__set_mode(clish_param_t * instance, clish_param_mode_e mode); clish_param_mode_e clish_param__get_mode(const clish_param_t * instance); clish_param_t *clish_param__get_param(const clish_param_t * instance, unsigned index); unsigned int clish_param__get_param_count(const clish_param_t * instance); clish_paramv_t *clish_param__get_paramv(clish_param_t * instance); void clish_param__set_optional(clish_param_t * instance, bool_t optional); bool_t clish_param__get_optional(const clish_param_t * instance); void clish_param__set_order(clish_param_t * instance, bool_t order); bool_t clish_param__get_order(const clish_param_t * instance); void clish_param__set_value(clish_param_t * instance, const char * value); char *clish_param__get_value(const clish_param_t * instance); void clish_param__set_hidden(clish_param_t * instance, bool_t hidden); bool_t clish_param__get_hidden(const clish_param_t * instance); void clish_param__set_test(clish_param_t * instance, const char *test); char *clish_param__get_test(const clish_param_t *instance); void clish_param__set_completion(clish_param_t *instance, const char *completion); char *clish_param__get_completion(const clish_param_t *instance); /* paramv methods */ clish_paramv_t *clish_paramv_new(void); void clish_paramv_delete(clish_paramv_t * instance); void clish_paramv_insert(clish_paramv_t * instance, clish_param_t * param); clish_param_t *clish_paramv__get_param(const clish_paramv_t * instance, unsigned index); unsigned int clish_paramv__get_count(const clish_paramv_t * instance); clish_param_t *clish_paramv_find_param(const clish_paramv_t * instance, const char *name); const char *clish_paramv_find_default(const clish_paramv_t * instance, const char *name); #endif /* _clish_param_h */ /** @} clish_param */
zzysjtu-klish
clish/param.h
C
bsd
3,872
/* * view.h */ /** \ingroup clish \defgroup clish_view view @{ \brief This class is a container of commands. A particular CLI session may contain a number of different views. Each view may contain its own specific commands as well as those available at a global scope. */ #ifndef _clish_view_h #define _clish_view_h typedef struct clish_view_s clish_view_t; typedef enum { CLISH_RESTORE_NONE, CLISH_RESTORE_DEPTH, CLISH_RESTORE_VIEW } clish_view_restore_t; #include "clish/command.h" #include "clish/nspace.h" #include "clish/var.h" /*===================================== * VIEW INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ clish_view_t *clish_view_new(const char *name, const char *prompt); int clish_view_bt_compare(const void *clientnode, const void *clientkey); void clish_view_bt_getkey(const void *clientnode, lub_bintree_key_t * key); size_t clish_view_bt_offset(void); /*----------------- * methods *----------------- */ void clish_view_delete(clish_view_t * instance); clish_command_t *clish_view_new_command(clish_view_t * instance, const char *name, const char *text); clish_command_t *clish_view_find_command(clish_view_t * instance, const char *name, bool_t inherit); const clish_command_t *clish_view_find_next_completion(clish_view_t * instance, const char *iter_cmd, const char *line, clish_nspace_visibility_t field, bool_t inherit); clish_command_t *clish_view_resolve_command(clish_view_t * instance, const char *line, bool_t inherit); clish_command_t *clish_view_resolve_prefix(clish_view_t * instance, const char *line, bool_t inherit); void clish_view_dump(clish_view_t * instance); void clish_view_insert_nspace(clish_view_t * instance, clish_nspace_t * nspace); void clish_view_clean_proxy(clish_view_t * instance); /*----------------- * attributes *----------------- */ const char *clish_view__get_name(const clish_view_t * instance); void clish_view__set_prompt(clish_view_t * instance, const char *prompt); char *clish_view__get_prompt(const clish_view_t *instance); unsigned int clish_view__get_nspace_count(const clish_view_t * instance); clish_nspace_t *clish_view__get_nspace(const clish_view_t * instance, unsigned index); void clish_view__set_depth(clish_view_t * instance, unsigned depth); unsigned clish_view__get_depth(const clish_view_t * instance); void clish_view__set_restore(clish_view_t * instance, clish_view_restore_t restore); clish_view_restore_t clish_view__get_restore(const clish_view_t * instance); #endif /* _clish_view_h */ /** @} clish_view */
zzysjtu-klish
clish/view.h
C
bsd
2,610
/* * action.h */ #include "clish/action.h" /*--------------------------------------------------------- * PRIVATE TYPES *--------------------------------------------------------- */ struct clish_action_s { char *script; char *builtin; char *shebang; };
zzysjtu-klish
clish/action/private.h
C
bsd
261
/* * action_dump.c */ #include "lub/dump.h" #include "private.h" /*--------------------------------------------------------- */ void clish_action_dump(const clish_action_t *this) { lub_dump_printf("action(%p)\n", this); lub_dump_indent(); lub_dump_printf("script : %s\n", this->script ? this->script : "(null)"); lub_dump_printf("builtin : %s\n", this->builtin ? this->builtin : "(null)"); lub_dump_printf("shebang : %s\n", this->shebang ? this->shebang : "(null)"); lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/action/action_dump.c
C
bsd
571
/* * action.c * * This file provides the implementation of a action definition */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include "private.h" #include "lub/bintree.h" #include "lub/string.h" /*--------------------------------------------------------- * PRIVATE METHODS *--------------------------------------------------------- */ static void clish_action_init(clish_action_t *this) { this->script = NULL; this->builtin = NULL; this->shebang = NULL; } /*--------------------------------------------------------- */ static void clish_action_fini(clish_action_t *this) { lub_string_free(this->script); lub_string_free(this->builtin); lub_string_free(this->shebang); } /*--------------------------------------------------------- * PUBLIC META FUNCTIONS *--------------------------------------------------------- */ clish_action_t *clish_action_new(void) { clish_action_t *this = malloc(sizeof(clish_action_t)); if (this) clish_action_init(this); return this; } /*--------------------------------------------------------- * PUBLIC METHODS *--------------------------------------------------------- */ void clish_action_delete(clish_action_t *this) { clish_action_fini(this); free(this); } /*--------------------------------------------------------- * PUBLIC ATTRIBUTES *--------------------------------------------------------- */ void clish_action__set_script(clish_action_t *this, const char *script) { if (this->script) lub_string_free(this->script); this->script = lub_string_dup(script); } /*--------------------------------------------------------- */ char *clish_action__get_script(const clish_action_t *this) { return this->script; } /*--------------------------------------------------------- */ void clish_action__set_builtin(clish_action_t *this, const char *builtin) { if (this->builtin) lub_string_free(this->builtin); this->builtin = lub_string_dup(builtin); } /*--------------------------------------------------------- */ const char *clish_action__get_builtin(const clish_action_t *this) { return this->builtin; } /*--------------------------------------------------------- */ void clish_action__set_shebang(clish_action_t *this, const char *shebang) { const char *prog = shebang; const char *prefix = "#!"; if (this->shebang) lub_string_free(this->shebang); if (lub_string_nocasestr(shebang, prefix) == shebang) prog += strlen(prefix); this->shebang = lub_string_dup(prog); } /*--------------------------------------------------------- */ const char *clish_action__get_shebang(const clish_action_t *this) { return this->shebang; }
zzysjtu-klish
clish/action/action.c
C
bsd
2,644
/* * config_dump.c */ #include "lub/dump.h" #include "private.h" /*--------------------------------------------------------- */ void clish_config_dump(const clish_config_t *this) { char *op; lub_dump_printf("config(%p)\n", this); lub_dump_indent(); switch (this->op) { case CLISH_CONFIG_NONE: op = "NONE"; break; case CLISH_CONFIG_SET: op = "SET"; break; case CLISH_CONFIG_UNSET: op = "UNSET"; break; case CLISH_CONFIG_DUMP: op = "DUMP"; break; default: op = "Unknown"; break; } lub_dump_printf("op : %s\n", op); lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/config/config_dump.c
C
bsd
642
/* * clish/config/private.h */ #include "clish/config.h" /*--------------------------------------------------------- * PRIVATE TYPES *--------------------------------------------------------- */ struct clish_config_s { clish_config_op_t op; /* CONFIG operation */ unsigned short priority; char *pattern; char *file; bool_t splitter; char *seq; bool_t unique; char *depth; };
zzysjtu-klish
clish/config/private.h
C
bsd
389
/* * config.c * * This file provides the implementation of a config definition */ #include <stdlib.h> #include <stdio.h> #include <assert.h> #include <string.h> #include "lub/types.h" #include "lub/string.h" #include "private.h" /*--------------------------------------------------------- * PRIVATE METHODS *--------------------------------------------------------- */ static void clish_config_init(clish_config_t *this) { this->op = CLISH_CONFIG_NONE; this->priority = 0; this->pattern = NULL; this->file = NULL; this->splitter = BOOL_TRUE; this->seq = NULL; this->unique = BOOL_TRUE; this->depth = NULL; } /*--------------------------------------------------------- */ static void clish_config_fini(clish_config_t *this) { lub_string_free(this->pattern); lub_string_free(this->file); lub_string_free(this->seq); lub_string_free(this->depth); } /*--------------------------------------------------------- * PUBLIC META FUNCTIONS *--------------------------------------------------------- */ clish_config_t *clish_config_new(void) { clish_config_t *this = malloc(sizeof(clish_config_t)); if (this) clish_config_init(this); return this; } /*--------------------------------------------------------- * PUBLIC METHODS *--------------------------------------------------------- */ void clish_config_delete(clish_config_t *this) { clish_config_fini(this); free(this); } /*--------------------------------------------------------- * PUBLIC ATTRIBUTES *--------------------------------------------------------- */ void clish_config__set_op(clish_config_t *this, clish_config_op_t op) { this->op = op; } /*--------------------------------------------------------- */ clish_config_op_t clish_config__get_op(const clish_config_t *this) { return this->op; } /*--------------------------------------------------------- */ void clish_config__set_priority(clish_config_t *this, unsigned short priority) { this->priority = priority; } /*--------------------------------------------------------- */ unsigned short clish_config__get_priority(const clish_config_t *this) { return this->priority; } /*--------------------------------------------------------- */ void clish_config__set_pattern(clish_config_t *this, const char *pattern) { assert(!this->pattern); this->pattern = lub_string_dup(pattern); } /*--------------------------------------------------------- */ char *clish_config__get_pattern(const clish_config_t *this) { return this->pattern; } /*--------------------------------------------------------- */ void clish_config__set_file(clish_config_t *this, const char *file) { assert(!this->file); this->file = lub_string_dup(file); } /*--------------------------------------------------------- */ char *clish_config__get_file(const clish_config_t *this) { return this->file; } /*--------------------------------------------------------- */ bool_t clish_config__get_splitter(const clish_config_t *this) { return this->splitter; } /*--------------------------------------------------------- */ void clish_config__set_splitter(clish_config_t *this, bool_t splitter) { this->splitter = splitter; } /*--------------------------------------------------------- */ void clish_config__set_seq(clish_config_t *this, const char *seq) { assert(!this->seq); this->seq = lub_string_dup(seq); } /*--------------------------------------------------------- */ const char *clish_config__get_seq(const clish_config_t *this) { return this->seq; } /*--------------------------------------------------------- */ bool_t clish_config__get_unique(const clish_config_t *this) { return this->unique; } /*--------------------------------------------------------- */ void clish_config__set_unique(clish_config_t *this, bool_t unique) { this->unique = unique; } /*--------------------------------------------------------- */ void clish_config__set_depth(clish_config_t *this, const char *depth) { assert(!this->depth); this->depth = lub_string_dup(depth); } /*--------------------------------------------------------- */ const char *clish_config__get_depth(const clish_config_t *this) { return this->depth; }
zzysjtu-klish
clish/config/config.c
C
bsd
4,151
/* * pargv.h */ /** \ingroup clish \defgroup clish_pargv pargv @{ \brief This class represents a vector of command line arguments. */ #ifndef _clish_pargv_h #define _clish_pargv_h typedef enum { CLISH_LINE_OK, CLISH_LINE_PARTIAL, CLISH_BAD_CMD, CLISH_BAD_PARAM, CLISH_BAD_HISTORY } clish_pargv_status_t; typedef struct clish_pargv_s clish_pargv_t; typedef struct clish_parg_s clish_parg_t; #include "clish/ptype.h" #include "clish/command.h" #include "clish/param.h" /*===================================== * PARGV INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ clish_pargv_t *clish_pargv_new(void); /*----------------- * methods *----------------- */ void clish_pargv_delete(clish_pargv_t * instance); const clish_parg_t *clish_pargv_find_arg(clish_pargv_t * instance, const char *name); int clish_pargv_insert(clish_pargv_t * instance, const clish_param_t * param, const char *value); void clish_pargv_dump(const clish_pargv_t * instance); /*----------------- * attributes *----------------- */ unsigned clish_pargv__get_count(clish_pargv_t * instance); clish_parg_t *clish_pargv__get_parg(clish_pargv_t * instance, unsigned index); const clish_param_t *clish_pargv__get_param(clish_pargv_t * instance, unsigned index); /*===================================== * PARG INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ /*----------------- * methods *----------------- */ void clish_parg_dump(const clish_parg_t * instance); /*----------------- * attributes *----------------- */ const char *clish_parg__get_name(const clish_parg_t * instance); const char *clish_parg__get_value(const clish_parg_t * instance); const clish_ptype_t *clish_parg__get_ptype(const clish_parg_t * instance); #endif /* _clish_pargv_h */ /** @} clish_pargv */
zzysjtu-klish
clish/pargv.h
C
bsd
1,901
/* * config.h */ #ifndef _clish_config_h #define _clish_config_h #include "lub/types.h" typedef struct clish_config_s clish_config_t; /* Possible CONFIG operations */ typedef enum { CLISH_CONFIG_NONE, CLISH_CONFIG_SET, CLISH_CONFIG_UNSET, CLISH_CONFIG_DUMP } clish_config_op_t; /*===================================== * COMMAND INTERFACE *===================================== */ /*----------------- * meta functions *----------------- */ clish_config_t *clish_config_new(void); /*----------------- * methods *----------------- */ void clish_config_delete(clish_config_t *instance); void clish_config_dump(const clish_config_t *instance); /*----------------- * attributes *----------------- */ void clish_config__set_op(clish_config_t *instance, clish_config_op_t op); clish_config_op_t clish_config__get_op(const clish_config_t *instance); void clish_config__set_priority(clish_config_t *instance, unsigned short priority); unsigned short clish_config__get_priority(const clish_config_t *instance); void clish_config__set_pattern(clish_config_t *instance, const char *pattern); char *clish_config__get_pattern(const clish_config_t *instance); void clish_config__set_file(clish_config_t *instance, const char *file); char *clish_config__get_file(const clish_config_t *instance); void clish_config__set_splitter(clish_config_t *instance, bool_t splitter); bool_t clish_config__get_splitter(const clish_config_t *instance); void clish_config__set_seq(clish_config_t *instance, const char *seq_num); const char *clish_config__get_seq(const clish_config_t *instance); bool_t clish_config__get_unique(const clish_config_t *instance); void clish_config__set_unique(clish_config_t *instance, bool_t unique); void clish_config__set_depth(clish_config_t *instance, const char *depth); const char *clish_config__get_depth(const clish_config_t *instance); #endif /* _clish_config_h */
zzysjtu-klish
clish/config.h
C
bsd
1,897
/* * var_dump.c */ #include "lub/dump.h" #include "clish/action.h" #include "private.h" /*--------------------------------------------------------- */ void clish_var_dump(const clish_var_t *this) { lub_dump_printf("var(%p)\n", this); lub_dump_indent(); lub_dump_printf("name : %s\n", this->name); lub_dump_printf("dynamic : %s\n", this->dynamic ? "true" : "false"); lub_dump_printf("value : %s\n", this->value); clish_action_dump(this->action); lub_dump_undent(); } /*--------------------------------------------------------- */
zzysjtu-klish
clish/var/var_dump.c
C
bsd
553
/* * var/private.h */ #include "clish/var.h" /*--------------------------------------------------------- * PRIVATE TYPES *--------------------------------------------------------- */ struct clish_var_s { lub_bintree_node_t bt_node; char *name; bool_t dynamic; char *value; char *saved; /* Saved value of static variable */ clish_action_t *action; };
zzysjtu-klish
clish/var/private.h
C
bsd
362
/* * var.c * * This file provides the implementation of the "var" class */ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "lub/string.h" #include "private.h" /*--------------------------------------------------------- * PRIVATE METHODS *--------------------------------------------------------- */ static void clish_var_init(clish_var_t *this, const char *name) { this->name = lub_string_dup(name); this->dynamic = BOOL_FALSE; this->value = NULL; this->action = clish_action_new(); this->saved = NULL; /* Be a good binary tree citizen */ lub_bintree_node_init(&this->bt_node); } /*--------------------------------------------------------- */ static void clish_var_fini(clish_var_t *this) { lub_string_free(this->name); lub_string_free(this->value); clish_action_delete(this->action); lub_string_free(this->saved); } /*--------------------------------------------------------- * PUBLIC META FUNCTIONS *--------------------------------------------------------- */ int clish_var_bt_compare(const void *clientnode, const void *clientkey) { const clish_var_t *this = clientnode; const char *key = clientkey; return strcmp(this->name, key); } /*-------------------------------------------------------- */ void clish_var_bt_getkey(const void *clientnode, lub_bintree_key_t * key) { const clish_var_t *this = clientnode; /* fill out the opaque key */ strcpy((char *)key, this->name); } /*--------------------------------------------------------- */ size_t clish_var_bt_offset(void) { return offsetof(clish_var_t, bt_node); } /*--------------------------------------------------------- */ clish_var_t *clish_var_new(const char *name) { clish_var_t *this = malloc(sizeof(clish_var_t)); if (this) clish_var_init(this, name); return this; } /*--------------------------------------------------------- * PUBLIC METHODS *--------------------------------------------------------- */ void clish_var_delete(clish_var_t *this) { clish_var_fini(this); free(this); } /*--------------------------------------------------------- * PUBLIC ATTRIBUTES *--------------------------------------------------------- */ const char *clish_var__get_name(const clish_var_t *this) { if (!this) return NULL; return this->name; } /*--------------------------------------------------------- */ void clish_var__set_dynamic(clish_var_t *this, bool_t dynamic) { this->dynamic = dynamic; } /*--------------------------------------------------------- */ bool_t clish_var__get_dynamic(const clish_var_t *this) { return this->dynamic; } /*--------------------------------------------------------- */ void clish_var__set_value(clish_var_t *this, const char *value) { if (this->value) lub_string_free(this->value); this->value = lub_string_dup(value); } /*--------------------------------------------------------- */ char *clish_var__get_value(const clish_var_t *this) { return this->value; } /*--------------------------------------------------------- */ clish_action_t *clish_var__get_action(const clish_var_t *this) { return this->action; } /*--------------------------------------------------------- */ void clish_var__set_saved(clish_var_t *this, const char *value) { if (this->saved) lub_string_free(this->saved); this->saved = lub_string_dup(value); } /*--------------------------------------------------------- */ char *clish_var__get_saved(const clish_var_t *this) { return this->saved; }
zzysjtu-klish
clish/var/var.c
C
bsd
3,465
/* * clish_access_callback.c * * * callback hook to check whether the current user is a * member of the specified group (access string) */ #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <assert.h> #include <string.h> #ifdef HAVE_CONFIG_H #include "config.h" #endif /* HAVE_CONFIG_H */ #ifdef HAVE_GRP_H #include <grp.h> #endif #include "lub/string.h" #include "lub/db.h" #include "internal.h" /*--------------------------------------------------------- */ bool_t clish_access_callback(const clish_shell_t * shell, const char *access) { bool_t allowed = BOOL_FALSE; /* assume the user is not allowed */ #ifdef HAVE_GRP_H int num_groups; long ngroups_max; gid_t *group_list; int i; char *tmp_access, *full_access; char *saveptr; assert(access); full_access = lub_string_dup(access); ngroups_max = sysconf(_SC_NGROUPS_MAX) + 1; group_list = (gid_t *)malloc(ngroups_max * sizeof(gid_t)); /* Get the groups for the current user */ num_groups = getgroups(ngroups_max, group_list); assert(num_groups != -1); /* Now check these against the access provided */ /* The external loop goes trough the list of valid groups */ /* The allowed groups are indicated by a colon-separated (:) list. */ for (tmp_access = strtok_r(full_access, ":", &saveptr); tmp_access; tmp_access = strtok_r(NULL, ":", &saveptr)) { /* The internal loop goes trough the system group list */ for (i = 0; i < num_groups; i++) { struct group *ptr = lub_db_getgrgid(group_list[i]); if (!ptr) continue; if (0 == strcmp(ptr->gr_name, tmp_access)) { /* The current user is permitted to use this command */ allowed = BOOL_TRUE; free(ptr); break; } free(ptr); } } lub_string_free(full_access); free(group_list); #endif return allowed; } /*--------------------------------------------------------- */
zzysjtu-klish
clish/callback_access.c
C
bsd
1,861
/* * ptype.h */ /** \ingroup clish \defgroup clish_ptype ptype @{ \brief This class represents a parameter type. Types are a syntatical template which parameters reference. */ #ifndef _clish_ptype_h #define _clish_ptype_h typedef struct clish_ptype_s clish_ptype_t; #include "lub/types.h" #include "lub/bintree.h" #include "lub/argv.h" #include <stddef.h> /*===================================== * PTYPE INTERFACE *===================================== */ /*----------------- * public types *----------------- */ /** * The means by which the pattern is interpreted and * validated. */ typedef enum { /** * [default] - A POSIX regular expression. */ CLISH_PTYPE_REGEXP, /** * A numeric definition "min..max" signed and unsigned versions */ CLISH_PTYPE_INTEGER, CLISH_PTYPE_UNSIGNEDINTEGER, /** * A list of possible values. * The syntax of the string is of the form: * "valueOne(ONE) valueTwo(TWO) valueThree(THREE)" * where the text before the parethesis defines the syntax * that the user must use, and the value within the parenthesis * is the result expanded as a parameter value. */ CLISH_PTYPE_SELECT } clish_ptype_method_e; /** * This defines the pre processing which is to be * performed before a string is validated. */ typedef enum { /** * [default] - do nothing */ CLISH_PTYPE_NONE, /** * before validation convert to uppercase. */ CLISH_PTYPE_TOUPPER, /** * before validation convert to lowercase. */ CLISH_PTYPE_TOLOWER } clish_ptype_preprocess_e; /*----------------- * meta functions *----------------- */ int clish_ptype_bt_compare(const void *clientnode, const void *clientkey); void clish_ptype_bt_getkey(const void *clientnode, lub_bintree_key_t * key); size_t clish_ptype_bt_offset(void); const char *clish_ptype_method__get_name(clish_ptype_method_e method); clish_ptype_method_e clish_ptype_method_resolve(const char *method_name); const char *clish_ptype_preprocess__get_name(clish_ptype_preprocess_e preprocess); clish_ptype_preprocess_e clish_ptype_preprocess_resolve(const char *preprocess_name); clish_ptype_t *clish_ptype_new(const char *name, const char *text, const char *pattern, clish_ptype_method_e method, clish_ptype_preprocess_e preprocess); /*----------------- * methods *----------------- */ void clish_ptype_delete(clish_ptype_t * instance); /** * This is the validation method for the specified type. * \return * - NULL if the validation is negative. * - A pointer to a string containing the validated text. NB. this * may not be identical to that passed in. e.g. it may have been * a case-modified "select" or a preprocessed value. */ char *clish_ptype_validate(const clish_ptype_t * instance, const char *text); /** * This is the translation method for the specified type. The text is * first validated then translated into the form which should be used * for variable substitutions in ACTION or VIEW_ID fields. * \return * - NULL if the validation is negative. * - A pointer to a string containing the translated text. NB. this * may not be identical to that passed in. e.g. it may have been * a translated "select" value. */ char *clish_ptype_translate(const clish_ptype_t * instance, const char *text); /** * This is used to perform parameter auto-completion */ void clish_ptype_word_generator(clish_ptype_t * instance, lub_argv_t *matches, const char *text); void clish_ptype_dump(clish_ptype_t * instance); /*----------------- * attributes *----------------- */ const char *clish_ptype__get_name(const clish_ptype_t * instance); const char *clish_ptype__get_text(const clish_ptype_t * instance); const char *clish_ptype__get_range(const clish_ptype_t * instance); void clish_ptype__set_preprocess(clish_ptype_t * instance, clish_ptype_preprocess_e preprocess); void clish_ptype__set_pattern(clish_ptype_t * instance, const char *pattern, clish_ptype_method_e method); void clish_ptype__set_text(clish_ptype_t * instance, const char *text); #endif /* _clish_ptype_h */ /** @} clish_ptype */
zzysjtu-klish
clish/ptype.h
C
bsd
4,118
#!/bin/sh set -x -e mkdir -p m4 autoreconf -fvi
zzysjtu-klish
autogen.sh
Shell
bsd
49
#include <stm32f10x.h> #include "led.h" const bsp_led_core_group_type led_core_group[ledCoreMax]= { {LED_USER_CORE_PORT, LED_USER_CORE_PIN } }; const bsp_led_bottom_group_type led_bottom_group[ledBottomMax]= { {LED_USER_BOTTOM_PORT, LED_USER_BOTTOM_PIN } }; void bsp_led_gpio_init(void) { GPIO_InitTypeDef GPIO_InitStructure; /* Configure the GPIO ports */ GPIO_InitStructure.GPIO_Pin = LED_USER_CORE_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(LED_USER_CORE_PORT, &GPIO_InitStructure); /* Configure the GPIO ports */ GPIO_InitStructure.GPIO_Pin = LED_USER_BOTTOM_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(LED_USER_BOTTOM_PORT, &GPIO_InitStructure); } void bsp_led_core_on(BSP_LED_CORE_Def led) { if( led >= ledCoreMax ) return; GPIO_SetBits(led_core_group[led].gpio_reg, led_core_group[led].pin); } void bsp_led_core_off(BSP_LED_CORE_Def led) { if( led >= ledCoreMax ) return; GPIO_ResetBits(led_core_group[led].gpio_reg, led_core_group[led].pin); } void bsp_led_core_toggle(BSP_LED_CORE_Def led) { s32 pins; if( led >= ledCoreMax ) return; pins = GPIO_ReadOutputData(led_core_group[ led ].gpio_reg); if ((pins & led_core_group[led].pin) == 0) { GPIO_SetBits(led_core_group[led].gpio_reg, led_core_group[led].pin); } else { GPIO_ResetBits(led_core_group[led].gpio_reg, led_core_group[led].pin); } } void bsp_led_bottom_on(BSP_LED_BOTTOM_Def led) { if( led >= ledBottomMax ) return; GPIO_SetBits(led_bottom_group[led].gpio_reg, led_bottom_group[led].pin); } void bsp_led_bottom_off(BSP_LED_BOTTOM_Def led) { if( led >= ledBottomMax ) return; GPIO_ResetBits(led_bottom_group[led].gpio_reg, led_bottom_group[led].pin); } void bsp_led_bottom_toggle(BSP_LED_BOTTOM_Def led) { s32 pins; if( led >= ledBottomMax ) return; pins = GPIO_ReadOutputData(led_bottom_group[ led ].gpio_reg); if ((pins & led_bottom_group[led].pin) == 0) { GPIO_SetBits(led_bottom_group[led].gpio_reg, led_bottom_group[led].pin); } else { GPIO_ResetBits(led_bottom_group[led].gpio_reg, led_bottom_group[led].pin); } }
zzqq5414-jk-rabbit
sw/all_demo/led.c
C
asf20
2,314
#ifndef USART_PRESENT #define USART_PRESENT #include <stm32f10x_usart.h> /* ------------------------------------------------------------------------------------------------- */ /* BSP USART */ /* ------------------------------------------------------------------------------------------------- */ typedef enum { usartmodeDMA, usartmodeIRQ, usartmodeMAX } usartmode_type; /* ------------------------------------------------------------------------------------------------- */ /* function USART */ /* ------------------------------------------------------------------------------------------------- */ void USART1_IRQHandler(void); /* ------------------------------------------------------------------------------------------------- */ /* extern USART */ /* ------------------------------------------------------------------------------------------------- */ extern void init_usart1_buffer(void); extern void usart_transmit_byte( USART_TypeDef* port, u16 chr); extern void usart1_transmit_byte( u16 chr); extern void usart1_tx_proc(void); extern void usart_transmit_string(USART_TypeDef* port, const void *data); extern void usart1_transmit_string(const void *data); extern void usart1_transmit_string_format(const char * szFormat, ... ); extern void bsp_init_irq_usart1(void/*isr_function usart1_isr*/); extern int usart_is_ne(USART_TypeDef* port); extern int usart1_is_ne(void); extern void* usart1_get_data(void); #endif /* End of module include. */
zzqq5414-jk-rabbit
sw/all_demo/usart.h
C
asf20
1,616
#ifndef _OV7670_H #define _OV7670_H //#include "hw_config.h" #include "sccb.h" ////////////////////////////////////// #undef CAM_PCLK #undef CAM_HREF #define OV7670_SW_V2 #define CAMERA_OV7670_PORT GPIOE // FIFO Setting #define FIFO_RD_PIN GPIO_Pin_3 #define FIFO_WRST_PIN GPIO_Pin_2 #define FIFO_RRST_PIN GPIO_Pin_1 #define FIFO_CS_PIN GPIO_Pin_0 #define FIFO_WE_PIN GPIO_Pin_4 #define FIFO_CS_H() GPIOE->BSRR = FIFO_CS_PIN #define FIFO_CS_L() GPIOE->BRR = FIFO_CS_PIN #define FIFO_WRST_H() GPIOE->BSRR = FIFO_WRST_PIN #define FIFO_WRST_L() GPIOE->BRR = FIFO_WRST_PIN #define FIFO_RRST_H() GPIOE->BSRR = FIFO_RRST_PIN #define FIFO_RRST_L() GPIOE->BRR = FIFO_RRST_PIN #define FIFO_RD_H() GPIOE->BSRR = FIFO_RD_PIN #define FIFO_RD_L() GPIOE->BRR = FIFO_RD_PIN #define FIFO_WE_H() GPIOE->BSRR = FIFO_WE_PIN #define FIFO_WE_L() GPIOE->BRR = FIFO_WE_PIN // Camera setting #define CAMERA_VSYNC_PIN GPIO_Pin_6 #ifdef CAM_PCLK #define CAMERA_PCLK_PIN GPIO_Pin_2 #endif #ifdef CAM_HREF #define CAMERA_HREF_PIN GPIO_Pin_4 #endif #define CAMERA_XCLK_PORT GPIOA #define CAMERA_XCLK_PIN GPIO_Pin_8 // CAMERA IRQ Pin define #define CAMERA_IRQ_PORT_SOURCE GPIO_PortSourceGPIOE #define CAMERA_VSYNC_IRQ_PIN_SOURCE GPIO_PinSource6 #ifdef CAM_PCLK #define CAMERA_PCLK_IRQ_PIN_SOURCE GPIO_PinSource0 #endif #ifdef CAM_HREF #define CAMERA_HREF_IRQ_PIN_SOURCE GPIO_PinSource4 #endif // KEY IRQ External Line #define CAMERA_VSYNC_IRQ_EXTI_Line EXTI_Line6 #ifdef CAM_PCLK #define CAMERA_PCLK_IRQ_EXTI_Line EXTI_Line2 #endif #ifdef CAM_HREF #define CAMERA_HREF_IRQ_EXTI_Line EXTI_Line4 #endif // KEY IRQ channel #define CAMERA_VSYNC_IRQ_CHANNEL EXTI9_5_IRQn #ifdef CAM_PCLK #define CAMERA_PCLK_IRQ_CHANNEL EXTI2_IRQn #endif #ifdef CAM_HREF #define CAMERA_HREF_IRQ_CHANNEL EXTI4_IRQn #endif #if 1 #define XCLK_H GPIOA->BSRR = CAMERA_XCLK_PIN;; #define XCLK_L GPIOA->BRR = CAMERA_XCLK_PIN;; #endif //#define CHANGE_REG_NUM 120 #define CHANGE_REG_NUM 167 /* * Basic window sizes. These probably belong somewhere more globally * useful. */ #define VGA_WIDTH 640 #define VGA_HEIGHT 480 #define QVGA_WIDTH 320 #define QVGA_HEIGHT 240 #define CIF_WIDTH 352 #define CIF_HEIGHT 288 #define QCIF_WIDTH 176 #define QCIF_HEIGHT 144 /* * Our nominal (default) frame rate. */ #define OV7670_FRAME_RATE 30 /* * The 7670 sits on i2c with ID 0x42 */ #define OV7670_I2C_ADDR 0x42 /* Registers */ #define REG_GAIN 0x00 /* Gain lower 8 bits (rest in vref) */ #define REG_BLUE 0x01 /* blue gain */ #define REG_RED 0x02 /* red gain */ #define REG_VREF 0x03 /* Pieces of GAIN, VSTART, VSTOP */ #define REG_COM1 0x04 /* Control 1 */ #define COM1_CCIR656 0x40 /* CCIR656 enable */ #define REG_BAVE 0x05 /* U/B Average level */ #define REG_GbAVE 0x06 /* Y/Gb Average level */ #define REG_AECHH 0x07 /* AEC MS 5 bits */ #define REG_RAVE 0x08 /* V/R Average level */ #define REG_COM2 0x09 /* Control 2 */ #define COM2_SSLEEP 0x10 /* Soft sleep mode */ #define REG_PID 0x0a /* Product ID MSB */ #define REG_VER 0x0b /* Product ID LSB */ #define REG_COM3 0x0c /* Control 3 */ #define COM3_SWAP 0x40 /* Byte swap */ #define COM3_SCALEEN 0x08 /* Enable scaling */ #define COM3_DCWEN 0x04 /* Enable downsamp/crop/window */ #define REG_COM4 0x0d /* Control 4 */ #define REG_COM5 0x0e /* All "reserved" */ #define REG_COM6 0x0f /* Control 6 */ #define REG_AECH 0x10 /* More bits of AEC value */ #define REG_CLKRC 0x11 /* Clocl control */ #define CLK_EXT 0x40 /* Use external clock directly */ #define CLK_SCALE 0x3f /* Mask for internal clock scale */ #define REG_COM7 0x12 /* Control 7 */ #define COM7_RESET 0x80 /* Register reset */ #define COM7_FMT_MASK 0x38 #define COM7_FMT_VGA 0x00 #define COM7_FMT_CIF 0x20 /* CIF format */ #define COM7_FMT_QVGA 0x10 /* QVGA format */ #define COM7_FMT_QCIF 0x08 /* QCIF format */ #define COM7_RGB 0x04 /* bits 0 and 2 - RGB format */ #define COM7_YUV 0x00 /* YUV */ #define COM7_BAYER 0x01 /* Bayer format */ #define COM7_PBAYER 0x05 /* "Processed bayer" */ #define REG_COM8 0x13 /* Control 8 */ #define COM8_FASTAEC 0x80 /* Enable fast AGC/AEC */ #define COM8_AECSTEP 0x40 /* Unlimited AEC step size */ #define COM8_BFILT 0x20 /* Band filter enable */ #define COM8_AGC 0x04 /* Auto gain enable */ #define COM8_AWB 0x02 /* White balance enable */ #define COM8_AEC 0x01 /* Auto exposure enable */ #define REG_COM9 0x14 /* Control 9 - gain ceiling */ #define REG_COM10 0x15 /* Control 10 */ #define COM10_HSYNC 0x40 /* HSYNC instead of HREF */ #define COM10_PCLK_HB 0x20 /* Suppress PCLK on horiz blank */ #define COM10_HREF_REV 0x08 /* Reverse HREF */ #define COM10_VS_LEAD 0x04 /* VSYNC on clock leading edge */ #define COM10_VS_NEG 0x02 /* VSYNC negative */ #define COM10_HS_NEG 0x01 /* HSYNC negative */ #define REG_HSTART 0x17 /* Horiz start high bits */ #define REG_HSTOP 0x18 /* Horiz stop high bits */ #define REG_VSTART 0x19 /* Vert start high bits */ #define REG_VSTOP 0x1a /* Vert stop high bits */ #define REG_PSHFT 0x1b /* Pixel delay after HREF */ #define REG_MIDH 0x1c /* Manuf. ID high */ #define REG_MIDL 0x1d /* Manuf. ID low */ #define REG_MVFP 0x1e /* Mirror / vflip */ #define MVFP_MIRROR 0x20 /* Mirror image */ #define MVFP_FLIP 0x10 /* Vertical flip */ #define REG_AEW 0x24 /* AGC upper limit */ #define REG_AEB 0x25 /* AGC lower limit */ #define REG_VPT 0x26 /* AGC/AEC fast mode op region */ #define REG_HSYST 0x30 /* HSYNC rising edge delay */ #define REG_HSYEN 0x31 /* HSYNC falling edge delay */ #define REG_HREF 0x32 /* HREF pieces */ #define REG_TSLB 0x3a /* lots of stuff */ #define TSLB_YLAST 0x04 /* UYVY or VYUY - see com13 */ #define REG_COM11 0x3b /* Control 11 */ #define COM11_NIGHT 0x80 /* NIght mode enable */ #define COM11_NMFR 0x60 /* Two bit NM frame rate */ #define COM11_HZAUTO 0x10 /* Auto detect 50/60 Hz */ #define COM11_50HZ 0x08 /* Manual 50Hz select */ #define COM11_EXP 0x02 #define REG_COM12 0x3c /* Control 12 */ #define COM12_HREF 0x80 /* HREF always */ #define REG_COM13 0x3d /* Control 13 */ #define COM13_GAMMA 0x80 /* Gamma enable */ #define COM13_UVSAT 0x40 /* UV saturation auto adjustment */ #define COM13_UVSWAP 0x01 /* V before U - w/TSLB */ #define REG_COM14 0x3e /* Control 14 */ #define COM14_DCWEN 0x10 /* DCW/PCLK-scale enable */ #define REG_EDGE 0x3f /* Edge enhancement factor */ #define REG_COM15 0x40 /* Control 15 */ #define COM15_R10F0 0x00 /* Data range 10 to F0 */ #define COM15_R01FE 0x80 /* 01 to FE */ #define COM15_R00FF 0xc0 /* 00 to FF */ #define COM15_RGB565 0x10 /* RGB565 output */ #define COM15_RGB555 0x30 /* RGB555 output */ #define REG_COM16 0x41 /* Control 16 */ #define COM16_AWBGAIN 0x08 /* AWB gain enable */ #define REG_COM17 0x42 /* Control 17 */ #define COM17_AECWIN 0xc0 /* AEC window - must match COM4 */ #define COM17_CBAR 0x08 /* DSP Color bar */ /* * This matrix defines how the colors are generated, must be * tweaked to adjust hue and saturation. * * Order: v-red, v-green, v-blue, u-red, u-green, u-blue * * They are nine-bit signed quantities, with the sign bit * stored in 0x58. Sign for v-red is bit 0, and up from there. */ #define REG_CMATRIX_BASE 0x4f #define CMATRIX_LEN 6 #define REG_CMATRIX_SIGN 0x58 #define REG_BRIGHT 0x55 /* Brightness */ #define REG_CONTRAST 0x56 /* Contrast control */ #define REG_GFIX 0x69 /* Fix gain control */ #define REG_REG76 0x76 /* OV's name */ #define R76_BLKPCOR 0x80 /* Black pixel correction enable */ #define R76_WHTPCOR 0x40 /* White pixel correction enable */ #define REG_RGB444 0x8c /* RGB 444 control */ #define R444_ENABLE 0x02 /* Turn on RGB444, overrides 5x5 */ #define R444_RGBX 0x01 /* Empty nibble at end */ #define REG_HAECC1 0x9f /* Hist AEC/AGC control 1 */ #define REG_HAECC2 0xa0 /* Hist AEC/AGC control 2 */ #define REG_BD50MAX 0xa5 /* 50hz banding step limit */ #define REG_HAECC3 0xa6 /* Hist AEC/AGC control 3 */ #define REG_HAECC4 0xa7 /* Hist AEC/AGC control 4 */ #define REG_HAECC5 0xa8 /* Hist AEC/AGC control 5 */ #define REG_HAECC6 0xa9 /* Hist AEC/AGC control 6 */ #define REG_HAECC7 0xaa /* Hist AEC/AGC control 7 */ #define REG_BD60MAX 0xab /* 60hz banding step limit */ ///////////////////////////////////////// void CLK_init_ON(void); void CLK_init_OFF(void); void CLK_init(void); u8 wrOV7670Reg(u8 regID, u8 regDat); u8 rdOV7670Reg(u8 regID, u8 *regDat); void OV7670_config_window(u16 startx,u16 starty,u16 width, u16 height); void my_delay_ms(u16 time);//delay some time u8 ov7670_init(void); void ov7670_set_qvga(void); void ov7670_set_cif(void); #endif /* _OV7670_H */
zzqq5414-jk-rabbit
sw/all_demo/ov7670.h
C
asf20
10,169
#ifndef RTC_PRESENT #define RTC_PRESENT typedef enum { rtcServiceFunction, rtcServiceFunctionMAX } rtc_register_function_type; typedef void (*rtc_register_function)(void); typedef struct _rtc_service_function_type { rtc_register_function_type service_type; rtc_register_function run; } rtc_service_function_type; /* ------------------------------------------------------------------------------------------------- */ /* BSP RTC */ /* ------------------------------------------------------------------------------------------------- */ extern void register_rtc_function(rtc_register_function_type timer_fn_type, rtc_register_function fn); extern void bsp_init_rtc(void); extern void rtc_configuration(void); extern void time_adjust(void); extern u32 time_regulate(void); #endif
zzqq5414-jk-rabbit
sw/all_demo/rtc.h
C
asf20
832
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_pwr.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Connection/disconnection & power management header ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_PWR_H #define __USB_PWR_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ typedef enum _RESUME_STATE { RESUME_EXTERNAL, RESUME_INTERNAL, RESUME_LATER, RESUME_WAIT, RESUME_START, RESUME_ON, RESUME_OFF, RESUME_ESOF } RESUME_STATE; typedef enum _DEVICE_STATE { UNCONNECTED, ATTACHED, POWERED, SUSPENDED, ADDRESSED, CONFIGURED } DEVICE_STATE; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Suspend(void); void Resume_Init(void); void Resume(RESUME_STATE eResumeSetVal); RESULT PowerOn(void); RESULT PowerOff(void); /* External variables --------------------------------------------------------*/ extern __IO uint32_t bDeviceState; /* USB device status */ extern __IO bool fSuspendEnabled; /* true when suspend is possible */ #endif /*__USB_PWR_H*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_pwr.h
C
asf20
2,244
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_istr.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : ISTR events interrupt service routines ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_prop.h" #include "usb_pwr.h" #include "usb_istr.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint16_t wIstr; /* ISTR register last read value */ __IO uint8_t bIntPackSOF = 0; /* SOFs received between 2 consecutive packets */ /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* function pointers to non-control endpoints service routines */ void (*pEpInt_IN[7])(void) = { EP1_IN_Callback, EP2_IN_Callback, EP3_IN_Callback, EP4_IN_Callback, EP5_IN_Callback, EP6_IN_Callback, EP7_IN_Callback, }; void (*pEpInt_OUT[7])(void) = { EP1_OUT_Callback, EP2_OUT_Callback, EP3_OUT_Callback, EP4_OUT_Callback, EP5_OUT_Callback, EP6_OUT_Callback, EP7_OUT_Callback, }; #ifndef STM32F10X_CL /******************************************************************************* * Function Name : USB_Istr * Description : ISTR events interrupt service routine * Input : None. * Output : None. * Return : None. *******************************************************************************/ void USB_Istr(void) { wIstr = _GetISTR(); #if (IMR_MSK & ISTR_CTR) if (wIstr & ISTR_CTR & wInterrupt_Mask) { /* servicing of the endpoint correct transfer interrupt */ /* clear of the CTR flag into the sub */ CTR_LP(); #ifdef CTR_CALLBACK CTR_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_RESET) if (wIstr & ISTR_RESET & wInterrupt_Mask) { _SetISTR((uint16_t)CLR_RESET); Device_Property.Reset(); #ifdef RESET_CALLBACK RESET_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_DOVR) if (wIstr & ISTR_DOVR & wInterrupt_Mask) { _SetISTR((uint16_t)CLR_DOVR); #ifdef DOVR_CALLBACK DOVR_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_ERR) if (wIstr & ISTR_ERR & wInterrupt_Mask) { _SetISTR((uint16_t)CLR_ERR); #ifdef ERR_CALLBACK ERR_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_WKUP) if (wIstr & ISTR_WKUP & wInterrupt_Mask) { _SetISTR((uint16_t)CLR_WKUP); Resume(RESUME_EXTERNAL); #ifdef WKUP_CALLBACK WKUP_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_SUSP) if (wIstr & ISTR_SUSP & wInterrupt_Mask) { /* check if SUSPEND is possible */ if (fSuspendEnabled) { Suspend(); } else { /* if not possible then resume after xx ms */ Resume(RESUME_LATER); } /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ _SetISTR((uint16_t)CLR_SUSP); #ifdef SUSP_CALLBACK SUSP_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_SOF) if (wIstr & ISTR_SOF & wInterrupt_Mask) { _SetISTR((uint16_t)CLR_SOF); bIntPackSOF++; #ifdef SOF_CALLBACK SOF_Callback(); #endif } #endif /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #if (IMR_MSK & ISTR_ESOF) if (wIstr & ISTR_ESOF & wInterrupt_Mask) { _SetISTR((uint16_t)CLR_ESOF); /* resume handling timing is made with ESOFs */ Resume(RESUME_ESOF); /* request without change of the machine state */ #ifdef ESOF_CALLBACK ESOF_Callback(); #endif } #endif } /* USB_Istr */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ #else /* STM32F10X_CL */ /******************************************************************************* * Function Name : STM32_PCD_OTG_ISR_Handler * Description : Handles all USB Device Interrupts * Input : None * Output : None * Return : status *******************************************************************************/ u32 STM32_PCD_OTG_ISR_Handler (void) { USB_OTG_GINTSTS_TypeDef gintr_status; u32 retval = 0; if (USBD_FS_IsDeviceMode()) /* ensure that we are in device mode */ { gintr_status.d32 = OTGD_FS_ReadCoreItr(); /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* If there is no interrupt pending exit the interrupt routine */ if (!gintr_status.d32) { return 0; } /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Early Suspend interrupt */ #ifdef INTR_ERLYSUSPEND if (gintr_status.b.erlysuspend) { retval |= OTGD_FS_Handle_EarlySuspend_ISR(); } #endif /* INTR_ERLYSUSPEND */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* End of Periodic Frame interrupt */ #ifdef INTR_EOPFRAME if (gintr_status.b.eopframe) { retval |= OTGD_FS_Handle_EOPF_ISR(); } #endif /* INTR_EOPFRAME */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Non Periodic Tx FIFO Emty interrupt */ #ifdef INTR_NPTXFEMPTY if (gintr_status.b.nptxfempty) { retval |= OTGD_FS_Handle_NPTxFE_ISR(); } #endif /* INTR_NPTXFEMPTY */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Wakeup or RemoteWakeup interrupt */ #ifdef INTR_WKUPINTR if (gintr_status.b.wkupintr) { retval |= OTGD_FS_Handle_Wakeup_ISR(); } #endif /* INTR_WKUPINTR */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Suspend interrupt */ #ifdef INTR_USBSUSPEND if (gintr_status.b.usbsuspend) { /* check if SUSPEND is possible */ if (fSuspendEnabled) { Suspend(); } else { /* if not possible then resume after xx ms */ Resume(RESUME_LATER); /* This case shouldn't happen in OTG Device mode because there's no ESOF interrupt to increment the ResumeS.bESOFcnt in the Resume state machine */ } retval |= OTGD_FS_Handle_USBSuspend_ISR(); } #endif /* INTR_USBSUSPEND */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Start of Frame interrupt */ #ifdef INTR_SOFINTR if (gintr_status.b.sofintr) { /* Update the frame number variable */ bIntPackSOF++; retval |= OTGD_FS_Handle_Sof_ISR(); } #endif /* INTR_SOFINTR */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Receive FIFO Queue Status Level interrupt */ #ifdef INTR_RXSTSQLVL if (gintr_status.b.rxstsqlvl) { retval |= OTGD_FS_Handle_RxStatusQueueLevel_ISR(); } #endif /* INTR_RXSTSQLVL */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Enumeration Done interrupt */ #ifdef INTR_ENUMDONE if (gintr_status.b.enumdone) { retval |= OTGD_FS_Handle_EnumDone_ISR(); } #endif /* INTR_ENUMDONE */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Reset interrutp */ #ifdef INTR_USBRESET if (gintr_status.b.usbreset) { retval |= OTGD_FS_Handle_UsbReset_ISR(); } #endif /* INTR_USBRESET */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* IN Endpoint interrupt */ #ifdef INTR_INEPINTR if (gintr_status.b.inepint) { retval |= OTGD_FS_Handle_InEP_ISR(); } #endif /* INTR_INEPINTR */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* OUT Endpoint interrupt */ #ifdef INTR_OUTEPINTR if (gintr_status.b.outepintr) { retval |= OTGD_FS_Handle_OutEP_ISR(); } #endif /* INTR_OUTEPINTR */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Mode Mismatch interrupt */ #ifdef INTR_MODEMISMATCH if (gintr_status.b.modemismatch) { retval |= OTGD_FS_Handle_ModeMismatch_ISR(); } #endif /* INTR_MODEMISMATCH */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Global IN Endpoints NAK Effective interrupt */ #ifdef INTR_GINNAKEFF if (gintr_status.b.ginnakeff) { retval |= OTGD_FS_Handle_GInNakEff_ISR(); } #endif /* INTR_GINNAKEFF */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Global OUT Endpoints NAK effective interrupt */ #ifdef INTR_GOUTNAKEFF if (gintr_status.b.goutnakeff) { retval |= OTGD_FS_Handle_GOutNakEff_ISR(); } #endif /* INTR_GOUTNAKEFF */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Isochrounous Out packet Dropped interrupt */ #ifdef INTR_ISOOUTDROP if (gintr_status.b.isooutdrop) { retval |= OTGD_FS_Handle_IsoOutDrop_ISR(); } #endif /* INTR_ISOOUTDROP */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Endpoint Mismatch error interrupt */ #ifdef INTR_EPMISMATCH if (gintr_status.b.epmismatch) { retval |= OTGD_FS_Handle_EPMismatch_ISR(); } #endif /* INTR_EPMISMATCH */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Incomplete Isochrous IN tranfer error interrupt */ #ifdef INTR_INCOMPLISOIN if (gintr_status.b.incomplisoin) { retval |= OTGD_FS_Handle_IncomplIsoIn_ISR(); } #endif /* INTR_INCOMPLISOIN */ /*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*/ /* Incomplete Isochrous OUT tranfer error interrupt */ #ifdef INTR_INCOMPLISOOUT if (gintr_status.b.outepintr) { retval |= OTGD_FS_Handle_IncomplIsoOut_ISR(); } #endif /* INTR_INCOMPLISOOUT */ } return retval; } #endif /* STM32F10X_CL */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_istr.c
C
asf20
11,753
#include "stm32f10x.h" #include <stm32f10x_spi.h> #include "hw_config.h" #include "mmc_sd.h" #include "spi.h" #include "usart.h" u8 SD_Type = 0; // SD card type // 2010/5/13 // Add some delay, measured to support TF card (1G/2G), Kingston 2G, 4G 16G SD Card // 2010/6/24 // Added u8 SD_GetResponse (u8 Response) function // Modified u8 SD_WaitDataReady (void) function // Added USB card reader support u8 MSD_ReadBuffer (u8 * pBuffer, u32 ReadAddr, u32 NumByteToRead); // And u8 MSD_WriteBuffer (u8 * pBuffer, u32 WriteAddr, u32 NumByteToWrite); two functions void bsp_sd_gpio_init(void) { GPIO_InitTypeDef GPIO_InitStructure; /* For use SD socket */ /* Configure SPI1 pins: SCK, MISO and MOSI */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); /* Configure PA3 pin: CS pin */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); #if 1 // schematic error : duplicate SPI control pin. /* Configure PD2 pin: SPI1_MOSI pin */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOD, &GPIO_InitStructure); /* Configure PC12 pin: SPI1_SCK pin */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_12; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOC, &GPIO_InitStructure); /* Configure PC11 pin: SPI1_CS pin */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOC, &GPIO_InitStructure); #endif } // Initialize SD card // Return if successful, it will automatically set the speed to 18Mhz SPI // Return value: 0: NO_ERR // 1: TIME_OUT // 99: NO_CARD u8 SD_Init (void) { SPI_InitTypeDef SPI_InitStructure; u8 r1; // return value of SD card storage u16 retry; // used to count out u8 buff[6] = {0,0,0,0,0}; MSD_CS_DISABLE(); // bsp_init_spi1(); /* SPI1 Config */ SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_Mode = SPI_Mode_Master; SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b; SPI_InitStructure.SPI_CPOL = SPI_CPOL_High; SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge; SPI_InitStructure.SPI_NSS = SPI_NSS_Soft; SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_256; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; SPI_Init(SPI1, &SPI_InitStructure); /* SPI1 enable */ SPI_Cmd(SPI1, ENABLE); bsp_set_spi1_speed(SPI_SPEED_256); // start transmission bsp_readwritebyte_spi1(0xff); if (SD_Idle_Sta()) return 1; // 1 set out to return to the idle mode failed //----------------- SD card is reset to the idle end of the ----------------- // Get the SD card version MSD_CS_ENABLE(); r1 = SD_SendCommand_NoDeassert (8, 0x1aa, 0x87); // If the version information is the v1.0 version of the card, ie r1 = 0x05, then the following initialization if (r1 == 0x05) { // Set the card type to SDV1.0, if the latter is detected as the MMC card, and then modified to MMC SD_Type = SD_TYPE_V1; // If the V1.0 card, CMD8 instruction did not follow-up data // Set chip select high end of the second order MSD_CS_ENABLE(); // Multiple 8 CLK, so that the end of follow-up operation SD bsp_readwritebyte_spi1 (0xFF); //----------------- SD card, MMC card initialization ----------------- // Initialize command CMD55 + ACMD41 Card // If there is response, that is the SD card, and the initialization is complete // No response, that is the MMC card, the corresponding additional initialization retry = 0; do { // Starting CMD55, should return 0x01; or wrong r1 = SD_SendCommand (CMD55, 0, 0); if (r1 == 0XFF) return r1; // if not 0xff, then sent to // Get the correct response, sent ACMD41, the return value should be 0x00, otherwise retry 200 r1 = SD_SendCommand (ACMD41, 0, 0); retry++; } while ((r1 != 0x00) && (retry <400)); // Determine the correct response is the time-out or // If response: is the SD card; did not respond: is the MMC card //---------- MMC card for additional initialization started ------------ if (retry == 400) { retry = 0; // Initialize command to send MMC card (not tested) do { r1 = SD_SendCommand (1,0,0); retry++; } while ((r1 != 0x00) && (retry <400)); if (retry == 400) return 1; // MMC card initialization timed out // Write card type SD_Type = SD_TYPE_MMC; } //---------- MMC card for additional initialization end ------------ // Set SPI high-speed mode bsp_set_spi1_speed(SPI_SPEED_4); bsp_readwritebyte_spi1 (0xFF); // Disable CRC check r1 = SD_SendCommand (CMD59, 0, 0x95); if (r1 != 0x00) return r1; // command error, returns r1 // Set Sector Size r1 = SD_SendCommand (CMD16, 512, 0x95); if (r1 != 0x00) return r1; // command error, returns r1 //----------------- SD card, MMC card initialization ended ----------------- } // SD Card for the V1.0 version of the initialization is complete // Here is the card initialization V2.0 // Which need to read the OCR data, with a diagnosis or SD2.0HC Card SD2.0 else if (r1 == 0x01) { // V2.0 card, CMD8 command returns 4 bytes of data, and then to skip the end of the command buff[0] = bsp_readwritebyte_spi1 (0xFF); // should be 0x00 buff[1] = bsp_readwritebyte_spi1 (0xFF); // should be 0x00 buff[2] = bsp_readwritebyte_spi1 (0xFF); // should be 0x01 buff[3] = bsp_readwritebyte_spi1 (0xFF); // should be 0xAA MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xFF); // the next 8 clocks // Determine whether the card supports a voltage range of 2.7V-3.6V // If (buff [2] == 0x01 && buff [3] == 0xAA) // do not judge, let the cards to support more { retry = 0; // Initialize command CMD55 + ACMD41 Card do { r1 = SD_SendCommand (CMD55, 0, 0); if (r1 != 0x01) return r1; r1 = SD_SendCommand (ACMD41, 0x40000000, 0); if (retry> 200) return r1; // timeout return status r1 } while (r1 != 0); // Initialize command to send to complete, the next access to OCR information // SD2.0 card identification since version //----------- ----------- r1 = SD_SendCommand_NoDeassert (CMD58, 0, 0); if (r1 != 0x00) { MSD_CS_DISABLE(); // release chip select signal SD return r1; // If the command does not return the correct response, direct withdrawal, return response } // Read OCR command is issued, followed by 4 bytes of OCR information buff [0] = bsp_readwritebyte_spi1 (0xFF); buff [1] = bsp_readwritebyte_spi1 (0xFF); buff [2] = bsp_readwritebyte_spi1 (0xFF); buff [3] = bsp_readwritebyte_spi1 (0xFF); // OCR to receive complete set of high chip select MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xFF); // Check the received OCR in bit30-bit (CCS), was identified as SD2.0 SDHC // If the CCS = 1: SDHC CCS = 0: SD2.0 if (buff [0] & 0x40) SD_Type = SD_TYPE_V2HC; // Check the CCS else SD_Type = SD_TYPE_V2; //----------- Identification card version of SD2.0 end ----------- // Set SPI high-speed mode bsp_set_spi1_speed(SPI_SPEED_4); } } return r1; } // Wait for response to SD card // Response: to get the feedback value // Return value: 0, success has been the value of the response // Otherwise, get the value of failure to respond u8 SD_GetResponse (u8 Response) { u16 Count = 0xFFF; // wait times while ((bsp_readwritebyte_spi1 (0XFF) != Response) && Count) Count--; // waiting to get an accurate response if (Count == 0) return MSD_RESPONSE_FAILURE; // get a response failure else return MSD_RESPONSE_NO_ERROR; // correct response } // Wait for write to complete the SD card // Return value: 0 success; // Other, error codes; u8 SD_WaitDataReady (void) { u8 r1 = MSD_DATA_OTHER_ERROR; u32 retry; retry = 0; do { r1 = bsp_readwritebyte_spi1 (0xFF) &0X1F; // read response if (retry == 0xfffe) return 1; retry++; switch (r1) { case MSD_DATA_OK: // correct the data reception r1 = MSD_DATA_OK; break; case MSD_DATA_CRC_ERROR: // CRC checksum error return MSD_DATA_CRC_ERROR; case MSD_DATA_WRITE_ERROR: // Data write error return MSD_DATA_WRITE_ERROR; default: // Unknown error r1 = MSD_DATA_OTHER_ERROR; break; } } while (r1 == MSD_DATA_OTHER_ERROR); // data errors have been waiting for retry = 0; while (bsp_readwritebyte_spi1 (0XFF) == 0) // read data to 0, the data has not yet completed writing { retry++; // Delay_us (10); // SD card write takes a long time to wait if (retry >= 0XFFFFFFFE) return 0XFF; // Wait failed }; return 0; // success } // Send a command to the SD card // Input: u8 cmd command // U32 arg command arguments // U8 crc crc checksum // Return value: SD card, the response returned u8 SD_SendCommand (u8 cmd, u32 arg, u8 crc) { u8 r1; u8 Retry = 0; // Close the chip select MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xff); // high-speed write command delay bsp_readwritebyte_spi1 (0xff); bsp_readwritebyte_spi1 (0xff); // Chip select low-end set, select the SD card MSD_CS_ENABLE(); // Send bsp_readwritebyte_spi1 (cmd | 0x40); // write command, respectively, bsp_readwritebyte_spi1 (arg>> 24); bsp_readwritebyte_spi1 (arg>> 16); bsp_readwritebyte_spi1 (arg>> 8); bsp_readwritebyte_spi1 (arg); bsp_readwritebyte_spi1 (crc); // Wait for a response, or time-out exit while ((r1 = bsp_readwritebyte_spi1 (0xFF)) == 0xFF) { Retry++; if (Retry> 200) break; } // Close the chip select MSD_CS_DISABLE(); // Additional 8 on the bus clock, so that SD card to complete the remaining work bsp_readwritebyte_spi1 (0xFF); // Return status values return r1; } // Send a command to the SD card (the end is yet to chip select, there came the follow-up data) // Input: u8 cmd command // U32 arg command arguments // U8 crc crc checksum // Return value: SD card, the response returned u8 SD_SendCommand_NoDeassert (u8 cmd, u32 arg, u8 crc) { u8 Retry = 0; u8 r1; bsp_readwritebyte_spi1 (0xff); // high-speed write command delay bsp_readwritebyte_spi1 (0xff); // chip select low-end set, select the SD card MSD_CS_ENABLE(); // Send bsp_readwritebyte_spi1 (cmd | 0x40); // write command, respectively, bsp_readwritebyte_spi1 (arg>> 24); bsp_readwritebyte_spi1 (arg>> 16); bsp_readwritebyte_spi1 (arg>> 8); bsp_readwritebyte_spi1 (arg); bsp_readwritebyte_spi1 (crc); // Wait for a response, or time-out exit while ((r1 = bsp_readwritebyte_spi1 (0xFF)) == 0xFF) { Retry++; if (Retry> 200) break; } // Return the response value return r1; } // Set the SD card into suspend mode // Return value: 0, successfully set // 1, setup failed u8 SD_Idle_Sta (void) { u16 i; u8 r1; u8 retry; for (i = 0; i <0xf00; i++);// pure delay, waiting for complete power-SD card // Should generate> 74 pulses, so that SD card to complete their initialization for (i = 0; i <10; i++) bsp_readwritebyte_spi1 (0xFF); //----------------- SD card is reset to the idle start ----------------- // Loop continuously sending CMD0, until the SD card back 0x01, enter the IDLE state // Timeout then exit retry = 0; do { // Send CMD0, so that SD card into the IDLE state r1 = SD_SendCommand (CMD0, 0, 0x95); retry++; } while ((r1 != 0x01) && (retry <200)); // Exit the loop, check reason: Initialization successful? or try out? if (retry == 200) return 1; // fail return 0; // success } // Read back from the SD card in the specified length of data placed in a given position // Input: u8 * data (read back the data storage memory> len) // U16 len (data length) // U8 release (whether to release the bus after transfer CS is set high 0: do not release 1: Release) // Return value: 0: NO_ERR // Other: Error Message u8 SD_ReceiveData (u8 * data, u16 len, u8 release) { // Start the first transfer MSD_CS_ENABLE(); if (SD_GetResponse (0xFE)) // wait for data sent back to the starting SD card token 0xFE { MSD_CS_DISABLE(); return 1; } while (len--) // Start receiving data { *data = bsp_readwritebyte_spi1 (0xFF); data++; } // Here are two pseudo-CRC (dummy CRC) bsp_readwritebyte_spi1 (0xFF); bsp_readwritebyte_spi1 (0xFF); if (release == RELEASE) // demand the release of the bus, the CS is set high { MSD_CS_DISABLE(); // end of transmission bsp_readwritebyte_spi1 (0xFF); } return 0; } // Get the SD card CID information, including manufacturer information // Input: u8 * cid_data (CID stored in the memory, at least 16Byte) // Return value: 0: NO_ERR // 1: TIME_OUT // Other: Error Message u8 SD_GetCID (u8 * cid_data) { u8 r1; // Send CMD10 command, read CID r1 = SD_SendCommand(CMD10,0,0xff); if (r1 != 0x00) return r1; // do not return the correct answer, then exit, error SD_ReceiveData (cid_data, 16, RELEASE); // 16 bytes of data received return 0; } // Get the SD card, CSD, including the capacity and speed of information // Input: u8 * cid_data (CID stored in the memory, at least 16Byte) // Return value: 0: NO_ERR // 1: TIME_OUT // Other: Error Message u8 SD_GetCSD (u8 *csd_data) { u8 r1; r1 = SD_SendCommand(CMD9, 0, 0xff); // send CMD9 command, read CSD if (r1) return r1; // do not return the correct answer, then exit, error SD_ReceiveData (csd_data, 16, RELEASE); // 16 bytes of data received return 0; } // Get the SD card capacity (bytes) // Return value: 0: take capacity error // Other: SD card capacity (bytes) u32 SD_GetCapacity (void) { u8 csd [16]; u32 Capacity; u8 r1; u16 i; u16 temp; // Get CSD information, if during the error, return 0 if (SD_GetCSD (csd) != 0) return 0; // If the SDHC card, calculated in accordance with the following if ((csd [0] & 0xC0) == 0x40) { Capacity = ((u32) csd [8]) <<8; Capacity += (u32) csd [9] +1; Capacity = (Capacity) * 1024; // get number of sectors Capacity *= 512; // get number of bytes } else { int j; for(j=0;j<16;j++) usart1_transmit_string_format("%x\r\n", csd[j]); i = csd [6] &0x03; usart1_transmit_string_format("\r\ni=%x", i); i <<= 8; usart1_transmit_string_format("\r\ni=%x", i); i += csd [7]; usart1_transmit_string_format("\r\ni=%x", i); i <<= 2; usart1_transmit_string_format("\r\ni=%x", i); i += ((csd [8] & 0xc0)>> 6); usart1_transmit_string_format("\r\ni=%x", i); // C_SIZE_MULT r1 = csd [9] &0x03; r1 <<= 1; r1 += ((csd [10] & 0x80)>> 7); r1 += 2; // BLOCKNR temp = 1; while (r1) { temp *= 2; r1--; } Capacity = ((u32) (i +1 ))*(( u32) temp); usart1_transmit_string_format("\r\ntemp=%d, Capacity=%d, i=%d\r\n", temp, Capacity, i); // READ_BL_LEN i = csd [5] &0x0f; // BLOCK_LEN temp = 1; while (i) { temp *= 2; i--; } usart1_transmit_string_format("\r\\ntemp=%d, Capacity=%d Bytes\r\n", temp, Capacity); // The final result Capacity *= (u32) temp; // in bytes } return (u32) Capacity; } // Read a block SD card // Input: u32 sector to take the address (sector value, non-physical address) // U8 * buffer data storage location (size at least 512byte) // Return value: 0: Success // Other: failure u8 SD_ReadSingleBlock (u32 sector, u8 * buffer) { u8 r1; // Set to high-speed mode // bsp_set_spi1_speed(SPI_SPEED_4); // If it is not SDHC, given that the sector address, convert it into a byte address if (SD_Type != SD_TYPE_V2HC) { sector = sector <<9; } r1 = SD_SendCommand (CMD17, sector, 0); // read command if (r1 != 0x00) return r1; r1 = SD_ReceiveData (buffer, 512, RELEASE); if (r1 != 0) return r1; // read data error! else return 0; } //////////////////////////// Function of the following two required /////////// USB reader ////////////// // Define block size SD card #define BLOCK_SIZE 512 // Write MSD / SD data // PBuffer: Data Storage // ReadAddr: writing the first address // NumByteToRead: number of bytes to write // Return value: 0, write to complete // Otherwise, write failure u8 MSD_WriteBuffer (u8 * pBuffer, u32 WriteAddr, u32 NumByteToWrite) { u32 i, NbrOfBlock = 0, Offset = 0; u32 sector; u8 r1; NbrOfBlock = NumByteToWrite / BLOCK_SIZE; // get the number of blocks to be written MSD_CS_ENABLE(); while (NbrOfBlock--) // write a sector { sector = WriteAddr + Offset; if (SD_Type == SD_TYPE_V2HC) sector >>= 9; // perform the reverse operation and common action r1 = SD_SendCommand_NoDeassert (CMD24, sector, 0xff); // write command if (r1) { MSD_CS_DISABLE(); return 1; // response is not correct, a direct return } bsp_readwritebyte_spi1 (0xFE); // put initial token 0xFE // Put data in a sector for (i = 0; i <512; i++) bsp_readwritebyte_spi1 (*pBuffer++); // Send the dummy CRC Byte 2 bsp_readwritebyte_spi1 (0xff); bsp_readwritebyte_spi1 (0xff); if (SD_WaitDataReady ())// SD card data is written to wait for the completion { MSD_CS_DISABLE(); return 2; } Offset += 512; } // Write completed, set to 1 chip select MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xff); return 0; } // Read the MSD / SD data // PBuffer: Data Storage // ReadAddr: Read the first address // NumByteToRead: number of bytes to read // Return value: 0, read out the complete // Others, read failure u8 MSD_ReadBuffer (u8 * pBuffer, u32 ReadAddr, u32 NumByteToRead) { u32 NbrOfBlock = 0, Offset = 0; u32 sector = 0; u8 r1 = 0; NbrOfBlock = NumByteToRead / BLOCK_SIZE; MSD_CS_ENABLE(); while (NbrOfBlock--) { sector = ReadAddr + Offset; if (SD_Type == SD_TYPE_V2HC) sector >>= 9; // perform the reverse operation and common action r1 = SD_SendCommand_NoDeassert (CMD17, sector, 0xff); // read command if (r1) // command to send an error { MSD_CS_DISABLE(); return r1; } r1 = SD_ReceiveData (pBuffer, 512, RELEASE); if (r1) // reading error { MSD_CS_DISABLE(); return r1; } pBuffer += 512; Offset += 512; } MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xff); return 0; } ////////////////////////////////////////////////////////////////////////// // Write SD card, a block (not actually tested) // Input: u32 sector sector address (sector value, non-physical address) // U8 * buffer data storage location (size at least 512byte) // Return value: 0: Success // Other: failure u8 SD_WriteSingleBlock (u32 sector, const u8 * data) { u8 r1; u16 i; u16 retry; // Set to high-speed mode // SPIx_SetSpeed(SPI_SPEED_HIGH); // If it is not SDHC, given that the sector address, convert it into a byte address if (SD_Type != SD_TYPE_V2HC) { sector = sector <<9; } r1 = SD_SendCommand (CMD24, sector, 0x00); if (r1 != 0x00) { return r1; // response is not correct, a direct return } // Start preparing data MSD_CS_ENABLE(); // First put three empty data, SD card ready to wait bsp_readwritebyte_spi1 (0xff); bsp_readwritebyte_spi1 (0xff); bsp_readwritebyte_spi1 (0xff); // Put initial token 0xFE bsp_readwritebyte_spi1 (0xFE); // Put data in a sector for (i = 0; i <512; i++) { bsp_readwritebyte_spi1 (* data++); } // Send a dummy CRC Byte 2 bsp_readwritebyte_spi1 (0xff); bsp_readwritebyte_spi1 (0xff); // Wait for answer SD Card r1 = bsp_readwritebyte_spi1 (0xff); if ((r1 & 0x1F) != 0x05) { MSD_CS_DISABLE(); return r1; } // Wait operation is completed retry = 0; while ( !bsp_readwritebyte_spi1 (0xff)) { retry++; if (retry> 0xfffe) // if not done for a long time to write, error exit { MSD_CS_DISABLE(); return 1; // write timeout return 1 } } // Write completed, set to 1 chip select MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xff); return 0; } // Read more than one SD card block (actually tested) // Input: u32 sector sector address (sector value, non-physical address) // U8 * buffer data storage location (size at least 512byte) // U8 count one continuous block read count // Return value: 0: Success // Other: failure u8 SD_ReadMultiBlock (u32 sector, u8 * buffer, u8 count) { u8 r1; // SPIx_SetSpeed(SPI_SPEED_HIGH); // set to high-speed mode // If it is not SDHC, the sector addresses turn into a byte address if (SD_Type != SD_TYPE_V2HC) sector = sector <<9; // SD_WaitDataReady (); // Read multi-block commands issued r1 = SD_SendCommand (CMD18, sector, 0); // read command if (r1 != 0x00) return r1; do // Start receiving data { if (SD_ReceiveData (buffer, 512, NO_RELEASE) != 0x00) break; buffer += 512; } while (--count); // All the transmission is completed, send the stop command SD_SendCommand (CMD12, 0, 0); // Release bus MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xFF); if (count != 0) return count; // end if not passed, return the remaining number of else return 0; } // Write SD card, N-block (not actually tested) // Input: u32 sector sector address (sector value, non-physical address) // U8 * buffer data storage location (size at least 512byte) // U8 count the number of write block // Return value: 0: Success // Other: failure u8 SD_WriteMultiBlock (u32 sector, const u8 * data, u8 count) { u8 r1; u16 i; // SPIx_SetSpeed (SPI_SPEED_HIGH); // set to high-speed mode if (SD_Type != SD_TYPE_V2HC) sector = sector <<9; // If it is not SDHC, given that the sector address, convert it to byte address if (SD_Type != SD_TYPE_MMC) r1 = SD_SendCommand (ACMD23, count, 0x00); // If the target card is not the MMC card, enable the command to enable pre-erase ACMD23 r1 = SD_SendCommand (CMD25, sector, 0x00); // send multi-block write command if (r1 != 0x00) return r1; // response is not correct, a direct return MSD_CS_ENABLE(); // start preparing data bsp_readwritebyte_spi1 (0xff); // first put three empty data, SD card ready to wait bsp_readwritebyte_spi1 (0xff); //-------- The following is written by N-loop part of the sector do { // Put the start token that is a multi-block write 0xFC bsp_readwritebyte_spi1 (0xFC); // Put data in a sector for (i = 0; i <512; i++) { bsp_readwritebyte_spi1 (* data++); } // Send a dummy CRC Byte 2 bsp_readwritebyte_spi1 (0xff); bsp_readwritebyte_spi1 (0xff); // Wait for answer SD Card r1 = bsp_readwritebyte_spi1 (0xff); if ((r1 & 0x1F) != 0x05) { MSD_CS_DISABLE(); // If the response is an error, then exit with error code return r1; } // Wait for write to complete the SD card if (SD_WaitDataReady () == 1) { MSD_CS_DISABLE(); // wait for write to complete the SD card out, exit error return 1; } } while (--count); // completion of the sector data transfer // Send end of the transmission token 0xFD r1 = bsp_readwritebyte_spi1 (0xFD); if (r1 == 0x00) { count = 0xfe; } if (SD_WaitDataReady ()) // wait for ready { MSD_CS_DISABLE(); return 1; } // Write completed, set to 1 chip select MSD_CS_DISABLE(); bsp_readwritebyte_spi1 (0xff); return count; // return count value, if finished then count = 0, otherwise, count = 1 } // In the specified sector, began to read out bytes from the offset byte // Input: u32 sector sector address (sector value, non-physical address) // U8 * buf data storage addresses (size <= 512byte) // U16 offset offset inside the sector // U16 bytes number of bytes to read // Return value: 0: Success // Other: failure u8 SD_Read_Bytes (unsigned long address, unsigned char * buf, unsigned int offset, unsigned int bytes) { u8 r1; u16 i = 0; r1 = SD_SendCommand (CMD17, address <<9,0); // send the Read Sector command if (r1) return r1; // response is not correct, a direct return MSD_CS_ENABLE(); // select the SD card if (SD_GetResponse (0xFE)) // wait for data sent back to the starting SD card token 0xFE { MSD_CS_DISABLE(); // close the SD card return 1; // read failure } for (i = 0; i <offset; i++) bsp_readwritebyte_spi1 (0xff); // skip the offset bits for (; i <offset + bytes; i++) * buf++= bsp_readwritebyte_spi1 (0xff); // read the useful data for (; i <512; i++) bsp_readwritebyte_spi1 (0xff); // read the remaining bytes bsp_readwritebyte_spi1 (0xff); // send the pseudo-code CRC bsp_readwritebyte_spi1 (0xff); MSD_CS_DISABLE(); // close the SD card return 0; } u8 SD_WaitReady(void) { u8 r1; u16 retry; retry = 0; do { r1 = bsp_readwritebyte_spi1(0xFF); if(retry==0xfffe) { return 1; } }while(r1!=0xFF); return 0; }
zzqq5414-jk-rabbit
sw/all_demo/mmc_sd.c
C
asf20
25,902
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_desc.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Descriptor Header for Joystick Mouse Demo ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_DESC_H #define __USB_DESC_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported define -----------------------------------------------------------*/ #define USB_DEVICE_DESCRIPTOR_TYPE 0x01 #define USB_CONFIGURATION_DESCRIPTOR_TYPE 0x02 #define USB_STRING_DESCRIPTOR_TYPE 0x03 #define USB_INTERFACE_DESCRIPTOR_TYPE 0x04 #define USB_ENDPOINT_DESCRIPTOR_TYPE 0x05 #define HID_DESCRIPTOR_TYPE 0x21 #define JOYSTICK_SIZ_HID_DESC 0x09 #define JOYSTICK_OFF_HID_DESC 0x12 #define JOYSTICK_SIZ_DEVICE_DESC 18 #define JOYSTICK_SIZ_CONFIG_DESC 34 #define JOYSTICK_SIZ_REPORT_DESC 74 #define JOYSTICK_SIZ_STRING_LANGID 4 #define JOYSTICK_SIZ_STRING_VENDOR 28 //38 #define JOYSTICK_SIZ_STRING_PRODUCT 30 #define JOYSTICK_SIZ_STRING_SERIAL 26 #define STANDARD_ENDPOINT_DESC_SIZE 0x09 /* Exported functions ------------------------------------------------------- */ extern const uint8_t Joystick_DeviceDescriptor[JOYSTICK_SIZ_DEVICE_DESC]; extern const uint8_t Joystick_ConfigDescriptor[JOYSTICK_SIZ_CONFIG_DESC]; extern const uint8_t Joystick_ReportDescriptor[JOYSTICK_SIZ_REPORT_DESC]; extern const uint8_t Joystick_StringLangID[JOYSTICK_SIZ_STRING_LANGID]; extern const uint8_t Joystick_StringVendor[JOYSTICK_SIZ_STRING_VENDOR]; extern const uint8_t Joystick_StringProduct[JOYSTICK_SIZ_STRING_PRODUCT]; extern uint8_t Joystick_StringSerial[JOYSTICK_SIZ_STRING_SERIAL]; #endif /* __USB_DESC_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_desc.h
C
asf20
3,030
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_prop.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : All processings related to Joystick Mouse demo ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_PROP_H #define __USB_PROP_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ typedef enum _HID_REQUESTS { GET_REPORT = 1, GET_IDLE, GET_PROTOCOL, SET_REPORT = 9, SET_IDLE, SET_PROTOCOL } HID_REQUESTS; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Joystick_init(void); void Joystick_Reset(void); void Joystick_SetConfiguration(void); void Joystick_SetDeviceAddress (void); void Joystick_Status_In (void); void Joystick_Status_Out (void); RESULT Joystick_Data_Setup(uint8_t); RESULT Joystick_NoData_Setup(uint8_t); RESULT Joystick_Get_Interface_Setting(uint8_t Interface, uint8_t AlternateSetting); uint8_t *Joystick_GetDeviceDescriptor(uint16_t ); uint8_t *Joystick_GetConfigDescriptor(uint16_t); uint8_t *Joystick_GetStringDescriptor(uint16_t); RESULT Joystick_SetProtocol(void); uint8_t *Joystick_GetProtocolValue(uint16_t Length); RESULT Joystick_SetProtocol(void); uint8_t *Joystick_GetReportDescriptor(uint16_t Length); uint8_t *Joystick_GetHIDDescriptor(uint16_t Length); /* Exported define -----------------------------------------------------------*/ #define Joystick_GetConfiguration NOP_Process //#define Joystick_SetConfiguration NOP_Process #define Joystick_GetInterface NOP_Process #define Joystick_SetInterface NOP_Process #define Joystick_GetStatus NOP_Process #define Joystick_ClearFeature NOP_Process #define Joystick_SetEndPointFeature NOP_Process #define Joystick_SetDeviceFeature NOP_Process //#define Joystick_SetDeviceAddress NOP_Process #define REPORT_DESCRIPTOR 0x22 #endif /* __USB_PROP_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_prop.h
C
asf20
3,122
#ifndef LED_PRESENT #define LED_PRESENT #include "hw_config.h" #include <stm32f10x.h> typedef enum { ledUserCore = 0x00, ledCoreMax } BSP_LED_CORE_Def; typedef enum { ledUserBottom = 0x00, ledBottomMax } BSP_LED_BOTTOM_Def; #define LED_USER_CORE_PORT GPIOC #define LED_USER_CORE_PIN GPIO_Pin_12 #define LED_USER_BOTTOM_PORT GPIOA #define LED_USER_BOTTOM_PIN GPIO_Pin_0 typedef struct { GPIO_TypeDef* gpio_reg; s16 pin; }bsp_led_core_group_type; typedef struct { GPIO_TypeDef* gpio_reg; s16 pin; }bsp_led_bottom_group_type; /* ------------------------------------------------------------------------------------------------- */ /* BSP LED */ /* ------------------------------------------------------------------------------------------------- */ extern void bsp_led_gpio_init(void); extern void bsp_led_core_on(BSP_LED_CORE_Def led); extern void bsp_led_core_off(BSP_LED_CORE_Def led); extern void bsp_led_core_toggle(BSP_LED_CORE_Def led); extern void bsp_led_bottom_on(BSP_LED_BOTTOM_Def led); extern void bsp_led_bottom_off(BSP_LED_BOTTOM_Def led); extern void bsp_led_bottom_toggle(BSP_LED_BOTTOM_Def led); #endif
zzqq5414-jk-rabbit
sw/all_demo/led.h
C
asf20
1,224
/*---------------------------------------------------------------------------/ / FatFs - FAT file system module include file R0.07c (C)ChaN, 2009 /----------------------------------------------------------------------------/ / FatFs module is an open source software to implement FAT file system to / small embedded systems. This is a free software and is opened for education, / research and commercial developments under license policy of following trems. / / Copyright (C) 2009, ChaN, all right reserved. / / * The FatFs module is a free software and there is NO WARRANTY. / * No restriction on use. You can use, modify and redistribute it for / personal, non-profit or commercial product UNDER YOUR RESPONSIBILITY. / * Redistributions of source code must retain the above copyright notice. /----------------------------------------------------------------------------*/ #include "integer.h" /*---------------------------------------------------------------------------/ / FatFs Configuration Options / / CAUTION! Do not forget to make clean the project after any changes to / the configuration options. / /----------------------------------------------------------------------------*/ #ifndef _FATFS #define _FATFS 0x007C #define _WORD_ACCESS 0 /* The _WORD_ACCESS option defines which access method is used to the word / data in the FAT structure. / / 0: Byte-by-byte access. Always compatible with all platforms. / 1: Word access. Do not choose this unless following condition is met. / / When the byte order on the memory is big-endian or address miss-aligned / word access results incorrect behavior, the _WORD_ACCESS must be set to 0. / If it is not the case, the value can also be set to 1 to improve the / performance and code efficiency. */ #define _FS_READONLY 0 /* Setting _FS_READONLY to 1 defines read only configuration. This removes / writing functions, f_write, f_sync, f_unlink, f_mkdir, f_chmod, f_rename, / f_truncate and useless f_getfree. */ #define _FS_MINIMIZE 0 /* The _FS_MINIMIZE option defines minimization level to remove some functions. / / 0: Full function. / 1: f_stat, f_getfree, f_unlink, f_mkdir, f_chmod, f_truncate and f_rename / are removed. / 2: f_opendir and f_readdir are removed in addition to level 1. / 3: f_lseek is removed in addition to level 2. */ #define _FS_TINY 0 /* When _FS_TINY is set to 1, FatFs uses the sector buffer in the file system / object instead of the sector buffer in the individual file object for file / data transfer. This reduces memory consumption 512 bytes each file object. */ #define _USE_STRFUNC 0 /* To enable string functions, set _USE_STRFUNC to 1 or 2. */ #define _USE_MKFS 0 /* To enable f_mkfs function, set _USE_MKFS to 1 and set _FS_READONLY to 0 */ #define _USE_FORWARD 0 /* To enable f_forward function, set _USE_FORWARD to 1 and set _FS_TINY to 1. */ #define _CODE_PAGE 932 /* The _CODE_PAGE specifies the OEM code page to be used on the target system. / / 932 - Japanese Shift-JIS (DBCS, OEM, Windows) / 936 - Simplified Chinese GBK (DBCS, OEM, Windows) / 949 - Korean (DBCS, OEM, Windows) / 950 - Traditional Chinese Big5 (DBCS, OEM, Windows) / 1250 - Central Europe (Windows) / 1251 - Cyrillic (Windows) / 1252 - Latin 1 (Windows) / 1253 - Greek (Windows) / 1254 - Turkish (Windows) / 1255 - Hebrew (Windows) / 1256 - Arabic (Windows) / 1257 - Baltic (Windows) / 1258 - Vietnam (OEM, Windows) / 437 - U.S. (OEM) / 720 - Arabic (OEM) / 737 - Greek (OEM) / 775 - Baltic (OEM) / 850 - Multilingual Latin 1 (OEM) / 858 - Multilingual Latin 1 + Euro (OEM) / 852 - Latin 2 (OEM) / 855 - Cyrillic (OEM) / 866 - Russian (OEM) / 857 - Turkish (OEM) / 862 - Hebrew (OEM) / 874 - Thai (OEM, Windows) / 1 - ASCII (Valid for only non LFN cfg.) */ #define _USE_LFN 0 #define _MAX_LFN 255 /* Maximum LFN length to handle (max:255) */ /* The _USE_LFN option switches the LFN support. / / 0: Disable LFN. / 1: Enable LFN with static working buffer on the bss. NOT REENTRANT. / 2: Enable LFN with dynamic working buffer on the caller's STACK. / / The working buffer occupies (_MAX_LFN + 1) * 2 bytes. When enable LFN, / a Unicode handling functions ff_convert() and ff_wtoupper() must be added / to the project. */ #define _FS_RPATH 0 /* When _FS_RPATH is set to 1, relative path feature is enabled and f_chdir, / f_chdrive function are available. / Note that output of the f_readdir fnction is affected by this option. */ #define _FS_REENTRANT 0 #define _TIMEOUT 1000 /* Timeout period in unit of time ticks of the OS */ #define _SYNC_t HANDLE /* Type of sync object used on the OS. e.g. HANDLE, OS_EVENT*, ID and etc.. */ /* To make the FatFs module re-entrant, set _FS_REENTRANT to 1 and add user / provided synchronization handlers, ff_req_grant, ff_rel_grant, ff_del_syncobj / and ff_cre_syncobj function to the project. */ #define _DRIVES 1 /* Number of volumes (logical drives) to be used. */ #define _MAX_SS 512 /* Maximum sector size to be handled. (512/1024/2048/4096) */ /* Usually set 512 for memory card and hard disk but 1024 for floppy disk, 2048 for MO disk */ /* When _MAX_SS > 512, GET_SECTOR_SIZE must be implememted to disk_ioctl() */ #define _MULTI_PARTITION 0 /* When _MULTI_PARTITION is set to 0, each volume is bound to the same physical / drive number and can mount only first primaly partition. When it is set to 1, / each volume is tied to the partitions listed in Drives[]. */ /* End of configuration options. Do not change followings without care. */ /*--------------------------------------------------------------------------*/ /* DBCS code ranges and SBCS extend char conversion table */ #if _CODE_PAGE == 932 /* Japanese Shift-JIS */ #define _DF1S 0x81 /* DBC 1st byte range 1 start */ #define _DF1E 0x9F /* DBC 1st byte range 1 end */ #define _DF2S 0xE0 /* DBC 1st byte range 2 start */ #define _DF2E 0xFC /* DBC 1st byte range 2 end */ #define _DS1S 0x40 /* DBC 2nd byte range 1 start */ #define _DS1E 0x7E /* DBC 2nd byte range 1 end */ #define _DS2S 0x80 /* DBC 2nd byte range 2 start */ #define _DS2E 0xFC /* DBC 2nd byte range 2 end */ #elif _CODE_PAGE == 936 /* Simplified Chinese GBK */ #define _DF1S 0x81 #define _DF1E 0xFE #define _DS1S 0x40 #define _DS1E 0x7E #define _DS2S 0x80 #define _DS2E 0xFE #elif _CODE_PAGE == 949 /* Korean */ #define _DF1S 0x81 #define _DF1E 0xFE #define _DS1S 0x41 #define _DS1E 0x5A #define _DS2S 0x61 #define _DS2E 0x7A #define _DS3S 0x81 #define _DS3E 0xFE #elif _CODE_PAGE == 950 /* Traditional Chinese Big5 */ #define _DF1S 0x81 #define _DF1E 0xFE #define _DS1S 0x40 #define _DS1E 0x7E #define _DS2S 0xA1 #define _DS2E 0xFE #elif _CODE_PAGE == 437 /* U.S. (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x9A,0x90,0x41,0x8E,0x41,0x8F,0x80,0x45,0x45,0x45,0x49,0x49,0x49,0x8E,0x8F,0x90,0x92,0x92,0x4F,0x99,0x4F,0x55,0x55,0x59,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 720 /* Arabic (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x45,0x41,0x84,0x41,0x86,0x43,0x45,0x45,0x45,0x49,0x49,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x49,0x49,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 737 /* Greek (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x92,0x92,0x93,0x94,0x95,0x96,0x97,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87, \ 0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0xAA,0x92,0x93,0x94,0x95,0x96,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0x97,0xEA,0xEB,0xEC,0xE4,0xED,0xEE,0xE7,0xE8,0xF1,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 775 /* Baltic (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x9A,0x91,0xA0,0x8E,0x95,0x8F,0x80,0xAD,0xED,0x8A,0x8A,0xA1,0x8D,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0x95,0x96,0x97,0x97,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \ 0xA0,0xA1,0xE0,0xA3,0xA3,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xB5,0xB6,0xB7,0xB8,0xBD,0xBE,0xC6,0xC7,0xA5,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE3,0xE8,0xE8,0xEA,0xEA,0xEE,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 850 /* Multilingual Latin 1 (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \ 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 852 /* Latin 2 (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xDE,0x8F,0x80,0x9D,0xD3,0x8A,0x8A,0xD7,0x8D,0x8E,0x8F,0x90,0x91,0x91,0xE2,0x99,0x95,0x95,0x97,0x97,0x99,0x9A,0x9B,0x9B,0x9D,0x9E,0x9F, \ 0xB5,0xD6,0xE0,0xE9,0xA4,0xA4,0xA6,0xA6,0xA8,0xA8,0xAA,0x8D,0xAC,0xB8,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBD,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC6,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD2,0xD5,0xD6,0xD7,0xB7,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE3,0xD5,0xE6,0xE6,0xE8,0xE9,0xE8,0xEB,0xED,0xED,0xDD,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xEB,0xFC,0xFC,0xFE,0xFF} #elif _CODE_PAGE == 855 /* Cyrillic (OEM) */ #define _DF1S 0 #define _EXCVT {0x81,0x81,0x83,0x83,0x85,0x85,0x87,0x87,0x89,0x89,0x8B,0x8B,0x8D,0x8D,0x8F,0x8F,0x91,0x91,0x93,0x93,0x95,0x95,0x97,0x97,0x99,0x99,0x9B,0x9B,0x9D,0x9D,0x9F,0x9F, \ 0xA1,0xA1,0xA3,0xA3,0xA5,0xA5,0xA7,0xA7,0xA9,0xA9,0xAB,0xAB,0xAD,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB6,0xB6,0xB8,0xB8,0xB9,0xBA,0xBB,0xBC,0xBE,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD3,0xD3,0xD5,0xD5,0xD7,0xD7,0xDD,0xD9,0xDA,0xDB,0xDC,0xDD,0xE0,0xDF, \ 0xE0,0xE2,0xE2,0xE4,0xE4,0xE6,0xE6,0xE8,0xE8,0xEA,0xEA,0xEC,0xEC,0xEE,0xEE,0xEF,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF8,0xFA,0xFA,0xFC,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 857 /* Turkish (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0x98,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x98,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9E, \ 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xDE,0x59,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 858 /* Multilingual Latin 1 + Euro (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x9A,0x90,0xB6,0x8E,0xB7,0x8F,0x80,0xD2,0xD3,0xD4,0xD8,0xD7,0xDE,0x8E,0x8F,0x90,0x92,0x92,0xE2,0x99,0xE3,0xEA,0xEB,0x59,0x99,0x9A,0x9D,0x9C,0x9D,0x9E,0x9F, \ 0xB5,0xD6,0xE0,0xE9,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC7,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE5,0xE5,0xE6,0xE7,0xE7,0xE9,0xEA,0xEB,0xED,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 862 /* Hebrew (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0x41,0x49,0x4F,0x55,0xA5,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0x21,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 866 /* Russian (OEM) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0x90,0x91,0x92,0x93,0x9d,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F,0xF0,0xF0,0xF2,0xF2,0xF4,0xF4,0xF6,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 874 /* Thai (OEM, Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 1250 /* Central Europe (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \ 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xA3,0xB4,0xB5,0xB6,0xB7,0xB8,0xA5,0xAA,0xBB,0xBC,0xBD,0xBC,0xAF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF} #elif _CODE_PAGE == 1251 /* Cyrillic (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x80,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x8D,0x8E,0x8F, \ 0xA0,0xA2,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB2,0xA5,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xA3,0xBD,0xBD,0xAF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF} #elif _CODE_PAGE == 1252 /* Latin 1 (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0xAd,0x9B,0x8C,0x9D,0xAE,0x9F, \ 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F} #elif _CODE_PAGE == 1253 /* Greek (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xA2,0xB8,0xB9,0xBA, \ 0xE0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xFB,0xBC,0xFD,0xBF,0xFF} #elif _CODE_PAGE == 1254 /* Turkish (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x8A,0x9B,0x8C,0x9D,0x9E,0x9F, \ 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0x9F} #elif _CODE_PAGE == 1255 /* Hebrew (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 1256 /* Arabic (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x8C,0x9D,0x9E,0x9F, \ 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0x41,0xE1,0x41,0xE3,0xE4,0xE5,0xE6,0x43,0x45,0x45,0x45,0x45,0xEC,0xED,0x49,0x49,0xF0,0xF1,0xF2,0xF3,0x4F,0xF5,0xF6,0xF7,0xF8,0x55,0xFA,0x55,0x55,0xFD,0xFE,0xFF} #elif _CODE_PAGE == 1257 /* Baltic (Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, \ 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xA8,0xB9,0xAA,0xBB,0xBC,0xBD,0xBE,0xAF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xFF} #elif _CODE_PAGE == 1258 /* Vietnam (OEM, Windows) */ #define _DF1S 0 #define _EXCVT {0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0xAC,0x9D,0x9E,0x9F, \ 0xA0,0x21,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF,0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, \ 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xEC,0xCD,0xCE,0xCF,0xD0,0xD1,0xF2,0xD3,0xD4,0xD5,0xD6,0xF7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xFE,0x9F} #elif _CODE_PAGE == 1 /* ASCII (for only non-LFN cfg) */ #define _DF1S 0 #else #error Unknown code page #endif /* Character code support macros */ #define IsUpper(c) (((c)>='A')&&((c)<='Z')) #define IsLower(c) (((c)>='a')&&((c)<='z')) #define IsDigit(c) (((c)>='0')&&((c)<='9')) #if _DF1S /* DBCS configuration */ #if _DF2S /* Two 1st byte areas */ #define IsDBCS1(c) (((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) || ((BYTE)(c) >= _DF2S && (BYTE)(c) <= _DF2E)) #else /* One 1st byte area */ #define IsDBCS1(c) ((BYTE)(c) >= _DF1S && (BYTE)(c) <= _DF1E) #endif #if _DS3S /* Three 2nd byte areas */ #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E) || ((BYTE)(c) >= _DS3S && (BYTE)(c) <= _DS3E)) #else /* Two 2nd byte areas */ #define IsDBCS2(c) (((BYTE)(c) >= _DS1S && (BYTE)(c) <= _DS1E) || ((BYTE)(c) >= _DS2S && (BYTE)(c) <= _DS2E)) #endif #else /* SBCS configuration */ #define IsDBCS1(c) 0 #define IsDBCS2(c) 0 #endif /* _DF1S */ /* Definitions corresponds to multi partition */ #if _MULTI_PARTITION /* Multiple partition configuration */ typedef struct _PARTITION { BYTE pd; /* Physical drive# */ BYTE pt; /* Partition # (0-3) */ } PARTITION; extern const PARTITION Drives[]; /* Logical drive# to physical location conversion table */ #define LD2PD(drv) (Drives[drv].pd) /* Get physical drive# */ #define LD2PT(drv) (Drives[drv].pt) /* Get partition# */ #else /* Single partition configuration */ #define LD2PD(drv) (drv) /* Physical drive# is equal to the logical drive# */ #define LD2PT(drv) 0 /* Always mounts the 1st partition */ #endif /* Definitions corresponds to multiple sector size */ #if _MAX_SS == 512 #define SS(fs) 512U #elif _MAX_SS == 1024 || _MAX_SS == 2048 || _MAX_SS == 4096 #define SS(fs) ((fs)->s_size) #else #error Sector size must be 512, 1024, 2048 or 4096. #endif /* Type of file name on FatFs API */ #if _LFN_UNICODE && _USE_LFN typedef WCHAR XCHAR; /* Unicode */ #else typedef char XCHAR; /* SBCS, DBCS */ #endif /* File system object structure */ typedef struct _FATFS_ { BYTE fs_type; /* FAT sub type */ BYTE drive; /* Physical drive number */ BYTE csize; /* Number of sectors per cluster */ BYTE n_fats; /* Number of FAT copies */ BYTE wflag; /* win[] dirty flag (1:must be written back) */ WORD id; /* File system mount ID */ WORD n_rootdir; /* Number of root directory entries (0 on FAT32) */ #if _FS_REENTRANT _SYNC_t sobj; /* Identifier of sync object */ #endif #if _MAX_SS != 512 WORD s_size; /* Sector size */ #endif #if !_FS_READONLY BYTE fsi_flag; /* fsinfo dirty flag (1:must be written back) */ DWORD last_clust; /* Last allocated cluster */ DWORD free_clust; /* Number of free clusters */ DWORD fsi_sector; /* fsinfo sector */ #endif #if _FS_RPATH DWORD cdir; /* Current directory (0:root)*/ #endif DWORD sects_fat; /* Sectors per fat */ DWORD max_clust; /* Maximum cluster# + 1. Number of clusters is max_clust - 2 */ DWORD fatbase; /* FAT start sector */ DWORD dirbase; /* Root directory start sector (Cluster# on FAT32) */ DWORD database; /* Data start sector */ DWORD winsect; /* Current sector appearing in the win[] */ BYTE win[_MAX_SS];/* Disk access window for Directory/FAT */ } FATFS; /* Directory object structure */ typedef struct _DIR_ { FATFS* fs; /* Pointer to the owner file system object */ WORD id; /* Owner file system mount ID */ WORD index; /* Current read/write index number */ DWORD sclust; /* Table start cluster (0:Static table) */ DWORD clust; /* Current cluster */ DWORD sect; /* Current sector */ BYTE* dir; /* Pointer to the current SFN entry in the win[] */ BYTE* fn; /* Pointer to the SFN (in/out) {file[8],ext[3],status[1]} */ #if _USE_LFN WCHAR* lfn; /* Pointer to the LFN working buffer */ WORD lfn_idx; /* Last matched LFN index number (0xFFFF:No LFN) */ #endif } DIR; /* File object structure */ typedef struct _FIL_ { FATFS* fs; /* Pointer to the owner file system object */ WORD id; /* Owner file system mount ID */ BYTE flag; /* File status flags */ BYTE csect; /* Sector address in the cluster */ DWORD fptr; /* File R/W pointer */ DWORD fsize; /* File size */ DWORD org_clust; /* File start cluster */ DWORD curr_clust; /* Current cluster */ DWORD dsect; /* Current data sector */ #if !_FS_READONLY DWORD dir_sect; /* Sector containing the directory entry */ BYTE* dir_ptr; /* Ponter to the directory entry in the window */ #endif #if !_FS_TINY BYTE buf[_MAX_SS];/* File R/W buffer */ #endif } FIL; /* File status structure */ typedef struct _FILINFO_ { DWORD fsize; /* File size */ WORD fdate; /* Last modified date */ WORD ftime; /* Last modified time */ BYTE fattrib; /* Attribute */ char fname[13]; /* Short file name (8.3 format) */ #if _USE_LFN XCHAR* lfname; /* Pointer to the LFN buffer */ int lfsize; /* Size of LFN buffer [chrs] */ #endif } FILINFO; /* File function return code (FRESULT) */ typedef enum { FR_OK = 0, /* 0 */ FR_DISK_ERR, /* 1 */ FR_INT_ERR, /* 2 */ FR_NOT_READY, /* 3 */ FR_NO_FILE, /* 4 */ FR_NO_PATH, /* 5 */ FR_INVALID_NAME, /* 6 */ FR_DENIED, /* 7 */ FR_EXIST, /* 8 */ FR_INVALID_OBJECT, /* 9 */ FR_WRITE_PROTECTED, /* 10 */ FR_INVALID_DRIVE, /* 11 */ FR_NOT_ENABLED, /* 12 */ FR_NO_FILESYSTEM, /* 13 */ FR_MKFS_ABORTED, /* 14 */ FR_TIMEOUT /* 15 */ } FRESULT; /*--------------------------------------------------------------*/ /* FatFs module application interface */ FRESULT f_mount (BYTE, FATFS*); /* Mount/Unmount a logical drive */ FRESULT f_open (FIL*, const XCHAR*, BYTE); /* Open or create a file */ FRESULT f_read (FIL*, void*, UINT, UINT*); /* Read data from a file */ FRESULT f_write (FIL*, const void*, UINT, UINT*); /* Write data to a file */ FRESULT f_lseek (FIL*, DWORD); /* Move file pointer of a file object */ FRESULT f_close (FIL*); /* Close an open file object */ FRESULT f_opendir (DIR*, const XCHAR*); /* Open an existing directory */ FRESULT f_readdir (DIR*, FILINFO*); /* Read a directory item */ FRESULT f_stat (const XCHAR*, FILINFO*); /* Get file status */ FRESULT f_getfree (const XCHAR*, DWORD*, FATFS**); /* Get number of free clusters on the drive */ FRESULT f_truncate (FIL*); /* Truncate file */ FRESULT f_sync (FIL*); /* Flush cached data of a writing file */ FRESULT f_unlink (const XCHAR*); /* Delete an existing file or directory */ FRESULT f_mkdir (const XCHAR*); /* Create a new directory */ FRESULT f_chmod (const XCHAR*, BYTE, BYTE); /* Change attriburte of the file/dir */ FRESULT f_utime (const XCHAR*, const FILINFO*); /* Change timestamp of the file/dir */ FRESULT f_rename (const XCHAR*, const XCHAR*); /* Rename/Move a file or directory */ FRESULT f_forward (FIL*, UINT(*)(const BYTE*,UINT), UINT, UINT*); /* Forward data to the stream */ FRESULT f_mkfs (BYTE, BYTE, WORD); /* Create a file system on the drive */ FRESULT f_chdir (const XCHAR*); /* Change current directory */ FRESULT f_chdrive (BYTE); /* Change current drive */ #if _USE_STRFUNC int f_putc (int, FIL*); /* Put a character to the file */ int f_puts (const char*, FIL*); /* Put a string to the file */ int f_printf (FIL*, const char*, ...); /* Put a formatted string to the file */ char* f_gets (char*, int, FIL*); /* Get a string from the file */ #define f_eof(fp) (((fp)->fptr == (fp)->fsize) ? 1 : 0) #define f_error(fp) (((fp)->flag & FA__ERROR) ? 1 : 0) #ifndef EOF #define EOF -1 #endif #endif /*--------------------------------------------------------------*/ /* User defined functions */ /* Real time clock */ #if !_FS_READONLY DWORD get_fattime (void); /* 31-25: Year(0-127 org.1980), 24-21: Month(1-12), 20-16: Day(1-31) */ /* 15-11: Hour(0-23), 10-5: Minute(0-59), 4-0: Second(0-29 *2) */ #endif /* Unicode - OEM code conversion */ #if _USE_LFN WCHAR ff_convert (WCHAR, UINT); WCHAR ff_wtoupper (WCHAR); #endif /* Sync functions */ #if _FS_REENTRANT BOOL ff_cre_syncobj(BYTE, _SYNC_t*); BOOL ff_del_syncobj(_SYNC_t); BOOL ff_req_grant(_SYNC_t); void ff_rel_grant(_SYNC_t); #endif /*--------------------------------------------------------------*/ /* Flags and offset address */ /* File access control and file status flags (FIL.flag) */ #define FA_READ 0x01 #define FA_OPEN_EXISTING 0x00 #if _FS_READONLY == 0 #define FA_WRITE 0x02 #define FA_CREATE_NEW 0x04 #define FA_CREATE_ALWAYS 0x08 #define FA_OPEN_ALWAYS 0x10 #define FA__WRITTEN 0x20 #define FA__DIRTY 0x40 #endif #define FA__ERROR 0x80 /* FAT sub type (FATFS.fs_type) */ #define FS_FAT12 1 #define FS_FAT16 2 #define FS_FAT32 3 /* File attribute bits for directory entry */ #define AM_RDO 0x01 /* Read only */ #define AM_HID 0x02 /* Hidden */ #define AM_SYS 0x04 /* System */ #define AM_VOL 0x08 /* Volume label */ #define AM_LFN 0x0F /* LFN entry */ #define AM_DIR 0x10 /* Directory */ #define AM_ARC 0x20 /* Archive */ #define AM_MASK 0x3F /* Mask of defined bits */ /* FatFs refers the members in the FAT structures with byte offset instead / of structure member because there are incompatibility of the packing option / between various compilers. */ #define BS_jmpBoot 0 #define BS_OEMName 3 #define BPB_BytsPerSec 11 #define BPB_SecPerClus 13 #define BPB_RsvdSecCnt 14 #define BPB_NumFATs 16 #define BPB_RootEntCnt 17 #define BPB_TotSec16 19 #define BPB_Media 21 #define BPB_FATSz16 22 #define BPB_SecPerTrk 24 #define BPB_NumHeads 26 #define BPB_HiddSec 28 #define BPB_TotSec32 32 #define BS_55AA 510 #define BS_DrvNum 36 #define BS_BootSig 38 #define BS_VolID 39 #define BS_VolLab 43 #define BS_FilSysType 54 #define BPB_FATSz32 36 #define BPB_ExtFlags 40 #define BPB_FSVer 42 #define BPB_RootClus 44 #define BPB_FSInfo 48 #define BPB_BkBootSec 50 #define BS_DrvNum32 64 #define BS_BootSig32 66 #define BS_VolID32 67 #define BS_VolLab32 71 #define BS_FilSysType32 82 #define FSI_LeadSig 0 #define FSI_StrucSig 484 #define FSI_Free_Count 488 #define FSI_Nxt_Free 492 #define MBR_Table 446 #define DIR_Name 0 #define DIR_Attr 11 #define DIR_NTres 12 #define DIR_CrtTime 14 #define DIR_CrtDate 16 #define DIR_FstClusHI 20 #define DIR_WrtTime 22 #define DIR_WrtDate 24 #define DIR_FstClusLO 26 #define DIR_FileSize 28 #define LDIR_Ord 0 #define LDIR_Attr 11 #define LDIR_Type 12 #define LDIR_Chksum 13 #define LDIR_FstClusLO 26 /*--------------------------------*/ /* Multi-byte word access macros */ #if _WORD_ACCESS == 1 /* Enable word access to the FAT structure */ #define LD_WORD(ptr) (WORD)(*(WORD*)(BYTE*)(ptr)) #define LD_DWORD(ptr) (DWORD)(*(DWORD*)(BYTE*)(ptr)) #define ST_WORD(ptr,val) *(WORD*)(BYTE*)(ptr)=(WORD)(val) #define ST_DWORD(ptr,val) *(DWORD*)(BYTE*)(ptr)=(DWORD)(val) #else /* Use byte-by-byte access to the FAT structure */ #define LD_WORD(ptr) (WORD)(((WORD)*(BYTE*)((ptr)+1)<<8)|(WORD)*(BYTE*)(ptr)) #define LD_DWORD(ptr) (DWORD)(((DWORD)*(BYTE*)((ptr)+3)<<24)|((DWORD)*(BYTE*)((ptr)+2)<<16)|((WORD)*(BYTE*)((ptr)+1)<<8)|*(BYTE*)(ptr)) #define ST_WORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *(BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8) #define ST_DWORD(ptr,val) *(BYTE*)(ptr)=(BYTE)(val); *(BYTE*)((ptr)+1)=(BYTE)((WORD)(val)>>8); *(BYTE*)((ptr)+2)=(BYTE)((DWORD)(val)>>16); *(BYTE*)((ptr)+3)=(BYTE)((DWORD)(val)>>24) #endif #endif /* _FATFS */
zzqq5414-jk-rabbit
sw/all_demo/ff.h
C
asf20
34,621
#ifndef NRF24L01_PRESENT #define NRF24L01_PRESENT #include "hw_config.h" #include <stm32f10x.h> ////////////////////////////////////////////////////////////////////////////////////////////////////////// // NRF24L01 register operation commands #define NRF24L01_READ_REG 0x00 // read configuration register, register address lower 5 bits #define NRF24L01_WRITE_REG 0x20 // write configuration register, register address lower 5 bits #define RD_RX_PLOAD 0x61 // read RX valid data, 1 ~ 32 bytes #define WR_TX_PLOAD 0xA0 // Write TX valid data, 1 ~ 32 bytes #define FLUSH_TX 0xE1 // Clear TX FIFO registers. Transmit mode with #define FLUSH_RX 0xE2 // clear the RX FIFO registers. Receive mode with #define REUSE_TX_PL 0xE3 // re-use on a packet of data, CE is high, the data packets are continuously sent. #define NOP 0xFF // air operations, can be used to read status register // SPI (NRF24L01) register address // configuration register address; // bit0 : 1 receive mode, 0 transmit mode; // bit1: electric choice; // bit2: CRC mode; // bit3: CRC enabled; // Bit4 : Interrupt MAX_RT (re-issued the maximum number of interrupt) is enabled; // bit5: Enable interrupt TX_DS; // bit6: Enable interrupt RX_DR #define CONFIG 0x00 #define EN_AA 0x01 // Enable auto answer bit0 ~ 5, corresponding to channel 0 to 5 #define EN_RXADDR 0x02 // recipient address allows, bit0 ~ 5, corresponding to channel 0 to 5 #define SETUP_AW 0x03 // set the address width (all data channels): bit1, 0:00,3 bytes; 01,4 bytes; 02,5 bytes; #define SETUP_RETR 0x04 // set up automatic repeat; bit3: 0, automatic repeat counter; bit7: 4, automatic re-issued delay of 250 * x +86 us #define RF_CH 0x05 // RF channel, bit6: 0, working channel frequency; #define RF_SETUP 0x06 // RF registers; bit3: transfer rate (0:1 Mbps, 1:2 Mbps); bit2: 1, transmission power; bit0: low-noise amplifier gain #define STATUS 0x07 // status register; bit0: TX FIFO full flag; bit3: 1, receive data channel number (maximum: 6); bit4, to achieve the best re-issued several times // Bit5: data transmission completion interrupt; bit6: receive data interrupt; #define MAX_TX 0x10 // send the maximum number of interrupt #define TX_OK 0x20 // TX interrupt transmission completed #define RX_OK 0x40 // receive data interrupt #define OBSERVE_TX 0x08 // send a test registers, bit7: 4, packet loss counter; bit3: 0, retransmission counter #define CD 0x09 // Carrier detect register, bit0, carrier detection; #define RX_ADDR_P0 0x0A // Receive data channel 0 address, the maximum length of 5 bytes, low byte first #define RX_ADDR_P1 0x0B // Data channel 1 receiver address, the maximum length of 5 bytes, low byte first #define RX_ADDR_P2 0x0C // Receive data channel 2 address byte can be set low, high byte must be the same RX_ADDR_P1 [39:8] are equal; #define RX_ADDR_P3 0x0D // data channel 3 receiver address, set the lowest byte, high byte must be the same RX_ADDR_P1 [39:8] are equal; #define RX_ADDR_P4 0x0E // data channel 4 receiver address, set the lowest byte, high byte must be the same RX_ADDR_P1 [39:8] are equal; #define RX_ADDR_P5 0x0F // data channel 5 to receive the address, set the lowest byte, high byte must be the same RX_ADDR_P1 [39:8] are equal; #define TX_ADDR 0x10 // send the address (LSB first), ShockBurstTM mode, RX_ADDR_P0 equal to this address #define RX_PW_P0 0x11 // Channel 0 receive data valid data width (1 to 32 bytes), set to 0 illicit #define RX_PW_P1 0x12 // Receive data channel 1 valid data width (1 to 32 bytes), set to 0 illicit #define RX_PW_P2 0x13 // receive data valid data width of the channel 2 (1 ~ 32 bytes), set to 0 illicit #define RX_PW_P3 0x14 // receive data channel 3 valid data width (1 to 32 bytes), set to 0 illicit #define RX_PW_P4 0x15 // receive data valid data width of the channel 4 (1 ~ 32 bytes), set to 0 illicit #define RX_PW_P5 0x16 // receive data channel 5 valid data width (1 to 32 bytes), set to 0 illicit #define FIFO_STATUS 0x17 // FIFO Status Register; bit0, RX FIFO register empty flag; bit1, RX FIFO full flag; bit2, 3, to retain // Bit4, TX FIFO empty flag; bit5, TX FIFO full flag; bit6, 1, loop sending data packets on a .0, no circulation; ////////////////////////////////////////////////////////////////////////////////////////////////////////// // 24L01 operating line #define NRF24L01_CE PAout (4) // 24L01 chip select signal #define NRF24L01_CSN PCout (4) // SPI Chip Select #define NRF24L01_IRQ PCin (5) // IRQ host data input // 24L01 send and receive data width defined #define TX_ADR_WIDTH 5 // 5 the width of the address byte #define RX_ADR_WIDTH 5 // 5 the width of the address byte #define TX_PLOAD_WIDTH 32 // 20 bytes of user data width #define RX_PLOAD_WIDTH 32 // 20 bytes of user data width void bsp_nrf24l01_init (void); // initialization void nRF24L01_RX_Mode (void); // configured to receive mode void nRF24L01_TX_Mode (void); // configured to transmit mode u8 nRF24L01_Write_Buf (u8 reg, u8 * pBuf, u8 u8s); // write data area u8 nRF24L01_Read_Buf (u8 reg, u8 * pBuf, u8 u8s); // read data area u8 nRF24L01_Read_Reg (u8 reg); // read register u8 nRF24L01_Write_Reg (u8 reg, u8 value); // write register u8 nRF24L01_Check (void); // check whether there 24L01 u8 nRF24L01_TxPacket (u8 * txbuf); // send a packet of data u8 nRF24L01_RxPacket (u8 * rxbuf); // Receive a packet of data #endif
zzqq5414-jk-rabbit
sw/all_demo/nrf24l01.h
C
asf20
5,517
#include "stm32f10x.h" #include "queue.h" /* ------------------------------------------------------------------------ ** For Win32 Systems, users may want to enable mutual exclusion for the ** queue operations, this provides a mutex per queue along with locking ** and unlocking primitives. ** ------------------------------------------------------------------------ */ #define q_lock( q ) INTLOCK( ) #define q_free( q ) INTFREE( ) void q_init_list(q_list_type* list) { list->first = list->last = NULL; } void q_add_tail(q_list_type* list, q_node_type* node) { node->next = list->first; node->prev = NULL; if( list->first ) list->first->prev = node; else list->last = node; list->first = node; list->count++; } void q_add_head(q_list_type* list, q_node_type* node) { node->next = list->first; node->prev = NULL; if( list->first ) list->first->prev = node; else list->last = node; list->first = node; list->count++; } void q_remove_node(q_list_type* list, q_node_type* node) { if( node->next ) node->next->prev = node->prev; else list->last = node->prev; if( node->prev ) node->prev->next = node->next; else list->first = node->next; list->count--; } q_node_type* q_remove_head(q_list_type* list) { q_node_type* node = list->first; if( !node ) return NULL; q_remove_node(list, node); return node; } q_node_type* q_remove_tail(q_list_type* list) { q_node_type* node = list->last; if( !node ) return NULL; q_remove_node(list, node); return node; } void q_remove_all(q_list_type* list) { q_node_type* node; while((node = q_remove_head(list)) != NULL ); } s16 q_get_count(q_list_type* list) { return list->count; }
zzqq5414-jk-rabbit
sw/all_demo/queue.c
C
asf20
1,781
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : hw_config.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Hardware Configuration & Setup ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" #include "hw_config.h" #include "usb_lib.h" #include "usb_desc.h" #include "platform_config.h" #include "usb_pwr.h" #include "usb_lib.h" #include "led.h" #include "mmc_sd.h" #include "key.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ ErrorStatus HSEStartUpStatus; // EXTI_InitTypeDef EXTI_InitStructure; /* Extern variables ----------------------------------------------------------*/ //static u8 fac_us=0; //static u16 fac_ms=0; /* Private function prototypes -----------------------------------------------*/ static void IntToUnicode (uint32_t value , uint8_t *pbuf , uint8_t len); /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : Set_System * Description : Configures Main system clocks & power. * Input : None. * Return : None. *******************************************************************************/ void bsp_init_rcc(void) { #if 1 /* SYSCLK, HCLK, PCLK2 and PCLK1 configuration -----------------------------*/ /* RCC system reset(for debug purpose) */ RCC_DeInit(); /* Enable HSE */ RCC_HSEConfig(RCC_HSE_ON); /* Wait till HSE is ready */ HSEStartUpStatus = RCC_WaitForHSEStartUp(); if (HSEStartUpStatus == SUCCESS) { /* Enable Prefetch Buffer */ FLASH_PrefetchBufferCmd(FLASH_PrefetchBuffer_Enable); /* Flash 2 wait state */ FLASH_SetLatency(FLASH_Latency_2); /* HCLK = SYSCLK */ RCC_HCLKConfig(RCC_SYSCLK_Div1); /* PCLK2 = HCLK */ RCC_PCLK2Config(RCC_HCLK_Div1); /* PCLK1 = HCLK/2 */ RCC_PCLK1Config(RCC_HCLK_Div2); #if defined( STM32F10X_CL ) /* Configure PLLs *********************************************************/ /* PLL2 configuration: PLL2CLK = (HSE / 5) * 8 = 40 MHz */ RCC_PREDIV2Config(RCC_PREDIV2_Div5); RCC_PLL2Config(RCC_PLL2Mul_8); /* Enable PLL2 */ RCC_PLL2Cmd(ENABLE); /* Wait till PLL2 is ready */ while (RCC_GetFlagStatus(RCC_FLAG_PLL2RDY) == RESET) {} #if defined (HSE_8MHZ) /* PLL configuration: PLLCLK = (PLL2 / 5) * 9 = 72 MHz */ RCC_PREDIV1Config(RCC_PREDIV1_Source_PLL2, RCC_PREDIV1_Div5); RCC_PLLConfig(RCC_PLLSource_PREDIV1, RCC_PLLMul_9); #endif #else #if defined (HSE_12MHZ) /* PLLCLK = 12MHz * 6 = 72 MHz */ RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_6); #elif defined( HSE_16MHZ ) /* PLLCLK = 16MHz /2 * 9 = 72 MHz */ RCC_PLLConfig(RCC_PLLSource_HSE_Div2, RCC_PLLMul_9); #else // 8MHZ /* PLLCLK = 8MHz * 9 = 72 MHz */ RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9); #endif #endif /* Enable PLL */ RCC_PLLCmd(ENABLE); /* Wait till PLL is ready */ while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) { } /* Select PLL as system clock source */ RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); /* Wait till PLL is used as system clock source */ while(RCC_GetSYSCLKSource() != 0x08) { } } else { /* If HSE fails to start-up, the application will have wrong clock configuration. User can add here some code to deal with this error */ /* Go to infinite loop */ while (1) { } } /* enable the PWR clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE); /* Enable GPIOA, GPIOB, GPIOC, GPIOD, GPIOE and AFIO clocks */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB |RCC_APB2Periph_GPIOC | RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE | RCC_APB2Periph_AFIO, ENABLE); /* USART1 Periph clock enable */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); /* TIM1 Periph clock enable */ // RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); /* SPI1 Periph clock enable */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE); /* ADC1 Periph clock enable */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); ///////////////////////////////////////////////////////////////////// // APB1 ///////////////////////////////////////////////////////////////////// /* TIM2 clock enable */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); /* TIM4 clock enable */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); /* USART3 clock enable */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); Set_USBClock(); #endif #if 0 SystemInit(); RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA |RCC_APB2Periph_GPIOB | RCC_APB2Periph_GPIOC |RCC_APB2Periph_GPIOD | RCC_APB2Periph_GPIOE |RCC_APB2Periph_ADC1 | RCC_APB2Periph_AFIO |RCC_APB2Periph_SPI1, ENABLE ); // RCC_APB2PeriphClockCmd(RCC_APB2Periph_ALL ,ENABLE ); RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4 |RCC_APB1Periph_USART3|RCC_APB1Periph_TIM2 , ENABLE ); RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE); #endif } /******************************************************************************* * Function Name : Set_USBClock * Description : Configures USB Clock input (48MHz). * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Set_USBClock(void) { #ifdef STM32F10X_CL /* Select USBCLK source */ RCC_OTGFSCLKConfig(RCC_OTGFSCLKSource_PLLVCO_Div3); /* Enable the USB clock */ RCC_AHBPeriphClockCmd(RCC_AHBPeriph_OTG_FS, ENABLE) ; #else /* Select USBCLK source */ RCC_USBCLKConfig(RCC_USBCLKSource_PLLCLK_1Div5); /* Enable the USB clock */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_USB, ENABLE); #endif /* STM32F10X_CL */ } /******************************************************************************* * Function Name : Enter_LowPowerMode. * Description : Power-off system clocks and power while entering suspend mode. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Enter_LowPowerMode(void) { #if 0 /* Set the device state to suspend */ bDeviceState = SUSPENDED; /* Clear EXTI Line18 pending bit */ EXTI_ClearITPendingBit(KEY_BUTTON_EXTI_LINE); /* Request to enter STOP mode with regulator in low power mode */ PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); #endif } /******************************************************************************* * Function Name : Leave_LowPowerMode. * Description : Restores system clocks and power while exiting suspend mode. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Leave_LowPowerMode(void) { DEVICE_INFO *pInfo = &Device_Info; /* Enable HSE */ RCC_HSEConfig(RCC_HSE_ON); /* Wait till HSE is ready */ HSEStartUpStatus = RCC_WaitForHSEStartUp(); /* Enable HSE */ RCC_HSEConfig(RCC_HSE_ON); /* Wait till HSE is ready */ while (RCC_GetFlagStatus(RCC_FLAG_HSERDY) == RESET) {} #ifdef STM32F10X_CL /* Enable PLL2 */ RCC_PLL2Cmd(ENABLE); /* Wait till PLL2 is ready */ while (RCC_GetFlagStatus(RCC_FLAG_PLL2RDY) == RESET) {} #endif /* STM32F10X_CL */ /* Enable PLL1 */ RCC_PLLCmd(ENABLE); /* Wait till PLL1 is ready */ while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) {} /* Select PLL as system clock source */ RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); /* Wait till PLL is used as system clock source */ while (RCC_GetSYSCLKSource() != 0x08) {} /* Set the device state to the correct state */ if (pInfo->Current_Configuration != 0) { /* Device configured */ bDeviceState = CONFIGURED; } else { bDeviceState = ATTACHED; } } /******************************************************************************* * Function Name : USB_Cable_Config. * Description : Software Connection/Disconnection of USB Cable. * Input : NewState: new state. * Output : None. * Return : None *******************************************************************************/ void USB_Cable_Config (FunctionalState NewState) { #ifdef USB_DISCONNECT_CONFIG if (NewState == DISABLE) { GPIO_ResetBits(USB_DISCONNECT, USB_DISCONNECT_PIN); } else { GPIO_SetBits(USB_DISCONNECT, USB_DISCONNECT_PIN); } #endif } /******************************************************************************* * Function Name : Get_SerialNum. * Description : Create the serial number string descriptor. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Get_SerialNum(void) { uint32_t Device_Serial0, Device_Serial1, Device_Serial2; Device_Serial0 = *(__IO uint32_t*)(0x1FFFF7E8); Device_Serial1 = *(__IO uint32_t*)(0x1FFFF7EC); Device_Serial2 = *(__IO uint32_t*)(0x1FFFF7F0); Device_Serial0 += Device_Serial2; if (Device_Serial0 != 0) { IntToUnicode (Device_Serial0, &Joystick_StringSerial[2] , 8); IntToUnicode (Device_Serial1, &Joystick_StringSerial[18], 4); } } /******************************************************************************* * Function Name : HexToChar. * Description : Convert Hex 32Bits value into char. * Input : None. * Output : None. * Return : None. *******************************************************************************/ static void IntToUnicode (uint32_t value , uint8_t *pbuf , uint8_t len) { uint8_t idx = 0; for( idx = 0 ; idx < len ; idx ++) { if( ((value >> 28)) < 0xA ) { pbuf[ 2* idx] = (value >> 28) + '0'; } else { pbuf[2* idx] = (value >> 28) + 'A' - 10; } value = value << 4; pbuf[ 2* idx + 1] = 0; } } #ifdef STM32F10X_CL /******************************************************************************* * Function Name : USB_OTG_BSP_uDelay. * Description : provide delay (usec). * Input : None. * Output : None. * Return : None. *******************************************************************************/ void USB_OTG_BSP_uDelay (const uint32_t usec) { RCC_ClocksTypeDef RCC_Clocks; /* Configure HCLK clock as SysTick clock source */ SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK); RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(usec * (RCC_Clocks.HCLK_Frequency / 1000000)); SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk ; while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)); } #endif void bsp_init_gpio(void) { GPIO_InitTypeDef GPIO_InitStructure; bsp_led_gpio_init(); bsp_key_gpio_init(); #ifdef USB_DISCONNECT_CONFIG /* GPIOA Configuration: */ GPIO_InitStructure.GPIO_Pin = USB_DISCONNECT_PIN; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(USB_DISCONNECT, &GPIO_InitStructure); #endif } void bsp_init_interrupt(void) { NVIC_InitTypeDef NVIC_InitStructure; /* Set the Vector Table base address at 0x08000000 */ //NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x00); /* 1 bit for pre-emption priority, 3 bits for subpriority */ /* 101111110100000000000000000 & */ /* 11000000000 */ /* SCB->AIRCR = 101111110100000011000000000 */ #if 1 #ifdef VECT_TAB_RAM /* Set the Vector Table base location at 0x20000000 */ NVIC_SetVectorTable(NVIC_VectTab_RAM, 0x0); #else /* VECT_TAB_FLASH */ /* Set the Vector Table base location at 0x08000000 */ NVIC_SetVectorTable(NVIC_VectTab_FLASH, 0x0); #endif #endif /* 2 bit for pre-emption priority, 2 bits for subpriority */ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1); #ifdef STM32F10X_CL /* Enable the USB Interrupts */ NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable the USB Wake-up interrupt */ // NVIC_InitStructure.NVIC_IRQChannel = OTG_FS_WKUP_IRQn; // NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; // NVIC_Init(&NVIC_InitStructure); #else /* Enable the USB interrupt */ NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* Enable the USB Wake-up interrupt */ // NVIC_InitStructure.NVIC_IRQChannel = USBWakeUp_IRQn; // NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; // NVIC_Init(&NVIC_InitStructure); #endif /* STM32F10X_CL */ /* Enable the RTC Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = RTC_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } // JTAG mode, the mode used to set the JTAG void JTAG_Set (u8 mode) { u32 temp; temp = mode; temp <<= 25; RCC->APB2ENR |= 1 <<0; // Open the secondary clock AFIO->MAPR &= 0XF8FFFFFF; // clear the MAPR's [26:24] AFIO->MAPR |= temp; // set the jtag mode } void delay_us (const uint32_t usec) { RCC_ClocksTypeDef RCC_Clocks; /* Configure HCLK clock as SysTick clock source */ SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK); RCC_GetClocksFreq(&RCC_Clocks); SysTick_Config(usec * (RCC_Clocks.HCLK_Frequency / 1000000)); SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk ; while (!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk)); } void delay_ms (const uint32_t usec) { delay_us(1000 * usec); } /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/hw_config.c
C
asf20
15,506
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : stm32f10x_conf.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Library configuration file. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F10x_CONF_H #define __STM32F10x_CONF_H /* Includes ------------------------------------------------------------------*/ /* Uncomment the line below to enable peripheral header file inclusion */ #include "stm32f10x_adc.h" #include "stm32f10x_bkp.h" /* #include "stm32f10x_can.h" */ /* #include "stm32f10x_crc.h" */ /* #include "stm32f10x_dac.h" */ /* #include "stm32f10x_dbgmcu.h" */ /* #include "stm32f10x_dma.h" */ #include "stm32f10x_exti.h" #include "stm32f10x_flash.h" /* #include "stm32f10x_fsmc.h" */ #include "stm32f10x_gpio.h" #include "stm32f10x_i2c.h" /* #include "stm32f10x_iwdg.h" */ #include "stm32f10x_pwr.h" #include "stm32f10x_rcc.h" #include "stm32f10x_rtc.h" /* #include "stm32f10x_sdio.h" */ /* #include "stm32f10x_spi.h" */ #include "stm32f10x_tim.h" #include "stm32f10x_usart.h" /* #include "stm32f10x_wwdg.h" */ #include "misc.h" /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Uncomment the line below to expanse the "assert_param" macro in the Standard Peripheral Library drivers code */ /* #define USE_FULL_ASSERT 1 */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /******************************************************************************* * Macro Name : assert_param * Description : The assert_param macro is used for function's parameters check. * Input : - expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * Return : None *******************************************************************************/ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #endif /* __STM32F10x_CONF_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/stm32f10x_conf.h
C
asf20
3,416
#ifndef TIMER_PRESENT #define TIMER_PRESENT typedef enum { timer1ServiceFunction, timer2ServiceFunction, timerServiceFunctionMAX } timer_register_function_type; typedef void (*timer_register_function)(void); typedef struct _timer_service_function_type { timer_register_function_type service_type; timer_register_function run; } timer_service_function_type; /* ------------------------------------------------------------------------------------------------- */ /* BSP Timer */ /* ------------------------------------------------------------------------------------------------- */ extern void register_timer_function(timer_register_function_type timer_fn_type, timer_register_function fn); extern void bsp_init_timer2(void/*isr_function timer4_isr*/); extern u16 bsp_get_timer2_cnt(void); extern void bsp_set_timer2_cnt( u16 cnt); #endif
zzqq5414-jk-rabbit
sw/all_demo/timer.h
C
asf20
894
/*----------------------------------------------------------------------- / Low level disk interface modlue include file R0.05 (C)ChaN, 2007 /-----------------------------------------------------------------------*/ #ifndef _DISKIO #define _READONLY 0 /* 1: Read-only mode */ #define _USE_IOCTL 1 #include "integer.h" /* Status of Disk Functions */ typedef BYTE DSTATUS; /* Results of Disk Functions */ typedef enum { RES_OK = 0, /* 0: Successful */ RES_ERROR, /* 1: R/W Error */ RES_WRPRT, /* 2: Write Protected */ RES_NOTRDY, /* 3: Not Ready */ RES_PARERR /* 4: Invalid Parameter */ } DRESULT; /*---------------------------------------*/ /* Prototypes for disk control functions */ DSTATUS disk_initialize (BYTE); DSTATUS disk_status (BYTE); DRESULT disk_read (BYTE, BYTE*, DWORD, BYTE); #if _READONLY == 0 DRESULT disk_write (BYTE, const BYTE*, DWORD, BYTE); #endif DRESULT disk_ioctl (BYTE, BYTE, void*); void disk_timerproc (void); /* Disk Status Bits (DSTATUS) */ #define STA_NOINIT 0x01 /* Drive not initialized */ #define STA_NODISK 0x02 /* No medium in the drive */ #define STA_PROTECT 0x04 /* Write protected */ /* Command code for disk_ioctrl() */ /* Generic command */ #define CTRL_SYNC 0 /* Mandatory for write functions */ #define GET_SECTOR_COUNT 1 /* Mandatory for only f_mkfs() */ #define GET_SECTOR_SIZE 2 #define GET_BLOCK_SIZE 3 /* Mandatory for only f_mkfs() */ #define CTRL_POWER 4 #define CTRL_LOCK 5 #define CTRL_EJECT 6 /* MMC/SDC command */ #define MMC_GET_TYPE 10 #define MMC_GET_CSD 11 #define MMC_GET_CID 12 #define MMC_GET_OCR 13 #define MMC_GET_SDSTAT 14 /* ATA/CF command */ #define ATA_GET_REV 20 #define ATA_GET_MODEL 21 #define ATA_GET_SN 22 #define _DISKIO #endif
zzqq5414-jk-rabbit
sw/all_demo/diskio.h
C
asf20
1,828
/*-------------------------------------------*/ /* Integer type definitions for FatFs module */ /*-------------------------------------------*/ #ifndef _INTEGER #if 0 #include <windows.h> #else /* These types must be 16-bit, 32-bit or larger integer */ typedef int INT; typedef unsigned int UINT; /* These types must be 8-bit integer */ typedef signed char CHAR; typedef unsigned char UCHAR; typedef unsigned char BYTE; /* These types must be 16-bit integer */ typedef short SHORT; typedef unsigned short USHORT; typedef unsigned short WORD; typedef unsigned short WCHAR; /* These types must be 32-bit integer */ typedef long LONG; typedef unsigned long ULONG; typedef unsigned long DWORD; /* Boolean type */ //typedef enum { FALSE = 0, TRUE } BOOL; #endif #define _INTEGER #endif
zzqq5414-jk-rabbit
sw/all_demo/integer.h
C
asf20
835
#ifndef SPI_PRESENT #define SPI_PRESENT /* ------------------------------------------------------------------------------------------------- */ /* BSP SPI */ /* ------------------------------------------------------------------------------------------------- */ #define SPI_SPEED_2 0 #define SPI_SPEED_4 1 #define SPI_SPEED_8 2 #define SPI_SPEED_16 3 #define SPI_SPEED_256 4 /* ------------------------------------------------------------------------------------------------- */ /* function SPI */ /* ------------------------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------------------------- */ /* extern SPI */ /* ------------------------------------------------------------------------------------------------- */ extern void bsp_set_spi1_speed (u8 speed); extern u8 bsp_readwritebyte_spi1 (u8 tx_data); #endif /* End of module include. */
zzqq5414-jk-rabbit
sw/all_demo/spi.h
C
asf20
1,101
#ifndef _MMC_SD_H_ #define _MMC_SD_H_ //#include <stm32f10x_lib.h> // Mini STM32 development board // SD card driver // Punctuality Atomic @ ALIENTEK // 2010/6/13 // SD data transmission whether to release the bus after the end of the macro definition #define NO_RELEASE 0 #define RELEASE 1 // SD Card Type Definition #define SD_TYPE_MMC 0 #define SD_TYPE_V1 1 #define SD_TYPE_V2 2 #define SD_TYPE_V2HC 4 // SD Card instruction sheet #define CMD0 0 // Card Reset #define CMD1 1 #define CMD9 9 // command 9, CSD data read #define CMD10 10 // Command 10, read CID data #define CMD12 12 // command 12, to stop data transmission #define CMD16 16 // Command 16, set SectorSize should return 0x00 #define CMD17 17 // Command 17, read sector #define CMD18 18 // Command 18, read Multi sector #define ACMD23 23 // Command 23, set the multi-sector erase writing in advance of a block N #define CMD24 24 // Command 24, write sector #define CMD25 25 // Command 25, write Multi sector #define ACMD41 41 // command to 41, should return 0x00 #define CMD55 55 // command to 55, should return 0x01 #define CMD58 58 // Command 58, read OCR information #define CMD59 59 // command to 59, enables / disables the CRC, should return 0x00 // Write data to respond to the word meaning #define MSD_DATA_OK 0x05 #define MSD_DATA_CRC_ERROR 0x0B #define MSD_DATA_WRITE_ERROR 0x0D #define MSD_DATA_OTHER_ERROR 0xFF // SD card labeled word response #define MSD_RESPONSE_NO_ERROR 0x00 #define MSD_IN_IDLE_STATE 0x01 #define MSD_ERASE_RESET 0x02 #define MSD_ILLEGAL_COMMAND 0x04 #define MSD_COM_CRC_ERROR 0x08 #define MSD_ERASE_SEQUENCE_ERROR 0x10 #define MSD_ADDRESS_ERROR 0x20 #define MSD_PARAMETER_ERROR 0x40 #define MSD_RESPONSE_FAILURE 0xFF // This part should be modified depending on the connection! // Mini STM32 uses SD cards as CS PA3 feet. // #define SD_CS PAout (3) // SD card selection pin /* Select MSD Card: ChipSelect pin low */ #define MSD_CS_ENABLE() GPIO_ResetBits(GPIOA, GPIO_Pin_3) /* Deselect MSD Card: ChipSelect pin high */ #define MSD_CS_DISABLE() GPIO_SetBits(GPIOA, GPIO_Pin_3) extern u8 SD_Type; // SD card type // Function state area void bsp_set_spi1_speed_mmcsd(u16 prescaler); u8 SD_WaitReady (void); // SD card ready to wait u8 SD_SendCommand (u8 cmd, u32 arg, u8 crc); // SD card to send a command u8 SD_SendCommand_NoDeassert (u8 cmd, u32 arg, u8 crc); u8 SD_Init (void); // SD Card initialization u8 SD_Idle_Sta (void); // set the SD card into suspend mode u8 SD_ReceiveData (u8 * data, u16 len, u8 release); // SD card reader data u8 SD_GetCID (u8 * cid_data); // reading SD card CID u8 SD_GetCSD (u8 * csd_data); // reading SD card CSD u32 SD_GetCapacity (void); // check SD card capacity // USB SD card reader operation function u8 MSD_WriteBuffer (u8 * pBuffer, u32 WriteAddr, u32 NumByteToWrite); u8 MSD_ReadBuffer (u8 * pBuffer, u32 ReadAddr, u32 NumByteToRead); u8 SD_ReadSingleBlock (u32 sector, u8 * buffer); // read a sector u8 SD_WriteSingleBlock (u32 sector, const u8 * buffer); // write a sector u8 SD_ReadMultiBlock (u32 sector, u8 * buffer, u8 count); // read multiple sector u8 SD_WriteMultiBlock (u32 sector, const u8 * data, u8 count); // write multiple sector u8 SD_Read_Bytes (unsigned long address, unsigned char * buf, unsigned int offset, unsigned int bytes); // read a byte u8 SD_WaitReady(void); extern void bsp_sd_gpio_init(void); #endif
zzqq5414-jk-rabbit
sw/all_demo/mmc_sd.h
C
asf20
3,497
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : stm32f10x_it.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : This file contains the headers of the interrupt handlers. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F10x_IT_H #define __STM32F10x_IT_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); void MemManage_Handler(void); void BusFault_Handler(void); void UsageFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); #ifndef STM32F10X_CL void USB_LP_CAN1_RX0_IRQHandler(void); #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL void OTG_FS_WKUP_IRQHandler(void); #else void USBWakeUp_IRQHandler(void); #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL void OTG_FS_IRQHandler(void); #endif /* STM32F10X_CL */ #endif /* __STM32F10x_IT_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/stm32f10x_it.h
C
asf20
2,201
/*-----------------------------------------------------------------------*/ /* Low level disk I/O module skeleton for FatFs (C)ChaN, 2007 */ /*-----------------------------------------------------------------------*/ /* by grqd_xp */ /* This is a stub disk I/O module that acts as front end of the existing */ /* disk I/O modules and attach it to FatFs module with common interface. */ /*-----------------------------------------------------------------------*/ #include <string.h> #include "stm32f10x.h" #include "hw_config.h" #include "diskio.h" #include "mmc_sd.h" /*-----------------------------------------------------------------------*/ /* Correspondence between physical drive number and physical drive. */ /* Note that Tiny-FatFs supports only single drive and always */ /* accesses drive number 0. */ #define SECTOR_SIZE 512U //u32 buff2[512/4]; /*-----------------------------------------------------------------------*/ /* Inidialize a Drive */ DSTATUS disk_initialize ( BYTE drv /* Physical drive nmuber (0..) */ ) { u8 state; if(drv) { return STA_NOINIT; // only supports the operation of the disk 0 } state = SD_Init(); if(state == STA_NODISK) { return STA_NODISK; } else if(state != 0) { return STA_NOINIT; // other error: initialization failed } else { return 0; // initialization succeeded } } /*-----------------------------------------------------------------------*/ /* Return Disk Status */ DSTATUS disk_status ( BYTE drv /* Physical drive nmuber (0..) */ ) { if(drv) { return STA_NOINIT; // only supports disk-0 operation } // Check whether the inserted SD card // if(!SD_DET()) // { // return STA_NODISK; // } return 0; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ DRESULT disk_read ( BYTE drv, /* Physical drive nmuber (0..) */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ BYTE count /* Number of sectors to read (1..255) */ ) { u8 res=0; if (drv || !count) { return RES_PARERR; // only supports single disk operation, count is not equal to 0, otherwise parameter error } // if(!SD_DET()) // { // return RES_NOTRDY; // does not detect SD card, NOT READY error reported // } if(count==1) // sector reads 1 { res = SD_ReadSingleBlock(sector, buff); } else // multiple sector read operations { res = SD_ReadMultiBlock(sector, buff, count); } /* do { if(SD_ReadSingleBlock(sector, buff)!=0) { res = 1; break; } buff+=512; }while(--count); */ // Process the return value, the return value of the SPI_SD_driver.c the return value turned into ff.c if(res == 0x00) { return RES_OK; } else { return RES_ERROR; } } /*-----------------------------------------------------------------------*/ /* Write Sector(s) */ #if _READONLY == 0 DRESULT disk_write ( BYTE drv, /* Physical drive nmuber (0..) */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ BYTE count /* Number of sectors to write (1..255) */ ) { u8 res; if (drv || !count) { return RES_PARERR; // only supports single disk operation, count is not equal to 0, otherwise parameter error } /* if(!SD_DET()) { return RES_NOTRDY; // does not detect SD card, NOT READY error reported } */ // Read and write operations if(count == 1) { res = SD_WriteSingleBlock(sector, buff); } else { res = SD_WriteMultiBlock(sector, buff, count); } // Return value to if(res == 0) { return RES_OK; } else { return RES_ERROR; } } #endif /* _READONLY */ /*-----------------------------------------------------------------------*/ /* Miscellaneous Functions */ DRESULT disk_ioctl ( BYTE drv, /* Physical drive nmuber (0..) */ BYTE ctrl, /* Control code */ void *buff /* Buffer to send/receive control data */ ) { DRESULT res; if (drv) { return RES_PARERR; // only supports single disk operation, or return parameter error } // FATFS only deal with the current version of CTRL_SYNC, GET_SECTOR_COUNT, GET_BLOCK_SIZ three commands switch(ctrl) { case CTRL_SYNC: MSD_CS_ENABLE(); if(SD_WaitReady()==0) { res = RES_OK; } else { res = RES_ERROR; } MSD_CS_DISABLE(); break; case GET_BLOCK_SIZE: *(WORD*)buff = 512; res = RES_OK; break; case GET_SECTOR_COUNT: *(DWORD*)buff = SD_GetCapacity(); res = RES_OK; break; default: res = RES_PARERR; break; } return res; } DWORD get_fattime(void){ return 0; }
zzqq5414-jk-rabbit
sw/all_demo/diskio.c
C
asf20
6,191
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : platform_config.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Evaluation board specific configuration file. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __PLATFORM_CONFIG_H #define __PLATFORM_CONFIG_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #endif /* __PLATFORM_CONFIG_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/platform_config.h
C
asf20
1,613
/*----------------------------------------------------------------------------/ / FatFs - FAT file system module R0.07c (C)ChaN, 2009 /-----------------------------------------------------------------------------/ / FatFs module is an open source software to implement FAT file system to / small embedded systems. This is a free software and is opened for education, / research and commercial use under license policy of following trems. / / Copyright (C) 2009, ChaN, all right reserved. / / * The FatFs module is a free software and there is NO WARRANTY. / * No restriction on use. You can use, modify and redistribute it for / personal, non-profit or commercial products UNDER YOUR RESPONSIBILITY. / * Redistributions of source code must retain the above copyright notice. / /-----------------------------------------------------------------------------/ / Feb 26,'06 R0.00 Prototype. / / Apr 29,'06 R0.01 First stable version. / / Jun 01,'06 R0.02 Added FAT12 support. / Removed unbuffered mode. / Fixed a problem on small (<32M) patition. / Jun 10,'06 R0.02a Added a configuration option (_FS_MINIMUM). / / Sep 22,'06 R0.03 Added f_rename(). / Changed option _FS_MINIMUM to _FS_MINIMIZE. / Dec 11,'06 R0.03a Improved cluster scan algolithm to write files fast. / Fixed f_mkdir() creates incorrect directory on FAT32. / / Feb 04,'07 R0.04 Supported multiple drive system. / Changed some interfaces for multiple drive system. / Changed f_mountdrv() to f_mount(). / Added f_mkfs(). / Apr 01,'07 R0.04a Supported multiple partitions on a plysical drive. / Added a capability of extending file size to f_lseek(). / Added minimization level 3. / Fixed an endian sensitive code in f_mkfs(). / May 05,'07 R0.04b Added a configuration option _USE_NTFLAG. / Added FSInfo support. / Fixed DBCS name can result FR_INVALID_NAME. / Fixed short seek (<= csize) collapses the file object. / / Aug 25,'07 R0.05 Changed arguments of f_read(), f_write() and f_mkfs(). / Fixed f_mkfs() on FAT32 creates incorrect FSInfo. / Fixed f_mkdir() on FAT32 creates incorrect directory. / Feb 03,'08 R0.05a Added f_truncate() and f_utime(). / Fixed off by one error at FAT sub-type determination. / Fixed btr in f_read() can be mistruncated. / Fixed cached sector is not flushed when create and close / without write. / / Apr 01,'08 R0.06 Added fputc(), fputs(), fprintf() and fgets(). / Improved performance of f_lseek() on moving to the same / or following cluster. / / Apr 01,'09 R0.07 Merged Tiny-FatFs as a buffer configuration option. / Added long file name support. / Added multiple code page support. / Added re-entrancy for multitask operation. / Added auto cluster size selection to f_mkfs(). / Added rewind option to f_readdir(). / Changed result code of critical errors. / Renamed string functions to avoid name collision. / Apr 14,'09 R0.07a Separated out OS dependent code on reentrant cfg. / Added multiple sector size support. / Jun 21,'09 R0.07c Fixed f_unlink() may return FR_OK on error. / Fixed wrong cache control in f_lseek(). / Added relative path feature. / Added f_chdir() and f_chdrive(). / Added proper case conversion to extended char. /---------------------------------------------------------------------------*/ #include "ff.h" /* FatFs configurations and declarations */ #include "diskio.h" /* Declarations of low level disk I/O functions */ #include "hw_config.h" /* FatFs configurations and declarations */ /*-------------------------------------------------------------------------- Module Private Definitions ---------------------------------------------------------------------------*/ #if _FS_REENTRANT #if _USE_LFN == 1 #error Static LFN work area must not be used in re-entrant configuration. #endif #define ENTER_FF(fs) { if (!lock_fs(fs)) return FR_TIMEOUT; } #define LEAVE_FF(fs, res) { unlock_fs(fs, res); return res; } #else #define ENTER_FF(fs) #define LEAVE_FF(fs, res) return res #endif #define ABORT(fs, res) { fp->flag |= FA__ERROR; LEAVE_FF(fs, res); } #ifndef NULL #define NULL 0 #endif /* Name status flags */ #define NS_LOSS 0x01 /* Lossy conversion */ #define NS_LFN 0x02 /* Force to create LFN entry */ #define NS_LAST 0x04 /* Last segment */ #define NS_BODY 0x08 /* Lower case flag (body) */ #define NS_EXT 0x10 /* Lower case flag (ext) */ #define NS_DOT 0x20 /* Dot entry */ /*-------------------------------------------------------------------------- Private Work Area ---------------------------------------------------------------------------*/ static FATFS *FatFs[_DRIVES]; /* Pointer to the file system objects (logical drives) */ static WORD Fsid; /* File system mount ID */ #if _FS_RPATH static BYTE Drive; /* Current drive */ #endif #if _USE_LFN == 1 /* LFN with static LFN working buffer */ static WORD LfnBuf[_MAX_LFN + 1]; #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR *lp = LfnBuf #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp #elif _USE_LFN > 1 /* LFN with dynamic LFN working buffer */ #define NAMEBUF(sp,lp) BYTE sp[12]; WCHAR lbuf[_MAX_LFN + 1], *lp = lbuf #define INITBUF(dj,sp,lp) dj.fn = sp; dj.lfn = lp #else /* No LFN */ #define NAMEBUF(sp,lp) BYTE sp[12] #define INITBUF(dj,sp,lp) dj.fn = sp #endif /*-------------------------------------------------------------------------- Private Functions ---------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* String functions */ /*-----------------------------------------------------------------------*/ /* Copy memory to memory */ static void mem_cpy (void* dst, const void* src, int cnt) { char *d = (char*)dst; const char *s = (const char *)src; while (cnt--) *d++ = *s++; } /* Fill memory */ static void mem_set (void* dst, int val, int cnt) { char *d = (char*)dst; while (cnt--) *d++ = (char)val; } /* Compare memory to memory */ static int mem_cmp (const void* dst, const void* src, int cnt) { const char *d = (const char *)dst, *s = (const char *)src; int r = 0; while (cnt-- && (r = *d++ - *s++) == 0) ; return r; } /* Check if chr is contained in the string */ static int chk_chr (const char* str, int chr) { while (*str && *str != chr) str++; return *str; } /*-----------------------------------------------------------------------*/ /* Request/Release grant to access the volume */ /*-----------------------------------------------------------------------*/ #if _FS_REENTRANT static BOOL lock_fs ( FATFS *fs /* File system object */ ) { return ff_req_grant(fs->sobj); } static void unlock_fs ( FATFS *fs, /* File system object */ FRESULT res /* Result code to be returned */ ) { if (res != FR_NOT_ENABLED && res != FR_INVALID_DRIVE && res != FR_INVALID_OBJECT && res != FR_TIMEOUT) { ff_rel_grant(fs->sobj); } } #endif /*-----------------------------------------------------------------------*/ /* Change window offset */ /*-----------------------------------------------------------------------*/ static FRESULT move_window ( FATFS *fs, /* File system object */ DWORD sector /* Sector number to make apperance in the fs->win[] */ ) /* Move to zero only writes back dirty window */ { DWORD wsect; wsect = fs->winsect; if (wsect != sector) { /* Changed current window */ #if !_FS_READONLY if (fs->wflag) { /* Write back dirty window if needed */ if (disk_write(fs->drive, fs->win, wsect, 1) != RES_OK) return FR_DISK_ERR; fs->wflag = 0; if (wsect < (fs->fatbase + fs->sects_fat)) { /* In FAT area */ BYTE nf; for (nf = fs->n_fats; nf > 1; nf--) { /* Refrect the change to all FAT copies */ wsect += fs->sects_fat; disk_write(fs->drive, fs->win, wsect, 1); } } } #endif if (sector) { if (disk_read(fs->drive, fs->win, sector, 1) != RES_OK) return FR_DISK_ERR; fs->winsect = sector; } } return FR_OK; } /*-----------------------------------------------------------------------*/ /* Clean-up cached data */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY static FRESULT sync ( /* FR_OK: successful, FR_DISK_ERR: failed */ FATFS *fs /* File system object */ ) { FRESULT res; res = move_window(fs, 0); if (res == FR_OK) { /* Update FSInfo sector if needed */ if (fs->fs_type == FS_FAT32 && fs->fsi_flag) { fs->winsect = 0; mem_set(fs->win, 0, 512); ST_WORD(fs->win+BS_55AA, 0xAA55); ST_DWORD(fs->win+FSI_LeadSig, 0x41615252); ST_DWORD(fs->win+FSI_StrucSig, 0x61417272); ST_DWORD(fs->win+FSI_Free_Count, fs->free_clust); ST_DWORD(fs->win+FSI_Nxt_Free, fs->last_clust); disk_write(fs->drive, fs->win, fs->fsi_sector, 1); fs->fsi_flag = 0; } /* Make sure that no pending write process in the physical drive */ if (disk_ioctl(fs->drive, CTRL_SYNC, (void*)NULL) != RES_OK) res = FR_DISK_ERR; } return res; } #endif /*-----------------------------------------------------------------------*/ /* FAT access - Read value of a FAT entry */ /*-----------------------------------------------------------------------*/ static DWORD get_fat ( /* 0xFFFFFFFF:Disk error, 1:Interal error, Else:Cluster status */ FATFS *fs, /* File system object */ DWORD clst /* Cluster# to get the link information */ ) { UINT wc, bc; DWORD fsect; if (clst < 2 || clst >= fs->max_clust) /* Range check */ return 1; fsect = fs->fatbase; switch (fs->fs_type) { case FS_FAT12 : bc = clst; bc += bc / 2; if (move_window(fs, fsect + (bc / SS(fs)))) break; wc = fs->win[bc & (SS(fs) - 1)]; bc++; if (move_window(fs, fsect + (bc / SS(fs)))) break; wc |= (WORD)fs->win[bc & (SS(fs) - 1)] << 8; return (clst & 1) ? (wc >> 4) : (wc & 0xFFF); case FS_FAT16 : if (move_window(fs, fsect + (clst / (SS(fs) / 2)))) break; return LD_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)]); case FS_FAT32 : if (move_window(fs, fsect + (clst / (SS(fs) / 4)))) break; return LD_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)]) & 0x0FFFFFFF; } return 0xFFFFFFFF; /* An error occured at the disk I/O layer */ } /*-----------------------------------------------------------------------*/ /* FAT access - Change value of a FAT entry */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY static FRESULT put_fat ( FATFS *fs, /* File system object */ DWORD clst, /* Cluster# to be changed in range of 2 to fs->max_clust - 1 */ DWORD val /* New value to mark the cluster */ ) { UINT bc; BYTE *p; DWORD fsect; FRESULT res; if (clst < 2 || clst >= fs->max_clust) { /* Range check */ res = FR_INT_ERR; } else { fsect = fs->fatbase; switch (fs->fs_type) { case FS_FAT12 : bc = clst; bc += bc / 2; res = move_window(fs, fsect + (bc / SS(fs))); if (res != FR_OK) break; p = &fs->win[bc & (SS(fs) - 1)]; *p = (clst & 1) ? ((*p & 0x0F) | ((BYTE)val << 4)) : (BYTE)val; bc++; fs->wflag = 1; res = move_window(fs, fsect + (bc / SS(fs))); if (res != FR_OK) break; p = &fs->win[bc & (SS(fs) - 1)]; *p = (clst & 1) ? (BYTE)(val >> 4) : ((*p & 0xF0) | ((BYTE)(val >> 8) & 0x0F)); break; case FS_FAT16 : res = move_window(fs, fsect + (clst / (SS(fs) / 2))); if (res != FR_OK) break; ST_WORD(&fs->win[((WORD)clst * 2) & (SS(fs) - 1)], (WORD)val); break; case FS_FAT32 : res = move_window(fs, fsect + (clst / (SS(fs) / 4))); if (res != FR_OK) break; ST_DWORD(&fs->win[((WORD)clst * 4) & (SS(fs) - 1)], val); break; default : res = FR_INT_ERR; } fs->wflag = 1; } return res; } #endif /* !_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* FAT handling - Remove a cluster chain */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY static FRESULT remove_chain ( FATFS *fs, /* File system object */ DWORD clst /* Cluster# to remove a chain from */ ) { FRESULT res; DWORD nxt; if (clst < 2 || clst >= fs->max_clust) { /* Check the range of cluster# */ res = FR_INT_ERR; } else { res = FR_OK; while (clst < fs->max_clust) { /* Not a last link? */ nxt = get_fat(fs, clst); /* Get cluster status */ if (nxt == 0) break; /* Empty cluster? */ if (nxt == 1) { res = FR_INT_ERR; break; } /* Internal error? */ if (nxt == 0xFFFFFFFF) { res = FR_DISK_ERR; break; } /* Disk error? */ res = put_fat(fs, clst, 0); /* Mark the cluster "empty" */ if (res != FR_OK) break; if (fs->free_clust != 0xFFFFFFFF) { /* Update FSInfo */ fs->free_clust++; fs->fsi_flag = 1; } clst = nxt; /* Next cluster */ } } return res; } #endif /*-----------------------------------------------------------------------*/ /* FAT handling - Stretch or Create a cluster chain */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY static DWORD create_chain ( /* 0:No free cluster, 1:Internal error, 0xFFFFFFFF:Disk error, >=2:New cluster# */ FATFS *fs, /* File system object */ DWORD clst /* Cluster# to stretch. 0 means create a new chain. */ ) { DWORD cs, ncl, scl, mcl; mcl = fs->max_clust; if (clst == 0) { /* Create new chain */ scl = fs->last_clust; /* Get suggested start point */ if (scl == 0 || scl >= mcl) scl = 1; } else { /* Stretch existing chain */ cs = get_fat(fs, clst); /* Check the cluster status */ if (cs < 2) return 1; /* It is an invalid cluster */ if (cs < mcl) return cs; /* It is already followed by next cluster */ scl = clst; } ncl = scl; /* Start cluster */ for (;;) { ncl++; /* Next cluster */ if (ncl >= mcl) { /* Wrap around */ ncl = 2; if (ncl > scl) return 0; /* No free custer */ } cs = get_fat(fs, ncl); /* Get the cluster status */ if (cs == 0) break; /* Found a free cluster */ if (cs == 0xFFFFFFFF || cs == 1)/* An error occured */ return cs; if (ncl == scl) return 0; /* No free custer */ } if (put_fat(fs, ncl, 0x0FFFFFFF)) /* Mark the new cluster "in use" */ return 0xFFFFFFFF; if (clst != 0) { /* Link it to the previous one if needed */ if (put_fat(fs, clst, ncl)) return 0xFFFFFFFF; } fs->last_clust = ncl; /* Update FSINFO */ if (fs->free_clust != 0xFFFFFFFF) { fs->free_clust--; fs->fsi_flag = 1; } return ncl; /* Return new cluster number */ } #endif /* !_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* Get sector# from cluster# */ /*-----------------------------------------------------------------------*/ static DWORD clust2sect ( /* !=0: Sector number, 0: Failed - invalid cluster# */ FATFS *fs, /* File system object */ DWORD clst /* Cluster# to be converted */ ) { clst -= 2; if (clst >= (fs->max_clust - 2)) return 0; /* Invalid cluster# */ return clst * fs->csize + fs->database; } /*-----------------------------------------------------------------------*/ /* Directory handling - Seek directory index */ /*-----------------------------------------------------------------------*/ static FRESULT dir_seek ( DIR *dj, /* Pointer to directory object */ WORD idx /* Directory index number */ ) { DWORD clst; WORD ic; dj->index = idx; clst = dj->sclust; if (clst == 1 || clst >= dj->fs->max_clust) /* Check start cluster range */ return FR_INT_ERR; if (!clst && dj->fs->fs_type == FS_FAT32) /* Replace cluster# 0 with root cluster# if in FAT32 */ clst = dj->fs->dirbase; if (clst == 0) { /* Static table */ dj->clust = clst; if (idx >= dj->fs->n_rootdir) /* Index is out of range */ return FR_INT_ERR; dj->sect = dj->fs->dirbase + idx / (SS(dj->fs) / 32); /* Sector# */ } else { /* Dynamic table */ ic = SS(dj->fs) / 32 * dj->fs->csize; /* Entries per cluster */ while (idx >= ic) { /* Follow cluster chain */ clst = get_fat(dj->fs, clst); /* Get next cluster */ if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Disk error */ if (clst < 2 || clst >= dj->fs->max_clust) /* Reached to end of table or int error */ return FR_INT_ERR; idx -= ic; } dj->clust = clst; dj->sect = clust2sect(dj->fs, clst) + idx / (SS(dj->fs) / 32); /* Sector# */ } dj->dir = dj->fs->win + (idx % (SS(dj->fs) / 32)) * 32; /* Ptr to the entry in the sector */ return FR_OK; /* Seek succeeded */ } /*-----------------------------------------------------------------------*/ /* Directory handling - Move directory index next */ /*-----------------------------------------------------------------------*/ static FRESULT dir_next ( /* FR_OK:Succeeded, FR_NO_FILE:End of table, FR_DENIED:EOT and could not streach */ DIR *dj, /* Pointer to directory object */ bool streach /* FALSE: Do not streach table, TRUE: Streach table if needed */ ) { DWORD clst; WORD i; i = dj->index + 1; if (!i || !dj->sect) /* Report EOT when index has reached 65535 */ return FR_NO_FILE; if (!(i % (SS(dj->fs) / 32))) { /* Sector changed? */ dj->sect++; /* Next sector */ if (dj->clust == 0) { /* Static table */ if (i >= dj->fs->n_rootdir) /* Report EOT when end of table */ return FR_NO_FILE; } else { /* Dynamic table */ if (((i / (SS(dj->fs) / 32)) & (dj->fs->csize - 1)) == 0) { /* Cluster changed? */ clst = get_fat(dj->fs, dj->clust); /* Get next cluster */ if (clst <= 1) return FR_INT_ERR; if (clst == 0xFFFFFFFF) return FR_DISK_ERR; if (clst >= dj->fs->max_clust) { /* When it reached end of dynamic table */ #if !_FS_READONLY BYTE c; if (!streach) return FR_NO_FILE; /* When do not streach, report EOT */ clst = create_chain(dj->fs, dj->clust); /* Streach cluster chain */ if (clst == 0) return FR_DENIED; /* No free cluster */ if (clst == 1) return FR_INT_ERR; if (clst == 0xFFFFFFFF) return FR_DISK_ERR; /* Clean-up streached table */ if (move_window(dj->fs, 0)) return FR_DISK_ERR; /* Flush active window */ mem_set(dj->fs->win, 0, SS(dj->fs)); /* Clear window buffer */ dj->fs->winsect = clust2sect(dj->fs, clst); /* Cluster start sector */ for (c = 0; c < dj->fs->csize; c++) { /* Fill the new cluster with 0 */ dj->fs->wflag = 1; if (move_window(dj->fs, 0)) return FR_DISK_ERR; dj->fs->winsect++; } dj->fs->winsect -= c; /* Rewind window address */ #else return FR_NO_FILE; /* Report EOT */ #endif } dj->clust = clst; /* Initialize data for new cluster */ dj->sect = clust2sect(dj->fs, clst); } } } dj->index = i; dj->dir = dj->fs->win + (i % (SS(dj->fs) / 32)) * 32; return FR_OK; } /*-----------------------------------------------------------------------*/ /* LFN handling - Test/Pick/Fit an LFN segment from/to directory entry */ /*-----------------------------------------------------------------------*/ #if _USE_LFN static const BYTE LfnOfs[] = {1,3,5,7,9,14,16,18,20,22,24,28,30}; /* Offset of LFN chars in the directory entry */ static bool cmp_lfn ( /* TRUE:Matched, FALSE:Not matched */ WCHAR *lfnbuf, /* Pointer to the LFN to be compared */ BYTE *dir /* Pointer to the directory entry containing a part of LFN */ ) { int i, s; WCHAR wc; i = ((dir[LDIR_Ord] & 0xBF) - 1) * 13; /* Get offset in the LFN buffer */ s = 0; do { wc = ff_wtoupper(LD_WORD(dir+LfnOfs[s])); /* Get an LFN character */ if (i >= _MAX_LFN || wc != ff_wtoupper(lfnbuf[i++])) /* Compare it with the reference character */ return FALSE; } while (++s < 13 && wc); /* Repeat until all chars in the entry or a NUL char is processed */ return TRUE; /* The LFN entry matched */ } static bool pick_lfn ( /* TRUE:Succeeded, FALSE:Buffer overflow */ WCHAR *lfnbuf, /* Pointer to the Unicode-LFN buffer */ BYTE *dir /* Pointer to the directory entry */ ) { int i, s; WCHAR wc; i = ((dir[LDIR_Ord] & 0x3F) - 1) * 13; /* Offset in the LFN buffer */ s = 0; do { if (i >= _MAX_LFN) return FALSE; /* Buffer overflow? */ wc = LD_WORD(dir+LfnOfs[s]); /* Get an LFN char */ if (!wc) break; /* End of LFN? */ lfnbuf[i++] = wc; /* Store it */ } while (++s < 13); /* Repeat until last char is copied */ if (dir[LDIR_Ord] & 0x40) { /* Put terminator if it is the last LFN part */ if (i >= _MAX_LFN) return FALSE; /* Buffer overflow? */ lfnbuf[i] = 0; } return TRUE; } #if !_FS_READONLY static void fit_lfn ( const WCHAR *lfnbuf, /* Pointer to the LFN buffer */ BYTE *dir, /* Pointer to the directory entry */ BYTE ord, /* LFN order (1-20) */ BYTE sum /* SFN sum */ ) { int i, s; WCHAR wc; dir[LDIR_Chksum] = sum; /* Set check sum */ dir[LDIR_Attr] = AM_LFN; /* Set attribute. LFN entry */ dir[LDIR_Type] = 0; ST_WORD(dir+LDIR_FstClusLO, 0); i = (ord - 1) * 13; /* Get offset in the LFN buffer */ s = wc = 0; do { if (wc != 0xFFFF) wc = lfnbuf[i++]; /* Get an effective char */ ST_WORD(dir+LfnOfs[s], wc); /* Put it */ if (!wc) wc = 0xFFFF; /* Padding chars following last char */ } while (++s < 13); if (wc == 0xFFFF || !lfnbuf[i]) ord |= 0x40; /* Bottom LFN part is the start of LFN sequence */ dir[LDIR_Ord] = ord; /* Set the LFN order */ } #endif #endif /*-----------------------------------------------------------------------*/ /* Create numbered name */ /*-----------------------------------------------------------------------*/ #if _USE_LFN void gen_numname ( BYTE *dst, /* Pointer to genartated SFN */ const BYTE *src, /* Pointer to source SFN to be modified */ const WCHAR *lfn, /* Pointer to LFN */ WORD num /* Sequense number */ ) { char ns[8]; int i, j; mem_cpy(dst, src, 11); if (num > 5) { /* On many collisions, generate a hash number instead of sequencial number */ do num = (num >> 1) + (num << 15) + (WORD)*lfn++; while (*lfn); } /* itoa */ i = 7; do { ns[i--] = (num % 10) + '0'; num /= 10; } while (num); ns[i] = '~'; /* Append the number */ for (j = 0; j < i && dst[j] != ' '; j++) { if (IsDBCS1(dst[j])) { if (j == i - 1) break; j++; } } do { dst[j++] = (i < 8) ? ns[i++] : ' '; } while (j < 8); } #endif /*-----------------------------------------------------------------------*/ /* Calculate sum of an SFN */ /*-----------------------------------------------------------------------*/ #if _USE_LFN static BYTE sum_sfn ( const BYTE *dir /* Ptr to directory entry */ ) { BYTE sum = 0; int n = 11; do sum = (sum >> 1) + (sum << 7) + *dir++; while (--n); return sum; } #endif /*-----------------------------------------------------------------------*/ /* Directory handling - Find an object in the directory */ /*-----------------------------------------------------------------------*/ static FRESULT dir_find ( DIR *dj /* Pointer to the directory object linked to the file name */ ) { FRESULT res; BYTE c, *dir; #if _USE_LFN BYTE a, lfen, ord, sum; #endif res = dir_seek(dj, 0); /* Rewind directory object */ if (res != FR_OK) return res; #if _USE_LFN ord = sum = 0xFF; lfen = *(dj->fn+11) & NS_LOSS; #endif do { res = move_window(dj->fs, dj->sect); if (res != FR_OK) break; dir = dj->dir; /* Ptr to the directory entry of current index */ c = dir[DIR_Name]; if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ #if _USE_LFN /* LFN configuration */ a = dir[DIR_Attr] & AM_MASK; if (c == 0xE5 || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */ ord = 0xFF; } else { if (a == AM_LFN) { /* An LFN entry is found */ if (dj->lfn) { if (c & 0x40) { /* Is it start of LFN sequence? */ sum = dir[LDIR_Chksum]; c &= 0xBF; ord = c; /* LFN start order */ dj->lfn_idx = dj->index; } /* Check LFN validity. Compare LFN if it is out of 8.3 format */ ord = (c == ord && sum == dir[LDIR_Chksum] && (!lfen || cmp_lfn(dj->lfn, dir))) ? ord - 1 : 0xFF; } } else { /* An SFN entry is found */ if (ord || sum != sum_sfn(dir)) /* Did not LFN match? */ dj->lfn_idx = 0xFFFF; if (lfen) { /* Match LFN if it is out of 8.3 format */ if (ord == 0) break; } else { /* Match SFN if LFN is in 8.3 format */ if (!mem_cmp(dir, dj->fn, 11)) break; } ord = 0xFF; } } #else /* Non LFN configuration */ if (!(dir[DIR_Attr] & AM_VOL) && !mem_cmp(dir, dj->fn, 11)) /* Is it a valid entry? */ break; #endif res = dir_next(dj, FALSE); /* Next entry */ } while (res == FR_OK); return res; } /*-----------------------------------------------------------------------*/ /* Read an object from the directory */ /*-----------------------------------------------------------------------*/ #if _FS_MINIMIZE <= 1 static FRESULT dir_read ( DIR *dj /* Pointer to the directory object that pointing the entry to be read */ ) { FRESULT res; BYTE c, *dir; #if _USE_LFN BYTE a, ord = 0xFF, sum = 0xFF; #endif res = FR_NO_FILE; while (dj->sect) { res = move_window(dj->fs, dj->sect); if (res != FR_OK) break; dir = dj->dir; /* Ptr to the directory entry of current index */ c = dir[DIR_Name]; if (c == 0) { res = FR_NO_FILE; break; } /* Reached to end of table */ #if _USE_LFN /* LFN configuration */ a = dir[DIR_Attr] & AM_MASK; if (c == 0xE5 || (!_FS_RPATH && c == '.') || ((a & AM_VOL) && a != AM_LFN)) { /* An entry without valid data */ ord = 0xFF; } else { if (a == AM_LFN) { /* An LFN entry is found */ if (c & 0x40) { /* Is it start of LFN sequence? */ sum = dir[LDIR_Chksum]; c &= 0xBF; ord = c; dj->lfn_idx = dj->index; } /* Check LFN validity and capture it */ ord = (c == ord && sum == dir[LDIR_Chksum] && pick_lfn(dj->lfn, dir)) ? ord - 1 : 0xFF; } else { /* An SFN entry is found */ if (ord || sum != sum_sfn(dir)) /* Is there a valid LFN entry? */ dj->lfn_idx = 0xFFFF; /* No LFN. */ break; } } #else /* Non LFN configuration */ if (c != 0xE5 && (_FS_RPATH || c != '.') && !(dir[DIR_Attr] & AM_VOL)) /* Is it a valid entry? */ break; #endif res = dir_next(dj, FALSE); /* Next entry */ if (res != FR_OK) break; } if (res != FR_OK) dj->sect = 0; return res; } #endif /*-----------------------------------------------------------------------*/ /* Register an object to the directory */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY static FRESULT dir_register ( /* FR_OK:Successful, FR_DENIED:No free entry or too many SFN collision, FR_DISK_ERR:Disk error */ DIR *dj /* Target directory with object name to be created */ ) { FRESULT res; BYTE c, *dir; #if _USE_LFN /* LFN configuration */ WORD n, ne, is; BYTE sn[12], *fn, sum; WCHAR *lfn; fn = dj->fn; lfn = dj->lfn; mem_cpy(sn, fn, 12); if (_FS_RPATH && (sn[11] & NS_DOT)) return FR_INVALID_NAME; /* Cannot create dot entry */ if (sn[11] & NS_LOSS) { /* When LFN is out of 8.3 format, generate a numbered name */ fn[11] = 0; dj->lfn = NULL; /* Find only SFN */ for (n = 1; n < 100; n++) { gen_numname(fn, sn, lfn, n); /* Generate a numbered name */ res = dir_find(dj); /* Check if the name collides with existing SFN */ if (res != FR_OK) break; } if (n == 100) return FR_DENIED; /* Abort if too many collisions */ if (res != FR_NO_FILE) return res; /* Abort if the result is other than 'not collided' */ fn[11] = sn[11]; dj->lfn = lfn; } if (sn[11] & NS_LFN) { /* When LFN is to be created, reserve reserve an SFN + LFN entries. */ for (ne = 0; lfn[ne]; ne++) ; ne = (ne + 25) / 13; } else { /* Otherwise reserve only an SFN entry. */ ne = 1; } /* Reserve contiguous entries */ res = dir_seek(dj, 0); if (res != FR_OK) return res; n = is = 0; do { res = move_window(dj->fs, dj->sect); if (res != FR_OK) break; c = *dj->dir; /* Check the entry status */ if (c == 0xE5 || c == 0) { /* Is it a blank entry? */ if (n == 0) is = dj->index; /* First index of the contigulus entry */ if (++n == ne) break; /* A contiguous entry that requiered count is found */ } else { n = 0; /* Not a blank entry. Restart to search */ } res = dir_next(dj, TRUE); /* Next entry with table streach */ } while (res == FR_OK); if (res == FR_OK && ne > 1) { /* Initialize LFN entry if needed */ res = dir_seek(dj, is); if (res == FR_OK) { sum = sum_sfn(dj->fn); /* Sum of the SFN tied to the LFN */ ne--; do { /* Store LFN entries in bottom first */ res = move_window(dj->fs, dj->sect); if (res != FR_OK) break; fit_lfn(dj->lfn, dj->dir, (BYTE)ne, sum); dj->fs->wflag = 1; res = dir_next(dj, FALSE); /* Next entry */ } while (res == FR_OK && --ne); } } #else /* Non LFN configuration */ res = dir_seek(dj, 0); if (res == FR_OK) { do { /* Find a blank entry for the SFN */ res = move_window(dj->fs, dj->sect); if (res != FR_OK) break; c = *dj->dir; if (c == 0xE5 || c == 0) break; /* Is it a blank entry? */ res = dir_next(dj, TRUE); /* Next entry with table streach */ } while (res == FR_OK); } #endif if (res == FR_OK) { /* Initialize the SFN entry */ res = move_window(dj->fs, dj->sect); if (res == FR_OK) { dir = dj->dir; mem_set(dir, 0, 32); /* Clean the entry */ mem_cpy(dir, dj->fn, 11); /* Put SFN */ dir[DIR_NTres] = *(dj->fn+11) & 0x18; /* Put NT flag */ dj->fs->wflag = 1; } } return res; } #endif /* !_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* Remove an object from the directory */ /*-----------------------------------------------------------------------*/ #if !_FS_READONLY && !_FS_MINIMIZE static FRESULT dir_remove ( /* FR_OK: Successful, FR_DISK_ERR: A disk error */ DIR *dj /* Directory object pointing the entry to be removed */ ) { FRESULT res; #if _USE_LFN /* LFN configuration */ WORD i; i = dj->index; /* SFN index */ res = dir_seek(dj, (WORD)((dj->lfn_idx == 0xFFFF) ? i : dj->lfn_idx)); /* Goto the SFN or top of the LFN entries */ if (res == FR_OK) { do { res = move_window(dj->fs, dj->sect); if (res != FR_OK) break; *dj->dir = 0xE5; /* Mark the entry "deleted" */ dj->fs->wflag = 1; if (dj->index >= i) break; /* When reached SFN, all entries of the object has been deleted. */ res = dir_next(dj, FALSE); /* Next entry */ } while (res == FR_OK); if (res == FR_NO_FILE) res = FR_INT_ERR; } #else /* Non LFN configuration */ res = dir_seek(dj, dj->index); if (res == FR_OK) { res = move_window(dj->fs, dj->sect); if (res == FR_OK) { *dj->dir = 0xE5; /* Mark the entry "deleted" */ dj->fs->wflag = 1; } } #endif return res; } #endif /* !_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* Pick a segment and create the object name in directory form */ /*-----------------------------------------------------------------------*/ static FRESULT create_name ( DIR *dj, /* Pointer to the directory object */ const XCHAR **path /* Pointer to pointer to the segment in the path string */ ) { #ifdef _EXCVT static const BYTE cvt[] = _EXCVT; #endif #if _USE_LFN /* LFN configuration */ BYTE b, cf; WCHAR w, *lfn; int i, ni, si, di; const XCHAR *p; /* Create LFN in Unicode */ si = di = 0; p = *path; lfn = dj->lfn; for (;;) { w = p[si++]; /* Get a character */ if (w < L' ' || w == L'/' || w == L'\\') break; /* Break on end of segment */ if (di >= _MAX_LFN) /* Reject too long name */ return FR_INVALID_NAME; #if !_LFN_UNICODE w &= 0xFF; if (IsDBCS1(w)) { /* If it is a DBC 1st byte */ BYTE c = p[si++]; /* Get 2nd byte */ if (!IsDBCS2(c)) /* Reject invalid code for DBC */ return FR_INVALID_NAME; w = (w << 8) + c; } w = ff_convert(w, 1); /* Convert OEM to Unicode */ if (!w) return FR_INVALID_NAME; /* Reject invalid code */ #endif if (w < 0x80 && chk_chr("\"*:<>\?|\x7F", w)) /* Reject unallowable chars for LFN */ return FR_INVALID_NAME; lfn[di++] = w; /* Store the Unicode char */ } *path = &p[si]; /* Rerurn pointer to the next segment */ cf = (w < L' ') ? NS_LAST : 0; /* Set last segment flag if end of path */ #if _FS_RPATH if ((di == 1 && lfn[di - 1] == L'.') || /* Is this a dot entry? */ (di == 2 && lfn[di - 1] == L'.' && lfn[di - 2] == L'.')) { lfn[di] = 0; for (i = 0; i < 11; i++) dj->fn[i] = (i < di) ? '.' : ' '; dj->fn[i] = cf | NS_DOT; /* This is a dot entry */ return FR_OK; } #endif while (di) { /* Strip trailing spaces and dots */ w = lfn[di - 1]; if (w != L' ' && w != L'.') break; di--; } if (!di) return FR_INVALID_NAME; /* Reject null string */ lfn[di] = 0; /* LFN is created */ /* Create SFN in directory form */ mem_set(dj->fn, ' ', 11); for (si = 0; lfn[si] == L' ' || lfn[si] == L'.'; si++) ; /* Strip leading spaces and dots */ if (si) cf |= NS_LOSS | NS_LFN; while (di && lfn[di - 1] != '.') di--; /* Find extension (di<=si: no extension) */ b = i = 0; ni = 8; for (;;) { w = lfn[si++]; /* Get an LFN char */ if (!w) break; /* Break when enf of the LFN */ if (w == L' ' || (w == L'.' && si != di)) { /* Remove spaces and dots */ cf |= NS_LOSS | NS_LFN; continue; } if (i >= ni || si == di) { /* Extension or end of SFN */ if (ni == 11) { /* Long extension */ cf |= NS_LOSS | NS_LFN; break; } if (si != di) cf |= NS_LOSS | NS_LFN; /* File name is longer than 8 bytes */ if (si > di) break; /* No extension */ si = di; i = 8; ni = 11; /* Enter extension section */ b <<= 2; continue; } if (w >= 0x80) { /* Non ASCII char */ #ifdef _EXCVT w = ff_convert(w, 0); /* Unicode -> OEM code */ if (w) w = cvt[w - 0x80]; /* Convert extend char (SBCS) */ #else w = ff_convert(ff_wtoupper(w), 0); /* Unicode (Caps) -> OEM code */ #endif cf |= NS_LFN; /* Force create an LFN */ } if (_DF1S && w >= 0x100) { /* Double byte char */ if (i >= ni - 1) { cf |= NS_LOSS | NS_LFN; i = ni; continue; } dj->fn[i++] = (BYTE)(w >> 8); } else { /* Single byte char */ if (!w || chk_chr("+,;[=]", w)) { /* Replace unallowable chars for SFN */ w = '_'; cf |= NS_LOSS | NS_LFN; /* Lossy conversion */ } else { if (IsUpper(w)) { /* Large capital */ b |= 2; } else { if (IsLower(w)) { /* Small capital */ b |= 1; w -= 0x20; } } } } dj->fn[i++] = (BYTE)w; } if (dj->fn[0] == 0xE5) dj->fn[0] = 0x05; /* If the first char collides with 0xE5, replace it with 0x05 */ if (ni == 8) b <<= 2; if ((b & 0x0C) == 0x0C || (b & 0x03) == 0x03) /* Create LFN entry when there are composite capitals */ cf |= NS_LFN; if (!(cf & NS_LFN)) { /* When LFN is in 8.3 format without extended char, NT flags are created */ if ((b & 0x03) == 0x01) cf |= NS_EXT; /* NT flag (Extension has only small capital) */ if ((b & 0x0C) == 0x04) cf |= NS_BODY; /* NT flag (Filename has only small capital) */ } dj->fn[11] = cf; /* SFN is created */ #else /* Non-LFN configuration */ BYTE b, c, d, *sfn; int ni, si, i; const char *p; /* Create file name in directory form */ sfn = dj->fn; mem_set(sfn, ' ', 11); si = i = b = 0; ni = 8; p = *path; #if _FS_RPATH if (p[si] == '.') { /* Is this a dot entry? */ for (;;) { c = p[si++]; if (c != '.' || si >= 3) break; sfn[i++] = c; } if (c != '/' && c != '\\' && c >= ' ') return FR_INVALID_NAME; *path = &p[si]; /* Rerurn pointer to the next segment */ sfn[11] = (c < ' ') ? NS_LAST|NS_DOT : NS_DOT; /* Set last segment flag if end of path */ return FR_OK; } #endif for (;;) { c = p[si++]; if (c < ' ' || c == '/' || c == '\\') break; /* Break on end of segment */ if (c == '.' || i >= ni) { if (ni != 8 || c != '.') return FR_INVALID_NAME; i = 8; ni = 11; b <<= 2; continue; } if (c >= 0x80) { /* Extended char */ #ifdef _EXCVT c = cvt[c - 0x80]; /* Convert extend char (SBCS) */ #else b |= 3; /* Eliminate NT flag if ext char is exist */ #if !_DF1S /* ASCII only cfg */ return FR_INVALID_NAME; #endif #endif } if (IsDBCS1(c)) { /* If it is DBC 1st byte */ d = p[si++]; /* Get 2nd byte */ if (!IsDBCS2(d) || i >= ni - 1) /* Reject invalid DBC */ return FR_INVALID_NAME; sfn[i++] = c; sfn[i++] = d; } else { if (chk_chr(" \"*+,[=]|\x7F", c)) /* Reject unallowable chrs for SFN */ return FR_INVALID_NAME; if (IsUpper(c)) { b |= 2; } else { if (IsLower(c)) { b |= 1; c -= 0x20; } } sfn[i++] = c; } } *path = &p[si]; /* Rerurn pointer to the next segment */ c = (c < ' ') ? NS_LAST : 0; /* Set last segment flag if end of path */ if (!i) return FR_INVALID_NAME; /* Reject null string */ if (sfn[0] == 0xE5) sfn[0] = 0x05; /* When first char collides with 0xE5, replace it with 0x05 */ if (ni == 8) b <<= 2; if ((b & 0x03) == 0x01) c |= NS_EXT; /* NT flag (Extension has only small capital) */ if ((b & 0x0C) == 0x04) c |= NS_BODY; /* NT flag (Filename has only small capital) */ sfn[11] = c; /* Store NT flag, File name is created */ #endif return FR_OK; } /*-----------------------------------------------------------------------*/ /* Get file information from directory entry */ /*-----------------------------------------------------------------------*/ #if _FS_MINIMIZE <= 1 static void get_fileinfo ( /* No return code */ DIR *dj, /* Pointer to the directory object */ FILINFO *fno /* Pointer to store the file information */ ) { int i; BYTE c, nt, *dir; char *p; #if _USE_LFN XCHAR *tp; #endif p = fno->fname; if (dj->sect) { dir = dj->dir; nt = dir[DIR_NTres]; /* NT flag */ for (i = 0; i < 8; i++) { /* Copy name body */ c = dir[i]; if (c == ' ') break; if (c == 0x05) c = 0xE5; if ((nt & 0x08) && IsUpper(c)) c += 0x20; *p++ = c; } if (dir[8] != ' ') { /* Copy name extension */ *p++ = '.'; for (i = 8; i < 11; i++) { c = dir[i]; if (c == ' ') break; if ((nt & 0x10) && IsUpper(c)) c += 0x20; *p++ = c; } } fno->fattrib = dir[DIR_Attr]; /* Attribute */ fno->fsize = LD_DWORD(dir+DIR_FileSize); /* Size */ fno->fdate = LD_WORD(dir+DIR_WrtDate); /* Date */ fno->ftime = LD_WORD(dir+DIR_WrtTime); /* Time */ } *p = 0; #if _USE_LFN tp = fno->lfname; if (tp) { WCHAR w, *lfn; i = 0; if (dj->sect && dj->lfn_idx != 0xFFFF) {/* Get LFN if available */ lfn = dj->lfn; while ((w = *lfn++) != 0) { /* Get an LFN char */ #if !_LFN_UNICODE w = ff_convert(w, 0); /* Unicode -> OEM conversion */ if (!w) { i = 0; break; } /* Could not convert, no LFN */ if (_DF1S && w >= 0x100) /* Put 1st byte if it is a DBC */ tp[i++] = (XCHAR)(w >> 8); if (i >= fno->lfsize - 1) { i = 0; break; } /* Buffer overrun, no LFN */ #endif tp[i++] = (XCHAR)w; } } tp[i] = 0; /* Terminator */ } #endif } #endif /* _FS_MINIMIZE <= 1 */ /*-----------------------------------------------------------------------*/ /* Follow a file path */ /*-----------------------------------------------------------------------*/ static FRESULT follow_path ( /* FR_OK(0): successful, !=0: error code */ DIR *dj, /* Directory object to return last directory and found object */ const XCHAR *path /* Full-path string to find a file or directory */ ) { FRESULT res; BYTE *dir, last; #if _FS_RPATH if (*path == '/' || *path == '\\') { /* There is a heading separator */ path++; dj->sclust = 0; /* Strip it and start from the root dir */ } else { /* No heading saparator */ dj->sclust = dj->fs->cdir; /* Start from the current dir */ } #else if (*path == '/' || *path == '\\') /* Strip heading separator if exist */ path++; dj->sclust = 0; /* Start from the root dir */ #endif if ((UINT)*path < ' ') { /* Null path means the start directory itself */ res = dir_seek(dj, 0); dj->dir = NULL; } else { /* Follow path */ for (;;) { res = create_name(dj, &path); /* Get a segment */ if (res != FR_OK) break; res = dir_find(dj); /* Find it */ last = *(dj->fn+11) & NS_LAST; if (res != FR_OK) { /* Could not find the object */ if (res == FR_NO_FILE && !last) res = FR_NO_PATH; break; } if (last) break; /* Last segment match. Function completed. */ dir = dj->dir; /* There is next segment. Follow the sub directory */ if (!(dir[DIR_Attr] & AM_DIR)) { /* Cannot follow because it is a file */ res = FR_NO_PATH; break; } dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); } } return res; } /*-----------------------------------------------------------------------*/ /* Load boot record and check if it is an FAT boot record */ /*-----------------------------------------------------------------------*/ static BYTE check_fs ( /* 0:The FAT boot record, 1:Valid boot record but not an FAT, 2:Not a boot record, 3:Error */ FATFS *fs, /* File system object */ DWORD sect /* Sector# (lba) to check if it is an FAT boot record or not */ ) { static const char fatstr[] = "FAT"; if (disk_read(fs->drive, fs->win, sect, 1) != RES_OK) /* Load boot record */ return 3; if (LD_WORD(&fs->win[BS_55AA]) != 0xAA55) /* Check record signature (always placed at offset 510 even if the sector size is >512) */ return 2; if (!mem_cmp(&fs->win[BS_FilSysType], fatstr, 3)) /* Check FAT signature */ return 0; if (!mem_cmp(&fs->win[BS_FilSysType32], fatstr, 3) && !(fs->win[BPB_ExtFlags] & 0x80)) return 0; return 1; } /*-----------------------------------------------------------------------*/ /* Make sure that the file system is valid */ /*-----------------------------------------------------------------------*/ static FRESULT auto_mount ( /* FR_OK(0): successful, !=0: any error occured */ const XCHAR **path, /* Pointer to pointer to the path name (drive number) */ FATFS **rfs, /* Pointer to pointer to the found file system object */ BYTE chk_wp /* !=0: Check media write protection for write access */ ) { FRESULT res; BYTE fmt, *tbl; UINT vol; DSTATUS stat; DWORD bsect, fsize, tsect, mclst; const XCHAR *p = *path; FATFS *fs; /* Get logical drive number from the path name */ vol = p[0] - '0'; /* Is there a drive number? */ if (vol <= 9 && p[1] == ':') { /* Found a drive number, get and strip it */ p += 2; *path = p; /* Return pointer to the path name */ } else { /* No drive number is given */ #if _FS_RPATH vol = Drive; /* Use current drive */ #else vol = 0; /* Use drive 0 */ #endif } /* Check if the logical drive is valid or not */ if (vol >= _DRIVES) /* Is the drive number valid? */ return FR_INVALID_DRIVE; *rfs = fs = FatFs[vol]; /* Returen pointer to the corresponding file system object */ if (!fs) return FR_NOT_ENABLED; /* Is the file system object registered? */ ENTER_FF(fs); /* Lock file system */ if (fs->fs_type) { /* If the logical drive has been mounted */ stat = disk_status(fs->drive); if (!(stat & STA_NOINIT)) { /* and the physical drive is kept initialized (has not been changed), */ #if !_FS_READONLY if (chk_wp && (stat & STA_PROTECT)) /* Check write protection if needed */ return FR_WRITE_PROTECTED; #endif return FR_OK; /* The file system object is valid */ } } /* The logical drive must be mounted. Following code attempts to mount the volume */ fs->fs_type = 0; /* Clear the file system object */ fs->drive = (BYTE)LD2PD(vol); /* Bind the logical drive and a physical drive */ stat = disk_initialize(fs->drive); /* Initialize low level disk I/O layer */ if (stat & STA_NOINIT) /* Check if the drive is ready */ return FR_NOT_READY; #if _MAX_SS != 512 /* Get disk sector size if needed */ if (disk_ioctl(fs->drive, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS) return FR_NO_FILESYSTEM; #endif #if !_FS_READONLY if (chk_wp && (stat & STA_PROTECT)) /* Check disk write protection if needed */ return FR_WRITE_PROTECTED; #endif /* Search FAT partition on the drive */ fmt = check_fs(fs, bsect = 0); /* Check sector 0 as an SFD format */ if (fmt == 1) { /* Not an FAT boot record, it may be patitioned */ /* Check a partition listed in top of the partition table */ tbl = &fs->win[MBR_Table + LD2PT(vol) * 16]; /* Partition table */ if (tbl[4]) { /* Is the partition existing? */ bsect = LD_DWORD(&tbl[8]); /* Partition offset in LBA */ fmt = check_fs(fs, bsect); /* Check the partition */ } } if (fmt == 3) return FR_DISK_ERR; if (fmt || LD_WORD(fs->win+BPB_BytsPerSec) != SS(fs)) /* No valid FAT patition is found */ return FR_NO_FILESYSTEM; /* Initialize the file system object */ fsize = LD_WORD(fs->win+BPB_FATSz16); /* Number of sectors per FAT */ if (!fsize) fsize = LD_DWORD(fs->win+BPB_FATSz32); fs->sects_fat = fsize; fs->n_fats = fs->win[BPB_NumFATs]; /* Number of FAT copies */ fsize *= fs->n_fats; /* (Number of sectors in FAT area) */ fs->fatbase = bsect + LD_WORD(fs->win+BPB_RsvdSecCnt); /* FAT start sector (lba) */ fs->csize = fs->win[BPB_SecPerClus]; /* Number of sectors per cluster */ fs->n_rootdir = LD_WORD(fs->win+BPB_RootEntCnt); /* Nmuber of root directory entries */ tsect = LD_WORD(fs->win+BPB_TotSec16); /* Number of sectors on the file system */ if (!tsect) tsect = LD_DWORD(fs->win+BPB_TotSec32); fs->max_clust = mclst = (tsect /* Last cluster# + 1 */ - LD_WORD(fs->win+BPB_RsvdSecCnt) - fsize - fs->n_rootdir / (SS(fs)/32) ) / fs->csize + 2; fmt = FS_FAT12; /* Determine the FAT sub type */ if (mclst >= 0xFF7) fmt = FS_FAT16; /* Number of clusters >= 0xFF5 */ if (mclst >= 0xFFF7) fmt = FS_FAT32; /* Number of clusters >= 0xFFF5 */ if (fmt == FS_FAT32) fs->dirbase = LD_DWORD(fs->win+BPB_RootClus); /* Root directory start cluster */ else fs->dirbase = fs->fatbase + fsize; /* Root directory start sector (lba) */ fs->database = fs->fatbase + fsize + fs->n_rootdir / (SS(fs)/32); /* Data start sector (lba) */ #if !_FS_READONLY /* Initialize allocation information */ fs->free_clust = 0xFFFFFFFF; fs->wflag = 0; /* Get fsinfo if needed */ if (fmt == FS_FAT32) { fs->fsi_flag = 0; fs->fsi_sector = bsect + LD_WORD(fs->win+BPB_FSInfo); if (disk_read(fs->drive, fs->win, fs->fsi_sector, 1) == RES_OK && LD_WORD(fs->win+BS_55AA) == 0xAA55 && LD_DWORD(fs->win+FSI_LeadSig) == 0x41615252 && LD_DWORD(fs->win+FSI_StrucSig) == 0x61417272) { fs->last_clust = LD_DWORD(fs->win+FSI_Nxt_Free); fs->free_clust = LD_DWORD(fs->win+FSI_Free_Count); } } #endif fs->fs_type = fmt; /* FAT sub-type */ fs->winsect = 0; /* Invalidate sector cache */ #if _FS_RPATH fs->cdir = 0; /* Current directory (root dir) */ #endif fs->id = ++Fsid; /* File system mount ID */ res = FR_OK; return res; } /*-----------------------------------------------------------------------*/ /* Check if the file/dir object is valid or not */ /*-----------------------------------------------------------------------*/ static FRESULT validate ( /* FR_OK(0): The object is valid, !=0: Invalid */ FATFS *fs, /* Pointer to the file system object */ WORD id /* Member id of the target object to be checked */ ) { if (!fs || !fs->fs_type || fs->id != id) return FR_INVALID_OBJECT; ENTER_FF(fs); /* Lock file system */ if (disk_status(fs->drive) & STA_NOINIT) return FR_NOT_READY; return FR_OK; } /*-------------------------------------------------------------------------- Public Functions --------------------------------------------------------------------------*/ /*-----------------------------------------------------------------------*/ /* Mount/Unmount a Locical Drive */ /*-----------------------------------------------------------------------*/ FRESULT f_mount ( BYTE vol, /* Logical drive number to be mounted/unmounted */ FATFS *fs /* Pointer to new file system object (NULL for unmount)*/ ) { FATFS *rfs; if (vol >= _DRIVES) /* Check if the drive number is valid */ return FR_INVALID_DRIVE; rfs = FatFs[vol]; /* Get current fs object */ if (rfs) { #if _FS_REENTRANT /* Discard sync object of the current volume */ if (!ff_del_syncobj(rfs->sobj)) return FR_INT_ERR; #endif rfs->fs_type = 0; /* Clear old fs object */ } if (fs) { fs->fs_type = 0; /* Clear new fs object */ #if _FS_REENTRANT /* Create sync object for the new volume */ if (!ff_cre_syncobj(vol, &fs->sobj)) return FR_INT_ERR; #endif } FatFs[vol] = fs; /* Register new fs object */ return FR_OK; } /*-----------------------------------------------------------------------*/ /* Open or Create a File */ /*-----------------------------------------------------------------------*/ FRESULT f_open ( FIL *fp, /* Pointer to the blank file object */ const XCHAR *path, /* Pointer to the file name */ BYTE mode /* Access mode and file open mode flags */ ) { FRESULT res; DIR dj; NAMEBUF(sfn, lfn); BYTE *dir; fp->fs = NULL; /* Clear file object */ #if !_FS_READONLY mode &= (FA_READ | FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW); res = auto_mount(&path, &dj.fs, (BYTE)(mode & (FA_WRITE | FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW))); #else mode &= FA_READ; res = auto_mount(&path, &dj.fs, 0); #endif if (res != FR_OK) LEAVE_FF(dj.fs, res); INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ #if !_FS_READONLY /* Create or Open a file */ if (mode & (FA_CREATE_ALWAYS | FA_OPEN_ALWAYS | FA_CREATE_NEW)) { DWORD ps, cl; if (res != FR_OK) { /* No file, create new */ if (res == FR_NO_FILE) /* There is no file to open, create a new entry */ res = dir_register(&dj); if (res != FR_OK) LEAVE_FF(dj.fs, res); mode |= FA_CREATE_ALWAYS; dir = dj.dir; /* Created entry (SFN entry) */ } else { /* Any object is already existing */ if (mode & FA_CREATE_NEW) /* Cannot create new */ LEAVE_FF(dj.fs, FR_EXIST); dir = dj.dir; if (!dir || (dir[DIR_Attr] & (AM_RDO | AM_DIR))) /* Cannot overwrite it (R/O or DIR) */ LEAVE_FF(dj.fs, FR_DENIED); if (mode & FA_CREATE_ALWAYS) { /* Resize it to zero on over write mode */ cl = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); /* Get start cluster */ ST_WORD(dir+DIR_FstClusHI, 0); /* cluster = 0 */ ST_WORD(dir+DIR_FstClusLO, 0); ST_DWORD(dir+DIR_FileSize, 0); /* size = 0 */ dj.fs->wflag = 1; ps = dj.fs->winsect; /* Remove the cluster chain */ if (cl) { res = remove_chain(dj.fs, cl); if (res) LEAVE_FF(dj.fs, res); dj.fs->last_clust = cl - 1; /* Reuse the cluster hole */ } res = move_window(dj.fs, ps); if (res != FR_OK) LEAVE_FF(dj.fs, res); } } if (mode & FA_CREATE_ALWAYS) { dir[DIR_Attr] = 0; /* Reset attribute */ ps = get_fattime(); ST_DWORD(dir+DIR_CrtTime, ps); /* Created time */ dj.fs->wflag = 1; mode |= FA__WRITTEN; /* Set file changed flag */ } } /* Open an existing file */ else { #endif /* !_FS_READONLY */ if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */ dir = dj.dir; if (!dir || (dir[DIR_Attr] & AM_DIR)) /* It is a directory */ LEAVE_FF(dj.fs, FR_NO_FILE); #if !_FS_READONLY if ((mode & FA_WRITE) && (dir[DIR_Attr] & AM_RDO)) /* R/O violation */ LEAVE_FF(dj.fs, FR_DENIED); } fp->dir_sect = dj.fs->winsect; /* Pointer to the directory entry */ fp->dir_ptr = dj.dir; #endif fp->flag = mode; /* File access mode */ fp->org_clust = /* File start cluster */ ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); fp->fsize = LD_DWORD(dir+DIR_FileSize); /* File size */ fp->fptr = 0; fp->csect = 255; /* File pointer */ fp->dsect = 0; fp->fs = dj.fs; fp->id = dj.fs->id; /* Owner file system object of the file */ LEAVE_FF(dj.fs, FR_OK); } /*-----------------------------------------------------------------------*/ /* Read File */ /*-----------------------------------------------------------------------*/ FRESULT f_read ( FIL *fp, /* Pointer to the file object */ void *buff, /* Pointer to data buffer */ UINT btr, /* Number of bytes to read */ UINT *br /* Pointer to number of bytes read */ ) { FRESULT res; DWORD clst, sect, remain; UINT rcnt, cc; BYTE *rbuff = buff; *br = 0; res = validate(fp->fs, fp->id); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); if (fp->flag & FA__ERROR) /* Check abort flag */ LEAVE_FF(fp->fs, FR_INT_ERR); if (!(fp->flag & FA_READ)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); remain = fp->fsize - fp->fptr; if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ for ( ; btr; /* Repeat until all data transferred */ rbuff += rcnt, fp->fptr += rcnt, *br += rcnt, btr -= rcnt) { if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ clst = (fp->fptr == 0) ? /* On the top of the file? */ fp->org_clust : get_fat(fp->fs, fp->curr_clust); if (clst <= 1) ABORT(fp->fs, FR_INT_ERR); if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); fp->curr_clust = clst; /* Update current cluster */ fp->csect = 0; /* Reset sector offset in the cluster */ } sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */ if (!sect) ABORT(fp->fs, FR_INT_ERR); sect += fp->csect; cc = btr / SS(fp->fs); /* When remaining bytes >= sector size, */ if (cc) { /* Read maximum contiguous sectors directly */ if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */ cc = fp->fs->csize - fp->csect; if (disk_read(fp->fs->drive, rbuff, sect, (BYTE)cc) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); #if !_FS_READONLY && _FS_MINIMIZE <= 2 #if _FS_TINY if (fp->fs->wflag && fp->fs->winsect - sect < cc) /* Replace one of the read sectors with cached data if it contains a dirty sector */ mem_cpy(rbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), fp->fs->win, SS(fp->fs)); #else if ((fp->flag & FA__DIRTY) && fp->dsect - sect < cc) /* Replace one of the read sectors with cached data if it contains a dirty sector */ mem_cpy(rbuff + ((fp->dsect - sect) * SS(fp->fs)), fp->buf, SS(fp->fs)); #endif #endif fp->csect += (BYTE)cc; /* Next sector address in the cluster */ rcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ continue; } #if !_FS_TINY #if !_FS_READONLY if (fp->flag & FA__DIRTY) { /* Write sector I/O buffer if needed */ if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif if (fp->dsect != sect) { /* Fill sector buffer with file data */ if (disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); } #endif fp->dsect = sect; fp->csect++; /* Next sector address in the cluster */ } rcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Get partial sector data from sector buffer */ if (rcnt > btr) rcnt = btr; #if _FS_TINY if (move_window(fp->fs, fp->dsect)) /* Move sector window */ ABORT(fp->fs, FR_DISK_ERR); mem_cpy(rbuff, &fp->fs->win[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */ #else mem_cpy(rbuff, &fp->buf[fp->fptr % SS(fp->fs)], rcnt); /* Pick partial sector */ #endif } LEAVE_FF(fp->fs, FR_OK); } #if !_FS_READONLY /*-----------------------------------------------------------------------*/ /* Write File */ /*-----------------------------------------------------------------------*/ FRESULT f_write ( FIL *fp, /* Pointer to the file object */ const void *buff, /* Pointer to the data to be written */ UINT btw, /* Number of bytes to write */ UINT *bw /* Pointer to number of bytes written */ ) { FRESULT res; DWORD clst, sect; UINT wcnt, cc; const BYTE *wbuff = buff; *bw = 0; res = validate(fp->fs, fp->id); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); if (fp->flag & FA__ERROR) /* Check abort flag */ LEAVE_FF(fp->fs, FR_INT_ERR); if (!(fp->flag & FA_WRITE)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); if (fp->fsize + btw < fp->fsize) btw = 0; /* File size cannot reach 4GB */ for ( ; btw; /* Repeat until all data transferred */ wbuff += wcnt, fp->fptr += wcnt, *bw += wcnt, btw -= wcnt) { if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ if (fp->fptr == 0) { /* On the top of the file? */ clst = fp->org_clust; /* Follow from the origin */ if (clst == 0) /* When there is no cluster chain, */ fp->org_clust = clst = create_chain(fp->fs, 0); /* Create a new cluster chain */ } else { /* Middle or end of the file */ clst = create_chain(fp->fs, fp->curr_clust); /* Follow or streach cluster chain */ } if (clst == 0) break; /* Could not allocate a new cluster (disk full) */ if (clst == 1) ABORT(fp->fs, FR_INT_ERR); if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); fp->curr_clust = clst; /* Update current cluster */ fp->csect = 0; /* Reset sector address in the cluster */ } #if _FS_TINY if (fp->fs->winsect == fp->dsect && move_window(fp->fs, 0)) /* Write back data buffer prior to following direct transfer */ ABORT(fp->fs, FR_DISK_ERR); #else if (fp->flag & FA__DIRTY) { /* Write back data buffer prior to following direct transfer */ if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif sect = clust2sect(fp->fs, fp->curr_clust); /* Get current sector */ if (!sect) ABORT(fp->fs, FR_INT_ERR); sect += fp->csect; cc = btw / SS(fp->fs); /* When remaining bytes >= sector size, */ if (cc) { /* Write maximum contiguous sectors directly */ if (fp->csect + cc > fp->fs->csize) /* Clip at cluster boundary */ cc = fp->fs->csize - fp->csect; if (disk_write(fp->fs->drive, wbuff, sect, (BYTE)cc) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); #if _FS_TINY if (fp->fs->winsect - sect < cc) { /* Refill sector cache if it gets dirty by the direct write */ mem_cpy(fp->fs->win, wbuff + ((fp->fs->winsect - sect) * SS(fp->fs)), SS(fp->fs)); fp->fs->wflag = 0; } #else if (fp->dsect - sect < cc) { /* Refill sector cache if it gets dirty by the direct write */ mem_cpy(fp->buf, wbuff + ((fp->dsect - sect) * SS(fp->fs)), SS(fp->fs)); fp->flag &= ~FA__DIRTY; } #endif fp->csect += (BYTE)cc; /* Next sector address in the cluster */ wcnt = SS(fp->fs) * cc; /* Number of bytes transferred */ continue; } #if _FS_TINY if (fp->fptr >= fp->fsize) { /* Avoid silly buffer filling at growing edge */ if (move_window(fp->fs, 0)) ABORT(fp->fs, FR_DISK_ERR); fp->fs->winsect = sect; } #else if (fp->dsect != sect) { /* Fill sector buffer with file data */ if (fp->fptr < fp->fsize && disk_read(fp->fs->drive, fp->buf, sect, 1) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); } #endif fp->dsect = sect; fp->csect++; /* Next sector address in the cluster */ } wcnt = SS(fp->fs) - (fp->fptr % SS(fp->fs)); /* Put partial sector into file I/O buffer */ if (wcnt > btw) wcnt = btw; #if _FS_TINY if (move_window(fp->fs, fp->dsect)) /* Move sector window */ ABORT(fp->fs, FR_DISK_ERR); mem_cpy(&fp->fs->win[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */ fp->fs->wflag = 1; #else mem_cpy(&fp->buf[fp->fptr % SS(fp->fs)], wbuff, wcnt); /* Fit partial sector */ fp->flag |= FA__DIRTY; #endif } if (fp->fptr > fp->fsize) fp->fsize = fp->fptr; /* Update file size if needed */ fp->flag |= FA__WRITTEN; /* Set file changed flag */ LEAVE_FF(fp->fs, FR_OK); } /*-----------------------------------------------------------------------*/ /* Synchronize the File Object */ /*-----------------------------------------------------------------------*/ FRESULT f_sync ( FIL *fp /* Pointer to the file object */ ) { FRESULT res; DWORD tim; BYTE *dir; res = validate(fp->fs, fp->id); /* Check validity of the object */ if (res == FR_OK) { if (fp->flag & FA__WRITTEN) { /* Has the file been written? */ #if !_FS_TINY /* Write-back dirty buffer */ if (fp->flag & FA__DIRTY) { if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK) LEAVE_FF(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif /* Update the directory entry */ res = move_window(fp->fs, fp->dir_sect); if (res == FR_OK) { dir = fp->dir_ptr; dir[DIR_Attr] |= AM_ARC; /* Set archive bit */ ST_DWORD(dir+DIR_FileSize, fp->fsize); /* Update file size */ ST_WORD(dir+DIR_FstClusLO, fp->org_clust); /* Update start cluster */ ST_WORD(dir+DIR_FstClusHI, fp->org_clust >> 16); tim = get_fattime(); /* Updated time */ ST_DWORD(dir+DIR_WrtTime, tim); fp->flag &= ~FA__WRITTEN; fp->fs->wflag = 1; res = sync(fp->fs); } } } LEAVE_FF(fp->fs, res); } #endif /* !_FS_READONLY */ /*-----------------------------------------------------------------------*/ /* Close File */ /*-----------------------------------------------------------------------*/ FRESULT f_close ( FIL *fp /* Pointer to the file object to be closed */ ) { FRESULT res; #if _FS_READONLY res = validate(fp->fs, fp->id); if (res == FR_OK) fp->fs = NULL; LEAVE_FF(fp->fs, res); #else res = f_sync(fp); if (res == FR_OK) fp->fs = NULL; return res; #endif } /*-----------------------------------------------------------------------*/ /* Change Current Drive/Directory */ /*-----------------------------------------------------------------------*/ #if _FS_RPATH FRESULT f_chdrive ( BYTE drv /* Drive number */ ) { if (drv >= _DRIVES) return FR_INVALID_DRIVE; Drive = drv; return FR_OK; } FRESULT f_chdir ( const XCHAR *path /* Pointer to the directory path */ ) { FRESULT res; DIR dj; NAMEBUF(sfn, lfn); BYTE *dir; res = auto_mount(&path, &dj.fs, 0); if (res == FR_OK) { INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ if (res == FR_OK) { /* Follow completed */ dir = dj.dir; /* Pointer to the entry */ if (!dir) { dj.fs->cdir = 0; /* No entry (root dir) */ } else { if (dir[DIR_Attr] & AM_DIR) /* Reached to the dir */ dj.fs->cdir = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); else res = FR_NO_PATH; /* Could not reach the dir (it is a file) */ } } if (res == FR_NO_FILE) res = FR_NO_PATH; } LEAVE_FF(dj.fs, res); } #endif #if _FS_MINIMIZE <= 2 /*-----------------------------------------------------------------------*/ /* Seek File R/W Pointer */ /*-----------------------------------------------------------------------*/ FRESULT f_lseek ( FIL *fp, /* Pointer to the file object */ DWORD ofs /* File pointer from top of file */ ) { FRESULT res; DWORD clst, bcs, nsect, ifptr; res = validate(fp->fs, fp->id); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); if (fp->flag & FA__ERROR) /* Check abort flag */ LEAVE_FF(fp->fs, FR_INT_ERR); if (ofs > fp->fsize /* In read-only mode, clip offset with the file size */ #if !_FS_READONLY && !(fp->flag & FA_WRITE) #endif ) ofs = fp->fsize; ifptr = fp->fptr; fp->fptr = nsect = 0; fp->csect = 255; if (ofs > 0) { bcs = (DWORD)fp->fs->csize * SS(fp->fs); /* Cluster size (byte) */ if (ifptr > 0 && (ofs - 1) / bcs >= (ifptr - 1) / bcs) { /* When seek to same or following cluster, */ fp->fptr = (ifptr - 1) & ~(bcs - 1); /* start from the current cluster */ ofs -= fp->fptr; clst = fp->curr_clust; } else { /* When seek to back cluster, */ clst = fp->org_clust; /* start from the first cluster */ #if !_FS_READONLY if (clst == 0) { /* If no cluster chain, create a new chain */ clst = create_chain(fp->fs, 0); if (clst == 1) ABORT(fp->fs, FR_INT_ERR); if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); fp->org_clust = clst; } #endif fp->curr_clust = clst; } if (clst != 0) { while (ofs > bcs) { /* Cluster following loop */ #if !_FS_READONLY if (fp->flag & FA_WRITE) { /* Check if in write mode or not */ clst = create_chain(fp->fs, clst); /* Force streached if in write mode */ if (clst == 0) { /* When disk gets full, clip file size */ ofs = bcs; break; } } else #endif clst = get_fat(fp->fs, clst); /* Follow cluster chain if not in write mode */ if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); if (clst <= 1 || clst >= fp->fs->max_clust) ABORT(fp->fs, FR_INT_ERR); fp->curr_clust = clst; fp->fptr += bcs; ofs -= bcs; } fp->fptr += ofs; fp->csect = (BYTE)(ofs / SS(fp->fs)); /* Sector offset in the cluster */ if (ofs % SS(fp->fs)) { nsect = clust2sect(fp->fs, clst); /* Current sector */ if (!nsect) ABORT(fp->fs, FR_INT_ERR); nsect += fp->csect; fp->csect++; } } } if (fp->fptr % SS(fp->fs) && nsect != fp->dsect) { #if !_FS_TINY #if !_FS_READONLY if (fp->flag & FA__DIRTY) { /* Write-back dirty buffer if needed */ if (disk_write(fp->fs->drive, fp->buf, fp->dsect, 1) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); fp->flag &= ~FA__DIRTY; } #endif if (disk_read(fp->fs->drive, fp->buf, nsect, 1) != RES_OK) ABORT(fp->fs, FR_DISK_ERR); #endif fp->dsect = nsect; } #if !_FS_READONLY if (fp->fptr > fp->fsize) { /* Set changed flag if the file size is extended */ fp->fsize = fp->fptr; fp->flag |= FA__WRITTEN; } #endif LEAVE_FF(fp->fs, res); } #if _FS_MINIMIZE <= 1 /*-----------------------------------------------------------------------*/ /* Create a Directroy Object */ /*-----------------------------------------------------------------------*/ FRESULT f_opendir ( DIR *dj, /* Pointer to directory object to create */ const XCHAR *path /* Pointer to the directory path */ ) { FRESULT res; NAMEBUF(sfn, lfn); BYTE *dir; res = auto_mount(&path, &dj->fs, 0); if (res == FR_OK) { INITBUF((*dj), sfn, lfn); res = follow_path(dj, path); /* Follow the path to the directory */ if (res == FR_OK) { /* Follow completed */ dir = dj->dir; if (dir) { /* It is not the root dir */ if (dir[DIR_Attr] & AM_DIR) { /* The object is a directory */ dj->sclust = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); } else { /* The object is not a directory */ res = FR_NO_PATH; } } if (res == FR_OK) { dj->id = dj->fs->id; res = dir_seek(dj, 0); /* Rewind dir */ } } if (res == FR_NO_FILE) res = FR_NO_PATH; } LEAVE_FF(dj->fs, res); } /*-----------------------------------------------------------------------*/ /* Read Directory Entry in Sequense */ /*-----------------------------------------------------------------------*/ FRESULT f_readdir ( DIR *dj, /* Pointer to the open directory object */ FILINFO *fno /* Pointer to file information to return */ ) { FRESULT res; NAMEBUF(sfn, lfn); res = validate(dj->fs, dj->id); /* Check validity of the object */ if (res == FR_OK) { INITBUF((*dj), sfn, lfn); if (!fno) { res = dir_seek(dj, 0); } else { res = dir_read(dj); if (res == FR_NO_FILE) { dj->sect = 0; res = FR_OK; } if (res == FR_OK) { /* A valid entry is found */ get_fileinfo(dj, fno); /* Get the object information */ res = dir_next(dj, FALSE); /* Increment index for next */ if (res == FR_NO_FILE) { dj->sect = 0; res = FR_OK; } } } } LEAVE_FF(dj->fs, res); } #if _FS_MINIMIZE == 0 /*-----------------------------------------------------------------------*/ /* Get File Status */ /*-----------------------------------------------------------------------*/ FRESULT f_stat ( const XCHAR *path, /* Pointer to the file path */ FILINFO *fno /* Pointer to file information to return */ ) { FRESULT res; DIR dj; NAMEBUF(sfn, lfn); res = auto_mount(&path, &dj.fs, 0); if (res == FR_OK) { INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ if (res == FR_OK) { /* Follwo completed */ if (dj.dir) /* Found an object */ get_fileinfo(&dj, fno); else /* It is root dir */ res = FR_INVALID_NAME; } } LEAVE_FF(dj.fs, res); } #if !_FS_READONLY /*-----------------------------------------------------------------------*/ /* Get Number of Free Clusters */ /*-----------------------------------------------------------------------*/ FRESULT f_getfree ( const XCHAR *path, /* Pointer to the logical drive number (root dir) */ DWORD *nclst, /* Pointer to the variable to return number of free clusters */ FATFS **fatfs /* Pointer to pointer to corresponding file system object to return */ ) { FRESULT res; DWORD n, clst, sect, stat; UINT i; BYTE fat, *p; /* Get drive number */ res = auto_mount(&path, fatfs, 0); if (res != FR_OK) LEAVE_FF(*fatfs, res); /* If number of free cluster is valid, return it without cluster scan. */ if ((*fatfs)->free_clust <= (*fatfs)->max_clust - 2) { *nclst = (*fatfs)->free_clust; LEAVE_FF(*fatfs, FR_OK); } /* Get number of free clusters */ fat = (*fatfs)->fs_type; n = 0; if (fat == FS_FAT12) { clst = 2; do { stat = get_fat(*fatfs, clst); if (stat == 0xFFFFFFFF) LEAVE_FF(*fatfs, FR_DISK_ERR); if (stat == 1) LEAVE_FF(*fatfs, FR_INT_ERR); if (stat == 0) n++; } while (++clst < (*fatfs)->max_clust); } else { clst = (*fatfs)->max_clust; sect = (*fatfs)->fatbase; i = 0; p = 0; do { if (!i) { res = move_window(*fatfs, sect++); if (res != FR_OK) LEAVE_FF(*fatfs, res); p = (*fatfs)->win; i = SS(*fatfs); } if (fat == FS_FAT16) { if (LD_WORD(p) == 0) n++; p += 2; i -= 2; } else { if (LD_DWORD(p) == 0) n++; p += 4; i -= 4; } } while (--clst); } (*fatfs)->free_clust = n; if (fat == FS_FAT32) (*fatfs)->fsi_flag = 1; *nclst = n; LEAVE_FF(*fatfs, FR_OK); } /*-----------------------------------------------------------------------*/ /* Truncate File */ /*-----------------------------------------------------------------------*/ FRESULT f_truncate ( FIL *fp /* Pointer to the file object */ ) { FRESULT res; DWORD ncl; res = validate(fp->fs, fp->id); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); if (fp->flag & FA__ERROR) /* Check abort flag */ LEAVE_FF(fp->fs, FR_INT_ERR); if (!(fp->flag & FA_WRITE)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); if (fp->fsize > fp->fptr) { fp->fsize = fp->fptr; /* Set file size to current R/W point */ fp->flag |= FA__WRITTEN; if (fp->fptr == 0) { /* When set file size to zero, remove entire cluster chain */ res = remove_chain(fp->fs, fp->org_clust); fp->org_clust = 0; } else { /* When truncate a part of the file, remove remaining clusters */ ncl = get_fat(fp->fs, fp->curr_clust); res = FR_OK; if (ncl == 0xFFFFFFFF) res = FR_DISK_ERR; if (ncl == 1) res = FR_INT_ERR; if (res == FR_OK && ncl < fp->fs->max_clust) { res = put_fat(fp->fs, fp->curr_clust, 0x0FFFFFFF); if (res == FR_OK) res = remove_chain(fp->fs, ncl); } } } if (res != FR_OK) fp->flag |= FA__ERROR; LEAVE_FF(fp->fs, res); } /*-----------------------------------------------------------------------*/ /* Delete a File or Directory */ /*-----------------------------------------------------------------------*/ FRESULT f_unlink ( const XCHAR *path /* Pointer to the file or directory path */ ) { FRESULT res; DIR dj, sdj; NAMEBUF(sfn, lfn); BYTE *dir; DWORD dclst; res = auto_mount(&path, &dj.fs, 1); if (res != FR_OK) LEAVE_FF(dj.fs, res); INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ if (_FS_RPATH && res == FR_OK && (dj.fn[11] & NS_DOT)) res = FR_INVALID_NAME; if (res != FR_OK) LEAVE_FF(dj.fs, res); /* Follow failed */ dir = dj.dir; if (!dir) /* Is it the root directory? */ LEAVE_FF(dj.fs, FR_INVALID_NAME); if (dir[DIR_Attr] & AM_RDO) /* Is it a R/O object? */ LEAVE_FF(dj.fs, FR_DENIED); dclst = ((DWORD)LD_WORD(dir+DIR_FstClusHI) << 16) | LD_WORD(dir+DIR_FstClusLO); if (dir[DIR_Attr] & AM_DIR) { /* It is a sub-directory */ if (dclst < 2) LEAVE_FF(dj.fs, FR_INT_ERR); mem_cpy(&sdj, &dj, sizeof(DIR)); /* Check if the sub-dir is empty or not */ sdj.sclust = dclst; res = dir_seek(&sdj, 0); if (res != FR_OK) LEAVE_FF(dj.fs, res); res = dir_read(&sdj); if (res == FR_OK) res = FR_DENIED; /* Not empty sub-dir */ if (res != FR_NO_FILE) LEAVE_FF(dj.fs, res); } res = dir_remove(&dj); /* Remove directory entry */ if (res == FR_OK) { if (dclst) res = remove_chain(dj.fs, dclst); /* Remove the cluster chain */ if (res == FR_OK) res = sync(dj.fs); } LEAVE_FF(dj.fs, res); } /*-----------------------------------------------------------------------*/ /* Create a Directory */ /*-----------------------------------------------------------------------*/ FRESULT f_mkdir ( const XCHAR *path /* Pointer to the directory path */ ) { FRESULT res; DIR dj; NAMEBUF(sfn, lfn); BYTE *dir, n; DWORD dsect, dclst, pclst, tim; res = auto_mount(&path, &dj.fs, 1); if (res != FR_OK) LEAVE_FF(dj.fs, res); INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ if (res == FR_OK) res = FR_EXIST; /* Any file or directory is already existing */ if (_FS_RPATH && res == FR_NO_FILE && (dj.fn[11] & NS_DOT)) res = FR_INVALID_NAME; if (res != FR_NO_FILE) /* Any error occured */ LEAVE_FF(dj.fs, res); dclst = create_chain(dj.fs, 0); /* Allocate a new cluster for new directory table */ res = FR_OK; if (dclst == 0) res = FR_DENIED; if (dclst == 1) res = FR_INT_ERR; if (dclst == 0xFFFFFFFF) res = FR_DISK_ERR; if (res == FR_OK) res = move_window(dj.fs, 0); if (res != FR_OK) LEAVE_FF(dj.fs, res); dsect = clust2sect(dj.fs, dclst); dir = dj.fs->win; /* Initialize the new directory table */ mem_set(dir, 0, SS(dj.fs)); mem_set(dir+DIR_Name, ' ', 8+3); /* Create "." entry */ dir[DIR_Name] = '.'; dir[DIR_Attr] = AM_DIR; tim = get_fattime(); ST_DWORD(dir+DIR_WrtTime, tim); ST_WORD(dir+DIR_FstClusLO, dclst); ST_WORD(dir+DIR_FstClusHI, dclst >> 16); mem_cpy(dir+32, dir, 32); /* Create ".." entry */ dir[33] = '.'; pclst = dj.sclust; if (dj.fs->fs_type == FS_FAT32 && pclst == dj.fs->dirbase) pclst = 0; ST_WORD(dir+32+DIR_FstClusLO, pclst); ST_WORD(dir+32+DIR_FstClusHI, pclst >> 16); for (n = 0; n < dj.fs->csize; n++) { /* Write dot entries and clear left sectors */ dj.fs->winsect = dsect++; dj.fs->wflag = 1; res = move_window(dj.fs, 0); if (res) LEAVE_FF(dj.fs, res); mem_set(dir, 0, SS(dj.fs)); } res = dir_register(&dj); if (res != FR_OK) { remove_chain(dj.fs, dclst); } else { dir = dj.dir; dir[DIR_Attr] = AM_DIR; /* Attribute */ ST_DWORD(dir+DIR_WrtTime, tim); /* Crated time */ ST_WORD(dir+DIR_FstClusLO, dclst); /* Table start cluster */ ST_WORD(dir+DIR_FstClusHI, dclst >> 16); dj.fs->wflag = 1; res = sync(dj.fs); } LEAVE_FF(dj.fs, res); } /*-----------------------------------------------------------------------*/ /* Change File Attribute */ /*-----------------------------------------------------------------------*/ FRESULT f_chmod ( const XCHAR *path, /* Pointer to the file path */ BYTE value, /* Attribute bits */ BYTE mask /* Attribute mask to change */ ) { FRESULT res; DIR dj; NAMEBUF(sfn, lfn); BYTE *dir; res = auto_mount(&path, &dj.fs, 1); if (res == FR_OK) { INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ if (_FS_RPATH && res == FR_OK && (dj.fn[11] & NS_DOT)) res = FR_INVALID_NAME; if (res == FR_OK) { dir = dj.dir; if (!dir) { /* Is it a root directory? */ res = FR_INVALID_NAME; } else { /* File or sub directory */ mask &= AM_RDO|AM_HID|AM_SYS|AM_ARC; /* Valid attribute mask */ dir[DIR_Attr] = (value & mask) | (dir[DIR_Attr] & (BYTE)~mask); /* Apply attribute change */ dj.fs->wflag = 1; res = sync(dj.fs); } } } LEAVE_FF(dj.fs, res); } /*-----------------------------------------------------------------------*/ /* Change Timestamp */ /*-----------------------------------------------------------------------*/ FRESULT f_utime ( const XCHAR *path, /* Pointer to the file/directory name */ const FILINFO *fno /* Pointer to the timestamp to be set */ ) { FRESULT res; DIR dj; NAMEBUF(sfn, lfn); BYTE *dir; res = auto_mount(&path, &dj.fs, 1); if (res == FR_OK) { INITBUF(dj, sfn, lfn); res = follow_path(&dj, path); /* Follow the file path */ if (_FS_RPATH && res == FR_OK && (dj.fn[11] & NS_DOT)) res = FR_INVALID_NAME; if (res == FR_OK) { dir = dj.dir; if (!dir) { /* Root directory */ res = FR_INVALID_NAME; } else { /* File or sub-directory */ ST_WORD(dir+DIR_WrtTime, fno->ftime); ST_WORD(dir+DIR_WrtDate, fno->fdate); dj.fs->wflag = 1; res = sync(dj.fs); } } } LEAVE_FF(dj.fs, res); } /*-----------------------------------------------------------------------*/ /* Rename File/Directory */ /*-----------------------------------------------------------------------*/ FRESULT f_rename ( const XCHAR *path_old, /* Pointer to the old name */ const XCHAR *path_new /* Pointer to the new name */ ) { FRESULT res; DIR dj_old, dj_new; NAMEBUF(sfn, lfn); BYTE buf[21], *dir; DWORD dw; INITBUF(dj_old, sfn, lfn); res = auto_mount(&path_old, &dj_old.fs, 1); if (res == FR_OK) { dj_new.fs = dj_old.fs; res = follow_path(&dj_old, path_old); /* Check old object */ if (_FS_RPATH && res == FR_OK && (dj_old.fn[11] & NS_DOT)) res = FR_INVALID_NAME; } if (res != FR_OK) LEAVE_FF(dj_old.fs, res); /* The old object is not found */ if (!dj_old.dir) LEAVE_FF(dj_old.fs, FR_NO_FILE); /* Is root dir? */ mem_cpy(buf, dj_old.dir+DIR_Attr, 21); /* Save the object information */ mem_cpy(&dj_new, &dj_old, sizeof(DIR)); res = follow_path(&dj_new, path_new); /* Check new object */ if (res == FR_OK) res = FR_EXIST; /* The new object name is already existing */ if (res == FR_NO_FILE) { /* Is it a valid path and no name collision? */ res = dir_register(&dj_new); /* Register the new object */ if (res == FR_OK) { dir = dj_new.dir; /* Copy object information into new entry */ mem_cpy(dir+13, buf+2, 19); dir[DIR_Attr] = buf[0] | AM_ARC; dj_old.fs->wflag = 1; if (dir[DIR_Attr] & AM_DIR) { /* Update .. entry in the directory if needed */ dw = clust2sect(dj_new.fs, (DWORD)LD_WORD(dir+DIR_FstClusHI) | LD_WORD(dir+DIR_FstClusLO)); if (!dw) { res = FR_INT_ERR; } else { res = move_window(dj_new.fs, dw); dir = dj_new.fs->win+32; if (res == FR_OK && dir[1] == '.') { dw = (dj_new.fs->fs_type == FS_FAT32 && dj_new.sclust == dj_new.fs->dirbase) ? 0 : dj_new.sclust; ST_WORD(dir+DIR_FstClusLO, dw); ST_WORD(dir+DIR_FstClusHI, dw >> 16); dj_new.fs->wflag = 1; } } } if (res == FR_OK) { res = dir_remove(&dj_old); /* Remove old entry */ if (res == FR_OK) res = sync(dj_old.fs); } } } LEAVE_FF(dj_old.fs, res); } #endif /* !_FS_READONLY */ #endif /* _FS_MINIMIZE == 0 */ #endif /* _FS_MINIMIZE <= 1 */ #endif /* _FS_MINIMIZE <= 2 */ /*-----------------------------------------------------------------------*/ /* Forward data to the stream directly (Available on only _FS_TINY cfg) */ /*-----------------------------------------------------------------------*/ #if _USE_FORWARD && _FS_TINY FRESULT f_forward ( FIL *fp, /* Pointer to the file object */ UINT (*func)(const BYTE*,UINT), /* Pointer to the streaming function */ UINT btr, /* Number of bytes to forward */ UINT *bf /* Pointer to number of bytes forwarded */ ) { FRESULT res; DWORD remain, clst, sect; UINT rcnt; *bf = 0; res = validate(fp->fs, fp->id); /* Check validity of the object */ if (res != FR_OK) LEAVE_FF(fp->fs, res); if (fp->flag & FA__ERROR) /* Check error flag */ LEAVE_FF(fp->fs, FR_INT_ERR); if (!(fp->flag & FA_READ)) /* Check access mode */ LEAVE_FF(fp->fs, FR_DENIED); remain = fp->fsize - fp->fptr; if (btr > remain) btr = (UINT)remain; /* Truncate btr by remaining bytes */ for ( ; btr && (*func)(NULL, 0); /* Repeat until all data transferred or stream becomes busy */ fp->fptr += rcnt, *bf += rcnt, btr -= rcnt) { if ((fp->fptr % SS(fp->fs)) == 0) { /* On the sector boundary? */ if (fp->csect >= fp->fs->csize) { /* On the cluster boundary? */ clst = (fp->fptr == 0) ? /* On the top of the file? */ fp->org_clust : get_fat(fp->fs, fp->curr_clust); if (clst <= 1) ABORT(fp->fs, FR_INT_ERR); if (clst == 0xFFFFFFFF) ABORT(fp->fs, FR_DISK_ERR); fp->curr_clust = clst; /* Update current cluster */ fp->csect = 0; /* Reset sector address in the cluster */ } fp->csect++; /* Next sector address in the cluster */ } sect = clust2sect(fp->fs, fp->curr_clust); /* Get current data sector */ if (!sect) ABORT(fp->fs, FR_INT_ERR); sect += fp->csect - 1; if (move_window(fp->fs, sect)) /* Move sector window */ ABORT(fp->fs, FR_DISK_ERR); fp->dsect = sect; rcnt = SS(fp->fs) - (WORD)(fp->fptr % SS(fp->fs)); /* Forward data from sector window */ if (rcnt > btr) rcnt = btr; rcnt = (*func)(&fp->fs->win[(WORD)fp->fptr % SS(fp->fs)], rcnt); if (!rcnt) ABORT(fp->fs, FR_INT_ERR); } LEAVE_FF(fp->fs, FR_OK); } #endif /* _USE_FORWARD */ #if _USE_MKFS && !_FS_READONLY /*-----------------------------------------------------------------------*/ /* Create File System on the Drive */ /*-----------------------------------------------------------------------*/ #define N_ROOTDIR 512 /* Multiple of 32 and <= 2048 */ #define N_FATS 1 /* 1 or 2 */ #define MAX_SECTOR 131072000UL /* Maximum partition size */ #define MIN_SECTOR 2000UL /* Minimum partition size */ FRESULT f_mkfs ( BYTE drv, /* Logical drive number */ BYTE partition, /* Partitioning rule 0:FDISK, 1:SFD */ WORD allocsize /* Allocation unit size [bytes] */ ) { static const DWORD sstbl[] = { 2048000, 1024000, 512000, 256000, 128000, 64000, 32000, 16000, 8000, 4000, 0 }; static const WORD cstbl[] = { 32768, 16384, 8192, 4096, 2048, 16384, 8192, 4096, 2048, 1024, 512 }; BYTE fmt, m, *tbl; DWORD b_part, b_fat, b_dir, b_data; /* Area offset (LBA) */ DWORD n_part, n_rsv, n_fat, n_dir; /* Area size */ DWORD n_clst, d, n; WORD as; FATFS *fs; DSTATUS stat; /* Check validity of the parameters */ if (drv >= _DRIVES) return FR_INVALID_DRIVE; if (partition >= 2) return FR_MKFS_ABORTED; /* Check mounted drive and clear work area */ fs = FatFs[drv]; if (!fs) return FR_NOT_ENABLED; fs->fs_type = 0; drv = LD2PD(drv); /* Get disk statics */ stat = disk_initialize(drv); if (stat & STA_NOINIT) return FR_NOT_READY; if (stat & STA_PROTECT) return FR_WRITE_PROTECTED; #if _MAX_SS != 512 /* Get disk sector size */ if (disk_ioctl(drv, GET_SECTOR_SIZE, &SS(fs)) != RES_OK || SS(fs) > _MAX_SS) return FR_MKFS_ABORTED; #endif if (disk_ioctl(drv, GET_SECTOR_COUNT, &n_part) != RES_OK || n_part < MIN_SECTOR) return FR_MKFS_ABORTED; if (n_part > MAX_SECTOR) n_part = MAX_SECTOR; b_part = (!partition) ? 63 : 0; /* Boot sector */ n_part -= b_part; for (d = 512; d <= 32768U && d != allocsize; d <<= 1) ; /* Check validity of the allocation unit size */ if (d != allocsize) allocsize = 0; if (!allocsize) { /* Auto selection of cluster size */ d = n_part; for (as = SS(fs); as > 512U; as >>= 1) d >>= 1; for (n = 0; d < sstbl[n]; n++) ; allocsize = cstbl[n]; } if (allocsize < SS(fs)) allocsize = SS(fs); allocsize /= SS(fs); /* Number of sectors per cluster */ /* Pre-compute number of clusters and FAT type */ n_clst = n_part / allocsize; fmt = FS_FAT12; if (n_clst >= 0xFF5) fmt = FS_FAT16; if (n_clst >= 0xFFF5) fmt = FS_FAT32; /* Determine offset and size of FAT structure */ switch (fmt) { case FS_FAT12: n_fat = ((n_clst * 3 + 1) / 2 + 3 + SS(fs) - 1) / SS(fs); n_rsv = 1 + partition; n_dir = N_ROOTDIR * 32 / SS(fs); break; case FS_FAT16: n_fat = ((n_clst * 2) + 4 + SS(fs) - 1) / SS(fs); n_rsv = 1 + partition; n_dir = N_ROOTDIR * 32 / SS(fs); break; default: n_fat = ((n_clst * 4) + 8 + SS(fs) - 1) / SS(fs); n_rsv = 33 - partition; n_dir = 0; } b_fat = b_part + n_rsv; /* FATs start sector */ b_dir = b_fat + n_fat * N_FATS; /* Directory start sector */ b_data = b_dir + n_dir; /* Data start sector */ /* Align data start sector to erase block boundary (for flash memory media) */ if (disk_ioctl(drv, GET_BLOCK_SIZE, &n) != RES_OK) return FR_MKFS_ABORTED; n = (b_data + n - 1) & ~(n - 1); n_fat += (n - b_data) / N_FATS; /* b_dir and b_data are no longer used below */ /* Determine number of cluster and final check of validity of the FAT type */ n_clst = (n_part - n_rsv - n_fat * N_FATS - n_dir) / allocsize; if ( (fmt == FS_FAT16 && n_clst < 0xFF5) || (fmt == FS_FAT32 && n_clst < 0xFFF5)) return FR_MKFS_ABORTED; /* Create partition table if needed */ if (!partition) { DWORD n_disk = b_part + n_part; mem_set(fs->win, 0, SS(fs)); tbl = fs->win+MBR_Table; ST_DWORD(tbl, 0x00010180); /* Partition start in CHS */ if (n_disk < 63UL * 255 * 1024) { /* Partition end in CHS */ n_disk = n_disk / 63 / 255; tbl[7] = (BYTE)n_disk; tbl[6] = (BYTE)((n_disk >> 2) | 63); } else { ST_WORD(&tbl[6], 0xFFFF); } tbl[5] = 254; if (fmt != FS_FAT32) /* System ID */ tbl[4] = (n_part < 0x10000) ? 0x04 : 0x06; else tbl[4] = 0x0c; ST_DWORD(tbl+8, 63); /* Partition start in LBA */ ST_DWORD(tbl+12, n_part); /* Partition size in LBA */ ST_WORD(tbl+64, 0xAA55); /* Signature */ if (disk_write(drv, fs->win, 0, 1) != RES_OK) return FR_DISK_ERR; partition = 0xF8; } else { partition = 0xF0; } /* Create boot record */ tbl = fs->win; /* Clear buffer */ mem_set(tbl, 0, SS(fs)); ST_DWORD(tbl+BS_jmpBoot, 0x90FEEB); /* Boot code (jmp $, nop) */ ST_WORD(tbl+BPB_BytsPerSec, SS(fs)); /* Sector size */ tbl[BPB_SecPerClus] = (BYTE)allocsize; /* Sectors per cluster */ ST_WORD(tbl+BPB_RsvdSecCnt, n_rsv); /* Reserved sectors */ tbl[BPB_NumFATs] = N_FATS; /* Number of FATs */ ST_WORD(tbl+BPB_RootEntCnt, SS(fs) / 32 * n_dir); /* Number of rootdir entries */ if (n_part < 0x10000) { /* Number of total sectors */ ST_WORD(tbl+BPB_TotSec16, n_part); } else { ST_DWORD(tbl+BPB_TotSec32, n_part); } tbl[BPB_Media] = partition; /* Media descripter */ ST_WORD(tbl+BPB_SecPerTrk, 63); /* Number of sectors per track */ ST_WORD(tbl+BPB_NumHeads, 255); /* Number of heads */ ST_DWORD(tbl+BPB_HiddSec, b_part); /* Hidden sectors */ n = get_fattime(); /* Use current time as a VSN */ if (fmt != FS_FAT32) { ST_DWORD(tbl+BS_VolID, n); /* Volume serial number */ ST_WORD(tbl+BPB_FATSz16, n_fat); /* Number of secters per FAT */ tbl[BS_DrvNum] = 0x80; /* Drive number */ tbl[BS_BootSig] = 0x29; /* Extended boot signature */ mem_cpy(tbl+BS_VolLab, "NO NAME FAT ", 19); /* Volume lavel, FAT signature */ } else { ST_DWORD(tbl+BS_VolID32, n); /* Volume serial number */ ST_DWORD(tbl+BPB_FATSz32, n_fat); /* Number of secters per FAT */ ST_DWORD(tbl+BPB_RootClus, 2); /* Root directory cluster (2) */ ST_WORD(tbl+BPB_FSInfo, 1); /* FSInfo record offset (bs+1) */ ST_WORD(tbl+BPB_BkBootSec, 6); /* Backup boot record offset (bs+6) */ tbl[BS_DrvNum32] = 0x80; /* Drive number */ tbl[BS_BootSig32] = 0x29; /* Extended boot signature */ mem_cpy(tbl+BS_VolLab32, "NO NAME FAT32 ", 19); /* Volume lavel, FAT signature */ } ST_WORD(tbl+BS_55AA, 0xAA55); /* Signature */ if (SS(fs) > 512U) { ST_WORD(tbl+SS(fs)-2, 0xAA55); } if (disk_write(drv, tbl, b_part+0, 1) != RES_OK) return FR_DISK_ERR; if (fmt == FS_FAT32) disk_write(drv, tbl, b_part+6, 1); /* Initialize FAT area */ for (m = 0; m < N_FATS; m++) { mem_set(tbl, 0, SS(fs)); /* 1st sector of the FAT */ if (fmt != FS_FAT32) { n = (fmt == FS_FAT12) ? 0x00FFFF00 : 0xFFFFFF00; n |= partition; ST_DWORD(tbl, n); /* Reserve cluster #0-1 (FAT12/16) */ } else { ST_DWORD(tbl+0, 0xFFFFFFF8); /* Reserve cluster #0-1 (FAT32) */ ST_DWORD(tbl+4, 0xFFFFFFFF); ST_DWORD(tbl+8, 0x0FFFFFFF); /* Reserve cluster #2 for root dir */ } if (disk_write(drv, tbl, b_fat++, 1) != RES_OK) return FR_DISK_ERR; mem_set(tbl, 0, SS(fs)); /* Following FAT entries are filled by zero */ for (n = 1; n < n_fat; n++) { if (disk_write(drv, tbl, b_fat++, 1) != RES_OK) return FR_DISK_ERR; } } /* Initialize Root directory */ m = (BYTE)((fmt == FS_FAT32) ? allocsize : n_dir); do { if (disk_write(drv, tbl, b_fat++, 1) != RES_OK) return FR_DISK_ERR; } while (--m); /* Create FSInfo record if needed */ if (fmt == FS_FAT32) { ST_WORD(tbl+BS_55AA, 0xAA55); ST_DWORD(tbl+FSI_LeadSig, 0x41615252); ST_DWORD(tbl+FSI_StrucSig, 0x61417272); ST_DWORD(tbl+FSI_Free_Count, n_clst - 1); ST_DWORD(tbl+FSI_Nxt_Free, 0xFFFFFFFF); disk_write(drv, tbl, b_part+1, 1); disk_write(drv, tbl, b_part+7, 1); } return (disk_ioctl(drv, CTRL_SYNC, (void*)NULL) == RES_OK) ? FR_OK : FR_DISK_ERR; } #endif /* _USE_MKFS && !_FS_READONLY */ #if _USE_STRFUNC /*-----------------------------------------------------------------------*/ /* Get a string from the file */ /*-----------------------------------------------------------------------*/ char* f_gets ( char* buff, /* Pointer to the string buffer to read */ int len, /* Size of string buffer */ FIL* fil /* Pointer to the file object */ ) { int i = 0; char *p = buff; UINT rc; while (i < len - 1) { /* Read bytes until buffer gets filled */ f_read(fil, p, 1, &rc); if (rc != 1) break; /* Break when no data to read */ #if _USE_STRFUNC >= 2 if (*p == '\r') continue; /* Strip '\r' */ #endif i++; if (*p++ == '\n') break; /* Break when reached end of line */ } *p = 0; return i ? buff : NULL; /* When no data read (eof or error), return with error. */ } #if !_FS_READONLY #include <stdarg.h> /*-----------------------------------------------------------------------*/ /* Put a character to the file */ /*-----------------------------------------------------------------------*/ int f_putc ( int chr, /* A character to be output */ FIL* fil /* Ponter to the file object */ ) { UINT bw; char c; #if _USE_STRFUNC >= 2 if (chr == '\n') f_putc ('\r', fil); /* LF -> CRLF conversion */ #endif if (!fil) { /* Special value may be used to switch the destination to any other device */ /* put_console(chr); */ return chr; } c = (char)chr; f_write(fil, &c, 1, &bw); /* Write a byte to the file */ return bw ? chr : EOF; /* Return the result */ } /*-----------------------------------------------------------------------*/ /* Put a string to the file */ /*-----------------------------------------------------------------------*/ int f_puts ( const char* str, /* Pointer to the string to be output */ FIL* fil /* Pointer to the file object */ ) { int n; for (n = 0; *str; str++, n++) { if (f_putc(*str, fil) == EOF) return EOF; } return n; } /*-----------------------------------------------------------------------*/ /* Put a formatted string to the file */ /*-----------------------------------------------------------------------*/ int f_printf ( FIL* fil, /* Pointer to the file object */ const char* str, /* Pointer to the format string */ ... /* Optional arguments... */ ) { va_list arp; UCHAR c, f, r; ULONG val; char s[16]; int i, w, res, cc; va_start(arp, str); for (cc = res = 0; cc != EOF; res += cc) { c = *str++; if (c == 0) break; /* End of string */ if (c != '%') { /* Non escape cahracter */ cc = f_putc(c, fil); if (cc != EOF) cc = 1; continue; } w = f = 0; c = *str++; if (c == '0') { /* Flag: '0' padding */ f = 1; c = *str++; } while (c >= '0' && c <= '9') { /* Precision */ w = w * 10 + (c - '0'); c = *str++; } if (c == 'l') { /* Prefix: Size is long int */ f |= 2; c = *str++; } if (c == 's') { /* Type is string */ cc = f_puts(va_arg(arp, char*), fil); continue; } if (c == 'c') { /* Type is character */ cc = f_putc(va_arg(arp, int), fil); if (cc != EOF) cc = 1; continue; } r = 0; if (c == 'd') r = 10; /* Type is signed decimal */ if (c == 'u') r = 10; /* Type is unsigned decimal */ if (c == 'X') r = 16; /* Type is unsigned hexdecimal */ if (r == 0) break; /* Unknown type */ if (f & 2) { /* Get the value */ val = (ULONG)va_arg(arp, long); } else { val = (c == 'd') ? (ULONG)(long)va_arg(arp, int) : (ULONG)va_arg(arp, unsigned int); } /* Put numeral string */ if (c == 'd') { if (val & 0x80000000) { val = 0 - val; f |= 4; } } i = sizeof(s) - 1; s[i] = 0; do { c = (UCHAR)(val % r + '0'); if (c > '9') c += 7; s[--i] = c; val /= r; } while (i && val); if (i && (f & 4)) s[--i] = '-'; w = sizeof(s) - 1 - w; while (i && i > w) s[--i] = (f & 1) ? '0' : ' '; cc = f_puts(&s[i], fil); } va_end(arp); return (cc == EOF) ? cc : res; } #endif /* !_FS_READONLY */ #endif /* _USE_STRFUNC */
zzqq5414-jk-rabbit
sw/all_demo/ff.c
C
asf20
99,200
#include <stm32f10x.h> #include "key.h" #include "ov7670.h" const bsp_key_group_type key_group[keyMax]= { {KEY_USER_PORT, KEY1_USER_PIN } #ifdef STM32_MIDDLE_HW_VER1 ,{KEY_USER_PORT, KEY2_USER_PIN } #endif }; exti_key_service_function_type gbl_ar_exti_key_service[extiKeyServiceFunctionMAX] = { {extiKey1ServiceFunction, NULL} #ifdef STM32_MIDDLE_HW_VER1 ,{extiKey2ServiceFunction, NULL} #endif }; void register_exti_key_function(exti_key_register_function_type exti_key_fn_type, exti_key_register_function fn) { gbl_ar_exti_key_service[exti_key_fn_type].run = fn; } // Camera EXTI exti_camera_service_function_type gbl_ar_exti_camera_service[extiCameraServiceFunctionMAX] = { {extiCameraVsyncServiceFunction, NULL}, {extiCameraPclkServiceFunction, NULL}, {extiCameraHrefServiceFunction, NULL} }; void register_camera_key_function(exti_camera_register_function_type exti_camera_fn_type, exti_camera_register_function fn) { gbl_ar_exti_camera_service[exti_camera_fn_type].run = fn; } void bsp_key_gpio_init(void) { EXTI_InitTypeDef EXTI_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; /* Configure the GPIO ports( key2 ) */ GPIO_InitStructure.GPIO_Pin = KEY1_USER_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(KEY_USER_PORT, &GPIO_InitStructure); #ifdef STM32_MIDDLE_HW_VER1 GPIO_InitStructure.GPIO_Pin = KEY2_USER_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(KEY_USER_PORT, &GPIO_InitStructure); #endif // interrupt disable /* Clear EXTI Line Pending Bit */ EXTI_ClearITPendingBit(KEY1_IRQ_EXTI_Line); #ifdef STM32_MIDDLE_HW_VER1 EXTI_ClearITPendingBit(KEY2_IRQ_EXTI_Line); #endif /* Configure EXTI to generate an interrupt on falling edge */ EXTI_InitStructure.EXTI_Line = KEY1_IRQ_EXTI_Line; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; EXTI_InitStructure.EXTI_LineCmd = DISABLE; EXTI_Init(&EXTI_InitStructure); #ifdef STM32_MIDDLE_HW_VER1 EXTI_InitStructure.EXTI_Line = KEY2_IRQ_EXTI_Line; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; EXTI_InitStructure.EXTI_LineCmd = DISABLE; EXTI_Init(&EXTI_InitStructure); #endif } void bsp_key_interrupt_init(void) { GPIO_InitTypeDef GPIO_InitStructure; EXTI_InitTypeDef EXTI_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; /* Configure the GPIO ports( key2 ) */ GPIO_InitStructure.GPIO_Pin = KEY1_USER_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(KEY_USER_PORT, &GPIO_InitStructure); #ifdef STM32_MIDDLE_HW_VER1 GPIO_InitStructure.GPIO_Pin = KEY2_USER_PIN; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_10MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU; GPIO_Init(KEY_USER_PORT, &GPIO_InitStructure); #endif /* Connect EXTI */ GPIO_EXTILineConfig(KEY_IRQ_PORT_SOURCE, KEY1_IRQ_PIN_SOURCE); #ifdef STM32_MIDDLE_HW_VER1 GPIO_EXTILineConfig(KEY_IRQ_PORT_SOURCE, KEY2_IRQ_PIN_SOURCE); #endif /* Configure EXTI to generate an interrupt on falling edge */ EXTI_InitStructure.EXTI_Line = KEY1_IRQ_EXTI_Line; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); #ifdef STM32_MIDDLE_HW_VER1 EXTI_InitStructure.EXTI_Line = KEY2_IRQ_EXTI_Line; EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); #endif /* 2 bit for pre-emption priority, 2 bits for subpriority */ NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); NVIC_InitStructure.NVIC_IRQChannel = KEY1_IRQ_CHANNEL; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #ifdef STM32_MIDDLE_HW_VER1 NVIC_InitStructure.NVIC_IRQChannel = KEY2_IRQ_CHANNEL; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); #endif /* Clear EXTI Line Pending Bit */ EXTI_ClearITPendingBit(KEY1_IRQ_EXTI_Line); #ifdef STM32_MIDDLE_HW_VER1 EXTI_ClearITPendingBit(KEY2_IRQ_EXTI_Line); #endif /* Enable the Key EXTI line Interrupt */ NVIC_ClearPendingIRQ(KEY1_IRQ_CHANNEL); #ifdef STM32_MIDDLE_HW_VER1 NVIC_ClearPendingIRQ(KEY2_IRQ_CHANNEL); #endif } void EXTI0_IRQHandler(void) { } void EXTI2_IRQHandler(void) { if(EXTI_GetITStatus(KEY1_IRQ_EXTI_Line) != RESET) { EXTI_ClearITPendingBit(KEY1_IRQ_EXTI_Line); if( gbl_ar_exti_key_service[extiKey1ServiceFunction].run != NULL ) { gbl_ar_exti_key_service[extiKey1ServiceFunction].run(); } } #ifdef CAM_PCLK if(EXTI_GetITStatus(CAMERA_PCLK_IRQ_EXTI_Line) != RESET) { EXTI_ClearITPendingBit(CAMERA_PCLK_IRQ_EXTI_Line); if( gbl_ar_exti_camera_service[extiCameraPclkServiceFunction].run != NULL ) { gbl_ar_exti_camera_service[extiCameraPclkServiceFunction].run(); } } #endif } void EXTI4_IRQHandler(void) { #ifdef CAM_HREF if(EXTI_GetITStatus(CAMERA_HREF_IRQ_EXTI_Line) != RESET) { EXTI_ClearITPendingBit(CAMERA_HREF_IRQ_EXTI_Line); if( gbl_ar_exti_camera_service[extiCameraHrefServiceFunction].run != NULL ) { gbl_ar_exti_camera_service[extiCameraHrefServiceFunction].run(); } } #endif } void EXTI9_5_IRQHandler(void) { if(EXTI_GetITStatus(CAMERA_VSYNC_IRQ_EXTI_Line) != RESET) { EXTI_ClearITPendingBit(CAMERA_VSYNC_IRQ_EXTI_Line); if( gbl_ar_exti_camera_service[extiCameraVsyncServiceFunction].run != NULL ) { gbl_ar_exti_camera_service[extiCameraVsyncServiceFunction].run(); } } } void EXTI15_10_IRQHandler(void) { }
zzqq5414-jk-rabbit
sw/all_demo/key.c
C
asf20
6,315
/******************** (C) COPYRIGHT 2009 STMicroelectronics ******************** * File Name : main.h * Author : MCD Application Team * Version : V2.0.0 * Date : 04/27/2009 * Description : Header for main.c module ******************************************************************************** * THE PRESENT SOFTWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH SOFTWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MAIN_H #define __MAIN_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x_it.h" #include "hw_config.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void bsp_init_rcc(void); void bsp_init_gpio(void); void bsp_init_interrupt(void); ErrorStatus Get_HSEStartUpStatus(void); typedef enum { MainService, Ledservice, TimerService, RtcService, SdService, UsbService, LcdService, TouchService, KeyService, RfService, CameraService, serviceMAX } service_define_type; typedef enum { ledUserCoreOnService, ledUserCoreOffService, ledUserBottomOnService, ledUserBottomOffService, ledExitService, ledServiceMAX } service_led_type; typedef enum { timerTIM2Service, timerTIM2Stop, timerExitService, timerServiceMAX } service_timer_type; typedef enum { rtcStartService, rtcStopService, rtcExitService, rtcServiceMAX } service_rtc_type; typedef enum { sdInitializeService, sdGetCapacityService, sdFileListService, sdExitService, sdServiceMAX } service_sd_type; typedef enum { usbStartService, usbStopService, usbExitService, usbServiceMAX } service_usb_type; typedef enum { lcdStartService, lcdStopService, lcdExitService, lcdServiceMAX } service_lcd_type; typedef enum { touchStartService, touchStopService, touchExitService, touchServiceMAX } service_touch_type; typedef enum { keyStartPollingService, keyStopPollingService, keyStartInterruptService, keyStopInterruptService, keyExitService, keyServiceMAX } service_key_type; typedef enum { rfStartRxService, rfStartTxService, #ifdef NRF24L01_BPS_CHECK rfStartRxBpsService, rfStartTxBpsService, #endif rfStopService, rfExitService, rfServiceMAX } service_rf_type; typedef enum { cameraStartOv7670Service, cameraStopOv7670Service, cameraExitOv7670Service, cameraServiceMAX } service_camera_type; typedef void (*service_function)(void); typedef struct _service_type { int service; char* service_string; service_function run; s8 cmd; } service_type; void service_led(void); void service_timer(void); void service_rtc(void); void service_sd(void); void service_usb(void); void service_lcd(void); void service_touch(void); void service_key(void); void service_rf(void); void service_camera(void); void service_user_led_core_on(void); void service_user_led_core_off(void); void service_user_led_bottom_on(void); void service_user_led_bottom_off(void); void service_led_exit(void); void service_tim2_ticktime(void); void service_tim2_stop(void); void service_timer_exit(void); void service_rtc_start(void); void service_rtc_stop(void); void service_rtc_exit(void); void service_sd_initialize(void); void service_sd_get_capacity(void); void service_sd_file_list(void); void service_sd_exit(void); void service_usb_start(void); void service_usb_stop(void); void service_usb_exit(void); void service_lcd_start(void); void service_lcd_stop(void); void service_lcd_exit(void); void lcd_test(void); void service_touch_start(void); void service_touch_stop(void); void service_touch_exit(void); void touch_test(void); void service_key_polling_start(void); void service_key_polling_stop(void); void service_key_interrupt_start(void); void service_key_interrupt_stop(void); void service_key_exit(void); void gpio_polling_key(void); void key1_interrupt_event(void); void key2_interrupt_event(void); void service_rf_start_rx(void); void service_rf_start_tx(void); void service_rf_bps_start_rx(void); void service_rf_bps_start_tx(void); void service_rf_stop(void); void service_rf_exit(void); void service_ov7670_start(void); void service_ov7670_stop(void); void service_ov7670_exit(void); void tim_display(u32 TimeVar); void time_show(void); void usb_mouse_control(s8 Keys); #endif /* __MAIN_H */ /******************* (C) COPYRIGHT 2009 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/main.h
C
asf20
5,351
#ifndef __LCD_H #define __LCD_H #define ID_AM 001 #define LCD_PORT GPIOC // LCD Setting #define LCD_CS_PIN GPIO_Pin_9 #define LCD_RS_PIN GPIO_Pin_8 #define LCD_WR_PIN GPIO_Pin_7 #define LCD_RD_PIN GPIO_Pin_6 #define LCD_RST_PIN GPIO_Pin_11 // 2.4/2.8 inch TFT LCD driver // Supported driver IC models include: ILI9325/RM68021/ILI9320/LGDP4531/SPFD5408 etc. #define GPIOA_ODR_Addr (GPIOA_BASE+12) //0x4001080C #define GPIOB_ODR_Addr (GPIOB_BASE+12) //0x40010C0C #define GPIOC_ODR_Addr (GPIOC_BASE+12) //0x4001100C #define GPIOD_ODR_Addr (GPIOD_BASE+12) //0x4001140C #define GPIOE_ODR_Addr (GPIOE_BASE+12) //0x4001180C #define GPIOF_ODR_Addr (GPIOF_BASE+12) //0x40011A0C #define GPIOG_ODR_Addr (GPIOG_BASE+12) //0x40011E0C #define GPIOA_IDR_Addr (GPIOA_BASE+8) //0x40010808 #define GPIOB_IDR_Addr (GPIOB_BASE+8) //0x40010C08 #define GPIOC_IDR_Addr (GPIOC_BASE+8) //0x40011008 #define GPIOD_IDR_Addr (GPIOD_BASE+8) //0x40011408 #define GPIOE_IDR_Addr (GPIOE_BASE+8) //0x40011808 #define GPIOF_IDR_Addr (GPIOF_BASE+8) //0x40011A08 #define GPIOG_IDR_Addr (GPIOG_BASE+8) //0x40011E08 #define BITBAND(addr, bitnum) ((addr & 0xF0000000)+0x2000000+((addr &0xFFFFF)<<5)+(bitnum<<2)) #define MEM_ADDR(addr) *((volatile unsigned long *)(addr)) #define BIT_ADDR(addr, bitnum) MEM_ADDR(BITBAND(addr, bitnum)) #define PAout(n) BIT_ADDR(GPIOA_ODR_Addr,n) #define PAin(n) BIT_ADDR(GPIOA_IDR_Addr,n) #define PBout(n) BIT_ADDR(GPIOB_ODR_Addr,n) #define PBin(n) BIT_ADDR(GPIOB_IDR_Addr,n) #define PCout(n) BIT_ADDR(GPIOC_ODR_Addr,n) #define PCin(n) BIT_ADDR(GPIOC_IDR_Addr,n) #define PDout(n) BIT_ADDR(GPIOD_ODR_Addr,n) #define PDin(n) BIT_ADDR(GPIOD_IDR_Addr,n) #define PEout(n) BIT_ADDR(GPIOE_ODR_Addr,n) #define PEin(n) BIT_ADDR(GPIOE_IDR_Addr,n) #define PFout(n) BIT_ADDR(GPIOF_ODR_Addr,n) #define PFin(n) BIT_ADDR(GPIOF_IDR_Addr,n) #define PGout(n) BIT_ADDR(GPIOG_ODR_Addr,n) #define PGin(n) BIT_ADDR(GPIOG_IDR_Addr,n) // TFTLCD part of the function to call outside the extern u16 POINT_COLOR; // default red extern u16 BACK_COLOR; // background color. The default is white // Define the size of LCD #define LCD_W 240 #define LCD_H 320 //----------------- LCD port definition ---------------- #define LCD_BL BIT_ADDR(GPIOC_ODR_Addr, 10) // LCD backlight, PC10 #define LCD_CS BIT_ADDR(GPIOC_ODR_Addr, 9) // chip select, PC9 #define LCD_RS BIT_ADDR(GPIOC_ODR_Addr, 8) // Data or Command, PC8 #define LCD_WR BIT_ADDR(GPIOC_ODR_Addr, 7) // write data, PC7 #define LCD_RD BIT_ADDR(GPIOC_ODR_Addr, 6) // read data, PC6 #define LCD_RST BIT_ADDR(GPIOC_ODR_Addr, 11) // lcd reset, PC11 // PB0 ~ 15, as the data line #define LCD_DATAOUT(x) GPIOB->ODR=x; // data output #define LCD_DATAIN GPIOB->IDR; // data entry // Pen color #define WHITE 0xFFFF #define BLACK 0x0000 #define BLUE 0x001F #define BRED 0XF81F #define GRED 0XFFE0 #define GBLUE 0X07FF #define RED 0xF800 #define MAGENTA 0xF81F #define GREEN 0x07E0 #define CYAN 0x7FFF #define YELLOW 0xFFE0 #define BROWN 0XBC40 #define BRRED 0XFC07 #define GRAY 0X8430 //GUI #define DARKBLUE 0X01CF #define LIGHTBLUE 0X7D7C #define GRAYBLUE 0X5458 // for PANEL #define LIGHTGREEN 0X841F //#define LIGHTGRAY 0XEF5B #define LGRAY 0XC618 #define LGRAYBLUE 0XA651 // light gray blue (middle layer color) #define LBBLUE 0X2B12 // light brown blue (select the entry of anti-color) extern u16 BACK_COLOR, POINT_COLOR ; void LCD_Init(void); void LCD_DisplayOn(void); void LCD_DisplayOff(void); void LCD_Clear(u16 Color); void LCD_SetCursor(u8 Xpos, u16 Ypos); void LCD_DrawPoint(u16 x,u16 y); u16 LCD_ReadPoint(u16 x,u16 y); void Draw_Circle(u8 x0,u16 y0,u8 r); void LCD_DrawLine(u16 x1, u16 y1, u16 x2, u16 y2); void LCD_DrawRectangle(u8 x1, u16 y1, u8 x2, u16 y2); void LCD_Fill(u8 xsta,u16 ysta,u8 xend,u16 yend,u16 color); void LCD_ShowChar(u8 x,u16 y,u8 num,u8 size,u8 mode); void LCD_ShowNum(u8 x,u16 y,u32 num,u8 len,u8 size); void LCD_Show2Num(u8 x,u16 y,u16 num,u8 len,u8 size,u8 mode); void LCD_ShowString(u8 x,u16 y,const u8 *p); // display a string of 16 fonts void LCD_WR_REG (u8 data); void LCD_WriteReg(u8 LCD_Reg, u16 LCD_RegValue); u16 LCD_ReadReg(u8 LCD_Reg); void LCD_WriteRAM_Prepare(void); void LCD_WriteRAM(u16 RGB_Code); u16 LCD_ReadRAM(void); // Write 8-bit data function // Use macro definitions, increased speed. #define LCD_WR_DATA(data){\ LCD_RS=1;\ LCD_CS=0;\ LCD_DATAOUT(data);\ LCD_WR=0;\ LCD_WR=1;\ LCD_CS=1;\ } // 9320/9325 LCD register #define R0 0x00 #define R1 0x01 #define R2 0x02 #define R3 0x03 #define R4 0x04 #define R5 0x05 #define R6 0x06 #define R7 0x07 #define R8 0x08 #define R9 0x09 #define R10 0x0A #define R12 0x0C #define R13 0x0D #define R14 0x0E #define R15 0x0F #define R16 0x10 #define R17 0x11 #define R18 0x12 #define R19 0x13 #define R20 0x14 #define R21 0x15 #define R22 0x16 #define R23 0x17 #define R24 0x18 #define R25 0x19 #define R26 0x1A #define R27 0x1B #define R28 0x1C #define R29 0x1D #define R30 0x1E #define R31 0x1F #define R32 0x20 #define R33 0x21 #define R34 0x22 #define R36 0x24 #define R37 0x25 #define R40 0x28 #define R41 0x29 #define R43 0x2B #define R45 0x2D #define R48 0x30 #define R49 0x31 #define R50 0x32 #define R51 0x33 #define R52 0x34 #define R53 0x35 #define R54 0x36 #define R55 0x37 #define R56 0x38 #define R57 0x39 #define R59 0x3B #define R60 0x3C #define R61 0x3D #define R62 0x3E #define R63 0x3F #define R64 0x40 #define R65 0x41 #define R66 0x42 #define R67 0x43 #define R68 0x44 #define R69 0x45 #define R70 0x46 #define R71 0x47 #define R72 0x48 #define R73 0x49 #define R74 0x4A #define R75 0x4B #define R76 0x4C #define R77 0x4D #define R78 0x4E #define R79 0x4F #define R80 0x50 #define R81 0x51 #define R82 0x52 #define R83 0x53 #define R96 0x60 #define R97 0x61 #define R106 0x6A #define R118 0x76 #define R128 0x80 #define R129 0x81 #define R130 0x82 #define R131 0x83 #define R132 0x84 #define R133 0x85 #define R134 0x86 #define R135 0x87 #define R136 0x88 #define R137 0x89 #define R139 0x8B #define R140 0x8C #define R141 0x8D #define R143 0x8F #define R144 0x90 #define R145 0x91 #define R146 0x92 #define R147 0x93 #define R148 0x94 #define R149 0x95 #define R150 0x96 #define R151 0x97 #define R152 0x98 #define R153 0x99 #define R154 0x9A #define R157 0x9D #define R192 0xC0 #define R193 0xC1 #define R229 0xE5 #endif
zzqq5414-jk-rabbit
sw/all_demo/lcd.h
C
asf20
8,119
#include "stm32f10x.h" #include "hw_config.h" #include "rtc.h" #include "usart.h" //#include <stm32f10x_rtc.h> //#include <stm32f10x_bkp.h> #define RTCClockSource_LSE /* Use the external 32.768 KHz oscillator as RTC clock source */ //#define RTCClockOutput_Enable /* RTC Clock/64 is output on tamper pin(PC.13) */ rtc_service_function_type gbl_ar_rtc_service[rtcServiceFunctionMAX] = { {rtcServiceFunction, NULL} }; /* ------------------------------------------------------------------------------------------------- */ /* BSP rtc */ /* ------------------------------------------------------------------------------------------------- */ void register_rtc_function(rtc_register_function_type rtc_fn_type, rtc_register_function fn) { gbl_ar_rtc_service[rtc_fn_type].run = fn; } void RTC_IRQHandler(void) { // Also cleared the wrong interrupt flag in the ISR TIM_ClearFlag(TIM2, TIM_FLAG_Update); // TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET TIM_ClearITPendingBit(TIM2, TIM_IT_Update); // Clear the interrupt flag if( gbl_ar_rtc_service[rtcServiceFunction].run != NULL ) { gbl_ar_rtc_service[rtcServiceFunction].run(); } } void bsp_init_rtc(void) { if(BKP_ReadBackupRegister(BKP_DR1) != 0xA5A5) { /* Backup data register value is not correct or not yet programmed (when the first time the program is executed) */ usart1_transmit_string("\r\n\n RTC not yet configured...."); /* RTC Configuration */ rtc_configuration(); usart1_transmit_string("\r\n RTC configured....\r\n"); /* Adjust time by values entred by the user on the hyperterminal */ time_adjust(); BKP_WriteBackupRegister(BKP_DR1, 0xA5A5); } else { /* Check if the Power On Reset flag is set */ if(RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET) { usart1_transmit_string("\r\n\n Power On Reset occurred....\r\n"); } /* Check if the Pin Reset flag is set */ else if(RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET) { usart1_transmit_string("\r\n\n External Reset occurred...."); } usart1_transmit_string("\r\n No need to configure RTC....\r\n"); /* Wait for RTC registers synchronization */ RTC_WaitForSynchro(); /* Enable the RTC Second */ RTC_ITConfig(RTC_IT_SEC, ENABLE); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); } /* Clear reset flags */ RCC_ClearFlag(); } void rtc_configuration(void) { /* Enable PWR and BKP clocks */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE); /* Allow access to BKP Domain */ PWR_BackupAccessCmd(ENABLE); /* Reset Backup Domain */ BKP_DeInit(); #ifdef RTCClockSource_LSI /* Enable LSI */ RCC_LSICmd(ENABLE); /* Wait till LSI is ready */ while(RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET) { } /* Select LSI as RTC Clock Source */ RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI); #elif defined RTCClockSource_LSE /* Enable LSE */ RCC_LSEConfig(RCC_LSE_ON); /* Wait till LSE is ready */ while(RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET) { } /* Select LSE as RTC Clock Source */ RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); #endif /* Enable RTC Clock */ RCC_RTCCLKCmd(ENABLE); #ifdef RTCClockOutput_Enable /* Disable the Tamper Pin */ BKP_TamperPinCmd(DISABLE); /* To output RTCCLK/64 on Tamper pin, the tamper functionality must be disabled */ /* Enable RTC Clock Output on Tamper Pin */ BKP_RTCCalibrationClockOutputCmd(ENABLE); #endif /* Wait for RTC registers synchronization */ RTC_WaitForSynchro(); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); /* Enable the RTC Second */ RTC_ITConfig(RTC_IT_SEC, ENABLE); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); /* Set RTC prescaler: set RTC period to 1sec */ #ifdef RTCClockSource_LSI RTC_SetPrescaler(31999); /* RTC period = RTCCLK/RTC_PR = (32.000 KHz)/(31999+1) */ #elif defined RTCClockSource_LSE RTC_SetPrescaler(32767); /* RTC period = RTCCLK/RTC_PR = (32.768 KHz)/(32767+1) */ #endif /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); } /******************************************************************************* * Function Name : time_adjust * Description : Adjusts time. * Input : None * Output : None * Return : None *******************************************************************************/ void time_adjust(void) { /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); /* Change the current time */ RTC_SetCounter(time_regulate()); /* Wait until last write operation on RTC registers has finished */ RTC_WaitForLastTask(); } /******************************************************************************* * Function Name : time_regulate * Description : Returns the time entered by user, using Hyperterminal. * Input : None * Output : None * Return : Current time RTC counter value *******************************************************************************/ u32 time_regulate(void) { u32 Tmp_HH = 0xa, Tmp_MM = 0xb, Tmp_SS = 0x00; #if 0 usart1_transmit_string("\r\n==============Time Settings====================================="); usart1_transmit_string("\r\n Please Set Hours"); while(Tmp_HH == 0xFF) { Tmp_HH = USART_Scanf(23); } usart1_transmit_string(": %d", Tmp_HH); usart1_transmit_string("\r\n Please Set Minutes"); while(Tmp_MM == 0xFF) { Tmp_MM = USART_Scanf(59); } usart1_transmit_string(": %d", Tmp_MM); usart1_transmit_string("\r\n Please Set Seconds"); while(Tmp_SS == 0xFF) { Tmp_SS = USART_Scanf(59); } usart1_transmit_string(": %d", Tmp_SS); #endif /* Return the value to store in RTC counter register */ return((Tmp_HH*3600 + Tmp_MM*60 + Tmp_SS)); }
zzqq5414-jk-rabbit
sw/all_demo/rtc.c
C
asf20
6,142
/* ********************************************************************************************************* * INCLUDE FILES ********************************************************************************************************* */ #include <stdio.h> #include "stm32f10x.h" #include <stm32f10x_spi.h> #include "hw_config.h" #include "spi.h" /* ------------------------------------------------------------------------------------------------- */ /* BSP SPI */ /* ------------------------------------------------------------------------------------------------- */ /* ------------------------------------------------------------------------------------------------- */ /* extern USART */ /* ------------------------------------------------------------------------------------------------- */ // SPI speed setting function // SpeedSet: // SPI_SPEED_2 2 frequency (SPI 36M @ sys 72M) // SPI_SPEED_4 4 frequency (SPI 18M @ sys 72M) // SPI_SPEED_8 8 frequency (SPI 9M @ sys 72M) // SPI_SPEED_16 16 frequency (SPI 4.5M @ sys 72M) // SPI_SPEED_256 256 frequency (SPI 281.25K @ sys 72M) void bsp_set_spi1_speed (u8 speed) { SPI1->CR1 &= 0XFFC7; // Fsck = Fcpu/256 switch (speed) { case SPI_SPEED_2: // Second division SPI1->CR1 |= 0<<3; // Fsck = Fpclk / 2 = 36Mhz break; case SPI_SPEED_4: // four-band SPI1-> CR1 |= 1<<3; // Fsck = Fpclk / 4 = 18Mhz break; case SPI_SPEED_8: // eighth of the frequency SPI1-> CR1 |= 2<<3; // Fsck = Fpclk / 8 = 9Mhz break; case SPI_SPEED_16: // sixteen frequency SPI1-> CR1 |= 3<<3; // Fsck = Fpclk/16 = 4.5Mhz break; case SPI_SPEED_256: // 256 frequency division SPI1-> CR1 |= 7<<3; // Fsck = Fpclk/16 = 281.25Khz break; } SPI1->CR1 |= 1<<6; // SPI devices enable } /******************************************************************************* * Function Name: bsp_readwritebyte_spi1 * Description: SPI read and write a single byte (to return after sending the data read in this Newsletter) * Input: u8 TxData the number to be sent * Output: None * Return: u8 RxData the number of received *******************************************************************************/ u8 bsp_readwritebyte_spi1 (u8 tx_data) { u8 retry=0; /* Loop while DR register in not emplty */ while (SPI_I2S_GetFlagStatus (SPI1, SPI_I2S_FLAG_TXE) == RESET) { retry++; if(retry>200) return 0; } /* Send byte through the SPI1 peripheral */ SPI_I2S_SendData (SPI1, tx_data); retry=0; /* Wait to receive a byte */ while (SPI_I2S_GetFlagStatus (SPI1, SPI_I2S_FLAG_RXNE) == RESET) { retry++; if(retry>200) return 0; } /* Return the byte read from the SPI bus */ return SPI_I2S_ReceiveData (SPI1); }
zzqq5414-jk-rabbit
sw/all_demo/spi.c
C
asf20
2,838
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : stm32f10x_it.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Main Interrupt Service Routines. * This file provides template for all exceptions handler * and peripherals interrupt service routine. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "stm32f10x_it.h" #include "usb_istr.h" #include "usb_lib.h" #include "usb_pwr.h" #include "platform_config.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************/ /* Cortex-M3 Processor Exceptions Handlers */ /******************************************************************************/ /******************************************************************************* * Function Name : NMI_Handler * Description : This function handles NMI exception. * Input : None * Output : None * Return : None *******************************************************************************/ void NMI_Handler(void) { } /******************************************************************************* * Function Name : HardFault_Handler * Description : This function handles Hard Fault exception. * Input : None * Output : None * Return : None *******************************************************************************/ void HardFault_Handler(void) { /* Go to infinite loop when Hard Fault exception occurs */ while (1) { } } /******************************************************************************* * Function Name : MemManage_Handler * Description : This function handles Memory Manage exception. * Input : None * Output : None * Return : None *******************************************************************************/ void MemManage_Handler(void) { /* Go to infinite loop when Memory Manage exception occurs */ while (1) { } } /******************************************************************************* * Function Name : BusFault_Handler * Description : This function handles Bus Fault exception. * Input : None * Output : None * Return : None *******************************************************************************/ void BusFault_Handler(void) { /* Go to infinite loop when Bus Fault exception occurs */ while (1) { } } /******************************************************************************* * Function Name : UsageFault_Handler * Description : This function handles Usage Fault exception. * Input : None * Output : None * Return : None *******************************************************************************/ void UsageFault_Handler(void) { /* Go to infinite loop when Usage Fault exception occurs */ while (1) { } } /******************************************************************************* * Function Name : SVC_Handler * Description : This function handles SVCall exception. * Input : None * Output : None * Return : None *******************************************************************************/ void SVC_Handler(void) { } /******************************************************************************* * Function Name : DebugMon_Handler * Description : This function handles Debug Monitor exception. * Input : None * Output : None * Return : None *******************************************************************************/ void DebugMon_Handler(void) { } /******************************************************************************* * Function Name : PendSV_Handler * Description : This function handles PendSVC exception. * Input : None * Output : None * Return : None *******************************************************************************/ void PendSV_Handler(void) { } /******************************************************************************* * Function Name : SysTick_Handler * Description : This function handles SysTick Handler. * Input : None * Output : None * Return : None *******************************************************************************/ void SysTick_Handler(void) { } /******************************************************************************/ /* STM32F10x Peripherals Interrupt Handlers */ /******************************************************************************/ #ifndef STM32F10X_CL /******************************************************************************* * Function Name : USB_LP_CAN1_RX0_IRQHandler * Description : This function handles USB Low Priority or CAN RX0 interrupts * requests. * Input : None * Output : None * Return : None *******************************************************************************/ void USB_LP_CAN1_RX0_IRQHandler(void) { USB_Istr(); } #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL /******************************************************************************* * Function Name : OTG_FS_WKUP_IRQHandler * Description : This function handles OTG WakeUp interrupt request. * Input : None * Output : None * Return : None *******************************************************************************/ void OTG_FS_WKUP_IRQHandler(void) { /* Initiate external resume sequence (1 step) */ // Resume(RESUME_EXTERNAL); // EXTI_ClearITPendingBit(EXTI_Line18); } #else /******************************************************************************* * Function Name : USBWakeUp_IRQHandler * Description : This function handles USB WakeUp interrupt request. * Input : None * Output : None * Return : None *******************************************************************************/ void USBWakeUp_IRQHandler(void) { // EXTI_ClearITPendingBit(EXTI_Line18); } #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL /******************************************************************************* * Function Name : OTG_FS_IRQHandler * Description : This function handles USB-On-The-Go FS global interrupt request. * Input : None * Output : None * Return : None *******************************************************************************/ void OTG_FS_IRQHandler(void) { STM32_PCD_OTG_ISR_Handler(); } #endif /* STM32F10X_CL */ /******************************************************************************/ /* STM32F10x Peripherals Interrupt Handlers */ /* Add here the Interrupt Handler for the used peripheral(s) (PPP), for the */ /* available peripheral interrupt handler's name please refer to the startup */ /* file (startup_stm32f10x_xx.s). */ /******************************************************************************/ /******************************************************************************* * Function Name : PPP_IRQHandler * Description : This function handles PPP interrupt request. * Input : None * Output : None * Return : None *******************************************************************************/ /*void PPP_IRQHandler(void) { }*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/stm32f10x_it.c
C
asf20
8,933
#ifndef KEY_PRESENT #define KEY_PRESENT #include "hw_config.h" #include <stm32f10x.h> typedef enum { key1User = 0x00, #ifdef STM32_MIDDLE_HW_VER1 key2User = 0x01, #endif keyMax } BSP_KEY_Def; #define KEY_USER_PORT GPIOA #define KEY1_USER_PIN GPIO_Pin_2 #ifdef STM32_MIDDLE_HW_VER1 #define KEY2_USER_PIN GPIO_Pin_8 #endif // KEY IRQ Pin define #define KEY_IRQ_PORT_SOURCE GPIO_PortSourceGPIOA #define KEY1_IRQ_PIN_SOURCE GPIO_PinSource2 #ifdef STM32_MIDDLE_HW_VER1 #define KEY2_IRQ_PIN_SOURCE GPIO_PinSource8 #endif // KEY IRQ External Line #define KEY1_IRQ_EXTI_Line EXTI_Line2 #ifdef STM32_MIDDLE_HW_VER1 #define KEY2_IRQ_EXTI_Line EXTI_Line8 #endif // KEY IRQ channel #define KEY1_IRQ_CHANNEL EXTI2_IRQn #ifdef STM32_MIDDLE_HW_VER1 #define KEY2_IRQ_CHANNEL EXTI9_5_IRQn #endif typedef struct { GPIO_TypeDef* gpio_reg; u16 pin; }bsp_key_group_type; typedef enum { extiKey1ServiceFunction = 0x00, #ifdef STM32_MIDDLE_HW_VER1 extiKey2ServiceFunction = 0x01, #endif extiKeyServiceFunctionMAX } exti_key_register_function_type; typedef void (*exti_key_register_function)(void); typedef struct _exti_key_service_function_type { exti_key_register_function_type service_type; exti_key_register_function run; } exti_key_service_function_type; // Camera EXTI typedef enum { extiCameraVsyncServiceFunction = 0x00, extiCameraPclkServiceFunction = 0x01, extiCameraHrefServiceFunction = 0x02, extiCameraServiceFunctionMAX } exti_camera_register_function_type; typedef void (*exti_camera_register_function)(void); typedef struct _exti_camera_service_function_type { exti_camera_register_function_type service_type; exti_camera_register_function run; } exti_camera_service_function_type; /* ------------------------------------------------------------------------------------------------- */ /* BSP KEY */ /* ------------------------------------------------------------------------------------------------- */ extern void register_exti_key_function(exti_key_register_function_type exti_key_fn_type, exti_key_register_function fn); extern void register_camera_key_function(exti_camera_register_function_type exti_camera_fn_type, exti_camera_register_function fn); extern void bsp_key_interrupt_init(void); extern void bsp_key_gpio_init(void); void EXTI0_IRQHandler(void); void EXTI2_IRQHandler(void); void EXTI4_IRQHandler(void); void EXTI9_5_IRQHandler(void); void EXTI15_10_IRQHandler(void); #endif
zzqq5414-jk-rabbit
sw/all_demo/key.h
C
asf20
2,594
#ifndef QUEUE_H #define QUEUE_H #include "hw_config.h" #include <stm32f10x.h> typedef struct struct_q_node { struct struct_q_node *prev; struct struct_q_node *next; s16 len; void* data; } q_node_type; typedef struct struct_q_list { struct struct_q_node *first; struct struct_q_node *last; struct struct_q_node *curr; s16 count; //int datasize; } q_list_type; extern void q_init_list(q_list_type* list); extern void q_add_tail(q_list_type* list, q_node_type* node); extern void q_add_head(q_list_type* list, q_node_type* node); extern void q_remove_node(q_list_type* list, q_node_type* node); extern q_node_type* q_remove_head(q_list_type* list); extern q_node_type* q_remove_tail(q_list_type* list); extern void q_remove_all(q_list_type* list); s16 q_get_count(q_list_type* list); #endif /* QUEUE_H */
zzqq5414-jk-rabbit
sw/all_demo/queue.h
C
asf20
860
/* ********************************************************************************************************* * INCLUDE FILES ********************************************************************************************************* */ #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdarg.h> #include "stm32f10x.h" #include "hw_config.h" #include "queue.h" #include "usart.h" // setting USART #define USART_TX_BUFF_CNT 64 #define USART_RX_BUFF_CNT 10 #define USART_TX_DMA_SIZ 64 #define USART_RX_DMA_SIZ 64 q_list_type gbl_qlist_usart1_tx; q_list_type gbl_qlist_usart1_tx_free; q_node_type gbl_qdata_usart1_tx[USART_TX_BUFF_CNT]; q_node_type gbl_qdata_usart1_tx_free[USART_TX_BUFF_CNT]; char gbl_usart1_tx_buff[USART_TX_BUFF_CNT][USART_TX_DMA_SIZ]; char gbl_usart1_tx_buff_dma[USART_TX_DMA_SIZ]; q_list_type gbl_qlist_usart1_rx; q_list_type gbl_qlist_usart1_rx_free; q_node_type gbl_qdata_usart1_rx[USART_RX_BUFF_CNT]; q_node_type gbl_qdata_usart1_rx_free[USART_RX_BUFF_CNT]; char gbl_usart1_rx_buff[USART_RX_BUFF_CNT][USART_RX_DMA_SIZ]; char gbl_usart1_rx_buff_dma[USART_RX_DMA_SIZ]; static u16 s_usart1_tx_send_cnt = 0; static u16 s_usart1_tx_q_free_cnt = 0; static u16 s_usart1_tx_q_send_cnt = 0; static s8 usart_format_buff[128]; #if 1 typedef struct { u16 wr_idx; u16 rd_idx; char buffer[USART_RX_DMA_SIZ]; }usart_rx_type; usart_rx_type gbl_usart1_rx_buff_proc; #endif u16 usart1_dma_transfering = FALSE; // static usartmode_type s_usart1_mode = usartmodeIRQ; /* ------------------------------------------------------------------------------------------------- */ /* BSP USART */ /* ------------------------------------------------------------------------------------------------- */ void init_usart1_buffer(void) { int i; q_remove_all(&gbl_qlist_usart1_tx); q_remove_all(&gbl_qlist_usart1_tx_free); // initialize usart tx queue buffer. for(i=0;i<USART_TX_BUFF_CNT;i++) { gbl_qdata_usart1_tx_free[i].data = &gbl_usart1_tx_buff[i]; q_add_tail(&gbl_qlist_usart1_tx_free, &gbl_qdata_usart1_tx_free[i]); } q_remove_all(&gbl_qlist_usart1_rx); q_remove_all(&gbl_qlist_usart1_rx_free); // initialize usart rx queue buffer. for(i=0;i<USART_RX_BUFF_CNT;i++) { gbl_qdata_usart1_rx_free[i].data = &gbl_usart1_rx_buff[i]; q_add_tail(&gbl_qlist_usart1_rx_free, &gbl_qdata_usart1_rx_free[i]); } memset(gbl_usart1_tx_buff_dma, 0x00, sizeof(char)*USART_TX_DMA_SIZ); memset(gbl_usart1_rx_buff_dma, 0x00, sizeof(char)*USART_RX_DMA_SIZ); memset(gbl_usart1_rx_buff_proc.buffer, 0x00, sizeof(char)*USART_RX_DMA_SIZ); gbl_usart1_rx_buff_proc.rd_idx = 0; gbl_usart1_rx_buff_proc.wr_idx = 0; usart1_dma_transfering = FALSE; } void usart_transmit_byte( USART_TypeDef* port, u16 chr) { USART_SendData(port, chr); while (USART_GetFlagStatus(port, USART_FLAG_TXE) == RESET) ; } void usart1_transmit_byte(u16 chr) { usart_transmit_byte(USART1, chr); } void usart1_tx_proc(void) { int i; u16 data_len; // char tx_data[USART_TX_DMA_SIZ]; q_node_type* q_usart_pkt_ptr; if( s_usart1_mode == usartmodeIRQ ) { while( (q_usart_pkt_ptr = q_remove_tail(&gbl_qlist_usart1_tx)) != NULL ) { data_len = q_usart_pkt_ptr->len; memcpy(gbl_usart1_tx_buff_dma, q_usart_pkt_ptr->data, q_usart_pkt_ptr->len); for(i=0;i<data_len;i++) { usart_transmit_byte(USART1, (u16)gbl_usart1_tx_buff_dma[i]); } q_add_tail(&gbl_qlist_usart1_tx_free, q_usart_pkt_ptr); } } } void usart_transmit_string(USART_TypeDef* port, const void *data) { int i; u16 data_len; int tx_count; const char* usart_data; q_node_type* q_usart_pkt_ptr; usart_data = (char*)data; data_len = strlen(usart_data); tx_count = (data_len - 1) / USART_TX_DMA_SIZ + 1; INTLOCK(); if( q_get_count(&gbl_qlist_usart1_tx_free) >= tx_count ) { for(i=0;i<tx_count-1;i++) { if( (q_usart_pkt_ptr = q_remove_tail(&gbl_qlist_usart1_tx_free)) != NULL ) { memcpy(q_usart_pkt_ptr->data, usart_data, USART_TX_DMA_SIZ); q_usart_pkt_ptr->len = USART_TX_DMA_SIZ; q_add_tail(&gbl_qlist_usart1_tx, q_usart_pkt_ptr); data_len = data_len - USART_TX_DMA_SIZ; usart_data += USART_TX_DMA_SIZ; } } if( (q_usart_pkt_ptr = q_remove_tail(&gbl_qlist_usart1_tx_free)) != NULL ) { memcpy(q_usart_pkt_ptr->data, usart_data, data_len); q_usart_pkt_ptr->len = data_len; q_add_tail(&gbl_qlist_usart1_tx, q_usart_pkt_ptr); } if( usart1_dma_transfering == FALSE ) usart1_tx_proc(); } INTFREE(); } void usart1_transmit_string(const void *data) { usart_transmit_string(USART1, data); } void usart1_transmit_string_format(const char * szFormat, ... ) { va_list varpars; int nLen; va_start(varpars, szFormat); nLen = vsprintf( (char*)usart_format_buff, szFormat, varpars); va_end(varpars); usart_format_buff[nLen] = 0x00; usart_transmit_string(USART1, usart_format_buff); } void bsp_init_irq_usart1(void/*isr_function usart1_isr*/) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; init_usart1_buffer(); /* Enable the USART1 Interrupt */ NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); /* USART1_REMAP USART1 remapping This bit is set and cleared by software. It controls the mapping of USART1 TX and RX alternate functions on the GPIO ports. 0: No remap (TX/PA9, RX/PA10) 1: Remap (TX/PB6, RX/PB7) */ // GPIO_PinRemapConfig(GPIO_Remap_USART1, ENABLE); /* Configure the GPIO ports( USART1 Transmit and Receive Lines) */ /* Configure the USART1_Tx as Alternate function Push-Pull */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &GPIO_InitStructure); /* Configure the USART1_Rx as input floating */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &GPIO_InitStructure); /* Configure the USART1 */ USART_InitStructure.USART_BaudRate = 115200; USART_InitStructure.USART_WordLength = USART_WordLength_8b; USART_InitStructure.USART_StopBits = USART_StopBits_1; USART_InitStructure.USART_Parity = USART_Parity_No; USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(USART1, &USART_InitStructure); USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); /* Enable the USART1 */ USART_Cmd(USART1, ENABLE); s_usart1_mode = usartmodeIRQ; } /* ------------------------------------------------------------------------------------------------- */ /* extern USART */ /* ------------------------------------------------------------------------------------------------- */ void USART1_IRQHandler(void) { u16 data_len; q_node_type* q_usart_pkt_ptr; s8 data[1]; // u16 wr_idx; if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) { data_len = 1; if( q_get_count(&gbl_qlist_usart1_rx_free) > 0 ) { if( (q_usart_pkt_ptr = q_remove_tail(&gbl_qlist_usart1_rx_free)) != NULL ) { data[0] = USART_ReceiveData(USART1) & 0xFF; memcpy(q_usart_pkt_ptr->data, data, data_len); q_usart_pkt_ptr->len = data_len; q_add_tail(&gbl_qlist_usart1_rx, q_usart_pkt_ptr); } } USART_ClearITPendingBit(USART1, USART_IT_RXNE); } } int usart_is_ne(USART_TypeDef* port) { if( port == USART1 ) { //if( gbl_usart1_rx_buff.wr_idx == gbl_usart1_rx_buff.rd_idx ) if( q_get_count(&gbl_qlist_usart1_rx) == 0 ) return FALSE; else { return TRUE; } } return FALSE; } int usart1_is_ne(void) { return usart_is_ne(USART1); } void* usart1_get_data(void) { u16 data_len; q_node_type* q_usart_pkt_ptr; //byte data[1]; s_usart1_tx_q_free_cnt = q_get_count(&gbl_qlist_usart1_tx_free); s_usart1_tx_q_send_cnt = q_get_count(&gbl_qlist_usart1_tx); if( usart_is_ne(USART1) ) { if( (q_usart_pkt_ptr = q_remove_tail(&gbl_qlist_usart1_rx)) != NULL ) { data_len = q_usart_pkt_ptr->len; memcpy(gbl_usart1_rx_buff_proc.buffer, q_usart_pkt_ptr->data, q_usart_pkt_ptr->len); q_add_tail(&gbl_qlist_usart1_rx_free, q_usart_pkt_ptr); return gbl_usart1_rx_buff_proc.buffer; } } return NULL; }
zzqq5414-jk-rabbit
sw/all_demo/usart.c
C
asf20
8,898
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_pwr.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Connection/disconnection & power management ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" #include "usb_lib.h" #include "usb_conf.h" #include "usb_pwr.h" #include "hw_config.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint32_t bDeviceState = UNCONNECTED; /* USB device status */ __IO bool fSuspendEnabled = TRUE; /* true when suspend is possible */ struct { __IO RESUME_STATE eState; __IO uint8_t bESOFcnt; } ResumeS; /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Extern function prototypes ------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : PowerOn * Description : * Input : None. * Output : None. * Return : USB_SUCCESS. *******************************************************************************/ RESULT PowerOn(void) { #ifndef STM32F10X_CL u16 wRegVal; /*** cable plugged-in ? ***/ USB_Cable_Config(ENABLE); /*** CNTR_PWDN = 0 ***/ wRegVal = CNTR_FRES; _SetCNTR(wRegVal); /*** CNTR_FRES = 0 ***/ wInterrupt_Mask = 0; _SetCNTR(wInterrupt_Mask); /*** Clear pending interrupts ***/ _SetISTR(0); /*** Set interrupt mask ***/ wInterrupt_Mask = CNTR_RESETM | CNTR_SUSPM | CNTR_WKUPM; _SetCNTR(wInterrupt_Mask); #endif /* STM32F10X_CL */ return USB_SUCCESS; } /******************************************************************************* * Function Name : PowerOff * Description : handles switch-off conditions * Input : None. * Output : None. * Return : USB_SUCCESS. *******************************************************************************/ RESULT PowerOff() { #ifndef STM32F10X_CL /* disable all ints and force USB reset */ _SetCNTR(CNTR_FRES); /* clear interrupt status register */ _SetISTR(0); /* Disable the Pull-Up*/ USB_Cable_Config(DISABLE); /* switch-off device */ _SetCNTR(CNTR_FRES + CNTR_PDWN); /* sw variables reset */ /* ... */ #endif /* STM32F10X_CL */ return USB_SUCCESS; } /******************************************************************************* * Function Name : Suspend * Description : sets suspend mode operating conditions * Input : None. * Output : None. * Return : USB_SUCCESS. *******************************************************************************/ void Suspend(void) { #ifndef STM32F10X_CL u16 wCNTR; /* suspend preparation */ /* ... */ /* macrocell enters suspend mode */ wCNTR = _GetCNTR(); wCNTR |= CNTR_FSUSP; _SetCNTR(wCNTR); /* ------------------ ONLY WITH BUS-POWERED DEVICES ---------------------- */ /* power reduction */ /* ... on connected devices */ /* force low-power mode in the macrocell */ wCNTR = _GetCNTR(); wCNTR |= CNTR_LPMODE; _SetCNTR(wCNTR); #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL /* Gate the PHY and AHB USB clocks */ _OTGD_FS_GATE_PHYCLK; #endif /* STM32F10X_CL */ /* switch-off the clocks */ /* ... */ Enter_LowPowerMode(); } /******************************************************************************* * Function Name : Resume_Init * Description : Handles wake-up restoring normal operations * Input : None. * Output : None. * Return : USB_SUCCESS. *******************************************************************************/ void Resume_Init(void) { #ifndef STM32F10X_CL u16 wCNTR; #endif /* STM32F10X_CL */ /* ------------------ ONLY WITH BUS-POWERED DEVICES ---------------------- */ /* restart the clocks */ /* ... */ #ifndef STM32F10X_CL /* CNTR_LPMODE = 0 */ wCNTR = _GetCNTR(); wCNTR &= (~CNTR_LPMODE); _SetCNTR(wCNTR); #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL /* Ungate the PHY and AHB USB clocks */ _OTGD_FS_UNGATE_PHYCLK; #endif /* STM32F10X_CL */ /* restore full power */ /* ... on connected devices */ Leave_LowPowerMode(); #ifndef STM32F10X_CL /* reset FSUSP bit */ _SetCNTR(IMR_MSK); #endif /* STM32F10X_CL */ /* reverse suspend preparation */ /* ... */ } /******************************************************************************* * Function Name : Resume * Description : This is the state machine handling resume operations and * timing sequence. The control is based on the Resume structure * variables and on the ESOF interrupt calling this subroutine * without changing machine state. * Input : a state machine value (RESUME_STATE) * RESUME_ESOF doesn't change ResumeS.eState allowing * decrementing of the ESOF counter in different states. * Output : None. * Return : None. *******************************************************************************/ void Resume(RESUME_STATE eResumeSetVal) { #ifndef STM32F10X_CL u16 wCNTR; #endif /* STM32F10X_CL */ if (eResumeSetVal != RESUME_ESOF) ResumeS.eState = eResumeSetVal; switch (ResumeS.eState) { case RESUME_EXTERNAL: Resume_Init(); ResumeS.eState = RESUME_OFF; break; case RESUME_INTERNAL: Resume_Init(); ResumeS.eState = RESUME_START; break; case RESUME_LATER: ResumeS.bESOFcnt = 2; ResumeS.eState = RESUME_WAIT; break; case RESUME_WAIT: ResumeS.bESOFcnt--; if (ResumeS.bESOFcnt == 0) ResumeS.eState = RESUME_START; break; case RESUME_START: #ifdef STM32F10X_CL OTGD_FS_SetRemoteWakeup(); #else wCNTR = _GetCNTR(); wCNTR |= CNTR_RESUME; _SetCNTR(wCNTR); #endif /* STM32F10X_CL */ ResumeS.eState = RESUME_ON; ResumeS.bESOFcnt = 10; break; case RESUME_ON: #ifndef STM32F10X_CL ResumeS.bESOFcnt--; if (ResumeS.bESOFcnt == 0) { #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL OTGD_FS_ResetRemoteWakeup(); #else wCNTR = _GetCNTR(); wCNTR &= (~CNTR_RESUME); _SetCNTR(wCNTR); #endif /* STM32F10X_CL */ ResumeS.eState = RESUME_OFF; #ifndef STM32F10X_CL } #endif /* STM32F10X_CL */ break; case RESUME_OFF: case RESUME_ESOF: default: ResumeS.eState = RESUME_OFF; break; } } /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_pwr.c
C
asf20
8,008
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_prop.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : All processings related to Joystick Mouse Demo ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_conf.h" #include "usb_prop.h" #include "usb_desc.h" #include "usb_pwr.h" #include "hw_config.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ uint32_t ProtocolValue; /* -------------------------------------------------------------------------- */ /* Structures initializations */ /* -------------------------------------------------------------------------- */ DEVICE Device_Table = { EP_NUM, 1 }; DEVICE_PROP Device_Property = { Joystick_init, Joystick_Reset, Joystick_Status_In, Joystick_Status_Out, Joystick_Data_Setup, Joystick_NoData_Setup, Joystick_Get_Interface_Setting, Joystick_GetDeviceDescriptor, Joystick_GetConfigDescriptor, Joystick_GetStringDescriptor, 0, 0x40 /*MAX PACKET SIZE*/ }; USER_STANDARD_REQUESTS User_Standard_Requests = { Joystick_GetConfiguration, Joystick_SetConfiguration, Joystick_GetInterface, Joystick_SetInterface, Joystick_GetStatus, Joystick_ClearFeature, Joystick_SetEndPointFeature, Joystick_SetDeviceFeature, Joystick_SetDeviceAddress }; ONE_DESCRIPTOR Device_Descriptor = { (uint8_t*)Joystick_DeviceDescriptor, JOYSTICK_SIZ_DEVICE_DESC }; ONE_DESCRIPTOR Config_Descriptor = { (uint8_t*)Joystick_ConfigDescriptor, JOYSTICK_SIZ_CONFIG_DESC }; ONE_DESCRIPTOR Joystick_Report_Descriptor = { (uint8_t *)Joystick_ReportDescriptor, JOYSTICK_SIZ_REPORT_DESC }; ONE_DESCRIPTOR Mouse_Hid_Descriptor = { (uint8_t*)Joystick_ConfigDescriptor + JOYSTICK_OFF_HID_DESC, JOYSTICK_SIZ_HID_DESC }; ONE_DESCRIPTOR String_Descriptor[4] = { {(uint8_t*)Joystick_StringLangID, JOYSTICK_SIZ_STRING_LANGID}, {(uint8_t*)Joystick_StringVendor, JOYSTICK_SIZ_STRING_VENDOR}, {(uint8_t*)Joystick_StringProduct, JOYSTICK_SIZ_STRING_PRODUCT}, {(uint8_t*)Joystick_StringSerial, JOYSTICK_SIZ_STRING_SERIAL} }; /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Extern function prototypes ------------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : Joystick_init. * Description : Joystick Mouse init routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Joystick_init(void) { /* Update the serial number string descriptor with the data from the unique ID*/ Get_SerialNum(); pInformation->Current_Configuration = 0; /* Connect the device */ PowerOn(); /* Perform basic device initialization operations */ USB_SIL_Init(); bDeviceState = UNCONNECTED; } /******************************************************************************* * Function Name : Joystick_Reset. * Description : Joystick Mouse reset routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Joystick_Reset(void) { /* Set Joystick_DEVICE as not configured */ pInformation->Current_Configuration = 0; pInformation->Current_Interface = 0;/*the default Interface*/ /* Current Feature initialization */ pInformation->Current_Feature = Joystick_ConfigDescriptor[7]; #ifdef STM32F10X_CL /* EP0 is already configured in DFU_Init() by USB_SIL_Init() function */ /* Init EP1 IN as Interrupt endpoint */ OTG_DEV_EP_Init(EP1_IN, OTG_DEV_EP_TYPE_INT, 4); #else SetBTABLE(BTABLE_ADDRESS); /* Initialize Endpoint 0 */ SetEPType(ENDP0, EP_CONTROL); SetEPTxStatus(ENDP0, EP_TX_STALL); SetEPRxAddr(ENDP0, ENDP0_RXADDR); SetEPTxAddr(ENDP0, ENDP0_TXADDR); Clear_Status_Out(ENDP0); SetEPRxCount(ENDP0, Device_Property.MaxPacketSize); SetEPRxValid(ENDP0); /* Initialize Endpoint 1 */ SetEPType(ENDP1, EP_INTERRUPT); SetEPTxAddr(ENDP1, ENDP1_TXADDR); SetEPTxCount(ENDP1, 4); SetEPRxStatus(ENDP1, EP_RX_DIS); SetEPTxStatus(ENDP1, EP_TX_NAK); /* Set this device to response on default address */ SetDeviceAddress(0); #endif /* STM32F10X_CL */ bDeviceState = ATTACHED; } /******************************************************************************* * Function Name : Joystick_SetConfiguration. * Description : Udpade the device state to configured. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Joystick_SetConfiguration(void) { DEVICE_INFO *pInfo = &Device_Info; if (pInfo->Current_Configuration != 0) { /* Device configured */ bDeviceState = CONFIGURED; } } /******************************************************************************* * Function Name : Joystick_SetConfiguration. * Description : Udpade the device state to addressed. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Joystick_SetDeviceAddress (void) { bDeviceState = ADDRESSED; } /******************************************************************************* * Function Name : Joystick_Status_In. * Description : Joystick status IN routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Joystick_Status_In(void) {} /******************************************************************************* * Function Name : Joystick_Status_Out * Description : Joystick status OUT routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void Joystick_Status_Out (void) {} /******************************************************************************* * Function Name : Joystick_Data_Setup * Description : Handle the data class specific requests. * Input : Request Nb. * Output : None. * Return : USB_UNSUPPORT or USB_SUCCESS. *******************************************************************************/ RESULT Joystick_Data_Setup(uint8_t RequestNo) { uint8_t *(*CopyRoutine)(uint16_t); CopyRoutine = NULL; if ((RequestNo == GET_DESCRIPTOR) && (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT)) && (pInformation->USBwIndex0 == 0)) { if (pInformation->USBwValue1 == REPORT_DESCRIPTOR) { CopyRoutine = Joystick_GetReportDescriptor; } else if (pInformation->USBwValue1 == HID_DESCRIPTOR_TYPE) { CopyRoutine = Joystick_GetHIDDescriptor; } } /* End of GET_DESCRIPTOR */ /*** GET_PROTOCOL ***/ else if ((Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) && RequestNo == GET_PROTOCOL) { CopyRoutine = Joystick_GetProtocolValue; } if (CopyRoutine == NULL) { return USB_UNSUPPORT; } pInformation->Ctrl_Info.CopyData = CopyRoutine; pInformation->Ctrl_Info.Usb_wOffset = 0; (*CopyRoutine)(0); return USB_SUCCESS; } /******************************************************************************* * Function Name : Joystick_NoData_Setup * Description : handle the no data class specific requests * Input : Request Nb. * Output : None. * Return : USB_UNSUPPORT or USB_SUCCESS. *******************************************************************************/ RESULT Joystick_NoData_Setup(uint8_t RequestNo) { if ((Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT)) && (RequestNo == SET_PROTOCOL)) { return Joystick_SetProtocol(); } else { return USB_UNSUPPORT; } } /******************************************************************************* * Function Name : Joystick_GetDeviceDescriptor. * Description : Gets the device descriptor. * Input : Length * Output : None. * Return : The address of the device descriptor. *******************************************************************************/ uint8_t *Joystick_GetDeviceDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &Device_Descriptor); } /******************************************************************************* * Function Name : Joystick_GetConfigDescriptor. * Description : Gets the configuration descriptor. * Input : Length * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ uint8_t *Joystick_GetConfigDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &Config_Descriptor); } /******************************************************************************* * Function Name : Joystick_GetStringDescriptor * Description : Gets the string descriptors according to the needed index * Input : Length * Output : None. * Return : The address of the string descriptors. *******************************************************************************/ uint8_t *Joystick_GetStringDescriptor(uint16_t Length) { uint8_t wValue0 = pInformation->USBwValue0; if (wValue0 > 4) { return NULL; } else { return Standard_GetDescriptorData(Length, &String_Descriptor[wValue0]); } } /******************************************************************************* * Function Name : Joystick_GetReportDescriptor. * Description : Gets the HID report descriptor. * Input : Length * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ uint8_t *Joystick_GetReportDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &Joystick_Report_Descriptor); } /******************************************************************************* * Function Name : Joystick_GetHIDDescriptor. * Description : Gets the HID descriptor. * Input : Length * Output : None. * Return : The address of the configuration descriptor. *******************************************************************************/ uint8_t *Joystick_GetHIDDescriptor(uint16_t Length) { return Standard_GetDescriptorData(Length, &Mouse_Hid_Descriptor); } /******************************************************************************* * Function Name : Joystick_Get_Interface_Setting. * Description : tests the interface and the alternate setting according to the * supported one. * Input : - Interface : interface number. * - AlternateSetting : Alternate Setting number. * Output : None. * Return : USB_SUCCESS or USB_UNSUPPORT. *******************************************************************************/ RESULT Joystick_Get_Interface_Setting(uint8_t Interface, uint8_t AlternateSetting) { if (AlternateSetting > 0) { return USB_UNSUPPORT; } else if (Interface > 0) { return USB_UNSUPPORT; } return USB_SUCCESS; } /******************************************************************************* * Function Name : Joystick_SetProtocol * Description : Joystick Set Protocol request routine. * Input : None. * Output : None. * Return : USB SUCCESS. *******************************************************************************/ RESULT Joystick_SetProtocol(void) { uint8_t wValue0 = pInformation->USBwValue0; ProtocolValue = wValue0; return USB_SUCCESS; } /******************************************************************************* * Function Name : Joystick_GetProtocolValue * Description : get the protocol value * Input : Length. * Output : None. * Return : address of the protcol value. *******************************************************************************/ uint8_t *Joystick_GetProtocolValue(uint16_t Length) { if (Length == 0) { pInformation->Ctrl_Info.Usb_wLength = 1; return NULL; } else { return (uint8_t *)(&ProtocolValue); } } /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_prop.c
C
asf20
14,088
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_istr.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : This file includes the peripherals header files in the * user application. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_ISTR_H #define __USB_ISTR_H /* Includes ------------------------------------------------------------------*/ #include "usb_conf.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #ifndef STM32F10X_CL void USB_Istr(void); #else /* STM32F10X_CL */ u32 STM32_PCD_OTG_ISR_Handler(void); #endif /* STM32F10X_CL */ /* function prototypes Automatically built defining related macros */ void EP1_IN_Callback(void); void EP2_IN_Callback(void); void EP3_IN_Callback(void); void EP4_IN_Callback(void); void EP5_IN_Callback(void); void EP6_IN_Callback(void); void EP7_IN_Callback(void); void EP1_OUT_Callback(void); void EP2_OUT_Callback(void); void EP3_OUT_Callback(void); void EP4_OUT_Callback(void); void EP5_OUT_Callback(void); void EP6_OUT_Callback(void); void EP7_OUT_Callback(void); #ifndef STM32F10X_CL #ifdef CTR_CALLBACK void CTR_Callback(void); #endif #ifdef DOVR_CALLBACK void DOVR_Callback(void); #endif #ifdef ERR_CALLBACK void ERR_Callback(void); #endif #ifdef WKUP_CALLBACK void WKUP_Callback(void); #endif #ifdef SUSP_CALLBACK void SUSP_Callback(void); #endif #ifdef RESET_CALLBACK void RESET_Callback(void); #endif #ifdef SOF_CALLBACK void SOF_Callback(void); #endif #ifdef ESOF_CALLBACK void ESOF_Callback(void); #endif #else /* STM32F10X_CL */ /* Interrupt subroutines user callbacks prototypes. These callbacks are called into the respective interrupt sunroutine functinos and can be tailored for various user application purposes. Note: Make sure that the correspondant interrupt is enabled through the definition in usb_conf.h file */ void INTR_MODEMISMATCH_Callback(void); void INTR_SOFINTR_Callback(void); void INTR_RXSTSQLVL_Callback(void); void INTR_NPTXFEMPTY_Callback(void); void INTR_GINNAKEFF_Callback(void); void INTR_GOUTNAKEFF_Callback(void); void INTR_ERLYSUSPEND_Callback(void); void INTR_USBSUSPEND_Callback(void); void INTR_USBRESET_Callback(void); void INTR_ENUMDONE_Callback(void); void INTR_ISOOUTDROP_Callback(void); void INTR_EOPFRAME_Callback(void); void INTR_EPMISMATCH_Callback(void); void INTR_INEPINTR_Callback(void); void INTR_OUTEPINTR_Callback(void); void INTR_INCOMPLISOIN_Callback(void); void INTR_INCOMPLISOOUT_Callback(void); void INTR_WKUPINTR_Callback(void); /* Isochronous data update */ void INTR_RXSTSQLVL_ISODU_Callback(void); #endif /* STM32F10X_CL */ #endif /*__USB_ISTR_H*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_istr.h
C
asf20
3,903
#ifndef _SCCB_H #define _SCCB_H #include "stm32f10x.h" #define SCCB_USER_PORT GPIOE #define SCCB_SCL_PIN GPIO_Pin_7 #define SCCB_SDA_PIN GPIO_Pin_8 #define SCCB_SIO_C 7 // 4 SCL #define SCCB_SIO_D 8 // 5 SDA #define SIO_C_SET {GPIOE->BSRR =(1<<SCCB_SIO_C);} #define SIO_C_CLR {GPIOE->BRR = (1<<SCCB_SIO_C);} #define SIO_D_SET {GPIOE->BSRR =(1<<SCCB_SIO_D);} #define SIO_D_CLR {GPIOE->BRR = (1<<SCCB_SIO_D);} #define SIO_D_IN {GPIO_InitStructure.GPIO_Pin = SCCB_SDA_PIN;\ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;\ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;\ GPIO_Init(GPIOE, &GPIO_InitStructure); } #define SIO_D_OUT {GPIO_InitStructure.GPIO_Pin = SCCB_SDA_PIN;\ GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;\ GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;\ GPIO_Init(GPIOE, &GPIO_InitStructure);} #define SIO_D_STATE ((GPIOE->IDR&(1<<SCCB_SIO_D))==(1<<SCCB_SIO_D)) /////////////////////////////////////////// void DelaySCCB(void); void InitSCCB(void); void startSCCB(void); void stopSCCB(void); void noAck(void); u8 SCCBwriteByte(u8 m_data); u8 SCCBreadByte(void); #endif /* _SCCB_H */
zzqq5414-jk-rabbit
sw/all_demo/sccb.h
C
asf20
1,315
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_desc.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Descriptors for Joystick Mouse Demo ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_desc.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Extern variables ----------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* USB Standard Device Descriptor */ const uint8_t Joystick_DeviceDescriptor[JOYSTICK_SIZ_DEVICE_DESC] = { 0x12, /*bLength */ USB_DEVICE_DESCRIPTOR_TYPE, /*bDescriptorType*/ 0x00, /*bcdUSB */ 0x02, 0x00, /*bDeviceClass*/ 0x00, /*bDeviceSubClass*/ 0x00, /*bDeviceProtocol*/ 0x40, /*bMaxPacketSize 64*/ 0x83, /*idVendor (0x0483)*/ 0x04, 0x10, /*idProduct = 0x5710*/ 0x57, 0x00, /*bcdDevice rel. 2.00*/ 0x02, 1, /*Index of string descriptor describing manufacturer */ 2, /*Index of string descriptor describing product*/ 3, /*Index of string descriptor describing the device serial number */ 0x01 /*bNumConfigurations*/ } ; /* Joystick_DeviceDescriptor */ /* USB Configuration Descriptor */ /* All Descriptors (Configuration, Interface, Endpoint, Class, Vendor */ const uint8_t Joystick_ConfigDescriptor[JOYSTICK_SIZ_CONFIG_DESC] = { 0x09, /* bLength: Configuation Descriptor size */ USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType: Configuration */ JOYSTICK_SIZ_CONFIG_DESC, /* wTotalLength: Bytes returned */ 0x00, 0x01, /*bNumInterfaces: 1 interface*/ 0x01, /*bConfigurationValue: Configuration value*/ 0x00, /*iConfiguration: Index of string descriptor describing the configuration*/ 0xE0, /*bmAttributes: bus powered */ 0x32, /*MaxPower 100 mA: this current is used for detecting Vbus*/ /************** Descriptor of Joystick Mouse interface ****************/ /* 09 */ 0x09, /*bLength: Interface Descriptor size*/ USB_INTERFACE_DESCRIPTOR_TYPE,/*bDescriptorType: Interface descriptor type*/ 0x00, /*bInterfaceNumber: Number of Interface*/ 0x00, /*bAlternateSetting: Alternate setting*/ 0x01, /*bNumEndpoints*/ 0x03, /*bInterfaceClass: HID*/ 0x01, /*bInterfaceSubClass : 1=BOOT, 0=no boot*/ 0x02, /*nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse*/ 0, /*iInterface: Index of string descriptor*/ /******************** Descriptor of Joystick Mouse HID ********************/ /* 18 */ 0x09, /*bLength: HID Descriptor size*/ HID_DESCRIPTOR_TYPE, /*bDescriptorType: HID*/ 0x00, /*bcdHID: HID Class Spec release number*/ 0x01, 0x00, /*bCountryCode: Hardware target country*/ 0x01, /*bNumDescriptors: Number of HID class descriptors to follow*/ 0x22, /*bDescriptorType*/ JOYSTICK_SIZ_REPORT_DESC,/*wItemLength: Total length of Report descriptor*/ 0x00, /******************** Descriptor of Joystick Mouse endpoint ********************/ /* 27 */ 0x07, /*bLength: Endpoint Descriptor size*/ USB_ENDPOINT_DESCRIPTOR_TYPE, /*bDescriptorType:*/ 0x81, /*bEndpointAddress: Endpoint Address (IN)*/ 0x03, /*bmAttributes: Interrupt endpoint*/ 0x04, /*wMaxPacketSize: 4 Byte max */ 0x00, 0x20, /*bInterval: Polling Interval (32 ms)*/ /* 34 */ } ; /* MOUSE_ConfigDescriptor */ const uint8_t Joystick_ReportDescriptor[JOYSTICK_SIZ_REPORT_DESC] = { 0x05, /*Usage Page(Generic Desktop)*/ 0x01, 0x09, /*Usage(Mouse)*/ 0x02, 0xA1, /*Collection(Logical)*/ 0x01, 0x09, /*Usage(Pointer)*/ 0x01, /* 8 */ 0xA1, /*Collection(Linked)*/ 0x00, 0x05, /*Usage Page(Buttons)*/ 0x09, 0x19, /*Usage Minimum(1)*/ 0x01, 0x29, /*Usage Maximum(3)*/ 0x03, /* 16 */ 0x15, /*Logical Minimum(0)*/ 0x00, 0x25, /*Logical Maximum(1)*/ 0x01, 0x95, /*Report Count(3)*/ 0x03, 0x75, /*Report Size(1)*/ 0x01, /* 24 */ 0x81, /*Input(Variable)*/ 0x02, 0x95, /*Report Count(1)*/ 0x01, 0x75, /*Report Size(5)*/ 0x05, 0x81, /*Input(Constant,Array)*/ 0x01, /* 32 */ 0x05, /*Usage Page(Generic Desktop)*/ 0x01, 0x09, /*Usage(X axis)*/ 0x30, 0x09, /*Usage(Y axis)*/ 0x31, 0x09, /*Usage(Wheel)*/ 0x38, /* 40 */ 0x15, /*Logical Minimum(-127)*/ 0x81, 0x25, /*Logical Maximum(127)*/ 0x7F, 0x75, /*Report Size(8)*/ 0x08, 0x95, /*Report Count(3)*/ 0x03, /* 48 */ 0x81, /*Input(Variable, Relative)*/ 0x06, 0xC0, /*End Collection*/ 0x09, 0x3c, 0x05, 0xff, 0x09, /* 56 */ 0x01, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, /* 64 */ 0x02, 0xb1, 0x22, 0x75, 0x06, 0x95, 0x01, 0xb1, /* 72 */ 0x01, 0xc0 } ; /* Joystick_ReportDescriptor */ /* USB String Descriptors (optional) */ const uint8_t Joystick_StringLangID[JOYSTICK_SIZ_STRING_LANGID] = { JOYSTICK_SIZ_STRING_LANGID, USB_STRING_DESCRIPTOR_TYPE, 0x09, 0x04 } ; /* LangID = 0x0409: U.S. English */ const uint8_t Joystick_StringVendor[JOYSTICK_SIZ_STRING_VENDOR] = { JOYSTICK_SIZ_STRING_VENDOR, /* Size of Vendor string */ USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType*/ /* Manufacturer: "STMicroelectronics" */ 'J', 0, 'K', 0, 'E', 0, 'l', 0, 'e', 0, 'c', 0, 't', 0, 'r', 0, 'o', 0, 'n', 0, 'i', 0, 'c', 0, 's', 0 }; const uint8_t Joystick_StringProduct[JOYSTICK_SIZ_STRING_PRODUCT] = { JOYSTICK_SIZ_STRING_PRODUCT, /* bLength */ USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */ 'J', 0, 'K', 0, ' ', 0, '3', 0, '2', 0, ' ', 0, 'J', 0, 'o', 0, 'y', 0, 's', 0, 't', 0, 'i', 0, 'c', 0, 'k', 0 }; uint8_t Joystick_StringSerial[JOYSTICK_SIZ_STRING_SERIAL] = { JOYSTICK_SIZ_STRING_SERIAL, /* bLength */ USB_STRING_DESCRIPTOR_TYPE, /* bDescriptorType */ 'J', 0, 'K', 0, ' ', 0, '3', 0, '2', 0, '1', 0, '0', 0 }; /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_desc.c
C
asf20
8,420
#ifndef __FONT_H #define __FONT_H // Common ASCII table // offset 32 // ASCII character set // offset 32 // Size: 12 * 6 const unsigned char asc2_1206[95][12]={ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*" ",0*/ {0x00,0x00,0x04,0x04,0x04,0x04,0x04,0x04,0x00,0x04,0x00,0x00},/*"!",1*/ {0x00,0x14,0x0A,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*""",2*/ {0x00,0x00,0x14,0x14,0x3F,0x14,0x0A,0x3F,0x0A,0x0A,0x00,0x00},/*"#",3*/ {0x00,0x04,0x1E,0x15,0x05,0x06,0x0C,0x14,0x15,0x0F,0x04,0x00},/*"$",4*/ {0x00,0x00,0x12,0x15,0x0D,0x0A,0x14,0x2C,0x2A,0x12,0x00,0x00},/*"%",5*/ {0x00,0x00,0x04,0x0A,0x0A,0x1E,0x15,0x15,0x09,0x36,0x00,0x00},/*"&",6*/ {0x00,0x02,0x02,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"'",7*/ {0x00,0x20,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x20,0x00},/*"(",8*/ {0x00,0x02,0x04,0x08,0x08,0x08,0x08,0x08,0x08,0x04,0x02,0x00},/*")",9*/ {0x00,0x00,0x00,0x04,0x15,0x0E,0x0E,0x15,0x04,0x00,0x00,0x00},/*"*",10*/ {0x00,0x00,0x04,0x04,0x04,0x1F,0x04,0x04,0x04,0x00,0x00,0x00},/*"+",11*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x02,0x01},/*",",12*/ {0x00,0x00,0x00,0x00,0x00,0x1F,0x00,0x00,0x00,0x00,0x00,0x00},/*"-",13*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x02,0x00,0x00},/*".",14*/ {0x00,0x10,0x08,0x08,0x08,0x04,0x04,0x02,0x02,0x02,0x01,0x00},/*"/",15*/ {0x00,0x00,0x0E,0x11,0x11,0x11,0x11,0x11,0x11,0x0E,0x00,0x00},/*"0",16*/ {0x00,0x00,0x04,0x06,0x04,0x04,0x04,0x04,0x04,0x0E,0x00,0x00},/*"1",17*/ {0x00,0x00,0x0E,0x11,0x11,0x08,0x04,0x02,0x01,0x1F,0x00,0x00},/*"2",18*/ {0x00,0x00,0x0E,0x11,0x10,0x0C,0x10,0x10,0x11,0x0E,0x00,0x00},/*"3",19*/ {0x00,0x00,0x08,0x0C,0x0A,0x0A,0x09,0x1E,0x08,0x18,0x00,0x00},/*"4",20*/ {0x00,0x00,0x1F,0x01,0x01,0x0F,0x10,0x10,0x11,0x0E,0x00,0x00},/*"5",21*/ {0x00,0x00,0x0E,0x09,0x01,0x0F,0x11,0x11,0x11,0x0E,0x00,0x00},/*"6",22*/ {0x00,0x00,0x1F,0x09,0x08,0x04,0x04,0x04,0x04,0x04,0x00,0x00},/*"7",23*/ {0x00,0x00,0x0E,0x11,0x11,0x0E,0x11,0x11,0x11,0x0E,0x00,0x00},/*"8",24*/ {0x00,0x00,0x0E,0x11,0x11,0x11,0x1E,0x10,0x12,0x0E,0x00,0x00},/*"9",25*/ {0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x04,0x00,0x00},/*":",26*/ {0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x04,0x00},/*";",27*/ {0x00,0x20,0x10,0x08,0x04,0x02,0x04,0x08,0x10,0x20,0x00,0x00},/*"<",28*/ {0x00,0x00,0x00,0x00,0x1F,0x00,0x00,0x1F,0x00,0x00,0x00,0x00},/*"=",29*/ {0x00,0x02,0x04,0x08,0x10,0x20,0x10,0x08,0x04,0x02,0x00,0x00},/*">",30*/ {0x00,0x00,0x0E,0x11,0x11,0x08,0x04,0x04,0x00,0x04,0x00,0x00},/*"?",31*/ {0x00,0x00,0x0E,0x11,0x19,0x15,0x15,0x1D,0x01,0x1E,0x00,0x00},/*"@",32*/ {0x00,0x00,0x04,0x04,0x0C,0x0A,0x0A,0x1E,0x12,0x33,0x00,0x00},/*"A",33*/ {0x00,0x00,0x0F,0x12,0x12,0x0E,0x12,0x12,0x12,0x0F,0x00,0x00},/*"B",34*/ {0x00,0x00,0x1E,0x11,0x01,0x01,0x01,0x01,0x11,0x0E,0x00,0x00},/*"C",35*/ {0x00,0x00,0x0F,0x12,0x12,0x12,0x12,0x12,0x12,0x0F,0x00,0x00},/*"D",36*/ {0x00,0x00,0x1F,0x12,0x0A,0x0E,0x0A,0x02,0x12,0x1F,0x00,0x00},/*"E",37*/ {0x00,0x00,0x1F,0x12,0x0A,0x0E,0x0A,0x02,0x02,0x07,0x00,0x00},/*"F",38*/ {0x00,0x00,0x1C,0x12,0x01,0x01,0x39,0x11,0x12,0x0C,0x00,0x00},/*"G",39*/ {0x00,0x00,0x33,0x12,0x12,0x1E,0x12,0x12,0x12,0x33,0x00,0x00},/*"H",40*/ {0x00,0x00,0x1F,0x04,0x04,0x04,0x04,0x04,0x04,0x1F,0x00,0x00},/*"I",41*/ {0x00,0x00,0x3E,0x08,0x08,0x08,0x08,0x08,0x08,0x09,0x07,0x00},/*"J",42*/ {0x00,0x00,0x37,0x12,0x0A,0x06,0x0A,0x0A,0x12,0x37,0x00,0x00},/*"K",43*/ {0x00,0x00,0x07,0x02,0x02,0x02,0x02,0x02,0x22,0x3F,0x00,0x00},/*"L",44*/ {0x00,0x00,0x1B,0x1B,0x1B,0x1B,0x15,0x15,0x15,0x15,0x00,0x00},/*"M",45*/ {0x00,0x00,0x3B,0x12,0x16,0x16,0x1A,0x1A,0x12,0x17,0x00,0x00},/*"N",46*/ {0x00,0x00,0x0E,0x11,0x11,0x11,0x11,0x11,0x11,0x0E,0x00,0x00},/*"O",47*/ {0x00,0x00,0x0F,0x12,0x12,0x0E,0x02,0x02,0x02,0x07,0x00,0x00},/*"P",48*/ {0x00,0x00,0x0E,0x11,0x11,0x11,0x11,0x17,0x19,0x0E,0x18,0x00},/*"Q",49*/ {0x00,0x00,0x0F,0x12,0x12,0x0E,0x0A,0x12,0x12,0x37,0x00,0x00},/*"R",50*/ {0x00,0x00,0x1E,0x11,0x01,0x06,0x08,0x10,0x11,0x0F,0x00,0x00},/*"S",51*/ {0x00,0x00,0x1F,0x15,0x04,0x04,0x04,0x04,0x04,0x0E,0x00,0x00},/*"T",52*/ {0x00,0x00,0x33,0x12,0x12,0x12,0x12,0x12,0x12,0x0C,0x00,0x00},/*"U",53*/ {0x00,0x00,0x33,0x12,0x12,0x0A,0x0A,0x0C,0x04,0x04,0x00,0x00},/*"V",54*/ {0x00,0x00,0x15,0x15,0x15,0x0E,0x0A,0x0A,0x0A,0x0A,0x00,0x00},/*"W",55*/ {0x00,0x00,0x1B,0x0A,0x0A,0x04,0x04,0x0A,0x0A,0x1B,0x00,0x00},/*"X",56*/ {0x00,0x00,0x1B,0x0A,0x0A,0x04,0x04,0x04,0x04,0x0E,0x00,0x00},/*"Y",57*/ {0x00,0x00,0x1F,0x09,0x08,0x04,0x04,0x02,0x12,0x1F,0x00,0x00},/*"Z",58*/ {0x00,0x1C,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x04,0x1C,0x00},/*"[",59*/ {0x00,0x02,0x02,0x02,0x04,0x04,0x08,0x08,0x08,0x10,0x00,0x00},/*"\",60*/ {0x00,0x0E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x0E,0x00},/*"]",61*/ {0x00,0x04,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"^",62*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3F},/*"_",63*/ {0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"`",64*/ {0x00,0x00,0x00,0x00,0x00,0x0C,0x12,0x1C,0x12,0x3C,0x00,0x00},/*"a",65*/ {0x00,0x00,0x03,0x02,0x02,0x0E,0x12,0x12,0x12,0x0E,0x00,0x00},/*"b",66*/ {0x00,0x00,0x00,0x00,0x00,0x1C,0x12,0x02,0x02,0x1C,0x00,0x00},/*"c",67*/ {0x00,0x00,0x18,0x10,0x10,0x1C,0x12,0x12,0x12,0x3C,0x00,0x00},/*"d",68*/ {0x00,0x00,0x00,0x00,0x00,0x0C,0x12,0x1E,0x02,0x1C,0x00,0x00},/*"e",69*/ {0x00,0x00,0x38,0x04,0x04,0x1E,0x04,0x04,0x04,0x1E,0x00,0x00},/*"f",70*/ {0x00,0x00,0x00,0x00,0x00,0x3C,0x12,0x0C,0x02,0x1E,0x22,0x1C},/*"g",71*/ {0x00,0x00,0x03,0x02,0x02,0x0E,0x12,0x12,0x12,0x37,0x00,0x00},/*"h",72*/ {0x00,0x00,0x04,0x00,0x00,0x06,0x04,0x04,0x04,0x0E,0x00,0x00},/*"i",73*/ {0x00,0x00,0x08,0x00,0x00,0x0C,0x08,0x08,0x08,0x08,0x08,0x07},/*"j",74*/ {0x00,0x00,0x03,0x02,0x02,0x3A,0x0A,0x0E,0x12,0x37,0x00,0x00},/*"k",75*/ {0x00,0x00,0x07,0x04,0x04,0x04,0x04,0x04,0x04,0x1F,0x00,0x00},/*"l",76*/ {0x00,0x00,0x00,0x00,0x00,0x0F,0x15,0x15,0x15,0x15,0x00,0x00},/*"m",77*/ {0x00,0x00,0x00,0x00,0x00,0x0F,0x12,0x12,0x12,0x37,0x00,0x00},/*"n",78*/ {0x00,0x00,0x00,0x00,0x00,0x0C,0x12,0x12,0x12,0x0C,0x00,0x00},/*"o",79*/ {0x00,0x00,0x00,0x00,0x00,0x0F,0x12,0x12,0x12,0x0E,0x02,0x07},/*"p",80*/ {0x00,0x00,0x00,0x00,0x00,0x1C,0x12,0x12,0x12,0x1C,0x10,0x38},/*"q",81*/ {0x00,0x00,0x00,0x00,0x00,0x1B,0x06,0x02,0x02,0x07,0x00,0x00},/*"r",82*/ {0x00,0x00,0x00,0x00,0x00,0x1E,0x02,0x0C,0x10,0x1E,0x00,0x00},/*"s",83*/ {0x00,0x00,0x00,0x04,0x04,0x0E,0x04,0x04,0x04,0x18,0x00,0x00},/*"t",84*/ {0x00,0x00,0x00,0x00,0x00,0x1B,0x12,0x12,0x12,0x3C,0x00,0x00},/*"u",85*/ {0x00,0x00,0x00,0x00,0x00,0x37,0x12,0x0A,0x0C,0x04,0x00,0x00},/*"v",86*/ {0x00,0x00,0x00,0x00,0x00,0x15,0x15,0x0E,0x0A,0x0A,0x00,0x00},/*"w",87*/ {0x00,0x00,0x00,0x00,0x00,0x1B,0x0A,0x04,0x0A,0x1B,0x00,0x00},/*"x",88*/ {0x00,0x00,0x00,0x00,0x00,0x37,0x12,0x0A,0x0C,0x04,0x04,0x03},/*"y",89*/ {0x00,0x00,0x00,0x00,0x00,0x1E,0x08,0x04,0x04,0x1E,0x00,0x00},/*"z",90*/ {0x00,0x18,0x08,0x08,0x08,0x04,0x08,0x08,0x08,0x08,0x18,0x00},/*"{",91*/ {0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08},/*"|",92*/ {0x00,0x06,0x04,0x04,0x04,0x08,0x04,0x04,0x04,0x04,0x06,0x00},/*"}",93*/ {0x02,0x25,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00} /*"~",94*/ }; const unsigned char asc2_1608[95][16]={ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*" ",0*/ {0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00,0x18,0x18,0x00,0x00},/*"!",1*/ {0x00,0x48,0x6C,0x24,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*""",2*/ {0x00,0x00,0x00,0x24,0x24,0x24,0x7F,0x12,0x12,0x12,0x7F,0x12,0x12,0x12,0x00,0x00},/*"#",3*/ {0x00,0x00,0x08,0x1C,0x2A,0x2A,0x0A,0x0C,0x18,0x28,0x28,0x2A,0x2A,0x1C,0x08,0x08},/*"$",4*/ {0x00,0x00,0x00,0x22,0x25,0x15,0x15,0x15,0x2A,0x58,0x54,0x54,0x54,0x22,0x00,0x00},/*"%",5*/ {0x00,0x00,0x00,0x0C,0x12,0x12,0x12,0x0A,0x76,0x25,0x29,0x11,0x91,0x6E,0x00,0x00},/*"&",6*/ {0x00,0x06,0x06,0x04,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"'",7*/ {0x00,0x40,0x20,0x10,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x10,0x10,0x20,0x40,0x00},/*"(",8*/ {0x00,0x02,0x04,0x08,0x08,0x10,0x10,0x10,0x10,0x10,0x10,0x08,0x08,0x04,0x02,0x00},/*")",9*/ {0x00,0x00,0x00,0x00,0x08,0x08,0x6B,0x1C,0x1C,0x6B,0x08,0x08,0x00,0x00,0x00,0x00},/*"*",10*/ {0x00,0x00,0x00,0x00,0x08,0x08,0x08,0x08,0x7F,0x08,0x08,0x08,0x08,0x00,0x00,0x00},/*"+",11*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x04,0x03},/*",",12*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFE,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"-",13*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x06,0x00,0x00},/*".",14*/ {0x00,0x00,0x80,0x40,0x40,0x20,0x20,0x10,0x10,0x08,0x08,0x04,0x04,0x02,0x02,0x00},/*"/",15*/ {0x00,0x00,0x00,0x18,0x24,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x24,0x18,0x00,0x00},/*"0",16*/ {0x00,0x00,0x00,0x08,0x0E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00},/*"1",17*/ {0x00,0x00,0x00,0x3C,0x42,0x42,0x42,0x20,0x20,0x10,0x08,0x04,0x42,0x7E,0x00,0x00},/*"2",18*/ {0x00,0x00,0x00,0x3C,0x42,0x42,0x20,0x18,0x20,0x40,0x40,0x42,0x22,0x1C,0x00,0x00},/*"3",19*/ {0x00,0x00,0x00,0x20,0x30,0x28,0x24,0x24,0x22,0x22,0x7E,0x20,0x20,0x78,0x00,0x00},/*"4",20*/ {0x00,0x00,0x00,0x7E,0x02,0x02,0x02,0x1A,0x26,0x40,0x40,0x42,0x22,0x1C,0x00,0x00},/*"5",21*/ {0x00,0x00,0x00,0x38,0x24,0x02,0x02,0x1A,0x26,0x42,0x42,0x42,0x24,0x18,0x00,0x00},/*"6",22*/ {0x00,0x00,0x00,0x7E,0x22,0x22,0x10,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x00,0x00},/*"7",23*/ {0x00,0x00,0x00,0x3C,0x42,0x42,0x42,0x24,0x18,0x24,0x42,0x42,0x42,0x3C,0x00,0x00},/*"8",24*/ {0x00,0x00,0x00,0x18,0x24,0x42,0x42,0x42,0x64,0x58,0x40,0x40,0x24,0x1C,0x00,0x00},/*"9",25*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00,0x00,0x00,0x18,0x18,0x00,0x00},/*":",26*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x08,0x08,0x04},/*";",27*/ {0x00,0x00,0x00,0x40,0x20,0x10,0x08,0x04,0x02,0x04,0x08,0x10,0x20,0x40,0x00,0x00},/*"<",28*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0x00,0x00,0x00,0x7F,0x00,0x00,0x00,0x00,0x00},/*"=",29*/ {0x00,0x00,0x00,0x02,0x04,0x08,0x10,0x20,0x40,0x20,0x10,0x08,0x04,0x02,0x00,0x00},/*">",30*/ {0x00,0x00,0x00,0x3C,0x42,0x42,0x46,0x40,0x20,0x10,0x10,0x00,0x18,0x18,0x00,0x00},/*"?",31*/ {0x00,0x00,0x00,0x1C,0x22,0x5A,0x55,0x55,0x55,0x55,0x2D,0x42,0x22,0x1C,0x00,0x00},/*"@",32*/ {0x00,0x00,0x00,0x08,0x08,0x18,0x14,0x14,0x24,0x3C,0x22,0x42,0x42,0xE7,0x00,0x00},/*"A",33*/ {0x00,0x00,0x00,0x1F,0x22,0x22,0x22,0x1E,0x22,0x42,0x42,0x42,0x22,0x1F,0x00,0x00},/*"B",34*/ {0x00,0x00,0x00,0x7C,0x42,0x42,0x01,0x01,0x01,0x01,0x01,0x42,0x22,0x1C,0x00,0x00},/*"C",35*/ {0x00,0x00,0x00,0x1F,0x22,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x22,0x1F,0x00,0x00},/*"D",36*/ {0x00,0x00,0x00,0x3F,0x42,0x12,0x12,0x1E,0x12,0x12,0x02,0x42,0x42,0x3F,0x00,0x00},/*"E",37*/ {0x00,0x00,0x00,0x3F,0x42,0x12,0x12,0x1E,0x12,0x12,0x02,0x02,0x02,0x07,0x00,0x00},/*"F",38*/ {0x00,0x00,0x00,0x3C,0x22,0x22,0x01,0x01,0x01,0x71,0x21,0x22,0x22,0x1C,0x00,0x00},/*"G",39*/ {0x00,0x00,0x00,0xE7,0x42,0x42,0x42,0x42,0x7E,0x42,0x42,0x42,0x42,0xE7,0x00,0x00},/*"H",40*/ {0x00,0x00,0x00,0x3E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00},/*"I",41*/ {0x00,0x00,0x00,0x7C,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x11,0x0F},/*"J",42*/ {0x00,0x00,0x00,0x77,0x22,0x12,0x0A,0x0E,0x0A,0x12,0x12,0x22,0x22,0x77,0x00,0x00},/*"K",43*/ {0x00,0x00,0x00,0x07,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x42,0x7F,0x00,0x00},/*"L",44*/ {0x00,0x00,0x00,0x77,0x36,0x36,0x36,0x36,0x2A,0x2A,0x2A,0x2A,0x2A,0x6B,0x00,0x00},/*"M",45*/ {0x00,0x00,0x00,0xE3,0x46,0x46,0x4A,0x4A,0x52,0x52,0x52,0x62,0x62,0x47,0x00,0x00},/*"N",46*/ {0x00,0x00,0x00,0x1C,0x22,0x41,0x41,0x41,0x41,0x41,0x41,0x41,0x22,0x1C,0x00,0x00},/*"O",47*/ {0x00,0x00,0x00,0x3F,0x42,0x42,0x42,0x42,0x3E,0x02,0x02,0x02,0x02,0x07,0x00,0x00},/*"P",48*/ {0x00,0x00,0x00,0x1C,0x22,0x41,0x41,0x41,0x41,0x41,0x4D,0x53,0x32,0x1C,0x60,0x00},/*"Q",49*/ {0x00,0x00,0x00,0x3F,0x42,0x42,0x42,0x3E,0x12,0x12,0x22,0x22,0x42,0xC7,0x00,0x00},/*"R",50*/ {0x00,0x00,0x00,0x7C,0x42,0x42,0x02,0x04,0x18,0x20,0x40,0x42,0x42,0x3E,0x00,0x00},/*"S",51*/ {0x00,0x00,0x00,0x7F,0x49,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x1C,0x00,0x00},/*"T",52*/ {0x00,0x00,0x00,0xE7,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x42,0x3C,0x00,0x00},/*"U",53*/ {0x00,0x00,0x00,0xE7,0x42,0x42,0x22,0x24,0x24,0x14,0x14,0x18,0x08,0x08,0x00,0x00},/*"V",54*/ {0x00,0x00,0x00,0x6B,0x49,0x49,0x49,0x49,0x55,0x55,0x36,0x22,0x22,0x22,0x00,0x00},/*"W",55*/ {0x00,0x00,0x00,0xE7,0x42,0x24,0x24,0x18,0x18,0x18,0x24,0x24,0x42,0xE7,0x00,0x00},/*"X",56*/ {0x00,0x00,0x00,0x77,0x22,0x22,0x14,0x14,0x08,0x08,0x08,0x08,0x08,0x1C,0x00,0x00},/*"Y",57*/ {0x00,0x00,0x00,0x7E,0x21,0x20,0x10,0x10,0x08,0x04,0x04,0x42,0x42,0x3F,0x00,0x00},/*"Z",58*/ {0x00,0x78,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x78,0x00},/*"[",59*/ {0x00,0x00,0x02,0x02,0x04,0x04,0x08,0x08,0x08,0x10,0x10,0x20,0x20,0x20,0x40,0x40},/*"\",60*/ {0x00,0x1E,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x1E,0x00},/*"]",61*/ {0x00,0x38,0x44,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"^",62*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFF},/*"_",63*/ {0x00,0x06,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"`",64*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x42,0x78,0x44,0x42,0x42,0xFC,0x00,0x00},/*"a",65*/ {0x00,0x00,0x00,0x03,0x02,0x02,0x02,0x1A,0x26,0x42,0x42,0x42,0x26,0x1A,0x00,0x00},/*"b",66*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0x44,0x02,0x02,0x02,0x44,0x38,0x00,0x00},/*"c",67*/ {0x00,0x00,0x00,0x60,0x40,0x40,0x40,0x78,0x44,0x42,0x42,0x42,0x64,0xD8,0x00,0x00},/*"d",68*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x42,0x7E,0x02,0x02,0x42,0x3C,0x00,0x00},/*"e",69*/ {0x00,0x00,0x00,0xF0,0x88,0x08,0x08,0x7E,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00},/*"f",70*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C,0x22,0x22,0x1C,0x02,0x3C,0x42,0x42,0x3C},/*"g",71*/ {0x00,0x00,0x00,0x03,0x02,0x02,0x02,0x3A,0x46,0x42,0x42,0x42,0x42,0xE7,0x00,0x00},/*"h",72*/ {0x00,0x00,0x00,0x0C,0x0C,0x00,0x00,0x0E,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00},/*"i",73*/ {0x00,0x00,0x00,0x30,0x30,0x00,0x00,0x38,0x20,0x20,0x20,0x20,0x20,0x20,0x22,0x1E},/*"j",74*/ {0x00,0x00,0x00,0x03,0x02,0x02,0x02,0x72,0x12,0x0A,0x16,0x12,0x22,0x77,0x00,0x00},/*"k",75*/ {0x00,0x00,0x00,0x0E,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x3E,0x00,0x00},/*"l",76*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7F,0x92,0x92,0x92,0x92,0x92,0xB7,0x00,0x00},/*"m",77*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3B,0x46,0x42,0x42,0x42,0x42,0xE7,0x00,0x00},/*"n",78*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3C,0x42,0x42,0x42,0x42,0x42,0x3C,0x00,0x00},/*"o",79*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1B,0x26,0x42,0x42,0x42,0x22,0x1E,0x02,0x07},/*"p",80*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x78,0x44,0x42,0x42,0x42,0x44,0x78,0x40,0xE0},/*"q",81*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x77,0x4C,0x04,0x04,0x04,0x04,0x1F,0x00,0x00},/*"r",82*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7C,0x42,0x02,0x3C,0x40,0x42,0x3E,0x00,0x00},/*"s",83*/ {0x00,0x00,0x00,0x00,0x00,0x08,0x08,0x3E,0x08,0x08,0x08,0x08,0x08,0x30,0x00,0x00},/*"t",84*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x63,0x42,0x42,0x42,0x42,0x62,0xDC,0x00,0x00},/*"u",85*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE7,0x42,0x24,0x24,0x14,0x08,0x08,0x00,0x00},/*"v",86*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xEB,0x49,0x49,0x55,0x55,0x22,0x22,0x00,0x00},/*"w",87*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x76,0x24,0x18,0x18,0x18,0x24,0x6E,0x00,0x00},/*"x",88*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xE7,0x42,0x24,0x24,0x14,0x18,0x08,0x08,0x07},/*"y",89*/ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7E,0x22,0x10,0x08,0x08,0x44,0x7E,0x00,0x00},/*"z",90*/ {0x00,0xC0,0x20,0x20,0x20,0x20,0x20,0x10,0x20,0x20,0x20,0x20,0x20,0x20,0xC0,0x00},/*"{",91*/ {0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10},/*"|",92*/ {0x00,0x06,0x08,0x08,0x08,0x08,0x08,0x10,0x08,0x08,0x08,0x08,0x08,0x08,0x06,0x00},/*"}",93*/ {0x0C,0x32,0xC2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},/*"~",94*/ }; #endif
zzqq5414-jk-rabbit
sw/all_demo/font.h
C
asf20
16,180
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_conf.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Joystick Mouse demo configuration file ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_CONF_H #define __USB_CONF_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ /* External variables --------------------------------------------------------*/ /*-------------------------------------------------------------*/ /* EP_NUM */ /* defines how many endpoints are used by the device */ /*-------------------------------------------------------------*/ #define EP_NUM (2) #ifndef STM32F10X_CL /*-------------------------------------------------------------*/ /* -------------- Buffer Description Table -----------------*/ /*-------------------------------------------------------------*/ /* buffer table base address */ /* buffer table base address */ #define BTABLE_ADDRESS (0x00) /* EP0 */ /* rx/tx buffer base address */ #define ENDP0_RXADDR (0x18) #define ENDP0_TXADDR (0x58) /* EP1 */ /* tx buffer base address */ #define ENDP1_TXADDR (0x100) /*-------------------------------------------------------------*/ /* ------------------- ISTR events -------------------------*/ /*-------------------------------------------------------------*/ /* IMR_MSK */ /* mask defining which events has to be handled */ /* by the device application software */ #define IMR_MSK (CNTR_CTRM | CNTR_WKUPM | CNTR_SUSPM | CNTR_ERRM | CNTR_SOFM \ | CNTR_ESOFM | CNTR_RESETM ) #endif /* STM32F10X_CL */ #ifdef STM32F10X_CL /******************************************************************************* * FIFO Size Configuration * * (i) Dedicated data FIFO SPRAM of 1.25 Kbytes = 1280 bytes = 320 32-bits words * available for the endpoints IN and OUT. * Device mode features: * -1 bidirectional CTRL EP 0 * -3 IN EPs to support any kind of Bulk, Interrupt or Isochronous transfer * -3 OUT EPs to support any kind of Bulk, Interrupt or Isochronous transfer * * ii) Receive data FIFO size = RAM for setup packets + * OUT endpoint control information + * data OUT packets + miscellaneous * Space = ONE 32-bits words * --> RAM for setup packets = 4 * n + 6 space * (n is the nbr of CTRL EPs the device core supports) * --> OUT EP CTRL info = 1 space * (one space for status information written to the FIFO along with each * received packet) * --> data OUT packets = (Largest Packet Size / 4) + 1 spaces * (MINIMUM to receive packets) * --> OR data OUT packets = at least 2*(Largest Packet Size / 4) + 1 spaces * (if high-bandwidth EP is enabled or multiple isochronous EPs) * --> miscellaneous = 1 space per OUT EP * (one space for transfer complete status information also pushed to the * FIFO with each endpoint's last packet) * * (iii)MINIMUM RAM space required for each IN EP Tx FIFO = MAX packet size for * that particular IN EP. More space allocated in the IN EP Tx FIFO results * in a better performance on the USB and can hide latencies on the AHB. * * (iv) TXn min size = 16 words. (n : Transmit FIFO index) * (v) When a TxFIFO is not used, the Configuration should be as follows: * case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes) * --> Txm can use the space allocated for Txn. * case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes) * --> Txn should be configured with the minimum space of 16 words * (vi) The FIFO is used optimally when used TxFIFOs are allocated in the top * of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones. *******************************************************************************/ #define RX_FIFO_SIZE 128 #define TX0_FIFO_SIZE 64 #define TX1_FIFO_SIZE 64 #define TX2_FIFO_SIZE 16 #define TX3_FIFO_SIZE 16 /* OTGD-FS-DEVICE IP interrupts Enable definitions */ /* Uncomment the define to enable the selected interrupt */ //#define INTR_MODEMISMATCH //#define INTR_SOFINTR #define INTR_RXSTSQLVL /* Mandatory */ //#define INTR_NPTXFEMPTY //#define INTR_GINNAKEFF //#define INTR_GOUTNAKEFF #define INTR_ERLYSUSPEND #define INTR_USBSUSPEND /* Mandatory */ #define INTR_USBRESET /* Mandatory */ #define INTR_ENUMDONE /* Mandatory */ //#define INTR_ISOOUTDROP //#define INTR_EOPFRAME //#define INTR_EPMISMATCH #define INTR_INEPINTR /* Mandatory */ #define INTR_OUTEPINTR /* Mandatory */ //#define INTR_INCOMPLISOIN //#define INTR_INCOMPLISOOUT #define INTR_WKUPINTR /* Mandatory */ /* OTGD-FS-DEVICE IP interrupts subroutines */ /* Comment the define to enable the selected interrupt subroutine and replace it by user code */ #define INTR_MODEMISMATCH_Callback NOP_Process #define INTR_SOFINTR_Callback NOP_Process #define INTR_RXSTSQLVL_Callback NOP_Process #define INTR_NPTXFEMPTY_Callback NOP_Process #define INTR_NPTXFEMPTY_Callback NOP_Process #define INTR_GINNAKEFF_Callback NOP_Process #define INTR_GOUTNAKEFF_Callback NOP_Process #define INTR_ERLYSUSPEND_Callback NOP_Process #define INTR_USBSUSPEND_Callback NOP_Process #define INTR_USBRESET_Callback NOP_Process #define INTR_ENUMDONE_Callback NOP_Process #define INTR_ISOOUTDROP_Callback NOP_Process #define INTR_EOPFRAME_Callback NOP_Process #define INTR_EPMISMATCH_Callback NOP_Process #define INTR_INEPINTR_Callback NOP_Process #define INTR_OUTEPINTR_Callback NOP_Process #define INTR_INCOMPLISOIN_Callback NOP_Process #define INTR_INCOMPLISOOUT_Callback NOP_Process #define INTR_WKUPINTR_Callback NOP_Process /* Isochronous data update */ #define INTR_RXSTSQLVL_ISODU_Callback NOP_Process /* Isochronous transfer parameters */ /* Size of a single Isochronous buffer (size of a single transfer) */ #define ISOC_BUFFER_SZE 1 /* Number of sub-buffers (number of single buffers/transfers), should be even */ #define NUM_SUB_BUFFERS 2 #endif /* STM32F10X_CL */ /* CTR service routines */ /* associated to defined endpoints */ #define EP1_IN_Callback NOP_Process #define EP2_IN_Callback NOP_Process #define EP3_IN_Callback NOP_Process #define EP4_IN_Callback NOP_Process #define EP5_IN_Callback NOP_Process #define EP6_IN_Callback NOP_Process #define EP7_IN_Callback NOP_Process #define EP1_OUT_Callback NOP_Process #define EP2_OUT_Callback NOP_Process #define EP3_OUT_Callback NOP_Process #define EP4_OUT_Callback NOP_Process #define EP5_OUT_Callback NOP_Process #define EP6_OUT_Callback NOP_Process #define EP7_OUT_Callback NOP_Process #endif /*__USB_CONF_H*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/all_demo/usb_conf.h
C
asf20
8,480
/* /* * newlib_stubs.c * * Created on: 2 Nov 2010 * Author: nanoage.co.uk */ #include <errno.h> #include <sys/stat.h> #include <sys/times.h> #include <sys/unistd.h> #include "stm32f10x_usart.h" #ifndef STDOUT_USART #define STDOUT_USART 2 #endif #ifndef STDERR_USART #define STDERR_USART 2 #endif #ifndef STDIN_USART #define STDIN_USART 2 #endif #undef errno extern int errno; /* environ A pointer to a list of environment variables and their values. For a minimal environment, this empty list is adequate: */ char *__env[1] = { 0 }; char **environ = __env; int _write(int file, char *ptr, int len); void _exit(int status) { _write(1, "exit", 4); while (1) { ; } } int _close(int file) { return -1; } /* execve Transfer control to a new process. Minimal implementation (for a system without processes): */ int _execve(char *name, char **argv, char **env) { errno = ENOMEM; return -1; } /* fork Create a new process. Minimal implementation (for a system without processes): */ int _fork() { errno = EAGAIN; return -1; } /* fstat Status of an open file. For consistency with other minimal implementations in these examples, all files are regarded as character special devices. The `sys/stat.h' header file required is distributed in the `include' subdirectory for this C library. */ int _fstat(int file, struct stat *st) { st->st_mode = S_IFCHR; return 0; } /* getpid Process-ID; this is sometimes used to generate strings unlikely to conflict with other processes. Minimal implementation, for a system without processes: */ int _getpid() { return 1; } /* isatty Query whether output stream is a terminal. For consistency with the other minimal implementations, */ int _isatty(int file) { switch (file){ case STDOUT_FILENO: case STDERR_FILENO: case STDIN_FILENO: return 1; default: //errno = ENOTTY; errno = EBADF; return 0; } } /* kill Send a signal. Minimal implementation: */ int _kill(int pid, int sig) { errno = EINVAL; return (-1); } /* link Establish a new name for an existing file. Minimal implementation: */ int _link(char *old, char *new) { errno = EMLINK; return -1; } /* lseek Set position in a file. Minimal implementation: */ int _lseek(int file, int ptr, int dir) { return 0; } /* sbrk Increase program data space. Malloc and related functions depend on this */ caddr_t _sbrk(int incr) { extern char _ebss; // Defined by the linker static char *heap_end; char *prev_heap_end; if (heap_end == 0) { heap_end = &_ebss; } prev_heap_end = heap_end; char * stack = (char*) __get_MSP(); if (heap_end + incr > stack) { _write (STDERR_FILENO, "Heap and stack collision\n", 25); errno = ENOMEM; return (caddr_t) -1; //abort (); } heap_end += incr; return (caddr_t) prev_heap_end; } /* read Read a character to a file. `libc' subroutines will use this system routine for input from all files, including stdin Returns -1 on error or blocks until the number of characters have been read. */ int _read(int file, char *ptr, int len) { int n; int num = 0; switch (file) { case STDIN_FILENO: for (n = 0; n < len; n++) { #if STDIN_USART == 1 while ((USART1->SR & USART_FLAG_RXNE) == (uint16_t)RESET) {} char c = (char)(USART1->DR & (uint16_t)0x01FF); #elif STDIN_USART == 2 while ((USART2->SR & USART_FLAG_RXNE) == (uint16_t) RESET) {} char c = (char) (USART2->DR & (uint16_t) 0x01FF); #elif STDIN_USART == 3 while ((USART3->SR & USART_FLAG_RXNE) == (uint16_t)RESET) {} char c = (char)(USART3->DR & (uint16_t)0x01FF); #endif *ptr++ = c; num++; } break; default: errno = EBADF; return -1; } return num; } /* stat Status of a file (by name). Minimal implementation: int _EXFUN(stat,( const char *__path, struct stat *__sbuf )); */ int _stat(const char *filepath, struct stat *st) { st->st_mode = S_IFCHR; return 0; } /* times Timing information for current process. Minimal implementation: */ clock_t _times(struct tms *buf) { return -1; } /* unlink Remove a file's directory entry. Minimal implementation: */ int _unlink(char *name) { errno = ENOENT; return -1; } /* wait Wait for a child process. Minimal implementation: */ int _wait(int *status) { errno = ECHILD; return -1; } /* write Write a character to a file. `libc' subroutines will use this system routine for output to all files, including stdout Returns -1 on error or number of bytes sent */ int _write(int file, char *ptr, int len) { int n; switch (file) { case STDOUT_FILENO: /*stdout*/ for (n = 0; n < len; n++) { #if STDOUT_USART == 1 while ((USART1->SR & USART_FLAG_TC) == (uint16_t)RESET) {} USART1->DR = (*ptr++ & (uint16_t)0x01FF); #elif STDOUT_USART == 2 while ((USART2->SR & USART_FLAG_TC) == (uint16_t) RESET) { } USART2->DR = (*ptr++ & (uint16_t) 0x01FF); #elif STDOUT_USART == 3 while ((USART3->SR & USART_FLAG_TC) == (uint16_t)RESET) {} USART3->DR = (*ptr++ & (uint16_t)0x01FF); #endif } break; case STDERR_FILENO: /* stderr */ for (n = 0; n < len; n++) { #if STDERR_USART == 1 while ((USART1->SR & USART_FLAG_TC) == (uint16_t)RESET) {} USART1->DR = (*ptr++ & (uint16_t)0x01FF); #elif STDERR_USART == 2 while ((USART2->SR & USART_FLAG_TC) == (uint16_t) RESET) { } USART2->DR = (*ptr++ & (uint16_t) 0x01FF); #elif STDERR_USART == 3 while ((USART3->SR & USART_FLAG_TC) == (uint16_t)RESET) {} USART3->DR = (*ptr++ & (uint16_t)0x01FF); #endif } break; default: errno = EBADF; return -1; } return len; }
zzqq5414-jk-rabbit
sw/all_demo/newlib_stubs.c
C
asf20
6,327
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_pwr.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Connection/disconnection & power management header ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_PWR_H #define __USB_PWR_H /* Includes ------------------------------------------------------------------*/ #include "usb_core.h" /* Exported types ------------------------------------------------------------*/ typedef enum _RESUME_STATE { RESUME_EXTERNAL, RESUME_INTERNAL, RESUME_LATER, RESUME_WAIT, RESUME_START, RESUME_ON, RESUME_OFF, RESUME_ESOF } RESUME_STATE; typedef enum _DEVICE_STATE { UNCONNECTED, ATTACHED, POWERED, SUSPENDED, ADDRESSED, CONFIGURED } DEVICE_STATE; /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Suspend(void); void Resume_Init(void); void Resume(RESUME_STATE eResumeSetVal); RESULT PowerOn(void); RESULT PowerOff(void); /* External variables --------------------------------------------------------*/ extern __IO uint32_t bDeviceState; /* USB device status */ extern __IO bool fSuspendEnabled; /* true when suspend is possible */ #endif /*__USB_PWR_H*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_pwr.h
C
asf20
2,265
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : memory.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Memory management layer ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __memory_H #define __memory_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ #define TXFR_IDLE 0 #define TXFR_ONGOING 1 /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Write_Memory (uint8_t lun, uint32_t Memory_Offset, uint32_t Transfer_Length); void Read_Memory (uint8_t lun, uint32_t Memory_Offset, uint32_t Transfer_Length); #endif /* __memory_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/memory.h
C
asf20
1,788
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : nand_if.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : All functions related to the NAND process ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __NAND_IF_H #define __NAND_IF_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ #define NAND_OK 0 #define NAND_FAIL 1 #define FREE_BLOCK (1 << 12 ) #define BAD_BLOCK (1 << 13 ) #define VALID_BLOCK (1 << 14 ) #define USED_BLOCK (1 << 15 ) #define MAX_PHY_BLOCKS_PER_ZONE 1024 #define MAX_LOG_BLOCKS_PER_ZONE 1000 /* Private Structures---------------------------------------------------------*/ typedef struct __SPARE_AREA { uint16_t LogicalIndex; uint16_t DataStatus; uint16_t BlockStatus; } SPARE_AREA; typedef enum { WRITE_IDLE = 0, POST_WRITE, PRE_WRITE, WRITE_CLEANUP, WRITE_ONGOING }WRITE_STATE; typedef enum { OLD_BLOCK = 0, UNUSED_BLOCK }BLOCK_STATE; /* Private macro --------------------------------------------------------------*/ //#define WEAR_LEVELLING_SUPPORT #define WEAR_DEPTH 10 #define PAGE_TO_WRITE (Transfer_Length/512) /* Private variables ----------------------------------------------------------*/ /* Private function prototypes ------------------------------------------------*/ /* exported functions ---------------------------------------------------------*/ uint16_t NAND_Init (void); uint16_t NAND_Write (uint32_t Memory_Offset, uint32_t *Writebuff, uint16_t Transfer_Length); uint16_t NAND_Read (uint32_t Memory_Offset, uint32_t *Readbuff, uint16_t Transfer_Length); uint16_t NAND_Format (void); SPARE_AREA ReadSpareArea (uint32_t address); #endif /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/nand_if.h
C
asf20
2,788
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : hw_config.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Hardware Configuration & Setup ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __HW_CONFIG_H #define __HW_CONFIG_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported define -----------------------------------------------------------*/ #define BULK_MAX_PACKET_SIZE 0x00000040 /* Exported functions ------------------------------------------------------- */ void Set_System(void); void Set_USBClock(void); void Enter_LowPowerMode(void); void Leave_LowPowerMode(void); void USB_Interrupts_Config(void); void Led_Config(void); void Led_RW_ON(void); void Led_RW_OFF(void); void USB_Configured_LED(void); void USB_NotConfigured_LED(void); void USB_Cable_Config (FunctionalState NewState); void Get_SerialNum(void); void MAL_Config(void); #if defined (USE_STM3210B_EVAL) || defined (USE_STM3210E_EVAL) void USB_Disconnect_Config(void); #endif /* USE_STM3210B_EVAL or USE_STM3210E_EVAL */ /* External variables --------------------------------------------------------*/ #endif /*__HW_CONFIG_H*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/hw_config.h
C
asf20
2,340
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_bot.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : BOT State Machine management ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_BOT_H #define __USB_BOT_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Bulk-only Command Block Wrapper */ typedef struct _Bulk_Only_CBW { uint32_t dSignature; uint32_t dTag; uint32_t dDataLength; uint8_t bmFlags; uint8_t bLUN; uint8_t bCBLength; uint8_t CB[16]; } Bulk_Only_CBW; /* Bulk-only Command Status Wrapper */ typedef struct _Bulk_Only_CSW { uint32_t dSignature; uint32_t dTag; uint32_t dDataResidue; uint8_t bStatus; } Bulk_Only_CSW; /* Exported constants --------------------------------------------------------*/ /*****************************************************************************/ /*********************** Bulk-Only Transfer State machine ********************/ /*****************************************************************************/ #define BOT_IDLE 0 /* Idle state */ #define BOT_DATA_OUT 1 /* Data Out state */ #define BOT_DATA_IN 2 /* Data In state */ #define BOT_DATA_IN_LAST 3 /* Last Data In Last */ #define BOT_CSW_Send 4 /* Command Status Wrapper */ #define BOT_ERROR 5 /* error state */ #define BOT_CBW_SIGNATURE 0x43425355 #define BOT_CSW_SIGNATURE 0x53425355 #define BOT_CBW_PACKET_LENGTH 31 #define CSW_DATA_LENGTH 0x000D /* CSW Status Definitions */ #define CSW_CMD_PASSED 0x00 #define CSW_CMD_FAILED 0x01 #define CSW_PHASE_ERROR 0x02 #define SEND_CSW_DISABLE 0 #define SEND_CSW_ENABLE 1 #define DIR_IN 0 #define DIR_OUT 1 #define BOTH_DIR 2 /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void Mass_Storage_In (void); void Mass_Storage_Out (void); void CBW_Decode(void); void Transfer_Data_Request(uint8_t* Data_Pointer, uint16_t Data_Len); void Set_CSW (uint8_t CSW_Status, uint8_t Send_Permission); void Bot_Abort(uint8_t Direction); #endif /* __USB_BOT_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_bot.h
C
asf20
3,461
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : mass_mal.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Header for mass_mal.c file. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __MASS_MAL_H #define __MASS_MAL_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ #define MAL_OK 0 #define MAL_FAIL 1 #define MAX_LUN 1 /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ uint16_t MAL_Init (uint8_t lun); uint16_t MAL_GetStatus (uint8_t lun); uint16_t MAL_Read(uint8_t lun, uint32_t Memory_Offset, uint32_t *Readbuff, uint16_t Transfer_Length); uint16_t MAL_Write(uint8_t lun, uint32_t Memory_Offset, uint32_t *Writebuff, uint16_t Transfer_Length); #endif /* __MASS_MAL_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/mass_mal.h
C
asf20
1,902
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : fsmc_nand.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Header for fsmc_nand.c file. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __FSMC_NAND_H #define __FSMC_NAND_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ typedef struct { uint8_t Maker_ID; uint8_t Device_ID; uint8_t Third_ID; uint8_t Fourth_ID; }NAND_IDTypeDef; typedef struct { uint16_t Zone; uint16_t Block; uint16_t Page; } NAND_ADDRESS; /* Exported constants --------------------------------------------------------*/ /* NAND Area definition for STM3210E-EVAL Board RevD */ #define CMD_AREA (uint32_t)(1<<16) /* A16 = CLE high */ #define ADDR_AREA (uint32_t)(1<<17) /* A17 = ALE high */ #define DATA_AREA ((uint32_t)0x00000000) /* FSMC NAND memory command */ #define NAND_CMD_AREA_A ((uint8_t)0x00) #define NAND_CMD_AREA_B ((uint8_t)0x01) #define NAND_CMD_AREA_C ((uint8_t)0x50) #define NAND_CMD_AREA_TRUE1 ((uint8_t)0x30) #define NAND_CMD_WRITE0 ((uint8_t)0x80) #define NAND_CMD_WRITE_TRUE1 ((uint8_t)0x10) #define NAND_CMD_ERASE0 ((uint8_t)0x60) #define NAND_CMD_ERASE1 ((uint8_t)0xD0) #define NAND_CMD_READID ((uint8_t)0x90) #define NAND_CMD_STATUS ((uint8_t)0x70) #define NAND_CMD_LOCK_STATUS ((uint8_t)0x7A) #define NAND_CMD_RESET ((uint8_t)0xFF) /* NAND memory status */ #define NAND_VALID_ADDRESS ((uint32_t)0x00000100) #define NAND_INVALID_ADDRESS ((uint32_t)0x00000200) #define NAND_TIMEOUT_ERROR ((uint32_t)0x00000400) #define NAND_BUSY ((uint32_t)0x00000000) #define NAND_ERROR ((uint32_t)0x00000001) #define NAND_READY ((uint32_t)0x00000040) /* FSMC NAND memory parameters */ #define NAND_PAGE_SIZE ((uint16_t)0x0200) /* 512 bytes per page w/o Spare Area */ #define NAND_BLOCK_SIZE ((uint16_t)0x0020) /* 32x512 bytes pages per block */ #define NAND_ZONE_SIZE ((uint16_t)0x0400) /* 1024 Block per zone */ #define NAND_SPARE_AREA_SIZE ((uint16_t)0x0010) /* last 16 bytes as spare area */ #define NAND_MAX_ZONE ((uint16_t)0x0004) /* 4 zones of 1024 block */ /* FSMC NAND memory address computation */ #define ADDR_1st_CYCLE(ADDR) (uint8_t)((ADDR)& 0xFF) /* 1st addressing cycle */ #define ADDR_2nd_CYCLE(ADDR) (uint8_t)(((ADDR)& 0xFF00) >> 8) /* 2nd addressing cycle */ #define ADDR_3rd_CYCLE(ADDR) (uint8_t)(((ADDR)& 0xFF0000) >> 16) /* 3rd addressing cycle */ #define ADDR_4th_CYCLE(ADDR) (uint8_t)(((ADDR)& 0xFF000000) >> 24) /* 4th addressing cycle */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void FSMC_NAND_Init(void); void FSMC_NAND_ReadID(NAND_IDTypeDef* NAND_ID); uint32_t FSMC_NAND_WriteSmallPage(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumPageToWrite); uint32_t FSMC_NAND_ReadSmallPage (uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumPageToRead); uint32_t FSMC_NAND_WriteSpareArea(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumSpareAreaTowrite); uint32_t FSMC_NAND_ReadSpareArea(uint8_t *pBuffer, NAND_ADDRESS Address, uint32_t NumSpareAreaToRead); uint32_t FSMC_NAND_EraseBlock(NAND_ADDRESS Address); uint32_t FSMC_NAND_Reset(void); uint32_t FSMC_NAND_GetStatus(void); uint32_t FSMC_NAND_ReadStatus(void); uint32_t FSMC_NAND_AddressIncrement(NAND_ADDRESS* Address); #endif /* __FSMC_NAND_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/fsmc_nand.h
C
asf20
4,768
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_desc.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Descriptor Header for Mass Storage Device ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_DESC_H #define __USB_DESC_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported define -----------------------------------------------------------*/ #define MASS_SIZ_DEVICE_DESC 18 #define MASS_SIZ_CONFIG_DESC 32 #define MASS_SIZ_STRING_LANGID 4 #define MASS_SIZ_STRING_VENDOR 38 #define MASS_SIZ_STRING_PRODUCT 38 #define MASS_SIZ_STRING_SERIAL 26 #define MASS_SIZ_STRING_INTERFACE 16 /* Exported functions ------------------------------------------------------- */ extern const uint8_t MASS_DeviceDescriptor[MASS_SIZ_DEVICE_DESC]; extern const uint8_t MASS_ConfigDescriptor[MASS_SIZ_CONFIG_DESC]; extern const uint8_t MASS_StringLangID[MASS_SIZ_STRING_LANGID]; extern const uint8_t MASS_StringVendor[MASS_SIZ_STRING_VENDOR]; extern const uint8_t MASS_StringProduct[MASS_SIZ_STRING_PRODUCT]; extern uint8_t MASS_StringSerial[MASS_SIZ_STRING_SERIAL]; extern const uint8_t MASS_StringInterface[MASS_SIZ_STRING_INTERFACE]; #endif /* __USB_DESC_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_desc.h
C
asf20
2,471
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_prop.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : All processing related to Mass Storage Demo (Endpoint 0) ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __usb_prop_H #define __usb_prop_H /* Includes ------------------------------------------------------------------*/ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ #define Mass_Storage_GetConfiguration NOP_Process /* #define Mass_Storage_SetConfiguration NOP_Process*/ #define Mass_Storage_GetInterface NOP_Process #define Mass_Storage_SetInterface NOP_Process #define Mass_Storage_GetStatus NOP_Process /* #define Mass_Storage_ClearFeature NOP_Process*/ #define Mass_Storage_SetEndPointFeature NOP_Process #define Mass_Storage_SetDeviceFeature NOP_Process /*#define Mass_Storage_SetDeviceAddress NOP_Process*/ /* MASS Storage Requests*/ #define GET_MAX_LUN 0xFE #define MASS_STORAGE_RESET 0xFF #define LUN_DATA_LENGTH 1 /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void MASS_init(void); void MASS_Reset(void); void Mass_Storage_SetConfiguration(void); void Mass_Storage_ClearFeature(void); void Mass_Storage_SetDeviceAddress (void); void MASS_Status_In (void); void MASS_Status_Out (void); RESULT MASS_Data_Setup(uint8_t); RESULT MASS_NoData_Setup(uint8_t); RESULT MASS_Get_Interface_Setting(uint8_t Interface, uint8_t AlternateSetting); uint8_t *MASS_GetDeviceDescriptor(uint16_t ); uint8_t *MASS_GetConfigDescriptor(uint16_t); uint8_t *MASS_GetStringDescriptor(uint16_t); uint8_t *Get_Max_Lun(uint16_t Length); #endif /* __usb_prop_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_prop.h
C
asf20
2,858
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : stm32f10x_conf.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Library configuration file. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F10x_CONF_H #define __STM32F10x_CONF_H /* Includes ------------------------------------------------------------------*/ /* Uncomment the line below to enable peripheral header file inclusion */ /* #include "stm32f10x_adc.h" */ /* #include "stm32f10x_bkp.h" */ /* #include "stm32f10x_can.h" */ /* #include "stm32f10x_crc.h" */ /* #include "stm32f10x_dac.h" */ /* #include "stm32f10x_dbgmcu.h" */ #include "stm32f10x_dma.h" #include "stm32f10x_exti.h" #include "stm32f10x_flash.h" #include "stm32f10x_fsmc.h" #include "stm32f10x_gpio.h" /* #include "stm32f10x_i2c.h" */ /* #include "stm32f10x_iwdg.h" */ /* #include "stm32f10x_pwr.h" */ #include "stm32f10x_rcc.h" /* #include "stm32f10x_rtc.h" */ #include "stm32f10x_sdio.h" #include "stm32f10x_spi.h" /* #include "stm32f10x_tim.h" */ #include "stm32f10x_usart.h" /* #include "stm32f10x_wwdg.h" */ #include "misc.h" /* High level functions for NVIC and SysTick (add-on to CMSIS functions) */ /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Uncomment the line below to expanse the "assert_param" macro in the Standard Peripheral Library drivers code */ /* #define USE_FULL_ASSERT 1 */ /* Exported macro ------------------------------------------------------------*/ #ifdef USE_FULL_ASSERT /******************************************************************************* * Macro Name : assert_param * Description : The assert_param macro is used for function's parameters check. * Input : - expr: If expr is false, it calls assert_failed function * which reports the name of the source file and the source * line number of the call that failed. * If expr is true, it returns no value. * Return : None *******************************************************************************/ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ void assert_failed(uint8_t* file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ #endif /* __STM32F10x_CONF_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/stm32f10x_conf.h
C
asf20
3,427
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : stm32f10x_it.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : This file contains the headers of the interrupt handlers. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __STM32F10x_IT_H #define __STM32F10x_IT_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void NMI_Handler(void); void HardFault_Handler(void); void MemManage_Handler(void); void BusFault_Handler(void); void UsageFault_Handler(void); void SVC_Handler(void); void DebugMon_Handler(void); void PendSV_Handler(void); void SysTick_Handler(void); #ifndef STM32F10X_CL void USB_HP_CAN1_TX_IRQHandler(void); void USB_LP_CAN1_RX0_IRQHandler(void); #endif /* STM32F10X_CL */ #if defined(STM32F10X_HD) || defined(STM32F10X_XL) void SDIO_IRQHandler(void); #endif /* STM32F10X_HD | STM32F10X_XL */ #ifdef STM32F10X_CL void OTG_FS_IRQHandler(void); #endif /* STM32F10X_CL */ #endif /* __STM32F10x_IT_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/stm32f10x_it.h
C
asf20
2,240
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : platform_config.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Evaluation board specific configuration file. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __PLATFORM_CONFIG_H #define __PLATFORM_CONFIG_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Uncomment the line corresponding to the STMicroelectronics evaluation board used to run the example */ #if !defined (USE_STM3210B_EVAL) && !defined (USE_STM3210E_EVAL) && !defined (USE_STM3210C_EVAL) //#define USE_STM3210B_EVAL //#define USE_STM3210E_EVAL #define USE_STM3210C_EVAL #endif /* Define the STM32F10x hardware depending on the used evaluation board */ #ifdef USE_STM3210B_EVAL #define USB_DISCONNECT GPIOD #define USB_DISCONNECT_PIN GPIO_Pin_9 #define RCC_APB2Periph_GPIO_DISCONNECT RCC_APB2Periph_GPIOD #elif defined (USE_STM3210E_EVAL) #define USB_DISCONNECT GPIOB #define USB_DISCONNECT_PIN GPIO_Pin_14 #define RCC_APB2Periph_GPIO_DISCONNECT RCC_APB2Periph_GPIOB #elif defined (USE_STM3210C_EVAL) #define USB_DISCONNECT 0 #define USB_DISCONNECT_PIN 0 #define RCC_APB2Periph_GPIO_DISCONNECT 0 #endif /* USE_STM3210B_EVAL */ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #endif /* __PLATFORM_CONFIG_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/platform_config.h
C
asf20
2,649
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_scsi.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : All processing related to the SCSI commands ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_SCSI_H #define __USB_SCSI_H /* Includes ------------------------------------------------------------------*/ #include "stm32f10x.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* SCSI Commands */ #define SCSI_FORMAT_UNIT 0x04 #define SCSI_INQUIRY 0x12 #define SCSI_MODE_SELECT6 0x15 #define SCSI_MODE_SELECT10 0x55 #define SCSI_MODE_SENSE6 0x1A #define SCSI_MODE_SENSE10 0x5A #define SCSI_ALLOW_MEDIUM_REMOVAL 0x1E #define SCSI_READ6 0x08 #define SCSI_READ10 0x28 #define SCSI_READ12 0xA8 #define SCSI_READ16 0x88 #define SCSI_READ_CAPACITY10 0x25 #define SCSI_READ_CAPACITY16 0x9E #define SCSI_REQUEST_SENSE 0x03 #define SCSI_START_STOP_UNIT 0x1B #define SCSI_TEST_UNIT_READY 0x00 #define SCSI_WRITE6 0x0A #define SCSI_WRITE10 0x2A #define SCSI_WRITE12 0xAA #define SCSI_WRITE16 0x8A #define SCSI_VERIFY10 0x2F #define SCSI_VERIFY12 0xAF #define SCSI_VERIFY16 0x8F #define SCSI_SEND_DIAGNOSTIC 0x1D #define SCSI_READ_FORMAT_CAPACITIES 0x23 #define NO_SENSE 0 #define RECOVERED_ERROR 1 #define NOT_READY 2 #define MEDIUM_ERROR 3 #define HARDWARE_ERROR 4 #define ILLEGAL_REQUEST 5 #define UNIT_ATTENTION 6 #define DATA_PROTECT 7 #define BLANK_CHECK 8 #define VENDOR_SPECIFIC 9 #define COPY_ABORTED 10 #define ABORTED_COMMAND 11 #define VOLUME_OVERFLOW 13 #define MISCOMPARE 14 #define INVALID_COMMAND 0x20 #define INVALID_FIELED_IN_COMMAND 0x24 #define PARAMETER_LIST_LENGTH_ERROR 0x1A #define INVALID_FIELD_IN_PARAMETER_LIST 0x26 #define ADDRESS_OUT_OF_RANGE 0x21 #define MEDIUM_NOT_PRESENT 0x3A #define MEDIUM_HAVE_CHANGED 0x28 #define READ_FORMAT_CAPACITY_DATA_LEN 0x0C #define READ_CAPACITY10_DATA_LEN 0x08 #define MODE_SENSE10_DATA_LEN 0x08 #define MODE_SENSE6_DATA_LEN 0x04 #define REQUEST_SENSE_DATA_LEN 0x12 #define STANDARD_INQUIRY_DATA_LEN 0x24 #define BLKVFY 0x04 extern uint8_t Page00_Inquiry_Data[]; extern uint8_t Standard_Inquiry_Data[]; extern uint8_t Standard_Inquiry_Data2[]; extern uint8_t Mode_Sense6_data[]; extern uint8_t Mode_Sense10_data[]; extern uint8_t Scsi_Sense_Data[]; extern uint8_t ReadCapacity10_Data[]; extern uint8_t ReadFormatCapacity_Data []; /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void SCSI_Inquiry_Cmd(uint8_t lun); void SCSI_ReadFormatCapacity_Cmd(uint8_t lun); void SCSI_ReadCapacity10_Cmd(uint8_t lun); void SCSI_RequestSense_Cmd (uint8_t lun); void SCSI_Start_Stop_Unit_Cmd(uint8_t lun); void SCSI_ModeSense6_Cmd (uint8_t lun); void SCSI_ModeSense10_Cmd (uint8_t lun); void SCSI_Write10_Cmd(uint8_t lun , uint32_t LBA , uint32_t BlockNbr); void SCSI_Read10_Cmd(uint8_t lun , uint32_t LBA , uint32_t BlockNbr); void SCSI_Verify10_Cmd(uint8_t lun); void SCSI_Invalid_Cmd(uint8_t lun); void SCSI_Valid_Cmd(uint8_t lun); bool SCSI_Address_Management(uint8_t lun , uint8_t Cmd , uint32_t LBA , uint32_t BlockNbr); void Set_Scsi_Sense_Data(uint8_t lun , uint8_t Sens_Key, uint8_t Asc); void SCSI_TestUnitReady_Cmd (uint8_t lun); void SCSI_Format_Cmd (uint8_t lun); //#define SCSI_TestUnitReady_Cmd SCSI_Valid_Cmd #define SCSI_Prevent_Removal_Cmd SCSI_Valid_Cmd /* Invalid (Unsupported) commands */ #define SCSI_READ_CAPACITY16_Cmd SCSI_Invalid_Cmd //#define SCSI_FormatUnit_Cmd SCSI_Invalid_Cmd #define SCSI_Write6_Cmd SCSI_Invalid_Cmd #define SCSI_Write16_Cmd SCSI_Invalid_Cmd #define SCSI_Write12_Cmd SCSI_Invalid_Cmd #define SCSI_Read6_Cmd SCSI_Invalid_Cmd #define SCSI_Read12_Cmd SCSI_Invalid_Cmd #define SCSI_Read16_Cmd SCSI_Invalid_Cmd #define SCSI_Send_Diagnostic_Cmd SCSI_Invalid_Cmd #define SCSI_Mode_Select6_Cmd SCSI_Invalid_Cmd #define SCSI_Mode_Select10_Cmd SCSI_Invalid_Cmd #define SCSI_Verify12_Cmd SCSI_Invalid_Cmd #define SCSI_Verify16_Cmd SCSI_Invalid_Cmd #endif /* __USB_SCSI_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_scsi.h
C
asf20
6,564
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_istr.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : This file includes the peripherals header files in the * user application. ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_ISTR_H #define __USB_ISTR_H /* Includes ------------------------------------------------------------------*/ #include "usb_conf.h" /* Exported types ------------------------------------------------------------*/ /* Exported constants --------------------------------------------------------*/ /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ #ifndef STM32F10X_CL void USB_Istr(void); #else /* STM32F10X_CL */ u32 STM32_PCD_OTG_ISR_Handler(void); #endif /* STM32F10X_CL */ /* function prototypes Automatically built defining related macros */ void EP1_IN_Callback(void); void EP2_IN_Callback(void); void EP3_IN_Callback(void); void EP4_IN_Callback(void); void EP5_IN_Callback(void); void EP6_IN_Callback(void); void EP7_IN_Callback(void); void EP1_OUT_Callback(void); void EP2_OUT_Callback(void); void EP3_OUT_Callback(void); void EP4_OUT_Callback(void); void EP5_OUT_Callback(void); void EP6_OUT_Callback(void); void EP7_OUT_Callback(void); #ifndef STM32F10X_CL #ifdef CTR_CALLBACK void CTR_Callback(void); #endif #ifdef DOVR_CALLBACK void DOVR_Callback(void); #endif #ifdef ERR_CALLBACK void ERR_Callback(void); #endif #ifdef WKUP_CALLBACK void WKUP_Callback(void); #endif #ifdef SUSP_CALLBACK void SUSP_Callback(void); #endif #ifdef RESET_CALLBACK void RESET_Callback(void); #endif #ifdef SOF_CALLBACK void SOF_Callback(void); #endif #ifdef ESOF_CALLBACK void ESOF_Callback(void); #endif #else /* STM32F10X_CL */ /* Interrupt subroutines user callbacks prototypes. These callbacks are called into the respective interrupt sunroutine functinos and can be tailored for various user application purposes. Note: Make sure that the correspondant interrupt is enabled through the definition in usb_conf.h file */ void INTR_MODEMISMATCH_Callback(void); void INTR_SOFINTR_Callback(void); void INTR_RXSTSQLVL_Callback(void); void INTR_NPTXFEMPTY_Callback(void); void INTR_GINNAKEFF_Callback(void); void INTR_GOUTNAKEFF_Callback(void); void INTR_ERLYSUSPEND_Callback(void); void INTR_USBSUSPEND_Callback(void); void INTR_USBRESET_Callback(void); void INTR_ENUMDONE_Callback(void); void INTR_ISOOUTDROP_Callback(void); void INTR_EOPFRAME_Callback(void); void INTR_EPMISMATCH_Callback(void); void INTR_INEPINTR_Callback(void); void INTR_OUTEPINTR_Callback(void); void INTR_INCOMPLISOIN_Callback(void); void INTR_INCOMPLISOOUT_Callback(void); void INTR_WKUPINTR_Callback(void); /* Isochronous data update */ void INTR_RXSTSQLVL_ISODU_Callback(void); #endif /* STM32F10X_CL */ #endif /*__USB_ISTR_H*/ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_istr.h
C
asf20
3,903
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_conf.h * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Mass Storage Demo configuration header ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __USB_CONF_H #define __USB_CONF_H /*-------------------------------------------------------------*/ /* EP_NUM */ /* defines how many endpoints are used by the device */ /*-------------------------------------------------------------*/ #define EP_NUM (3) #ifndef STM32F10X_CL /*-------------------------------------------------------------*/ /* -------------- Buffer Description Table -----------------*/ /*-------------------------------------------------------------*/ /* buffer table base address */ #define BTABLE_ADDRESS (0x00) /* EP0 */ /* rx/tx buffer base address */ #define ENDP0_RXADDR (0x18) #define ENDP0_TXADDR (0x58) /* EP1 */ /* tx buffer base address */ #define ENDP1_TXADDR (0x98) /* EP2 */ /* Rx buffer base address */ #define ENDP2_RXADDR (0xD8) /* ISTR events */ /* IMR_MSK */ /* mask defining which events has to be handled */ /* by the device application software */ #define IMR_MSK (CNTR_CTRM | CNTR_RESETM) #endif /* STM32F10X_CL */ /* CTR service routines */ /* associated to defined endpoints */ //#define EP1_IN_Callback NOP_Process #define EP2_IN_Callback NOP_Process #define EP3_IN_Callback NOP_Process #define EP4_IN_Callback NOP_Process #define EP5_IN_Callback NOP_Process #define EP6_IN_Callback NOP_Process #define EP7_IN_Callback NOP_Process #define EP1_OUT_Callback NOP_Process //#define EP2_OUT_Callback NOP_Process #define EP3_OUT_Callback NOP_Process #define EP4_OUT_Callback NOP_Process #define EP5_OUT_Callback NOP_Process #define EP6_OUT_Callback NOP_Process #define EP7_OUT_Callback NOP_Process #ifdef STM32F10X_CL /******************************************************************************* * FIFO Size Configuration * * (i) Dedicated data FIFO SPRAM of 1.25 Kbytes = 1280 bytes = 320 32-bits words * available for the endpoints IN and OUT. * Device mode features: * -1 bidirectional CTRL EP 0 * -3 IN EPs to support any kind of Bulk, Interrupt or Isochronous transfer * -3 OUT EPs to support any kind of Bulk, Interrupt or Isochronous transfer * * ii) Receive data FIFO size = RAM for setup packets + * OUT endpoint control information + * data OUT packets + miscellaneous * Space = ONE 32-bits words * --> RAM for setup packets = 4 * n + 6 space * (n is the nbr of CTRL EPs the device core supports) * --> OUT EP CTRL info = 1 space * (one space for status information written to the FIFO along with each * received packet) * --> data OUT packets = (Largest Packet Size / 4) + 1 spaces * (MINIMUM to receive packets) * --> OR data OUT packets = at least 2*(Largest Packet Size / 4) + 1 spaces * (if high-bandwidth EP is enabled or multiple isochronous EPs) * --> miscellaneous = 1 space per OUT EP * (one space for transfer complete status information also pushed to the * FIFO with each endpoint's last packet) * * (iii)MINIMUM RAM space required for each IN EP Tx FIFO = MAX packet size for * that particular IN EP. More space allocated in the IN EP Tx FIFO results * in a better performance on the USB and can hide latencies on the AHB. * * (iv) TXn min size = 16 words. (n : Transmit FIFO index) * (v) When a TxFIFO is not used, the Configuration should be as follows: * case 1 : n > m and Txn is not used (n,m : Transmit FIFO indexes) * --> Txm can use the space allocated for Txn. * case2 : n < m and Txn is not used (n,m : Transmit FIFO indexes) * --> Txn should be configured with the minimum space of 16 words * (vi) The FIFO is used optimally when used TxFIFOs are allocated in the top * of the FIFO.Ex: use EP1 and EP2 as IN instead of EP1 and EP3 as IN ones. *******************************************************************************/ #define RX_FIFO_SIZE 128 #define TX0_FIFO_SIZE 64 #define TX1_FIFO_SIZE 64 #define TX2_FIFO_SIZE 16 #define TX3_FIFO_SIZE 16 /* OTGD-FS-DEVICE IP interrupts Enable definitions */ /* Uncomment the define to enable the selected interrupt */ //#define INTR_MODEMISMATCH #define INTR_SOFINTR #define INTR_RXSTSQLVL /* Mandatory */ //#define INTR_NPTXFEMPTY //#define INTR_GINNAKEFF //#define INTR_GOUTNAKEFF //#define INTR_ERLYSUSPEND #define INTR_USBSUSPEND /* Mandatory */ #define INTR_USBRESET /* Mandatory */ #define INTR_ENUMDONE /* Mandatory */ //#define INTR_ISOOUTDROP #define INTR_EOPFRAME //#define INTR_EPMISMATCH #define INTR_INEPINTR /* Mandatory */ #define INTR_OUTEPINTR /* Mandatory */ //#define INTR_INCOMPLISOIN //#define INTR_INCOMPLISOOUT #define INTR_WKUPINTR /* Mandatory */ /* OTGD-FS-DEVICE IP interrupts subroutines */ /* Comment the define to enable the selected interrupt subroutine and replace it by user code */ #define INTR_MODEMISMATCH_Callback NOP_Process #define INTR_SOFINTR_Callback NOP_Process #define INTR_RXSTSQLVL_Callback NOP_Process #define INTR_NPTXFEMPTY_Callback NOP_Process #define INTR_NPTXFEMPTY_Callback NOP_Process #define INTR_GINNAKEFF_Callback NOP_Process #define INTR_GOUTNAKEFF_Callback NOP_Process #define INTR_ERLYSUSPEND_Callback NOP_Process #define INTR_USBSUSPEND_Callback NOP_Process #define INTR_USBRESET_Callback NOP_Process #define INTR_ENUMDONE_Callback NOP_Process #define INTR_ISOOUTDROP_Callback NOP_Process #define INTR_EOPFRAME_Callback NOP_Process #define INTR_EPMISMATCH_Callback NOP_Process #define INTR_INEPINTR_Callback NOP_Process #define INTR_OUTEPINTR_Callback NOP_Process #define INTR_INCOMPLISOIN_Callback NOP_Process #define INTR_INCOMPLISOOUT_Callback NOP_Process #define INTR_WKUPINTR_Callback NOP_Process /* Isochronous data update */ #define INTR_RXSTSQLVL_ISODU_Callback NOP_Process /* Isochronous transfer parameters */ /* Size of a single Isochronous buffer (size of a single transfer) */ #define ISOC_BUFFER_SZE 1 /* Number of sub-buffers (number of single buffers/transfers), should be even */ #define NUM_SUB_BUFFERS 2 #endif /* STM32F10X_CL */ #endif /* __USB_CONF_H */ /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/inc/usb_conf.h
C
asf20
7,787
/******************** (C) COPYRIGHT 2010 STMicroelectronics ******************** * File Name : usb_endp.c * Author : MCD Application Team * Version : V3.2.1 * Date : 07/05/2010 * Description : Endpoint routines ******************************************************************************** * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME. * AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT, * INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE * CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING * INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. *******************************************************************************/ /* Includes ------------------------------------------------------------------*/ #include "usb_lib.h" #include "usb_bot.h" #include "usb_istr.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /******************************************************************************* * Function Name : EP1_IN_Callback * Description : EP1 IN Callback Routine * Input : None. * Output : None. * Return : None. *******************************************************************************/ void EP1_IN_Callback(void) { Mass_Storage_In(); } /******************************************************************************* * Function Name : EP2_OUT_Callback. * Description : EP2 OUT Callback Routine. * Input : None. * Output : None. * Return : None. *******************************************************************************/ void EP2_OUT_Callback(void) { Mass_Storage_Out(); } /******************* (C) COPYRIGHT 2010 STMicroelectronics *****END OF FILE****/
zzqq5414-jk-rabbit
sw/lib/STM32_USB-FS-Device_Lib_V3.2.1/Project/Mass_Storage/src/usb_endp.c
C
asf20
2,393