Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
openspace-socket-api-example
const net = require('net');
const connection = {
connect: (onConnected) => {
this._client = net.createConnection({ port: 8000 }, () => {
console.log('Connected to OpenSpace backend');
onConnected();
});
this._client.on('data', (data) => {
const messageObject = JSON.parse(data.toString());
if (messageObject.topic !== undefined) {
this._callbacks[messageObject.topic](messageObject.payload);
}
});
this._client.on('end', () => {
console.log('Disconnected from OpenSpace');
});
this._callbacks = {};
this._nextTopicId = 0;
},
disconnect: () => {
this._client.end();
},
startTopic: (type, payload, callback) => {
const topic = this._nextTopicId++;
const messageObject = {
topic: topic,
type: type,
payload: payload
};
this._callbacks[topic] = callback || function() {};
this._client.write(JSON.stringify(messageObject) + "\n");
return topic;
},
talk: (topic, payload) => {
const messageObject = {
topic: topic,
payload: payload
};
this._client.write(JSON.stringify(messageObject) + "\n");
}
}
connection.connect(() => {
// First, make Earth bigger
connection.startTopic('set', {property: 'Scene.Earth.Scale.Scale', value: "2"});
console.log("Set value of Earth Scale to 2");
// Get Earth scale
setTimeout(() => {
connection.startTopic('get', {property: 'Scene.Earth.Scale.Scale'}, (response) => {
console.log("Got value of Earth Scale ", response.Value)
});
}, 100)
let subscriptionTopic = -1;
// Subscribe to Earth scale
setTimeout(() => {
subscriptionTopic = connection.startTopic(
'subscribe',
{event: 'start_subscription', property: 'Scene.Earth.Scale.Scale'},
(response) => {
console.log("Got new value of Earth Scale through subscription: ", response.Value)
}
);
console.log("Subscription topic is " + subscriptionTopic);
}, 200);
// Reset Earth scale
setTimeout(() => {
connection.startTopic('set', {property: 'Scene.Earth.Scale.Scale', value: "1"});
console.log("Reset value of Earth Scale");
}, 300);
// Unscubscribe
setTimeout(() => {
connection.talk(subscriptionTopic, {property: 'Scene.Earth.Scale.Scale', event: 'stop_subscription'});
console.log("Unsubscribed to Earth Scale");
}, 400);
// Execute script to speed up time
setTimeout(() => {
connection.startTopic('luascript', {script: 'openspace.time.interpolateDeltaTime(10000, 1);'});
}, 500);
// Execute script to slow down time
setTimeout(() => {
connection.startTopic('luascript', {script: 'openspace.time.interpolateDeltaTime(1, 1);'});
}, 2500);
setTimeout(() => {
connection.disconnect();
}, 2600);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.