Node.js中为while循环加暂停解决BlueLinky车辆数据顺序问题
问题:BlueLinky车辆数据插入MariaDB时的顺序与重复插入问题
我使用BlueLinky追踪车辆数据,已成功从服务器拉取数据并上传至MariaDB数据库。目前遇到两个问题:
- 最初数据插入顺序不符合时间戳升序要求,尝试用倒序遍历(
i -= 1)解决但效果不稳定,推测是Hyundai服务器与本地机器的延迟导致,希望通过在while循环中添加暂停/setTimeout机制解决该问题。 - 后续顺序问题解决后,又出现重复插入问题:例如昨天仅行驶4次,日志却显示插入了10次。
以下是我的代码:
// Use the MariaDB Node.js Connector and run npm install mariadb const mariadb = require('mariadb'); const { kill } = require('process'); // Create a connection pool const pool = mariadb.createPool({ host: 'host', port: port, user: 'user', password: 'password', database: 'db' }); //Bluelinky verbinden const BlueLinky = require("bluelinky"); const client = new BlueLinky({ username: 'user', password: 'password', brand: 'brand', // 'hyundai', 'kia' region: 'country', // 'US', 'EU', 'CA' pin: 'pin' }); //get yesterdays date const repdate = new Date(); repdate.setDate(repdate.getDate()-1); // -1 => yesterday, blank => today // called when the client logs in successfully client.on("ready", async () => { const vehicle = client.getVehicle("carnumber"); const trpInfo = await vehicle.tripInfo({year: repdate.getFullYear(), month: repdate.getMonth()+1, day: repdate.getDate()}); if (trpInfo != '') { //Erstelle Datum const tripdaydateraw = trpInfo[0].dayRaw.slice(4,6) + '/' + trpInfo[0].dayRaw.slice(6,8) + '/' + trpInfo[0].dayRaw.slice(0,4); const tripdaydate = trpInfo[0].dayRaw.slice(0,4) + '-' + trpInfo[0].dayRaw.slice(4,6) + '-' + trpInfo[0].dayRaw.slice(6,8); const tripdaynameraw = new Date(tripdaydateraw).toLocaleDateString('de-de', {weekday: 'long'}); const tripdayname = tripdaynameraw; //Erstelle Anzahl der Fahrten const tripdayCnt = trpInfo[0].tripsCount; //Erstelle Tagesdistanz const tripdayDistance = trpInfo[0].distance; //Erstelle Tagedurchschnittsgeschwindigkeit const tripdayavgSpeed = trpInfo[0].speed.avg; //Erstelle maximale Tagesgeschwindigkeit const tripdaymaxSpeed = trpInfo[0].speed.max; // Errechne Anzahl der Fahrten let n = 0, i = tripdayCnt - 1 while(n <= i) { //Restliche Werte definieren //Erstelle Durchschnittsgeschwindigkeit Fahrt const tripavgSpeed = trpInfo[0].trips[i].speed.avg; //Erstelle maximal Fahrgeschwindigkeit const tripmaxSpeed = trpInfo[0].trips[i].speed.max; //Startzeit const strttimstamp = trpInfo[0].trips[i].start; //Enzeit const endtimstamp = trpInfo[0].trips[i].end; //Startdatum const strtdate = strttimstamp.toLocaleDateString(); //toLocaleTimeString konvertiert GMT + 1, Startzeit const strtime = strttimstamp.toLocaleTimeString() ; //Enddatum const enddate = endtimstamp.toLocaleDateString(); //toLocaleTimeString konvertiert GMT + 1, Endzeit const endtime = endtimstamp.toLocaleTimeString(); //Fahrzeit in Minuten const drvtime_minutes = trpInfo[0].trips[i].durations.drive; //Stehzeit in Minuten const idletime_minutes = trpInfo[0].trips[i].durations.idle; //Distanz const drvdistance = trpInfo[0].trips[i].distance; //Tankrechnung const refuel_amt = '0.00' //Werte Ausgeben const tripinfodata = tripdaydate + ', ' + tripdayCnt + ', ' + tripdayDistance + ', ' + tripdayavgSpeed + ', ' + tripdaymaxSpeed + ', ' + tripavgSpeed + ', ' + tripmaxSpeed + ', ' + strtime + ', ' + endtime + ', ' + drvtime_minutes + ', ' + drvdistance + ', ' + tripdayname; //SQL Statement bauen let connection try { connection = await pool.getConnection() } catch(error) { //not connected pool.end() return // or: log and/or throw error again } // run insert query const queryString = "INSERT INTO nightfury_trips (tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, idletime_minutes, drvdistance, tripdayname, refuel_amt) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?);" const queryData = [tripdaydate, tripdayCnt, tripdayDistance, tripdayavgSpeed, tripdaymaxSpeed, tripavgSpeed, tripmaxSpeed, strtime, endtime, drvtime_minutes, idletime_minutes, drvdistance, tripdayname, refuel_amt] let rowsInserted try { rowsInserted = connection.query(queryString, queryData) } catch (error) { // handle error console.log(error); connection.end(); // continue on the next loop n -= 1; continue; } // rows inserted successfully, log them console.log(rowsInserted) n -= 1 } pool.end() console.log('finished!') } // call myLoop. // this is an async function myLoop() .then(() => console.log('myLoop finished!')) .catch((error) => console.error('unexpected error:', error)) });
2023年5月4日22:14 更新
感谢@dave newton的快速回复,当前输出结果如下:
2023-05-04, 2, 3, 41, 89, 35, 60, 20:37:02, 20:42:02, 5, 2, Donnerstag 2023-05-04, 2, 3, 41, 89, 47, 89, 07:49:48, 07:52:48, 3, 1, Donnerstag
我需要按时间戳升序排列数据,因此使用了i -= 1倒序遍历,但该方法并不稳定,推测是Hyundai服务器与本地机器的延迟导致的。
2023年5月6日08:06 更新
感谢@tmilar的帮助,顺序问题已解决,但出现重复插入问题:例如昨天行驶4次,日志却显示插入了10次,运行日志如下:
PS C:\Users\Josi\Downloads\bluelinky> node nightfury_trip_DBupload_sorted.js Register request has failed with Error=PHONE_REGISTRATION_ERROR Retry... 1 Register request has failed with Error=PHONE_REGISTRATION_ERROR Retry... 2 Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> } Promise { <pending> }
内容的提问来源于stack exchange,提问作者moses19850
相关产品推荐
相关产品推荐

