Commit 8f1af6cd authored by Bruno Laurencich's avatar Bruno Laurencich

start & stop ops

parent d3d0e0b2
[submodule "dnspython"]
path = dnspython
url = git://github.com/rthalley/dnspython.git
[submodule "requests"]
path = requests
url = https://github.com/requests/requests.git
......@@ -9,10 +9,16 @@ if "bpy" in locals():
import imp
imp.reload(connection)
imp.reload(panel)
imp.reload(remote_runner)
imp.reload(utils)
else:
from . import connection
from . import panel
from . import remote_runner
from . import utils
import bpy
......@@ -31,6 +37,16 @@ class Chord_Properties(bpy.types.PropertyGroup):
items=connection.possible_states(),\
options={'SKIP_SAVE'})
notochord_msg =props.StringProperty( default = "" )
notochord_hostname =props.StringProperty( default = "notochord" )
notochord_ip =props.StringProperty( default = "" )
last_check =props.IntProperty( default = 0 )
max_ip_discover_attempts = props.IntProperty( default = 3 )
# ====== End of GLOBAL PROPERTIES =======
......@@ -38,7 +54,7 @@ def register():
# bpy.utils.register_class(Chord_Get_Ip)
bpy.utils.register_class(Chord_Properties)
WindowManager.chordata = \
bpy.props.PointerProperty(type=Chord_Properties)
bpy.props.PointerProperty(type=Chord_Properties, options={'SKIP_SAVE'})
bpy.utils.register_module(__name__)
......
......@@ -17,8 +17,9 @@ def possible_states(raw = True):
return [
("Disconnected", "no-conn", "", "COLOR_RED", 0),
("Connected", "conn", "", "COLOR_GREEN", 1),
("Searching..", "search1", "", "INLINK", 2),
("Searching.", "search2", "", "LINK", 3),
("Transfering", "transfer", "", "POSE_DATA", 2),
("Searching..", "search1", "", "INLINK", 3),
("Searching.", "search2", "", "LINK", 4),
]
......@@ -48,7 +49,7 @@ class Chord_Get_Ip(bpy.types.Operator):
context.object.rotation_euler.y +=0.3
if self.query_thread.is_alive():
print("ip query ongoing..")
self.chord_global.state = \
possible_states()[self.counter%2+2][0]
else:
......@@ -56,11 +57,12 @@ class Chord_Get_Ip(bpy.types.Operator):
if self.found_ip:
self.chord_global.state = possible_states()[1][0]
self.report({"INFO"}, "IP found :" + self.found_ip)
self.chord_global.notochord_ip = self.found_ip
else:
self.chord_global.state = possible_states()[0][0]
self.report({"WARNING"}, "IP NOT found")
print("IP found :", self.found_ip)
self.cancel(context)
return {'FINISHED'}
......@@ -72,25 +74,27 @@ class Chord_Get_Ip(bpy.types.Operator):
# ----------- DO QUERY (thread handler) -----------
def do_query(self):
print("query thread running")
ip = mdns.get_ip()
while not ip and mdns.timeout < 5:
mdns.set_timeout(mdns.timeout + 2)
print("*** new timeout ", mdns.timeout)
self.report({"DEBUG"}, "Query Thread running.")
ip = mdns.get_ip(self.chord_global.notochord_hostname+".local")
max_attempts = self.chord_global.max_ip_discover_attempts
if max_attempts == 0: max_attempts = 100
n = 1
while not ip and n < max_attempts:
ip = mdns.get_ip(self.chord_global.notochord_hostname+".local")
if ip: break
mdns.set_timeout(mdns.timeout * 2)
with self.query_lock:
self.report({"INFO"},\
"ip not found, retrying in %d secs" %mdns.timeout)
if mdns.timeout >= 5:
mdns.set_nameserver()
ip = mdns.get_ip()
n += 1
with self.query_lock:
self.found_ip = ip
print("*** Thread terminating..")
self.report({"DEBUG"}, "Query Thread terminating..")
return
# ----------- EXECUTE -----------
......@@ -98,6 +102,7 @@ class Chord_Get_Ip(bpy.types.Operator):
def execute(self, context):
self.chord_global = context.window_manager.chordata
self.chord_global.state = possible_states()[0][0]
self.chord_global.notochord_ip = ""
self.report({"INFO"},"ip query ongoing..")
wm = context.window_manager
......
......@@ -10,7 +10,7 @@ from dns.exception import Timeout
myRes=Resolver()
myRes.nameservers=['224.0.0.252'] #mdns multicast address
myRes.nameservers=['224.0.0.251'] #mdns multicast address
myRes.port=5353 #mdns port
timeout = myRes.lifetime
......@@ -31,10 +31,10 @@ def set_nameserver(name = '224.0.0.251', port=5353):
myRes.nameservers = [name]
myRes.port = port
def query(host = 'raspberrypi.local', field = "A"):
def query(host = 'notochord.local', field = "A"):
return myRes.query(host,field)
def get_ip(host = 'raspberrypi.local'):
def get_ip(host = 'notochord.local'):
try:
return query(host)[0].to_text()
except Timeout as e:
......
import bpy
from time import time
from sys import path
from os.path import join, abspath, dirname
path.append(join(dirname(abspath(__file__)), "requests"))
from requests import get as http_get
from requests.exceptions import RequestException as Http_Error
CHECK_PERIOD = 5
def get_conn_state_attr(context, attr = "name"):
current = context.window_manager.chordata.state
......@@ -17,15 +25,47 @@ class Chord_tools_panel(bpy.types.Panel):
bl_space_type = "VIEW_3D"
bl_region_type = "TOOLS"
def check_connection(self):
try:
r = http_get("http://%s/watchdog" % self.chord_global.notochord_ip, timeout=1)
except Http_Error:
# self.report({"WARNING"},"Notochord disconnected")
self.chord_global.state = "Disconnected"
return
if r.status_code != 200:
# self.report({"WARNING"},"Notochord disconnected")
self.chord_global.state = "Disconnected"
# else:
# self.report({"INFO"},"Notochord still there")
def draw(self, context):
self.chord_global = context.window_manager.chordata
layout = self.layout
if get_conn_state_attr(context, "value") > 1:
if time() - self.chord_global.last_check > CHECK_PERIOD:
self.chord_global.last_check = time()
if self.chord_global.state == "Connected":
self.check_connection()
if get_conn_state_attr(context, "value") > 2:
layout.enabled= False
layout.operator("chordata.get_ip", "Connect")
# layout.prop(context.window_manager.chordata, "state", expand=True)
layout.label(context.window_manager.chordata.state,\
layout.label(self.chord_global.state,\
icon= get_conn_state_attr(context, "icon"))
layout.operator("chordata.start_notochord", "Start")
layout.operator("chordata.close_notochord", "Stop")
### PROPS BOX
layout.separator()
box = layout.box()
layout.operator("chordata.dale", "DALE!")
box.prop(self.chord_global, "last_check")
box.prop(self.chord_global, "notochord_hostname")
# conn_state = get_conn_state_attr(context, "name")
# print(conn_state)
......
import bpy
from time import time
from sys import path
from os.path import join, abspath, dirname
path.append(join(dirname(abspath(__file__)), "requests"))
from requests import get as http_get
from requests.exceptions import RequestException as Http_Error
if "u" in locals():
import imp
imp.reload(u)
else:
from . import utils as u
#TODO:
# Prepara pr EXEC_DEFAULT contest (check inside execute if invoke was called)
# put connection states inside utils
# Create receive op that starts, receives and stops on exit (perhaps also takes mouse input)
# =====================================================
# = OPERATOR: START NOTOCHORD =
# =====================================================
def popup_message(self, context):
self.layout.label("Notochord message.")
class Chord_Runner_Base(bpy.types.Operator):
m_no_ip = """Imposible to resolve notochord address"""
m_not_connected = """Notochord is not connected"""
m_error = """There was an error with the notochord program"""
def disconnected(self):
self.report({"WARNING"},self.m_not_connected)
bpy.context.window_manager.popup_menu( popup_message,
title=self.m_not_connected, icon='ERROR')
self.chord_global.state = "Disconnected"
return {"CANCELLED"}
def remote_error(self):
self.report({"WARNING"},self.m_error)
bpy.context.window_manager.popup_menu( popup_message,
title=self.m_error, icon='ERROR')
return {"CANCELLED"}
class Chord_Start_Notochord(Chord_Runner_Base):
"""Starts the notochord program"""
bl_idname = "chordata.start_notochord"
bl_label = "Chordata: Start the notochord"
bl_options = {'REGISTER'}
def draw(self, context):
self.layout.separator()
self.layout.label("Press OK to start the notochord, might take some seconds")
def invoke(self, context, event):
self.chord_global = context.window_manager.chordata
if not self.chord_global.notochord_ip:
self.report({"WARNING"}, self.m_no_ip)
bpy.context.window_manager.popup_menu(popup_message,
title=self.m_no_ip, icon='ERROR')
return {"FINISHED"}
try:
r = http_get("http://%s/command/init" % self.chord_global.notochord_ip, timeout=1)
except Http_Error:
return self.disconnected()
if r.status_code != 200:
return self.disconnected()
notochord_response = r.json()
u.write_blender_console(context, notochord_response["msg"])
if notochord_response["mode"] != "normal":
return self.remote_error()
return context.window_manager.invoke_props_dialog(self)
# ----------- EXECUTE -----------
def execute(self, context):
self.chord_global = context.window_manager.chordata
self.report({"INFO"},"Starting notochord..")
try:
r = http_get("http://%s/command/send" % self.chord_global.notochord_ip, timeout=1)
except Http_Error:
return self.disconnected()
if r.status_code != 202:
return self.disconnected()
notochord_response = r.json()
if notochord_response["mode"] != "normal":
return self.remote_error()
self.report({"INFO"},"Transfering pose data..")
self.chord_global.state = "Transfering"
return {'FINISHED'}
# ====== End of OPERATOR: START NOTOCHORD =======
# =================================================
# = OPERATOR: CLOSE NOTOCHORD =
# =================================================
class Chord_Close_Notochord(Chord_Runner_Base):
"""Starts the notochord program"""
bl_idname = "chordata.close_notochord"
bl_label = "Chordata: Close the notochord"
bl_options = {'REGISTER'}
def draw(self, context):
self.layout.separator()
self.layout.label("Stop the notochord?")
def invoke(self, context, event):
return context.window_manager.invoke_props_dialog(self)
# ----------- EXECUTE -----------
def execute(self, context):
self.chord_global = context.window_manager.chordata
self.report({"INFO"},"Closing notochord..")
try:
r = http_get("http://%s/command/close" % self.chord_global.notochord_ip, timeout=1)
except Http_Error:
return self.disconnected()
if r.status_code != 200:
return self.disconnected()
notochord_response = r.json()
if notochord_response["state"] != 0:
return self.remote_error()
self.chord_global.state = "Connected"
u.write_blender_console(context, notochord_response["msg"])
return {'FINISHED'}
# ====== End of OPERATOR: CLOSE NOTOCHORD =======
Subproject commit ef88b9faa6d73bc83a07ddebc424c551d2ee671c
import bpy
def write_blender_console(context, t):
screen = context.screen
for area in screen.areas:
if area.type == 'CONSOLE':
for r in area.regions:
if r.type == "WINDOW":
override = {'window': context.window, 'screen': screen,
'area': area, "region": r}
for line in t.split("\r\n"):
bpy.ops.console.scrollback_append(override, text=line)
break
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment