Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/node
- var http = require('http'),
- events = require('events'),
- qs = require('querystring'),
- fs = require('fs'),
- mod = require('./mod');
- var main = {};
- var data = {
- obj: [],
- item: [],
- limA : 1
- }
- function init() {
- // ... тут задаются начальные значения объектов
- }
- main.evt = new events.EventEmitter();
- // ========= Очередь команд ==========
- main.queue = [];
- function checkQueueHandler() { // проверяем, обрабатывается ли очередь, если нет, то запускаем обработку
- if (main.queue.length > 0) {
- if (!main.isQueueHandled) {
- main.isQueueHandled = true;
- queueHandler();
- }
- }
- }
- function proceedQueue() { // продолжаем обработку очереди, если есть комадны, либо останавливаем если команд нет
- if (main.queue[0]) {
- queueHandler();
- } else {
- main.isQueueHandled = false;
- }
- }
- function cmdCompose(context) { // определяем тип команды, компонуем и ставим в очередь
- var r = context.request;
- var cmd = {};
- switch (r.t) {
- case '0':
- break
- case '1':
- cmd.action = 'setAcceleration';
- cmd.obj = r.pid;
- cmd.value = {ax: r.ax, ay: r.ay};
- break
- case '2':
- cmd.action = 'getItem';
- cmd.obj = r.pid;
- cmd.subj = r.trg;
- cmd.value = {item: r.itm, number: r.n};
- break
- case '3':
- cmd.action = 'putItem';
- cmd.obj = r.pid;
- cmd.subj = r.trg;
- cmd.value = {item: r.itm, number: r.n};
- break
- default:
- console.log('Неизвестный тип команды');
- }
- if (cmd.action) {
- cmd.onExecute = 'c' + context.id;
- main.queue.push(cmd);
- console.log(cmd);
- }
- checkQueueHandler();
- main.evt.emit('c' + context.id);
- }
- function queueHandler() { // выполняем команду из очереди
- var worker = main.queue.shift();
- var o = data.obj[worker.obj];
- switch (worker.action) {
- case 'setAcceleration':
- calculateMv.call(o.mv);
- o.mv.ax = worker.value.ax;
- o.mv.ay = worker.value.ay;
- main.evt.emit(worker.onExecute);
- break
- default:
- console.log('Cannot handle command!!!');
- }
- proceedQueue();
- }
- // ========== Вычисления =============
- function calculateMv() {
- var t = (Date.now() - this.lt) / 1000;
- this.x += t * this.vx + (this.ax * t * t) / 2;
- this.y += t * this.vy + (this.ay * t * t) / 2;
- this.vx += t * this.ax;
- this.vy += t * this.ay;
- this.ax *= 1;
- this.ay *= 1;
- this.lt = Date.now();
- }
- // ========== Сервер =================
- function replyHandler(context) {
- var r = {};
- var pid = context.request.pid;
- r.st = Date.now();
- r.o = [];
- calculateMv.call(data.obj[pid].mv);
- getObjectsInSector(r, pid);
- context.reply = JSON.stringify(r);
- main.evt.emit('s' + context.id);
- }
- function getObjectsInSector(r, pid) {
- for (var i in data.obj) {
- var d = Math.sqrt(Math.pow((data.obj[i].mv.x - data.obj[pid].mv.x),2) + Math.pow((data.obj[i].mv.y - data.obj[pid].mv.y),2));
- if (d < 25000) {
- r.o.push({id: i, mv: data.obj[i].mv});
- }
- }
- }
- function connectHandler(req, rep) {
- if (req) {
- if (req.method === 'POST') {
- var body = '';
- req.on('data', function(data) {
- body += data;
- });
- req.on('end', function() {
- console.log('\n===\n' + new Date().toTimeString() + ' >>> REQUEST: ' + body);
- var context = {};
- context.request = qs.parse(body);
- context.id = context.request.pid + Date.now();
- var cid = context.id;
- main.evt.once('c' + cid, function() { // компонуем ответ после выполнения команды
- replyHandler(context);
- });
- main.evt.once('s' + cid, function() { // отправляем ответ после компоновки
- console.log(new Date().toTimeString() + ' >>> REPLY: ' + context.reply + '\n===');
- if (!context.reply) {
- context.reply = 'no reply'
- }
- rep.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': 'null'});
- rep.write(context.reply);
- rep.end();
- });
- cmdCompose(context); // ставим команду в очередь на исполнение
- });
- }
- }
- }
- init();
- http.createServer(connectHandler).listen(8000, '127.0.0.1');
- console.log('%%%%%%%\n' + new Date().toString() + ' - сервер запущен\n%%%%%%%');
Add Comment
Please, Sign In to add comment