diff options
| author | Bernard Xiong <[email protected]> | 2013-01-08 18:13:32 -0800 |
|---|---|---|
| committer | Bernard Xiong <[email protected]> | 2013-01-08 18:13:32 -0800 |
| commit | accace98e05eda28c116eb04502eb92d01b6ef1e (patch) | |
| tree | 4a425c96e0be3980779c8205c7c3fe2f1a144630 /bsp/simulator | |
| parent | 1fab41d48a490f6483582147500d43f4ca889a8e (diff) | |
| parent | 02b8e9366f362926799bfaecc0891830ba62f646 (diff) | |
Merge pull request #8 from mbbill/correct_crlf
Correct crlf
Diffstat (limited to 'bsp/simulator')
36 files changed, 6294 insertions, 6294 deletions
diff --git a/bsp/simulator/SConscript b/bsp/simulator/SConscript index d9c64eb9f9..0992612410 100644 --- a/bsp/simulator/SConscript +++ b/bsp/simulator/SConscript @@ -1,12 +1,12 @@ -from building import *
-
-cwd = GetCurrentDir()
-objs = []
-list = os.listdir(cwd)
-
-for d in list:
- path = os.path.join(cwd, d)
- if os.path.isfile(os.path.join(path, 'SConscript')):
- objs = objs + SConscript(os.path.join(d, 'SConscript'))
-
-Return('objs')
+from building import * + +cwd = GetCurrentDir() +objs = [] +list = os.listdir(cwd) + +for d in list: + path = os.path.join(cwd, d) + if os.path.isfile(os.path.join(path, 'SConscript')): + objs = objs + SConscript(os.path.join(d, 'SConscript')) + +Return('objs') diff --git a/bsp/simulator/SConstruct b/bsp/simulator/SConstruct index 513a5a41ed..0bd7e05ec8 100644 --- a/bsp/simulator/SConstruct +++ b/bsp/simulator/SConstruct @@ -1,85 +1,85 @@ -import os
-import sys
-import rtconfig
-
-if os.getenv('RTT_ROOT'):
- RTT_ROOT = os.getenv('RTT_ROOT')
-else:
- RTT_ROOT = os.path.normpath(os.getcwd() + '/../..')
-
-if os.getenv('RTT_RTGUI'):
- RTT_RTGUI = os.getenv('RTT_RTGUI')
-else:
- # set the rtgui root directory by hand
- # empty string means use the RTGUI in svn
- # RTT_RTGUI = os.path.normpath(r'F:\Project\git\rt-gui\components\rtgui')
- RTT_RTGUI =''
-
-sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')]
-from building import *
-
-TARGET = 'rtthread-win32.' + rtconfig.TARGET_EXT
-
-env = Environment()
-
-Export('RTT_ROOT')
-Export('rtconfig')
-
-libs = Split('''
-winmm
-gdi32
-winspool
-comdlg32
-advapi32
-shell32
-ole32
-oleaut32
-uuid
-odbc32
-odbccp32
-''')
-definitions = Split('''
-WIN32
-_DEBUG
-_CONSOLE
-MSVC
-_TIME_T_DEFINED
-''')
-
-env.Append(CCFLAGS=rtconfig.CFLAGS)
-env.Append(LINKFLAGS=rtconfig.LFLAGS)
-env['LIBS']=libs
-env['CPPDEFINES']=definitions
-
-# prepare building environment
-
-objs = PrepareBuilding(env, RTT_ROOT, has_libcpu=False, remove_components=['rtgui'])
-if GetDepend('RT_USING_RTGUI'):
- sdl_lib = ['SDL', 'SDLmain']
- sdl_lib_path = [os.path.abspath('SDL/lib/x86')]
- sdl_include_path = [os.path.abspath('SDL/include')]
- env.Append(LIBS=sdl_lib)
- env.Append(LIBPATH=sdl_lib_path)
- env.Append(CPPPATH=sdl_include_path)
-
- if RTT_RTGUI:
- objs += SConscript(os.path.join(RTT_RTGUI, 'SConscript'),
- variant_dir='build/components/rtgui',
- duplicate=0)
- objs = objs + SConscript(RTT_RTGUI+'/../../demo/examples/SConscript',
- variant_dir='build/examples/gui', duplicate=0)
- else:
- objs += SConscript(os.path.join(RTT_ROOT + '/components/rtgui', 'SConscript'),
- variant_dir='build/components/rtgui',
- duplicate=0)
- objs = objs + SConscript(RTT_ROOT + '/examples/gui/SConscript',
- variant_dir='build/examples/gui', duplicate=0)
-
-if GetDepend('RT_USING_TC'):
- objs = objs + SConscript(RTT_ROOT + '/examples/kernel/SConscript', variant_dir = 'build/tc/kernel', duplicate=0)
-
-# build program
-program = env.Program(TARGET, objs)
-
-# end building
-EndBuilding(TARGET, program)
+import os +import sys +import rtconfig + +if os.getenv('RTT_ROOT'): + RTT_ROOT = os.getenv('RTT_ROOT') +else: + RTT_ROOT = os.path.normpath(os.getcwd() + '/../..') + +if os.getenv('RTT_RTGUI'): + RTT_RTGUI = os.getenv('RTT_RTGUI') +else: + # set the rtgui root directory by hand + # empty string means use the RTGUI in svn + # RTT_RTGUI = os.path.normpath(r'F:\Project\git\rt-gui\components\rtgui') + RTT_RTGUI ='' + +sys.path = sys.path + [os.path.join(RTT_ROOT, 'tools')] +from building import * + +TARGET = 'rtthread-win32.' + rtconfig.TARGET_EXT + +env = Environment() + +Export('RTT_ROOT') +Export('rtconfig') + +libs = Split(''' +winmm +gdi32 +winspool +comdlg32 +advapi32 +shell32 +ole32 +oleaut32 +uuid +odbc32 +odbccp32 +''') +definitions = Split(''' +WIN32 +_DEBUG +_CONSOLE +MSVC +_TIME_T_DEFINED +''') + +env.Append(CCFLAGS=rtconfig.CFLAGS) +env.Append(LINKFLAGS=rtconfig.LFLAGS) +env['LIBS']=libs +env['CPPDEFINES']=definitions + +# prepare building environment + +objs = PrepareBuilding(env, RTT_ROOT, has_libcpu=False, remove_components=['rtgui']) +if GetDepend('RT_USING_RTGUI'): + sdl_lib = ['SDL', 'SDLmain'] + sdl_lib_path = [os.path.abspath('SDL/lib/x86')] + sdl_include_path = [os.path.abspath('SDL/include')] + env.Append(LIBS=sdl_lib) + env.Append(LIBPATH=sdl_lib_path) + env.Append(CPPPATH=sdl_include_path) + + if RTT_RTGUI: + objs += SConscript(os.path.join(RTT_RTGUI, 'SConscript'), + variant_dir='build/components/rtgui', + duplicate=0) + objs = objs + SConscript(RTT_RTGUI+'/../../demo/examples/SConscript', + variant_dir='build/examples/gui', duplicate=0) + else: + objs += SConscript(os.path.join(RTT_ROOT + '/components/rtgui', 'SConscript'), + variant_dir='build/components/rtgui', + duplicate=0) + objs = objs + SConscript(RTT_ROOT + '/examples/gui/SConscript', + variant_dir='build/examples/gui', duplicate=0) + +if GetDepend('RT_USING_TC'): + objs = objs + SConscript(RTT_ROOT + '/examples/kernel/SConscript', variant_dir = 'build/tc/kernel', duplicate=0) + +# build program +program = env.Program(TARGET, objs) + +# end building +EndBuilding(TARGET, program) diff --git a/bsp/simulator/SDL/BUGS b/bsp/simulator/SDL/BUGS index d7058f6209..218bf3d15b 100644 --- a/bsp/simulator/SDL/BUGS +++ b/bsp/simulator/SDL/BUGS @@ -1,18 +1,18 @@ -
-Bugs are now managed in the SDL bug tracker, here:
-
- http://bugzilla.libsdl.org/
-
-You may report bugs there, and search to see if a given issue has already
- been reported, discussed, and maybe even fixed.
-
-
-
-You may also find help at the SDL mailing list. Subscription information:
-
- http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org
-
-Bug reports are welcome here, but we really appreciate if you use Bugzilla, as
- bugs discussed on the mailing list may be forgotten or missed.
-
-
+ +Bugs are now managed in the SDL bug tracker, here: + + http://bugzilla.libsdl.org/ + +You may report bugs there, and search to see if a given issue has already + been reported, discussed, and maybe even fixed. + + + +You may also find help at the SDL mailing list. Subscription information: + + http://lists.libsdl.org/listinfo.cgi/sdl-libsdl.org + +Bug reports are welcome here, but we really appreciate if you use Bugzilla, as + bugs discussed on the mailing list may be forgotten or missed. + + diff --git a/bsp/simulator/SDL/COPYING b/bsp/simulator/SDL/COPYING index 8904ea404e..2cba2ac74c 100644 --- a/bsp/simulator/SDL/COPYING +++ b/bsp/simulator/SDL/COPYING @@ -1,458 +1,458 @@ - GNU LESSER GENERAL PUBLIC LICENSE
- Version 2.1, February 1999
-
- Copyright (C) 1991, 1999 Free Software Foundation, Inc.
- 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-[This is the first released version of the Lesser GPL. It also counts
- as the successor of the GNU Library Public License, version 2, hence
- the version number 2.1.]
-
- Preamble
-
- The licenses for most software are designed to take away your
-freedom to share and change it. By contrast, the GNU General Public
-Licenses are intended to guarantee your freedom to share and change
-free software--to make sure the software is free for all its users.
-
- This license, the Lesser General Public License, applies to some
-specially designated software packages--typically libraries--of the
-Free Software Foundation and other authors who decide to use it. You
-can use it too, but we suggest you first think carefully about whether
-this license or the ordinary General Public License is the better
-strategy to use in any particular case, based on the explanations below.
-
- When we speak of free software, we are referring to freedom of use,
-not price. Our General Public Licenses are designed to make sure that
-you have the freedom to distribute copies of free software (and charge
-for this service if you wish); that you receive source code or can get
-it if you want it; that you can change the software and use pieces of
-it in new free programs; and that you are informed that you can do
-these things.
-
- To protect your rights, we need to make restrictions that forbid
-distributors to deny you these rights or to ask you to surrender these
-rights. These restrictions translate to certain responsibilities for
-you if you distribute copies of the library or if you modify it.
-
- For example, if you distribute copies of the library, whether gratis
-or for a fee, you must give the recipients all the rights that we gave
-you. You must make sure that they, too, receive or can get the source
-code. If you link other code with the library, you must provide
-complete object files to the recipients, so that they can relink them
-with the library after making changes to the library and recompiling
-it. And you must show them these terms so they know their rights.
-
- We protect your rights with a two-step method: (1) we copyright the
-library, and (2) we offer you this license, which gives you legal
-permission to copy, distribute and/or modify the library.
-
- To protect each distributor, we want to make it very clear that
-there is no warranty for the free library. Also, if the library is
-modified by someone else and passed on, the recipients should know
-that what they have is not the original version, so that the original
-author's reputation will not be affected by problems that might be
-introduced by others.
-
- Finally, software patents pose a constant threat to the existence of
-any free program. We wish to make sure that a company cannot
-effectively restrict the users of a free program by obtaining a
-restrictive license from a patent holder. Therefore, we insist that
-any patent license obtained for a version of the library must be
-consistent with the full freedom of use specified in this license.
-
- Most GNU software, including some libraries, is covered by the
-ordinary GNU General Public License. This license, the GNU Lesser
-General Public License, applies to certain designated libraries, and
-is quite different from the ordinary General Public License. We use
-this license for certain libraries in order to permit linking those
-libraries into non-free programs.
-
- When a program is linked with a library, whether statically or using
-a shared library, the combination of the two is legally speaking a
-combined work, a derivative of the original library. The ordinary
-General Public License therefore permits such linking only if the
-entire combination fits its criteria of freedom. The Lesser General
-Public License permits more lax criteria for linking other code with
-the library.
-
- We call this license the "Lesser" General Public License because it
-does Less to protect the user's freedom than the ordinary General
-Public License. It also provides other free software developers Less
-of an advantage over competing non-free programs. These disadvantages
-are the reason we use the ordinary General Public License for many
-libraries. However, the Lesser license provides advantages in certain
-special circumstances.
-
- For example, on rare occasions, there may be a special need to
-encourage the widest possible use of a certain library, so that it becomes
-a de-facto standard. To achieve this, non-free programs must be
-allowed to use the library. A more frequent case is that a free
-library does the same job as widely used non-free libraries. In this
-case, there is little to gain by limiting the free library to free
-software only, so we use the Lesser General Public License.
-
- In other cases, permission to use a particular library in non-free
-programs enables a greater number of people to use a large body of
-free software. For example, permission to use the GNU C Library in
-non-free programs enables many more people to use the whole GNU
-operating system, as well as its variant, the GNU/Linux operating
-system.
-
- Although the Lesser General Public License is Less protective of the
-users' freedom, it does ensure that the user of a program that is
-linked with the Library has the freedom and the wherewithal to run
-that program using a modified version of the Library.
-
- The precise terms and conditions for copying, distribution and
-modification follow. Pay close attention to the difference between a
-"work based on the library" and a "work that uses the library". The
-former contains code derived from the library, whereas the latter must
-be combined with the library in order to run.
-
- GNU LESSER GENERAL PUBLIC LICENSE
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
-
- 0. This License Agreement applies to any software library or other
-program which contains a notice placed by the copyright holder or
-other authorized party saying it may be distributed under the terms of
-this Lesser General Public License (also called "this License").
-Each licensee is addressed as "you".
-
- A "library" means a collection of software functions and/or data
-prepared so as to be conveniently linked with application programs
-(which use some of those functions and data) to form executables.
-
- The "Library", below, refers to any such software library or work
-which has been distributed under these terms. A "work based on the
-Library" means either the Library or any derivative work under
-copyright law: that is to say, a work containing the Library or a
-portion of it, either verbatim or with modifications and/or translated
-straightforwardly into another language. (Hereinafter, translation is
-included without limitation in the term "modification".)
-
- "Source code" for a work means the preferred form of the work for
-making modifications to it. For a library, complete source code means
-all the source code for all modules it contains, plus any associated
-interface definition files, plus the scripts used to control compilation
-and installation of the library.
-
- Activities other than copying, distribution and modification are not
-covered by this License; they are outside its scope. The act of
-running a program using the Library is not restricted, and output from
-such a program is covered only if its contents constitute a work based
-on the Library (independent of the use of the Library in a tool for
-writing it). Whether that is true depends on what the Library does
-and what the program that uses the Library does.
-
- 1. You may copy and distribute verbatim copies of the Library's
-complete source code as you receive it, in any medium, provided that
-you conspicuously and appropriately publish on each copy an
-appropriate copyright notice and disclaimer of warranty; keep intact
-all the notices that refer to this License and to the absence of any
-warranty; and distribute a copy of this License along with the
-Library.
-
- You may charge a fee for the physical act of transferring a copy,
-and you may at your option offer warranty protection in exchange for a
-fee.
-
- 2. You may modify your copy or copies of the Library or any portion
-of it, thus forming a work based on the Library, and copy and
-distribute such modifications or work under the terms of Section 1
-above, provided that you also meet all of these conditions:
-
- a) The modified work must itself be a software library.
-
- b) You must cause the files modified to carry prominent notices
- stating that you changed the files and the date of any change.
-
- c) You must cause the whole of the work to be licensed at no
- charge to all third parties under the terms of this License.
-
- d) If a facility in the modified Library refers to a function or a
- table of data to be supplied by an application program that uses
- the facility, other than as an argument passed when the facility
- is invoked, then you must make a good faith effort to ensure that,
- in the event an application does not supply such function or
- table, the facility still operates, and performs whatever part of
- its purpose remains meaningful.
-
- (For example, a function in a library to compute square roots has
- a purpose that is entirely well-defined independent of the
- application. Therefore, Subsection 2d requires that any
- application-supplied function or table used by this function must
- be optional: if the application does not supply it, the square
- root function must still compute square roots.)
-
-These requirements apply to the modified work as a whole. If
-identifiable sections of that work are not derived from the Library,
-and can be reasonably considered independent and separate works in
-themselves, then this License, and its terms, do not apply to those
-sections when you distribute them as separate works. But when you
-distribute the same sections as part of a whole which is a work based
-on the Library, the distribution of the whole must be on the terms of
-this License, whose permissions for other licensees extend to the
-entire whole, and thus to each and every part regardless of who wrote
-it.
-
-Thus, it is not the intent of this section to claim rights or contest
-your rights to work written entirely by you; rather, the intent is to
-exercise the right to control the distribution of derivative or
-collective works based on the Library.
-
-In addition, mere aggregation of another work not based on the Library
-with the Library (or with a work based on the Library) on a volume of
-a storage or distribution medium does not bring the other work under
-the scope of this License.
-
- 3. You may opt to apply the terms of the ordinary GNU General Public
-License instead of this License to a given copy of the Library. To do
-this, you must alter all the notices that refer to this License, so
-that they refer to the ordinary GNU General Public License, version 2,
-instead of to this License. (If a newer version than version 2 of the
-ordinary GNU General Public License has appeared, then you can specify
-that version instead if you wish.) Do not make any other change in
-these notices.
-
- Once this change is made in a given copy, it is irreversible for
-that copy, so the ordinary GNU General Public License applies to all
-subsequent copies and derivative works made from that copy.
-
- This option is useful when you wish to copy part of the code of
-the Library into a program that is not a library.
-
- 4. You may copy and distribute the Library (or a portion or
-derivative of it, under Section 2) in object code or executable form
-under the terms of Sections 1 and 2 above provided that you accompany
-it with the complete corresponding machine-readable source code, which
-must be distributed under the terms of Sections 1 and 2 above on a
-medium customarily used for software interchange.
-
- If distribution of object code is made by offering access to copy
-from a designated place, then offering equivalent access to copy the
-source code from the same place satisfies the requirement to
-distribute the source code, even though third parties are not
-compelled to copy the source along with the object code.
-
- 5. A program that contains no derivative of any portion of the
-Library, but is designed to work with the Library by being compiled or
-linked with it, is called a "work that uses the Library". Such a
-work, in isolation, is not a derivative work of the Library, and
-therefore falls outside the scope of this License.
-
- However, linking a "work that uses the Library" with the Library
-creates an executable that is a derivative of the Library (because it
-contains portions of the Library), rather than a "work that uses the
-library". The executable is therefore covered by this License.
-Section 6 states terms for distribution of such executables.
-
- When a "work that uses the Library" uses material from a header file
-that is part of the Library, the object code for the work may be a
-derivative work of the Library even though the source code is not.
-Whether this is true is especially significant if the work can be
-linked without the Library, or if the work is itself a library. The
-threshold for this to be true is not precisely defined by law.
-
- If such an object file uses only numerical parameters, data
-structure layouts and accessors, and small macros and small inline
-functions (ten lines or less in length), then the use of the object
-file is unrestricted, regardless of whether it is legally a derivative
-work. (Executables containing this object code plus portions of the
-Library will still fall under Section 6.)
-
- Otherwise, if the work is a derivative of the Library, you may
-distribute the object code for the work under the terms of Section 6.
-Any executables containing that work also fall under Section 6,
-whether or not they are linked directly with the Library itself.
-
- 6. As an exception to the Sections above, you may also combine or
-link a "work that uses the Library" with the Library to produce a
-work containing portions of the Library, and distribute that work
-under terms of your choice, provided that the terms permit
-modification of the work for the customer's own use and reverse
-engineering for debugging such modifications.
-
- You must give prominent notice with each copy of the work that the
-Library is used in it and that the Library and its use are covered by
-this License. You must supply a copy of this License. If the work
-during execution displays copyright notices, you must include the
-copyright notice for the Library among them, as well as a reference
-directing the user to the copy of this License. Also, you must do one
-of these things:
-
- a) Accompany the work with the complete corresponding
- machine-readable source code for the Library including whatever
- changes were used in the work (which must be distributed under
- Sections 1 and 2 above); and, if the work is an executable linked
- with the Library, with the complete machine-readable "work that
- uses the Library", as object code and/or source code, so that the
- user can modify the Library and then relink to produce a modified
- executable containing the modified Library. (It is understood
- that the user who changes the contents of definitions files in the
- Library will not necessarily be able to recompile the application
- to use the modified definitions.)
-
- b) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (1) uses at run time a
- copy of the library already present on the user's computer system,
- rather than copying library functions into the executable, and (2)
- will operate properly with a modified version of the library, if
- the user installs one, as long as the modified version is
- interface-compatible with the version that the work was made with.
-
- c) Accompany the work with a written offer, valid for at
- least three years, to give the same user the materials
- specified in Subsection 6a, above, for a charge no more
- than the cost of performing this distribution.
-
- d) If distribution of the work is made by offering access to copy
- from a designated place, offer equivalent access to copy the above
- specified materials from the same place.
-
- e) Verify that the user has already received a copy of these
- materials or that you have already sent this user a copy.
-
- For an executable, the required form of the "work that uses the
-Library" must include any data and utility programs needed for
-reproducing the executable from it. However, as a special exception,
-the materials to be distributed need not include anything that is
-normally distributed (in either source or binary form) with the major
-components (compiler, kernel, and so on) of the operating system on
-which the executable runs, unless that component itself accompanies
-the executable.
-
- It may happen that this requirement contradicts the license
-restrictions of other proprietary libraries that do not normally
-accompany the operating system. Such a contradiction means you cannot
-use both them and the Library together in an executable that you
-distribute.
-
- 7. You may place library facilities that are a work based on the
-Library side-by-side in a single library together with other library
-facilities not covered by this License, and distribute such a combined
-library, provided that the separate distribution of the work based on
-the Library and of the other library facilities is otherwise
-permitted, and provided that you do these two things:
-
- a) Accompany the combined library with a copy of the same work
- based on the Library, uncombined with any other library
- facilities. This must be distributed under the terms of the
- Sections above.
-
- b) Give prominent notice with the combined library of the fact
- that part of it is a work based on the Library, and explaining
- where to find the accompanying uncombined form of the same work.
-
- 8. You may not copy, modify, sublicense, link with, or distribute
-the Library except as expressly provided under this License. Any
-attempt otherwise to copy, modify, sublicense, link with, or
-distribute the Library is void, and will automatically terminate your
-rights under this License. However, parties who have received copies,
-or rights, from you under this License will not have their licenses
-terminated so long as such parties remain in full compliance.
-
- 9. You are not required to accept this License, since you have not
-signed it. However, nothing else grants you permission to modify or
-distribute the Library or its derivative works. These actions are
-prohibited by law if you do not accept this License. Therefore, by
-modifying or distributing the Library (or any work based on the
-Library), you indicate your acceptance of this License to do so, and
-all its terms and conditions for copying, distributing or modifying
-the Library or works based on it.
-
- 10. Each time you redistribute the Library (or any work based on the
-Library), the recipient automatically receives a license from the
-original licensor to copy, distribute, link with or modify the Library
-subject to these terms and conditions. You may not impose any further
-restrictions on the recipients' exercise of the rights granted herein.
-You are not responsible for enforcing compliance by third parties with
-this License.
-
- 11. If, as a consequence of a court judgment or allegation of patent
-infringement or for any other reason (not limited to patent issues),
-conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot
-distribute so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you
-may not distribute the Library at all. For example, if a patent
-license would not permit royalty-free redistribution of the Library by
-all those who receive copies directly or indirectly through you, then
-the only way you could satisfy both it and this License would be to
-refrain entirely from distribution of the Library.
-
-If any portion of this section is held invalid or unenforceable under any
-particular circumstance, the balance of the section is intended to apply,
-and the section as a whole is intended to apply in other circumstances.
-
-It is not the purpose of this section to induce you to infringe any
-patents or other property right claims or to contest validity of any
-such claims; this section has the sole purpose of protecting the
-integrity of the free software distribution system which is
-implemented by public license practices. Many people have made
-generous contributions to the wide range of software distributed
-through that system in reliance on consistent application of that
-system; it is up to the author/donor to decide if he or she is willing
-to distribute software through any other system and a licensee cannot
-impose that choice.
-
-This section is intended to make thoroughly clear what is believed to
-be a consequence of the rest of this License.
-
- 12. If the distribution and/or use of the Library is restricted in
-certain countries either by patents or by copyrighted interfaces, the
-original copyright holder who places the Library under this License may add
-an explicit geographical distribution limitation excluding those countries,
-so that distribution is permitted only in or among countries not thus
-excluded. In such case, this License incorporates the limitation as if
-written in the body of this License.
-
- 13. The Free Software Foundation may publish revised and/or new
-versions of the Lesser General Public License from time to time.
-Such new versions will be similar in spirit to the present version,
-but may differ in detail to address new problems or concerns.
-
-Each version is given a distinguishing version number. If the Library
-specifies a version number of this License which applies to it and
-"any later version", you have the option of following the terms and
-conditions either of that version or of any later version published by
-the Free Software Foundation. If the Library does not specify a
-license version number, you may choose any version ever published by
-the Free Software Foundation.
-
- 14. If you wish to incorporate parts of the Library into other free
-programs whose distribution conditions are incompatible with these,
-write to the author to ask for permission. For software which is
-copyrighted by the Free Software Foundation, write to the Free
-Software Foundation; we sometimes make exceptions for this. Our
-decision will be guided by the two goals of preserving the free status
-of all derivatives of our free software and of promoting the sharing
-and reuse of software generally.
-
- NO WARRANTY
-
- 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
-WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
-EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
-OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
-KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
-LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
-THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
-WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
-AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
-FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
-CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
-LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
-RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
-FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
-SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
-DAMAGES.
-
- END OF TERMS AND CONDITIONS
+ GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS diff --git a/bsp/simulator/SDL/README b/bsp/simulator/SDL/README index e9e1d1a983..7c0dd5890c 100644 --- a/bsp/simulator/SDL/README +++ b/bsp/simulator/SDL/README @@ -1,49 +1,49 @@ -
- Simple DirectMedia Layer
-
- (SDL)
-
- Version 1.2
-
----
-http://www.libsdl.org/
-
-This is the Simple DirectMedia Layer, a general API that provides low
-level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL,
-and 2D framebuffer across multiple platforms.
-
-The current version supports Linux, Windows CE/95/98/ME/XP/Vista, BeOS,
-MacOS Classic, Mac OS X, FreeBSD, NetBSD, OpenBSD, BSD/OS, Solaris, IRIX,
-and QNX. The code contains support for Dreamcast, Atari, AIX, OSF/Tru64,
-RISC OS, SymbianOS, Nintendo DS, and OS/2, but these are not officially
-supported.
-
-SDL is written in C, but works with C++ natively, and has bindings to
-several other languages, including Ada, C#, Eiffel, Erlang, Euphoria,
-Guile, Haskell, Java, Lisp, Lua, ML, Objective C, Pascal, Perl, PHP,
-Pike, Pliant, Python, Ruby, and Smalltalk.
-
-This library is distributed under GNU LGPL version 2, which can be
-found in the file "COPYING". This license allows you to use SDL
-freely in commercial programs as long as you link with the dynamic
-library.
-
-The best way to learn how to use SDL is to check out the header files in
-the "include" subdirectory and the programs in the "test" subdirectory.
-The header files and test programs are well commented and always up to date.
-More documentation is available in HTML format in "docs/index.html", and
-a documentation wiki is available online at:
- http://www.libsdl.org/cgi/docwiki.cgi
-
-The test programs in the "test" subdirectory are in the public domain.
-
-Frequently asked questions are answered online:
- http://www.libsdl.org/faq.php
-
-If you need help with the library, or just want to discuss SDL related
-issues, you can join the developers mailing list:
- http://www.libsdl.org/mailing-list.php
-
-Enjoy!
- Sam Lantinga ([email protected])
-
+ + Simple DirectMedia Layer + + (SDL) + + Version 1.2 + +--- +http://www.libsdl.org/ + +This is the Simple DirectMedia Layer, a general API that provides low +level access to audio, keyboard, mouse, joystick, 3D hardware via OpenGL, +and 2D framebuffer across multiple platforms. + +The current version supports Linux, Windows CE/95/98/ME/XP/Vista, BeOS, +MacOS Classic, Mac OS X, FreeBSD, NetBSD, OpenBSD, BSD/OS, Solaris, IRIX, +and QNX. The code contains support for Dreamcast, Atari, AIX, OSF/Tru64, +RISC OS, SymbianOS, Nintendo DS, and OS/2, but these are not officially +supported. + +SDL is written in C, but works with C++ natively, and has bindings to +several other languages, including Ada, C#, Eiffel, Erlang, Euphoria, +Guile, Haskell, Java, Lisp, Lua, ML, Objective C, Pascal, Perl, PHP, +Pike, Pliant, Python, Ruby, and Smalltalk. + +This library is distributed under GNU LGPL version 2, which can be +found in the file "COPYING". This license allows you to use SDL +freely in commercial programs as long as you link with the dynamic +library. + +The best way to learn how to use SDL is to check out the header files in +the "include" subdirectory and the programs in the "test" subdirectory. +The header files and test programs are well commented and always up to date. +More documentation is available in HTML format in "docs/index.html", and +a documentation wiki is available online at: + http://www.libsdl.org/cgi/docwiki.cgi + +The test programs in the "test" subdirectory are in the public domain. + +Frequently asked questions are answered online: + http://www.libsdl.org/faq.php + +If you need help with the library, or just want to discuss SDL related +issues, you can join the developers mailing list: + http://www.libsdl.org/mailing-list.php + +Enjoy! + Sam Lantinga ([email protected]) + diff --git a/bsp/simulator/SDL/README-SDL.txt b/bsp/simulator/SDL/README-SDL.txt index 1669736cb5..4d36ca9dce 100644 --- a/bsp/simulator/SDL/README-SDL.txt +++ b/bsp/simulator/SDL/README-SDL.txt @@ -1,13 +1,13 @@ -
-Please distribute this file with the SDL runtime environment:
-
-The Simple DirectMedia Layer (SDL for short) is a cross-platfrom library
-designed to make it easy to write multi-media software, such as games and
-emulators.
-
-The Simple DirectMedia Layer library source code is available from:
-http://www.libsdl.org/
-
-This library is distributed under the terms of the GNU LGPL license:
-http://www.gnu.org/copyleft/lesser.html
-
+ +Please distribute this file with the SDL runtime environment: + +The Simple DirectMedia Layer (SDL for short) is a cross-platfrom library +designed to make it easy to write multi-media software, such as games and +emulators. + +The Simple DirectMedia Layer library source code is available from: +http://www.libsdl.org/ + +This library is distributed under the terms of the GNU LGPL license: +http://www.gnu.org/copyleft/lesser.html + diff --git a/bsp/simulator/SDL/WhatsNew b/bsp/simulator/SDL/WhatsNew index 7fae760f7c..927fdd264f 100644 --- a/bsp/simulator/SDL/WhatsNew +++ b/bsp/simulator/SDL/WhatsNew @@ -1,727 +1,727 @@ -
-This is a list of API changes in SDL's version history.
-
-Version 1.0:
-
-1.2.14:
- Added cast macros for correct usage with C++:
- SDL_reinterpret_cast(type, expression)
- SDL_static_cast(type, expression)
-
- Added SDL_VIDEO_FULLSCREEN_DISPLAY as a preferred synonym for
- SDL_VIDEO_FULLSCREEN_HEAD on X11.
-
- Added SDL_DISABLE_LOCK_KEYS environment variable to enable normal
- up/down events for Caps-Lock and Num-Lock keys.
-
-1.2.13:
- Added SDL_BUTTON_X1 and SDL_BUTTON_X2 constants.
-
-1.2.12:
- Added SDL_VIDEO_ALLOW_SCREENSAVER to override SDL's disabling
- of the screensaver on Mac OS X and X11.
-
-1.2.10:
- If SDL_OpenAudio() is passed zero for the desired format
- fields, the following environment variables will be used
- to fill them in:
- SDL_AUDIO_FREQUENCY
- SDL_AUDIO_FORMAT
- SDL_AUDIO_CHANNELS
- SDL_AUDIO_SAMPLES
- If an environment variable is not specified, it will be set
- to a reasonable default value.
-
- Added support for the SDL_VIDEO_FULLSCREEN_HEAD environment
- variable, currently supported on X11 Xinerama configurations.
-
- Added SDL_GL_SWAP_CONTROL to wait for vsync in OpenGL applications.
-
- Added SDL_GL_ACCELERATED_VISUAL to guarantee hardware acceleration.
-
- Added current_w and current_h to the SDL_VideoInfo structure,
- which is set to the desktop resolution during video intialization,
- and then set to the current resolution when a video mode is set.
-
- SDL_SetVideoMode() now accepts 0 for width or height and will use
- the current video mode (or the desktop mode if no mode has been set.)
-
- Added SDL_GetKeyRepeat()
-
- Added SDL_config.h, with defaults for various build environments.
-
-1.2.7:
- Added CPU feature detection functions to SDL_cpuinfo.h:
- SDL_HasRDTSC(), SDL_HasMMX(), SDL_Has3DNow(), SDL_HasSSE(),
- SDL_HasAltiVec()
- Added function to create RWops from const memory: SDL_RWFromConstMem()
-
-1.2.6:
- Added SDL_LoadObject(), SDL_LoadFunction(), and SDL_UnloadObject()
-
- Added SDL_GL_MULTISAMPLEBUFFERS and SDL_GL_MULTISAMPLESAMPLES for FSAA
-
-1.2.5:
- Added SDL_BUTTON_WHEELUP (4) and SDL_BUTTON_WHEELDOWN (5)
-
- Added SDL_GL_STEREO for stereoscopic OpenGL contexts
-
-1.2.0:
- Added SDL_VIDEOEXPOSE event to signal that the screen needs to
- be redrawn. This is currently only delivered to OpenGL windows
- on X11, though it may be delivered in the future when the video
- memory is lost under DirectX.
-
-1.1.8:
- You can pass SDL_NOFRAME to SDL_VideoMode() to create a window
- that has no title bar or frame decoration. Fullscreen video
- modes automatically have this flag set.
-
- Added a function to query the clipping rectangle for a surface:
- void SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect)
-
- Added a function to query the current event filter:
- SDL_EventFilter SDL_GetEventFilter(void)
-
- If you pass -1 to SDL_ShowCursor(), it won't change the current
- cursor visibility state, but will still return it.
-
- SDL_LockSurface() and SDL_UnlockSurface() are recursive, meaning
- you can nest them as deep as you want, as long as each lock call
- has a matching unlock call. The surface remains locked until the
- last matching unlock call.
-
- Note that you may not blit to or from a locked surface.
-
-1.1.7:
- The SDL_SetGammaRamp() and SDL_GetGammaRamp() functions now take
- arrays of Uint16 values instead of Uint8 values. For the most part,
- you can just take your old values and shift them up 8 bits to get
- new correct values for your gamma ramps.
-
- You can pass SDL_RLEACCEL in flags passed to SDL_ConvertSurface()
- and SDL will try to RLE accelerate colorkey and alpha blits in the
- resulting surface.
-
-1.1.6:
- Added a function to return the thread ID of a specific thread:
- Uint32 SDL_GetThreadID(SDL_Thread *thread)
- If 'thread' is NULL, this function returns the id for this thread.
-
-1.1.5:
- The YUV overlay structure has been changed to use an array of
- pitches and pixels representing the planes of a YUV image, to
- better enable hardware acceleration. The YV12 and IYUV formats
- each have three planes, corresponding to the Y, U, and V portions
- of the image, while packed pixel YUV formats just have one plane.
-
- For palettized mode (8bpp), the screen colormap is now split in
- a physical and a logical palette. The physical palette determines
- what colours the screen pixels will get when displayed, and the
- logical palette controls the mapping from blits to/from the screen.
- A new function, SDL_SetPalette() has been added to change
- logical and physical palettes separately. SDL_SetColors() works
- just as before, and is equivalent to calling SDL_SetPalette() with
- a flag argument of (SDL_LOGPAL|SDL_PHYSPAL).
-
- SDL_BlitSurface() no longer modifies the source rectangle, only the
- destination rectangle. The width/height members of the destination
- rectangle are ignored, only the position is used.
-
- The old source clipping function SDL_SetClipping() has been replaced
- with a more useful function to set the destination clipping rectangle:
- SDL_bool SDL_SetClipRect(SDL_Surface *surface, SDL_Rect *rect)
-
- Added a function to see what subsystems have been initialized:
- Uint32 SDL_WasInit(Uint32 flags)
-
- The Big Alpha Flip: SDL now treats alpha as opacity like everybody
- else, and not as transparency:
-
- A new cpp symbol: SDL_ALPHA_OPAQUE is defined as 255
- A new cpp symbol: SDL_ALPHA_TRANSPARENT is defined as 0
- Values between 0 and 255 vary from fully transparent to fully opaque.
-
- New functions:
- SDL_DisplayFormatAlpha()
- Returns a surface converted to a format with alpha-channel
- that can be blit efficiently to the screen. (In other words,
- like SDL_DisplayFormat() but the resulting surface has
- an alpha channel.) This is useful for surfaces with alpha.
- SDL_MapRGBA()
- Works as SDL_MapRGB() but takes an additional alpha parameter.
- SDL_GetRGBA()
- Works as SDL_GetRGB() but also returns the alpha value
- (SDL_ALPHA_OPAQUE for formats without an alpha channel)
-
- Both SDL_GetRGB() and SDL_GetRGBA() now always return values in
- the [0..255] interval. Previously, SDL_GetRGB() would return
- (0xf8, 0xfc, 0xf8) for a completely white pixel in RGB565 format.
- (N.B.: This is broken for bit fields < 3 bits.)
-
- SDL_MapRGB() returns pixels in which the alpha channel is set opaque.
-
- SDL_SetAlpha() can now be used for both setting the per-surface
- alpha, using the new way of thinking of alpha, and also to enable
- and disable per-pixel alpha blending for surfaces with an alpha
- channel:
- To disable alpha blending:
- SDL_SetAlpha(surface, 0, 0);
- To re-enable alpha blending:
- SDL_SetAlpha(surface, SDL_SRCALPHA, 0);
- Surfaces with an alpha channel have blending enabled by default.
-
- SDL_SetAlpha() now accepts SDL_RLEACCEL as a flag, which requests
- RLE acceleration of blits, just as like with SDL_SetColorKey().
- This flag can be set for both surfaces with an alpha channel
- and surfaces with an alpha value set by SDL_SetAlpha().
- As always, RLE surfaces must be locked before pixel access is
- allowed, and unlocked before any other SDL operations are done
- on it.
-
- The blit semantics for surfaces with and without alpha and colorkey
- have now been defined:
-
- RGBA->RGB:
- SDL_SRCALPHA set:
- alpha-blend (using alpha-channel).
- SDL_SRCCOLORKEY ignored.
- SDL_SRCALPHA not set:
- copy RGB.
- if SDL_SRCCOLORKEY set, only copy the pixels matching the
- RGB values of the source colour key, ignoring alpha in the
- comparison.
-
- RGB->RGBA:
- SDL_SRCALPHA set:
- alpha-blend (using the source per-surface alpha value);
- set destination alpha to opaque.
- SDL_SRCALPHA not set:
- copy RGB, set destination alpha to opaque.
- both:
- if SDL_SRCCOLORKEY set, only copy the pixels matching the
- source colour key.
-
- RGBA->RGBA:
- SDL_SRCALPHA set:
- alpha-blend (using the source alpha channel) the RGB values;
- leave destination alpha untouched. [Note: is this correct?]
- SDL_SRCCOLORKEY ignored.
- SDL_SRCALPHA not set:
- copy all of RGBA to the destination.
- if SDL_SRCCOLORKEY set, only copy the pixels matching the
- RGB values of the source colour key, ignoring alpha in the
- comparison.
-
- RGB->RGB:
- SDL_SRCALPHA set:
- alpha-blend (using the source per-surface alpha value).
- SDL_SRCALPHA not set:
- copy RGB.
- both:
- if SDL_SRCCOLORKEY set, only copy the pixels matching the
- source colour key.
-
- As a special case, blits from surfaces with per-surface alpha
- value of 128 (50% transparency) are optimised and much faster
- than other alpha values. This does not apply to surfaces with
- alpha channels (per-pixel alpha).
-
- New functions for manipulating the gamma of the display have
- been added:
- int SDL_SetGamma(float red, float green, float blue);
- int SDL_SetGammaRamp(Uint8 *red, Uint8 *green, Uint8 *blue);
- int SDL_GetGammaRamp(Uint8 *red, Uint8 *green, Uint8 *blue);
- Gamma ramps are tables with 256 entries which map the screen color
- components into actually displayed colors. For an example of
- implementing gamma correction and gamma fades, see test/testgamma.c
- Gamma control is not supported on all hardware.
-
-1.1.4:
- The size of the SDL_CDtrack structure changed from 8 to 12 bytes
- as the size of the length member was extended to 32 bits.
-
- You can now use SDL for 2D blitting with a GL mode by passing the
- SDL_OPENGLBLIT flag to SDL_SetVideoMode(). You can specify 16 or
- 32 bpp, and the data in the framebuffer is put into the GL scene
- when you call SDL_UpdateRects(), and the scene will be visible
- when you call SDL_GL_SwapBuffers().
-
- Run the "testgl" test program with the -logo command line option
- to see an example of this blending of 2D and 3D in SDL.
-
-1.1.3:
- Added SDL_FreeRW() to the API, to complement SDL_AllocRW()
-
- Added resizable window support - just add SDL_RESIZABLE to the
- SDL_SetVideoMode() flags, and then wait for SDL_VIDEORESIZE events.
- See SDL_events.h for details on the new SDL_ResizeEvent structure.
-
- Added condition variable support, based on mutexes and semaphores.
- SDL_CreateCond()
- SDL_DestroyCond()
- SDL_CondSignal()
- SDL_CondBroadcast()
- SDL_CondWait()
- SDL_CondTimedWait()
- The new function prototypes are in SDL_mutex.h
-
- Added counting semaphore support, based on the mutex primitive.
- SDL_CreateSemaphore()
- SDL_DestroySemaphore()
- SDL_SemWait()
- SDL_SemTryWait()
- SDL_SemWaitTimeout()
- SDL_SemPost()
- SDL_SemValue()
- The new function prototypes are in SDL_mutex.h
-
- Added support for asynchronous blitting. To take advantage of this,
- you must set the SDL_ASYNCBLIT flag when setting the video mode and
- creating surfaces that you want accelerated in this way. You must
- lock surfaces that have this flag set, and the lock will block until
- any queued blits have completed.
-
- Added YUV video overlay support.
- The supported YUV formats are: YV12, IYUV, YUY2, UYVY, and YVYU.
- This function creates an overlay surface:
- SDL_CreateYUVOverlay()
- You must lock and unlock the overlay to get access to the data:
- SDL_LockYUVOverlay() SDL_UnlockYUVOverlay()
- You can then display the overlay:
- SDL_DisplayYUVOverlay()
- You must free the overlay when you are done using it:
- SDL_FreeYUVOverlay()
- See SDL_video.h for the full function prototypes.
-
- The joystick hat position constants have been changed:
- Old constant New constant
- ------------ ------------
- 0 SDL_HAT_CENTERED
- 1 SDL_HAT_UP
- 2 SDL_HAT_RIGHTUP
- 3 SDL_HAT_RIGHT
- 4 SDL_HAT_RIGHTDOWN
- 5 SDL_HAT_DOWN
- 6 SDL_HAT_LEFTDOWN
- 7 SDL_HAT_LEFT
- 8 SDL_HAT_LEFTUP
- The new constants are bitmasks, so you can check for the
- individual axes like this:
- if ( hat_position & SDL_HAT_UP ) {
- }
- and you'll catch left-up, up, and right-up.
-
-1.1.2:
- Added multiple timer support:
- SDL_AddTimer() and SDL_RemoveTimer()
-
- SDL_WM_SetIcon() now respects the icon colorkey if mask is NULL.
-
-1.1.0:
- Added initial OpenGL support.
- First set GL attributes (such as RGB depth, alpha depth, etc.)
- SDL_GL_SetAttribute()
- Then call SDL_SetVideoMode() with the SDL_OPENGL flag.
- Perform all of your normal GL drawing.
- Finally swap the buffers with the new SDL function:
- SDL_GL_SwapBuffers()
- See the new 'testgl' test program for an example of using GL with SDL.
-
- You can load GL extension functions by using the function:
- SDL_GL_LoadProcAddress()
-
- Added functions to initialize and cleanup specific SDL subsystems:
- SDL_InitSubSystem() and SDL_QuitSubSystem()
-
- Added user-defined event type:
- typedef struct {
- Uint8 type;
- int code;
- void *data1;
- void *data2;
- } SDL_UserEvent;
- This structure is in the "user" member of an SDL_Event.
-
- Added a function to push events into the event queue:
- SDL_PushEvent()
-
- Example of using the new SDL user-defined events:
- {
- SDL_Event event;
-
- event.type = SDL_USEREVENT;
- event.user.code = my_event_code;
- event.user.data1 = significant_data;
- event.user.data2 = 0;
- SDL_PushEvent(&event);
- }
-
- Added a function to get mouse deltas since last query:
- SDL_GetRelativeMouseState()
-
- Added a boolean datatype to SDL_types.h:
- SDL_bool = { SDL_TRUE, SDL_FALSE }
-
- Added a function to get the current audio status:
- SDL_GetAudioState();
- It returns one of:
- SDL_AUDIO_STOPPED,
- SDL_AUDIO_PLAYING,
- SDL_AUDIO_PAUSED
-
- Added an AAlib driver (ASCII Art) - by Stephane Peter.
-
-1.0.6:
- The input grab state is reset after each call to SDL_SetVideoMode().
- The input is grabbed by default in fullscreen mode, and ungrabbed in
- windowed mode. If you want to set input grab to a particular value,
- you should set it after each call to SDL_SetVideoMode().
-
-1.0.5:
- Exposed SDL_AudioInit(), SDL_VideoInit()
- Added SDL_AudioDriverName() and SDL_VideoDriverName()
-
- Added new window manager function:
- SDL_WM_ToggleFullScreen()
- This is currently implemented only on Linux
-
- The ALT-ENTER code has been removed - it's not appropriate for a
- lib to bind keys when they aren't even emergency escape sequences.
-
- ALT-ENTER functionality can be implemented with the following code:
-
- int Handle_AltEnter(const SDL_Event *event)
- {
- if ( event->type == SDL_KEYDOWN ) {
- if ( (event->key.keysym.sym == SDLK_RETURN) &&
- (event->key.keysym.mod & KMOD_ALT) ) {
- SDL_WM_ToggleFullScreen(SDL_GetVideoSurface());
- return(0);
- }
- }
- return(1);
- }
- SDL_SetEventFilter(Handle_AltEnter);
-
-1.0.3:
- Under X11, if you grab the input and hide the mouse cursor,
- the mouse will go into a "relative motion" mode where you
- will always get relative motion events no matter how far in
- each direction you move the mouse - relative motion is not
- bounded by the edges of the window (though the absolute values
- of the mouse positions are clamped by the size of the window).
- The SVGAlib, framebuffer console, and DirectInput drivers all
- have this behavior naturally, and the GDI and BWindow drivers
- never go into "relative motion" mode.
-
-1.0.2:
- Added a function to enable keyboard repeat:
- SDL_EnableKeyRepeat()
-
- Added a function to grab the mouse and keyboard input
- SDL_WM_GrabInput()
-
- Added a function to iconify the window.
- SDL_WM_IconifyWindow()
- If this function succeeds, the application will receive an event
- signaling SDL_APPACTIVE event
-
-1.0.1:
- Added constants to SDL_audio.h for 16-bit native byte ordering:
- AUDIO_U16SYS, AUDIO_S16SYS
-
-1.0.0:
- New public release
-
-Version 0.11:
-
-0.11.5:
- A new function SDL_GetVideoSurface() has been added, and returns
- a pointer to the current display surface.
-
- SDL_AllocSurface() has been renamed SDL_CreateRGBSurface(), and
- a new function SDL_CreateRGBSurfaceFrom() has been added to allow
- creating an SDL surface from an existing pixel data buffer.
-
- Added SDL_GetRGB() to the headers and documentation.
-
-0.11.4:
- SDL_SetLibraryPath() is no longer meaningful, and has been removed.
-
-0.11.3:
- A new flag for SDL_Init(), SDL_INIT_NOPARACHUTE, prevents SDL from
- installing fatal signal handlers on operating systems that support
- them.
-
-Version 0.9:
-
-0.9.15:
- SDL_CreateColorCursor() has been removed. Color cursors should
- be implemented as sprites, blitted by the application when the
- cursor moves. To get smooth color cursor updates when the app
- is busy, pass the SDL_INIT_EVENTTHREAD flag to SDL_Init(). This
- allows you to handle the mouse motion in another thread from an
- event filter function, but is currently only supported by Linux
- and BeOS. Note that you'll have to protect the display surface
- from multi-threaded access by using mutexes if you do this.
-
- Thread-safe surface support has been removed from SDL.
- This makes blitting somewhat faster, by removing SDL_MiddleBlit().
- Code that used SDL_MiddleBlit() should use SDL_LowerBlit() instead.
- You can make your surfaces thread-safe by allocating your own
- mutex and making lock/unlock calls around accesses to your surface.
-
-0.9.14:
- SDL_GetMouseState() now takes pointers to int rather than Uint16.
-
- If you set the SDL_WINDOWID environment variable under UNIX X11,
- SDL will use that as the main window instead of creating it's own.
- This is an unsupported extension to SDL, and not portable at all.
-
-0.9.13:
- Added a function SDL_SetLibraryPath() which can be used to specify
- the directory containing the SDL dynamic libraries. This is useful
- for commercial applications which ship with particular versions
- of the libraries, and for security on multi-user systems.
- If this function is not used, the default system directories are
- searched using the native dynamic object loading mechanism.
-
- In order to support C linkage under Visual C++, you must declare
- main() without any return type:
- main(int argc, char *argv[]) {
- /* Do the program... */
- return(0);
- }
- C++ programs should also return a value if compiled under VC++.
-
- The blit_endian member of the SDL_VideoInfo struct has been removed.
-
- SDL_SymToASCII() has been replaced with SDL_GetKeyName(), so there
- is now no longer any function to translate a keysym to a character.
-
- The SDL_keysym structure has been extended with a 'scancode' and
- 'unicode' member. The 'scancode' is a hardware specific scancode
- for the key that was pressed, and may be 0. The 'unicode' member
- is a 16-bit UNICODE translation of the key that was pressed along
- with any modifiers or compose keys that have been pressed.
- If no UNICODE translation exists for the key, 'unicode' will be 0.
-
- Added a function SDL_EnableUNICODE() to enable/disable UNICODE
- translation of character keypresses. Translation defaults off.
-
- To convert existing code to use the new API, change code which
- uses SDL_SymToASCII() to get the keyname to use SDL_GetKeyName(),
- and change code which uses it to get the ASCII value of a sym to
- use the 'unicode' member of the event keysym.
-
-0.9.12:
- There is partial support for 64-bit datatypes. I don't recommend
- you use this if you have a choice, because 64-bit datatypes are not
- supported on many platforms. On platforms for which it is supported,
- the SDL_HAS_64BIT_TYPE C preprocessor define will be enabled, and
- you can use the Uint64 and Sint64 datatypes.
-
- Added functions to SDL_endian.h to support 64-bit datatypes:
- SDL_SwapLE64(), SDL_SwapBE64(),
- SDL_ReadLE64(), SDL_ReadBE64(), SDL_WriteLE64(), SDL_WriteBE64()
-
- A new member "len_ratio" has been added to the SDL_AudioCVT structure,
- and allows you to determine either the original buffer length or the
- converted buffer length, given the other.
-
- A new function SDL_FreeWAV() has been added to the API to free data
- allocated by SDL_LoadWAV_RW(). This is necessary under Win32 since
- the gcc compiled DLL uses a different heap than VC++ compiled apps.
-
- SDL now has initial support for international keyboards using the
- Latin character set.
- If a particular mapping is desired, you can set the DEFAULT_KEYBOARD
- compile-time variable, or you can set the environment variable
- "SDL_KEYBOARD" to a string identifying the keyboard mapping you desire.
- The valid values for these variables can be found in SDL_keyboard.c
-
- Full support for German and French keyboards under X11 is implemented.
-
-0.9.11:
- The THREADED_EVENTS compile-time define has been replaced with the
- SDL_INIT_EVENTTHREAD flag. If this flag is passed to SDL_Init(),
- SDL will create a separate thread to perform input event handling.
- If this flag is passed to SDL_Init(), and the OS doesn't support
- event handling in a separate thread, SDL_Init() will fail.
- Be sure to add calls to SDL_Delay() in your main thread to allow
- the OS to schedule your event thread, or it may starve, leading
- to slow event delivery and/or dropped events.
- Currently MacOS and Win32 do not support this flag, while BeOS
- and Linux do support it. I recommend that your application only
- use this flag if absolutely necessary.
-
- The SDL thread function passed to SDL_CreateThread() now returns a
- status. This status can be retrieved by passing a non-NULL pointer
- as the 'status' argument to SDL_WaitThread().
-
- The volume parameter to SDL_MixAudio() has been increased in range
- from (0-8) to (0-128)
-
- SDL now has a data source abstraction which can encompass a file,
- an area of memory, or any custom object you can envision. It uses
- these abstractions, SDL_RWops, in the endian read/write functions,
- and the built-in WAV and BMP file loaders. This means you can load
- WAV chunks from memory mapped files, compressed archives, network
- pipes, or anything else that has a data read abstraction.
-
- There are three built-in data source abstractions:
- SDL_RWFromFile(), SDL_RWFromFP(), SDL_RWFromMem()
- along with a generic data source allocation function:
- SDL_AllocRW()
- These data sources can be used like stdio file pointers with the
- following convenience functions:
- SDL_RWseek(), SDL_RWread(), SDL_RWwrite(), SDL_RWclose()
- These functions are defined in the new header file "SDL_rwops.h"
-
- The endian swapping functions have been turned into macros for speed
- and SDL_CalculateEndian() has been removed. SDL_endian.h now defines
- SDL_BYTEORDER as either SDL_BIG_ENDIAN or SDL_LIL_ENDIAN depending on
- the endianness of the host system.
-
- The endian read/write functions now take an SDL_RWops pointer
- instead of a stdio FILE pointer, to support the new data source
- abstraction.
-
- The SDL_*LoadWAV() functions have been replaced with a single
- SDL_LoadWAV_RW() function that takes a SDL_RWops pointer as it's
- first parameter, and a flag whether or not to automatically
- free it as the second parameter. SDL_LoadWAV() is a macro for
- backward compatibility and convenience:
- SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...);
-
- The SDL_*LoadBMP()/SDL_*SaveBMP() functions have each been replaced
- with a single function that takes a SDL_RWops pointer as it's
- first parameter, and a flag whether or not to automatically
- free it as the second parameter. SDL_LoadBMP() and SDL_SaveBMP()
- are macros for backward compatibility and convenience:
- SDL_LoadBMP_RW(SDL_RWFromFile("sample.bmp", "rb"), 1, ...);
- SDL_SaveBMP_RW(SDL_RWFromFile("sample.bmp", "wb"), 1, ...);
- Note that these functions use SDL_RWseek() extensively, and should
- not be used on pipes or other non-seekable data sources.
-
-0.9.10:
- The Linux SDL_SysWMInfo and SDL_SysWMMsg structures have been
- extended to support multiple types of display drivers, as well as
- safe access to the X11 display when THREADED_EVENTS is enabled.
- The new structures are documented in the SDL_syswm.h header file.
-
- Thanks to John Elliott <[email protected]>, the UK keyboard
- should now work properly, as well as the "Windows" keys on US
- keyboards.
-
- The Linux CD-ROM code now reads the CD-ROM devices from /etc/fstab
- instead of trying to open each block device on the system.
- The CD must be listed in /etc/fstab as using the iso9660 filesystem.
-
- On Linux, if you define THREADED_EVENTS at compile time, a separate
- thread will be spawned to gather X events asynchronously from the
- graphics updates. This hasn't been extensively tested, but it does
- provide a means of handling keyboard and mouse input in a separate
- thread from the graphics thread. (This is now enabled by default.)
-
- A special access function SDL_PeepEvents() allows you to manipulate
- the event queue in a thread-safe manner, including peeking at events,
- removing events of a specified type, and adding new events of arbitrary
- type to the queue (use the new 'user' member of the SDL_Event type).
-
- If you use SDL_PeepEvents() to gather events, then the main graphics
- thread needs to call SDL_PumpEvents() periodically to drive the event
- loop and generate input events. This is not necessary if SDL has been
- compiled with THREADED_EVENTS defined, but doesn't hurt.
-
- A new function SDL_ThreadID() returns the identifier associated with
- the current thread.
-
-0.9.9:
- The AUDIO_STEREO format flag has been replaced with a new 'channels'
- member of the SDL_AudioSpec structure. The channels are 1 for mono
- audio, and 2 for stereo audio. In the future more channels may be
- supported for 3D surround sound.
-
- The SDL_MixAudio() function now takes an additional volume parameter,
- which should be set to SDL_MIX_MAXVOLUME for compatibility with the
- original function.
-
- The CD-ROM functions which take a 'cdrom' parameter can now be
- passed NULL, and will act on the last successfully opened CD-ROM.
-
-0.9.8:
- No changes, bugfixes only.
-
-0.9.7:
- No changes, bugfixes only.
-
-0.9.6:
- Added a fast rectangle fill function: SDL_FillRect()
-
- Addition of a useful function for getting info on the video hardware:
- const SDL_VideoInfo *SDL_GetVideoInfo(void)
- This function replaces SDL_GetDisplayFormat().
-
- Initial support for double-buffering:
- Use the SDL_DOUBLEBUF flag in SDL_SetVideoMode()
- Update the screen with a new function: SDL_Flip()
-
- SDL_AllocSurface() takes two new flags:
- SDL_SRCCOLORKEY means that the surface will be used for colorkey blits
- and if the hardware supports hardware acceleration of colorkey blits
- between two surfaces in video memory, to place the surface in video
- memory if possible, otherwise it will be placed in system memory.
- SDL_SRCALPHA means that the surface will be used for alpha blits and
- if the hardware supports hardware acceleration of alpha blits between
- two surfaces in video memory, to place the surface in video memory
- if possible, otherwise it will be placed in system memory.
- SDL_HWSURFACE now means that the surface will be created with the
- same format as the display surface, since having surfaces in video
- memory is only useful for fast blitting to the screen, and you can't
- blit surfaces with different surface formats in video memory.
-
-0.9.5:
- You can now pass a NULL mask to SDL_WM_SetIcon(), and it will assume
- that the icon consists of the entire image.
-
- SDL_LowerBlit() is back -- but don't use it on the display surface.
- It is exactly the same as SDL_MiddleBlit(), but doesn't check for
- thread safety.
-
- Added SDL_FPLoadBMP(), SDL_FPSaveBMP(), SDL_FPLoadWAV(), which take
- a FILE pointer instead of a file name.
-
- Added CD-ROM audio control API:
- SDL_CDNumDrives()
- SDL_CDName()
- SDL_CDOpen()
- SDL_CDStatus()
- SDL_CDPlayTracks()
- SDL_CDPlay()
- SDL_CDPause()
- SDL_CDResume()
- SDL_CDStop()
- SDL_CDEject()
- SDL_CDClose()
-
-0.9.4:
- No changes, bugfixes only.
-
-0.9.3:
- Mouse motion event now includes relative motion information:
- Sint16 event->motion.xrel, Sint16 event->motion.yrel
-
- X11 keyrepeat handling can be disabled by defining IGNORE_X_KEYREPEAT
- (Add -DIGNORE_X_KEYREPEAT to CFLAGS line in obj/x11Makefile)
-
-0.9.2:
- No changes, bugfixes only.
-
-0.9.1:
- Removed SDL_MapSurface() and SDL_UnmapSurface() -- surfaces are now
- automatically mapped on blit.
-
-0.8.0:
- SDL stable release
+ +This is a list of API changes in SDL's version history. + +Version 1.0: + +1.2.14: + Added cast macros for correct usage with C++: + SDL_reinterpret_cast(type, expression) + SDL_static_cast(type, expression) + + Added SDL_VIDEO_FULLSCREEN_DISPLAY as a preferred synonym for + SDL_VIDEO_FULLSCREEN_HEAD on X11. + + Added SDL_DISABLE_LOCK_KEYS environment variable to enable normal + up/down events for Caps-Lock and Num-Lock keys. + +1.2.13: + Added SDL_BUTTON_X1 and SDL_BUTTON_X2 constants. + +1.2.12: + Added SDL_VIDEO_ALLOW_SCREENSAVER to override SDL's disabling + of the screensaver on Mac OS X and X11. + +1.2.10: + If SDL_OpenAudio() is passed zero for the desired format + fields, the following environment variables will be used + to fill them in: + SDL_AUDIO_FREQUENCY + SDL_AUDIO_FORMAT + SDL_AUDIO_CHANNELS + SDL_AUDIO_SAMPLES + If an environment variable is not specified, it will be set + to a reasonable default value. + + Added support for the SDL_VIDEO_FULLSCREEN_HEAD environment + variable, currently supported on X11 Xinerama configurations. + + Added SDL_GL_SWAP_CONTROL to wait for vsync in OpenGL applications. + + Added SDL_GL_ACCELERATED_VISUAL to guarantee hardware acceleration. + + Added current_w and current_h to the SDL_VideoInfo structure, + which is set to the desktop resolution during video intialization, + and then set to the current resolution when a video mode is set. + + SDL_SetVideoMode() now accepts 0 for width or height and will use + the current video mode (or the desktop mode if no mode has been set.) + + Added SDL_GetKeyRepeat() + + Added SDL_config.h, with defaults for various build environments. + +1.2.7: + Added CPU feature detection functions to SDL_cpuinfo.h: + SDL_HasRDTSC(), SDL_HasMMX(), SDL_Has3DNow(), SDL_HasSSE(), + SDL_HasAltiVec() + Added function to create RWops from const memory: SDL_RWFromConstMem() + +1.2.6: + Added SDL_LoadObject(), SDL_LoadFunction(), and SDL_UnloadObject() + + Added SDL_GL_MULTISAMPLEBUFFERS and SDL_GL_MULTISAMPLESAMPLES for FSAA + +1.2.5: + Added SDL_BUTTON_WHEELUP (4) and SDL_BUTTON_WHEELDOWN (5) + + Added SDL_GL_STEREO for stereoscopic OpenGL contexts + +1.2.0: + Added SDL_VIDEOEXPOSE event to signal that the screen needs to + be redrawn. This is currently only delivered to OpenGL windows + on X11, though it may be delivered in the future when the video + memory is lost under DirectX. + +1.1.8: + You can pass SDL_NOFRAME to SDL_VideoMode() to create a window + that has no title bar or frame decoration. Fullscreen video + modes automatically have this flag set. + + Added a function to query the clipping rectangle for a surface: + void SDL_GetClipRect(SDL_Surface *surface, SDL_Rect *rect) + + Added a function to query the current event filter: + SDL_EventFilter SDL_GetEventFilter(void) + + If you pass -1 to SDL_ShowCursor(), it won't change the current + cursor visibility state, but will still return it. + + SDL_LockSurface() and SDL_UnlockSurface() are recursive, meaning + you can nest them as deep as you want, as long as each lock call + has a matching unlock call. The surface remains locked until the + last matching unlock call. + + Note that you may not blit to or from a locked surface. + +1.1.7: + The SDL_SetGammaRamp() and SDL_GetGammaRamp() functions now take + arrays of Uint16 values instead of Uint8 values. For the most part, + you can just take your old values and shift them up 8 bits to get + new correct values for your gamma ramps. + + You can pass SDL_RLEACCEL in flags passed to SDL_ConvertSurface() + and SDL will try to RLE accelerate colorkey and alpha blits in the + resulting surface. + +1.1.6: + Added a function to return the thread ID of a specific thread: + Uint32 SDL_GetThreadID(SDL_Thread *thread) + If 'thread' is NULL, this function returns the id for this thread. + +1.1.5: + The YUV overlay structure has been changed to use an array of + pitches and pixels representing the planes of a YUV image, to + better enable hardware acceleration. The YV12 and IYUV formats + each have three planes, corresponding to the Y, U, and V portions + of the image, while packed pixel YUV formats just have one plane. + + For palettized mode (8bpp), the screen colormap is now split in + a physical and a logical palette. The physical palette determines + what colours the screen pixels will get when displayed, and the + logical palette controls the mapping from blits to/from the screen. + A new function, SDL_SetPalette() has been added to change + logical and physical palettes separately. SDL_SetColors() works + just as before, and is equivalent to calling SDL_SetPalette() with + a flag argument of (SDL_LOGPAL|SDL_PHYSPAL). + + SDL_BlitSurface() no longer modifies the source rectangle, only the + destination rectangle. The width/height members of the destination + rectangle are ignored, only the position is used. + + The old source clipping function SDL_SetClipping() has been replaced + with a more useful function to set the destination clipping rectangle: + SDL_bool SDL_SetClipRect(SDL_Surface *surface, SDL_Rect *rect) + + Added a function to see what subsystems have been initialized: + Uint32 SDL_WasInit(Uint32 flags) + + The Big Alpha Flip: SDL now treats alpha as opacity like everybody + else, and not as transparency: + + A new cpp symbol: SDL_ALPHA_OPAQUE is defined as 255 + A new cpp symbol: SDL_ALPHA_TRANSPARENT is defined as 0 + Values between 0 and 255 vary from fully transparent to fully opaque. + + New functions: + SDL_DisplayFormatAlpha() + Returns a surface converted to a format with alpha-channel + that can be blit efficiently to the screen. (In other words, + like SDL_DisplayFormat() but the resulting surface has + an alpha channel.) This is useful for surfaces with alpha. + SDL_MapRGBA() + Works as SDL_MapRGB() but takes an additional alpha parameter. + SDL_GetRGBA() + Works as SDL_GetRGB() but also returns the alpha value + (SDL_ALPHA_OPAQUE for formats without an alpha channel) + + Both SDL_GetRGB() and SDL_GetRGBA() now always return values in + the [0..255] interval. Previously, SDL_GetRGB() would return + (0xf8, 0xfc, 0xf8) for a completely white pixel in RGB565 format. + (N.B.: This is broken for bit fields < 3 bits.) + + SDL_MapRGB() returns pixels in which the alpha channel is set opaque. + + SDL_SetAlpha() can now be used for both setting the per-surface + alpha, using the new way of thinking of alpha, and also to enable + and disable per-pixel alpha blending for surfaces with an alpha + channel: + To disable alpha blending: + SDL_SetAlpha(surface, 0, 0); + To re-enable alpha blending: + SDL_SetAlpha(surface, SDL_SRCALPHA, 0); + Surfaces with an alpha channel have blending enabled by default. + + SDL_SetAlpha() now accepts SDL_RLEACCEL as a flag, which requests + RLE acceleration of blits, just as like with SDL_SetColorKey(). + This flag can be set for both surfaces with an alpha channel + and surfaces with an alpha value set by SDL_SetAlpha(). + As always, RLE surfaces must be locked before pixel access is + allowed, and unlocked before any other SDL operations are done + on it. + + The blit semantics for surfaces with and without alpha and colorkey + have now been defined: + + RGBA->RGB: + SDL_SRCALPHA set: + alpha-blend (using alpha-channel). + SDL_SRCCOLORKEY ignored. + SDL_SRCALPHA not set: + copy RGB. + if SDL_SRCCOLORKEY set, only copy the pixels matching the + RGB values of the source colour key, ignoring alpha in the + comparison. + + RGB->RGBA: + SDL_SRCALPHA set: + alpha-blend (using the source per-surface alpha value); + set destination alpha to opaque. + SDL_SRCALPHA not set: + copy RGB, set destination alpha to opaque. + both: + if SDL_SRCCOLORKEY set, only copy the pixels matching the + source colour key. + + RGBA->RGBA: + SDL_SRCALPHA set: + alpha-blend (using the source alpha channel) the RGB values; + leave destination alpha untouched. [Note: is this correct?] + SDL_SRCCOLORKEY ignored. + SDL_SRCALPHA not set: + copy all of RGBA to the destination. + if SDL_SRCCOLORKEY set, only copy the pixels matching the + RGB values of the source colour key, ignoring alpha in the + comparison. + + RGB->RGB: + SDL_SRCALPHA set: + alpha-blend (using the source per-surface alpha value). + SDL_SRCALPHA not set: + copy RGB. + both: + if SDL_SRCCOLORKEY set, only copy the pixels matching the + source colour key. + + As a special case, blits from surfaces with per-surface alpha + value of 128 (50% transparency) are optimised and much faster + than other alpha values. This does not apply to surfaces with + alpha channels (per-pixel alpha). + + New functions for manipulating the gamma of the display have + been added: + int SDL_SetGamma(float red, float green, float blue); + int SDL_SetGammaRamp(Uint8 *red, Uint8 *green, Uint8 *blue); + int SDL_GetGammaRamp(Uint8 *red, Uint8 *green, Uint8 *blue); + Gamma ramps are tables with 256 entries which map the screen color + components into actually displayed colors. For an example of + implementing gamma correction and gamma fades, see test/testgamma.c + Gamma control is not supported on all hardware. + +1.1.4: + The size of the SDL_CDtrack structure changed from 8 to 12 bytes + as the size of the length member was extended to 32 bits. + + You can now use SDL for 2D blitting with a GL mode by passing the + SDL_OPENGLBLIT flag to SDL_SetVideoMode(). You can specify 16 or + 32 bpp, and the data in the framebuffer is put into the GL scene + when you call SDL_UpdateRects(), and the scene will be visible + when you call SDL_GL_SwapBuffers(). + + Run the "testgl" test program with the -logo command line option + to see an example of this blending of 2D and 3D in SDL. + +1.1.3: + Added SDL_FreeRW() to the API, to complement SDL_AllocRW() + + Added resizable window support - just add SDL_RESIZABLE to the + SDL_SetVideoMode() flags, and then wait for SDL_VIDEORESIZE events. + See SDL_events.h for details on the new SDL_ResizeEvent structure. + + Added condition variable support, based on mutexes and semaphores. + SDL_CreateCond() + SDL_DestroyCond() + SDL_CondSignal() + SDL_CondBroadcast() + SDL_CondWait() + SDL_CondTimedWait() + The new function prototypes are in SDL_mutex.h + + Added counting semaphore support, based on the mutex primitive. + SDL_CreateSemaphore() + SDL_DestroySemaphore() + SDL_SemWait() + SDL_SemTryWait() + SDL_SemWaitTimeout() + SDL_SemPost() + SDL_SemValue() + The new function prototypes are in SDL_mutex.h + + Added support for asynchronous blitting. To take advantage of this, + you must set the SDL_ASYNCBLIT flag when setting the video mode and + creating surfaces that you want accelerated in this way. You must + lock surfaces that have this flag set, and the lock will block until + any queued blits have completed. + + Added YUV video overlay support. + The supported YUV formats are: YV12, IYUV, YUY2, UYVY, and YVYU. + This function creates an overlay surface: + SDL_CreateYUVOverlay() + You must lock and unlock the overlay to get access to the data: + SDL_LockYUVOverlay() SDL_UnlockYUVOverlay() + You can then display the overlay: + SDL_DisplayYUVOverlay() + You must free the overlay when you are done using it: + SDL_FreeYUVOverlay() + See SDL_video.h for the full function prototypes. + + The joystick hat position constants have been changed: + Old constant New constant + ------------ ------------ + 0 SDL_HAT_CENTERED + 1 SDL_HAT_UP + 2 SDL_HAT_RIGHTUP + 3 SDL_HAT_RIGHT + 4 SDL_HAT_RIGHTDOWN + 5 SDL_HAT_DOWN + 6 SDL_HAT_LEFTDOWN + 7 SDL_HAT_LEFT + 8 SDL_HAT_LEFTUP + The new constants are bitmasks, so you can check for the + individual axes like this: + if ( hat_position & SDL_HAT_UP ) { + } + and you'll catch left-up, up, and right-up. + +1.1.2: + Added multiple timer support: + SDL_AddTimer() and SDL_RemoveTimer() + + SDL_WM_SetIcon() now respects the icon colorkey if mask is NULL. + +1.1.0: + Added initial OpenGL support. + First set GL attributes (such as RGB depth, alpha depth, etc.) + SDL_GL_SetAttribute() + Then call SDL_SetVideoMode() with the SDL_OPENGL flag. + Perform all of your normal GL drawing. + Finally swap the buffers with the new SDL function: + SDL_GL_SwapBuffers() + See the new 'testgl' test program for an example of using GL with SDL. + + You can load GL extension functions by using the function: + SDL_GL_LoadProcAddress() + + Added functions to initialize and cleanup specific SDL subsystems: + SDL_InitSubSystem() and SDL_QuitSubSystem() + + Added user-defined event type: + typedef struct { + Uint8 type; + int code; + void *data1; + void *data2; + } SDL_UserEvent; + This structure is in the "user" member of an SDL_Event. + + Added a function to push events into the event queue: + SDL_PushEvent() + + Example of using the new SDL user-defined events: + { + SDL_Event event; + + event.type = SDL_USEREVENT; + event.user.code = my_event_code; + event.user.data1 = significant_data; + event.user.data2 = 0; + SDL_PushEvent(&event); + } + + Added a function to get mouse deltas since last query: + SDL_GetRelativeMouseState() + + Added a boolean datatype to SDL_types.h: + SDL_bool = { SDL_TRUE, SDL_FALSE } + + Added a function to get the current audio status: + SDL_GetAudioState(); + It returns one of: + SDL_AUDIO_STOPPED, + SDL_AUDIO_PLAYING, + SDL_AUDIO_PAUSED + + Added an AAlib driver (ASCII Art) - by Stephane Peter. + +1.0.6: + The input grab state is reset after each call to SDL_SetVideoMode(). + The input is grabbed by default in fullscreen mode, and ungrabbed in + windowed mode. If you want to set input grab to a particular value, + you should set it after each call to SDL_SetVideoMode(). + +1.0.5: + Exposed SDL_AudioInit(), SDL_VideoInit() + Added SDL_AudioDriverName() and SDL_VideoDriverName() + + Added new window manager function: + SDL_WM_ToggleFullScreen() + This is currently implemented only on Linux + + The ALT-ENTER code has been removed - it's not appropriate for a + lib to bind keys when they aren't even emergency escape sequences. + + ALT-ENTER functionality can be implemented with the following code: + + int Handle_AltEnter(const SDL_Event *event) + { + if ( event->type == SDL_KEYDOWN ) { + if ( (event->key.keysym.sym == SDLK_RETURN) && + (event->key.keysym.mod & KMOD_ALT) ) { + SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); + return(0); + } + } + return(1); + } + SDL_SetEventFilter(Handle_AltEnter); + +1.0.3: + Under X11, if you grab the input and hide the mouse cursor, + the mouse will go into a "relative motion" mode where you + will always get relative motion events no matter how far in + each direction you move the mouse - relative motion is not + bounded by the edges of the window (though the absolute values + of the mouse positions are clamped by the size of the window). + The SVGAlib, framebuffer console, and DirectInput drivers all + have this behavior naturally, and the GDI and BWindow drivers + never go into "relative motion" mode. + +1.0.2: + Added a function to enable keyboard repeat: + SDL_EnableKeyRepeat() + + Added a function to grab the mouse and keyboard input + SDL_WM_GrabInput() + + Added a function to iconify the window. + SDL_WM_IconifyWindow() + If this function succeeds, the application will receive an event + signaling SDL_APPACTIVE event + +1.0.1: + Added constants to SDL_audio.h for 16-bit native byte ordering: + AUDIO_U16SYS, AUDIO_S16SYS + +1.0.0: + New public release + +Version 0.11: + +0.11.5: + A new function SDL_GetVideoSurface() has been added, and returns + a pointer to the current display surface. + + SDL_AllocSurface() has been renamed SDL_CreateRGBSurface(), and + a new function SDL_CreateRGBSurfaceFrom() has been added to allow + creating an SDL surface from an existing pixel data buffer. + + Added SDL_GetRGB() to the headers and documentation. + +0.11.4: + SDL_SetLibraryPath() is no longer meaningful, and has been removed. + +0.11.3: + A new flag for SDL_Init(), SDL_INIT_NOPARACHUTE, prevents SDL from + installing fatal signal handlers on operating systems that support + them. + +Version 0.9: + +0.9.15: + SDL_CreateColorCursor() has been removed. Color cursors should + be implemented as sprites, blitted by the application when the + cursor moves. To get smooth color cursor updates when the app + is busy, pass the SDL_INIT_EVENTTHREAD flag to SDL_Init(). This + allows you to handle the mouse motion in another thread from an + event filter function, but is currently only supported by Linux + and BeOS. Note that you'll have to protect the display surface + from multi-threaded access by using mutexes if you do this. + + Thread-safe surface support has been removed from SDL. + This makes blitting somewhat faster, by removing SDL_MiddleBlit(). + Code that used SDL_MiddleBlit() should use SDL_LowerBlit() instead. + You can make your surfaces thread-safe by allocating your own + mutex and making lock/unlock calls around accesses to your surface. + +0.9.14: + SDL_GetMouseState() now takes pointers to int rather than Uint16. + + If you set the SDL_WINDOWID environment variable under UNIX X11, + SDL will use that as the main window instead of creating it's own. + This is an unsupported extension to SDL, and not portable at all. + +0.9.13: + Added a function SDL_SetLibraryPath() which can be used to specify + the directory containing the SDL dynamic libraries. This is useful + for commercial applications which ship with particular versions + of the libraries, and for security on multi-user systems. + If this function is not used, the default system directories are + searched using the native dynamic object loading mechanism. + + In order to support C linkage under Visual C++, you must declare + main() without any return type: + main(int argc, char *argv[]) { + /* Do the program... */ + return(0); + } + C++ programs should also return a value if compiled under VC++. + + The blit_endian member of the SDL_VideoInfo struct has been removed. + + SDL_SymToASCII() has been replaced with SDL_GetKeyName(), so there + is now no longer any function to translate a keysym to a character. + + The SDL_keysym structure has been extended with a 'scancode' and + 'unicode' member. The 'scancode' is a hardware specific scancode + for the key that was pressed, and may be 0. The 'unicode' member + is a 16-bit UNICODE translation of the key that was pressed along + with any modifiers or compose keys that have been pressed. + If no UNICODE translation exists for the key, 'unicode' will be 0. + + Added a function SDL_EnableUNICODE() to enable/disable UNICODE + translation of character keypresses. Translation defaults off. + + To convert existing code to use the new API, change code which + uses SDL_SymToASCII() to get the keyname to use SDL_GetKeyName(), + and change code which uses it to get the ASCII value of a sym to + use the 'unicode' member of the event keysym. + +0.9.12: + There is partial support for 64-bit datatypes. I don't recommend + you use this if you have a choice, because 64-bit datatypes are not + supported on many platforms. On platforms for which it is supported, + the SDL_HAS_64BIT_TYPE C preprocessor define will be enabled, and + you can use the Uint64 and Sint64 datatypes. + + Added functions to SDL_endian.h to support 64-bit datatypes: + SDL_SwapLE64(), SDL_SwapBE64(), + SDL_ReadLE64(), SDL_ReadBE64(), SDL_WriteLE64(), SDL_WriteBE64() + + A new member "len_ratio" has been added to the SDL_AudioCVT structure, + and allows you to determine either the original buffer length or the + converted buffer length, given the other. + + A new function SDL_FreeWAV() has been added to the API to free data + allocated by SDL_LoadWAV_RW(). This is necessary under Win32 since + the gcc compiled DLL uses a different heap than VC++ compiled apps. + + SDL now has initial support for international keyboards using the + Latin character set. + If a particular mapping is desired, you can set the DEFAULT_KEYBOARD + compile-time variable, or you can set the environment variable + "SDL_KEYBOARD" to a string identifying the keyboard mapping you desire. + The valid values for these variables can be found in SDL_keyboard.c + + Full support for German and French keyboards under X11 is implemented. + +0.9.11: + The THREADED_EVENTS compile-time define has been replaced with the + SDL_INIT_EVENTTHREAD flag. If this flag is passed to SDL_Init(), + SDL will create a separate thread to perform input event handling. + If this flag is passed to SDL_Init(), and the OS doesn't support + event handling in a separate thread, SDL_Init() will fail. + Be sure to add calls to SDL_Delay() in your main thread to allow + the OS to schedule your event thread, or it may starve, leading + to slow event delivery and/or dropped events. + Currently MacOS and Win32 do not support this flag, while BeOS + and Linux do support it. I recommend that your application only + use this flag if absolutely necessary. + + The SDL thread function passed to SDL_CreateThread() now returns a + status. This status can be retrieved by passing a non-NULL pointer + as the 'status' argument to SDL_WaitThread(). + + The volume parameter to SDL_MixAudio() has been increased in range + from (0-8) to (0-128) + + SDL now has a data source abstraction which can encompass a file, + an area of memory, or any custom object you can envision. It uses + these abstractions, SDL_RWops, in the endian read/write functions, + and the built-in WAV and BMP file loaders. This means you can load + WAV chunks from memory mapped files, compressed archives, network + pipes, or anything else that has a data read abstraction. + + There are three built-in data source abstractions: + SDL_RWFromFile(), SDL_RWFromFP(), SDL_RWFromMem() + along with a generic data source allocation function: + SDL_AllocRW() + These data sources can be used like stdio file pointers with the + following convenience functions: + SDL_RWseek(), SDL_RWread(), SDL_RWwrite(), SDL_RWclose() + These functions are defined in the new header file "SDL_rwops.h" + + The endian swapping functions have been turned into macros for speed + and SDL_CalculateEndian() has been removed. SDL_endian.h now defines + SDL_BYTEORDER as either SDL_BIG_ENDIAN or SDL_LIL_ENDIAN depending on + the endianness of the host system. + + The endian read/write functions now take an SDL_RWops pointer + instead of a stdio FILE pointer, to support the new data source + abstraction. + + The SDL_*LoadWAV() functions have been replaced with a single + SDL_LoadWAV_RW() function that takes a SDL_RWops pointer as it's + first parameter, and a flag whether or not to automatically + free it as the second parameter. SDL_LoadWAV() is a macro for + backward compatibility and convenience: + SDL_LoadWAV_RW(SDL_RWFromFile("sample.wav", "rb"), 1, ...); + + The SDL_*LoadBMP()/SDL_*SaveBMP() functions have each been replaced + with a single function that takes a SDL_RWops pointer as it's + first parameter, and a flag whether or not to automatically + free it as the second parameter. SDL_LoadBMP() and SDL_SaveBMP() + are macros for backward compatibility and convenience: + SDL_LoadBMP_RW(SDL_RWFromFile("sample.bmp", "rb"), 1, ...); + SDL_SaveBMP_RW(SDL_RWFromFile("sample.bmp", "wb"), 1, ...); + Note that these functions use SDL_RWseek() extensively, and should + not be used on pipes or other non-seekable data sources. + +0.9.10: + The Linux SDL_SysWMInfo and SDL_SysWMMsg structures have been + extended to support multiple types of display drivers, as well as + safe access to the X11 display when THREADED_EVENTS is enabled. + The new structures are documented in the SDL_syswm.h header file. + + Thanks to John Elliott <[email protected]>, the UK keyboard + should now work properly, as well as the "Windows" keys on US + keyboards. + + The Linux CD-ROM code now reads the CD-ROM devices from /etc/fstab + instead of trying to open each block device on the system. + The CD must be listed in /etc/fstab as using the iso9660 filesystem. + + On Linux, if you define THREADED_EVENTS at compile time, a separate + thread will be spawned to gather X events asynchronously from the + graphics updates. This hasn't been extensively tested, but it does + provide a means of handling keyboard and mouse input in a separate + thread from the graphics thread. (This is now enabled by default.) + + A special access function SDL_PeepEvents() allows you to manipulate + the event queue in a thread-safe manner, including peeking at events, + removing events of a specified type, and adding new events of arbitrary + type to the queue (use the new 'user' member of the SDL_Event type). + + If you use SDL_PeepEvents() to gather events, then the main graphics + thread needs to call SDL_PumpEvents() periodically to drive the event + loop and generate input events. This is not necessary if SDL has been + compiled with THREADED_EVENTS defined, but doesn't hurt. + + A new function SDL_ThreadID() returns the identifier associated with + the current thread. + +0.9.9: + The AUDIO_STEREO format flag has been replaced with a new 'channels' + member of the SDL_AudioSpec structure. The channels are 1 for mono + audio, and 2 for stereo audio. In the future more channels may be + supported for 3D surround sound. + + The SDL_MixAudio() function now takes an additional volume parameter, + which should be set to SDL_MIX_MAXVOLUME for compatibility with the + original function. + + The CD-ROM functions which take a 'cdrom' parameter can now be + passed NULL, and will act on the last successfully opened CD-ROM. + +0.9.8: + No changes, bugfixes only. + +0.9.7: + No changes, bugfixes only. + +0.9.6: + Added a fast rectangle fill function: SDL_FillRect() + + Addition of a useful function for getting info on the video hardware: + const SDL_VideoInfo *SDL_GetVideoInfo(void) + This function replaces SDL_GetDisplayFormat(). + + Initial support for double-buffering: + Use the SDL_DOUBLEBUF flag in SDL_SetVideoMode() + Update the screen with a new function: SDL_Flip() + + SDL_AllocSurface() takes two new flags: + SDL_SRCCOLORKEY means that the surface will be used for colorkey blits + and if the hardware supports hardware acceleration of colorkey blits + between two surfaces in video memory, to place the surface in video + memory if possible, otherwise it will be placed in system memory. + SDL_SRCALPHA means that the surface will be used for alpha blits and + if the hardware supports hardware acceleration of alpha blits between + two surfaces in video memory, to place the surface in video memory + if possible, otherwise it will be placed in system memory. + SDL_HWSURFACE now means that the surface will be created with the + same format as the display surface, since having surfaces in video + memory is only useful for fast blitting to the screen, and you can't + blit surfaces with different surface formats in video memory. + +0.9.5: + You can now pass a NULL mask to SDL_WM_SetIcon(), and it will assume + that the icon consists of the entire image. + + SDL_LowerBlit() is back -- but don't use it on the display surface. + It is exactly the same as SDL_MiddleBlit(), but doesn't check for + thread safety. + + Added SDL_FPLoadBMP(), SDL_FPSaveBMP(), SDL_FPLoadWAV(), which take + a FILE pointer instead of a file name. + + Added CD-ROM audio control API: + SDL_CDNumDrives() + SDL_CDName() + SDL_CDOpen() + SDL_CDStatus() + SDL_CDPlayTracks() + SDL_CDPlay() + SDL_CDPause() + SDL_CDResume() + SDL_CDStop() + SDL_CDEject() + SDL_CDClose() + +0.9.4: + No changes, bugfixes only. + +0.9.3: + Mouse motion event now includes relative motion information: + Sint16 event->motion.xrel, Sint16 event->motion.yrel + + X11 keyrepeat handling can be disabled by defining IGNORE_X_KEYREPEAT + (Add -DIGNORE_X_KEYREPEAT to CFLAGS line in obj/x11Makefile) + +0.9.2: + No changes, bugfixes only. + +0.9.1: + Removed SDL_MapSurface() and SDL_UnmapSurface() -- surfaces are now + automatically mapped on blit. + +0.8.0: + SDL stable release diff --git a/bsp/simulator/applications/SConscript b/bsp/simulator/applications/SConscript index 4fe38ed0cf..4ccb177207 100644 --- a/bsp/simulator/applications/SConscript +++ b/bsp/simulator/applications/SConscript @@ -1,9 +1,9 @@ -from building import *
-
-cwd = GetCurrentDir()
-src = Glob('*.c')
-CPPPATH = [cwd, str(Dir('#'))]
-
-group = DefineGroup('Applications', src, depend = [''], CPPPATH = CPPPATH)
-
-Return('group')
+from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') +CPPPATH = [cwd, str(Dir('#'))] + +group = DefineGroup('Applications', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/simulator/applications/application.c b/bsp/simulator/applications/application.c index 42b157facb..abd582c3ce 100644 --- a/bsp/simulator/applications/application.c +++ b/bsp/simulator/applications/application.c @@ -1,122 +1,122 @@ -/*
- * File : application.c
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2006, RT-Thread Development Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2009-01-05 Bernard the first version
- */
-
-#include <rtthread.h>
-#include <stdio.h>
-#include <board.h>
-
-#include <components.h>
-
-void rt_init_thread_entry(void *parameter)
-{
-#ifdef RT_USING_LWIP
- pcap_netif_hw_init();
-#endif
-
- /* initialization RT-Thread Components */
- rt_components_init();
-
- rt_platform_init();
-
- /* File system Initialization */
-#ifdef RT_USING_DFS
- {
-#ifdef RT_USING_DFS_WINSHAREDIR
- {
- extern rt_err_t rt_win_sharedir_init(const char *name);
- extern int dfs_win32_init(void);
-
- rt_win_sharedir_init("wdd");
- dfs_win32_init();
-
- if (dfs_mount("wdd", "/", "wdir", 0, 0) == 0)
- rt_kprintf("win32 share directory initialized!\n");
- else
- rt_kprintf("win32 share directory initialized failed!\n");
- }
-#endif
-
-#ifdef RT_USING_DFS_ELMFAT
- /* mount sd card fatfs as root directory */
- if (dfs_mount("sd0", "/disk/sd", "elm", 0, 0) == 0)
- rt_kprintf("fatfs initialized!\n");
- else
- rt_kprintf("fatfs initialization failed!\n");
-#endif
-
-#ifdef RT_USING_DFS_UFFS
- /* mount uffs as the nand flash file system */
- if (dfs_mount("nand0", "/disk/nand", "uffs", 0, 0) == 0)
- rt_kprintf("uffs initialized!\n");
- else
- rt_kprintf("uffs initialization failed!\n");
-#endif
-
-#ifdef RT_USING_DFS_JFFS2
- /* mount jffs2 as the nor flash file system */
- if (dfs_mount("nor", "/disk/nor", "jffs2", 0, 0) == 0)
- rt_kprintf("jffs2 initialized!\n");
- else
- rt_kprintf("jffs2 initialization failed!\n");
-#endif
-
- }
-#endif
-
-#if 0
- {
- extern void application_init(void);
- rt_thread_delay(RT_TICK_PER_SECOND);
- application_init();
- }
-#endif
-
-#if defined(RT_USING_RTGUI)
- rt_thread_delay(3000);
- snake_main();
-#endif
-}
-
-static void rt_test_thread_entry(void *parameter)
-{
- int i;
- for (i = 0; i < 10; i++)
- {
- rt_kprintf("hello, world\n");
- rt_thread_delay(100);
- }
-}
-
-int rt_application_init()
-{
- rt_thread_t tid;
-
- tid = rt_thread_create("init",
- rt_init_thread_entry, RT_NULL,
- 2048, RT_THREAD_PRIORITY_MAX / 3, 20);
-
- if (tid != RT_NULL)
- rt_thread_startup(tid);
-
- tid = rt_thread_create("test",
- rt_test_thread_entry, RT_NULL,
- 2048, RT_THREAD_PRIORITY_MAX * 3 / 4, 20);
- if (tid != RT_NULL)
- rt_thread_startup(tid);
-
- return 0;
-}
-
-
-/*@}*/
+/* + * File : application.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2009-01-05 Bernard the first version + */ + +#include <rtthread.h> +#include <stdio.h> +#include <board.h> + +#include <components.h> + +void rt_init_thread_entry(void *parameter) +{ +#ifdef RT_USING_LWIP + pcap_netif_hw_init(); +#endif + + /* initialization RT-Thread Components */ + rt_components_init(); + + rt_platform_init(); + + /* File system Initialization */ +#ifdef RT_USING_DFS + { +#ifdef RT_USING_DFS_WINSHAREDIR + { + extern rt_err_t rt_win_sharedir_init(const char *name); + extern int dfs_win32_init(void); + + rt_win_sharedir_init("wdd"); + dfs_win32_init(); + + if (dfs_mount("wdd", "/", "wdir", 0, 0) == 0) + rt_kprintf("win32 share directory initialized!\n"); + else + rt_kprintf("win32 share directory initialized failed!\n"); + } +#endif + +#ifdef RT_USING_DFS_ELMFAT + /* mount sd card fatfs as root directory */ + if (dfs_mount("sd0", "/disk/sd", "elm", 0, 0) == 0) + rt_kprintf("fatfs initialized!\n"); + else + rt_kprintf("fatfs initialization failed!\n"); +#endif + +#ifdef RT_USING_DFS_UFFS + /* mount uffs as the nand flash file system */ + if (dfs_mount("nand0", "/disk/nand", "uffs", 0, 0) == 0) + rt_kprintf("uffs initialized!\n"); + else + rt_kprintf("uffs initialization failed!\n"); +#endif + +#ifdef RT_USING_DFS_JFFS2 + /* mount jffs2 as the nor flash file system */ + if (dfs_mount("nor", "/disk/nor", "jffs2", 0, 0) == 0) + rt_kprintf("jffs2 initialized!\n"); + else + rt_kprintf("jffs2 initialization failed!\n"); +#endif + + } +#endif + +#if 0 + { + extern void application_init(void); + rt_thread_delay(RT_TICK_PER_SECOND); + application_init(); + } +#endif + +#if defined(RT_USING_RTGUI) + rt_thread_delay(3000); + snake_main(); +#endif +} + +static void rt_test_thread_entry(void *parameter) +{ + int i; + for (i = 0; i < 10; i++) + { + rt_kprintf("hello, world\n"); + rt_thread_delay(100); + } +} + +int rt_application_init() +{ + rt_thread_t tid; + + tid = rt_thread_create("init", + rt_init_thread_entry, RT_NULL, + 2048, RT_THREAD_PRIORITY_MAX / 3, 20); + + if (tid != RT_NULL) + rt_thread_startup(tid); + + tid = rt_thread_create("test", + rt_test_thread_entry, RT_NULL, + 2048, RT_THREAD_PRIORITY_MAX * 3 / 4, 20); + if (tid != RT_NULL) + rt_thread_startup(tid); + + return 0; +} + + +/*@}*/ diff --git a/bsp/simulator/applications/dfs_win32.c b/bsp/simulator/applications/dfs_win32.c index 605d6533b4..121ed39b81 100644 --- a/bsp/simulator/applications/dfs_win32.c +++ b/bsp/simulator/applications/dfs_win32.c @@ -1,551 +1,551 @@ -
-/*
- * File : rtthread.h
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2006-2012, RT-Thread Development Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE.
- *
- * Change Logs:
- * Date Author Notes
- * 2012-11-27 prife the first version
- */
-#include <rtthread.h>
-
-#include <dfs_fs.h>
-#include <dfs_def.h>
-#include <rtdevice.h>
-//#include "dfs_win32.h"
-
-#include <io.h>
-#include <fcntl.h>
-#include <string.h>
-#include <stdio.h>
-#include <string.h>
-#include <WinError.h>
-#include <windows.h>
-
-/*
- * RT-Thread DFS Interface for win-directory as an disk device
- */
-#define FILE_PATH_MAX 256 /* the longest file path */
-
-#define WIN32_DIRDISK_ROOT "." /* "F:\\Project\\svn\\rtt\\trunk\\bsp\\simulator_test" */
-
-/* There are so many error codes in windows, you'd better google for details.
- * google "System Error Codes (Windows)"
- * http://msdn.microsoft.com/ZH-CN/library/windows/desktop/ms681381(v=vs.85).aspx
- */
-
-struct _errcode_map
-{
- rt_uint16_t dfserr;
- rt_uint16_t win32err;
-};
-
-static const struct _errcode_map errcode_table[] =
-{
- {DFS_STATUS_ENOENT, ERROR_FILE_NOT_FOUND },
- {DFS_STATUS_ENOENT, ERROR_PATH_NOT_FOUND },
- {DFS_STATUS_EEXIST, ERROR_FILE_EXISTS },
- {DFS_STATUS_EEXIST, ERROR_ALREADY_EXISTS },
- {DFS_STATUS_ENOTEMPTY, ERROR_DIR_NOT_EMPTY },
- {DFS_STATUS_EBUSY, ERROR_PATH_BUSY },
- {DFS_STATUS_EINVAL, ERROR_ACCESS_DENIED },
-
-#if 0 /* TODO: MORE NEED BE ADDED */
- {DFS_STATUS_EISDIR, ERROR_FILE_EXISTS },
- {DFS_STATUS_ENOTDIR, ERROR_FILE_EXISTS },
- {DFS_STATUS_EBADF, ERROR_FILE_EXISTS },
- {DFS_STATUS_EBUSY, ERROR_FILE_EXISTS },
- {DFS_STATUS_ENOMEM, ERROR_FILE_EXISTS },
- {DFS_STATUS_ENOSPC, ERROR_FILE_EXISTS },
-#endif
-};
-static int win32_result_to_dfs(DWORD res)
-{
- int i;
- int err = 0;
- for (i = 0; i < sizeof(errcode_table) / sizeof(struct _errcode_map); i++)
- {
- if (errcode_table[i].win32err == (res & 0xFFFF))
- {
- err = -errcode_table[i].dfserr;
- return err;
- }
- }
-
- /* unknown error */
- rt_kprintf("dfs win32 error not supported yet: %d\n", res);
- return -1;
-}
-
-static int dfs_win32_mount(
- struct dfs_filesystem *fs,
- unsigned long rwflag,
- const void *data)
-{
- return 0;
-}
-
-static int dfs_win32_unmount(struct dfs_filesystem *fs)
-{
- return 0;
-}
-
-static int dfs_win32_mkfs(const char *device_name)
-{
- return -DFS_STATUS_ENOSYS;
-}
-
-static int dfs_win32_statfs(struct dfs_filesystem *fs,
- struct statfs *buf)
-{
- return -DFS_STATUS_ENOSYS;
-}
-
-static char *winpath_dirdup(char *des, const char *src)
-{
- char *path;
- int i = 0;
-
- path = rt_malloc(FILE_PATH_MAX);
- if (path == RT_NULL)
- return RT_NULL;
-
- strcpy(path, des);
- strcat(path, src);
-
- while (1)
- {
- if (path[i] == 0)
- break;
-
- if (path[i] == '/')
- path[i] = '\\';
-
- i++;
- }
-
- return path;
-}
-
-static int dfs_win32_open(struct dfs_fd *file)
-{
- int fd;
- int oflag, mode;
- char *file_path;
- int res;
-
- oflag = file->flags;
- if (oflag & DFS_O_DIRECTORY) /* operations about dir */
- {
- struct _finddata_t dir;
- int handle;
- int len;
-
- file_path = winpath_dirdup(WIN32_DIRDISK_ROOT, file->path);
-
- if (oflag & DFS_O_CREAT) /* create a dir*/
- {
- res = CreateDirectory(file_path, NULL);
- if (res == 0)
- {
- rt_free(file_path);
- return win32_result_to_dfs(GetLastError());
- }
- }
-
- len = strlen(file_path);
- if (file_path[len - 1] != '\\')
- {
- file_path[len] = '\\';
- file_path[len + 1] = 0;
- }
-
- strcat(file_path, "*.*");
- /* _findfirst will get '.' */
- if ((handle = _findfirst(file_path, &dir)) == -1)
- {
- rt_free(file_path);
- goto __err;
- }
-
- /* save this pointer,will used by dfs_win32_getdents*/
- file->data = (void *)handle;
- rt_free(file_path);
- return DFS_STATUS_OK;
- }
- /* regular file operations */
- mode = O_BINARY;
- if (oflag & DFS_O_RDONLY) mode |= O_RDONLY;
- if (oflag & DFS_O_WRONLY) mode |= O_WRONLY;
- if (oflag & DFS_O_RDWR) mode |= O_RDWR;
- /* Opens the file, if it is existing. If not, a new file is created. */
- if (oflag & DFS_O_CREAT) mode |= O_CREAT;
- /* Creates a new file. If the file is existing, it is truncated and overwritten. */
- if (oflag & DFS_O_TRUNC) mode |= O_TRUNC;
- /* Creates a new file. The function fails if the file is already existing. */
- if (oflag & DFS_O_EXCL) mode |= O_EXCL;
-
- file_path = winpath_dirdup(WIN32_DIRDISK_ROOT, file->path);
- fd = _open(file_path, mode, 0x0100 | 0x0080); /* _S_IREAD | _S_IWRITE */
- rt_free(file_path);
-
- if (fd < 0)
- goto __err;
-
- /* save this pointer, it will be used when calling read(), write(),
- * flush(), seek(), and will be free when calling close()*/
- file->data = (void *)fd;
- file->pos = 0;
- file->size = _lseek(fd, 0, SEEK_END);
-
- if (oflag & DFS_O_APPEND)
- {
- file->pos = file->size;
- }
- else
- _lseek(fd, 0, SEEK_SET);
-
- return 0;
-
-__err:
- res = GetLastError();
- return win32_result_to_dfs(res);
-}
-
-static int dfs_win32_close(struct dfs_fd *file)
-{
- int oflag;
-
- oflag = file->flags;
- if (oflag & DFS_O_DIRECTORY)
- {
- /* operations about dir */
- if (_findclose((intptr_t)file->data) < 0)
- goto __err;
-
- return 0;
- }
-
- /* regular file operations */
- if (_close((int)(file->data)) < 0)
- goto __err;
-
- return 0;
-
-__err:
- return win32_result_to_dfs(GetLastError());
-}
-
-static int dfs_win32_ioctl(struct dfs_fd *file, int cmd, void *args)
-{
- return -DFS_STATUS_ENOSYS;
-}
-
-static int dfs_win32_read(struct dfs_fd *file, void *buf, rt_size_t len)
-{
- int fd;
- int char_read;
-
- fd = (int)(file->data);
- char_read = _read(fd, buf, len);
- if (char_read < 0)
- return win32_result_to_dfs(GetLastError());
-
- /* update position */
- file->pos = _lseek(fd, 0, SEEK_CUR);
- return char_read;
-}
-
-static int dfs_win32_write(struct dfs_fd *file,
- const void *buf,
- rt_size_t len)
-{
- int fd;
- int char_write;
-
- fd = (int)(file->data);
-
- char_write = _write(fd, buf, len);
- if (char_write < 0)
- return win32_result_to_dfs(GetLastError());
-
- /* update position */
- file->pos = _lseek(fd, 0, SEEK_CUR);
- return char_write;
-}
-
-static int dfs_win32_flush(struct dfs_fd *file)
-{
- return 0;
-}
-
-static int dfs_win32_seek(struct dfs_fd *file,
- rt_off_t offset)
-{
- int result;
-
- /* set offset as current offset */
- if (file->type == FT_DIRECTORY)
- {
- return -DFS_STATUS_ENOSYS;
- }
- else if (file->type == FT_REGULAR)
- {
- result = _lseek((int)(file->data), offset, SEEK_SET);
- if (result >= 0)
- return offset;
- }
-
- return win32_result_to_dfs(GetLastError());
-}
-
-/* return the size of struct dirent*/
-static int dfs_win32_getdents(
- struct dfs_fd *file,
- struct dirent *dirp,
- rt_uint32_t count)
-{
- rt_uint32_t index;
- struct dirent *d;
- struct _finddata_t fileinfo;
- int handle;
- int result;
-
- handle = (int)(file->data);
- RT_ASSERT(handle != RT_NULL);
-
- /* round count, count is always 1 */
- count = (count / sizeof(struct dirent)) * sizeof(struct dirent);
- if (count == 0) return -DFS_STATUS_EINVAL;
-
- index = 0;
- /* usually, the while loop should only be looped only once! */
- while (1)
- {
- d = dirp + index;
- if (_findnext(handle, &fileinfo) != 0) //-1 failed
- goto __err;
-
- if (fileinfo.attrib & _A_SUBDIR)
- d->d_type = DFS_DT_DIR; /* directory */
- else
- d->d_type = DFS_DT_REG;
-
- /* write the rest arguments of struct dirent* dirp */
- d->d_namlen = strlen(fileinfo.name);
- d->d_reclen = (rt_uint16_t)sizeof(struct dirent);
- strcpy(d->d_name, fileinfo.name);
-
- index ++;
- if (index * sizeof(struct dirent) >= count)
- break;
- }
- if (index == 0)
- return 0;
-
- file->pos += index * sizeof(struct dirent);
-
- return index * sizeof(struct dirent);
-
-__err:
- if ((result = GetLastError()) == ERROR_NO_MORE_FILES)
- return 0;
- else
- return win32_result_to_dfs(result);
-}
-
-static int dfs_win32_unlink(struct dfs_filesystem *fs, const char *path)
-{
- int result;
- char *fp;
- fp = winpath_dirdup(WIN32_DIRDISK_ROOT, path);
- if (fp == RT_NULL)
- {
- rt_kprintf("out of memory.\n");
- return -DFS_STATUS_ENOMEM;
- }
-
- result = GetFileAttributes(fp);
- if (result == INVALID_FILE_ATTRIBUTES)
- goto __err;
-
- if (result & FILE_ATTRIBUTE_DIRECTORY)//winnt.h
- {
- if (RemoveDirectory(fp) == RT_FALSE)
- goto __err;
- }
- else //(result & FILE_ATTRIBUTE_NORMAL)
- {
- if (_unlink(fp) < 0)
- goto __err;
- }
-
- rt_free(fp);
- return 0;
-__err:
- rt_free(fp);
- return win32_result_to_dfs(GetLastError());
-}
-
-static int dfs_win32_rename(
- struct dfs_filesystem *fs,
- const char *oldpath,
- const char *newpath)
-{
- int result;
- char *op, *np;
- op = winpath_dirdup(WIN32_DIRDISK_ROOT, oldpath);
- np = winpath_dirdup(WIN32_DIRDISK_ROOT, newpath);
- if (op == RT_NULL || np == RT_NULL)
- {
- rt_kprintf("out of memory.\n");
- return -DFS_STATUS_ENOMEM;
- }
-
- /* If the function fails, the return value is zero. */
- result = MoveFile(op, np);
-
- rt_free(op);
- rt_free(np);
-
- if (result == 0)
- return win32_result_to_dfs(GetLastError());
-
- return 0;
-}
-
-static int dfs_win32_stat(struct dfs_filesystem *fs, const char *path, struct stat *st)
-{
- WIN32_FIND_DATA fileInfo;
- HANDLE hFind;
- char *fp;
- fp = winpath_dirdup(WIN32_DIRDISK_ROOT, path);
- if (fp == RT_NULL)
- {
- rt_kprintf("out of memory.\n");
- return -DFS_STATUS_ENOMEM;
- }
-
- hFind = FindFirstFile(fp, &fileInfo);
- rt_free(fp);
-
- if (hFind == INVALID_HANDLE_VALUE)
- goto __err;
-
- st->st_mode = DFS_S_IFREG | DFS_S_IRUSR | DFS_S_IRGRP | DFS_S_IROTH |
- DFS_S_IWUSR | DFS_S_IWGRP | DFS_S_IWOTH;
-
- /* convert file info to dfs stat structure */
- if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
- {
- st->st_mode &= ~DFS_S_IFREG;
- st->st_mode |= DFS_S_IFDIR | DFS_S_IXUSR | DFS_S_IXGRP | DFS_S_IXOTH;
- }
-
- st->st_dev = 0;
- st->st_size = fileInfo.nFileSizeLow;
- st->st_mtime = 0;
- st->st_blksize = 0;
-
- FindClose(hFind);
-
- return 0;
-
-__err:
- return win32_result_to_dfs(GetLastError());
-}
-
-static const struct dfs_filesystem_operation dfs_win32_ops =
-{
- "wdir", /* file system type: dir */
- DFS_FS_FLAG_DEFAULT,
- dfs_win32_mount,
- dfs_win32_unmount,
- dfs_win32_mkfs,
- dfs_win32_statfs,
-
- dfs_win32_open,
- dfs_win32_close,
- dfs_win32_ioctl,
- dfs_win32_read,
- dfs_win32_write,
- dfs_win32_flush,
- dfs_win32_seek,
- dfs_win32_getdents,
- dfs_win32_unlink,
- dfs_win32_stat,
- dfs_win32_rename,
-};
-
-int dfs_win32_init(void)
-{
- /* register uffs file system */
- dfs_register(&dfs_win32_ops);
-
- return 0;
-}
-
-static rt_err_t nop_init(rt_device_t dev)
-{
- return RT_EOK;
-}
-
-static rt_err_t nop_open(rt_device_t dev, rt_uint16_t oflag)
-{
- return RT_EOK;
-}
-
-static rt_err_t nop_close(rt_device_t dev)
-{
- return RT_EOK;
-}
-
-static rt_size_t nop_read(rt_device_t dev,
- rt_off_t pos,
- void *buffer,
- rt_size_t size)
-{
- return size;
-}
-
-static rt_size_t nop_write(rt_device_t dev,
- rt_off_t pos,
- const void *buffer,
- rt_size_t size)
-{
- return size;
-}
-
-static rt_err_t nop_control(rt_device_t dev, rt_uint8_t cmd, void *args)
-{
- return RT_EOK;
-}
-
-static struct rt_device win_sharedir_dev;
-rt_err_t rt_win_sharedir_init(const char *name)
-{
- rt_device_t dev;
-
- dev = &win_sharedir_dev;
- RT_ASSERT(dev != RT_NULL);
-
- /* set device class and generic device interface */
- dev->type = RT_Device_Class_Block;
- dev->init = nop_init;
- dev->open = nop_open;
- dev->read = nop_read;
- dev->write = nop_write;
- dev->close = nop_close;
- dev->control = nop_control;
-
- dev->rx_indicate = RT_NULL;
- dev->tx_complete = RT_NULL;
-
- /* register to RT-Thread device system */
- return rt_device_register(dev, name, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STANDALONE);
-}
+ +/* + * File : rtthread.h + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006-2012, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE. + * + * Change Logs: + * Date Author Notes + * 2012-11-27 prife the first version + */ +#include <rtthread.h> + +#include <dfs_fs.h> +#include <dfs_def.h> +#include <rtdevice.h> +//#include "dfs_win32.h" + +#include <io.h> +#include <fcntl.h> +#include <string.h> +#include <stdio.h> +#include <string.h> +#include <WinError.h> +#include <windows.h> + +/* + * RT-Thread DFS Interface for win-directory as an disk device + */ +#define FILE_PATH_MAX 256 /* the longest file path */ + +#define WIN32_DIRDISK_ROOT "." /* "F:\\Project\\svn\\rtt\\trunk\\bsp\\simulator_test" */ + +/* There are so many error codes in windows, you'd better google for details. + * google "System Error Codes (Windows)" + * http://msdn.microsoft.com/ZH-CN/library/windows/desktop/ms681381(v=vs.85).aspx + */ + +struct _errcode_map +{ + rt_uint16_t dfserr; + rt_uint16_t win32err; +}; + +static const struct _errcode_map errcode_table[] = +{ + {DFS_STATUS_ENOENT, ERROR_FILE_NOT_FOUND }, + {DFS_STATUS_ENOENT, ERROR_PATH_NOT_FOUND }, + {DFS_STATUS_EEXIST, ERROR_FILE_EXISTS }, + {DFS_STATUS_EEXIST, ERROR_ALREADY_EXISTS }, + {DFS_STATUS_ENOTEMPTY, ERROR_DIR_NOT_EMPTY }, + {DFS_STATUS_EBUSY, ERROR_PATH_BUSY }, + {DFS_STATUS_EINVAL, ERROR_ACCESS_DENIED }, + +#if 0 /* TODO: MORE NEED BE ADDED */ + {DFS_STATUS_EISDIR, ERROR_FILE_EXISTS }, + {DFS_STATUS_ENOTDIR, ERROR_FILE_EXISTS }, + {DFS_STATUS_EBADF, ERROR_FILE_EXISTS }, + {DFS_STATUS_EBUSY, ERROR_FILE_EXISTS }, + {DFS_STATUS_ENOMEM, ERROR_FILE_EXISTS }, + {DFS_STATUS_ENOSPC, ERROR_FILE_EXISTS }, +#endif +}; +static int win32_result_to_dfs(DWORD res) +{ + int i; + int err = 0; + for (i = 0; i < sizeof(errcode_table) / sizeof(struct _errcode_map); i++) + { + if (errcode_table[i].win32err == (res & 0xFFFF)) + { + err = -errcode_table[i].dfserr; + return err; + } + } + + /* unknown error */ + rt_kprintf("dfs win32 error not supported yet: %d\n", res); + return -1; +} + +static int dfs_win32_mount( + struct dfs_filesystem *fs, + unsigned long rwflag, + const void *data) +{ + return 0; +} + +static int dfs_win32_unmount(struct dfs_filesystem *fs) +{ + return 0; +} + +static int dfs_win32_mkfs(const char *device_name) +{ + return -DFS_STATUS_ENOSYS; +} + +static int dfs_win32_statfs(struct dfs_filesystem *fs, + struct statfs *buf) +{ + return -DFS_STATUS_ENOSYS; +} + +static char *winpath_dirdup(char *des, const char *src) +{ + char *path; + int i = 0; + + path = rt_malloc(FILE_PATH_MAX); + if (path == RT_NULL) + return RT_NULL; + + strcpy(path, des); + strcat(path, src); + + while (1) + { + if (path[i] == 0) + break; + + if (path[i] == '/') + path[i] = '\\'; + + i++; + } + + return path; +} + +static int dfs_win32_open(struct dfs_fd *file) +{ + int fd; + int oflag, mode; + char *file_path; + int res; + + oflag = file->flags; + if (oflag & DFS_O_DIRECTORY) /* operations about dir */ + { + struct _finddata_t dir; + int handle; + int len; + + file_path = winpath_dirdup(WIN32_DIRDISK_ROOT, file->path); + + if (oflag & DFS_O_CREAT) /* create a dir*/ + { + res = CreateDirectory(file_path, NULL); + if (res == 0) + { + rt_free(file_path); + return win32_result_to_dfs(GetLastError()); + } + } + + len = strlen(file_path); + if (file_path[len - 1] != '\\') + { + file_path[len] = '\\'; + file_path[len + 1] = 0; + } + + strcat(file_path, "*.*"); + /* _findfirst will get '.' */ + if ((handle = _findfirst(file_path, &dir)) == -1) + { + rt_free(file_path); + goto __err; + } + + /* save this pointer,will used by dfs_win32_getdents*/ + file->data = (void *)handle; + rt_free(file_path); + return DFS_STATUS_OK; + } + /* regular file operations */ + mode = O_BINARY; + if (oflag & DFS_O_RDONLY) mode |= O_RDONLY; + if (oflag & DFS_O_WRONLY) mode |= O_WRONLY; + if (oflag & DFS_O_RDWR) mode |= O_RDWR; + /* Opens the file, if it is existing. If not, a new file is created. */ + if (oflag & DFS_O_CREAT) mode |= O_CREAT; + /* Creates a new file. If the file is existing, it is truncated and overwritten. */ + if (oflag & DFS_O_TRUNC) mode |= O_TRUNC; + /* Creates a new file. The function fails if the file is already existing. */ + if (oflag & DFS_O_EXCL) mode |= O_EXCL; + + file_path = winpath_dirdup(WIN32_DIRDISK_ROOT, file->path); + fd = _open(file_path, mode, 0x0100 | 0x0080); /* _S_IREAD | _S_IWRITE */ + rt_free(file_path); + + if (fd < 0) + goto __err; + + /* save this pointer, it will be used when calling read(), write(), + * flush(), seek(), and will be free when calling close()*/ + file->data = (void *)fd; + file->pos = 0; + file->size = _lseek(fd, 0, SEEK_END); + + if (oflag & DFS_O_APPEND) + { + file->pos = file->size; + } + else + _lseek(fd, 0, SEEK_SET); + + return 0; + +__err: + res = GetLastError(); + return win32_result_to_dfs(res); +} + +static int dfs_win32_close(struct dfs_fd *file) +{ + int oflag; + + oflag = file->flags; + if (oflag & DFS_O_DIRECTORY) + { + /* operations about dir */ + if (_findclose((intptr_t)file->data) < 0) + goto __err; + + return 0; + } + + /* regular file operations */ + if (_close((int)(file->data)) < 0) + goto __err; + + return 0; + +__err: + return win32_result_to_dfs(GetLastError()); +} + +static int dfs_win32_ioctl(struct dfs_fd *file, int cmd, void *args) +{ + return -DFS_STATUS_ENOSYS; +} + +static int dfs_win32_read(struct dfs_fd *file, void *buf, rt_size_t len) +{ + int fd; + int char_read; + + fd = (int)(file->data); + char_read = _read(fd, buf, len); + if (char_read < 0) + return win32_result_to_dfs(GetLastError()); + + /* update position */ + file->pos = _lseek(fd, 0, SEEK_CUR); + return char_read; +} + +static int dfs_win32_write(struct dfs_fd *file, + const void *buf, + rt_size_t len) +{ + int fd; + int char_write; + + fd = (int)(file->data); + + char_write = _write(fd, buf, len); + if (char_write < 0) + return win32_result_to_dfs(GetLastError()); + + /* update position */ + file->pos = _lseek(fd, 0, SEEK_CUR); + return char_write; +} + +static int dfs_win32_flush(struct dfs_fd *file) +{ + return 0; +} + +static int dfs_win32_seek(struct dfs_fd *file, + rt_off_t offset) +{ + int result; + + /* set offset as current offset */ + if (file->type == FT_DIRECTORY) + { + return -DFS_STATUS_ENOSYS; + } + else if (file->type == FT_REGULAR) + { + result = _lseek((int)(file->data), offset, SEEK_SET); + if (result >= 0) + return offset; + } + + return win32_result_to_dfs(GetLastError()); +} + +/* return the size of struct dirent*/ +static int dfs_win32_getdents( + struct dfs_fd *file, + struct dirent *dirp, + rt_uint32_t count) +{ + rt_uint32_t index; + struct dirent *d; + struct _finddata_t fileinfo; + int handle; + int result; + + handle = (int)(file->data); + RT_ASSERT(handle != RT_NULL); + + /* round count, count is always 1 */ + count = (count / sizeof(struct dirent)) * sizeof(struct dirent); + if (count == 0) return -DFS_STATUS_EINVAL; + + index = 0; + /* usually, the while loop should only be looped only once! */ + while (1) + { + d = dirp + index; + if (_findnext(handle, &fileinfo) != 0) //-1 failed + goto __err; + + if (fileinfo.attrib & _A_SUBDIR) + d->d_type = DFS_DT_DIR; /* directory */ + else + d->d_type = DFS_DT_REG; + + /* write the rest arguments of struct dirent* dirp */ + d->d_namlen = strlen(fileinfo.name); + d->d_reclen = (rt_uint16_t)sizeof(struct dirent); + strcpy(d->d_name, fileinfo.name); + + index ++; + if (index * sizeof(struct dirent) >= count) + break; + } + if (index == 0) + return 0; + + file->pos += index * sizeof(struct dirent); + + return index * sizeof(struct dirent); + +__err: + if ((result = GetLastError()) == ERROR_NO_MORE_FILES) + return 0; + else + return win32_result_to_dfs(result); +} + +static int dfs_win32_unlink(struct dfs_filesystem *fs, const char *path) +{ + int result; + char *fp; + fp = winpath_dirdup(WIN32_DIRDISK_ROOT, path); + if (fp == RT_NULL) + { + rt_kprintf("out of memory.\n"); + return -DFS_STATUS_ENOMEM; + } + + result = GetFileAttributes(fp); + if (result == INVALID_FILE_ATTRIBUTES) + goto __err; + + if (result & FILE_ATTRIBUTE_DIRECTORY)//winnt.h + { + if (RemoveDirectory(fp) == RT_FALSE) + goto __err; + } + else //(result & FILE_ATTRIBUTE_NORMAL) + { + if (_unlink(fp) < 0) + goto __err; + } + + rt_free(fp); + return 0; +__err: + rt_free(fp); + return win32_result_to_dfs(GetLastError()); +} + +static int dfs_win32_rename( + struct dfs_filesystem *fs, + const char *oldpath, + const char *newpath) +{ + int result; + char *op, *np; + op = winpath_dirdup(WIN32_DIRDISK_ROOT, oldpath); + np = winpath_dirdup(WIN32_DIRDISK_ROOT, newpath); + if (op == RT_NULL || np == RT_NULL) + { + rt_kprintf("out of memory.\n"); + return -DFS_STATUS_ENOMEM; + } + + /* If the function fails, the return value is zero. */ + result = MoveFile(op, np); + + rt_free(op); + rt_free(np); + + if (result == 0) + return win32_result_to_dfs(GetLastError()); + + return 0; +} + +static int dfs_win32_stat(struct dfs_filesystem *fs, const char *path, struct stat *st) +{ + WIN32_FIND_DATA fileInfo; + HANDLE hFind; + char *fp; + fp = winpath_dirdup(WIN32_DIRDISK_ROOT, path); + if (fp == RT_NULL) + { + rt_kprintf("out of memory.\n"); + return -DFS_STATUS_ENOMEM; + } + + hFind = FindFirstFile(fp, &fileInfo); + rt_free(fp); + + if (hFind == INVALID_HANDLE_VALUE) + goto __err; + + st->st_mode = DFS_S_IFREG | DFS_S_IRUSR | DFS_S_IRGRP | DFS_S_IROTH | + DFS_S_IWUSR | DFS_S_IWGRP | DFS_S_IWOTH; + + /* convert file info to dfs stat structure */ + if (fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + st->st_mode &= ~DFS_S_IFREG; + st->st_mode |= DFS_S_IFDIR | DFS_S_IXUSR | DFS_S_IXGRP | DFS_S_IXOTH; + } + + st->st_dev = 0; + st->st_size = fileInfo.nFileSizeLow; + st->st_mtime = 0; + st->st_blksize = 0; + + FindClose(hFind); + + return 0; + +__err: + return win32_result_to_dfs(GetLastError()); +} + +static const struct dfs_filesystem_operation dfs_win32_ops = +{ + "wdir", /* file system type: dir */ + DFS_FS_FLAG_DEFAULT, + dfs_win32_mount, + dfs_win32_unmount, + dfs_win32_mkfs, + dfs_win32_statfs, + + dfs_win32_open, + dfs_win32_close, + dfs_win32_ioctl, + dfs_win32_read, + dfs_win32_write, + dfs_win32_flush, + dfs_win32_seek, + dfs_win32_getdents, + dfs_win32_unlink, + dfs_win32_stat, + dfs_win32_rename, +}; + +int dfs_win32_init(void) +{ + /* register uffs file system */ + dfs_register(&dfs_win32_ops); + + return 0; +} + +static rt_err_t nop_init(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_err_t nop_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} + +static rt_err_t nop_close(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_size_t nop_read(rt_device_t dev, + rt_off_t pos, + void *buffer, + rt_size_t size) +{ + return size; +} + +static rt_size_t nop_write(rt_device_t dev, + rt_off_t pos, + const void *buffer, + rt_size_t size) +{ + return size; +} + +static rt_err_t nop_control(rt_device_t dev, rt_uint8_t cmd, void *args) +{ + return RT_EOK; +} + +static struct rt_device win_sharedir_dev; +rt_err_t rt_win_sharedir_init(const char *name) +{ + rt_device_t dev; + + dev = &win_sharedir_dev; + RT_ASSERT(dev != RT_NULL); + + /* set device class and generic device interface */ + dev->type = RT_Device_Class_Block; + dev->init = nop_init; + dev->open = nop_open; + dev->read = nop_read; + dev->write = nop_write; + dev->close = nop_close; + dev->control = nop_control; + + dev->rx_indicate = RT_NULL; + dev->tx_complete = RT_NULL; + + /* register to RT-Thread device system */ + return rt_device_register(dev, name, RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STANDALONE); +} diff --git a/bsp/simulator/applications/platform.c b/bsp/simulator/applications/platform.c index d178f28ec8..3c7ffdb541 100644 --- a/bsp/simulator/applications/platform.c +++ b/bsp/simulator/applications/platform.c @@ -1,29 +1,29 @@ -#include <rtthread.h>
-#include "board.h"
-
-void rt_platform_init(void)
-{
-#ifdef RT_USING_DFS
- /* initialize sd card */
- rt_hw_sdcard_init();
-
-#if defined(RT_USING_MTD_NAND)
- rt_hw_mtd_nand_init();
-#endif
-
-#if defined(RT_USING_MTD_NOR)
- sst25vfxx_mtd_init("nor", 0, RT_UINT32_MAX);
-#endif
-
-#endif /* RT_USING_DFS */
-
-#ifdef RT_USING_RTGUI
- /* start sdl thread to simulate an LCD */
- rt_hw_sdl_start();
-#endif /* RT_USING_RTGUI */
-
-#ifdef _WIN32
- rt_thread_idle_sethook(rt_hw_win32_low_cpu);
-#endif
-}
-
+#include <rtthread.h> +#include "board.h" + +void rt_platform_init(void) +{ +#ifdef RT_USING_DFS + /* initialize sd card */ + rt_hw_sdcard_init(); + +#if defined(RT_USING_MTD_NAND) + rt_hw_mtd_nand_init(); +#endif + +#if defined(RT_USING_MTD_NOR) + sst25vfxx_mtd_init("nor", 0, RT_UINT32_MAX); +#endif + +#endif /* RT_USING_DFS */ + +#ifdef RT_USING_RTGUI + /* start sdl thread to simulate an LCD */ + rt_hw_sdl_start(); +#endif /* RT_USING_RTGUI */ + +#ifdef _WIN32 + rt_thread_idle_sethook(rt_hw_win32_low_cpu); +#endif +} + diff --git a/bsp/simulator/applications/startup.c b/bsp/simulator/applications/startup.c index fd46980b42..2b21c69016 100644 --- a/bsp/simulator/applications/startup.c +++ b/bsp/simulator/applications/startup.c @@ -1,92 +1,92 @@ -/*
- * File : startup.c
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2006, RT-Thread Develop Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://openlab.rt-thread.com/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2012-09-03 prife first implementation
- */
-
-#include <rthw.h>
-#include <rtthread.h>
-
-#include "board.h"
-
-/**
- * @addtogroup win32
- */
-
-/*@{*/
-
-extern int rt_application_init(void);
-#ifdef RT_USING_FINSH
-extern void finsh_system_init(void);
-extern void finsh_set_device(const char *device);
-#endif
-
-extern rt_uint8_t *heap;
-/**
- * This function will startup RT-Thread RTOS.
- */
-void rtthread_startup(void)
-{
- /* init board */
- rt_hw_board_init();
-
- /* show version */
- rt_show_version();
-
- /* init tick */
- rt_system_tick_init();
-
- /* init kernel object */
- rt_system_object_init();
-
- /* init timer system */
- rt_system_timer_init();
-
-#ifdef RT_USING_HEAP
- /* init memory system */
- rt_system_heap_init((void *)heap, (void *)&heap[RT_HEAP_SIZE - 1]);
-#endif
-
- /* init scheduler system */
- rt_system_scheduler_init();
-
- /* init all device */
-#ifdef RT_USING_DEVICE
- rt_device_init_all();
-#endif
- /* init application */
- rt_application_init();
-
- /* init timer thread */
- rt_system_timer_thread_init();
-
- /* init idle thread */
- rt_thread_idle_init();
-
- /* start scheduler */
- rt_system_scheduler_start();
-
- /* never reach here */
- return ;
-}
-
-int main(void)
-{
- /* disable interrupt first */
- rt_hw_interrupt_disable();
-
- /* startup RT-Thread RTOS */
- rtthread_startup();
-
- return 0;
-}
-
-/*@}*/
+/* + * File : startup.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006, RT-Thread Develop Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://openlab.rt-thread.com/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2012-09-03 prife first implementation + */ + +#include <rthw.h> +#include <rtthread.h> + +#include "board.h" + +/** + * @addtogroup win32 + */ + +/*@{*/ + +extern int rt_application_init(void); +#ifdef RT_USING_FINSH +extern void finsh_system_init(void); +extern void finsh_set_device(const char *device); +#endif + +extern rt_uint8_t *heap; +/** + * This function will startup RT-Thread RTOS. + */ +void rtthread_startup(void) +{ + /* init board */ + rt_hw_board_init(); + + /* show version */ + rt_show_version(); + + /* init tick */ + rt_system_tick_init(); + + /* init kernel object */ + rt_system_object_init(); + + /* init timer system */ + rt_system_timer_init(); + +#ifdef RT_USING_HEAP + /* init memory system */ + rt_system_heap_init((void *)heap, (void *)&heap[RT_HEAP_SIZE - 1]); +#endif + + /* init scheduler system */ + rt_system_scheduler_init(); + + /* init all device */ +#ifdef RT_USING_DEVICE + rt_device_init_all(); +#endif + /* init application */ + rt_application_init(); + + /* init timer thread */ + rt_system_timer_thread_init(); + + /* init idle thread */ + rt_thread_idle_init(); + + /* start scheduler */ + rt_system_scheduler_start(); + + /* never reach here */ + return ; +} + +int main(void) +{ + /* disable interrupt first */ + rt_hw_interrupt_disable(); + + /* startup RT-Thread RTOS */ + rtthread_startup(); + + return 0; +} + +/*@}*/ diff --git a/bsp/simulator/drivers/SConscript b/bsp/simulator/drivers/SConscript index ef725a5b6a..94fc2fa643 100644 --- a/bsp/simulator/drivers/SConscript +++ b/bsp/simulator/drivers/SConscript @@ -1,20 +1,20 @@ -from building import *
-
-cwd = GetCurrentDir()
-src = Glob('*.c')
-
-# remove no need file.
-if GetDepend('RT_USING_RTGUI') == False:
- SrcRemove(src, 'sdl_fb.c')
-if GetDepend('RT_USING_DFS') == False or GetDepend('RT_USING_DFS_ELMFAT') == False:
- SrcRemove(src, 'sd_sim.c')
-if GetDepend('RT_USING_DFS') == False or GetDepend('RT_USING_MTD_NAND') == False:
- SrcRemove(src, 'nanddrv_file.c')
-if GetDepend('RT_USING_DFS') == False or GetDepend('RT_USING_MTD_NOR') == False:
- SrcRemove(src, 'sst25vfxx_mtd_sim.c')
-
-CPPPATH = [cwd]
-
-group = DefineGroup('Drivers', src, depend = [''], CPPPATH = CPPPATH)
-
-Return('group')
+from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +# remove no need file. +if GetDepend('RT_USING_RTGUI') == False: + SrcRemove(src, 'sdl_fb.c') +if GetDepend('RT_USING_DFS') == False or GetDepend('RT_USING_DFS_ELMFAT') == False: + SrcRemove(src, 'sd_sim.c') +if GetDepend('RT_USING_DFS') == False or GetDepend('RT_USING_MTD_NAND') == False: + SrcRemove(src, 'nanddrv_file.c') +if GetDepend('RT_USING_DFS') == False or GetDepend('RT_USING_MTD_NOR') == False: + SrcRemove(src, 'sst25vfxx_mtd_sim.c') + +CPPPATH = [cwd] + +group = DefineGroup('Drivers', src, depend = [''], CPPPATH = CPPPATH) + +Return('group') diff --git a/bsp/simulator/drivers/board.c b/bsp/simulator/drivers/board.c index 079071cb6e..c6320d27b5 100644 --- a/bsp/simulator/drivers/board.c +++ b/bsp/simulator/drivers/board.c @@ -1,75 +1,75 @@ -/*
- * File : board.c
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2009 RT-Thread Develop Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2009-01-05 Bernard first implementation
- */
-
-#include <rthw.h>
-#include <rtthread.h>
-#include "board.h"
-#include <stdlib.h>
-#include <windows.h>
-
-/**
- * @addtogroup simulator on win32
- */
-rt_uint8_t *heap;
-
-rt_uint8_t *rt_hw_sram_init(void)
-{
- rt_uint8_t *heap;
- heap = malloc(RT_HEAP_SIZE);
- if (heap == RT_NULL)
- {
- rt_kprintf("there is no memory in pc.");
- _exit(1);
- }
- return heap;
-}
-
-void rt_hw_win32_low_cpu(void)
-{
- Sleep(1000);
-}
-
-#if defined(RT_USING_FINSH)
-
-#ifndef _CRT_TERMINATE_DEFINED
-#define _CRT_TERMINATE_DEFINED
-_CRTIMP __declspec(noreturn) void __cdecl exit(__in int _Code);
-_CRTIMP __declspec(noreturn) void __cdecl _exit(__in int _Code);
-_CRTIMP void __cdecl abort(void);
-#endif
-
-#include <finsh.h>
-void rt_hw_exit(void)
-{
- rt_kprintf("RT-Thread, bye\n");
- exit(0);
-}
-FINSH_FUNCTION_EXPORT_ALIAS(rt_hw_exit, exit, exit rt - thread);
-#endif /* RT_USING_FINSH */
-
-/**
- * This function will initial win32
- */
-void rt_hw_board_init()
-{
- /* init system memory */
- heap = rt_hw_sram_init();
-
-#if defined(RT_USING_CONSOLE)
- rt_hw_usart_init();
- rt_hw_serial_init();
- rt_console_set_device(RT_CONSOLE_DEVICE_NAME);
-#endif
-}
-/*@}*/
+/* + * File : board.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2009 RT-Thread Develop Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2009-01-05 Bernard first implementation + */ + +#include <rthw.h> +#include <rtthread.h> +#include "board.h" +#include <stdlib.h> +#include <windows.h> + +/** + * @addtogroup simulator on win32 + */ +rt_uint8_t *heap; + +rt_uint8_t *rt_hw_sram_init(void) +{ + rt_uint8_t *heap; + heap = malloc(RT_HEAP_SIZE); + if (heap == RT_NULL) + { + rt_kprintf("there is no memory in pc."); + _exit(1); + } + return heap; +} + +void rt_hw_win32_low_cpu(void) +{ + Sleep(1000); +} + +#if defined(RT_USING_FINSH) + +#ifndef _CRT_TERMINATE_DEFINED +#define _CRT_TERMINATE_DEFINED +_CRTIMP __declspec(noreturn) void __cdecl exit(__in int _Code); +_CRTIMP __declspec(noreturn) void __cdecl _exit(__in int _Code); +_CRTIMP void __cdecl abort(void); +#endif + +#include <finsh.h> +void rt_hw_exit(void) +{ + rt_kprintf("RT-Thread, bye\n"); + exit(0); +} +FINSH_FUNCTION_EXPORT_ALIAS(rt_hw_exit, exit, exit rt - thread); +#endif /* RT_USING_FINSH */ + +/** + * This function will initial win32 + */ +void rt_hw_board_init() +{ + /* init system memory */ + heap = rt_hw_sram_init(); + +#if defined(RT_USING_CONSOLE) + rt_hw_usart_init(); + rt_hw_serial_init(); + rt_console_set_device(RT_CONSOLE_DEVICE_NAME); +#endif +} +/*@}*/ diff --git a/bsp/simulator/drivers/board.h b/bsp/simulator/drivers/board.h index b84d90f9a8..7edb856505 100644 --- a/bsp/simulator/drivers/board.h +++ b/bsp/simulator/drivers/board.h @@ -1,33 +1,33 @@ -/*
- * File : board.h
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2009, RT-Thread Development Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2009-09-22 Bernard add board.h to this bsp
- */
-
-#ifndef __BOARD_H__
-#define __BOARD_H__
-void rt_hw_board_init(void);
-rt_uint8_t *rt_hw_sram_init(void);
-
-/* SD Card init function */
-void rt_hw_sdcard_init(void);
-
-int rt_hw_mtd_nand_init(void);
-int sst25vfxx_mtd_init(const char *, unsigned int , unsigned int);
-void pcap_netif_hw_init(void);
-void rt_platform_init(void);
-void rt_hw_usart_init(void);
-void rt_hw_serial_init(void);
-void rt_hw_sdl_start(void);
-void rt_hw_win32_low_cpu(void);
-
-void rt_hw_exit(void);
-#endif
+/* + * File : board.h + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2009, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2009-09-22 Bernard add board.h to this bsp + */ + +#ifndef __BOARD_H__ +#define __BOARD_H__ +void rt_hw_board_init(void); +rt_uint8_t *rt_hw_sram_init(void); + +/* SD Card init function */ +void rt_hw_sdcard_init(void); + +int rt_hw_mtd_nand_init(void); +int sst25vfxx_mtd_init(const char *, unsigned int , unsigned int); +void pcap_netif_hw_init(void); +void rt_platform_init(void); +void rt_hw_usart_init(void); +void rt_hw_serial_init(void); +void rt_hw_sdl_start(void); +void rt_hw_win32_low_cpu(void); + +void rt_hw_exit(void); +#endif diff --git a/bsp/simulator/drivers/nanddrv_file.c b/bsp/simulator/drivers/nanddrv_file.c index 0b25da4052..770751ac79 100644 --- a/bsp/simulator/drivers/nanddrv_file.c +++ b/bsp/simulator/drivers/nanddrv_file.c @@ -1,399 +1,399 @@ -#include <rtdevice.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#define NAND_SIM "nand.bin"
-#if 1
-#define OOB_SIZE 64
-#define PAGE_DATA_SIZE 2048
-#define PAGE_SIZE (2048 + 64)
-#define PAGE_PER_BLOCK 64
-#define BLOCK_SIZE (PAGE_SIZE * PAGE_PER_BLOCK)
-#define BLOCK_NUM 512
-// #define BLOCK_NUM 2048
-#else
-#define OOB_SIZE 16
-#define PAGE_SIZE (512 + OOB_SIZE)
-#define PAGE_PER_BLOCK 32
-#define BLOCK_SIZE (PAGE_SIZE * PAGE_PER_BLOCK)
-#define BLOCK_NUM 512
-#endif
-
-#define ECC_SIZE ((PAGE_DATA_SIZE) * 3 / 256)
-
-static unsigned char block_data[BLOCK_SIZE];
-static struct rt_mtd_nand_device _nanddrv_file_device;
-static FILE *file = NULL;
-
-static rt_uint8_t CountBitsInByte(rt_uint8_t byte)
-{
- rt_uint8_t count = 0;
-
- while (byte > 0)
- {
- if (byte & 1)
- {
- count++;
- }
- byte >>= 1;
- }
-
- return count;
-}
-
-static void Compute256(const rt_uint8_t *data, rt_uint8_t *code)
-{
- rt_uint32_t i;
- rt_uint8_t columnSum = 0;
- rt_uint8_t evenLineCode = 0;
- rt_uint8_t oddLineCode = 0;
- rt_uint8_t evenColumnCode = 0;
- rt_uint8_t oddColumnCode = 0;
-
- // Xor all bytes together to get the column sum;
- // At the same time, calculate the even and odd line codes
- for (i = 0; i < 256; i++)
- {
- columnSum ^= data[i];
-
- // If the xor sum of the byte is 0, then this byte has no incidence on
- // the computed code; so check if the sum is 1.
- if ((CountBitsInByte(data[i]) & 1) == 1)
- {
- // Parity groups are formed by forcing a particular index bit to 0
- // (even) or 1 (odd).
- // Example on one byte:
- //
- // bits (dec) 7 6 5 4 3 2 1 0
- // (bin) 111 110 101 100 011 010 001 000
- // '---'---'---'----------.
- // |
- // groups P4' ooooooooooooooo eeeeeeeeeeeeeee P4 |
- // P2' ooooooo eeeeeee ooooooo eeeeeee P2 |
- // P1' ooo eee ooo eee ooo eee ooo eee P1 |
- // |
- // We can see that: |
- // - P4 -> bit 2 of index is 0 --------------------'
- // - P4' -> bit 2 of index is 1.
- // - P2 -> bit 1 of index if 0.
- // - etc...
- // We deduce that a bit position has an impact on all even Px if
- // the log2(x)nth bit of its index is 0
- // ex: log2(4) = 2, bit2 of the index must be 0 (-> 0 1 2 3)
- // and on all odd Px' if the log2(x)nth bit of its index is 1
- // ex: log2(2) = 1, bit1 of the index must be 1 (-> 0 1 4 5)
- //
- // As such, we calculate all the possible Px and Px' values at the
- // same time in two variables, evenLineCode and oddLineCode, such as
- // evenLineCode bits: P128 P64 P32 P16 P8 P4 P2 P1
- // oddLineCode bits: P128' P64' P32' P16' P8' P4' P2' P1'
- //
- evenLineCode ^= (255 - i);
- oddLineCode ^= i;
- }
- }
-
- // At this point, we have the line parities, and the column sum. First, We
- // must caculate the parity group values on the column sum.
- for (i = 0; i < 8; i++)
- {
- if (columnSum & 1)
- {
- evenColumnCode ^= (7 - i);
- oddColumnCode ^= i;
- }
- columnSum >>= 1;
- }
-
- // Now, we must interleave the parity values, to obtain the following layout:
- // Code[0] = Line1
- // Code[1] = Line2
- // Code[2] = Column
- // Line = Px' Px P(x-1)- P(x-1) ...
- // Column = P4' P4 P2' P2 P1' P1 PadBit PadBit
- code[0] = 0;
- code[1] = 0;
- code[2] = 0;
-
- for (i = 0; i < 4; i++)
- {
- code[0] <<= 2;
- code[1] <<= 2;
- code[2] <<= 2;
-
- // Line 1
- if ((oddLineCode & 0x80) != 0)
- {
- code[0] |= 2;
- }
-
- if ((evenLineCode & 0x80) != 0)
- {
- code[0] |= 1;
- }
-
- // Line 2
- if ((oddLineCode & 0x08) != 0)
- {
- code[1] |= 2;
- }
-
- if ((evenLineCode & 0x08) != 0)
- {
- code[1] |= 1;
- }
-
- // Column
- if ((oddColumnCode & 0x04) != 0)
- {
- code[2] |= 2;
- }
-
- if ((evenColumnCode & 0x04) != 0)
- {
- code[2] |= 1;
- }
-
- oddLineCode <<= 1;
- evenLineCode <<= 1;
- oddColumnCode <<= 1;
- evenColumnCode <<= 1;
- }
-
- // Invert codes (linux compatibility)
- code[0] = (~(rt_uint32_t)code[0]);
- code[1] = (~(rt_uint32_t)code[1]);
- code[2] = (~(rt_uint32_t)code[2]);
-}
-
-void ecc_hamming_compute256x(const rt_uint8_t *pucData, rt_uint32_t dwSize, rt_uint8_t *puCode)
-{
- while (dwSize > 0)
- {
- Compute256(pucData, puCode) ;
-
- pucData += 256;
- puCode += 3;
- dwSize -= 256;
- }
-}
-
-/* read chip id */
-static rt_uint32_t nanddrv_file_read_id(struct rt_mtd_nand_device *device)
-{
- return 0x00;
-}
-
-/* read/write/move page */
-static rt_err_t nanddrv_file_read_page(struct rt_mtd_nand_device *device,
- rt_off_t page,
- rt_uint8_t *data, rt_uint32_t data_len,
- rt_uint8_t *spare, rt_uint32_t spare_len)
-{
- rt_uint32_t offset;
- rt_uint8_t oob_ecc [ECC_SIZE];
- rt_uint8_t ecc [ECC_SIZE];
-
- page = page + device->block_start * device->pages_per_block;
-
- if (page / device->pages_per_block > device->block_end)
- {
- return -RT_EIO;
- }
-
- /* write page */
- offset = page * PAGE_SIZE;
- if (data != NULL && data_len != 0)
- {
- fseek(file, offset, SEEK_SET);
- fread(data, data_len, 1, file);
- if (data_len == PAGE_DATA_SIZE)
- {
- /* read ecc size */
- fread(oob_ecc, ECC_SIZE, 1, file);
-
- /* verify ECC */
- ecc_hamming_compute256x(data, PAGE_DATA_SIZE, &ecc[0]);
- if (memcmp(&oob_ecc[0], &ecc[0], ECC_SIZE) != 0)
- return -RT_MTD_EECC;
- }
- }
-
- if (spare != NULL && spare_len)
- {
- offset = page * PAGE_SIZE + PAGE_DATA_SIZE;
- fseek(file, offset, SEEK_SET);
- fread(spare, spare_len, 1, file);
- }
-
- return RT_EOK;
-}
-
-static rt_err_t nanddrv_file_write_page(struct rt_mtd_nand_device *device,
- rt_off_t page,
- const rt_uint8_t *data, rt_uint32_t data_len,
- const rt_uint8_t *oob, rt_uint32_t spare_len)
-{
- rt_uint32_t offset;
- rt_uint8_t ecc[ECC_SIZE];
-
- page = page + device->block_start * device->pages_per_block;
- if (page / device->pages_per_block > device->block_end)
- {
- return -RT_EIO;
- }
-
- /* write page */
- offset = page * PAGE_SIZE;
- if (data != RT_NULL && data_len != 0)
- {
- fseek(file, offset, SEEK_SET);
- fwrite(data, data_len, 1, file);
-
- if (data_len == PAGE_DATA_SIZE)
- {
- /*write the ecc information */
- ecc_hamming_compute256x(data, PAGE_DATA_SIZE, ecc);
-
- fwrite(ecc, ECC_SIZE, 1, file);
- }
- }
-
- if (oob != RT_NULL && spare_len != 0)
- {
- offset = page * PAGE_SIZE + PAGE_DATA_SIZE + ECC_SIZE;
- fseek(file, offset, SEEK_SET);
- fwrite(&oob[ECC_SIZE], spare_len-ECC_SIZE, 1, file);
- }
-
- return RT_EOK;
-}
-
-static rt_err_t nanddrv_file_move_page(struct rt_mtd_nand_device *device, rt_off_t from, rt_off_t to)
-{
- rt_uint32_t offset;
- rt_uint8_t page_buffer[PAGE_DATA_SIZE];
- rt_uint8_t oob_buffer[OOB_SIZE];
-
- from = from + device->block_start * device->pages_per_block;
- to = to + device->block_start * device->pages_per_block;
-
- if (from / device->pages_per_block > device->block_end ||
- to / device->pages_per_block > device->block_end)
- {
- return -RT_EIO;
- }
-
- if (device->plane_num > 1)
- {
- rt_uint32_t mask;
- rt_uint16_t from_block, to_block;
-
- from_block = (rt_uint16_t)(from / PAGE_PER_BLOCK);
- to_block = (rt_uint16_t)(to / PAGE_PER_BLOCK);
- mask = device->plane_num - 1;
-
- if ((from_block & mask) != (to_block & mask))
- {
- rt_kprintf("invalid page copy on the block. from [%d] --> to[%d]\n", from_block, to_block);
- return -RT_EIO;
- }
- }
-
- /* read page */
- offset = from * PAGE_SIZE;
- fseek(file, offset, SEEK_SET);
- fread(page_buffer, sizeof(page_buffer), 1, file);
- fread(oob_buffer, sizeof(oob_buffer), 1, file);
-
- /* write page */
- offset = to * PAGE_SIZE;
- fseek(file, offset, SEEK_SET);
- fwrite(page_buffer, sizeof(page_buffer), 1, file);
- fwrite(oob_buffer, sizeof(oob_buffer), 1, file);
-
- return RT_EOK;
-}
-
-/* erase block */
-static rt_err_t nanddrv_file_erase_block(struct rt_mtd_nand_device *device, rt_uint32_t block)
-{
- if (block > BLOCK_NUM) return -RT_EIO;
-
- /* add the start blocks */
- block = block + device->block_start;
-
- fseek(file, block * BLOCK_SIZE, SEEK_SET);
- fwrite(block_data, sizeof(block_data), 1, file);
-
- return RT_EOK;
-}
-
-const static struct rt_mtd_nand_driver_ops _ops =
-{
- nanddrv_file_read_id,
- nanddrv_file_read_page,
- nanddrv_file_write_page,
- nanddrv_file_move_page,
- nanddrv_file_erase_block,
- RT_NULL,
- RT_NULL,
-};
-
-void nand_eraseall(void);
-
-void rt_hw_mtd_nand_init(void)
-{
- rt_uint16_t ecc_size;
- rt_uint32_t size;
-
- memset(block_data, 0xff, sizeof(block_data));
- /* open file */
- file = fopen(NAND_SIM, "rb+");
- if (file == NULL)
- {
- file = fopen(NAND_SIM, "wb+");
- }
- fseek(file, 0, SEEK_END);
- size = ftell(file);
-
- fseek(file, 0, SEEK_SET);
- if (size < BLOCK_NUM * BLOCK_SIZE)
- {
- rt_uint32_t index;
- fseek(file, 0, SEEK_SET);
- for (index = 0; index < BLOCK_NUM; index ++)
- {
- fwrite(block_data, sizeof(block_data), 1, file);
- }
- }
- fseek(file, 0, SEEK_SET);
-
- ecc_size = (PAGE_DATA_SIZE) * 3 / 256;
- _nanddrv_file_device.plane_num = 2;
- _nanddrv_file_device.oob_size = OOB_SIZE;
- _nanddrv_file_device.oob_free = OOB_SIZE - ecc_size;
- _nanddrv_file_device.page_size = PAGE_DATA_SIZE;
- _nanddrv_file_device.pages_per_block = PAGE_PER_BLOCK;
- _nanddrv_file_device.block_start = 0;
- _nanddrv_file_device.block_end = BLOCK_NUM / 2;
- _nanddrv_file_device.block_total = _nanddrv_file_device.block_end - _nanddrv_file_device.block_start;
- _nanddrv_file_device.ops = &_ops;
-
- rt_mtd_nand_register_device("nand0", &_nanddrv_file_device);
-}
-
-#if defined(RT_USING_FINSH)
-#include <finsh.h>
-void nand_eraseall()
-{
- int index;
- for (index = 0; index < _nanddrv_file_device.block_total; index ++)
- {
- nanddrv_file_erase_block(&_nanddrv_file_device, index);
- }
-}
-FINSH_FUNCTION_EXPORT(nand_eraseall, erase all of block in the nand flash);
-
-#endif //RT_USING_FINSH
+#include <rtdevice.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#define NAND_SIM "nand.bin" +#if 1 +#define OOB_SIZE 64 +#define PAGE_DATA_SIZE 2048 +#define PAGE_SIZE (2048 + 64) +#define PAGE_PER_BLOCK 64 +#define BLOCK_SIZE (PAGE_SIZE * PAGE_PER_BLOCK) +#define BLOCK_NUM 512 +// #define BLOCK_NUM 2048 +#else +#define OOB_SIZE 16 +#define PAGE_SIZE (512 + OOB_SIZE) +#define PAGE_PER_BLOCK 32 +#define BLOCK_SIZE (PAGE_SIZE * PAGE_PER_BLOCK) +#define BLOCK_NUM 512 +#endif + +#define ECC_SIZE ((PAGE_DATA_SIZE) * 3 / 256) + +static unsigned char block_data[BLOCK_SIZE]; +static struct rt_mtd_nand_device _nanddrv_file_device; +static FILE *file = NULL; + +static rt_uint8_t CountBitsInByte(rt_uint8_t byte) +{ + rt_uint8_t count = 0; + + while (byte > 0) + { + if (byte & 1) + { + count++; + } + byte >>= 1; + } + + return count; +} + +static void Compute256(const rt_uint8_t *data, rt_uint8_t *code) +{ + rt_uint32_t i; + rt_uint8_t columnSum = 0; + rt_uint8_t evenLineCode = 0; + rt_uint8_t oddLineCode = 0; + rt_uint8_t evenColumnCode = 0; + rt_uint8_t oddColumnCode = 0; + + // Xor all bytes together to get the column sum; + // At the same time, calculate the even and odd line codes + for (i = 0; i < 256; i++) + { + columnSum ^= data[i]; + + // If the xor sum of the byte is 0, then this byte has no incidence on + // the computed code; so check if the sum is 1. + if ((CountBitsInByte(data[i]) & 1) == 1) + { + // Parity groups are formed by forcing a particular index bit to 0 + // (even) or 1 (odd). + // Example on one byte: + // + // bits (dec) 7 6 5 4 3 2 1 0 + // (bin) 111 110 101 100 011 010 001 000 + // '---'---'---'----------. + // | + // groups P4' ooooooooooooooo eeeeeeeeeeeeeee P4 | + // P2' ooooooo eeeeeee ooooooo eeeeeee P2 | + // P1' ooo eee ooo eee ooo eee ooo eee P1 | + // | + // We can see that: | + // - P4 -> bit 2 of index is 0 --------------------' + // - P4' -> bit 2 of index is 1. + // - P2 -> bit 1 of index if 0. + // - etc... + // We deduce that a bit position has an impact on all even Px if + // the log2(x)nth bit of its index is 0 + // ex: log2(4) = 2, bit2 of the index must be 0 (-> 0 1 2 3) + // and on all odd Px' if the log2(x)nth bit of its index is 1 + // ex: log2(2) = 1, bit1 of the index must be 1 (-> 0 1 4 5) + // + // As such, we calculate all the possible Px and Px' values at the + // same time in two variables, evenLineCode and oddLineCode, such as + // evenLineCode bits: P128 P64 P32 P16 P8 P4 P2 P1 + // oddLineCode bits: P128' P64' P32' P16' P8' P4' P2' P1' + // + evenLineCode ^= (255 - i); + oddLineCode ^= i; + } + } + + // At this point, we have the line parities, and the column sum. First, We + // must caculate the parity group values on the column sum. + for (i = 0; i < 8; i++) + { + if (columnSum & 1) + { + evenColumnCode ^= (7 - i); + oddColumnCode ^= i; + } + columnSum >>= 1; + } + + // Now, we must interleave the parity values, to obtain the following layout: + // Code[0] = Line1 + // Code[1] = Line2 + // Code[2] = Column + // Line = Px' Px P(x-1)- P(x-1) ... + // Column = P4' P4 P2' P2 P1' P1 PadBit PadBit + code[0] = 0; + code[1] = 0; + code[2] = 0; + + for (i = 0; i < 4; i++) + { + code[0] <<= 2; + code[1] <<= 2; + code[2] <<= 2; + + // Line 1 + if ((oddLineCode & 0x80) != 0) + { + code[0] |= 2; + } + + if ((evenLineCode & 0x80) != 0) + { + code[0] |= 1; + } + + // Line 2 + if ((oddLineCode & 0x08) != 0) + { + code[1] |= 2; + } + + if ((evenLineCode & 0x08) != 0) + { + code[1] |= 1; + } + + // Column + if ((oddColumnCode & 0x04) != 0) + { + code[2] |= 2; + } + + if ((evenColumnCode & 0x04) != 0) + { + code[2] |= 1; + } + + oddLineCode <<= 1; + evenLineCode <<= 1; + oddColumnCode <<= 1; + evenColumnCode <<= 1; + } + + // Invert codes (linux compatibility) + code[0] = (~(rt_uint32_t)code[0]); + code[1] = (~(rt_uint32_t)code[1]); + code[2] = (~(rt_uint32_t)code[2]); +} + +void ecc_hamming_compute256x(const rt_uint8_t *pucData, rt_uint32_t dwSize, rt_uint8_t *puCode) +{ + while (dwSize > 0) + { + Compute256(pucData, puCode) ; + + pucData += 256; + puCode += 3; + dwSize -= 256; + } +} + +/* read chip id */ +static rt_uint32_t nanddrv_file_read_id(struct rt_mtd_nand_device *device) +{ + return 0x00; +} + +/* read/write/move page */ +static rt_err_t nanddrv_file_read_page(struct rt_mtd_nand_device *device, + rt_off_t page, + rt_uint8_t *data, rt_uint32_t data_len, + rt_uint8_t *spare, rt_uint32_t spare_len) +{ + rt_uint32_t offset; + rt_uint8_t oob_ecc [ECC_SIZE]; + rt_uint8_t ecc [ECC_SIZE]; + + page = page + device->block_start * device->pages_per_block; + + if (page / device->pages_per_block > device->block_end) + { + return -RT_EIO; + } + + /* write page */ + offset = page * PAGE_SIZE; + if (data != NULL && data_len != 0) + { + fseek(file, offset, SEEK_SET); + fread(data, data_len, 1, file); + if (data_len == PAGE_DATA_SIZE) + { + /* read ecc size */ + fread(oob_ecc, ECC_SIZE, 1, file); + + /* verify ECC */ + ecc_hamming_compute256x(data, PAGE_DATA_SIZE, &ecc[0]); + if (memcmp(&oob_ecc[0], &ecc[0], ECC_SIZE) != 0) + return -RT_MTD_EECC; + } + } + + if (spare != NULL && spare_len) + { + offset = page * PAGE_SIZE + PAGE_DATA_SIZE; + fseek(file, offset, SEEK_SET); + fread(spare, spare_len, 1, file); + } + + return RT_EOK; +} + +static rt_err_t nanddrv_file_write_page(struct rt_mtd_nand_device *device, + rt_off_t page, + const rt_uint8_t *data, rt_uint32_t data_len, + const rt_uint8_t *oob, rt_uint32_t spare_len) +{ + rt_uint32_t offset; + rt_uint8_t ecc[ECC_SIZE]; + + page = page + device->block_start * device->pages_per_block; + if (page / device->pages_per_block > device->block_end) + { + return -RT_EIO; + } + + /* write page */ + offset = page * PAGE_SIZE; + if (data != RT_NULL && data_len != 0) + { + fseek(file, offset, SEEK_SET); + fwrite(data, data_len, 1, file); + + if (data_len == PAGE_DATA_SIZE) + { + /*write the ecc information */ + ecc_hamming_compute256x(data, PAGE_DATA_SIZE, ecc); + + fwrite(ecc, ECC_SIZE, 1, file); + } + } + + if (oob != RT_NULL && spare_len != 0) + { + offset = page * PAGE_SIZE + PAGE_DATA_SIZE + ECC_SIZE; + fseek(file, offset, SEEK_SET); + fwrite(&oob[ECC_SIZE], spare_len-ECC_SIZE, 1, file); + } + + return RT_EOK; +} + +static rt_err_t nanddrv_file_move_page(struct rt_mtd_nand_device *device, rt_off_t from, rt_off_t to) +{ + rt_uint32_t offset; + rt_uint8_t page_buffer[PAGE_DATA_SIZE]; + rt_uint8_t oob_buffer[OOB_SIZE]; + + from = from + device->block_start * device->pages_per_block; + to = to + device->block_start * device->pages_per_block; + + if (from / device->pages_per_block > device->block_end || + to / device->pages_per_block > device->block_end) + { + return -RT_EIO; + } + + if (device->plane_num > 1) + { + rt_uint32_t mask; + rt_uint16_t from_block, to_block; + + from_block = (rt_uint16_t)(from / PAGE_PER_BLOCK); + to_block = (rt_uint16_t)(to / PAGE_PER_BLOCK); + mask = device->plane_num - 1; + + if ((from_block & mask) != (to_block & mask)) + { + rt_kprintf("invalid page copy on the block. from [%d] --> to[%d]\n", from_block, to_block); + return -RT_EIO; + } + } + + /* read page */ + offset = from * PAGE_SIZE; + fseek(file, offset, SEEK_SET); + fread(page_buffer, sizeof(page_buffer), 1, file); + fread(oob_buffer, sizeof(oob_buffer), 1, file); + + /* write page */ + offset = to * PAGE_SIZE; + fseek(file, offset, SEEK_SET); + fwrite(page_buffer, sizeof(page_buffer), 1, file); + fwrite(oob_buffer, sizeof(oob_buffer), 1, file); + + return RT_EOK; +} + +/* erase block */ +static rt_err_t nanddrv_file_erase_block(struct rt_mtd_nand_device *device, rt_uint32_t block) +{ + if (block > BLOCK_NUM) return -RT_EIO; + + /* add the start blocks */ + block = block + device->block_start; + + fseek(file, block * BLOCK_SIZE, SEEK_SET); + fwrite(block_data, sizeof(block_data), 1, file); + + return RT_EOK; +} + +const static struct rt_mtd_nand_driver_ops _ops = +{ + nanddrv_file_read_id, + nanddrv_file_read_page, + nanddrv_file_write_page, + nanddrv_file_move_page, + nanddrv_file_erase_block, + RT_NULL, + RT_NULL, +}; + +void nand_eraseall(void); + +void rt_hw_mtd_nand_init(void) +{ + rt_uint16_t ecc_size; + rt_uint32_t size; + + memset(block_data, 0xff, sizeof(block_data)); + /* open file */ + file = fopen(NAND_SIM, "rb+"); + if (file == NULL) + { + file = fopen(NAND_SIM, "wb+"); + } + fseek(file, 0, SEEK_END); + size = ftell(file); + + fseek(file, 0, SEEK_SET); + if (size < BLOCK_NUM * BLOCK_SIZE) + { + rt_uint32_t index; + fseek(file, 0, SEEK_SET); + for (index = 0; index < BLOCK_NUM; index ++) + { + fwrite(block_data, sizeof(block_data), 1, file); + } + } + fseek(file, 0, SEEK_SET); + + ecc_size = (PAGE_DATA_SIZE) * 3 / 256; + _nanddrv_file_device.plane_num = 2; + _nanddrv_file_device.oob_size = OOB_SIZE; + _nanddrv_file_device.oob_free = OOB_SIZE - ecc_size; + _nanddrv_file_device.page_size = PAGE_DATA_SIZE; + _nanddrv_file_device.pages_per_block = PAGE_PER_BLOCK; + _nanddrv_file_device.block_start = 0; + _nanddrv_file_device.block_end = BLOCK_NUM / 2; + _nanddrv_file_device.block_total = _nanddrv_file_device.block_end - _nanddrv_file_device.block_start; + _nanddrv_file_device.ops = &_ops; + + rt_mtd_nand_register_device("nand0", &_nanddrv_file_device); +} + +#if defined(RT_USING_FINSH) +#include <finsh.h> +void nand_eraseall() +{ + int index; + for (index = 0; index < _nanddrv_file_device.block_total; index ++) + { + nanddrv_file_erase_block(&_nanddrv_file_device, index); + } +} +FINSH_FUNCTION_EXPORT(nand_eraseall, erase all of block in the nand flash); + +#endif //RT_USING_FINSH diff --git a/bsp/simulator/drivers/sd_sim.c b/bsp/simulator/drivers/sd_sim.c index a9e327ad51..7c9844bae3 100644 --- a/bsp/simulator/drivers/sd_sim.c +++ b/bsp/simulator/drivers/sd_sim.c @@ -1,193 +1,193 @@ -#include <rtthread.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <dfs_def.h>
-
-// #define SD_TRACE rt_kprintf
-#define SD_TRACE(...)
-
-//#define SDCARD_SIM "F:\\Project\\tools\\SDCARD"
-#define SDCARD_SIM "sd.bin"
-#define SDCARD_SIZE (16*1024*1024) //16M
-
-struct sdcard_device
-{
- struct rt_device parent;
- FILE *file;
-};
-static struct sdcard_device _sdcard;
-
-#define SDCARD_DEVICE(device) (( struct sdcard_device*)(device))
-
-static rt_mutex_t lock;
-
-/* RT-Thread device interface */
-
-static rt_err_t rt_sdcard_init(rt_device_t dev)
-{
- return RT_EOK;
-}
-
-static rt_err_t rt_sdcard_open(rt_device_t dev, rt_uint16_t oflag)
-{
- return RT_EOK;
-}
-
-static rt_err_t rt_sdcard_close(rt_device_t dev)
-{
- return RT_EOK;
-}
-
-/* position: block page address, not bytes address
- * buffer:
- * size : how many blocks
- */
-static rt_size_t rt_sdcard_read(rt_device_t device, rt_off_t position, void *buffer, rt_size_t size)
-{
- struct sdcard_device *sd;
- int result = 0;
-
- SD_TRACE("sd read: pos %d, size %d\n", position, size);
-
- rt_mutex_take(lock, RT_WAITING_FOREVER);
- sd = SDCARD_DEVICE(device);
- fseek(sd->file, position * SECTOR_SIZE, SEEK_SET);
-
- result = fread(buffer, size * SECTOR_SIZE, 1, sd->file);
- if (result < 0)
- goto _err;
-
- rt_mutex_release(lock);
- return size;
-
-_err:
- SD_TRACE("sd read errors!\n");
- rt_mutex_release(lock);
- return 0;
-}
-
-/* position: block page address, not bytes address
- * buffer:
- * size : how many blocks
- */
-static rt_size_t rt_sdcard_write(rt_device_t device, rt_off_t position, const void *buffer, rt_size_t size)
-{
- struct sdcard_device *sd;
- int result = 0;
-
- SD_TRACE("sst write: pos %d, size %d\n", position, size);
-
- rt_mutex_take(lock, RT_WAITING_FOREVER);
- sd = SDCARD_DEVICE(device);
- fseek(sd->file, position * SECTOR_SIZE, SEEK_SET);
-
- result = fwrite(buffer, size * SECTOR_SIZE, 1, sd->file);
- if (result < 0)
- goto _err;
-
- rt_mutex_release(lock);
- return size;
-
-_err:
- SD_TRACE("sd write errors!\n");
- rt_mutex_release(lock);
- return 0;
-}
-
-static rt_err_t rt_sdcard_control(rt_device_t dev, rt_uint8_t cmd, void *args)
-{
- struct sdcard_device *sd;
- unsigned int size;
-
- RT_ASSERT(dev != RT_NULL);
-
- sd = SDCARD_DEVICE(dev);
-
- if (cmd == RT_DEVICE_CTRL_BLK_GETGEOME)
- {
- struct rt_device_blk_geometry *geometry;
-
- geometry = (struct rt_device_blk_geometry *)args;
- if (geometry == RT_NULL) return -RT_ERROR;
-
- geometry->bytes_per_sector = SECTOR_SIZE;
- geometry->block_size = SECTOR_SIZE;
-
- fseek(sd->file, 0, SEEK_END);
- size = ftell(sd->file);
-
- geometry->sector_count = size / SECTOR_SIZE;
- }
- return RT_EOK;
-}
-
-
-rt_err_t rt_hw_sdcard_init(const char *spi_device_name)
-{
- int size;
- struct sdcard_device *sd;
- struct rt_device *device;
-
- sd = &_sdcard;
- device = &(sd->parent);
-
- lock = rt_mutex_create("lock", RT_IPC_FLAG_FIFO);
-
- /* open sd card file, if not exist, then create it */
- sd->file = fopen(SDCARD_SIM, "rb+");
- if (sd->file == NULL)
- {
- /* create a file to simulate sd card */
- sd->file = fopen(SDCARD_SIM, "wb+");
-
- fseek(sd->file, 0, SEEK_END);
- size = ftell(sd->file);
-
- fseek(sd->file, 0, SEEK_SET);
- if (size < SDCARD_SIZE)
- {
- int i;
- unsigned char *ptr;
-
- ptr = (unsigned char *) malloc(1024 * 1024);
- if (ptr == NULL)
- {
- SD_TRACE("malloc error, no memory!\n");
- return RT_ERROR;
- }
- memset(ptr, 0x0, 1024 * 1024);
-
- fseek(sd->file, 0, SEEK_SET);
-
- for (i = 0; i < (SDCARD_SIZE / (1024 * 1024)); i++)
- fwrite(ptr, 1024 * 1024, 1, sd->file);
-
- free(ptr);
- }
- }
- fseek(sd->file, 0, SEEK_SET);
-
- device->type = RT_Device_Class_Block;
- device->init = rt_sdcard_init;
- device->open = rt_sdcard_open;
- device->close = rt_sdcard_close;
- device->read = rt_sdcard_read;
- device->write = rt_sdcard_write;
- device->control = rt_sdcard_control;
- device->user_data = NULL;
-
- rt_device_register(device, "sd0",
- RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_REMOVABLE | RT_DEVICE_FLAG_STANDALONE);
-
- return RT_EOK;
-}
-
-#ifdef RT_USING_FINSH
-#include <finsh.h>
-void eraseall(void)
-{
- printf("had not implemented yet!\n");
-}
-FINSH_FUNCTION_EXPORT(eraseall, erase all block in SPI flash);
-#endif
+#include <rtthread.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <dfs_def.h> + +// #define SD_TRACE rt_kprintf +#define SD_TRACE(...) + +//#define SDCARD_SIM "F:\\Project\\tools\\SDCARD" +#define SDCARD_SIM "sd.bin" +#define SDCARD_SIZE (16*1024*1024) //16M + +struct sdcard_device +{ + struct rt_device parent; + FILE *file; +}; +static struct sdcard_device _sdcard; + +#define SDCARD_DEVICE(device) (( struct sdcard_device*)(device)) + +static rt_mutex_t lock; + +/* RT-Thread device interface */ + +static rt_err_t rt_sdcard_init(rt_device_t dev) +{ + return RT_EOK; +} + +static rt_err_t rt_sdcard_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} + +static rt_err_t rt_sdcard_close(rt_device_t dev) +{ + return RT_EOK; +} + +/* position: block page address, not bytes address + * buffer: + * size : how many blocks + */ +static rt_size_t rt_sdcard_read(rt_device_t device, rt_off_t position, void *buffer, rt_size_t size) +{ + struct sdcard_device *sd; + int result = 0; + + SD_TRACE("sd read: pos %d, size %d\n", position, size); + + rt_mutex_take(lock, RT_WAITING_FOREVER); + sd = SDCARD_DEVICE(device); + fseek(sd->file, position * SECTOR_SIZE, SEEK_SET); + + result = fread(buffer, size * SECTOR_SIZE, 1, sd->file); + if (result < 0) + goto _err; + + rt_mutex_release(lock); + return size; + +_err: + SD_TRACE("sd read errors!\n"); + rt_mutex_release(lock); + return 0; +} + +/* position: block page address, not bytes address + * buffer: + * size : how many blocks + */ +static rt_size_t rt_sdcard_write(rt_device_t device, rt_off_t position, const void *buffer, rt_size_t size) +{ + struct sdcard_device *sd; + int result = 0; + + SD_TRACE("sst write: pos %d, size %d\n", position, size); + + rt_mutex_take(lock, RT_WAITING_FOREVER); + sd = SDCARD_DEVICE(device); + fseek(sd->file, position * SECTOR_SIZE, SEEK_SET); + + result = fwrite(buffer, size * SECTOR_SIZE, 1, sd->file); + if (result < 0) + goto _err; + + rt_mutex_release(lock); + return size; + +_err: + SD_TRACE("sd write errors!\n"); + rt_mutex_release(lock); + return 0; +} + +static rt_err_t rt_sdcard_control(rt_device_t dev, rt_uint8_t cmd, void *args) +{ + struct sdcard_device *sd; + unsigned int size; + + RT_ASSERT(dev != RT_NULL); + + sd = SDCARD_DEVICE(dev); + + if (cmd == RT_DEVICE_CTRL_BLK_GETGEOME) + { + struct rt_device_blk_geometry *geometry; + + geometry = (struct rt_device_blk_geometry *)args; + if (geometry == RT_NULL) return -RT_ERROR; + + geometry->bytes_per_sector = SECTOR_SIZE; + geometry->block_size = SECTOR_SIZE; + + fseek(sd->file, 0, SEEK_END); + size = ftell(sd->file); + + geometry->sector_count = size / SECTOR_SIZE; + } + return RT_EOK; +} + + +rt_err_t rt_hw_sdcard_init(const char *spi_device_name) +{ + int size; + struct sdcard_device *sd; + struct rt_device *device; + + sd = &_sdcard; + device = &(sd->parent); + + lock = rt_mutex_create("lock", RT_IPC_FLAG_FIFO); + + /* open sd card file, if not exist, then create it */ + sd->file = fopen(SDCARD_SIM, "rb+"); + if (sd->file == NULL) + { + /* create a file to simulate sd card */ + sd->file = fopen(SDCARD_SIM, "wb+"); + + fseek(sd->file, 0, SEEK_END); + size = ftell(sd->file); + + fseek(sd->file, 0, SEEK_SET); + if (size < SDCARD_SIZE) + { + int i; + unsigned char *ptr; + + ptr = (unsigned char *) malloc(1024 * 1024); + if (ptr == NULL) + { + SD_TRACE("malloc error, no memory!\n"); + return RT_ERROR; + } + memset(ptr, 0x0, 1024 * 1024); + + fseek(sd->file, 0, SEEK_SET); + + for (i = 0; i < (SDCARD_SIZE / (1024 * 1024)); i++) + fwrite(ptr, 1024 * 1024, 1, sd->file); + + free(ptr); + } + } + fseek(sd->file, 0, SEEK_SET); + + device->type = RT_Device_Class_Block; + device->init = rt_sdcard_init; + device->open = rt_sdcard_open; + device->close = rt_sdcard_close; + device->read = rt_sdcard_read; + device->write = rt_sdcard_write; + device->control = rt_sdcard_control; + device->user_data = NULL; + + rt_device_register(device, "sd0", + RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_REMOVABLE | RT_DEVICE_FLAG_STANDALONE); + + return RT_EOK; +} + +#ifdef RT_USING_FINSH +#include <finsh.h> +void eraseall(void) +{ + printf("had not implemented yet!\n"); +} +FINSH_FUNCTION_EXPORT(eraseall, erase all block in SPI flash); +#endif diff --git a/bsp/simulator/drivers/sdl_fb.c b/bsp/simulator/drivers/sdl_fb.c index fca7e3ed79..790797f2af 100644 --- a/bsp/simulator/drivers/sdl_fb.c +++ b/bsp/simulator/drivers/sdl_fb.c @@ -1,304 +1,304 @@ -#include <rtthread.h>
-
-#include <sdl.h>
-#include <rtdevice.h>
-#include <rtgui/driver.h>
-
-#define SDL_SCREEN_WIDTH 800
-#define SDL_SCREEN_HEIGHT 480
-
-struct sdlfb_device
-{
- struct rt_device parent;
-
- SDL_Surface *screen;
- rt_uint16_t width;
- rt_uint16_t height;
-};
-struct sdlfb_device _device;
-
-/* common device interface */
-static rt_err_t sdlfb_init(rt_device_t dev)
-{
- return RT_EOK;
-}
-static rt_err_t sdlfb_open(rt_device_t dev, rt_uint16_t oflag)
-{
- return RT_EOK;
-}
-static rt_err_t sdlfb_close(rt_device_t dev)
-{
- SDL_Quit();
- return RT_EOK;
-}
-
-static rt_mutex_t sdllock;
-static rt_err_t sdlfb_control(rt_device_t dev, rt_uint8_t cmd, void *args)
-{
- struct sdlfb_device *device;
-
- rt_mutex_take(sdllock, RT_WAITING_FOREVER);
- device = (struct sdlfb_device *)dev;
- RT_ASSERT(device != RT_NULL);
- RT_ASSERT(device->screen != RT_NULL);
-
- switch (cmd)
- {
- case RTGRAPHIC_CTRL_GET_INFO:
- {
- struct rt_device_graphic_info *info;
-
- info = (struct rt_device_graphic_info *) args;
- info->bits_per_pixel = 16;
- info->pixel_format = RTGRAPHIC_PIXEL_FORMAT_RGB565P;
- info->framebuffer = device->screen->pixels;
- info->width = device->screen->w;
- info->height = device->screen->h;
- }
- break;
- case RTGRAPHIC_CTRL_RECT_UPDATE:
- {
- struct rt_device_rect_info *rect;
- rect = (struct rt_device_rect_info *)args;
-
- /* SDL_UpdateRect(_device.screen, rect->x, rect->y, rect->x + rect->w, rect->y + rect->h); */
- SDL_UpdateRect(_device.screen, 0, 0, device->width, device->height);
- }
- break;
- case RTGRAPHIC_CTRL_SET_MODE:
- {
-#if 0
- struct rt_device_rect_info *rect;
-
- rect = (struct rt_device_rect_info *)args;
- if ((_device.width == rect->width) && (_device.height == rect->height)) return -RT_ERROR;
-
- _device.width = rect->width;
- _device.height = rect->height;
-
- if (_device.screen != RT_NULL)
- {
- SDL_FreeSurface(_device.screen);
-
- /* re-create screen surface */
- _device.screen = SDL_SetVideoMode(_device.width, _device.height, 16, SDL_SWSURFACE | SDL_DOUBLEBUF);
- if (_device.screen == NULL)
- {
- fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
- exit(1);
- }
-
- SDL_WM_SetCaption("RT-Thread/GUI Simulator", NULL);
- }
-#endif
- }
- break;
- }
- rt_mutex_release(sdllock);
- return RT_EOK;
-}
-
-static void sdlfb_hw_init(void)
-{
- /* set video driver for VC++ debug */
- //_putenv("SDL_VIDEODRIVER=windib");
-
- //if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0)
- if (SDL_Init(SDL_INIT_EVERYTHING) < 0)
- {
- fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError());
- exit(1);
- }
-
- _device.parent.init = sdlfb_init;
- _device.parent.open = sdlfb_open;
- _device.parent.close = sdlfb_close;
- _device.parent.read = RT_NULL;
- _device.parent.write = RT_NULL;
- _device.parent.control = sdlfb_control;
-
- _device.width = SDL_SCREEN_WIDTH;
- _device.height = SDL_SCREEN_HEIGHT;
- _device.screen = SDL_SetVideoMode(_device.width, _device.height, 16, SDL_SWSURFACE | SDL_DOUBLEBUF);
- if (_device.screen == NULL)
- {
- fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError());
- exit(1);
- }
-
- SDL_WM_SetCaption("RT-Thread/GUI Simulator", NULL);
- rt_device_register(RT_DEVICE(&_device), "sdl", RT_DEVICE_FLAG_RDWR);
-
- sdllock = rt_mutex_create("fb", RT_IPC_FLAG_FIFO);
-}
-
-#include <windows.h>
-#include <mmsystem.h>
-#include <stdio.h>
-#include <sdl.h>
-#include <rtgui/event.h>
-#include <rtgui/kbddef.h>
-#include <rtgui/rtgui_server.h>
-#include <rtgui/rtgui_system.h>
-
-static DWORD WINAPI sdl_loop(LPVOID lpParam)
-{
- int quit = 0;
- SDL_Event event;
- int button_state = 0;
-
- rt_device_t device;
- sdlfb_hw_init();
-
- device = rt_device_find("sdl");
- rtgui_graphic_set_device(device);
-
- /* handle SDL event */
- while (!quit)
- {
- SDL_WaitEvent(&event);
-
- switch (event.type)
- {
- case SDL_MOUSEMOTION:
-#if 0
- {
- struct rtgui_event_mouse emouse;
- emouse.parent.type = RTGUI_EVENT_MOUSE_MOTION;
- emouse.parent.sender = RT_NULL;
- emouse.wid = RT_NULL;
-
- emouse.x = ((SDL_MouseMotionEvent *)&event)->x;
- emouse.y = ((SDL_MouseMotionEvent *)&event)->y;
-
- /* init mouse button */
- emouse.button = button_state;
-
- /* send event to server */
- rtgui_server_post_event(&emouse.parent, sizeof(struct rtgui_event_mouse));
- }
-#endif
- break;
-
- case SDL_MOUSEBUTTONDOWN:
- case SDL_MOUSEBUTTONUP:
- {
- struct rtgui_event_mouse emouse;
- SDL_MouseButtonEvent *mb;
-
- emouse.parent.type = RTGUI_EVENT_MOUSE_BUTTON;
- emouse.parent.sender = RT_NULL;
- emouse.wid = RT_NULL;
-
- mb = (SDL_MouseButtonEvent *)&event;
-
- emouse.x = mb->x;
- emouse.y = mb->y;
-
- /* init mouse button */
- emouse.button = 0;
-
- /* set emouse button */
- if (mb->button & (1 << (SDL_BUTTON_LEFT - 1)))
- {
- emouse.button |= RTGUI_MOUSE_BUTTON_LEFT;
- }
- else if (mb->button & (1 << (SDL_BUTTON_RIGHT - 1)))
- {
- emouse.button |= RTGUI_MOUSE_BUTTON_RIGHT;
- }
- else if (mb->button & (1 << (SDL_BUTTON_MIDDLE - 1)))
- {
- emouse.button |= RTGUI_MOUSE_BUTTON_MIDDLE;
- }
-
- if (mb->type == SDL_MOUSEBUTTONDOWN)
- {
- emouse.button |= RTGUI_MOUSE_BUTTON_DOWN;
- button_state = emouse.button;
- }
- else
- {
- emouse.button |= RTGUI_MOUSE_BUTTON_UP;
- button_state = 0;
- }
-
-
- /* send event to server */
- rtgui_server_post_event(&emouse.parent, sizeof(struct rtgui_event_mouse));
- }
- break;
-
- case SDL_KEYUP:
- {
- struct rtgui_event_kbd ekbd;
- ekbd.parent.type = RTGUI_EVENT_KBD;
- ekbd.parent.sender = RT_NULL;
- ekbd.type = RTGUI_KEYUP;
- ekbd.wid = RT_NULL;
- ekbd.mod = event.key.keysym.mod;
- ekbd.key = event.key.keysym.sym;
-
- /* FIXME: unicode */
- ekbd.unicode = 0;
-
- /* send event to server */
- rtgui_server_post_event(&ekbd.parent, sizeof(struct rtgui_event_kbd));
- }
- break;
-
- case SDL_KEYDOWN:
- {
- struct rtgui_event_kbd ekbd;
- ekbd.parent.type = RTGUI_EVENT_KBD;
- ekbd.parent.sender = RT_NULL;
- ekbd.type = RTGUI_KEYDOWN;
- ekbd.wid = RT_NULL;
- ekbd.mod = event.key.keysym.mod;
- ekbd.key = event.key.keysym.sym;
-
- /* FIXME: unicode */
- ekbd.unicode = 0;
-
- /* send event to server */
- rtgui_server_post_event(&ekbd.parent, sizeof(struct rtgui_event_kbd));
- }
- break;
-
- case SDL_QUIT:
- SDL_Quit();
- quit = 1;
- break;
-
- default:
- break;
- }
-
- if (quit)
- break;
- }
- //exit(0);
- return 0;
-}
-
-/* start sdl thread */
-void rt_hw_sdl_start(void)
-{
- HANDLE thread;
- DWORD thread_id;
-
- /* create thread that loop sdl event */
- thread = CreateThread(NULL,
- 0,
- (LPTHREAD_START_ROUTINE)sdl_loop,
- 0,
- CREATE_SUSPENDED,
- &thread_id);
- if (thread == NULL)
- {
- //Display Error Message
-
- return;
- }
- ResumeThread(thread);
-}
+#include <rtthread.h> + +#include <sdl.h> +#include <rtdevice.h> +#include <rtgui/driver.h> + +#define SDL_SCREEN_WIDTH 800 +#define SDL_SCREEN_HEIGHT 480 + +struct sdlfb_device +{ + struct rt_device parent; + + SDL_Surface *screen; + rt_uint16_t width; + rt_uint16_t height; +}; +struct sdlfb_device _device; + +/* common device interface */ +static rt_err_t sdlfb_init(rt_device_t dev) +{ + return RT_EOK; +} +static rt_err_t sdlfb_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} +static rt_err_t sdlfb_close(rt_device_t dev) +{ + SDL_Quit(); + return RT_EOK; +} + +static rt_mutex_t sdllock; +static rt_err_t sdlfb_control(rt_device_t dev, rt_uint8_t cmd, void *args) +{ + struct sdlfb_device *device; + + rt_mutex_take(sdllock, RT_WAITING_FOREVER); + device = (struct sdlfb_device *)dev; + RT_ASSERT(device != RT_NULL); + RT_ASSERT(device->screen != RT_NULL); + + switch (cmd) + { + case RTGRAPHIC_CTRL_GET_INFO: + { + struct rt_device_graphic_info *info; + + info = (struct rt_device_graphic_info *) args; + info->bits_per_pixel = 16; + info->pixel_format = RTGRAPHIC_PIXEL_FORMAT_RGB565P; + info->framebuffer = device->screen->pixels; + info->width = device->screen->w; + info->height = device->screen->h; + } + break; + case RTGRAPHIC_CTRL_RECT_UPDATE: + { + struct rt_device_rect_info *rect; + rect = (struct rt_device_rect_info *)args; + + /* SDL_UpdateRect(_device.screen, rect->x, rect->y, rect->x + rect->w, rect->y + rect->h); */ + SDL_UpdateRect(_device.screen, 0, 0, device->width, device->height); + } + break; + case RTGRAPHIC_CTRL_SET_MODE: + { +#if 0 + struct rt_device_rect_info *rect; + + rect = (struct rt_device_rect_info *)args; + if ((_device.width == rect->width) && (_device.height == rect->height)) return -RT_ERROR; + + _device.width = rect->width; + _device.height = rect->height; + + if (_device.screen != RT_NULL) + { + SDL_FreeSurface(_device.screen); + + /* re-create screen surface */ + _device.screen = SDL_SetVideoMode(_device.width, _device.height, 16, SDL_SWSURFACE | SDL_DOUBLEBUF); + if (_device.screen == NULL) + { + fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); + exit(1); + } + + SDL_WM_SetCaption("RT-Thread/GUI Simulator", NULL); + } +#endif + } + break; + } + rt_mutex_release(sdllock); + return RT_EOK; +} + +static void sdlfb_hw_init(void) +{ + /* set video driver for VC++ debug */ + //_putenv("SDL_VIDEODRIVER=windib"); + + //if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) < 0) + if (SDL_Init(SDL_INIT_EVERYTHING) < 0) + { + fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); + exit(1); + } + + _device.parent.init = sdlfb_init; + _device.parent.open = sdlfb_open; + _device.parent.close = sdlfb_close; + _device.parent.read = RT_NULL; + _device.parent.write = RT_NULL; + _device.parent.control = sdlfb_control; + + _device.width = SDL_SCREEN_WIDTH; + _device.height = SDL_SCREEN_HEIGHT; + _device.screen = SDL_SetVideoMode(_device.width, _device.height, 16, SDL_SWSURFACE | SDL_DOUBLEBUF); + if (_device.screen == NULL) + { + fprintf(stderr, "Couldn't set video mode: %s\n", SDL_GetError()); + exit(1); + } + + SDL_WM_SetCaption("RT-Thread/GUI Simulator", NULL); + rt_device_register(RT_DEVICE(&_device), "sdl", RT_DEVICE_FLAG_RDWR); + + sdllock = rt_mutex_create("fb", RT_IPC_FLAG_FIFO); +} + +#include <windows.h> +#include <mmsystem.h> +#include <stdio.h> +#include <sdl.h> +#include <rtgui/event.h> +#include <rtgui/kbddef.h> +#include <rtgui/rtgui_server.h> +#include <rtgui/rtgui_system.h> + +static DWORD WINAPI sdl_loop(LPVOID lpParam) +{ + int quit = 0; + SDL_Event event; + int button_state = 0; + + rt_device_t device; + sdlfb_hw_init(); + + device = rt_device_find("sdl"); + rtgui_graphic_set_device(device); + + /* handle SDL event */ + while (!quit) + { + SDL_WaitEvent(&event); + + switch (event.type) + { + case SDL_MOUSEMOTION: +#if 0 + { + struct rtgui_event_mouse emouse; + emouse.parent.type = RTGUI_EVENT_MOUSE_MOTION; + emouse.parent.sender = RT_NULL; + emouse.wid = RT_NULL; + + emouse.x = ((SDL_MouseMotionEvent *)&event)->x; + emouse.y = ((SDL_MouseMotionEvent *)&event)->y; + + /* init mouse button */ + emouse.button = button_state; + + /* send event to server */ + rtgui_server_post_event(&emouse.parent, sizeof(struct rtgui_event_mouse)); + } +#endif + break; + + case SDL_MOUSEBUTTONDOWN: + case SDL_MOUSEBUTTONUP: + { + struct rtgui_event_mouse emouse; + SDL_MouseButtonEvent *mb; + + emouse.parent.type = RTGUI_EVENT_MOUSE_BUTTON; + emouse.parent.sender = RT_NULL; + emouse.wid = RT_NULL; + + mb = (SDL_MouseButtonEvent *)&event; + + emouse.x = mb->x; + emouse.y = mb->y; + + /* init mouse button */ + emouse.button = 0; + + /* set emouse button */ + if (mb->button & (1 << (SDL_BUTTON_LEFT - 1))) + { + emouse.button |= RTGUI_MOUSE_BUTTON_LEFT; + } + else if (mb->button & (1 << (SDL_BUTTON_RIGHT - 1))) + { + emouse.button |= RTGUI_MOUSE_BUTTON_RIGHT; + } + else if (mb->button & (1 << (SDL_BUTTON_MIDDLE - 1))) + { + emouse.button |= RTGUI_MOUSE_BUTTON_MIDDLE; + } + + if (mb->type == SDL_MOUSEBUTTONDOWN) + { + emouse.button |= RTGUI_MOUSE_BUTTON_DOWN; + button_state = emouse.button; + } + else + { + emouse.button |= RTGUI_MOUSE_BUTTON_UP; + button_state = 0; + } + + + /* send event to server */ + rtgui_server_post_event(&emouse.parent, sizeof(struct rtgui_event_mouse)); + } + break; + + case SDL_KEYUP: + { + struct rtgui_event_kbd ekbd; + ekbd.parent.type = RTGUI_EVENT_KBD; + ekbd.parent.sender = RT_NULL; + ekbd.type = RTGUI_KEYUP; + ekbd.wid = RT_NULL; + ekbd.mod = event.key.keysym.mod; + ekbd.key = event.key.keysym.sym; + + /* FIXME: unicode */ + ekbd.unicode = 0; + + /* send event to server */ + rtgui_server_post_event(&ekbd.parent, sizeof(struct rtgui_event_kbd)); + } + break; + + case SDL_KEYDOWN: + { + struct rtgui_event_kbd ekbd; + ekbd.parent.type = RTGUI_EVENT_KBD; + ekbd.parent.sender = RT_NULL; + ekbd.type = RTGUI_KEYDOWN; + ekbd.wid = RT_NULL; + ekbd.mod = event.key.keysym.mod; + ekbd.key = event.key.keysym.sym; + + /* FIXME: unicode */ + ekbd.unicode = 0; + + /* send event to server */ + rtgui_server_post_event(&ekbd.parent, sizeof(struct rtgui_event_kbd)); + } + break; + + case SDL_QUIT: + SDL_Quit(); + quit = 1; + break; + + default: + break; + } + + if (quit) + break; + } + //exit(0); + return 0; +} + +/* start sdl thread */ +void rt_hw_sdl_start(void) +{ + HANDLE thread; + DWORD thread_id; + + /* create thread that loop sdl event */ + thread = CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)sdl_loop, + 0, + CREATE_SUSPENDED, + &thread_id); + if (thread == NULL) + { + //Display Error Message + + return; + } + ResumeThread(thread); +} diff --git a/bsp/simulator/drivers/serial.c b/bsp/simulator/drivers/serial.c index 2eff97a443..5a18d98bde 100644 --- a/bsp/simulator/drivers/serial.c +++ b/bsp/simulator/drivers/serial.c @@ -1,170 +1,170 @@ -/*
-******************************************************************************
-* By : parai
-* email:[email protected]
-* virtual serial driver
-******************************************************************************
-*/
-
-#include <rthw.h>
-#include <rtthread.h>
-
-#define _DEBUG_SERIAL 0
-#include "serial.h"
-#include <stdio.h>
-struct rt_device serial_device;
-extern struct serial_int_rx serial_rx;
-static FILE *fp = RT_NULL;
-
-/*@{*/
-
-/* RT-Thread Device Interface */
-/**
- * This function initializes serial
- */
-static rt_err_t rt_serial_init(rt_device_t dev)
-{
- if (!(dev->flag & RT_DEVICE_FLAG_ACTIVATED))
- {
- if (dev->flag & RT_DEVICE_FLAG_INT_RX)
- {
- rt_memset(serial_rx.rx_buffer, 0,
- sizeof(serial_rx.rx_buffer));
- serial_rx.read_index = 0;
- serial_rx.save_index = 0;
- }
-
- dev->flag |= RT_DEVICE_FLAG_ACTIVATED;
- }
- return RT_EOK;
-}
-
-static rt_err_t rt_serial_open(rt_device_t dev, rt_uint16_t oflag)
-{
-#if _DEBUG_SERIAL==1
- printf("in rt_serial_open()\n");
-#endif
- return RT_EOK;
-}
-
-static rt_err_t rt_serial_close(rt_device_t dev)
-{
-#if _DEBUG_SERIAL==1
- printf("in rt_serial_close()\n");
-#endif
- return RT_EOK;
-}
-static rt_size_t rt_serial_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size)
-{
- rt_uint8_t *ptr;
- rt_err_t err_code;
-
- ptr = buffer;
- err_code = RT_EOK;
-
- if (dev->flag & RT_DEVICE_FLAG_INT_RX)
- {
- /* interrupt mode Rx */
- while (size)
- {
- rt_base_t level;
-
- /* disable interrupt */
- level = rt_hw_interrupt_disable();
-
- if (serial_rx.read_index != serial_rx.save_index)
- {
- /* read a character */
- *ptr++ = serial_rx.rx_buffer[serial_rx.read_index];
- size--;
-
- /* move to next position */
- serial_rx.read_index ++;
- if (serial_rx.read_index >= SERIAL_RX_BUFFER_SIZE)
- serial_rx.read_index = 0;
- }
- else
- {
- /* set error code */
- err_code = -RT_EEMPTY;
-
- /* enable interrupt */
- rt_hw_interrupt_enable(level);
- break;
- }
-
- /* enable interrupt */
- rt_hw_interrupt_enable(level);
- }
- }
-
-
- /* set error code */
- rt_set_errno(err_code);
- return (rt_uint32_t)ptr - (rt_uint32_t)buffer;
-}
-
-static rt_size_t rt_serial_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size)
-{
-#if _DEBUG_SERIAL==1
- printf("in rt_serial_write()\n");
-#endif
- if (fp == NULL)
- fp = fopen("log.txt", "wb+");
-
- if (fp != NULL)
- fwrite(buffer, size, 1, fp);
-
- printf("%s", (char *)buffer);
- return size;
-}
-
-static rt_err_t rt_serial_control(rt_device_t dev, rt_uint8_t cmd, void *args)
-{
- RT_ASSERT(dev != RT_NULL);
-
- switch (cmd)
- {
- case RT_DEVICE_CTRL_SUSPEND:
- /* suspend device */
- dev->flag |= RT_DEVICE_FLAG_SUSPENDED;
- break;
-
- case RT_DEVICE_CTRL_RESUME:
- /* resume device */
- dev->flag &= ~RT_DEVICE_FLAG_SUSPENDED;
- break;
- }
-
- return RT_EOK;
-}
-
-/*
- * serial register
- */
-static rt_err_t rt_hw_serial_register(rt_device_t device, const char *name, rt_uint32_t flag)
-{
- RT_ASSERT(device != RT_NULL);
-#if _DEBUG_SERIAL==1
- printf("in rt_serial_register()\n");
-#endif
- device->type = RT_Device_Class_Char;
- device->rx_indicate = RT_NULL;
- device->tx_complete = RT_NULL;
- device->init = rt_serial_init;
- device->open = rt_serial_open;
- device->close = rt_serial_close;
- device->read = rt_serial_read;
- device->write = rt_serial_write;
- device->control = rt_serial_control;
- device->user_data = RT_NULL;
-
- /* register a character device */
- return rt_device_register(device, name, (rt_uint16_t)(RT_DEVICE_FLAG_RDWR | flag));
-}
-
-rt_err_t rt_hw_serial_init(void)
-{
- return rt_hw_serial_register(&serial_device, RT_CONSOLE_DEVICE_NAME,
- RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM);
-}
+/* +****************************************************************************** +* By : parai +* email:[email protected] +* virtual serial driver +****************************************************************************** +*/ + +#include <rthw.h> +#include <rtthread.h> + +#define _DEBUG_SERIAL 0 +#include "serial.h" +#include <stdio.h> +struct rt_device serial_device; +extern struct serial_int_rx serial_rx; +static FILE *fp = RT_NULL; + +/*@{*/ + +/* RT-Thread Device Interface */ +/** + * This function initializes serial + */ +static rt_err_t rt_serial_init(rt_device_t dev) +{ + if (!(dev->flag & RT_DEVICE_FLAG_ACTIVATED)) + { + if (dev->flag & RT_DEVICE_FLAG_INT_RX) + { + rt_memset(serial_rx.rx_buffer, 0, + sizeof(serial_rx.rx_buffer)); + serial_rx.read_index = 0; + serial_rx.save_index = 0; + } + + dev->flag |= RT_DEVICE_FLAG_ACTIVATED; + } + return RT_EOK; +} + +static rt_err_t rt_serial_open(rt_device_t dev, rt_uint16_t oflag) +{ +#if _DEBUG_SERIAL==1 + printf("in rt_serial_open()\n"); +#endif + return RT_EOK; +} + +static rt_err_t rt_serial_close(rt_device_t dev) +{ +#if _DEBUG_SERIAL==1 + printf("in rt_serial_close()\n"); +#endif + return RT_EOK; +} +static rt_size_t rt_serial_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size) +{ + rt_uint8_t *ptr; + rt_err_t err_code; + + ptr = buffer; + err_code = RT_EOK; + + if (dev->flag & RT_DEVICE_FLAG_INT_RX) + { + /* interrupt mode Rx */ + while (size) + { + rt_base_t level; + + /* disable interrupt */ + level = rt_hw_interrupt_disable(); + + if (serial_rx.read_index != serial_rx.save_index) + { + /* read a character */ + *ptr++ = serial_rx.rx_buffer[serial_rx.read_index]; + size--; + + /* move to next position */ + serial_rx.read_index ++; + if (serial_rx.read_index >= SERIAL_RX_BUFFER_SIZE) + serial_rx.read_index = 0; + } + else + { + /* set error code */ + err_code = -RT_EEMPTY; + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + break; + } + + /* enable interrupt */ + rt_hw_interrupt_enable(level); + } + } + + + /* set error code */ + rt_set_errno(err_code); + return (rt_uint32_t)ptr - (rt_uint32_t)buffer; +} + +static rt_size_t rt_serial_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size) +{ +#if _DEBUG_SERIAL==1 + printf("in rt_serial_write()\n"); +#endif + if (fp == NULL) + fp = fopen("log.txt", "wb+"); + + if (fp != NULL) + fwrite(buffer, size, 1, fp); + + printf("%s", (char *)buffer); + return size; +} + +static rt_err_t rt_serial_control(rt_device_t dev, rt_uint8_t cmd, void *args) +{ + RT_ASSERT(dev != RT_NULL); + + switch (cmd) + { + case RT_DEVICE_CTRL_SUSPEND: + /* suspend device */ + dev->flag |= RT_DEVICE_FLAG_SUSPENDED; + break; + + case RT_DEVICE_CTRL_RESUME: + /* resume device */ + dev->flag &= ~RT_DEVICE_FLAG_SUSPENDED; + break; + } + + return RT_EOK; +} + +/* + * serial register + */ +static rt_err_t rt_hw_serial_register(rt_device_t device, const char *name, rt_uint32_t flag) +{ + RT_ASSERT(device != RT_NULL); +#if _DEBUG_SERIAL==1 + printf("in rt_serial_register()\n"); +#endif + device->type = RT_Device_Class_Char; + device->rx_indicate = RT_NULL; + device->tx_complete = RT_NULL; + device->init = rt_serial_init; + device->open = rt_serial_open; + device->close = rt_serial_close; + device->read = rt_serial_read; + device->write = rt_serial_write; + device->control = rt_serial_control; + device->user_data = RT_NULL; + + /* register a character device */ + return rt_device_register(device, name, (rt_uint16_t)(RT_DEVICE_FLAG_RDWR | flag)); +} + +rt_err_t rt_hw_serial_init(void) +{ + return rt_hw_serial_register(&serial_device, RT_CONSOLE_DEVICE_NAME, + RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_INT_RX | RT_DEVICE_FLAG_STREAM); +} diff --git a/bsp/simulator/drivers/serial.h b/bsp/simulator/drivers/serial.h index bd7fff655c..010631ab32 100644 --- a/bsp/simulator/drivers/serial.h +++ b/bsp/simulator/drivers/serial.h @@ -1,22 +1,22 @@ -/*
-*********************************************************************************************************
-* MC9S12DP256/DG128 Specific code
-* BANKED MEMORY MODEL
-*
-* File : rthw.c
-* By : parai
-* email:[email protected]
-*******************************************************************************************************/
-
-#ifndef __RT_HW_SERIAL_H__
-#define __RT_HW_SERIAL_H__
-
-#define SERIAL_RX_BUFFER_SIZE 80
-struct serial_int_rx
-{
- rt_uint8_t rx_buffer[SERIAL_RX_BUFFER_SIZE];
- rt_uint32_t read_index, save_index;
-};
-
-rt_err_t rt_hw_serial_init(void);
-#endif
+/* +********************************************************************************************************* +* MC9S12DP256/DG128 Specific code +* BANKED MEMORY MODEL +* +* File : rthw.c +* By : parai +* email:[email protected] +*******************************************************************************************************/ + +#ifndef __RT_HW_SERIAL_H__ +#define __RT_HW_SERIAL_H__ + +#define SERIAL_RX_BUFFER_SIZE 80 +struct serial_int_rx +{ + rt_uint8_t rx_buffer[SERIAL_RX_BUFFER_SIZE]; + rt_uint32_t read_index, save_index; +}; + +rt_err_t rt_hw_serial_init(void); +#endif diff --git a/bsp/simulator/drivers/sst25vfxx_mtd.h b/bsp/simulator/drivers/sst25vfxx_mtd.h index 5b8a3c5474..cb0bb84129 100644 --- a/bsp/simulator/drivers/sst25vfxx_mtd.h +++ b/bsp/simulator/drivers/sst25vfxx_mtd.h @@ -1,24 +1,24 @@ -/*
- * File : sst25vfxx_mtd.h
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2006 - 2011, RT-Thread Development Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2011-12-16 aozima the first version
- * 2012-02-01 mbbill MTD driver version
- */
-
-#ifndef SST25VFXX_MTD_H
-#define SST25VFXX_MTD_H
-
-#include <rtthread.h>
-#include <drivers/spi.h>
-
-rt_err_t sst25vfxx_mtd_init(const char *spi_device_name, rt_uint32_t block_start, rt_uint32_t block_end);
-
-#endif
+/* + * File : sst25vfxx_mtd.h + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2011, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2011-12-16 aozima the first version + * 2012-02-01 mbbill MTD driver version + */ + +#ifndef SST25VFXX_MTD_H +#define SST25VFXX_MTD_H + +#include <rtthread.h> +#include <drivers/spi.h> + +rt_err_t sst25vfxx_mtd_init(const char *spi_device_name, rt_uint32_t block_start, rt_uint32_t block_end); + +#endif diff --git a/bsp/simulator/drivers/sst25vfxx_mtd_sim.c b/bsp/simulator/drivers/sst25vfxx_mtd_sim.c index 2c1e5a9dc2..9271c1bb03 100644 --- a/bsp/simulator/drivers/sst25vfxx_mtd_sim.c +++ b/bsp/simulator/drivers/sst25vfxx_mtd_sim.c @@ -1,227 +1,227 @@ -/*
- * File : rtdef.h
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2012-10-21 prife the first version
- */
-
-#include <rtdevice.h>
-#include <stdio.h>
-#include <string.h>
-#include <stdlib.h>
-#include "sst25vfxx_mtd.h"
-
-#ifdef RT_USING_MTD_NOR
-#define NOR_SIM "nor.bin"
-/* JEDEC Manufacturer��s ID */
-#define MF_ID (0xBF)
-/* JEDEC Device ID : Memory Type */
-#define MT_ID (0x25)
-/* JEDEC Device ID: Memory Capacity */
-#define MC_ID_SST25VF016 (0x41)
-#define MC_ID_SST25VF032 (0x4A)
-#define MC_ID_SST25VF064 (0x4B)
-
-#define BLOCK_SIZE (64*1024)
-
-
-#define SST25_MTD(device) ((struct sst25_mtd*)(device))
-struct sst25_mtd
-{
- struct rt_mtd_nor_device parent;
- FILE *file;
-};
-static struct sst25_mtd _sst25_mtd;
-
-static struct rt_mutex flash_lock;
-
-/* RT-Thread MTD device interface */
-static rt_uint32_t sst25vfxx_read_id(struct rt_mtd_nor_device *device)
-{
- rt_uint8_t id_recv[3] = {MF_ID, MT_ID, MC_ID_SST25VF016};
-
- return (id_recv[0] << 16) | (id_recv[1] << 8) | id_recv[2];
-}
-
-static int sst25vfxx_read(struct rt_mtd_nor_device *device, rt_off_t position, rt_uint8_t *data, rt_size_t size)
-{
- struct sst25_mtd *sst25;
- int result;
-
- sst25 = SST25_MTD(device);
- RT_ASSERT(sst25 != RT_NULL);
-
- rt_mutex_take(&flash_lock, RT_WAITING_FOREVER);
-
- fseek(sst25->file, position, SEEK_SET);
- result = fread(data, size, 1, sst25->file);
- if (result < 0)
- rt_kprintf("sst read error.\n");
-
- rt_mutex_release(&flash_lock);
- return size;
-}
-
-static int sst25vfxx_write(struct rt_mtd_nor_device *device, rt_off_t position,
- const rt_uint8_t *data, rt_size_t size)
-{
- struct sst25_mtd *sst25;
- int result;
-
- sst25 = SST25_MTD(device);
- RT_ASSERT(sst25 != RT_NULL);
-
- rt_mutex_take(&flash_lock, RT_WAITING_FOREVER);
-
- fseek(sst25->file, position, SEEK_SET);
- result = fwrite(data, size, 1, sst25->file);
- if (result < 0)
- rt_kprintf("sst write error.\n");
-
- rt_mutex_release(&flash_lock);
- return size;
-}
-
-static char block_buffer[BLOCK_SIZE];
-static rt_err_t sst25vfxx_erase_block(struct rt_mtd_nor_device *device, rt_off_t offset, rt_uint32_t length)
-{
- struct sst25_mtd *sst25;
- int result;
-
- sst25 = SST25_MTD(device);
-
- RT_ASSERT(sst25 != RT_NULL);
-
- rt_mutex_take(&flash_lock, RT_WAITING_FOREVER);
-
- memset(block_buffer, 0xFF, BLOCK_SIZE);
- fseek(sst25->file, offset, SEEK_SET);
-
- result = fwrite(block_buffer, BLOCK_SIZE, 1, sst25->file);
- if (result < 0)
- rt_kprintf("sst write error.\n");
-
- rt_mutex_release(&flash_lock);
- return RT_EOK;
-}
-
-const static struct rt_mtd_nor_driver_ops sst25vfxx_mtd_ops =
-{
- sst25vfxx_read_id,
- sst25vfxx_read,
- sst25vfxx_write,
- sst25vfxx_erase_block,
-};
-static rt_err_t sst25vfxx_hw_init(struct sst25_mtd *mtd)
-{
- mtd = mtd;
- return RT_EOK;
-}
-
-/**
- * SST25vfxx API
- */
-rt_err_t sst25vfxx_mtd_init(const char *nor_name,
- rt_uint32_t block_start,
- rt_uint32_t block_end)
-{
- rt_uint32_t id, total_block;
- struct sst25_mtd *sst25;
- struct rt_mtd_nor_device *mtd;
-
-
- sst25 = &_sst25_mtd;
- mtd = &(sst25->parent);
-
- /* set page size and block size */
- mtd->block_size = 64 * 1024; /* 64kByte */
- mtd->ops = &sst25vfxx_mtd_ops;
-
- /* initialize mutex */
- if (rt_mutex_init(&flash_lock, nor_name, RT_IPC_FLAG_FIFO) != RT_EOK)
- {
- rt_kprintf("init sd lock mutex failed\n");
- }
-
- /* initialize flash */
- id = sst25vfxx_read_id(mtd);
- switch (id & 0xff)
- {
- case MC_ID_SST25VF016:
- total_block = (16 * 1024 * 1024 / 8) / mtd->block_size;
- break;
- case MC_ID_SST25VF032:
- total_block = (32 * 1024 * 1024 / 8) / mtd->block_size;
- break;
- case MC_ID_SST25VF064:
- total_block = (64 * 1024 * 1024 / 8) / mtd->block_size;
- break;
- default:
- rt_kprintf("SST25 detection error, id: %x\n", id);
- return -RT_ERROR;
- }
-
- if ((block_end == RT_UINT32_MAX) || (block_end == 0))
- {
- block_end = total_block;
- }
- else if (block_end > total_block)
- {
- rt_kprintf("SST25 total block: %d, out of block\n", total_block);
- return -RT_ERROR;
- }
-
- mtd->block_start = block_start;
- mtd->block_end = block_end;
-
- /* open nor file, if not exist, then create it */
- sst25->file = fopen(NOR_SIM, "rb+");
- if (sst25->file == NULL)
- {
- rt_uint32_t i;
- /* create a file to simulate nor */
- sst25->file = fopen(NOR_SIM, "wb+");
-
- memset(block_buffer, 0xFF, sizeof(block_buffer));
- for (i = 0; i < total_block; i++)
- {
- fseek(sst25->file, i * BLOCK_SIZE, SEEK_SET);
- fwrite(block_buffer, BLOCK_SIZE, 1, sst25->file);
- }
- }
-
- fseek(sst25->file, 0, SEEK_SET);
-
- /* initialize hardware */
- sst25vfxx_hw_init(&_sst25_mtd);
-
- /* register MTD device */
- rt_mtd_nor_register_device("nor", mtd);
-
- return RT_EOK;
-}
-
-#ifdef RT_USING_FINSH
-#include <finsh.h>
-void nor_erase(void)
-{
- rt_uint32_t index;
- struct rt_mtd_nor_device *mtd;
-
- mtd = RT_MTD_NOR_DEVICE(&_sst25_mtd);
- for (index = mtd->block_start; index < mtd->block_end; index ++)
- {
- sst25vfxx_erase_block(mtd, index * mtd->block_size, BLOCK_SIZE);
- }
-}
-FINSH_FUNCTION_EXPORT(nor_erase, erase all block in SPI flash);
-#endif
-
-#endif
+/* + * File : rtdef.h + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2012, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2012-10-21 prife the first version + */ + +#include <rtdevice.h> +#include <stdio.h> +#include <string.h> +#include <stdlib.h> +#include "sst25vfxx_mtd.h" + +#ifdef RT_USING_MTD_NOR +#define NOR_SIM "nor.bin" +/* JEDEC Manufacturer��s ID */ +#define MF_ID (0xBF) +/* JEDEC Device ID : Memory Type */ +#define MT_ID (0x25) +/* JEDEC Device ID: Memory Capacity */ +#define MC_ID_SST25VF016 (0x41) +#define MC_ID_SST25VF032 (0x4A) +#define MC_ID_SST25VF064 (0x4B) + +#define BLOCK_SIZE (64*1024) + + +#define SST25_MTD(device) ((struct sst25_mtd*)(device)) +struct sst25_mtd +{ + struct rt_mtd_nor_device parent; + FILE *file; +}; +static struct sst25_mtd _sst25_mtd; + +static struct rt_mutex flash_lock; + +/* RT-Thread MTD device interface */ +static rt_uint32_t sst25vfxx_read_id(struct rt_mtd_nor_device *device) +{ + rt_uint8_t id_recv[3] = {MF_ID, MT_ID, MC_ID_SST25VF016}; + + return (id_recv[0] << 16) | (id_recv[1] << 8) | id_recv[2]; +} + +static int sst25vfxx_read(struct rt_mtd_nor_device *device, rt_off_t position, rt_uint8_t *data, rt_size_t size) +{ + struct sst25_mtd *sst25; + int result; + + sst25 = SST25_MTD(device); + RT_ASSERT(sst25 != RT_NULL); + + rt_mutex_take(&flash_lock, RT_WAITING_FOREVER); + + fseek(sst25->file, position, SEEK_SET); + result = fread(data, size, 1, sst25->file); + if (result < 0) + rt_kprintf("sst read error.\n"); + + rt_mutex_release(&flash_lock); + return size; +} + +static int sst25vfxx_write(struct rt_mtd_nor_device *device, rt_off_t position, + const rt_uint8_t *data, rt_size_t size) +{ + struct sst25_mtd *sst25; + int result; + + sst25 = SST25_MTD(device); + RT_ASSERT(sst25 != RT_NULL); + + rt_mutex_take(&flash_lock, RT_WAITING_FOREVER); + + fseek(sst25->file, position, SEEK_SET); + result = fwrite(data, size, 1, sst25->file); + if (result < 0) + rt_kprintf("sst write error.\n"); + + rt_mutex_release(&flash_lock); + return size; +} + +static char block_buffer[BLOCK_SIZE]; +static rt_err_t sst25vfxx_erase_block(struct rt_mtd_nor_device *device, rt_off_t offset, rt_uint32_t length) +{ + struct sst25_mtd *sst25; + int result; + + sst25 = SST25_MTD(device); + + RT_ASSERT(sst25 != RT_NULL); + + rt_mutex_take(&flash_lock, RT_WAITING_FOREVER); + + memset(block_buffer, 0xFF, BLOCK_SIZE); + fseek(sst25->file, offset, SEEK_SET); + + result = fwrite(block_buffer, BLOCK_SIZE, 1, sst25->file); + if (result < 0) + rt_kprintf("sst write error.\n"); + + rt_mutex_release(&flash_lock); + return RT_EOK; +} + +const static struct rt_mtd_nor_driver_ops sst25vfxx_mtd_ops = +{ + sst25vfxx_read_id, + sst25vfxx_read, + sst25vfxx_write, + sst25vfxx_erase_block, +}; +static rt_err_t sst25vfxx_hw_init(struct sst25_mtd *mtd) +{ + mtd = mtd; + return RT_EOK; +} + +/** + * SST25vfxx API + */ +rt_err_t sst25vfxx_mtd_init(const char *nor_name, + rt_uint32_t block_start, + rt_uint32_t block_end) +{ + rt_uint32_t id, total_block; + struct sst25_mtd *sst25; + struct rt_mtd_nor_device *mtd; + + + sst25 = &_sst25_mtd; + mtd = &(sst25->parent); + + /* set page size and block size */ + mtd->block_size = 64 * 1024; /* 64kByte */ + mtd->ops = &sst25vfxx_mtd_ops; + + /* initialize mutex */ + if (rt_mutex_init(&flash_lock, nor_name, RT_IPC_FLAG_FIFO) != RT_EOK) + { + rt_kprintf("init sd lock mutex failed\n"); + } + + /* initialize flash */ + id = sst25vfxx_read_id(mtd); + switch (id & 0xff) + { + case MC_ID_SST25VF016: + total_block = (16 * 1024 * 1024 / 8) / mtd->block_size; + break; + case MC_ID_SST25VF032: + total_block = (32 * 1024 * 1024 / 8) / mtd->block_size; + break; + case MC_ID_SST25VF064: + total_block = (64 * 1024 * 1024 / 8) / mtd->block_size; + break; + default: + rt_kprintf("SST25 detection error, id: %x\n", id); + return -RT_ERROR; + } + + if ((block_end == RT_UINT32_MAX) || (block_end == 0)) + { + block_end = total_block; + } + else if (block_end > total_block) + { + rt_kprintf("SST25 total block: %d, out of block\n", total_block); + return -RT_ERROR; + } + + mtd->block_start = block_start; + mtd->block_end = block_end; + + /* open nor file, if not exist, then create it */ + sst25->file = fopen(NOR_SIM, "rb+"); + if (sst25->file == NULL) + { + rt_uint32_t i; + /* create a file to simulate nor */ + sst25->file = fopen(NOR_SIM, "wb+"); + + memset(block_buffer, 0xFF, sizeof(block_buffer)); + for (i = 0; i < total_block; i++) + { + fseek(sst25->file, i * BLOCK_SIZE, SEEK_SET); + fwrite(block_buffer, BLOCK_SIZE, 1, sst25->file); + } + } + + fseek(sst25->file, 0, SEEK_SET); + + /* initialize hardware */ + sst25vfxx_hw_init(&_sst25_mtd); + + /* register MTD device */ + rt_mtd_nor_register_device("nor", mtd); + + return RT_EOK; +} + +#ifdef RT_USING_FINSH +#include <finsh.h> +void nor_erase(void) +{ + rt_uint32_t index; + struct rt_mtd_nor_device *mtd; + + mtd = RT_MTD_NOR_DEVICE(&_sst25_mtd); + for (index = mtd->block_start; index < mtd->block_end; index ++) + { + sst25vfxx_erase_block(mtd, index * mtd->block_size, BLOCK_SIZE); + } +} +FINSH_FUNCTION_EXPORT(nor_erase, erase all block in SPI flash); +#endif + +#endif diff --git a/bsp/simulator/drivers/usart_sim.c b/bsp/simulator/drivers/usart_sim.c index a5b1da7b62..efc04614cb 100644 --- a/bsp/simulator/drivers/usart_sim.c +++ b/bsp/simulator/drivers/usart_sim.c @@ -1,134 +1,134 @@ -#include <rthw.h>
-#include <rtthread.h>
-#include <windows.h>
-#include <mmsystem.h>
-#include <stdio.h>
-#include <conio.h>
-
-#include "serial.h"
-
-struct serial_int_rx serial_rx;
-extern struct rt_device serial_device;
-
-/*
- * Handler for OSKey Thread
- */
-static HANDLE OSKey_Thread;
-static DWORD OSKey_ThreadID;
-
-static DWORD WINAPI ThreadforKeyGet(LPVOID lpParam);
-void rt_hw_usart_init(void)
-{
-
- /*
- * create serial thread that receive key input from keyboard
- */
-
- OSKey_Thread = CreateThread(NULL,
- 0,
- (LPTHREAD_START_ROUTINE)ThreadforKeyGet,
- 0,
- CREATE_SUSPENDED,
- &OSKey_ThreadID);
- if (OSKey_Thread == NULL)
- {
- //Display Error Message
-
- return;
- }
- SetThreadPriority(OSKey_Thread,
- THREAD_PRIORITY_NORMAL);
- SetThreadPriorityBoost(OSKey_Thread,
- TRUE);
- SetThreadAffinityMask(OSKey_Thread,
- 0x01);
- /*
- * Start OS get key Thread
- */
- ResumeThread(OSKey_Thread);
-
-}
-
-/*
- * �����(��)�� 0xe04b
- * �����(��)�� 0xe048
- * �����(��)�� 0xe04d
- * �����(��)�� 0xe050
- */
-static int savekey(unsigned char key)
-{
- /* save on rx buffer */
- {
- rt_base_t level;
-
- /* disable interrupt */
- //��ʱ�ر��жϣ���ΪҪ����uart���ݽṹ
- level = rt_hw_interrupt_disable();
-
- /* save character */
- serial_rx.rx_buffer[serial_rx.save_index] = key;
- serial_rx.save_index ++;
- //����Ĵ�����save_index�Ƿ��Ѿ�����������β������������ת��ͷ������Ϊһ�����λ�����
- if (serial_rx.save_index >= SERIAL_RX_BUFFER_SIZE)
- serial_rx.save_index = 0;
-
- //���������ʾ��ת���save_index����read_index��������read_index������һ���ɵ�����
- /* if the next position is read index, discard this 'read char' */
- if (serial_rx.save_index == serial_rx.read_index)
- {
- serial_rx.read_index ++;
- if (serial_rx.read_index >= SERIAL_RX_BUFFER_SIZE)
- serial_rx.read_index = 0;
- }
-
- /* enable interrupt */
- //uart���ݽṹ�Ѿ�������ɣ�����ʹ���ж�
- rt_hw_interrupt_enable(level);
- }
-
- /* invoke callback */
- if (serial_device.rx_indicate != RT_NULL)
- {
- rt_size_t rx_length;
-
- /* get rx length */
- rx_length = serial_rx.read_index > serial_rx.save_index ?
- SERIAL_RX_BUFFER_SIZE - serial_rx.read_index + serial_rx.save_index :
- serial_rx.save_index - serial_rx.read_index;
-
- serial_device.rx_indicate(&serial_device, rx_length);
- }
- return 0;
-}
-static DWORD WINAPI ThreadforKeyGet(LPVOID lpParam)
-{
- unsigned char key;
-
- (void)lpParam; //prevent compiler warnings
-
- for (;;)
- {
- key = getch();
- if (key == 0xE0)
- {
- key = getch();
-
- if (key == 0x48) //up key , 0x1b 0x5b 0x41
- {
- savekey(0x1b);
- savekey(0x5b);
- savekey(0x41);
- }
- else if (key == 0x50)//0x1b 0x5b 0x42
- {
- savekey(0x1b);
- savekey(0x5b);
- savekey(0x42);
- }
-
- continue;
- }
-
- savekey(key);
- }
+#include <rthw.h> +#include <rtthread.h> +#include <windows.h> +#include <mmsystem.h> +#include <stdio.h> +#include <conio.h> + +#include "serial.h" + +struct serial_int_rx serial_rx; +extern struct rt_device serial_device; + +/* + * Handler for OSKey Thread + */ +static HANDLE OSKey_Thread; +static DWORD OSKey_ThreadID; + +static DWORD WINAPI ThreadforKeyGet(LPVOID lpParam); +void rt_hw_usart_init(void) +{ + + /* + * create serial thread that receive key input from keyboard + */ + + OSKey_Thread = CreateThread(NULL, + 0, + (LPTHREAD_START_ROUTINE)ThreadforKeyGet, + 0, + CREATE_SUSPENDED, + &OSKey_ThreadID); + if (OSKey_Thread == NULL) + { + //Display Error Message + + return; + } + SetThreadPriority(OSKey_Thread, + THREAD_PRIORITY_NORMAL); + SetThreadPriorityBoost(OSKey_Thread, + TRUE); + SetThreadAffinityMask(OSKey_Thread, + 0x01); + /* + * Start OS get key Thread + */ + ResumeThread(OSKey_Thread); + +} + +/* + * �����(��)�� 0xe04b + * �����(��)�� 0xe048 + * �����(��)�� 0xe04d + * �����(��)�� 0xe050 + */ +static int savekey(unsigned char key) +{ + /* save on rx buffer */ + { + rt_base_t level; + + /* disable interrupt */ + //��ʱ�ر��жϣ���ΪҪ����uart���ݽṹ + level = rt_hw_interrupt_disable(); + + /* save character */ + serial_rx.rx_buffer[serial_rx.save_index] = key; + serial_rx.save_index ++; + //����Ĵ�����save_index�Ƿ��Ѿ�����������β������������ת��ͷ������Ϊһ�����λ����� + if (serial_rx.save_index >= SERIAL_RX_BUFFER_SIZE) + serial_rx.save_index = 0; + + //���������ʾ��ת���save_index����read_index��������read_index������һ���ɵ����� + /* if the next position is read index, discard this 'read char' */ + if (serial_rx.save_index == serial_rx.read_index) + { + serial_rx.read_index ++; + if (serial_rx.read_index >= SERIAL_RX_BUFFER_SIZE) + serial_rx.read_index = 0; + } + + /* enable interrupt */ + //uart���ݽṹ�Ѿ�������ɣ�����ʹ���ж� + rt_hw_interrupt_enable(level); + } + + /* invoke callback */ + if (serial_device.rx_indicate != RT_NULL) + { + rt_size_t rx_length; + + /* get rx length */ + rx_length = serial_rx.read_index > serial_rx.save_index ? + SERIAL_RX_BUFFER_SIZE - serial_rx.read_index + serial_rx.save_index : + serial_rx.save_index - serial_rx.read_index; + + serial_device.rx_indicate(&serial_device, rx_length); + } + return 0; +} +static DWORD WINAPI ThreadforKeyGet(LPVOID lpParam) +{ + unsigned char key; + + (void)lpParam; //prevent compiler warnings + + for (;;) + { + key = getch(); + if (key == 0xE0) + { + key = getch(); + + if (key == 0x48) //up key , 0x1b 0x5b 0x41 + { + savekey(0x1b); + savekey(0x5b); + savekey(0x41); + } + else if (key == 0x50)//0x1b 0x5b 0x42 + { + savekey(0x1b); + savekey(0x5b); + savekey(0x42); + } + + continue; + } + + savekey(key); + } } /*** ThreadforKeyGet ***/
\ No newline at end of file diff --git a/bsp/simulator/pcap/Include/Packet32.h b/bsp/simulator/pcap/Include/Packet32.h index 1e0eacd77d..64be055d96 100644 --- a/bsp/simulator/pcap/Include/Packet32.h +++ b/bsp/simulator/pcap/Include/Packet32.h @@ -1,359 +1,359 @@ -/*
- * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
- * Copyright (c) 2005 - 2007 CACE Technologies, Davis (California)
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the Politecnico di Torino, CACE Technologies
- * nor the names of its contributors may be used to endorse or promote
- * products derived from this software without specific prior written
- * permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-/** @ingroup packetapi
- * @{
- */
-
-/** @defgroup packet32h Packet.dll definitions and data structures
- * Packet32.h contains the data structures and the definitions used by packet.dll.
- * The file is used both by the Win9x and the WinNTx versions of packet.dll, and can be included
- * by the applications that use the functions of this library
- * @{
- */
-
-#ifndef __PACKET32
-#define __PACKET32
-
-#include <winsock2.h>
-
-#ifdef HAVE_AIRPCAP_API
-#include <airpcap.h>
-#else
-#if !defined(AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_)
-#define AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_
-typedef struct _AirpcapHandle *PAirpcapHandle;
-#endif /* AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ */
-#endif /* HAVE_AIRPCAP_API */
-
-#ifdef HAVE_DAG_API
-#include <dagc.h>
-#endif /* HAVE_DAG_API */
-
-// Working modes
-#define PACKET_MODE_CAPT 0x0 ///< Capture mode
-#define PACKET_MODE_STAT 0x1 ///< Statistical mode
-#define PACKET_MODE_MON 0x2 ///< Monitoring mode
-#define PACKET_MODE_DUMP 0x10 ///< Dump mode
-#define PACKET_MODE_STAT_DUMP MODE_DUMP | MODE_STAT ///< Statistical dump Mode
-
-
-/// Alignment macro. Defines the alignment size.
-#define Packet_ALIGNMENT sizeof(int)
-/// Alignment macro. Rounds up to the next even multiple of Packet_ALIGNMENT.
-#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1))
-
-#define NdisMediumNull -1 ///< Custom linktype: NDIS doesn't provide an equivalent
-#define NdisMediumCHDLC -2 ///< Custom linktype: NDIS doesn't provide an equivalent
-#define NdisMediumPPPSerial -3 ///< Custom linktype: NDIS doesn't provide an equivalent
-#define NdisMediumBare80211 -4 ///< Custom linktype: NDIS doesn't provide an equivalent
-#define NdisMediumRadio80211 -5 ///< Custom linktype: NDIS doesn't provide an equivalent
-#define NdisMediumPpi -6 ///< Custom linktype: NDIS doesn't provide an equivalent
-
-// Loopback behaviour definitions
-#define NPF_DISABLE_LOOPBACK 1 ///< Drop the packets sent by the NPF driver
-#define NPF_ENABLE_LOOPBACK 2 ///< Capture the packets sent by the NPF driver
-
-/*!
- \brief Network type structure.
-
- This structure is used by the PacketGetNetType() function to return information on the current adapter's type and speed.
-*/
-typedef struct NetType
-{
- UINT LinkType; ///< The MAC of the current network adapter (see function PacketGetNetType() for more information)
- ULONGLONG LinkSpeed; ///< The speed of the network in bits per second
-}NetType;
-
-
-//some definitions stolen from libpcap
-
-#ifndef BPF_MAJOR_VERSION
-
-/*!
- \brief A BPF pseudo-assembly program.
-
- The program will be injected in the kernel by the PacketSetBPF() function and applied to every incoming packet.
-*/
-struct bpf_program
-{
- UINT bf_len; ///< Indicates the number of instructions of the program, i.e. the number of struct bpf_insn that will follow.
- struct bpf_insn *bf_insns; ///< A pointer to the first instruction of the program.
-};
-
-/*!
- \brief A single BPF pseudo-instruction.
-
- bpf_insn contains a single instruction for the BPF register-machine. It is used to send a filter program to the driver.
-*/
-struct bpf_insn
-{
- USHORT code; ///< Instruction type and addressing mode.
- UCHAR jt; ///< Jump if true
- UCHAR jf; ///< Jump if false
- int k; ///< Generic field used for various purposes.
-};
-
-/*!
- \brief Structure that contains a couple of statistics values on the current capture.
-
- It is used by packet.dll to return statistics about a capture session.
-*/
-struct bpf_stat
-{
- UINT bs_recv; ///< Number of packets that the driver received from the network adapter
- ///< from the beginning of the current capture. This value includes the packets
- ///< lost by the driver.
- UINT bs_drop; ///< number of packets that the driver lost from the beginning of a capture.
- ///< Basically, a packet is lost when the the buffer of the driver is full.
- ///< In this situation the packet cannot be stored and the driver rejects it.
- UINT ps_ifdrop; ///< drops by interface. XXX not yet supported
- UINT bs_capt; ///< number of packets that pass the filter, find place in the kernel buffer and
- ///< thus reach the application.
-};
-
-/*!
- \brief Packet header.
-
- This structure defines the header associated with every packet delivered to the application.
-*/
-struct bpf_hdr
-{
- struct timeval bh_tstamp; ///< The timestamp associated with the captured packet.
- ///< It is stored in a TimeVal structure.
- UINT bh_caplen; ///< Length of captured portion. The captured portion <b>can be different</b>
- ///< from the original packet, because it is possible (with a proper filter)
- ///< to instruct the driver to capture only a portion of the packets.
- UINT bh_datalen; ///< Original length of packet
- USHORT bh_hdrlen; ///< Length of bpf header (this struct plus alignment padding). In some cases,
- ///< a padding could be added between the end of this structure and the packet
- ///< data for performance reasons. This filed can be used to retrieve the actual data
- ///< of the packet.
-};
-
-/*!
- \brief Dump packet header.
-
- This structure defines the header associated with the packets in a buffer to be used with PacketSendPackets().
- It is simpler than the bpf_hdr, because it corresponds to the header associated by WinPcap and libpcap to a
- packet in a dump file. This makes straightforward sending WinPcap dump files to the network.
-*/
-struct dump_bpf_hdr{
- struct timeval ts; ///< Time stamp of the packet
- UINT caplen; ///< Length of captured portion. The captured portion can smaller than the
- ///< the original packet, because it is possible (with a proper filter) to
- ///< instruct the driver to capture only a portion of the packets.
- UINT len; ///< Length of the original packet (off wire).
-};
-
-
-#endif
-
-struct bpf_stat;
-
-#define DOSNAMEPREFIX TEXT("Packet_") ///< Prefix added to the adapters device names to create the WinPcap devices
-#define MAX_LINK_NAME_LENGTH 64 //< Maximum length of the devices symbolic links
-#define NMAX_PACKET 65535
-
-/*!
- \brief Addresses of a network adapter.
-
- This structure is used by the PacketGetNetInfoEx() function to return the IP addresses associated with
- an adapter.
-*/
-typedef struct npf_if_addr {
- struct sockaddr_storage IPAddress; ///< IP address.
- struct sockaddr_storage SubnetMask; ///< Netmask for that address.
- struct sockaddr_storage Broadcast; ///< Broadcast address.
-}npf_if_addr;
-
-
-#define ADAPTER_NAME_LENGTH 256 + 12 ///< Maximum length for the name of an adapter. The value is the same used by the IP Helper API.
-#define ADAPTER_DESC_LENGTH 128 ///< Maximum length for the description of an adapter. The value is the same used by the IP Helper API.
-#define MAX_MAC_ADDR_LENGTH 8 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API.
-#define MAX_NETWORK_ADDRESSES 16 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API.
-
-
-typedef struct WAN_ADAPTER_INT WAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API
-typedef WAN_ADAPTER *PWAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API
-
-#define INFO_FLAG_NDIS_ADAPTER 0 ///< Flag for ADAPTER_INFO: this is a traditional ndis adapter
-#define INFO_FLAG_NDISWAN_ADAPTER 1 ///< Flag for ADAPTER_INFO: this is a NdisWan adapter, and it's managed by WANPACKET
-#define INFO_FLAG_DAG_CARD 2 ///< Flag for ADAPTER_INFO: this is a DAG card
-#define INFO_FLAG_DAG_FILE 6 ///< Flag for ADAPTER_INFO: this is a DAG file
-#define INFO_FLAG_DONT_EXPORT 8 ///< Flag for ADAPTER_INFO: when this flag is set, the adapter will not be listed or openend by winpcap. This allows to prevent exporting broken network adapters, like for example FireWire ones.
-#define INFO_FLAG_AIRPCAP_CARD 16 ///< Flag for ADAPTER_INFO: this is an airpcap card
-#define INFO_FLAG_NPFIM_DEVICE 32
-
-/*!
- \brief Describes an opened network adapter.
-
- This structure is the most important for the functioning of packet.dll, but the great part of its fields
- should be ignored by the user, since the library offers functions that avoid to cope with low-level parameters
-*/
-typedef struct _ADAPTER {
- HANDLE hFile; ///< \internal Handle to an open instance of the NPF driver.
- CHAR SymbolicLink[MAX_LINK_NAME_LENGTH]; ///< \internal A string containing the name of the network adapter currently opened.
- int NumWrites; ///< \internal Number of times a packets written on this adapter will be repeated
- ///< on the wire.
- HANDLE ReadEvent; ///< A notification event associated with the read calls on the adapter.
- ///< It can be passed to standard Win32 functions (like WaitForSingleObject
- ///< or WaitForMultipleObjects) to wait until the driver's buffer contains some
- ///< data. It is particularly useful in GUI applications that need to wait
- ///< concurrently on several events. In Windows NT/2000 the PacketSetMinToCopy()
- ///< function can be used to define the minimum amount of data in the kernel buffer
- ///< that will cause the event to be signalled.
-
- UINT ReadTimeOut; ///< \internal The amount of time after which a read on the driver will be released and
- ///< ReadEvent will be signaled, also if no packets were captured
- CHAR Name[ADAPTER_NAME_LENGTH];
- PWAN_ADAPTER pWanAdapter;
- UINT Flags; ///< Adapter's flags. Tell if this adapter must be treated in a different way, using the Netmon API or the dagc API.
-
-#ifdef HAVE_AIRPCAP_API
- PAirpcapHandle AirpcapAd;
-#endif // HAVE_AIRPCAP_API
-
-#ifdef HAVE_NPFIM_API
- void* NpfImHandle;
-#endif // HAVE_NPFIM_API
-
-#ifdef HAVE_DAG_API
- dagc_t *pDagCard; ///< Pointer to the dagc API adapter descriptor for this adapter
- PCHAR DagBuffer; ///< Pointer to the buffer with the packets that is received from the DAG card
- struct timeval DagReadTimeout; ///< Read timeout. The dagc API requires a timeval structure
- unsigned DagFcsLen; ///< Length of the frame check sequence attached to any packet by the card. Obtained from the registry
- DWORD DagFastProcess; ///< True if the user requests fast capture processing on this card. Higher level applications can use this value to provide a faster but possibly unprecise capture (for example, libpcap doesn't convert the timestamps).
-#endif // HAVE_DAG_API
-} ADAPTER, *LPADAPTER;
-
-/*!
- \brief Structure that contains a group of packets coming from the driver.
-
- This structure defines the header associated with every packet delivered to the application.
-*/
-typedef struct _PACKET {
- HANDLE hEvent; ///< \deprecated Still present for compatibility with old applications.
- OVERLAPPED OverLapped; ///< \deprecated Still present for compatibility with old applications.
- PVOID Buffer; ///< Buffer with containing the packets. See the PacketReceivePacket() for
- ///< details about the organization of the data in this buffer
- UINT Length; ///< Length of the buffer
- DWORD ulBytesReceived; ///< Number of valid bytes present in the buffer, i.e. amount of data
- ///< received by the last call to PacketReceivePacket()
- BOOLEAN bIoComplete; ///< \deprecated Still present for compatibility with old applications.
-} PACKET, *LPPACKET;
-
-/*!
- \brief Structure containing an OID request.
-
- It is used by the PacketRequest() function to send an OID to the interface card driver.
- It can be used, for example, to retrieve the status of the error counters on the adapter, its MAC address,
- the list of the multicast groups defined on it, and so on.
-*/
-struct _PACKET_OID_DATA {
- ULONG Oid; ///< OID code. See the Microsoft DDK documentation or the file ntddndis.h
- ///< for a complete list of valid codes.
- ULONG Length; ///< Length of the data field
- UCHAR Data[1]; ///< variable-lenght field that contains the information passed to or received
- ///< from the adapter.
-};
-typedef struct _PACKET_OID_DATA PACKET_OID_DATA, *PPACKET_OID_DATA;
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * @}
- */
-
-/*
-BOOLEAN QueryWinPcapRegistryStringA(CHAR *SubKeyName,
- CHAR *Value,
- UINT *pValueLen,
- CHAR *DefaultVal);
-
-BOOLEAN QueryWinPcapRegistryStringW(WCHAR *SubKeyName,
- WCHAR *Value,
- UINT *pValueLen,
- WCHAR *DefaultVal);
-*/
-
-//---------------------------------------------------------------------------
-// EXPORTED FUNCTIONS
-//---------------------------------------------------------------------------
-
-PCHAR PacketGetVersion();
-PCHAR PacketGetDriverVersion();
-BOOLEAN PacketSetMinToCopy(LPADAPTER AdapterObject,int nbytes);
-BOOLEAN PacketSetNumWrites(LPADAPTER AdapterObject,int nwrites);
-BOOLEAN PacketSetMode(LPADAPTER AdapterObject,int mode);
-BOOLEAN PacketSetReadTimeout(LPADAPTER AdapterObject,int timeout);
-BOOLEAN PacketSetBpf(LPADAPTER AdapterObject,struct bpf_program *fp);
-BOOLEAN PacketSetLoopbackBehavior(LPADAPTER AdapterObject, UINT LoopbackBehavior);
-INT PacketSetSnapLen(LPADAPTER AdapterObject,int snaplen);
-BOOLEAN PacketGetStats(LPADAPTER AdapterObject,struct bpf_stat *s);
-BOOLEAN PacketGetStatsEx(LPADAPTER AdapterObject,struct bpf_stat *s);
-BOOLEAN PacketSetBuff(LPADAPTER AdapterObject,int dim);
-BOOLEAN PacketGetNetType (LPADAPTER AdapterObject,NetType *type);
-LPADAPTER PacketOpenAdapter(PCHAR AdapterName);
-BOOLEAN PacketSendPacket(LPADAPTER AdapterObject,LPPACKET pPacket,BOOLEAN Sync);
-INT PacketSendPackets(LPADAPTER AdapterObject,PVOID PacketBuff,ULONG Size, BOOLEAN Sync);
-LPPACKET PacketAllocatePacket(void);
-VOID PacketInitPacket(LPPACKET lpPacket,PVOID Buffer,UINT Length);
-VOID PacketFreePacket(LPPACKET lpPacket);
-BOOLEAN PacketReceivePacket(LPADAPTER AdapterObject,LPPACKET lpPacket,BOOLEAN Sync);
-BOOLEAN PacketSetHwFilter(LPADAPTER AdapterObject,ULONG Filter);
-BOOLEAN PacketGetAdapterNames(PTSTR pStr,PULONG BufferSize);
-BOOLEAN PacketGetNetInfoEx(PCHAR AdapterName, npf_if_addr* buffer, PLONG NEntries);
-BOOLEAN PacketRequest(LPADAPTER AdapterObject,BOOLEAN Set,PPACKET_OID_DATA OidData);
-HANDLE PacketGetReadEvent(LPADAPTER AdapterObject);
-BOOLEAN PacketSetDumpName(LPADAPTER AdapterObject, void *name, int len);
-BOOLEAN PacketSetDumpLimits(LPADAPTER AdapterObject, UINT maxfilesize, UINT maxnpacks);
-BOOLEAN PacketIsDumpEnded(LPADAPTER AdapterObject, BOOLEAN sync);
-BOOL PacketStopDriver();
-VOID PacketCloseAdapter(LPADAPTER lpAdapter);
-BOOLEAN PacketStartOem(PCHAR errorString, UINT errorStringLength);
-BOOLEAN PacketStartOemEx(PCHAR errorString, UINT errorStringLength, ULONG flags);
-PAirpcapHandle PacketGetAirPcapHandle(LPADAPTER AdapterObject);
-
-//
-// Used by PacketStartOemEx
-//
-#define PACKET_START_OEM_NO_NETMON 0x00000001
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //__PACKET32
+/* + * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy) + * Copyright (c) 2005 - 2007 CACE Technologies, Davis (California) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Politecnico di Torino, CACE Technologies + * nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +/** @ingroup packetapi + * @{ + */ + +/** @defgroup packet32h Packet.dll definitions and data structures + * Packet32.h contains the data structures and the definitions used by packet.dll. + * The file is used both by the Win9x and the WinNTx versions of packet.dll, and can be included + * by the applications that use the functions of this library + * @{ + */ + +#ifndef __PACKET32 +#define __PACKET32 + +#include <winsock2.h> + +#ifdef HAVE_AIRPCAP_API +#include <airpcap.h> +#else +#if !defined(AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_) +#define AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ +typedef struct _AirpcapHandle *PAirpcapHandle; +#endif /* AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ */ +#endif /* HAVE_AIRPCAP_API */ + +#ifdef HAVE_DAG_API +#include <dagc.h> +#endif /* HAVE_DAG_API */ + +// Working modes +#define PACKET_MODE_CAPT 0x0 ///< Capture mode +#define PACKET_MODE_STAT 0x1 ///< Statistical mode +#define PACKET_MODE_MON 0x2 ///< Monitoring mode +#define PACKET_MODE_DUMP 0x10 ///< Dump mode +#define PACKET_MODE_STAT_DUMP MODE_DUMP | MODE_STAT ///< Statistical dump Mode + + +/// Alignment macro. Defines the alignment size. +#define Packet_ALIGNMENT sizeof(int) +/// Alignment macro. Rounds up to the next even multiple of Packet_ALIGNMENT. +#define Packet_WORDALIGN(x) (((x)+(Packet_ALIGNMENT-1))&~(Packet_ALIGNMENT-1)) + +#define NdisMediumNull -1 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumCHDLC -2 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumPPPSerial -3 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumBare80211 -4 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumRadio80211 -5 ///< Custom linktype: NDIS doesn't provide an equivalent +#define NdisMediumPpi -6 ///< Custom linktype: NDIS doesn't provide an equivalent + +// Loopback behaviour definitions +#define NPF_DISABLE_LOOPBACK 1 ///< Drop the packets sent by the NPF driver +#define NPF_ENABLE_LOOPBACK 2 ///< Capture the packets sent by the NPF driver + +/*! + \brief Network type structure. + + This structure is used by the PacketGetNetType() function to return information on the current adapter's type and speed. +*/ +typedef struct NetType +{ + UINT LinkType; ///< The MAC of the current network adapter (see function PacketGetNetType() for more information) + ULONGLONG LinkSpeed; ///< The speed of the network in bits per second +}NetType; + + +//some definitions stolen from libpcap + +#ifndef BPF_MAJOR_VERSION + +/*! + \brief A BPF pseudo-assembly program. + + The program will be injected in the kernel by the PacketSetBPF() function and applied to every incoming packet. +*/ +struct bpf_program +{ + UINT bf_len; ///< Indicates the number of instructions of the program, i.e. the number of struct bpf_insn that will follow. + struct bpf_insn *bf_insns; ///< A pointer to the first instruction of the program. +}; + +/*! + \brief A single BPF pseudo-instruction. + + bpf_insn contains a single instruction for the BPF register-machine. It is used to send a filter program to the driver. +*/ +struct bpf_insn +{ + USHORT code; ///< Instruction type and addressing mode. + UCHAR jt; ///< Jump if true + UCHAR jf; ///< Jump if false + int k; ///< Generic field used for various purposes. +}; + +/*! + \brief Structure that contains a couple of statistics values on the current capture. + + It is used by packet.dll to return statistics about a capture session. +*/ +struct bpf_stat +{ + UINT bs_recv; ///< Number of packets that the driver received from the network adapter + ///< from the beginning of the current capture. This value includes the packets + ///< lost by the driver. + UINT bs_drop; ///< number of packets that the driver lost from the beginning of a capture. + ///< Basically, a packet is lost when the the buffer of the driver is full. + ///< In this situation the packet cannot be stored and the driver rejects it. + UINT ps_ifdrop; ///< drops by interface. XXX not yet supported + UINT bs_capt; ///< number of packets that pass the filter, find place in the kernel buffer and + ///< thus reach the application. +}; + +/*! + \brief Packet header. + + This structure defines the header associated with every packet delivered to the application. +*/ +struct bpf_hdr +{ + struct timeval bh_tstamp; ///< The timestamp associated with the captured packet. + ///< It is stored in a TimeVal structure. + UINT bh_caplen; ///< Length of captured portion. The captured portion <b>can be different</b> + ///< from the original packet, because it is possible (with a proper filter) + ///< to instruct the driver to capture only a portion of the packets. + UINT bh_datalen; ///< Original length of packet + USHORT bh_hdrlen; ///< Length of bpf header (this struct plus alignment padding). In some cases, + ///< a padding could be added between the end of this structure and the packet + ///< data for performance reasons. This filed can be used to retrieve the actual data + ///< of the packet. +}; + +/*! + \brief Dump packet header. + + This structure defines the header associated with the packets in a buffer to be used with PacketSendPackets(). + It is simpler than the bpf_hdr, because it corresponds to the header associated by WinPcap and libpcap to a + packet in a dump file. This makes straightforward sending WinPcap dump files to the network. +*/ +struct dump_bpf_hdr{ + struct timeval ts; ///< Time stamp of the packet + UINT caplen; ///< Length of captured portion. The captured portion can smaller than the + ///< the original packet, because it is possible (with a proper filter) to + ///< instruct the driver to capture only a portion of the packets. + UINT len; ///< Length of the original packet (off wire). +}; + + +#endif + +struct bpf_stat; + +#define DOSNAMEPREFIX TEXT("Packet_") ///< Prefix added to the adapters device names to create the WinPcap devices +#define MAX_LINK_NAME_LENGTH 64 //< Maximum length of the devices symbolic links +#define NMAX_PACKET 65535 + +/*! + \brief Addresses of a network adapter. + + This structure is used by the PacketGetNetInfoEx() function to return the IP addresses associated with + an adapter. +*/ +typedef struct npf_if_addr { + struct sockaddr_storage IPAddress; ///< IP address. + struct sockaddr_storage SubnetMask; ///< Netmask for that address. + struct sockaddr_storage Broadcast; ///< Broadcast address. +}npf_if_addr; + + +#define ADAPTER_NAME_LENGTH 256 + 12 ///< Maximum length for the name of an adapter. The value is the same used by the IP Helper API. +#define ADAPTER_DESC_LENGTH 128 ///< Maximum length for the description of an adapter. The value is the same used by the IP Helper API. +#define MAX_MAC_ADDR_LENGTH 8 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API. +#define MAX_NETWORK_ADDRESSES 16 ///< Maximum length for the link layer address of an adapter. The value is the same used by the IP Helper API. + + +typedef struct WAN_ADAPTER_INT WAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API +typedef WAN_ADAPTER *PWAN_ADAPTER; ///< Describes an opened wan (dialup, VPN...) network adapter using the NetMon API + +#define INFO_FLAG_NDIS_ADAPTER 0 ///< Flag for ADAPTER_INFO: this is a traditional ndis adapter +#define INFO_FLAG_NDISWAN_ADAPTER 1 ///< Flag for ADAPTER_INFO: this is a NdisWan adapter, and it's managed by WANPACKET +#define INFO_FLAG_DAG_CARD 2 ///< Flag for ADAPTER_INFO: this is a DAG card +#define INFO_FLAG_DAG_FILE 6 ///< Flag for ADAPTER_INFO: this is a DAG file +#define INFO_FLAG_DONT_EXPORT 8 ///< Flag for ADAPTER_INFO: when this flag is set, the adapter will not be listed or openend by winpcap. This allows to prevent exporting broken network adapters, like for example FireWire ones. +#define INFO_FLAG_AIRPCAP_CARD 16 ///< Flag for ADAPTER_INFO: this is an airpcap card +#define INFO_FLAG_NPFIM_DEVICE 32 + +/*! + \brief Describes an opened network adapter. + + This structure is the most important for the functioning of packet.dll, but the great part of its fields + should be ignored by the user, since the library offers functions that avoid to cope with low-level parameters +*/ +typedef struct _ADAPTER { + HANDLE hFile; ///< \internal Handle to an open instance of the NPF driver. + CHAR SymbolicLink[MAX_LINK_NAME_LENGTH]; ///< \internal A string containing the name of the network adapter currently opened. + int NumWrites; ///< \internal Number of times a packets written on this adapter will be repeated + ///< on the wire. + HANDLE ReadEvent; ///< A notification event associated with the read calls on the adapter. + ///< It can be passed to standard Win32 functions (like WaitForSingleObject + ///< or WaitForMultipleObjects) to wait until the driver's buffer contains some + ///< data. It is particularly useful in GUI applications that need to wait + ///< concurrently on several events. In Windows NT/2000 the PacketSetMinToCopy() + ///< function can be used to define the minimum amount of data in the kernel buffer + ///< that will cause the event to be signalled. + + UINT ReadTimeOut; ///< \internal The amount of time after which a read on the driver will be released and + ///< ReadEvent will be signaled, also if no packets were captured + CHAR Name[ADAPTER_NAME_LENGTH]; + PWAN_ADAPTER pWanAdapter; + UINT Flags; ///< Adapter's flags. Tell if this adapter must be treated in a different way, using the Netmon API or the dagc API. + +#ifdef HAVE_AIRPCAP_API + PAirpcapHandle AirpcapAd; +#endif // HAVE_AIRPCAP_API + +#ifdef HAVE_NPFIM_API + void* NpfImHandle; +#endif // HAVE_NPFIM_API + +#ifdef HAVE_DAG_API + dagc_t *pDagCard; ///< Pointer to the dagc API adapter descriptor for this adapter + PCHAR DagBuffer; ///< Pointer to the buffer with the packets that is received from the DAG card + struct timeval DagReadTimeout; ///< Read timeout. The dagc API requires a timeval structure + unsigned DagFcsLen; ///< Length of the frame check sequence attached to any packet by the card. Obtained from the registry + DWORD DagFastProcess; ///< True if the user requests fast capture processing on this card. Higher level applications can use this value to provide a faster but possibly unprecise capture (for example, libpcap doesn't convert the timestamps). +#endif // HAVE_DAG_API +} ADAPTER, *LPADAPTER; + +/*! + \brief Structure that contains a group of packets coming from the driver. + + This structure defines the header associated with every packet delivered to the application. +*/ +typedef struct _PACKET { + HANDLE hEvent; ///< \deprecated Still present for compatibility with old applications. + OVERLAPPED OverLapped; ///< \deprecated Still present for compatibility with old applications. + PVOID Buffer; ///< Buffer with containing the packets. See the PacketReceivePacket() for + ///< details about the organization of the data in this buffer + UINT Length; ///< Length of the buffer + DWORD ulBytesReceived; ///< Number of valid bytes present in the buffer, i.e. amount of data + ///< received by the last call to PacketReceivePacket() + BOOLEAN bIoComplete; ///< \deprecated Still present for compatibility with old applications. +} PACKET, *LPPACKET; + +/*! + \brief Structure containing an OID request. + + It is used by the PacketRequest() function to send an OID to the interface card driver. + It can be used, for example, to retrieve the status of the error counters on the adapter, its MAC address, + the list of the multicast groups defined on it, and so on. +*/ +struct _PACKET_OID_DATA { + ULONG Oid; ///< OID code. See the Microsoft DDK documentation or the file ntddndis.h + ///< for a complete list of valid codes. + ULONG Length; ///< Length of the data field + UCHAR Data[1]; ///< variable-lenght field that contains the information passed to or received + ///< from the adapter. +}; +typedef struct _PACKET_OID_DATA PACKET_OID_DATA, *PPACKET_OID_DATA; + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @} + */ + +/* +BOOLEAN QueryWinPcapRegistryStringA(CHAR *SubKeyName, + CHAR *Value, + UINT *pValueLen, + CHAR *DefaultVal); + +BOOLEAN QueryWinPcapRegistryStringW(WCHAR *SubKeyName, + WCHAR *Value, + UINT *pValueLen, + WCHAR *DefaultVal); +*/ + +//--------------------------------------------------------------------------- +// EXPORTED FUNCTIONS +//--------------------------------------------------------------------------- + +PCHAR PacketGetVersion(); +PCHAR PacketGetDriverVersion(); +BOOLEAN PacketSetMinToCopy(LPADAPTER AdapterObject,int nbytes); +BOOLEAN PacketSetNumWrites(LPADAPTER AdapterObject,int nwrites); +BOOLEAN PacketSetMode(LPADAPTER AdapterObject,int mode); +BOOLEAN PacketSetReadTimeout(LPADAPTER AdapterObject,int timeout); +BOOLEAN PacketSetBpf(LPADAPTER AdapterObject,struct bpf_program *fp); +BOOLEAN PacketSetLoopbackBehavior(LPADAPTER AdapterObject, UINT LoopbackBehavior); +INT PacketSetSnapLen(LPADAPTER AdapterObject,int snaplen); +BOOLEAN PacketGetStats(LPADAPTER AdapterObject,struct bpf_stat *s); +BOOLEAN PacketGetStatsEx(LPADAPTER AdapterObject,struct bpf_stat *s); +BOOLEAN PacketSetBuff(LPADAPTER AdapterObject,int dim); +BOOLEAN PacketGetNetType (LPADAPTER AdapterObject,NetType *type); +LPADAPTER PacketOpenAdapter(PCHAR AdapterName); +BOOLEAN PacketSendPacket(LPADAPTER AdapterObject,LPPACKET pPacket,BOOLEAN Sync); +INT PacketSendPackets(LPADAPTER AdapterObject,PVOID PacketBuff,ULONG Size, BOOLEAN Sync); +LPPACKET PacketAllocatePacket(void); +VOID PacketInitPacket(LPPACKET lpPacket,PVOID Buffer,UINT Length); +VOID PacketFreePacket(LPPACKET lpPacket); +BOOLEAN PacketReceivePacket(LPADAPTER AdapterObject,LPPACKET lpPacket,BOOLEAN Sync); +BOOLEAN PacketSetHwFilter(LPADAPTER AdapterObject,ULONG Filter); +BOOLEAN PacketGetAdapterNames(PTSTR pStr,PULONG BufferSize); +BOOLEAN PacketGetNetInfoEx(PCHAR AdapterName, npf_if_addr* buffer, PLONG NEntries); +BOOLEAN PacketRequest(LPADAPTER AdapterObject,BOOLEAN Set,PPACKET_OID_DATA OidData); +HANDLE PacketGetReadEvent(LPADAPTER AdapterObject); +BOOLEAN PacketSetDumpName(LPADAPTER AdapterObject, void *name, int len); +BOOLEAN PacketSetDumpLimits(LPADAPTER AdapterObject, UINT maxfilesize, UINT maxnpacks); +BOOLEAN PacketIsDumpEnded(LPADAPTER AdapterObject, BOOLEAN sync); +BOOL PacketStopDriver(); +VOID PacketCloseAdapter(LPADAPTER lpAdapter); +BOOLEAN PacketStartOem(PCHAR errorString, UINT errorStringLength); +BOOLEAN PacketStartOemEx(PCHAR errorString, UINT errorStringLength, ULONG flags); +PAirpcapHandle PacketGetAirPcapHandle(LPADAPTER AdapterObject); + +// +// Used by PacketStartOemEx +// +#define PACKET_START_OEM_NO_NETMON 0x00000001 + +#ifdef __cplusplus +} +#endif + +#endif //__PACKET32 diff --git a/bsp/simulator/pcap/Include/Win32-Extensions.h b/bsp/simulator/pcap/Include/Win32-Extensions.h index d3b063b0fd..ad3be25cfa 100644 --- a/bsp/simulator/pcap/Include/Win32-Extensions.h +++ b/bsp/simulator/pcap/Include/Win32-Extensions.h @@ -1,113 +1,113 @@ -/*
- * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy)
- * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California)
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the Politecnico di Torino, CACE Technologies
- * nor the names of its contributors may be used to endorse or promote
- * products derived from this software without specific prior written
- * permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-#ifndef __WIN32_EXTENSIONS_H__
-#define __WIN32_EXTENSIONS_H__
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/* Definitions */
-
-/*!
- \brief A queue of raw packets that will be sent to the network with pcap_sendqueue_transmit().
-*/
-struct pcap_send_queue
-{
- u_int maxlen; ///< Maximum size of the the queue, in bytes. This variable contains the size of the buffer field.
- u_int len; ///< Current size of the queue, in bytes.
- char *buffer; ///< Buffer containing the packets to be sent.
-};
-
-typedef struct pcap_send_queue pcap_send_queue;
-
-/*!
- \brief This typedef is a support for the pcap_get_airpcap_handle() function
-*/
-#if !defined(AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_)
-#define AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_
-typedef struct _AirpcapHandle *PAirpcapHandle;
-#endif
-
-#define BPF_MEM_EX_IMM 0xc0
-#define BPF_MEM_EX_IND 0xe0
-
-/*used for ST*/
-#define BPF_MEM_EX 0xc0
-#define BPF_TME 0x08
-
-#define BPF_LOOKUP 0x90
-#define BPF_EXECUTE 0xa0
-#define BPF_INIT 0xb0
-#define BPF_VALIDATE 0xc0
-#define BPF_SET_ACTIVE 0xd0
-#define BPF_RESET 0xe0
-#define BPF_SET_MEMORY 0x80
-#define BPF_GET_REGISTER_VALUE 0x70
-#define BPF_SET_REGISTER_VALUE 0x60
-#define BPF_SET_WORKING 0x50
-#define BPF_SET_ACTIVE_READ 0x40
-#define BPF_SET_AUTODELETION 0x30
-#define BPF_SEPARATION 0xff
-
-/* Prototypes */
-pcap_send_queue* pcap_sendqueue_alloc(u_int memsize);
-
-void pcap_sendqueue_destroy(pcap_send_queue* queue);
-
-int pcap_sendqueue_queue(pcap_send_queue* queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data);
-
-u_int pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue* queue, int sync);
-
-HANDLE pcap_getevent(pcap_t *p);
-
-struct pcap_stat *pcap_stats_ex(pcap_t *p, int *pcap_stat_size);
-
-int pcap_setuserbuffer(pcap_t *p, int size);
-
-int pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks);
-
-int pcap_live_dump_ended(pcap_t *p, int sync);
-
-int pcap_offline_filter(struct bpf_program *prog, const struct pcap_pkthdr *header, const u_char *pkt_data);
-
-int pcap_start_oem(char* err_str, int flags);
-
-PAirpcapHandle pcap_get_airpcap_handle(pcap_t *p);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif //__WIN32_EXTENSIONS_H__
+/* + * Copyright (c) 1999 - 2005 NetGroup, Politecnico di Torino (Italy) + * Copyright (c) 2005 - 2006 CACE Technologies, Davis (California) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Politecnico di Torino, CACE Technologies + * nor the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#ifndef __WIN32_EXTENSIONS_H__ +#define __WIN32_EXTENSIONS_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Definitions */ + +/*! + \brief A queue of raw packets that will be sent to the network with pcap_sendqueue_transmit(). +*/ +struct pcap_send_queue +{ + u_int maxlen; ///< Maximum size of the the queue, in bytes. This variable contains the size of the buffer field. + u_int len; ///< Current size of the queue, in bytes. + char *buffer; ///< Buffer containing the packets to be sent. +}; + +typedef struct pcap_send_queue pcap_send_queue; + +/*! + \brief This typedef is a support for the pcap_get_airpcap_handle() function +*/ +#if !defined(AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_) +#define AIRPCAP_HANDLE__EAE405F5_0171_9592_B3C2_C19EC426AD34__DEFINED_ +typedef struct _AirpcapHandle *PAirpcapHandle; +#endif + +#define BPF_MEM_EX_IMM 0xc0 +#define BPF_MEM_EX_IND 0xe0 + +/*used for ST*/ +#define BPF_MEM_EX 0xc0 +#define BPF_TME 0x08 + +#define BPF_LOOKUP 0x90 +#define BPF_EXECUTE 0xa0 +#define BPF_INIT 0xb0 +#define BPF_VALIDATE 0xc0 +#define BPF_SET_ACTIVE 0xd0 +#define BPF_RESET 0xe0 +#define BPF_SET_MEMORY 0x80 +#define BPF_GET_REGISTER_VALUE 0x70 +#define BPF_SET_REGISTER_VALUE 0x60 +#define BPF_SET_WORKING 0x50 +#define BPF_SET_ACTIVE_READ 0x40 +#define BPF_SET_AUTODELETION 0x30 +#define BPF_SEPARATION 0xff + +/* Prototypes */ +pcap_send_queue* pcap_sendqueue_alloc(u_int memsize); + +void pcap_sendqueue_destroy(pcap_send_queue* queue); + +int pcap_sendqueue_queue(pcap_send_queue* queue, const struct pcap_pkthdr *pkt_header, const u_char *pkt_data); + +u_int pcap_sendqueue_transmit(pcap_t *p, pcap_send_queue* queue, int sync); + +HANDLE pcap_getevent(pcap_t *p); + +struct pcap_stat *pcap_stats_ex(pcap_t *p, int *pcap_stat_size); + +int pcap_setuserbuffer(pcap_t *p, int size); + +int pcap_live_dump(pcap_t *p, char *filename, int maxsize, int maxpacks); + +int pcap_live_dump_ended(pcap_t *p, int sync); + +int pcap_offline_filter(struct bpf_program *prog, const struct pcap_pkthdr *header, const u_char *pkt_data); + +int pcap_start_oem(char* err_str, int flags); + +PAirpcapHandle pcap_get_airpcap_handle(pcap_t *p); + +#ifdef __cplusplus +} +#endif + +#endif //__WIN32_EXTENSIONS_H__ diff --git a/bsp/simulator/pcap/Include/remote-ext.h b/bsp/simulator/pcap/Include/remote-ext.h index 9f54d6974c..35a2fff6c2 100644 --- a/bsp/simulator/pcap/Include/remote-ext.h +++ b/bsp/simulator/pcap/Include/remote-ext.h @@ -1,444 +1,444 @@ -/*
- * Copyright (c) 2002 - 2003
- * NetGroup, Politecnico di Torino (Italy)
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. Neither the name of the Politecnico di Torino nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- */
-
-
-#ifndef __REMOTE_EXT_H__
-#define __REMOTE_EXT_H__
-
-
-#ifndef HAVE_REMOTE
-#error Please do not include this file directly. Just define HAVE_REMOTE and then include pcap.h
-#endif
-
-// Definition for Microsoft Visual Studio
-#if _MSC_VER > 1000
-#pragma once
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/*!
- \file remote-ext.h
-
- The goal of this file it to include most of the new definitions that should be
- placed into the pcap.h file.
-
- It includes all new definitions (structures and functions like pcap_open().
- Some of the functions are not really a remote feature, but, right now,
- they are placed here.
-*/
-
-
-
-// All this stuff is public
-/*! \addtogroup remote_struct
- \{
-*/
-
-
-
-
-/*!
- \brief Defines the maximum buffer size in which address, port, interface names are kept.
-
- In case the adapter name or such is larger than this value, it is truncated.
- This is not used by the user; however it must be aware that an hostname / interface
- name longer than this value will be truncated.
-*/
-#define PCAP_BUF_SIZE 1024
-
-
-/*! \addtogroup remote_source_ID
- \{
-*/
-
-
-/*!
- \brief Internal representation of the type of source in use (file,
- remote/local interface).
-
- This indicates a file, i.e. the user want to open a capture from a local file.
-*/
-#define PCAP_SRC_FILE 2
-/*!
- \brief Internal representation of the type of source in use (file,
- remote/local interface).
-
- This indicates a local interface, i.e. the user want to open a capture from
- a local interface. This does not involve the RPCAP protocol.
-*/
-#define PCAP_SRC_IFLOCAL 3
-/*!
- \brief Internal representation of the type of source in use (file,
- remote/local interface).
-
- This indicates a remote interface, i.e. the user want to open a capture from
- an interface on a remote host. This does involve the RPCAP protocol.
-*/
-#define PCAP_SRC_IFREMOTE 4
-
-/*!
- \}
-*/
-
-
-
-/*! \addtogroup remote_source_string
-
- The formats allowed by the pcap_open() are the following:
- - file://path_and_filename [opens a local file]
- - rpcap://devicename [opens the selected device devices available on the local host, without using the RPCAP protocol]
- - rpcap://host/devicename [opens the selected device available on a remote host]
- - rpcap://host:port/devicename [opens the selected device available on a remote host, using a non-standard port for RPCAP]
- - adaptername [to open a local adapter; kept for compability, but it is strongly discouraged]
- - (NULL) [to open the first local adapter; kept for compability, but it is strongly discouraged]
-
- The formats allowed by the pcap_findalldevs_ex() are the following:
- - file://folder/ [lists all the files in the given folder]
- - rpcap:// [lists all local adapters]
- - rpcap://host:port/ [lists the devices available on a remote host]
-
- Referring to the 'host' and 'port' paramters, they can be either numeric or literal. Since
- IPv6 is fully supported, these are the allowed formats:
-
- - host (literal): e.g. host.foo.bar
- - host (numeric IPv4): e.g. 10.11.12.13
- - host (numeric IPv4, IPv6 style): e.g. [10.11.12.13]
- - host (numeric IPv6): e.g. [1:2:3::4]
- - port: can be either numeric (e.g. '80') or literal (e.g. 'http')
-
- Here you find some allowed examples:
- - rpcap://host.foo.bar/devicename [everything literal, no port number]
- - rpcap://host.foo.bar:1234/devicename [everything literal, with port number]
- - rpcap://10.11.12.13/devicename [IPv4 numeric, no port number]
- - rpcap://10.11.12.13:1234/devicename [IPv4 numeric, with port number]
- - rpcap://[10.11.12.13]:1234/devicename [IPv4 numeric with IPv6 format, with port number]
- - rpcap://[1:2:3::4]/devicename [IPv6 numeric, no port number]
- - rpcap://[1:2:3::4]:1234/devicename [IPv6 numeric, with port number]
- - rpcap://[1:2:3::4]:http/devicename [IPv6 numeric, with literal port number]
-
- \{
-*/
-
-
-/*!
- \brief String that will be used to determine the type of source in use (file,
- remote/local interface).
-
- This string will be prepended to the interface name in order to create a string
- that contains all the information required to open the source.
-
- This string indicates that the user wants to open a capture from a local file.
-*/
-#define PCAP_SRC_FILE_STRING "file://"
-/*!
- \brief String that will be used to determine the type of source in use (file,
- remote/local interface).
-
- This string will be prepended to the interface name in order to create a string
- that contains all the information required to open the source.
-
- This string indicates that the user wants to open a capture from a network interface.
- This string does not necessarily involve the use of the RPCAP protocol. If the
- interface required resides on the local host, the RPCAP protocol is not involved
- and the local functions are used.
-*/
-#define PCAP_SRC_IF_STRING "rpcap://"
-
-/*!
- \}
-*/
-
-
-
-
-
-/*!
- \addtogroup remote_open_flags
- \{
-*/
-
-/*!
- \brief Defines if the adapter has to go in promiscuous mode.
-
- It is '1' if you have to open the adapter in promiscuous mode, '0' otherwise.
- Note that even if this parameter is false, the interface could well be in promiscuous
- mode for some other reason (for example because another capture process with
- promiscuous mode enabled is currently using that interface).
- On on Linux systems with 2.2 or later kernels (that have the "any" device), this
- flag does not work on the "any" device; if an argument of "any" is supplied,
- the 'promisc' flag is ignored.
-*/
-#define PCAP_OPENFLAG_PROMISCUOUS 1
-
-/*!
- \brief Defines if the data trasfer (in case of a remote
- capture) has to be done with UDP protocol.
-
- If it is '1' if you want a UDP data connection, '0' if you want
- a TCP data connection; control connection is always TCP-based.
- A UDP connection is much lighter, but it does not guarantee that all
- the captured packets arrive to the client workstation. Moreover,
- it could be harmful in case of network congestion.
- This flag is meaningless if the source is not a remote interface.
- In that case, it is simply ignored.
-*/
-#define PCAP_OPENFLAG_DATATX_UDP 2
-
-
-/*!
- \brief Defines if the remote probe will capture its own generated traffic.
-
- In case the remote probe uses the same interface to capture traffic and to send
- data back to the caller, the captured traffic includes the RPCAP traffic as well.
- If this flag is turned on, the RPCAP traffic is excluded from the capture, so that
- the trace returned back to the collector is does not include this traffic.
-*/
-#define PCAP_OPENFLAG_NOCAPTURE_RPCAP 4
-
-/*!
- \brief Defines if the local adapter will capture its own generated traffic.
-
- This flag tells the underlying capture driver to drop the packets that were sent by itself.
- This is usefult when building applications like bridges, that should ignore the traffic
- they just sent.
-*/
-#define PCAP_OPENFLAG_NOCAPTURE_LOCAL 8
-
-/*!
- \brief This flag configures the adapter for maximum responsiveness.
-
- In presence of a large value for nbytes, WinPcap waits for the arrival of several packets before
- copying the data to the user. This guarantees a low number of system calls, i.e. lower processor usage,
- i.e. better performance, which is good for applications like sniffers. If the user sets the
- PCAP_OPENFLAG_MAX_RESPONSIVENESS flag, the capture driver will copy the packets as soon as the application
- is ready to receive them. This is suggested for real time applications (like, for example, a bridge)
- that need the best responsiveness.*/
-#define PCAP_OPENFLAG_MAX_RESPONSIVENESS 16
-
-/*!
- \}
-*/
-
-
-/*!
- \addtogroup remote_samp_methods
- \{
-*/
-
-/*!
- \brief No sampling has to be done on the current capture.
-
- In this case, no sampling algorithms are applied to the current capture.
-*/
-#define PCAP_SAMP_NOSAMP 0
-
-/*!
- \brief It defines that only 1 out of N packets must be returned to the user.
-
- In this case, the 'value' field of the 'pcap_samp' structure indicates the
- number of packets (minus 1) that must be discarded before one packet got accepted.
- In other words, if 'value = 10', the first packet is returned to the caller, while
- the following 9 are discarded.
-*/
-#define PCAP_SAMP_1_EVERY_N 1
-
-/*!
- \brief It defines that we have to return 1 packet every N milliseconds.
-
- In this case, the 'value' field of the 'pcap_samp' structure indicates the 'waiting
- time' in milliseconds before one packet got accepted.
- In other words, if 'value = 10', the first packet is returned to the caller; the next
- returned one will be the first packet that arrives when 10ms have elapsed.
-*/
-#define PCAP_SAMP_FIRST_AFTER_N_MS 2
-
-/*!
- \}
-*/
-
-
-/*!
- \addtogroup remote_auth_methods
- \{
-*/
-
-/*!
- \brief It defines the NULL authentication.
-
- This value has to be used within the 'type' member of the pcap_rmtauth structure.
- The 'NULL' authentication has to be equal to 'zero', so that old applications
- can just put every field of struct pcap_rmtauth to zero, and it does work.
-*/
-#define RPCAP_RMTAUTH_NULL 0
-/*!
- \brief It defines the username/password authentication.
-
- With this type of authentication, the RPCAP protocol will use the username/
- password provided to authenticate the user on the remote machine. If the
- authentication is successful (and the user has the right to open network devices)
- the RPCAP connection will continue; otherwise it will be dropped.
-
- This value has to be used within the 'type' member of the pcap_rmtauth structure.
-*/
-#define RPCAP_RMTAUTH_PWD 1
-
-/*!
- \}
-*/
-
-
-
-
-/*!
-
- \brief This structure keeps the information needed to autheticate
- the user on a remote machine.
-
- The remote machine can either grant or refuse the access according
- to the information provided.
- In case the NULL authentication is required, both 'username' and
- 'password' can be NULL pointers.
-
- This structure is meaningless if the source is not a remote interface;
- in that case, the functions which requires such a structure can accept
- a NULL pointer as well.
-*/
-struct pcap_rmtauth
-{
- /*!
- \brief Type of the authentication required.
-
- In order to provide maximum flexibility, we can support different types
- of authentication based on the value of this 'type' variable. The currently
- supported authentication methods are defined into the
- \link remote_auth_methods Remote Authentication Methods Section\endlink.
-
- */
- int type;
- /*!
- \brief Zero-terminated string containing the username that has to be
- used on the remote machine for authentication.
-
- This field is meaningless in case of the RPCAP_RMTAUTH_NULL authentication
- and it can be NULL.
- */
- char *username;
- /*!
- \brief Zero-terminated string containing the password that has to be
- used on the remote machine for authentication.
-
- This field is meaningless in case of the RPCAP_RMTAUTH_NULL authentication
- and it can be NULL.
- */
- char *password;
-};
-
-
-/*!
- \brief This structure defines the information related to sampling.
-
- In case the sampling is requested, the capturing device should read
- only a subset of the packets coming from the source. The returned packets depend
- on the sampling parameters.
-
- \warning The sampling process is applied <strong>after</strong> the filtering process.
- In other words, packets are filtered first, then the sampling process selects a
- subset of the 'filtered' packets and it returns them to the caller.
-*/
-struct pcap_samp
-{
- /*!
- Method used for sampling. Currently, the supported methods are listed in the
- \link remote_samp_methods Sampling Methods Section\endlink.
- */
- int method;
-
- /*!
- This value depends on the sampling method defined. For its meaning, please check
- at the \link remote_samp_methods Sampling Methods Section\endlink.
- */
- int value;
-};
-
-
-
-
-//! Maximum lenght of an host name (needed for the RPCAP active mode)
-#define RPCAP_HOSTLIST_SIZE 1024
-
-
-/*!
- \}
-*/ // end of public documentation
-
-
-// Exported functions
-
-
-
-/** \name New WinPcap functions
-
- This section lists the new functions that are able to help considerably in writing
- WinPcap programs because of their easiness of use.
- */
-//\{
-pcap_t *pcap_open(const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf);
-int pcap_createsrcstr(char *source, int type, const char *host, const char *port, const char *name, char *errbuf);
-int pcap_parsesrcstr(const char *source, int *type, char *host, char *port, char *name, char *errbuf);
-int pcap_findalldevs_ex(char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf);
-struct pcap_samp *pcap_setsampling(pcap_t *p);
-
-//\}
-// End of new winpcap functions
-
-
-
-/** \name Remote Capture functions
- */
-//\{
-SOCKET pcap_remoteact_accept(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf);
-int pcap_remoteact_list(char *hostlist, char sep, int size, char *errbuf);
-int pcap_remoteact_close(const char *host, char *errbuf);
-void pcap_remoteact_cleanup();
-//\}
-// End of remote capture functions
-
-#ifdef __cplusplus
-}
-#endif
-
-
-#endif
-
+/* + * Copyright (c) 2002 - 2003 + * NetGroup, Politecnico di Torino (Italy) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the Politecnico di Torino nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + + +#ifndef __REMOTE_EXT_H__ +#define __REMOTE_EXT_H__ + + +#ifndef HAVE_REMOTE +#error Please do not include this file directly. Just define HAVE_REMOTE and then include pcap.h +#endif + +// Definition for Microsoft Visual Studio +#if _MSC_VER > 1000 +#pragma once +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/*! + \file remote-ext.h + + The goal of this file it to include most of the new definitions that should be + placed into the pcap.h file. + + It includes all new definitions (structures and functions like pcap_open(). + Some of the functions are not really a remote feature, but, right now, + they are placed here. +*/ + + + +// All this stuff is public +/*! \addtogroup remote_struct + \{ +*/ + + + + +/*! + \brief Defines the maximum buffer size in which address, port, interface names are kept. + + In case the adapter name or such is larger than this value, it is truncated. + This is not used by the user; however it must be aware that an hostname / interface + name longer than this value will be truncated. +*/ +#define PCAP_BUF_SIZE 1024 + + +/*! \addtogroup remote_source_ID + \{ +*/ + + +/*! + \brief Internal representation of the type of source in use (file, + remote/local interface). + + This indicates a file, i.e. the user want to open a capture from a local file. +*/ +#define PCAP_SRC_FILE 2 +/*! + \brief Internal representation of the type of source in use (file, + remote/local interface). + + This indicates a local interface, i.e. the user want to open a capture from + a local interface. This does not involve the RPCAP protocol. +*/ +#define PCAP_SRC_IFLOCAL 3 +/*! + \brief Internal representation of the type of source in use (file, + remote/local interface). + + This indicates a remote interface, i.e. the user want to open a capture from + an interface on a remote host. This does involve the RPCAP protocol. +*/ +#define PCAP_SRC_IFREMOTE 4 + +/*! + \} +*/ + + + +/*! \addtogroup remote_source_string + + The formats allowed by the pcap_open() are the following: + - file://path_and_filename [opens a local file] + - rpcap://devicename [opens the selected device devices available on the local host, without using the RPCAP protocol] + - rpcap://host/devicename [opens the selected device available on a remote host] + - rpcap://host:port/devicename [opens the selected device available on a remote host, using a non-standard port for RPCAP] + - adaptername [to open a local adapter; kept for compability, but it is strongly discouraged] + - (NULL) [to open the first local adapter; kept for compability, but it is strongly discouraged] + + The formats allowed by the pcap_findalldevs_ex() are the following: + - file://folder/ [lists all the files in the given folder] + - rpcap:// [lists all local adapters] + - rpcap://host:port/ [lists the devices available on a remote host] + + Referring to the 'host' and 'port' paramters, they can be either numeric or literal. Since + IPv6 is fully supported, these are the allowed formats: + + - host (literal): e.g. host.foo.bar + - host (numeric IPv4): e.g. 10.11.12.13 + - host (numeric IPv4, IPv6 style): e.g. [10.11.12.13] + - host (numeric IPv6): e.g. [1:2:3::4] + - port: can be either numeric (e.g. '80') or literal (e.g. 'http') + + Here you find some allowed examples: + - rpcap://host.foo.bar/devicename [everything literal, no port number] + - rpcap://host.foo.bar:1234/devicename [everything literal, with port number] + - rpcap://10.11.12.13/devicename [IPv4 numeric, no port number] + - rpcap://10.11.12.13:1234/devicename [IPv4 numeric, with port number] + - rpcap://[10.11.12.13]:1234/devicename [IPv4 numeric with IPv6 format, with port number] + - rpcap://[1:2:3::4]/devicename [IPv6 numeric, no port number] + - rpcap://[1:2:3::4]:1234/devicename [IPv6 numeric, with port number] + - rpcap://[1:2:3::4]:http/devicename [IPv6 numeric, with literal port number] + + \{ +*/ + + +/*! + \brief String that will be used to determine the type of source in use (file, + remote/local interface). + + This string will be prepended to the interface name in order to create a string + that contains all the information required to open the source. + + This string indicates that the user wants to open a capture from a local file. +*/ +#define PCAP_SRC_FILE_STRING "file://" +/*! + \brief String that will be used to determine the type of source in use (file, + remote/local interface). + + This string will be prepended to the interface name in order to create a string + that contains all the information required to open the source. + + This string indicates that the user wants to open a capture from a network interface. + This string does not necessarily involve the use of the RPCAP protocol. If the + interface required resides on the local host, the RPCAP protocol is not involved + and the local functions are used. +*/ +#define PCAP_SRC_IF_STRING "rpcap://" + +/*! + \} +*/ + + + + + +/*! + \addtogroup remote_open_flags + \{ +*/ + +/*! + \brief Defines if the adapter has to go in promiscuous mode. + + It is '1' if you have to open the adapter in promiscuous mode, '0' otherwise. + Note that even if this parameter is false, the interface could well be in promiscuous + mode for some other reason (for example because another capture process with + promiscuous mode enabled is currently using that interface). + On on Linux systems with 2.2 or later kernels (that have the "any" device), this + flag does not work on the "any" device; if an argument of "any" is supplied, + the 'promisc' flag is ignored. +*/ +#define PCAP_OPENFLAG_PROMISCUOUS 1 + +/*! + \brief Defines if the data trasfer (in case of a remote + capture) has to be done with UDP protocol. + + If it is '1' if you want a UDP data connection, '0' if you want + a TCP data connection; control connection is always TCP-based. + A UDP connection is much lighter, but it does not guarantee that all + the captured packets arrive to the client workstation. Moreover, + it could be harmful in case of network congestion. + This flag is meaningless if the source is not a remote interface. + In that case, it is simply ignored. +*/ +#define PCAP_OPENFLAG_DATATX_UDP 2 + + +/*! + \brief Defines if the remote probe will capture its own generated traffic. + + In case the remote probe uses the same interface to capture traffic and to send + data back to the caller, the captured traffic includes the RPCAP traffic as well. + If this flag is turned on, the RPCAP traffic is excluded from the capture, so that + the trace returned back to the collector is does not include this traffic. +*/ +#define PCAP_OPENFLAG_NOCAPTURE_RPCAP 4 + +/*! + \brief Defines if the local adapter will capture its own generated traffic. + + This flag tells the underlying capture driver to drop the packets that were sent by itself. + This is usefult when building applications like bridges, that should ignore the traffic + they just sent. +*/ +#define PCAP_OPENFLAG_NOCAPTURE_LOCAL 8 + +/*! + \brief This flag configures the adapter for maximum responsiveness. + + In presence of a large value for nbytes, WinPcap waits for the arrival of several packets before + copying the data to the user. This guarantees a low number of system calls, i.e. lower processor usage, + i.e. better performance, which is good for applications like sniffers. If the user sets the + PCAP_OPENFLAG_MAX_RESPONSIVENESS flag, the capture driver will copy the packets as soon as the application + is ready to receive them. This is suggested for real time applications (like, for example, a bridge) + that need the best responsiveness.*/ +#define PCAP_OPENFLAG_MAX_RESPONSIVENESS 16 + +/*! + \} +*/ + + +/*! + \addtogroup remote_samp_methods + \{ +*/ + +/*! + \brief No sampling has to be done on the current capture. + + In this case, no sampling algorithms are applied to the current capture. +*/ +#define PCAP_SAMP_NOSAMP 0 + +/*! + \brief It defines that only 1 out of N packets must be returned to the user. + + In this case, the 'value' field of the 'pcap_samp' structure indicates the + number of packets (minus 1) that must be discarded before one packet got accepted. + In other words, if 'value = 10', the first packet is returned to the caller, while + the following 9 are discarded. +*/ +#define PCAP_SAMP_1_EVERY_N 1 + +/*! + \brief It defines that we have to return 1 packet every N milliseconds. + + In this case, the 'value' field of the 'pcap_samp' structure indicates the 'waiting + time' in milliseconds before one packet got accepted. + In other words, if 'value = 10', the first packet is returned to the caller; the next + returned one will be the first packet that arrives when 10ms have elapsed. +*/ +#define PCAP_SAMP_FIRST_AFTER_N_MS 2 + +/*! + \} +*/ + + +/*! + \addtogroup remote_auth_methods + \{ +*/ + +/*! + \brief It defines the NULL authentication. + + This value has to be used within the 'type' member of the pcap_rmtauth structure. + The 'NULL' authentication has to be equal to 'zero', so that old applications + can just put every field of struct pcap_rmtauth to zero, and it does work. +*/ +#define RPCAP_RMTAUTH_NULL 0 +/*! + \brief It defines the username/password authentication. + + With this type of authentication, the RPCAP protocol will use the username/ + password provided to authenticate the user on the remote machine. If the + authentication is successful (and the user has the right to open network devices) + the RPCAP connection will continue; otherwise it will be dropped. + + This value has to be used within the 'type' member of the pcap_rmtauth structure. +*/ +#define RPCAP_RMTAUTH_PWD 1 + +/*! + \} +*/ + + + + +/*! + + \brief This structure keeps the information needed to autheticate + the user on a remote machine. + + The remote machine can either grant or refuse the access according + to the information provided. + In case the NULL authentication is required, both 'username' and + 'password' can be NULL pointers. + + This structure is meaningless if the source is not a remote interface; + in that case, the functions which requires such a structure can accept + a NULL pointer as well. +*/ +struct pcap_rmtauth +{ + /*! + \brief Type of the authentication required. + + In order to provide maximum flexibility, we can support different types + of authentication based on the value of this 'type' variable. The currently + supported authentication methods are defined into the + \link remote_auth_methods Remote Authentication Methods Section\endlink. + + */ + int type; + /*! + \brief Zero-terminated string containing the username that has to be + used on the remote machine for authentication. + + This field is meaningless in case of the RPCAP_RMTAUTH_NULL authentication + and it can be NULL. + */ + char *username; + /*! + \brief Zero-terminated string containing the password that has to be + used on the remote machine for authentication. + + This field is meaningless in case of the RPCAP_RMTAUTH_NULL authentication + and it can be NULL. + */ + char *password; +}; + + +/*! + \brief This structure defines the information related to sampling. + + In case the sampling is requested, the capturing device should read + only a subset of the packets coming from the source. The returned packets depend + on the sampling parameters. + + \warning The sampling process is applied <strong>after</strong> the filtering process. + In other words, packets are filtered first, then the sampling process selects a + subset of the 'filtered' packets and it returns them to the caller. +*/ +struct pcap_samp +{ + /*! + Method used for sampling. Currently, the supported methods are listed in the + \link remote_samp_methods Sampling Methods Section\endlink. + */ + int method; + + /*! + This value depends on the sampling method defined. For its meaning, please check + at the \link remote_samp_methods Sampling Methods Section\endlink. + */ + int value; +}; + + + + +//! Maximum lenght of an host name (needed for the RPCAP active mode) +#define RPCAP_HOSTLIST_SIZE 1024 + + +/*! + \} +*/ // end of public documentation + + +// Exported functions + + + +/** \name New WinPcap functions + + This section lists the new functions that are able to help considerably in writing + WinPcap programs because of their easiness of use. + */ +//\{ +pcap_t *pcap_open(const char *source, int snaplen, int flags, int read_timeout, struct pcap_rmtauth *auth, char *errbuf); +int pcap_createsrcstr(char *source, int type, const char *host, const char *port, const char *name, char *errbuf); +int pcap_parsesrcstr(const char *source, int *type, char *host, char *port, char *name, char *errbuf); +int pcap_findalldevs_ex(char *source, struct pcap_rmtauth *auth, pcap_if_t **alldevs, char *errbuf); +struct pcap_samp *pcap_setsampling(pcap_t *p); + +//\} +// End of new winpcap functions + + + +/** \name Remote Capture functions + */ +//\{ +SOCKET pcap_remoteact_accept(const char *address, const char *port, const char *hostlist, char *connectinghost, struct pcap_rmtauth *auth, char *errbuf); +int pcap_remoteact_list(char *hostlist, char sep, int size, char *errbuf); +int pcap_remoteact_close(const char *host, char *errbuf); +void pcap_remoteact_cleanup(); +//\} +// End of remote capture functions + +#ifdef __cplusplus +} +#endif + + +#endif + diff --git a/bsp/simulator/pcap/SConscript b/bsp/simulator/pcap/SConscript index 2e5ad4fdcc..e554e7a075 100644 --- a/bsp/simulator/pcap/SConscript +++ b/bsp/simulator/pcap/SConscript @@ -1,13 +1,13 @@ -from building import *
-
-cwd = GetCurrentDir()
-src = Glob('*.c')
-
-CPPPATH = [cwd + '/Include']
-LIBPATH = [cwd + '/Lib']
-CPPDEFINES = ['WIN32']
-LIBS = ['wpcap']
-
-group = DefineGroup('Pcap', src, depend = ['RT_USING_LWIP'], CPPPATH = CPPPATH, LIBPATH=LIBPATH, CPPDEFINES=CPPDEFINES, LIBS=LIBS)
-
-Return('group')
+from building import * + +cwd = GetCurrentDir() +src = Glob('*.c') + +CPPPATH = [cwd + '/Include'] +LIBPATH = [cwd + '/Lib'] +CPPDEFINES = ['WIN32'] +LIBS = ['wpcap'] + +group = DefineGroup('Pcap', src, depend = ['RT_USING_LWIP'], CPPPATH = CPPPATH, LIBPATH=LIBPATH, CPPDEFINES=CPPDEFINES, LIBS=LIBS) + +Return('group') diff --git a/bsp/simulator/pcap/pcap_netif.c b/bsp/simulator/pcap/pcap_netif.c index 7c9aeac86e..58bc89f7b4 100644 --- a/bsp/simulator/pcap/pcap_netif.c +++ b/bsp/simulator/pcap/pcap_netif.c @@ -1,305 +1,305 @@ -/*
- * File : pcap_netif.c
- * This file is part of RT-Thread RTOS
- * COPYRIGHT (C) 2012, RT-Thread Development Team
- *
- * The license and distribution terms for this file may be
- * found in the file LICENSE in this distribution or at
- * http://www.rt-thread.org/license/LICENSE
- *
- * Change Logs:
- * Date Author Notes
- * 2012-11-05 Bernard the first version
- * 2012-11-13 Bernard merge prife's patch for exclusive
- * access pcap driver.
- */
-
-#ifdef _TIME_T_DEFINED
-#undef _TIME_T_DEFINED
-#endif
-
-#ifdef _MSC_VER
-/*
- * we do not want the warnings about the old deprecated and unsecure CRT functions
- * since these examples can be compiled under *nix as well
- */
-#define _CRT_SECURE_NO_WARNINGS
-#endif
-#include <pcap.h>
-
-#include <rtthread.h>
-#include <netif/ethernetif.h>
-
-#define MAX_ADDR_LEN 6
-
-#define NETIF_DEVICE(netif) ((struct pcap_netif*)(netif))
-#define NETIF_PCAP(netif) (NETIF_DEVICE(netif)->tap)
-
-struct pcap_netif
-{
- /* inherit from ethernet device */
- struct eth_device parent;
-
- pcap_t *tap;
- /* interface address info. */
- rt_uint8_t dev_addr[MAX_ADDR_LEN]; /* hw address */
-};
-static struct pcap_netif pcap_netif_device;
-static struct rt_semaphore sem_lock;
-static rt_mailbox_t packet_mb = RT_NULL;
-
-static void pcap_thread_entry(void* parameter)
-{
- pcap_if_t *netif;
- pcap_t *tap;
- char errbuf[PCAP_ERRBUF_SIZE];
- struct pcap_pkthdr *header;
- const u_char *pkt_data;
- int res;
-
- netif = (pcap_if_t *) parameter;
-
- /* Open the adapter */
- if ((tap = pcap_open_live(netif->name,
- 65536, // portion of the packet to capture.
- 1, // promiscuous mode (nonzero means promiscuous)
- 1, // read timeout, 0 blocked, -1 no timeout
- errbuf )) == NULL)
- {
- rt_kprintf("Unable to open the adapter. %s is not supported by WinPcap\n", netif->name);
- return;
- }
-
- NETIF_PCAP(&pcap_netif_device) = tap;
-
- /* Read the packets */
- while (1)
- {
- struct eth_device* eth;
- struct pbuf *p;
-
- rt_enter_critical();
- res = pcap_next_ex(tap, &header, &pkt_data);
- rt_exit_critical();
-
- if (res == 0) continue;
-
- eth = (struct eth_device*) &pcap_netif_device;
-
- p = pbuf_alloc(PBUF_LINK, header->len, PBUF_RAM);
- pbuf_take(p, pkt_data, header->len);
-
- /* send to packet mailbox */
- rt_mb_send_wait(packet_mb, (rt_uint32_t)p, RT_WAITING_FOREVER);
- /* notify eth rx thread to receive packet */
- eth_device_ready(eth);
- }
-}
-
-static rt_err_t pcap_netif_init(rt_device_t dev)
-{
- rt_thread_t tid;
- pcap_if_t *alldevs;
- pcap_if_t *d;
- pcap_t *tap;
- int inum, i=0;
- char errbuf[PCAP_ERRBUF_SIZE];
-
- /* Retrieve the device list */
- if(pcap_findalldevs(&alldevs, errbuf) == -1)
- {
- rt_kprintf("Error in pcap_findalldevs: %s\n", errbuf);
- return -RT_ERROR;
- }
-
- /* Print the list */
- for(d = alldevs; d; d = d->next)
- {
- rt_kprintf("%d. %s", ++i, d->name);
- if (d->description)
- rt_kprintf(" (%s)\n", d->description);
- else
- rt_kprintf(" (No description available)\n");
- }
- if(i == 0)
- {
- rt_kprintf("\nNo interfaces found! Make sure WinPcap is installed.\n");
- return -RT_ERROR;
- }
-
- inum = 1;
- /* Jump to the selected adapter */
- for(d = alldevs, i = 0; i < inum-1 ;d = d->next, i++);
-
- {
- rt_kprintf("Select (%s) as network interface\n", d->description);
- packet_mb = rt_mb_create("pcap", 64, RT_IPC_FLAG_FIFO);
- tid = rt_thread_create("pcap", pcap_thread_entry, d,
- 2048, RT_THREAD_PRIORITY_MAX - 1, 10);
- if (tid != RT_NULL)
- {
- rt_thread_startup(tid);
- }
-
- rt_thread_delay(100);
- }
-
- pcap_freealldevs(alldevs);
-
- return RT_EOK;
-}
-
-static rt_err_t pcap_netif_open(rt_device_t dev, rt_uint16_t oflag)
-{
- return RT_EOK;
-}
-
-static rt_err_t pcap_netif_close(rt_device_t dev)
-{
- pcap_t *tap;
-
- tap = NETIF_PCAP(dev);
-
- pcap_close(tap);
- return RT_EOK;
-}
-
-static rt_size_t pcap_netif_read(rt_device_t dev, rt_off_t pos, void* buffer, rt_size_t size)
-{
- rt_set_errno(-RT_ENOSYS);
- return 0;
-}
-
-static rt_size_t pcap_netif_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size)
-{
- rt_set_errno(-RT_ENOSYS);
- return 0;
-}
-
-static rt_err_t pcap_netif_control(rt_device_t dev, rt_uint8_t cmd, void *args)
-{
- switch (cmd)
- {
- case NIOCTL_GADDR:
- /* get mac address */
- if (args) rt_memcpy(args, pcap_netif_device.dev_addr, 6);
- else return -RT_ERROR;
- break;
-
- default :
- break;
- }
-
- return RT_EOK;
-}
-
-rt_err_t pcap_netif_tx( rt_device_t dev, struct pbuf* p)
-{
- struct pbuf *q;
- rt_uint8_t *ptr;
- rt_uint8_t buf[2048];
- rt_err_t result = RT_EOK;
- pcap_t *tap;
- int res;
-
- tap = NETIF_PCAP(dev);
-
- /* lock EMAC device */
- rt_sem_take(&sem_lock, RT_WAITING_FOREVER);
-
- /* copy data to tx buffer */
- q = p;
- ptr = (rt_uint8_t*)buf;
- while (q)
- {
- memcpy(ptr, q->payload, q->len);
- ptr += q->len;
- q = q->next;
- }
-
- rt_enter_critical();
- res = pcap_sendpacket(tap, buf, p->tot_len);
- rt_exit_critical();
-
- if (res != 0)
- {
- rt_kprintf("Error sending the packet: \n", pcap_geterr(tap));
- result = -RT_ERROR;
- }
-
- /* unlock EMAC device */
- rt_sem_release(&sem_lock);
-
- return result;
-}
-
-struct pbuf *pcap_netif_rx(rt_device_t dev)
-{
- struct pbuf* p = RT_NULL;
-
- rt_mb_recv(packet_mb, (rt_uint32_t*)&p, 0);
-
- return p;
-}
-
-void pcap_netif_hw_init(void)
-{
- rt_sem_init(&sem_lock, "eth_lock", 1, RT_IPC_FLAG_FIFO);
-
- pcap_netif_device.dev_addr[0] = 0x00;
- pcap_netif_device.dev_addr[1] = 0x60;
- pcap_netif_device.dev_addr[2] = 0x37;
- /* set mac address: (only for test) */
- pcap_netif_device.dev_addr[3] = 0x12;
- pcap_netif_device.dev_addr[4] = 0x34;
- pcap_netif_device.dev_addr[5] = 0x56;
-
- pcap_netif_device.parent.parent.init = pcap_netif_init;
- pcap_netif_device.parent.parent.open = pcap_netif_open;
- pcap_netif_device.parent.parent.close = pcap_netif_close;
- pcap_netif_device.parent.parent.read = pcap_netif_read;
- pcap_netif_device.parent.parent.write = pcap_netif_write;
- pcap_netif_device.parent.parent.control = pcap_netif_control;
- pcap_netif_device.parent.parent.user_data = RT_NULL;
-
- pcap_netif_device.parent.eth_rx = pcap_netif_rx;
- pcap_netif_device.parent.eth_tx = pcap_netif_tx;
-
- eth_device_init(&(pcap_netif_device.parent), "e0");
-}
-
-#include <finsh.h>
-void list_pcap(void)
-{
- int i=0;
- pcap_if_t *alldevs;
- pcap_if_t *d;
- char errbuf[PCAP_ERRBUF_SIZE];
-
- /* Retrieve the device list */
- if(pcap_findalldevs(&alldevs, errbuf) == -1)
- {
- rt_kprintf("Error in pcap_findalldevs: %s\n", errbuf);
- return -RT_ERROR;
- }
-
- /* Print the list */
- for(d = alldevs; d; d = d->next)
- {
- rt_kprintf("%d. %s", ++i, d->name);
- if (d->description)
- rt_kprintf(" (%s)\n", d->description);
- else
- rt_kprintf(" (No description available)\n");
- }
- if(i == 0)
- {
- rt_kprintf("\nNo interfaces found! Make sure WinPcap is installed.\n");
- return -RT_ERROR;
- }
-
- pcap_freealldevs(alldevs);
-
- return ;
-}
-FINSH_FUNCTION_EXPORT(list_pcap, show host netif adapter);
+/* + * File : pcap_netif.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2012, RT-Thread Development Team + * + * The license and distribution terms for this file may be + * found in the file LICENSE in this distribution or at + * http://www.rt-thread.org/license/LICENSE + * + * Change Logs: + * Date Author Notes + * 2012-11-05 Bernard the first version + * 2012-11-13 Bernard merge prife's patch for exclusive + * access pcap driver. + */ + +#ifdef _TIME_T_DEFINED +#undef _TIME_T_DEFINED +#endif + +#ifdef _MSC_VER +/* + * we do not want the warnings about the old deprecated and unsecure CRT functions + * since these examples can be compiled under *nix as well + */ +#define _CRT_SECURE_NO_WARNINGS +#endif +#include <pcap.h> + +#include <rtthread.h> +#include <netif/ethernetif.h> + +#define MAX_ADDR_LEN 6 + +#define NETIF_DEVICE(netif) ((struct pcap_netif*)(netif)) +#define NETIF_PCAP(netif) (NETIF_DEVICE(netif)->tap) + +struct pcap_netif +{ + /* inherit from ethernet device */ + struct eth_device parent; + + pcap_t *tap; + /* interface address info. */ + rt_uint8_t dev_addr[MAX_ADDR_LEN]; /* hw address */ +}; +static struct pcap_netif pcap_netif_device; +static struct rt_semaphore sem_lock; +static rt_mailbox_t packet_mb = RT_NULL; + +static void pcap_thread_entry(void* parameter) +{ + pcap_if_t *netif; + pcap_t *tap; + char errbuf[PCAP_ERRBUF_SIZE]; + struct pcap_pkthdr *header; + const u_char *pkt_data; + int res; + + netif = (pcap_if_t *) parameter; + + /* Open the adapter */ + if ((tap = pcap_open_live(netif->name, + 65536, // portion of the packet to capture. + 1, // promiscuous mode (nonzero means promiscuous) + 1, // read timeout, 0 blocked, -1 no timeout + errbuf )) == NULL) + { + rt_kprintf("Unable to open the adapter. %s is not supported by WinPcap\n", netif->name); + return; + } + + NETIF_PCAP(&pcap_netif_device) = tap; + + /* Read the packets */ + while (1) + { + struct eth_device* eth; + struct pbuf *p; + + rt_enter_critical(); + res = pcap_next_ex(tap, &header, &pkt_data); + rt_exit_critical(); + + if (res == 0) continue; + + eth = (struct eth_device*) &pcap_netif_device; + + p = pbuf_alloc(PBUF_LINK, header->len, PBUF_RAM); + pbuf_take(p, pkt_data, header->len); + + /* send to packet mailbox */ + rt_mb_send_wait(packet_mb, (rt_uint32_t)p, RT_WAITING_FOREVER); + /* notify eth rx thread to receive packet */ + eth_device_ready(eth); + } +} + +static rt_err_t pcap_netif_init(rt_device_t dev) +{ + rt_thread_t tid; + pcap_if_t *alldevs; + pcap_if_t *d; + pcap_t *tap; + int inum, i=0; + char errbuf[PCAP_ERRBUF_SIZE]; + + /* Retrieve the device list */ + if(pcap_findalldevs(&alldevs, errbuf) == -1) + { + rt_kprintf("Error in pcap_findalldevs: %s\n", errbuf); + return -RT_ERROR; + } + + /* Print the list */ + for(d = alldevs; d; d = d->next) + { + rt_kprintf("%d. %s", ++i, d->name); + if (d->description) + rt_kprintf(" (%s)\n", d->description); + else + rt_kprintf(" (No description available)\n"); + } + if(i == 0) + { + rt_kprintf("\nNo interfaces found! Make sure WinPcap is installed.\n"); + return -RT_ERROR; + } + + inum = 1; + /* Jump to the selected adapter */ + for(d = alldevs, i = 0; i < inum-1 ;d = d->next, i++); + + { + rt_kprintf("Select (%s) as network interface\n", d->description); + packet_mb = rt_mb_create("pcap", 64, RT_IPC_FLAG_FIFO); + tid = rt_thread_create("pcap", pcap_thread_entry, d, + 2048, RT_THREAD_PRIORITY_MAX - 1, 10); + if (tid != RT_NULL) + { + rt_thread_startup(tid); + } + + rt_thread_delay(100); + } + + pcap_freealldevs(alldevs); + + return RT_EOK; +} + +static rt_err_t pcap_netif_open(rt_device_t dev, rt_uint16_t oflag) +{ + return RT_EOK; +} + +static rt_err_t pcap_netif_close(rt_device_t dev) +{ + pcap_t *tap; + + tap = NETIF_PCAP(dev); + + pcap_close(tap); + return RT_EOK; +} + +static rt_size_t pcap_netif_read(rt_device_t dev, rt_off_t pos, void* buffer, rt_size_t size) +{ + rt_set_errno(-RT_ENOSYS); + return 0; +} + +static rt_size_t pcap_netif_write (rt_device_t dev, rt_off_t pos, const void* buffer, rt_size_t size) +{ + rt_set_errno(-RT_ENOSYS); + return 0; +} + +static rt_err_t pcap_netif_control(rt_device_t dev, rt_uint8_t cmd, void *args) +{ + switch (cmd) + { + case NIOCTL_GADDR: + /* get mac address */ + if (args) rt_memcpy(args, pcap_netif_device.dev_addr, 6); + else return -RT_ERROR; + break; + + default : + break; + } + + return RT_EOK; +} + +rt_err_t pcap_netif_tx( rt_device_t dev, struct pbuf* p) +{ + struct pbuf *q; + rt_uint8_t *ptr; + rt_uint8_t buf[2048]; + rt_err_t result = RT_EOK; + pcap_t *tap; + int res; + + tap = NETIF_PCAP(dev); + + /* lock EMAC device */ + rt_sem_take(&sem_lock, RT_WAITING_FOREVER); + + /* copy data to tx buffer */ + q = p; + ptr = (rt_uint8_t*)buf; + while (q) + { + memcpy(ptr, q->payload, q->len); + ptr += q->len; + q = q->next; + } + + rt_enter_critical(); + res = pcap_sendpacket(tap, buf, p->tot_len); + rt_exit_critical(); + + if (res != 0) + { + rt_kprintf("Error sending the packet: \n", pcap_geterr(tap)); + result = -RT_ERROR; + } + + /* unlock EMAC device */ + rt_sem_release(&sem_lock); + + return result; +} + +struct pbuf *pcap_netif_rx(rt_device_t dev) +{ + struct pbuf* p = RT_NULL; + + rt_mb_recv(packet_mb, (rt_uint32_t*)&p, 0); + + return p; +} + +void pcap_netif_hw_init(void) +{ + rt_sem_init(&sem_lock, "eth_lock", 1, RT_IPC_FLAG_FIFO); + + pcap_netif_device.dev_addr[0] = 0x00; + pcap_netif_device.dev_addr[1] = 0x60; + pcap_netif_device.dev_addr[2] = 0x37; + /* set mac address: (only for test) */ + pcap_netif_device.dev_addr[3] = 0x12; + pcap_netif_device.dev_addr[4] = 0x34; + pcap_netif_device.dev_addr[5] = 0x56; + + pcap_netif_device.parent.parent.init = pcap_netif_init; + pcap_netif_device.parent.parent.open = pcap_netif_open; + pcap_netif_device.parent.parent.close = pcap_netif_close; + pcap_netif_device.parent.parent.read = pcap_netif_read; + pcap_netif_device.parent.parent.write = pcap_netif_write; + pcap_netif_device.parent.parent.control = pcap_netif_control; + pcap_netif_device.parent.parent.user_data = RT_NULL; + + pcap_netif_device.parent.eth_rx = pcap_netif_rx; + pcap_netif_device.parent.eth_tx = pcap_netif_tx; + + eth_device_init(&(pcap_netif_device.parent), "e0"); +} + +#include <finsh.h> +void list_pcap(void) +{ + int i=0; + pcap_if_t *alldevs; + pcap_if_t *d; + char errbuf[PCAP_ERRBUF_SIZE]; + + /* Retrieve the device list */ + if(pcap_findalldevs(&alldevs, errbuf) == -1) + { + rt_kprintf("Error in pcap_findalldevs: %s\n", errbuf); + return -RT_ERROR; + } + + /* Print the list */ + for(d = alldevs; d; d = d->next) + { + rt_kprintf("%d. %s", ++i, d->name); + if (d->description) + rt_kprintf(" (%s)\n", d->description); + else + rt_kprintf(" (No description available)\n"); + } + if(i == 0) + { + rt_kprintf("\nNo interfaces found! Make sure WinPcap is installed.\n"); + return -RT_ERROR; + } + + pcap_freealldevs(alldevs); + + return ; +} +FINSH_FUNCTION_EXPORT(list_pcap, show host netif adapter); diff --git a/bsp/simulator/readme.txt b/bsp/simulator/readme.txt index e73313f295..7ef04e627d 100644 --- a/bsp/simulator/readme.txt +++ b/bsp/simulator/readme.txt @@ -1,142 +1,142 @@ -说明: 本BSP可以如下演示
-默认演示realtouch GUI效果,并提供了一个贪吃的demo用于演示
-
-目前支持的功能有
-1). LWIP(可以打开LWIP选项,不过尚存在bug,不建议使用)
-2). 文件系统支持,支持ELM FatFS,UFFS,JFFS2
-3). RTGUI支持
- 目前SVN中的RTGUI源码可以直接用于simulator。
- 如果读者想快速在simulator上体验RTGUI,那么不需要修改任何文件,首先在命令行中使用
- scons --target=vs -s
- 生成工程后,打开project.vsproj编译,即可看到realtouch的ui出现,然后执行
- 在finsh中执行snake_main(),即可运行贪吃蛇demo
-
- 再补充说明一点,RTGUI的最新源码目前是托管在git上。
- github网页:https://github.com/RT-Thread/RTGUI
- 如果要使用rtgui中的最新源码,共有两种方法。
-方法1 添加环境变量
- 向系统环境变量中加入RTT_RTGUI,其值为刚才github上下载的rtgui源码包的路径。
- 例如笔者的rtgui源码包解压至 F:\Project\git\rt-gui\下
- 则将此环境变量配置为 F:\Project\git\rt-gui\components\rtgui
-方法2 不添加环境变量
- 打开SConstruct文件,
- ....
- 10 if os.getenv('RTT_RTGUI'):
- 11 RTT_RTGUI = os.getenv('RTT_RTGUI')
- 12 else:
- 13 # set the rtgui root directory by hand
- 14 # empty string means use the RTGUI in svn
- 15 # RTT_RTGUI = os.path.normpath(r'F:\Project\git\rt-gui\components\rtgui')
- 16 RTT_RTGUI =''
- ....
-将15,16行修改为
- 14 # empty string means use the RTGUI in svn
- 15 RTT_RTGUI = os.path.normpath(r'F:\Project\git\rt-gui\components\rtgui')
- 16 # RTT_RTGUI =''
-简单说明一下:
- 1)#号表示注释,类似于c语言中的//,
- 2)其中15行的路径为你的RTGUI路径源码,注意不是压缩包路径,而是压缩包路径下的 components\rtgui目录的绝对路径。
-
-1 编译:
-1.1 使用Visual Studio(2005以上版本)
- 在命令行中执行 scons --target=vs -s 可以生成vs2005的工程,名为project.vsproj
-
- 编译后运行
-
-1.2 使用scons编译,在当前目录中打开cmd,输入
- scons -j4
- 编译完成后会在当前目录下生成 rtthrad-win32.exe,双击即可运行。
-
-2. 测试文件系统
-运行:
- 编译后运行,会弹出CMD命令行窗口,可以看到控制台的输出信息,如下所示
-
- \ | /
- - RT - Thread Operating System
- / | \ 1.1.0 build Oct 21 2012
- 2006 - 2012 Copyright by rt-thread team
- init jffs2 lock mutex okay
- hello, world
- finsh>>fatfs initialzation failed!
- uffs initialzation failed!
- jffs2 initialzation failed!
- thread 29e4 exit
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- thread 2898 exit
-
- 注意上面的信息显示,fatfs/uffs/jffs2均挂载失败,这是因为我们还没有为sd.bin创建fat分区,并且sd上也没有目录用于挂载jffs2和uffs。
-
- 并且此时当前bsp目录下,新增了三个文件用于模拟sd卡,nand flash与nor flash,它们是
- sd.bin--模拟SD卡,挂载fat,大小为16M
- nand.bin-模拟nand flash,挂载uffs,参数page=2048+64bytes,block=64pages,16M
- nor.bin--模拟nor flash,挂载jffs2,型号为sst25vf,2M
-
- 按下回车,出现finsh,然后输入如下命令格式化sd.bin
-
- finsh>>mkfs("elm", "sd0")
- 0, 0x00000000
- finsh>>
-
- 关闭程序重新运行,此时可以看到fatfs挂载成功,不过jffs2和uffs依然失败,如下所示。
- \ | /
- - RT - Thread Operating System
- / | \ 1.1.0 build Oct 21 2012
- 2006 - 2012 Copyright by rt-thread team
- init jffs2 lock mutex okay
- hello, world
- finsh>>fatfs initialized!
- uffs initialzation failed!
- jffs2 initialzation failed!
-
- 这是因为sd上还没有目录来用于挂载jffs2和uffs,在finsh中输入如下命令在sd上创建nand与nor文件夹,分别用于挂载uffs与jffs2文件系统。
-
- finsh>>mkdir("/nand")
- 0, 0x00000000
- finsh>>mkdir("/nor")
- 0, 0x00000000
- finsh>>
- 然后再次关闭程序后重新运行,此时可以看到jffs2与uffs挂载成功。
-
- 最终输出如下所示:
-
- \ | /
- - RT - Thread Operating System
- / | \ 1.1.0 build Oct 21 2012
- 2006 - 2012 Copyright by rt-thread team
- init jffs2 lock mutex okay
- hello, world
- finsh>>fatfs initialized!
- os : system memory alloc 320 bytes
- flsh: ECC size 24
- flsh: UFFS consume spare data size 34
- os : system memory alloc 83520 bytes
- os : system memory alloc 52400 bytes
- os : system memory alloc 2048 bytes
- tree: DIR 0, FILE 0, DATA 0
- uffs initialized!
- jffs2 initialized!
- thread 2fb4 exit
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- thread 312c exit
-
-Ok,到现在,一个完整的文件系统测试环境就搭建完毕了,enjoy~~
-
-3 测试RTGUI
- 启动后就会看到GUI窗口,分辨率800×480串口,并出现图形界面。
- 此时在finsh中输入 snake_main()并回车,即可运行贪吃蛇程序。
+说明: 本BSP可以如下演示 +默认演示realtouch GUI效果,并提供了一个贪吃的demo用于演示 + +目前支持的功能有 +1). LWIP(可以打开LWIP选项,不过尚存在bug,不建议使用) +2). 文件系统支持,支持ELM FatFS,UFFS,JFFS2 +3). RTGUI支持 + 目前SVN中的RTGUI源码可以直接用于simulator。 + 如果读者想快速在simulator上体验RTGUI,那么不需要修改任何文件,首先在命令行中使用 + scons --target=vs -s + 生成工程后,打开project.vsproj编译,即可看到realtouch的ui出现,然后执行 + 在finsh中执行snake_main(),即可运行贪吃蛇demo + + 再补充说明一点,RTGUI的最新源码目前是托管在git上。 + github网页:https://github.com/RT-Thread/RTGUI + 如果要使用rtgui中的最新源码,共有两种方法。 +方法1 添加环境变量 + 向系统环境变量中加入RTT_RTGUI,其值为刚才github上下载的rtgui源码包的路径。 + 例如笔者的rtgui源码包解压至 F:\Project\git\rt-gui\下 + 则将此环境变量配置为 F:\Project\git\rt-gui\components\rtgui +方法2 不添加环境变量 + 打开SConstruct文件, + .... + 10 if os.getenv('RTT_RTGUI'): + 11 RTT_RTGUI = os.getenv('RTT_RTGUI') + 12 else: + 13 # set the rtgui root directory by hand + 14 # empty string means use the RTGUI in svn + 15 # RTT_RTGUI = os.path.normpath(r'F:\Project\git\rt-gui\components\rtgui') + 16 RTT_RTGUI ='' + .... +将15,16行修改为 + 14 # empty string means use the RTGUI in svn + 15 RTT_RTGUI = os.path.normpath(r'F:\Project\git\rt-gui\components\rtgui') + 16 # RTT_RTGUI ='' +简单说明一下: + 1)#号表示注释,类似于c语言中的//, + 2)其中15行的路径为你的RTGUI路径源码,注意不是压缩包路径,而是压缩包路径下的 components\rtgui目录的绝对路径。 + +1 编译: +1.1 使用Visual Studio(2005以上版本) + 在命令行中执行 scons --target=vs -s 可以生成vs2005的工程,名为project.vsproj + + 编译后运行 + +1.2 使用scons编译,在当前目录中打开cmd,输入 + scons -j4 + 编译完成后会在当前目录下生成 rtthrad-win32.exe,双击即可运行。 + +2. 测试文件系统 +运行: + 编译后运行,会弹出CMD命令行窗口,可以看到控制台的输出信息,如下所示 + + \ | / + - RT - Thread Operating System + / | \ 1.1.0 build Oct 21 2012 + 2006 - 2012 Copyright by rt-thread team + init jffs2 lock mutex okay + hello, world + finsh>>fatfs initialzation failed! + uffs initialzation failed! + jffs2 initialzation failed! + thread 29e4 exit + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + thread 2898 exit + + 注意上面的信息显示,fatfs/uffs/jffs2均挂载失败,这是因为我们还没有为sd.bin创建fat分区,并且sd上也没有目录用于挂载jffs2和uffs。 + + 并且此时当前bsp目录下,新增了三个文件用于模拟sd卡,nand flash与nor flash,它们是 + sd.bin--模拟SD卡,挂载fat,大小为16M + nand.bin-模拟nand flash,挂载uffs,参数page=2048+64bytes,block=64pages,16M + nor.bin--模拟nor flash,挂载jffs2,型号为sst25vf,2M + + 按下回车,出现finsh,然后输入如下命令格式化sd.bin + + finsh>>mkfs("elm", "sd0") + 0, 0x00000000 + finsh>> + + 关闭程序重新运行,此时可以看到fatfs挂载成功,不过jffs2和uffs依然失败,如下所示。 + \ | / + - RT - Thread Operating System + / | \ 1.1.0 build Oct 21 2012 + 2006 - 2012 Copyright by rt-thread team + init jffs2 lock mutex okay + hello, world + finsh>>fatfs initialized! + uffs initialzation failed! + jffs2 initialzation failed! + + 这是因为sd上还没有目录来用于挂载jffs2和uffs,在finsh中输入如下命令在sd上创建nand与nor文件夹,分别用于挂载uffs与jffs2文件系统。 + + finsh>>mkdir("/nand") + 0, 0x00000000 + finsh>>mkdir("/nor") + 0, 0x00000000 + finsh>> + 然后再次关闭程序后重新运行,此时可以看到jffs2与uffs挂载成功。 + + 最终输出如下所示: + + \ | / + - RT - Thread Operating System + / | \ 1.1.0 build Oct 21 2012 + 2006 - 2012 Copyright by rt-thread team + init jffs2 lock mutex okay + hello, world + finsh>>fatfs initialized! + os : system memory alloc 320 bytes + flsh: ECC size 24 + flsh: UFFS consume spare data size 34 + os : system memory alloc 83520 bytes + os : system memory alloc 52400 bytes + os : system memory alloc 2048 bytes + tree: DIR 0, FILE 0, DATA 0 + uffs initialized! + jffs2 initialized! + thread 2fb4 exit + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + thread 312c exit + +Ok,到现在,一个完整的文件系统测试环境就搭建完毕了,enjoy~~ + +3 测试RTGUI + 启动后就会看到GUI窗口,分辨率800×480串口,并出现图形界面。 + 此时在finsh中输入 snake_main()并回车,即可运行贪吃蛇程序。 diff --git a/bsp/simulator/readme_en.txt b/bsp/simulator/readme_en.txt index 5e6b39d29f..2c6db87844 100644 --- a/bsp/simulator/readme_en.txt +++ b/bsp/simulator/readme_en.txt @@ -1,102 +1,102 @@ -compile bsp:
-There are two ways.
-1). Visual Studio(2005 or newer version), open vs2005.vcproj with visual studio
- compile, then run it.
-
-2). use scons, open cmd console, change to current path, then do
- scons -j4
-scons will compile this bsp with cl(the compiler of vs), then rtthrad-win32.exe will be created in current directory. Run it by double click it.
-
-run:
- Run, then you can see the following message on CMD window.
-
- \ | /
- - RT - Thread Operating System
- / | \ 1.1.0 build Oct 21 2012
- 2006 - 2012 Copyright by rt-thread team
- init jffs2 lock mutex okay
- hello, world
- finsh>>fatfs initialzation failed!
- uffs initialzation failed!
- jffs2 initialzation failed!
- thread 29e4 exit
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- thread 2898 exit
-
-Then you may note that, three file (sd.bin, nand.bin, nor.bin) are created. These three files are used to simulate as SD CARD, nand flash and nor flash.
- sd.bin--SD card, fatfs, 16M
- nand.bin--nand flash, uffs, page=2048+64bytes, block=64pages, 16M
- nor.bin--nor flash, jffs2, block size is 64K, 2M
-
-Note, it failed to mount fatfs,uffs and jffs2, because there is valid partition on sd card, and there is no directory to mount uffs and jffs2.
-
-So, we should mount sd card at first.
-Press ENTER, and run the command "mkfs", like,
-
- finsh>>mkfs("elm", "sd0")
- 0, 0x00000000
- finsh>>
-
-Then close CMD, and then re-run it. This time, you can see that fatfs is mounted correctly, While uffs and jffs2 are still failed to mount for the reason that there is no any directories for uffs and jffs2.
- \ | /
- - RT - Thread Operating System
- / | \ 1.1.0 build Oct 21 2012
- 2006 - 2012 Copyright by rt-thread team
- init jffs2 lock mutex okay
- hello, world
- finsh>>fatfs initialized!
- uffs initialzation failed!
- jffs2 initialzation failed!
-
-so, in order to mount uffs and jffs2, we should create directories for them. Do the following commands.
-
- finsh>>mkdir("/nand")
- 0, 0x00000000
- finsh>>mkdir("/nor")
- 0, 0x00000000
- finsh>>
-
-Close the CMD console, and restart, then you can see this:
-
- \ | /
- - RT - Thread Operating System
- / | \ 1.1.0 build Oct 21 2012
- 2006 - 2012 Copyright by rt-thread team
- init jffs2 lock mutex okay
- hello, world
- finsh>>fatfs initialized!
- os : system memory alloc 320 bytes
- flsh: ECC size 24
- flsh: UFFS consume spare data size 34
- os : system memory alloc 83520 bytes
- os : system memory alloc 52400 bytes
- os : system memory alloc 2048 bytes
- tree: DIR 0, FILE 0, DATA 0
- uffs initialized!
- jffs2 initialized!
- thread 2fb4 exit
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- hello, world
- thread 312c exit
-
-Ok, everything is okay, you can develop rt-thread with visual studio.
-
-Any questions about this bsp, please email me, [email protected]
-
-Enjoy~~
- prife 2012/10/21
+compile bsp: +There are two ways. +1). Visual Studio(2005 or newer version), open vs2005.vcproj with visual studio + compile, then run it. + +2). use scons, open cmd console, change to current path, then do + scons -j4 +scons will compile this bsp with cl(the compiler of vs), then rtthrad-win32.exe will be created in current directory. Run it by double click it. + +run: + Run, then you can see the following message on CMD window. + + \ | / + - RT - Thread Operating System + / | \ 1.1.0 build Oct 21 2012 + 2006 - 2012 Copyright by rt-thread team + init jffs2 lock mutex okay + hello, world + finsh>>fatfs initialzation failed! + uffs initialzation failed! + jffs2 initialzation failed! + thread 29e4 exit + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + thread 2898 exit + +Then you may note that, three file (sd.bin, nand.bin, nor.bin) are created. These three files are used to simulate as SD CARD, nand flash and nor flash. + sd.bin--SD card, fatfs, 16M + nand.bin--nand flash, uffs, page=2048+64bytes, block=64pages, 16M + nor.bin--nor flash, jffs2, block size is 64K, 2M + +Note, it failed to mount fatfs,uffs and jffs2, because there is valid partition on sd card, and there is no directory to mount uffs and jffs2. + +So, we should mount sd card at first. +Press ENTER, and run the command "mkfs", like, + + finsh>>mkfs("elm", "sd0") + 0, 0x00000000 + finsh>> + +Then close CMD, and then re-run it. This time, you can see that fatfs is mounted correctly, While uffs and jffs2 are still failed to mount for the reason that there is no any directories for uffs and jffs2. + \ | / + - RT - Thread Operating System + / | \ 1.1.0 build Oct 21 2012 + 2006 - 2012 Copyright by rt-thread team + init jffs2 lock mutex okay + hello, world + finsh>>fatfs initialized! + uffs initialzation failed! + jffs2 initialzation failed! + +so, in order to mount uffs and jffs2, we should create directories for them. Do the following commands. + + finsh>>mkdir("/nand") + 0, 0x00000000 + finsh>>mkdir("/nor") + 0, 0x00000000 + finsh>> + +Close the CMD console, and restart, then you can see this: + + \ | / + - RT - Thread Operating System + / | \ 1.1.0 build Oct 21 2012 + 2006 - 2012 Copyright by rt-thread team + init jffs2 lock mutex okay + hello, world + finsh>>fatfs initialized! + os : system memory alloc 320 bytes + flsh: ECC size 24 + flsh: UFFS consume spare data size 34 + os : system memory alloc 83520 bytes + os : system memory alloc 52400 bytes + os : system memory alloc 2048 bytes + tree: DIR 0, FILE 0, DATA 0 + uffs initialized! + jffs2 initialized! + thread 2fb4 exit + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + hello, world + thread 312c exit + +Ok, everything is okay, you can develop rt-thread with visual studio. + +Any questions about this bsp, please email me, [email protected] + +Enjoy~~ + prife 2012/10/21 diff --git a/bsp/simulator/rtconfig.h b/bsp/simulator/rtconfig.h index 5b7db3bdb6..c138acb438 100644 --- a/bsp/simulator/rtconfig.h +++ b/bsp/simulator/rtconfig.h @@ -1,224 +1,224 @@ -/* RT-Thread config file */
-#ifndef __RTTHREAD_CFG_H__
-#define __RTTHREAD_CFG_H__
-
-/* SECTION: port for visual studio */
-#ifdef _MSC_VER
-#undef RT_USING_NEWLIB
-#undef RT_USING_MINILIBC
-#define NORESOURCE //RT_VESRION in winuser.h
-#define _CRT_ERRNO_DEFINED //errno macro redefinition
-
-#define RT_HEAP_SIZE (1024*1024*2)
-
-/* disable some warning in MSC */
-#pragma warning(disable:4273) /* to ignore: warning C4273: inconsistent dll linkage */
-#pragma warning(disable:4312) /* to ignore: warning C4312: 'type cast' : conversion from 'rt_uint32_t' to 'rt_uint32_t *' */
-#pragma warning(disable:4311) /* to ignore: warning C4311: 'type cast' : pointer truncation from 'short *__w64 ' to 'long' */
-#pragma warning(disable:4996) /* to ignore: warning C4996: The POSIX name for this item is deprecated. */
-#pragma warning(disable:4267) /* to ignore: warning C4267: conversion from 'size_t' to 'rt_size_t', possible loss of data */
-#pragma warning(disable:4244) /* to ignore: warning C4244: '=' : conversion from '__w64 int' to 'rt_size_t', possible loss of data */
-#endif
-
-/* SECTION: basic kernel options */
-/* RT_NAME_MAX*/
-#define RT_NAME_MAX 8
-
-/* RT_ALIGN_SIZE*/
-#define RT_ALIGN_SIZE 4
-
-/* PRIORITY_MAX */
-#define RT_THREAD_PRIORITY_MAX 32
-
-/* Tick per Second */
-#define RT_TICK_PER_SECOND 1000
-
-/* SECTION: RT_DEBUG */
-/* Thread Debug */
-#define RT_DEBUG
-#define RT_THREAD_DEBUG
-
-#define RT_USING_OVERFLOW_CHECK
-
-/* Using Hook */
-#define RT_USING_HOOK
-
-/* Using Software Timer */
-/* #define RT_USING_TIMER_SOFT */
-#define RT_TIMER_THREAD_PRIO 4
-#define RT_TIMER_THREAD_STACK_SIZE 512
-#define RT_TIMER_TICK_PER_SECOND 10
-
-/* SECTION: IPC */
-/* Using Semaphore*/
-#define RT_USING_SEMAPHORE
-
-/* Using Mutex */
-#define RT_USING_MUTEX
-
-/* Using Event */
-#define RT_USING_EVENT
-
-/* Using MailBox */
-#define RT_USING_MAILBOX
-
-/* Using Message Queue */
-#define RT_USING_MESSAGEQUEUE
-
-/* SECTION: Memory Management */
-/* Using Memory Pool Management*/
-/* #define RT_USING_MEMPOOL */
-
-/* Using Dynamic Heap Management */
-#define RT_USING_HEAP
-
-/* Using Small MM */
-#define RT_USING_SMALL_MEM
-/* #define RT_TINY_SIZE */
-
-/* SECTION: Device System */
-/* Using Device System */
-#define RT_USING_DEVICE
-/* #define RT_USING_UART1 */
-
-/* SECTION: Console options */
-#define RT_USING_CONSOLE
-/* the buffer size of console*/
-#define RT_CONSOLEBUF_SIZE 128
-#define RT_CONSOLE_DEVICE_NAME "sci0"
-
-/* SECTION: component options */
-#define RT_USING_COMPONENTS_INIT
-
-/* SECTION: MTD interface options */
-/* using mtd nand flash */
-#define RT_USING_MTD_NAND
-/* using mtd nor flash */
-#define RT_USING_MTD_NOR
-
-/* SECTION: finsh, a C-Express shell */
-#define RT_USING_FINSH
-/* Using symbol table */
-#define FINSH_USING_SYMTAB
-#define FINSH_USING_DESCRIPTION
-
-/* SECTION: device file system */
-#define RT_USING_DFS
-#define DFS_FILESYSTEM_TYPES_MAX 8
-
-/* DFS: ELM FATFS options */
-#define RT_USING_DFS_ELMFAT
-#define RT_DFS_ELM_WORD_ACCESS
-/* Reentrancy (thread safe) of the FatFs module. */
-#define RT_DFS_ELM_REENTRANT
-/* Number of volumes (logical drives) to be used. */
-#define RT_DFS_ELM_DRIVES 2
-/* #define RT_DFS_ELM_USE_LFN 1 */
-#define RT_DFS_ELM_MAX_LFN 255
-/* Maximum sector size to be handled. */
-#define RT_DFS_ELM_MAX_SECTOR_SIZE 512
-
-/* DFS: network file system options */
-/* #define RT_USING_DFS_NFS */
-
-/* DFS: UFFS nand file system options */
-#define RT_USING_DFS_UFFS
-/* configuration for uffs, more to see dfs_uffs.h and uffs_config.h */
-#define RT_CONFIG_UFFS_ECC_MODE UFFS_ECC_HW_AUTO
-/* enable this ,you need provide a mark_badblock/check_block function */
-/* #define RT_UFFS_USE_CHECK_MARK_FUNCITON */
-
-/* DFS: JFFS2 nor flash file system options */
-#define RT_USING_DFS_JFFS2
-
-/* DFS: windows share directory mounted to rt-thread/dfs */
-/* only used in bsp/simulator */
-#define RT_USING_DFS_WINSHAREDIR
-
-/* the max number of mounted file system */
-#define DFS_FILESYSTEMS_MAX 4
-/* the max number of opened files */
-#define DFS_FD_MAX 4
-
-/* SECTION: lwip, a lightweight TCP/IP protocol stack */
-/* #define RT_USING_LWIP */
-/* LwIP uses RT-Thread Memory Management */
-#define RT_LWIP_USING_RT_MEM
-/* Enable ICMP protocol*/
-#define RT_LWIP_ICMP
-/* Enable UDP protocol*/
-#define RT_LWIP_UDP
-/* Enable TCP protocol*/
-#define RT_LWIP_TCP
-/* Enable DNS */
-#define RT_LWIP_DNS
-
-/* the number of simultaneously active TCP connections*/
-#define RT_LWIP_TCP_PCB_NUM 5
-
-/* Using DHCP */
-/* #define RT_LWIP_DHCP */
-
-/* ip address of target*/
-#define RT_LWIP_IPADDR0 192
-#define RT_LWIP_IPADDR1 168
-#define RT_LWIP_IPADDR2 126
-#define RT_LWIP_IPADDR3 30
-
-/* gateway address of target*/
-#define RT_LWIP_GWADDR0 192
-#define RT_LWIP_GWADDR1 168
-#define RT_LWIP_GWADDR2 126
-#define RT_LWIP_GWADDR3 1
-
-/* mask address of target*/
-#define RT_LWIP_MSKADDR0 255
-#define RT_LWIP_MSKADDR1 255
-#define RT_LWIP_MSKADDR2 255
-#define RT_LWIP_MSKADDR3 0
-
-/* tcp thread options */
-#define RT_LWIP_TCPTHREAD_PRIORITY 12
-#define RT_LWIP_TCPTHREAD_MBOX_SIZE 10
-#define RT_LWIP_TCPTHREAD_STACKSIZE 1024
-
-/* Ethernet if thread options */
-#define RT_LWIP_ETHTHREAD_PRIORITY 15
-#define RT_LWIP_ETHTHREAD_MBOX_SIZE 10
-#define RT_LWIP_ETHTHREAD_STACKSIZE 512
-
-/* TCP sender buffer space */
-#define RT_LWIP_TCP_SND_BUF 8192
-/* TCP receive window. */
-#define RT_LWIP_TCP_WND 8192
-
-/* SECTION: RT-Thread/GUI */
-#define RT_USING_RTGUI
-
-/* name length of RTGUI object */
-#define RTGUI_NAME_MAX 12
-/* support 16 weight font */
-#define RTGUI_USING_FONT16
-/* support Chinese font */
-#define RTGUI_USING_FONTHZ
-/* use DFS as file interface */
-#define RTGUI_USING_DFS_FILERW
-/* use font file as Chinese font */
-/* #define RTGUI_USING_HZ_FILE */
-/* use Chinese bitmap font */
-#define RTGUI_USING_HZ_BMP
-/* use small size in RTGUI */
-#define RTGUI_USING_SMALL_SIZE
-/* use mouse cursor */
-/* #define RTGUI_USING_MOUSE_CURSOR */
-/* default font size in RTGUI */
-#define RTGUI_DEFAULT_FONT_SIZE 16
-
-/* image support */
-#define RTGUI_IMAGE_XPM
-#define RTGUI_IMAGE_BMP
-/* #define RTGUI_IMAGE_JPEG */
-/* #define RTGUI_IMAGE_PNG */
-#define RTGUI_USING_NOTEBOOK_IMAGE
-
-#endif
+/* RT-Thread config file */ +#ifndef __RTTHREAD_CFG_H__ +#define __RTTHREAD_CFG_H__ + +/* SECTION: port for visual studio */ +#ifdef _MSC_VER +#undef RT_USING_NEWLIB +#undef RT_USING_MINILIBC +#define NORESOURCE //RT_VESRION in winuser.h +#define _CRT_ERRNO_DEFINED //errno macro redefinition + +#define RT_HEAP_SIZE (1024*1024*2) + +/* disable some warning in MSC */ +#pragma warning(disable:4273) /* to ignore: warning C4273: inconsistent dll linkage */ +#pragma warning(disable:4312) /* to ignore: warning C4312: 'type cast' : conversion from 'rt_uint32_t' to 'rt_uint32_t *' */ +#pragma warning(disable:4311) /* to ignore: warning C4311: 'type cast' : pointer truncation from 'short *__w64 ' to 'long' */ +#pragma warning(disable:4996) /* to ignore: warning C4996: The POSIX name for this item is deprecated. */ +#pragma warning(disable:4267) /* to ignore: warning C4267: conversion from 'size_t' to 'rt_size_t', possible loss of data */ +#pragma warning(disable:4244) /* to ignore: warning C4244: '=' : conversion from '__w64 int' to 'rt_size_t', possible loss of data */ +#endif + +/* SECTION: basic kernel options */ +/* RT_NAME_MAX*/ +#define RT_NAME_MAX 8 + +/* RT_ALIGN_SIZE*/ +#define RT_ALIGN_SIZE 4 + +/* PRIORITY_MAX */ +#define RT_THREAD_PRIORITY_MAX 32 + +/* Tick per Second */ +#define RT_TICK_PER_SECOND 1000 + +/* SECTION: RT_DEBUG */ +/* Thread Debug */ +#define RT_DEBUG +#define RT_THREAD_DEBUG + +#define RT_USING_OVERFLOW_CHECK + +/* Using Hook */ +#define RT_USING_HOOK + +/* Using Software Timer */ +/* #define RT_USING_TIMER_SOFT */ +#define RT_TIMER_THREAD_PRIO 4 +#define RT_TIMER_THREAD_STACK_SIZE 512 +#define RT_TIMER_TICK_PER_SECOND 10 + +/* SECTION: IPC */ +/* Using Semaphore*/ +#define RT_USING_SEMAPHORE + +/* Using Mutex */ +#define RT_USING_MUTEX + +/* Using Event */ +#define RT_USING_EVENT + +/* Using MailBox */ +#define RT_USING_MAILBOX + +/* Using Message Queue */ +#define RT_USING_MESSAGEQUEUE + +/* SECTION: Memory Management */ +/* Using Memory Pool Management*/ +/* #define RT_USING_MEMPOOL */ + +/* Using Dynamic Heap Management */ +#define RT_USING_HEAP + +/* Using Small MM */ +#define RT_USING_SMALL_MEM +/* #define RT_TINY_SIZE */ + +/* SECTION: Device System */ +/* Using Device System */ +#define RT_USING_DEVICE +/* #define RT_USING_UART1 */ + +/* SECTION: Console options */ +#define RT_USING_CONSOLE +/* the buffer size of console*/ +#define RT_CONSOLEBUF_SIZE 128 +#define RT_CONSOLE_DEVICE_NAME "sci0" + +/* SECTION: component options */ +#define RT_USING_COMPONENTS_INIT + +/* SECTION: MTD interface options */ +/* using mtd nand flash */ +#define RT_USING_MTD_NAND +/* using mtd nor flash */ +#define RT_USING_MTD_NOR + +/* SECTION: finsh, a C-Express shell */ +#define RT_USING_FINSH +/* Using symbol table */ +#define FINSH_USING_SYMTAB +#define FINSH_USING_DESCRIPTION + +/* SECTION: device file system */ +#define RT_USING_DFS +#define DFS_FILESYSTEM_TYPES_MAX 8 + +/* DFS: ELM FATFS options */ +#define RT_USING_DFS_ELMFAT +#define RT_DFS_ELM_WORD_ACCESS +/* Reentrancy (thread safe) of the FatFs module. */ +#define RT_DFS_ELM_REENTRANT +/* Number of volumes (logical drives) to be used. */ +#define RT_DFS_ELM_DRIVES 2 +/* #define RT_DFS_ELM_USE_LFN 1 */ +#define RT_DFS_ELM_MAX_LFN 255 +/* Maximum sector size to be handled. */ +#define RT_DFS_ELM_MAX_SECTOR_SIZE 512 + +/* DFS: network file system options */ +/* #define RT_USING_DFS_NFS */ + +/* DFS: UFFS nand file system options */ +#define RT_USING_DFS_UFFS +/* configuration for uffs, more to see dfs_uffs.h and uffs_config.h */ +#define RT_CONFIG_UFFS_ECC_MODE UFFS_ECC_HW_AUTO +/* enable this ,you need provide a mark_badblock/check_block function */ +/* #define RT_UFFS_USE_CHECK_MARK_FUNCITON */ + +/* DFS: JFFS2 nor flash file system options */ +#define RT_USING_DFS_JFFS2 + +/* DFS: windows share directory mounted to rt-thread/dfs */ +/* only used in bsp/simulator */ +#define RT_USING_DFS_WINSHAREDIR + +/* the max number of mounted file system */ +#define DFS_FILESYSTEMS_MAX 4 +/* the max number of opened files */ +#define DFS_FD_MAX 4 + +/* SECTION: lwip, a lightweight TCP/IP protocol stack */ +/* #define RT_USING_LWIP */ +/* LwIP uses RT-Thread Memory Management */ +#define RT_LWIP_USING_RT_MEM +/* Enable ICMP protocol*/ +#define RT_LWIP_ICMP +/* Enable UDP protocol*/ +#define RT_LWIP_UDP +/* Enable TCP protocol*/ +#define RT_LWIP_TCP +/* Enable DNS */ +#define RT_LWIP_DNS + +/* the number of simultaneously active TCP connections*/ +#define RT_LWIP_TCP_PCB_NUM 5 + +/* Using DHCP */ +/* #define RT_LWIP_DHCP */ + +/* ip address of target*/ +#define RT_LWIP_IPADDR0 192 +#define RT_LWIP_IPADDR1 168 +#define RT_LWIP_IPADDR2 126 +#define RT_LWIP_IPADDR3 30 + +/* gateway address of target*/ +#define RT_LWIP_GWADDR0 192 +#define RT_LWIP_GWADDR1 168 +#define RT_LWIP_GWADDR2 126 +#define RT_LWIP_GWADDR3 1 + +/* mask address of target*/ +#define RT_LWIP_MSKADDR0 255 +#define RT_LWIP_MSKADDR1 255 +#define RT_LWIP_MSKADDR2 255 +#define RT_LWIP_MSKADDR3 0 + +/* tcp thread options */ +#define RT_LWIP_TCPTHREAD_PRIORITY 12 +#define RT_LWIP_TCPTHREAD_MBOX_SIZE 10 +#define RT_LWIP_TCPTHREAD_STACKSIZE 1024 + +/* Ethernet if thread options */ +#define RT_LWIP_ETHTHREAD_PRIORITY 15 +#define RT_LWIP_ETHTHREAD_MBOX_SIZE 10 +#define RT_LWIP_ETHTHREAD_STACKSIZE 512 + +/* TCP sender buffer space */ +#define RT_LWIP_TCP_SND_BUF 8192 +/* TCP receive window. */ +#define RT_LWIP_TCP_WND 8192 + +/* SECTION: RT-Thread/GUI */ +#define RT_USING_RTGUI + +/* name length of RTGUI object */ +#define RTGUI_NAME_MAX 12 +/* support 16 weight font */ +#define RTGUI_USING_FONT16 +/* support Chinese font */ +#define RTGUI_USING_FONTHZ +/* use DFS as file interface */ +#define RTGUI_USING_DFS_FILERW +/* use font file as Chinese font */ +/* #define RTGUI_USING_HZ_FILE */ +/* use Chinese bitmap font */ +#define RTGUI_USING_HZ_BMP +/* use small size in RTGUI */ +#define RTGUI_USING_SMALL_SIZE +/* use mouse cursor */ +/* #define RTGUI_USING_MOUSE_CURSOR */ +/* default font size in RTGUI */ +#define RTGUI_DEFAULT_FONT_SIZE 16 + +/* image support */ +#define RTGUI_IMAGE_XPM +#define RTGUI_IMAGE_BMP +/* #define RTGUI_IMAGE_JPEG */ +/* #define RTGUI_IMAGE_PNG */ +#define RTGUI_USING_NOTEBOOK_IMAGE + +#endif diff --git a/bsp/simulator/rtconfig.py b/bsp/simulator/rtconfig.py index cb86c719ca..543026c549 100644 --- a/bsp/simulator/rtconfig.py +++ b/bsp/simulator/rtconfig.py @@ -1,77 +1,77 @@ -# toolchains options
-ARCH='sim'
-CPU='win32' #CPU='posix'
-CROSS_TOOL='msvc' #win32
-
-# lcd panel options
-# 'FMT0371','ILI932X', 'SSD1289'
-# RT_USING_LCD_TYPE = 'SSD1289'
-
-# cross_tool provides the cross compiler
-# EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR
-if CROSS_TOOL == 'gcc':
- PLATFORM = 'gcc'
- EXEC_PATH = '/usr/bin/gcc'
-
-if CROSS_TOOL == 'msvc':
- PLATFORM = 'cl'
- EXEC_PATH = ''
-
-BUILD = 'debug'
-#BUILD = ''
-
-if PLATFORM == 'gcc':
- # toolchains
- PREFIX = ''
- CC = PREFIX + 'gcc'
- AS = PREFIX + 'gcc'
- AR = PREFIX + 'ar'
- LINK = PREFIX + 'gcc'
- TARGET_EXT = 'axf'
- SIZE = PREFIX + 'size'
- OBJDUMP = PREFIX + 'objdump'
- OBJCPY = PREFIX + 'objcopy'
-
- DEVICE = ' -ffunction-sections -fdata-sections'
- CFLAGS = DEVICE
- AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp'
- #LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-linux.map,-cref,-u,Reset_Handler -T stm32_rom.ld'
- LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-linux.map -lpthread'
-
- CPATH = ''
- LPATH = ''
-
- if BUILD == 'debug':
- CFLAGS += ' -O0 -gdwarf-2'
- AFLAGS += ' -gdwarf-2'
- else:
- CFLAGS += ' -O2'
-
- POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread.bin\n' + SIZE + ' $TARGET \n'
-
-elif PLATFORM == 'cl':
- # toolchains
- PREFIX = ''
- TARGET_EXT = 'exe'
- AS = PREFIX + 'cl'
- CC = PREFIX + 'cl'
- AR = PREFIX + 'cl'
- LINK = PREFIX + 'cl'
- AFLAGS = ''
- CFLAGS = ''
- LFLAGS = ''
-
- if BUILD == 'debug':
- CFLAGS += ' /MTd'
- LFLAGS += ' /DEBUG'
- else:
- CFLAGS += ' /MT'
- LFLAGS += ''
-
- CFLAGS += ' /ZI /Od /W 3 /WL '
- LFLAGS += ' /SUBSYSTEM:CONSOLE /MACHINE:X86 '
-
- CPATH = ''
- LPATH = ''
-
- POST_ACTION = ''
+# toolchains options +ARCH='sim' +CPU='win32' #CPU='posix' +CROSS_TOOL='msvc' #win32 + +# lcd panel options +# 'FMT0371','ILI932X', 'SSD1289' +# RT_USING_LCD_TYPE = 'SSD1289' + +# cross_tool provides the cross compiler +# EXEC_PATH is the compiler execute path, for example, CodeSourcery, Keil MDK, IAR +if CROSS_TOOL == 'gcc': + PLATFORM = 'gcc' + EXEC_PATH = '/usr/bin/gcc' + +if CROSS_TOOL == 'msvc': + PLATFORM = 'cl' + EXEC_PATH = '' + +BUILD = 'debug' +#BUILD = '' + +if PLATFORM == 'gcc': + # toolchains + PREFIX = '' + CC = PREFIX + 'gcc' + AS = PREFIX + 'gcc' + AR = PREFIX + 'ar' + LINK = PREFIX + 'gcc' + TARGET_EXT = 'axf' + SIZE = PREFIX + 'size' + OBJDUMP = PREFIX + 'objdump' + OBJCPY = PREFIX + 'objcopy' + + DEVICE = ' -ffunction-sections -fdata-sections' + CFLAGS = DEVICE + AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp' + #LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-linux.map,-cref,-u,Reset_Handler -T stm32_rom.ld' + LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-linux.map -lpthread' + + CPATH = '' + LPATH = '' + + if BUILD == 'debug': + CFLAGS += ' -O0 -gdwarf-2' + AFLAGS += ' -gdwarf-2' + else: + CFLAGS += ' -O2' + + POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread.bin\n' + SIZE + ' $TARGET \n' + +elif PLATFORM == 'cl': + # toolchains + PREFIX = '' + TARGET_EXT = 'exe' + AS = PREFIX + 'cl' + CC = PREFIX + 'cl' + AR = PREFIX + 'cl' + LINK = PREFIX + 'cl' + AFLAGS = '' + CFLAGS = '' + LFLAGS = '' + + if BUILD == 'debug': + CFLAGS += ' /MTd' + LFLAGS += ' /DEBUG' + else: + CFLAGS += ' /MT' + LFLAGS += '' + + CFLAGS += ' /ZI /Od /W 3 /WL ' + LFLAGS += ' /SUBSYSTEM:CONSOLE /MACHINE:X86 ' + + CPATH = '' + LPATH = '' + + POST_ACTION = '' diff --git a/bsp/simulator/rtgui_demo/SConscript b/bsp/simulator/rtgui_demo/SConscript index d9c64eb9f9..0992612410 100644 --- a/bsp/simulator/rtgui_demo/SConscript +++ b/bsp/simulator/rtgui_demo/SConscript @@ -1,12 +1,12 @@ -from building import *
-
-cwd = GetCurrentDir()
-objs = []
-list = os.listdir(cwd)
-
-for d in list:
- path = os.path.join(cwd, d)
- if os.path.isfile(os.path.join(path, 'SConscript')):
- objs = objs + SConscript(os.path.join(d, 'SConscript'))
-
-Return('objs')
+from building import * + +cwd = GetCurrentDir() +objs = [] +list = os.listdir(cwd) + +for d in list: + path = os.path.join(cwd, d) + if os.path.isfile(os.path.join(path, 'SConscript')): + objs = objs + SConscript(os.path.join(d, 'SConscript')) + +Return('objs') diff --git a/bsp/simulator/rtgui_demo/snake/snake.c b/bsp/simulator/rtgui_demo/snake/snake.c index a9f57e6091..87e1c8b36f 100644 --- a/bsp/simulator/rtgui_demo/snake/snake.c +++ b/bsp/simulator/rtgui_demo/snake/snake.c @@ -1,271 +1,271 @@ -#include <string.h>
-#include <stdlib.h>
-#include <rtthread.h>
-#include "snake.h"
-
-#define ASSERT_RET(x, ret) \
- do{ \
- if (x) \
- return ret; \
- }while(0)
-
-rt_list_t snake_head;
-SNAKE_DIR prevdir, newdir;
-
-static SNAKE_DIR dir_adjust(SNAKE_DIR dir)
-{
- if ((SNAKE_DIR_UP == prevdir && SNAKE_DIR_DOWN != dir)
- || (SNAKE_DIR_DOWN == prevdir && SNAKE_DIR_UP != dir)
- || (SNAKE_DIR_LEFT == prevdir && SNAKE_DIR_RIGHT != dir)
- || (SNAKE_DIR_RIGHT == prevdir && SNAKE_DIR_LEFT != dir)
- )
- {
- newdir = dir;
- }
- else
- {
- rt_kprintf("dirction change error\n\r");
- }
-
- return newdir;
-}
-
-static void across_XY(point_t *node, const map_t *map)
-{
- RT_ASSERT(node != RT_NULL && map != RT_NULL);
-
- // ������ȳ�����ǰ�߿�����Դ�Խǽ������
- node->x = (node->x + map->width) % map->width;
- node->y = (node->y + map->height) % map->height;
-}
-
-static SYS_STE node_update(snake_t *tail, const point_t *node, map_t *map)
-{
- SYS_STE ret;
- point_t *pos;
-
- RT_ASSERT(tail != RT_NULL && node != RT_NULL && map != RT_NULL);
-
- pos = map->snake_flush;
- pos[0].x = pos[0].y = -1;
- pos[1].x = pos[1].y = -1;
-
- ret = (SYS_STE)map->range[node->y * map->width + node->x];
-
- if (FOOD == map->range[node->y * map->width + node->x])
- {
- // ��һ��ʳ������һ���ڵ�
- snake_t *new = (snake_t *)rt_malloc(sizeof(snake_t));
- if (!new)
- return NORMAL;
-
- pos[0] = *node;
- new->body = *node;
- rt_list_insert_after(&snake_head, &new->list);
- }
- else if (NORMAL == map->range[node->y * map->width + node->x])
- {
- // ��β���ĺ��õ�ͷ������������
- rt_list_remove(&tail->list);
- map->range[tail->body.y * map->width + tail->body.x] = NORMAL;
-
- pos[0] = *node;
- pos[1] = tail->body;
-
- tail->body = *node;
- rt_list_insert_after(&snake_head, &tail->list);
- }
-
- map->range[node->y * map->width + node->x] = OVER;
-
- if (ret != OVER)
- prevdir = newdir;
-
- return ret;
-}
-
-
-map_t *map_init(rt_uint32_t width, rt_uint32_t heigth)
-{
- map_t *map = rt_malloc(sizeof(map_t));
-
- if (map != RT_NULL)
- {
- map->range = rt_malloc(heigth * width);
-
- if (!map->range)
- {
- rt_free(map);
- map = RT_NULL;
- }
- else
- {
- map->width = width;
- map->height = heigth;
- memset(map->range, NORMAL, heigth * width);
- }
- }
-
- return map;
-}
-
-// ����һ��ָ�����ȵ�����ָ����
-rt_bool_t snake_init(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map)
-{
- rt_int32_t i;
- rt_int32_t inc_x, inc_y;
- point_t old = *start;
-
- ASSERT_RET(!map || !start, RT_FALSE);
-
- rt_list_init(&snake_head);
-
- if (dir == SNAKE_DIR_UP || dir == SNAKE_DIR_DOWN)
- {
- if (map->height <= length)
- return RT_FALSE;
-
- inc_x = 0;
- inc_y = dir == SNAKE_DIR_DOWN ? 1 : -1; // �����ӳ����ӣ�ͷ����ָ��λ��
- old.y -= inc_y;
- }
- else
- {
- if (map->width <= length)
- return RT_FALSE;
-
- inc_y = 0;
- inc_x = dir == SNAKE_DIR_RIGHT ? -1 : 1;
- old.x -= inc_x;
- }
-
- for (i = 0; i < length; i++)
- {
- snake_t *new = (snake_t *)rt_malloc(sizeof(snake_t));
- if (!new)
- return RT_FALSE;
-
- new->body.y = inc_y + old.y;
- new->body.x = inc_x + old.x;
-
- // ������ȳ�����ǰ�߿�����Դ�Խǽ������
- across_XY(&new->body, map);
-
- map->range[new->body.y * map->width + new->body.x] = OVER;
-
- old = new->body;
- rt_list_insert_before(&snake_head, &new->list);
- }
-
- prevdir = dir;
-
- return RT_TRUE;
-}
-
-// �����ʳ��
-rt_bool_t food_init(map_t *map, rt_uint32_t max_num)
-{
- point_t food;
-
-#ifndef FOOD_TIMEOUT
-#define FOOD_TIMEOUT 10
-#endif
-
- rt_uint32_t timeout, num;
-
- ASSERT_RET(!map, RT_FALSE);
-
- num = 0;
- timeout = rt_tick_get();
- srand(rand());
-
- map->food_flush[0].x = map->food_flush[0].y = -1;
-
- do
- {
- food.x = rand() % map->width;
- food.y = rand() % map->height;
-
- if (map->range[food.y * map->width + food.x] == NORMAL)
- {
- map->food_flush[0] = food;
- map->range[food.y * map->width + food.x] = FOOD;
- num++;
- }
- }
- while (num < max_num && rt_tick_get() - timeout < FOOD_TIMEOUT);
-
- return num;
-}
-
-void map_deinit(map_t *map)
-{
- if (map)
- {
- if (map->range)
- {
- rt_free(map->range);
- map->range = RT_NULL;
- }
- rt_free(map);
- }
-}
-
-void snake_deinit(void)
-{
- snake_t *node;
-
- while (!rt_list_isempty(&snake_head))
- {
- node = rt_list_entry(snake_head.prev, snake_t, list);
- rt_list_remove(&node->list);
- rt_free(node);
- }
-}
-
-void food_deinit(void)
-{
-
-}
-
-SYS_STE snake_step(SNAKE_DIR dir, map_t *map)
-{
- snake_t *tail, *head;
- point_t node;
-
- ASSERT_RET(!map, RT_FALSE);
-
- dir = dir_adjust(dir);
-
- // ȡ��ͷβ�����ڵ㣬�����ڵ㲻��Ҫ�ı�
- tail = rt_list_entry(snake_head.prev, snake_t, list);
- head = rt_list_entry(snake_head.next, snake_t, list);
-
- node = head->body;
-
- // ����һ���µ���ͷ����
- switch (dir)
- {
- case SNAKE_DIR_UP:
- case SNAKE_DIR_DOWN:
- node.y = head->body.y + (dir == SNAKE_DIR_DOWN ? -1 : 1);
- break;
- case SNAKE_DIR_LEFT:
- case SNAKE_DIR_RIGHT:
- node.x = head->body.x + (dir == SNAKE_DIR_RIGHT ? 1 : -1);
- break;
- }
- across_XY(&node, map);
-
- return node_update(tail, &node, map);
-}
-
-rt_bool_t snake_restart(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map)
-{
- ASSERT_RET(!map || !start, RT_FALSE);
-
- snake_deinit();
- memset(map->range, NORMAL, map->width * map->height);
-
- return snake_init(start, length, dir, map);
-}
+#include <string.h> +#include <stdlib.h> +#include <rtthread.h> +#include "snake.h" + +#define ASSERT_RET(x, ret) \ + do{ \ + if (x) \ + return ret; \ + }while(0) + +rt_list_t snake_head; +SNAKE_DIR prevdir, newdir; + +static SNAKE_DIR dir_adjust(SNAKE_DIR dir) +{ + if ((SNAKE_DIR_UP == prevdir && SNAKE_DIR_DOWN != dir) + || (SNAKE_DIR_DOWN == prevdir && SNAKE_DIR_UP != dir) + || (SNAKE_DIR_LEFT == prevdir && SNAKE_DIR_RIGHT != dir) + || (SNAKE_DIR_RIGHT == prevdir && SNAKE_DIR_LEFT != dir) + ) + { + newdir = dir; + } + else + { + rt_kprintf("dirction change error\n\r"); + } + + return newdir; +} + +static void across_XY(point_t *node, const map_t *map) +{ + RT_ASSERT(node != RT_NULL && map != RT_NULL); + + // ������ȳ�����ǰ�߿�����Դ�Խǽ������ + node->x = (node->x + map->width) % map->width; + node->y = (node->y + map->height) % map->height; +} + +static SYS_STE node_update(snake_t *tail, const point_t *node, map_t *map) +{ + SYS_STE ret; + point_t *pos; + + RT_ASSERT(tail != RT_NULL && node != RT_NULL && map != RT_NULL); + + pos = map->snake_flush; + pos[0].x = pos[0].y = -1; + pos[1].x = pos[1].y = -1; + + ret = (SYS_STE)map->range[node->y * map->width + node->x]; + + if (FOOD == map->range[node->y * map->width + node->x]) + { + // ��һ��ʳ������һ���ڵ� + snake_t *new = (snake_t *)rt_malloc(sizeof(snake_t)); + if (!new) + return NORMAL; + + pos[0] = *node; + new->body = *node; + rt_list_insert_after(&snake_head, &new->list); + } + else if (NORMAL == map->range[node->y * map->width + node->x]) + { + // ��β���ĺ��õ�ͷ������������ + rt_list_remove(&tail->list); + map->range[tail->body.y * map->width + tail->body.x] = NORMAL; + + pos[0] = *node; + pos[1] = tail->body; + + tail->body = *node; + rt_list_insert_after(&snake_head, &tail->list); + } + + map->range[node->y * map->width + node->x] = OVER; + + if (ret != OVER) + prevdir = newdir; + + return ret; +} + + +map_t *map_init(rt_uint32_t width, rt_uint32_t heigth) +{ + map_t *map = rt_malloc(sizeof(map_t)); + + if (map != RT_NULL) + { + map->range = rt_malloc(heigth * width); + + if (!map->range) + { + rt_free(map); + map = RT_NULL; + } + else + { + map->width = width; + map->height = heigth; + memset(map->range, NORMAL, heigth * width); + } + } + + return map; +} + +// ����һ��ָ�����ȵ�����ָ���� +rt_bool_t snake_init(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map) +{ + rt_int32_t i; + rt_int32_t inc_x, inc_y; + point_t old = *start; + + ASSERT_RET(!map || !start, RT_FALSE); + + rt_list_init(&snake_head); + + if (dir == SNAKE_DIR_UP || dir == SNAKE_DIR_DOWN) + { + if (map->height <= length) + return RT_FALSE; + + inc_x = 0; + inc_y = dir == SNAKE_DIR_DOWN ? 1 : -1; // �����ӳ����ӣ�ͷ����ָ��λ�� + old.y -= inc_y; + } + else + { + if (map->width <= length) + return RT_FALSE; + + inc_y = 0; + inc_x = dir == SNAKE_DIR_RIGHT ? -1 : 1; + old.x -= inc_x; + } + + for (i = 0; i < length; i++) + { + snake_t *new = (snake_t *)rt_malloc(sizeof(snake_t)); + if (!new) + return RT_FALSE; + + new->body.y = inc_y + old.y; + new->body.x = inc_x + old.x; + + // ������ȳ�����ǰ�߿�����Դ�Խǽ������ + across_XY(&new->body, map); + + map->range[new->body.y * map->width + new->body.x] = OVER; + + old = new->body; + rt_list_insert_before(&snake_head, &new->list); + } + + prevdir = dir; + + return RT_TRUE; +} + +// �����ʳ�� +rt_bool_t food_init(map_t *map, rt_uint32_t max_num) +{ + point_t food; + +#ifndef FOOD_TIMEOUT +#define FOOD_TIMEOUT 10 +#endif + + rt_uint32_t timeout, num; + + ASSERT_RET(!map, RT_FALSE); + + num = 0; + timeout = rt_tick_get(); + srand(rand()); + + map->food_flush[0].x = map->food_flush[0].y = -1; + + do + { + food.x = rand() % map->width; + food.y = rand() % map->height; + + if (map->range[food.y * map->width + food.x] == NORMAL) + { + map->food_flush[0] = food; + map->range[food.y * map->width + food.x] = FOOD; + num++; + } + } + while (num < max_num && rt_tick_get() - timeout < FOOD_TIMEOUT); + + return num; +} + +void map_deinit(map_t *map) +{ + if (map) + { + if (map->range) + { + rt_free(map->range); + map->range = RT_NULL; + } + rt_free(map); + } +} + +void snake_deinit(void) +{ + snake_t *node; + + while (!rt_list_isempty(&snake_head)) + { + node = rt_list_entry(snake_head.prev, snake_t, list); + rt_list_remove(&node->list); + rt_free(node); + } +} + +void food_deinit(void) +{ + +} + +SYS_STE snake_step(SNAKE_DIR dir, map_t *map) +{ + snake_t *tail, *head; + point_t node; + + ASSERT_RET(!map, RT_FALSE); + + dir = dir_adjust(dir); + + // ȡ��ͷβ�����ڵ㣬�����ڵ㲻��Ҫ�ı� + tail = rt_list_entry(snake_head.prev, snake_t, list); + head = rt_list_entry(snake_head.next, snake_t, list); + + node = head->body; + + // ����һ���µ���ͷ���� + switch (dir) + { + case SNAKE_DIR_UP: + case SNAKE_DIR_DOWN: + node.y = head->body.y + (dir == SNAKE_DIR_DOWN ? -1 : 1); + break; + case SNAKE_DIR_LEFT: + case SNAKE_DIR_RIGHT: + node.x = head->body.x + (dir == SNAKE_DIR_RIGHT ? 1 : -1); + break; + } + across_XY(&node, map); + + return node_update(tail, &node, map); +} + +rt_bool_t snake_restart(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map) +{ + ASSERT_RET(!map || !start, RT_FALSE); + + snake_deinit(); + memset(map->range, NORMAL, map->width * map->height); + + return snake_init(start, length, dir, map); +} diff --git a/bsp/simulator/rtgui_demo/snake/snake.h b/bsp/simulator/rtgui_demo/snake/snake.h index 4892ad7de9..557d4d9241 100644 --- a/bsp/simulator/rtgui_demo/snake/snake.h +++ b/bsp/simulator/rtgui_demo/snake/snake.h @@ -1,68 +1,68 @@ -#ifndef _SNAKE_H_
-#define _SNAKE_H_
-
-#include <rtthread.h>
-
-#define snake_length_max 20 //����߳�
-#define snake_length_init 3 //��ʼ���߳�
-#define snake_room_size_hight 8 //���Ӹ� 0-255 ����>8
-#define snake_room_size_widht 8 //���ӿ� 0-255 ����>8
-
-#define snake_init_pointx 1
-#define snake_init_pointy 2
-
-typedef struct
-{
- rt_int32_t x, y;
-} point_t;
-
-typedef struct
-{
- rt_int32_t width; // max x
- rt_int32_t height; // max y
- rt_uint8_t *range; // map, map->range[y * map->width + x]
- point_t snake_flush[2];
- point_t food_flush[1];
-} map_t;
-
-typedef enum
-{
- SNAKE_DIR_UP,
- SNAKE_DIR_DOWN,
- SNAKE_DIR_LEFT,
- SNAKE_DIR_RIGHT
-} SNAKE_DIR;
-
-typedef enum
-{
- FOOD, // �Ե�ˮ��
- OVER, // ҧ������
- NORMAL // �����ж�
-} SYS_STE;
-
-typedef struct
-{
- point_t body;
- rt_list_t list;
-} snake_t;
-
-// ����һ����ͼ
-map_t *map_init(rt_uint32_t width, rt_uint32_t heigth);
-
-// ����һ��ָ�����ȵ�����ָ����
-rt_bool_t snake_init(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map);
-
-// �����ʳ��
-rt_bool_t food_init(map_t *map, rt_uint32_t max_num);
-
-void map_deinit(map_t *map);
-
-void snake_deinit(void);
-
-void food_deinit(void);
-
-SYS_STE snake_step(SNAKE_DIR dir, map_t *map);
-
-rt_bool_t snake_restart(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map);
-
-#endif
+#ifndef _SNAKE_H_ +#define _SNAKE_H_ + +#include <rtthread.h> + +#define snake_length_max 20 //����߳� +#define snake_length_init 3 //��ʼ���߳� +#define snake_room_size_hight 8 //���Ӹ� 0-255 ����>8 +#define snake_room_size_widht 8 //���ӿ� 0-255 ����>8 + +#define snake_init_pointx 1 +#define snake_init_pointy 2 + +typedef struct +{ + rt_int32_t x, y; +} point_t; + +typedef struct +{ + rt_int32_t width; // max x + rt_int32_t height; // max y + rt_uint8_t *range; // map, map->range[y * map->width + x] + point_t snake_flush[2]; + point_t food_flush[1]; +} map_t; + +typedef enum +{ + SNAKE_DIR_UP, + SNAKE_DIR_DOWN, + SNAKE_DIR_LEFT, + SNAKE_DIR_RIGHT +} SNAKE_DIR; + +typedef enum +{ + FOOD, // �Ե�ˮ�� + OVER, // ҧ������ + NORMAL // �����ж� +} SYS_STE; + +typedef struct +{ + point_t body; + rt_list_t list; +} snake_t; + +// ����һ����ͼ +map_t *map_init(rt_uint32_t width, rt_uint32_t heigth); + +// ����һ��ָ�����ȵ�����ָ���� +rt_bool_t snake_init(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map); + +// �����ʳ�� +rt_bool_t food_init(map_t *map, rt_uint32_t max_num); + +void map_deinit(map_t *map); + +void snake_deinit(void); + +void food_deinit(void); + +SYS_STE snake_step(SNAKE_DIR dir, map_t *map); + +rt_bool_t snake_restart(const point_t *start, const int length, const SNAKE_DIR dir, map_t *map); + +#endif diff --git a/bsp/simulator/rtgui_demo/snake/snake_gui.c b/bsp/simulator/rtgui_demo/snake/snake_gui.c index c25e94c4ee..836355236b 100644 --- a/bsp/simulator/rtgui_demo/snake/snake_gui.c +++ b/bsp/simulator/rtgui_demo/snake/snake_gui.c @@ -1,400 +1,400 @@ -#include <string.h>
-#include <rtthread.h>
-
-#include <rtgui/rtgui.h>
-#include <rtgui/rtgui_app.h>
-#include <rtgui/widgets/container.h>
-#include <rtgui/widgets/window.h>
-#include <rtgui/widgets/button.h>
-
-#include "snake.h"
-
-#define LATTICE_SIZE (20)
-#define FOOD_MAX (8)
-
-#define WALL_COLOR RTGUI_RGB(255, 0, 0)
-#define SNAKE_COLOR RTGUI_RGB(0, 100, 200)
-#define SNAKE_HEAD_COLOR RTGUI_RGB(180, 70, 130)
-#define BACKGROUND_COLOR RTGUI_RGB(153, 153, 0)
-#define FOOD_COLOR RTGUI_RGB(128, 0, 0)
-
-static rtgui_timer_t *timer;
-static rt_size_t room_size_x, room_size_y;
-static rt_size_t lattice_size_x, lattice_size_y;
-static struct rtgui_rect room_rect, lattice_rect;
-
-map_t *map;
-SNAKE_DIR run_state;
-rt_int32_t snake_len;
-rt_int32_t food_num;
-point_t second_node;
-
-static void snake_fill_lattice(struct rtgui_dc *dc,
- rt_uint32_t x,
- rt_uint32_t y,
- rtgui_color_t color)
-{
- struct rtgui_rect rect;
-
- // coordinate conversion
- y = (lattice_size_y - 1) - y;
-
- RTGUI_DC_BC(dc) = color;
-
- rect.x1 = lattice_rect.x1 + (LATTICE_SIZE * x);
- rect.x2 = rect.x1 + LATTICE_SIZE;
- rect.x1 += 2;
-
- rect.y1 = lattice_rect.y1 + (LATTICE_SIZE * y);
- rect.y2 = rect.y1 + LATTICE_SIZE;
- rect.y1 += 2;
-
- rtgui_dc_fill_rect(dc, &rect);
-}
-
-static void snake_draw(struct rtgui_widget *widget)
-{
- struct rtgui_dc *dc;
- struct rtgui_rect rect;
- rt_uint32_t i;
-
- dc = rtgui_dc_begin_drawing(widget);
- if (dc == RT_NULL)
- {
- rt_kprintf("dc == RT_NULL\r\n");
- return;
- }
-
- /* get room size, run once frist. */
- if ((room_size_x == 0) || (room_size_y == 0))
- {
- rt_size_t tmp;
-
- rtgui_widget_get_rect(widget, &rect);
- rt_kprintf("rect => x1:%d x2:%d, y1:%d y2:%d\r\n", rect.x1, rect.x2, rect.y1, rect.y2);
-
- room_size_x = rect.x2 - rect.x1;
- room_size_y = rect.y2 - rect.y1;
- memcpy(&room_rect, &rect, sizeof(struct rtgui_rect));
- rt_kprintf("room_rect => x1:%d x2:%d, y1:%d y2:%d\r\n",
- room_rect.x1, room_rect.x2,
- room_rect.y1, room_rect.y2);
-
- lattice_size_x = (room_rect.x2 - room_rect.x1) / LATTICE_SIZE;
- lattice_size_y = (room_rect.y2 - room_rect.y1) / LATTICE_SIZE;
- lattice_size_x -= 2;
- lattice_size_y -= 2;
- rt_kprintf("lattice_size_x:%d lattice_size_y:%d\r\n",
- lattice_size_x,
- lattice_size_y);
-
- tmp = (room_rect.x2 - room_rect.x1) - (LATTICE_SIZE * lattice_size_x);
- lattice_rect.x1 = room_rect.x1 + (tmp / 2);
- lattice_rect.x2 = lattice_rect.x1 + (LATTICE_SIZE * lattice_size_x);
-
- tmp = (room_rect.y2 - room_rect.y1) - (LATTICE_SIZE * lattice_size_y);
- lattice_rect.y1 = room_rect.y1 + (tmp / 2);
- lattice_rect.y2 = lattice_rect.y1 + (LATTICE_SIZE * lattice_size_y);
- rt_kprintf("lattice_rect => x1:%d x2:%d, y1:%d y2:%d\r\n",
- lattice_rect.x1, lattice_rect.x2,
- lattice_rect.y1, lattice_rect.y2);
-
- /* create snake. */
- {
- point_t start;
- map = map_init(lattice_size_x, lattice_size_y);
- if (map != RT_NULL)
- {
- start.x = snake_init_pointx;
- start.y = snake_init_pointy;
- run_state = SNAKE_DIR_DOWN;
-
- if (snake_init(&start, snake_length_init, run_state, map))
- {
- food_num = 1;
- food_init(map, food_num);
- }
- else
- {
- map_deinit(map);
- map = RT_NULL;
- }
- }
- }
- }
-
- RTGUI_DC_BC(dc) = BACKGROUND_COLOR;
- rtgui_dc_fill_rect(dc, &room_rect);
-
- memcpy(&rect, &lattice_rect, sizeof(struct rtgui_rect));
- rect.x2 += 1;
- rect.y2 += 1;
- RTGUI_DC_FC(dc) = WALL_COLOR;
- rtgui_dc_draw_rect(dc, &rect);
-
- for (i = 1; i < lattice_size_y; i++)
- {
- memcpy(&rect, &lattice_rect, sizeof(struct rtgui_rect));
- rect.x1 += 1;
- rect.x2 -= 1;
- rtgui_dc_draw_horizontal_line(dc, rect.x1, rect.x2,
- rect.y1 + (LATTICE_SIZE * i));
- }
-
- for (i = 1; i < lattice_size_x; i++)
- {
- memcpy(&rect, &lattice_rect, sizeof(struct rtgui_rect));
- rect.y1 += 1;
- rect.y2 -= 1;
- rtgui_dc_draw_vertical_line(dc, rect.x1 + (LATTICE_SIZE * i),
- rect.y1, rect.y2);
- }
-
- /* draw snake. */
- {
- rt_int32_t x, y;
- rt_bool_t first_node = RT_TRUE;
-
- for (y = 0; y < map->height; y++)
- {
- for (x = 0; x < map->width; x++)
- {
- switch (map->range[y * map->width + x])
- {
- case NORMAL:
- break;
- case FOOD:
- snake_fill_lattice(dc, x, y, FOOD_COLOR);
- break;
- case OVER:
- if (first_node)
- {
- first_node = RT_FALSE;
- second_node.x = x;
- second_node.y = y;
- snake_fill_lattice(dc, x, y, SNAKE_HEAD_COLOR);
- }
- else
- {
- snake_fill_lattice(dc, x, y, SNAKE_COLOR);
- }
- break;
- }
- }
-
- }
- }
-
- rtgui_dc_end_drawing(dc);
-
- return;
-}
-
-static void snake_update(struct rtgui_widget *widget)
-{
- struct rtgui_dc *dc;
- rt_int32_t x, y;
- rt_uint32_t i;
-
- dc = rtgui_dc_begin_drawing(widget);
- if (dc == RT_NULL)
- {
- rt_kprintf("dc == RT_NULL\r\n");
- return;
- }
-
- snake_fill_lattice(dc, second_node.x, second_node.y, SNAKE_COLOR);
- second_node = map->snake_flush[0];
-
- for (i = 0; i < 3; i++)
- {
- if (i < 2)
- {
- x = map->snake_flush[i].x;
- y = map->snake_flush[i].y;
- }
- else
- {
- x = map->food_flush[0].x;
- y = map->food_flush[0].y;
- }
-
- if ((x >= 0) && (y >= 0))
- {
- switch (map->range[(map->width * y) + x])
- {
- case NORMAL:
- snake_fill_lattice(dc, x, y, BACKGROUND_COLOR);
- break;
- case FOOD:
- snake_fill_lattice(dc, x, y, FOOD_COLOR);
- break;
- case OVER:
- if (0 == i)
- snake_fill_lattice(dc, x, y, SNAKE_HEAD_COLOR);
- else
- snake_fill_lattice(dc, x, y, SNAKE_COLOR);
- break;
- }
- }
- }
-
- rtgui_dc_end_drawing(dc);
- return;
-}
-
-static void snake_handler(struct rtgui_widget *widget, rtgui_event_t *event)
-{
- struct rtgui_event_kbd *ekbd;
-
- ekbd = (struct rtgui_event_kbd *) event;
- if (ekbd->type == RTGUI_KEYDOWN)
- {
- switch (ekbd->key)
- {
- case RTGUIK_UP:
- rt_kprintf("RTGUIK_UP\r\n");
- run_state = SNAKE_DIR_UP;
- break;
- case RTGUIK_DOWN:
- rt_kprintf("RTGUIK_DOWN\r\n");
- run_state = SNAKE_DIR_DOWN;
- break;
- case RTGUIK_LEFT:
- rt_kprintf("RTGUIK_LEFT\r\n");
- run_state = SNAKE_DIR_LEFT;
- break;
- case RTGUIK_RIGHT:
- rt_kprintf("RTGUIK_RIGHT\r\n");
- run_state = SNAKE_DIR_RIGHT;
- break;
- default:
- break;
- }
- }
-}
-
-static rt_bool_t event_handler(struct rtgui_object *object, rtgui_event_t *event)
-{
- struct rtgui_widget *widget = RTGUI_WIDGET(object);
-
- rt_kprintf("event_handler\r\n");
-
- if (event->type == RTGUI_EVENT_PAINT)
- {
- rt_kprintf("RTGUI_EVENT_PAINT\r\n");
- rtgui_win_event_handler((struct rtgui_object *)object, event);
- snake_draw(widget);
- rtgui_timer_start(timer);
- }
- else if (event->type == RTGUI_EVENT_SHOW)
- {
- rt_kprintf("RTGUI_EVENT_SHOW\r\n");
- rtgui_win_event_handler((struct rtgui_object *)object, event);
- snake_draw(widget);
- rtgui_timer_start(timer);
- }
- else if (event->type == RTGUI_EVENT_HIDE)
- {
- rt_kprintf("RTGUI_EVENT_HIDE\r\n");
- rtgui_win_event_handler((struct rtgui_object *)object, event);
- rtgui_timer_stop(timer);
- }
- else if (event->type == RTGUI_EVENT_WIN_DEACTIVATE)
- {
- rt_kprintf("RTGUI_EVENT_WIN_DEACTIVATE\r\n");
- rtgui_win_event_handler((struct rtgui_object *)object, event);
- rtgui_timer_stop(timer);
- }
- else if (event->type == RTGUI_EVENT_KBD)
- {
- rtgui_win_event_handler((struct rtgui_object *)object, event);
- snake_handler(widget, event);
- }
- else
- {
- rt_kprintf("event->type:%d\r\n", event->type);
- return rtgui_win_event_handler((struct rtgui_object *)object, event);
- }
-
- return RT_FALSE;
-}
-
-static void timeout(struct rtgui_timer *timer, void *parameter)
-{
- struct rtgui_widget *widget;
- SYS_STE ret;
-
- if (!map)
- return;
-
- ret = snake_step(run_state, map);
- if (OVER == ret)
- return;
-
- if (FOOD == ret)
- {
- snake_len++;
- if (snake_len >= (map->width * map->height) / 3)
- {
- point_t start;
-
- start.x = snake_init_pointx;
- start.y = snake_init_pointy;
- run_state = SNAKE_DIR_DOWN;
- snake_len = snake_length_init;
-
- if (!snake_restart(&start, snake_len, run_state, map))
- {
- map_deinit(map);
- snake_deinit();
- map = RT_NULL;
- }
- }
-
- food_init(map, 1);
- }
-
- widget = RTGUI_WIDGET(parameter);
- snake_update(widget);
-}
-
-void snake_main(void)
-{
- struct rtgui_app *application;
- struct rtgui_win *win;
- rtgui_rect_t rect;
-
- application = rtgui_app_create(rt_thread_self(), "sanke_app");
- if (application != RT_NULL)
- {
- rtgui_get_screen_rect(&rect);
- rtgui_set_mainwin_rect(&rect);
- win = rtgui_mainwin_create(RT_NULL,
- "sanke_win",
- RTGUI_WIN_STYLE_MAINWIN | RTGUI_WIN_STYLE_DESTROY_ON_CLOSE);
- if (win == RT_NULL)
- {
- rt_kprintf("sanke_win create fail!\r\n");
- return;
- }
-
- rtgui_object_set_event_handler(RTGUI_OBJECT(win), event_handler);
-
- timer = rtgui_timer_create(RT_TICK_PER_SECOND / 2,
- RT_TIMER_FLAG_PERIODIC,
- timeout,
- (void *)win);
-
- rtgui_win_show(win, RT_TRUE);
-
- //�˳���ŷ���
- map_deinit(map);
- snake_deinit();
- food_deinit();
- rtgui_app_destroy(application);
- }
-}
-
-#include <finsh.h>
+#include <string.h> +#include <rtthread.h> + +#include <rtgui/rtgui.h> +#include <rtgui/rtgui_app.h> +#include <rtgui/widgets/container.h> +#include <rtgui/widgets/window.h> +#include <rtgui/widgets/button.h> + +#include "snake.h" + +#define LATTICE_SIZE (20) +#define FOOD_MAX (8) + +#define WALL_COLOR RTGUI_RGB(255, 0, 0) +#define SNAKE_COLOR RTGUI_RGB(0, 100, 200) +#define SNAKE_HEAD_COLOR RTGUI_RGB(180, 70, 130) +#define BACKGROUND_COLOR RTGUI_RGB(153, 153, 0) +#define FOOD_COLOR RTGUI_RGB(128, 0, 0) + +static rtgui_timer_t *timer; +static rt_size_t room_size_x, room_size_y; +static rt_size_t lattice_size_x, lattice_size_y; +static struct rtgui_rect room_rect, lattice_rect; + +map_t *map; +SNAKE_DIR run_state; +rt_int32_t snake_len; +rt_int32_t food_num; +point_t second_node; + +static void snake_fill_lattice(struct rtgui_dc *dc, + rt_uint32_t x, + rt_uint32_t y, + rtgui_color_t color) +{ + struct rtgui_rect rect; + + // coordinate conversion + y = (lattice_size_y - 1) - y; + + RTGUI_DC_BC(dc) = color; + + rect.x1 = lattice_rect.x1 + (LATTICE_SIZE * x); + rect.x2 = rect.x1 + LATTICE_SIZE; + rect.x1 += 2; + + rect.y1 = lattice_rect.y1 + (LATTICE_SIZE * y); + rect.y2 = rect.y1 + LATTICE_SIZE; + rect.y1 += 2; + + rtgui_dc_fill_rect(dc, &rect); +} + +static void snake_draw(struct rtgui_widget *widget) +{ + struct rtgui_dc *dc; + struct rtgui_rect rect; + rt_uint32_t i; + + dc = rtgui_dc_begin_drawing(widget); + if (dc == RT_NULL) + { + rt_kprintf("dc == RT_NULL\r\n"); + return; + } + + /* get room size, run once frist. */ + if ((room_size_x == 0) || (room_size_y == 0)) + { + rt_size_t tmp; + + rtgui_widget_get_rect(widget, &rect); + rt_kprintf("rect => x1:%d x2:%d, y1:%d y2:%d\r\n", rect.x1, rect.x2, rect.y1, rect.y2); + + room_size_x = rect.x2 - rect.x1; + room_size_y = rect.y2 - rect.y1; + memcpy(&room_rect, &rect, sizeof(struct rtgui_rect)); + rt_kprintf("room_rect => x1:%d x2:%d, y1:%d y2:%d\r\n", + room_rect.x1, room_rect.x2, + room_rect.y1, room_rect.y2); + + lattice_size_x = (room_rect.x2 - room_rect.x1) / LATTICE_SIZE; + lattice_size_y = (room_rect.y2 - room_rect.y1) / LATTICE_SIZE; + lattice_size_x -= 2; + lattice_size_y -= 2; + rt_kprintf("lattice_size_x:%d lattice_size_y:%d\r\n", + lattice_size_x, + lattice_size_y); + + tmp = (room_rect.x2 - room_rect.x1) - (LATTICE_SIZE * lattice_size_x); + lattice_rect.x1 = room_rect.x1 + (tmp / 2); + lattice_rect.x2 = lattice_rect.x1 + (LATTICE_SIZE * lattice_size_x); + + tmp = (room_rect.y2 - room_rect.y1) - (LATTICE_SIZE * lattice_size_y); + lattice_rect.y1 = room_rect.y1 + (tmp / 2); + lattice_rect.y2 = lattice_rect.y1 + (LATTICE_SIZE * lattice_size_y); + rt_kprintf("lattice_rect => x1:%d x2:%d, y1:%d y2:%d\r\n", + lattice_rect.x1, lattice_rect.x2, + lattice_rect.y1, lattice_rect.y2); + + /* create snake. */ + { + point_t start; + map = map_init(lattice_size_x, lattice_size_y); + if (map != RT_NULL) + { + start.x = snake_init_pointx; + start.y = snake_init_pointy; + run_state = SNAKE_DIR_DOWN; + + if (snake_init(&start, snake_length_init, run_state, map)) + { + food_num = 1; + food_init(map, food_num); + } + else + { + map_deinit(map); + map = RT_NULL; + } + } + } + } + + RTGUI_DC_BC(dc) = BACKGROUND_COLOR; + rtgui_dc_fill_rect(dc, &room_rect); + + memcpy(&rect, &lattice_rect, sizeof(struct rtgui_rect)); + rect.x2 += 1; + rect.y2 += 1; + RTGUI_DC_FC(dc) = WALL_COLOR; + rtgui_dc_draw_rect(dc, &rect); + + for (i = 1; i < lattice_size_y; i++) + { + memcpy(&rect, &lattice_rect, sizeof(struct rtgui_rect)); + rect.x1 += 1; + rect.x2 -= 1; + rtgui_dc_draw_horizontal_line(dc, rect.x1, rect.x2, + rect.y1 + (LATTICE_SIZE * i)); + } + + for (i = 1; i < lattice_size_x; i++) + { + memcpy(&rect, &lattice_rect, sizeof(struct rtgui_rect)); + rect.y1 += 1; + rect.y2 -= 1; + rtgui_dc_draw_vertical_line(dc, rect.x1 + (LATTICE_SIZE * i), + rect.y1, rect.y2); + } + + /* draw snake. */ + { + rt_int32_t x, y; + rt_bool_t first_node = RT_TRUE; + + for (y = 0; y < map->height; y++) + { + for (x = 0; x < map->width; x++) + { + switch (map->range[y * map->width + x]) + { + case NORMAL: + break; + case FOOD: + snake_fill_lattice(dc, x, y, FOOD_COLOR); + break; + case OVER: + if (first_node) + { + first_node = RT_FALSE; + second_node.x = x; + second_node.y = y; + snake_fill_lattice(dc, x, y, SNAKE_HEAD_COLOR); + } + else + { + snake_fill_lattice(dc, x, y, SNAKE_COLOR); + } + break; + } + } + + } + } + + rtgui_dc_end_drawing(dc); + + return; +} + +static void snake_update(struct rtgui_widget *widget) +{ + struct rtgui_dc *dc; + rt_int32_t x, y; + rt_uint32_t i; + + dc = rtgui_dc_begin_drawing(widget); + if (dc == RT_NULL) + { + rt_kprintf("dc == RT_NULL\r\n"); + return; + } + + snake_fill_lattice(dc, second_node.x, second_node.y, SNAKE_COLOR); + second_node = map->snake_flush[0]; + + for (i = 0; i < 3; i++) + { + if (i < 2) + { + x = map->snake_flush[i].x; + y = map->snake_flush[i].y; + } + else + { + x = map->food_flush[0].x; + y = map->food_flush[0].y; + } + + if ((x >= 0) && (y >= 0)) + { + switch (map->range[(map->width * y) + x]) + { + case NORMAL: + snake_fill_lattice(dc, x, y, BACKGROUND_COLOR); + break; + case FOOD: + snake_fill_lattice(dc, x, y, FOOD_COLOR); + break; + case OVER: + if (0 == i) + snake_fill_lattice(dc, x, y, SNAKE_HEAD_COLOR); + else + snake_fill_lattice(dc, x, y, SNAKE_COLOR); + break; + } + } + } + + rtgui_dc_end_drawing(dc); + return; +} + +static void snake_handler(struct rtgui_widget *widget, rtgui_event_t *event) +{ + struct rtgui_event_kbd *ekbd; + + ekbd = (struct rtgui_event_kbd *) event; + if (ekbd->type == RTGUI_KEYDOWN) + { + switch (ekbd->key) + { + case RTGUIK_UP: + rt_kprintf("RTGUIK_UP\r\n"); + run_state = SNAKE_DIR_UP; + break; + case RTGUIK_DOWN: + rt_kprintf("RTGUIK_DOWN\r\n"); + run_state = SNAKE_DIR_DOWN; + break; + case RTGUIK_LEFT: + rt_kprintf("RTGUIK_LEFT\r\n"); + run_state = SNAKE_DIR_LEFT; + break; + case RTGUIK_RIGHT: + rt_kprintf("RTGUIK_RIGHT\r\n"); + run_state = SNAKE_DIR_RIGHT; + break; + default: + break; + } + } +} + +static rt_bool_t event_handler(struct rtgui_object *object, rtgui_event_t *event) +{ + struct rtgui_widget *widget = RTGUI_WIDGET(object); + + rt_kprintf("event_handler\r\n"); + + if (event->type == RTGUI_EVENT_PAINT) + { + rt_kprintf("RTGUI_EVENT_PAINT\r\n"); + rtgui_win_event_handler((struct rtgui_object *)object, event); + snake_draw(widget); + rtgui_timer_start(timer); + } + else if (event->type == RTGUI_EVENT_SHOW) + { + rt_kprintf("RTGUI_EVENT_SHOW\r\n"); + rtgui_win_event_handler((struct rtgui_object *)object, event); + snake_draw(widget); + rtgui_timer_start(timer); + } + else if (event->type == RTGUI_EVENT_HIDE) + { + rt_kprintf("RTGUI_EVENT_HIDE\r\n"); + rtgui_win_event_handler((struct rtgui_object *)object, event); + rtgui_timer_stop(timer); + } + else if (event->type == RTGUI_EVENT_WIN_DEACTIVATE) + { + rt_kprintf("RTGUI_EVENT_WIN_DEACTIVATE\r\n"); + rtgui_win_event_handler((struct rtgui_object *)object, event); + rtgui_timer_stop(timer); + } + else if (event->type == RTGUI_EVENT_KBD) + { + rtgui_win_event_handler((struct rtgui_object *)object, event); + snake_handler(widget, event); + } + else + { + rt_kprintf("event->type:%d\r\n", event->type); + return rtgui_win_event_handler((struct rtgui_object *)object, event); + } + + return RT_FALSE; +} + +static void timeout(struct rtgui_timer *timer, void *parameter) +{ + struct rtgui_widget *widget; + SYS_STE ret; + + if (!map) + return; + + ret = snake_step(run_state, map); + if (OVER == ret) + return; + + if (FOOD == ret) + { + snake_len++; + if (snake_len >= (map->width * map->height) / 3) + { + point_t start; + + start.x = snake_init_pointx; + start.y = snake_init_pointy; + run_state = SNAKE_DIR_DOWN; + snake_len = snake_length_init; + + if (!snake_restart(&start, snake_len, run_state, map)) + { + map_deinit(map); + snake_deinit(); + map = RT_NULL; + } + } + + food_init(map, 1); + } + + widget = RTGUI_WIDGET(parameter); + snake_update(widget); +} + +void snake_main(void) +{ + struct rtgui_app *application; + struct rtgui_win *win; + rtgui_rect_t rect; + + application = rtgui_app_create(rt_thread_self(), "sanke_app"); + if (application != RT_NULL) + { + rtgui_get_screen_rect(&rect); + rtgui_set_mainwin_rect(&rect); + win = rtgui_mainwin_create(RT_NULL, + "sanke_win", + RTGUI_WIN_STYLE_MAINWIN | RTGUI_WIN_STYLE_DESTROY_ON_CLOSE); + if (win == RT_NULL) + { + rt_kprintf("sanke_win create fail!\r\n"); + return; + } + + rtgui_object_set_event_handler(RTGUI_OBJECT(win), event_handler); + + timer = rtgui_timer_create(RT_TICK_PER_SECOND / 2, + RT_TIMER_FLAG_PERIODIC, + timeout, + (void *)win); + + rtgui_win_show(win, RT_TRUE); + + //�˳���ŷ��� + map_deinit(map); + snake_deinit(); + food_deinit(); + rtgui_app_destroy(application); + } +} + +#include <finsh.h> FINSH_FUNCTION_EXPORT(snake_main, snake run)
\ No newline at end of file |
