# main.ino

- Project: [AstroPort](https://flashesp.com/explore/NCGayNJtPfwOtr1SDeESq.md) by amirkarls
- Board: M5Stick-C
- Language: Arduino (C++)
- Web page: https://flashesp.com/explore/NCGayNJtPfwOtr1SDeESq/files/7IJ6dtmjKYZ2R8x0QIbqK

```cpp
#include <M5StickCPlus2.h>
#include <WiFi.h>
#include <WebServer.h>
#include <WebSocketsServer.h>
#include <esp_wifi.h>
#include <esp_system.h>
#include <EEPROM.h>

// ========== CONFIG ==========
const char* ap_ssid = "Astro";
const char* ap_password = "AstroHome";
#define EEPROM_SIZE 64

// ========== PINS ==========
#define PIN_G26       26
#define PIN_G19       19

// ========== COLORS (Bruce style) ==========
#define COLOR_BG      TFT_BLACK
#define COLOR_FG      TFT_CYAN
#define COLOR_SEL     TFT_BLUE
#define COLOR_ALERT   TFT_RED
#define COLOR_SUCCESS TFT_GREEN

// ========== GLOBALS ==========
WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
float roll = 0, pitch = 0;
bool g26State = false;
bool g19State = false;
int buzzerVolume = 128;
bool buzzerEnabled = true;
bool webServerEnabled = true;
bool bleSpamActive = false;
bool wifiDeauthActive = false;
bool sirenActive = false;
unsigned long sirenLastToggle = 0;
int sirenStep = 0;

// Menu
int menuIndex = 0;
int menuOffset = 0;
int maxVisibleItems = 5;
int numMenuItems = 15;

String menuItems[] = {
  "Web Server", "BLE Spam", "WiFi Deauth", "G26 Control", "G19 Control",
  "Police Siren", "Buzzer Test", "Buzzer Enable", "System Info", "Themes",
  "Snake Game", "Pong Game", "Evil Portal", "WiFi Scan", "Power Off"
};

// Themes
int currentTheme = 0;
uint16_t themes[][4] = {
  {TFT_BLACK, TFT_CYAN, TFT_BLUE, TFT_WHITE},      // Default
  {TFT_BLACK, TFT_MAGENTA, TFT_PURPLE, TFT_YELLOW}, // Purple
  {TFT_BLACK, TFT_GREEN, TFT_DARKGREEN, TFT_WHITE}, // Green
  {TFT_BLACK, TFT_RED, TFT_MAROON, TFT_YELLOW},     // Red
};

// Games
int snakeX[100], snakeY[100];
int snakeLen = 3;
int foodX, foodY;
int gameDir = 2;
bool gameRunning = false;
int pongBallX = 60, pongBallY = 50, pongPaddleY = 50, pongScore = 0;
int ballDirX = 2, ballDirY = 1;

// Battery
float batteryVoltage = 0;
int batteryPercent = 0;
unsigned long lastBatteryUpdate = 0;

// ========== BATTERY ==========
void updateBattery() {
  if (millis() - lastBatteryUpdate > 5000) {
    batteryVoltage = analogRead(38) * 2.0 * 3.3 / 4095.0;
    batteryPercent = (int)((batteryVoltage - 3.0) / 1.2 * 100);
    if (batteryPercent > 100) batteryPercent = 100;
    if (batteryPercent < 0) batteryPercent = 0;
    lastBatteryUpdate = millis();
  }
}

void drawBatteryIcon(int x, int y) {
  M5.Lcd.drawRect(x, y, 30, 12, COLOR_FG);
  M5.Lcd.fillRect(x + 30, y + 3, 3, 6, COLOR_FG);
  int fillWidth = (batteryPercent * 28) / 100;
  if (fillWidth > 0) {
    uint16_t batteryColor = batteryPercent > 60 ? TFT_GREEN : (batteryPercent > 20 ? TFT_YELLOW : TFT_RED);
    M5.Lcd.fillRect(x + 1, y + 1, fillWidth, 10, batteryColor);
  }
  M5.Lcd.setCursor(x + 35, y + 2);
  M5.Lcd.setTextColor(COLOR_FG);
  M5.Lcd.print(String(batteryPercent) + "%");
}

// ========== UTILS ==========
void playTone(int frequency, int duration, int volume) {
  if (!buzzerEnabled) return;
  ledcSetup(15, frequency, 8);
  ledcAttachPin(GPIO_NUM_2, 15);
  ledcWrite(15, volume);
  delay(duration);
  ledcWrite(15, 0);
}

void saveSettings() {
  EEPROM.begin(EEPROM_SIZE);
  EEPROM.write(0, currentTheme);
  EEPROM.write(1, buzzerEnabled ? 1 : 0);
  EEPROM.commit();
}

void loadSettings() {
  EEPROM.begin(EEPROM_SIZE);
  currentTheme = EEPROM.read(0);
  if (currentTheme > 3) currentTheme = 0;
  buzzerEnabled = (EEPROM.read(1) == 1);
}

void drawHeader(const char* title) {
  M5.Lcd.fillRect(0, 0, 240, 16, themes[currentTheme][2]);
  M5.Lcd.setTextColor(themes[currentTheme][1]);
  M5.Lcd.setCursor(80, 4);
  M5.Lcd.println(title);
  drawBatteryIcon(190, 2);
}

void displayMessage(const char* msg, uint16_t color) {
  M5.Lcd.fillRect(0, 100, 240, 20, COLOR_BG);
  M5.Lcd.setTextColor(color);
  M5.Lcd.setCursor(20, 105);
  M5.Lcd.println(msg);
  delay(1500);
}

// ========== MENU (Bruce style) ==========
void drawMenu() {
  M5.Lcd.fillScreen(themes[currentTheme][0]);
  drawHeader("AstroHack");
  
  for (int i = 0; i < maxVisibleItems; i++) {
    int itemIndex = menuOffset + i;
    if (itemIndex >= numMenuItems) break;
    
    int y = 25 + (i * 20);
    if (itemIndex == menuIndex) {
      M5.Lcd.fillRect(5, y-2, 230, 18, themes[currentTheme][2]);
      M5.Lcd.setTextColor(themes[currentTheme][3]);
      M5.Lcd.setCursor(20, y);
      M5.Lcd.print("> ");
    } else {
      M5.Lcd.setTextColor(themes[currentTheme][1]);
      M5.Lcd.setCursor(20, y);
      M5.Lcd.print("  ");
    }
    M5.Lcd.print(menuItems[itemIndex]);
    
    M5.Lcd.setTextColor(TFT_YELLOW);
    M5.Lcd.setCursor(170, y);
    if (menuItems[itemIndex] == "Web Server") M5.Lcd.print(webServerEnabled ? "ON" : "OFF");
    else if (menuItems[itemIndex] == "BLE Spam") M5.Lcd.print(bleSpamActive ? "ACT" : "");
    else if (menuItems[itemIndex] == "WiFi Deauth") M5.Lcd.print(wifiDeauthActive ? "ACT" : "");
    else if (menuItems[itemIndex] == "G26 Control") M5.Lcd.print(g26State ? "ON" : "OFF");
    else if (menuItems[itemIndex] == "G19 Control") M5.Lcd.print(g19State ? "ON" : "OFF");
    else if (menuItems[itemIndex] == "Police Siren") M5.Lcd.print(sirenActive ? "ON" : "OFF");
    else if (menuItems[itemIndex] == "Buzzer Enable") M5.Lcd.print(buzzerEnabled ? "ON" : "OFF");
  }
  
  M5.Lcd.setTextColor(themes[currentTheme][1]);
  M5.Lcd.fillRect(0, 115, 240, 10, themes[currentTheme][2]);
  M5.Lcd.setCursor(10, 117);
  M5.Lcd.print("A:Select B:Down C:Up");
}

void scrollUp() {
  if (menuIndex > 0) {
    menuIndex--;
    if (menuIndex < menuOffset) menuOffset = menuIndex;
    drawMenu();
  }
}

void scrollDown() {
  if (menuIndex < numMenuItems - 1) {
    menuIndex++;
    if (menuIndex >= menuOffset + maxVisibleItems) menuOffset = menuIndex - maxVisibleItems + 1;
    drawMenu();
  }
}

// ========== POLICE SIREN ==========
void startSiren() {
  sirenActive = true;
  sirenStep = 0;
  pinMode(PIN_G26, OUTPUT);
  pinMode(PIN_G19, OUTPUT);
  displayMessage("SIREN ACTIVE", COLOR_ALERT);
}

void stopSiren() {
  sirenActive = false;
  digitalWrite(PIN_G26, LOW);
  digitalWrite(PIN_G19, LOW);
  displayMessage("Siren OFF", COLOR_SUCCESS);
}

void updateSiren() {
  if (!sirenActive) return;
  
  if (millis() - sirenLastToggle > 100) {
    sirenLastToggle = millis();
    sirenStep++;
    
    if (sirenStep % 2 == 0) {
      digitalWrite(PIN_G26, HIGH);
      digitalWrite(PIN_G19, LOW);
      playTone(800, 80, buzzerVolume);
    } else {
      digitalWrite(PIN_G26, LOW);
      digitalWrite(PIN_G19, HIGH);
      playTone(600, 80, buzzerVolume);
    }
    if (sirenStep > 20) sirenStep = 0;
  }
}

// ========== SNAKE GAME ==========
void initSnake() {
  snakeLen = 3;
  snakeX[0] = 10; snakeY[0] = 10;
  snakeX[1] = 9; snakeY[1] = 10;
  snakeX[2] = 8; snakeY[2] = 10;
  foodX = 15; foodY = 10;
  gameDir = 2;
  gameRunning = true;
}

void drawSnake() {
  M5.Lcd.fillScreen(themes[currentTheme][0]);
  M5.Lcd.setTextColor(TFT_GREEN);
  M5.Lcd.setCursor(10, 5);
  M5.Lcd.print("Score: " + String(snakeLen - 3));
  drawBatteryIcon(190, 2);
  
  for (int i = 0; i < snakeLen; i++) {
    M5.Lcd.fillRect(snakeX[i] * 6, snakeY[i] * 6 + 20, 5, 5, TFT_GREEN);
  }
  M5.Lcd.fillRect(foodX * 6, foodY * 6 + 20, 5, 5, TFT_RED);
}

void updateSnake() {
  int newX = snakeX[0];
  int newY = snakeY[0];
  if (gameDir == 0) newY--;
  else if (gameDir == 1) newX++;
  else if (gameDir == 2) newY++;
  else if (gameDir == 3) newX--;
  
  if (newX == foodX && newY == foodY) {
    snakeLen++;
    snakeX[snakeLen-1] = snakeX[snakeLen-2];
    snakeY[snakeLen-1] = snakeY[snakeLen-2];
    foodX = random(5, 35);
    foodY = random(5, 15);
    playTone(800, 50, buzzerVolume);
  }
  
  for (int i = snakeLen-1; i > 0; i--) {
    snakeX[i] = snakeX[i-1];
    snakeY[i] = snakeY[i-1];
  }
  snakeX[0] = newX;
  snakeY[0] = newY;
  
  if (newX < 0 || newX > 39 || newY < 0 || newY > 19) gameRunning = false;
  for (int i = 1; i < snakeLen; i++) {
    if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) gameRunning = false;
  }
  drawSnake();
}

// ========== PONG GAME ==========
void initPong() {
  pongBallX = 60;
  pongBallY = 50;
  pongPaddleY = 50;
  pongScore = 0;
  ballDirX = 2;
  ballDirY = 1;
  gameRunning = true;
}

void drawPong() {
  M5.Lcd.fillScreen(themes[currentTheme][0]);
  M5.Lcd.fillCircle(pongBallX, pongBallY, 3, TFT_WHITE);
  M5.Lcd.fillRect(220, pongPaddleY, 5, 30, TFT_WHITE);
  M5.Lcd.setCursor(10, 5);
  M5.Lcd.print("Score: " + String(pongScore));
  drawBatteryIcon(190, 2);
}

void updatePong() {
  pongBallX += ballDirX;
  pongBallY += ballDirY;
  
  if (pongBallY < 10 || pongBallY > 110) ballDirY = -ballDirY;
  if (pongBallX > 210) {
    if (abs(pongBallY - pongPaddleY) < 30) {
      ballDirX = -ballDirX;
      pongScore++;
      playTone(600, 50, buzzerVolume);
    } else {
      gameRunning = false;
    }
  }
  if (pongBallX < 10) ballDirX = -ballDirX;
  
  if (M5.BtnA.wasPressed()) pongPaddleY -= 10;
  if (M5.BtnB.wasPressed()) pongPaddleY += 10;
  if (pongPaddleY < 10) pongPaddleY = 10;
  if (pongPaddleY > 90) pongPaddleY = 90;
  drawPong();
}

// ========== SYSTEM INFO ==========
void showSystemInfo() {
  M5.Lcd.fillScreen(themes[currentTheme][0]);
  drawHeader("System Info");
  M5.Lcd.setTextSize(1);
  M5.Lcd.setTextColor(themes[currentTheme][1]);
  M5.Lcd.setCursor(10, 25);
  M5.Lcd.print("Chip: ESP32");
  M5.Lcd.setCursor(10, 40);
  M5.Lcd.print("Flash: " + String(ESP.getFlashChipSize() / 1024 / 1024) + " MB");
  M5.Lcd.setCursor(10, 55);
  M5.Lcd.print("Free Heap: " + String(ESP.getFreeHeap() / 1024) + " KB");
  M5.Lcd.setCursor(10, 70);
  M5.Lcd.print("Free PSRAM: " + String(ESP.getFreePsram() / 1024) + " KB");
  M5.Lcd.setCursor(10, 85);
  M5.Lcd.print("Battery: " + String(batteryVoltage, 2) + "V (" + String(batteryPercent) + "%)");
  M5.Lcd.setCursor(10, 100);
  M5.Lcd.print("Uptime: " + String(millis() / 1000 / 60) + " min");
  delay(3000);
}

// ========== WEB SERVER ==========
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>AstroHack</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{background:#0a0f1e;color:#0fc;font-family:monospace;padding:20px}
h1{text-align:center;margin-bottom:20px}
.section{background:#0d1525;border-radius:15px;padding:15px;margin-bottom:15px}
.section h2{color:#ff3366;margin-bottom:10px;font-size:18px}
.grid{display:grid;grid-template-columns:repeat(2,1fr);gap:10px}
button{background:#1a2a3a;color:#0fc;padding:12px;border:none;border-radius:10px;font-size:14px;cursor:pointer}
button:active{transform:scale(0.95)}
.status{background:#0a0f1e;padding:10px;border-radius:10px;margin-top:10px;font-size:12px}
</style>
</head>
<body>
<h1>⚡ ASTROHACK ⚡</h1>
<div class="section"><h2>GPIO Control</h2>
<div class="grid">
<button onclick="fetch('/g26/on')">G26 ON</button>
<button onclick="fetch('/g26/off')">G26 OFF</button>
<button onclick="fetch('/g19/on')">G19 ON</button>
<button onclick="fetch('/g19/off')">G19 OFF</button>
<button onclick="fetch('/flash')">✨ FLASH</button>
</div></div>
<div class="section"><h2>Attacks</h2>
<div class="grid">
<button onclick="fetch('/ble/spam')">📱 BLE Spam</button>
<button onclick="fetch('/deauth')">📡 Deauth</button>
<button onclick="fetch('/siren/on')">🚨 Siren ON</button>
<button onclick="fetch('/siren/off')">🛑 Siren OFF</button>
</div></div>
<div class="section"><h2>Buzzer</h2>
<div class="grid">
<button onclick="fetch('/buzzer/on')">🔊 Buzzer ON</button>
<button onclick="fetch('/buzzer/off')">🔇 Buzzer OFF</button>
<button onclick="fetch('/buzzer/test')">🔊 Test</button>
</div></div>
<div class="section"><h2>System</h2>
<div class="grid">
<button onclick="fetch('/info')">📊 Info</button>
<button onclick="fetch('/web/off')">🌐 Web OFF</button>
</div></div>
<div class="status" id="status">Ready</div>
<script>
setInterval(()=>{fetch('/ping').then(r=>r.text()).then(t=>document.getElementById('status').innerHTML='Status: '+t)},3000);
</script>
</body>
</html>
)rawliteral";

void setupWebServer() {
  server.on("/", []() { server.send(200, "text/html", index_html); });
  server.on("/g26/on", []() { g26State=true; digitalWrite(PIN_G26,HIGH); server.send(200,"text/plain","OK"); });
  server.on("/g26/off", []() { g26State=false; digitalWrite(PIN_G26,LOW); server.send(200,"text/plain","OK"); });
  server.on("/g19/on", []() { g19State=true; digitalWrite(PIN_G19,HIGH); server.send(200,"text/plain","OK"); });
  server.on("/g19/off", []() { g19State=false; digitalWrite(PIN_G19,LOW); server.send(200,"text/plain","OK"); });
  server.on("/flash", []() {
    for(int i=0;i<3;i++){ digitalWrite(PIN_G19,HIGH); digitalWrite(PIN_G26,HIGH); delay(100);
    digitalWrite(PIN_G19,LOW); digitalWrite(PIN_G26,LOW); delay(100); }
    server.send(200,"text/plain","OK");
  });
  server.on("/ble/spam", []() { bleSpamActive=!bleSpamActive; server.send(200,"text/plain",bleSpamActive?"ON":"OFF"); });
  server.on("/deauth", []() { wifiDeauthActive=!wifiDeauthActive; server.send(200,"text/plain",wifiDeauthActive?"ON":"OFF"); });
  server.on("/siren/on", []() { startSiren(); server.send(200,"text/plain","SIREN ON"); });
  server.on("/siren/off", []() { stopSiren(); server.send(200,"text/plain","SIREN OFF"); });
  server.on("/buzzer/on", []() { buzzerEnabled=true; saveSettings(); server.send(200,"text/plain","OK"); });
  server.on("/buzzer/off", []() { buzzerEnabled=false; saveSettings(); server.send(200,"text/plain","OK"); });
  server.on("/buzzer/test", []() { playTone(1000,200,buzzerVolume); server.send(200,"text/plain","OK"); });
  server.on("/info", []() { showSystemInfo(); server.send(200,"text/plain","OK"); });
  server.on("/web/off", []() { webServerEnabled=false; server.stop(); server.send(200,"text/plain","WEB OFF"); });
  server.on("/ping", []() { server.send(200,"text/plain","pong"); });
  server.begin();
}

// ========== POWER OFF ==========
void checkPowerOff() {
  if (M5.BtnC.pressedFor(3000)) {
    M5.Lcd.fillScreen(COLOR_BG);
    M5.Lcd.setTextColor(COLOR_ALERT);
    M5.Lcd.setCursor(30,50);
    M5.Lcd.println("SHUTDOWN");
    for(int i=3;i>0;i--){
      M5.Lcd.fillRect(50,80,30,20,COLOR_BG);
      M5.Lcd.setCursor(60,80);
      M5.Lcd.println(String(i));
      playTone(1000,100,buzzerVolume);
      delay(1000);
    }
    esp_deep_sleep_start();
  }
}

// ========== SETUP ==========
void setup() {
  M5.begin();
  M5.Lcd.setRotation(3);
  loadSettings();
  
  // Boot animation
  M5.Lcd.fillScreen(COLOR_BG);
  M5.Lcd.setTextColor(TFT_YELLOW);
  M5.Lcd.setTextSize(2);
  M5.Lcd.setCursor(50,50);
  M5.Lcd.println("AstroHack");
  M5.Lcd.setTextSize(1);
  for(int i=0;i<=100;i+=10){
    M5.Lcd.fillRect(30,90,(i*180)/100,10,TFT_GREEN);
    delay(30);
  }
  delay(500);
  
  pinMode(PIN_G26, OUTPUT);
  pinMode(PIN_G19, OUTPUT);
  pinMode(38, INPUT);
  M5.Imu.init();
  
  WiFi.mode(WIFI_AP);
  WiFi.softAP(ap_ssid, ap_password);
  setupWebServer();
  webSocket.begin();
  
  drawMenu();
  playTone(2000,100,buzzerVolume);
}

// ========== LOOP ==========
void loop() {
  if (webServerEnabled) server.handleClient();
  M5.update();
  
  checkPowerOff();
  updateSiren();
  updateBattery();
  
  if (M5.BtnB.wasPressed()) scrollDown();
  if (M5.BtnC.wasPressed()) scrollUp();
  
  if (M5.BtnA.wasPressed()) {
    String selected = menuItems[menuIndex];
    
    if (selected == "Web Server") {
      webServerEnabled = !webServerEnabled;
      if (!webServerEnabled) server.stop();
      else setupWebServer();
      displayMessage(webServerEnabled ? "Web ON" : "Web OFF", COLOR_SUCCESS);
    }
    else if (selected == "BLE Spam") {
      bleSpamActive = !bleSpamActive;
      displayMessage(bleSpamActive ? "BLE Spam ON" : "BLE Spam OFF", bleSpamActive ? COLOR_ALERT : COLOR_SUCCESS);
    }
    else if (selected == "WiFi Deauth") {
      wifiDeauthActive = !wifiDeauthActive;
      displayMessage(wifiDeauthActive ? "Deauth ON" : "Deauth OFF", wifiDeauthActive ? COLOR_ALERT : COLOR_SUCCESS);
    }
    else if (selected == "G26 Control") {
      g26State = !g26State;
      digitalWrite(PIN_G26, g26State ? HIGH : LOW);
      displayMessage(g26State ? "G26 ON" : "G26 OFF", COLOR_SUCCESS);
    }
    else if (selected == "G19 Control") {
      g19State = !g19State;
      digitalWrite(PIN_G19, g19State ? HIGH : LOW);
      displayMessage(g19State ? "G19 ON" : "G19 OFF", COLOR_SUCCESS);
    }
    else if (selected == "Police Siren") {
      if (!sirenActive) startSiren();
      else stopSiren();
    }
    else if (selected == "Buzzer Test") {
      for (int f=500; f<=2000; f+=500) playTone(f,200,buzzerVolume);
    }
    else if (selected == "Buzzer Enable") {
      buzzerEnabled = !buzzerEnabled;
      saveSettings();
      displayMessage(buzzerEnabled ? "Buzzer ON" : "Buzzer OFF", COLOR_SUCCESS);
    }
    else if (selected == "System Info") {
      showSystemInfo();
    }
    else if (selected == "Themes") {
      currentTheme = (currentTheme + 1) % 4;
      saveSettings();
      drawMenu();
    }
    else if (selected == "Snake Game") {
      initSnake();
      while(gameRunning && !M5.BtnC.wasPressed()) {
        if (M5.BtnA.wasPressed()) gameDir = 0;
        if (M5.BtnB.wasPressed()) gameDir = 2;
        updateSnake();
        delay(200);
        M5.update();
      }
    }
    else if (selected == "Pong Game") {
      initPong();
      while(gameRunning && !M5.BtnC.wasPressed()) {
        updatePong();
        delay(30);
        M5.update();
      }
    }
    else if (selected == "Power Off") {
      esp_deep_sleep_start();
    }
    drawMenu();
  }
  
  delay(50);
}
```
