diff --git a/CMakeLists.txt b/CMakeLists.txt index 92cb4146f..0e5b40c30 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -203,6 +203,7 @@ option(WITH_PLAYERONE "Install Player One Astronomy's Camera Driver" On) option(WITH_WEEWX_JSON "Install Weewx JSON Driver" On) option(WITH_ROLLOFFINO "Install RollOff ino Dome Driver" On) option(WITH_ASTROASIS "Install Astroasis Driver" On) +option(WITH_TICFOCUSER "Install Pololu TicFocuser Driver" On) # FFMPEG required for INDI Webcam driver find_package(FFmpeg) @@ -768,6 +769,11 @@ SET(LIBRARIES_FOUND FALSE) endif(ASTROASIS_FOUND) endif(WITH_ASTROASIS) +# Pololu Tic Focuser +if (WITH_TICFOCUSER) +add_subdirectory(indi-ticfocuser) +endif(WITH_TICFOCUSER) + # Check if libraries are found. If not, we must build them, install them, THEN run CMake again to build and instal the drivers. If all the libraraies are installed, then we build and install the drivers only now. if (LIBRARIES_FOUND) message(STATUS "############################################################################") diff --git a/cmake_modules/FindGPIOD.cmake b/cmake_modules/FindGPIOD.cmake new file mode 100644 index 000000000..31c57abd0 --- /dev/null +++ b/cmake_modules/FindGPIOD.cmake @@ -0,0 +1,55 @@ +# - Try to find GPIOD +# Once done this will define +# +# GPIOD_FOUND - system has libgpiod +# GPIOD_INCLUDE_DIR - the libgpiod include directory +# GPIOD_LIBRARIES - Link these to use libgpiod +# +# N.B. This is for C++ only, you need to include +# +#include +# +# Redistribution and use is allowed according to the terms of the BSD license. +# For details see the accompanying COPYING-CMAKE-SCRIPTS file. + +if (GPIOD_INCLUDE_DIR AND GPIOD_LIBRARIES) + + # in cache already + set(GPIOD_FOUND TRUE) + message(STATUS "Found libgpiod: ${GPIOD_LIBRARIES}") + +else (GPIOD_INCLUDE_DIR AND GPIOD_LIBRARIES) + + find_path(GPIOD_INCLUDE_DIR gpiod.hpp + ${_obIncDir} + ${GNUWIN32_DIR}/include + /usr/local/include + ) + + find_library(GPIOD_LIBRARIES NAMES gpiodcxx + PATHS + ${_obLinkDir} + ${GNUWIN32_DIR}/lib + /usr/local/lib + ) + + if(GPIOD_INCLUDE_DIR AND GPIOD_LIBRARIES) + set(GPIOD_FOUND TRUE) + else (GPIOD_INCLUDE_DIR AND GPIOD_LIBRARIES) + set(GPIOD_FOUND FALSE) + endif(GPIOD_INCLUDE_DIR AND GPIOD_LIBRARIES) + + + if (GPIOD_FOUND) + if (NOT GPIOD_FIND_QUIETLY) + message(STATUS "Found GPIOD: ${GPIOD_LIBRARIES}") + endif (NOT GPIOD_FIND_QUIETLY) + else (GPIOD_FOUND) + if (GPIOD_FIND_REQUIRED) + message(FATAL_ERROR "libgpiod not found. Please install libgpiod-dev") + endif (GPIOD_FIND_REQUIRED) + endif (GPIOD_FOUND) + + mark_as_advanced(GPIOD_INCLUDE_DIR GPIOD_LIBRARIES) + +endif (GPIOD_INCLUDE_DIR AND GPIOD_LIBRARIES) diff --git a/cmake_modules/FindLIBBLUETOOTH.cmake b/cmake_modules/FindLIBBLUETOOTH.cmake new file mode 100644 index 000000000..691aeaa25 --- /dev/null +++ b/cmake_modules/FindLIBBLUETOOTH.cmake @@ -0,0 +1,70 @@ +# - Find libbluetooth +# Find the Bluez Linux Bluetooth library +# +# LIBBLUETOOTH_INCLUDE_DIR - where to find bluetooth.h etc. +# LIBBLUETOOTH_LIBRARIES - List of libraries when using libbluetooth. +# LIBBLUETOOTH_FOUND - True if libbluetooth was found. + + +# [License] +# The Ariba-Underlay Copyright +# +# Copyright (c) 2008-2012, Institute of Telematics, UniversitÀt Karlsruhe (TH) +# +# Institute of Telematics +# UniversitÀt Karlsruhe (TH) +# Zirkel 2, 76128 Karlsruhe +# Germany +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE INSTITUTE OF TELEMATICS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OF TELEMATICS OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# The views and conclusions contained in the software and documentation +# are those of the authors and should not be interpreted as representing +# official policies, either expressed or implied, of the Institute of +# Telematics. +# [License] + + +# Look for the header files. +find_path(LIBBLUETOOTH_INCLUDE_DIR NAMES bluetooth/bluetooth.h) +mark_as_advanced(LIBBLUETOOTH_INCLUDE_DIR) + + +# Look for the library. +find_library(LIBBLUETOOTH_LIBRARY NAMES bluetooth + DOC "The path to the Bluez Linux Bluetooth library" + ) +mark_as_advanced(LIBBLUETOOTH_LIBRARY) + + +# handle the QUIETLY and REQUIRED arguments and set LIBBLUETOOTH_FOUND to TRUE +# if all listed variables are TRUE +find_package(PackageHandleStandardArgs) +find_package_handle_standard_args(LibBluetooth DEFAULT_MSG + LIBBLUETOOTH_LIBRARY + LIBBLUETOOTH_INCLUDE_DIR + ) + +if(LIBBLUETOOTH_FOUND) + set(LIBBLUETOOTH_LIBRARIES "${LIBBLUETOOTH_LIBRARY}") +endif() \ No newline at end of file diff --git a/cmake_modules/FindLIBTIC1.cmake b/cmake_modules/FindLIBTIC1.cmake new file mode 100644 index 000000000..0e080199f --- /dev/null +++ b/cmake_modules/FindLIBTIC1.cmake @@ -0,0 +1,49 @@ +# - Find LIBTIC1 +# Find the Pololu Tic Library + +pkg_check_modules(LIBTIC1 QUIET libpololu-tic-1) + +find_path(LIBTIC1_INCLUDE_DIR + NAMES + tic.h + HINTS + ${LIBTIC1_INCLUDE_DIRS} + PATH_SUFFIXES + libpololu-tic-1 +) + +find_library(LIBTIC1_LIBRARY + NAMES + ${LIBTIC1_LIBRARIES} + libpololu-tic-1 + HINTS + ${LIBTIC1_LIBRARY_DIRS} +) + +set(LIBTIC1_INCLUDE_DIRS ${LIBTIC1_INCLUDE_DIR}) +set(LIBTIC1_LIBRARIES ${LIBTIC1_LIBRARY}) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args(LIBTIC1 + FOUND_VAR + LIBTIC1_FOUND + REQUIRED_VARS + LIBTIC1_LIBRARY + LIBTIC1_INCLUDE_DIR + VERSION_VAR + PC_LIBLIBTIC1_VERSION +) + +set(LIBTIC1_INCLUDE_DIRS ${LIBTIC1_INCLUDE_DIR}) +set(LIBTIC1_LIBRARIES ${LIBTIC1_LIBRARY}) + +mark_as_advanced(LIBTIC1_INCLUDE_DIRS LIBTIC1_LIBRARIES) + +IF(LIBTIC1_FOUND) + include(CheckCXXSourceCompiles) + include(CMakePushCheckState) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_INCLUDES ${LIBTIC1_INCLUDE_DIRS}) + set(CMAKE_REQUIRED_LIBRARIES ${LIBTIC1_LIBRARIES}) + cmake_pop_check_state() +ENDIF(LIBTIC1_FOUND) diff --git a/indi-ticfocuser/AUTHORS b/indi-ticfocuser/AUTHORS new file mode 100644 index 000000000..cef0ee714 --- /dev/null +++ b/indi-ticfocuser/AUTHORS @@ -0,0 +1,3 @@ +Radek Kaczorek (rkaczorek AT gmail DOT com) +Helge Kutzop +Sebastian Baberowski (sebastian AT baberowski DOT com) diff --git a/indi-ticfocuser/CMakeLists.txt b/indi-ticfocuser/CMakeLists.txt new file mode 100644 index 000000000..9b7753be2 --- /dev/null +++ b/indi-ticfocuser/CMakeLists.txt @@ -0,0 +1,98 @@ +cmake_minimum_required(VERSION 3.16) + +if(COMMAND cmake_policy) + cmake_policy(SET CMP0003 NEW) +endif(COMMAND cmake_policy) + +PROJECT(TicFocuserNG CXX) + +set (TICFOCUSER_VERSION_MAJOR 1) +set (TICFOCUSER_VERSION_MINOR 0) + +LIST(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules/") +LIST(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../cmake_modules/") +include(GNUInstallDirs) + +set(BIN_INSTALL_DIR "${CMAKE_INSTALL_PREFIX}/bin") +set(INDI_DATA_DIR "${CMAKE_INSTALL_PREFIX}/share/indi") +set(CMAKE_CXX_FLAGS "-std=c++0x ${CMAKE_CXX_FLAGS}") + + +set(INDI_TICFOCUSER-NG_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/TicFocuser.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/UsbConnectionBase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/SerialConnection.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/driver_interfaces/TiclibInterface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/ticlib/TicBase.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/ticlib/TicDefs.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/ticlib/StreamSerial.cpp + ) + +add_executable(indi_ticfocuser-ng) + +find_package(INDI REQUIRED) +target_link_libraries( indi_ticfocuser-ng indidriver) + +include_directories( ${CMAKE_CURRENT_BINARY_DIR}) +include_directories( ${CMAKE_CURRENT_SOURCE_DIR}) + +include_directories( + {CMAKE_CURRENT_BINARY_DIR} + ${INDI_INCLUDE_DIR} ) + +find_package(USB1) +if (USB1_FOUND) + + list(APPEND INDI_TICFOCUSER-NG_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/connection/LibUsbConnection.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/ticlib/TicUsb.cpp + ) + + include_directories(${USB1_INCLUDE_DIRS}) + target_link_libraries( indi_ticfocuser-ng "${USB1_LIBRARIES}") + + set(WITH_LIBUSB TRUE) +endif() + +find_package(LIBBLUETOOTH) +if (LIBBLUETOOTH_FOUND) + + list(APPEND INDI_TICFOCUSER-NG_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/connection/ticlib/StreamBT.cpp ${CMAKE_CURRENT_SOURCE_DIR}/connection/BluetoothConnection.cpp + ) + + target_link_libraries( indi_ticfocuser-ng "${LIBBLUETOOTH_LIBRARIES}") + + set(WITH_BLUETOOTH TRUE) +endif() + + +find_package(LIBTIC1) +if(LIBTIC1_FOUND) + + list(APPEND INDI_TICFOCUSER-NG_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/connection/driver_interfaces/PololuUsbInterface.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/connection/PololuUsbConnection.cpp + ) + include_directories(${LIBTIC1_INCLUDE_DIR}) + target_compile_options(indi_ticfocuser-ng PUBLIC ${LIBTIC1_CFLAGS}) + target_link_libraries( indi_ticfocuser-ng "${LIBTIC1_LIBRARIES}") + + set(WITH_LIBTIC TRUE) +endif() + +target_sources(indi_ticfocuser-ng PUBLIC ${INDI_TICFOCUSER-NG_SRCS}) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/TicFocuser_config.h.in + ${CMAKE_CURRENT_BINARY_DIR}/TicFocuser_config.h +) + +configure_file( + ${CMAKE_CURRENT_SOURCE_DIR}/indi_ticfocuser.xml.cmake + ${CMAKE_CURRENT_BINARY_DIR}/indi_ticfocuser.xml +) + +install(TARGETS indi_ticfocuser-ng RUNTIME DESTINATION bin ) +install(FILES ${CMAKE_CURRENT_BINARY_DIR}/indi_ticfocuser.xml DESTINATION ${INDI_DATA_DIR}) + diff --git a/indi-ticfocuser/LICENSE b/indi-ticfocuser/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/indi-ticfocuser/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/indi-ticfocuser/README.md b/indi-ticfocuser/README.md new file mode 100644 index 000000000..2574a519a --- /dev/null +++ b/indi-ticfocuser/README.md @@ -0,0 +1,59 @@ +# TicFocuser-ng +INDI Driver for USB focuser based on Pololu Tic controller. + +This is an integration of the project from Sebastian Baberowski (https://github.com/sebo-b/TicFocuser-ng), based on the work of Helge Kutzop (https://github.com/HelgeMK/TicFocuser)/ + +Check the upstream Sebastian Baberowski page for more informations/updates and the building process of this DIY Focuser. + +I (Bruno Bzeznik) just copied the upstream and adapted Cmake confguration to integrate correctly into the latest indi-3rdparty drivers. + +Here is a relevant extract from the original Readme file from upstream: + +### Connections + +The driver can utilize various connection interfaces to communicate with Pololu Tic controller. Some connections require particular libraries to be installed in your machine, CMake script will automatically detect these dependencies and enable only these connections, which can be compiled. + +There are two separate libraries used to manage Tic protocol. These are [Pololu Tic USB C library](https://github.com/pololu/pololu-tic-software) and [Pololu Tic Arduino library](https://github.com/pololu/tic-arduino). Both libraries are developed by Pololu, but apparently they doesn't share the code. The first one can be used only for USB connection. The second one is more generic and can utilize serial connections. However, it is developed for Arduino and was probably not meant to be compiled on Linux. I have ported it to Linux and extended for Bluetooth and USB (it can also be extended to I2C, but so far there was no such a request from the community). + +Available connections: +1. PololuUSB - this is a USB connection which utilizes [Pololu Tic C library](https://github.com/pololu/pololu-tic-software). Check [dependencies](#Dependencies) section for more info about installing it. +2. LibUSB - this is a USB connection with utilizes standard libusb-1 library probably available on all Linux distributiins. It use modified [Pololu Tic Arduino library](https://github.com/pololu/tic-arduino) which is included in this repo. Only libusb-1 is needed to make it work. +3. Bluetooth - this is a serial Bluetooth connection. It also uses [Pololu Tic Arduino library](https://github.com/pololu/tic-arduino) and depends on standard libbluetooth. +4. Serial - this is a regular serial connection (after configuring rfcomm tty can be also used for Bluetooth). This connection is always compiled. + +### Dependencies + +Please note that you need these libraries for compilation, so on most Linux distributions you'll need *-dev versions of these. + +1. You need INDI library installed together with headers. Most of Linux distributions have it in the repo. To install it on Arch simply type `pacman -S libindi` + +2. PololuUSB - for this connection you'll need Pololu Tic library. You can find instructions on how to download it and compile on [Pololu site](https://www.pololu.com/docs/0J71). On Arch you can use AUR package created by myself available [here](https://aur.archlinux.org/packages/pololu-tic-software/). + +3. LibUSB - for LibUSB based connection you need libusb-1. A lot of software depends on this library, so it is usually already installed in the system. If it is not installed, install it from your Linux distribution repository. + +4. LibBluetooth - if you are going to use Bluetooth, you need libbluetooth. If it is not installed, install it from your Linux distribution repository. + +### Compilation + +``` +$ mkdir build && cd build +$ cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr .. +$ make +$ sudo make install +``` + +### Configure Pololu Tic + +If you haven't done so, execute `ticgui` and properly configure Tic controller. For various reasons, motor parameters are not controlled by TicFocuser driver. + +At minimum: +* Configure your motor parameters like: current limit, step mode, speed, acceleration, etc. + +![ticcmd](https://raw.githubusercontent.com/sebo-b/TicFocuser-ng/master/extras/ticgui_motorsettings.png) + +* Uncheck `Enable command timeout` checkbox in the `Serial` box. More info abt it in [chapter 4.4 of Pololu Tic documentation](https://www.pololu.com/docs/0J71/all#4.4). + +* Test from `ticgui` if your focuser works correctly. + +You can read more about setting up proper motor parameters in [chapter 4.3 of Pololu Tic documentation](https://www.pololu.com/docs/0J71/all#4.3). In my setup I'm using current limit much lower than the rate of my motor because not much force is needed for my focuser, I save power and what's most important vibrations caused by the motor are marginalized. + diff --git a/indi-ticfocuser/TicFocuser.cpp b/indi-ticfocuser/TicFocuser.cpp new file mode 100644 index 000000000..c997d2940 --- /dev/null +++ b/indi-ticfocuser/TicFocuser.cpp @@ -0,0 +1,457 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019-2021 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include +#include +#include +#include +#include + +#include +#include + +#include "TicFocuser_config.h" +#include "TicFocuser.h" + +#include "connection/SerialConnection.h" +#include "connection/ticlib/TicDefs.h" + +#ifdef WITH_LIBTIC +#include "connection/PololuUsbConnection.h" +#endif + +#ifdef WITH_LIBUSB +#include "connection/LibUsbConnection.h" +#endif + +#ifdef WITH_BLUETOOTH +#include "connection/BluetoothConnection.h" +#endif + +//#include +//INDI::Logger::getInstance().print("TIC Focuser NG",INDI::Logger::DBG_WARNING, __FILE__, __LINE__,"jest context"); + + +std::unique_ptr ticFocuser(new TicFocuser()); + +void ISGetProperties(const char *dev) +{ + ticFocuser->ISGetProperties(dev); +} + +void ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int num) +{ + ticFocuser->ISNewSwitch(dev, name, states, names, num); +} + +void ISNewText( const char *dev, const char *name, char *texts[], char *names[], int num) +{ + ticFocuser->ISNewText(dev, name, texts, names, num); +} + +void ISNewNumber(const char *dev, const char *name, double values[], char *names[], int num) +{ + ticFocuser->ISNewNumber(dev, name, values, names, num); +} + +void ISNewBLOB (const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[], char *names[], int n) +{ + INDI_UNUSED(dev); + INDI_UNUSED(name); + INDI_UNUSED(sizes); + INDI_UNUSED(blobsizes); + INDI_UNUSED(blobs); + INDI_UNUSED(formats); + INDI_UNUSED(names); + INDI_UNUSED(n); +} + +void ISSnoopDevice (XMLEle *root) +{ + ticFocuser->ISSnoopDevice(root); +} + +TicFocuser::TicFocuser(): + lastTimerHitError(false), + moveRelInitialValue(-1), + lastFocusDir(FOCUS_INWARD) +{ + setVersion(TICFOCUSER_VERSION_MAJOR,TICFOCUSER_VERSION_MINOR); + setSupportedConnections(CONNECTION_NONE); + FI::SetCapability(FOCUSER_CAN_ABS_MOVE | FOCUSER_CAN_REL_MOVE | FOCUSER_CAN_SYNC | FOCUSER_CAN_ABORT | FOCUSER_HAS_BACKLASH); + + InfoErrorS = new IText[tic_error_names_ui_size]; +} + +TicFocuser::~TicFocuser() +{ + delete [] InfoErrorS; +} + +bool TicFocuser::initProperties() +{ + INDI::Focuser::initProperties(); + + IUFillSwitch(&FocusParkingModeS[0],"FOCUS_PARKON","Enable",ISS_OFF); + IUFillSwitch(&FocusParkingModeS[1],"FOCUS_PARKOFF","Disable",ISS_ON); + IUFillSwitchVector(&FocusParkingModeSP,FocusParkingModeS,2,getDeviceName(),"FOCUS_PARK_MODE","Parking Mode",OPTIONS_TAB,IP_RW,ISR_1OFMANY,60,IPS_IDLE); + + IUFillSwitch(&EnergizeFocuserS[0],"ENERGIZE_FOCUSER","Energize focuser",ISS_OFF); + IUFillSwitch(&EnergizeFocuserS[1],"DEENERGIZE_FOCUSER","De-energize focuser",ISS_OFF); + IUFillSwitchVector(&EnergizeFocuserSP,EnergizeFocuserS,2,getDeviceName(),"ENERGIZE_FOCUSER","Energize",MAIN_CONTROL_TAB,IP_RW,ISR_1OFMANY,60,IPS_IDLE); + + /***** INFO_TAB */ + IUFillText(&InfoS[VIN_VOLTAGE], "VIN_VOLTAGE", "Vin voltage", ""); + IUFillText(&InfoS[CURRENT_LIMIT], "CURRENT_LIMIT", "Current limit", ""); + IUFillText(&InfoS[STEP_MODE], "STEP_MODE", "Step mode", ""); + IUFillText(&InfoS[ENERGIZED], "ENERGIZED", "Energized", ""); + IUFillText(&InfoS[OPERATION_STATE], "OPERATION_STATE", "Operational state", ""); + IUFillTextVector(&InfoSP, InfoS, InfoTabSize, getDeviceName(), "TIC_INFO", "Tic Info", INFO_TAB, IP_RO, 60, IPS_IDLE); + + /***** INFO_TAB > Error */ + for (size_t i = 0; i < tic_error_names_ui_size; ++i) + IUFillText(&InfoErrorS[i], tic_error_names_ui[i].name, tic_error_names_ui[i].name, ""); + IUFillTextVector(&InfoErrorSP, InfoErrorS, tic_error_names_ui_size, getDeviceName(), "TIC_INFO_ERROR", "Tic Error", INFO_TAB, IP_RO, 60, IPS_IDLE); + + /***** Connections */ +#ifdef WITH_LIBTIC + registerConnection(new PololuUsbConnection(this)); +#endif +#ifdef WITH_LIBUSB + registerConnection(new LibUsbConnection(this)); +#endif +#ifdef WITH_BLUETOOTH + registerConnection(new BluetoothConnection(this)); +#endif + registerConnection(new SerialConnection(this)); + + return true; +} + +bool TicFocuser::updateProperties() +{ + INDI::Focuser::updateProperties(); + + if (isConnected()) + { + defineSwitch(&EnergizeFocuserSP); + defineSwitch(&FocusParkingModeSP); + defineText(&InfoSP); + defineText(&InfoErrorSP); + } + else + { + deleteProperty(FocusParkingModeSP.name); + deleteProperty(EnergizeFocuserSP.name); + deleteProperty(InfoSP.name); + deleteProperty(InfoErrorSP.name); + } + + return true; +} + +bool TicFocuser::ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n) +{ + return INDI::Focuser::ISNewNumber(dev,name,values,names,n); +} + +bool TicFocuser::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) +{ + // first we check if it's for our device + if (!strcmp(dev, getDeviceName())) + { + // handle parking mode + if(!strcmp(name, FocusParkingModeSP.name)) + { + IUUpdateSwitch(&FocusParkingModeSP, states, names, n); + FocusParkingModeSP.s = IPS_OK; + IDSetSwitch(&FocusParkingModeSP, NULL); + return true; + } + + if(!strcmp(name, EnergizeFocuserSP.name)) + { + bool res; + + if (!strcmp(names[0],EnergizeFocuserS[0].name)) + res = energizeFocuser(); + else + res = deenergizeFocuser(); + + EnergizeFocuserSP.s = res? IPS_OK: IPS_ALERT; + IDSetSwitch(&EnergizeFocuserSP, NULL); + + return true; + } + + + } + return INDI::Focuser::ISNewSwitch(dev,name,states,names,n); +} + +bool TicFocuser::saveConfigItems(FILE *fp) +{ + if (!Focuser::saveConfigItems(fp)) + return false; + + IUSaveConfigSwitch(fp, &FocusParkingModeSP); + + return true; +} + +bool TicFocuser::Disconnect() +{ + // park focuser + if (FocusParkingModeS[0].s != ISS_ON) { + LOG_INFO("Parking mode disabled, parking not performed."); + } + else { + MoveAbsFocuser(0); + } + + return Focuser::Disconnect(); +} + +bool TicFocuser::Connect() +{ + bool res = Focuser::Connect(); + + if (res) { + energizeFocuser(); // Error will be shown by energizeFocuser() function, no need to show it here + } + + return res; +} + +void TicFocuser::TimerHit() +{ + if (!isConnected()) + return; + + TicConnectionInterface* conn = dynamic_cast(getActiveConnection()); + TicDriverInterface& driverInterface = conn->getTicDriverInterface(); + + TicDriverInterface::TicVariables ticVariables; + bool res = driverInterface.getVariables(&ticVariables); + + if (res) { + + lastTimerHitError = false; + + FocusAbsPosN[0].value = ticVariables.currentPosition; + FocusSyncN[0].value = ticVariables.currentPosition; + + if (FocusAbsPosNP.s == IPS_BUSY) { + + if (moveRelInitialValue >= 0) { + FocusRelPosN[0].value = abs( moveRelInitialValue - ticVariables.currentPosition); + } + + if ( ticVariables.currentPosition == ticVariables.targetPosition) { + FocusAbsPosNP.s = IPS_OK; + FocusRelPosNP.s = IPS_OK; + moveRelInitialValue = -1; + } + } + + IDSetNumber(&FocusAbsPosNP, nullptr); + IDSetNumber(&FocusRelPosNP, nullptr); + IDSetNumber(&FocusSyncNP, nullptr); + + /** INFO_TAB */ + char buf[20]; + std::snprintf(buf,sizeof(buf),"%.2f V", ((double)ticVariables.vinVoltage)/1000); + IUSaveText( &InfoS[VIN_VOLTAGE], buf); + if (ticVariables.currentLimit > 1000) + std::snprintf(buf,sizeof(buf),"%.2f A", ((double)ticVariables.currentLimit)/1000); + else + std::snprintf(buf,sizeof(buf),"%d mA", ticVariables.currentLimit); + + IUSaveText( &InfoS[CURRENT_LIMIT], buf); + IUSaveText( &InfoS[ENERGIZED], ticVariables.energized? "Yes": "No"); + IUSaveText( &InfoS[STEP_MODE], ticVariables.stepMode.c_str()); + IUSaveText( &InfoS[OPERATION_STATE], ticVariables.operationalState.c_str()); + IDSetText(&InfoSP, nullptr); + + /***** INFO_TAB > Error */ + for (size_t i = 0; i < tic_error_names_ui_size; ++i) + { + if (tic_error_names_ui[i].code & ticVariables.errorStatus) + IUSaveText(&InfoErrorS[i], "Error"); + else + IUSaveText(&InfoErrorS[i], "-"); + } + IDSetText(&InfoErrorSP, nullptr); + + } + else if (!lastTimerHitError) { + LOGF_ERROR("Cannot receive variables: %s", driverInterface.getLastErrorMsg()); + lastTimerHitError = true; + } + + SetTimer(POLLMS); +} + +bool TicFocuser::energizeFocuser() +{ + TicConnectionInterface* conn = dynamic_cast(getActiveConnection()); + TicDriverInterface& driverInterface = conn->getTicDriverInterface(); + + if (!driverInterface.energize()) + { + LOGF_ERROR("Cannot energize motor. Error: %s", driverInterface.getLastErrorMsg()); + return false; + } + + + if (!driverInterface.exitSafeStart()) + { + LOGF_ERROR("Cannot exit safe start. Error: %s", driverInterface.getLastErrorMsg()); + return false; + } + + return true; +} + +bool TicFocuser::deenergizeFocuser() +{ + TicConnectionInterface* conn = dynamic_cast(getActiveConnection()); + TicDriverInterface& driverInterface = conn->getTicDriverInterface(); + + if (!driverInterface.deenergize()) + { + LOGF_ERROR("Cannot de-energize motor. Error: %s", driverInterface.getLastErrorMsg()); + return false; + } + else + { + LOG_INFO("Focuser de-energized. You must energize it to resume normal operation."); + } + + return true; +} + +bool TicFocuser::SyncFocuser(uint32_t ticks) +{ + TicConnectionInterface* conn = dynamic_cast(getActiveConnection()); + TicDriverInterface& driverInterface = conn->getTicDriverInterface(); + + if (!driverInterface.haltAndSetPosition(ticks)) + { + LOGF_ERROR("Cannot sync focuser. Error: %s", driverInterface.getLastErrorMsg()); + return false; + } + + return true; +} + + +bool TicFocuser::AbortFocuser() +{ + + TicConnectionInterface* conn = dynamic_cast(getActiveConnection()); + TicDriverInterface& driverInterface = conn->getTicDriverInterface(); + + if (!driverInterface.haltAndHold()) + { + LOGF_ERROR("Cannot abort TIC. Error: %s", driverInterface.getLastErrorMsg()); + return false; + } + + return true; +} + +IPState TicFocuser::MoveFocuser(FocusDirection dir, int speed, uint16_t duration) +{ + INDI_UNUSED(dir); + INDI_UNUSED(speed); + INDI_UNUSED(duration); + LOG_ERROR("Focuser does not support timer based motion."); + + return IPS_ALERT; +} + +IPState TicFocuser::MoveRelFocuser(FocusDirection dir, uint32_t ticks) +{ + int32_t absTicks = FocusAbsPosN[0].value; + int32_t targetTicks; + if (dir == FOCUS_OUTWARD) + targetTicks = absTicks + ticks; + else + targetTicks = absTicks - ticks; + + IPState ret = MoveAbsFocuser(targetTicks); + + moveRelInitialValue = ret == IPS_BUSY? absTicks: -1; + + FocusAbsPosNP.s = ret; + IDSetNumber(&FocusAbsPosNP, nullptr); + + return ret; +} + +IPState TicFocuser::MoveAbsFocuser(uint32_t ticks) +{ + if (ticks == FocusAbsPosN[0].value) + { + return IPS_OK; + } + else if (ticks > FocusAbsPosN[0].value) + { + if(lastFocusDir == FOCUS_INWARD && FocusBacklashS[INDI_ENABLED].s == ISS_ON) + { + uint32_t nominal = ticks; + ticks = static_cast(std::min(ticks + FocusBacklashN[0].value, FocusAbsPosN[0].max)); + LOGF_INFO("Apply backlash (in->out): +%d", ticks - nominal); + } + lastFocusDir = FOCUS_OUTWARD; + } + else if (ticks < FocusAbsPosN[0].value && FocusBacklashS[INDI_ENABLED].s == ISS_ON) + { + if(lastFocusDir == FOCUS_OUTWARD) + { + uint32_t nominal = ticks; + ticks = static_cast(std::max(ticks - FocusBacklashN[0].value, FocusAbsPosN[0].min)); + LOGF_INFO("Apply backlash (out->in): %d", ticks - nominal); + } + lastFocusDir = FOCUS_INWARD; + } + + if (ticks < FocusAbsPosN[0].min || ticks > FocusAbsPosN[0].max) + { + LOGF_ERROR("Requested position is out of range: %d", ticks); + return IPS_ALERT; + } + + TicConnectionInterface* conn = dynamic_cast(getActiveConnection()); + TicDriverInterface& driverInterface = conn->getTicDriverInterface(); + + if (!driverInterface.setTargetPosition(ticks)) + { + LOGF_ERROR("Cannot set target position. Error: %s", driverInterface.getLastErrorMsg()); + return IPS_ALERT; + } + + return IPS_BUSY; +} + +bool TicFocuser::SetFocuserBacklash(int32_t steps) +{ + INDI_UNUSED(steps); + return true; +} diff --git a/indi-ticfocuser/TicFocuser.h b/indi-ticfocuser/TicFocuser.h new file mode 100644 index 000000000..860cd3407 --- /dev/null +++ b/indi-ticfocuser/TicFocuser.h @@ -0,0 +1,87 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019-2021 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef TICFOCUSER_H +#define TICFOCUSER_H + +#include + +class TicFocuser : public INDI::Focuser +{ + public: + + TicFocuser(); + virtual ~TicFocuser(); + + const char *getDefaultName() { return "TIC Focuser NG"; } + + virtual bool initProperties(); + virtual bool updateProperties(); + + bool ISNewNumber (const char *dev, const char *name, double values[], char *names[], int n); + bool ISNewSwitch (const char *dev, const char *name, ISState *states, char *names[], int n); + + bool saveConfigItems(FILE *fp); + + bool Disconnect(); + bool Connect(); + + IPState MoveFocuser(FocusDirection dir, int speed, uint16_t duration); + IPState MoveAbsFocuser(uint32_t ticks); + IPState MoveRelFocuser(FocusDirection dir, uint32_t ticks); + bool AbortFocuser(); + bool SyncFocuser(uint32_t ticks); + + void TimerHit(); + + bool energizeFocuser(); + bool deenergizeFocuser(); + + protected: + virtual bool SetFocuserBacklash(int32_t steps) override; + + private: + + bool lastTimerHitError; //< used to not flood user with the same error messge if it repeats + int32_t moveRelInitialValue; //< used to simulate MoveRelFocuser + FocusDirection lastFocusDir; //< used to identify direction reversal (for backlash) + + ISwitch FocusParkingModeS[2]; + ISwitchVectorProperty FocusParkingModeSP; + + ISwitch EnergizeFocuserS[2]; + ISwitchVectorProperty EnergizeFocuserSP; + + enum InfoTab { + VIN_VOLTAGE, + CURRENT_LIMIT, + ENERGIZED, + STEP_MODE, + OPERATION_STATE, + + InfoTabSize + }; + + IText InfoS[InfoTabSize] = {}; + ITextVectorProperty InfoSP; + + IText* InfoErrorS; + ITextVectorProperty InfoErrorSP; +}; + +#endif // TICFOCUSER_H diff --git a/indi-ticfocuser/TicFocuser_config.h.in b/indi-ticfocuser/TicFocuser_config.h.in new file mode 100644 index 000000000..46a0413b9 --- /dev/null +++ b/indi-ticfocuser/TicFocuser_config.h.in @@ -0,0 +1,11 @@ +#ifndef TICFOCUSER_CONFIG_H +#define TICFOCUSER_CONFIG_H + +#define TICFOCUSER_VERSION_MAJOR @TICFOCUSER_VERSION_MAJOR@ +#define TICFOCUSER_VERSION_MINOR @TICFOCUSER_VERSION_MINOR@ + +#cmakedefine WITH_LIBUSB +#cmakedefine WITH_BLUETOOTH +#cmakedefine WITH_LIBTIC + +#endif // TICFOCUSER_CONFIG_H \ No newline at end of file diff --git a/indi-ticfocuser/connection/BluetoothConnection.cpp b/indi-ticfocuser/connection/BluetoothConnection.cpp new file mode 100644 index 000000000..6be160441 --- /dev/null +++ b/indi-ticfocuser/connection/BluetoothConnection.cpp @@ -0,0 +1,165 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "BluetoothConnection.h" + +#include "driver_interfaces/TiclibInterface.h" +#include "ticlib/TicBase.h" +#include "ticlib/StreamBT.h" + +#include +#include + +BluetoothConnection::BluetoothConnection(INDI::DefaultDevice *dev): + Interface(dev, CONNECTION_CUSTOM) +{ + const size_t MAX_BT_MAC = 40; // bt mac has 17 characters, 40 is super safe + char btMacAddress[MAX_BT_MAC]; + + if (IUGetConfigText(dev->getDeviceName(), "BT_MAC_TP", "BT_MAC_ADDRESS", btMacAddress, MAX_BT_MAC)) { + btMacAddress[0] = '\0'; + } + else { + requiredBtMacAddress = btMacAddress; + } + + IUFillText(BtMacAddressT, "BT_MAC_ADDRESS", "Bluetooth MAC address", btMacAddress); + IUFillTextVector(&BtMacAddressTP, BtMacAddressT, 1, getDeviceName(), "BT_MAC_TP", "Bluetooth MAC address", CONNECTION_TAB, + IP_RW, 60, IPS_IDLE); + LOG_WARN("IUFillText in BluetoothConnection"); + + streamBT = new StreamBT; + ticSerial = new TicSerial(*streamBT); + + ticDriverInterface = new TiclibInterface(*ticSerial); + + registerHandshake([&]() + { + return callHandshake(); + }); +} + +BluetoothConnection::~BluetoothConnection() +{ + delete ticDriverInterface; + delete ticSerial; + delete streamBT; +} + +bool BluetoothConnection::Connect() +{ + if (!streamBT->connect(requiredBtMacAddress.c_str())) + { + LOGF_ERROR("Cannot connect to bluetooth device with MAC address %s", requiredBtMacAddress.c_str()); + return false; + } + + if (!Handshake()) + { + LOG_ERROR("Bluetooth device handshake failed."); + streamBT->disconnect(); + return false; + } + + LOGF_INFO("Connected to Bluetooth device with MAC: %s",requiredBtMacAddress.c_str()); + + BtMacAddressTP.s = IPS_OK; + IUSaveText(BtMacAddressT, requiredBtMacAddress.c_str()); + IDSetText(&BtMacAddressTP, nullptr); + + return true; +} + +bool BluetoothConnection::Disconnect() +{ + streamBT->disconnect(); + + LOG_INFO("Bluetooth disconnected."); + return true; +} + +bool BluetoothConnection::callHandshake() +{ + uint32_t uptime = ticSerial->getUpTime(); + return !ticSerial->getLastError() && uptime > 0; +} + +void BluetoothConnection::Activated() +{ + m_Device->defineText(&BtMacAddressTP); +} + +void BluetoothConnection::Deactivated() +{ + m_Device->deleteProperty(BtMacAddressTP.name); +} + +bool BluetoothConnection::saveConfigItems(FILE *fp) { + + if (!Connection::Interface::saveConfigItems(fp)) + return false; + + if (!requiredBtMacAddress.empty()) { + + // make sure we are storing requiredBtMacAddress as BtMacAddressT may contain connected BT mac + char* tmpText = BtMacAddressT[0].text; + BtMacAddressT[0].text = const_cast(requiredBtMacAddress.c_str()); + + IUSaveConfigText(fp,&BtMacAddressTP); + + BtMacAddressT[0].text = tmpText; + } + + return true; +} + +bool BluetoothConnection::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) +{ + if (!strcmp(dev, m_Device->getDeviceName())) + { + if (!strcmp(name, BtMacAddressTP.name)) { + + if (requiredBtMacAddress == texts[0]) + return true; + + requiredBtMacAddress = texts[0]; + + if (m_Device->isConnected()) { + + if (requiredBtMacAddress.empty()) { + BtMacAddressTP.s = IPS_IDLE; + } + else { + LOG_WARN("Serial number selected. You must reconnect TicFocuser."); + BtMacAddressTP.s = IPS_BUSY; + } + + } + else { + IUUpdateText(&BtMacAddressTP, texts, names, n); + BtMacAddressTP.s = requiredBtMacAddress.empty()? IPS_IDLE: IPS_OK; + } + + IDSetText(&BtMacAddressTP, nullptr); + + return true; + } + } + + return Connection::Interface::ISNewText(dev,name,texts,names,n); +} diff --git a/indi-ticfocuser/connection/BluetoothConnection.h b/indi-ticfocuser/connection/BluetoothConnection.h new file mode 100644 index 000000000..087b1402e --- /dev/null +++ b/indi-ticfocuser/connection/BluetoothConnection.h @@ -0,0 +1,65 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef BLUETOOTHCONNECTION_H +#define BLUETOOTHCONNECTION_H + +#include +#include "TicConnectionInterface.h" + +class StreamBT; +class TicSerial; + +class BluetoothConnection: + public Connection::Interface, + public TicConnectionInterface +{ + public: + + BluetoothConnection(INDI::DefaultDevice *dev); + ~BluetoothConnection(); + + std::string name() { return "Tic Bluetooth Connection"; }; + std::string label() { return "Bluetooth"; }; + + bool Connect(); + bool Disconnect(); + void Activated(); + void Deactivated(); + + bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n); + bool saveConfigItems(FILE *fp); + + TicDriverInterface& getTicDriverInterface() { return *ticDriverInterface; } + + private: + + bool callHandshake(); + + IText BtMacAddressT[1] {}; + ITextVectorProperty BtMacAddressTP; + + std::string requiredBtMacAddress; + + TicDriverInterface* ticDriverInterface; + + StreamBT* streamBT; + TicSerial* ticSerial; +}; + +#endif // BLUETOOTHCONNECTION_H diff --git a/indi-ticfocuser/connection/LibUsbConnection.cpp b/indi-ticfocuser/connection/LibUsbConnection.cpp new file mode 100644 index 000000000..ff2b3763e --- /dev/null +++ b/indi-ticfocuser/connection/LibUsbConnection.cpp @@ -0,0 +1,70 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "LibUsbConnection.h" + +#include "driver_interfaces/TiclibInterface.h" +#include "ticlib/TicUsb.h" + +#include +#include + +LibUsbConnection::LibUsbConnection(INDI::DefaultDevice *dev): + UsbConnectionBase("LIBUSB_SERIAL_NUMBER",dev) + +{ + ticUsb = new TicUsb(); + ticDriverInterface = new TiclibInterface(*ticUsb); +} + +LibUsbConnection::~LibUsbConnection() +{ + delete ticDriverInterface; + delete ticUsb; +} + +bool LibUsbConnection::Connect() +{ + Disconnect(); + + ticUsb->connect(requiredSerialNumber.c_str()); + if (ticUsb->getLastError()) + { + LOGF_ERROR("TicUsb error: %s",ticUsb->getLastErrorMsg()); + if (requiredSerialNumber.empty()) + LOG_ERROR("No TIC device found."); + else + LOGF_ERROR("No TIC device found with serial: %s. You can set serial to empty to connect to the first found Tic device.", requiredSerialNumber.c_str()); + + return false; + } + + LOGF_INFO("Connected to Tic with serial: %s",ticUsb->getSerial()); + + TicSerialNumberTP.s = requiredSerialNumber.empty()? IPS_IDLE: IPS_OK; + IUSaveText(TicSerialNumberT, ticUsb->getSerial()); + IDSetText(&TicSerialNumberTP, nullptr); + + return true; +} + +bool LibUsbConnection::Disconnect() +{ + ticUsb->disconnect(); + return true; +} diff --git a/indi-ticfocuser/connection/LibUsbConnection.h b/indi-ticfocuser/connection/LibUsbConnection.h new file mode 100644 index 000000000..2e7a54d13 --- /dev/null +++ b/indi-ticfocuser/connection/LibUsbConnection.h @@ -0,0 +1,44 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef LIBUSBCONNECTION_H +#define LIBUSBCONNECTION_H + +#include +#include "UsbConnectionBase.h" + +class TicUsb; + +class LibUsbConnection: public UsbConnectionBase +{ + + TicUsb* ticUsb; + + public: + + LibUsbConnection(INDI::DefaultDevice *dev); + ~LibUsbConnection(); + + bool Connect(); + bool Disconnect(); + + std::string name() { return "Lib USB Connection"; }; + std::string label() { return "LibUSB"; }; +}; + +#endif // LIBUSBCONNECTION_H diff --git a/indi-ticfocuser/connection/PololuUsbConnection.cpp b/indi-ticfocuser/connection/PololuUsbConnection.cpp new file mode 100644 index 000000000..90b16563e --- /dev/null +++ b/indi-ticfocuser/connection/PololuUsbConnection.cpp @@ -0,0 +1,109 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "PololuUsbConnection.h" + +#include "driver_interfaces/PololuUsbInterface.h" + +#include +#include +#include + +PololuUsbConnection::PololuUsbConnection(INDI::DefaultDevice *dev): + UsbConnectionBase("PUSB_SERIAL_NUMBER",dev), + handle(NULL) +{ + ticDriverInterface = new PololuUsbInterface(handle); +} + +PololuUsbConnection::~PololuUsbConnection() +{ + if (handle) + tic_handle_close(handle); + + delete ticDriverInterface; +} + +bool PololuUsbConnection::Connect() +{ + Disconnect(); + + std::string devSerialNumber; + tic_device** deviceList; + + tic_error* error = tic_list_connected_devices(&deviceList,NULL); + if (error) + { + LOGF_ERROR("Cannot list connected devices. Error: %s", tic_error_get_message(error)); + tic_error_free(error); + return false; + } + + for (tic_device** d = deviceList; *d; ++d) { + + devSerialNumber = tic_device_get_serial_number(*d); + + if (requiredSerialNumber.empty() || requiredSerialNumber == devSerialNumber) + { + error = tic_handle_open(*d,&handle); + if (error) + { + LOGF_WARN("Cannot open tic device. Error: %s", tic_error_get_message(error)); + tic_error_free(error); + continue; + } + + break; + } + } + + for (tic_device** d = deviceList; *d; ++d) + tic_device_free(*d); + tic_list_free(deviceList); + + if (handle == NULL) + { + if (requiredSerialNumber.empty()) + LOG_ERROR("No TIC device found."); + else + LOGF_ERROR("No TIC device found with serial: %s. You can set serial to empty to connect to the first found Tic device.", requiredSerialNumber.c_str()); + return false; + } + + LOGF_INFO("Connected to Tic with serial: %s",devSerialNumber.c_str()); + + TicSerialNumberTP.s = requiredSerialNumber.empty()? IPS_IDLE: IPS_OK; + IUSaveText(TicSerialNumberT, devSerialNumber.c_str()); + IDSetText(&TicSerialNumberTP, nullptr); + + return true; +} + +bool PololuUsbConnection::Disconnect() +{ + bool ret = UsbConnectionBase::Disconnect(); + if (!ret) + return ret; + + if (handle) + tic_handle_close(handle); + handle = NULL; + + return true; +} + diff --git a/indi-ticfocuser/connection/PololuUsbConnection.h b/indi-ticfocuser/connection/PololuUsbConnection.h new file mode 100644 index 000000000..686e98665 --- /dev/null +++ b/indi-ticfocuser/connection/PololuUsbConnection.h @@ -0,0 +1,44 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef POLOLUUSBCONNECTION_H +#define POLOLUUSBCONNECTION_H + +#include +#include "UsbConnectionBase.h" + +class tic_handle; + +class PololuUsbConnection: public UsbConnectionBase +{ + tic_handle* handle; + + public: + + PololuUsbConnection(INDI::DefaultDevice *dev); + ~PololuUsbConnection(); + + bool Connect(); + bool Disconnect(); + + std::string name() { return "Pololu USB Connection"; }; + std::string label() { return "PololuUSB"; }; + +}; + +#endif // POLOLUUSBCONNECTION_H diff --git a/indi-ticfocuser/connection/SerialConnection.cpp b/indi-ticfocuser/connection/SerialConnection.cpp new file mode 100644 index 000000000..40970fb68 --- /dev/null +++ b/indi-ticfocuser/connection/SerialConnection.cpp @@ -0,0 +1,144 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "SerialConnection.h" + +#include "driver_interfaces/TiclibInterface.h" +#include "ticlib/TicBase.h" +#include "ticlib/StreamSerial.h" + +#include +#include + +SerialConnection::SerialConnection(INDI::DefaultDevice *dev): + Connection::Serial(dev) +{ + streamSerial = new StreamSerial(PortFD); + ticSerial = new TicSerial(*streamSerial); + ticDriverInterface = new TiclibInterface(*ticSerial); + + registerHandshake([&]() + { + return callHandshake(); + }); +} + +SerialConnection::~SerialConnection() +{ +// delete ticDriverInterface; +// delete ticSerial; +// delete streamBT; +} + +bool SerialConnection::callHandshake() +{ + uint32_t uptime = ticSerial->getUpTime(); + return !ticSerial->getLastError() && uptime > 0; +} + +#if 0 + +bool SerialConnection::Connect() +{ + bool res = Connection::Serial::Connect(); + + if (res) + { + streamSerial->connect(PortFD); +// + + } + + return res; +} + + +bool BluetoothConnection::Disconnect() +{ + streamBT->disconnect(); + + LOG_INFO("Bluetooth disconnected."); + return true; +} + +void BluetoothConnection::Activated() +{ + m_Device->defineText(&BtMacAddressTP); +} + +void BluetoothConnection::Deactivated() +{ + m_Device->deleteProperty(BtMacAddressTP.name); +} + +bool BluetoothConnection::saveConfigItems(FILE *fp) { + + if (!Connection::Interface::saveConfigItems(fp)) + return false; + + if (!requiredBtMacAddress.empty()) { + + // make sure we are storing requiredBtMacAddress as BtMacAddressT may contain connected BT mac + char* tmpText = BtMacAddressT[0].text; + BtMacAddressT[0].text = const_cast(requiredBtMacAddress.c_str()); + + IUSaveConfigText(fp,&BtMacAddressTP); + + BtMacAddressT[0].text = tmpText; + } + + return true; +} + +bool BluetoothConnection::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) +{ + if (!strcmp(dev, m_Device->getDeviceName())) + { + if (!strcmp(name, BtMacAddressTP.name)) { + + if (requiredBtMacAddress == texts[0]) + return true; + + requiredBtMacAddress = texts[0]; + + if (m_Device->isConnected()) { + + if (requiredBtMacAddress.empty()) { + BtMacAddressTP.s = IPS_IDLE; + } + else { + LOG_WARN("Serial number selected. You must reconnect TicFocuser."); + BtMacAddressTP.s = IPS_BUSY; + } + + } + else { + IUUpdateText(&BtMacAddressTP, texts, names, n); + BtMacAddressTP.s = requiredBtMacAddress.empty()? IPS_IDLE: IPS_OK; + } + + IDSetText(&BtMacAddressTP, nullptr); + + return true; + } + } + + return Connection::Interface::ISNewText(dev,name,texts,names,n); +} + +#endif diff --git a/indi-ticfocuser/connection/SerialConnection.h b/indi-ticfocuser/connection/SerialConnection.h new file mode 100644 index 000000000..301b9f654 --- /dev/null +++ b/indi-ticfocuser/connection/SerialConnection.h @@ -0,0 +1,58 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef SERIALCONNECTION_H +#define SERIALCONNECTION_H + +#include +#include "TicConnectionInterface.h" + +class StreamSerial; +class TicSerial; + +class SerialConnection: + public Connection::Serial, + public TicConnectionInterface +{ + public: + + SerialConnection(INDI::DefaultDevice *dev); + ~SerialConnection(); + + std::string name() { return "Tic Serial Connection"; }; + +// bool Connect(); +// bool Disconnect(); +// void Activated(); +// void Deactivated(); +// +// bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n); +// bool saveConfigItems(FILE *fp); + + TicDriverInterface& getTicDriverInterface() { return *ticDriverInterface; } + + private: + + bool callHandshake(); + + TicDriverInterface* ticDriverInterface; + StreamSerial* streamSerial; + TicSerial* ticSerial; +}; + +#endif // SERIALCONNECTION_H diff --git a/indi-ticfocuser/connection/TicConnectionInterface.h b/indi-ticfocuser/connection/TicConnectionInterface.h new file mode 100644 index 000000000..6210ffa72 --- /dev/null +++ b/indi-ticfocuser/connection/TicConnectionInterface.h @@ -0,0 +1,32 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef TICCONNECTIONINTERFACE_H +#define TICCONNECTIONINTERFACE_H + +#include "driver_interfaces/TicDriverInterface.h" +#include + +class TicConnectionInterface +{ +public: + virtual ~TicConnectionInterface() {} + virtual TicDriverInterface& getTicDriverInterface() = 0; +}; + +#endif // TICCONNECTIONINTERFACE_H diff --git a/indi-ticfocuser/connection/UsbConnectionBase.cpp b/indi-ticfocuser/connection/UsbConnectionBase.cpp new file mode 100644 index 000000000..4c5441fd3 --- /dev/null +++ b/indi-ticfocuser/connection/UsbConnectionBase.cpp @@ -0,0 +1,126 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "UsbConnectionBase.h" +#include "driver_interfaces/TicDriverInterface.h" + +#include +#include + +UsbConnectionBase::UsbConnectionBase(const char* serialNFieldName, INDI::DefaultDevice *dev): + Interface(dev, CONNECTION_USB) +{ + const size_t MAX_SERIAL_NUMBER = 20; // serial number has 8 characters, 20 is super safe + char serialNumber[MAX_SERIAL_NUMBER]; + + if (IUGetConfigText(dev->getDeviceName(), "TIC_SERIAL_TP", "TIC_SERIAL_NUMBER", serialNumber, MAX_SERIAL_NUMBER)) { + serialNumber[0] = '\0'; + } + else { + requiredSerialNumber = serialNumber; + } + + std::string serialNFieldNameTP = serialNFieldName; + serialNFieldNameTP += "_TP"; + + IUFillText(TicSerialNumberT, serialNFieldName, "Tic Serial Number", serialNumber); + IUFillTextVector(&TicSerialNumberTP, TicSerialNumberT, 1, getDeviceName(), serialNFieldNameTP.c_str(), "Tic Serial Number", CONNECTION_TAB, + IP_RW, 60, IPS_IDLE); +}; + +UsbConnectionBase::~UsbConnectionBase() +{ +}; + +bool UsbConnectionBase::Disconnect() +{ + IUSaveText(TicSerialNumberT, requiredSerialNumber.c_str()); + TicSerialNumberTP.s = requiredSerialNumber.empty()? IPS_IDLE: IPS_OK; + IDSetText(&TicSerialNumberTP, nullptr); + + return true; //Connection::Interface::Disconnect(); +}; + +void UsbConnectionBase::Activated() +{ + m_Device->defineText(&TicSerialNumberTP); + + //Connection::Interface::Activated(); +}; + +void UsbConnectionBase::Deactivated() +{ + m_Device->deleteProperty(TicSerialNumberTP.name); + + //Connection::Interface::Deactivated(); +}; + +bool UsbConnectionBase::saveConfigItems(FILE *fp) { + + if (!Connection::Interface::saveConfigItems(fp)) + return false; + + if (!requiredSerialNumber.empty()) { + + // make sure we are storing requiredSerialNumber as TicSerialNumberT may contain connected TIC serial + char* tmpText = TicSerialNumberT[0].text; + TicSerialNumberT[0].text = const_cast(requiredSerialNumber.c_str()); + + IUSaveConfigText(fp,&TicSerialNumberTP); + + TicSerialNumberT[0].text = tmpText; + } + + return true; +} + +bool UsbConnectionBase::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) +{ + if (!strcmp(dev, m_Device->getDeviceName())) + { + if (!strcmp(name, TicSerialNumberTP.name)) { + + if (requiredSerialNumber == texts[0]) + return true; + + requiredSerialNumber = texts[0]; + + if (m_Device->isConnected()) { + + if (requiredSerialNumber.empty()) { + TicSerialNumberTP.s = IPS_IDLE; + } + else { + LOG_WARN("Serial number selected. You must reconnect TicFocuser."); + TicSerialNumberTP.s = IPS_BUSY; + } + + } + else { + IUUpdateText(&TicSerialNumberTP, texts, names, n); + TicSerialNumberTP.s = requiredSerialNumber.empty()? IPS_IDLE: IPS_OK; + } + + IDSetText(&TicSerialNumberTP, nullptr); + + return true; + } + } + + return Connection::Interface::ISNewText(dev,name,texts,names,n); +} diff --git a/indi-ticfocuser/connection/UsbConnectionBase.h b/indi-ticfocuser/connection/UsbConnectionBase.h new file mode 100644 index 000000000..1137a043f --- /dev/null +++ b/indi-ticfocuser/connection/UsbConnectionBase.h @@ -0,0 +1,57 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef USBCONNECTIONBASE_H +#define USBCONNECTIONBASE_H + +#include +#include "TicConnectionInterface.h" + +class TicDriverInterface; + +class UsbConnectionBase: + public Connection::Interface, + public TicConnectionInterface +{ + public: + + // serialNFieldName - each derived class must use its own name for UI fields + UsbConnectionBase(const char* serialNFieldName, INDI::DefaultDevice *dev); + ~UsbConnectionBase(); + + bool Disconnect(); + void Activated(); + void Deactivated(); + + bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n); + + bool saveConfigItems(FILE *fp); + + TicDriverInterface& getTicDriverInterface() { return *ticDriverInterface; } + + protected: + + IText TicSerialNumberT[1] {}; + ITextVectorProperty TicSerialNumberTP; + + std::string requiredSerialNumber; + + TicDriverInterface* ticDriverInterface; +}; + +#endif // USBCONNECTIONBASE_H diff --git a/indi-ticfocuser/connection/driver_interfaces/PololuUsbInterface.cpp b/indi-ticfocuser/connection/driver_interfaces/PololuUsbInterface.cpp new file mode 100644 index 000000000..3db3450c7 --- /dev/null +++ b/indi-ticfocuser/connection/driver_interfaces/PololuUsbInterface.cpp @@ -0,0 +1,130 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "PololuUsbInterface.h" + +#include +#include + +bool PololuUsbInterface::energize() +{ + tic_error* err = tic_energize(handle); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + return true; +} + +bool PololuUsbInterface::deenergize() +{ + tic_error* err = tic_deenergize(handle); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + return true; + +} + +bool PololuUsbInterface::exitSafeStart() +{ + tic_error* err = tic_exit_safe_start(handle); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + return true; +} + +bool PololuUsbInterface::haltAndHold() +{ + tic_error* err = tic_halt_and_hold(handle); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + return true; +} + +bool PololuUsbInterface::setTargetPosition(int position) +{ + tic_error* err = tic_set_target_position(handle, position); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + return true; +} + +bool PololuUsbInterface::haltAndSetPosition(int position) +{ + tic_error* err = tic_halt_and_set_position(handle, position); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + return true; +} + +bool PololuUsbInterface::getVariables(TicVariables* vars) +{ + tic_variables* variables = NULL; + + tic_error* err = tic_get_variables(handle,&variables,false); + if (err) { + lastErrorMsg = tic_error_get_message(err); + tic_error_free(err); + return false; + } + lastErrorMsg = "OK"; + + vars->currentPosition = tic_variables_get_current_position(variables); + vars->targetPosition = tic_variables_get_target_position(variables); + + vars->vinVoltage = tic_variables_get_vin_voltage(variables); + vars->currentLimit = tic_variables_get_current_limit(variables); + vars->energized = tic_variables_get_energized(variables); + vars->stepMode = tic_look_up_step_mode_name_ui( + tic_variables_get_step_mode(variables)); + vars->operationalState = tic_look_up_operation_state_name_ui( + tic_variables_get_operation_state(variables)); + + vars->errorStatus = tic_variables_get_error_status(variables); + + tic_variables_free(variables); + return true; +} diff --git a/indi-ticfocuser/connection/driver_interfaces/PololuUsbInterface.h b/indi-ticfocuser/connection/driver_interfaces/PololuUsbInterface.h new file mode 100644 index 000000000..3df2de2eb --- /dev/null +++ b/indi-ticfocuser/connection/driver_interfaces/PololuUsbInterface.h @@ -0,0 +1,50 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef POLOLUUSBINTERFACE_H +#define POLOLUUSBINTERFACE_H + +#include "TicDriverInterface.h" +#include + +struct tic_handle; + +class PololuUsbInterface: public TicDriverInterface +{ + tic_handle*& handle; + std::string lastErrorMsg; + +public: + + PololuUsbInterface(tic_handle*& handle): handle( handle) {} + + bool energize(); + bool deenergize(); + + bool exitSafeStart(); + bool haltAndHold(); + + bool setTargetPosition(int position); + bool haltAndSetPosition(int position); + + bool getVariables(TicVariables*); + + const char* getLastErrorMsg() { return lastErrorMsg.c_str(); } +}; + +#endif // POLOLUUSBINTERFACE_H diff --git a/indi-ticfocuser/connection/driver_interfaces/TicDriverInterface.h b/indi-ticfocuser/connection/driver_interfaces/TicDriverInterface.h new file mode 100644 index 000000000..499968741 --- /dev/null +++ b/indi-ticfocuser/connection/driver_interfaces/TicDriverInterface.h @@ -0,0 +1,59 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef TICDRIVERINTERFACE_H +#define TICDRIVERINTERFACE_H + +#include +#include + +class TicDriverInterface +{ +public: + + virtual ~TicDriverInterface() {} + + virtual bool energize() = 0; + virtual bool deenergize() = 0; + + virtual bool exitSafeStart() = 0; + virtual bool haltAndHold() = 0; + + virtual bool setTargetPosition(int position) = 0; + virtual bool haltAndSetPosition(int position) = 0; + + class TicVariables { + public: + int currentPosition; + int targetPosition; + + int vinVoltage; + int currentLimit; + bool energized; + std::string stepMode; + std::string operationalState; + + uint16_t errorStatus; + }; + + virtual bool getVariables(TicVariables*) = 0; + + virtual const char* getLastErrorMsg() = 0; +}; + +#endif // TICDRIVERINTERFACE_H diff --git a/indi-ticfocuser/connection/driver_interfaces/TiclibInterface.cpp b/indi-ticfocuser/connection/driver_interfaces/TiclibInterface.cpp new file mode 100644 index 000000000..11ba7a2a5 --- /dev/null +++ b/indi-ticfocuser/connection/driver_interfaces/TiclibInterface.cpp @@ -0,0 +1,133 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#include "TiclibInterface.h" + +#include "connection/ticlib/TicBase.h" +#include "connection/ticlib/TicDefs.h" + +#include + +bool TiclibInterface::energize() +{ + ticBase.energize(); + if (ticBase.getLastError()) + { + lastErrorMsg = "Energize error"; + return false; + } + + lastErrorMsg = "OK"; + return true; +} + +bool TiclibInterface::deenergize() +{ + ticBase.deenergize(); + if (ticBase.getLastError()) + { + lastErrorMsg = "De-energize error"; + return false; + } + + lastErrorMsg = "OK"; + return true; +} + +bool TiclibInterface::exitSafeStart() +{ + ticBase.exitSafeStart(); + if (ticBase.getLastError()) + { + lastErrorMsg = "ExitSafeStart error"; + return false; + } + + lastErrorMsg = "OK"; + return true; +} + +bool TiclibInterface::haltAndHold() +{ + ticBase.haltAndHold(); + if (ticBase.getLastError()) + { + lastErrorMsg = "HaltAndHold error"; + return false; + } + + lastErrorMsg = "OK"; + return true; +} + +bool TiclibInterface::setTargetPosition(int position) +{ + ticBase.setTargetPosition(position); + if (ticBase.getLastError()) + { + lastErrorMsg = "SetTargetPosition error"; + return false; + } + + lastErrorMsg = "OK"; + return true; +} + +bool TiclibInterface::haltAndSetPosition(int position) +{ + ticBase.haltAndSetPosition(position); + if (ticBase.getLastError()) + { + lastErrorMsg = "HaltAndSetPosition error"; + return false; + } + + lastErrorMsg = "OK"; + return true; +} + +bool TiclibInterface::getVariables(TicVariables* vars) +{ + vars->targetPosition = ticBase.getTargetPosition(); + if (ticBase.getLastError()) + { + lastErrorMsg = "GetTargetPosition error"; + return false; + } + + vars->currentPosition = ticBase.getCurrentPosition(); + if (ticBase.getLastError()) + { + lastErrorMsg = "GetCurrentPosition error"; + return false; + } + + + vars->vinVoltage = ticBase.getVinVoltage(); + vars->currentLimit = ticBase.getCurrentLimit(); + vars->energized = ticBase.getEnergized(); + + vars->stepMode = tic_look_up_step_mode_name_ui((int)ticBase.getStepMode()); + vars->operationalState = tic_look_up_operation_state_name_ui((int)ticBase.getOperationState()); + + vars->errorStatus = ticBase.getErrorStatus(); + + lastErrorMsg = "OK"; + return true; +} + diff --git a/indi-ticfocuser/connection/driver_interfaces/TiclibInterface.h b/indi-ticfocuser/connection/driver_interfaces/TiclibInterface.h new file mode 100644 index 000000000..aa0a77870 --- /dev/null +++ b/indi-ticfocuser/connection/driver_interfaces/TiclibInterface.h @@ -0,0 +1,53 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program 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 General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*******************************************************************************/ + +#ifndef TICLIBINTERFACE_H +#define TICLIBINTERFACE_H + +#include "TicDriverInterface.h" +#include + +class TicBase; + +/** + * Interface class (a wrapper) for ticlib + */ +class TiclibInterface: public TicDriverInterface +{ + TicBase& ticBase; + std::string lastErrorMsg; + +public: + + TiclibInterface(TicBase& ticBase): ticBase( ticBase) {} + + bool energize(); + bool deenergize(); + + bool exitSafeStart(); + bool haltAndHold(); + + bool setTargetPosition(int position); + bool haltAndSetPosition(int position); + + bool getVariables(TicVariables*); + + const char* getLastErrorMsg() { return lastErrorMsg.c_str(); } +}; + +#endif // TICLIBINTERFACE_H diff --git a/indi-ticfocuser/connection/ticlib/LICENSE.txt b/indi-ticfocuser/connection/ticlib/LICENSE.txt new file mode 100644 index 000000000..714d2d141 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/LICENSE.txt @@ -0,0 +1,25 @@ +Copyright (c) 2017 Pololu Corporation. For more information, see + +http://www.pololu.com/ +http://forum.pololu.com/ + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. diff --git a/indi-ticfocuser/connection/ticlib/README.md b/indi-ticfocuser/connection/ticlib/README.md new file mode 100644 index 000000000..2782e5ecc --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/README.md @@ -0,0 +1,17 @@ + +This is a modified [tic-arduino](https://github.com/pololu/tic-arduino) library. +Two files: tic_internal.h and tic_names.c are copied from [tic-usb library](https://github.com/pololu/pololu-tic-software). + +Goals: +- make it work on Linux, +- make as few changes as possible (to efficiently follow the origin). + +Reasons to use tic-arduino over [tic-usb library](https://github.com/pololu/pololu-tic-software): +- it is more generic than tic-usb library, which supports only USB connection, +- it can be easily extended to support Serial, Bluetooth or I2C, +- it doesn't depend on Pololu [libusbp library](https://github.com/pololu/libusbp), +- it is light and comes without external dependencies (except regular libusb for USB connection). + +Modified Pololu createdfiles are LICENSE.txt, TicBase.h and TicBase.cpp. TicBase.h and .cpp are renamed from Tic.h and Tic.cpp to not create conflicts with pololu-tic-software library. + +All changes of code are published on the same license as the original library, which is MIT. diff --git a/indi-ticfocuser/connection/ticlib/Stream.h b/indi-ticfocuser/connection/ticlib/Stream.h new file mode 100644 index 000000000..1945de820 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/Stream.h @@ -0,0 +1,42 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + + +#pragma once + +#include +#include + +class Stream +{ +public: + virtual ~Stream() {} + virtual size_t write(uint8_t byte) = 0; + virtual size_t readBytes(char *buffer, size_t length) = 0; + virtual size_t readBytes(uint8_t *buffer, size_t length) { + return readBytes((char *) buffer, length); + } +}; diff --git a/indi-ticfocuser/connection/ticlib/StreamBT.cpp b/indi-ticfocuser/connection/ticlib/StreamBT.cpp new file mode 100644 index 000000000..ab4831d06 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/StreamBT.cpp @@ -0,0 +1,153 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian BaberowbtSocketi + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + +#include "StreamBT.h" + +#include + +#include +#include + +StreamBT::StreamBT(): + btSocket(-1) +{ +} + +StreamBT::~StreamBT() +{ + disconnect(); +} + +bool StreamBT::reconnect() +{ + if (btMacAddress.empty()) + return false; + + struct sockaddr_rc laddr, raddr; + + laddr.rc_family = AF_BLUETOOTH; + laddr.rc_channel = 0; + str2ba("00:00:00:00:00:00",&laddr.rc_bdaddr); + //bacpy(&laddr.rc_bdaddr,BDADDR_ANY); + + raddr.rc_family = AF_BLUETOOTH; + raddr.rc_channel = 1; + str2ba(btMacAddress.c_str(),&raddr.rc_bdaddr); + + btSocket = ::socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); + if (btSocket < 0) + return false; + + timeval timeout = { 1, 0 }; + if (setsockopt(btSocket, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(timeout))) { + close(btSocket); + return false; + } + + if (setsockopt(btSocket, SOL_SOCKET, SO_SNDTIMEO, (char *) &timeout, sizeof(timeout))) { + close(btSocket); + return false; + } + + if (::bind(btSocket, (struct sockaddr *) &laddr, sizeof(laddr)) < 0) { + close(btSocket); + return false; + } + + if (::connect(btSocket, (struct sockaddr *) &raddr, sizeof(raddr)) < 0) { + close(btSocket); + return false; + } + + return true; +} + +bool StreamBT::connect(const char* btMacAddress) +{ + StreamBT::btMacAddress = btMacAddress; + return reconnect(); +} + +void StreamBT::disconnect() +{ + if (btSocket >= 0) + close(btSocket); + btSocket = -1; +} + +size_t StreamBT::write(uint8_t byte) +{ + ssize_t c = 0; + int numZeros = 0; // safety counter, if we read 5x0 in a row, we eject + + while (numZeros < 3) + { + c = ::write(btSocket,&byte,sizeof(byte)); + + if (c > 0) + break; + + reconnect(); + usleep(10); + ++numZeros; + } + + return c; +} + +size_t StreamBT::readBytes(char *buffer, size_t length) +{ + size_t readC = 0; + int numZeros = 0; // safety counter, if we read 5x0 in a row, we eject + + // try to read until we receive enough bytes + while (readC < length && numZeros < 5) + { + + if (readC > 0) + usleep(10); + + ssize_t c = ::read(btSocket, buffer + readC, length - readC); + + // BT got disconnected + if (c < 0) { + reconnect(); + } + + if (c > 0) + { + readC += c; + numZeros = 0; + } + else + { + ++numZeros; + } + } + + return readC; +} + diff --git a/indi-ticfocuser/connection/ticlib/StreamBT.h b/indi-ticfocuser/connection/ticlib/StreamBT.h new file mode 100644 index 000000000..0b9870527 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/StreamBT.h @@ -0,0 +1,48 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + + +#pragma once + +#include "Stream.h" +#include + +class StreamBT: public Stream +{ + int btSocket; + std::string btMacAddress; + +public: + StreamBT(); + ~StreamBT(); + + bool connect(const char* btMacAddress); + bool reconnect(); + void disconnect(); + + size_t write(uint8_t byte); + size_t readBytes(char *buffer, size_t length); +}; diff --git a/indi-ticfocuser/connection/ticlib/StreamSerial.cpp b/indi-ticfocuser/connection/ticlib/StreamSerial.cpp new file mode 100644 index 000000000..86c4a502b --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/StreamSerial.cpp @@ -0,0 +1,75 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian BaberowbtSocketi + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + +#include "StreamSerial.h" + +#include + + +size_t StreamSerial::write(uint8_t byte) +{ + return ::write(fd,&byte,sizeof(byte)); +} + +size_t StreamSerial::readBytes(char *buffer, size_t length) +{ + size_t readC = 0; + int numZeros = 0; // safety counter, if we read 5x0 in a row, we eject + + // try to read until we receive enough bytes + while (readC < length && numZeros < 5) + { + + if (readC > 0) + usleep(10); + + size_t c = ::read(fd, buffer + readC, length - readC); + readC += c; + + if (c > 0) + { + readC += c; + numZeros = 0; + } + else + { + ++numZeros; + } + } + + return readC; +} + + + + + + + + + + + diff --git a/indi-ticfocuser/connection/ticlib/StreamSerial.h b/indi-ticfocuser/connection/ticlib/StreamSerial.h new file mode 100644 index 000000000..37fdffe9a --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/StreamSerial.h @@ -0,0 +1,44 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + + +#pragma once + +#include "Stream.h" + +#include +#include + +class StreamSerial: public Stream +{ + const int& fd; + +public: + StreamSerial(const int& fd): fd( fd) {} + + size_t write(uint8_t byte); + size_t readBytes(char *buffer, size_t length); +}; diff --git a/indi-ticfocuser/connection/ticlib/TicBase.cpp b/indi-ticfocuser/connection/ticlib/TicBase.cpp new file mode 100644 index 000000000..144b63663 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/TicBase.cpp @@ -0,0 +1,178 @@ +// Copyright (C) Pololu Corporation. See LICENSE.txt for details. + +#include "TicBase.h" +#include + +static const uint16_t Tic03aCurrentTable[33] = +{ + 0, + 1, + 174, + 343, + 495, + 634, + 762, + 880, + 990, + 1092, + 1189, + 1281, + 1368, + 1452, + 1532, + 1611, + 1687, + 1762, + 1835, + 1909, + 1982, + 2056, + 2131, + 2207, + 2285, + 2366, + 2451, + 2540, + 2634, + 2734, + 2843, + 2962, + 3093, +}; + +void TicBase::setCurrentLimit(uint16_t limit) +{ + uint8_t code = 0; + + if (product == TicProduct::T500) + { + for (uint8_t i = 0; i < 33; i++) + { + if (Tic03aCurrentTable[i] <= limit) + { + code = i; + } + else + { + break; + } + } + } + else if (product == TicProduct::T249) + { + code = limit / TicT249CurrentUnits; + } + else if (product == TicProduct::Tic36v4) + { + if (limit < 72) { code = 0; } + else if (limit >= 9095) { code = 127; } + else + { + code = ((uint32_t)limit * 768 - 55000 / 2) / 55000; + if (code < 127 && (((uint32_t)55000 * (code + 1) + 384) / 768) <= limit) + { + code++; + } + } + } + else + { + code = limit / TicCurrentUnits; + } + + commandW7(TicCommand::SetCurrentLimit, code); +} + +uint16_t TicBase::getCurrentLimit() +{ + uint8_t code = getVar8(VarOffset::CurrentLimit); + if (product == TicProduct::T500) + { + if (code > 32) { code = 32; } + return Tic03aCurrentTable[code]; + } + else if (product == TicProduct::T249) + { + return code * TicT249CurrentUnits; + } + else if (product == TicProduct::Tic36v4) + { + return ((uint32_t)55000 * code + 384) / 768; + } + else + { + return code * TicCurrentUnits; + } +} + +/**** TicSerial ****/ + +void TicSerial::commandW32(TicCommand cmd, uint32_t val) +{ + sendCommandHeader(cmd); + + // byte with MSbs: + // bit 0 = MSb of first (least significant) data byte + // bit 1 = MSb of second data byte + // bit 2 = MSb of third data byte + // bit 3 = MSb of fourth (most significant) data byte + serialW7(((val >> 7) & 1) | + ((val >> 14) & 2) | + ((val >> 21) & 4) | + ((val >> 28) & 8)); + + serialW7(val >> 0); // least significant byte with MSb cleared + serialW7(val >> 8); + serialW7(val >> 16); + serialW7(val >> 24); // most significant byte with MSb cleared + + _lastError = 0; +} + +void TicSerial::commandW7(TicCommand cmd, uint8_t val) +{ + sendCommandHeader(cmd); + serialW7(val); + + _lastError = 0; +} + +void TicSerial::getSegment(TicCommand cmd, uint8_t offset, + uint8_t length, void * buffer) +{ + length &= 0x3F; + sendCommandHeader(cmd); + serialW7(offset & 0x7F); + serialW7(length | (offset >> 1 & 0x40)); + + uint8_t byteCount = _stream->readBytes((uint8_t *)buffer, length); + if (byteCount != length) + { + _lastError = 50; + + // Set the buffer bytes to 0 so the program will not use an uninitialized + // variable. + memset(buffer, 0, length); + return; + } + + _lastError = 0; +} + +void TicSerial::sendCommandHeader(TicCommand cmd) +{ + if (_deviceNumber == 255) + { + // Compact protocol + _stream->write((uint8_t)cmd); + } + else + { + // Pololu protocol + _stream->write(0xAA); + serialW7(_deviceNumber); + serialW7((uint8_t)cmd); + } + _lastError = 0; +} + diff --git a/indi-ticfocuser/connection/ticlib/TicBase.h b/indi-ticfocuser/connection/ticlib/TicBase.h new file mode 100644 index 000000000..da55a105b --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/TicBase.h @@ -0,0 +1,1419 @@ +// Copyright (C) Pololu Corporation. See LICENSE.txt for details. + +/// \file Tic.h +/// +/// This is the main header file for the Tic Stepper Motor Controller library +/// for Arduino. +/// +/// For more information about the library, see the main repository at: +/// https://github.com/pololu/tic-arduino + +#pragma once + +#include +#include +#include "Stream.h" + +enum class TicProduct +{ + Unknown = 0, + T825 = 1, + T834 = 2, + T500 = 3, + T249 = 4, + Tic36v4 = 5, +}; + +/// This constant is used by the library to convert between milliamps and the +/// Tic's native current unit, which is 32 mA. This is only valid for the Tic +/// T825 and Tic T834. +const uint8_t TicCurrentUnits = 32; + +/// This constant is used by the library to convert between milliamps and the +/// Tic T249 native current unit, which is 40 mA. +const uint8_t TicT249CurrentUnits = 40; + +/// This is used to represent a null or missing value for some of the Tic's +/// 16-bit input variables. +const uint16_t TicInputNull = 0xFFFF; + +/// This enum defines the Tic's error bits. See the "Error handling" section of +/// the Tic user's guide for more information about what these errors mean. +/// +/// See TicBase::getErrorStatus() and TicBase::getErrorsOccurred(). +enum class TicError +{ + IntentionallyDeenergized = 0, + MotorDriverError = 1, + LowVin = 2, + KillSwitch = 3, + RequiredInputInvalid = 4, + SerialError = 5, + CommandTimeout = 6, + SafeStartViolation = 7, + ErrLineHigh = 8, + SerialFraming = 16, + RxOverrun = 17, + Format = 18, + Crc = 19, + EncoderSkip = 20, +}; + +/// This enum defines the Tic command codes which are used for its serial, I2C, +/// and USB interface. These codes are used by the library and you should not +/// need to use them. +enum class TicCommand +{ + SetTargetPosition = 0xE0, + SetTargetVelocity = 0xE3, + HaltAndSetPosition = 0xEC, + HaltAndHold = 0x89, + GoHome = 0x97, + ResetCommandTimeout = 0x8C, + Deenergize = 0x86, + Energize = 0x85, + ExitSafeStart = 0x83, + EnterSafeStart = 0x8F, + Reset = 0xB0, + ClearDriverError = 0x8A, + SetSpeedMax = 0xE6, + SetStartingSpeed = 0xE5, + SetAccelMax = 0xEA, + SetDecelMax = 0xE9, + SetStepMode = 0x94, + SetCurrentLimit = 0x91, + SetDecayMode = 0x92, + SetAgcOption = 0x98, + GetVariable = 0xA1, + GetVariableAndClearErrorsOccurred = 0xA2, + GetSetting = 0xA8, +}; + +/// This enum defines the possible operation states for the Tic. +/// +/// See TicBase::getOperationState(). +enum class TicOperationState +{ + Reset = 0, + Deenergized = 2, + SoftError = 4, + WaitingForErrLine = 6, + StartingUp = 8, + Normal = 10, +}; + +/// This enum defines the possible planning modes for the Tic's step generation +/// code. +/// +/// See TicBase::getPlanningMode(). +enum class TicPlanningMode +{ + Off = 0, + TargetPosition = 1, + TargetVelocity = 2, +}; + +/// This enum defines the possible causes of a full microcontroller reset for +/// the Tic. +/// +/// See TicBase::getDeviceReset(). +enum class TicReset +{ + PowerUp = 0, + Brownout = 1, + ResetLine = 2, + Watchdog = 4, + Software = 8, + StackOverflow = 16, + StackUnderflow = 32, +}; + +/// This enum defines the possible decay modes. +/// +/// See TicBase::getDecayMode() and TicBase::setDecayMode(). +enum class TicDecayMode +{ + /// This specifies "Mixed" decay mode on the Tic T825 + /// and "Mixed 50%" on the Tic T824. + Mixed = 0, + + /// This specifies "Slow" decay mode. + Slow = 1, + + /// This specifies "Fast" decay mode. + Fast = 2, + + /// This is the same as TicDecayMode::Mixed, but better expresses your + /// intent if you want to use "Mixed 50%' mode on a Tic T834. + Mixed50 = 0, + + /// This specifies "Mixed 25%" decay mode on the Tic T824 + /// and is the same as TicDecayMode::Mixed on the Tic T825. + Mixed25 = 3, + + /// This specifies "Mixed 75%" decay mode on the Tic T824 + /// and is the same as TicDecayMode::Mixed on the Tic T825. + Mixed75 = 4, +}; + +/// This enum defines the possible step modes. +/// +/// See TicBase::getStepMode() and TicBase::setStepMode(). +enum class TicStepMode +{ + Full = 0, + Half = 1, + + Microstep1 = 0, + Microstep2 = 1, + Microstep4 = 2, + Microstep8 = 3, + Microstep16 = 4, + Microstep32 = 5, + Microstep2_100p = 6, + Microstep64 = 7, + Microstep128 = 8, + Microstep256 = 9, +}; + +/// This enum defines possible AGC modes. +/// +/// See TicBase::setAgcMode() and TicBase::getAgcMode(). +enum class TicAgcMode +{ + Off = 0, + On = 1, + ActiveOff = 2, +}; + +/// This enum defines possible AGC buttom current limit percentages. +/// +/// See TicBase::setAgcBottomCurrentLimit() and +/// TicBase:getAgcBottomCurrentLimit(). +enum class TicAgcBottomCurrentLimit +{ + P45 = 0, + P50 = 1, + P55 = 2, + P60 = 3, + P65 = 4, + P70 = 5, + P75 = 6, + P80 = 7, +}; + +/// This enum defines possible AGC current boost steps values. +/// +/// See TicBase::setAgcCurrentBoostSteps() and +/// TicBase::getAgcCurrentBoostSteps(). +enum class TicAgcCurrentBoostSteps +{ + S5 = 0, + S7 = 1, + S9 = 2, + S11 = 3, +}; + +/// This enuam defines possible AGC frequency limit values. +/// +/// See TicBase::setAgcFrequencyLimit() and TicBase::getAgcFrequencyLimit(). +enum class TicAgcFrequencyLimit +{ + Off = 0, + F225Hz = 1, + F450Hz = 2, + F675Hz = 3, +}; + +/// This enum defines the Tic's control pins. +enum class TicPin +{ + SCL = 0, + SDA = 1, + TX = 2, + RX = 3, + RC = 4, +}; + +/// This enum defines the Tic's pin states. +/// +/// See TicBase::getPinState(). +enum class TicPinState +{ + HighImpedance = 0, + InputPullUp = 1, + OutputLow = 2, + OutputHigh = 3, +}; + +/// This enum defines the possible states of the Tic's main input. +enum class TicInputState +{ + /// The input is not ready yet. More samples are needed, or a command has not + /// been received yet. + NotReady = 0, + + /// The input is invalid. + Invalid = 1, + + /// The input is valid and is telling the Tic to halt the motor. + Halt = 2, + + /// The input is valid and is telling the Tic to go to a target position, + /// which you can get with TicBase::getInputAfterScaling(). + Position = 3, + + /// The input is valid and is telling the Tic to go to a target velocity, + /// which you can get with TicBase::getInputAfterScaling(). + Velocity = 4, +}; + +/// This enum defines the bits in the Tic's Misc Flags 1 register. You should +/// not need to use this directly. See TicBase::getEnergized() and +/// TicBase::getPositionUncertain(). +enum class TicMiscFlags1 +{ + Energized = 0, + PositionUncertain = 1, + ForwardLimitActive = 2, + ReverseLimitActive = 3, + HomingActive = 4, +}; + +/// This enum defines possible motor driver errors for the Tic T249. +/// +/// See TicBase::getLastMotorDriverError(). +enum class TicMotorDriverError +{ + None = 0, + OverCurrent = 1, + OverTemperature = 2, +}; + +/// This enum defines the bits in the "Last HP driver errors" variable. +/// +/// See TicBase::getLastHpDriverErrors(). +enum class TicHpDriverError +{ + OverTemperature = 0, + OverCurrentA = 1, + OverCurrentB = 2, + PreDriverFaultA = 3, + PreDriverFaultB = 4, + UnderVoltage = 5, + Verify = 7, +}; + +/// This is a base class used to represent a connection to a Tic. This class +/// provides high-level functions for sending commands to the Tic and reading +/// data from it. +/// +/// See the subclasses of this class, TicSerial and TicI2C. +class TicBase +{ +public: + + virtual ~TicBase() {} + + /// You can use this function to specify what type of Tic you are using. + /// + /// Example usage (pick one of the following): + /// ``` + /// tic.setProduct(TicProduct::T500); + /// tic.setProduct(TicProduct::T834); + /// tic.setProduct(TicProduct::T825); + /// tic.setProduct(TicProduct::T249); + /// tic.setProduct(TicProduct::Tic36v4); + /// ``` + /// + /// This changes the behavior of the setCurrentLimit() function. + void setProduct(TicProduct product) + { + this->product = product; + } + + /// Sets the target position of the Tic, in microsteps. + /// + /// Example usage: + /// ``` + /// tic.setTargetPosition(100); + /// ``` + /// + /// This function sends a "Set target position" to the Tic. If the Control + /// mode is set to Serial/I2C/USB, the Tic will start moving the motor to + /// reach the target position. If the control mode is something other than + /// Serial, this command will be silently ignored. + /// + /// See also getTargetPosition(). + void setTargetPosition(int32_t position) + { + commandW32(TicCommand::SetTargetPosition, position); + } + + /// Sets the target velocity of the Tic, in microsteps per 10000 seconds. + /// + /// Example usage: + /// ``` + /// tic.setTargetVelocity(-1800000); // -180 steps per second + /// ``` + /// + /// This function sends a "Set target velocity" command to the Tic. If the + /// Control mode is set to Serial/I2C/USB, the Tic will start accelerating or + /// decelerating to reach the target velocity. + /// + /// If the control mode is something other than Serial, this command will be + /// silently ignored. + /// + /// See also getTargetVelocity(). + void setTargetVelocity(int32_t velocity) + { + commandW32(TicCommand::SetTargetVelocity, velocity); + } + + /// Stops the motor abruptly without respecting the deceleration limit and + /// sets the "Current position" variable, which represents where the Tic + /// currently thinks the motor's output is. + /// + /// Example usage: + /// ``` + /// tic.haltAndSetPosition(0); + /// ``` + /// + /// This function sends a "Halt and set position" command to the Tic. Besides + /// stopping the motor and setting the current position, this command also + /// clears the "Postion uncertain" flag, sets the "Input state" to "halt", and + /// clears the "Input after scaling" variable. + /// + /// If the control mode is something other than Serial, this command will + /// be silently ignored. + void haltAndSetPosition(int32_t position) + { + commandW32(TicCommand::HaltAndSetPosition, position); + } + + /// Stops the motor abruptly without respecting the deceleration limit. + /// + /// Example usage: + /// ``` + /// tic.haltAndHold(); + /// ``` + /// + /// This function sends a "Halt and hold" command to the Tic. Besides stopping + /// the motor, this command also sets the "Position uncertain" flag (because + /// the abrupt stop might cause steps to be missed), sets the "Input state" to + /// "halt", and clears the "Input after scaling" variable. + /// + /// If the control mode is something other than Serial/I2C/USB, ths + /// command will be silently ignored. + /// + /// See also deenergize(). + void haltAndHold() + { + commandQuick(TicCommand::HaltAndHold); + } + + /// Tells the Tic to start its homing procedure in the reverse direction. + /// + /// See the "Homing" section of the Tic user's guide for details. + /// + /// See also goHomeForward(). + void goHomeReverse() + { + commandW7(TicCommand::GoHome, 0); + } + + /// Tells the Tic to start its homing procedure in the forward direction. + /// + /// See the "Homing" section of the Tic user's guide for details. + /// + /// See also goHomeReverse(). + void goHomeForward() + { + commandW7(TicCommand::GoHome, 1); + } + + /// Prevents the "Command timeout" error from happening for some time. + /// + /// Example usage: + /// ``` + /// tic.resetCommandTimeout(); + /// ``` + /// + /// This function sends a "Reset command timeout" command to the Tic. + void resetCommandTimeout() + { + commandQuick(TicCommand::ResetCommandTimeout); + } + + /// De-energizes the stepper motor coils. + /// + /// Example usage: + /// ``` + /// tic.deenergize(); + /// ``` + /// + /// This function sends a De-energize command to the Tic, causing it to disable + /// its stepper motor driver. The motor will stop moving and consuming power. + /// The Tic will set the "Intentionally de-energized" error bit, turn on its + /// red LED, and drive its ERR line high. This command also sets the + /// "Position uncertain" flag (because the Tic is no longer in control of the + /// motor's position). + /// + /// Note that the Energize command, which can be sent with energize(), will + /// undo the effect of this command (except it will leave the "Position + /// uncertain" flag set) and could make the system start up again. + /// + /// See also haltAndHold(). + void deenergize() + { + commandQuick(TicCommand::Deenergize); + } + + /// Sends the Energize command. + /// + /// Example usage: + /// ``` + /// tic.energize(); + /// ``` + /// + /// This function sends an Energize command to the Tic, clearing the + /// "Intentionally de-energized" error bit. If there are no other errors, + /// this allows the system to start up. + void energize() + { + commandQuick(TicCommand::Energize); + } + + /// Sends the "Exit safe start" command. + /// + /// Example usage: + /// ``` + /// tic.exitSafeStart(); + /// ``` + /// + /// In Serial/I2C/USB control mode, this command causes the safe start + /// violation error to be cleared for 200 ms. If there are no other errors, + /// this allows the system to start up. + void exitSafeStart() + { + commandQuick(TicCommand::ExitSafeStart); + } + + /// Sends the "Enter safe start" command. + /// + /// Example usage: + /// ``` + /// tic.enterSafeStart(); + /// ``` + /// + /// This command has no effect if safe-start is disabled in the Tic's settings. + /// + /// In Serial/I2C/USB control mode, this command causes the Tic to stop the + /// motor and set its safe start violation error bit. An "Exit safe start" + /// command is required before the Tic will move the motor again. + /// + /// See the Tic user's guide for information about what this command does in + /// the other control modes. + void enterSafeStart() + { + commandQuick(TicCommand::EnterSafeStart); + } + + /// Sends the Reset command. + /// + /// Example usage: + /// ``` + /// tic.reset(); + /// ``` + /// + /// This command makes the Tic forget most parts of its current state. For + /// more information, see the Tic user's guide. + void reset() + { + commandQuick(TicCommand::Reset); + + // The Tic's serial and I2C interfaces will be unreliable for a brief period + // after the Tic receives the Reset command, so we delay 10 ms here. + usleep(10); + } + + /// Attempts to clear a motor driver error. + /// + /// Example usage: + /// ``` + /// tic.clearDriverError(); + /// ``` + /// + /// This function sends a "Clear driver error" command to the Tic. For more + /// information, see the Tic user's guide. + void clearDriverError() + { + commandQuick(TicCommand::ClearDriverError); + } + + /// Temporarily sets the maximum speed, in units of steps per 10000 seconds. + /// + /// Example usage: + /// ``` + /// tic.setMaxSpeed(5550000); // 555 steps per second + /// ``` + /// + /// This function sends a "Set max speed" command to the Tic. For more + /// information, see the Tic user's guide. + /// + /// See also getMaxSpeed(). + void setMaxSpeed(uint32_t speed) + { + commandW32(TicCommand::SetSpeedMax, speed); + } + + /// Temporarily sets the starting speed, in units of steps per 10000 seconds. + /// + /// Example usage: + /// ``` + /// tic.setStartingSpeed(500000); // 50 steps per second + /// ``` + /// + /// This function sends a "Set starting speed" command to the Tic. For more + /// information, see the Tic user's guide. + /// + /// See also getStartingSpeed(). + void setStartingSpeed(uint32_t speed) + { + commandW32(TicCommand::SetStartingSpeed, speed); + } + + /// Temporarily sets the maximum acceleration, in units of steps per second + /// per 100 seconds. + /// + /// Example usage: + /// ``` + /// tic.setMaxAccel(10000); // 100 steps per second per second + /// ``` + /// + /// This function sends a "Set max acceleration" command to the Tic. For more + /// information, see the Tic user's guide. + /// + /// See also getMaxAccel(). + void setMaxAccel(uint32_t accel) + { + commandW32(TicCommand::SetAccelMax, accel); + } + + /// Temporarily sets the maximum deceleration, in units of steps per second + /// per 100 seconds. + /// + /// Example usage: + /// ``` + /// tic.setMaxDecel(10000); // 100 steps per second per second + /// ``` + /// + /// This function sends a "Set max deceleration" command to the Tic. For more + /// information, see the Tic user's guide. + /// + /// See also getMaxDecel(). + void setMaxDecel(uint32_t decel) + { + commandW32(TicCommand::SetDecelMax, decel); + } + + /// Temporarily sets the stepper motor's step mode, which defines how many + /// microsteps correspond to one full step. + /// + /// Example usage: + /// ``` + /// tic.setStepMode(TicStepMode::Microstep8); + /// ``` + /// + /// This function sends a "Set step mode" command to the Tic. For more + /// information, see the Tic user's guide. + /// + /// See also getStepMode(). + void setStepMode(TicStepMode mode) + { + commandW7(TicCommand::SetStepMode, (uint8_t)mode); + } + + /// Temporarily sets the stepper motor coil current limit in milliamps. If + /// the desired current limit is not available, this function uses the closest + /// current limit that is lower than the desired one. + /// + /// When converting the current limit from milliamps to a code to send to the + /// Tic, this function needs to know what kind of Tic you are using. By + /// default, this function assumes you are using a Tic T825 or Tic T834. If + /// you are using a different kind of Tic, we recommend calling setProduct() + /// some time before calling setCurrentLimit(). + /// + /// Example usage: + /// ``` + /// tic.setCurrentLimit(500); // 500 mA + /// ``` + /// + /// This function sends a "Set current limit" command to the Tic. For more + /// information about this command and how to choose a good current limit, see + /// the Tic user's guide. + /// + /// See also getCurrentLimit(). + void setCurrentLimit(uint16_t limit); + + /// Temporarily sets the stepper motor driver's decay mode. + /// + /// Example usage: + /// ``` + /// tic.setDecayMode(TicDecayMode::Slow); + /// ``` + /// + /// The decay modes are documented in the Tic user's guide. + /// + /// See also getDecayMode(). + void setDecayMode(TicDecayMode mode) + { + commandW7(TicCommand::SetDecayMode, (uint8_t)mode); + } + + /// Temporarily sets the AGC mode. + /// + /// This is only valid for the Tic T249. + /// + /// See also getAgcMode(). + void setAgcMode(TicAgcMode mode) + { + commandW7(TicCommand::SetAgcOption, (uint8_t)mode & 0xF); + } + + /// Temporarily sets the AGC bottom current limit. + /// + /// This is only valid for the Tic T249. + /// + /// See also getAgcBottomCurrentLimit(). + void setAgcBottomCurrentLimit(TicAgcBottomCurrentLimit limit) + { + commandW7(TicCommand::SetAgcOption, 0x10 | ((uint8_t)limit & 0xF)); + } + + /// Temporarily sets the AGC current boost steps. + /// + /// This is only valid for the Tic T249. + /// + /// See also getAgcCurrentBoostSteps(). + void setAgcCurrentBoostSteps(TicAgcCurrentBoostSteps steps) + { + commandW7(TicCommand::SetAgcOption, 0x20 | ((uint8_t)steps & 0xF)); + } + + /// Temporarily sets the AGC frequency limit. + /// + /// This is only valid for the Tic T249. + /// + /// See also getAgcFrequencyLimit(). + void setAgcFrequencyLimit(TicAgcFrequencyLimit limit) + { + commandW7(TicCommand::SetAgcOption, 0x30 | ((uint8_t)limit & 0xF)); + } + + /// Gets the Tic's current operation state, which indicates whether it is + /// operating normally or in an error state. + /// + /// Example usage: + /// ``` + /// if (tic.getOperationState() != TicOperationState::Normal) + /// { + /// // There is an error, or the Tic is starting up. + /// } + /// ``` + /// + /// For more information, see the "Error handling" section of the Tic user's + /// guide. + TicOperationState getOperationState() + { + return (TicOperationState)getVar8(VarOffset::OperationState); + } + + /// Returns true if the motor driver is energized (trying to send current to + /// its outputs). + bool getEnergized() + { + return getVar8(VarOffset::MiscFlags1) >> + (uint8_t)TicMiscFlags1::Energized & 1; + } + + /// Gets a flag that indicates whether there has been external confirmation that + /// the value of the Tic's "Current position" variable is correct. + /// + /// For more information, see the "Error handling" section of the Tic user's + /// guide. + bool getPositionUncertain() + { + return getVar8(VarOffset::MiscFlags1) >> + (uint8_t)TicMiscFlags1::PositionUncertain & 1; + } + + /// Returns true if one of the forward limit switches is active. + bool getForwardLimitActive() + { + return getVar8(VarOffset::MiscFlags1) >> + (uint8_t)TicMiscFlags1::ForwardLimitActive & 1; + } + + /// Returns true if one of the reverse limit switches is active. + bool getReverseLimitActive() + { + return getVar8(VarOffset::MiscFlags1) >> + (uint8_t)TicMiscFlags1::ReverseLimitActive & 1; + } + + /// Returns true if the Tic's homing procedure is running. + bool getHomingActive() + { + return getVar8(VarOffset::MiscFlags1) >> + (uint8_t)TicMiscFlags1::HomingActive & 1; + } + + /// Gets the errors that are currently stopping the motor. + /// + /// Each bit in the returned register represents a different error. The bits + /// are defined in ::TicError enum. + /// + /// Example usage: + /// ``` + /// uint16_t errors = tic.getErrorStatus(); + /// if (errors & (1 << (uint8_t)TicError::LowVin)) + /// { + /// // handle loss of power + /// } + /// ``` + uint16_t getErrorStatus() + { + return getVar16(VarOffset::ErrorStatus); + } + + /// Gets the errors that have occurred since the last time this function was called. + /// + /// Note that the Tic Control Center constantly clears the bits in this + /// register, so if you are running the Tic Control Center then you will not + /// be able to reliably detect errors with this function. + /// + /// Each bit in the returned register represents a different error. The bits + /// are defined in ::TicError enum. + /// + /// Example usage: + /// ``` + /// uint32_t errors = tic.getErrorsOccurred(); + /// if (errors & (1 << (uint8_t)TicError::MotorDriverError)) + /// { + /// // handle a motor driver error + /// } + /// ``` + uint32_t getErrorsOccurred() + { + uint32_t result; + getSegment(TicCommand::GetVariableAndClearErrorsOccurred, + VarOffset::ErrorsOccurred, 4, &result); + return result; + } + + /// Returns the current planning mode for the Tic's step generation code. + /// + /// This tells us whether the Tic is sending steps, and if it is sending + /// steps, tells us whether it is in Target Position or Target Velocity mode. + /// + /// Example usage: + /// ``` + /// if (tic.getPlanningMode() == TicPlanningMode::TargetPosition) + /// { + /// // The Tic is moving the stepper motor to a target position, or has + /// // already reached it and is at rest. + /// } + /// ``` + TicPlanningMode getPlanningMode() + { + return (TicPlanningMode)getVar8(VarOffset::PlanningMode); + } + + /// Gets the target position, in microsteps. + /// + /// This is only relevant if the planning mode from getPlanningMode() is + /// TicPlanningMode::Position. + /// + /// See also setTargetPosition(). + int32_t getTargetPosition() + { + return getVar32(VarOffset::TargetPosition); + } + + /// Gets the target velocity, in microsteps per 10000 seconds. + /// + /// This is only relevant if the planning mode from getPlanningMode() is + /// TicPlanningMode::Velocity. + /// + /// See also setTargetVelocity(). + int32_t getTargetVelocity() + { + return getVar32(VarOffset::TargetVelocity); + } + + /// Gets the current maximum speed, in microsteps per 10000 seconds. + /// + /// This is the current value, which could differ from the value in the Tic's + /// settings. + /// + /// See also setMaxSpeed(). + uint32_t getMaxSpeed() + { + return getVar32(VarOffset::SpeedMax); + } + + /// Gets the starting speed in microsteps per 10000 seconds. + /// + /// This is the current value, which could differ from the value in the + /// Tic's settings. + /// + /// Example usage: + /// ``` + /// uint32_t startingSpeed = tic.getStartingSpeed(); + /// ``` + /// + /// See also setStartingSpeed(). + uint32_t getStartingSpeed() + { + return getVar32(VarOffset::StartingSpeed); + } + + /// Gets the maximum acceleration, in microsteps per second per 100 seconds. + /// + /// This is the current value, which could differ from the value in the Tic's + /// settings. + /// + /// Example usage: + /// ``` + /// uint32_t accelMax = tic.getMaxAccel(); + /// ``` + /// + /// See also setMaxAccel(). + uint32_t getMaxAccel() + { + return getVar32(VarOffset::AccelMax); + } + + /// Gets the maximum deceleration, in microsteps per second per 100 seconds. + /// + /// This is the current value, which could differ from the value in the Tic's + /// settings. + /// + /// Example usage: + /// ``` + /// uint32_t decelMax = tic.getMaxDecel(); + /// ``` + /// + /// See also setMaxDecel(). + uint32_t getMaxDecel() + { + return getVar32(VarOffset::DecelMax); + } + + /// Gets the current position of the stepper motor, in microsteps. + /// + /// Note that this just tracks steps that the Tic has commanded the stepper + /// driver to take; it could be different from the actual position of the + /// motor for various reasons. + /// + /// For an example of how to use this this, see the SerialPositionControl + /// example or the I2CPositionControl exmaple. + /// + /// See also haltAndSetPosition(). + int32_t getCurrentPosition() + { + return getVar32(VarOffset::CurrentPosition); + } + + /// Gets the current velocity of the stepper motor, in microsteps per 10000 + /// seconds. + /// + /// Note that this is just the velocity used in the Tic's step planning + /// algorithms, and it might not correspond to the actual velocity of the + /// motor for various reasons. + /// + /// Example usage: + /// ``` + /// int32_t velocity = tic.getCurrentVelocity(); + /// ``` + int32_t getCurrentVelocity() + { + return getVar32(VarOffset::CurrentVelocity); + } + + /// Gets the acting target position, in microsteps. + /// + /// This is a variable used in the Tic's target position step planning + /// algorithm, and it could be invalid while the motor is stopped. + /// + /// This is mainly intended for getting insight into how the Tic's algorithms + /// work or troubleshooting issues, and most people should not use this. + uint32_t getActingTargetPosition() + { + return getVar32(VarOffset::ActingTargetPosition); + } + + /// Gets the time since the last step, in timer ticks. + /// + /// Each timer tick represents one third of a microsecond. The Tic only + /// updates this variable every 5 milliseconds or so, and it could be invalid + /// while the motor is stopped. + /// + /// This is mainly intended for getting insight into how the Tic's algorithms + /// work or troubleshooting issues, and most people should not use this. + uint32_t getTimeSinceLastStep() + { + return getVar32(VarOffset::TimeSinceLastStep); + } + + /// Gets the cause of the controller's last full microcontroller reset. + /// + /// Example usage: + /// ``` + /// if (tic.getDeviceReset() == TicReset::Brownout) + /// { + /// // There was a brownout reset; the power supply could not keep up. + /// } + /// ``` + /// + /// The Reset command (reset()) does not affect this variable. + TicReset getDeviceReset() + { + return (TicReset)getVar8(VarOffset::DeviceReset); + } + + /// Gets the current measurement of the VIN voltage, in millivolts. + /// + /// Example usage: + /// ``` + /// uint16_t power = tic.getVinVoltage(); + /// ``` + uint16_t getVinVoltage() + { + return getVar16(VarOffset::VinVoltage); + } + + /// Gets the time since the last full reset of the Tic's microcontroller, in + /// milliseconds. + /// + /// Example usage: + /// ``` + /// uint32_t upTime = tic.getUpTime(); + /// ``` + /// + /// A Reset command (reset())does not count. + uint32_t getUpTime() + { + return getVar32(VarOffset::UpTime); + } + + /// Gets the raw encoder count measured from the Tic's RX and TX lines. + /// + /// Example usage: + /// ``` + /// int32_t encoderPosition = getEncoderPosition(); + /// ``` + int32_t getEncoderPosition() + { + return getVar32(VarOffset::EncoderPosition); + } + + /// Gets the raw pulse width measured on the Tic's RC input, in units of + /// twelfths of a microsecond. + /// + /// Returns TicInputNull if the RC input is missing or invalid. + /// + /// Example usage: + /// ``` + /// uint16_t pulseWidth = tic.getRCPulseWidth(); + /// if (pulseWidth != TicInputNull && pulseWidth > 18000) + /// { + /// // Pulse width is greater than 1500 microseconds. + /// } + /// ``` + uint16_t getRCPulseWidth() + { + return getVar16(VarOffset::RCPulseWidth); + } + + /// Gets the analog reading from the specified pin. + /// + /// The reading is left-justified, so 0xFFFF represents a voltage equal to the + /// Tic's 5V pin (approximately 4.8 V). + /// + /// Returns TicInputNull if the analog reading is disabled or not ready. + /// + /// Example usage: + /// ``` + /// uint16_t reading = getAnalogReading(TicPin::SDA); + /// if (reading != TicInputNull && reading < 32768) + /// { + /// // The reading is less than about 2.4 V. + /// } + /// ``` + uint16_t getAnalogReading(TicPin pin) + { + uint8_t offset = VarOffset::AnalogReadingSCL + 2 * (uint8_t)pin; + return getVar16(offset); + } + + /// Gets a digital reading from the specified pin. + /// + /// Returns `true` for high and `false` for low. + /// + /// Example usage: + /// ``` + /// if (tic.getDigitalReading(TicPin::RC)) + /// { + /// // Something is driving the RC pin high. + /// } + /// ``` + bool getDigitalReading(TicPin pin) + { + uint8_t readings = getVar8(VarOffset::DigitalReadings); + return (readings >> (uint8_t)pin) & 1; + } + + /// Gets the current state of a pin, i.e. what kind of input or output it is. + /// + /// Note that the state might be misleading if the pin is being used as a + /// serial or I2C pin. + /// + /// Example usage: + /// + /// ``` + /// if (tic.getPinState(TicPin::SCL) == TicPinState::OutputHigh) + /// { + /// // SCL is driving high. + /// } + /// ``` + TicPinState getPinState(TicPin pin) + { + uint8_t states = getVar8(VarOffset::PinStates); + return (TicPinState)(states >> (2 * (uint8_t)pin) & 0b11); + } + + /// Gets the current step mode of the stepper motor. + /// + /// Example usage: + /// ``` + /// if (tic.getStepMode() == TicStepMode::Microstep8) + /// { + /// // The Tic is currently using 1/8 microsteps. + /// } + /// ``` + TicStepMode getStepMode() + { + return (TicStepMode)getVar8(VarOffset::StepMode); + } + + /// Gets the stepper motor coil current limit in milliamps. + /// + /// This is the value being used now, which could differ from the value in the + /// Tic's settings. + /// + /// Example usage: + /// ``` + /// uint16_t current = tic.getCurrentLimit(); + /// ``` + /// + /// By default, this function assumes you are using a Tic T825 or Tic T834. + /// If you are using a different kind of Tic, we recommend calling + /// setProduct() some time before calling getCurrentLimit(). + /// + /// See also setCurrentLimit(). + uint16_t getCurrentLimit(); + + /// Gets the current decay mode of the stepper motor driver. + /// + /// Example usage: + /// ``` + /// if (tic.getDecayMode() == TicDecayMode::Slow) + /// { + /// // The Tic is in slow decay mode. + /// } + /// ``` + /// + /// See setDecayMode(). + TicDecayMode getDecayMode() + { + return (TicDecayMode)getVar8(VarOffset::DecayMode); + } + + /// Gets the current state of the Tic's main input. + /// + /// Example usage: + /// ``` + /// if (tic.getInputState() == TicInputState::Position) + /// { + /// // The Tic's input is specifying a target position. + /// } + /// ``` + /// + /// See TicInputState for more information. + TicInputState getInputState() + { + return (TicInputState)getVar8(VarOffset::InputState); + } + + /// Gets a variable used in the process that converts raw RC and analog values + /// into a motor position or speed. This is mainly for debugging your input + /// scaling settings in an RC or analog mode. + /// + /// A value of TicInputNull means the input value is not available. + uint16_t getInputAfterAveraging() + { + return getVar16(VarOffset::InputAfterAveraging); + } + + /// Gets a variable used in the process that converts raw RC and analog values + /// into a motor position or speed. This is mainly for debugging your input + /// scaling settings in an RC or analog mode. + /// + /// A value of TicInputNull means the input value is not available. + uint16_t getInputAfterHysteresis() + { + return getVar16(VarOffset::InputAfterHysteresis); + } + + /// Gets the value of the Tic's main input after scaling has been applied. + /// + /// If the input is valid, this number is the target position or target + /// velocity specified by the input. + /// + /// Example usage: + /// ``` + /// if (tic.getInputAfter + /// ``` + /// + /// See also getInputState(). + int32_t getInputAfterScaling() + { + return getVar32(VarOffset::InputAfterScaling); + } + + /// Gets the cause of the last motor driver error. + /// + /// This is only valid for the Tic T249. + TicMotorDriverError getLastMotorDriverError() + { + return (TicMotorDriverError)getVar8(VarOffset::LastMotorDriverError); + } + + /// Gets the AGC mode. + /// + /// This is only valid for the Tic T249. + /// + /// See also setAgcMode(). + TicAgcMode getAgcMode() + { + return (TicAgcMode)getVar8(VarOffset::AgcMode); + } + + /// Gets the AGC bottom current limit. + /// + /// This is only valid for the Tic T249. + /// + /// See also setAgcBottomCurrentLimit(). + TicAgcBottomCurrentLimit getAgcBottomCurrentLimit() + { + return (TicAgcBottomCurrentLimit)getVar8(VarOffset::AgcBottomCurrentLimit); + } + + /// Gets the AGC current boost steps. + /// + /// This is only valid for the Tic T249. + /// + /// See also setAgcCurrentBoostSteps(). + TicAgcCurrentBoostSteps getAgcCurrentBoostSteps() + { + return (TicAgcCurrentBoostSteps)getVar8(VarOffset::AgcCurrentBoostSteps); + } + + /// Gets the AGC frequency limit. + /// + /// This is only valid for the Tic T249. + /// + /// See also setAgcFrequencyLimit(). + TicAgcFrequencyLimit getAgcFrequencyLimit() + { + return (TicAgcFrequencyLimit)getVar8(VarOffset::AgcFrequencyLimit); + } + + /// Gets the "Last HP driver errors" variable. + /// + /// Each bit in this register represents an error. If the bit is 1, the + /// error was one of the causes of the Tic's last motor driver error. + /// + /// This is only valid for the Tic 36v4. + uint8_t getLastHpDriverErrors() + { + return getVar8(VarOffset::LastHpDriverErrors); + } + + /// Gets a contiguous block of settings from the Tic's EEPROM. + /// + /// The maximum length that can be fetched is 15 bytes. + /// + /// Example usage: + /// ``` + /// // Get the Tic's serial device number. + /// uint8_t deviceNumber; + /// tic.getSetting(7, 1, &deviceNumber); + /// ``` + /// + /// This library does not attempt to interpret the settings and say what they + /// mean. If you are interested in how the settings are encoded in the Tic's + /// EEPROM, see the "Settings reference" section of the Tic user's guide. + void getSetting(uint8_t offset, uint8_t length, uint8_t * buffer) + { + getSegment(TicCommand::GetSetting, offset, length, buffer); + } + + /// Returns 0 if the last communication with the device was successful, and + /// non-zero if there was an error. + uint8_t getLastError() + { + return _lastError; + } + +protected: + /// Zero if the last communication with the device was successful, non-zero + /// otherwise. + uint8_t _lastError = 0; + +private: + enum VarOffset + { + OperationState = 0x00, // uint8_t + MiscFlags1 = 0x01, // uint8_t + ErrorStatus = 0x02, // uint16_t + ErrorsOccurred = 0x04, // uint32_t + PlanningMode = 0x09, // uint8_t + TargetPosition = 0x0A, // int32_t + TargetVelocity = 0x0E, // int32_t + StartingSpeed = 0x12, // uint32_t + SpeedMax = 0x16, // uint32_t + DecelMax = 0x1A, // uint32_t + AccelMax = 0x1E, // uint32_t + CurrentPosition = 0x22, // int32_t + CurrentVelocity = 0x26, // int32_t + ActingTargetPosition = 0x2A, // int32_t + TimeSinceLastStep = 0x2E, // uint32_t + DeviceReset = 0x32, // uint8_t + VinVoltage = 0x33, // uint16_t + UpTime = 0x35, // uint32_t + EncoderPosition = 0x39, // int32_t + RCPulseWidth = 0x3D, // uint16_t + AnalogReadingSCL = 0x3F, // uint16_t + AnalogReadingSDA = 0x41, // uint16_t + AnalogReadingTX = 0x43, // uint16_t + AnalogReadingRX = 0x45, // uint16_t + DigitalReadings = 0x47, // uint8_t + PinStates = 0x48, // uint8_t + StepMode = 0x49, // uint8_t + CurrentLimit = 0x4A, // uint8_t + DecayMode = 0x4B, // uint8_t + InputState = 0x4C, // uint8_t + InputAfterAveraging = 0x4D, // uint16_t + InputAfterHysteresis = 0x4F, // uint16_t + InputAfterScaling = 0x51, // uint16_t + LastMotorDriverError = 0x55, // uint8_t + AgcMode = 0x56, // uint8_t + AgcBottomCurrentLimit = 0x57, // uint8_t + AgcCurrentBoostSteps = 0x58, // uint8_t + AgcFrequencyLimit = 0x59, // uint8_t + LastHpDriverErrors = 0xFF, // uint8_t + }; + + uint8_t getVar8(uint8_t offset) + { + uint8_t result; + getSegment(TicCommand::GetVariable, offset, 1, &result); + return result; + } + + uint16_t getVar16(uint8_t offset) + { + uint8_t buffer[2]; + getSegment(TicCommand::GetVariable, offset, 2, &buffer); + return ((uint16_t)buffer[0] << 0) | ((uint16_t)buffer[1] << 8); + } + + uint32_t getVar32(uint8_t offset) + { + uint8_t buffer[4]; + getSegment(TicCommand::GetVariable, offset, 4, buffer); + return ((uint32_t)buffer[0] << 0) | + ((uint32_t)buffer[1] << 8) | + ((uint32_t)buffer[2] << 16) | + ((uint32_t)buffer[3] << 24); + } + + virtual void commandQuick(TicCommand cmd) = 0; + virtual void commandW32(TicCommand cmd, uint32_t val) = 0; + virtual void commandW7(TicCommand cmd, uint8_t val) = 0; + virtual void getSegment(TicCommand cmd, uint8_t offset, + uint8_t length, void * buffer) = 0; + + TicProduct product = TicProduct::Unknown; +}; + +/// Represents a serial connection to a Tic. +/// +/// For the high-level commands you can use on this object, see TicBase. +class TicSerial : public TicBase +{ +public: + /// Creates a new TicSerial object. + /// + /// The `stream` argument should be a hardware or software serial object. + /// This class will store a pointer to it and use it to communicate with the + /// Tic. You should initialize it and set it to use the correct baud rate + /// before sending commands with this class. + /// + /// The `deviceNumber` argument is optional. If it is omitted or 255, the + /// TicSerial object will use the compact protocol. If it is a number between + /// 0 and 127, it specifies the device number to use in Pololu protocol, + /// allowing you to control multiple Tic controllers on a single serial bus. + /// + /// For example, to use the first open hardware serial port to send compact + /// protocol commands to one Tic, write this at the top of your sketch: + /// ``` + /// TicSerial tic(SERIAL_PORT_HARDWARE_OPEN); + /// ``` + /// + /// For example, to use a SoftwareSerial port and send Pololu protocol + /// commands to two different Tic controllers, write this at the top of your sketch: + /// + /// ``` + /// #include + /// SoftwareSerial ticSerial(10, 11); + /// TicSerial tic1(ticSerial, 14); + /// TicSerial tic2(ticSerial, 15); + /// ``` + TicSerial(Stream & stream, uint8_t deviceNumber = 255) : + _stream(&stream), + _deviceNumber(deviceNumber) + { + } + + /// Gets the serial device number specified in the constructor. + uint8_t getDeviceNumber() { return _deviceNumber; } + +private: + Stream * const _stream; + const uint8_t _deviceNumber; + + void commandQuick(TicCommand cmd) { sendCommandHeader(cmd); } + void commandW32(TicCommand cmd, uint32_t val); + void commandW7(TicCommand cmd, uint8_t val); + uint8_t commandR8(TicCommand cmd); + void getSegment(TicCommand cmd, uint8_t offset, + uint8_t length, void * buffer); + + void sendCommandHeader(TicCommand cmd); + void serialW7(uint8_t val) { _stream->write(val & 0x7F); } +}; + diff --git a/indi-ticfocuser/connection/ticlib/TicDefs.cpp b/indi-ticfocuser/connection/ticlib/TicDefs.cpp new file mode 100644 index 000000000..0e9ec71c2 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/TicDefs.cpp @@ -0,0 +1,123 @@ +// Copyright (C) Pololu Corporation. See www.pololu.com for details. + +#include "TicDefs.h" +#include "TicBase.h" + +// copied from tic_protocol.h and modified to use TicBase.h +#define TIC_ERROR_INTENTIONALLY_DEENERGIZED (int)TicError::IntentionallyDeenergized +#define TIC_ERROR_MOTOR_DRIVER_ERROR (int)TicError::MotorDriverError +#define TIC_ERROR_LOW_VIN (int)TicError::LowVin +#define TIC_ERROR_KILL_SWITCH (int)TicError::KillSwitch +#define TIC_ERROR_REQUIRED_INPUT_INVALID (int)TicError::RequiredInputInvalid +#define TIC_ERROR_SERIAL_ERROR (int)TicError::SerialError +#define TIC_ERROR_COMMAND_TIMEOUT (int)TicError::CommandTimeout +#define TIC_ERROR_SAFE_START_VIOLATION (int)TicError::SafeStartViolation +#define TIC_ERROR_ERR_LINE_HIGH (int)TicError::ErrLineHigh +#define TIC_ERROR_SERIAL_FRAMING (int)TicError::SerialFraming +#define TIC_ERROR_SERIAL_RX_OVERRUN (int)TicError::RxOverrun +#define TIC_ERROR_SERIAL_FORMAT (int)TicError::Format +#define TIC_ERROR_SERIAL_CRC (int)TicError::Crc +#define TIC_ERROR_ENCODER_SKIP (int)TicError::EncoderSkip + +#define TIC_STEP_MODE_MICROSTEP1 (int)TicStepMode::Microstep1 +#define TIC_STEP_MODE_MICROSTEP2 (int)TicStepMode::Microstep2 +#define TIC_STEP_MODE_MICROSTEP4 (int)TicStepMode::Microstep4 +#define TIC_STEP_MODE_MICROSTEP8 (int)TicStepMode::Microstep8 +#define TIC_STEP_MODE_MICROSTEP16 (int)TicStepMode::Microstep16 +#define TIC_STEP_MODE_MICROSTEP32 (int)TicStepMode::Microstep32 +#define TIC_STEP_MODE_MICROSTEP2_100P (int)TicStepMode::Microstep2_100p +#define TIC_STEP_MODE_MICROSTEP64 (int)TicStepMode::Microstep64 +#define TIC_STEP_MODE_MICROSTEP128 (int)TicStepMode::Microstep128 +#define TIC_STEP_MODE_MICROSTEP256 (int)TicStepMode::Microstep256 + +#define TIC_OPERATION_STATE_RESET (int)TicOperationState::Reset +#define TIC_OPERATION_STATE_DEENERGIZED (int)TicOperationState::Deenergized +#define TIC_OPERATION_STATE_SOFT_ERROR (int)TicOperationState::SoftError +#define TIC_OPERATION_STATE_WAITING_FOR_ERR_LINE (int)TicOperationState::WaitingForErrLine +#define TIC_OPERATION_STATE_STARTING_UP (int)TicOperationState::StartingUp +#define TIC_OPERATION_STATE_NORMAL (int)TicOperationState::Normal + +// copied from pololu-tic-software/lib/tic_names.c +const tic_name tic_error_names_ui[] = +{ + { "Intentionally de-energized", 1 << TIC_ERROR_INTENTIONALLY_DEENERGIZED }, + { "Motor driver error", 1 << TIC_ERROR_MOTOR_DRIVER_ERROR }, + { "Low VIN", 1 << TIC_ERROR_LOW_VIN }, + { "Kill switch active", 1 << TIC_ERROR_KILL_SWITCH }, + { "Required input invalid", 1 << TIC_ERROR_REQUIRED_INPUT_INVALID }, + { "Serial error", 1 << TIC_ERROR_SERIAL_ERROR }, + { "Command timeout", 1 << TIC_ERROR_COMMAND_TIMEOUT }, + { "Safe start violation", 1 << TIC_ERROR_SAFE_START_VIOLATION }, + { "ERR line high", 1 << TIC_ERROR_ERR_LINE_HIGH }, + { "Serial framing", 1 << TIC_ERROR_SERIAL_FRAMING }, + { "Serial RX overrun", 1 << TIC_ERROR_SERIAL_RX_OVERRUN }, + { "Serial format", 1 << TIC_ERROR_SERIAL_FORMAT }, + { "Serial CRC", 1 << TIC_ERROR_SERIAL_CRC }, + { "Encoder skip", 1 << TIC_ERROR_ENCODER_SKIP }, + { NULL, 0 }, +}; + +// added +const size_t tic_error_names_ui_size = sizeof(tic_error_names_ui)/sizeof(tic_error_names_ui[0]) - 1; + +// copied from pololu-tic-software/lib/tic_names.c +const tic_name tic_step_mode_names_ui[] = +{ + { "Full step", TIC_STEP_MODE_MICROSTEP1 }, + { "1/2 step", TIC_STEP_MODE_MICROSTEP2 }, + { "1/2 step 100%", TIC_STEP_MODE_MICROSTEP2_100P }, + { "1/4 step", TIC_STEP_MODE_MICROSTEP4 }, + { "1/8 step", TIC_STEP_MODE_MICROSTEP8 }, + { "1/16 step", TIC_STEP_MODE_MICROSTEP16 }, + { "1/32 step", TIC_STEP_MODE_MICROSTEP32 }, + { "1/64 step", TIC_STEP_MODE_MICROSTEP64 }, + { "1/128 step", TIC_STEP_MODE_MICROSTEP128 }, + { "1/256 step", TIC_STEP_MODE_MICROSTEP256 }, + { NULL, 0 }, +}; + +// copied from pololu-tic-software/lib/tic_names.c +const tic_name tic_operation_state_names_ui[] = +{ + { "Reset", TIC_OPERATION_STATE_RESET }, + { "De-energized", TIC_OPERATION_STATE_DEENERGIZED }, + { "Soft error", TIC_OPERATION_STATE_SOFT_ERROR }, + { "Waiting for ERR line", TIC_OPERATION_STATE_WAITING_FOR_ERR_LINE }, + { "Starting up", TIC_OPERATION_STATE_STARTING_UP }, + { "Normal", TIC_OPERATION_STATE_NORMAL }, + { NULL, 0 }, +}; + +// copied from pololu-tic-software/lib/tic_names.c +bool tic_code_to_name(const tic_name * table, uint32_t code, const char ** name) +{ + if (!table) { return false; } + + for (const tic_name * p = table; p->name; p++) + { + if (p->code == code) + { + if (name) { *name = p->name; } + return true; + } + } + + return false; +} + +// copied from pololu-tic-software/lib/tic_names.c +const char * tic_look_up_operation_state_name_ui(uint8_t operation_state) +{ + const char * str = "(Unknown)"; + tic_code_to_name(tic_operation_state_names_ui, operation_state, &str); + return str; +} + +// copied from pololu-tic-software/lib/tic_names.c +const char * tic_look_up_step_mode_name_ui(uint8_t step_mode) +{ + const char * str = "(Unknown)"; + tic_code_to_name(tic_step_mode_names_ui, step_mode, &str); + return str; +} + diff --git a/indi-ticfocuser/connection/ticlib/TicDefs.h b/indi-ticfocuser/connection/ticlib/TicDefs.h new file mode 100644 index 000000000..fb4e72cc1 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/TicDefs.h @@ -0,0 +1,34 @@ +// Copyright (C) Pololu Corporation. See www.pololu.com for details. + +#ifndef TICDEFS_H +#define TICDEFS_H + +#include +#include + +// copied from pololu-tic-software/include/tic_protocol.h +// licensed on MIT license +#define TIC_VENDOR_ID 0x1FFB +#define TIC_PRODUCT_ID_T825 0x00B3 +#define TIC_PRODUCT_ID_T834 0x00B5 +#define TIC_PRODUCT_ID_T500 0x00BD +#define TIC_PRODUCT_ID_N825 0x00C3 +#define TIC_PRODUCT_ID_T249 0x00C9 +#define TIC_PRODUCT_ID_36V4 0x00CB + +// copied from pololu-tic-software/tic/tic_internal.h +typedef struct tic_name +{ + const char * name; + uint32_t code; +} tic_name; + +// copied from pololu-tic-software/lib/tic_names.c +extern const tic_name tic_error_names_ui[]; +extern const size_t tic_error_names_ui_size; + +// copied from pololu-tic-software/include/tic.h +const char * tic_look_up_operation_state_name_ui(uint8_t operation_state); +const char * tic_look_up_step_mode_name_ui(uint8_t step_mode); + +#endif // TICDEFS_H diff --git a/indi-ticfocuser/connection/ticlib/TicUsb.cpp b/indi-ticfocuser/connection/ticlib/TicUsb.cpp new file mode 100644 index 000000000..09753beb4 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/TicUsb.cpp @@ -0,0 +1,166 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + +#include "TicUsb.h" +#include "TicDefs.h" + +#include +#include + +static const size_t MAX_SERIAL_NUMBER = 20; // serial number has 8 characters, 20 is super safe + +TicUsb::TicUsb(): + handle(NULL), context(NULL) +{ + _lastError = libusb_init(&context); +} + +TicUsb::~TicUsb() +{ + disconnect(); + + if (context) + libusb_exit(context); + + context = NULL; +} + +void TicUsb::connect(const char* serialNo) +{ + if (!context) + return; + + disconnect(); + + libusb_device** devs = NULL; + _lastError = libusb_get_device_list(context, &devs); + if (_lastError <= 0) + return; + + _lastError = 0; + + size_t serialNoLen = serialNo? strlen(serialNo): 0; + libusb_device** dev = devs; + + for (; *dev != NULL; ++dev) + { + libusb_device_descriptor desc; + _lastError = libusb_get_device_descriptor(*dev, &desc); + if (_lastError) + break; + + if (desc.idVendor != TIC_VENDOR_ID || + (desc.idProduct != TIC_PRODUCT_ID_T825 && + desc.idProduct != TIC_PRODUCT_ID_T834 && + desc.idProduct != TIC_PRODUCT_ID_T500 && + desc.idProduct != TIC_PRODUCT_ID_N825 && + desc.idProduct != TIC_PRODUCT_ID_T249 && + desc.idProduct != TIC_PRODUCT_ID_36V4) ) + { + continue; + } + + if (!desc.iSerialNumber) + continue; + + _lastError = libusb_open(*dev, &handle); + if (_lastError) + { + handle = NULL; + break; + } + + unsigned char devSerial[MAX_SERIAL_NUMBER]; + size_t serialLen = 0; + + serialLen = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, devSerial, MAX_SERIAL_NUMBER); + if (serialLen >= 0 && + (serialNoLen == 0 || + (serialLen == serialNoLen && !strncmp(serialNo,(char*)devSerial,serialLen))) ) + { + serialNumber = (const char*)devSerial; + break; + } + + libusb_close(handle); + handle = NULL; + _lastError = serialLen > 0? 0: serialLen; + } + + libusb_free_device_list(devs,1); + + if (_lastError) + return; + + if (!handle) + _lastError = LIBUSB_ERROR_NO_DEVICE; +} + +void TicUsb::disconnect() +{ + if (handle) + libusb_close(handle); + + handle = NULL; + serialNumber.clear(); +} + +void TicUsb::commandQuick(TicCommand cmd) +{ + _lastError = libusb_control_transfer(handle, 0x40, (uint8_t)cmd, 0, 0, NULL, 0, 0); + _lastError = _lastError > 0? 0: _lastError; +} +void TicUsb::commandW32(TicCommand cmd, uint32_t val) { + + uint16_t wValue = (uint32_t)val; + uint16_t wIndex = (uint32_t)val >> 16; + + _lastError = libusb_control_transfer(handle, 0x40, (uint8_t)cmd, wValue, wIndex, NULL, 0, 0); + _lastError = _lastError > 0? 0: _lastError; +} + +void TicUsb::commandW7(TicCommand cmd, uint8_t val) +{ + _lastError = libusb_control_transfer(handle, 0x40, (uint8_t)cmd, val, 0, NULL, 0, 0); + _lastError = _lastError > 0? 0: _lastError; +} + +void TicUsb::getSegment(TicCommand cmd, uint8_t offset, uint8_t length, void * buffer) +{ + _lastError = libusb_control_transfer(handle, 0xC0, (uint8_t)cmd, 0, offset, (unsigned char*)buffer, length, 0); + + if (_lastError < 0) + return; + else if (_lastError != length) + _lastError = LIBUSB_ERROR_OTHER; + else + _lastError = 0; +} + +const char* TicUsb::getLastErrorMsg() +{ + return libusb_error_name( _lastError); +} diff --git a/indi-ticfocuser/connection/ticlib/TicUsb.h b/indi-ticfocuser/connection/ticlib/TicUsb.h new file mode 100644 index 000000000..5d9cf3847 --- /dev/null +++ b/indi-ticfocuser/connection/ticlib/TicUsb.h @@ -0,0 +1,59 @@ +/******************************************************************************* +TicFocuser +Copyright (C) 2019 Sebastian Baberowski + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +*******************************************************************************/ + +#ifndef TICUSB_H +#define TICUSB_H + +#include "TicBase.h" +#include + +struct libusb_device_handle; +struct libusb_context; + +class TicUsb: public TicBase { + + libusb_device_handle *handle; + libusb_context *context; + std::string serialNumber; + +public: + + TicUsb(); + ~TicUsb(); + + void connect(const char* serialNo); + void disconnect(); + const char* getSerial() { return serialNumber.c_str(); } + + void commandQuick(TicCommand cmd); + void commandW32(TicCommand cmd, uint32_t val); + void commandW7(TicCommand cmd, uint8_t val); + void getSegment(TicCommand cmd, uint8_t offset, uint8_t length, void * buffer); + + const char* getLastErrorMsg(); +}; + +#endif // TICUSB_H \ No newline at end of file diff --git a/indi-ticfocuser/indi_ticfocuser.xml.cmake b/indi-ticfocuser/indi_ticfocuser.xml.cmake new file mode 100644 index 000000000..fd5d1774e --- /dev/null +++ b/indi-ticfocuser/indi_ticfocuser.xml.cmake @@ -0,0 +1,9 @@ + + + + + indi_ticfocuser-ng + @TICFOCUSER_VERSION_MAJOR@.@TICFOCUSER_VERSION_MINOR@ + + +