kilon

Stream socket server blender addon

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