feat: implement client start/stop commands
- add ClientCommand struct to handle incoming commands
- introduce timerStopChannel to manage timer stopping
- modify startTimer to return a boolean for success/failure
- update runPomodoroTimer to handle timer start/stop commands
- add start and stop buttons in the index.html for user interaction
🤖
This commit is contained in:
parent
fa4eebbe76
commit
6d73711341
2 changed files with 122 additions and 35 deletions
76
GoTomato.go
76
GoTomato.go
|
@ -4,6 +4,7 @@ import (
|
|||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
@ -23,7 +24,14 @@ type BroadcastMessage struct {
|
|||
TimeLeft int `json:"time_left"`
|
||||
}
|
||||
|
||||
type ClientCommand struct {
|
||||
Command string `json:"command"`
|
||||
}
|
||||
|
||||
var clients = make(map[*websocket.Conn]bool)
|
||||
var timerRunning bool
|
||||
var timerStopChannel = make(chan bool, 1)
|
||||
var mu sync.Mutex // to synchronize access to shared state
|
||||
|
||||
// broadcastMessage sends the remaining time to all connected clients.
|
||||
func broadcastMessage(message BroadcastMessage) {
|
||||
|
@ -38,39 +46,56 @@ func broadcastMessage(message BroadcastMessage) {
|
|||
}
|
||||
}
|
||||
|
||||
// start a countdown and broadcast ever second
|
||||
func startTimer(remaining_seconds int, mode string, session int) {
|
||||
for remaining_seconds > 0 {
|
||||
// startTimer runs the countdown and broadcasts every second.
|
||||
func startTimer(remainingSeconds int, mode string, session int) bool {
|
||||
for remainingSeconds > 0 {
|
||||
select {
|
||||
case <-timerStopChannel:
|
||||
return false // Stop the timer if a stop command is received
|
||||
default:
|
||||
broadcastMessage(BroadcastMessage{
|
||||
Mode: mode,
|
||||
Session: session,
|
||||
MaxSession: sessions,
|
||||
TimeLeft: remaining_seconds,
|
||||
TimeLeft: remainingSeconds,
|
||||
})
|
||||
time.Sleep(time.Second)
|
||||
remaining_seconds--
|
||||
remainingSeconds--
|
||||
}
|
||||
}
|
||||
// send final 0 timer
|
||||
broadcastMessage(BroadcastMessage{
|
||||
Mode: mode,
|
||||
Session: 1,
|
||||
MaxSession: 4,
|
||||
Session: session,
|
||||
MaxSession: sessions,
|
||||
TimeLeft: 0,
|
||||
})
|
||||
return true
|
||||
}
|
||||
|
||||
// iterate the Pomodoro work/break sessions
|
||||
// runPomodoroTimer iterates the Pomodoro work/break sessions.
|
||||
func runPomodoroTimer() {
|
||||
mu.Lock()
|
||||
timerRunning = true
|
||||
|
||||
for session := 1; session <= sessions; session++ {
|
||||
startTimer(workDuration, "Work", session)
|
||||
if !startTimer(workDuration, "Work", session) {
|
||||
break
|
||||
}
|
||||
if session == sessions {
|
||||
startTimer(longBreakDuration, "LongBreak", session)
|
||||
if !startTimer(longBreakDuration, "LongBreak", session) {
|
||||
break
|
||||
}
|
||||
} else {
|
||||
startTimer(shortBreakDuration, "ShortBreak", session)
|
||||
if !startTimer(shortBreakDuration, "ShortBreak", session) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
timerRunning = false
|
||||
mu.Unlock()
|
||||
}
|
||||
|
||||
// upgrade HTTP requests to WebSocket connections.
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
|
@ -88,23 +113,40 @@ func handleConnections(w http.ResponseWriter, r *http.Request) {
|
|||
// Register the new client
|
||||
clients[ws] = true
|
||||
|
||||
// Clean up when the client disconnects
|
||||
// Listen for commands from this client
|
||||
for {
|
||||
_, _, err := ws.ReadMessage()
|
||||
_, message, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
log.Printf("Client disconnected: %v", err)
|
||||
delete(clients, ws)
|
||||
break
|
||||
}
|
||||
|
||||
// Handle incoming commands
|
||||
var command ClientCommand
|
||||
err = json.Unmarshal(message, &command)
|
||||
if err != nil {
|
||||
log.Printf("Error unmarshalling command: %v", err)
|
||||
continue
|
||||
}
|
||||
|
||||
// Process the commands
|
||||
switch command.Command {
|
||||
case "start":
|
||||
if !timerRunning {
|
||||
go runPomodoroTimer()
|
||||
}
|
||||
case "stop":
|
||||
if timerRunning {
|
||||
timerStopChannel <- true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
http.HandleFunc("/ws", handleConnections)
|
||||
|
||||
// Start a goroutine that runs the Pomodoro timer and broadcasts updates.
|
||||
go runPomodoroTimer()
|
||||
|
||||
log.Println("Pomodoro WebSocket server started on :8080")
|
||||
err := http.ListenAndServe(":8080", nil)
|
||||
if err != nil {
|
||||
|
|
47
index.html
47
index.html
|
@ -5,22 +5,67 @@
|
|||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Pomodoro Timer</title>
|
||||
<style>
|
||||
button {
|
||||
padding: 10px 20px;
|
||||
margin: 5px;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
#timer {
|
||||
font-size: 24px;
|
||||
margin-top: 20px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Pomodoro Timer</h1>
|
||||
<div id="timer">Connecting to server...</div>
|
||||
|
||||
<!-- Buttons to start and stop the timer -->
|
||||
<button id="startButton">Start</button>
|
||||
<button id="stopButton">Stop</button>
|
||||
|
||||
<script>
|
||||
var ws = new WebSocket("ws://localhost:8080/ws");
|
||||
|
||||
ws.onopen = function () {
|
||||
document.getElementById("timer").innerText = "Connected to server.";
|
||||
};
|
||||
|
||||
// Handle incoming messages and update the timer display
|
||||
ws.onmessage = function (event) {
|
||||
document.getElementById("timer").innerText = event.data;
|
||||
var data = JSON.parse(event.data);
|
||||
var mode = data.mode;
|
||||
var session = data.session;
|
||||
var maxSession = data.max_session;
|
||||
var timeLeft = data.time_left;
|
||||
|
||||
document.getElementById("timer").innerText =
|
||||
mode + " Session " + session + "/" + maxSession + ": " + formatTime(timeLeft);
|
||||
};
|
||||
|
||||
ws.onclose = function () {
|
||||
document.getElementById("timer").innerText = "Connection closed.";
|
||||
};
|
||||
|
||||
// Format time in MM:SS
|
||||
function formatTime(seconds) {
|
||||
var minutes = Math.floor(seconds / 60);
|
||||
var remainingSeconds = seconds % 60;
|
||||
return minutes.toString().padStart(2, '0') + ":" + remainingSeconds.toString().padStart(2, '0');
|
||||
}
|
||||
|
||||
// Send start command to the server
|
||||
document.getElementById("startButton").addEventListener("click", function () {
|
||||
ws.send(JSON.stringify({command: "start"}));
|
||||
});
|
||||
|
||||
// Send stop command to the server
|
||||
document.getElementById("stopButton").addEventListener("click", function () {
|
||||
ws.send(JSON.stringify({command: "stop"}));
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
|
||||
|
|
Loading…
Reference in a new issue