[tuxdroid-svn] r797 - in api/python/branches: . 0.2 0.2/trunk
Status: Beta
Brought to you by:
ks156
From: remi <c2m...@c2...> - 2007-12-14 13:34:46
|
Author: remi Date: 2007-12-14 14:34:39 +0100 (Fri, 14 Dec 2007) New Revision: 797 Added: api/python/branches/0.2/ api/python/branches/0.2/branches/ api/python/branches/0.2/tags/ api/python/branches/0.2/trunk/ api/python/branches/0.2/trunk/AUTHORS api/python/branches/0.2/trunk/CHANGES api/python/branches/0.2/trunk/COPYING api/python/branches/0.2/trunk/README api/python/branches/0.2/trunk/TODO api/python/branches/0.2/trunk/tux.py api/python/branches/0.2/trunk/tuxapi_class.py api/python/branches/0.2/trunk/tuxapi_const.py api/python/branches/0.2/trunk/tuxapi_wav_merger.py Log: ADD: python api 0.2.X branche Added: api/python/branches/0.2/trunk/AUTHORS =================================================================== --- api/python/branches/0.2/trunk/AUTHORS (rev 0) +++ api/python/branches/0.2/trunk/AUTHORS 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,7 @@ +$Id: $ + +Tux python API was written by: + + R Jocaille <rem...@c2...> + +Contributors: Added: api/python/branches/0.2/trunk/CHANGES =================================================================== --- api/python/branches/0.2/trunk/CHANGES (rev 0) +++ api/python/branches/0.2/trunk/CHANGES 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,40 @@ +$Id: CHANGES 317 2007-05-12 11:57:43Z jaguarondi $ + +Approximate change log by version. + +(For more detailed changes, see svn log.) + +---------------------------------------------------------------------- +Current: + +Version 0.2.0: + + * The api was completely remade. I Kept the changes made by Neimad lately. + Sorry for this brutal update. + * I have implemented the 'join()' suggestion from Damien for the threads too. + Consequently, this api is not fully compatible with the last one. + * A documentation system based on the docstring has been implemented and you + can build this with the function 'tux.misc.build_documentation'. + See 'tux.misc.doc(tux.misc.build_documentation)'. + See 'tux.misc.doc(tux)' too + +Version 0.1.2: + + * Alsa tux card device name is now constructed by the api for example, + it is used for playing a sound with "aplay" + * Fixed a typo in api/python/trunk/tuxapi_class.py + * New boolean variable "print_warnings" has been added for print or not + of the warning messages. + * print_api_version() command has been moved. + +Version 0.1.1: + + * Added a limitation of the wav file to store the sounds in the local flash to 70 seconds. + * New functions and events are added. + * Minor modifications. + +Version 0.1.0: + + * Initial public release. + Most functions are implmeneted and should work with tuxdaemon 0.2.0 + Added: api/python/branches/0.2/trunk/COPYING =================================================================== --- api/python/branches/0.2/trunk/COPYING (rev 0) +++ api/python/branches/0.2/trunk/COPYING 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,340 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Library General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE 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. + + 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 +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 2 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, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This 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 Library General +Public License instead of this License. Added: api/python/branches/0.2/trunk/README =================================================================== --- api/python/branches/0.2/trunk/README (rev 0) +++ api/python/branches/0.2/trunk/README 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,19 @@ +$Id: README 118 2007-03-01 16:26:31Z jaguarondi $ + +Tux Droid Python API +This is the Python API that can be used to communicate with the Tux Droid +daemon. + +To install it, you only need to copy it to: + + /opt/tuxdroid/api/python/ + + Check this how-to for more information on the installation of the daemon and the API: + + http://www.tuxisalive.com/documentation/how-to/daemon-and-api-setup + +For all information about tuxdroid, please visit: + + http://www.tuxisalive.com + + Added: api/python/branches/0.2/trunk/TODO =================================================================== --- api/python/branches/0.2/trunk/TODO (rev 0) +++ api/python/branches/0.2/trunk/TODO 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,6 @@ +$Id: TODO 164 2007-03-14 14:36:16Z jaguarondi $ + +- Add documentation with Doxygen or something more adapted to python. + +- Create a regular python package/module out of this API. + Added: api/python/branches/0.2/trunk/tux.py =================================================================== --- api/python/branches/0.2/trunk/tux.py (rev 0) +++ api/python/branches/0.2/trunk/tux.py 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,41 @@ +#!/usr/bin/python +# -*- coding: latin-1 -*- + +import sys +from tuxapi_const import * +import tuxapi_class +import tuxapi_wav_merger +import signal +import atexit + +global tux + +# If run as main, print version banner. Otherwise, keep quiet. +if __name__ == "__main__": + misc = tuxapi_class.TUXmisc(None) + misc.print_api_version() + del misc + # Trick to detect whether python is in interactive mode + if not 'readline' in sys.modules: + print "For interactive use, run: python -i tux.py" + sys.exit(0) + +tux=tuxapi_class.TUXTCPCommunicator() +wavs=tuxapi_wav_merger.WavMerger(tux) +tux.daemon.connect() +tux.tts.connect() +tux.daemon.set_my_client_name("Py Client") +tux.print_warnings=True +tux.daemon.auto_connect(True) +tux.tts.auto_connect(True) + +def exit(signum,frame): + sys.exit(signum) + +def my_exitfunct(): + tux.destroy() + +signal.signal(signal.SIGTERM, exit) +signal.signal(signal.SIGINT, exit) +atexit.register(my_exitfunct) + Added: api/python/branches/0.2/trunk/tuxapi_class.py =================================================================== --- api/python/branches/0.2/trunk/tuxapi_class.py (rev 0) +++ api/python/branches/0.2/trunk/tuxapi_class.py 2007-12-14 13:34:39 UTC (rev 797) @@ -0,0 +1,5717 @@ +#!/usr/bin/python + +# ----------------------------------------------------------------------------- +# Tux Droid - API Class +# Copyright (C) 2007 C2ME Sa <rem...@c2...> +# +# 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 2, 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, write to the Free Software +# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA +# 02111-1307, USA. +# ----------------------------------------------------------------------------- +# $Id: tuxapi_class.py 192 2007-03-22 14:25:37Z remi $ +# ----------------------------------------------------------------------------- + +import sys +import os +import time +import socket +import thread +import threading +import string +import signal +import subprocess +import math +from tuxapi_const import * +from copy import deepcopy + +#============================================================================== +# Constants +#============================================================================== + +api_version ="0.2.3 (SVN/UNRELEASED)" +TCPIP_FRAME_LENGTH = 16 + +#============================================================================== +# EventControl - class +#============================================================================== +class EventControl(object): + + def __init__(self): + self.__funct_ptr_list = [] + self.__fifo_list = [] + self.__list_mutex = threading.Lock() + self.__threads_list = [] + + def destroy(self): + for my_thread in self.__threads_list: + if my_thread.isAlive(): + my_thread.join() + + def connect(self, funct_ptr): + self.__list_mutex.acquire() + idx = len(self.__funct_ptr_list) + self.__funct_ptr_list.append(funct_ptr) + self.__list_mutex.release() + return idx + + def push(self): + self.__list_mutex.acquire() + self.__fifo_list.append(self.__funct_ptr_list) + self.__list_mutex.release() + self.clear() + + def pop(self): + if len(self.__fifo_list) > 0: + self.__list_mutex.acquire() + self.__funct_ptr_list = self.__fifo_list.pop() + self.__list_mutex.release() + + def clear(self): + self.__list_mutex.acquire() + self.__funct_ptr_list = [] + self.__list_mutex.release() + + def disconnect(self, idx): + self.__list_mutex.acquire() + self.__funct_ptr_list[idx] = None + self.__list_mutex.release() + + def __refresh_threads_list(self): + nl = [] + for t in self.__threads_list: + if t.isAlive(): + nl.append(t) + self.__threads_list = nl + + def __run(self, funct_ptr, idx, fargs): + try: + funct_ptr(*fargs) + except: + self.__list_mutex.acquire() + self.__funct_ptr_list[idx] == None + self.__list_mutex.release() + + def notify(self, *fargs): + self.__list_mutex.acquire() + if len(self.__funct_ptr_list) == 0: + self.__list_mutex.release() + return + try: + funct_ptr_list = self.__funct_ptr_list + except: + self.__list_mutex.release() + return + self.__list_mutex.release() + for idx, funct_ptr in enumerate(funct_ptr_list): + if funct_ptr != None: + self.__refresh_threads_list() + t=threading.Thread(target=self.__run, args=(funct_ptr, idx, fargs)) + t.setName('EventControl') + t.start() + self.__threads_list.append(t) + +#============================================================================== +# TUXTCPCommunicator class +#============================================================================== +class TUXTCPCommunicator(object): + """ + Main class of tux object + + Sub class of this class: + "cmd" as class : Class which manages the tux commands + "connect" as class : Class which manages connection functions + "daemon" as class : Class which manages the daemon commands + "event" as class : Class which manages the events + "hw" as class : Class which manages the tux hardware + "micro" as class : Class which manages the microphone functions + "misc" as class : Class which manages the miscellaneous + functions + "monitoring" as class : Class which manages the monitoring + "status" as class : Class which manages the request of a + status + "sys" as class : Class which manages the system functions + "tts" as class : Class which manages the text to speech + "wav" as class : Class which manages the wav functions + + Global variables of this class: + "my_name" as string : Name of the api instance + "print_status" as boolean : Allow to print the raw statuses + "print_warnings" as boolean : Allow to print the warnings + + Comments: + Call the destroying function at the end of your script for closing + the api correctly. + >>> tux.destroy() + + "tts" class is compatible with "tuxttsd" v 0.3.0 or more recent + """ + #-------------------------------------------------------------------------- + # Constructor of class + #-------------------------------------------------------------------------- + def __init__(self,deprecated_p=5000,deprecated_a='localhost'): + """ + Constructor of class + + Example: + >>> tux=TUXTCPCommunicator() + """ + self.sock = None + self.main_thread_list=[] + self.exit_flag=False + self.tcp_mutex=threading.Lock() + self.print_warnings_mutex=threading.Lock() + self.my_name="Tux client" + self.print_status=False + self.print_warnings=True + self.print_debug_thread=False + self.lock_list = [] + self.lock_list_mutex = threading.Lock() + self.tcp_data_fifo_lock = [] + self.tcp_data_fifo_lock_mutex = threading.Lock() + self.tcp_data_fifo_event = [] + self.tcp_data_fifo_event_mutex = threading.Lock() + self.event=TUXevent(self) + self.cmd=TUXcmd(self) + self.connect=TUXconnect(self) + self.sys=TUXsys(self) + self.daemon=TUXdaemon(self) + self.sdaemon=self.daemon + self.status=TUXStatus(self) + self.hw=TUXhw(self) + self.tts=TUXtts(self) + self.misc=TUXmisc(self) + self.monitoring = TUXmonitoring(self) + self.wav = TUXwav(self) + self.micro = TUXmicro(self) + self._switches = [] + self.api_version = api_version + + self.connected=False #deprecated + t=threading.Thread(target=self.daemon._loop_auto_connect) + t.setName('daemon._loop_auto_connect') + t.start() + self.main_thread_list.append(t) + t=threading.Thread(target=self.tts._loop_auto_connect) + t.setName('tts._loop_auto_connect') + t.start() + self.main_thread_list.append(t) + + #-------------------------------------------------------------------------- + # Destructor of class + #-------------------------------------------------------------------------- + def destroy(self): + if self.exit_flag: return + self.daemon.auto_connect(False) + self.tts.auto_connect(False) + self.daemon.disconnect() + self.tts.disconnect() + self.tts.destroy() + self.daemon._tcp_threads_join() + self.tts._tcp_threads_join() + self.micro.destroy() + self.wav.destroy() + self.exit_flag=True + for main_thread in self.main_thread_list: + if self.print_debug_thread: + print "'%s' has been released"%main_thread.getName() + if main_thread.isAlive(): + main_thread.join() + self=None + print "Tux object has been destroyed" + + #-------------------------------------------------------------------------- + # Send a frame to tuxd + #-------------------------------------------------------------------------- + def _sock_send_frame(self, frame): + try: + self.sock.send(frame) + except: + pass + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _loop_tux_tcp_msg(self): + """ + Not a user function + """ + while self.daemon.connected: + try: + tmp_tcp_data=self.sock.recv(16) + except socket.timeout: + time.sleep(0.01) + continue + except socket.error: + self.sock.close() + self.daemon.connected=False + time.sleep(0.01) + continue + if len(tmp_tcp_data)<16: + time.sleep(0.01) + continue + self.tcp_data_fifo_lock_mutex.acquire() + self.tcp_data_fifo_lock.append(tmp_tcp_data) + self.tcp_data_fifo_lock_mutex.release() + self.tcp_data_fifo_event_mutex.acquire() + self.tcp_data_fifo_event.append(tmp_tcp_data) + self.tcp_data_fifo_event_mutex.release() + if self.print_status: + struct_data = ["%.2x" % ord(datae) for datae in tmp_tcp_data] + print " ".join(struct_data) + time.sleep(0.01) + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _loop_lock_list(self): + """ + Not a user function + self.lock_list + self.lock_list_mutex + self.tcp_data_fifo_lock + self.tcp_data_fifo_lock_mutex + """ + while self.daemon.connected: + # get a private lock_list from the class lock_list + self.lock_list_mutex.acquire() + lock_list = self.lock_list + self.lock_list_mutex.release() + # get a private data_fifo from the class data_fifo + self.tcp_data_fifo_lock_mutex.acquire() + if len(self.tcp_data_fifo_lock) > 0: + data_fifo = self.tcp_data_fifo_lock.pop(0) + else: + data_fifo = (chr(99))*16 + self.tcp_data_fifo_lock_mutex.release() + # get the time now in seconds + now = self.sys.time() + # check the whole of the lock elements + # lock[0] : list of data to match + # lock[1] : condition mutex + # lock[2] : data returned + for i,lock in enumerate(lock_list): + # for the whole of the lock data + for lock_data in lock[0]: + # if the lock data is matched + if lock_data[0] in [ord(data_fifo[0]), 999]\ + and lock_data[1] in [ord(data_fifo[1]), 999]\ + and lock_data[2] in [ord(data_fifo[2]), 999]\ + and lock_data[3] in [ord(data_fifo[3]), 999]\ + and lock_data[4] in [ord(data_fifo[4]), 999]\ + and lock_data[5] in [ord(data_fifo[5]), 999]\ + and lock_data[6] in [ord(data_fifo[6]), 999]\ + and lock_data[7] in [ord(data_fifo[7]), 999]\ + and lock_data[8] in [ord(data_fifo[8]), 999]\ + and lock_data[9] in [ord(data_fifo[9]), 999]\ + and lock_data[10] in [ord(data_fifo[10]), 999]\ + and lock_data[11] in [ord(data_fifo[11]), 999]\ + and lock_data[12] in [ord(data_fifo[12]), 999]\ + and lock_data[13] in [ord(data_fifo[13]), 999]\ + and lock_data[14] in [ord(data_fifo[14]), 999]\ + and lock_data[15] in [ord(data_fifo[15]), 999]: + # return the data ones who have unblocked the lock + lock[2].append(data_fifo) + # unblock the lock + lock[1].acquire() + lock[1].notify() + lock[1].release() + lock_list.pop(i) + continue + time.sleep(0.01) + # kill the whole of the lock elements from the list + self._close_lock_list() + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _close_lock_list(self): + self.lock_list_mutex.acquire() + # unblock the whole of the lock elements + for i,lock in enumerate(self.lock_list): + lock[1].acquire() + lock[1].notify() + lock[1].release() + self.lock_list = [] + self.lock_list_mutex.release() + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _insert_lock_in_list(self,data_to_match_list,cond_lock_mutex, \ + returned_data): + # lock[0] : list of the possible frames to match + # lock[1] : condition mutex + # lock[2] : data returned + lock = [] + lock.append(data_to_match_list) + lock.append(cond_lock_mutex) + lock.append(returned_data) + self.lock_list_mutex.acquire() + self.lock_list.append(lock) + self.lock_list_mutex.release() + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _loop_tux_data_dispatching(self): + """ + Not a user function + """ + while self.daemon.connected: + data = () + self.tcp_data_fifo_event_mutex.acquire() + if len(self.tcp_data_fifo_event) > 0: + data = self.tcp_data_fifo_event.pop(0) + else: + self.tcp_data_fifo_event_mutex.release() + time.sleep(0.003) + continue + self.tcp_data_fifo_event_mutex.release() + self._dispatch_data_main(data) + time.sleep(0.003) + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _dispatch_data_main(self,data): + """ + Not a user function + """ + # from daemon + if ord(data[0])==SOURCE_SUB_DAEMON: + self._dispatch_data_from_daemon(data) + # from tux droid + if ord(data[0])==SOURCE_TUX: + self._dispatch_data_from_tux(data) + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _dispatch_data_from_daemon(self,data): + """ + Not a user function + """ + # data type command + if ord(data[2])==DATA_TP_CMD: + if ord(data[3])==SUBDATA_TP_STRUCT: + # daemon close + if ord(data[4])==SUB_D_CMD_STRUC_DISCONNECT_CLIENT: + self.daemon.disconnect() + + #-------------------------------------------------------------------------- + # SYSTEM function + #-------------------------------------------------------------------------- + def _dispatch_data_from_tux(self,data): + """ + Not a user function + """ + # data type response + if ord(data[2])==DATA_TP_RSP: + if ord(data[3])==SUBDATA_TP_STATUS: + #Head button + if ord(data[4])==DATAS_STATUS_HEAD_PUSH_SWITCH: + if ord(data[5])==1: + if self.event.on_head_bt_pushed!=None: + self.event.on_head_bt_pushed() + if self.event.on_bt_pushed!=None: + self.event.on_bt_pushed() + else: + if self.event.on_head_bt_released!=None: + self.event.on_head_bt_released() + if self.event.on_bt_released!=None: + self.event.on_bt_released() + #Left wing button + if ord(data[4])==DATAS_STATUS_LEFT_WING_PUSH: + if ord(data[5])==1: + if self.event.on_lwing_bt_pushed!=None: + self.event.on_lwing_bt_pushed() + if self.event.on_bt_pushed!=None: + self.event.on_bt_pushed() + else: + if self.event.on_lwing_bt_released!=None: + self.event.on_lwing_bt_released() + if self.event.on_bt_released!=None: + self.event.on_bt_released() + #Right wing button + if ord(data[4])==DATAS_STATUS_RIGHT_WING_PUSH: + if ord(data[5])==1: + if self.event.on_rwing_bt_pushed!=None: + self.event.on_rwing_bt_pushed() + if self.event.on_bt_pushed!=None: + self.event.on_bt_pushed() + else: + if self.event.on_rwing_bt_released!=None: + self.event.on_rwing_bt_released() + if self.event.on_bt_released!=None: + self.event.on_bt_released() + #Remote button + if ord(data[4])==DATAS_STATUS_IR_CODE: + if self.event.on_remote_bt[ord(data[5])]!=None: + thread.start_new_thread( \ + self.event.on_remote_bt[ord(data[5])], ()) + #self.event.on_remote_bt[ord(data[5])]() + if self.event.on_remote!=None: + thread.start_new_thread( \ + self.event.on_remote, (ord(data[5]),)) + #self.event.on_remote(ord(data[5])) + #Mouth open + if ord(data[4])==DATAS_STATUS_MOUTH_OPEN_POSITION: + if ord(data[5])==0: + if self.event.on_mouth_open!=None: + self.event.on_mouth_open() + #Mouth close + if ord(data[4])==DATAS_STATUS_MOUTH_CLOSED_POSITION: + if ord(data[5])==0: + if self.event.on_mouth_close!=None: + self.event.on_mouth_close() + #Ledl + if ord(data[4])==DATAS_STATUS_LEFT_BLUE_LED: + if ord(data[5])==1: + if self.event.on_left_blue_led_on!=None: + self.event.on_left_blue_led_on() + else: + if self.event.on_left_blue_led_off!=None: + self.event.on_left_blue_led_off() + #Ledr + if ord(data[4])==DATAS_STATUS_RIGHT_BLUE_LED: + if ord(data[5])==1: + if self.event.on_right_blue_led_on!=None: + self.event.on_right_blue_led_on() + else: + if self.event.on_right_blue_led_off!=None: + self.event.on_right_blue_led_off() + #Eyes open/close + if ord(data[4])==DATAS_STATUS_EYES_CLOSED_POSITION_SWITCH: + if ord(data[5])==0: + if self.event.on_eyes_close!=None: + self.event.on_eyes_close() + else: + if self.event.on_eyes_open!=None: + self.event.on_eyes_open() + #Power plug switch + if ord(data[4])==DATAS_STATUS_POWER_PLUG_SWITCH: + if ord(data[5])==1: + if self.event.on_power_plugged!=None: + self.event.on_power_plugged() + else: + if self.event.on_power_unplugged!=None: + self.event.on_power_unplugged() + #RF status + if ord(data[4])==DATAS_STATUS_RF_CONNECTED: + if ord(data[5])==1: + self.status.rf_connected=True + if self.event.on_rf_connected!=None: + self.event.on_rf_connected() + else: + self.status.rf_connected=False + if self.event.on_rf_disconnected!=None: + self.event.on_rf_disconnected() + #PONG + if ord(data[4])==DATAS_STATUS_PONG: + if self.event.on_pong_received!=None: + rcv=ord(data[6]) + rem=ord(data[5]) + avg=int((100*rcv)/(200-rem)) + self.event.on_pong_received(rcv,rem,avg) + #mouth stop + if ord(data[4])==DATAS_STATUS_MOUTH_POSITION_COUNTER: + if ord(data[5])==0: + if self.event.on_mouth_stop!=None: + self.event.on_mouth_stop() + #eyes stop + if ord(data[4])==DATAS_STATUS_EYES_POSITION_COUNTER: + if ord(data[5])==0: + if self.event.on_eyes_stop!=None: + self.event.on_eyes_stop() + + #wings stop + if ord(data[4])==DATAS_STATUS_WINGS_POSITION_COUNTER: + if ord(data[5])==0: + if self.event.on_wings_stop!=None: + self.event.on_wings_stop() + #spin stop + if ord(data[4])==DATAS_STATUS_SPIN_POSITION_COUNTER: + if ord(data[5])==0: + if self.event.on_spin_stop!=None: + self.event.on_spin_stop() + #on status + if self.event.on_status!=None: + self.event.on_status(data) + #on monitoring + self.monitoring.check_events(data) + + for switch in self._switches: + try: + switch._notify(ord(data[4]), ord(data[5])) + except: + pass + + + #-------------------------------------------------------------------------- + # Deprecated functions + #-------------------------------------------------------------------------- + def explicit_status(self,frame): + """ + Deprecated : see 'tux.status.to_string' + """ + return self.status.to_string(frame) + + def connect_to_daemon(self): + """ + Deprecated : see 'tux.daemon.connect' + """ + return self.daemon.connect() + + def disconnect_from_daemon(self): + """ + Deprecated : see 'tux.daemon.disconnect' + """ + self.daemon.disconnect() + +#============================================================================== +# TUXTCPCommunicator - connect - class +#============================================================================== +class TUXconnect(object): + """ + Class which manages connection functions + + Functions list for the users: + tux.connect.disconnect_from_tux + tux.connect.connect_to_tux + tux.connect.random_connect_to_tux + tux.connect.id_request + tux.connect.id_lookup + tux.connect.change_id + tux.connect.sleep + tux.connect.wakeup + tux.connect.avoid_wifi + """ + + #-------------------------------------------------------------------------- + # Constructor of the class + #-------------------------------------------------------------------------- + def __init__(self,parent): + """ + Constructor of the class + """ + self.parent=parent + + #-------------------------------------------------------------------------- + # Send a connection command and wait for the result + #-------------------------------------------------------------------------- + def tux_connection(self, connection_command, connection_args=[]): + """ + Not a user function + """ + if not self.parent.daemon.connected: + return 0 + data=[DEST_TUX, SD_DEFAULT, USB_CONNECTION_CMD, 0, connection_command] + data.extend(connection_args) + if len(data) > TCPIP_FRAME_LENGTH: + return False + # Fill up the end of the frame with 0 + data.extend([0] * (TCPIP_FRAME_LENGTH - len(data))) + self.parent._sock_send_frame("".join( [chr(x) for x in data] )) + return self.parent.status.rsp_status(connection_command, timeout=5) + + #-------------------------------------------------------------------------- + # Disconnect from tux + #-------------------------------------------------------------------------- + def disconnect_from_tux(self): + """ + Disconnect from tux + + Parameters: + "seconds" as float : Time to wait in seconds + + Example: + >>> tux.sys.wait(2.4) + """ + ack_frame = self.tux_connection(TUX_CONNECTION_DISCONNECT) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + #-------------------------------------------------------------------------- + # Connect to a tux by its ID + #-------------------------------------------------------------------------- + def connect_to_tux(self, id): + """ + Connect to a tux by its ID + + Parameters: + "id" as uint16 : ID of the tux you want to connect to + 0 and 0xFFFF (65536) are not valid ID's + + Returns: + "True" if the command has been sent successfully, + "False" otherwise. + + Example: + >>> tux.connect.connect_to_tux(300) + """ + # 0 is an invalid id and 0xFFFF is reserved + assert 0 < id < 0xFFFF + id_msb = id >> 8 + id_lsb = id & 0xFF + ack_frame = self.tux_connection(TUX_CONNECTION_CONNECT, + [id_msb, id_lsb]) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + #-------------------------------------------------------------------------- + # Connect to the first tux discovered + #-------------------------------------------------------------------------- + def random_connect_to_tux(self): + """ + Connect to the first tux discovered + + Catch any disconnected tux, request it's ID and connect to it. + + Returns: + "True" if the command has been sent successfully, + "False" otherwise. + + """ + ack_frame = self.tux_connection(TUX_CONNECTION_RANDOM) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + #-------------------------------------------------------------------------- + # Get the ID of the first disconnected tux which is discoverred + #-------------------------------------------------------------------------- + def id_request(self): + """ + Get the ID of tux currently connected + + Returns: + "id" as uint16 (0 < id < 65536) if the command has been sent + successfully, + "False" otherwise. + """ + ack_frame = self.tux_connection(TUX_CONNECTION_ID_REQUEST) + if ack_frame and ord(ack_frame[5]) == TUX_CONNECTION_ACK: + return (ord(ack_frame[6])*256) + ord(ack_frame[7]) + + return False + + #-------------------------------------------------------------------------- + # Get the ID of the first disconnected tux which is discoverred + #-------------------------------------------------------------------------- + def id_lookup(self): + """ + Get the ID of the first disconnected tux which is discoverred + + The first disconnected tux that will detect this command will reply + with it's ID and disconnect immediately. You can then connect to + that tux with the ID you just got. + + In order to get the ID's of more than one disconnected tux, you have + to issue this command multiple times until you don't get any new ID. + + Returns: + "id" as uint16 (0 < id < 65536) if the command has been sent + successfully, + "False" otherwise. + """ + ack_frame = self.tux_connection(TUX_CONNECTION_ID_LOOKUP) + if ack_frame and ord(ack_frame[5]) == TUX_CONNECTION_ACK: + return (ord(ack_frame[6])*256) + ord(ack_frame[7]) + + return False + + #-------------------------------------------------------------------------- + # Changes the ID of a disconnected tux + #-------------------------------------------------------------------------- + def change_id(self, id): + """ + Changes the ID of a disconnected tux + + You have to push on the head button of tux for XXX seconds while + sending this command in order to validate the ID change request, this + in order to avoid stealing a tux too easily. + + Parameters: + "id" as uint16 : new ID you want to set to your tux + 0 and 0xFFFF (65536) are not valid ID's + + Returns: + "True" if the command has been sent successfully, + "False" otherwise. + """ + assert 0 < id < 0xFFFF + id_msb = id >> 8 + id_lsb = id % 256 + ack_frame = self.tux_connection(TUX_CONNECTION_CHANGE_ID, + [id_msb, id_lsb]) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + #-------------------------------------------------------------------------- + # Set tux in sleep mode + #-------------------------------------------------------------------------- + def sleep(self): + """ + Set tux in sleep mode + + Returns: + "True" if the command has been sent successfully, + "False" otherwise. + """ + ack_frame = self.tux_connection(TUX_CONNECTION_SLEEP) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + #-------------------------------------------------------------------------- + # Wake-up a tux if it's in sleep mode. + #-------------------------------------------------------------------------- + def wakeup(self, id): + """ + Wake-up a tux if it's in sleep mode. + + Parameters: + "id" as uint16 : ID of the tux you want to wake-up + 0 and 0xFFFF (65536) are not valid ID's + + Returns: + "True" if the command has been sent successfully, + "False" otherwise. + """ + assert 0 < id < 0xFFFF + id_msb = id >> 8 + id_lsb = id % 256 + ack_frame = self.tux_connection(TUX_CONNECTION_WAKEUP, + [id_msb, id_lsb]) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + #-------------------------------------------------------------------------- + # Configure the RF module to avoid a given wifi channel + #-------------------------------------------------------------------------- + def avoid_wifi(self, channel): + """ + Configure the RF module to avoid a given wifi channel + + + Parameters: + "channel" : wifi channel number that tux should avoid using + Channels from 1 to 14 are valid wifi channels. Set the wifi + channel to 0 to disable channel avoidance and use the + complete range of frequencies. + + Returns: + "True" if the command has been sent successfully, + "False" otherwise. + """ + ack_frame = self.tux_connection(TUX_CONNECTION_WIRELESS_CHANNEL, + [channel]) + if not ack_frame or ord(ack_frame[5]) != TUX_CONNECTION_ACK: + return False + + return True + + +#============================================================================== +# TUXTCPCommunicator - sys - class +#============================================================================== +class TUXsys(object): + """ + Class which manages the system functions + + Functions list for the users: + tux.sys.add_time_event + tux.sys.clear_time_events + tux.sys.delayed_function + tux.sys.delete_time_event + tux.sys.looped_function + tux.sys.shell + tux.sys.shell_free + tux.sys.time + tux.sys.wait + """ + + #-------------------------------------------------------------------------- + # Constructor of class + #-------------------------------------------------------------------------- + def __init__(self,parent): + """ + Constructor of class + """ + self.parent = parent + self.events_list = [[0,'NONE',9999,99,99,99,99,99]] + self.__time_event_mutex = threading.Lock() + + #-------------------------------------------------------------------------- + # Get the current time in seconds + #-------------------------------------------------------------------------- + def time(self): + """ + Get the current time in seconds + + Return an integer + + Example: + >>> var=tux.sys.time() + """ + return (time.localtime()[3]*3600)+(time.localtime()[4]*60)+ \ + time.localtime()[5] + + #-------------------------------------------------------------------------- + # Wait a time in seconds + #-------------------------------------------------------------------------- + def wait(self,seconds): + """ + Wait a time in seconds + + Parameters: + "seconds" as float : Time to wait in seconds + + Example: + >>> tux.sys.wait(2.4) + """ + time.sleep(seconds) + + #-------------------------------------------------------------------------- + # Execute a shell command + #-------------------------------------------------------------------------- + def shell(self,command): + """ + Execute a shell command + + Parameters: + "command" as string : Shell command + + Example: + >>> tux.sys.shell('ls -al') + """ + os.system(command) + + #-------------------------------------------------------------------------- + # Execute a shell command in free mode ... [truncated message content] |