speedtest_worker.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /*
  2. HTML5 Speedtest v4.5.5
  3. by Federico Dossena
  4. https://github.com/adolfintel/speedtest/
  5. GNU LGPLv3 License
  6. */
  7. // data reported to main thread
  8. var testStatus = -1 // -1=not started, 0=starting, 1=download test, 2=ping+jitter test, 3=upload test, 4=finished, 5=abort/error
  9. var dlStatus = '' // download speed in megabit/s with 2 decimal digits
  10. var ulStatus = '' // upload speed in megabit/s with 2 decimal digits
  11. var pingStatus = '' // ping in milliseconds with 2 decimal digits
  12. var jitterStatus = '' // jitter in milliseconds with 2 decimal digits
  13. var clientIp = '' // client's IP address as reported by getIP.php
  14. var dlProgress = 0 //progress of download test 0-1
  15. var ulProgress = 0 //progress of upload test 0-1
  16. var pingProgress = 0 //progress of ping+jitter test 0-1
  17. var log='' //telemetry log
  18. function tlog(s){log+=Date.now()+': '+s+'\n'}
  19. function twarn(s){log+=Date.now()+' WARN: '+s+'\n'; console.warn(s)}
  20. // test settings. can be overridden by sending specific values with the start command
  21. var settings = {
  22. test_order: "IP_D_U", //order in which tests will be performed as a string. D=Download, U=Upload, P=Ping+Jitter, I=IP, _=1 second delay
  23. time_ul: 15, // duration of upload test in seconds
  24. time_dl: 15, // duration of download test in seconds
  25. time_ulGraceTime: 3, //time to wait in seconds before actually measuring ul speed (wait for buffers to fill)
  26. time_dlGraceTime: 1.5, //time to wait in seconds before actually measuring dl speed (wait for TCP window to increase)
  27. count_ping: 35, // number of pings to perform in ping test
  28. url_dl: 'garbage.php', // path to a large file or garbage.php, used for download test. must be relative to this js file
  29. url_ul: 'empty.php', // path to an empty file, used for upload test. must be relative to this js file
  30. url_ping: 'empty.php', // path to an empty file, used for ping test. must be relative to this js file
  31. url_getIp: 'getIP.php', // path to getIP.php relative to this js file, or a similar thing that outputs the client's ip
  32. getIp_ispInfo: true, //if set to true, the server will include ISP info with the IP address
  33. getIp_ispInfo_distance: 'km', //km or mi=estimate distance from server in km/mi; set to false to disable distance estimation. getIp_ispInfo must be enabled in order for this to work
  34. xhr_dlMultistream: 10, // number of download streams to use (can be different if enable_quirks is active)
  35. xhr_ulMultistream: 3, // number of upload streams to use (can be different if enable_quirks is active)
  36. xhr_multistreamDelay: 300, //how much concurrent requests should be delayed
  37. xhr_ignoreErrors: 1, // 0=fail on errors, 1=attempt to restart a stream if it fails, 2=ignore all errors
  38. xhr_dlUseBlob: false, // if set to true, it reduces ram usage but uses the hard drive (useful with large garbagePhp_chunkSize and/or high xhr_dlMultistream)
  39. xhr_ul_blob_megabytes: 20, //size in megabytes of the upload blobs sent in the upload test (forced to 4 on chrome mobile)
  40. garbagePhp_chunkSize: 20, // size of chunks sent by garbage.php (can be different if enable_quirks is active)
  41. enable_quirks: true, // enable quirks for specific browsers. currently it overrides settings to optimize for specific browsers, unless they are already being overridden with the start command
  42. ping_allowPerformanceApi: true, // if enabled, the ping test will attempt to calculate the ping more precisely using the Performance API. Currently works perfectly in Chrome, badly in Edge, and not at all in Firefox. If Performance API is not supported or the result is obviously wrong, a fallback is provided.
  43. overheadCompensationFactor: 1.06, //can be changed to compensatie for transport overhead. (see doc.md for some other values)
  44. useMebibits: false, //if set to true, speed will be reported in mebibits/s instead of megabits/s
  45. telemetry_level: 0, // 0=disabled, 1=basic (results only), 2=full (results+log)
  46. url_telemetry: 'telemetry.php' // path to the script that adds telemetry data to the database
  47. }
  48. var xhr = null // array of currently active xhr requests
  49. var interval = null // timer used in tests
  50. var test_pointer = 0 //pointer to the next test to run inside settings.test_order
  51. /*
  52. this function is used on URLs passed in the settings to determine whether we need a ? or an & as a separator
  53. */
  54. function url_sep (url) { return url.match(/\?/) ? '&' : '?'; }
  55. /*
  56. listener for commands from main thread to this worker.
  57. commands:
  58. -status: returns the current status as a string of values spearated by a semicolon (;) in this order: testStatus;dlStatus;ulStatus;pingStatus;clientIp;jitterStatus;dlProgress;ulProgress;pingProgress
  59. -abort: aborts the current test
  60. -start: starts the test. optionally, settings can be passed as JSON.
  61. example: start {"time_ul":"10", "time_dl":"10", "count_ping":"50"}
  62. */
  63. this.addEventListener('message', function (e) {
  64. var params = e.data.split(' ')
  65. if (params[0] === 'status') { // return status
  66. postMessage(testStatus + ';' + dlStatus + ';' + ulStatus + ';' + pingStatus + ';' + clientIp + ';' + jitterStatus + ';' + dlProgress + ';' + ulProgress + ';' + pingProgress)
  67. }
  68. if (params[0] === 'start' && testStatus === -1) { // start new test
  69. testStatus = 0
  70. try {
  71. // parse settings, if present
  72. var s = {}
  73. try{
  74. var ss = e.data.substring(5)
  75. if (ss) s = JSON.parse(ss)
  76. }catch(e){ twarn('Error parsing custom settings JSON. Please check your syntax') }
  77. //copy custom settings
  78. for(var key in s){
  79. if(typeof settings[key] !== 'undefined') settings[key]=s[key]; else twarn("Unknown setting ignored: "+key);
  80. }
  81. // quirks for specific browsers. apply only if not overridden. more may be added in future releases
  82. if (settings.enable_quirks||(typeof s.enable_quirks !== 'undefined' && s.enable_quirks)) {
  83. var ua = navigator.userAgent
  84. if (/Firefox.(\d+\.\d+)/i.test(ua)) {
  85. if(typeof s.xhr_ulMultistream === 'undefined'){
  86. // ff more precise with 1 upload stream
  87. settings.xhr_ulMultistream = 1
  88. }
  89. }
  90. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  91. if(typeof s.xhr_dlMultistream === 'undefined'){
  92. // edge more precise with 3 download streams
  93. settings.xhr_dlMultistream = 3
  94. }
  95. }
  96. if (/Chrome.(\d+)/i.test(ua) && (!!self.fetch)) {
  97. if(typeof s.xhr_dlMultistream === 'undefined'){
  98. // chrome more precise with 5 streams
  99. settings.xhr_dlMultistream = 5
  100. }
  101. }
  102. }
  103. if (/Edge.(\d+\.\d+)/i.test(ua)) {
  104. //Edge 15 introduced a bug that causes onprogress events to not get fired, we have to use the "small chunks" workaround that reduces accuracy
  105. settings.forceIE11Workaround = true
  106. }
  107. if (/Chrome.(\d+)/i.test(ua)&&/Android|iPhone|iPad|iPod|Windows Phone/i.test(ua)){ //cheap af
  108. //Chrome mobile introduced a limitation somewhere around version 65, we have to limit XHR upload size to 4 megabytes
  109. settings.xhr_ul_blob_megabytes=4;
  110. }
  111. //telemetry_level has to be parsed and not just copied
  112. if(typeof s.telemetry_level !== 'undefined') settings.telemetry_level = s.telemetry_level === 'basic' ? 1 : s.telemetry_level === 'full' ? 2 : 0; // telemetry level
  113. //transform test_order to uppercase, just in case
  114. settings.test_order=settings.test_order.toUpperCase();
  115. } catch (e) { twarn('Possible error in custom test settings. Some settings may not be applied. Exception: '+e) }
  116. // run the tests
  117. tlog(JSON.stringify(settings))
  118. test_pointer=0;
  119. var iRun=false,dRun=false,uRun=false,pRun=false;
  120. var runNextTest=function(){
  121. if(testStatus==5) return;
  122. if(test_pointer>=settings.test_order.length){testStatus=4; sendTelemetry(); return;}
  123. switch(settings.test_order.charAt(test_pointer)){
  124. case 'I':{test_pointer++; if(iRun) {runNextTest(); return;} else iRun=true; getIp(runNextTest);} break;
  125. case 'D':{test_pointer++; if(dRun) {runNextTest(); return;} else dRun=true; testStatus=1; dlTest(runNextTest);} break;
  126. case 'U':{test_pointer++; if(uRun) {runNextTest(); return;} else uRun=true; testStatus=3; ulTest(runNextTest);} break;
  127. case 'P':{test_pointer++; if(pRun) {runNextTest(); return;} else pRun=true; testStatus=2; pingTest(runNextTest);} break;
  128. case '_':{test_pointer++; setTimeout(runNextTest,1000);} break;
  129. default: test_pointer++;
  130. }
  131. }
  132. runNextTest()
  133. }
  134. if (params[0] === 'abort') { // abort command
  135. tlog('manually aborted')
  136. clearRequests() // stop all xhr activity
  137. runNextTest=null;
  138. if (interval) clearInterval(interval) // clear timer if present
  139. if (settings.telemetry_level > 1) sendTelemetry()
  140. testStatus = 5; dlStatus = ''; ulStatus = ''; pingStatus = ''; jitterStatus = '' // set test as aborted
  141. }
  142. })
  143. // stops all XHR activity, aggressively
  144. function clearRequests () {
  145. tlog('stopping pending XHRs')
  146. if (xhr) {
  147. for (var i = 0; i < xhr.length; i++) {
  148. try { xhr[i].onprogress = null; xhr[i].onload = null; xhr[i].onerror = null } catch (e) { }
  149. try { xhr[i].upload.onprogress = null; xhr[i].upload.onload = null; xhr[i].upload.onerror = null } catch (e) { }
  150. try { xhr[i].abort() } catch (e) { }
  151. try { delete (xhr[i]) } catch (e) { }
  152. }
  153. xhr = null
  154. }
  155. }
  156. // gets client's IP using url_getIp, then calls the done function
  157. var ipCalled = false // used to prevent multiple accidental calls to getIp
  158. function getIp (done) {
  159. tlog('getIp')
  160. if (ipCalled) return; else ipCalled = true // getIp already called?
  161. xhr = new XMLHttpRequest()
  162. xhr.onload = function () {
  163. tlog("IP: "+xhr.responseText)
  164. clientIp = xhr.responseText
  165. done()
  166. }
  167. xhr.onerror = function () {
  168. tlog('getIp failed')
  169. done()
  170. }
  171. xhr.open('GET', settings.url_getIp + url_sep(settings.url_getIp) + (settings.getIp_ispInfo?("isp=true"+(settings.getIp_ispInfo_distance?("&distance="+settings.getIp_ispInfo_distance+"&"):"&")):"&") + 'r=' + Math.random(), true)
  172. xhr.send()
  173. }
  174. // download test, calls done function when it's over
  175. var dlCalled = false // used to prevent multiple accidental calls to dlTest
  176. function dlTest (done) {
  177. tlog('dlTest')
  178. if (dlCalled) return; else dlCalled = true // dlTest already called?
  179. var totLoaded = 0.0, // total number of loaded bytes
  180. startT = new Date().getTime(), // timestamp when test was started
  181. graceTimeDone = false, //set to true after the grace time is past
  182. failed = false // set to true if a stream fails
  183. xhr = []
  184. // function to create a download stream. streams are slightly delayed so that they will not end at the same time
  185. var testStream = function (i, delay) {
  186. setTimeout(function () {
  187. if (testStatus !== 1) return // delayed stream ended up starting after the end of the download test
  188. tlog('dl test stream started '+i+' '+delay)
  189. var prevLoaded = 0 // number of bytes loaded last time onprogress was called
  190. var x = new XMLHttpRequest()
  191. xhr[i] = x
  192. xhr[i].onprogress = function (event) {
  193. tlog('dl stream progress event '+i+' '+event.loaded)
  194. if (testStatus !== 1) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the download test
  195. // progress event, add number of new loaded bytes to totLoaded
  196. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  197. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  198. totLoaded += loadDiff
  199. prevLoaded = event.loaded
  200. }.bind(this)
  201. xhr[i].onload = function () {
  202. // the large file has been loaded entirely, start again
  203. tlog('dl stream finished '+i)
  204. try { xhr[i].abort() } catch (e) { } // reset the stream data to empty ram
  205. testStream(i, 0)
  206. }.bind(this)
  207. xhr[i].onerror = function () {
  208. // error
  209. tlog('dl stream failed '+i)
  210. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  211. try { xhr[i].abort() } catch (e) { }
  212. delete (xhr[i])
  213. if (settings.xhr_ignoreErrors === 1) testStream(i, 0) //restart stream
  214. }.bind(this)
  215. // send xhr
  216. try { if (settings.xhr_dlUseBlob) xhr[i].responseType = 'blob'; else xhr[i].responseType = 'arraybuffer' } catch (e) { }
  217. xhr[i].open('GET', settings.url_dl + url_sep(settings.url_dl) + 'r=' + Math.random() + '&ckSize=' + settings.garbagePhp_chunkSize, true) // random string to prevent caching
  218. xhr[i].send()
  219. }.bind(this), 1 + delay)
  220. }.bind(this)
  221. // open streams
  222. for (var i = 0; i < settings.xhr_dlMultistream; i++) {
  223. testStream(i, settings.xhr_multistreamDelay * i)
  224. }
  225. // every 200ms, update dlStatus
  226. interval = setInterval(function () {
  227. tlog('DL: '+dlStatus+(graceTimeDone?'':' (in grace time)'))
  228. var t = new Date().getTime() - startT
  229. if (graceTimeDone) dlProgress = t / (settings.time_dl * 1000)
  230. if (t < 200) return
  231. if (!graceTimeDone){
  232. if (t > 1000 * settings.time_dlGraceTime){
  233. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  234. startT = new Date().getTime()
  235. totLoaded = 0.0;
  236. }
  237. graceTimeDone = true;
  238. }
  239. }else{
  240. var speed = totLoaded / (t / 1000.0)
  241. dlStatus = ((speed * 8 * settings.overheadCompensationFactor)/(settings.useMebibits?1048576:1000000)).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
  242. if (((t / 1000.0) > settings.time_dl && dlStatus > 0) || failed) { // test is over, stop streams and timer
  243. if (failed || isNaN(dlStatus)) dlStatus = 'Fail'
  244. clearRequests()
  245. clearInterval(interval)
  246. dlProgress = 1
  247. tlog('dlTest finished '+dlStatus)
  248. done()
  249. }
  250. }
  251. }.bind(this), 200)
  252. }
  253. // upload test, calls done function whent it's over
  254. var ulCalled = false // used to prevent multiple accidental calls to ulTest
  255. function ulTest (done) {
  256. tlog('ulTest')
  257. if (ulCalled) return; else ulCalled = true // ulTest already called?
  258. // garbage data for upload test
  259. var r = new ArrayBuffer(1048576)
  260. var maxInt=Math.pow(2,32)-1;
  261. try { r = new Uint32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random()*maxInt } catch (e) { }
  262. var req = []
  263. var reqsmall = []
  264. for (var i = 0; i < settings.xhr_ul_blob_megabytes; i++) req.push(r)
  265. req = new Blob(req)
  266. r = new ArrayBuffer(262144)
  267. try { r = new Uint32Array(r); for (var i = 0; i < r.length; i++)r[i] = Math.random()*maxInt } catch (e) { }
  268. reqsmall.push(r)
  269. reqsmall = new Blob(reqsmall)
  270. var totLoaded = 0.0, // total number of transmitted bytes
  271. startT = new Date().getTime(), // timestamp when test was started
  272. graceTimeDone = false, //set to true after the grace time is past
  273. failed = false // set to true if a stream fails
  274. xhr = []
  275. // function to create an upload stream. streams are slightly delayed so that they will not end at the same time
  276. var testStream = function (i, delay) {
  277. setTimeout(function () {
  278. if (testStatus !== 3) return // delayed stream ended up starting after the end of the upload test
  279. tlog('ul test stream started '+i+' '+delay)
  280. var prevLoaded = 0 // number of bytes transmitted last time onprogress was called
  281. var x = new XMLHttpRequest()
  282. xhr[i] = x
  283. var ie11workaround
  284. if (settings.forceIE11Workaround) ie11workaround = true; else {
  285. try {
  286. xhr[i].upload.onprogress
  287. ie11workaround = false
  288. } catch (e) {
  289. ie11workaround = true
  290. }
  291. }
  292. if (ie11workaround) {
  293. // IE11 workarond: xhr.upload does not work properly, therefore we send a bunch of small 256k requests and use the onload event as progress. This is not precise, especially on fast connections
  294. xhr[i].onload = function () {
  295. tlog('ul stream progress event (ie11wa)')
  296. totLoaded += reqsmall.size;
  297. testStream(i, 0)
  298. }
  299. xhr[i].onerror = function () {
  300. // error, abort
  301. tlog('ul stream failed (ie11wa)')
  302. if (settings.xhr_ignoreErrors === 0) failed = true //abort
  303. try { xhr[i].abort() } catch (e) { }
  304. delete (xhr[i])
  305. if (settings.xhr_ignoreErrors === 1) testStream(i,0); //restart stream
  306. }
  307. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  308. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  309. xhr[i].send(reqsmall)
  310. } else {
  311. // REGULAR version, no workaround
  312. xhr[i].upload.onprogress = function (event) {
  313. tlog('ul stream progress event '+i+' '+event.loaded)
  314. if (testStatus !== 3) { try { x.abort() } catch (e) { } } // just in case this XHR is still running after the upload test
  315. // progress event, add number of new loaded bytes to totLoaded
  316. var loadDiff = event.loaded <= 0 ? 0 : (event.loaded - prevLoaded)
  317. if (isNaN(loadDiff) || !isFinite(loadDiff) || loadDiff < 0) return // just in case
  318. totLoaded += loadDiff
  319. prevLoaded = event.loaded
  320. }.bind(this)
  321. xhr[i].upload.onload = function () {
  322. // this stream sent all the garbage data, start again
  323. tlog('ul stream finished '+i)
  324. testStream(i, 0)
  325. }.bind(this)
  326. xhr[i].upload.onerror = function () {
  327. tlog('ul stream failed '+i)
  328. if (settings.xhr_ignoreErrors === 0) failed=true //abort
  329. try { xhr[i].abort() } catch (e) { }
  330. delete (xhr[i])
  331. if (settings.xhr_ignoreErrors === 1) testStream(i, 0) //restart stream
  332. }.bind(this)
  333. // send xhr
  334. xhr[i].open('POST', settings.url_ul + url_sep(settings.url_ul) + 'r=' + Math.random(), true) // random string to prevent caching
  335. xhr[i].setRequestHeader('Content-Encoding', 'identity') // disable compression (some browsers may refuse it, but data is incompressible anyway)
  336. xhr[i].send(req)
  337. }
  338. }.bind(this), 1)
  339. }.bind(this)
  340. // open streams
  341. for (var i = 0; i < settings.xhr_ulMultistream; i++) {
  342. testStream(i, settings.xhr_multistreamDelay * i)
  343. }
  344. // every 200ms, update ulStatus
  345. interval = setInterval(function () {
  346. tlog('UL: '+ulStatus+(graceTimeDone?'':' (in grace time)'))
  347. var t = new Date().getTime() - startT
  348. if (graceTimeDone) ulProgress = t / (settings.time_ul * 1000)
  349. if (t < 200) return
  350. if (!graceTimeDone){
  351. if (t > 1000 * settings.time_ulGraceTime){
  352. if (totLoaded > 0){ // if the connection is so slow that we didn't get a single chunk yet, do not reset
  353. startT = new Date().getTime()
  354. totLoaded = 0.0;
  355. }
  356. graceTimeDone = true;
  357. }
  358. }else{
  359. var speed = totLoaded / (t / 1000.0)
  360. ulStatus = ((speed * 8 * settings.overheadCompensationFactor)/(settings.useMebibits?1048576:1000000)).toFixed(2) // speed is multiplied by 8 to go from bytes to bits, overhead compensation is applied, then everything is divided by 1048576 or 1000000 to go to megabits/mebibits
  361. if (((t / 1000.0) > settings.time_ul && ulStatus > 0) || failed) { // test is over, stop streams and timer
  362. if (failed || isNaN(ulStatus)) ulStatus = 'Fail'
  363. clearRequests()
  364. clearInterval(interval)
  365. ulProgress = 1
  366. tlog('ulTest finished '+ulStatus)
  367. done()
  368. }
  369. }
  370. }.bind(this), 200)
  371. }
  372. // ping+jitter test, function done is called when it's over
  373. var ptCalled = false // used to prevent multiple accidental calls to pingTest
  374. function pingTest (done) {
  375. tlog('pingTest')
  376. if (ptCalled) return; else ptCalled = true // pingTest already called?
  377. var prevT = null // last time a pong was received
  378. var ping = 0.0 // current ping value
  379. var jitter = 0.0 // current jitter value
  380. var i = 0 // counter of pongs received
  381. var prevInstspd = 0 // last ping time, used for jitter calculation
  382. xhr = []
  383. // ping function
  384. var doPing = function () {
  385. tlog('ping')
  386. pingProgress = i / settings.count_ping
  387. prevT = new Date().getTime()
  388. xhr[0] = new XMLHttpRequest()
  389. xhr[0].onload = function () {
  390. // pong
  391. tlog('pong')
  392. if (i === 0) {
  393. prevT = new Date().getTime() // first pong
  394. } else {
  395. var instspd = new Date().getTime() - prevT
  396. if(settings.ping_allowPerformanceApi){
  397. try{
  398. //try to get accurate performance timing using performance api
  399. var p=performance.getEntries()
  400. p=p[p.length-1]
  401. var d = p.responseStart - p.requestStart //best precision: chromium-based
  402. if (d<=0) d=p.duration //edge: not so good precision because it also considers the overhead and there is no way to avoid it
  403. if (d>0&&d<instspd) instspd=d
  404. }catch(e){
  405. //if not possible, keep the estimate
  406. //firefox can't access performance api from worker: worst precision
  407. tlog('Performance API not supported, using estimate')
  408. }
  409. }
  410. var instjitter = Math.abs(instspd - prevInstspd)
  411. if (i === 1) ping = instspd; /* first ping, can't tell jitter yet*/ else {
  412. ping = ping * 0.9 + instspd * 0.1 // ping, weighted average
  413. jitter = instjitter > jitter ? (jitter * 0.2 + instjitter * 0.8) : (jitter * 0.9 + instjitter * 0.1) // update jitter, weighted average. spikes in ping values are given more weight.
  414. }
  415. prevInstspd = instspd
  416. }
  417. pingStatus = ping.toFixed(2)
  418. jitterStatus = jitter.toFixed(2)
  419. i++
  420. tlog('PING: '+pingStatus+' JITTER: '+jitterStatus)
  421. if (i < settings.count_ping) doPing(); else {pingProgress = 1; done()} // more pings to do?
  422. }.bind(this)
  423. xhr[0].onerror = function () {
  424. // a ping failed, cancel test
  425. tlog('ping failed')
  426. if (settings.xhr_ignoreErrors === 0) { //abort
  427. pingStatus = 'Fail'
  428. jitterStatus = 'Fail'
  429. clearRequests()
  430. done()
  431. }
  432. if (settings.xhr_ignoreErrors === 1) doPing() //retry ping
  433. if (settings.xhr_ignoreErrors === 2){ //ignore failed ping
  434. i++
  435. if (i < settings.count_ping) doPing(); else done() // more pings to do?
  436. }
  437. }.bind(this)
  438. // send xhr
  439. xhr[0].open('GET', settings.url_ping + url_sep(settings.url_ping) + 'r=' + Math.random(), true) // random string to prevent caching
  440. xhr[0].send()
  441. }.bind(this)
  442. doPing() // start first ping
  443. }
  444. // telemetry
  445. function sendTelemetry(){
  446. if (settings.telemetry_level < 1) return
  447. xhr = new XMLHttpRequest()
  448. xhr.onload = function () { console.log('TELEMETRY OL '+xhr.responseText) }
  449. xhr.onerror = function () { console.log('TELEMETRY ERROR '+xhr) }
  450. xhr.open('POST', settings.url_telemetry+url_sep(settings.url_telemetry)+"r="+Math.random(), true);
  451. try{
  452. var fd = new FormData()
  453. fd.append('ispinfo', clientIp) //clientIp also contains ISP info
  454. fd.append('dl', dlStatus)
  455. fd.append('ul', ulStatus)
  456. fd.append('ping', pingStatus)
  457. fd.append('jitter', jitterStatus)
  458. fd.append('log', settings.telemetry_level>1?log:"")
  459. xhr.send(fd)
  460. }catch(ex){
  461. var postData = 'ispinfo='+encodeURIComponent(clientIp)+'dl='+encodeURIComponent(dlStatus)+'&ul='+encodeURIComponent(ulStatus)+'&ping='+encodeURIComponent(pingStatus)+'&jitter='+encodeURIComponent(jitterStatus)+'&log='+encodeURIComponent(settings.telemetry_level>1?log:'')
  462. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  463. xhr.send(postData)
  464. }
  465. }