Skip to content

Commit

Permalink
修改前端使用jsrpc
Browse files Browse the repository at this point in the history
  • Loading branch information
zzldjkzxf committed May 9, 2018
1 parent eb39ef8 commit 189a681
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 133 deletions.
2 changes: 1 addition & 1 deletion gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ var watchify = require('gulp-watchify');
var sourcemap = require('gulp-sourcemaps')


var jsxpath = 'lib/modules/**/*.jsx';
var jsxpath = 'lib/modules/**/*.js*';
var jsxoutput = 'lib/babel-build/';
var bundleoutput = 'lib/js-build/';
var entries = [
Expand Down
18 changes: 11 additions & 7 deletions lib/modules/jsrpc/rpcbase.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class RpcBase {
this._id = 0
this.id_to_resolve = {}
this.id_to_reject = {}
this._data = new Buffer(0)
this._data = window.Buffer(0)
this.msg_len = -1
}

Expand Down Expand Up @@ -34,17 +34,17 @@ class RpcBase {

get_buffer_from_msg(msg) {
let len = msg.length
let buf_msg = new Buffer(len)
let buf_msg = window.Buffer(len)
buf_msg.write(msg, 0, len)
let buf_len = new Buffer(4)
let buf_len = window.Buffer(4)
buf_len.writeUInt8(len, 0, 4 )
let buf = Buffer.concat([buf_len, buf_msg])
let buf = window.Buffer.concat([buf_len, buf_msg])
return buf
}

onMessage(data) {
if (this.msg_len != -1) {
this._data = Buffer.concat([this._data, data])
this._data = window.Buffer.concat([this._data, data])
}
else {
let buf_len = data.slice(0,4)
Expand All @@ -59,13 +59,17 @@ class RpcBase {
console.log("need read more msg....")
return
}
else if (this._data.length - 4 > this.msg_len) {
this._data = this._data.slice(0, this.msg_len + 4)
}

let _str = this._data.toString("ascii", 4)
console.log(this._data.length, this.msg_len)
let _str = this._data.toString("utf8", 4)
var _result = this.msg_to_json(_str)

let _id = _result.id
this.msg_len = -1
this._data = new Buffer(0)
this._data = window.Buffer(0)
if (_result.hasOwnProperty("result")) {
this.id_to_resolve[_id](_result.result)
}
Expand Down
2 changes: 1 addition & 1 deletion lib/modules/jsrpc/transport.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@

var net = require("net")
const net = window.require("net")
var Promise = require("bluebird")

class ClientSocket {
Expand Down
148 changes: 24 additions & 124 deletions lib/modules/viewer/backend/unity3d.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import {Icon} from '../../util/icon'

import {InspectorViewBase} from '../hierarchyViewer'

const RpcClient = require('../../jsrpc/rpcclient')
const clientSocket = require('../../jsrpc/transport')
const Screen = require('../../poco-driver/std/screen')
const Dumper = require('../../poco-driver/std/dumper')

const Promise = window.require('bluebird')
const {spawn} = window.require('child_process')

Expand All @@ -34,139 +39,34 @@ export class Unity3dInspectorView extends InspectorViewBase {
this.state.sdkVersionCode = 'unknown'
autoBind(this)

this.inBox = ''

let python_executable = `${AppResourcePath}/venv-${window.process.platform}/bin/python`
console.log(python_executable)
this.pocoProc = spawn(python_executable, ['-u', '-m', 'poco.drivers.unity3d.repl'])
this.pocoProc.stdout.on('data', data => {
data = data.toString()
this.inBox += data

// parse hierarchy
let hierarchyEndIndex = this.inBox.indexOf(HierarchyBoundaryEnd)
if (hierarchyEndIndex >= 0) {
let hierarchyStartIndex = this.inBox.indexOf(HierarchyBoundary)
let jsonHierarchy = this.inBox.substring(hierarchyStartIndex + HierarchyBoundary.length, hierarchyEndIndex)
this.setState({hierarchyTree: JSON.parse(jsonHierarchy)})
this.inBox = this.inBox.substring(hierarchyEndIndex + HierarchyBoundaryEnd.length)
}

// parse screen
let screenEndIndex = this.inBox.indexOf(ScreenBoundaryEnd)
if (screenEndIndex >= 0) {
let screenStartIndex = this.inBox.indexOf(ScreenBoundary)
let screenData = this.inBox.substring(screenStartIndex + ScreenBoundary.length, screenEndIndex)
this.setState({screen: screenData})
this.inBox = this.inBox.substring(screenEndIndex + ScreenBoundaryEnd.length)
}

// parse profile data
let profileDataEndIndex = this.inBox.indexOf(ProfileDataBoundaryEnd)
if (profileDataEndIndex >= 0) {
let profileDataStartIndex = this.inBox.indexOf(ProfileDataBoundary)
let jsonProfileData = this.inBox.substring(profileDataStartIndex + ProfileDataBoundary.length, profileDataEndIndex)
let pfData = JSON.parse(jsonProfileData)
let {profileData} = this.state
Object.assign(profileData, pfData)
this.setState({profileData})
this.inBox = this.inBox.substring(profileDataEndIndex + ProfileDataBoundaryEnd.length)
}

// parse sdk version code
let sdkVersionCodeEndIndex = this.inBox.indexOf(SDKVersionBoundaryEnd)
if (sdkVersionCodeEndIndex >= 0) {
console.log(this.inBox)
let sdkVersionCodeStartIndex = this.inBox.indexOf(SDKVersionBoundary)
let versionCodeStr = this.inBox.substring(sdkVersionCodeStartIndex + SDKVersionBoundary.length, sdkVersionCodeEndIndex)
this.setState({sdkVersionCode: versionCodeStr})
this.inBox = this.inBox.substring(sdkVersionCodeEndIndex + SDKVersionBoundaryEnd.length)
}
})
this.pocoProc.stderr.on('data', data => {
data = data.toString()
console.error(data)
toastr["warning"](data)
})
this.pocoProc.on('close', exitCode => {
let client_s = new clientSocket.ClientSocket()
let client = new RpcClient(client_s)
this.connection = client.connect(this.props.ip, this.props.port).then(() => {
this.screen = new Screen(client)
this.dumper = new Dumper(client)
this.refresh()
// this.getSDKVersion()
})

this.refresh(720)
this.getSDKVersion()
}

execPy(code) {
this.pocoProc.stdin.write(code)
this.pocoProc.stdin.write('\n')
refreshScreen(width) {
this.screen.getScreen(width).then(res => {
var screenData = "data:image/" + res[1] + ";base64," + res[0]
this.setState({screen: screenData})
})
}

connectAirtestDevice(devUri) {
let code = `
from airtest.core.api import connect_device
connect_device('${devUri}')
`
this.execPy(code)
refreshDumper() {
this.dumper.dumpHierarchy().then(jsonHierarchy => {
this.setState({hierarchyTree: jsonHierarchy})
})
}

refresh(width) {
let isUnityEditor = this.props.platform === 'windows' && this.props.options.isUnityEditor
// 只有windows版的非editor mode 才需要主动connect到device
if (this.props.platform === 'windows' && !this.props.options.isUnityEditor) {
this.connectAirtestDevice(`Windows:///?title_re=${this.props.options.titleRe}&class_name=UnityWndClass`)
}

let code = `
def get_hierarchy_and_screen():
# cache poco instance globally to speed up
poco = globals().get('poco')
if poco is None:
poco = UnityPoco(("${this.props.ip}", ${this.props.port}), ${isUnityEditor ? 'True' : 'False'}, connect_default_device=False)
globals()['poco'] = poco
try:
h = poco.agent.hierarchy.dump()
except Exception as e:
sys.stderr.write('Error: cannot dump hierarchy from remote device. {}'.format(e.message))
sys.stderr.flush()
else:
print("${HierarchyBoundary}")
print(json.dumps(h))
print("${HierarchyBoundaryEnd}")
try:
pf = poco.agent.get_debug_profiling_data()
print("${ProfileDataBoundary}")
print(json.dumps({'dump': pf['dump'], 'dumpSerialize': pf['handleRpcRequest'] - pf['dump']}))
print("${ProfileDataBoundaryEnd}")
except Exception as e:
sys.stderr.write('Error: cannot get debug profiling data from remote device. {}'.format(e.message))
sys.stderr.flush()
try:
s, fmt = poco.snapshot(${width})
except Exception as e:
sys.stderr.write('Error: cannot take screenshot from remote device. {}'.format(e.message))
sys.stderr.flush()
else:
print("${ScreenBoundary}")
print("data:image/" + fmt + ";base64," + s)
print("${ScreenBoundaryEnd}")
try:
pf = poco.agent.get_debug_profiling_data()
print("${ProfileDataBoundary}")
print(json.dumps({'screenshot': pf['screenshot']}))
print("${ProfileDataBoundaryEnd}")
except Exception as e:
sys.stderr.write('Error: cannot get debug profiling data from remote device. {}'.format(e.message))
sys.stderr.flush()
get_hierarchy_and_screen()
# end-proc #
`
this.execPy(code)
this.refreshScreen(width)
this.refreshDumper()
}

getSDKVersion() {
let isUnityEditor = this.props.platform === 'windows' && this.props.options.isUnityEditor
let code = `
Expand Down

0 comments on commit 189a681

Please sign in to comment.