Best JavaScript code snippet using devicefarmer-stf
index.js
Source:index.js
...18 .dependency(require('../../resources/minitouch'))19 .dependency(require('../util/flags'))20 .define(function(options, adb, router, minitouch, flags) {21 var log = logger.createLogger('device:plugins:touch')22 function TouchConsumer(config) {23 EventEmitter.call(this)24 this.actionQueue = []25 this.runningState = TouchConsumer.STATE_STOPPED26 this.desiredState = new StateQueue()27 this.output = null28 this.socket = null29 this.banner = null30 this.touchConfig = config31 this.starter = Promise.resolve(true)32 this.failCounter = new FailCounter(3, 10000)33 this.failCounter.on('exceedLimit', this._failLimitExceeded.bind(this))34 this.failed = false35 this.readableListener = this._readableListener.bind(this)36 this.writeQueue = []37 }38 util.inherits(TouchConsumer, EventEmitter)39 TouchConsumer.STATE_STOPPED = 140 TouchConsumer.STATE_STARTING = 241 TouchConsumer.STATE_STARTED = 342 TouchConsumer.STATE_STOPPING = 443 TouchConsumer.prototype._queueWrite = function(writer) {44 switch (this.runningState) {45 case TouchConsumer.STATE_STARTED:46 writer.call(this)47 break48 default:49 this.writeQueue.push(writer)50 break51 }52 }53 TouchConsumer.prototype.touchDown = function(point) {54 this._queueWrite(function() {55 return this._write(util.format(56 'd %s %s %s %s\n'57 , point.contact58 , Math.floor(this.touchConfig.origin.x(point) * this.banner.maxX)59 , Math.floor(this.touchConfig.origin.y(point) * this.banner.maxY)60 , Math.floor((point.pressure || 0.5) * this.banner.maxPressure)61 ))62 })63 }64 TouchConsumer.prototype.touchMove = function(point) {65 this._queueWrite(function() {66 return this._write(util.format(67 'm %s %s %s %s\n'68 , point.contact69 , Math.floor(this.touchConfig.origin.x(point) * this.banner.maxX)70 , Math.floor(this.touchConfig.origin.y(point) * this.banner.maxY)71 , Math.floor((point.pressure || 0.5) * this.banner.maxPressure)72 ))73 })74 }75 TouchConsumer.prototype.touchUp = function(point) {76 this._queueWrite(function() {77 return this._write(util.format(78 'u %s\n'79 , point.contact80 ))81 })82 }83 TouchConsumer.prototype.touchCommit = function() {84 this._queueWrite(function() {85 return this._write('c\n')86 })87 }88 TouchConsumer.prototype.touchReset = function() {89 this._queueWrite(function() {90 return this._write('r\n')91 })92 }93 TouchConsumer.prototype.tap = function(point) {94 this.touchDown(point)95 this.touchCommit()96 this.touchUp(point)97 this.touchCommit()98 }99 TouchConsumer.prototype._ensureState = function() {100 if (this.desiredState.empty()) {101 return102 }103 if (this.failed) {104 log.warn('Will not apply desired state due to too many failures')105 return106 }107 switch (this.runningState) {108 case TouchConsumer.STATE_STARTING:109 case TouchConsumer.STATE_STOPPING:110 // Just wait.111 break112 case TouchConsumer.STATE_STOPPED:113 if (this.desiredState.next() === TouchConsumer.STATE_STARTED) {114 this.runningState = TouchConsumer.STATE_STARTING115 this.starter = this._startService().bind(this)116 .then(function(out) {117 this.output = new RiskyStream(out)118 .on('unexpectedEnd', this._outputEnded.bind(this))119 return this._readOutput(this.output.stream)120 })121 .then(function() {122 return this._connectService()123 })124 .then(function(socket) {125 this.socket = new RiskyStream(socket)126 .on('unexpectedEnd', this._socketEnded.bind(this))127 return this._readBanner(this.socket.stream)128 })129 .then(function(banner) {130 this.banner = banner131 return this._readUnexpected(this.socket.stream)132 })133 .then(function() {134 this._processWriteQueue()135 })136 .then(function() {137 this.runningState = TouchConsumer.STATE_STARTED138 this.emit('start')139 })140 .catch(Promise.CancellationError, function() {141 return this._stop()142 })143 .catch(function(err) {144 return this._stop().finally(function() {145 this.failCounter.inc()146 this.emit('error', err)147 })148 })149 .finally(function() {150 this._ensureState()151 })152 }153 else {154 setImmediate(this._ensureState.bind(this))155 }156 break157 case TouchConsumer.STATE_STARTED:158 if (this.desiredState.next() === TouchConsumer.STATE_STOPPED) {159 this.runningState = TouchConsumer.STATE_STOPPING160 this._stop().finally(function() {161 this._ensureState()162 })163 }164 else {165 setImmediate(this._ensureState.bind(this))166 }167 break168 }169 }170 TouchConsumer.prototype.start = function() {171 log.info('Requesting touch consumer to start')172 this.desiredState.push(TouchConsumer.STATE_STARTED)173 this._ensureState()174 }175 TouchConsumer.prototype.stop = function() {176 log.info('Requesting touch consumer to stop')177 this.desiredState.push(TouchConsumer.STATE_STOPPED)178 this._ensureState()179 }180 TouchConsumer.prototype.restart = function() {181 switch (this.runningState) {182 case TouchConsumer.STATE_STARTED:183 case TouchConsumer.STATE_STARTING:184 this.starter.cancel()185 this.desiredState.push(TouchConsumer.STATE_STOPPED)186 this.desiredState.push(TouchConsumer.STATE_STARTED)187 this._ensureState()188 break189 }190 }191 TouchConsumer.prototype._configChanged = function() {192 this.restart()193 }194 TouchConsumer.prototype._socketEnded = function() {195 log.warn('Connection to minitouch ended unexpectedly')196 this.failCounter.inc()197 this.restart()198 }199 TouchConsumer.prototype._outputEnded = function() {200 log.warn('Shell keeping minitouch running ended unexpectedly')201 this.failCounter.inc()202 this.restart()203 }204 TouchConsumer.prototype._failLimitExceeded = function(limit, time) {205 this._stop()206 this.failed = true207 this.emit('error', new Error(util.format(208 'Failed more than %d times in %dms'209 , limit210 , time211 )))212 }213 TouchConsumer.prototype._startService = function() {214 log.info('Launching touch service')215 return minitouch.run()216 .timeout(10000)217 }218 TouchConsumer.prototype._readOutput = function(out) {219 out.pipe(split()).on('data', function(line) {220 var trimmed = line.toString().trim()221 if (trimmed === '') {222 return223 }224 if (/ERROR/.test(line)) {225 log.fatal('minitouch error: "%s"', line)226 return lifecycle.fatal()227 }228 log.info('minitouch says: "%s"', line)229 })230 }231 TouchConsumer.prototype._connectService = function() {232 function tryConnect(times, delay) {233 return adb.openLocal(options.serial, 'localabstract:minitouch')234 .timeout(10000)235 .then(function(out) {236 return out237 })238 .catch(function(err) {239 if (/closed/.test(err.message) && times > 1) {240 return Promise.delay(delay)241 .then(function() {242 return tryConnect(times - 1, delay * 2)243 })244 }245 return Promise.reject(err)246 })247 }248 log.info('Connecting to minitouch service')249 // SH-03G can be very slow to start sometimes. Make sure we try long250 // enough.251 return tryConnect(7, 100)252 }253 TouchConsumer.prototype._stop = function() {254 return this._disconnectService(this.socket).bind(this)255 .timeout(2000)256 .then(function() {257 return this._stopService(this.output).timeout(10000)258 })259 .then(function() {260 this.runningState = TouchConsumer.STATE_STOPPED261 this.emit('stop')262 })263 .catch(function(err) {264 // In practice we _should_ never get here due to _stopService()265 // being quite aggressive. But if we do, well... assume it266 // stopped anyway for now.267 this.runningState = TouchConsumer.STATE_STOPPED268 this.emit('error', err)269 this.emit('stop')270 })271 .finally(function() {272 this.output = null273 this.socket = null274 this.banner = null275 })276 }277 TouchConsumer.prototype._disconnectService = function(socket) {278 log.info('Disconnecting from minitouch service')279 if (!socket || socket.ended) {280 return Promise.resolve(true)281 }282 socket.stream.removeListener('readable', this.readableListener)283 var endListener284 return new Promise(function(resolve) {285 socket.on('end', endListener = function() {286 resolve(true)287 })288 socket.stream.resume()289 socket.end()290 })291 .finally(function() {292 socket.removeListener('end', endListener)293 })294 }295 TouchConsumer.prototype._stopService = function(output) {296 log.info('Stopping minitouch service')297 if (!output || output.ended) {298 return Promise.resolve(true)299 }300 var pid = this.banner ? this.banner.pid : -1301 function kill(signal) {302 if (pid <= 0) {303 return Promise.reject(new Error('Minitouch service pid is unknown'))304 }305 var signum = {306 SIGTERM: -15307 , SIGKILL: -9308 }[signal]309 log.info('Sending %s to minitouch', signal)310 return Promise.all([311 output.waitForEnd()312 , adb.shell(options.serial, ['kill', signum, pid])313 .then(adbkit.util.readAll)314 .return(true)315 ])316 .timeout(2000)317 }318 function kindKill() {319 return kill('SIGTERM')320 }321 function forceKill() {322 return kill('SIGKILL')323 }324 function forceEnd() {325 log.info('Ending minitouch I/O as a last resort')326 output.end()327 return Promise.resolve(true)328 }329 return kindKill()330 .catch(Promise.TimeoutError, forceKill)331 .catch(forceEnd)332 }333 TouchConsumer.prototype._readBanner = function(socket) {334 log.info('Reading minitouch banner')335 var parser = new Parser(socket)336 var banner = {337 pid: -1 // @todo338 , version: 0339 , maxContacts: 0340 , maxX: 0341 , maxY: 0342 , maxPressure: 0343 }344 function readVersion() {345 return parser.readLine()346 .then(function(chunk) {347 var args = chunk.toString().split(/ /g)348 switch (args[0]) {349 case 'v':350 banner.version = Number(args[1])351 break352 default:353 throw new Error(util.format(354 'Unexpected output "%s", expecting version line'355 , chunk356 ))357 }358 })359 }360 function readLimits() {361 return parser.readLine()362 .then(function(chunk) {363 var args = chunk.toString().split(/ /g)364 switch (args[0]) {365 case '^':366 banner.maxContacts = args[1]367 banner.maxX = args[2]368 banner.maxY = args[3]369 banner.maxPressure = args[4]370 break371 default:372 throw new Error(util.format(373 'Unknown output "%s", expecting limits line'374 , chunk375 ))376 }377 })378 }379 function readPid() {380 return parser.readLine()381 .then(function(chunk) {382 var args = chunk.toString().split(/ /g)383 switch (args[0]) {384 case '$':385 banner.pid = Number(args[1])386 break387 default:388 throw new Error(util.format(389 'Unexpected output "%s", expecting pid line'390 , chunk391 ))392 }393 })394 }395 return readVersion()396 .then(readLimits)397 .then(readPid)398 .return(banner)399 .timeout(2000)400 }401 TouchConsumer.prototype._readUnexpected = function(socket) {402 socket.on('readable', this.readableListener)403 // We may already have data pending.404 this.readableListener()405 }406 TouchConsumer.prototype._readableListener = function() {407 var chunk408 while ((chunk = this.socket.stream.read())) {409 log.warn('Unexpected output from minitouch socket', chunk)410 }411 }412 TouchConsumer.prototype._processWriteQueue = function() {413 for (var i = 0, l = this.writeQueue.length; i < l; ++i) {414 this.writeQueue[i].call(this)415 }416 this.writeQueue = []417 }418 TouchConsumer.prototype._write = function(chunk) {419 this.socket.stream.write(chunk)420 }421 function startConsumer() {422 var touchConsumer = new TouchConsumer({423 // Usually the touch origin is the same as the display's origin,424 // but sometimes it might not be.425 origin: (function(origin) {426 log.info('Touch origin is %s', origin)427 return {428 'top left': {429 x: function(point) {430 return point.x431 }432 , y: function(point) {433 return point.y434 }435 }436 // So far the only device we've seen exhibiting this behavior...
Using AI Code Generation
1var TouchConsumer = require('devicefarmer-stf-client').TouchConsumer;2var touchConsumer = new TouchConsumer();3touchConsumer.on('data', function(data) {4 console.log(data);5});6touchConsumer.on('end', function(data) {7 console.log('end');8});9touchConsumer.on('error', function(data) {10 console.log('error');11});12var TouchProducer = require('devicefarmer-stf-client').TouchProducer;13var touchProducer = new TouchProducer();14touchProducer.on('data', function(data) {15 console.log(data);16});17touchProducer.on('end', function(data) {18 console.log('end');19});20touchProducer.on('error', function(data) {21 console.log('error');22});23var DeviceConsumer = require('devicefarmer-stf-client').DeviceConsumer;24var deviceConsumer = new DeviceConsumer();25deviceConsumer.on('data', function(data) {26 console.log(data);27});28deviceConsumer.on('end', function(data) {29 console.log('end');30});31deviceConsumer.on('error', function(data) {32 console.log('error');33});34var DeviceProducer = require('devicefarmer-stf-client').DeviceProducer;35var deviceProducer = new DeviceProducer();36deviceProducer.on('data', function(data) {37 console.log(data);38});39deviceProducer.on('end', function(data) {40 console.log('end');41});42deviceProducer.on('error', function(data) {43 console.log('error');44});45var DeviceConsumer = require('devicefarmer-stf-client').DeviceConsumer;46var deviceConsumer = new DeviceConsumer();47deviceConsumer.on('data', function(data) {48 console.log(data);49});50deviceConsumer.on('end', function(data) {51 console.log('end');52});53deviceConsumer.on('error', function(data) {54 console.log('error');55});
Using AI Code Generation
1var TouchConsumer = require('devicefarmer-stf').TouchConsumer;2var touchConsumer = new TouchConsumer();3touchConsumer.on('connect', function() {4 console.log('Connected to the remote control server');5});6touchConsumer.on('disconnect', function() {7 console.log('Disconnected from the remote control server');8});9touchConsumer.on('error', function() {10 console.log('Error connecting to the remote control server');11});12touchConsumer.on('message', function(message) {13 console.log('Received message from the remote control server');14 console.log(message);15});16touchConsumer.on('touch', function(touch) {17 console.log('Received touch from the remote control server');18 console.log(touch);19});20touchConsumer.on('swipe', function(swipe) {21 console.log('Received swipe from the remote control server');22 console.log(swipe);23});24touchConsumer.on('rotate', function(rotate) {25 console.log('Received rotate from the remote control server');26 console.log(rotate);27});28touchConsumer.on('keyevent', function(keyevent) {29 console.log('Received keyevent from the remote control server');30 console.log(keyevent);31});32touchConsumer.on('text', function(text) {33 console.log('Received text from the remote control server');34 console.log(text);35});36touchConsumer.on('clipboard', function(clipboard) {37 console.log('Received clipboard from the remote control server');38 console.log(clipboard);39});40touchConsumer.on('shell', function(shell) {41 console.log('Received shell from the remote control server');42 console.log(shell);43});44touchConsumer.on('exec', function(exec) {45 console.log('Received exec from the remote control server');46 console.log(exec);47});48touchConsumer.on('browser', function(browser) {49 console.log('Received browser from the remote control server');50 console.log(browser);51});52touchConsumer.on('file', function(file) {53 console.log('Received file from the remote control server');54 console.log(file);55});56touchConsumer.on('custom', function(custom) {57 console.log('Received custom from the remote control server');58 console.log(custom);59});60touchConsumer.on('ping', function(ping) {61 console.log('Received ping from the remote control server');62 console.log(ping);63});64touchConsumer.on('pong', function(pong) {65 console.log('Received pong from the remote control server');
Using AI Code Generation
1var Client = require('devicefarmer-stf-client');2client.getDevices(function(err, devices) {3 devices[0].touchConsumer(function(err, touchConsumer) {4 touchConsumer.tap(100, 200, function(err) {5 console.log('Tapped');6 });7 });8});9tap(x, y, callback)10swipe(x1, y1, x2, y2, callback)11press(x, y, callback)12release(x, y, callback)13touchConsumer.tap(100, 200).swipe(100, 200, 300, 400).press(100, 200).release(100, 200, function(err) {14 console.log('Done');15});16touchConsumer.tap(100, 200).swipe(touchConsumer.x, touchConsumer.y, 300, 400).press(100, 200).release(100, 200, function(err) {17 console.log('Done');18});19The above code will tap on the device at the coordinates (100,200), then swipe from (100,200) to
Using AI Code Generation
1var DeviceFarmer = require('devicefarmer-stf-client');2var deviceFarmer = new DeviceFarmer();3deviceFarmer.getDevice('serial', function(err, device) {4 if (err) {5 console.log('error: ' + err);6 return;7 }8 device.TouchConsumer(function(err, touchConsumer) {9 if (err) {10 console.log('error: ' + err);11 return;12 }13 touchConsumer.touch(100, 100);14 });15});16var DeviceFarmer = require('devicefarmer-stf-client');17var deviceFarmer = new DeviceFarmer();18deviceFarmer.getDevice('serial', function(err, device) {19 if (err) {20 console.log('error: ' + err);21 return;22 }23 device.TouchConsumer(function(err, touchConsumer) {24 if (err) {25 console.log('error: ' + err);26 return;27 }28 touchConsumer.touch(100, 100);29 });30});31var DeviceFarmer = require('devicefarmer-stf-client');32var deviceFarmer = new DeviceFarmer();33deviceFarmer.getDevice('serial', function(err, device) {34 if (err) {35 console.log('error: ' + err);36 return;37 }38 device.TouchConsumer(function(err, touchConsumer) {39 if (err) {40 console.log('error: ' + err);41 return;42 }43 touchConsumer.touch(100, 100);44 });45});46Device#TouchConsumer(callback)47callback: function(err, touchConsumer)48device.TouchConsumer(function(err, touchConsumer) {49 if (err) {50 console.log('error: ' + err);51 return;52 }53 touchConsumer.touch(100, 100);54});55TouchConsumer#touch(x, y, callback)56callback: function(err)57TouchConsumer#swipe(x1, y1, x2, y2,
Using AI Code Generation
1var TouchConsumer = require('devicefarmer-stf-client').TouchConsumer;2touchConsumer.on('error', function(error) {3 console.log('error:', error);4});5touchConsumer.on('connect', function() {6 console.log('connected');7});8touchConsumer.on('disconnect', function() {9 console.log('disconnected');10});11touchConsumer.on('message', function(message) {12 console.log('message:', message);13});14touchConsumer.on('end', function() {15 console.log('end');16});17touchConsumer.connect();18var TouchConsumer = require('devicefarmer-stf-client').TouchConsumer;19touchConsumer.on('error', function(error) {20 console.log('error:', error);21});22touchConsumer.on('connect', function() {23 console.log('connected');24});25touchConsumer.on('disconnect', function() {26 console.log('disconnected');27});28touchConsumer.on('message', function(message) {29 console.log('message:', message);30});31touchConsumer.on('end', function() {32 console.log('end');33});34touchConsumer.connect();35var TouchConsumer = require('devicefarmer-stf-client').TouchConsumer;36touchConsumer.on('error', function(error) {37 console.log('error:', error);38});39touchConsumer.on('connect', function() {40 console.log('connected');41});42touchConsumer.on('disconnect', function() {43 console.log('disconnected');44});45touchConsumer.on('message', function(message) {46 console.log('message:', message);47});48touchConsumer.on('end', function() {49 console.log('end');50});51touchConsumer.connect();52var TouchConsumer = require('devicefarmer-stf-client').TouchConsumer;53touchConsumer.on('error
Using AI Code Generation
1var touchConsumer = require('devicefarmer-stf').TouchConsumer;2var consumer = new touchConsumer();3consumer.on('ready', function() {4 console.log('TouchConsumer ready');5 consumer.touch(100, 100);6});7consumer.on('error', function(err) {8 console.log('TouchConsumer error: ' + err);9});10consumer.on('end', function() {11 console.log('TouchConsumer end');12});13consumer.connect(3000);
Using AI Code Generation
1var TouchConsumer = require('devicefarmer-stf').TouchConsumer;2touchConsumer.touch(100, 100);3var TouchConsumer = require('devicefarmer-stf').TouchConsumer;4touchConsumer.touch(100, 100);5var touch = require('devicefarmer-stf').touch;6var swipe = require('devicefarmer-stf').swipe;
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!