1Imports System
2Imports System.Threading
3
4Public Module TrafficLightControllerModule
5
6' Define the states of the traffic light
7Public Enum TrafficLightState
8Red
9Yellow
10Green
11End Enum
12
13' Define the events that can trigger state transitions
14Public Enum TrafficLightEvent
15TimerTick
16End Enum
17
18' Class to manage the traffic light state and transitions
19Public Class TrafficLight
20Private currentState As TrafficLightState
21Private isRunning As Boolean = False
22Private simulationThread As Thread
23Private stopEvent As New ManualResetEvent(False)
24Private const LOG_FILE_PATH As String = "C:\Temp\TrafficLightLog.txt"
25Private logLock As New Object()
26
27' State durations in milliseconds
28Private ReadOnly stateDurations As New Dictionary(Of TrafficLightState, Integer)() From {
29{TrafficLightState.Red, 5000},
30{TrafficLightState.Yellow, 1500},
31{TrafficLightState.Green, 5000}
32}
33
34''' <summary>
35''' Initializes a new instance of the TrafficLight.
36''' </summary>
37Public Sub New()
38' Initial state is Red
39currentState = TrafficLightState.Red
40LogMessage($"Traffic light initialized. Current state: {currentState}")
41End Sub
42
43''' <summary>
44''' Starts the traffic light simulation.
45''' </summary>
46Public Sub StartSimulation()
47If isRunning Then
48LogMessage("Simulation is already running.")
49Return
50End If
51
52LogMessage("Starting traffic light simulation...")
53isRunning = True
54stopEvent.Reset()
55simulationThread = New Thread(AddressOf SimulationLoop) With {.IsBackground = True, .Name = "TrafficLightSimulator"}
56simulationThread.Start()
57LogMessage("Traffic light simulation started.")
58End Sub
59
60''' <summary>
61''' Stops the traffic light simulation gracefully.
62''' </summary>
63Public Sub StopSimulation()
64If Not isRunning Then
65LogMessage("Simulation is not running.")
66Return
67End If
68
69LogMessage("Stopping traffic light simulation...")
70stopEvent.Set()
71simulationThread.Join()
72isRunning = False
73LogMessage("Traffic light simulation stopped.")
74End Sub
75
76''' <summary>
77''' The main simulation loop that drives state transitions.
78''' </summary>
79Private Sub SimulationLoop()
80While Not stopEvent.WaitOne(0) ' Check if stop signal is set without blocking
81Dim currentDuration As Integer = stateDurations(currentState)
82LogMessage($"State: {currentState}, Duration: {currentDuration}ms")
83
84' Wait for the duration of the current state or until stop signal is received
85Dim waitResult As WaitHandle.WaitAny({stopEvent, Task.Delay(currentDuration).AsWaitHandle()})
86
87If waitResult = 0 Then ' stopEvent was signaled
88Exit While
89End If
90
91' If we reach here, the timer for the current state has elapsed.
92' Trigger the transition event.
93HandleEvent(TrafficLightEvent.TimerTick)
94End While
95End Sub
96
97''' <summary>
98''' Handles incoming events and triggers state transitions.
99''' </summary>
100''' <param name="eventToHandle">The event to handle.</param>
101Public Sub HandleEvent(eventToHandle As TrafficLightEvent)
102Select Case currentState
103Case TrafficLightState.Red
104If eventToHandle = TrafficLightEvent.TimerTick Then
105TransitionTo(TrafficLightState.Green)
106End If
107Case TrafficLightState.Yellow
108If eventToHandle = TrafficLightEvent.TimerTick Then
109TransitionTo(TrafficLightState.Red)
110End If
111Case TrafficLightState.Green
112If eventToHandle = TrafficLightEvent.TimerTick Then
113TransitionTo(TrafficLightState.Yellow)
114End If
115End Select
116End Sub
117
118''' <summary>
119''' Performs the state transition and executes entry actions.
120''' </summary>
121''' <param name="nextState">The state to transition to.</param>
122Private Sub TransitionTo(nextState As TrafficLightState)
123LogMessage($"Transitioning from {currentState} to {nextState}")
124currentState = nextState
125' Execute entry actions for the new state
126ExecuteEntryAction(currentState)
127End Sub
128
129''' <summary>
130''' Executes actions upon entering a specific state.
131''' </summary>
132''' <param name="state">The state being entered.</param>
133Private Sub ExecuteEntryAction(state As TrafficLightState)
134Select Case state
135Case TrafficLightState.Red
136Console.WriteLine("Light is RED. Stop.")
137Case TrafficLightState.Yellow
138Console.WriteLine("Light is YELLOW. Prepare to stop.")
139Case TrafficLightState.Green
140Console.WriteLine("Light is GREEN. Go.")
141End Select
142End Sub
143
144''' <summary>
145''' Writes a message to the log file.
146''' </summary>
147''' <param name="message">The message to log.</param>
148Private Sub LogMessage(message As String)
149Try
150SyncLock logLock
151Using writer As New System.IO.StreamWriter(LOG_FILE_PATH, True)
152writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} - {message}")
153End Using
154End SyncLock
155Catch ex As Exception
156Console.WriteLine($"FATAL: Failed to write to log file: {ex.Message}")
157End Try
158End Sub
159
160' Example Usage
161Public Shared Sub MainExample()
162Dim controller As New TrafficLight()
163controller.StartSimulation()
164
165' Let it run for a few cycles
166Thread.Sleep(20000) ' Run for 20 seconds
167
168controller.StopSimulation()
169End Sub
170
171End Class
172
173End Module