MySafeCode commited on
Commit
dcc2634
·
verified ·
1 Parent(s): 7b55add

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -51
app.py CHANGED
@@ -1,4 +1,3 @@
1
- # app.py - SIMPLE VERSION THAT WORKS
2
  import pygame
3
  import time
4
  import threading
@@ -9,12 +8,18 @@ from flask_socketio import SocketIO, emit
9
  from io import BytesIO
10
 
11
  os.environ['SDL_VIDEODRIVER'] = 'dummy'
12
- pygame.init()
 
 
 
 
 
 
13
 
14
  app = Flask(__name__)
15
- app.config['SECRET_KEY'] = 'secret!'
16
 
17
- # Use threading mode instead of eventlet
18
  socketio = SocketIO(app, async_mode='threading', cors_allowed_origins="*")
19
 
20
  WIDTH, HEIGHT = 400, 300
@@ -26,20 +31,35 @@ shared = {
26
  }
27
 
28
  def game_loop():
29
- """Background thread generating frames"""
30
- print("🎮 PyGame loop started")
 
 
 
 
 
 
 
 
 
 
 
 
31
  screen = pygame.Surface((WIDTH, HEIGHT))
32
  x, speed = 200, 5
33
 
 
 
 
34
  while shared["streaming"]:
35
  start_time = time.time()
36
 
37
- # Update position
38
  x += speed
39
  if x < 30 or x > WIDTH-30:
40
  speed *= -1
41
 
42
- # Draw frame
43
  screen.fill((25, 25, 45))
44
  pygame.draw.circle(screen, (255, 80, 80), (int(x), 150), 20)
45
 
@@ -48,21 +68,27 @@ def game_loop():
48
  pygame.image.save(screen, buf, format='JPEG', quality=85)
49
  frame_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
50
 
51
- # Broadcast to all connected clients
52
  socketio.emit('new_frame', {
53
  'frame': frame_b64,
54
  'count': shared['frame_count'],
55
- 'x': x
56
- }, namespace='/')
 
57
 
 
58
  shared['x'] = x
59
  shared['frame_count'] += 1
 
60
 
61
- # Log every 30 frames
62
- if shared['frame_count'] % 30 == 0:
63
- print(f"Frame {shared['frame_count']}: X={x}, Clients={shared['clients']}")
 
 
 
64
 
65
- # Control FPS
66
  elapsed = time.time() - start_time
67
  if elapsed < 1.0/30:
68
  time.sleep(1.0/30 - elapsed)
@@ -73,63 +99,94 @@ def game_loop():
73
  def index():
74
  return render_template_string('''
75
  <!DOCTYPE html>
76
- <html>
77
- <head>
78
- <script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
79
- <style>
80
- body { background: #0f172a; color: white; text-align: center; padding: 20px; }
81
- #streamImg { border: 3px solid #60a5fa; width: 400px; height: 300px; }
82
- </style>
83
- </head>
84
- <body>
85
- <h1>🔄 Flask-SocketIO (Threading)</h1>
86
- <img id="streamImg">
87
- <p>Frame: <span id="counter">0</span> | X: <span id="pos">200</span></p>
88
- <p>Status: <span id="status">Connecting...</span></p>
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- <script>
91
- const socket = io();
92
-
93
- socket.on('connect', () => {
94
- console.log('✅ Connected');
95
- document.getElementById('status').textContent = 'Connected';
96
- document.body.style.background = '#1a5c1a';
97
- });
 
 
98
 
99
- socket.on('new_frame', (data) => {
100
- document.getElementById('streamImg').src =
101
- 'data:image/jpeg;base64,' + data.frame;
102
- document.getElementById('counter').textContent = data.count;
103
- document.getElementById('pos').textContent = data.x;
104
- });
105
 
106
- socket.on('disconnect', () => {
107
- console.log('❌ Disconnected');
108
- document.getElementById('status').textContent = 'Disconnected';
109
- document.body.style.background = '#5c1a1a';
110
- });
111
- </script>
112
- </body>
113
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  ''')
115
 
116
  @socketio.on('connect')
117
  def handle_connect():
118
  shared['clients'] += 1
119
  print(f"Client connected. Total: {shared['clients']}")
 
120
 
121
  @socketio.on('disconnect')
122
  def handle_disconnect():
123
  shared['clients'] -= 1
124
  print(f"Client disconnected. Total: {shared['clients']}")
 
125
 
126
  if __name__ == '__main__':
127
- print("🚀 Starting Flask-SocketIO server...")
128
 
129
  # Start PyGame thread
130
  game_thread = threading.Thread(target=game_loop, daemon=True)
131
  game_thread.start()
132
 
 
 
 
133
  # Start server
134
  socketio.run(
135
  app,
 
 
1
  import pygame
2
  import time
3
  import threading
 
8
  from io import BytesIO
9
 
10
  os.environ['SDL_VIDEODRIVER'] = 'dummy'
11
+
12
+ try:
13
+ pygame.init()
14
+ print("✅ PyGame initialized successfully")
15
+ except Exception as e:
16
+ print(f"❌ PyGame init failed: {e}")
17
+ # Create a fallback mode
18
 
19
  app = Flask(__name__)
20
+ app.config['SECRET_KEY'] = 'simple_stream_key'
21
 
22
+ # Use threading mode - avoids eventlet issues
23
  socketio = SocketIO(app, async_mode='threading', cors_allowed_origins="*")
24
 
25
  WIDTH, HEIGHT = 400, 300
 
31
  }
32
 
33
  def game_loop():
34
+ """Simple PyGame loop"""
35
+ print("🎬 Starting PyGame loop")
36
+
37
+ # Test PyGame drawing
38
+ test_screen = pygame.Surface((100, 100))
39
+ test_screen.fill((255, 0, 0))
40
+ pygame.draw.circle(test_screen, (0, 255, 0), (50, 50), 30)
41
+ test_pixel = test_screen.get_at((50, 50))
42
+ print(f"🧪 PyGame test - Pixel at (50,50): {test_pixel}")
43
+
44
+ if test_pixel != (0, 255, 0, 255):
45
+ print("⚠️ WARNING: PyGame drawing might not work correctly")
46
+
47
+ # Main game surface
48
  screen = pygame.Surface((WIDTH, HEIGHT))
49
  x, speed = 200, 5
50
 
51
+ frame_counter = 0
52
+ last_log_time = time.time()
53
+
54
  while shared["streaming"]:
55
  start_time = time.time()
56
 
57
+ # Update
58
  x += speed
59
  if x < 30 or x > WIDTH-30:
60
  speed *= -1
61
 
62
+ # Draw
63
  screen.fill((25, 25, 45))
64
  pygame.draw.circle(screen, (255, 80, 80), (int(x), 150), 20)
65
 
 
68
  pygame.image.save(screen, buf, format='JPEG', quality=85)
69
  frame_b64 = base64.b64encode(buf.getvalue()).decode('utf-8')
70
 
71
+ # Broadcast frame
72
  socketio.emit('new_frame', {
73
  'frame': frame_b64,
74
  'count': shared['frame_count'],
75
+ 'x': x,
76
+ 'timestamp': time.time()
77
+ })
78
 
79
+ # Update shared state
80
  shared['x'] = x
81
  shared['frame_count'] += 1
82
+ frame_counter += 1
83
 
84
+ # Log every second
85
+ current_time = time.time()
86
+ if current_time - last_log_time >= 1.0:
87
+ print(f"📊 FPS: {frame_counter} | Total: {shared['frame_count']} | Clients: {shared['clients']}")
88
+ frame_counter = 0
89
+ last_log_time = current_time
90
 
91
+ # Frame rate control
92
  elapsed = time.time() - start_time
93
  if elapsed < 1.0/30:
94
  time.sleep(1.0/30 - elapsed)
 
99
  def index():
100
  return render_template_string('''
101
  <!DOCTYPE html>
102
+ <html>
103
+ <head>
104
+ <script src="https://cdn.socket.io/4.5.0/socket.io.min.js"></script>
105
+ <style>
106
+ body { background: #0f172a; color: white; text-align: center; padding: 20px; }
107
+ #streamImg { border: 3px solid #60a5fa; width: 400px; height: 300px; }
108
+ .stats { background: #1e293b; padding: 15px; border-radius: 10px; margin: 20px auto; width: 400px; }
109
+ </style>
110
+ </head>
111
+ <body>
112
+ <h1>🔄 Working PyGame Stream</h1>
113
+
114
+ <img id="streamImg">
115
+
116
+ <div class="stats">
117
+ <div>Frame: <span id="counter">0</span></div>
118
+ <div>Position: X=<span id="pos">200</span></div>
119
+ <div>Status: <span id="status">Connecting...</span></div>
120
+ <div>Clients: <span id="clients">0</span></div>
121
+ </div>
122
+
123
+ <script>
124
+ const socket = io();
125
+ let streamFrames = 0;
126
+ let lastFpsUpdate = Date.now();
127
 
128
+ socket.on('connect', () => {
129
+ console.log('✅ Connected to server');
130
+ document.getElementById('status').textContent = 'Connected';
131
+ document.body.style.background = '#1a5c1a';
132
+ });
133
+
134
+ socket.on('new_frame', (data) => {
135
+ // Update image
136
+ document.getElementById('streamImg').src =
137
+ 'data:image/jpeg;base64,' + data.frame;
138
 
139
+ // Update stats
140
+ document.getElementById('counter').textContent = data.count;
141
+ document.getElementById('pos').textContent = data.x;
 
 
 
142
 
143
+ // Calculate stream FPS
144
+ streamFrames++;
145
+ const now = Date.now();
146
+ if (now - lastFpsUpdate >= 1000) {
147
+ document.title = `Stream FPS: ${streamFrames}`;
148
+ streamFrames = 0;
149
+ lastFpsUpdate = now;
150
+ }
151
+ });
152
+
153
+ socket.on('client_count', (count) => {
154
+ document.getElementById('clients').textContent = count;
155
+ });
156
+
157
+ socket.on('disconnect', () => {
158
+ document.getElementById('status').textContent = 'Disconnected';
159
+ document.body.style.background = '#5c1a1a';
160
+ });
161
+
162
+ console.log('SocketIO client started');
163
+ </script>
164
+ </body>
165
+ </html>
166
  ''')
167
 
168
  @socketio.on('connect')
169
  def handle_connect():
170
  shared['clients'] += 1
171
  print(f"Client connected. Total: {shared['clients']}")
172
+ socketio.emit('client_count', shared['clients'])
173
 
174
  @socketio.on('disconnect')
175
  def handle_disconnect():
176
  shared['clients'] -= 1
177
  print(f"Client disconnected. Total: {shared['clients']}")
178
+ socketio.emit('client_count', shared['clients'])
179
 
180
  if __name__ == '__main__':
181
+ print("🚀 Starting server...")
182
 
183
  # Start PyGame thread
184
  game_thread = threading.Thread(target=game_loop, daemon=True)
185
  game_thread.start()
186
 
187
+ # Give it a moment
188
+ time.sleep(1)
189
+
190
  # Start server
191
  socketio.run(
192
  app,