### Quick Start Example (cURL) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A minimal runnable example demonstrating how to get started with IslandMQ using cURL. ```Bash # Example: Ping server curl http://localhost:5000/api/ping # Example: Get current time curl http://localhost:5000/api/time ``` -------------------------------- ### Quick Start Example (Python) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A minimal runnable example demonstrating how to get started with IslandMQ using Python. ```Python import requests # Example: Ping server response = requests.get("http://localhost:5000/api/ping") print(response.json()) # Example: Get current time response = requests.get("http://localhost:5000/api/time") print(response.json()) ``` -------------------------------- ### Quick Start Example (JavaScript) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A minimal runnable example demonstrating how to get started with IslandMQ using JavaScript. ```JavaScript // Example: Ping server fetch("http://localhost:5000/api/ping") .then(response => response.json()) .then(data => console.log(data)); // Example: Get current time fetch("http://localhost:5000/api/time") .then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### Configuration Example (Minimal) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A minimal configuration example for IslandMQ, showing the essential settings to get the server running. ```JSON { "NetMQ": { "Enabled": true, "Host": "127.0.0.1", "Port": 5555 }, "HttpServer": { "Enabled": true, "Host": "127.0.0.1", "Port": 5000 } } ``` -------------------------------- ### Complete NetMQREQServer Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/api-reference/netmq-req-server.md A comprehensive example demonstrating the creation, configuration, starting, and stopping of a NetMQREQServer. It includes subscribing to error events and proper disposal. ```csharp // 创建并启动服务器 var server = new NetMQREQServer("tcp://0.0.0.0:5555"); // 订阅错误事件 server.ErrorOccurred += (sender, ex) => { Console.WriteLine($"Server error: {ex}"); }; // 启动服务器 server.Start(); // 保持服务器运行 Thread.Sleep(Timeout.Infinite); // 停止并释放 server.Stop(); server.Dispose(); ``` -------------------------------- ### NetMQ REQ Server Start/Stop Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Demonstrates starting, stopping, and disposing of the NetMQREQServer. Ensure proper resource management by calling Dispose. ```C# using IslandMQ.Core; var server = new NetMQREQServer("127.0.0.1", 5555); server.ErrorOccurred += (sender, e) => Console.WriteLine($"Error: {e.Message}"); server.Start(); Console.WriteLine("Server started. Press Enter to stop."); Console.ReadLine(); server.Stop(); server.Dispose(); Console.WriteLine("Server stopped and disposed."); ``` -------------------------------- ### Install pyzmq Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Install the pyzmq library to enable ZeroMQ communication. This is a prerequisite for using the provided Python examples. ```bash pip install pyzmq ``` -------------------------------- ### Full Workflow Example (Bash) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A comprehensive example in Bash demonstrating a typical workflow involving multiple IslandMQ API commands. ```Bash # Example: Get current time TIME_INFO=$(curl -s http://localhost:5000/api/time) echo "Current Time: $TIME_INFO" # Example: Send a notification curl -X POST -H "Content-Type: application/json" -d '{"command": "notice", "parameters": {"message": "System maintenance soon."}}' http://localhost:5000/api/command # Example: Get class plan (assuming a class ID is known) # curl -X POST -H "Content-Type: application/json" -d '{"command": "get_classplan", "parameters": {"classId": "12345"}}' http://localhost:5000/api/command ``` -------------------------------- ### Subscribe to ZeroMQ Events (Python Example) Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Example using Python to subscribe to all events published via ZeroMQ on tcp://localhost:5556. Ensure ZeroMQ is installed. ```bash # 使用 Python 示例 python subscriber.py ``` -------------------------------- ### Full Workflow Example (Python) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A comprehensive example in Python demonstrating a typical workflow involving multiple IslandMQ API commands. ```Python import requests import json BASE_URL = "http://localhost:5000/api" def send_command(command, parameters=None): payload = { "command": command, "parameters": parameters or {} } response = requests.post(f"{BASE_URL}/command", json=payload) return response.json() # Example: Get current time time_response = requests.get(f"{BASE_URL}/time") print(f"Current Time: {time_response.json()}") # Example: Send a notification notice_result = send_command("notice", {"message": "System maintenance soon."}) print(f"Notice Result: {notice_result}") # Example: Get class plan classplan_result = send_command("get_classplan", {"classId": "12345"}) print(f"Class Plan Result: {classplan_result}") ``` -------------------------------- ### Class Plan Response Example Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md This is an example of the JSON response received after successfully executing the 'get_classplan' command. ```jsonc { "success": true, "message": "Class plan retrieved successfully", "data": { "Date": "2026-03-01", "ClassPlan": { "TimeLayoutId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "TimeRule": { "WeekDay": 1, "WeekRotation": 0, "StartDate": "2024-01-01T00:00:00", "EndDate": "2024-12-31T23:59:59" }, "Name": "周一课表", "IsOverlay": false, "OverlaySourceId": null, "OverlaySetupTime": "2024-01-01T00:00:00", "IsEnabled": true, "AssociatedGroup": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "AttachedObjects": {}, "IsActive": false, "TimeLayout": { "Name": "默认时间表", "Layouts": [ { "StartTime": "08:00:00", "EndTime": "08:45:00", "TimeType": 0, "IsHideDefault": false, "DefaultClassId": "00000000-0000-0000-0000-000000000000", "BreakName": "", "ActionSet": null, "AttachedObjects": {}, "IsActive": false, "Class": { "SubjectId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "IsChangedClass": false, "IsEnabled": true, "AttachedObjects": {}, "IsActive": false, "Subject": { "Name": "数学", "Initial": "数", "TeacherName": "张老师", "IsOutDoor": false } } } // 更多时间点... ] } } }, "request_id": 1, "status_code": 200, "version": 0 } ``` -------------------------------- ### Valid 'command' Parameter Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This is an example of a correctly formatted JSON request with a valid 'command' parameter. ```json { "command": "ping" } ``` -------------------------------- ### Configuration Example (Full) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A comprehensive configuration for IslandMQ, including detailed settings for NetMQ, HTTP server, and CORS. ```JSON { "NetMQ": { "Enabled": true, "Host": "0.0.0.0", "Port": 5555, "RetryIntervalSeconds": 5 }, "HttpServer": { "Enabled": true, "Host": "0.0.0.0", "Port": 5000, "Cors": { "Policy": "AllowAll" } }, "Logging": { "LogLevel": "Information" } } ``` -------------------------------- ### Get Lesson Command Response Example Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md This JSON response provides detailed information about the current and upcoming lessons, including subject names, teachers, schedule details, and timings. It is returned upon successful execution of the 'get_lesson' command. ```json { "success": true, "message": "Lesson data retrieved successfully", "data": { "CurrentSubject": { "Name": "???", "Initial": "?", "TeacherName": "", "IsOutDoor": false, "AttachedObjects": {}, "IsActive": false }, "NextClassSubject": { "Name": "???", "Initial": "?", "TeacherName": "", "IsOutDoor": false, "AttachedObjects": {}, "IsActive": false }, "CurrentState": 0, "CurrentTimeLayoutItem": { "StartSecond": "", "EndSecond": "", "StartTime": "00:00:00", "EndTime": "00:00:00", "TimeType": 0, "IsHideDefault": false, "DefaultClassId": "00000000-0000-0000-0000-000000000000", "BreakName": "", "ActionSet": null, "AttachedObjects": {}, "IsActive": false }, "CurrentClassPlan": { "TimeLayoutId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Name": "周一课表", "TimeRule": { "WeekDay": 1, "WeekRotation": 0, "StartDate": "2024-01-01T00:00:00", "EndDate": "2024-12-31T23:59:59" }, "IsActive": true, "IsOverlay": false, "OverlaySourceId": null, "OverlaySetupTime": "2024-01-01T00:00:00", "IsEnabled": true, "AssociatedGroup": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "Classes": [ { "SubjectId": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "IsChangedClass": false, "IsEnabled": true, "AttachedObjects": {}, "IsActive": false, "Subject": { "Name": "数学", "Initial": "M", "TeacherName": "张老师", "IsOutDoor": false } } ] }, "NextBreakingTimeLayoutItem": { "StartSecond": "", "EndSecond": "", "StartTime": "00:00:00", "EndTime": "00:00:00", "TimeType": 0, "IsHideDefault": false, "DefaultClassId": "00000000-0000-0000-0000-000000000000", "BreakName": "", "ActionSet": null, "AttachedObjects": {}, "IsActive": false }, "NextClassTimeLayoutItem": { "StartSecond": "", "EndSecond": "", "StartTime": "00:00:00", "EndTime": "00:00:00", "TimeType": 0, "IsHideDefault": false, "DefaultClassId": "00000000-0000-0000-0000-000000000000", "BreakName": "", "ActionSet": null, "AttachedObjects": {}, "IsActive": false }, "CurrentSelectedIndex": -1, "OnClassLeftTime": "00:00:00", "OnBreakingTimeLeftTime": "00:00:00", "IsClassPlanEnabled": true, "IsClassPlanLoaded": false, "IsLessonConfirmed": false }, "request_id": 1, "status_code": 200, "version": 0 } ``` -------------------------------- ### Subscribe to ZeroMQ Events (Node.js Example) Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Example using Node.js to subscribe to all events published via ZeroMQ on tcp://localhost:5556. Requires the 'zeromq' npm package. ```javascript # 或使用其他支持 ZeroMQ 的语言 # 例如 Node.js: # const zmq = require('zeromq'); # const sock = new zmq.Subscriber(); # sock.connect('tcp://localhost:5556'); # sock.subscribe(''); # console.log('Subscribed to events'); # for await (const [msg] of sock) { # console.log('Received event:', msg.toString()); # } ``` -------------------------------- ### Start Server Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/api-reference/netmq-req-server.md Starts the server's background thread to begin processing requests. Ensure the server is not already running before calling this method. ```csharp public void Start() ``` ```csharp var server = new NetMQREQServer("tcp://127.0.0.1:5555"); server.Start(); ``` -------------------------------- ### Configuration Example (Development) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md A development-focused configuration for IslandMQ, enabling all features and setting up CORS for easy local testing. ```JSON { "NetMQ": { "Enabled": true, "Host": "0.0.0.0", "Port": 5555 }, "HttpServer": { "Enabled": true, "Host": "0.0.0.0", "Port": 5000, "Cors": { "Policy": "AllowAll" } } } ``` -------------------------------- ### Valid 'change_lesson' Command Structure Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md An example of a correctly structured JSON request for the 'change_lesson' command, including 'operation', 'class_index', and 'subject_id'. ```json { "command": "change_lesson", "operation": "replace", "class_index": 0, "subject_id": "550e8400-e29b-41d4-a716-446655440000" } ``` -------------------------------- ### Plugin Initialize and Event Handling Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Shows the basic lifecycle of a plugin, including initialization and handling events like OnClass and OnBreakingTime. ```C# using IslandMQ.Core; using IslandMQ.Core.Events; public class MyPlugin : Plugin { public override void Initialize() { Console.WriteLine("MyPlugin Initialized."); // Register event handlers OnClass += HandleClassEvent; OnBreakingTime += HandleBreakingTimeEvent; } private void HandleClassEvent(object sender, ClassEventArgs e) => Console.WriteLine($"Class Event: {e.ClassName}"); private void HandleBreakingTimeEvent(object sender, BreakingTimeEventArgs e) => Console.WriteLine($"Breaking Time: {e.EndTime}"); // Other methods like Start/Stop servers would be called here or in Initialize public override void Dispose() { Console.WriteLine("MyPlugin Disposing."); // Unregister event handlers OnClass -= HandleClassEvent; OnBreakingTime -= HandleBreakingTimeEvent; base.Dispose(); } } ``` -------------------------------- ### Start Method Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/api-reference/netmq-req-server.md Starts the server's background thread to begin processing requests. It includes logic to handle cases where a previous server task might still be running. ```APIDOC ## Start Method ### Description Starts the server's background thread to begin processing requests. It includes logic to handle cases where a previous server task might still be running. ### Parameters None ### Method `Start()` ### Endpoint N/A ### Request Example ```csharp var server = new NetMQREQServer("tcp://127.0.0.1:5555"); server.Start(); ``` ### Response N/A ``` -------------------------------- ### NetMQ PUB Server Publish Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Shows how to publish messages using the NetMQPUBServer. The Publish method is used to broadcast messages to connected subscribers. ```C# using IslandMQ.Core; var server = new NetMQPUBServer("127.0.0.1", 5556); server.ErrorOccurred += (sender, e) => Console.WriteLine($"Error: {e.Message}"); server.Start(); Console.WriteLine("PUB Server started. Publishing messages..."); // Publish a message server.Publish("Hello, subscribers!"); // Keep server running (in a real app, this would be managed differently) // For demonstration, we'll just wait a bit before stopping await Task.Delay(5000); server.Stop(); server.Dispose(); Console.WriteLine("PUB Server stopped."); ``` -------------------------------- ### Configuration Example (Limited CORS) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Configuration for IslandMQ with restricted CORS settings, allowing access only from specific origins. ```JSON { "NetMQ": { "Enabled": true, "Host": "127.0.0.1", "Port": 5555 }, "HttpServer": { "Enabled": true, "Host": "127.0.0.1", "Port": 5000, "Cors": { "Policy": "Limited", "AllowedOrigins": [ "https://example.com", "http://localhost:3000" ] } } } ``` -------------------------------- ### REQ/REP Example Request Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md A sample JSON request to send to IslandMQ using the REQ/REP pattern. This format is used for commands like 'notice'. ```json { "version": 0, "command": "notice", "args": ["测试提醒", "--context=这是一条测试提醒", "--mask-duration=2.0", "--overlay-duration=6.0"] } ``` -------------------------------- ### PUB/SUB Example Code Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Python code demonstrating how to subscribe to events from IslandMQ using the PUB/SUB pattern. It connects to the specified port and continuously receives messages. ```python import zmq context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://localhost:5556") socket.setsockopt_string(zmq.SUBSCRIBE, "") while True: message = socket.recv_string() print(f"Received event: {message}") socket.close() context.term() ``` -------------------------------- ### Client Error Handling Example (Python) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Example of how a client can handle errors returned by the IslandMQ API. It checks the 'success' field and processes the 'message' or 'data' accordingly. ```Python import requests import json BASE_URL = "http://localhost:5000/api" def get_time(): response = requests.get(f"{BASE_URL}/time") data = response.json() if data.get("success", False): print(f"Current time: {data.get('data')}") else: print(f"Error getting time: {data.get('message')}") def send_notice(message): payload = { "command": "notice", "parameters": {"message": message} } response = requests.post(f"{BASE_URL}/command", json=payload) data = response.json() if data.get("success", False): print(f"Notice sent successfully.") else: print(f"Error sending notice: {data.get('message')}") get_time() send_notice("Test notification") ``` -------------------------------- ### Notice Command JSON Response Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Example JSON response after successfully sending a 'notice' command, confirming the notification was processed. ```json { "success": true, "message": "Notice sent successfully", "data": null, "request_id": 1, "status_code": 200, "version": 0 } ``` -------------------------------- ### Correct 'notice' Command Structure with Title Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md Example of a correctly structured JSON request for the 'notice' command, including the required 'title' in the 'args' array. ```json { "command": "notice", "args": ["通知标题"] } ``` -------------------------------- ### Time Command JSON Response Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Example JSON response for the 'time' command, showing the time difference in milliseconds. ```json { "success": true, "message": "1919.8106", "data": null, "request_id": 1, "status_code": 200, "version": 0 } ``` -------------------------------- ### Sisk HTTP Server Broadcast Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Demonstrates broadcasting a message using the SiskHttpServer. This is useful for sending real-time updates to connected WebSocket clients. ```C# using IslandMQ.Core; using System.Text.Json; var server = new SiskHttpServer(5000, cors: CorsPolicy.AllowAll); server.ErrorOccurred += (sender, e) => Console.WriteLine($"Error: {e.Message}"); server.Start(); Console.WriteLine("HTTP Server started on port 5000."); // Example: Broadcast a JSON message var message = new { type = "update", data = "New data available" }; server.Broadcast(JsonSerializer.Serialize(message)); Console.WriteLine("Broadcasted message."); // Keep server running (in a real app, this would be managed differently) await Task.Delay(5000); server.Stop(); server.Dispose(); Console.WriteLine("HTTP Server stopped."); ``` -------------------------------- ### ClassIslandAPIHelper ProcessRequest Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Demonstrates using the ClassIslandAPIHelper to process requests, such as 'ping', 'time', or 'notice'. The ProcessRequest method handles command parsing and execution. ```C# using IslandMQ.Core.Utils; var apiHelper = new ClassIslandAPIHelper(); // Example: Ping command var pingResult = apiHelper.ProcessRequest("ping"); Console.WriteLine($"Ping Result: {pingResult.Success}"); // Example: Time command var timeResult = apiHelper.ProcessRequest("time"); Console.WriteLine($"Time Result: {timeResult.Data}"); // Example: Notice command var noticeResult = apiHelper.ProcessRequest("notice", new Dictionary { { "message", "Hello World" } }); Console.WriteLine($"Notice Result: {noticeResult.Success}"); ``` -------------------------------- ### Client Error Handling Example (JavaScript) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Example of how a JavaScript client can handle errors returned by the IslandMQ API. It checks the response status and content to determine success or failure. ```JavaScript const BASE_URL = "http://localhost:5000/api"; async function getTime() { try { const response = await fetch(`${BASE_URL}/time`); const data = await response.json(); if (data.success) { console.log(`Current time: ${data.data}`); } else { console.error(`Error getting time: ${data.message}`); } } catch (error) { console.error('Network or server error:', error); } } async function sendNotice(message) { try { const response = await fetch(`${BASE_URL}/command`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'notice', parameters: { message: message } }) }); const data = await response.json(); if (data.success) { console.log('Notice sent successfully.'); } else { console.error(`Error sending notice: ${data.message}`); } } catch (error) { console.error('Network or server error:', error); } } getTime(); sendNotice('Test notification'); ``` -------------------------------- ### Retry Strategy Code Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Illustrates a basic retry strategy that can be implemented in a client to handle transient network errors or temporary service unavailability. ```Python import requests import time MAX_RETRIES = 3 RETRY_DELAY_SECONDS = 5 def send_request_with_retry(url, method='GET', **kwargs): for attempt in range(MAX_RETRIES): try: response = requests.request(method, url, **kwargs) response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx) return response.json() except requests.exceptions.RequestException as e: print(f"Attempt {attempt + 1} failed: {e}") if attempt < MAX_RETRIES - 1: time.sleep(RETRY_DELAY_SECONDS) else: print("Max retries reached. Giving up.") raise return None # Example usage: # try: # result = send_request_with_retry("http://localhost:5000/api/ping") # print(result) # except Exception as e: # print(f"Request ultimately failed: {e}") ``` -------------------------------- ### Get Lesson Command Request Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md This is the JSON payload used to request current lesson information from the IslandMQ system. ```json { "version": 0, "command": "get_lesson" } ``` -------------------------------- ### NetMQ PUB Server Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md Documentation for the NetMQ PUB server, used for broadcasting events using the publish-subscribe pattern. It covers the `NetMQPUBServer` class, event broadcasting, and client subscription examples. ```APIDOC ## NetMQ PUB Server ### Description Broadcasts events using the NetMQ PUB/SUB pattern over TCP. ### Class `NetMQPUBServer` ### Usage Clients can subscribe to events broadcast by this server on `tcp://127.0.0.1:5556`. ### Events Broadcast - `OnClass` - `OnBreakingTime` - `OnAfterSchool` - `CurrentTimeStateChanged` ``` -------------------------------- ### Get Class Plan Command Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Use the 'get_classplan' command to retrieve the class schedule for a specific date. The date parameter is optional and defaults to the current day. ```json { "version": 0, "command": "get_classplan", "date": "2026-03-01" } ``` -------------------------------- ### NetMQ REQ Server Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md Documentation for the NetMQ REQ server, which handles request-response communication. It details the `NetMQREQServer` class, its methods, request processing, response formats, and provides usage examples. ```APIDOC ## NetMQ REQ Server ### Description Provides request-response communication using the NetMQ REQ pattern over TCP. ### Class `NetMQREQServer` ### Usage Connect to `tcp://127.0.0.1:5555` and send JSON requests with a `command` field. ### Request Example (Python) ```python import zmq import json context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:5555") # Send request socket.send_json({"command": "ping"}) # Receive response response = socket.recv_json() print(response) socket.close() context.term() ``` ### Response Example ```json { "success": true, "message": "OK", "data": null } ``` ``` -------------------------------- ### API Helper Result Example Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/INDEX.md Illustrates the structure of ApiHelperResult and ApiHelperResult used for returning API responses. These classes indicate success or failure and contain data or error information. ```C# using IslandMQ.Core.Utils; // Example of ApiHelperResult (for operations without specific data return) var successResult = new ApiHelperResult { Success = true, Message = "Operation completed successfully." }; Console.WriteLine($"Success: {successResult.Success}, Message: {successResult.Message}"); var errorResult = new ApiHelperResult { Success = false, Message = "An error occurred.", ErrorCode = 400 }; Console.WriteLine($"Success: {errorResult.Success}, Message: {errorResult.Message}, Code: {errorResult.ErrorCode}"); // Example of ApiHelperResult (for operations returning specific data) var dataResult = new ApiHelperResult { Success = true, Data = "Some data payload" }; Console.WriteLine($"Data Result: {dataResult.Data}"); ``` -------------------------------- ### Get Current IslandMQ Configuration in C# Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/configuration.md This C# code snippet demonstrates how to retrieve the IslandMQ settings service and access individual configuration values like server enablement and CORS origins. ```csharp using ClassIsland.Shared; using IslandMQ.Services; // 获取配置服务 var settingsService = IAppHost.GetService(); // 读取配置 bool reqEnabled = settingsService.Settings.IsReqServerEnabled; int reqPort = settingsService.Settings.ReqServerPort; string corsOrigins = settingsService.Settings.CorsAllowedOrigins; ``` -------------------------------- ### Invalid subject_id Format Error Response (400) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This error occurs when the 'subject_id' field is not a valid GUID string. Ensure 'subject_id' is provided in the correct GUID format. ```json { "success": false, "message": "Invalid subject_id format", "error": "Invalid subject_id format", "request_id": 3, "status_code": 400, "version": 0 } ``` -------------------------------- ### Plugin Entry and Lifecycle Management Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md Documentation for the main plugin class, handling entry points and lifecycle management. It covers the `Plugin` class, event handling, service management, and application startup/shutdown processes. ```APIDOC ## Plugin Entry and Lifecycle Management ### Description Manages the entry point and lifecycle of the IslandMQ plugin. ### Class `Plugin` (aliased as `[PluginEntrance]`) ### Responsibilities - Event handling - Service management - Application startup and shutdown processes ``` -------------------------------- ### NetMQREQServer Constructor Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/api-reference/netmq-req-server.md Initializes a new instance of the NetMQREQServer class, allowing configuration of the binding endpoint. ```APIDOC ## NetMQREQServer Constructor ### Description Initializes a new instance of the NetMQREQServer class, allowing configuration of the binding endpoint. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Constructor ### Endpoint N/A ### Request Example ```csharp // Using the default endpoint tcp://127.0.0.1:5555 var server = new NetMQREQServer(); // Using a custom endpoint var server = new NetMQREQServer("tcp://0.0.0.0:9999"); ``` ### Response N/A ``` -------------------------------- ### Ping Command JSON Response Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Example JSON response received after sending a 'ping' command, indicating a successful health check. ```json { "success": true, "message": "OK", "data": null, "request_id": 1, "status_code": 200, "version": 0 } ``` -------------------------------- ### NetMQREQServer Constructor Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/api-reference/netmq-req-server.md Initializes a NetMQ request-response server instance. You can specify a custom endpoint or use the default. ```csharp public NetMQREQServer(string endpoint = "tcp://127.0.0.1:5555") ``` ```csharp // 使用默认端点 tcp://127.0.0.1:5555 var server = new NetMQREQServer(); // 使用自定义端点 var server = new NetMQREQServer("tcp://0.0.0.0:9999"); ``` -------------------------------- ### Simple Notice Command JSON Request Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md A simplified JSON request for the 'notice' command, sending only a title without additional context or duration parameters. ```json { "version": 0, "command": "notice", "args": ["简单提醒"] } ``` -------------------------------- ### Change Lesson Command: Swap Operation Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Use the 'change_lesson' command with the 'swap' operation to exchange two lessons. Requires the indices of both classes to be swapped. ```json { "version": 0, "command": "change_lesson", "operation": "swap", "class_index1": 1, "class_index2": 3, "date": "2026-02-28" } ``` -------------------------------- ### HTTP/WebSocket Server Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md Documentation for the HTTP and WebSocket server, enabling REST API access and real-time push notifications. It details the `SiskHttpServer` class, endpoint configuration, CORS, and WebSocket event pushing. ```APIDOC ## HTTP/WebSocket Server ### Description Provides a REST API via HTTP and real-time event push via WebSockets. ### Class `SiskHttpServer` ### Endpoints - **HTTP API**: `POST /api`, `GET /api`, `OPTIONS /api` - **WebSocket**: `GET /ws` ### Configuration Supports HTTP endpoint configuration, CORS, and WebSocket event pushing. ### Request Example (JavaScript - HTTP POST) ```javascript const response = await fetch('http://127.0.0.1:8080/api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ command: 'ping' }) }); const data = await response.json(); console.log(data); ``` ### Request Example (JavaScript - WebSocket) ```javascript import websocket from 'websocket'; // Assuming a library like 'websocket' const ws = new websocket.WebSocket('ws://127.0.0.1:8080/ws'); ws.onopen = () => { console.log('WebSocket connection opened'); }; ws.onmessage = (event) => { console.log(`Received event: ${event.data}`); }; ws.onclose = () => { console.log('WebSocket connection closed'); }; ws.onerror = (error) => { console.error(`WebSocket error: ${error}`); }; ``` ``` -------------------------------- ### Class Plan Not Found Error Response (404) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This response indicates that no valid class plan was found for the specified date, possibly due to weekends, holidays, or configuration errors. Try a different date or check ClassIsland configuration. ```json { "success": false, "message": "Class plan not found for the specified date", "error": "Class plan not found for the specified date", "request_id": 4, "status_code": 404, "version": 0 } ``` -------------------------------- ### Invalid subject_id Format for change_lesson command Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md The 'subject_id' field for the 'change_lesson' command must be a valid GUID string. This error indicates an invalid format was provided. ```APIDOC ## Invalid subject_id Format for change_lesson command (400) ### Description This error occurs when the 'subject_id' is not a valid GUID string for the 'change_lesson' command. ### Method POST (Assumed) ### Endpoint / ### Parameters #### Request Body - **subject_id** (string) - Required - A valid GUID string. ### Request Example ```json { "subject_id": "550e8400-e29b-41d4-a716-446655440000" } ``` ### Response #### Error Response (400) ```json { "success": false, "message": "Invalid subject_id format", "error": "Invalid subject_id format", "request_id": 3, "status_code": 400, "version": 0 } ``` ``` -------------------------------- ### API Helper Class Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md Documentation for the `ClassIslandAPIHelper` static class, which serves as the command processing engine. It details all supported commands, parameter parsing, and validation. ```APIDOC ## API Helper Class ### Description Provides a static interface for interacting with the IslandMQ command processing engine. ### Class `ClassIslandAPIHelper` (static) ### Supported Commands - `ping`: Checks service availability. Returns no data. - `time`: Retrieves system or precise time difference. Returns time difference in milliseconds. - `notice`: Sends a notification message. Returns no data. - `get_lesson`: Fetches current timetable information. Returns timetable and time information. - `change_lesson`: Executes a course change operation. Returns no data. - `get_classplan`: Queries the timetable for a specified date. Returns detailed timetable information. ### Usage Commands can be invoked via NetMQ REQ, HTTP POST, or other supported interfaces. Parameters are parsed and validated by this class. ``` -------------------------------- ### Event Subscription Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Subscribe to event messages using ZeroMQ SUB mode on tcp://localhost:5556. An empty string subscribes to all messages. ```APIDOC ## Event Subscription ### Description Subscribe to event messages using ZeroMQ SUB mode on tcp://localhost:5556. An empty string subscribes to all messages. ### Connection `tcp://localhost:5556` ### Subscription Subscribe to all messages by providing an empty string. ### Example (Python) ```python import zmq context = zmq.Context() subscriber = context.socket(zmq.SUB) socket_address = 'tcp://localhost:5556' subscriber.connect(socket_address) subscriber.setsockopt_string(zmq.SUBSCRIBE, '') print(f"Subscribed to events on {socket_address}") while True: message = subscriber.recv_string() print(f"Received event: {message}") ``` ### Example (Node.js) ```javascript const zmq = require('zeromq'); const sock = zmq.subscriber(); sock.connect('tcp://localhost:5556'); sock.subscribe(''); console.log('Subscribed to events'); (async () => { for await (const [msg] of sock) { console.log('Received event:', msg.toString()); } })(); ``` ``` -------------------------------- ### Missing Required Parameter 'operation' for 'change_lesson' Command (400) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This error signifies a missing 'operation' field when using the 'change_lesson' command. Ensure the 'operation' field is included with a valid value. ```json { "success": false, "message": "Missing required parameter 'operation'", "error": "Missing required parameter 'operation'", "request_id": 3, "status_code": 400, "version": 0 } ``` -------------------------------- ### Python WebSocket 客户端示例 Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md 使用 Python 和 WebSocket 库连接到 IslandMQ 的 WebSocket 端点以接收实时事件。确保已安装 websocket-client 库。 ```python import websocket ws = websocket.WebSocket() ws.connect("ws://127.0.0.1:8080/ws") print("Waiting for events...") while True: event = ws.recv() print(f"Event: {event}") # 接收 'OnClass', 'OnBreakingTime' 等 ``` -------------------------------- ### Subject Does Not Exist for change_lesson command Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This error indicates that the 'subject_id' provided for the 'change_lesson' command does not correspond to an existing subject in the system. Verify the subject ID. ```APIDOC ## Subject Does Not Exist for change_lesson command (400) ### Description This error occurs when the specified 'subject_id' does not exist in the system for the 'change_lesson' command. ### Method POST (Assumed) ### Endpoint / ### Response #### Error Response (400) ```json { "success": false, "message": "Invalid request parameters", "error": "Invalid request parameters", "request_id": 3, "status_code": 400, "version": 0 } ``` ### Solution - Use the `get_lesson` command to view available subjects. - Use the GUIDs returned in the data. ``` -------------------------------- ### Python NetMQ REQ 客户端示例 Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/README.md 使用 Python 和 NetMQ 发送 REQ 请求并接收响应。确保已安装 PyZMQ 库。 ```python import zmq import json context = zmq.Context() socket = context.socket(zmq.REQ) socket.connect("tcp://127.0.0.1:5555") # 发送请求 socket.send_json({"command": "ping"}) # 接收响应 response = socket.recv_json() print(response) # {'success': True, 'message': 'OK', ...} socket.close() context.term() ``` -------------------------------- ### Change Lesson Command: Batch Operation Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Use the 'change_lesson' command with the 'batch' operation for multiple lesson replacements. Provide a JSON object mapping class indices to new subject IDs. ```json { "version": 0, "command": "change_lesson", "operation": "batch", "changes": { "0": "550e8400-e29b-41d4-a716-446655440000", "2": "6ba7b810-9dad-11d1-80b4-00c04fd430c8" }, "date": "2026-02-28" } ``` -------------------------------- ### Allow Remote Connections Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/configuration.md Set IP addresses to '0.0.0.0' to allow connections from any network interface, enabling remote access. ```json { "netMqServerIp": "0.0.0.0", "httpServerIp": "0.0.0.0" } ``` -------------------------------- ### Change Lesson Command: Replace Operation Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Use the 'change_lesson' command with the 'replace' operation to substitute a single lesson. Requires the class index and the new subject ID. ```json { "version": 0, "command": "change_lesson", "operation": "replace", "class_index": 2, "subject_id": "550e8400-e29b-41d4-a716-446655440000", "date": "2026-02-28" } ``` -------------------------------- ### Missing Required Parameter 'title' for 'notice' Command (400) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This error occurs when the 'notice' command is missing the required 'title' argument. Ensure the 'args' array includes the notification title. ```json { "success": false, "message": "Missing required parameter 'title'", "error": "Missing required parameter 'title'", "request_id": 2, "status_code": 400, "version": 0 } ``` -------------------------------- ### Missing or Invalid 'command' Parameter Error Response (400) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This JSON response indicates a missing or invalid 'command' parameter in the request. Ensure the 'command' field is present and is a string. ```json { "success": false, "message": "Missing or invalid 'command' parameter", "error": "Missing or invalid 'command' parameter", "request_id": 1, "status_code": 400, "version": 0 } ``` -------------------------------- ### change_lesson Command Source: https://github.com/doudou0720/islandmq/blob/publish/sample/README.md Performs class schedule modifications including replace, swap, batch replace, and clear operations. Requires specifying an operation type and relevant parameters. ```APIDOC ## change_lesson Command ### Description Performs class schedule modifications including replace, swap, batch replace, and clear operations. Requires specifying an operation type and relevant parameters. ### Command change_lesson ### Operations - `replace`: Replace a single class. - `swap`: Swap two classes. - `batch`: Batch replace multiple classes. - `clear`: Clear all class changes for the day. ### Request Body Examples #### 1. Replace Operation ```json { "version": 0, "command": "change_lesson", "operation": "replace", "class_index": 2, "subject_id": "550e8400-e29b-41d4-a716-446655440000", "date": "2026-02-28" } ``` #### 2. Swap Operation ```json { "version": 0, "command": "change_lesson", "operation": "swap", "class_index1": 1, "class_index2": 3, "date": "2026-02-28" } ``` #### 3. Batch Operation ```json { "version": 0, "command": "change_lesson", "operation": "batch", "changes": { "0": "550e8400-e29b-41d4-a716-446655440000", "2": "6ba7b810-9dad-11d1-80b4-00c04fd430c8" }, "date": "2026-02-28" } ``` #### 4. Clear Operation ```json { "version": 0, "command": "change_lesson", "operation": "clear", "date": "2026-02-28" } ``` ### Parameters #### Replace Operation Parameters - `class_index` (Required): Index of the class to replace (0-based), corresponding to TimeType==0. - `subject_id` (Required): GUID of the new subject. - `date` (Optional): Date in YYYY-MM-DD format. Defaults to today. #### Swap Operation Parameters - `class_index1` (Required): Index of the first class to swap (0-based). - `class_index2` (Required): Index of the second class to swap (0-based). - `date` (Optional): Date in YYYY-MM-DD format. Defaults to today. #### Batch Operation Parameters - `changes` (Required): JSON object where keys are class indices and values are new subject GUIDs. - `date` (Optional): Date in YYYY-MM-DD format. Defaults to today. #### Clear Operation Parameters - `date` (Optional): Date in YYYY-MM-DD format. Defaults to today. ### Notes - Ensure subject GUIDs are valid. - Class indices must be within the valid range. - Date format must be YYYY-MM-DD. - Batch changes must follow the correct JSON format. - Change operations create temporary schedules. - `IsChangedClass` will be set to `true` for modified classes. - Class indices refer to TimeType==0 points (classes), not breaks or other types. - For cross-day changes, use two separate operations with specified dates. ``` -------------------------------- ### Class Index Out of Range Error Response (400) Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md This response indicates that the provided 'class_index' is outside the valid range of courses for the current schedule. Verify the 'class_index' against the number of courses obtained from 'get_lesson'. ```json { "success": false, "message": "Invalid request parameters", "error": "Invalid request parameters", "request_id": 3, "status_code": 400, "version": 0 } ``` -------------------------------- ### Invalid class_index Format for change_lesson command Source: https://github.com/doudou0720/islandmq/blob/publish/_autodocs/errors.md The 'class_index' field for the 'change_lesson' command must be a non-negative integer. This error indicates an incorrect format was provided. ```APIDOC ## Invalid class_index Format for change_lesson command (400) ### Description This error occurs when the 'class_index' is not an integer for the 'change_lesson' command. ### Method POST (Assumed) ### Endpoint / ### Parameters #### Request Body - **class_index** (integer) - Required - A non-negative integer representing the class index. ### Request Example ```json { "class_index": 0 } ``` ### Response #### Error Response (400) ```json { "success": false, "message": "Invalid class_index format", "error": "Invalid class_index format", "request_id": 3, "status_code": 400, "version": 0 } ``` ```