Light Control Examples
Table of Contents
Overview
These examples demonstrate how to control lights in the RCAMS system, including sending commands to individual lights, groups, schools, and districts. Light control is the primary function of the RCAMS system, allowing you to trigger visual emergency notifications throughout your facilities.
Note: Light commands trigger actual visual alerts in your facilities. Exercise caution when testing these commands to avoid causing confusion or panic.
Light Command Types
| Command | Color | Protocol |
|---|---|---|
MODE:0 |
Off | Return to normal |
MODE:1 |
Red | Lockdown |
MODE:2 |
Blue | Secure |
MODE:3 |
White | Team Assist |
MODE:4 |
Green | Evacuate |
MODE:5 |
Orange | Shelter |
MODE:6 |
Purple | Hold |
Light Command System
This example demonstrates a comprehensive light control system, including sending commands to lights and retrieving command history.
// RCAMS Light Control System Example
// Helper function for making API requests
async function makeApiRequest(endpoint, params, apiCredentials) {
const { username, password } = apiCredentials;
// Create json data from params
const json = {};
for (const [key, value] of Object.entries(params)) {
json[key] = value;
}
const jsonString = JSON.stringify(json);
try {
const response = await fetch(`https://rcamsapi.spheronomics.com/api/v2/${endpoint}`, {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(`${username}:${password}`)
},
body: jsonString
});
return await response.json();
} catch (error) {
console.error(`API request to ${endpoint} failed:`, error);
throw error;
}
}
// Light Command Constants
const LIGHT_COMMANDS = {
OFF: 'MODE:0', // Turn off the light
LOCKDOWN: 'MODE:1', // RED - Lockdown
SECURE: 'MODE:2', // BLUE - Secure
TEAM_ASSIST: 'MODE:3', // WHITE - Team Assist
EVACUATE: 'MODE:4', // GREEN - Evacuate
SHELTER: 'MODE:5', // ORANGE - Shelter
HOLD: 'MODE:6' // PURPLE - Hold
};
// Light Control System Example
async function lightControlExample() {
// User credentials - replace with actual values
const userCredentials = {
email: 'user@example.com',
password: 'user_password'
};
try {
// Step 1: Get user data to find available schools, groups, and lights
console.log('Getting user data...');
const userData = await makeApiRequest('userdata.php', {}, apiCredentials);
if (userData.status !== 'OK') {
throw new Error(`Failed to get user data: ${userData.message}`);
}
// Step 2: Get a list of lights for a specific school and group
// For this example, we'll use the first school and group from user data
if (!userData.districts || userData.districts.length === 0) {
throw new Error('No districts found for this user.');
}
const firstDistrict = userData.districts[0];
if (!firstDistrict.schools || firstDistrict.schools.length === 0) {
throw new Error('No schools found in the first district.');
}
const firstSchool = firstDistrict.schools[0];
if (!firstSchool.groups || firstSchool.groups.length === 0) {
throw new Error('No groups found in the first school.');
}
const firstGroup = firstSchool.groups[0];
console.log(`Using school ID ${firstSchool.school_id} and group ID ${firstGroup.group_id}...`);
const lightsResponse = await makeApiRequest('lightlist.php', {
school_id: firstSchool.school_id,
group_id: firstGroup.group_id
}, userCredentials);
if (lightsResponse.status !== 'OK') {
throw new Error(`Failed to get lights: ${lightsResponse.message}`);
}
if (!lightsResponse.lights || lightsResponse.lights.length === 0) {
throw new Error('No lights found in the specified school and group.');
}
console.log(`Found ${lightsResponse.lights.length} lights.`);
const firstLight = lightsResponse.lights[0];
console.log(`Using light: ${firstLight.light_name} (MAC: ${firstLight.light_mac})`);
// Step 4: Send a command to an individual light (e.g., Blue/Secure)
console.log('Sending SECURE command to individual light...');
const individualCommandResponse = await makeApiRequest('lightcommands.php', {
light_mac: firstLight.light_mac,
message: LIGHT_COMMANDS.SECURE
}, userCredentials);
if (individualCommandResponse.status !== 'OK') {
throw new Error(`Failed to send command to individual light: ${individualCommandResponse.message}`);
}
console.log('Command sent successfully to individual light.');
// Wait 2 seconds before next command
await new Promise(resolve => setTimeout(resolve, 2000));
// Step 5: Send a command to a group of lights (e.g., Green/Evacuate)
console.log('Sending EVACUATE command to group...');
const groupCommandResponse = await makeApiRequest('lightcommandsgroup.php', {
group_id: firstGroup.group_id,
message: LIGHT_COMMANDS.EVACUATE
}, userCredentials);
if (groupCommandResponse.status !== 'OK') {
throw new Error(`Failed to send command to group: ${groupCommandResponse.message}`);
}
console.log('Command sent successfully to group.');
console.log('Group command results:', groupCommandResponse.results);
// Wait 2 seconds before next command
await new Promise(resolve => setTimeout(resolve, 2000));
// Step 6: Send a command to an entire school (e.g., Off/Normal)
console.log('Sending OFF command to entire school...');
const schoolCommandResponse = await makeApiRequest('lightcommandsclient.php', {
school_id: firstSchool.school_id,
message: LIGHT_COMMANDS.OFF
}, userCredentials);
if (schoolCommandResponse.status !== 'OK') {
throw new Error(`Failed to send command to school: ${schoolCommandResponse.message}`);
}
console.log('Command sent successfully to entire school.');
console.log('School command results summary:',
`${schoolCommandResponse.results.filter(r => r.status === 'OK').length} successful, ` +
`${schoolCommandResponse.results.filter(r => r.status !== 'OK').length} failed`
);
// Step 7: Get light command history
console.log('Getting light command history...');
const historyResponse = await makeApiRequest('lighthistory.php', {
school_id: firstSchool.school_id,
group_id: firstGroup.group_id
}, userCredentials);
if (historyResponse.status !== 'OK' && historyResponse.satus !== 'OK') { // Handle both spelling variations
throw new Error(`Failed to get light history: ${historyResponse.message}`);
}
console.log('Light command history retrieved successfully.');
// Process and display history summary
let totalCommands = 0;
let successfulCommands = 0;
for (const schoolName in historyResponse.data) {
for (const groupName in historyResponse.data[schoolName]) {
for (const lightName in historyResponse.data[schoolName][groupName]) {
const light = historyResponse.data[schoolName][groupName][lightName];
console.log(`Light: ${lightName} (${light.mac})`);
if (light.history && light.history.length > 0) {
console.log(' Recent commands:');
const recentCommands = light.history.slice(0, Math.min(3, light.history.length));
recentCommands.forEach(cmd => {
totalCommands++;
const success = cmd.result === 'message published';
if (success) successfulCommands++;
console.log(` ${cmd.Timestamp}: ${cmd.message} (${success ? 'Success' : 'Failed: ' + cmd.result})`);
});
if (light.history.length > 3) {
console.log(` ... and ${light.history.length - 3} more commands`);
// Count remaining commands
light.history.slice(3).forEach(cmd => {
totalCommands++;
if (cmd.result === 'message published') successfulCommands++;
});
}
} else {
console.log(' No command history available.');
}
}
}
}
console.log(`\nCommand history summary: ${totalCommands} total commands, ${successfulCommands} successful (${Math.round(successfulCommands / totalCommands * 100)}% success rate)`);
// Step 8: Logout
console.log('Logging out...');
await makeApiRequest('logout.php', {}, userCredentials);
console.log('Light control example completed successfully.');
} catch (error) {
console.error('Light control example error:', error);
}
}
// Run the light control example
// lightControlExample();
Warning: When implementing light controls in a production environment, ensure you have proper safeguards to prevent accidental triggering of alerts. Consider implementing confirmation dialogs, user permission checks, and audit logging.