gsmopen: adding libctb-0.16

This commit is contained in:
Giovanni Maruzzelli 2012-04-02 11:07:47 +02:00
parent fc4c61570b
commit 282a1885e7
59 changed files with 15449 additions and 0 deletions

View File

@ -0,0 +1,18 @@
Copyright
Copyright (C) 1999-2010 Joachim Buermann (jbuermann@iftools.com)
ctb is free software; you can redistribute it and/or modify it under
the term of the GNU Library General Public Licence as published by the
Free Software Foundation.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public Licence for more details
EXCEPTION NOTICE
As a special exception, you may use, copy, link, modify and distribute
under the user's own terms, binary object code versions of works based
on the library.

View File

@ -0,0 +1,293 @@
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.5 (http://www.bakefile.org)
# Do not modify, all changes will be overwritten!
# =========================================================================
# -------------------------------------------------------------------------
# These are configurable options:
# -------------------------------------------------------------------------
# 'install' program location
INSTALL ?= install
# Location where the package is installed by 'make install'
prefix ?= /usr/local
# Destination root (/ is used if empty)
DESTDIR ?=
#
AR ?= ar
#
RANLIB ?= ranlib
# Compiler flags to link shared library
LINK_DLL_FLAGS ?= -shared
# C++ compiler
CXX = g++
# Standard flags for C++
CXXFLAGS ?=
# Standard preprocessor flags (common for CC and CXX)
CPPFLAGS ?=
# Standard linker flags
LDFLAGS ?=
# Set to 1 to build debug version [0,1]
DEBUG ?= 0
#
GPIB ?= 0
# -------------------------------------------------------------------------
# Do not modify the rest of this file!
# -------------------------------------------------------------------------
### Variables: ###
CPPDEPS = -MT$@ -MF`echo $@ | sed -e 's,\.o$$,.d,'` -MD -MP
CTB_LIB_CXXFLAGS = $(____DEBUG) $(____DEBUG_1) -D_THREAD_SAFE -pthread \
$(__OPTIMIZE_FLAG) -I../include $(CPPFLAGS) $(CXXFLAGS)
CTB_LIB_OBJECTS = \
$(OUTPUT)/ctb_lib_fifo.o \
$(OUTPUT)/ctb_lib_getopt.o \
$(OUTPUT)/ctb_lib_iobase.o \
$(OUTPUT)/ctb_lib_portscan.o \
$(OUTPUT)/ctb_lib_serportx.o \
$(OUTPUT)/ctb_lib_serport.o \
$(OUTPUT)/ctb_lib_timer.o \
$(__GPIBSRC_OBJECTS)
CTB_DLL_CXXFLAGS = $(____DEBUG) $(____DEBUG_1) -D_THREAD_SAFE -pthread \
$(__OPTIMIZE_FLAG) -I../include -fPIC -DPIC $(CPPFLAGS) $(CXXFLAGS)
CTB_DLL_OBJECTS = \
$(OUTPUT)/ctb_dll_fifo.o \
$(OUTPUT)/ctb_dll_getopt.o \
$(OUTPUT)/ctb_dll_iobase.o \
$(OUTPUT)/ctb_dll_portscan.o \
$(OUTPUT)/ctb_dll_serportx.o \
$(OUTPUT)/ctb_dll_serport.o \
$(OUTPUT)/ctb_dll_timer.o \
$(__GPIBSRC_OBJECTS_1)
CTBTEST_CXXFLAGS = $(____DEBUG) $(____DEBUG_1) -DGPIB=$(GPIB) -D_THREAD_SAFE \
-pthread $(__OPTIMIZE_FLAG) -I../include $(CPPFLAGS) $(CXXFLAGS)
CTBTEST_OBJECTS = \
$(OUTPUT)/ctbtest_ctbtest.o
### Conditionally set variables: ###
ifeq ($(DEBUG),0)
OUTPUT = release
endif
ifeq ($(DEBUG),1)
OUTPUT = debug
endif
ifeq ($(DEBUG),1)
LIBFLAG = d
endif
ifeq ($(GPIB),1)
GPIBFLAG = _gpib
endif
ifeq ($(GPIB),1)
GPIBINC = gpib.h
endif
ifeq ($(GPIB),1)
__GPIBSRC_OBJECTS = \
$(OUTPUT)/ctb_lib_gpib.o
endif
ifeq ($(GPIB),1)
__GPIBSRC_OBJECTS_1 = \
$(OUTPUT)/ctb_dll_gpib.o
endif
ifeq ($(DEBUG),0)
____DEBUG = -DNDEBUG
endif
ifeq ($(DEBUG),1)
____DEBUG =
endif
ifeq ($(DEBUG),0)
__OPTIMIZE_FLAG = -O0
endif
ifeq ($(DEBUG),1)
__OPTIMIZE_FLAG = -O2
endif
ifeq ($(GPIB),1)
__SYSLIB2_p = -lgpib
endif
ifeq ($(DEBUG),0)
____DEBUG_1 =
endif
ifeq ($(DEBUG),1)
____DEBUG_1 = -g
endif
all: $(OUTPUT)
$(OUTPUT):
@mkdir -p $(OUTPUT)
### Targets: ###
all: ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so $(OUTPUT)/ctbtest tip-linux
install: install_ctb_lib install_ctb_dll
$(INSTALL) -d $(DESTDIR)$(prefix)/include/ctb-0.16
for f in ctb.h fifo.h getopt.h $(GPIBINC) iobase.h linux/serport.h linux/timer.h portscan.h serport.h serportx.h timer.h; do \
if test ! -d $(DESTDIR)$(prefix)/include/ctb-0.16/`dirname $$f` ; then \
$(INSTALL) -d $(DESTDIR)$(prefix)/include/ctb-0.16/`dirname $$f`; \
fi; \
$(INSTALL) -m 644 ../include/ctb-0.16/$$f $(DESTDIR)$(prefix)/include/ctb-0.16/$$f; \
done
uninstall: uninstall_ctb_lib uninstall_ctb_dll
for f in ctb.h fifo.h getopt.h $(GPIBINC) iobase.h linux/serport.h linux/timer.h portscan.h serport.h serportx.h timer.h; do \
rm -f $(DESTDIR)$(prefix)/include/ctb-0.16/$$f; \
done
clean:
rm -f $(OUTPUT)/*.o
rm -f $(OUTPUT)/*.d
rm -f ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
rm -f ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so
rm -f ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so
rm -f $(OUTPUT)/ctbtest
htmldoc:
(cd ..; tar -cvzf manual/libctb-0.16-htmldoc.tar.gz docs/html/ )
tarball:
(cd ../..; tar -cvzf libctb-0.16.tar.gz \
libctb-0.16/build/ \
libctb-0.16/manual/refman.pdf \
libctb-0.16/include \
libctb-0.16/python \
libctb-0.16/samples \
libctb-0.16/src \
libctb-0.16/lib/gpib32.lib \
--exclude=release \
--exclude=debug \
--exclude=install \
--exclude=output \
--exclude=website \
--exclude=*~ \
--exclude=buildall.sh \
--exclude=buildall.bat \
--exclude=version-update.sh \
--exclude=libctb-0.16.tar.gz \
--exclude=*.ilk \
--exclude=*.log \
--exclude=*.o* \
--exclude=*.pdb \
--exclude=*.pyc \
--exclude=.svn; mv libctb-0.16.tar.gz libctb-0.16/build )
../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a: $(CTB_LIB_OBJECTS)
rm -f $@
$(AR) rcu $@ $(CTB_LIB_OBJECTS)
$(RANLIB) $@
install_ctb_lib: ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
$(INSTALL) -d $(DESTDIR)$(prefix)/lib
$(INSTALL) -m 644 ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a $(DESTDIR)$(prefix)/lib
uninstall_ctb_lib:
rm -f $(DESTDIR)$(prefix)/lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so: $(CTB_DLL_OBJECTS)
$(CXX) $(LINK_DLL_FLAGS) -fPIC -o $@ $(CTB_DLL_OBJECTS) $(____DEBUG_1) -pthread -L../lib $(LDFLAGS) -lpthread $(__SYSLIB2_p)
install_ctb_dll: ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so
$(INSTALL) -d $(DESTDIR)$(prefix)/lib
$(INSTALL) -m 644 ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so $(DESTDIR)$(prefix)/lib
install -c ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so $(DESTDIR)$(prefix)/lib
uninstall_ctb_dll:
rm -f $(DESTDIR)$(prefix)/lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so
rm -f $(DESTDIR)$(prefix)/lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.so
$(OUTPUT)/ctbtest: $(CTBTEST_OBJECTS) ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
$(CXX) -o $@ $(CTBTEST_OBJECTS) $(____DEBUG_1) -pthread -L../lib $(LDFLAGS) ../lib/libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a -lpthread $(__SYSLIB2_p)
tip-linux:
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. On Linux you'll now"
@echo " have to run (as root):"
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) install"
@echo " "
@echo " to install the libraries in $(prefix)/lib"
@echo " and the header files in $(prefix)/include/ctb-0.16"
@echo " "
@echo " Don't forget to run ldconfig (also as root)"
@echo " "
@echo " ctb comes with no guarantees and doesn't claim"
@echo " to be suitable for any purpose."
@echo "================================================================"
@echo " "
$(OUTPUT)/ctb_lib_fifo.o: ./../src/fifo.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_getopt.o: ./../src/getopt.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_iobase.o: ./../src/iobase.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_portscan.o: ./../src/portscan.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_serportx.o: ./../src/serportx.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_serport.o: ./../src/linux/serport.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_timer.o: ./../src/linux/timer.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_lib_gpib.o: ./../src/gpib.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_fifo.o: ./../src/fifo.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_getopt.o: ./../src/getopt.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_iobase.o: ./../src/iobase.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_portscan.o: ./../src/portscan.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_serportx.o: ./../src/serportx.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_serport.o: ./../src/linux/serport.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_timer.o: ./../src/linux/timer.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctb_dll_gpib.o: ./../src/gpib.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)/ctbtest_ctbtest.o: ./../samples/ctbtest.cpp
$(CXX) -c -o $@ $(CTBTEST_CXXFLAGS) $(CPPDEPS) $<
.PHONY: all install uninstall clean install_ctb_lib uninstall_ctb_lib \
install_ctb_dll uninstall_ctb_dll
# Dependencies tracking:
-include $(OUTPUT)/*.d

View File

@ -0,0 +1,169 @@
CTB (Communication toolbox library) 08.02.2010
======================================================================
Website: http://www.iftools.com/opensource/ctb.en.php
Version: 0.16
Linux GCC compiliation
----------------------------------------------------------------
Type 'make DEBUG=x GPIB=x' or 'make -f GNUmakefile DEBUG=x GPIB=x'
Type the same command with an additional install as root to copy the
headers and libs to there according system places
(i.e. /usr/local/include/ctb-0.16 and /usr/local/lib/libctb-0.16.a)
like:
sudo make DEBUG=x GPIB=x install
Microsoft MingW32 compilation
----------------------------------------------------------------
Type mingw32-make -f makefile.gcc DEBUG=x GPIB=x
Please note! Currently only a shared ctb library will be created.
You have to copy the ctb-VERSION.dll in the application path of
your application linked with ctb or in a global dll folder (but
not recommented!)
Microsoft Visual C++ compilation
----------------------------------------------------------------
Type 'nmake -f makefile.vc DEBUG=x GPIB=x'
To create all libs (debug/release with and without gpib support)
just input: ./buildall.bat in the build folder.
Borland C++ 5.0/5.5 compilation
----------------------------------------------------------------
Type 'make -f makefile.bcc DEBUG=x GPIB=x'
Watcom C++ 10.6/11 and OpenWatcom compilation
----------------------------------------------------------------
Type 'wmake -f makefile.wat'
Python support
--------------
Since version 0.9 ctb also includes a python module ctb.py.
To build the python module by yourself, your system has to satisfy
the following requirements:
- the SWIG program, you get it at http://www.swig.org/ (for linux,
take a look in your favorite distribution package manager).
The current ctb module was build with SWIG version 1.3.29 (linux)
and version 1.3.40 (Windows)
- the develop files for python (means the header and the library
files). I tested it with Python 2.4. You will get it at:
http://www.python.org/ftp/python/2.4.4/python-2.4.4.msi
- if you want to communicate via GPIB, a GPIB installation (GPIB
controller and software, for instance a Nation Instruments or
Keithley card). On Linux the libgpib.
Like the building of the wxctb C++ library, you also can choose
between GPIB and non GPIB (default) support.
Compile the python module
Linux
cd in the python/src/linux folder and type:
./makepy.sh USE_GPIB
or
./makepy.sh
if you don't need any GPIB support
Windows
cd in the python/src/windows folder. Open the makepy.bat with your
favorite editor and set the commented enviroment variables. See the
makepy.bat file for more information, how you can do that.
After that, just type:
./makepy.sh USE_GPIB
(for GPIB support) or
./makepy.sh
if you don't need any GPIB support
At last set the python modul path to the ctb-0.15/python/module
path.
On linux:
export PYTHONPATH=somepath/ctb-0.15/python/module/linux
On Windows:
set PYTHONPATH=drive:\somepath\ctb-0.15\python\module\win32
ChangeLog
---------
0.16
- added port scan function.
- bug fixes for MingW build.
0.15
- added ctb namespace and removed all wx prefix (also in the header
path).
- Linux: A serial port cannot opened twice or more any longer.
- 9 bit data transmission support using the parity bit as ninth bit.
- improved documentation
- Some more documentation
0.14
- Support for non-standard baudrates (depends on the used UART
or USB to RS232 converter.
0.13
- remove the expect and match mechanism. They didn't work very
well, and a future implementation should be done as a
independent library. If someone missed this functions, please
let me know.
0.12
- more documentation for doxygen
- replace the ugly GetSettingsAsString methods by a more intuitive
one.
- wxGPIB::Read now checks the MAV bit before reading. This resolves
some stderr stuff on linux.
0.11
- the gpib sources are no longer depending on the OS. They are
identical for linux and windows.
- add the current version to the ctb include path, so you can
handle a parallel installation of different versions.
For instance: The header path wx/ctb is replaced by wx/ctb-0.11
0.10
- replace the former gpib async io access with the standard
NI-488 functions (ibrd,ibwrt). To avoid blocking, the internal
gpib timeout was set to the lowest value, whereas the wxIOBase
methods handles the timeout in a global and transparent manner.
- add a FindListener method in the wxGPIB class to look for all
connected gpib devices (listeners).
- The Read and Readv method of the python wxIOBase class returns
additional zero bytes, fixed.
0.9
- added python support for both, serial and gpib
0.8
- added bakefile support
0.7
- added GPIB (Nation Instruments GPIB cards) support
Authors' info
-------------
Joachim Buermann jbuermann@iftools.com

View File

@ -0,0 +1,281 @@
<?xml version="1.0" ?>
<makefile>
<requires version="0.1.1"/>
<include file="presets/simple.bkl"/>
<using module="datafiles"/>
<!-- default is NO GPIB support, you can change this by -->
<!-- calling make with the Option GPIB=1 -->
<option name="GPIB">
<default-value>0</default-value>
</option>
<!-- the actual ctb library version -->
<set var="VERSION">0.16</set>
<set var="NAME">libctb</set>
<!-- The directory where wxWidgets is installed: -->
<set var="ENV_VAR">
<if cond="FORMAT=='watcom'">%</if>
<if cond="FORMAT!='watcom'"></if>
</set>
<option name="WXDIR">
<default-value>$(DOLLAR)($(ENV_VAR)WXWIN)</default-value>
</option>
<option name="INSTALLDIR">
<default-value>$(DOLLAR)($(ENV_VAR)WXWIN)</default-value>
</option>
<!-- the output of the compiler/linker will be put in a release -->
<!-- or debug folder! -->
<set var="OUTPUT">
<if cond="DEBUG=='1'">debug</if>
<if cond="DEBUG=='0'">release</if>
</set>
<set var="BUILDDIR">$(OUTPUT)</set>
<set var="INSTALLDIR">
<if cond="PLATFORM_WIN32=='1' and WXDIR==''">..$(DIRSEP)lib</if>
</set>
<!-- set the library name dependent on debug/gpib support -->
<set var="LIBFLAG">
<if cond="DEBUG=='1'">d</if>
</set>
<set var="SYSLIB1">
<if cond="PLATFORM_UNIX=='1'">pthread</if>
<if cond="PLATFORM_WIN32=='1'">winmm</if>
</set>
<set var="SYSLIB2">
<if cond="PLATFORM_UNIX=='1' and GPIB=='1'">gpib</if>
<if cond="PLATFORM_WIN32=='1' and GPIB=='1'">gpib32</if>
</set>
<set var="OS">
<if cond="PLATFORM_UNIX=='1'">linux</if>
<if cond="PLATFORM_WIN32=='1'">win32</if>
</set>
<set var="GPIBFLAG">
<if cond="GPIB=='1'">_gpib</if>
</set>
<set var="GPIBSRC">
<if cond="GPIB=='1'">
../src/gpib.cpp
</if>
</set>
<set var="GPIBINC">
<if cond="GPIB=='1'">
gpib.h
</if>
</set>
<set var="OPTIMIZE_FLAG">
<if cond="DEBUG=='0'">off</if>
<if cond="DEBUG=='1'">speed</if>
</set>
<set var="FILES">
../src/fifo.cpp
../src/getopt.cpp
../src/iobase.cpp
../src/portscan.cpp
../src/serportx.cpp
../src/$(OS)/serport.cpp
../src/$(OS)/timer.cpp
</set>
<define-tag name="run-htmldoc" rules="action">
<command>
(cd ..; tar -cvzf manual/$(value) docs/html/ )
</command>
</define-tag>
<if cond="PLATFORM_UNIX=='1'">
<action id="htmldoc">
<run-htmldoc>$(NAME)-$(VERSION)-htmldoc.tar.gz</run-htmldoc>
</action>
</if>
<define-tag name="run-tarball" rules="action">
<command>
(cd ../..; tar -cvzf $(value) \
$(NAME)-$(VERSION)/build/ \
$(NAME)-$(VERSION)/manual/refman.pdf \
$(NAME)-$(VERSION)/include \
$(NAME)-$(VERSION)/python \
$(NAME)-$(VERSION)/samples \
$(NAME)-$(VERSION)/src \
$(NAME)-$(VERSION)/lib/gpib32.lib \
--exclude=release \
--exclude=debug \
--exclude=install \
--exclude=output \
--exclude=website \
--exclude=*~ \
--exclude=buildall.sh \
--exclude=buildall.bat \
--exclude=g++.sh \
--exclude=version-update.sh \
--exclude=$(value) \
--exclude=*.ilk \
--exclude=*.log \
--exclude=*.o* \
--exclude=*.pdb \
--exclude=*.pyc \
--exclude=.svn; mv $(value) $(NAME)-$(VERSION)/build )
</command>
</define-tag>
<if cond="PLATFORM_UNIX=='1'">
<action id="tarball">
<run-tarball>$(NAME)-$(VERSION).tar.gz</run-tarball>
</action>
</if>
<!-- This is only for UNIX like OS -->
<data-files-tree id="install-headers">
<srcdir>..$(DIRSEP)include$(DIRSEP)ctb-$(VERSION)</srcdir>
<files>
ctb.h
fifo.h
getopt.h
$(GPIBINC)
iobase.h
linux/serport.h
linux/timer.h
portscan.h
serport.h
serportx.h
timer.h
</files>
<install-to>$(INCLUDEDIR)$(DIRSEP)ctb-$(VERSION)</install-to>
</data-files-tree>
<lib id="ctb_lib" template="simple">
<dirname>../lib</dirname>
<libname>ctb$(LIBFLAG)$(GPIBFLAG)-$(VERSION)</libname>
<!-- for /MT -->
<threading>multi</threading>
<runtime-libs>static</runtime-libs>
<optimize>$(OPTIMIZE_FLAG)</optimize>
<sources>
$(FILES)
$(GPIBSRC)
</sources>
<lib-path>../lib</lib-path>
<sys-lib>$(SYSLIB1)</sys-lib>
<sys-lib>$(SYSLIB2)</sys-lib>
<include>../include</include>
<install-to>$(LIBDIR)</install-to>
</lib>
<dll id="ctb_dll" template="simple">
<dirname>../lib</dirname>
<threading>multi</threading>
<dllname>ctb$(LIBFLAG)$(GPIBFLAG)-$(VERSION)</dllname>
<runtime-libs>static</runtime-libs>
<optimize>$(OPTIMIZE_FLAG)</optimize>
<libname>ctb$(LIBFLAG)$(GPIBFLAG)-$(VERSION)</libname>
<sources>
$(FILES)
$(GPIBSRC)
</sources>
<lib-path>../lib</lib-path>
<sys-lib>$(SYSLIB1)</sys-lib>
<sys-lib>$(SYSLIB2)</sys-lib>
<include>../include</include>
<install-to>$(LIBDIR)</install-to>
</dll>
<!-- The sample of ctb -->
<!-- ==================== -->
<exe id="ctbtest" template="simple">
<define>GPIB=$(GPIB)</define>
<threading>multi</threading>
<runtime-libs>static</runtime-libs>
<optimize>$(OPTIMIZE_FLAG)</optimize>
<sources>
../samples/ctbtest.cpp
</sources>
<include>../include</include>
<lib-path>../lib</lib-path>
<library>ctb_lib</library>
<sys-lib>$(SYSLIB1)</sys-lib>
<sys-lib>$(SYSLIB2)</sys-lib>
</exe>
<set var="LIBNAME">
<if cond="FORMAT=='msvc'">vc</if>
<if cond="FORMAT!='msvc'">$(FORMAT)</if>
</set>
<action id="wxinstall" cond="PLATFORM_WIN32=='1'">
<command>
<!-- create the lib directory if it doesn't exist -->
@if not exist $(INSTALLDIR)\lib\$(LIBNAME)_lib mkdir $(INSTALLDIR)\lib\$(LIBNAME)_lib
<!-- copy the libraries (lib,dll) -->
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-$(VERSION).lib $(INSTALLDIR)\lib\$(LIBNAME)_lib
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-$(VERSION).dll $(INSTALLDIR)\lib\$(LIBNAME)_lib
<!-- copy the header files -->
@if not exist $(INSTALLDIR)\include\ctb-$(VERSION)\win32 mkdir $(INSTALLDIR)\include\ctb-$(VERSION)\win32
@copy ..\include\ctb-$(VERSION)\*.h $(INSTALLDIR)\include\ctb-$(VERSION)
@copy ..\include\ctb-$(VERSION)\win32\*.h $(INSTALLDIR)\include\ctb-$(VERSION)\win32
</command>
</action>
<action id="tip-linux" cond="PLATFORM_UNIX=='1'">
<dependency-of>all</dependency-of>
<command>
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. On Linux you'll now"
@echo " have to run (as root):"
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) install"
@echo " "
@echo " to install the libraries in $(LIBDIR)"
@echo " and the header files in $(INCLUDEDIR)/ctb-$(VERSION)"
@echo " "
@echo " Don't forget to run ldconfig (also as root)"
@echo " "
@echo " ctb comes with no guarantees and doesn't claim"
@echo " to be suitable for any purpose."
@echo "================================================================"
@echo " "
</command>
</action>
<action id="tip-win32" cond="PLATFORM_WIN32=='1'">
<dependency-of>all</dependency-of>
<command>
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. If you have an installed "
@echo " wxWidget package (WXWIN must be defined in the enviroment), "
@echo " you'll now have to run: "
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) wxinstall "
@echo " "
@echo " to install the libraries in: "
@echo " $(INSTALLDIR)$(DIRSEP)lib$(DIRSEP)$(LIBNAME)_lib "
@echo " and the header files in"
@echo " $(INSTALLDIR)$(DIRSEP)ctb-$(VERSION)"
@echo " "
@echo " If you are using another compiler (Borland, Watcom, mingw,...) "
@echo " take a look in the README in this directory! "
@echo " "
@echo " ctb comes with no guarantees and doesn't claim "
@echo " to be suitable for any purpose. "
@echo "================================================================"
@echo " "
</command>
</action>
</makefile>

View File

@ -0,0 +1,269 @@
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.5 (http://www.bakefile.org)
# Do not modify, all changes will be overwritten!
# =========================================================================
.autodepend
!ifndef BCCDIR
!ifndef MAKEDIR
!error Your Borland compiler does not define MAKEDIR. Please define the BCCDIR variable, e.g. BCCDIR=d:\bc4
!endif
BCCDIR = $(MAKEDIR)\..
!endif
# -------------------------------------------------------------------------
# These are configurable options:
# -------------------------------------------------------------------------
# C++ compiler
!ifndef CXX
CXX = bcc32
!endif
# Standard flags for C++
!ifndef CXXFLAGS
CXXFLAGS =
!endif
# Standard preprocessor flags (common for CC and CXX)
!ifndef CPPFLAGS
CPPFLAGS = -a8 -g0
!endif
# Standard linker flags
!ifndef LDFLAGS
LDFLAGS =
!endif
# Set to 1 to build debug version [0,1]
!ifndef DEBUG
DEBUG = 0
!endif
#
!ifndef GPIB
GPIB = 0
!endif
#
!ifndef WXDIR
WXDIR = $(WXWIN)
!endif
#
!ifndef INSTALLDIR
INSTALLDIR = $(WXWIN)
!endif
# -------------------------------------------------------------------------
# Do not modify the rest of this file!
# -------------------------------------------------------------------------
### Variables: ###
CTB_LIB_CXXFLAGS = -I$(BCCDIR)\include $(____DEBUG) $(____DEBUG_2) -tWM \
$(__OPTIMIZE_FLAG) -I..\include $(CPPFLAGS) $(CXXFLAGS)
CTB_LIB_OBJECTS = \
$(OUTPUT)\ctb_lib_fifo.obj \
$(OUTPUT)\ctb_lib_getopt.obj \
$(OUTPUT)\ctb_lib_iobase.obj \
$(OUTPUT)\ctb_lib_portscan.obj \
$(OUTPUT)\ctb_lib_serportx.obj \
$(OUTPUT)\ctb_lib_serport.obj \
$(OUTPUT)\ctb_lib_timer.obj \
$(____GPIBSRC_FILENAMES_OBJECTS)
CTB_DLL_CXXFLAGS = -I$(BCCDIR)\include $(____DEBUG) $(____DEBUG_2) -tWM \
$(__OPTIMIZE_FLAG) -I..\include $(CPPFLAGS) $(CXXFLAGS)
CTB_DLL_OBJECTS = \
$(OUTPUT)\ctb_dll_fifo.obj \
$(OUTPUT)\ctb_dll_getopt.obj \
$(OUTPUT)\ctb_dll_iobase.obj \
$(OUTPUT)\ctb_dll_portscan.obj \
$(OUTPUT)\ctb_dll_serportx.obj \
$(OUTPUT)\ctb_dll_serport.obj \
$(OUTPUT)\ctb_dll_timer.obj \
$(____GPIBSRC_FILENAMES_1_OBJECTS)
CTBTEST_CXXFLAGS = -I$(BCCDIR)\include $(____DEBUG) $(____DEBUG_2) \
-DGPIB=$(GPIB) -tWM $(__OPTIMIZE_FLAG) -I..\include $(CPPFLAGS) $(CXXFLAGS)
CTBTEST_OBJECTS = \
$(OUTPUT)\ctbtest_ctbtest.obj
### Conditionally set variables: ###
!if "$(DEBUG)" == "0"
OUTPUT = release
!endif
!if "$(DEBUG)" == "1"
OUTPUT = debug
!endif
!if "$(WXDIR)" == ""
INSTALLDIR = ..\lib
!endif
!if "$(DEBUG)" == "1"
LIBFLAG = d
!endif
!if "$(GPIB)" == "1"
GPIBFLAG = _gpib
!endif
!if "$(GPIB)" == "1"
____GPIBSRC_FILENAMES_OBJECTS = \
$(OUTPUT)\ctb_lib_gpib.obj
!endif
!if "$(GPIB)" == "1"
____GPIBSRC_FILENAMES_1_OBJECTS = \
$(OUTPUT)\ctb_dll_gpib.obj
!endif
!if "$(DEBUG)" == "0"
____DEBUG = -DNDEBUG
!endif
!if "$(DEBUG)" == "1"
____DEBUG =
!endif
!if "$(DEBUG)" == "0"
__OPTIMIZE_FLAG = -Od
!endif
!if "$(DEBUG)" == "1"
__OPTIMIZE_FLAG = -O2
!endif
!if "$(GPIB)" == "1"
__SYSLIB2_p = gpib32.lib
!endif
!if "$(DEBUG)" == "0"
____DEBUG_2 = -v-
!endif
!if "$(DEBUG)" == "1"
____DEBUG_2 = -v
!endif
all: $(OUTPUT)
$(OUTPUT):
-if not exist $(OUTPUT) mkdir $(OUTPUT)
### Targets: ###
all: ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(OUTPUT)\ctbtest.exe tip-win32
clean:
-if exist $(OUTPUT)\*.obj del $(OUTPUT)\*.obj
-if exist $(OUTPUT)\*.res del $(OUTPUT)\*.res
-if exist $(OUTPUT)\*.csm del $(OUTPUT)\*.csm
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.tds del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.tds
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ilc del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ilc
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ild del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ild
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ilf del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ilf
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ils del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ils
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
-if exist $(OUTPUT)\ctbtest.exe del $(OUTPUT)\ctbtest.exe
-if exist $(OUTPUT)\ctbtest.tds del $(OUTPUT)\ctbtest.tds
-if exist $(OUTPUT)\ctbtest.ilc del $(OUTPUT)\ctbtest.ilc
-if exist $(OUTPUT)\ctbtest.ild del $(OUTPUT)\ctbtest.ild
-if exist $(OUTPUT)\ctbtest.ilf del $(OUTPUT)\ctbtest.ilf
-if exist $(OUTPUT)\ctbtest.ils del $(OUTPUT)\ctbtest.ils
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib: $(CTB_LIB_OBJECTS)
if exist $@ del $@
tlib /a /p4096 $@ @&&|
$(CTB_LIB_OBJECTS)
|
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll: $(CTB_DLL_OBJECTS)
ilink32 -Tpd -q -L$(BCCDIR)\lib -L$(BCCDIR)\lib\psdk $(____DEBUG_2) -L..\lib $(LDFLAGS) @&&|
c0d32.obj $(CTB_DLL_OBJECTS),$@,, winmm.lib $(__SYSLIB2_p) import32.lib cw32mt.lib,,
|
implib -f ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16 $@
$(OUTPUT)\ctbtest.exe: $(CTBTEST_OBJECTS) ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
ilink32 -Tpe -q -L$(BCCDIR)\lib -L$(BCCDIR)\lib\psdk $(____DEBUG_2) -L..\lib $(LDFLAGS) @&&|
c0x32.obj $(CTBTEST_OBJECTS),$@,, ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib winmm.lib $(__SYSLIB2_p) import32.lib cw32mt.lib,,
|
wxinstall:
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib $(INSTALLDIR)\lib\borland_lib
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(INSTALLDIR)\lib\borland_lib
@if not exist $(INSTALLDIR)\include\ctb-0.16\win32 mkdir $(INSTALLDIR)\include\ctb-0.16\win32
@copy ..\include\ctb-0.16\*.h $(INSTALLDIR)\include\ctb-0.16
@copy ..\include\ctb-0.16\win32\*.h $(INSTALLDIR)\include\ctb-0.16\win32
tip-win32:
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. If you have an installed "
@echo " wxWidget package (WXWIN must be defined in the enviroment), "
@echo " you'll now have to run: "
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) wxinstall "
@echo " "
@echo " to install the libraries in: "
@echo " $(INSTALLDIR)\lib\borland_lib "
@echo " and the header files in"
@echo " $(INSTALLDIR)\ctb-0.16"
@echo " "
@echo " If you are using another compiler (Borland, Watcom, mingw,...) "
@echo " take a look in the README in this directory! "
@echo " "
@echo " ctb comes with no guarantees and doesn't claim "
@echo " to be suitable for any purpose. "
@echo "================================================================"
@echo " "
$(OUTPUT)\ctb_lib_fifo.obj: .\..\src\fifo.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\fifo.cpp
$(OUTPUT)\ctb_lib_getopt.obj: .\..\src\getopt.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\getopt.cpp
$(OUTPUT)\ctb_lib_iobase.obj: .\..\src\iobase.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\iobase.cpp
$(OUTPUT)\ctb_lib_portscan.obj: .\..\src\portscan.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\portscan.cpp
$(OUTPUT)\ctb_lib_serportx.obj: .\..\src\serportx.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\serportx.cpp
$(OUTPUT)\ctb_lib_serport.obj: .\..\src\win32\serport.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\win32\serport.cpp
$(OUTPUT)\ctb_lib_timer.obj: .\..\src\win32\timer.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\win32\timer.cpp
$(OUTPUT)\ctb_lib_gpib.obj: .\..\src\gpib.cpp
$(CXX) -q -c -P -o$@ $(CTB_LIB_CXXFLAGS) .\..\src\gpib.cpp
$(OUTPUT)\ctb_dll_fifo.obj: .\..\src\fifo.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\fifo.cpp
$(OUTPUT)\ctb_dll_getopt.obj: .\..\src\getopt.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\getopt.cpp
$(OUTPUT)\ctb_dll_iobase.obj: .\..\src\iobase.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\iobase.cpp
$(OUTPUT)\ctb_dll_portscan.obj: .\..\src\portscan.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\portscan.cpp
$(OUTPUT)\ctb_dll_serportx.obj: .\..\src\serportx.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\serportx.cpp
$(OUTPUT)\ctb_dll_serport.obj: .\..\src\win32\serport.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\win32\serport.cpp
$(OUTPUT)\ctb_dll_timer.obj: .\..\src\win32\timer.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\win32\timer.cpp
$(OUTPUT)\ctb_dll_gpib.obj: .\..\src\gpib.cpp
$(CXX) -q -c -P -o$@ $(CTB_DLL_CXXFLAGS) .\..\src\gpib.cpp
$(OUTPUT)\ctbtest_ctbtest.obj: .\..\samples\ctbtest.cpp
$(CXX) -q -c -P -o$@ $(CTBTEST_CXXFLAGS) .\..\samples\ctbtest.cpp

View File

@ -0,0 +1,238 @@
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.5 (http://www.bakefile.org)
# Do not modify, all changes will be overwritten!
# =========================================================================
# -------------------------------------------------------------------------
# These are configurable options:
# -------------------------------------------------------------------------
# Compiler flags to link shared library
LINK_DLL_FLAGS ?= -shared
# C++ compiler
CXX = g++
# Standard flags for C++
CXXFLAGS ?=
# Standard preprocessor flags (common for CC and CXX)
CPPFLAGS ?=
# Standard linker flags
LDFLAGS ?=
# Set to 1 to build debug version [0,1]
DEBUG ?= 0
#
GPIB ?= 0
#
WXDIR ?= $(WXWIN)
#
INSTALLDIR ?= $(WXWIN)
# -------------------------------------------------------------------------
# Do not modify the rest of this file!
# -------------------------------------------------------------------------
### Variables: ###
CPPDEPS = -MT$@ -MF$@.d -MD -MP
CTB_LIB_CXXFLAGS = $(____DEBUG) $(____DEBUG_1) -mthreads $(__OPTIMIZE_FLAG) \
-I..\include $(CPPFLAGS) $(CXXFLAGS)
CTB_LIB_OBJECTS = \
$(OUTPUT)\ctb_lib_fifo.o \
$(OUTPUT)\ctb_lib_getopt.o \
$(OUTPUT)\ctb_lib_iobase.o \
$(OUTPUT)\ctb_lib_portscan.o \
$(OUTPUT)\ctb_lib_serportx.o \
$(OUTPUT)\ctb_lib_serport.o \
$(OUTPUT)\ctb_lib_timer.o \
$(____GPIBSRC_FILENAMES_OBJECTS)
CTB_DLL_CXXFLAGS = $(____DEBUG) $(____DEBUG_1) -mthreads $(__OPTIMIZE_FLAG) \
-I..\include $(CPPFLAGS) $(CXXFLAGS)
CTB_DLL_OBJECTS = \
$(OUTPUT)\ctb_dll_fifo.o \
$(OUTPUT)\ctb_dll_getopt.o \
$(OUTPUT)\ctb_dll_iobase.o \
$(OUTPUT)\ctb_dll_portscan.o \
$(OUTPUT)\ctb_dll_serportx.o \
$(OUTPUT)\ctb_dll_serport.o \
$(OUTPUT)\ctb_dll_timer.o \
$(____GPIBSRC_FILENAMES_1_OBJECTS)
CTBTEST_CXXFLAGS = $(____DEBUG) $(____DEBUG_1) -DGPIB=$(GPIB) -mthreads \
$(__OPTIMIZE_FLAG) -I..\include $(CPPFLAGS) $(CXXFLAGS)
CTBTEST_OBJECTS = \
$(OUTPUT)\ctbtest_ctbtest.o
### Conditionally set variables: ###
ifeq ($(DEBUG),0)
OUTPUT = release
endif
ifeq ($(DEBUG),1)
OUTPUT = debug
endif
ifeq ($(WXDIR),)
INSTALLDIR = ..\lib
endif
ifeq ($(DEBUG),1)
LIBFLAG = d
endif
ifeq ($(GPIB),1)
GPIBFLAG = _gpib
endif
ifeq ($(GPIB),1)
____GPIBSRC_FILENAMES_OBJECTS = \
$(OUTPUT)\ctb_lib_gpib.o
endif
ifeq ($(GPIB),1)
____GPIBSRC_FILENAMES_1_OBJECTS = \
$(OUTPUT)\ctb_dll_gpib.o
endif
ifeq ($(DEBUG),0)
____DEBUG = -DNDEBUG
endif
ifeq ($(DEBUG),1)
____DEBUG =
endif
ifeq ($(DEBUG),0)
__OPTIMIZE_FLAG = -O0
endif
ifeq ($(DEBUG),1)
__OPTIMIZE_FLAG = -O2
endif
ifeq ($(GPIB),1)
__SYSLIB2_p = -lgpib32
endif
ifeq ($(DEBUG),0)
____DEBUG_1 =
endif
ifeq ($(DEBUG),1)
____DEBUG_1 = -g
endif
all: $(OUTPUT)
$(OUTPUT):
-if not exist $(OUTPUT) mkdir $(OUTPUT)
### Targets: ###
all: ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(OUTPUT)\ctbtest.exe tip-win32
clean:
-if exist $(OUTPUT)\*.o del $(OUTPUT)\*.o
-if exist $(OUTPUT)\*.d del $(OUTPUT)\*.d
-if exist ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a del ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll
-if exist ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a del ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
-if exist $(OUTPUT)\ctbtest.exe del $(OUTPUT)\ctbtest.exe
..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a: $(CTB_LIB_OBJECTS)
if exist $@ del $@
ar rcu $@ $(CTB_LIB_OBJECTS)
ranlib $@
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll: $(CTB_DLL_OBJECTS)
$(CXX) $(LINK_DLL_FLAGS) -fPIC -o $@ $(CTB_DLL_OBJECTS) $(____DEBUG_1) -mthreads -Wl,--out-implib=..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a -L..\lib $(LDFLAGS) -lwinmm $(__SYSLIB2_p)
$(OUTPUT)\ctbtest.exe: $(CTBTEST_OBJECTS) ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a
$(CXX) -o $@ $(CTBTEST_OBJECTS) $(____DEBUG_1) -mthreads -L..\lib $(LDFLAGS) ..\lib\libctb$(LIBFLAG)$(GPIBFLAG)-0.16.a -lwinmm $(__SYSLIB2_p)
wxinstall:
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib $(INSTALLDIR)\lib\mingw_lib
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(INSTALLDIR)\lib\mingw_lib
@if not exist $(INSTALLDIR)\include\ctb-0.16\win32 mkdir $(INSTALLDIR)\include\ctb-0.16\win32
@copy ..\include\ctb-0.16\*.h $(INSTALLDIR)\include\ctb-0.16
@copy ..\include\ctb-0.16\win32\*.h $(INSTALLDIR)\include\ctb-0.16\win32
tip-win32:
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. If you have an installed "
@echo " wxWidget package (WXWIN must be defined in the enviroment), "
@echo " you'll now have to run: "
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) wxinstall "
@echo " "
@echo " to install the libraries in: "
@echo " $(INSTALLDIR)\lib\mingw_lib "
@echo " and the header files in"
@echo " $(INSTALLDIR)\ctb-0.16"
@echo " "
@echo " If you are using another compiler (Borland, Watcom, mingw,...) "
@echo " take a look in the README in this directory! "
@echo " "
@echo " ctb comes with no guarantees and doesn't claim "
@echo " to be suitable for any purpose. "
@echo "================================================================"
@echo " "
$(OUTPUT)\ctb_lib_fifo.o: ./../src/fifo.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_getopt.o: ./../src/getopt.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_iobase.o: ./../src/iobase.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_portscan.o: ./../src/portscan.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_serportx.o: ./../src/serportx.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_serport.o: ./../src/win32/serport.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_timer.o: ./../src/win32/timer.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_lib_gpib.o: ./../src/gpib.cpp
$(CXX) -c -o $@ $(CTB_LIB_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_fifo.o: ./../src/fifo.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_getopt.o: ./../src/getopt.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_iobase.o: ./../src/iobase.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_portscan.o: ./../src/portscan.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_serportx.o: ./../src/serportx.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_serport.o: ./../src/win32/serport.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_timer.o: ./../src/win32/timer.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctb_dll_gpib.o: ./../src/gpib.cpp
$(CXX) -c -o $@ $(CTB_DLL_CXXFLAGS) $(CPPDEPS) $<
$(OUTPUT)\ctbtest_ctbtest.o: ./../samples/ctbtest.cpp
$(CXX) -c -o $@ $(CTBTEST_CXXFLAGS) $(CPPDEPS) $<
.PHONY: all clean
SHELL := $(COMSPEC)
# Dependencies tracking:
-include $(OUTPUT)/*.d

View File

@ -0,0 +1,260 @@
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.5 (http://www.bakefile.org)
# Do not modify, all changes will be overwritten!
# =========================================================================
# -------------------------------------------------------------------------
# These are configurable options:
# -------------------------------------------------------------------------
# C++ compiler
CXX = cl
# Standard flags for C++
CXXFLAGS =
# Standard preprocessor flags (common for CC and CXX)
CPPFLAGS =
# Standard linker flags
LDFLAGS =
# Set to 1 to build debug version [0,1]
# 0 - Release
# 1 - Debug
DEBUG = 0
#
GPIB = 0
#
WXDIR = $(WXWIN)
#
INSTALLDIR = $(WXWIN)
# -------------------------------------------------------------------------
# Do not modify the rest of this file!
# -------------------------------------------------------------------------
### Variables: ###
CTB_LIB_CXXFLAGS = /MT$(____DEBUG_4) /DWIN32 $(____DEBUG) $(____DEBUG_2) \
$(______DEBUG) /Fd..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.pdb \
$(__OPTIMIZE_FLAG) /I..\include /GR /EHsc $(CPPFLAGS) $(CXXFLAGS)
CTB_LIB_OBJECTS = \
$(OUTPUT)\ctb_lib_fifo.obj \
$(OUTPUT)\ctb_lib_getopt.obj \
$(OUTPUT)\ctb_lib_iobase.obj \
$(OUTPUT)\ctb_lib_portscan.obj \
$(OUTPUT)\ctb_lib_serportx.obj \
$(OUTPUT)\ctb_lib_serport.obj \
$(OUTPUT)\ctb_lib_timer.obj \
$(____GPIBSRC_FILENAMES_OBJECTS)
CTB_DLL_CXXFLAGS = /MT$(____DEBUG_4) /DWIN32 $(____DEBUG) $(____DEBUG_2) \
$(______DEBUG) /Fd..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.pdb \
$(__OPTIMIZE_FLAG) /I..\include /GR /EHsc $(CPPFLAGS) $(CXXFLAGS)
CTB_DLL_OBJECTS = \
$(OUTPUT)\ctb_dll_fifo.obj \
$(OUTPUT)\ctb_dll_getopt.obj \
$(OUTPUT)\ctb_dll_iobase.obj \
$(OUTPUT)\ctb_dll_portscan.obj \
$(OUTPUT)\ctb_dll_serportx.obj \
$(OUTPUT)\ctb_dll_serport.obj \
$(OUTPUT)\ctb_dll_timer.obj \
$(____GPIBSRC_FILENAMES_1_OBJECTS)
CTBTEST_CXXFLAGS = /MT$(____DEBUG_4) /DWIN32 $(____DEBUG) $(____DEBUG_2) \
$(______DEBUG) /Fd$(OUTPUT)\ctbtest.pdb /DGPIB=$(GPIB) $(__OPTIMIZE_FLAG) \
/I..\include /GR /EHsc $(CPPFLAGS) $(CXXFLAGS)
CTBTEST_OBJECTS = \
$(OUTPUT)\ctbtest_ctbtest.obj
### Conditionally set variables: ###
!if "$(DEBUG)" == "0"
OUTPUT = release
!endif
!if "$(DEBUG)" == "1"
OUTPUT = debug
!endif
!if "$(WXDIR)" == ""
INSTALLDIR = ..\lib
!endif
!if "$(DEBUG)" == "1"
LIBFLAG = d
!endif
!if "$(GPIB)" == "1"
GPIBFLAG = _gpib
!endif
!if "$(GPIB)" == "1"
____GPIBSRC_FILENAMES_OBJECTS = \
$(OUTPUT)\ctb_lib_gpib.obj
!endif
!if "$(GPIB)" == "1"
____GPIBSRC_FILENAMES_1_OBJECTS = \
$(OUTPUT)\ctb_dll_gpib.obj
!endif
!if "$(DEBUG)" == "0"
____DEBUG = /DNDEBUG
!endif
!if "$(DEBUG)" == "1"
____DEBUG =
!endif
!if "$(DEBUG)" == "0"
____DEBUG_2 =
!endif
!if "$(DEBUG)" == "1"
____DEBUG_2 = /Zi
!endif
!if "$(DEBUG)" == "0"
____DEBUG_3 =
!endif
!if "$(DEBUG)" == "1"
____DEBUG_3 = /DEBUG
!endif
!if "$(DEBUG)" == "0"
______DEBUG =
!endif
!if "$(DEBUG)" == "1"
______DEBUG = /D_DEBUG
!endif
!if "$(DEBUG)" == "0"
____DEBUG_4 =
!endif
!if "$(DEBUG)" == "1"
____DEBUG_4 = d
!endif
!if "$(DEBUG)" == "0"
__OPTIMIZE_FLAG = /Od
!endif
!if "$(DEBUG)" == "1"
__OPTIMIZE_FLAG = /O2
!endif
!if "$(GPIB)" == "1"
__SYSLIB2_p = gpib32.lib
!endif
all: $(OUTPUT)
$(OUTPUT):
-if not exist $(OUTPUT) mkdir $(OUTPUT)
### Targets: ###
all: ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(OUTPUT)\ctbtest.exe tip-win32
clean:
-if exist $(OUTPUT)\*.obj del $(OUTPUT)\*.obj
-if exist $(OUTPUT)\*.res del $(OUTPUT)\*.res
-if exist $(OUTPUT)\*.pch del $(OUTPUT)\*.pch
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ilk del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.ilk
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.pdb del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.pdb
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
-if exist $(OUTPUT)\ctbtest.exe del $(OUTPUT)\ctbtest.exe
-if exist $(OUTPUT)\ctbtest.ilk del $(OUTPUT)\ctbtest.ilk
-if exist $(OUTPUT)\ctbtest.pdb del $(OUTPUT)\ctbtest.pdb
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib: $(CTB_LIB_OBJECTS)
if exist $@ del $@
link /LIB /NOLOGO /OUT:$@ @<<
$(CTB_LIB_OBJECTS)
<<
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll: $(CTB_DLL_OBJECTS)
link /DLL /NOLOGO /OUT:$@ $(____DEBUG_3) /pdb:"..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.pdb" /LIBPATH:..\lib $(LDFLAGS) @<<
$(CTB_DLL_OBJECTS) winmm.lib $(__SYSLIB2_p) /IMPLIB:..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
<<
$(OUTPUT)\ctbtest.exe: $(CTBTEST_OBJECTS) ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
link /NOLOGO /OUT:$@ $(____DEBUG_3) /pdb:"$(OUTPUT)\ctbtest.pdb" /LIBPATH:..\lib $(LDFLAGS) @<<
$(CTBTEST_OBJECTS) ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib winmm.lib $(__SYSLIB2_p)
<<
wxinstall:
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib $(INSTALLDIR)\lib\vc_lib
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(INSTALLDIR)\lib\vc_lib
@if not exist $(INSTALLDIR)\include\ctb-0.16\win32 mkdir $(INSTALLDIR)\include\ctb-0.16\win32
@copy ..\include\ctb-0.16\*.h $(INSTALLDIR)\include\ctb-0.16
@copy ..\include\ctb-0.16\win32\*.h $(INSTALLDIR)\include\ctb-0.16\win32
tip-win32:
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. If you have an installed "
@echo " wxWidget package (WXWIN must be defined in the enviroment), "
@echo " you'll now have to run: "
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) wxinstall "
@echo " "
@echo " to install the libraries in: "
@echo " $(INSTALLDIR)\lib\vc_lib "
@echo " and the header files in"
@echo " $(INSTALLDIR)\ctb-0.16"
@echo " "
@echo " If you are using another compiler (Borland, Watcom, mingw,...) "
@echo " take a look in the README in this directory! "
@echo " "
@echo " ctb comes with no guarantees and doesn't claim "
@echo " to be suitable for any purpose. "
@echo "================================================================"
@echo " "
$(OUTPUT)\ctb_lib_fifo.obj: .\..\src\fifo.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\fifo.cpp
$(OUTPUT)\ctb_lib_getopt.obj: .\..\src\getopt.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\getopt.cpp
$(OUTPUT)\ctb_lib_iobase.obj: .\..\src\iobase.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\iobase.cpp
$(OUTPUT)\ctb_lib_portscan.obj: .\..\src\portscan.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\portscan.cpp
$(OUTPUT)\ctb_lib_serportx.obj: .\..\src\serportx.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\serportx.cpp
$(OUTPUT)\ctb_lib_serport.obj: .\..\src\win32\serport.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\win32\serport.cpp
$(OUTPUT)\ctb_lib_timer.obj: .\..\src\win32\timer.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\win32\timer.cpp
$(OUTPUT)\ctb_lib_gpib.obj: .\..\src\gpib.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_LIB_CXXFLAGS) .\..\src\gpib.cpp
$(OUTPUT)\ctb_dll_fifo.obj: .\..\src\fifo.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\fifo.cpp
$(OUTPUT)\ctb_dll_getopt.obj: .\..\src\getopt.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\getopt.cpp
$(OUTPUT)\ctb_dll_iobase.obj: .\..\src\iobase.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\iobase.cpp
$(OUTPUT)\ctb_dll_portscan.obj: .\..\src\portscan.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\portscan.cpp
$(OUTPUT)\ctb_dll_serportx.obj: .\..\src\serportx.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\serportx.cpp
$(OUTPUT)\ctb_dll_serport.obj: .\..\src\win32\serport.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\win32\serport.cpp
$(OUTPUT)\ctb_dll_timer.obj: .\..\src\win32\timer.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\win32\timer.cpp
$(OUTPUT)\ctb_dll_gpib.obj: .\..\src\gpib.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTB_DLL_CXXFLAGS) .\..\src\gpib.cpp
$(OUTPUT)\ctbtest_ctbtest.obj: .\..\samples\ctbtest.cpp
$(CXX) /c /nologo /TP /Fo$@ $(CTBTEST_CXXFLAGS) .\..\samples\ctbtest.cpp

View File

@ -0,0 +1,283 @@
# =========================================================================
# This makefile was generated by
# Bakefile 0.2.5 (http://www.bakefile.org)
# Do not modify, all changes will be overwritten!
# =========================================================================
# -------------------------------------------------------------------------
# These are configurable options:
# -------------------------------------------------------------------------
# C++ compiler
CXX = wpp386
# Standard flags for C++
CXXFLAGS =
# Standard preprocessor flags (common for CC and CXX)
CPPFLAGS =
# Standard linker flags
LDFLAGS =
# Set to 1 to build debug version [0,1]
# 0 - Release
# 1 - Debug
DEBUG = 0
#
GPIB = 0
#
WXDIR = $(%WXWIN)
#
INSTALLDIR = $(%WXWIN)
# -------------------------------------------------------------------------
# Do not modify the rest of this file!
# -------------------------------------------------------------------------
# Speed up compilation a bit:
!ifdef __LOADDLL__
! loaddll wcc wccd
! loaddll wccaxp wccdaxp
! loaddll wcc386 wccd386
! loaddll wpp wppdi86
! loaddll wppaxp wppdaxp
! loaddll wpp386 wppd386
! loaddll wlink wlink
! loaddll wlib wlibd
!endif
# We need these variables in some bakefile-made rules:
WATCOM_CWD = $+ $(%cdrive):$(%cwd) $-
### Conditionally set variables: ###
OUTPUT =
!ifeq DEBUG 0
OUTPUT = release
!endif
!ifeq DEBUG 1
OUTPUT = debug
!endif
INSTALLDIR =
!ifeq WXDIR
INSTALLDIR = ..\lib
!endif
LIBFLAG =
!ifeq DEBUG 1
LIBFLAG = d
!endif
GPIBFLAG =
!ifeq GPIB 1
GPIBFLAG = _gpib
!endif
____GPIBSRC_FILENAMES_OBJECTS =
!ifeq GPIB 1
____GPIBSRC_FILENAMES_OBJECTS = &
$(OUTPUT)\ctb_lib_gpib.obj
!endif
____GPIBSRC_FILENAMES_1_OBJECTS =
!ifeq GPIB 1
____GPIBSRC_FILENAMES_1_OBJECTS = &
$(OUTPUT)\ctb_dll_gpib.obj
!endif
____DEBUG =
!ifeq DEBUG 0
____DEBUG = -dNDEBUG
!endif
!ifeq DEBUG 1
____DEBUG =
!endif
____DEBUG_0 =
!ifeq DEBUG 0
____DEBUG_0 = -d0
!endif
!ifeq DEBUG 1
____DEBUG_0 = -d2
!endif
____DEBUG_2 =
!ifeq DEBUG 0
____DEBUG_2 =
!endif
!ifeq DEBUG 1
____DEBUG_2 = debug all
!endif
__OPTIMIZE_FLAG =
!ifeq DEBUG 0
__OPTIMIZE_FLAG = -od
!endif
!ifeq DEBUG 1
__OPTIMIZE_FLAG = -ot -ox
!endif
__SYSLIB2_p =
!ifeq GPIB 1
__SYSLIB2_p = gpib32.lib
!endif
### Variables: ###
CTB_LIB_CXXFLAGS = $(____DEBUG) $(____DEBUG_0) -bm $(__OPTIMIZE_FLAG) &
-i=..\include $(CPPFLAGS) $(CXXFLAGS)
CTB_LIB_OBJECTS = &
$(OUTPUT)\ctb_lib_fifo.obj &
$(OUTPUT)\ctb_lib_getopt.obj &
$(OUTPUT)\ctb_lib_iobase.obj &
$(OUTPUT)\ctb_lib_portscan.obj &
$(OUTPUT)\ctb_lib_serportx.obj &
$(OUTPUT)\ctb_lib_serport.obj &
$(OUTPUT)\ctb_lib_timer.obj &
$(____GPIBSRC_FILENAMES_OBJECTS)
CTB_DLL_CXXFLAGS = -bd $(____DEBUG) $(____DEBUG_0) -bm $(__OPTIMIZE_FLAG) &
-i=..\include $(CPPFLAGS) $(CXXFLAGS)
CTB_DLL_OBJECTS = &
$(OUTPUT)\ctb_dll_fifo.obj &
$(OUTPUT)\ctb_dll_getopt.obj &
$(OUTPUT)\ctb_dll_iobase.obj &
$(OUTPUT)\ctb_dll_portscan.obj &
$(OUTPUT)\ctb_dll_serportx.obj &
$(OUTPUT)\ctb_dll_serport.obj &
$(OUTPUT)\ctb_dll_timer.obj &
$(____GPIBSRC_FILENAMES_1_OBJECTS)
CTBTEST_CXXFLAGS = $(____DEBUG) $(____DEBUG_0) -dGPIB=$(GPIB) -bm &
$(__OPTIMIZE_FLAG) -i=..\include $(CPPFLAGS) $(CXXFLAGS)
CTBTEST_OBJECTS = &
$(OUTPUT)\ctbtest_ctbtest.obj
all : $(OUTPUT)
$(OUTPUT) :
-if not exist $(OUTPUT) mkdir $(OUTPUT)
### Targets: ###
all : .SYMBOLIC ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(OUTPUT)\ctbtest.exe tip-win32
clean : .SYMBOLIC
-if exist $(OUTPUT)\*.obj del $(OUTPUT)\*.obj
-if exist $(OUTPUT)\*.res del $(OUTPUT)\*.res
-if exist $(OUTPUT)\*.lbc del $(OUTPUT)\*.lbc
-if exist $(OUTPUT)\*.ilk del $(OUTPUT)\*.ilk
-if exist $(OUTPUT)\*.pch del $(OUTPUT)\*.pch
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll
-if exist ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib del ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
-if exist $(OUTPUT)\ctbtest.exe del $(OUTPUT)\ctbtest.exe
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib : $(CTB_LIB_OBJECTS)
@%create $(OUTPUT)\ctb_lib.lbc
@for %i in ($(CTB_LIB_OBJECTS)) do @%append $(OUTPUT)\ctb_lib.lbc +%i
wlib -q -p4096 -n -b $^@ @$(OUTPUT)\ctb_lib.lbc
..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll : $(CTB_DLL_OBJECTS)
@%create $(OUTPUT)\ctb_dll.lbc
@%append $(OUTPUT)\ctb_dll.lbc option quiet
@%append $(OUTPUT)\ctb_dll.lbc name $^@
@%append $(OUTPUT)\ctb_dll.lbc option caseexact
@%append $(OUTPUT)\ctb_dll.lbc $(____DEBUG_2) libpath ..\lib $(LDFLAGS)
@for %i in ($(CTB_DLL_OBJECTS)) do @%append $(OUTPUT)\ctb_dll.lbc file %i
@for %i in ( winmm.lib $(__SYSLIB2_p)) do @%append $(OUTPUT)\ctb_dll.lbc library %i
@%append $(OUTPUT)\ctb_dll.lbc
@%append $(OUTPUT)\ctb_dll.lbc system nt_dll
wlink @$(OUTPUT)\ctb_dll.lbc
wlib -q -n -b ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib +$^@
$(OUTPUT)\ctbtest.exe : $(CTBTEST_OBJECTS) ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib
@%create $(OUTPUT)\ctbtest.lbc
@%append $(OUTPUT)\ctbtest.lbc option quiet
@%append $(OUTPUT)\ctbtest.lbc name $^@
@%append $(OUTPUT)\ctbtest.lbc option caseexact
@%append $(OUTPUT)\ctbtest.lbc $(____DEBUG_2) libpath ..\lib $(LDFLAGS)
@for %i in ($(CTBTEST_OBJECTS)) do @%append $(OUTPUT)\ctbtest.lbc file %i
@for %i in ( ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib winmm.lib $(__SYSLIB2_p)) do @%append $(OUTPUT)\ctbtest.lbc library %i
@%append $(OUTPUT)\ctbtest.lbc
@for %i in () do @%append $(OUTPUT)\ctbtest.lbc option stack=%i
wlink @$(OUTPUT)\ctbtest.lbc
wxinstall :
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.lib $(INSTALLDIR)\lib\watcom_lib
@copy ..\lib\ctb$(LIBFLAG)$(GPIBFLAG)-0.16.dll $(INSTALLDIR)\lib\watcom_lib
@if not exist $(INSTALLDIR)\include\ctb-0.16\win32 mkdir $(INSTALLDIR)\include\ctb-0.16\win32
@copy ..\include\ctb-0.16\*.h $(INSTALLDIR)\include\ctb-0.16
@copy ..\include\ctb-0.16\win32\*.h $(INSTALLDIR)\include\ctb-0.16\win32
tip-win32 :
@echo " "
@echo "================================================================"
@echo " The building of ctb is finished. If you have an installed "
@echo " wxWidget package (WXWIN must be defined in the enviroment), "
@echo " you'll now have to run: "
@echo " "
@echo " make DEBUG=$(DEBUG) GPIB=$(GPIB) wxinstall "
@echo " "
@echo " to install the libraries in: "
@echo " $(INSTALLDIR)\lib\watcom_lib "
@echo " and the header files in"
@echo " $(INSTALLDIR)\ctb-0.16"
@echo " "
@echo " If you are using another compiler (Borland, Watcom, mingw,...) "
@echo " take a look in the README in this directory! "
@echo " "
@echo " ctb comes with no guarantees and doesn't claim "
@echo " to be suitable for any purpose. "
@echo "================================================================"
@echo " "
$(OUTPUT)\ctb_lib_fifo.obj : .AUTODEPEND .\..\src\fifo.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_getopt.obj : .AUTODEPEND .\..\src\getopt.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_iobase.obj : .AUTODEPEND .\..\src\iobase.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_portscan.obj : .AUTODEPEND .\..\src\portscan.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_serportx.obj : .AUTODEPEND .\..\src\serportx.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_serport.obj : .AUTODEPEND .\..\src\win32\serport.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_timer.obj : .AUTODEPEND .\..\src\win32\timer.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_lib_gpib.obj : .AUTODEPEND .\..\src\gpib.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_LIB_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_fifo.obj : .AUTODEPEND .\..\src\fifo.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_getopt.obj : .AUTODEPEND .\..\src\getopt.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_iobase.obj : .AUTODEPEND .\..\src\iobase.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_portscan.obj : .AUTODEPEND .\..\src\portscan.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_serportx.obj : .AUTODEPEND .\..\src\serportx.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_serport.obj : .AUTODEPEND .\..\src\win32\serport.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_timer.obj : .AUTODEPEND .\..\src\win32\timer.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctb_dll_gpib.obj : .AUTODEPEND .\..\src\gpib.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTB_DLL_CXXFLAGS) $<
$(OUTPUT)\ctbtest_ctbtest.obj : .AUTODEPEND .\..\samples\ctbtest.cpp
$(CXX) -bt=nt -zq -fo=$^@ $(CTBTEST_CXXFLAGS) $<

View File

@ -0,0 +1,139 @@
#ifndef LIBCTB_CTB_H_INCLUDED_
#define LIBCTB_CTB_H_INCLUDED_
#include "ctb-0.16/fifo.h"
#if ( GPIB )
# include "ctb-0.16/gpib.h"
#endif
#include "ctb-0.16/getopt.h"
#include "ctb-0.16/iobase.h"
#include "ctb-0.16/kbhit.h"
#include "ctb-0.16/portscan.h"
#include "ctb-0.16/serport.h"
#include "ctb-0.16/serportx.h"
#include "ctb-0.16/timer.h"
/*!
\mainpage ctb overview
The ctb (communication toolbox) library was realized, to simplify the
communication with other instruments throughout the serial com ports
(at first). To make my life easier, it should works with Linux and
all win32 plattforms (excepted windows 3.1, which is a only 16bit OS)
because I develope my applications for both plattforms).\n
Some times later GPIB support was added to make ctb an integrated part
for the extensive test and calibration system of a company I worked
these days.\n
The main goal of the library was a non-blocked communication to avoid
frozen GUIs waiting for data which in some conditions never arrives.
On the base ctb defines an abstract class IOBase, which must be
derivate for several interfaces (at now this was done for the
RS232 comports and GPIB IEEE488 interface).
This leads to another feature: Because all classes depends on one
super class, you have just open your wanted interface and don't
worry about it's special typ later. This is like the 'Virtual
Instrument' featured by Nation Instruments LabView.
Last not least: ctb provides one written code for Linux and Windows
(compiles well with GNU G++ and VC++). Without any dependences (execept
for a standard C++ compilier) ctb runs also in small enviroments like
embedded systems and doesn't need any graphic stuff for use.
ctb is composed of five parts:
- ctb::IOBase class
- ctb::SerialPort class
- ctb::GpibDevice class
- ctb::Timer class
- ctb::Fifo class
\section IOBase IOBase class
An abstract class for different interfaces. The idea behind this:
Similar to the virtual file system this class defines a lot of
preset member functions, which the derivate classes must be
overload.\n
In the main thing these are: open a interface (such as RS232),
reading and writing non blocked through the interface and at
last, close it.\n
For special interface settings the method ioctl was defined.
(control interface). ioctl covers some interface dependent
settings like switch on/off the RS232 status lines and must also
be defined from each derivated class.
\section SerialPort SerialPort class
The class for the serial ports is named as
ctb::SerialPort. SerialPort is a wrapper for non blocked reading and
writing. This is easy under linux, but with windows a lot more
tricky. SerialPort is as simple as possible. It doesn't create any
gui events or signals, so it works also standalone. It's also not a
device driver, means, you must call the read method, if you look for
receiving data.
You can write any desired data with any length (length type is
size_t, I think, on win32 and linux this is a 32Bit integer) and
SerialPort returns the really writen data length, also you can read
a lot of data and SerialPort returns the really received data count.
Both, read and write returns immediatelly. Using these, the program
never blocks. Also IOBase implements a blocked read and write. You can
use these functions, if you want a definitiv count of data and never
accept less than this. Because there is a difficulty, when the
communication is interrupted or death, both blocked functions get a
timeout flag to returns after a given time interval. The timeouts
will be handled with the second timer class.
As an additional benefit ctb features also 9 Bit transmission (with
take advantage of the parity bit), non-standard baudrates (depending
on your hardware but not on ctb) and all parity eventualities
including static parity settings like Mark and Space.
\section GpibDevice GpibDevice class
Named as ctb::GpibDevice. In the philosophy of the SerialPort class
GpibDevice also supports non-blocking communication. You can instant
as many GpibDevice objects as you need for instance to communicate
with a lot of different bus participants in a typical GPIB enviroment.
GPIB support was tested with PCI cards and USB adapter from Nation
Instrument and Keithley.
\section Timer Timer class
The idea of the ctb::Timer class is to base on the Unix C alarm
function. You create a Timer with a given alarm time and a adress of
flag, which the timer must set after the time is over.
Because the alarm function cannot used more than once in the same
process (under windows I don't know a similar function), every timer
instance will be a separate thread after starting it. So you can start
a timer and continue in your program, make a lot of things and test
the flag whenever you want this. (For example, you read/write a
given count of data).
\note
I think, it's a better style, to request a given count of data in
100ms (for example) and trap the situation, if there are not enough
data after this time. And not do this for every byte!
\section Fifo Fifo cass
Provides a simple thread safe fifo to realize a fast and simple
communication pipe between two threads (and was used also as a put
back mechanism for the wxIOBase and it's derivated classes).\n
ctb::Fifo tackles the concurrently access from different threads with an
internal temporary pointer asignment which was atomic. From there no
mutex or semaphore is involved and lead to a fast access.
Please note:\n
The thread safeness is limited to the put/get write/read methods but
which should be sufficent for a fifo.
\latexonly \newpage \endlatexonly
*/
#endif

View File

@ -0,0 +1,96 @@
#ifndef __LIBCTB_FIFO_H_INCLUDED_
#define __LIBCTB_FIFO_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: fifo.h
// Purpose:
// Author: Joachim Buermann, Michael Hungershausen
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include <sys/types.h>
/**
\file fifo.h
*/
namespace ctb {
/*!
\class Fifo
A simple thread safe fifo to realize a put back mechanism for the
wxIOBase and it's derivated classes.
*/
class Fifo
{
protected:
/*! the size of the fifo */
size_t m_size;
/*! the start of the internal fifo buffer */
char* m_begin;
/*!
the end of the internal fifo buffer (m_end marks the first
invalid byte AFTER the internal buffer)
*/
char* m_end;
/*! the current read position */
char* m_rdptr;
/*! the current write position */
char* m_wrptr;
public:
/*!
\brief the constructor initialize a fifo with the given size.
\param size size of the fifo
*/
Fifo(size_t size);
/*!
\brief the destructor destroys all internal memory.
*/
virtual ~Fifo();
/*!
\brief clear all internal memory and set the read and write
pointers to the start of the internal memory.
\Note This function is not thread safe! Don't use it, if another
thread takes access to the fifo instance. Use a looping get() or
read() call instead of this.
*/
virtual void clear();
/*!
\brief fetch the next available byte from the fifo.
\param ch points to a charater to store the result
\return 1 if successful, 0 otherwise
*/
virtual int get(char* ch);
/*!
\brief query the fifo for it's available bytes.
\return count of readable bytes, storing in the fifo
*/
size_t items();
/*!
\brief put a character into the fifo.
\param ch the character to put in
\return 1 if successful, 0 otherwise
*/
virtual int put(char ch);
/*!
\brief read a given count of bytes out of the fifo.
\param data memory to store the readed data
\param count number of bytes to read
\return On success, the number of bytes read are returned,
0 otherwise
*/
virtual int read(char* data,int count);
/*!
\brief write a given count of bytes into the fifo.
\param data start of the data to write
\param count number of bytes to write
\return On success, the number of bytes written are returned,
0 otherwise
*/
virtual int write(char* data,int count);
};
} // namespace ctb
#endif

View File

@ -0,0 +1,19 @@
#ifndef LIBCTB_GETOPT_H_INCLUDED_
#define LIBCTB_GETOPT_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: getopt.h
// Purpose: Simple wrapper file
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#if defined (WIN32)
# include "win32/getopt.h"
#else
# include <getopt.h>
#endif
#endif
// __WX_GETOPT_H

View File

@ -0,0 +1,378 @@
#ifndef LIBCTB_GPIB_H_INCLUDED_
#define LIBCTB_GPIB_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: gpibx.h
// Purpose: base class for gpib devices
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/iobase.h"
namespace ctb {
/*!
\file gpib.h
*/
/*! defines the os specific name for the first gpib controller */
extern const char* GPIB1;
/*! defines the os specific name for the second gpib controller */
extern const char* GPIB2;
/*!
\enum GpibTimeout
NI488.2 API defines the following valid timeouts.
*/
enum GpibTimeout
{
/// no timeout (infinity)
GpibTimeoutNone = 0,
/// 10 micro seconds
GpibTimeout10us,
/// 30 micro seconds
GpibTimeout30us,
/// 100 micro seconds
GpibTimeout100us,
/// 300 micro seconds
GpibTimeout300us,
/// 1 milli second
GpibTimeout1ms,
/// 3 milli seconds
GpibTimeout3ms,
/// 10 milli seconds
GpibTimeout10ms,
/// 30 milli seconds
GpibTimeout30ms,
/// 0.1 seconds
GpibTimeout100ms,
/// 0.3 seconds
GpibTimeout300ms,
/// 1 second
GpibTimeout1s,
/// 3 seconds
GpibTimeout3s,
/// 10 seconds
GpibTimeout10s,
/// 30 seconds
GpibTimeout30s,
/// 100 seconds
GpibTimeout100s,
/// 300 seconds (5 minutes)
GpibTimeout300s,
/// 1000 seconds
GpibTimeout1000s
};
/*!
\struct Gpib_DCS
The device control struct for the gpib communication class.
This struct should be used, if you refer advanced parameter.
*/
struct Gpib_DCS
{
/*! primary address of GPIB device */
int m_address1;
/*! secondary address of GPIB device */
int m_address2;
/*! I/O timeout */
GpibTimeout m_timeout;
/*! EOT enable */
bool m_eot;
/*!
Defines the EOS character.
Note! Defining an EOS byte does not cause the driver to
automatically send that byte at the end of write I/O
operations. The application is responsible for placing the
EOS byte at the end of the data strings that it defines.
(National Instruments NI-488.2M Function Reference Manual)
*/
unsigned char m_eosChar;
/*!
Set the EOS mode (handling).m_eosMode may be a combination
of bits ORed together. The following bits can be used:
0x04: Terminate read when EOS is detected.
0x08: Set EOI (End or identify line) with EOS on write function
0x10: Compare all 8 bits of EOS byte rather than low 7 bits
(all read and write functions).
*/
unsigned char m_eosMode;
/*! buffer for internal use */
char m_buf[32];
/*! to avoid memory leak warnings generated by swig */
~Gpib_DCS() {};
/*!
\brief the constructor initiate the device control struct with
the common useful values and set the internal timeout for the
GPIB controller to 1ms to avoid (or better reduce) blocking
*/
Gpib_DCS() {
/*! set default device address to 1 */
m_address1 = 1;
m_address2 = 0;
/*!
set the timeout to a short value to avoid blocking
(default are 1msec)
*/
m_timeout = GpibTimeout1ms;
m_eot = true;
/*! EOS character, see above! */
m_eosChar = 0;//'\n';
/*! EOS mode, see above! */
m_eosMode = 0;
};
/*!
\brief returns the internal parameters in a more human readable
string format like 'Adr: (1,0) to:1ms'.
\return the settings as a null terminated string
*/
char* GetSettings();
};
/*!
\enum GpibIoctls
The following Ioctl calls are only valid for the GpibDevice class.
*/
enum GpibIoctls {
/*!
Set the adress of the via gpib connected device.
*/
CTB_GPIB_SETADR = CTB_GPIB,
/*!
Get the serial poll byte
*/
CTB_GPIB_GETRSP,
/*!
Get the GPIB status
*/
CTB_GPIB_GETSTA,
/*!
Get the last GPIB error number
*/
CTB_GPIB_GETERR,
/*!
Get the GPIB line status (hardware control lines) as an
integer. The lowest 8 bits correspond to the current state
of the lines.
*/
CTB_GPIB_GETLINES,
/*!
Set the GPIB specific timeout
*/
CTB_GPIB_SETTIMEOUT,
/*!
Forces the specified device to go to local program mode
*/
CTB_GPIB_GTL,
/*!
This routine can only be used if the specified GPIB
Interface Board is the System Controller.
Remember that even though the REN line is asserted,
the device(s) will not be put into remote state until is
addressed to listen by the Active Controller
*/
CTB_GPIB_REN,
/*!
The command asserts the GPIB interface clear (IFC) line for
ast least 100us if the GPIB board is the system controller.
This initializes the GPIB and makes the interface CIC and
active controller with ATN asserted.
Note! The IFC signal resets only the GPIB interface functions
of the bus devices and not the internal device functions.
For a device reset you should use the CTB_RESET command above.
*/
CTB_GPIB_RESET_BUS,
/*!
Configure the end-of-string (EOS) termination character.
Note! Defining an EOS byte does not cause the driver to
automatically send that byte at the end of write I/O
operations. The application is responsible for placing the
EOS byte at the end of the data strings that it defines.
(National Instruments NI-488.2M Function Reference Manual)
*/
CTB_GPIB_SET_EOS_CHAR,
/*!
Get the internal EOS termination character (see above).
*/
CTB_GPIB_GET_EOS_CHAR,
/*!
Set the EOS mode (handling).m_eosMode may be a combination
of bits ORed together. The following bits can be used:
0x04: Terminate read when EOS is detected.
0x08: Set EOI (End or identify line) with EOS on write function
0x10: Compare all 8 bits of EOS byte rather than low 7 bits
(all read and write functions).
*/
CTB_GPIB_SET_EOS_MODE,
/*!
Get the internal EOS mode (see above).
*/
CTB_GPIB_GET_EOS_MODE,
};
/*!
\class GpibDevice
GpibDevice is the basic class for communication via the GPIB bus.
*/
class GpibDevice : public IOBase
{
protected:
/*!
\brief
the internal board identifier, 0 for the first gpib controller,
1 for the second one
*/
int m_board;
/*!
\brief
the file descriptor of the connected gpib device
*/
int m_hd;
/*!
\brief
contains the internal conditions of the GPIB communication like
GPIB error, timeout and so on...
*/
int m_state;
/*! the internal GPIB error number */
int m_error;
/*! the count of data read or written */
int m_count;
/*!
\brief contains the internal settings of the GPIB connection like
address, timeout, end of string character and so one...
*/
Gpib_DCS m_dcs;
int CloseDevice();
/*!
\brief returns a short notation or more detail description of
the given GPIB error number.
\param error the occured GPIB error
\param detailed true for a more detailed description, false
otherwise
\return a null terminated string with the short or detailed
error message.
*/
virtual const char* GetErrorString(int error,bool detailed);
/*!
Open the interface (internally to request a file descriptor for the
given interface). The second parameter is a undefined pointer of a
Gpib_DCS data struct.
\param devname the name of the GPIB device, GPIB1 means the first
GPIB controller, GPIB2 the second (if available).
\param dcs untyped pointer of advanced device parameters,
\sa struct Gpib_DCS (data struct for the gpib device)
\return zero on success, otherwise -1
*/
int OpenDevice(const char* devname, void* dcs);
public:
GpibDevice() {
m_board = -1;
m_hd = -1;
m_state = m_count = m_error = 0;
};
virtual ~GpibDevice() {Close();};
/*!
\brief returns the name of the class instance. You find this useful,
if you handle different devices like a serial port or a gpib device
via a IOBase pointer.
\return name of the class.
*/
const char* ClassName() {return "ctb::GpibDevice";};
/*!
\brief returns a more detail description of the given error
number.
\param error the occured error number
\return null terminated string with the error description
*/
virtual const char* GetErrorDescription(int error) {
return GetErrorString(error,true);
};
/*!
\brief returns a short notation like 'EABO' of the given error
number.
\param error the occured error number
\return null terminated string with the short error notation
*/
virtual const char* GetErrorNotation(int error) {
return GetErrorString(error,false);
};
/*!
\brief request the current settings of the connected gpib device
as a null terminated string.
\return the settings as a string like 'Adr: (1,0) to:1ms'
*/
virtual char* GetSettingsAsString() {
return m_dcs.GetSettings();
};
/// This is only for internal usage
int Ibrd(char* buf,size_t len);
/// This is only for internal usage
int Ibwrt(char* buf,size_t len);
/*!
\brief Many operating characteristics are only possible for
special devices. To avoid the need of a lot of different functions
and to give the user a uniform interface, all this special
operating instructions will covered by one Ioctl methode (like
the linux ioctl call).
The Ioctl command (cmd) has encoded in it whether the argument
is an in parameter or out parameter, and the size of the
argument args in bytes. Macros and defines used in specifying an
ioctl request are located in iobase.h and the header file for
the derivated device (for example in gpib.h).
\param cmd one of GpibIoctls specify the ioctl request.
\param args is a typeless pointer to a memory location, where
Ioctl reads the request arguments or write the results.
Please note, that an invalid memory location or size involving
a buffer overflow or segmention fault!
*/
virtual int Ioctl(int cmd,void* args);
/*!
Returns the current state of the device.
\return 1 if device is valid and open, otherwise 0
*/
int IsOpen() {
return m_hd >= 0;
};
/*!
\brief Opens a GPIB device in a user likely way. Insteed of
using the Device Control Struct just input your parameter in a
more intuitive manner.
\param devname the name of the GPIB controler like GPIB1 or GPIB2
\param address the address of the connected device (1...31)
\return the new file descriptor, or -1 if an error occurred
*/
int Open( const char* devname, int address );
// Open overrides and hides the IOBase::Open( const char*
// devname, void* dcs ) of the base class! So bring it into scope
// again!
using IOBase::Open;
int Read(char* buf,size_t len);
int Write(char* buf,size_t len);
/*!
\brief FindListener returns all listening devices connected to
the GPIB bus of the given board.
This function is not member of the GPIB class, becauce it
should do it's job before you open any GPIB connection.
\param board the board nummber. Default is the first board (=0).
Valid board numbers are 0 and 1.
\return -1 if an error occurred, otherwise a setting bit for
each listener address. Bit0 is always 0 (address 0 isn't valid,
Bit1 means address 1, Bit2 address 2 and so on...
*/
static int FindListeners(int board = 0);
};
} // namespace ctb
#endif

View File

@ -0,0 +1,294 @@
#ifndef LIBCTB_IOBASE_H_INCLUDED_
#define LIBCTB_IOBASE_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: iobase.h
// Purpose: io basic class
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/fifo.h"
#include <sys/types.h>
/**
\file iobase.h
*/
namespace ctb {
enum {
CTB_COMMON = 0x0000,
CTB_SERIAL = 0x0100,
CTB_GPIB = 0x0200,
CTB_TIMEOUT_INFINITY = 0xFFFFFFFF
};
// const unsigned int wxTIMEOUT_INFINITY = 0xFFFFFFFF;
/*!
\enum IOBaseIoctls
Defines the ioctl calls for derivated classes. The following Ioctl
calls are valid for all from wxIOBase derivated classes.
*/
enum IOBaseIoctls {
/*!
Reset the connected device. For a serial (RS232) connection,
a break is send. For GPIB the IFC (Interface Clear) line is
set.
*/
CTB_RESET = CTB_COMMON
};
/*!
\class IOBase
An abstract class for different interfaces. The idea behind this:
Similar to the virtual file system this class defines a lot of
preset member functions, which the derivate classes must be
overload.
In the main thing these are: open a interface (such as RS232),
reading and writing non blocked through the interface and at
last, close it.
For special interface settings the method ioctl was defined.
(control interface). ioctl covers some interface dependent
settings like switch on/off the RS232 status lines and must also
be defined from each derivated class.
*/
class IOBase
{
protected:
/*!
\brief internal fifo (first in, first out queue) to put back
already readed bytes into the reading stream. After put back a single
byte or sequence of characters, you can read them again with the
next Read call.
*/
Fifo* m_fifo;
enum {
/// fifosize of the putback fifo
fifoSize = 256
};
/*!
Close the interface (internally the file descriptor, which was
connected with the interface).
\return zero on success, otherwise -1.
*/
virtual int CloseDevice() = 0;
/*!
Open the interface (internally to request a file descriptor for the
given interface). The second parameter is a undefined pointer of a
device dependent data struct. It must be undefined, because different
devices have different settings. A serial device like the com ports
points here to a data struct, includes information like baudrate,
parity, count of stopbits and wordlen and so on. Another devices
(for example a IEEE) needs a adress and EOS (end of string character)
and don't use baudrate or parity.
\param devname the name of the device, presents the given interface.
Under windows for example COM1, under Linux /dev/cua0. Use wxCOMn to
avoid plattform depended code (n is the serial port number, beginning
with 1).
\param dcs untyped pointer of advanced device parameters,
\sa struct dcs_devCUA (data struct for the serail com ports)
\return zero on success, otherwise -1
*/
virtual int OpenDevice(const char* devname, void* dcs = 0L) = 0;
public:
/*!
Default constructor
*/
IOBase() {
m_fifo = new Fifo(fifoSize);
};
/*!
Default destructor
*/
virtual ~IOBase() {
delete m_fifo;
};
/*!
\brief A little helper function to detect the class name
\return the name of the class
*/
virtual const char* ClassName() {return "ctb::IOBase";};
/*!
Closed the interface. Internally it calls the CloseDevice()
method, which must be defined in the derivated class.
\return zero on success, or -1 if an error occurred.
*/
int Close() {return CloseDevice();};
/*!
In this method we can do all things, which are different
between the discrete interfaces. The method is similar to the
C ioctl function. We take a command number and a integer
pointer as command parameter.
An example for this is the reset of a connection between a PC
and one ore more other instruments. On serial (RS232) connections
mostly a break will be send, GPIB on the other hand defines a
special line on the GPIB bus, to reset all connected devices.
If you only want to reset your connection, you should use the
Ioctl methode for doing this, independent of the real type of
the connection.
\param cmd a command identifier, (under Posix such as TIOCMBIS
for RS232 interfaces), IOBaseIoctls
\param args typeless parameter pointer for the command above.
\return zero on success, or -1 if an error occurred.
*/
virtual int Ioctl(int cmd,void* args) {return -1;};
/*!
Returns the current state of the device.
\return 1 if device is valid and open, otherwise 0
*/
virtual int IsOpen() = 0;
/*!
\param devname name of the interface, we want to open
\param dcs a untyped pointer to a device control struct. If
he is NULL, the default device parameter will be used.
\return the new file descriptor, or -1 if an error occurred
The pointer dcs will be used for special device dependent
settings. Because this is very specific, the struct or
destination of the pointer will be defined by every device
itself. (For example: a serial device class should refer
things like parity, word length and count of stop bits,
a IEEE class adress and EOS character).
*/
int Open(const char* devname,void* dcs=0L) {
return OpenDevice(devname,dcs);
};
/*!
\brief In some circumstances you want to put back a already
readed byte (for instance, you have overreaded it and like to
parse the recieving bytes again).
The internal fifo stores fifoSize characters until you
have to read again.
\param ch the character to put back in the input stream
\return 1, if successful, otherwise 0
*/
int PutBack(char ch) {
return m_fifo->put(ch);
};
/*!
Read attempt to read len bytes from the interface into the buffer
starting with buf. Read never blocks. If there are no bytes for
reading, Read returns zero otherwise the count of bytes been readed.
\param buf starting adress of the buffer
\param len count of bytes, we want to read
\return -1 on fails, otherwise the count of readed bytes
*/
virtual int Read(char* buf,size_t len) = 0;
/*!
\brief
ReadUntilEos read bytes from the interface until the EOS string
was received or a timeout occurs.
ReadUntilEos returns the count of bytes been readed. The received
bytes are stored on the heap point by the readbuf pointer and
must delete by the caller.
\param readbuf points to the start of the readed bytes. You must
delete them, also if you received no byte.
\param readedBytes A pointer to the variable that receives the number
of bytes read.
\param eosString is the null terminated end of string sequence.
Default is the linefeed character.
\param timeout_in_ms the function returns after this time, also
if no eos occured (default is 1s).
\param quota defines a character between those an EOS doesn't
terminate the string
\return 1 on sucess (the operation ends successfull without a timeout),
0 if a timeout occurred and -1 otherwise
*/
virtual int ReadUntilEOS(char*& readbuf,
size_t* readedBytes,
char* eosString = "\n",
long timeout_in_ms = 1000L,
char quota = 0);
/*!
\brief
readv() attempts to read up to len bytes from the interface
into the buffer starting at buf.
readv() is blocked till len bytes are readed or the given
timeout in milliseconds was reached.
\param buf starting address of the buffer
\param len count bytes, we want to read
\param timeout_in_ms in milliseconds. If you don't want any timeout,
you give the wxTIMEOUT_INFINITY here.
But think of it: In this case, this function never returns
if there a not enough bytes to read.
\return the number of data bytes successfully read
*/
int Readv(char* buf,size_t len,unsigned int timeout_in_ms);
/*!
\brief
readv() attempts to read up to len bytes from the interface
into the buffer starting at buf.
readv() is blocked till len bytes are readed or the timeout_flag
points on a int greater then zero.
\param buf starting adress of the buffer
\param len count bytes, we want to read
\param timeout_flag a pointer to an integer. If you don't want
any timeout, you given a null pointer here.
But think of it: In this case, this function comes never
back, if there a not enough bytes to read.
\param nice if true go to sleep for one ms (reduce CPU last),
if there is no byte available (default is false)
*/
int Readv(char* buf,size_t len,int* timeout_flag,bool nice=false);
/*!
Write writes up to len bytes from the buffer starting with buf
into the interface.
\param buf start adress of the buffer
\param len count of bytes, we want to write
\return on success, the number of bytes written are returned
(zero indicates nothing was written). On error, -1 is returned.
*/
virtual int Write(char* buf,size_t len) = 0;
/*!
Writev() writes up to len bytes to the interface from the buffer,
starting at buf.
Also Writev() blocks till all bytes are written or the given
timeout in milliseconds was reached.
\param buf starting address of the buffer
\param len count bytes, we want to write
\param timeout_in_ms timeout in milliseconds. If you give
wxTIMEOUT_INFINITY here, the function blocks, till all data was
written.
\return the number of data bytes successfully written.
*/
int Writev(char* buf,size_t len,unsigned int timeout_in_ms);
/*!
Writev() writes up to len bytes to the interface from the buffer,
starting at buf.
Also Writev() blocks till all bytes are written or the timeout_flag
points to an integer greater then zero.
\param buf starting adress of the buffer
\param len count bytes, we want to write
\param timeout_flag a pointer to an integer. You also can give a null
pointer here. This blocks, til all data is writen.
\param nice if true go to sleep for one ms (reduce CPU last),
if there is no byte available (default is false)
*/
int Writev(char* buf,size_t len,int* timeout_flag,bool nice = false);
};
} // namespace ctb
#endif

View File

@ -0,0 +1,10 @@
#ifndef LIBCTB_KBHIT_H_INCLUDED_
#define LIBCTB_KBHIT_H_INCLUDED_
namespace ctb {
char GetKey();
} // namespace ctb
#endif

View File

@ -0,0 +1,94 @@
#ifndef LIBCTB_LINUX_SERPORT_H_INCLUDED_
#define LIBCTB_LINUX_SERPORT_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: linux/serport.h
// Purpose:
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/serportx.h"
#include <linux/serial.h>
#include <termios.h>
namespace ctb {
/*!
\class SerialPort
\brief the linux version
*/
class SerialPort : public SerialPort_x
{
protected:
/*!
\brief under Linux, the serial ports are normal file descriptor
*/
int fd;
/*!
\brief Linux defines this struct termios for controling asynchronous
communication. t covered the active settings, save_t the original
settings.
*/
struct termios t, save_t;
/*!
\brief The Linux serial driver summing all breaks, framings, overruns
and parity errors for each port during system runtime. Because we only
need the errors during a active connection, we must save the actual
error numbers in this separate structurs.
*/
struct serial_icounter_struct save_info, last_info;
/*!
\brief adaptor member function, to convert the plattform independent
type wxBaud into a linux conform value.
\param baud the baudrate as wxBaud type
\return speed_t linux specific data type, defined in termios.h
*/
speed_t AdaptBaudrate( int baud );
int CloseDevice();
int OpenDevice(const char* devname, void* dcs);
/*!
\brief internal member function to set an unusal (non-standard)
baudrate. Called by SetBaudrate.
*/
int SetBaudrateAny( int baudrate );
/*!
\brief internal member function to set a standard baudrate.
Called by SetBaudrate.
*/
int SetBaudrateStandard( int baudrate );
public:
SerialPort();
~SerialPort();
int ChangeLineState( SerialLineState flags );
int ClrLineState( SerialLineState flags );
int GetLineState();
int Ioctl(int cmd,void* args);
int IsOpen();
int Read(char* buf,size_t len);
int SendBreak(int duration);
int SetBaudrate( int baudrate );
int SetParityBit( bool parity );
int SetLineState( SerialLineState flags );
int Write(char* buf,size_t len);
};
} // namespace ctb
#endif

View File

@ -0,0 +1,139 @@
#ifndef LIBCTB_LINUX_TIMER_H_INCLUDED_
#define LIBCTB_LINUX_TIMER_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: linux/timer.h
// Purpose:
// Author: Joachim Buermann
// Id: $Id: timer.h,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
/**
\file timer.h
*/
#include <pthread.h>
namespace ctb {
/*!
\brief A data struct, using from class timer.
*/
struct timer_control
{
/*!
under linux, we used usec internally
*/
unsigned int usecs;
/*!
covers the adress of the exitflag
*/
int *exitflag;
/*!
covers the adress of the exit function. NULL, if
there was no exit function.
*/
void* (*exitfnc)(void*);
};
/*!
\class Timer
\brief A thread based timer class for handling timeouts in
an easier way.
On starting every timer instance will create it's own thread.
The thread makes simply nothing, until it's given time is over.
After that, he set a variable, refer by it's adress to one
and exit.
There are a lot of situations, which the timer class must handle.
The timer instance leaves his valid range (for example, the
timer instance is local inside a function, and the function fished)
BEFORE the thread was ending. In this case, the destructor must
terminate the thread in a correct way. (This is very different
between the OS. threads are a system resource like file descriptors
and must be deallocated after using it).
The thread should be asynchronously stopped. Means, under all
circumstance, it must be possible, to finish the timer and start
it again.
Several timer instance can be used simultanously.
*/
class Timer
{
protected:
/*!
control covers the time interval, the adress
of the exitflag, and if not null, a function, which will
be called on the end.
*/
timer_control control;
/*!
stopped will be set by calling the stop() method.
Internaly the timer thread steadily tests the state of
this variable. If stopped not zero, the thread will be
finished.
*/
int stopped;
/*!
under linux we use the pthread library. tid covers the
identifier for a separate threads.
*/
pthread_t tid;
/*!
here we store the time interval, whilst the timer run.
This is waste!!!
*/
unsigned int timer_secs;
public:
/*!
The constructor creates an timer object with the given
properties. The timer at this moment is not started. This
will be done with the start() member function.
\param msec time interval after that the the variable
pointed by exitflag is setting to one.
\param exitflag the adress of an integer, which was set
to one after the given time interval.
\warning The integer variable shouldn't leave it's valid
range, before the timer was finished. So never take a
local variable.
\param exitfnc A function, which was called after msec.
If you don't want this, refer a NULL pointer.
*/
Timer(unsigned int msec,int* exitflag,void*(*exitfnc)(void*));
/*!
the destructor. If his was called (for example by leaving the
valid range of the timer object), the timer thread automaticaly
will finished. The exitflag wouldn't be set, also the exitfnc
wouldn't be called.
*/
~Timer();
/*!
starts the timer. But now a thread will created and started.
After this, the timer thread will be running until he was stopped
by calling stop() or reached his given time interval.
*/
int start();
/*!
stops the timer and canceled the timer thread. After timer::stop() a new
start() will started the timer from beginning.
*/
int stop();
};
/*!
\brief sleepms
A plattform independent function, to go to sleep for the given
time interval.
\param ms time interval in milli seconds
*/
void sleepms(unsigned int ms);
} // namespace ctb
#endif

View File

@ -0,0 +1,25 @@
#ifndef LIBCTB_PORTSCAN_H_INCLUDED_
#define LIBCTB_PORTSCAN_H_INCLUDED_
#include <string>
#include <vector>
/**
\file portscan.h
*/
namespace ctb {
/*!
\brief returns all available COM ports as an array of strings.
\param result stores the available COM ports
\param checkInUse return only ports which are available AND
unused (default)
\return true if successful, false otherwise
*/
bool GetAvailablePorts( std::vector<std::string>& result,
bool checkInUse = true );
} // namespace ctb
#endif

View File

@ -0,0 +1,20 @@
#ifndef LIBCTB_SERPORT_H_INCLUDED_
#define LIBCTB_SERPORT_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: serport.h
// Purpose: simple wrapper file
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#if defined (WIN32)
# include "ctb-0.16/win32/serport.h"
#else
# include "ctb-0.16/linux/serport.h"
#endif
#endif
// __SERPORT_BASE_H

View File

@ -0,0 +1,451 @@
#ifndef LIBCTB_SERPORTX_H_INCLUDED_
#define LIBCTB_SERPORTX_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: serportx.h
// Purpose:
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include "ctb-0.16/iobase.h"
#if defined (WIN32)
# define snprintf _snprintf
#endif
/**
\file serportx.h
*/
/*!
\def SERIALPORT_NAME_LEN
defines the maximum length of the os depending serial port names
*/
#define SERIALPORT_NAME_LEN 32
namespace ctb {
/*! specifices the first serial port */
extern const char* COM1;
/*! specifies the second serial port */
extern const char* COM2;
/*! specifies the third serial port */
extern const char* COM3;
/*! specifies the fourth serial port */
extern const char* COM4;
/*! specifies the fifth serial port */
extern const char* COM5;
/*! specifies the sixth serial port */
extern const char* COM6;
/*! specifies the seventh serial port */
extern const char* COM7;
/*! specifies the eighth serial port */
extern const char* COM8;
/*! specifies the ninth serial port */
extern const char* COM9;
/*! specifies the tenth serial port */
extern const char* COM10;
/*! specifies the eleventh serial port */
extern const char* COM11;
/*! specifies the twelfth serial port */
extern const char* COM12;
/*! specifies the thriteenth serial port */
extern const char* COM13;
/*! specifies the fourteenth serial port */
extern const char* COM14;
/*! specifies the fiveteenth serial port */
extern const char* COM15;
/*! specifies the sixteenth serial port */
extern const char* COM16;
/*! specifies the seventeenth serial port */
extern const char* COM17;
/*! specifies the eighteenth serial port */
extern const char* COM18;
/*! specifies the nineteenth serial port */
extern const char* COM19;
/*! specifies the twentieth serial port */
extern const char* COM20;
/*!
\enum Parity
\brief Defines the different modes of parity checking. Under
Linux, the struct termios will be set to provide the wanted
behaviour.
*/
enum Parity
{
/*! no parity check */
ParityNone,
/*! odd parity check */
ParityOdd,
/*! even parity check */
ParityEven,
/*! mark (not implemented yet) */
ParityMark,
/*! space (not implemented yet) */
ParitySpace
};
/*!
\enum SerialLineState
Defines the different modem control lines. The value for
each item are defined in /usr/include/bits/ioctl-types.h.
This is the linux definition. The window version translate
each item in it's own value.
modem lines defined in ioctl-types.h
\code
#define TIOCM_LE 0x001
#define TIOCM_DTR 0x002
#define TIOCM_RTS 0x004
#define TIOCM_ST 0x008
#define TIOCM_SR 0x010
#define TIOCM_CTS 0x020
#define TIOCM_CAR 0x040
#define TIOCM_RNG 0x080
#define TIOCM_DSR 0x100
#define TIOCM_CD TIOCM_CAR
#define TIOCM_RI TIOCM_RNG
\endcode
*/
enum SerialLineState
{
/*! Data Carrier Detect (read only) */
LinestateDcd = 0x040,
/*! Clear To Send (read only) */
LinestateCts = 0x020,
/*! Data Set Ready (read only) */
LinestateDsr = 0x100,
/*! Data Terminal Ready (write only) */
LinestateDtr = 0x002,
/*! Ring Detect (read only) */
LinestateRing = 0x080,
/*! Request To Send (write only) */
LinestateRts = 0x004,
/*! no active line state, use this for clear */
LinestateNull = 0x000
};
/*!
\struct SerialPort_DCS
The device control struct for the serial communication class.
This struct should be used, if you refer advanced parameter.
*/
struct SerialPort_DCS
{
/*! the baudrate */
int baud;
/*! the parity */
Parity parity;
/*! the wordlen */
unsigned char wordlen;
/*! count of stopbits */
unsigned char stopbits;
/*! rtscts flow control */
bool rtscts;
/*! XON/XOFF flow control */
bool xonxoff;
/*! buffer for internal use */
char buf[16];
SerialPort_DCS() {
baud = 38400;
parity = ParityNone;
wordlen = 8;
stopbits = 1;
rtscts = false;
xonxoff = false;
};
// to avoid memory leak warnings generated by swig
~SerialPort_DCS() {};
/*!
\brief returns the internal settings of the DCS as a human
readable string like '8N1 115200'.
\return the internal settings as null terminated string
*/
char* GetSettings() {
const char ac[5] = {'N','O','E','M','S'};
memset(buf,0,sizeof(buf));
snprintf(buf,sizeof(buf)-1,"%i%c%i %i",
wordlen,
ac[parity],
stopbits,
baud);
return buf;
};
};
/*!
\struct SerialPort_EINFO
The internal communication error struct. It contains the number
of each error (break, framing, overrun and parity) since opening
the serial port. Each error number will be cleared if the open
methode was called.
*/
struct SerialPort_EINFO
{
/*! number of breaks */
int brk;
/*! number of framing errors */
int frame;
/*! number of overrun errors */
int overrun;
/*! number of parity errors */
int parity;
SerialPort_EINFO() {
brk = frame = overrun = parity = 0;
};
~SerialPort_EINFO() {};
};
/*!
\enum SerialPortIoctls
The following Ioctl calls are only valid for the SerialPort
class.
*/
enum SerialPortIoctls {
/*!
Get all numbers of occured communication errors (breaks
framing, overrun and parity), so the args parameter of
the Ioctl call must pointed to a SerialPort_EINFO
struct.
*/
CTB_SER_GETEINFO = CTB_SERIAL,
/*!
Get integer 1, if a break occured since the last call
so the args parameter of the Ioctl methode must pointed
to an integer value. If there was no break, the result
is integer 0.
*/
CTB_SER_GETBRK,
/*!
Get integer 1, if a framing occured since the last call
so the args parameter of the Ioctl methode must pointed
to an integer value. If there was no break, the result
is integer 0.
*/
CTB_SER_GETFRM,
/*!
Get integer 1, if a overrun occured since the last call
so the args parameter of the Ioctl methode must pointed
to an integer value. If there was no break, the result
is integer 0.
*/
CTB_SER_GETOVR,
/*!
Get integer 1, if a parity occured since the last call
so the args parameter of the Ioctl methode must pointed
to an integer value. If there was no break, the result
is integer 0.
*/
CTB_SER_GETPAR,
/*!
Get the number of bytes received by the serial port driver
but not yet read by a Read or Readv Operation.
*/
CTB_SER_GETINQUE,
/*!
Set the parity bit on or off to use it as a ninth bit.
*/
CTB_SER_SETPAR
};
/*!
\class SerialPort_x
SerialPort_x is the basic class for serial communication via
the serial comports. It is also an abstract class and defines
all necessary methods, which the derivated plattform depended
classes must be invoke.
*/
class SerialPort_x : public IOBase
{
protected:
/*!
\brief contains the internal settings of the serial port like
baudrate, protocol, wordlen and so on.
*/
SerialPort_DCS m_dcs;
/*!
\brief contains the internal (os specific) name of the serial
device.
*/
char m_devname[SERIALPORT_NAME_LEN];
public:
/*!
\enum FlowControl
\brief Specifies the flow control.
*/
enum FlowControl
{
NoFlowControl, /*!< No flow control at all */
RtsCtsFlowControl, /*!< Enable RTS/CTS hardware flow control */
XonXoffFlowControl /*!< Enable XON/XOFF protocol */
};
SerialPort_x() {m_devname[0] = '\0';};
virtual ~SerialPort_x() {};
/*!
\brief returns the name of the class instance. You find this useful,
if you handle different devices like a serial port or a gpib device
via a IOBase pointer.
\return name of the class.
*/
const char* ClassName() {return "ctb::SerialPort";};
/*!
\brief change the linestates according to which bits
are set/unset in flags.
\param flags valid line flags are SERIAL_LINESTATE_DSR and/or
SERIAL_LINESTATE_RTS
\return zero on success, -1 if an error occurs
*/
virtual int ChangeLineState( SerialLineState flags ) = 0;
/*!
\brief turn off status lines depending upon which bits (DSR and/or RTS)
are set in flags.
\param flags valid line flags are SERIAL_LINESTATE_DSR and/or
SERIAL_LINESTATE_RTS
\return zero on success, -1 if an error occurs
*/
virtual int ClrLineState( SerialLineState flags ) = 0;
/*!
\brief Read the line states of DCD, CTS, DSR and RING
\return returns the appropriate bits on sucess, otherwise -1
*/
virtual int GetLineState() = 0;
/*!
\brief request the current settings of the connected serial port
as a null terminated string.
\return the settings as a string like '8N1 115200'
*/
virtual char* GetSettingsAsString() {
return m_dcs.GetSettings();
};
/*!
\brief Many operating characteristics are only possible for
special devices. To avoid the need of a lot of different functions
and to give the user a uniform interface, all this special
operating instructions will covered by one Ioctl methode (like
the linux ioctl call).
The Ioctl command (cmd) has encoded in it whether the argument
is an in parameter or out parameter, and the size of the
argument args in bytes. Macros and defines used in specifying an
ioctl request are located in iobase.h and the header file for
the derivated device (for example in serportx.h).
\param cmd one of SerialPortIoctls specify the ioctl request.
\param args is a typeless pointer to a memory location, where
Ioctl reads the request arguments or write the results.
Please note, that an invalid memory location or size involving
a buffer overflow or segmention fault!
*/
virtual int Ioctl(int cmd,void* args) {return -1;};
/*!
\brief Opens a serial port in a user likely way. Insteed of
using the Device Control Struct just input your parameter in a
more intuitive manner.
\param portname the name of the serial port
\param baudrate any baudrate, also an unusual one, if your
serial device support them
\param protocol a string with the number of databits (5...8),
the parity setting (N=None,O=Odd,E=Even,M=Mark,S=Space), also
in lower case, and the count of stopbits (1...2)
\param flowControl one of NoFlowControl, RtsCtsFlowControl or
XonXoffFlowControl.
\return the new file descriptor, or -1 if an error occurred
*/
int Open( const char* portname, int baudrate,
const char* protocol = "8N1",
FlowControl flowControl = NoFlowControl );
/*!
\brief Opens the serial port with the given number.
\note The port numbering starts with 1 (COM1 for windows and
/dev/ttyS0 for Linux. Please note, that USB to RS232 converter
in Linux are named as /dev/ttyUSBx and from there have to
opened with their device name!
\param number of the serial port count from 1
\param baudrate any baudrate, also an unusual one, if your
serial device support them
\param protocol a string with the number of databits (5...8),
the parity setting (N=None,O=Odd,E=Even,M=Mark,S=Space), also
in lower case, and the count of stopbits (1...2)
\param flowControl one of NoFlowControl, RtsCtsFlowControl or
XonXoffFlowControl.
\return the new file descriptor, or -1 if an error occurred
*/
int Open( const int portnumber, int baudrate,
const char* protocol = "8N1",
FlowControl flowControl = NoFlowControl );
// Open overrides and hides the IOBase::Open( const char*
// devname, void* dcs ) of the base class! So bring it into scope
// again!
using IOBase::Open;
/*!
\brief Sendbreak transmits a continuous stream of zero-valued
bits for a specific duration.
\param duration If duration is zero, it transmits
zero-valued bits for at least 0.25 seconds, and not more that
0.5 seconds. If duration is not zero, it sends zero-valued bits
for duration*N seconds, where N is at least 0.25, and not more
than 0.5.
\return zero on success, -1 if an error occurs.
*/
virtual int SendBreak(int duration) = 0;
/*!
\brief Set the baudrate (also non-standard)
Please note: Non-standard baudrates like 70000 are not supported
by each UART and depends on the RS232 chipset you apply.
\param baudrate the new baudrate
\return zero on success, -1 if an error occurs
*/
virtual int SetBaudrate( int baudrate ) = 0;
/*!
\brief turn on status lines depending upon which bits (DSR and/or RTS)
are set in flags.
\param flags valid line flags are SERIAL_LINESTATE_DSR and/or
SERIAL_LINESTATE_RTS
\return zero on success, -1 if an error occurs
*/
virtual int SetLineState( SerialLineState flags ) = 0;
/*!
\brief Set the parity bit to a firm state, for instance to use
the parity bit as the ninth bit in a 9 bit dataword
communication.
\return zero on succes, a negative value if an error occurs
*/
virtual int SetParityBit( bool parity ) = 0;
/*!
\brief check the given baudrate against a list of standard rates.
\ return true, if the baudrate is a standard value, false
otherwise
*/
static bool IsStandardRate( int rate );
};
} // namespace ctb
#endif

View File

@ -0,0 +1,19 @@
#ifndef LIBCTB_TIMER_H_INCLUDED_
#define LIBCTB_TIMER_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: timer.h
// Purpose: simple wrapper file
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#if defined (WIN32)
# include "win32/timer.h"
#else
# include "linux/timer.h"
#endif
#endif

View File

@ -0,0 +1,17 @@
#ifndef LIBCTB_WIN32_GETOPT_H_INCLUDED_
#define LIBCTB_WIN32_GETOPT_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: win32/getopt.h
// Purpose:
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
extern char* optarg;
extern int optind;
int getopt(int argc, char* argv[], char* optstring);
#endif

View File

@ -0,0 +1,414 @@
/*
*
*
* Win32 include file
* for accessing the 32-bit GPIB DLL (gpib-32.dll)
*
*
* Contains user variables (ibsta, iberr, ibcnt, ibcntl),
* function prototypes and useful defined constants for
* calling NI-488 and NI-488.2 routines from a Microsoft
* C/C++ Win32 application.
*
*
* Copyright 1998 National Instruments Corporation
*
*/
#ifndef DECL_32_H // ensure we are only included once
#define DECL_32_H
#include "windows.h"
#ifdef __cplusplus
extern "C" {
#endif
/***************************************************************************/
/* HANDY CONSTANTS FOR USE BY APPLICATION PROGRAMS ... */
/***************************************************************************/
#define UNL 0x3f /* GPIB unlisten command */
#define UNT 0x5f /* GPIB untalk command */
#define GTL 0x01 /* GPIB go to local */
#define SDC 0x04 /* GPIB selected device clear */
#define PPC 0x05 /* GPIB parallel poll configure */
#define GET 0x08 /* GPIB group execute trigger */
#define TCT 0x09 /* GPIB take control */
#define LLO 0x11 /* GPIB local lock out */
#define DCL 0x14 /* GPIB device clear */
#define PPU 0.16 /* GPIB parallel poll unconfigure */
#define SPE 0x18 /* GPIB serial poll enable */
#define SPD 0x19 /* GPIB serial poll disable */
#define PPE 0x60 /* GPIB parallel poll enable */
#define PPD 0x70 /* GPIB parallel poll disable */
/* GPIB status bit vector : */
/* global variable ibsta and wait mask */
#define ERR (1<<15) /* Error detected */
#define TIMO (1<<14) /* Timeout */
#define END (1<<13) /* EOI or EOS detected */
#define SRQI (1<<12) /* SRQ detected by CIC */
#define RQS (1<<11) /* Device needs service */
#define CMPL (1<<8) /* I/O completed */
#define LOK (1<<7) /* Local lockout state */
#define REM (1<<6) /* Remote state */
#define CIC (1<<5) /* Controller-in-Charge */
#define ATN (1<<4) /* Attention asserted */
#define TACS (1<<3) /* Talker active */
#define LACS (1<<2) /* Listener active */
#define DTAS (1<<1) /* Device trigger state */
#define DCAS (1<<0) /* Device clear state */
/* Error messages returned in global variable iberr */
#define EDVR 0 /* System error */
#define ECIC 1 /* Function requires GPIB board to be CIC */
#define ENOL 2 /* Write function detected no Listeners */
#define EADR 3 /* Interface board not addressed correctly*/
#define EARG 4 /* Invalid argument to function call */
#define ESAC 5 /* Function requires GPIB board to be SAC */
#define EABO 6 /* I/O operation aborted */
#define ENEB 7 /* Non-existent interface board */
#define EDMA 8 /* Error performing DMA */
#define EOIP 10 /* I/O operation started before previous */
/* operation completed */
#define ECAP 11 /* No capability for intended operation */
#define EFSO 12 /* File system operation error */
#define EBUS 14 /* Command error during device call */
#define ESTB 15 /* Serial poll status byte lost */
#define ESRQ 16 /* SRQ remains asserted */
#define ETAB 20 /* The return buffer is full. */
#define ELCK 21 /* Address or board is locked. */
/* EOS mode bits */
#define BIN (1<<12) /* Eight bit compare */
#define XEOS (1<<11) /* Send END with EOS byte */
#define REOS (1<<10) /* Terminate read on EOS */
/* Timeout values and meanings */
#define TNONE 0 /* Infinite timeout (disabled) */
#define T10us 1 /* Timeout of 10 us (ideal) */
#define T30us 2 /* Timeout of 30 us (ideal) */
#define T100us 3 /* Timeout of 100 us (ideal) */
#define T300us 4 /* Timeout of 300 us (ideal) */
#define T1ms 5 /* Timeout of 1 ms (ideal) */
#define T3ms 6 /* Timeout of 3 ms (ideal) */
#define T10ms 7 /* Timeout of 10 ms (ideal) */
#define T30ms 8 /* Timeout of 30 ms (ideal) */
#define T100ms 9 /* Timeout of 100 ms (ideal) */
#define T300ms 10 /* Timeout of 300 ms (ideal) */
#define T1s 11 /* Timeout of 1 s (ideal) */
#define T3s 12 /* Timeout of 3 s (ideal) */
#define T10s 13 /* Timeout of 10 s (ideal) */
#define T30s 14 /* Timeout of 30 s (ideal) */
#define T100s 15 /* Timeout of 100 s (ideal) */
#define T300s 16 /* Timeout of 300 s (ideal) */
#define T1000s 17 /* Timeout of 1000 s (ideal) */
/* IBLN Constants */
#define NO_SAD 0
#define ALL_SAD -1
/* The following constants are used for the second parameter of the
* ibconfig function. They are the "option" selection codes.
*/
#define IbcPAD 0x0001 /* Primary Address */
#define IbcSAD 0x0002 /* Secondary Address */
#define IbcTMO 0x0003 /* Timeout Value */
#define IbcEOT 0x0004 /* Send EOI with last data byte? */
#define IbcPPC 0x0005 /* Parallel Poll Configure */
#define IbcREADDR 0x0006 /* Repeat Addressing */
#define IbcAUTOPOLL 0x0007 /* Disable Auto Serial Polling */
#define IbcCICPROT 0x0008 /* Use the CIC Protocol? */
#define IbcIRQ 0x0009 /* Use PIO for I/O */
#define IbcSC 0x000A /* Board is System Controller? */
#define IbcSRE 0x000B /* Assert SRE on device calls? */
#define IbcEOSrd 0x000C /* Terminate reads on EOS */
#define IbcEOSwrt 0x000D /* Send EOI with EOS character */
#define IbcEOScmp 0x000E /* Use 7 or 8-bit EOS compare */
#define IbcEOSchar 0x000F /* The EOS character. */
#define IbcPP2 0x0010 /* Use Parallel Poll Mode 2. */
#define IbcTIMING 0x0011 /* NORMAL, HIGH, or VERY_HIGH timing. */
#define IbcDMA 0x0012 /* Use DMA for I/O */
#define IbcReadAdjust 0x0013 /* Swap bytes during an ibrd. */
#define IbcWriteAdjust 0x014 /* Swap bytes during an ibwrt. */
#define IbcSendLLO 0x0017 /* Enable/disable the sending of LLO. */
#define IbcSPollTime 0x0018 /* Set the timeout value for serial polls. */
#define IbcPPollTime 0x0019 /* Set the parallel poll length period. */
#define IbcEndBitIsNormal 0x001A /* Remove EOS from END bit of IBSTA. */
#define IbcUnAddr 0x001B /* Enable/disable device unaddressing. */
#define IbcSignalNumber 0x001C /* Set UNIX signal number - unsupported */
#define IbcBlockIfLocked 0x001D /* Enable/disable blocking for locked boards/devices */
#define IbcHSCableLength 0x001F /* Length of cable specified for high speed timing.*/
#define IbcIst 0x0020 /* Set the IST bit. */
#define IbcRsv 0x0021 /* Set the RSV byte. */
/*
* Constants that can be used (in addition to the ibconfig constants)
* when calling the ibask() function.
*/
#define IbaPAD IbcPAD
#define IbaSAD IbcSAD
#define IbaTMO IbcTMO
#define IbaEOT IbcEOT
#define IbaPPC IbcPPC
#define IbaREADDR IbcREADDR
#define IbaAUTOPOLL IbcAUTOPOLL
#define IbaCICPROT IbcCICPROT
#define IbaIRQ IbcIRQ
#define IbaSC IbcSC
#define IbaSRE IbcSRE
#define IbaEOSrd IbcEOSrd
#define IbaEOSwrt IbcEOSwrt
#define IbaEOScmp IbcEOScmp
#define IbaEOSchar IbcEOSchar
#define IbaPP2 IbcPP2
#define IbaTIMING IbcTIMING
#define IbaDMA IbcDMA
#define IbaReadAdjust IbcReadAdjust
#define IbaWriteAdjust IbcWriteAdjust
#define IbaSendLLO IbcSendLLO
#define IbaSPollTime IbcSPollTime
#define IbaPPollTime IbcPPollTime
#define IbaEndBitIsNormal IbcEndBitIsNormal
#define IbaUnAddr IbcUnAddr
#define IbaSignalNumber IbcSignalNumber
#define IbaBlockIfLocked IbcBlockIfLocked
#define IbaHSCableLength IbcHSCableLength
#define IbaIst IbcIst
#define IbaRsv IbcRsv
#define IbaBNA 0x0200 /* A device's access board. */
/* Values used by the Send 488.2 command. */
#define NULLend 0x00 /* Do nothing at the end of a transfer.*/
#define NLend 0x01 /* Send NL with EOI after a transfer. */
#define DABend 0x02 /* Send EOI with the last DAB. */
/* Value used by the 488.2 Receive command.
*/
#define STOPend 0x0100
/* Address type (for 488.2 calls) */
typedef short Addr4882_t; /* System dependent: must be 16 bits */
/*
* This macro can be used to easily create an entry in address list
* that is required by many of the 488.2 functions. The primary address goes in the
* lower 8-bits and the secondary address goes in the upper 8-bits.
*/
#define MakeAddr(pad, sad) ((Addr4882_t)(((pad)&0xFF) | ((sad)<<8)))
/*
* This value is used to terminate an address list. It should be
* assigned to the last entry.
*/
#ifndef NOADDR
#define NOADDR (Addr4882_t)((unsigned short)0xFFFF)
#endif
/*
* The following two macros are used to "break apart" an address list
* entry. They take an unsigned integer and return either the primary
* or secondary address stored in the integer.
*/
#define GetPAD(val) ((val) & 0xFF)
#define GetSAD(val) (((val) >> 8) & 0xFF)
/* iblines constants */
#define ValidEOI (short)0x0080
#define ValidATN (short)0x0040
#define ValidSRQ (short)0x0020
#define ValidREN (short)0x0010
#define ValidIFC (short)0x0008
#define ValidNRFD (short)0x0004
#define ValidNDAC (short)0x0002
#define ValidDAV (short)0x0001
#define BusEOI (short)0x8000
#define BusATN (short)0x4000
#define BusSRQ (short)0x2000
#define BusREN (short)0x1000
#define BusIFC (short)0x0800
#define BusNRFD (short)0x0400
#define BusNDAC (short)0x0200
#define BusDAV (short)0x0100
/****
**** typedef for ibnotify callback ****
****/
typedef int (__stdcall * GpibNotifyCallback_t)(int, int, int, long, PVOID);
#define IBNOTIFY_REARM_FAILED 0xE00A003F
/*************************************************************************/
/* */
/* iblockx and ibunlockx definitions --- for use with GPIB-ENET only !! */
/* */
/*************************************************************************/
#define TIMMEDIATE -1
#define TINFINITE -2
#define MAX_LOCKSHARENAME_LENGTH 64
#if defined(UNICODE)
#define iblockx iblockxW
#else
#define iblockx iblockxA
#endif
extern int __stdcall iblockxA (int ud, int LockWaitTime, PCHAR LockShareName);
extern int __stdcall iblockxW (int ud, int LockWaitTime, PWCHAR LockShareName);
extern int __stdcall ibunlockx (int ud);
/***************************************************************************/
/* IBSTA, IBERR, IBCNT, IBCNTL and FUNCTION PROTOTYPES */
/* ( only included if not accessing the 32-bit DLL directly ) */
/***************************************************************************/
#if !defined(GPIB_DIRECT_ACCESS)
/*
* Set up access to the user variables (ibsta, iberr, ibcnt, ibcntl).
* These are declared and exported by the 32-bit DLL. Separate copies
* exist for each process that accesses the DLL. They are shared by
* multiple threads of a single process.
*/
extern int ibsta;
extern int iberr;
extern int ibcnt;
extern long ibcntl;
#if defined(UNICODE)
#define ibbna ibbnaW
#define ibfind ibfindW
#define ibrdf ibrdfW
#define ibwrtf ibwrtfW
#else
#define ibbna ibbnaA
#define ibfind ibfindA
#define ibrdf ibrdfA
#define ibwrtf ibwrtfA
#endif
/*
* Extern 32-bit GPIB DLL functions
*/
/* NI-488 Function Prototypes */
extern int __stdcall ibfindA (LPCSTR udname);
extern int __stdcall ibbnaA (int ud, LPCSTR udname);
extern int __stdcall ibrdfA (int ud, LPCSTR filename);
extern int __stdcall ibwrtfA (int ud, LPCSTR filename);
extern int __stdcall ibfindW (LPCWSTR udname);
extern int __stdcall ibbnaW (int ud, LPCWSTR udname);
extern int __stdcall ibrdfW (int ud, LPCWSTR filename);
extern int __stdcall ibwrtfW (int ud, LPCWSTR filename);
extern int __stdcall ibask (int ud, int option, PINT v);
extern int __stdcall ibcac (int ud, int v);
extern int __stdcall ibclr (int ud);
extern int __stdcall ibcmd (int ud, PVOID buf, long cnt);
extern int __stdcall ibcmda (int ud, PVOID buf, long cnt);
extern int __stdcall ibconfig (int ud, int option, int v);
extern int __stdcall ibdev (int boardID, int pad, int sad, int tmo, int eot, int eos);
extern int __stdcall ibdiag (int ud, PVOID buf, long cnt);
extern int __stdcall ibdma (int ud, int v);
extern int __stdcall ibeos (int ud, int v);
extern int __stdcall ibeot (int ud, int v);
extern int __stdcall ibgts (int ud, int v);
extern int __stdcall ibist (int ud, int v);
extern int __stdcall iblines (int ud, PSHORT result);
extern int __stdcall ibln (int ud, int pad, int sad, PSHORT listen);
extern int __stdcall ibloc (int ud);
extern int __stdcall ibnotify (int ud, int mask, GpibNotifyCallback_t Callback, PVOID RefData);
extern int __stdcall ibonl (int ud, int v);
extern int __stdcall ibpad (int ud, int v);
extern int __stdcall ibpct (int ud);
extern int __stdcall ibpoke (int ud, long option, long v);
extern int __stdcall ibppc (int ud, int v);
extern int __stdcall ibrd (int ud, PVOID buf, long cnt);
extern int __stdcall ibrda (int ud, PVOID buf, long cnt);
extern int __stdcall ibrpp (int ud, PCHAR ppr);
extern int __stdcall ibrsc (int ud, int v);
extern int __stdcall ibrsp (int ud, PCHAR spr);
extern int __stdcall ibrsv (int ud, int v);
extern int __stdcall ibsad (int ud, int v);
extern int __stdcall ibsic (int ud);
extern int __stdcall ibsre (int ud, int v);
extern int __stdcall ibstop (int ud);
extern int __stdcall ibtmo (int ud, int v);
extern int __stdcall ibtrg (int ud);
extern int __stdcall ibwait (int ud, int mask);
extern int __stdcall ibwrt (int ud, PVOID buf, long cnt);
extern int __stdcall ibwrta (int ud, PVOID buf, long cnt);
// GPIB-ENET only functions to support locking across machines
extern int __stdcall iblock (int ud);
extern int __stdcall ibunlock (int ud);
/**************************************************************************/
/* Functions to access Thread-Specific copies of the GPIB global vars */
extern int __stdcall ThreadIbsta (void);
extern int __stdcall ThreadIberr (void);
extern int __stdcall ThreadIbcnt (void);
extern long __stdcall ThreadIbcntl (void);
/**************************************************************************/
/* NI-488.2 Function Prototypes */
extern void __stdcall AllSpoll (int boardID, Addr4882_t * addrlist, PSHORT results);
extern void __stdcall DevClear (int boardID, Addr4882_t addr);
extern void __stdcall DevClearList (int boardID, Addr4882_t * addrlist);
extern void __stdcall EnableLocal (int boardID, Addr4882_t * addrlist);
extern void __stdcall EnableRemote (int boardID, Addr4882_t * addrlist);
extern void __stdcall FindLstn (int boardID, Addr4882_t * addrlist, Addr4882_t * results, int limit);
extern void __stdcall FindRQS (int boardID, Addr4882_t * addrlist, PSHORT dev_stat);
extern void __stdcall PPoll (int boardID, PSHORT result);
extern void __stdcall PPollConfig (int boardID, Addr4882_t addr, int dataLine, int lineSense);
extern void __stdcall PPollUnconfig (int boardID, Addr4882_t * addrlist);
extern void __stdcall PassControl (int boardID, Addr4882_t addr);
extern void __stdcall RcvRespMsg (int boardID, PVOID buffer, long cnt, int Termination);
extern void __stdcall ReadStatusByte(int boardID, Addr4882_t addr, PSHORT result);
extern void __stdcall Receive (int boardID, Addr4882_t addr, PVOID buffer, long cnt, int Termination);
extern void __stdcall ReceiveSetup (int boardID, Addr4882_t addr);
extern void __stdcall ResetSys (int boardID, Addr4882_t * addrlist);
extern void __stdcall Send (int boardID, Addr4882_t addr, PVOID databuf, long datacnt, int eotMode);
extern void __stdcall SendCmds (int boardID, PVOID buffer, long cnt);
extern void __stdcall SendDataBytes (int boardID, PVOID buffer, long cnt, int eot_mode);
extern void __stdcall SendIFC (int boardID);
extern void __stdcall SendLLO (int boardID);
extern void __stdcall SendList (int boardID, Addr4882_t * addrlist, PVOID databuf, long datacnt, int eotMode);
extern void __stdcall SendSetup (int boardID, Addr4882_t * addrlist);
extern void __stdcall SetRWLS (int boardID, Addr4882_t * addrlist);
extern void __stdcall TestSRQ (int boardID, PSHORT result);
extern void __stdcall TestSys (int boardID, Addr4882_t * addrlist, PSHORT results);
extern void __stdcall Trigger (int boardID, Addr4882_t addr);
extern void __stdcall TriggerList (int boardID, Addr4882_t * addrlist);
extern void __stdcall WaitSRQ (int boardID, PSHORT result);
#endif
#ifdef __cplusplus
}
#endif
#endif // DECL_32_H

View File

@ -0,0 +1,74 @@
#ifndef LIBCTB_WIN32_TIMER_H_INCLUDED_
#define LIBCTB_WIN32_TIMER_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: win32/serport.h
// Purpose:
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "../serportx.h"
#include <windows.h>
namespace ctb {
/*!
\class SerialPort
\brief the win32 version
*/
class SerialPort : public SerialPort_x
{
protected:
/*!
\brief the win32 api equivalent for the Linux
file descriptor
*/
HANDLE fd;
/*!
\brief a very special struct in the win32 api for controling
an asynchronous serial communication through the com ports.
*/
OVERLAPPED m_ov;
/*!
\brief The win32 API only allows to test for an existing
break, framing, overrun or parity, not for the occured numbers.
So every error event decrement this internal error struct and
can request by an Ioctl call.
*/
SerialPort_EINFO einfo;
/*!
\brief The win32 API doesn't have any function to detect the
current state of the output lines RST and DTR (if someone knows
some function, please contact me).
So we save the state always after changing one or both lines
(for example, on Open, SetLineState and ChangeLineState)
*/
int m_rtsdtr_state;
int CloseDevice();
int OpenDevice(const char* devname, void* dcs);
public:
SerialPort();
~SerialPort();
int ChangeLineState( SerialLineState flags );
int ClrLineState( SerialLineState flags );
int GetLineState();
int Ioctl(int cmd,void* args);
int IsOpen();
int Read(char* buf,size_t len);
int SendBreak(int duration);
int SetBaudrate( int baudrate );
int SetLineState( SerialLineState flags );
int SetParityBit( bool parity );
int Write(char* buf,size_t len);
};
} // namespace ctb
#endif

View File

@ -0,0 +1,140 @@
#ifndef LIBCTB_WINDOWS_TIMER_H_INCLUDED_
#define LIBCTB_WINDOWS_TIMER_H_INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// Name: win32/timer.h
// Purpose:
// Author: Joachim Buermann
// Copyright: (c) 2010 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include <windows.h>
namespace ctb {
/*!
\brief A data struct, using from class timer.
*/
struct timer_control
{
/*!
under win32, we used msec internally
*/
unsigned int msecs;
/*!
covers the adress of the exitflag
*/
int *exitflag;
/*!
the running thread steadily polls this variable (only under win32).
If it's not zero, the thread terminate.
*/
MMRESULT stop;
/*!
covers the adress of the exit function. NULL, if
there was no exit function.
*/
void* (*exitfnc)(void*);
};
/*!
\class Timer
\brief A thread based timer class for handling timeouts in
an easier way.
On starting every timer instance will create it's own thread.
The thread makes simply nothing, until it's given time is over.
After that, he set a variable, refer by it's adress to one
and exit.
There are a lot of situations, which the timer class must handle.
The timer instance leaves his valid range (for example, the
timer instance is local inside a function, and the function fished)
BEFORE the thread was ending. In this case, the destructor must
terminate the thread in a correct way. (This is very different
between the OS. threads are a system resource like file descriptors
and must be deallocated after using it).
The thread should be asynchronously stopped. Means, under all
circumstance, it must be possible, to finish the timer and start
it again.
Several timer instance can be used simultanously.
*/
class Timer
{
protected:
/*!
\brief win32 needs this
*/
DWORD id;
/*!
\brief in win32 internal handle for the timer thread
*/
MMRESULT h;
/*!
control covers the time interval, the adress
of the exitflag, and if not null, a function, which will
be called on the end.
*/
timer_control control;
/*!
here we store the time interval, whilst the timer run.
This is waste!!!
*/
unsigned int timer_secs;
public:
/*!
The constructor creates an timer object with the given
properties. The timer at this moment is not started. This
will be done with the start() member function.
\param msec time interval after that the the variable
pointed by exitflag is setting to one.
\param exitflag the adress of an integer, which was set
to one after the given time interval.
\warning The integer variable shouldn't leave it's valid
range, before the timer was finished. So never take a
local variable.
\param exitfnc A function, which was called after msec.
If you don't want this, refer a NULL pointer.
*/
Timer(unsigned int msec,int* exitflag,void*(*exitfnc)(void*));
/*!
the destructor. If his was called (for example by leaving the
valid range of the timer object), the timer thread automaticaly
will finished. The exitflag wouldn't be set, also the exitfnc
wouldn't be called.
*/
~Timer();
/*!
starts the timer. But now a thread will created and started.
After this, the timer thread will be running until he was stopped
by calling stop() or reached his given time interval.
*/
int start();
/*!
stops the timer and canceled the timer thread. After timer::stop() a new
start() will started the timer from beginning.
*/
int stop();
};
/*!
\fn kill_all_timer()
\warning This function don't works under win32 and will be removed next
time. So don't use that!
*/
void kill_all_timer();
/*!
\fn
A plattform independent function, to go to sleep for the given
time interval.
\param ms time interval in milli seconds
*/
void sleepms(unsigned int ms);
} // namespace ctb
#endif

View File

@ -0,0 +1,455 @@
import wxctb, sys, re
DCD = wxctb.LinestateDcd
CTS = wxctb.LinestateCts
DSR = wxctb.LinestateDsr
DTR = wxctb.LinestateDtr
RING = wxctb.LinestateRing
RTS = wxctb.LinestateRts
NULL = wxctb.LinestateNull
def abstract():
import inspect
caller = inspect.getouterframes(inspect.currentframe())[1][3]
raise NotImplementedError(caller + ' must be implemented in subclass')
class IOBase:
def __init__(self):
self.device = None
# set timeout to 1000ms (the default)
self.timeout = 1000
def __del__(self):
pass
def Close(self):
if self.device:
self.device.Close()
def GetTimeout(self):
"""
Returns the internal timeout value in milliseconds
"""
return self.timeout
def Ioctl(self,cmd,arg):
if self.device:
self.device.Ioctl(cmd,arg)
def Open(self):
abstract()
def PutBack(self,char):
return self.device.PutBack(char)
def Read(self,length):
"""
Try to read the given count of data (length) and returns the
successfully readed number of data. The function never blocks.
For example:
readed = dev.Read(100)
"""
buf = "\x00"*(length+1)
rd = self.device.Read(buf,length)
return buf[0:rd]
def ReadBinary(self,eos="\n"):
"""
Special SCPI command. Read the next data coded as a SCPI
binary format.
A binary data transfer will be startet by '#'. The next byte
tells the count of bytes for the binary length header,
following by the length bytes. After these the data begins.
For example:
#500004xxxx
The header length covers 5 Byte, the length of the binary
data is 4 (x means the binary data bytes)
"""
try:
eoslen = len(eos)
b=self.Readv(2)
if len(b) == 2:
hl = int(b[1])
b = self.Readv(hl)
if len(b) == hl:
dl = int(b)
# don't left over the eos string or character in the
# device input buffer
data = self.Readv(dl+eoslen)
# check, if the binary data block is complete
if data[dl] == '#':
# not complete, another block is following
for c in data[dl:dl+eoslen]:
self.PutBack(c)
data = data[:dl] + self.ReadBinary()
return data
except:
pass
return ''
def ReadUntilEOS(self,eos="\n",quota=0):
"""
ReadUntilEOS(eosString=\"\\n\",timeout=1000)
Reads data until the given eos string was received (default is
the linefeed character (0x0a) or the internal timeout
(default 1000ms) was reached.
ReadUntilEOS returns the result as the following tuple:
['received string',state,readedBytes]
If a timeout occurred, state is 0, otherwise 1
"""
return self.device.ReadUntilEOS("",0,eos,self.timeout,quota)
def Readv(self,length):
"""
Try to read the given count of data. Readv blocks until all data
was readed successfully or the internal timeout, set with the
class member function SetTimeout(timeout), was reached.
Returns the readed data.
"""
buf = "\x00"*length
rd = self.device.Readv(buf,length,self.timeout)
return buf[0:rd]
def ResetBus(self):
"""
If the underlaying interface needs some special reset operations
(for instance the GPIB distinguish between a normal device reset
and a special bus reset), you can put some code here)
"""
pass
def SetTimeout(self,timeout):
"""
Set the internal timeout value in milliseconds for all blocked
operations like ReadUntilEOS, Readv and Writev.
"""
self.timeout = timeout
def Write(self,string):
"""
Writes the given string to the device and returns immediately.
Write returns the number of data bytes successfully written or a
negativ number if an error occured. For some circumstances, not
the complete string was written.
So you have to verify the return value to check this out.
"""
return self.device.Write(string,len(string))
def Writev(self,string):
"""
Writes the given string to the device. The function blocks until
the complete string was written or the internal timeout, set with
SetTimeout(timeout), was reached.
Writev returns the number of data successfully written or a
negativ value, if an errors occurred.
"""
return self.device.Writev(string,len(string),self.timeout)
class SerialPort(IOBase):
def __init__(self):
IOBase.__init__(self)
def __del__(self):
self.Close()
def ChangeLineState(self,lineState):
"""
Change (toggle) the state of each the lines given in the
linestate parameter. Possible values are DTR and/or RTS.
For example to toggle the RTS line only:
dev.ChangeLineState(RTS)
"""
self.device.ChangeLineState(lineState)
def ClrLineState(self,lineState):
"""
Clear the lines given in the linestate parameter. Possible
values are DTR and/or RTS. For example to clear only
the RTS line:
dev.ClrLineState(RTS)
"""
self.device.ClrLineState(lineState)
def GetAvailableBytes(self):
"""
Returns the available bytes in the input queue of the serial
driver.
"""
n = wxctb.new_intp()
wxctb.intp_assign(n, 0)
self.device.Ioctl(wxctb.CTB_SER_GETINQUE,n)
return wxctb.intp_value(n)
def GetCommErrors(self):
"""
Get the internal communication errors like breaks, framing,
parity or overrun errors.
Returns the count of each error as a tuple like this:
(b,f,o,p) = dev.GetCommErrors()
b: breaks, f: framing errors, o: overruns, p: parity errors
"""
einfo = wxctb.SerialPort_EINFO()
self.device.Ioctl(wxctb.CTB_SER_GETEINFO,einfo)
return einfo.brk,einfo.frame,einfo.overrun,einfo.parity
def GetLineState(self):
"""
Returns the current linestates of the CTS, DCD, DSR and RING
signal line as an integer value with the appropriate bits or
-1 on error.
For example:
lines = dev.GetLineState()
if lines & CTS:
print \"CTS is on\"
"""
return self.device.GetLineState()
def Open(self,devname,baudrate,protocol='8N1',handshake='no_handshake'):
"""
Open the device devname with the given baudrate, the protocol
like '8N1' (default) and the use of the handshake [no_handshake
(default), rtscts or xonxoff]
For example:
At Linux:
dev = SerialPort()
dev.Open(\"/dev/ttyS0\",115200)
or with a datalen of 7 bits, even parity, 2 stopbits and rts/cts
handshake:
dev.Open(\"/dev/ttyS0\",115200,'7E2',True)
At Windows:
dev = SerialPort()
dev.Open(\"COM1\",115200)
dev.Open(\"COM1\",115200,'7E2',True)
Returns the handle on success or a negativ value on failure.
"""
# the following parity values are valid:
# N:None, O:Odd, E:Even, M:Mark, S:Space
parity = {'N':0,'O':1,'E':2,'M':3,'S':4}
# the regular expression ensures a valid value for the datalen
# (5...8 bit) and the count of stopbits (1,2)
reg=re.compile(r"(?P<w>[8765])"r"(?P<p>[NOEMS])"r"(?P<s>[12])")
self.device = wxctb.SerialPort()
dcs = wxctb.SerialPort_DCS()
dcs.baud = baudrate
res = reg.search(protocol)
# handle the given protocol
if res:
dcs.wordlen = int(res.group('w'))
dcs.stopbits = int(res.group('s'))
dcs.parity = parity[res.group('p')]
# valid handshake are no one, rts/cts or xon/xoff
if handshake == 'rtscts':
dcs.rtscts = True
elif handshake == 'xonxoff':
dcs.xonxoff = True
return self.device.Open(devname,dcs)
def Reset(self):
"""
Send a break for 0.25s.
"""
self.device.SendBreak(0)
def SetBaudrate(self,baudrate):
"""
Set the baudrate for the device.
"""
self.device.SetBaudrate(baudrate)
def SetLineState(self,lineState):
"""
Set the lines given in the linestate parameter. Possible
values are DTR and/or RTS. For example to set both:
dev.SetLineState( DTR | RTS)
"""
self.device.SetLineState(lineState)
def SetParityBit(self,parity):
"""
Set the parity bit explicitly to 0 or 1. Use this function, if
you would like to simulate a 9 bit wordlen at what the ninth bit
was represented by the parity bit value. For example:
dev.SetParityBit( 0 )
dev.Write('some data sent with parity 0')
dev.SetParityBit( 1 )
dev.Write('another sequence with parity 1')
"""
return self.device.SetParityBit( parity )
class GpibDevice(IOBase):
"""
GPIB class
"""
def __init__(self):
IOBase.__init__(self)
def __del__(self):
self.Close()
def FindListeners(self,board = 0):
"""
Returns the address of the connected devices as a list.
If no device is listening, the list is empty. If an error
occurs an IOError exception raised. For example:
g = GPIB()
listeners = g.FindListeners()
"""
listeners = wxctb.GPIB_x_FindListeners(board)
if listeners < 0:
raise IOError("GPIB board error")
result = []
for i in range(1,31):
if listeners & (1 << i):
result.append(i)
return result
def GetEosChar(self):
"""
Get the internal EOS termination character (see SetEosChar).
For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosChar()
"""
eos = wxctb.new_intp()
wxctb.intp_assign(eos, 0)
self.device.Ioctl(wxctb.CTB_GPIB_GET_EOS_CHAR,eos)
return wxctb.intp_value(eos)
def GetEosMode(self):
"""
Get the internal EOS mode (see SetEosMode).
For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosMode()
"""
mode = wxctb.new_intp()
wxctb.intp_assign(mode, 0)
self.device.Ioctl(wxctb.CTB_GPIB_GET_EOS_MODE,mode)
return wxctb.intp_value(mode)
def GetError(self):
errorString = " "*256
self.device.GetError(errorString,256)
return errorString
def GetSTB(self):
"""
Returns the value of the internal GPIB status byte register.
"""
stb = wxctb.new_intp()
wxctb.intp_assign(stb, 0)
self.device.Ioctl(wxctb.CTB_GPIB_GETRSP,stb)
return wxctb.intp_value(stb)
# This is only for internal usage!!!
def Ibrd(self,length):
buf = "\x00"*length
state = self.device.Ibrd(buf,length)
return state,buf
# This is only for internal usage!!!
def Ibwrt(self,string):
return self.device.Ibwrt(string,len(string))
def Open(self,devname,adr,eosChar=10,eosMode=0x08|0x04):
"""
Open(gpibdevice,address,eosChar,eosMode)
Opens a connected device at the GPIB bus. gpibdevice means the
controller, (mostly \"gpib1\"), address the address of the desired
device in the range 1...31. The eosChar defines the EOS character
(default is linefeed), eosMode may be a combination of bits ORed
together. The following bits can be used:
0x04: Terminate read when EOS is detected.
0x08: Set EOI (End or identify line) with EOS on write function
0x10: Compare all 8 bits of EOS byte rather than low 7 bits
(all read and write functions). Default is 0x12
For example:
dev = GPIB()
dev.Open(\"gpib1\",17)
Opens the device with the address 17, linefeed as EOS (default)
and eos mode with 0x04 and 0x08.
Open returns >= 0 or a negativ value, if something going wrong.
"""
self.device = wxctb.GpibDevice()
dcs = wxctb.Gpib_DCS()
dcs.m_address1 = adr
dcs.m_eosChar = eosChar
dcs.m_eosMode = eosMode
result = self.device.Open(devname,dcs)
return result
def Reset(self):
"""
Resets the connected device. In the GPIB definition, the device
should be reset to it's initial state, so you can restart a
formely lost communication.
"""
self.device.Ioctl(wxctb.CTB_RESET,None)
def ResetBus(self):
"""
The command asserts the GPIB interface clear (IFC) line for
ast least 100us if the GPIB board is the system controller.
This initializes the GPIB and makes the interface CIC and
active controller with ATN asserted.
Note! The IFC signal resets only the GPIB interface functions
of the bus devices and not the internal device functions.
For a device reset you should use the Reset() command above.
"""
self.device.Ioctl(wxctb.CTB_GPIB_RESET_BUS,None)
def SetEosChar(self,eos):
"""
Configure the end-of-string (EOS) termination character.
Note! Defining an EOS byte does not cause the driver to
automatically send that byte at the end of write I/O
operations. The application is responsible for placing the
EOS byte at the end of the data strings that it defines.
(National Instruments NI-488.2M Function Reference Manual)
For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosChar(0x10)
"""
intp = wxctb.new_intp()
wxctb.intp_assign(intp, eos)
return self.device.Ioctl(wxctb.CTB_GPIB_SET_EOS_CHAR,intp)
def SetEosMode(self,mode):
"""
Set the EOS mode (handling).m_eosMode may be a combination
of bits ORed together. The following bits can be used:
0x04: Terminate read when EOS is detected.
0x08: Set EOI (End or identify line) with EOS on write function
0x10: Compare all 8 bits of EOS byte rather than low 7 bits
(all read and write functions). For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosMode(0x04 | 0x08)
"""
intp = wxctb.new_intp()
wxctb.intp_assign(intp, mode)
return self.device.Ioctl(wxctb.CTB_GPIB_SET_EOS_MODE,intp)
def GetKey():
"""
Returns the current pressed key or '\0', if no key is pressed.
You can simply create a query loop with:
while GetKey() == '\0':
... make some stuff ...
"""
return wxctb.GetKey()
def GetVersion():
"""
Returns the version of the ctb python module. The numbering
has the following format: x.y.z
x.y means the version of the underlaying ctb lib, z the version
of the python port.
"""
return "0.16"

View File

@ -0,0 +1,264 @@
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.40
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_wxctb', [dirname(__file__)])
except ImportError:
import _wxctb
return _wxctb
if fp is not None:
try:
_mod = imp.load_module('_wxctb', fp, pathname, description)
finally:
fp.close()
return _mod
_wxctb = swig_import_helper()
del swig_import_helper
else:
import _wxctb
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
def new_intp():
return _wxctb.new_intp()
new_intp = _wxctb.new_intp
def copy_intp(*args, **kwargs):
return _wxctb.copy_intp(*args, **kwargs)
copy_intp = _wxctb.copy_intp
def delete_intp(*args, **kwargs):
return _wxctb.delete_intp(*args, **kwargs)
delete_intp = _wxctb.delete_intp
def intp_assign(*args, **kwargs):
return _wxctb.intp_assign(*args, **kwargs)
intp_assign = _wxctb.intp_assign
def intp_value(*args, **kwargs):
return _wxctb.intp_value(*args, **kwargs)
intp_value = _wxctb.intp_value
class timer_control(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
__repr__ = _swig_repr
usecs = _swig_property(_wxctb.timer_control_usecs_get, _wxctb.timer_control_usecs_set)
exitflag = _swig_property(_wxctb.timer_control_exitflag_get, _wxctb.timer_control_exitflag_set)
exitfnc = _swig_property(_wxctb.timer_control_exitfnc_get, _wxctb.timer_control_exitfnc_set)
timer_control_swigregister = _wxctb.timer_control_swigregister
timer_control_swigregister(timer_control)
class Timer(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
this = _wxctb.new_Timer(*args, **kwargs)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_Timer
__del__ = lambda self : None;
def start(self): return _wxctb.Timer_start(self)
def stop(self): return _wxctb.Timer_stop(self)
Timer_swigregister = _wxctb.Timer_swigregister
Timer_swigregister(Timer)
def sleepms(*args, **kwargs):
return _wxctb.sleepms(*args, **kwargs)
sleepms = _wxctb.sleepms
CTB_RESET = _wxctb.CTB_RESET
class IOBase(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _wxctb.delete_IOBase
__del__ = lambda self : None;
def ClassName(self): return _wxctb.IOBase_ClassName(self)
def Close(self): return _wxctb.IOBase_Close(self)
def Ioctl(self, *args, **kwargs): return _wxctb.IOBase_Ioctl(self, *args, **kwargs)
def IsOpen(self): return _wxctb.IOBase_IsOpen(self)
def Open(self, *args, **kwargs): return _wxctb.IOBase_Open(self, *args, **kwargs)
def PutBack(self, *args, **kwargs): return _wxctb.IOBase_PutBack(self, *args, **kwargs)
def Read(self, *args, **kwargs): return _wxctb.IOBase_Read(self, *args, **kwargs)
def ReadUntilEOS(self, *args, **kwargs): return _wxctb.IOBase_ReadUntilEOS(self, *args, **kwargs)
def Readv(self, *args, **kwargs): return _wxctb.IOBase_Readv(self, *args, **kwargs)
def Write(self, *args, **kwargs): return _wxctb.IOBase_Write(self, *args, **kwargs)
def Writev(self, *args, **kwargs): return _wxctb.IOBase_Writev(self, *args, **kwargs)
IOBase_swigregister = _wxctb.IOBase_swigregister
IOBase_swigregister(IOBase)
ParityNone = _wxctb.ParityNone
ParityOdd = _wxctb.ParityOdd
ParityEven = _wxctb.ParityEven
ParityMark = _wxctb.ParityMark
ParitySpace = _wxctb.ParitySpace
LinestateDcd = _wxctb.LinestateDcd
LinestateCts = _wxctb.LinestateCts
LinestateDsr = _wxctb.LinestateDsr
LinestateDtr = _wxctb.LinestateDtr
LinestateRing = _wxctb.LinestateRing
LinestateRts = _wxctb.LinestateRts
LinestateNull = _wxctb.LinestateNull
class SerialPort_DCS(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
baud = _swig_property(_wxctb.SerialPort_DCS_baud_get, _wxctb.SerialPort_DCS_baud_set)
parity = _swig_property(_wxctb.SerialPort_DCS_parity_get, _wxctb.SerialPort_DCS_parity_set)
wordlen = _swig_property(_wxctb.SerialPort_DCS_wordlen_get, _wxctb.SerialPort_DCS_wordlen_set)
stopbits = _swig_property(_wxctb.SerialPort_DCS_stopbits_get, _wxctb.SerialPort_DCS_stopbits_set)
rtscts = _swig_property(_wxctb.SerialPort_DCS_rtscts_get, _wxctb.SerialPort_DCS_rtscts_set)
xonxoff = _swig_property(_wxctb.SerialPort_DCS_xonxoff_get, _wxctb.SerialPort_DCS_xonxoff_set)
buf = _swig_property(_wxctb.SerialPort_DCS_buf_get, _wxctb.SerialPort_DCS_buf_set)
def __init__(self):
this = _wxctb.new_SerialPort_DCS()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_SerialPort_DCS
__del__ = lambda self : None;
def GetSettings(self): return _wxctb.SerialPort_DCS_GetSettings(self)
SerialPort_DCS_swigregister = _wxctb.SerialPort_DCS_swigregister
SerialPort_DCS_swigregister(SerialPort_DCS)
class SerialPort_EINFO(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
brk = _swig_property(_wxctb.SerialPort_EINFO_brk_get, _wxctb.SerialPort_EINFO_brk_set)
frame = _swig_property(_wxctb.SerialPort_EINFO_frame_get, _wxctb.SerialPort_EINFO_frame_set)
overrun = _swig_property(_wxctb.SerialPort_EINFO_overrun_get, _wxctb.SerialPort_EINFO_overrun_set)
parity = _swig_property(_wxctb.SerialPort_EINFO_parity_get, _wxctb.SerialPort_EINFO_parity_set)
def __init__(self):
this = _wxctb.new_SerialPort_EINFO()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_SerialPort_EINFO
__del__ = lambda self : None;
SerialPort_EINFO_swigregister = _wxctb.SerialPort_EINFO_swigregister
SerialPort_EINFO_swigregister(SerialPort_EINFO)
CTB_SER_GETEINFO = _wxctb.CTB_SER_GETEINFO
CTB_SER_GETBRK = _wxctb.CTB_SER_GETBRK
CTB_SER_GETFRM = _wxctb.CTB_SER_GETFRM
CTB_SER_GETOVR = _wxctb.CTB_SER_GETOVR
CTB_SER_GETPAR = _wxctb.CTB_SER_GETPAR
CTB_SER_GETINQUE = _wxctb.CTB_SER_GETINQUE
CTB_SER_SETPAR = _wxctb.CTB_SER_SETPAR
class SerialPort_x(IOBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _wxctb.delete_SerialPort_x
__del__ = lambda self : None;
def ClassName(self): return _wxctb.SerialPort_x_ClassName(self)
def ChangeLineState(self, *args, **kwargs): return _wxctb.SerialPort_x_ChangeLineState(self, *args, **kwargs)
def ClrLineState(self, *args, **kwargs): return _wxctb.SerialPort_x_ClrLineState(self, *args, **kwargs)
def GetLineState(self): return _wxctb.SerialPort_x_GetLineState(self)
def GetSettingsAsString(self): return _wxctb.SerialPort_x_GetSettingsAsString(self)
def Ioctl(self, *args, **kwargs): return _wxctb.SerialPort_x_Ioctl(self, *args, **kwargs)
def SendBreak(self, *args, **kwargs): return _wxctb.SerialPort_x_SendBreak(self, *args, **kwargs)
def SetBaudrate(self, *args, **kwargs): return _wxctb.SerialPort_x_SetBaudrate(self, *args, **kwargs)
def SetLineState(self, *args, **kwargs): return _wxctb.SerialPort_x_SetLineState(self, *args, **kwargs)
def SetParityBit(self, *args, **kwargs): return _wxctb.SerialPort_x_SetParityBit(self, *args, **kwargs)
IsStandardRate = staticmethod(_wxctb.SerialPort_x_IsStandardRate)
SerialPort_x_swigregister = _wxctb.SerialPort_x_swigregister
SerialPort_x_swigregister(SerialPort_x)
def SerialPort_x_IsStandardRate(*args, **kwargs):
return _wxctb.SerialPort_x_IsStandardRate(*args, **kwargs)
SerialPort_x_IsStandardRate = _wxctb.SerialPort_x_IsStandardRate
COM1 = "/dev/ttyS0"
COM2 = "/dev/ttyS1"
COM3 = "/dev/ttyS2"
COM4 = "/dev/ttyS3"
COM5 = "/dev/ttyS4"
COM6 = "/dev/ttyS5"
COM7 = "/dev/ttyS6"
COM8 = "/dev/ttyS7"
COM9 = "/dev/ttyS8"
class SerialPort(SerialPort_x):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
this = _wxctb.new_SerialPort()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_SerialPort
__del__ = lambda self : None;
def ChangeLineState(self, *args, **kwargs): return _wxctb.SerialPort_ChangeLineState(self, *args, **kwargs)
def ClrLineState(self, *args, **kwargs): return _wxctb.SerialPort_ClrLineState(self, *args, **kwargs)
def GetLineState(self): return _wxctb.SerialPort_GetLineState(self)
def Ioctl(self, *args, **kwargs): return _wxctb.SerialPort_Ioctl(self, *args, **kwargs)
def IsOpen(self): return _wxctb.SerialPort_IsOpen(self)
def Read(self, *args, **kwargs): return _wxctb.SerialPort_Read(self, *args, **kwargs)
def SendBreak(self, *args, **kwargs): return _wxctb.SerialPort_SendBreak(self, *args, **kwargs)
def SetBaudrate(self, *args, **kwargs): return _wxctb.SerialPort_SetBaudrate(self, *args, **kwargs)
def SetLineState(self, *args, **kwargs): return _wxctb.SerialPort_SetLineState(self, *args, **kwargs)
def SetParityBit(self, *args, **kwargs): return _wxctb.SerialPort_SetParityBit(self, *args, **kwargs)
def Write(self, *args, **kwargs): return _wxctb.SerialPort_Write(self, *args, **kwargs)
SerialPort_swigregister = _wxctb.SerialPort_swigregister
SerialPort_swigregister(SerialPort)
def GetKey():
return _wxctb.GetKey()
GetKey = _wxctb.GetKey

View File

@ -0,0 +1,70 @@
#!/usr/bin/python
import getopt, time, sys
sys.path.insert( 0, r'/home/jb/project/libctb-0.16/python/module/linux')
import ctb
def main():
baudrate = 19200
devname = ""
protocol = '8N1'
try:
opt,arg = getopt.getopt(sys.argv[1:],
'b:d:p:',
['baudrate=',
'device=',
'protocol='
])
except getopt.GetoptError:
print "usage: parity.py [options]\n"\
"\t-b baudrate\n"\
"\t--baudrate=baudrate"\
"\t-d device\n"\
"\t--device=serial device name like /dev/ttyS0 or COM1\n"\
"\t-h\n"\
"\t--help print this\n"\
"\n"
sys.exit(0)
for o,a in opt:
if o in ("-b","--baudrate"):
baudrate = int(a)
if o in ("-d","--device"):
devname = a
if o in ("-p","--protocol"):
protocol = a
print "Using ctb version " + ctb.GetVersion()
dev = ctb.SerialPort()
if dev.Open( devname, baudrate, protocol ) < 0:
print "Cannot open " + devname + "\n"
# send the following string with a always set parity bit
dev.SetParityBit( 1 )
dev.Writev( "Hello World" )
# send the following string with a always cleared parity bit
dev.SetParityBit( 0 )
dev.Writev( "Hello World" )
main()

View File

@ -0,0 +1,88 @@
#!/usr/bin/python
import getopt, time, sys
sys.path.insert( 0, r'/home/jb/project/libctb-0.16/python/module/linux')
import ctb
def DataBlock():
data = ''
for c in range( 0, 256):
data += '%c' % c
return data
def main():
baudrate = 19200
devname = ""
try:
opt,arg = getopt.getopt(sys.argv[1:],
'b:d:',
['baudrate=',
'device='
])
except getopt.GetoptError:
print "usage: protocol.py [options]\n"\
"\t-b baudrate\n"\
"\t--baudrate=baudrate"\
"\t-d device\n"\
"\t--device=serial device name like /dev/ttyS0 or COM1\n"\
"\t-h\n"\
"\t--help print this\n"\
"\n"
sys.exit(0)
for o,a in opt:
if o in ("-b","--baudrate"):
baudrate = int(a)
if o in ("-d","--device"):
devname = a
print "Using ctb version " + ctb.GetVersion()
dev = ctb.SerialPort()
protocols = [
'8N1','8O1','8E1','8S1','8M1'
]
dev.SetTimeout( 1000 )
for protocol in protocols:
if dev.Open( devname, baudrate, protocol ) < 0:
print "Cannot open " + devname + "\n"
sys.exit( 1 )
else:
print( "%i %s" % ( baudrate, protocol ) )
for i in range(0, 4 ):
dev.Writev( "\x33" )
time.sleep( 0.0006 )
dev.Writev( "\x31" )
time.sleep( 0.0006 )
time.sleep( 0.5 )
dev.Close()
main()

View File

@ -0,0 +1,53 @@
#!/usr/bin/python
import getopt, time, sys
sys.path.insert( 0, r'/home/jb/project/libctb-0.16/python/module/linux')
import ctb
def main():
devname = ""
try:
opt,arg = getopt.getopt(sys.argv[1:],
'd:',
['device='
])
except getopt.GetoptError:
print "usage: parity.py [options]\n"\
"\t-d device\n"\
"\t--device=serial device name like /dev/ttyS0 or COM1\n"\
"\t-h\n"\
"\t--help print this\n"\
"\n"
sys.exit(0)
for o,a in opt:
if o in ("-d","--device"):
devname = a
print "Using ctb version " + ctb.GetVersion()
dev = ctb.SerialPort()
if dev.Open( devname, 38400 ) < 0:
print "Cannot open " + devname + "\n"
dev.SetLineState( ctb.DTR )
dev.ClrLineState( ctb.RTS )
for i in range( 0, 100 ) :
time.sleep( 0.01 )
dev.ChangeLineState( ctb.DTR | ctb.RTS )
main()

View File

@ -0,0 +1,353 @@
<!doctype html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>Python: module ctb</title>
</head><body bgcolor="#f0f0f8">
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading">
<tr bgcolor="#7799ee">
<td valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong>ctb</strong></big></big></font></td
><td align=right valign=bottom
><font color="#ffffff" face="helvetica, arial"><a href=".">index</a><br><a href="file:/mnt/s/wxaddons/wxctb-0.9/SWIG/ctb.py">/mnt/s/wxaddons/wxctb-0.9/SWIG/ctb.py</a></font></td></tr></table>
<p></p>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#aa55cc">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#fffff" face="helvetica, arial"><big><strong>Modules</strong></big></font></td></tr>
<tr><td bgcolor="#aa55cc"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><table width="100%" summary="list"><tr><td width="25%" valign=top><a href="re.html">re</a><br>
</td><td width="25%" valign=top><a href="sys.html">sys</a><br>
</td><td width="25%" valign=top><a href="wxctb.html">wxctb</a><br>
</td><td width="25%" valign=top></td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ee77aa">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Classes</strong></big></font></td></tr>
<tr><td bgcolor="#ee77aa"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><dl>
<dt><font face="helvetica, arial"><a href="ctb.html#wxIOBase">wxIOBase</a>
</font></dt><dd>
<dl>
<dt><font face="helvetica, arial"><a href="ctb.html#wxGPIB">wxGPIB</a>
</font></dt><dt><font face="helvetica, arial"><a href="ctb.html#wxSerialPort">wxSerialPort</a>
</font></dt></dl>
</dd>
</dl>
<p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#000000" face="helvetica, arial"><a name="wxGPIB">class <strong>wxGPIB</strong></a>(<a href="ctb.html#wxIOBase">wxIOBase</a>)</font></td></tr>
<tr bgcolor="#ffc8d8"><td rowspan=2><tt>&nbsp;&nbsp;&nbsp;</tt></td>
<td colspan=2><tt><a href="#wxGPIB">wxGPIB</a>&nbsp;class<br>&nbsp;</tt></td></tr>
<tr><td>&nbsp;</td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="wxGPIB-GetError"><strong>GetError</strong></a>(self)</dt></dl>
<dl><dt><a name="wxGPIB-GetSTB"><strong>GetSTB</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;value&nbsp;of&nbsp;the&nbsp;internal&nbsp;GPIB&nbsp;status&nbsp;byte&nbsp;register.</tt></dd></dl>
<dl><dt><a name="wxGPIB-Ibrd"><strong>Ibrd</strong></a>(self, length)</dt><dd><tt>#&nbsp;This&nbsp;is&nbsp;only&nbsp;for&nbsp;internal&nbsp;usage!!!</tt></dd></dl>
<dl><dt><a name="wxGPIB-Ibwrt"><strong>Ibwrt</strong></a>(self, string)</dt><dd><tt>#&nbsp;This&nbsp;is&nbsp;only&nbsp;for&nbsp;internal&nbsp;usage!!!</tt></dd></dl>
<dl><dt><a name="wxGPIB-Open"><strong>Open</strong></a>(self, devname, adr)</dt><dd><tt><a href="#wxGPIB-Open">Open</a>(gpibdevice,address)<br>
Opens&nbsp;a&nbsp;connected&nbsp;device&nbsp;at&nbsp;the&nbsp;GPIB&nbsp;bus.&nbsp;gpibdevice&nbsp;means&nbsp;the<br>
controller,&nbsp;(mostly&nbsp;"gpib1"),&nbsp;address&nbsp;the&nbsp;address&nbsp;of&nbsp;the&nbsp;desired<br>
device&nbsp;in&nbsp;the&nbsp;range&nbsp;1...31.&nbsp;For&nbsp;example:<br>
dev&nbsp;=&nbsp;<a href="#wxGPIB">wxGPIB</a>()<br>
dev.<a href="#wxGPIB-Open">Open</a>("gpib1",17)<br>
Opens&nbsp;the&nbsp;device&nbsp;with&nbsp;the&nbsp;address&nbsp;17.<br>
Open&nbsp;returns&nbsp;&gt;=&nbsp;0&nbsp;or&nbsp;a&nbsp;negativ&nbsp;value,&nbsp;if&nbsp;something&nbsp;going&nbsp;wrong.</tt></dd></dl>
<dl><dt><a name="wxGPIB-Reset"><strong>Reset</strong></a>(self)</dt><dd><tt>Resets&nbsp;the&nbsp;connected&nbsp;device.&nbsp;In&nbsp;the&nbsp;GPIB&nbsp;definition,&nbsp;the&nbsp;device<br>
should&nbsp;be&nbsp;reset&nbsp;to&nbsp;it's&nbsp;initial&nbsp;state,&nbsp;so&nbsp;you&nbsp;can&nbsp;restart&nbsp;a<br>
formely&nbsp;lost&nbsp;communication.</tt></dd></dl>
<dl><dt><a name="wxGPIB-ResetBus"><strong>ResetBus</strong></a>(self)</dt><dd><tt>The&nbsp;command&nbsp;asserts&nbsp;the&nbsp;GPIB&nbsp;interface&nbsp;clear&nbsp;(IFC)&nbsp;line&nbsp;for<br>
ast&nbsp;least&nbsp;100us&nbsp;if&nbsp;the&nbsp;GPIB&nbsp;board&nbsp;is&nbsp;the&nbsp;system&nbsp;controller.<br>
This&nbsp;initializes&nbsp;the&nbsp;GPIB&nbsp;and&nbsp;makes&nbsp;the&nbsp;interface&nbsp;CIC&nbsp;and<br>
active&nbsp;controller&nbsp;with&nbsp;ATN&nbsp;asserted.<br>
Note!&nbsp;The&nbsp;IFC&nbsp;signal&nbsp;resets&nbsp;only&nbsp;the&nbsp;GPIB&nbsp;interface&nbsp;functions<br>
of&nbsp;the&nbsp;bus&nbsp;devices&nbsp;and&nbsp;not&nbsp;the&nbsp;internal&nbsp;device&nbsp;functions.<br>
For&nbsp;a&nbsp;device&nbsp;reset&nbsp;you&nbsp;should&nbsp;use&nbsp;the&nbsp;<a href="#wxGPIB-Reset">Reset</a>()&nbsp;command&nbsp;above.</tt></dd></dl>
<dl><dt><a name="wxGPIB-__del__"><strong>__del__</strong></a>(self)</dt></dl>
<dl><dt><a name="wxGPIB-__init__"><strong>__init__</strong></a>(self)</dt></dl>
<hr>
Methods inherited from <a href="ctb.html#wxIOBase">wxIOBase</a>:<br>
<dl><dt><a name="wxGPIB-Close"><strong>Close</strong></a>(self)</dt></dl>
<dl><dt><a name="wxGPIB-GetTimeout"><strong>GetTimeout</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;internal&nbsp;timeout&nbsp;value&nbsp;in&nbsp;milliseconds</tt></dd></dl>
<dl><dt><a name="wxGPIB-Ioctl"><strong>Ioctl</strong></a>(self, cmd, arg)</dt></dl>
<dl><dt><a name="wxGPIB-PutBack"><strong>PutBack</strong></a>(self, char)</dt></dl>
<dl><dt><a name="wxGPIB-Read"><strong>Read</strong></a>(self, length)</dt><dd><tt>Try&nbsp;to&nbsp;read&nbsp;the&nbsp;given&nbsp;count&nbsp;of&nbsp;data&nbsp;(length)&nbsp;and&nbsp;returns&nbsp;the<br>
successfully&nbsp;readed&nbsp;number&nbsp;of&nbsp;data.&nbsp;The&nbsp;function&nbsp;never&nbsp;blocks.<br>
For&nbsp;example:<br>
readed&nbsp;=&nbsp;dev.<a href="#wxGPIB-Read">Read</a>(100)</tt></dd></dl>
<dl><dt><a name="wxGPIB-ReadBinary"><strong>ReadBinary</strong></a>(self, eos<font color="#909090">='<font color="#c040c0">\n</font>'</font>)</dt><dd><tt>Special&nbsp;SCPI&nbsp;command.&nbsp;Read&nbsp;the&nbsp;next&nbsp;data&nbsp;coded&nbsp;as&nbsp;a&nbsp;SCPI<br>
binary&nbsp;format.<br>
A&nbsp;binary&nbsp;data&nbsp;transfer&nbsp;will&nbsp;be&nbsp;startet&nbsp;by&nbsp;'#'.&nbsp;The&nbsp;next&nbsp;byte<br>
tells&nbsp;the&nbsp;count&nbsp;of&nbsp;bytes&nbsp;for&nbsp;the&nbsp;binary&nbsp;length&nbsp;header,<br>
following&nbsp;by&nbsp;the&nbsp;length&nbsp;bytes.&nbsp;After&nbsp;these&nbsp;the&nbsp;data&nbsp;begins.<br>
For&nbsp;example:<br>
#500004xxxx<br>
The&nbsp;header&nbsp;length&nbsp;covers&nbsp;5&nbsp;Byte,&nbsp;the&nbsp;length&nbsp;of&nbsp;the&nbsp;binary<br>
data&nbsp;is&nbsp;4&nbsp;(x&nbsp;means&nbsp;the&nbsp;binary&nbsp;data&nbsp;bytes)</tt></dd></dl>
<dl><dt><a name="wxGPIB-ReadUntilEOS"><strong>ReadUntilEOS</strong></a>(self, eos<font color="#909090">='<font color="#c040c0">\n</font>'</font>, quota<font color="#909090">=0</font>)</dt><dd><tt><a href="#wxGPIB-ReadUntilEOS">ReadUntilEOS</a>(eosString="\n",timeout=1000)<br>
Reads&nbsp;data&nbsp;until&nbsp;the&nbsp;given&nbsp;eos&nbsp;string&nbsp;was&nbsp;received&nbsp;(default&nbsp;is<br>
the&nbsp;linefeed&nbsp;character&nbsp;(0x0a)&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout<br>
(default&nbsp;1000ms)&nbsp;was&nbsp;reached.<br>
ReadUntilEOS&nbsp;returns&nbsp;the&nbsp;result&nbsp;as&nbsp;the&nbsp;following&nbsp;tuple:<br>
['received&nbsp;string',state,readedBytes]<br>
If&nbsp;a&nbsp;timeout&nbsp;occurred,&nbsp;state&nbsp;is&nbsp;0,&nbsp;otherwise&nbsp;1</tt></dd></dl>
<dl><dt><a name="wxGPIB-Readv"><strong>Readv</strong></a>(self, length)</dt><dd><tt>Try&nbsp;to&nbsp;read&nbsp;the&nbsp;given&nbsp;count&nbsp;of&nbsp;data.&nbsp;Readv&nbsp;blocks&nbsp;until&nbsp;all&nbsp;data<br>
was&nbsp;readed&nbsp;successfully&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout,&nbsp;set&nbsp;with&nbsp;the<br>
class&nbsp;member&nbsp;function&nbsp;<a href="#wxGPIB-SetTimeout">SetTimeout</a>(timeout),&nbsp;was&nbsp;reached.<br>
Returns&nbsp;the&nbsp;readed&nbsp;data.</tt></dd></dl>
<dl><dt><a name="wxGPIB-SetTimeout"><strong>SetTimeout</strong></a>(self, timeout)</dt><dd><tt>Set&nbsp;the&nbsp;internal&nbsp;timeout&nbsp;value&nbsp;in&nbsp;milliseconds&nbsp;for&nbsp;all&nbsp;blocked<br>
operations&nbsp;like&nbsp;ReadUntilEOS,&nbsp;Readv&nbsp;and&nbsp;Writev.</tt></dd></dl>
<dl><dt><a name="wxGPIB-Write"><strong>Write</strong></a>(self, string)</dt><dd><tt>Writes&nbsp;the&nbsp;given&nbsp;string&nbsp;to&nbsp;the&nbsp;device&nbsp;and&nbsp;returns&nbsp;immediately.<br>
Write&nbsp;returns&nbsp;the&nbsp;number&nbsp;of&nbsp;data&nbsp;bytes&nbsp;successfully&nbsp;written&nbsp;or&nbsp;a<br>
negativ&nbsp;number&nbsp;if&nbsp;an&nbsp;error&nbsp;occured.&nbsp;For&nbsp;some&nbsp;circumstances,&nbsp;not<br>
the&nbsp;complete&nbsp;string&nbsp;was&nbsp;written.<br>
So&nbsp;you&nbsp;have&nbsp;to&nbsp;verify&nbsp;the&nbsp;return&nbsp;value&nbsp;to&nbsp;check&nbsp;this&nbsp;out.</tt></dd></dl>
<dl><dt><a name="wxGPIB-Writev"><strong>Writev</strong></a>(self, string)</dt><dd><tt>Writes&nbsp;the&nbsp;given&nbsp;string&nbsp;to&nbsp;the&nbsp;device.&nbsp;The&nbsp;function&nbsp;blocks&nbsp;until<br>
the&nbsp;complete&nbsp;string&nbsp;was&nbsp;written&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout,&nbsp;set&nbsp;with<br>
<a href="#wxGPIB-SetTimeout">SetTimeout</a>(timeout),&nbsp;was&nbsp;reached.<br>
Writev&nbsp;returns&nbsp;the&nbsp;number&nbsp;of&nbsp;data&nbsp;successfully&nbsp;written&nbsp;or&nbsp;a<br>
negativ&nbsp;value,&nbsp;if&nbsp;an&nbsp;errors&nbsp;occurred.</tt></dd></dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#000000" face="helvetica, arial"><a name="wxIOBase">class <strong>wxIOBase</strong></a></font></td></tr>
<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="wxIOBase-Close"><strong>Close</strong></a>(self)</dt></dl>
<dl><dt><a name="wxIOBase-GetTimeout"><strong>GetTimeout</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;internal&nbsp;timeout&nbsp;value&nbsp;in&nbsp;milliseconds</tt></dd></dl>
<dl><dt><a name="wxIOBase-Ioctl"><strong>Ioctl</strong></a>(self, cmd, arg)</dt></dl>
<dl><dt><a name="wxIOBase-Open"><strong>Open</strong></a>(self)</dt></dl>
<dl><dt><a name="wxIOBase-PutBack"><strong>PutBack</strong></a>(self, char)</dt></dl>
<dl><dt><a name="wxIOBase-Read"><strong>Read</strong></a>(self, length)</dt><dd><tt>Try&nbsp;to&nbsp;read&nbsp;the&nbsp;given&nbsp;count&nbsp;of&nbsp;data&nbsp;(length)&nbsp;and&nbsp;returns&nbsp;the<br>
successfully&nbsp;readed&nbsp;number&nbsp;of&nbsp;data.&nbsp;The&nbsp;function&nbsp;never&nbsp;blocks.<br>
For&nbsp;example:<br>
readed&nbsp;=&nbsp;dev.<a href="#wxIOBase-Read">Read</a>(100)</tt></dd></dl>
<dl><dt><a name="wxIOBase-ReadBinary"><strong>ReadBinary</strong></a>(self, eos<font color="#909090">='<font color="#c040c0">\n</font>'</font>)</dt><dd><tt>Special&nbsp;SCPI&nbsp;command.&nbsp;Read&nbsp;the&nbsp;next&nbsp;data&nbsp;coded&nbsp;as&nbsp;a&nbsp;SCPI<br>
binary&nbsp;format.<br>
A&nbsp;binary&nbsp;data&nbsp;transfer&nbsp;will&nbsp;be&nbsp;startet&nbsp;by&nbsp;'#'.&nbsp;The&nbsp;next&nbsp;byte<br>
tells&nbsp;the&nbsp;count&nbsp;of&nbsp;bytes&nbsp;for&nbsp;the&nbsp;binary&nbsp;length&nbsp;header,<br>
following&nbsp;by&nbsp;the&nbsp;length&nbsp;bytes.&nbsp;After&nbsp;these&nbsp;the&nbsp;data&nbsp;begins.<br>
For&nbsp;example:<br>
#500004xxxx<br>
The&nbsp;header&nbsp;length&nbsp;covers&nbsp;5&nbsp;Byte,&nbsp;the&nbsp;length&nbsp;of&nbsp;the&nbsp;binary<br>
data&nbsp;is&nbsp;4&nbsp;(x&nbsp;means&nbsp;the&nbsp;binary&nbsp;data&nbsp;bytes)</tt></dd></dl>
<dl><dt><a name="wxIOBase-ReadUntilEOS"><strong>ReadUntilEOS</strong></a>(self, eos<font color="#909090">='<font color="#c040c0">\n</font>'</font>, quota<font color="#909090">=0</font>)</dt><dd><tt><a href="#wxIOBase-ReadUntilEOS">ReadUntilEOS</a>(eosString="\n",timeout=1000)<br>
Reads&nbsp;data&nbsp;until&nbsp;the&nbsp;given&nbsp;eos&nbsp;string&nbsp;was&nbsp;received&nbsp;(default&nbsp;is<br>
the&nbsp;linefeed&nbsp;character&nbsp;(0x0a)&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout<br>
(default&nbsp;1000ms)&nbsp;was&nbsp;reached.<br>
ReadUntilEOS&nbsp;returns&nbsp;the&nbsp;result&nbsp;as&nbsp;the&nbsp;following&nbsp;tuple:<br>
['received&nbsp;string',state,readedBytes]<br>
If&nbsp;a&nbsp;timeout&nbsp;occurred,&nbsp;state&nbsp;is&nbsp;0,&nbsp;otherwise&nbsp;1</tt></dd></dl>
<dl><dt><a name="wxIOBase-Readv"><strong>Readv</strong></a>(self, length)</dt><dd><tt>Try&nbsp;to&nbsp;read&nbsp;the&nbsp;given&nbsp;count&nbsp;of&nbsp;data.&nbsp;Readv&nbsp;blocks&nbsp;until&nbsp;all&nbsp;data<br>
was&nbsp;readed&nbsp;successfully&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout,&nbsp;set&nbsp;with&nbsp;the<br>
class&nbsp;member&nbsp;function&nbsp;<a href="#wxIOBase-SetTimeout">SetTimeout</a>(timeout),&nbsp;was&nbsp;reached.<br>
Returns&nbsp;the&nbsp;readed&nbsp;data.</tt></dd></dl>
<dl><dt><a name="wxIOBase-ResetBus"><strong>ResetBus</strong></a>(self)</dt><dd><tt>If&nbsp;the&nbsp;underlaying&nbsp;interface&nbsp;needs&nbsp;some&nbsp;special&nbsp;reset&nbsp;operations<br>
(for&nbsp;instance&nbsp;the&nbsp;GPIB&nbsp;distinguish&nbsp;between&nbsp;a&nbsp;normal&nbsp;device&nbsp;reset<br>
and&nbsp;a&nbsp;special&nbsp;bus&nbsp;reset),&nbsp;you&nbsp;can&nbsp;put&nbsp;some&nbsp;code&nbsp;here)</tt></dd></dl>
<dl><dt><a name="wxIOBase-SetTimeout"><strong>SetTimeout</strong></a>(self, timeout)</dt><dd><tt>Set&nbsp;the&nbsp;internal&nbsp;timeout&nbsp;value&nbsp;in&nbsp;milliseconds&nbsp;for&nbsp;all&nbsp;blocked<br>
operations&nbsp;like&nbsp;ReadUntilEOS,&nbsp;Readv&nbsp;and&nbsp;Writev.</tt></dd></dl>
<dl><dt><a name="wxIOBase-Write"><strong>Write</strong></a>(self, string)</dt><dd><tt>Writes&nbsp;the&nbsp;given&nbsp;string&nbsp;to&nbsp;the&nbsp;device&nbsp;and&nbsp;returns&nbsp;immediately.<br>
Write&nbsp;returns&nbsp;the&nbsp;number&nbsp;of&nbsp;data&nbsp;bytes&nbsp;successfully&nbsp;written&nbsp;or&nbsp;a<br>
negativ&nbsp;number&nbsp;if&nbsp;an&nbsp;error&nbsp;occured.&nbsp;For&nbsp;some&nbsp;circumstances,&nbsp;not<br>
the&nbsp;complete&nbsp;string&nbsp;was&nbsp;written.<br>
So&nbsp;you&nbsp;have&nbsp;to&nbsp;verify&nbsp;the&nbsp;return&nbsp;value&nbsp;to&nbsp;check&nbsp;this&nbsp;out.</tt></dd></dl>
<dl><dt><a name="wxIOBase-Writev"><strong>Writev</strong></a>(self, string)</dt><dd><tt>Writes&nbsp;the&nbsp;given&nbsp;string&nbsp;to&nbsp;the&nbsp;device.&nbsp;The&nbsp;function&nbsp;blocks&nbsp;until<br>
the&nbsp;complete&nbsp;string&nbsp;was&nbsp;written&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout,&nbsp;set&nbsp;with<br>
<a href="#wxIOBase-SetTimeout">SetTimeout</a>(timeout),&nbsp;was&nbsp;reached.<br>
Writev&nbsp;returns&nbsp;the&nbsp;number&nbsp;of&nbsp;data&nbsp;successfully&nbsp;written&nbsp;or&nbsp;a<br>
negativ&nbsp;value,&nbsp;if&nbsp;an&nbsp;errors&nbsp;occurred.</tt></dd></dl>
<dl><dt><a name="wxIOBase-__del__"><strong>__del__</strong></a>(self)</dt></dl>
<dl><dt><a name="wxIOBase-__init__"><strong>__init__</strong></a>(self)</dt></dl>
</td></tr></table> <p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#ffc8d8">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#000000" face="helvetica, arial"><a name="wxSerialPort">class <strong>wxSerialPort</strong></a>(<a href="ctb.html#wxIOBase">wxIOBase</a>)</font></td></tr>
<tr><td bgcolor="#ffc8d8"><tt>&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%">Methods defined here:<br>
<dl><dt><a name="wxSerialPort-ChangeLineState"><strong>ChangeLineState</strong></a>(self, lineState)</dt><dd><tt>Change&nbsp;(toggle)&nbsp;the&nbsp;state&nbsp;of&nbsp;each&nbsp;the&nbsp;lines&nbsp;given&nbsp;in&nbsp;the<br>
linestate&nbsp;parameter.&nbsp;Possible&nbsp;values&nbsp;are&nbsp;wxSERIAL_LINESTATE_DTR<br>
(means&nbsp;the&nbsp;DTR&nbsp;signal)&nbsp;and/or&nbsp;wxSERIAL_LINESTATE_RTS&nbsp;(RTS&nbsp;signal).<br>
For&nbsp;example&nbsp;to&nbsp;toggle&nbsp;the&nbsp;RTS&nbsp;line&nbsp;only:<br>
dev.<a href="#wxSerialPort-ChangeLineState">ChangeLineState</a>(wxSERIAL_LINESTATE_RTS)</tt></dd></dl>
<dl><dt><a name="wxSerialPort-ClrLineState"><strong>ClrLineState</strong></a>(self, lineState)</dt><dd><tt>Clear&nbsp;the&nbsp;lines&nbsp;given&nbsp;in&nbsp;the&nbsp;linestate&nbsp;parameter.&nbsp;Possible<br>
values&nbsp;are&nbsp;wxSERIAL_LINESTATE_DTR&nbsp;(means&nbsp;the&nbsp;DTR&nbsp;signal)&nbsp;and/or<br>
wxSERIAL_LINESTATE_RTS&nbsp;(RTS&nbsp;signal).&nbsp;For&nbsp;example&nbsp;to&nbsp;clear&nbsp;only<br>
the&nbsp;RTS&nbsp;line:<br>
dev.<a href="#wxSerialPort-ClrLineState">ClrLineState</a>(wxSERIAL_LINESTATE_RTS)</tt></dd></dl>
<dl><dt><a name="wxSerialPort-GetAvailableBytes"><strong>GetAvailableBytes</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;available&nbsp;bytes&nbsp;in&nbsp;the&nbsp;input&nbsp;queue&nbsp;of&nbsp;the&nbsp;serial<br>
driver.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-GetCommErrors"><strong>GetCommErrors</strong></a>(self)</dt><dd><tt>Get&nbsp;the&nbsp;internal&nbsp;communication&nbsp;errors&nbsp;like&nbsp;breaks,&nbsp;framing,<br>
parity&nbsp;or&nbsp;overrun&nbsp;errors.<br>
Returns&nbsp;the&nbsp;count&nbsp;of&nbsp;each&nbsp;error&nbsp;as&nbsp;a&nbsp;tuple&nbsp;like&nbsp;this:<br>
(b,f,o,p)&nbsp;=&nbsp;dev.<a href="#wxSerialPort-GetCommErrors">GetCommErrors</a>()<br>
b:&nbsp;breaks,&nbsp;f:&nbsp;framing&nbsp;errors,&nbsp;&nbsp;o:&nbsp;overruns,&nbsp;p:&nbsp;parity&nbsp;errors</tt></dd></dl>
<dl><dt><a name="wxSerialPort-GetLineState"><strong>GetLineState</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;current&nbsp;linestates&nbsp;of&nbsp;the&nbsp;CTS,&nbsp;DCD,&nbsp;DSR&nbsp;and&nbsp;RING<br>
signal&nbsp;line&nbsp;as&nbsp;an&nbsp;integer&nbsp;value&nbsp;with&nbsp;the&nbsp;appropriate&nbsp;bits&nbsp;or<br>
-1&nbsp;on&nbsp;error.<br>
For&nbsp;example:<br>
lines&nbsp;=&nbsp;dev.<a href="#wxSerialPort-GetLineState">GetLineState</a>()<br>
if&nbsp;lines&nbsp;&amp;&nbsp;wxSERIAL_LINESTATE_CTS:<br>
&nbsp;&nbsp;&nbsp;&nbsp;print&nbsp;"CTS&nbsp;is&nbsp;on"</tt></dd></dl>
<dl><dt><a name="wxSerialPort-Open"><strong>Open</strong></a>(self, devname, baudrate, protocol<font color="#909090">='8N1'</font>, handshake<font color="#909090">='no_handshake'</font>)</dt><dd><tt>Open&nbsp;the&nbsp;device&nbsp;devname&nbsp;with&nbsp;the&nbsp;given&nbsp;baudrate,&nbsp;the&nbsp;protocol<br>
like&nbsp;'8N1'&nbsp;(default)&nbsp;and&nbsp;the&nbsp;use&nbsp;of&nbsp;the&nbsp;handshake&nbsp;[no_handshake<br>
(default),&nbsp;rtscts&nbsp;or&nbsp;xonxoff]<br>
For&nbsp;example:<br>
At&nbsp;Linux:<br>
dev&nbsp;=&nbsp;<a href="#wxSerialPort">wxSerialPort</a>()<br>
dev.<a href="#wxSerialPort-Open">Open</a>("/dev/ttyS0",115200)<br>
or&nbsp;with&nbsp;a&nbsp;datalen&nbsp;of&nbsp;7&nbsp;bits,&nbsp;even&nbsp;parity,&nbsp;2&nbsp;stopbits&nbsp;and&nbsp;rts/cts<br>
handshake:<br>
dev.<a href="#wxSerialPort-Open">Open</a>("/dev/ttyS0",115200,'7E2',True)<br>
At&nbsp;Windows:<br>
dev&nbsp;=&nbsp;<a href="#wxSerialPort">wxSerialPort</a>()<br>
dev.<a href="#wxSerialPort-Open">Open</a>("COM1",115200)<br>
dev.<a href="#wxSerialPort-Open">Open</a>("COM1",115200,'7E2',True)<br>
Returns&nbsp;the&nbsp;handle&nbsp;on&nbsp;success&nbsp;or&nbsp;a&nbsp;negativ&nbsp;value&nbsp;on&nbsp;failure.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-Reset"><strong>Reset</strong></a>(self)</dt><dd><tt>Send&nbsp;a&nbsp;break&nbsp;for&nbsp;0.25s.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-SetBaudRate"><strong>SetBaudRate</strong></a>(self, baudrate)</dt><dd><tt>Set&nbsp;the&nbsp;baudrate&nbsp;for&nbsp;the&nbsp;device.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-SetLineState"><strong>SetLineState</strong></a>(self, lineState)</dt><dd><tt>Set&nbsp;the&nbsp;lines&nbsp;given&nbsp;in&nbsp;the&nbsp;linestate&nbsp;parameter.&nbsp;Possible<br>
values&nbsp;are&nbsp;wxSERIAL_LINESTATE_DTR&nbsp;(means&nbsp;the&nbsp;DTR&nbsp;signal)&nbsp;and/or<br>
wxSERIAL_LINESTATE_RTS&nbsp;(RTS&nbsp;signal).&nbsp;For&nbsp;example&nbsp;to&nbsp;set&nbsp;both:<br>
dev.<a href="#wxSerialPort-SetLineState">SetLineState</a>(wxSERIAL_LINESTATE_DTR&nbsp;|&nbsp;wxSERIAL_LINESTATE_RTS)</tt></dd></dl>
<dl><dt><a name="wxSerialPort-__del__"><strong>__del__</strong></a>(self)</dt></dl>
<dl><dt><a name="wxSerialPort-__init__"><strong>__init__</strong></a>(self)</dt></dl>
<hr>
Methods inherited from <a href="ctb.html#wxIOBase">wxIOBase</a>:<br>
<dl><dt><a name="wxSerialPort-Close"><strong>Close</strong></a>(self)</dt></dl>
<dl><dt><a name="wxSerialPort-GetTimeout"><strong>GetTimeout</strong></a>(self)</dt><dd><tt>Returns&nbsp;the&nbsp;internal&nbsp;timeout&nbsp;value&nbsp;in&nbsp;milliseconds</tt></dd></dl>
<dl><dt><a name="wxSerialPort-Ioctl"><strong>Ioctl</strong></a>(self, cmd, arg)</dt></dl>
<dl><dt><a name="wxSerialPort-PutBack"><strong>PutBack</strong></a>(self, char)</dt></dl>
<dl><dt><a name="wxSerialPort-Read"><strong>Read</strong></a>(self, length)</dt><dd><tt>Try&nbsp;to&nbsp;read&nbsp;the&nbsp;given&nbsp;count&nbsp;of&nbsp;data&nbsp;(length)&nbsp;and&nbsp;returns&nbsp;the<br>
successfully&nbsp;readed&nbsp;number&nbsp;of&nbsp;data.&nbsp;The&nbsp;function&nbsp;never&nbsp;blocks.<br>
For&nbsp;example:<br>
readed&nbsp;=&nbsp;dev.<a href="#wxSerialPort-Read">Read</a>(100)</tt></dd></dl>
<dl><dt><a name="wxSerialPort-ReadBinary"><strong>ReadBinary</strong></a>(self, eos<font color="#909090">='<font color="#c040c0">\n</font>'</font>)</dt><dd><tt>Special&nbsp;SCPI&nbsp;command.&nbsp;Read&nbsp;the&nbsp;next&nbsp;data&nbsp;coded&nbsp;as&nbsp;a&nbsp;SCPI<br>
binary&nbsp;format.<br>
A&nbsp;binary&nbsp;data&nbsp;transfer&nbsp;will&nbsp;be&nbsp;startet&nbsp;by&nbsp;'#'.&nbsp;The&nbsp;next&nbsp;byte<br>
tells&nbsp;the&nbsp;count&nbsp;of&nbsp;bytes&nbsp;for&nbsp;the&nbsp;binary&nbsp;length&nbsp;header,<br>
following&nbsp;by&nbsp;the&nbsp;length&nbsp;bytes.&nbsp;After&nbsp;these&nbsp;the&nbsp;data&nbsp;begins.<br>
For&nbsp;example:<br>
#500004xxxx<br>
The&nbsp;header&nbsp;length&nbsp;covers&nbsp;5&nbsp;Byte,&nbsp;the&nbsp;length&nbsp;of&nbsp;the&nbsp;binary<br>
data&nbsp;is&nbsp;4&nbsp;(x&nbsp;means&nbsp;the&nbsp;binary&nbsp;data&nbsp;bytes)</tt></dd></dl>
<dl><dt><a name="wxSerialPort-ReadUntilEOS"><strong>ReadUntilEOS</strong></a>(self, eos<font color="#909090">='<font color="#c040c0">\n</font>'</font>, quota<font color="#909090">=0</font>)</dt><dd><tt><a href="#wxSerialPort-ReadUntilEOS">ReadUntilEOS</a>(eosString="\n",timeout=1000)<br>
Reads&nbsp;data&nbsp;until&nbsp;the&nbsp;given&nbsp;eos&nbsp;string&nbsp;was&nbsp;received&nbsp;(default&nbsp;is<br>
the&nbsp;linefeed&nbsp;character&nbsp;(0x0a)&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout<br>
(default&nbsp;1000ms)&nbsp;was&nbsp;reached.<br>
ReadUntilEOS&nbsp;returns&nbsp;the&nbsp;result&nbsp;as&nbsp;the&nbsp;following&nbsp;tuple:<br>
['received&nbsp;string',state,readedBytes]<br>
If&nbsp;a&nbsp;timeout&nbsp;occurred,&nbsp;state&nbsp;is&nbsp;0,&nbsp;otherwise&nbsp;1</tt></dd></dl>
<dl><dt><a name="wxSerialPort-Readv"><strong>Readv</strong></a>(self, length)</dt><dd><tt>Try&nbsp;to&nbsp;read&nbsp;the&nbsp;given&nbsp;count&nbsp;of&nbsp;data.&nbsp;Readv&nbsp;blocks&nbsp;until&nbsp;all&nbsp;data<br>
was&nbsp;readed&nbsp;successfully&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout,&nbsp;set&nbsp;with&nbsp;the<br>
class&nbsp;member&nbsp;function&nbsp;<a href="#wxSerialPort-SetTimeout">SetTimeout</a>(timeout),&nbsp;was&nbsp;reached.<br>
Returns&nbsp;the&nbsp;readed&nbsp;data.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-ResetBus"><strong>ResetBus</strong></a>(self)</dt><dd><tt>If&nbsp;the&nbsp;underlaying&nbsp;interface&nbsp;needs&nbsp;some&nbsp;special&nbsp;reset&nbsp;operations<br>
(for&nbsp;instance&nbsp;the&nbsp;GPIB&nbsp;distinguish&nbsp;between&nbsp;a&nbsp;normal&nbsp;device&nbsp;reset<br>
and&nbsp;a&nbsp;special&nbsp;bus&nbsp;reset),&nbsp;you&nbsp;can&nbsp;put&nbsp;some&nbsp;code&nbsp;here)</tt></dd></dl>
<dl><dt><a name="wxSerialPort-SetTimeout"><strong>SetTimeout</strong></a>(self, timeout)</dt><dd><tt>Set&nbsp;the&nbsp;internal&nbsp;timeout&nbsp;value&nbsp;in&nbsp;milliseconds&nbsp;for&nbsp;all&nbsp;blocked<br>
operations&nbsp;like&nbsp;ReadUntilEOS,&nbsp;Readv&nbsp;and&nbsp;Writev.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-Write"><strong>Write</strong></a>(self, string)</dt><dd><tt>Writes&nbsp;the&nbsp;given&nbsp;string&nbsp;to&nbsp;the&nbsp;device&nbsp;and&nbsp;returns&nbsp;immediately.<br>
Write&nbsp;returns&nbsp;the&nbsp;number&nbsp;of&nbsp;data&nbsp;bytes&nbsp;successfully&nbsp;written&nbsp;or&nbsp;a<br>
negativ&nbsp;number&nbsp;if&nbsp;an&nbsp;error&nbsp;occured.&nbsp;For&nbsp;some&nbsp;circumstances,&nbsp;not<br>
the&nbsp;complete&nbsp;string&nbsp;was&nbsp;written.<br>
So&nbsp;you&nbsp;have&nbsp;to&nbsp;verify&nbsp;the&nbsp;return&nbsp;value&nbsp;to&nbsp;check&nbsp;this&nbsp;out.</tt></dd></dl>
<dl><dt><a name="wxSerialPort-Writev"><strong>Writev</strong></a>(self, string)</dt><dd><tt>Writes&nbsp;the&nbsp;given&nbsp;string&nbsp;to&nbsp;the&nbsp;device.&nbsp;The&nbsp;function&nbsp;blocks&nbsp;until<br>
the&nbsp;complete&nbsp;string&nbsp;was&nbsp;written&nbsp;or&nbsp;the&nbsp;internal&nbsp;timeout,&nbsp;set&nbsp;with<br>
<a href="#wxSerialPort-SetTimeout">SetTimeout</a>(timeout),&nbsp;was&nbsp;reached.<br>
Writev&nbsp;returns&nbsp;the&nbsp;number&nbsp;of&nbsp;data&nbsp;successfully&nbsp;written&nbsp;or&nbsp;a<br>
negativ&nbsp;value,&nbsp;if&nbsp;an&nbsp;errors&nbsp;occurred.</tt></dd></dl>
</td></tr></table></td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#eeaa77">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Functions</strong></big></font></td></tr>
<tr><td bgcolor="#eeaa77"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><dl><dt><a name="-GetKey"><strong>GetKey</strong></a>()</dt><dd><tt>Returns&nbsp;the&nbsp;current&nbsp;pressed&nbsp;key&nbsp;or&nbsp;'',&nbsp;if&nbsp;no&nbsp;key&nbsp;is&nbsp;pressed.<br>
You&nbsp;can&nbsp;simply&nbsp;create&nbsp;a&nbsp;query&nbsp;loop&nbsp;with:<br>
while&nbsp;<a href="#-GetKey">GetKey</a>()&nbsp;==&nbsp;'':<br>
&nbsp;&nbsp;&nbsp;&nbsp;...&nbsp;make&nbsp;some&nbsp;stuff&nbsp;...</tt></dd></dl>
<dl><dt><a name="-abstract"><strong>abstract</strong></a>()</dt></dl>
</td></tr></table><p>
<table width="100%" cellspacing=0 cellpadding=2 border=0 summary="section">
<tr bgcolor="#55aa55">
<td colspan=3 valign=bottom>&nbsp;<br>
<font color="#ffffff" face="helvetica, arial"><big><strong>Data</strong></big></font></td></tr>
<tr><td bgcolor="#55aa55"><tt>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</tt></td><td>&nbsp;</td>
<td width="100%"><strong>wxSERIAL_LINESTATE_CTS</strong> = 32<br>
<strong>wxSERIAL_LINESTATE_DCD</strong> = 64<br>
<strong>wxSERIAL_LINESTATE_DSR</strong> = 256<br>
<strong>wxSERIAL_LINESTATE_DTR</strong> = 2<br>
<strong>wxSERIAL_LINESTATE_NULL</strong> = 0<br>
<strong>wxSERIAL_LINESTATE_RING</strong> = 128<br>
<strong>wxSERIAL_LINESTATE_RTS</strong> = 4</td></tr></table>
</body></html>

View File

@ -0,0 +1,455 @@
import wxctb, sys, re
DCD = wxctb.LinestateDcd
CTS = wxctb.LinestateCts
DSR = wxctb.LinestateDsr
DTR = wxctb.LinestateDtr
RING = wxctb.LinestateRing
RTS = wxctb.LinestateRts
NULL = wxctb.LinestateNull
def abstract():
import inspect
caller = inspect.getouterframes(inspect.currentframe())[1][3]
raise NotImplementedError(caller + ' must be implemented in subclass')
class IOBase:
def __init__(self):
self.device = None
# set timeout to 1000ms (the default)
self.timeout = 1000
def __del__(self):
pass
def Close(self):
if self.device:
self.device.Close()
def GetTimeout(self):
"""
Returns the internal timeout value in milliseconds
"""
return self.timeout
def Ioctl(self,cmd,arg):
if self.device:
self.device.Ioctl(cmd,arg)
def Open(self):
abstract()
def PutBack(self,char):
return self.device.PutBack(char)
def Read(self,length):
"""
Try to read the given count of data (length) and returns the
successfully readed number of data. The function never blocks.
For example:
readed = dev.Read(100)
"""
buf = "\x00"*(length+1)
rd = self.device.Read(buf,length)
return buf[0:rd]
def ReadBinary(self,eos="\n"):
"""
Special SCPI command. Read the next data coded as a SCPI
binary format.
A binary data transfer will be startet by '#'. The next byte
tells the count of bytes for the binary length header,
following by the length bytes. After these the data begins.
For example:
#500004xxxx
The header length covers 5 Byte, the length of the binary
data is 4 (x means the binary data bytes)
"""
try:
eoslen = len(eos)
b=self.Readv(2)
if len(b) == 2:
hl = int(b[1])
b = self.Readv(hl)
if len(b) == hl:
dl = int(b)
# don't left over the eos string or character in the
# device input buffer
data = self.Readv(dl+eoslen)
# check, if the binary data block is complete
if data[dl] == '#':
# not complete, another block is following
for c in data[dl:dl+eoslen]:
self.PutBack(c)
data = data[:dl] + self.ReadBinary()
return data
except:
pass
return ''
def ReadUntilEOS(self,eos="\n",quota=0):
"""
ReadUntilEOS(eosString=\"\\n\",timeout=1000)
Reads data until the given eos string was received (default is
the linefeed character (0x0a) or the internal timeout
(default 1000ms) was reached.
ReadUntilEOS returns the result as the following tuple:
['received string',state,readedBytes]
If a timeout occurred, state is 0, otherwise 1
"""
return self.device.ReadUntilEOS("",0,eos,self.timeout,quota)
def Readv(self,length):
"""
Try to read the given count of data. Readv blocks until all data
was readed successfully or the internal timeout, set with the
class member function SetTimeout(timeout), was reached.
Returns the readed data.
"""
buf = "\x00"*length
rd = self.device.Readv(buf,length,self.timeout)
return buf[0:rd]
def ResetBus(self):
"""
If the underlaying interface needs some special reset operations
(for instance the GPIB distinguish between a normal device reset
and a special bus reset), you can put some code here)
"""
pass
def SetTimeout(self,timeout):
"""
Set the internal timeout value in milliseconds for all blocked
operations like ReadUntilEOS, Readv and Writev.
"""
self.timeout = timeout
def Write(self,string):
"""
Writes the given string to the device and returns immediately.
Write returns the number of data bytes successfully written or a
negativ number if an error occured. For some circumstances, not
the complete string was written.
So you have to verify the return value to check this out.
"""
return self.device.Write(string,len(string))
def Writev(self,string):
"""
Writes the given string to the device. The function blocks until
the complete string was written or the internal timeout, set with
SetTimeout(timeout), was reached.
Writev returns the number of data successfully written or a
negativ value, if an errors occurred.
"""
return self.device.Writev(string,len(string),self.timeout)
class SerialPort(IOBase):
def __init__(self):
IOBase.__init__(self)
def __del__(self):
self.Close()
def ChangeLineState(self,lineState):
"""
Change (toggle) the state of each the lines given in the
linestate parameter. Possible values are DTR and/or RTS.
For example to toggle the RTS line only:
dev.ChangeLineState(RTS)
"""
self.device.ChangeLineState(lineState)
def ClrLineState(self,lineState):
"""
Clear the lines given in the linestate parameter. Possible
values are DTR and/or RTS. For example to clear only
the RTS line:
dev.ClrLineState(RTS)
"""
self.device.ClrLineState(lineState)
def GetAvailableBytes(self):
"""
Returns the available bytes in the input queue of the serial
driver.
"""
n = wxctb.new_intp()
wxctb.intp_assign(n, 0)
self.device.Ioctl(wxctb.CTB_SER_GETINQUE,n)
return wxctb.intp_value(n)
def GetCommErrors(self):
"""
Get the internal communication errors like breaks, framing,
parity or overrun errors.
Returns the count of each error as a tuple like this:
(b,f,o,p) = dev.GetCommErrors()
b: breaks, f: framing errors, o: overruns, p: parity errors
"""
einfo = wxctb.SerialPort_EINFO()
self.device.Ioctl(wxctb.CTB_SER_GETEINFO,einfo)
return einfo.brk,einfo.frame,einfo.overrun,einfo.parity
def GetLineState(self):
"""
Returns the current linestates of the CTS, DCD, DSR and RING
signal line as an integer value with the appropriate bits or
-1 on error.
For example:
lines = dev.GetLineState()
if lines & CTS:
print \"CTS is on\"
"""
return self.device.GetLineState()
def Open(self,devname,baudrate,protocol='8N1',handshake='no_handshake'):
"""
Open the device devname with the given baudrate, the protocol
like '8N1' (default) and the use of the handshake [no_handshake
(default), rtscts or xonxoff]
For example:
At Linux:
dev = SerialPort()
dev.Open(\"/dev/ttyS0\",115200)
or with a datalen of 7 bits, even parity, 2 stopbits and rts/cts
handshake:
dev.Open(\"/dev/ttyS0\",115200,'7E2',True)
At Windows:
dev = SerialPort()
dev.Open(\"COM1\",115200)
dev.Open(\"COM1\",115200,'7E2',True)
Returns the handle on success or a negativ value on failure.
"""
# the following parity values are valid:
# N:None, O:Odd, E:Even, M:Mark, S:Space
parity = {'N':0,'O':1,'E':2,'M':3,'S':4}
# the regular expression ensures a valid value for the datalen
# (5...8 bit) and the count of stopbits (1,2)
reg=re.compile(r"(?P<w>[8765])"r"(?P<p>[NOEMS])"r"(?P<s>[12])")
self.device = wxctb.SerialPort()
dcs = wxctb.SerialPort_DCS()
dcs.baud = baudrate
res = reg.search(protocol)
# handle the given protocol
if res:
dcs.wordlen = int(res.group('w'))
dcs.stopbits = int(res.group('s'))
dcs.parity = parity[res.group('p')]
# valid handshake are no one, rts/cts or xon/xoff
if handshake == 'rtscts':
dcs.rtscts = True
elif handshake == 'xonxoff':
dcs.xonxoff = True
return self.device.Open(devname,dcs)
def Reset(self):
"""
Send a break for 0.25s.
"""
self.device.SendBreak(0)
def SetBaudrate(self,baudrate):
"""
Set the baudrate for the device.
"""
self.device.SetBaudrate(baudrate)
def SetLineState(self,lineState):
"""
Set the lines given in the linestate parameter. Possible
values are DTR and/or RTS. For example to set both:
dev.SetLineState( DTR | RTS)
"""
self.device.SetLineState(lineState)
def SetParityBit(self,parity):
"""
Set the parity bit explicitly to 0 or 1. Use this function, if
you would like to simulate a 9 bit wordlen at what the ninth bit
was represented by the parity bit value. For example:
dev.SetParityBit( 0 )
dev.Write('some data sent with parity 0')
dev.SetParityBit( 1 )
dev.Write('another sequence with parity 1')
"""
return self.device.SetParityBit( parity )
class GpibDevice(IOBase):
"""
GPIB class
"""
def __init__(self):
IOBase.__init__(self)
def __del__(self):
self.Close()
def FindListeners(self,board = 0):
"""
Returns the address of the connected devices as a list.
If no device is listening, the list is empty. If an error
occurs an IOError exception raised. For example:
g = GPIB()
listeners = g.FindListeners()
"""
listeners = wxctb.GPIB_x_FindListeners(board)
if listeners < 0:
raise IOError("GPIB board error")
result = []
for i in range(1,31):
if listeners & (1 << i):
result.append(i)
return result
def GetEosChar(self):
"""
Get the internal EOS termination character (see SetEosChar).
For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosChar()
"""
eos = wxctb.new_intp()
wxctb.intp_assign(eos, 0)
self.device.Ioctl(wxctb.CTB_GPIB_GET_EOS_CHAR,eos)
return wxctb.intp_value(eos)
def GetEosMode(self):
"""
Get the internal EOS mode (see SetEosMode).
For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosMode()
"""
mode = wxctb.new_intp()
wxctb.intp_assign(mode, 0)
self.device.Ioctl(wxctb.CTB_GPIB_GET_EOS_MODE,mode)
return wxctb.intp_value(mode)
def GetError(self):
errorString = " "*256
self.device.GetError(errorString,256)
return errorString
def GetSTB(self):
"""
Returns the value of the internal GPIB status byte register.
"""
stb = wxctb.new_intp()
wxctb.intp_assign(stb, 0)
self.device.Ioctl(wxctb.CTB_GPIB_GETRSP,stb)
return wxctb.intp_value(stb)
# This is only for internal usage!!!
def Ibrd(self,length):
buf = "\x00"*length
state = self.device.Ibrd(buf,length)
return state,buf
# This is only for internal usage!!!
def Ibwrt(self,string):
return self.device.Ibwrt(string,len(string))
def Open(self,devname,adr,eosChar=10,eosMode=0x08|0x04):
"""
Open(gpibdevice,address,eosChar,eosMode)
Opens a connected device at the GPIB bus. gpibdevice means the
controller, (mostly \"gpib1\"), address the address of the desired
device in the range 1...31. The eosChar defines the EOS character
(default is linefeed), eosMode may be a combination of bits ORed
together. The following bits can be used:
0x04: Terminate read when EOS is detected.
0x08: Set EOI (End or identify line) with EOS on write function
0x10: Compare all 8 bits of EOS byte rather than low 7 bits
(all read and write functions). Default is 0x12
For example:
dev = GPIB()
dev.Open(\"gpib1\",17)
Opens the device with the address 17, linefeed as EOS (default)
and eos mode with 0x04 and 0x08.
Open returns >= 0 or a negativ value, if something going wrong.
"""
self.device = wxctb.GpibDevice()
dcs = wxctb.Gpib_DCS()
dcs.m_address1 = adr
dcs.m_eosChar = eosChar
dcs.m_eosMode = eosMode
result = self.device.Open(devname,dcs)
return result
def Reset(self):
"""
Resets the connected device. In the GPIB definition, the device
should be reset to it's initial state, so you can restart a
formely lost communication.
"""
self.device.Ioctl(wxctb.CTB_RESET,None)
def ResetBus(self):
"""
The command asserts the GPIB interface clear (IFC) line for
ast least 100us if the GPIB board is the system controller.
This initializes the GPIB and makes the interface CIC and
active controller with ATN asserted.
Note! The IFC signal resets only the GPIB interface functions
of the bus devices and not the internal device functions.
For a device reset you should use the Reset() command above.
"""
self.device.Ioctl(wxctb.CTB_GPIB_RESET_BUS,None)
def SetEosChar(self,eos):
"""
Configure the end-of-string (EOS) termination character.
Note! Defining an EOS byte does not cause the driver to
automatically send that byte at the end of write I/O
operations. The application is responsible for placing the
EOS byte at the end of the data strings that it defines.
(National Instruments NI-488.2M Function Reference Manual)
For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosChar(0x10)
"""
intp = wxctb.new_intp()
wxctb.intp_assign(intp, eos)
return self.device.Ioctl(wxctb.CTB_GPIB_SET_EOS_CHAR,intp)
def SetEosMode(self,mode):
"""
Set the EOS mode (handling).m_eosMode may be a combination
of bits ORed together. The following bits can be used:
0x04: Terminate read when EOS is detected.
0x08: Set EOI (End or identify line) with EOS on write function
0x10: Compare all 8 bits of EOS byte rather than low 7 bits
(all read and write functions). For example:
g = GPIB()
g.Open(\"gpib1\",1)
eos = g.GetEosMode(0x04 | 0x08)
"""
intp = wxctb.new_intp()
wxctb.intp_assign(intp, mode)
return self.device.Ioctl(wxctb.CTB_GPIB_SET_EOS_MODE,intp)
def GetKey():
"""
Returns the current pressed key or '\0', if no key is pressed.
You can simply create a query loop with:
while GetKey() == '\0':
... make some stuff ...
"""
return wxctb.GetKey()
def GetVersion():
"""
Returns the version of the ctb python module. The numbering
has the following format: x.y.z
x.y means the version of the underlaying ctb lib, z the version
of the python port.
"""
return "0.16"

View File

@ -0,0 +1,96 @@
%{
#include "ctb-0.16/gpib.h"
%}
%include iobase.i
namespace ctb {
%typemap(in) void * dcs (Gpib_DCS tmp) {
/* dont check for list */
$1 = &tmp;
}
enum GpibTimeout
{
GpibTimeoutNONE = 0,
GpibTimeout10us,
GpibTimeout30us,
GpibTimeout100us,
GpibTimeout300us,
GpibTimeout1ms,
GpibTimeout3ms,
GpibTimeout10ms,
GpibTimeout30ms,
GpibTimeout100ms,
GpibTimeout300ms,
GpibTimeout1s,
GpibTimeout3s,
GpibTimeout10s,
GpibTimeout30s,
GpibTimeout100s,
GpibTimeout300s,
GpibTimeout1000s
};
struct Gpib_DCS
{
int m_address1;
int m_address2;
GpibTimeout m_timeout;
bool m_eot;
unsigned char m_eosChar;
unsigned char m_eosMode;
Gpib_DCS();
~Gpib_DCS();
char* GetSettings();
};
enum {
CTB_GPIB_SETADR = CTB_GPIB,
CTB_GPIB_GETRSP,
CTB_GPIB_GETSTA,
CTB_GPIB_GETERR,
CTB_GPIB_GETLINES,
CTB_GPIB_SETTIMEOUT,
CTB_GPIB_GTL,
CTB_GPIB_REN,
CTB_GPIB_RESET_BUS,
CTB_GPIB_SET_EOS_CHAR,
CTB_GPIB_GET_EOS_CHAR,
CTB_GPIB_SET_EOS_MODE,
CTB_GPIB_GET_EOS_MODE
};
class GpibDevice : public IOBase
{
protected:
int m_board;
int m_hd;
int m_state;
int m_error;
int m_count;
int m_asyncio;
Gpib_DCS m_dcs;
int CloseDevice();
int OpenDevice(const char* devname, void* dcs);
virtual const char* GetErrorString(int error,bool detailed);
public:
GpibDevice();
virtual ~GpibDevice();
const char* ClassName();
virtual const char* GetErrorDescription(int error);
virtual const char* GetErrorNotation(int error);
virtual char* GetSettingsAsString();
int Ibrd(char* buf,size_t len);
int Ibwrt(char* buf,size_t len);
virtual int Ioctl(int cmd,void* args);
int IsOpen();
int Read(char* buf,size_t len);
int Write(char* buf,size_t len);
static int FindListeners(int board = 0);
};
};

View File

@ -0,0 +1,59 @@
%{
#include "ctb-0.16/iobase.h"
%}
namespace ctb {
enum {
CTB_RESET = CTB_COMMON
};
%typemap(in) char *& readbuf (char * tmp) {
/* dont check for list */
$1 = &tmp;
}
%typemap(argout) char *& readbuf {
PyObject * plist = PyList_New(2);
PyList_SetItem(plist, 0, PyString_FromString(*$1));
PyList_SetItem(plist, 1, $result);
$result = plist;
delete *$1;
}
%typemap(in) size_t * readedBytes (size_t tmp) {
/* dont check for list */
$1 = &tmp;
}
%typemap(argout) size_t * readedBytes {
PyList_Append($result, PyInt_FromLong(*$1));
}
class IOBase
{
protected:
virtual int CloseDevice() = 0;
virtual int OpenDevice(const char* devname, void* dcs = 0L) = 0;
public:
IOBase();
virtual ~IOBase();
virtual const char* ClassName();
int Close();
virtual int Ioctl(int cmd,void* args);
virtual int IsOpen() = 0;
int Open(const char* devname,void* dcs=0L);
int PutBack(char ch);
virtual int Read(char* buf,size_t len) = 0;
virtual int ReadUntilEOS(char*& readbuf,
size_t* readedBytes,
char* eosString = "\n",
long timeout_in_ms = 1000L,
char quota = 0);
int Readv(char* buf,size_t len,unsigned int timeout_in_ms);
virtual int Write(char* buf,size_t len) = 0;
int Writev(char* buf,size_t len,unsigned int timeout_in_ms);
};
};

View File

@ -0,0 +1,9 @@
%{
#include "ctb-0.16/kbhit.h"
%}
namespace ctb {
char GetKey();
};

View File

@ -0,0 +1,63 @@
#!/bin/bash
CFLAG=''
GPIB_SOURCES=''
GPIB_LIB=''
GPIB_SUPPORT=''
# the python develop version. Please check the right version of your
# python developent enviroment
PYTHON_VERSION='2.6'
for arg in $*; do
if [ "$arg" = "USE_GPIB" ]; then
GPIB_SOURCES='../../../src/gpib.cpp'
GPIB_LIB='-lgpib'
GPIB_SUPPORT='Yes'
else
echo '============================================================'
echo 'You run makepy.sh without GPIB support.'
echo 'If you want to create the python wxctb library with'
echo 'GPIB support, rerun the command with:'
echo 'makepy.sh USE_GPIB=1'
echo '============================================================'
GPIB_SUPPORT='No'
fi
if [ "$arg" = "USE_DEBUG" ]; then
CFLAG='-g'
fi
done
echo "// This file is created automatically, don't change it!" > wxctb.i
echo "%module wxctb" >> wxctb.i
echo "typedef int size_t;" >> wxctb.i
echo "%include timer.i" >> wxctb.i
echo "%include serport.i" >> wxctb.i
echo "%include ../kbhit.i" >> wxctb.i
if [ "$arg" = "USE_GPIB" ]; then
echo "%include ../gpib.i" >> wxctb.i
fi
echo "swig generates python wrapper files..."
swig -c++ -Wall -nodefault -python -keyword -new_repr -modern wxctb.i
echo "create shared library wxctb with GPIB=$GPIB_SUPPORT for python"\
"$PYTHON_VERSION ..."
g++ -Wall $CFLAG -shared -I /usr/include/python$PYTHON_VERSION/ \
-I ../../../include \
wxctb_wrap.cxx \
../../../src/linux/timer.cpp \
../../../src/linux/serport.cpp \
../../../src/serportx.cpp \
../../../src/kbhit.cpp \
../../../src/iobase.cpp \
../../../src/fifo.cpp \
$GPIB_SOURCES \
$GPIB_LIB \
-o _wxctb.so
echo "copy ctb.py, wxctb.py and _wxctb.so to the module/linux folder..."
mkdir -p ../../module/linux
cp ../ctb.py ../../module/linux/
cp wxctb.py ../../module/linux/
cp _wxctb.so ../../module/linux/

View File

@ -0,0 +1,50 @@
%module serport
%{
#include "ctb-0.16/linux/serport.h"
%}
%include ../serportx.i
namespace ctb {
%pythoncode {
COM1 = "/dev/ttyS0"
COM2 = "/dev/ttyS1"
COM3 = "/dev/ttyS2"
COM4 = "/dev/ttyS3"
COM5 = "/dev/ttyS4"
COM6 = "/dev/ttyS5"
COM7 = "/dev/ttyS6"
COM8 = "/dev/ttyS7"
COM9 = "/dev/ttyS8"
};
class SerialPort : public SerialPort_x
{
protected:
int fd;
struct termios t, save_t;
struct serial_icounter_struct save_info, last_info;
speed_t AdaptBaudrate(int baud);
int CloseDevice();
int OpenDevice(const char* devname, void* dcs);
public:
SerialPort();
~SerialPort();
int ChangeLineState(SerialLineState flags);
int ClrLineState(SerialLineState flags);
int GetLineState();
int Ioctl(int cmd,void* args);
int IsOpen();
int Read(char* buf,size_t len);
int SendBreak(int duration);
int SetBaudrate(int baudrate);
int SetLineState(SerialLineState flags);
int SetParityBit( bool parity );
int Write(char* buf,size_t len);
};
};

View File

@ -0,0 +1,37 @@
%{
#include "ctb-0.16/linux/timer.h"
%}
%include cpointer.i
// lets create new fuctions for pointer handling in python (for int *exitflag)
%pointer_functions(int, intp);
namespace ctb {
// perhaps we doesn''t need timer_control to export
// but we need if we want to inherit from timer in python
struct timer_control
{
unsigned int usecs;
int *exitflag;
void* (*exitfnc)(void*);
};
class Timer
{
protected:
timer_control control;
int stopped;
pthread_t tid;
unsigned int timer_secs;
public:
Timer(unsigned int msec,int* exitflag,void*(*exitfnc)(void*)=NULL);
~Timer();
int start();
int stop();
};
void sleepms(unsigned int ms);
};

View File

@ -0,0 +1,6 @@
// This file is created automatically, don't change it!
%module wxctb
typedef int size_t;
%include timer.i
%include serport.i
%include ../kbhit.i

View File

@ -0,0 +1,264 @@
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.40
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import dirname
import imp
fp = None
try:
fp, pathname, description = imp.find_module('_wxctb', [dirname(__file__)])
except ImportError:
import _wxctb
return _wxctb
if fp is not None:
try:
_mod = imp.load_module('_wxctb', fp, pathname, description)
finally:
fp.close()
return _mod
_wxctb = swig_import_helper()
del swig_import_helper
else:
import _wxctb
del version_info
try:
_swig_property = property
except NameError:
pass # Python < 2.2 doesn't have 'property'.
def _swig_setattr_nondynamic(self,class_type,name,value,static=1):
if (name == "thisown"): return self.this.own(value)
if (name == "this"):
if type(value).__name__ == 'SwigPyObject':
self.__dict__[name] = value
return
method = class_type.__swig_setmethods__.get(name,None)
if method: return method(self,value)
if (not static) or hasattr(self,name):
self.__dict__[name] = value
else:
raise AttributeError("You cannot add attributes to %s" % self)
def _swig_setattr(self,class_type,name,value):
return _swig_setattr_nondynamic(self,class_type,name,value,0)
def _swig_getattr(self,class_type,name):
if (name == "thisown"): return self.this.own()
method = class_type.__swig_getmethods__.get(name,None)
if method: return method(self)
raise AttributeError(name)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__()
except: strthis = ""
return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try:
_object = object
_newclass = 1
except AttributeError:
class _object : pass
_newclass = 0
def _swig_setattr_nondynamic_method(set):
def set_attr(self,name,value):
if (name == "thisown"): return self.this.own(value)
if hasattr(self,name) or (name == "this"):
set(self,name,value)
else:
raise AttributeError("You cannot add attributes to %s" % self)
return set_attr
def new_intp():
return _wxctb.new_intp()
new_intp = _wxctb.new_intp
def copy_intp(*args, **kwargs):
return _wxctb.copy_intp(*args, **kwargs)
copy_intp = _wxctb.copy_intp
def delete_intp(*args, **kwargs):
return _wxctb.delete_intp(*args, **kwargs)
delete_intp = _wxctb.delete_intp
def intp_assign(*args, **kwargs):
return _wxctb.intp_assign(*args, **kwargs)
intp_assign = _wxctb.intp_assign
def intp_value(*args, **kwargs):
return _wxctb.intp_value(*args, **kwargs)
intp_value = _wxctb.intp_value
class timer_control(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined")
__repr__ = _swig_repr
usecs = _swig_property(_wxctb.timer_control_usecs_get, _wxctb.timer_control_usecs_set)
exitflag = _swig_property(_wxctb.timer_control_exitflag_get, _wxctb.timer_control_exitflag_set)
exitfnc = _swig_property(_wxctb.timer_control_exitfnc_get, _wxctb.timer_control_exitfnc_set)
timer_control_swigregister = _wxctb.timer_control_swigregister
timer_control_swigregister(timer_control)
class Timer(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args, **kwargs):
this = _wxctb.new_Timer(*args, **kwargs)
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_Timer
__del__ = lambda self : None;
def start(self): return _wxctb.Timer_start(self)
def stop(self): return _wxctb.Timer_stop(self)
Timer_swigregister = _wxctb.Timer_swigregister
Timer_swigregister(Timer)
def sleepms(*args, **kwargs):
return _wxctb.sleepms(*args, **kwargs)
sleepms = _wxctb.sleepms
CTB_RESET = _wxctb.CTB_RESET
class IOBase(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _wxctb.delete_IOBase
__del__ = lambda self : None;
def ClassName(self): return _wxctb.IOBase_ClassName(self)
def Close(self): return _wxctb.IOBase_Close(self)
def Ioctl(self, *args, **kwargs): return _wxctb.IOBase_Ioctl(self, *args, **kwargs)
def IsOpen(self): return _wxctb.IOBase_IsOpen(self)
def Open(self, *args, **kwargs): return _wxctb.IOBase_Open(self, *args, **kwargs)
def PutBack(self, *args, **kwargs): return _wxctb.IOBase_PutBack(self, *args, **kwargs)
def Read(self, *args, **kwargs): return _wxctb.IOBase_Read(self, *args, **kwargs)
def ReadUntilEOS(self, *args, **kwargs): return _wxctb.IOBase_ReadUntilEOS(self, *args, **kwargs)
def Readv(self, *args, **kwargs): return _wxctb.IOBase_Readv(self, *args, **kwargs)
def Write(self, *args, **kwargs): return _wxctb.IOBase_Write(self, *args, **kwargs)
def Writev(self, *args, **kwargs): return _wxctb.IOBase_Writev(self, *args, **kwargs)
IOBase_swigregister = _wxctb.IOBase_swigregister
IOBase_swigregister(IOBase)
ParityNone = _wxctb.ParityNone
ParityOdd = _wxctb.ParityOdd
ParityEven = _wxctb.ParityEven
ParityMark = _wxctb.ParityMark
ParitySpace = _wxctb.ParitySpace
LinestateDcd = _wxctb.LinestateDcd
LinestateCts = _wxctb.LinestateCts
LinestateDsr = _wxctb.LinestateDsr
LinestateDtr = _wxctb.LinestateDtr
LinestateRing = _wxctb.LinestateRing
LinestateRts = _wxctb.LinestateRts
LinestateNull = _wxctb.LinestateNull
class SerialPort_DCS(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
baud = _swig_property(_wxctb.SerialPort_DCS_baud_get, _wxctb.SerialPort_DCS_baud_set)
parity = _swig_property(_wxctb.SerialPort_DCS_parity_get, _wxctb.SerialPort_DCS_parity_set)
wordlen = _swig_property(_wxctb.SerialPort_DCS_wordlen_get, _wxctb.SerialPort_DCS_wordlen_set)
stopbits = _swig_property(_wxctb.SerialPort_DCS_stopbits_get, _wxctb.SerialPort_DCS_stopbits_set)
rtscts = _swig_property(_wxctb.SerialPort_DCS_rtscts_get, _wxctb.SerialPort_DCS_rtscts_set)
xonxoff = _swig_property(_wxctb.SerialPort_DCS_xonxoff_get, _wxctb.SerialPort_DCS_xonxoff_set)
buf = _swig_property(_wxctb.SerialPort_DCS_buf_get, _wxctb.SerialPort_DCS_buf_set)
def __init__(self):
this = _wxctb.new_SerialPort_DCS()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_SerialPort_DCS
__del__ = lambda self : None;
def GetSettings(self): return _wxctb.SerialPort_DCS_GetSettings(self)
SerialPort_DCS_swigregister = _wxctb.SerialPort_DCS_swigregister
SerialPort_DCS_swigregister(SerialPort_DCS)
class SerialPort_EINFO(object):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
brk = _swig_property(_wxctb.SerialPort_EINFO_brk_get, _wxctb.SerialPort_EINFO_brk_set)
frame = _swig_property(_wxctb.SerialPort_EINFO_frame_get, _wxctb.SerialPort_EINFO_frame_set)
overrun = _swig_property(_wxctb.SerialPort_EINFO_overrun_get, _wxctb.SerialPort_EINFO_overrun_set)
parity = _swig_property(_wxctb.SerialPort_EINFO_parity_get, _wxctb.SerialPort_EINFO_parity_set)
def __init__(self):
this = _wxctb.new_SerialPort_EINFO()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_SerialPort_EINFO
__del__ = lambda self : None;
SerialPort_EINFO_swigregister = _wxctb.SerialPort_EINFO_swigregister
SerialPort_EINFO_swigregister(SerialPort_EINFO)
CTB_SER_GETEINFO = _wxctb.CTB_SER_GETEINFO
CTB_SER_GETBRK = _wxctb.CTB_SER_GETBRK
CTB_SER_GETFRM = _wxctb.CTB_SER_GETFRM
CTB_SER_GETOVR = _wxctb.CTB_SER_GETOVR
CTB_SER_GETPAR = _wxctb.CTB_SER_GETPAR
CTB_SER_GETINQUE = _wxctb.CTB_SER_GETINQUE
CTB_SER_SETPAR = _wxctb.CTB_SER_SETPAR
class SerialPort_x(IOBase):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
def __init__(self, *args, **kwargs): raise AttributeError("No constructor defined - class is abstract")
__repr__ = _swig_repr
__swig_destroy__ = _wxctb.delete_SerialPort_x
__del__ = lambda self : None;
def ClassName(self): return _wxctb.SerialPort_x_ClassName(self)
def ChangeLineState(self, *args, **kwargs): return _wxctb.SerialPort_x_ChangeLineState(self, *args, **kwargs)
def ClrLineState(self, *args, **kwargs): return _wxctb.SerialPort_x_ClrLineState(self, *args, **kwargs)
def GetLineState(self): return _wxctb.SerialPort_x_GetLineState(self)
def GetSettingsAsString(self): return _wxctb.SerialPort_x_GetSettingsAsString(self)
def Ioctl(self, *args, **kwargs): return _wxctb.SerialPort_x_Ioctl(self, *args, **kwargs)
def SendBreak(self, *args, **kwargs): return _wxctb.SerialPort_x_SendBreak(self, *args, **kwargs)
def SetBaudrate(self, *args, **kwargs): return _wxctb.SerialPort_x_SetBaudrate(self, *args, **kwargs)
def SetLineState(self, *args, **kwargs): return _wxctb.SerialPort_x_SetLineState(self, *args, **kwargs)
def SetParityBit(self, *args, **kwargs): return _wxctb.SerialPort_x_SetParityBit(self, *args, **kwargs)
IsStandardRate = staticmethod(_wxctb.SerialPort_x_IsStandardRate)
SerialPort_x_swigregister = _wxctb.SerialPort_x_swigregister
SerialPort_x_swigregister(SerialPort_x)
def SerialPort_x_IsStandardRate(*args, **kwargs):
return _wxctb.SerialPort_x_IsStandardRate(*args, **kwargs)
SerialPort_x_IsStandardRate = _wxctb.SerialPort_x_IsStandardRate
COM1 = "/dev/ttyS0"
COM2 = "/dev/ttyS1"
COM3 = "/dev/ttyS2"
COM4 = "/dev/ttyS3"
COM5 = "/dev/ttyS4"
COM6 = "/dev/ttyS5"
COM7 = "/dev/ttyS6"
COM8 = "/dev/ttyS7"
COM9 = "/dev/ttyS8"
class SerialPort(SerialPort_x):
thisown = _swig_property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self):
this = _wxctb.new_SerialPort()
try: self.this.append(this)
except: self.this = this
__swig_destroy__ = _wxctb.delete_SerialPort
__del__ = lambda self : None;
def ChangeLineState(self, *args, **kwargs): return _wxctb.SerialPort_ChangeLineState(self, *args, **kwargs)
def ClrLineState(self, *args, **kwargs): return _wxctb.SerialPort_ClrLineState(self, *args, **kwargs)
def GetLineState(self): return _wxctb.SerialPort_GetLineState(self)
def Ioctl(self, *args, **kwargs): return _wxctb.SerialPort_Ioctl(self, *args, **kwargs)
def IsOpen(self): return _wxctb.SerialPort_IsOpen(self)
def Read(self, *args, **kwargs): return _wxctb.SerialPort_Read(self, *args, **kwargs)
def SendBreak(self, *args, **kwargs): return _wxctb.SerialPort_SendBreak(self, *args, **kwargs)
def SetBaudrate(self, *args, **kwargs): return _wxctb.SerialPort_SetBaudrate(self, *args, **kwargs)
def SetLineState(self, *args, **kwargs): return _wxctb.SerialPort_SetLineState(self, *args, **kwargs)
def SetParityBit(self, *args, **kwargs): return _wxctb.SerialPort_SetParityBit(self, *args, **kwargs)
def Write(self, *args, **kwargs): return _wxctb.SerialPort_Write(self, *args, **kwargs)
SerialPort_swigregister = _wxctb.SerialPort_swigregister
SerialPort_swigregister(SerialPort)
def GetKey():
return _wxctb.GetKey()
GetKey = _wxctb.GetKey

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,84 @@
%{
#include "ctb-0.16/serportx.h"
%}
%include iobase.i
namespace ctb {
enum Parity
{
ParityNone,
ParityOdd,
ParityEven,
ParityMark,
ParitySpace
};
enum SerialLineState
{
LinestateDcd = 0x040,
LinestateCts = 0x020,
LinestateDsr = 0x100,
LinestateDtr = 0x002,
LinestateRing = 0x080,
LinestateRts = 0x004,
LinestateNull = 0x000
};
struct SerialPort_DCS
{
int baud;
Parity parity;
unsigned char wordlen;
unsigned char stopbits;
bool rtscts;
bool xonxoff;
char buf[16];
SerialPort_DCS();
~SerialPort_DCS();
char* GetSettings();
};
struct SerialPort_EINFO
{
int brk;
int frame;
int overrun;
int parity;
SerialPort_EINFO();
~SerialPort_EINFO();
};
enum {
CTB_SER_GETEINFO = CTB_SERIAL,
CTB_SER_GETBRK,
CTB_SER_GETFRM,
CTB_SER_GETOVR,
CTB_SER_GETPAR,
CTB_SER_GETINQUE,
CTB_SER_SETPAR,
};
class SerialPort_x : public IOBase
{
protected:
SerialPort_DCS m_dcs;
char m_devname[SERIALPORT_NAME_LEN];
public:
SerialPort_x();
virtual ~SerialPort_x();
const char* ClassName();
virtual int ChangeLineState(SerialLineState flags) = 0;
virtual int ClrLineState(SerialLineState flags) = 0;
virtual int GetLineState() = 0;
virtual char* GetSettingsAsString();
virtual int Ioctl(int cmd,void* args);
virtual int SendBreak(int duration) = 0;
virtual int SetBaudrate(int baudrate) = 0;
virtual int SetLineState(SerialLineState flags) = 0;
virtual int SetParityBit( bool parity ) = 0;
static bool IsStandardRate( long rate );
};
};

View File

@ -0,0 +1,65 @@
@ECHO OFF
REM ##################################################################
REM # set the path/settings of your compiler enviroment and remove the
REM # comment command (REM)
REM # (you don't need this, if you set it always in your system
REM # enviroment)
REM ##################################################################
REM CALL "c:\Programme\Microsoft Visual C++ Toolkit 2003\vcvars32.bat"
REM ##################################################################
REM # set the path to your python24 (or python23) library, for example
REM # works for me with C:\Program Files\Python2.4\libs\python24.lib
REM ##################################################################
SET PYTHON_LIB="C:\Program Files\Python2.4\libs\python24.lib"
REM ##################################################################
REM # set the include path of your python24 (python23) deleveloper
REM # header files. For me, it's on C:\Program Files
REM ##################################################################
SET PYTHON_INCLUDE="C:\Program Files\Python2.4\include"
REM ##################################################################
REM # after installing swig, set the path, so the script can find it
REM ##################################################################
SET SWIG="C:\Program Files\swigwin-1.3.40\swig"
REM ##################################################################
REM # DON'T CHANGE ANYMORE AT THE FOLLOWING LINES!!!
REM ##################################################################
SET GPIB_LIB=
SET GPIB_SRC=
ECHO // This file is created automatically, don't change it! > wxctb.i
ECHO %%module wxctb >> wxctb.i
ECHO typedef int size_t; >> wxctb.i
ECHO %%include timer.i >> wxctb.i
ECHO %%include serport.i >> wxctb.i
ECHO %%include ../kbhit.i >> wxctb.i
IF NOT [%1]==[USE_GPIB] GOTO nogpib
SET GPIB_LIB=../../../lib/gpib32.lib
SET GPIB_SRC=../../../src/gpib.cpp
ECHO %%include ../gpib.i >> wxctb.i
:nogpib
DEL *.obj wxctb_wrap.cxx *.lib *.dll *.exp
ECHO "swig generates python wrapper files..."
%SWIG% -c++ -Wall -nodefault -python -keyword -new_repr -modern wxctb.i
ECHO "create shared library wxctb for python 2.4..."
cl /LD /D WIN32 /I %PYTHON_INCLUDE% /I ../../../include wxctb_wrap.cxx ../../../src/win32/serport.cpp ../../../src/serportx.cpp ../../../src/win32/timer.cpp ../../../src/kbhit.cpp ../../../src/iobase.cpp %GPIB_SRC% ../../../src/fifo.cpp /link %PYTHON_LIB% winmm.lib %GPIB_LIB%
MOVE wxctb_wrap.dll _wxctb.dll
ECHO "copy ctb.py, wxctb.py and _wxctb.so to the module/win32 folder..."
MKDIR ..\..\module\win32
COPY ..\ctb.py ..\..\module\win32
COPY wxctb.py ..\..\module\win32
COPY _wxctb.dll ..\..\module\win32

View File

@ -0,0 +1,57 @@
%{
#include "ctb-0.16/win32/serport.h"
%}
%include ../serportx.i
namespace ctb {
%pythoncode {
COM1 = "com1"
COM2 = "com2"
COM3 = "com3"
COM4 = "com4"
COM5 = "com5"
COM6 = "com6"
COM7 = "com7"
COM8 = "com8"
COM9 = "com9"
COM10 = "\\\\.\\com10"
COM11 = "\\\\.\\com11"
COM12 = "\\\\.\\com12"
COM13 = "\\\\.\\com13"
COM14 = "\\\\.\\com14"
COM15 = "\\\\.\\com15"
COM16 = "\\\\.\\com16"
COM17 = "\\\\.\\com17"
COM18 = "\\\\.\\com18"
COM19 = "\\\\.\\com19"
};
class SerialPort : public SerialPort_x
{
protected:
HANDLE fd;
OVERLAPPED ov;
SerialPort_EINFO einfo;
int CloseDevice();
int OpenDevice(const char* devname, void* dcs);
public:
SerialPort();
~SerialPort();
int ChangeLineState(SerialLineState flags);
int ClrLineState(SerialLineState flags);
int GetLineState();
int Ioctl(int cmd,void* args);
int IsOpen();
int Read(char* buf,size_t len);
int SendBreak(int duration);
int SetBaudrate(int baudrate);
int SetLineState(SerialLineState flags);
int SetParityBit( bool parity );
int Write(char* buf,size_t len);
};
};

View File

@ -0,0 +1,39 @@
%{
#include "ctb-0.16/win32/timer.h"
%}
%include cpointer.i
// lets create new fuctions for pointer handling in python (for int *exitflag)
%pointer_functions(int, intp);
namespace ctb {
// perhaps we doesn''t need timer_control to export
// but we need if we want to inherit from timer in python
struct timer_control
{
unsigned int msecs;
int *exitflag;
MMRESULT stop;
void* (*exitfnc)(void*);
};
class Timer
{
protected:
DWORD id;
MMRESULT h;
timer_control control;
unsigned int timer_secs;
public:
Timer(unsigned int msec,int* exitflag,void*(*exitfnc)(void*)=NULL);
~Timer();
int start();
int stop();
};
void sleepms(unsigned int ms);
};

View File

@ -0,0 +1,6 @@
// This file is created automatically, don't change it!
%module wxctb
typedef int size_t;
%include timer.i
%include serport.i
%include ../kbhit.i

View File

@ -0,0 +1,181 @@
#include "ctb-0.16/ctb.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
// ----------------- options -------------------------------
const char* options="a:b:d:e:hlp:t:";
const char* helpMessage =
{
"A simple serial port class test\n"
"ctbtest [options]\n"
"available options are:\n"
"-a : address (only GPIB)\n"
"-b : baudrate [any value], default is 38400\n"
"-d : connected device, default is COM1\n"
"-e : eos\n"
"-h : print this\n"
"-l : list all available serial ports\n"
"-p : protocol like 8N1\n"
"-t : communication timeout in ms (default is 100ms)\n"
};
int main(int argc,char* argv[])
{
int address = 15;
int baudrate = 19200;
string devname = ctb::COM1;
string eos = "\r\n";
string protocol = "8N1";
int timeout = 100;
bool showAvailablePorts = false;
int quit = 0;
int val;
while ( ( val=getopt( argc, argv, (char*)options ) ) != EOF ) {
switch ( val ) {
case 'a' : address = strtol( optarg, NULL, 10 ); break;
case 'b' : baudrate = strtol( optarg, NULL, 10 ); break;
case 'd' : devname = optarg; break;
case 'h' : cerr << helpMessage << endl; exit( 0 );
case 'l' : showAvailablePorts = true; break;
case 'p' : protocol = optarg; break;
case 't' : timeout = strtol( optarg, NULL, 10 ); break;
}
}
ctb::IOBase* device = NULL;
std::vector<std::string> ports;
if( ctb::GetAvailablePorts( ports ) && showAvailablePorts ) {
for( int i = 0; i < ports.size();
std::cout << ports[ i++ ] << endl ) {};
return 0;
}
#if ( GPIB )
if( ( devname == ctb::GPIB1 ) || ( devname == ctb::GPIB2 ) ) {
ctb::GpibDevice* gpibDevice = new ctb::GpibDevice();
if( gpibDevice->Open( devname.c_str(), address ) >= 0 ) {
device = gpibDevice;
}
}
else {
#endif
ctb::SerialPort* serialPort = new ctb::SerialPort();
if( serialPort->Open( devname.c_str(), baudrate,
protocol.c_str(),
ctb::SerialPort::NoFlowControl ) >= 0 ) {
device = serialPort;
}
#if ( GPIB )
}
#endif
if( ! device ) {
cout << "Cannot open " << devname.c_str() << endl;
return -1;
}
// up to know you don't have to worry any longer about the kind of
// the connected device. As long as you do nothing something device
// specific (like toggle some modem control lines), the access is
// the same for each device.
string line;
char receiveBuf[ 128 ];
cout << "Enter your command or just press Enter without any\n"
"input for exit!";
while( true ) {
cout << endl << "Your input >";
// read the string to send
getline( cin, line );
// add some defined EOS (end of string sequence or character)
if( line.empty() ) {
break;
}
line += eos;
// send data throughout the connected device independent of the typ
if( device->Writev( (char*)line.c_str(),
line.size(),
timeout ) != line.size() ) {
cerr << "Incomplete data transmission" << endl;
}
int readed = 0;
do {
// in case of an event driven GUI you better use a non blocking
// Read(...) in your idle function. Here we have to wait for the
// response before we send another user command...
readed = device->Readv( receiveBuf,
sizeof( receiveBuf ) - 1,
timeout);
// something received?
if( readed > 0 ) {
receiveBuf[ readed ] = 0;
cout << receiveBuf;
}
} while( readed > 0 );
cout << endl;
} // while( true )
device->Close();
delete device;
return 0;
}

View File

@ -0,0 +1,130 @@
/////////////////////////////////////////////////////////////////////////////
// Name: fifo.cpp
// Purpose:
// Author: Joachim Buermann, Michael Hungershausen
// Id: $Id$
// Copyright: (c) 2006,2007 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/fifo.h"
namespace ctb {
Fifo::Fifo(size_t size) :
m_size(size)
{
m_begin = new char[size];
m_end = m_begin + m_size;
m_rdptr = m_wrptr = m_begin;
};
Fifo::~Fifo()
{
delete m_begin;
};
void Fifo::clear()
{
m_rdptr = m_wrptr = m_begin;
};
int Fifo::get(char* ch)
{
if(m_rdptr != m_wrptr) {
*ch = *m_rdptr++;
if(m_rdptr >= m_end) {
m_rdptr = m_begin;
}
return 1;
}
return 0;
};
size_t Fifo::items()
{
char* tmp_wrptr = m_wrptr;
// the rdptr will only changed by the reader. If we suppose, that
// the caller of the items() method is identical with the reader,
// this should be thread save.
char* tmp_rdptr = m_rdptr;
// if the write pointer is identical with the read, there are no
// more data in the Fifo
if(tmp_wrptr == tmp_rdptr) {
return 0;
}
// the write pointer is greater as the read pointer, so we just
// can calculate the difference for the remaining data
if(tmp_wrptr > tmp_rdptr) {
return (tmp_wrptr - tmp_rdptr);
}
// the write pointer has circulate and stands against the read
// pointer
else {
return (m_size - (tmp_rdptr - tmp_wrptr));
}
};
int Fifo::put(char ch)
{
// for a thread safe operation, the write of a data byte must be
// atomic. So we first assign the current position of the write
// pointer to a temporary pointer.
// Increment it for the comparison with the end of the internal
// buffer and the read pointer
char* tmp_wrptr = m_wrptr + 1;
if(tmp_wrptr >= m_end) {
tmp_wrptr = m_begin;
}
if(tmp_wrptr == m_rdptr) {
return 0;
}
// this don't changes the write pointer!
*m_wrptr = ch;
// that's the trick! The following assignment is atomic and cannot
// interrupted within a read access by the read thread
m_wrptr = tmp_wrptr;
return 1;
};
int Fifo::read(char* data,int n)
{
int nresult = 0;
while(n--) {
// the same as get()
if(m_rdptr != m_wrptr) {
*data = *m_rdptr++;
if(m_rdptr >= m_end) {
m_rdptr = m_begin;
}
}
else {
break;
}
nresult++;
data++;
}
return nresult;
};
int Fifo::write(char* data,int n)
{
int nresult = 0;
while(n--) {
// the same as put()
char* tmp_wrptr = m_wrptr + 1;
if(tmp_wrptr >= m_end) {
tmp_wrptr = m_begin;
}
if(tmp_wrptr == m_rdptr) {
break;
}
*m_wrptr = *data++;
m_wrptr = tmp_wrptr;
nresult++;
}
return nresult;
};
} // namespace ctb

View File

@ -0,0 +1,14 @@
/////////////////////////////////////////////////////////////////////////////
// Name: getopt.cpp
// Purpose: simple wrapper file
// Author: Joachim Buermann
// Id: $Id: timer.h,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#if defined (WIN32)
# include "win32/getopt.cpp"
#endif

View File

@ -0,0 +1,338 @@
/////////////////////////////////////////////////////////////////////////////
// Name: gpibx.cpp
// Purpose:
// Author: Joachim Buermann
// Id: $Id: gpibx.cpp,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001,2004 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/gpib.h"
#include "ctb-0.16/timer.h"
#include <stdio.h>
#include <string.h>
#ifdef WIN32
# include "ctb-0.16/win32/gpib-32.h"
# define snprintf _snprintf
#elif __GNUG__
# include <gpib/ib.h>
#endif
namespace ctb {
const char* GPIB1 = "gpib1";
const char* GPIB2 = "gpib2";
struct gpibErr_t {
int m_errno;
const char* m_notation;
const char* m_description;
};
static gpibErr_t gpibErrors[] = {
{0,"EDVR","DOS Error"},
{1,"ECIC","Specified GPIB Interface Board is Not Active Controller"},
{2,"ENOL","No present listing device"},
{3,"EADR","GPIB Board has not been addressed properly"},
{4,"EARG","Invalid argument"},
{5,"ESAC","Specified GPIB Interface Board is not System Controller"},
{6,"EABO","I/O operation aborted (time-out)"},
{7,"ENEB","Non-existent GPIB board"},
{10,"EOIP","Routine not allowed during asynchronous I/O operation"},
{11,"ECAP","No capability for operation"},
{12,"EFSO","File System Error"},
{14,"EBUS","Command byte transfer error"},
{15,"ESTB","Serial poll status byte lost"},
{16,"ESQR","SRQ stuck in ON position"},
{20,"ETAB","Table problem"},
{247,"EINT","No interrupt configured on board"},
{248,"EWMD","Windows is not in Enhanced mode"},
{249,"EVDD","GPIB driver is not installed"},
{250,"EOVR","Buffer Overflow"},
{251,"ESML","Two library calls running simultaneously"},
{252,"ECFG","Board type does not match GPIB.CFG"},
{253,"ETMR","No Windows timers available"},
{254,"ESLC","No Windows selectors available"},
{255,"EBRK","Control-Break pressed"}
};
char* Gpib_DCS::GetSettings()
{
const char* to[] = {
"None","10us","30us","100us","300us","1ms","3ms","10ms","30ms",
"100ms","300ms","1s","3s","10s","30s","100s","300s","1000s"
};
memset(m_buf,0,sizeof(m_buf));
snprintf(m_buf,sizeof(m_buf)-1,"Adr: (%i,%i) to:%s",
m_address1,
m_address2,
to[m_timeout]);
return m_buf;
};
int GpibDevice::CloseDevice()
{
if(m_hd != -1) {
// goto local...
ibloc(m_hd);
// ...and switch device offline
ibonl(m_hd,0);
m_hd = -1;
m_board = -1;
}
return 0;
};
const char* GpibDevice::GetErrorString(int error,bool detailed)
{
for(size_t i=0;i<(sizeof(gpibErrors)/sizeof(gpibErr_t));i++) {
if(gpibErrors[i].m_errno == error) {
if(detailed) {
return gpibErrors[i].m_description;
}
else {
return gpibErrors[i].m_notation;
}
}
}
return 0;
};
// This is only for internal usage
int GpibDevice::Ibrd(char* buf,size_t len)
{
return ibrd(m_hd,buf,len);
};
// This is only for internal usage
int GpibDevice::Ibwrt(char* buf,size_t len)
{
return ibwrt(m_hd,buf,len);
};
int GpibDevice::Ioctl(int cmd,void* args)
{
switch(cmd) {
case CTB_RESET:
if(m_hd >= 0) {
ibclr(m_hd);
return 0;
}
return -1;
case CTB_GPIB_GETRSP: {
char spr = 0;
if(m_hd >= 0) {
ibrsp(m_hd,&spr);
*(int*)args = (int)spr;
return 0;
}
return 1; }
case CTB_GPIB_GETSTA:
*(int*)args = m_state;
return 0;
case CTB_GPIB_GETERR:
*(int*)args = m_error;
return 0;
case CTB_GPIB_GETLINES: {
short state = 0;
if(m_hd >= 0) {
iblines(m_board,&state);
*(int*)args = (int)state;
return 0;
}
return -1; }
case CTB_GPIB_SETTIMEOUT: {
if(m_hd >= 0) {
GpibTimeout timeout;
unsigned long to = *(unsigned long*)args;
// convert the timeout in ms (given by args) into the
// traditional NI-488.2 timeout period
if(to > 1000000) timeout = GpibTimeout1000s;
else if(to >= 300000) timeout = GpibTimeout300s;
else if(to >= 100000) timeout = GpibTimeout100s;
else if(to >= 30000) timeout = GpibTimeout30s;
else if(to >= 10000) timeout = GpibTimeout10s;
else if(to >= 3000) timeout = GpibTimeout3s;
else if(to >= 1000) timeout = GpibTimeout1s;
else if(to >= 300) timeout = GpibTimeout300ms;
else if(to >= 100) timeout = GpibTimeout100ms;
else if(to >= 30) timeout = GpibTimeout30ms;
else if(to >= 10) timeout = GpibTimeout10ms;
else if(to >= 3) timeout = GpibTimeout3ms;
else if(to >= 1) timeout = GpibTimeout1ms;
else timeout = GpibTimeoutNone;
ibtmo(m_hd,timeout);
return 0;
}
return -1; }
case CTB_GPIB_GTL:
// Forces the specified device to go to local program mode
if(m_hd >= 0) {
ibloc(m_hd);
return 0;
}
return -1;
case CTB_GPIB_REN:
// This routine can only be used if the specified GPIB
// Interface Board is the System Controller.
// Remember that even though the REN line is asserted,
// the device(s) will not be put into remote state until is
// addressed to listen by the Active Controller
if(m_hd) {
char adr = (char)m_dcs.m_address1;
ibsre(m_board,1);
ibcmd(m_board,&adr,1);
return 0;
}
return -1;
case CTB_GPIB_RESET_BUS:
ibsic(m_board);
return 0;
case CTB_GPIB_GET_EOS_CHAR:
if( m_hd ) {
*(int*)args = (int)m_dcs.m_eosChar;
return 0;
}
return -1;
case CTB_GPIB_SET_EOS_CHAR:
#ifdef __GNUG__
// FIXME!
// Doesn't work with linux-gpib-3.2.08. All EOS beside 0x00
// are blocking during sending data to the device. (Look at
// function my_ibwrt in linux-gpib-3.2.08/lib/ibWrt.c
if( m_hd ) {
m_dcs.m_eosChar = (char)*(int*)args;
ibeos(m_hd,(m_dcs.m_eosMode << 8) | m_dcs.m_eosChar);
return 0;
}
#endif
return -1;
case CTB_GPIB_GET_EOS_MODE:
if( m_hd ) {
*(int*)args = (int)m_dcs.m_eosMode;
return 0;
}
return -1;
case CTB_GPIB_SET_EOS_MODE:
if( m_hd ) {
m_dcs.m_eosMode = (char)*(int*)args;
ibeos(m_hd,(m_dcs.m_eosMode << 8) | m_dcs.m_eosChar);
return 0;
}
return -1;
}
// error or unknown command
return -1;
};
int GpibDevice::FindListeners(int board)
{
int listeners = 0;
if((unsigned int)board > 1) {
return -1;
}
// reset the GPIB, otherwise no connected device is found (linux)
SendIFC(board);
// list of primary addresses to searching for. Must be terminated
// with NOADDR.
Addr4882_t addrlist[31];
// The range of valid addresses is 1...30, 0 is reservated by the
// controller, 31 is not valid
for(int i = 0;i < 30; i++) addrlist[i] = (Addr4882_t) i + 1;
addrlist[30] = NOADDR;
// place to store the results
Addr4882_t results[31];
memset(results,0,sizeof(results));
FindLstn(board, addrlist, results, 31);
if(ibsta & ERR) {
return -1;
}
for(int i=0;i<=30;i++) {
if(results[i]) {
listeners |= 1 << results[i];
}
}
return listeners;
};
int GpibDevice::Open( const char* devname, int address )
{
m_dcs.m_address1 = address;
return OpenDevice( devname, &m_dcs );
}
int GpibDevice::OpenDevice(const char* devname, void* dcs)
{
// if dcs isn't NULL, type cast
if(dcs) m_dcs = *(Gpib_DCS*)dcs;
if(strncmp(devname,"gpib1",5) == 0) m_board = 0;
else if(strncmp(devname,"gpib2",5) == 0) m_board = 1;
if(m_board < 0) {
return -1;
}
// check for a valid timeout
if((unsigned int)m_dcs.m_timeout > GpibTimeout1000s) {
m_dcs.m_timeout = GpibTimeout10us;
}
m_hd = ibdev(m_board,
m_dcs.m_address1,
m_dcs.m_address2,
m_dcs.m_timeout,
m_dcs.m_eot,
#ifdef __GNUG__
// FIXME!
// linux-gpib-3.2.08 doesn't work with any EOS (blocks).
// Because we always has to add an EOS on the message
// (independent of the m_eosChar setting), we can ignore it!
0
#else
(m_dcs.m_eosMode << 8) | m_dcs.m_eosChar
#endif
);
if(m_hd < 0) {
// no gpib controller installed (not found)
return -2;
}
// test for a connected listener (device with given address)
short int listen = 0;
ibln(m_board,m_dcs.m_address1,NO_SAD,&listen);
if(!listen) {
// no listener at the given address
CloseDevice();
return -3;
}
// reset device
ibclr(m_hd);
// save state, error and count
m_state = ThreadIbsta();
m_count = ThreadIbcnt();
m_error = ThreadIberr();
// no error
return 0;
};
int GpibDevice::Read(char* buf,size_t len)
{
// if something is in the fifo, first read that
if(m_fifo->items() > 0) {
return m_fifo->read(buf,len);
}
m_state = ibrd(m_hd,buf,len);
m_error = ThreadIberr();
m_count = ThreadIbcnt();
return m_count;
};
int GpibDevice::Write(char* buf,size_t len)
{
m_state = ibwrt(m_hd,buf,len);
m_error = ThreadIberr();
m_count = ThreadIbcnt();
return m_count;
};
} // namespace ctb

View File

@ -0,0 +1,211 @@
/////////////////////////////////////////////////////////////////////////////
// Name: iobase.cpp
// Purpose:
// Author: Joachim Buermann
// Id: $Id: iobase.cpp,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
#include "ctb-0.16/iobase.h"
#include "ctb-0.16/timer.h"
namespace ctb {
#define DELTA_BUFSIZE 512
int IOBase::Readv(char* buf,size_t len,unsigned int timeout_in_ms)
{
char *cp = buf;
int n = 0;
int timeout = 0;
size_t toread = len;
Timer t(timeout_in_ms,&timeout,NULL);
if(timeout_in_ms != 0xFFFFFFFF) {
t.start();
}
while(!timeout && (toread > 0)) {
if((n = Read(cp,toread)) < 0) {
break;
}
if(!n) {
sleepms(1);
}
toread -= n;
cp += n;
}
// ok, all bytes received
return(len - toread);
};
/*
Readv() calls the member function Read() repeatedly, til all
demand bytes were received. To avoid an endless loop, you
can refer an integer, which was set unequal zero after a
specific time. (See the timer class)
*/
int IOBase::Readv(char* buf,size_t len,int* timeout_flag,bool nice)
{
size_t toread = len;
int n = 0;
char *cp = buf;
while(toread > 0) {
if(timeout_flag && (*timeout_flag > 0)) {
return (len - toread);
}
if((n = Read(cp,toread)) < 0) {
return (len - toread);
}
if(!n && nice) {
sleepms(1);
}
if (n > 0)
{
toread -= n;
cp += n;
}
}
// ok, all bytes received
return(len - toread);
};
int IOBase::ReadUntilEOS(char*& readbuf,
size_t* readedBytes,
char* eosString,
long timeout_in_ms,
char quota)
{
int n = 0;
int timeout = 0;
int bufsize = DELTA_BUFSIZE;
int result = 0;
int quoted = 0;
char* buf = new char[bufsize];
char* des = buf;
char* eos = eosString;
char ch;
Timer t(timeout_in_ms,&timeout,NULL);
t.start();
while(!timeout) {
if(des >= &buf[bufsize]) {
// buffer full, realloc more memory
char* tmp = new char[bufsize + DELTA_BUFSIZE + 1];
memcpy(tmp,buf,bufsize);
delete[] buf;
buf = tmp;
des = &buf[bufsize];
bufsize += DELTA_BUFSIZE;
}
// read next byte
n = Read(&ch,1);
if(n < 0) {
// an error occured
result = -1;
break;
}
else if(n == 0) {
// no data available, give up the processor for some time
// to reduce the cpu last
sleepms(10);
continue;
}
// if eos is composed of more than one char, and the current
// byte doesn't match the next eos character, we handle the
// readed byte as a normal char (and not an eos)
if((eos != eosString) && (ch != *eos)) {
// FIXME!
// write all characters, which was matched the eos string
// until now (with the first wrong character all received
// eos characters are invalid and must handled as normal
// characters).
// This doesn't work right and is only a little workaround
// because the received eos chars are lost
PutBack(ch);
// because we doesn't match the eos string, we must 'reset'
// the eos match
eos = eosString;
continue;
}
else {
if((ch == *eos) && !quoted) {
if(*++eos == 0) {
// the eos string is complete
result = 1;
break;
}
continue;
}
}
if(ch == quota) {
quoted ^= 1;
}
*des++ = ch;
}
*des = 0;
readbuf = buf;
*readedBytes = des - buf;
return result;
};
int IOBase::Writev(char* buf,size_t len,unsigned int timeout_in_ms)
{
char *cp = buf;
int n = 0;
int timeout = 0;
size_t towrite = len;
Timer t(timeout_in_ms,&timeout,NULL);
if(timeout_in_ms != 0xFFFFFFFF) {
t.start();
}
while(!timeout && (towrite > 0)) {
if((n = Write(cp,towrite)) < 0) {
// an error occurs
break;
}
if(!n) {
sleepms(1);
}
towrite -= n;
cp += n;
}
return (len - towrite);
};
/*
Similar to Readv(). Writev() calls Write() repeatedly till
all bytes are written.
*/
int IOBase::Writev(char* buf,size_t len,int* timeout_flag,bool nice)
{
size_t towrite = len;
int n = 0;
char *cp = buf;
while(towrite > 0) {
if(timeout_flag && (*timeout_flag > 0)) {
return (len - towrite);
}
if((n = Write(cp,towrite)) < 0) {
// an error occurs
return (len - towrite);
}
if(!n && nice) {
sleepms(1);
}
towrite -= n;
cp += n;
}
return(len);
};
} // namespace ctb

View File

@ -0,0 +1,37 @@
#if defined ( WIN32 )
# include <conio.h>
#else
# include <stdio.h>
# include <termios.h>
#endif
namespace ctb {
char GetKey()
{
#if defined ( WIN32 )
if(_kbhit()) {
return _getch();
}
return '\0';
#else
int ch;
static struct termios t, save_t;
tcgetattr(0,&t);
save_t = t;
t.c_lflag &= ~(ICANON);
t.c_cc[VMIN] = 0;
t.c_cc[VTIME] = 0;
tcsetattr(0,TCSANOW,&t);
ch = fgetc(stdin);
tcsetattr(0,TCSANOW,&save_t);
if(ch != EOF) {
return ch;
}
return '\0';
#endif
}
} // namespace ctb

View File

@ -0,0 +1,443 @@
/////////////////////////////////////////////////////////////////////////////
// Name: linux/serport.cpp
// Purpose:
// Author: Joachim Buermann
// Id: $Id: serport.cpp,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/linux/serport.h"
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <unistd.h>
#define CMSPAR 010000000000 /* mark or space (stick) parity */
namespace ctb {
const char* COM1 = "/dev/ttyS0";
const char* COM2 = "/dev/ttyS1";
const char* COM3 = "/dev/ttyS2";
const char* COM4 = "/dev/ttyS3";
const char* COM5 = "/dev/ttyS4";
const char* COM6 = "/dev/ttyS5";
const char* COM7 = "/dev/ttyS6";
const char* COM8 = "/dev/ttyS7";
const char* COM9 = "/dev/ttyS8";
const char* COM10 = "/dev/ttyS9";
const char* COM11= "/dev/ttyS10";
const char* COM12= "/dev/ttyS11";
const char* COM13 = "/dev/ttyS12";
const char* COM14 = "/dev/ttyS13";
const char* COM15 = "/dev/ttyS14";
const char* COM16 = "/dev/ttyS15";
const char* COM17 = "/dev/ttyS16";
const char* COM18 = "/dev/ttyS17";
const char* COM19 = "/dev/ttyS18";
const char* COM20 = "/dev/ttyS19";
SerialPort::SerialPort() :
SerialPort_x()
{
fd = -1;
};
SerialPort::~SerialPort()
{
Close();
};
speed_t SerialPort::AdaptBaudrate( int baud )
{
switch(baud) {
case 150: return B150;
case 300: return B300;
case 600: return B600;
case 1200: return B1200;
case 2400: return B2400;
case 4800: return B4800;
case 9600: return B9600;
case 19200: return B19200;
case 57600: return B57600;
case 115200: return B115200;
case 230400: return B230400;
case 460800: return B460800;
case 921600: return B921600;
// NOTE! The speed of 38400 is required, if you want to set
// an non-standard baudrate. See below!
default: return B38400;
}
};
int SerialPort::CloseDevice()
{
int err = 0;
// only close an open file handle
if(fd < 0) return EBADF;
// With some systems, it is recommended to flush the serial port's
// Output before closing it, in order to avoid a possible hang of
// the process...
// Thanks to Germain (I couldn't answer you, because your email
// address was invalid)
tcflush(fd, TCOFLUSH);
// Don't recover the orgin settings while the device is open. This
// implicate a mismatched data output!
// Just close device
err = close( fd );
fd = -1;
return err;
};
int SerialPort::ChangeLineState( SerialLineState flags )
{
int state;
ioctl(fd,TIOCMGET,&state);
state ^= flags;
return ioctl(fd,TIOCMSET,&state);
};
int SerialPort::ClrLineState( SerialLineState flags )
{
return ioctl(fd,TIOCMBIC,&flags);
};
int SerialPort::GetLineState()
{
SerialLineState flags = LinestateNull;
if( ioctl( fd, TIOCMGET, &flags ) < 0 ) {
return -1;
}
return (int)( flags & 0x1FF );
};
//
// included from /usr/include/linux/serial.h
//
// struct serial_icounter_struct {
// int cts, dsr, rng, dcd;
// int rx, tx;
// int frame, overrun, parity, brk;
// int buf_overrun;
// int reserved[9];
// };
//
int SerialPort::Ioctl(int cmd, void* args)
{
int count = 0;
int err = 0;
struct serial_icounter_struct info;
SerialPort_EINFO einfo;
switch(cmd) {
case CTB_RESET:
return SendBreak(0);
case CTB_SER_GETEINFO:
err = ioctl(fd,TIOCGICOUNT,&info);
if(err) return err;
einfo.brk = info.brk - save_info.brk;
einfo.frame = info.frame - save_info.frame;
einfo.overrun = info.overrun - save_info.overrun;
einfo.parity = info.parity - save_info.parity;
*(SerialPort_EINFO*)args = einfo;
break;
case CTB_SER_GETBRK:
err = ioctl(fd,TIOCGICOUNT,&info);
if(err) return err;
if(last_info.brk != info.brk) count = 1;
break;
case CTB_SER_GETFRM:
err = ioctl(fd,TIOCGICOUNT,&info);
if(err) return err;
if(last_info.frame != info.frame) count = 1;
break;
case CTB_SER_GETOVR:
err = ioctl(fd,TIOCGICOUNT,&info);
if(err) return err;
if(last_info.overrun != info.overrun) count = 1;
break;
case CTB_SER_GETPAR:
err = ioctl(fd,TIOCGICOUNT,&info);
if(err) return err;
if(last_info.parity != info.parity) count = 1;
break;
case CTB_SER_GETINQUE:
err = ioctl(fd,TIOCINQ,&count);
if(err) return err;
*(int*)args = count;
return 0;
case CTB_SER_SETPAR:
return SetParityBit( *(int*)args == 1 );
default:
return -1;
}
last_info = info;
return 0;
};
int SerialPort::IsOpen()
{
return (fd != -1);
};
int SerialPort::OpenDevice(const char* devname, void* dcs)
{
// if dcs isn't NULL, type cast
if(dcs) m_dcs = *(SerialPort_DCS*)dcs;
// open serial comport device for reading and writing,
// don't wait (O_NONBLOCK)
fd = open(devname, O_RDWR | O_NOCTTY | O_NONBLOCK);
if(fd >= 0) {
// exclusive use
int dummy;
ioctl( fd, TIOCEXCL, &dummy );
tcgetattr(fd,&t);
save_t = t;
// save the device name
strncpy(m_devname,(char*)devname,sizeof(m_devname));
// we write an eos to avoid a buffer overflow
m_devname[sizeof(m_devname)-1] = '\0';
// Fill the internal terios struct.
// If the given baudrate is an non-standard one, the AdaptBaudrate
// call returns the linux specific value B38400 which is a
// condition for the later switch to an unusual baudrate!
cfsetspeed(&t, AdaptBaudrate( m_dcs.baud ) );
//cfsetospeed(&t, AdaptBaudrate( m_dcs.baud ) );
// parity settings
switch( m_dcs.parity ) {
case ParityNone:
t.c_cflag &= ~PARENB; break;
case ParityOdd:
t.c_cflag |= PARENB;
t.c_cflag |= PARODD;
break;
case ParityEven:
t.c_cflag |= PARENB;
t.c_cflag &= ~PARODD;
break;
case ParityMark:
t.c_cflag |= PARENB | CMSPAR | PARODD;
break;
case ParitySpace:
t.c_cflag |= PARENB | CMSPAR;
t.c_cflag &= ~PARODD;
break;
}
// stopbits
if(m_dcs.stopbits == 2)
t.c_cflag |= CSTOPB;
else
t.c_cflag &= ~CSTOPB;
// wordlen
t.c_cflag &= ~CSIZE;
if(m_dcs.wordlen == 7) t.c_cflag |= CS7;
else if(m_dcs.wordlen == 6) t.c_cflag |= CS6;
else if(m_dcs.wordlen == 5) t.c_cflag |= CS5;
// this is the default
else t.c_cflag |= CS8;
// rts/cts
if(m_dcs.rtscts == false)
t.c_cflag &= ~CRTSCTS;
else
t.c_cflag |= CRTSCTS;
t.c_lflag &= ~(ICANON | ECHO | ISIG | IEXTEN);
t.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON | IXOFF | IXANY);
t.c_iflag |= IGNPAR;
t.c_oflag &= ~OPOST;
if(m_dcs.xonxoff == true) {
t.c_iflag |= (IXON | IXOFF);
}
// look out!
// MIN = 1 means, in TIME (1/10 secs) defined timeout
// will be started AFTER receiving the first byte
// so we must set MIN = 0. (timeout starts immediately, abort
// also without readed byte)
t.c_cc[VMIN] = 0;
// timeout in 1/10 secs
// no timeout for non blocked transfer
t.c_cc[VTIME] = 0;
// write the settings
tcsetattr(fd,TCSANOW,&t);
// it's careless, but in the moment we don't test
// the return of tcsetattr (normally there is no error)
// request the actual numbers of breaks, framing, overrun
// and parity errors (because Linux summing all of them during
// system lifetime, not only while serial port is open.
ioctl(fd,TIOCGICOUNT,&save_info);
// it's also careless, but we assume, that there was no error
last_info = save_info;
// in case of a non-standard rate, the termios struct have to set
// with the B38400 rate, see above!
if( ! IsStandardRate( m_dcs.baud ) ) {
SetBaudrateAny( m_dcs.baud );
}
}
return fd;
};
int SerialPort::Read(char* buf,size_t len)
{
if(m_fifo->items() > 0) {
return m_fifo->read(buf,len);
}
// Read() (using read() ) will return an 'error' EAGAIN as it is
// set to non-blocking. This is not a true error within the
// functionality of Read, and thus should be handled by the caller.
int n = read(fd,buf,len);
if((n < 0) && (errno == EAGAIN)) return 0;
return n;
};
int SerialPort::SendBreak(int duration)
{
// the parameter is equal with linux
return tcsendbreak(fd,duration);
};
/*
Note: The following hints are copied from the ftdi_sio.c sources of
the kernel modul for the USB to RS232 converter using an FTDI
chipset (FT232BM or similar). Thanks to all those people
contribute code and above all helpful comments to this modul.
*/
/*
* The logic involved in setting the baudrate can be cleanly split in 3 steps.
* Obtaining the actual baud rate is a little tricky since unix traditionally
* somehow ignored the possibility to set non-standard baud rates.
* 1. Standard baud rates are set in tty->termios->c_cflag
* 2. If these are not enough, you can set any speed using alt_speed as
* follows:
* - set tty->termios->c_cflag speed to B38400
* - set your real speed in tty->alt_speed; it gets ignored when
* alt_speed==0, (or)
* - call TIOCSSERIAL ioctl with (struct serial_struct) set as follows:
* flags & ASYNC_SPD_MASK == ASYNC_SPD_[HI, VHI, SHI, WARP], this just
* sets alt_speed to (HI: 57600, VHI: 115200, SHI: 230400, WARP: 460800)
* ** Steps 1, 2 are done courtesy of tty_get_baud_rate
* 3. You can also set baud rate by setting custom divisor as follows
* - set tty->termios->c_cflag speed to B38400
* - call TIOCSSERIAL ioctl with (struct serial_struct) set as follows:
* o flags & ASYNC_SPD_MASK == ASYNC_SPD_CUST
* o custom_divisor set to baud_base / your_new_baudrate
* ** Step 3 is done courtesy of code borrowed from serial.c - I should really
* spend some time and separate+move this common code to serial.c, it is
* replicated in nearly every serial driver you see.
*/
int SerialPort::SetBaudrateAny( int baudrate )
{
struct serial_struct ser_info;
int result = ioctl( fd, TIOCGSERIAL, &ser_info );
ser_info.flags = ASYNC_SPD_CUST | ASYNC_LOW_LATENCY;
ser_info.custom_divisor = ser_info.baud_base / baudrate;
result = ioctl( fd, TIOCSSERIAL, &ser_info );
return result;
}
int SerialPort::SetBaudrateStandard( int baudrate )
{
speed_t baud = AdaptBaudrate( baudrate );
// setting the input baudrate
if(cfsetspeed(&t,baud) < 0) {
return -1;
}
// take over
m_dcs.baud = baudrate;
tcsetattr(fd,TCSANOW,&t);
return tcgetattr( fd, &t );
};
int SerialPort::SetBaudrate( int baudrate )
{
return IsStandardRate( baudrate ) ?
SetBaudrateStandard( baudrate ) :
SetBaudrateAny( baudrate );
}
int SerialPort::SetLineState( SerialLineState flags )
{
return ioctl(fd,TIOCMBIS,&flags);
};
int SerialPort::SetParityBit( bool parity )
{
// waits until all output has been transmitted
tcdrain( fd );
// now read the current termios settings and manipulate
// the parity
tcgetattr( fd, &t );
if( parity ) {
t.c_cflag |= PARENB | CMSPAR | PARODD;
}
else {
t.c_cflag |= PARENB | CMSPAR;
t.c_cflag &= ~PARODD;
}
tcsetattr( fd,TCSANOW, &t );
tcgetattr( fd, &t );
return 0;
}
int SerialPort::Write(char* buf,size_t len)
{
// Write() (using write() ) will return an 'error' EAGAIN as it is
// set to non-blocking. This is not a true error within the
// functionality of Write, and thus should be handled by the caller.
int n = write(fd,buf,len);
if((n < 0) && (errno == EAGAIN)) return 0;
return n;
};
} // namespace ctb

View File

@ -0,0 +1,97 @@
/////////////////////////////////////////////////////////////////////////////
// Name: linux/timer.cpp
// Purpose:
// Author: Joachim Buermann
// Id: $Id: timer.cpp,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "ctb-0.16/timer.h"
#include <unistd.h>
namespace ctb {
// a dummy function, see below
static void timer_exit(void* arg)
{
};
static void* timer_fnc(void* arg)
{
// the timer thread should be canceled every time
// (asyncronously)
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
// this is tricky, but absolutly necessarily to avoid segfaults
// if the destructor finished a running thread
pthread_cleanup_push(timer_exit,NULL);
timer_control *tc = (timer_control*)arg;
// linux allows a real sleep, means the timer thread will
// be sleeping (no reduce of the system performance)
usleep(tc->usecs);
// time is over, system reawake the thread.
// if there is an exit function, calling it
if(tc->exitfnc) tc->exitfnc(NULL);
// set the exit flag
if(tc->exitflag) *tc->exitflag = 1;
// deallocate the system resources (thread)
pthread_cleanup_pop(1);
return NULL;
};
// the constructor initiate the internal control struct
Timer::Timer( unsigned int msecs, int* exitflag, void*( *exitfnc )(void*) )
{
control.usecs = msecs * 1000;
control.exitflag = exitflag;
control.exitfnc = exitfnc;
stopped = 1;
};
// if a timer instance leave it's valid range, it automaticaly will
// be finished
Timer::~Timer()
{
if(!stopped) {
// only a running thread may be canceled
stop();
}
};
// starts the timer thread
int Timer::start()
{
stopped = 0;
if(pthread_create(&tid, // result parameter, covers the id
// of the new threads
NULL, // thread attribute object, NULL means
// the defaults
timer_fnc, // start function of the thread
&control // start function parameter, must refer
// as void*
) == -1) {
return -1; // there was something going wrong
}
pthread_detach(tid); // thread status must be "detach". In the other
// case, the destructor call of a running
// thread throws a segfault
return 0;
};
// stop the timer thread
int Timer::stop()
{
if(control.exitflag && (*control.exitflag == 0)) {
pthread_cancel(tid);
}
stopped = 1;
return 0;
};
void sleepms(unsigned int ms)
{
usleep(ms * 1000);
};
} // namespace ctb

View File

@ -0,0 +1,109 @@
#include "ctb-0.16/ctb.h"
#include "ctb-0.16/portscan.h"
#include <sstream>
#ifndef _WIN32
# include <glob.h>
#endif
namespace ctb {
bool GetAvailablePorts( std::vector<std::string>& result,
bool checkInUse )
{
#ifdef _WIN32
std::stringstream devname;
for( int i = 1; i < 100; i++ ) {
devname.clear(); devname.str( "" );
// some systems like WinCE doesn't like the extended port numbering...
i < 10 ? devname << "com" << i : devname << "\\\\.\\com" << i;
COMMCONFIG cc;
DWORD dwSize = sizeof( cc );
if ( ::GetDefaultCommConfig( devname.str().c_str(), &cc, &dwSize ) ) {
if( cc.dwProviderSubType == PST_RS232 ) {
ctb::SerialPort com;
if( com.Open( devname.str().c_str() ) < 0 ) {
continue;
}
result.push_back( devname.str().c_str() );
}
}
}
#else
glob_t globbuf;
// search for standard serial ports
int res = glob( "/dev/ttyS*", GLOB_ERR, NULL, &globbuf );
if( res == 0 ) {
// no error, glob was successful
for( int i = 0; i < globbuf.gl_pathc; i++ ) {
if( checkInUse ) {
ctb::SerialPort com;
if( com.Open( globbuf.gl_pathv[ i ] ) < 0 ) {
continue;
}
result.push_back( std::string( globbuf.gl_pathv[ i ] ) );
}
}
}
globfree( &globbuf );
// search for USB to RS232 converters
res = glob( "/dev/ttyUSB*", GLOB_ERR, NULL, &globbuf );
if( res == 0 ) {
// no error, glob was successful
for( int i = 0; i < globbuf.gl_pathc; i++ ) {
if( checkInUse ) {
ctb::SerialPort com;
if( com.Open( globbuf.gl_pathv[ i ] ) < 0 ) {
continue;
}
result.push_back( std::string( globbuf.gl_pathv[ i ] ) );
}
}
}
globfree( &globbuf );
#endif
return result.size();
}
} // namespace ctb

View File

@ -0,0 +1,104 @@
#include "ctb-0.16/serportx.h"
#include <sstream>
namespace ctb {
int SerialPort_x::Open( const char* portname, int baudrate,
const char* protocol,
FlowControl flowControl )
{
SerialPort_DCS dcs;
dcs.baud = baudrate;
// default wordlen is 8
if( ( protocol[ 0 ] >= '5' ) && ( protocol[ 0 ] <= '8' )) {
dcs.wordlen = protocol[ 0 ] - '0';
}
else {
return -1;
}
// protocol is given as a string like "8N1", the first
// character specifies the data bits (5...8), the second
// the parity (None,Odd,Even,Mark,Space).
// The third character defines the stopbit (1...2).
switch( protocol[ 1 ] ) {
case 'N': case 'n': dcs.parity = ParityNone; break;
case 'O': case 'o': dcs.parity = ParityOdd; break;
case 'E': case 'e': dcs.parity = ParityEven; break;
case 'M': case 'm': dcs.parity = ParityMark; break;
case 'S': case 's': dcs.parity = ParitySpace; break;
// all other parameters cause an error!
default: return -1;
}
// default stopbits is 1
if( ( protocol[ 2 ] >= '1' ) && ( protocol[ 2 ] <= '2' )) {
dcs.stopbits = protocol[ 2 ] - '0';
}
else {
return -1;
}
// default flow control is disabled
dcs.rtscts = ( flowControl == RtsCtsFlowControl );
dcs.xonxoff = ( flowControl == XonXoffFlowControl );
// save the settings in the internal dcs for later use
m_dcs = dcs;
return OpenDevice( portname, &m_dcs );
}
int SerialPort_x::Open( const int portnumber, int baudrate,
const char* protocol,
FlowControl flowControl )
{
// portnumbers start with 1
if( portnumber < 1 ) {
return -1;
}
std::stringstream devname;
#if defined ( WIN32 )
// some systems like WinCE doesn't like the extended port numbering...
portnumber < 10 ? devname << "com" << portnumber :
devname << "\\\\.\\com" << portnumber;
#else
devname << "/dev/ttyS" << ( portnumber - 1 );
#endif
return Open( devname.str().c_str(), baudrate, protocol, flowControl );
}
bool SerialPort_x::IsStandardRate( int rate )
{
const int rates[] = {
150, 300, 600, 1200, 2400, 4800, 9600, 19200, 38400, 57600,
115200, 230400, 460800, 921600
};
for( unsigned int i = 0; i < ( sizeof( rates ) / sizeof( int ) ); i++ ) {
if( rate == rates[ i ] ) {
return true;
}
}
return false;
}
} // namespace ctb

View File

@ -0,0 +1,66 @@
/////////////////////////////////////////////////////////////////////////////
// Name: win32/getopt.cpp
// Purpose:
// Author: unknown, I found it in the internet
// Id: $Id: getopt.cpp,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 ?
// Licence: (I think Open Source)
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <string.h>
char *optarg; /* Global argument pointer. */
int optind = 0; /* Global argv index. */
static char *scan = NULL; /* Private scan pointer. */
/* found char, or NULL if none */
static char *index(const char* s,char charwanted)
{
return(strchr((char*)s, charwanted));
}
int getopt(int argc, char* argv[], char* optstring)
{
register char c;
register char *place;
optarg = NULL;
if (scan == NULL || *scan == '\0') {
if (optind == 0)
optind++;
if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
return(EOF);
if (strcmp(argv[optind], "--")==0) {
optind++;
return(EOF);
}
scan = argv[optind]+1;
optind++;
}
c = *scan++;
place = index(optstring, c);
if (place == NULL || c == ':') {
fprintf(stderr, "%s: unknown option -%c\n", argv[0], c);
return('?');
}
place++;
if (*place == ':') {
if (*scan != '\0') {
optarg = scan;
scan = NULL;
} else {
optarg = argv[optind];
optind++;
}
}
return(c);
}

View File

@ -0,0 +1,452 @@
/////////////////////////////////////////////////////////////////////////////
// Name: serport.cpp
// Purpose:
// Author: Joachim Buermann
// Id: $Id: serport.cpp,v 1.1.1.1 2004/11/24 10:30:11 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include <string.h>
#include "ctb-0.16/serport.h"
#define SERIALPORT_BUFSIZE 4096
namespace ctb {
const char* COM1 = "com1";
const char* COM2 = "com2";
const char* COM3 = "com3";
const char* COM4 = "com4";
const char* COM5 = "com5";
const char* COM6 = "com6";
const char* COM7 = "com7";
const char* COM8 = "com8";
const char* COM9 = "com9";
const char* COM10 = "\\\\.\\com10";
const char* COM11 = "\\\\.\\com11";
const char* COM12 = "\\\\.\\com12";
const char* COM13 = "\\\\.\\com13";
const char* COM14 = "\\\\.\\com14";
const char* COM15 = "\\\\.\\com15";
const char* COM16 = "\\\\.\\com16";
const char* COM17 = "\\\\.\\com17";
const char* COM18 = "\\\\.\\com18";
const char* COM19 = "\\\\.\\com19";
const char* COM20 = "\\\\.\\com20";
SerialPort::SerialPort()
{
memset( &m_ov, 0, sizeof( OVERLAPPED ) );
fd = INVALID_HANDLE_VALUE;
m_rtsdtr_state = LinestateNull;
};
SerialPort::~SerialPort()
{
Close();
};
int SerialPort::CloseDevice()
{
if(fd != INVALID_HANDLE_VALUE) {
CloseHandle(m_ov.hEvent);
CloseHandle(fd);
fd = INVALID_HANDLE_VALUE;
}
return 0;
};
int SerialPort::ChangeLineState( SerialLineState flags )
{
bool ok = false;
if(flags & LinestateDtr) {
if(m_rtsdtr_state & LinestateDtr) {
ok = EscapeCommFunction(fd,CLRDTR);
}
else {
ok = EscapeCommFunction(fd,SETDTR);
}
m_rtsdtr_state ^= LinestateDtr;
}
if(flags & LinestateRts) {
if(m_rtsdtr_state & LinestateRts) {
ok = EscapeCommFunction(fd,CLRRTS);
}
else {
ok = EscapeCommFunction(fd,SETRTS);
}
m_rtsdtr_state ^= LinestateRts;
}
if(!ok) return -1;
return 0;
};
int SerialPort::ClrLineState( SerialLineState flags )
{
BOOL ok = false;
if(flags & LinestateDtr) {
ok = EscapeCommFunction(fd,CLRDTR);
m_rtsdtr_state &= ~LinestateDtr;
}
if(flags & LinestateRts) {
ok = EscapeCommFunction(fd,CLRRTS);
m_rtsdtr_state &= ~LinestateRts;
}
if(!ok) return -1;
return 0;
};
int SerialPort::GetLineState()
{
BOOL ok = false;
DWORD stat;
int flags = 0;
if(GetCommModemStatus(fd,&stat)) {
if(stat & MS_CTS_ON)
flags |= LinestateCts;
if(stat & MS_DSR_ON)
flags |= LinestateDsr;
if(stat & MS_RING_ON)
flags |= LinestateRing;
if(stat & MS_RLSD_ON)
flags |= LinestateDcd;
ok = true;
}
if(!ok) return -1;
return flags;
};
int SerialPort::Ioctl(int cmd,void* args)
{
COMSTAT comstat;
DWORD errors;
int result = 0;
bool brk;
switch(cmd) {
case CTB_RESET:
return SendBreak(0);
case CTB_SER_GETEINFO:
if(ClearCommError(fd,&errors,&comstat)) {
// actualize the last events
if(errors & CE_BREAK) einfo.brk++;
if(errors & CE_FRAME) einfo.frame++;
if(errors & CE_OVERRUN) einfo.overrun++;
if(errors & CE_RXPARITY) einfo.parity++;
*(SerialPort_EINFO*)args = einfo;
return 0;
}
case CTB_SER_GETBRK:
if(ClearCommError(fd,&errors,&comstat)) {
if(errors & CE_BREAK) result = 1;
einfo.brk += result;
*(int*)args = result;
return 0;
}
break;
case CTB_SER_GETFRM:
if(ClearCommError(fd,&errors,&comstat)) {
if(errors & CE_FRAME) result = 1;
einfo.frame += result;
*(int*)args = result;
return 0;
}
case CTB_SER_GETOVR:
if(ClearCommError(fd,&errors,&comstat)) {
if(errors & CE_OVERRUN) result = 1;
einfo.overrun += result;
*(int*)args = result;
return 0;
}
break;
case CTB_SER_GETPAR:
if(ClearCommError(fd,&errors,&comstat)) {
if(errors & CE_RXPARITY) result = 1;
einfo.parity += result;
*(int*)args = result;
return 0;
}
break;
case CTB_SER_GETINQUE:
if(ClearCommError(fd,&errors,&comstat)) {
*(int*)args = (int)comstat.cbInQue;
return 0;
}
break;
case CTB_SER_SETPAR:
return SetParityBit( *(int*)args == 1 );
}
// error or unknown command
return -1;
};
int SerialPort::IsOpen()
{
return (fd != INVALID_HANDLE_VALUE);
};
int SerialPort::OpenDevice(const char* devname, void* dcs)
{
// if dcs isn't NULL, type cast
if(dcs) m_dcs = *(SerialPort_DCS*)dcs;
fd = CreateFile(devname, // device name
GENERIC_READ | GENERIC_WRITE, // O_RDWR
0, // not shared
NULL, // default value for object security ?!?
OPEN_EXISTING, // file (device) exists
FILE_FLAG_OVERLAPPED, // asynchron handling
NULL); // no more handle flags
if(fd == INVALID_HANDLE_VALUE) {
return -1;
}
// save the device name
strncpy(m_devname,(char*)devname,sizeof(m_devname));
// we write an eos to avoid a buffer overflow
m_devname[sizeof(m_devname)-1] = '\0';
// device control block
DCB dcb;
memset(&dcb,0,sizeof(dcb));
dcb.DCBlength = sizeof(dcb);
dcb.BaudRate = m_dcs.baud;
dcb.fBinary = 1;
m_rtsdtr_state = LinestateNull;
// Specifies whether the CTS (clear-to-send) signal is monitored
// for output flow control. If this member is TRUE and CTS is turned
// off, output is suspended until CTS is sent again.
dcb.fOutxCtsFlow = m_dcs.rtscts;
// Specifies the DTR (data-terminal-ready) flow control.
// This member can be one of the following values:
// DTR_CONTROL_DISABLE Disables the DTR line when the device is
// opened and leaves it disabled.
// DTR_CONTROL_ENABLE Enables the DTR line when the device is
// opened and leaves it on.
// DTR_CONTROL_HANDSHAKE Enables DTR handshaking. If handshaking is
// enabled, it is an error for the application
// to adjust the line by using the
// EscapeCommFunction function.
dcb.fDtrControl = DTR_CONTROL_DISABLE;
m_rtsdtr_state |= LinestateDtr;
// Specifies the RTS flow control. If this value is zero, the
// default is RTS_CONTROL_HANDSHAKE. This member can be one of
// the following values:
// RTS_CONTROL_DISABLE Disables the RTS line when device is
// opened and leaves it disabled.
// RTS_CONTROL_ENABLED Enables the RTS line when device is
// opened and leaves it on.
// RTS_CONTROL_HANDSHAKE Enables RTS handshaking. The driver
// raises the RTS line when the
// "type-ahead" (input)buffer is less than
// one-half full and lowers the RTS line
// when the buffer is more than three-quarters
// full. If handshaking is enabled, it is an
// error for the application to adjust the
// line by using the EscapeCommFunction function.
// RTS_CONTROL_TOGGLE Specifies that the RTS line will be high if
// bytes are available for transmission. After
// all buffered bytes have been send, the RTS
// line will be low.
if(m_dcs.rtscts) dcb.fRtsControl = RTS_CONTROL_HANDSHAKE;
else {
dcb.fRtsControl = RTS_CONTROL_DISABLE;
m_rtsdtr_state |= LinestateRts;
}
// Specifies the XON/XOFF flow control.
// If fOutX is true (the default is false), transmission stops when the
// XOFF character is received and starts again, when the XON character
// is received.
dcb.fOutX = m_dcs.xonxoff;
// If fInX is true (default is false), the XOFF character is sent when
// the input buffer comes within XoffLim bytes of being full, and the
// XON character is sent, when the input buffer comes within XonLim
// bytes of being empty.
dcb.fInX = m_dcs.xonxoff;
// default character for XOFF is 0x13 (hex 13)
dcb.XoffChar = 0x13;
// default character for XON is 0x11 (hex 11)
dcb.XonChar = 0x11;
// set the minimum number of bytes allowed in the input buffer before
// the XON character is sent (3/4 of full size)
dcb.XonLim = (SERIALPORT_BUFSIZE >> 2) * 3;
// set the maximum number of free bytes in the input buffer, before the
// XOFF character is sent (3/4 of full size)
dcb.XoffLim = (SERIALPORT_BUFSIZE >> 2) * 3;
// parity
switch( m_dcs.parity ) {
case ParityOdd: dcb.Parity = ODDPARITY; break;
case ParityEven: dcb.Parity = EVENPARITY; break;
case ParityMark: dcb.Parity = MARKPARITY; break;
case ParitySpace: dcb.Parity = SPACEPARITY; break;
default: dcb.Parity = NOPARITY;
}
// stopbits
if(m_dcs.stopbits == 2) dcb.StopBits = TWOSTOPBITS;
else dcb.StopBits = ONESTOPBIT;
// wordlen, valid values are 5,6,7,8
dcb.ByteSize = m_dcs.wordlen;
if(!SetCommState(fd,&dcb))
return -2;
// create event for overlapped I/O
// we need a event object, which inform us about the
// end of an operation (here reading device)
m_ov.hEvent = CreateEvent(NULL,// LPSECURITY_ATTRIBUTES lpsa
TRUE, // BOOL fManualReset
TRUE, // BOOL fInitialState
NULL); // LPTSTR lpszEventName
if(m_ov.hEvent == INVALID_HANDLE_VALUE) {
return -3;
}
/* THIS IS OBSOLETE!!!
// event should be triggered, if there are some received data
if(!SetCommMask(fd,EV_RXCHAR))
return -4;
*/
COMMTIMEOUTS cto = {MAXDWORD,0,0,0,0};
if(!SetCommTimeouts(fd,&cto))
return -5;
// for a better performance with win95/98 I increased the internal
// buffer to SERIALPORT_BUFSIZE (normal size is 1024, but this can
// be a little bit to small, if you use a higher baudrate like 115200)
if(!SetupComm(fd,SERIALPORT_BUFSIZE,SERIALPORT_BUFSIZE))
return -6;
// clear the internal error struct
memset(&einfo,0,sizeof(einfo));
return 0;
};
int SerialPort::Read(char* buf,size_t len)
{
DWORD read;
int m = m_fifo->items();
while(len) {
if(m_fifo->get(buf) == 1) {
len--;
buf++;
}
else {
break;
}
}
if(!ReadFile(fd,buf,len,&read,&m_ov)) {
// if we use a asynchrone reading, ReadFile gives always
// FALSE
// ERROR_IO_PENDING means ok, other values show an error
if(GetLastError() != ERROR_IO_PENDING) {
// oops..., error in communication
return -1;
}
}
else {
// ok, we have read all wanted bytes
return (int)read + m;
}
return 0;
};
int SerialPort::SendBreak(int duration)
{
if(duration <= 0) duration = 1;
if(!SetCommBreak(fd)) return -1;
// win32 Sleep parameter is ms
Sleep(duration * 250);
if(!ClearCommBreak(fd)) return -1;
// no error
return 0;
};
/*
FIXME! : We need some additional code to check the success of the
baudrate modulation (non-standard rates depend on the used
UART chipset).
*/
int SerialPort::SetBaudrate( int baudrate )
{
DCB dcb;
// get the current dcb...
if(!GetCommState(fd,&dcb)) {
return -1;
}
dcb.BaudRate = baudrate;
// and write it back
if(!SetCommState(fd,&dcb)) {
return -1;
}
m_dcs.baud = baudrate;
return 0;
}
int SerialPort::SetLineState( SerialLineState flags )
{
BOOL ok = false;
if(flags & LinestateDtr) {
ok = EscapeCommFunction(fd,SETDTR);
// save the new state
m_rtsdtr_state |= LinestateDtr;
}
if(flags & LinestateRts) {
ok = EscapeCommFunction(fd,SETRTS);
// save the new state
m_rtsdtr_state |= LinestateRts;
}
if(!ok) return -1;
return 0;
};
int SerialPort::SetParityBit( bool parity )
{
DCB dcb;
if( ! GetCommState( fd, &dcb ) ) {
return -1;
}
parity ? dcb.Parity = MARKPARITY : dcb.Parity = SPACEPARITY;
if( ! SetCommState( fd, &dcb ) ) {
return -2;
}
return 0;
}
int SerialPort::Write(char* buf,size_t len)
{
DWORD write;
if(!WriteFile(fd,buf,len,&write,&m_ov)) {
if(GetLastError() != ERROR_IO_PENDING) {
return -1;
}
else {
// VERY IMPORTANT to flush the data out of the internal
// buffer
FlushFileBuffers(fd);
// first you must call GetOverlappedResult, then you
// get the REALLY transmitted count of bytes
if(!GetOverlappedResult(fd,&m_ov,&write,TRUE)) {
// ooops... something is going wrong
return (int)write;
}
}
}
return write;
};
} // namespace ctb

View File

@ -0,0 +1,85 @@
/////////////////////////////////////////////////////////////////////////////
// Name: win32/timer.cpp
// Purpose:
// Author: Joachim Buermann
// Id: $Id: timer.cpp,v 1.2 2004/11/30 12:39:17 jb Exp $
// Copyright: (c) 2001 Joachim Buermann
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#ifdef WIN32
#include <windows.h>
# ifndef DWORD_PTR
# define DWORD_PTR DWORD*
# endif
#endif
#include "ctb-0.16/timer.h"
namespace ctb {
static void WINAPI timer_fnc(UINT uTimerID,
UINT uMsg,
DWORD_PTR dwUser,
DWORD_PTR dw1,
DWORD_PTR dw2)
{
timer_control *tc = (timer_control*)dwUser;
if(tc->exitfnc) tc->exitfnc(NULL);
if(tc->exitflag) *tc->exitflag = 1;
tc->stop = 0;
};
Timer::Timer(unsigned int msecs,int* exitflag,void*(*exitfnc)(void*))
{
control.msecs = msecs;
if(!control.msecs) control.msecs = 1;
control.exitflag = exitflag;
control.exitfnc = exitfnc;
control.stop = 0;
};
Timer::~Timer()
{
stop(); // stop the thread
};
int Timer::start()
{
stop();
control.stop = timeSetEvent(control.msecs,
(control.msecs > 10) ? 5 : 1,
(LPTIMECALLBACK) timer_fnc,
(DWORD) &control,
TIME_ONESHOT | TIME_CALLBACK_FUNCTION);
return 0;
};
int Timer::stop()
{
if (control.stop)
timeKillEvent(control.stop);
control.stop = 0;
return 0;
};
void kill_all_timer()
{
};
void sleepms(unsigned int ms)
{
// set the granularity of Sleep() for the application, that
// calls it so Sleep(1) will truly sleep for just a millisecond,
// rather than the default 10!
// See: http://www.geisswerks.com/ryan/FAQS/timing.html
timeBeginPeriod(1);
SleepEx(ms,false);
timeEndPeriod(1);
};
} // namespace ctb