kilon

Stream socket server blender addon

Jul 26th, 2014
662
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.95 KB | None | 0 0
  1. #-*- coding: utf-8 -*-
  2.  
  3. #------------------------------------------
  4. #   pyEphestos
  5. #
  6. #    Morpheas is the GUI side of Ephestos based on morphic.py
  7. #
  8. #
  9. #    written by Kilon Alios
  10. #
  11. #    version April-2012
  12. #
  13. #    Copyright (C) 2012 by Kilon Alios
  14. #
  15. #    Under GPL license for more info see the Blender license
  16. #
  17. #---------------------------------------
  18. #    Permission is hereby granted, free of charge, to any person
  19. #    obtaining a copy of this software and associated documentation
  20. #    files (the "Software"), to deal in the Software without
  21. #    restriction, including without limitation the rights to use, copy,
  22. #    modify, merge, publish, distribute, sublicense, and/or sell copies
  23. #    of the Software, and to permit persons to whom the Software is
  24. #    furnished to do so, subject to the following conditions:
  25. #
  26. #    The above copyright notice and this permission notice shall be
  27. #    included in all copies or substantial portions of the Software.
  28. #
  29. #    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  30. #    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  31. #    MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  32. #    NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  33. #    HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  34. #    WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  35. #    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  36. #    DEALINGS IN THE SOFTWARE.
  37. #
  38.  
  39. """ Pharo code:
  40. stream := SocketStream openConnectionToHostNamed: ' 127.0.0.1'  port: 4000 .
  41. stream sendCommand: 'Hello Pharo AGAIN!!!!'.
  42. stream close."""
  43.  
  44. bl_info = {
  45.     "name": "Ephestos : communication tool for Pharo",
  46.     "description": "Ephestos is a communication tool to allow Pharo to control Blender. This allows Pharo to control blender via Blender Python API. Pharo is a simple programming language , very powerful IDE and a fun live coding enviroment.",
  47.     "author": "Kilon",
  48.     "version": (0, 0, 1),
  49.     "blender": (2, 7, 1),
  50.     "location": "View3D > Left panel ",
  51.     "warning": 'Warning !!! It may crash Blender ! Always save your work !',  # used for warning icon and text in addons panel
  52.     "wiki_url": "",
  53.     "tracker_url": "https://github.com/kilon/pyEphestos",
  54.     "category": "Development"}
  55.  
  56.  
  57. import time
  58. import bpy
  59. import threading
  60. import socket
  61. from bpy.props import *
  62.  
  63. ephestos_running = False
  64. thread_created = False
  65. threadSocket = 0
  66. socketServer = 0
  67. receivedSocket = "none"
  68. listening = False
  69. socketMessages = []
  70. receivedData = ''
  71. pherror = []
  72.  
  73. def create_thread():
  74.  
  75.     global threadSocket,listening
  76.     threadSocket = threading.Thread(name='threadSocket', target= socket_listen)
  77.     listening = True
  78.     create_socket_connection()
  79.     threadSocket.start()
  80.     #threadSocket.join()
  81.  
  82. def socket_listen():
  83.     global receivedSocket,listening, receivedData,socketServer, socketMessages, pherror
  84.     socketServer.listen(5)
  85.  
  86.     while listening:
  87.         (receivedSocket , adreess) = socketServer.accept()
  88.         receivedData = (receivedSocket.recv(1024)).decode("utf-8")[:-2]
  89.  
  90.         #exec(receivedData)
  91.         socketMessages.append(receivedData)
  92.         """ for err in pherror:
  93.            #receivedSocket.sendall((err+'\r\n').encode("ascii"))
  94.            receivedSocket.sendall(err+'\n')
  95.            pherror.remove(err)"""
  96.         receivedSocket.sendall('Hello from Blender!\n')
  97.         receivedSocket.close()
  98.  
  99.  
  100.  
  101.  
  102. def create_socket_connection():
  103.     global socketServer
  104.     socketServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  105.     socketServer.bind(('127.0.0.1',4000))
  106.  
  107.  
  108. class open_ephestos(bpy.types.Operator):
  109.     bl_idname = "ephestos_button.modal"
  110.     bl_label = "enable Ephestos"
  111.     _timer = None
  112.  
  113.     def modal(self, context, event):
  114.         global ephestos_running, thread_created, listening, socketServer, socketMessages, pherror
  115.         result =  {'PASS_THROUGH'}
  116.         #context.area.tag_redraw()
  117.         #context.area.header_text_set("Welcome to Ephestos")
  118.         #if context.area:
  119.            # context.area.tag_redraw()
  120.  
  121.  
  122.         if context.area.type == 'VIEW_3D' and ephestos_running and event.type in {'ESC',}:
  123.  
  124.             ephestos_running = False
  125.             listening = False
  126.             #time.sleep(1)
  127.             socketServer.close()
  128.             context.window_manager.event_timer_remove(self._timer)
  129.             #time.sleep(1)
  130.             thread_created = False
  131.             result = {'CANCELLED'}
  132.             self.report({'WARNING'}, "Ephestos has been closed")
  133.  
  134.         if context.area.type == 'VIEW_3D' and ephestos_running and event.type == 'TIMER' :
  135.           for msg in socketMessages:
  136.               try:
  137.  
  138.                   exec(msg,globals())
  139.                   #socketMessages.remove(msg)
  140.                   pherror = 'no error'
  141.               except Exception as e:
  142.                   pherror.append( "Error:" +str(e)+" with :" + msg)
  143.  
  144.                   #self.report({'WARNING'}, pherror)
  145.                   #socketMessages.remove(msg)
  146.               socketMessages.remove(msg)
  147.           # create_thread()
  148.           # thread_created = True
  149.  
  150.         return result
  151.  
  152.     def invoke(self, context, event):
  153.         global ephestos_running,thread_created
  154.         if context.area.type == 'VIEW_3D' and ephestos_running == False :
  155.             self.cursor_on_handle = 'None'
  156.  
  157.             # Add the region OpenGL drawing callback
  158.             # draw in view space with 'POST_VIEW' and 'PRE_VIEW'
  159.             #self._handle =bpy.types.SpaceView3D.draw_handler_add(draw_ephestos,(self,context), 'WINDOW', 'POST_PIXEL')
  160.  
  161.             self._timer = context.window_manager.event_timer_add(0.001,context.window)
  162.             ephestos_running = True
  163.             context.window_manager.modal_handler_add(self)
  164.             create_thread()
  165.             thread_created = True
  166.             return {'RUNNING_MODAL'}
  167.         else:
  168.             self.report({'WARNING'}, "Ephestos is already opened and running")
  169.             return {'CANCELLED'}
  170.  
  171.  
  172. class ephestos_panel(bpy.types.Panel):
  173.     bl_label = "Ephestos"
  174.     bl_space_type = "VIEW_3D"
  175.     bl_region_type = "TOOLS"
  176.     def draw(self, context):
  177.         global receivedSocket,listening,pherror
  178.  
  179.         sce = context.scene
  180.         layout = self.layout
  181.         box = layout.box()
  182.         box.label(text="Ephestos WIP not finished yet")
  183.         box.label(text="-----------------------------")
  184.  
  185.         if listening:
  186.             box.label(text="Listening")
  187.         else:
  188.             box.label(text="Not Listening")
  189.  
  190.         box.label(text="ReceivedData:")
  191.         box.label(text=receivedData)
  192.         if len(pherror) == 0:
  193.             box.label(text="Error: no error ")
  194.         else:
  195.             box.label(text=pherror[-1])
  196.         box.operator("ephestos_button.modal")
  197.  
  198.  
  199. def register():
  200.     bpy.utils.register_module(__name__)
  201.  
  202. def unregister():
  203.     bpy.utils.unregister_module(__name__)
  204.  
  205. if __name__ == "__main__":
  206.     register()
Add Comment
Please, Sign In to add comment