ยง2024-09-19

$ cat indexCron.js 
const http = require('http');
const { Server } = require('socket.io');
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const cron = require('node-cron');

const app = express();
const server = http.createServer(app);
const io = new Server(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/bootstrapRowsColsCron.html');
});

const uri = "mongodb://siteRootAdmin:b23258585@x8664Arch.yushei.com.tw:27017,hc4Jammy.yushei.com.tw:27017,n2Jammy.yushei.com.tw:27017/YuSheiDBTest?replicaSet=odroid01&authSource=admin";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function start() {
  await client.connect();
  const adminDb = client.db('admin'); // Connect to the admin database
  const db = client.db('YuSheiDBTest');
  const collection = db.collection('inLaneCapped');

  const changeStream = collection.watch();

  setInterval(async () => {
    try {
      const log = await adminDb.command({ replSetGetStatus: 1 }); // Execute against admin database
      // console.log("what is in log at line 28", log);

      let simpleLog = [];
      // console.log("What is log.members[0]", log.members[0]);

      for (let i = 0; i < log.members.length; i++){
          // console.log("_id: ", log[i]._id, "name: ", log[i].name, "health: ", log[i].health, "state: ", log[i].state, "stateStr: ", log[i].stateStr);
              simpleLog[i] = {
                      "_id": log.members[i]._id,
                      "name": log.members[i].name,
                      "health": log.members[i].health,
                      "state": log.members[i].state,
                      "stateStr": log.members[i].stateStr
              }
      }
      console.log('\n');
//      console.log("simpleLog just log", simpleLog);
      // console.table does not work here!
      // console.table("simpleLog Table", simpleLog);
      console.log(" _id |                name                | health | state |  stateStr   ");
      console.log("--------------------------------------------------------------------------");
      simpleLog.forEach(member => {
        console.log(` ${String(member._id).padEnd(3)} | ${String(member.name).padEnd(35)} |   ${String(member.health).padEnd(3)}   |   ${String(member.state).padEnd(3)}  | ${member.stateStr}`);
      });

      console.log(Date().toLocaleString());

      io.emit('replicationStatus', simpleLog);
      // console.log('Replication Status:', simpleLog);
    } catch (error) {
      console.error('Error fetching replication status:', error);
    }
  }, 60000); // Fetch replication status every minutes 1 seconds=1000


  changeStream.on('change', (change) => {
    io.emit('change', change);
    if (change.operationType === 'insert') {
      const { _id, plateText, cameraSource, inTime, inCarJpg } = change.fullDocument;
      console.log(`Change ID: ${_id}`);
      console.log(`plateText: ${plateText}`);
      console.log(`camerSource: ${cameraSource}`);
      console.log(`inTime: ${inTime}`);
    }
  });
  // HighPorts ,TCP/43000-48500 defined in munetaka.me
  server.listen(48595, () => {
    console.log('Server is listening on port 48595');
  });
}

const options = { timeZone: 'Asia/Taipei', timeZoneName: 'short' };
// const localTime = now.toLocaleString('en-US', options);

// set io.emit()
function saveAndResetPictureCounts() {
  let now = new Date();
  let localTime = now.toLocaleString('en-US', options);
  io.emit('saveAndResetPictureCounts', localTime)
}

// Schedule resetPictureCountsAtMidnight to run at 1:00 AM every day
cron.schedule('0 1 * * *', () => {
// Schedule the function to run every 5 minutes
// cron.schedule('*/5 * * * *', () =>{
  saveAndResetPictureCounts();
});

start().catch(console.error);