Repository navigation
Expand file tree
/
Copy pathweb-server.js
More file actions
854 lines (733 loc) · 32.8 KB
/
Copy pathweb-server.js
File metadata and controls
854 lines (733 loc) · 32.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const path = require('path');
const { spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
// Config dosyası yönetimi
let configPath;
let userConfigPath;
// Electron modunda config dosyasını kullanıcı dizinine kopyala
if (process.env.ELECTRON_MODE === 'true') {
// Electron modunda, ana process'ten userDataPath gelecek
const userDataPath = process.env.USER_DATA_PATH;
if (userDataPath) {
userConfigPath = path.join(userDataPath, 'config.env');
configPath = userConfigPath;
} else {
// Fallback olarak home directory kullan
const userHome = os.homedir();
userConfigPath = path.join(userHome, '.aprs-config.env');
configPath = userConfigPath;
}
} else {
// Normal modda proje dizinindeki .env dosyasını kullan
configPath = path.join(__dirname, '.env');
}
// Config dosyasını initialize et
function initializeConfig() {
const defaultConfigPath = path.join(__dirname, '.env');
console.log(`🔧 Config initialize - Default path: ${defaultConfigPath}`);
console.log(`🔧 Config initialize - User path: ${userConfigPath}`);
// Kullanıcı config dosyası yoksa varsayılan dosyayı kopyala
if (userConfigPath && !fs.existsSync(userConfigPath)) {
console.log(`📝 User config dosyası bulunamadı, oluşturuluyor...`);
try {
if (fs.existsSync(defaultConfigPath)) {
fs.copyFileSync(defaultConfigPath, userConfigPath);
console.log(`✅ Config dosyası kopyalandı: ${userConfigPath}`);
} else {
console.log(`⚠️ Varsayılan config dosyası bulunamadı, yeni oluşturuluyor...`);
// Varsayılan config dosyası yoksa boş bir dosya oluştur
const defaultConfig = `CALLSIGN="N0CALL"
LATITUDE="0.0"
LONGITUDE="0.0"
COMMENT="APRS Position Sender"
SYMBOL="/>"
APRS_PATH="APRS"
AUTO_SEND_ENABLED="false"
AUTO_SEND_INTERVAL="600"
AUTO_SEND_COUNT="10"
DEMO_MODE="false"`;
fs.writeFileSync(userConfigPath, defaultConfig);
console.log(`✅ Varsayılan config dosyası oluşturuldu: ${userConfigPath}`);
}
} catch (error) {
console.error('❌ Config dosyası kopyalanırken hata:', error.message);
}
} else if (userConfigPath) {
console.log(`✅ User config dosyası mevcut: ${userConfigPath}`);
}
}
// Config'i yükle
function loadConfig() {
console.log(`🔧 Config yükleniyor - ELECTRON_MODE: ${process.env.ELECTRON_MODE}`);
console.log(`📁 Config path: ${configPath}`);
console.log(`📁 User config path: ${userConfigPath}`);
// Config dosyasını initialize et
initializeConfig();
// Config dosyasını dotenv ile yükle
require('dotenv').config({ path: configPath });
console.log(`✅ Config yüklendi - CALLSIGN: ${process.env.CALLSIGN}`);
}
// Config'i yükle
loadConfig();
// APRS sınıflarını import et
const { APRSPositionSender, APRSISClient, calculatePasscode } = require('./index.js');
// Electron modu kontrolü
const isElectronMode = process.env.ELECTRON_MODE === 'true';
// Node.js executable path'ini belirle
function getNodePath() {
if (isElectronMode) {
// Electron ortamında process.execPath'i kullan
return process.execPath;
} else {
// Normal ortamda node komutunu kullan
return 'node';
}
}
// Güvenli spawn fonksiyonu
function safeSpawn(command, args, options = {}) {
if (isElectronMode) {
// Packaged Electron uygulamasında child process sorunları yaşanıyor
// macOS Gatekeeper ve asar dosyası sınırlamaları nedeniyle
const isPackaged = process.env.APP_PATH && (
process.env.APP_PATH.includes('app.asar') ||
process.env.APP_PATH.includes('Resources/app')
);
if (isPackaged) {
console.log(`� Packaged app detected - child process disabled for macOS compatibility`);
// Packaged modda fake process döndür
const fakeProcess = {
stdout: { on: () => {} },
stderr: { on: () => {} },
on: (event, callback) => {
if (event === 'close') {
// Simulated success
setTimeout(() => callback(0), 1000);
} else if (event === 'error') {
// Error handling placeholder
}
},
kill: () => {}
};
// APRS işlemini doğrudan çalıştır
const scriptName = args[0]; // 'index.js'
const scriptArgs = args.slice(1); // ['--auto'] gibi
if (scriptArgs.includes('--auto')) {
console.log(`🚀 Running APRS auto mode directly in main thread...`);
setTimeout(() => {
runAPRSAutoMode();
}, 1000);
} else if (scriptArgs.includes('--send')) {
console.log(`📡 Running APRS single send directly in main thread...`);
setTimeout(() => {
runAPRSSingleSend();
}, 1000);
} else if (scriptArgs.includes('--status')) {
console.log(`� Running APRS status send directly in main thread...`);
setTimeout(() => {
runAPRSStatusSend();
}, 1000);
}
return fakeProcess;
} else {
// Development mode - normal fork kullan
return forkAPRSProcess(command, args, options);
}
} else {
// Normal ortamda spawn kullan
const nodePath = getNodePath();
return spawn(nodePath, args, options);
}
}
// Development modunda fork kullan
function forkAPRSProcess(command, args, options) {
const { fork } = require('child_process');
// args'dan 'node' ve script adını ayır
const scriptName = args[0]; // 'index.js'
const scriptArgs = args.slice(1); // ['--auto'] gibi
// Script yolunu belirle
const appPath = process.env.APP_PATH || __dirname;
const scriptPath = path.join(appPath, scriptName);
console.log(`🔧 Fork process:`);
console.log(` Script: ${scriptPath}`);
console.log(` Args: ${scriptArgs.join(' ')}`);
console.log(` Script exists: ${fs.existsSync(scriptPath)}`);
// Script dosyasının varlığını kontrol et
if (!fs.existsSync(scriptPath)) {
const error = new Error(`Script not found: ${scriptPath}`);
console.error(`❌ ${error.message}`);
throw error;
}
const childProcess = fork(scriptPath, scriptArgs, {
cwd: appPath,
silent: false,
stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
env: { ...process.env, ...options.env },
execArgv: []
});
// Child process error handling
childProcess.on('error', (err) => {
console.error(`❌ Child process error (${scriptName}):`, err);
});
childProcess.on('exit', (code, signal) => {
if (signal) {
console.log(`⚠️ Child process killed by signal: ${signal}`);
} else if (code !== 0) {
console.log(`⚠️ Child process exited with code: ${code}`);
}
});
return childProcess;
}
// Package.json'dan versiyon bilgisini oku
let packageInfo = {};
try {
const packageData = fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8');
packageInfo = JSON.parse(packageData);
} catch (error) {
console.warn('Package.json okunamadı:', error.message);
packageInfo = { name: 'APRS-FI', version: '1.0.0' };
}
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
const PORT = process.env.PORT || process.env.WEB_PORT || 3000;
// Electron modunda farklı log çıktısı
function log(message) {
const timestamp = new Date().toISOString();
if (isElectronMode) {
console.log(`[${timestamp}] ${message}`);
} else {
console.log(message);
}
}
// Log helper fonksiyonu - undefined döndürmesini engeller
function emitLog(type, message) {
io.emit('log', { type, message });
// Explicitly return void to prevent undefined in console
return;
}
// Static dosyalar için middleware
app.use(express.static('public'));
app.use(express.json());
// Ana sayfa
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// APRS konfigürasyon bilgilerini al
app.get('/api/config', (req, res) => {
res.json({
callsign: process.env.CALLSIGN || 'N/A',
latitude: process.env.LATITUDE || 'N/A',
longitude: process.env.LONGITUDE || 'N/A',
comment: process.env.COMMENT || 'N/A',
symbol: process.env.SYMBOL || '/>',
path: process.env.APRS_PATH || 'APRS',
autoEnabled: process.env.AUTO_SEND_ENABLED === 'true',
interval: process.env.AUTO_SEND_INTERVAL || '600',
count: process.env.AUTO_SEND_COUNT || '10',
demoMode: process.env.DEMO_MODE === 'true',
demoMessage: process.env.DEMO_MESSAGE || 'Bu demo sürümüdür.',
version: packageInfo.version || '1.0.0',
appName: packageInfo.name || 'APRS Position Sender',
isElectron: isElectronMode
});
});
// Config güncelleme endpoint'i
app.post('/api/config', (req, res) => {
try {
const {
callsign,
latitude,
longitude,
comment,
symbol,
path,
autoEnabled,
interval,
count,
demoMode
} = req.body;
// Config dosyasını oku
let configContent = '';
if (fs.existsSync(configPath)) {
configContent = fs.readFileSync(configPath, 'utf8');
}
// Mevcut değerleri güncelle
const configMap = {};
// Mevcut config'i parse et
configContent.split('\n').forEach(line => {
const trimmed = line.trim();
if (trimmed && !trimmed.startsWith('#')) {
const match = trimmed.match(/^([^=]+)=(.*)$/);
if (match) {
const key = match[1].trim();
const value = match[2].trim().replace(/^["']|["']$/g, '');
configMap[key] = value;
}
}
});
// Yeni değerleri güncelle
if (callsign !== undefined) configMap['CALLSIGN'] = callsign;
if (latitude !== undefined) configMap['LATITUDE'] = latitude;
if (longitude !== undefined) configMap['LONGITUDE'] = longitude;
if (comment !== undefined) configMap['COMMENT'] = comment;
if (symbol !== undefined) configMap['SYMBOL'] = symbol;
if (path !== undefined) configMap['APRS_PATH'] = path;
if (autoEnabled !== undefined) configMap['AUTO_SEND_ENABLED'] = autoEnabled.toString();
if (interval !== undefined) configMap['AUTO_SEND_INTERVAL'] = interval;
if (count !== undefined) configMap['AUTO_SEND_COUNT'] = count;
if (demoMode !== undefined) configMap['DEMO_MODE'] = demoMode.toString();
// Config dosyasını yeniden oluştur
let newConfigContent = '';
for (const [key, value] of Object.entries(configMap)) {
newConfigContent += `${key}="${value}"\n`;
}
// Dosyayı yaz
fs.writeFileSync(configPath, newConfigContent);
// Environment variables'ı güncelle
for (const [key, value] of Object.entries(configMap)) {
process.env[key] = value;
}
log('Config güncellendi: ' + configPath);
res.json({ success: true, message: 'Konfigürasyon başarıyla güncellendi' });
} catch (error) {
console.error('Config güncellenirken hata:', error);
res.status(500).json({ success: false, message: 'Konfigürasyon güncellenirken hata oluştu' });
}
});
// Aktif process'ler
let activeProcesses = {
auto: null,
send: null
};
// Socket.IO bağlantı yönetimi
io.on('connection', (socket) => {
console.log('🌐 Web arayüzü bağlandı:', socket.id);
// Socket error handling
socket.on('error', (error) => {
console.error('Socket hatası:', error);
});
// Konfigürasyonu gönder
socket.emit('config', {
callsign: process.env.CALLSIGN || 'N/A',
latitude: process.env.LATITUDE || 'N/A',
longitude: process.env.LONGITUDE || 'N/A',
comment: process.env.COMMENT || 'N/A',
symbol: process.env.SYMBOL || '/>',
path: process.env.APRS_PATH || 'APRS',
autoEnabled: process.env.AUTO_SEND_ENABLED === 'true',
interval: process.env.AUTO_SEND_INTERVAL || '600',
count: process.env.AUTO_SEND_COUNT || '10',
demoMode: process.env.DEMO_MODE === 'true',
demoMessage: process.env.DEMO_MESSAGE || 'Bu demo sürümüdür.',
version: packageInfo.version || '1.0.0',
appName: packageInfo.name || 'APRS-FI',
isElectron: isElectronMode
});
// Eğer otomatik process çalışıyorsa bunu bildir
if (activeProcesses.auto) {
socket.emit('log', { type: 'info', message: '🤖 Otomatik gönderim arka planda çalışıyor...' });
socket.emit('log', { type: 'info', message: '📊 AUTO_START_ON_DEPLOY ile başlatıldı' });
}
// Otomatik gönderim başlat
socket.on('start-auto', () => {
try {
// Demo mode kontrolü
if (process.env.DEMO_MODE === 'true') {
socket.emit('log', {
type: 'warning',
message: `🚫 ${process.env.DEMO_MESSAGE || 'Bu demo sürümüdür. APRS gönderimi devre dışıdır.'}`
});
return;
}
if (activeProcesses.auto) {
socket.emit('log', { type: 'warning', message: '⚠️ Otomatik gönderim zaten çalışıyor!' });
return;
}
socket.emit('log', { type: 'info', message: '🚀 Otomatik gönderim başlatılıyor...' });
activeProcesses.auto = safeSpawn('node', ['index.js', '--auto'], {
cwd: process.env.APP_PATH || __dirname
});
// Process error handling
activeProcesses.auto.on('error', (err) => {
console.error('❌ Auto process error:', err);
io.emit('log', { type: 'error', message: `❌ Process hatası: ${err.message}` });
activeProcesses.auto = null;
io.emit('status', { auto: false, send: false });
});
activeProcesses.auto.stdout.on('data', (data) => {
const message = data.toString().trim();
if (message) {
io.emit('log', { type: 'info', message: message }); // Sadece tüm client'lara gönder
}
});
activeProcesses.auto.stderr.on('data', (data) => {
const message = data.toString().trim();
if (message) {
io.emit('log', { type: 'error', message: `❌ ${message}` });
}
});
activeProcesses.auto.on('close', (code, signal) => {
activeProcesses.auto = null;
let message;
if (signal) {
message = `🏁 Otomatik gönderim durduruldu (Signal: ${signal})`;
} else {
message = `🏁 Otomatik gönderim tamamlandı (Exit code: ${code})`;
}
io.emit('log', { type: 'info', message: message });
io.emit('status', { auto: false, send: false });
});
// Process başlatıldığında durum güncelle
io.emit('status', { auto: true, send: false });
} catch (error) {
console.error('❌ start-auto error:', error);
socket.emit('log', { type: 'error', message: `❌ Otomatik gönderim başlatılamadı: ${error.message}` });
activeProcesses.auto = null;
io.emit('status', { auto: false, send: false });
}
});
// Tek gönderim
socket.on('send-once', () => {
try {
// Demo mode kontrolü
if (process.env.DEMO_MODE === 'true') {
socket.emit('log', {
type: 'warning',
message: `🚫 ${process.env.DEMO_MESSAGE || 'Bu demo sürümüdür. APRS gönderimi devre dışıdır.'}`
});
return;
}
if (activeProcesses.send) {
socket.emit('log', { type: 'warning', message: '⚠️ Gönderim zaten çalışıyor!' });
return;
}
socket.emit('log', { type: 'info', message: '📡 Tek gönderim başlatılıyor...' });
activeProcesses.send = safeSpawn('node', ['index.js', '--send'], {
cwd: process.env.APP_PATH || __dirname
});
// Process error handling
activeProcesses.send.on('error', (err) => {
console.error('❌ Send process error:', err);
io.emit('log', { type: 'error', message: `❌ Gönderim hatası: ${err.message}` });
activeProcesses.send = null;
io.emit('status', { auto: !!activeProcesses.auto, send: false });
});
activeProcesses.send.stdout.on('data', (data) => {
const message = data.toString().trim();
if (message) {
io.emit('log', { type: 'info', message: message });
}
});
activeProcesses.send.stderr.on('data', (data) => {
const message = data.toString().trim();
if (message) {
io.emit('log', { type: 'error', message: `❌ ${message}` });
}
});
activeProcesses.send.on('close', (code, signal) => {
activeProcesses.send = null;
let message;
if (signal) {
message = `✅ Tek gönderim durduruldu (Signal: ${signal})`;
} else {
message = `✅ Tek gönderim tamamlandı (Exit code: ${code})`;
}
io.emit('log', { type: 'info', message: message });
io.emit('status', { auto: !!activeProcesses.auto, send: false });
});
io.emit('status', { auto: !!activeProcesses.auto, send: true });
} catch (error) {
console.error('❌ send-once error:', error);
socket.emit('log', { type: 'error', message: `❌ Tek gönderim başlatılamadı: ${error.message}` });
activeProcesses.send = null;
io.emit('status', { auto: !!activeProcesses.auto, send: false });
}
});
// Process'leri durdur
socket.on('stop-auto', () => {
if (activeProcesses.auto) {
activeProcesses.auto.kill('SIGINT');
io.emit('log', { type: 'warning', message: '🛑 Otomatik gönderim durduruldu' });
}
});
// Log'ları temizle
socket.on('clear-logs', () => {
io.emit('clear-logs');
});
// Durum bilgisi gönder
socket.on('send-status', () => {
try {
// Demo mode kontrolü
if (process.env.DEMO_MODE === 'true') {
socket.emit('log', {
type: 'warning',
message: `🚫 ${process.env.DEMO_MESSAGE || 'Bu demo sürümüdür. APRS gönderimi devre dışıdır.'}`
});
return;
}
socket.emit('log', { type: 'info', message: '📢 Durum bilgisi gönderiliyor...' });
const statusProcess = safeSpawn('node', ['index.js', '--status'], {
cwd: process.env.APP_PATH || __dirname
});
// Process error handling
statusProcess.on('error', (err) => {
console.error('❌ Status process error:', err);
io.emit('log', { type: 'error', message: `❌ Durum gönderim hatası: ${err.message}` });
});
statusProcess.stdout.on('data', (data) => {
const message = data.toString().trim();
if (message) {
io.emit('log', { type: 'info', message: message });
}
});
statusProcess.stderr.on('data', (data) => {
const message = data.toString().trim();
if (message) {
io.emit('log', { type: 'error', message: `❌ ${message}` });
}
});
statusProcess.on('close', (code, signal) => {
let message;
if (signal) {
message = `📢 Durum gönderimi durduruldu (Signal: ${signal})`;
} else {
message = `📢 Durum gönderimi tamamlandı (Exit code: ${code})`;
}
io.emit('log', { type: 'info', message: message });
});
} catch (error) {
console.error('❌ send-status error:', error);
socket.emit('log', { type: 'error', message: `❌ Durum gönderimi başlatılamadı: ${error.message}` });
}
});
// Bağlantı koptuğunda
socket.on('disconnect', (reason) => {
console.log(`🌐 Web arayüzü bağlantısı kesildi: ${socket.id} - Neden: ${reason}`);
// Bağlantı kopma nedenini logla
if (reason === 'io server disconnect') {
console.log('⚠️ Sunucu tarafından bağlantı kapatıldı');
} else if (reason === 'io client disconnect') {
console.log('⚠️ İstemci tarafından bağlantı kapatıldı');
} else if (reason === 'ping timeout') {
console.log('⚠️ Ping timeout - bağlantı zaman aşımı');
} else if (reason === 'transport close') {
console.log('⚠️ Transport kapandı');
} else if (reason === 'transport error') {
console.log('⚠️ Transport hatası');
} else {
console.log(`⚠️ Bilinmeyen neden: ${reason}`);
}
});
// Bağlantı hatası durumunda
socket.on('connect_error', (error) => {
console.error('🔌 Socket bağlantı hatası:', error);
});
// Mevcut durum bilgisi gönder
socket.emit('status', {
auto: !!activeProcesses.auto,
send: !!activeProcesses.send
});
});
// Durum gönderimi endpoint'i
app.post('/send-status', async (req, res) => {
try {
if (process.env.DEMO_MODE === 'true') {
emitLog('warning', '⚠️ Demo modunda - durum paketi simülasyonu');
const sender = new APRSPositionSender();
const packet = sender.sendStatusFromEnv();
if (packet) {
emitLog('info', `📢 Demo Durum Paketi: ${packet}`);
res.json({ success: true, message: 'Demo durum paketi oluşturuldu', packet });
} else {
res.json({ success: false, message: 'Durum paketi oluşturulamadı' });
}
return;
}
emitLog('info', '🚀 Durum paketi gönderimi başlatıldı...');
const sender = new APRSPositionSender();
const success = await sender.sendStatusToAPRSIS();
if (success) {
emitLog('success', '✅ Durum paketi başarıyla gönderildi!');
res.json({ success: true, message: 'Durum paketi gönderildi' });
} else {
emitLog('error', '❌ Durum paketi gönderilemedi');
res.json({ success: false, message: 'Durum paketi gönderilemedi' });
}
} catch (error) {
emitLog('error', `❌ Durum gönderim hatası: ${error.message}`);
res.status(500).json({ success: false, message: error.message });
}
});
// Packaged Electron uygulaması için in-thread APRS fonksiyonları
// macOS'ta child process spawn sorunları nedeniyle bu fonksiyonlar kullanılır
function runAPRSAutoMode() {
try {
console.log('🚀 APRS Auto mode starting in main thread...');
io.emit('log', { type: 'info', message: '🚀 Otomatik gönderim başlatıldı (main thread)' });
const sender = new APRSPositionSender();
// Otomatik gönderim simülasyonu
let sendCount = 0;
const maxCount = parseInt(process.env.AUTO_SEND_COUNT || '10');
const interval = parseInt(process.env.AUTO_SEND_INTERVAL || '600') * 1000; // saniye -> milisaniye
const autoInterval = setInterval(async () => {
try {
sendCount++;
io.emit('log', { type: 'info', message: `📡 Otomatik gönderim ${sendCount}/${maxCount}` });
const success = await sender.sendPositionToAPRSIS();
if (success) {
io.emit('log', { type: 'success', message: `✅ Paket ${sendCount} başarıyla gönderildi` });
} else {
io.emit('log', { type: 'error', message: `❌ Paket ${sendCount} gönderilemedi` });
}
if (sendCount >= maxCount) {
clearInterval(autoInterval);
io.emit('log', { type: 'info', message: '🏁 Otomatik gönderim tamamlandı' });
io.emit('status', { auto: false, send: false });
}
} catch (error) {
io.emit('log', { type: 'error', message: `❌ Gönderim hatası: ${error.message}` });
}
}, interval);
// Global olarak sakla ki durdurulabilsin
global.activeAutoInterval = autoInterval;
io.emit('status', { auto: true, send: false });
} catch (error) {
console.error('❌ Auto mode error:', error);
io.emit('log', { type: 'error', message: `❌ Otomatik gönderim hatası: ${error.message}` });
io.emit('status', { auto: false, send: false });
}
}
function runAPRSSingleSend() {
try {
console.log('📡 APRS Single send starting in main thread...');
io.emit('log', { type: 'info', message: '📡 Tek gönderim başlatıldı (main thread)' });
io.emit('status', { auto: !!global.activeAutoInterval, send: true });
const sender = new APRSPositionSender();
// Async olarak çalıştır
sender.sendPositionToAPRSIS().then(success => {
if (success) {
io.emit('log', { type: 'success', message: '✅ Tek gönderim başarıyla tamamlandı' });
} else {
io.emit('log', { type: 'error', message: '❌ Tek gönderim başarısız' });
}
io.emit('status', { auto: !!global.activeAutoInterval, send: false });
}).catch(error => {
io.emit('log', { type: 'error', message: `❌ Tek gönderim hatası: ${error.message}` });
io.emit('status', { auto: !!global.activeAutoInterval, send: false });
});
} catch (error) {
console.error('❌ Single send error:', error);
io.emit('log', { type: 'error', message: `❌ Tek gönderim hatası: ${error.message}` });
io.emit('status', { auto: !!global.activeAutoInterval, send: false });
}
}
function runAPRSStatusSend() {
try {
console.log('📢 APRS Status send starting in main thread...');
io.emit('log', { type: 'info', message: '📢 Durum gönderimi başlatıldı (main thread)' });
const sender = new APRSPositionSender();
// Async olarak çalıştır
sender.sendStatusToAPRSIS().then(success => {
if (success) {
io.emit('log', { type: 'success', message: '✅ Durum gönderimi başarıyla tamamlandı' });
} else {
io.emit('log', { type: 'error', message: '❌ Durum gönderimi başarısız' });
}
}).catch(error => {
io.emit('log', { type: 'error', message: `❌ Durum gönderim hatası: ${error.message}` });
});
} catch (error) {
console.error('❌ Status send error:', error);
io.emit('log', { type: 'error', message: `❌ Durum gönderim hatası: ${error.message}` });
}
}
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\n🛑 Web server kapatılıyor...');
// Aktif process'leri temizle
Object.values(activeProcesses).forEach(proc => {
if (proc) {
proc.kill('SIGINT');
}
});
server.close(() => {
console.log('✅ Web server kapatıldı');
process.exit(0);
});
});
server.listen(PORT, () => {
if (isElectronMode) {
console.log(`🖥️ APRS-FI Desktop sunucusu başlatıldı: http://localhost:${PORT}`);
console.log(`📡 Electron modu aktif - Desktop uygulaması hazır`);
} else {
console.log(`🌐 APRS Web Arayüzü çalışıyor: http://localhost:${PORT}`);
console.log(`📡 APRS gönderimlerini web üzerinden kontrol edebilirsiniz`);
}
// Environment variables debug
console.log(`🔍 AUTO_START_ON_DEPLOY: ${process.env.AUTO_START_ON_DEPLOY}`);
console.log(`🔍 DEMO_MODE: ${process.env.DEMO_MODE}`);
console.log(`🔍 CALLSIGN: ${process.env.CALLSIGN}`);
console.log(`🔍 ELECTRON_MODE: ${isElectronMode}`);
// Sunucu başlarken otomatik gönderimi başlat
if (process.env.AUTO_START_ON_DEPLOY === 'true') {
console.log('🚀 AUTO_START_ON_DEPLOY aktif - Otomatik gönderim başlatılıyor...');
// Demo mode kontrolü - uyarı ver ama devam et
if (process.env.DEMO_MODE === 'true') {
console.log(`🚫 Demo Mode aktif: ${process.env.DEMO_MESSAGE || 'APRS gönderimi devre dışıdır.'}`);
console.log('⚠️ Demo mode aktif olmasına rağmen AUTO_START_ON_DEPLOY nedeniyle gönderim başlatılıyor...');
}
// Otomatik gönderimi başlat (her durumda)
setTimeout(() => {
if (!activeProcesses.auto) {
console.log('📡 Deployment sonrası otomatik APRS gönderimi başlatılıyor...');
try {
activeProcesses.auto = safeSpawn('node', ['index.js', '--auto'], {
cwd: process.env.APP_PATH || __dirname
});
activeProcesses.auto.stdout.on('data', (data) => {
const message = data.toString().trim();
if (message) {
console.log(`[AUTO] ${message}`);
// Tüm bağlı socket'lere log gönder
io.emit('log', { type: 'info', message: `🤖 ${message}` });
}
});
activeProcesses.auto.stderr.on('data', (data) => {
const message = data.toString().trim();
if (message) {
console.error(`[AUTO ERROR] ${message}`);
io.emit('log', { type: 'error', message: `❌ ${message}` });
}
});
activeProcesses.auto.on('close', (code) => {
console.log(`[AUTO] Process kapandı - kod: ${code}`);
activeProcesses.auto = null;
io.emit('log', { type: 'warning', message: `⚠️ Otomatik gönderim durdu (kod: ${code})` });
io.emit('status', { auto: false, send: false });
});
activeProcesses.auto.on('error', (error) => {
console.error(`[AUTO ERROR] Process hatası:`, error);
activeProcesses.auto = null;
io.emit('log', { type: 'error', message: `❌ Otomatik gönderim hatası: ${error.message}` });
io.emit('status', { auto: false, send: false });
});
// Status güncelle
io.emit('status', { auto: true, send: false });
io.emit('log', { type: 'info', message: '🚀 Deployment sonrası otomatik gönderim başlatıldı!' });
console.log('✅ Auto start process başarıyla oluşturuldu');
} catch (error) {
console.error('❌ Auto start spawn hatası:', error);
io.emit('log', { type: 'error', message: `❌ Auto start hatası: ${error.message}` });
}
} else {
console.log('⚠️ Auto process zaten çalışıyor, yeni başlatılmadı');
}
}, 2000); // 2 saniye bekle ki server tamamen hazır olsun
} else {
console.log('ℹ️ AUTO_START_ON_DEPLOY false veya tanımlı değil - otomatik başlatma yok');
}
});