BusInfo.js 5.07 KB
let request = require('request');
let cheerio = require('cheerio');

const bus_url = 'http://apis.data.go.kr/6410000/busarrivalservice/getBusArrivalList';
//const stationID = '228000708'; // 사색의광장 들어오는 방향
const gateStationID = '203000125'

require('dotenv').config();

//const BusArrivalUrl = bus_url + '?servicekey=' + process.env.key + '&stationId=' + stationID;// 사색의광장 정류장 버스 도착 정보 조회용
//console.log(BusArrivalUrl);

var routeID = ['200000112', '200000115', '234000016', '200000103'];
var Bus = [];
var busNum = [];
// request(BusArrivalUrl, (err, res, body) => {
//     var $ = cheerio.load(body, {decodeEntities: false});

//     $('busArrivalList').each(function(idx){
//         let route = $(this).find('routeId').text();
//         routeID.push(route);
//     })
//     //console.log(routeID);
// })

const route_url = 'http://apis.data.go.kr/6410000/busrouteservice/getBusRouteInfoItem';
var index = 0;
function getBusNum(){
    var BusRouteUrl = route_url + '?servicekey=' + process.env.key + '&routeId='; // 각 버스 정보 조회용
    BusRouteUrl += routeID[index++];
    //console.log(BusRouteUrl);

    request(BusRouteUrl, (err, res, body) => {
        var $ = cheerio.load(body, {decodeEntities: false});

        $('busRouteInfoItem').each(function(idx){
            var id = $(this).find('routeId').text();            //버스 노선 id
            var num = $(this).find('routeName').text();         //버스 번호
            var firsttime = $(this).find('upFirstTime').text(); //평일 기점 첫차시간
            var lasttime = $(this).find('upLastTime').text();   //평일 기점 막차 시간
            var mintime = $(this).find('peekAlloc').text();     //평일 최소 배차시간
            var maxtime = $(this).find('nPeekAlloc').text();    //평일 최대 배차시간

            //var idx = Bus.findIndex((item, idx) => { return item.routeId = id})

            var newBus = new Object();

            newBus.routeId = id;
            newBus.BusNum = num;
            newBus.FirstTime = firsttime;
            newBus.LastTime = lasttime;
            newBus.MinTime = mintime;
            newBus.MaxTime = maxtime;

            console.log(newBus);
            Bus.push(newBus);
            busNum.push(num);
        })
    })
}

for(var i=0; i<routeID.length; i++){
    getBusNum();
}

const GateBusUrl = bus_url + '?servicekey=' + process.env.key + '&stationId=' + gateStationID; //국제캠 정문 정류장
let date = new Date();
let predictTime = ['-1', '-1', '-1', '-1'];

function predict(){
    console.log(GateBusUrl);
    request(GateBusUrl, (err, res, body) => {
        var $ = cheerio.load(body, {decodeEntities: false});

        $('busArrivalList').each(function(idx){
            let route = $(this).find('routeId').text();

            var index = Bus.findIndex(function(e, idx){ return e.routeId == route;});
            console.log(index);
            if(index > -1){
                //var num = $(this).find('plateNo1').text(); // 버스 차량번호 ex) 70사 1290
                var time = $(this).find('predictTime1').text(); // 버스 예상 도착시간
                var predictHour1 = date.getHours();
                var predictMinute1 = date.getMinutes() + parseInt(Bus[index].MinTime) - (3 - parseInt(time)); // 사색의 광장 -> 경희대학교 3분정도 소요
                var predictHour2 = date.getHours();
                var predictMinute2 = date.getMinutes() + parseInt(Bus[index].MaxTime)- (3 - parseInt(time)); // time*1 : string to integer 형변환

                if(predictMinute1 >= 60){
                    predictHour1 += 1;
                    predictMinute1 -= 60;
                }
                if(predictMinute2 >= 60){
                    predictHour2 += 1;
                    predictMinute2 -= 60;
                }

                Bus[index]["MinPredictTime"] = predictHour1 + ":" + predictMinute1;
                Bus[index]["MaxPredictTime"] = predictHour2 + ":" + predictMinute2;

                predictTime = [predictHour1 + "", predictMinute1 + "", predictHour2 + "", predictMinute2 + ""]

                const dateBusDeparture = new Date(date.getFullYear(), date.getMonth(), date.getDate(), predictTime[0]*1, predictTime[1]*1, 0);

                var gapSec = (dateBusDeparture.getTime() - date.getTime())/1000;
                var gapHour = Math.floor(gapSec / 60 / 60);
                var gapMin = Math.floor((gapSec - gapHour * 3600) / 60);
                module.exports.data = {};

                module.exports.data.remainTime = gapHour + "시간" + gapMin + "분 이상";
                module.exports.data.ETD_min_H = predictTime[0];
                module.exports.data.ETD_min_M = predictTime[1];
                module.exports.data.ETD_max_H = predictTime[2];
                module.exports.data.ETD_max_M = predictTime[3];
                module.exports.data.busNum = Bus[index]["BusNum"];

                console.log(predictTime);
            }
        })
    })
}

function start(){
    setInterval(predict, 60000);
    console.log(Bus);
    console.log(busNum);
}

setTimeout(start, 10000);