speedtest_worker.js 22 KB

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