Guest User

Untitled

a guest
Jan 16th, 2019
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.67 KB | None | 0 0
  1. #!/usr/bin/node
  2. var http = require('http'),
  3. events = require('events'),
  4. qs = require('querystring'),
  5. fs = require('fs'),
  6. mod = require('./mod');
  7.  
  8. var main = {};
  9. var data = {
  10. obj: [],
  11. item: [],
  12. limA : 1
  13. }
  14.  
  15. function init() {
  16. // ... тут задаются начальные значения объектов
  17. }
  18.  
  19. main.evt = new events.EventEmitter();
  20.  
  21. // ========= Очередь команд ==========
  22.  
  23. main.queue = [];
  24.  
  25. function checkQueueHandler() { // проверяем, обрабатывается ли очередь, если нет, то запускаем обработку
  26. if (main.queue.length > 0) {
  27. if (!main.isQueueHandled) {
  28. main.isQueueHandled = true;
  29. queueHandler();
  30. }
  31. }
  32. }
  33.  
  34. function proceedQueue() { // продолжаем обработку очереди, если есть комадны, либо останавливаем если команд нет
  35. if (main.queue[0]) {
  36. queueHandler();
  37. } else {
  38. main.isQueueHandled = false;
  39. }
  40. }
  41.  
  42. function cmdCompose(context) { // определяем тип команды, компонуем и ставим в очередь
  43. var r = context.request;
  44. var cmd = {};
  45. switch (r.t) {
  46. case '0':
  47. break
  48. case '1':
  49. cmd.action = 'setAcceleration';
  50. cmd.obj = r.pid;
  51. cmd.value = {ax: r.ax, ay: r.ay};
  52. break
  53. case '2':
  54. cmd.action = 'getItem';
  55. cmd.obj = r.pid;
  56. cmd.subj = r.trg;
  57. cmd.value = {item: r.itm, number: r.n};
  58. break
  59. case '3':
  60. cmd.action = 'putItem';
  61. cmd.obj = r.pid;
  62. cmd.subj = r.trg;
  63. cmd.value = {item: r.itm, number: r.n};
  64. break
  65. default:
  66. console.log('Неизвестный тип команды');
  67. }
  68. if (cmd.action) {
  69. cmd.onExecute = 'c' + context.id;
  70. main.queue.push(cmd);
  71. console.log(cmd);
  72. }
  73. checkQueueHandler();
  74. main.evt.emit('c' + context.id);
  75. }
  76.  
  77. function queueHandler() { // выполняем команду из очереди
  78. var worker = main.queue.shift();
  79. var o = data.obj[worker.obj];
  80. switch (worker.action) {
  81. case 'setAcceleration':
  82. calculateMv.call(o.mv);
  83. o.mv.ax = worker.value.ax;
  84. o.mv.ay = worker.value.ay;
  85. main.evt.emit(worker.onExecute);
  86. break
  87. default:
  88. console.log('Cannot handle command!!!');
  89. }
  90. proceedQueue();
  91. }
  92.  
  93. // ========== Вычисления =============
  94.  
  95. function calculateMv() {
  96. var t = (Date.now() - this.lt) / 1000;
  97. this.x += t * this.vx + (this.ax * t * t) / 2;
  98. this.y += t * this.vy + (this.ay * t * t) / 2;
  99. this.vx += t * this.ax;
  100. this.vy += t * this.ay;
  101. this.ax *= 1;
  102. this.ay *= 1;
  103. this.lt = Date.now();
  104. }
  105.  
  106. // ========== Сервер =================
  107.  
  108. function replyHandler(context) {
  109. var r = {};
  110. var pid = context.request.pid;
  111. r.st = Date.now();
  112. r.o = [];
  113. calculateMv.call(data.obj[pid].mv);
  114. getObjectsInSector(r, pid);
  115. context.reply = JSON.stringify(r);
  116. main.evt.emit('s' + context.id);
  117. }
  118.  
  119. function getObjectsInSector(r, pid) {
  120. for (var i in data.obj) {
  121. 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));
  122. if (d < 25000) {
  123. r.o.push({id: i, mv: data.obj[i].mv});
  124. }
  125. }
  126. }
  127.  
  128. function connectHandler(req, rep) {
  129. if (req) {
  130. if (req.method === 'POST') {
  131. var body = '';
  132. req.on('data', function(data) {
  133. body += data;
  134. });
  135. req.on('end', function() {
  136. console.log('\n===\n' + new Date().toTimeString() + ' >>> REQUEST: ' + body);
  137. var context = {};
  138. context.request = qs.parse(body);
  139. context.id = context.request.pid + Date.now();
  140. var cid = context.id;
  141. main.evt.once('c' + cid, function() { // компонуем ответ после выполнения команды
  142. replyHandler(context);
  143. });
  144. main.evt.once('s' + cid, function() { // отправляем ответ после компоновки
  145. console.log(new Date().toTimeString() + ' >>> REPLY: ' + context.reply + '\n===');
  146. if (!context.reply) {
  147. context.reply = 'no reply'
  148. }
  149. rep.writeHead(200, {'Content-Type': 'text/plain', 'Access-Control-Allow-Origin': 'null'});
  150. rep.write(context.reply);
  151. rep.end();
  152. });
  153. cmdCompose(context); // ставим команду в очередь на исполнение
  154. });
  155. }
  156. }
  157. }
  158.  
  159. init();
  160. http.createServer(connectHandler).listen(8000, '127.0.0.1');
  161. console.log('%%%%%%%\n' + new Date().toString() + ' - сервер запущен\n%%%%%%%');
Add Comment
Please, Sign In to add comment