speedtest_worker.js 22 KB

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