Connect digital.auto playground to third party system via socket.io
There is many ways to connect to digital.auto from 3rd systems/apps such as HTTP API, SOAP, etc., however those methods are just one-way request. To support you fetch continuous data, 2-ways communication, we build up some socker.io servers below:
https://bridge.digitalauto.tech
https://bridge.digitalauto.asia
(our server run socket.io version 4.x, no auth require)
For more infomation, visit there site: https://socket.io/
const loadScript = (boxWindow, url) => {
return new Promise(async (resolve, reject) => {
try {
const script = boxWindow.document.createElement("script");
script.defer = true;
script.referrerPolicy = "origin"
script.src = url;
boxWindow.document.head.appendChild(script);
script.addEventListener("load", () => resolve(undefined));
} catch (e) {
reject();
}
});
}
const PROVIDER_ID = "PYTHON-CLIENT-SAMPLE"
const plugin = ({widgets, simulator, vehicle}) => {
widgets.register("Client", async (box) => {
})
return {}
}
await loadScript(box.window, `https://cdn.socket.io/4.6.0/socket.io.min.js`)
const socket = box.window.io("https://bridge.digitalauto.tech");
const onConnected = () => {
console.log("Io connected")
socket.emit("register_client", {
master_provider_id: PROVIDER_ID
})
}
socket.on("connect", onConnected);
From now on, when provider sends some data, you can get it. Now we define function to handle message from provider.
const messageFromProvider = (payload) => {
if(payload.cmd == 'showSpeed') {
lblSpeed.innerText = payload.data
}
}
socket.on('message_from_provider', messageFromProvider)
On provider side, when provider calls socket.emit(“send_to_all_clients”, payload) then the function messageFromProvider
will be called with the payload
data
socket.emit("request_provider", {
to_provider_id: PROVIDER_ID,
cmd: "Start", // cmd send to provider
data: 1 // data for the cmd, data may be number, string, object or null depend on cmd
})
// now server will handle that cmd and reply to you (only reply to the requester, not other clients)
// we add a function to handle data reply from provider
const messageFromProvider = (payload) => {
if(payload.cmd == 'showSpeed') {
lblSpeed.innerText = payload.data
}
}
socket.on('provider_reply', onProviderReply)
You have the free to define cmd set and data. On your provider code, handle commands and reply to client.
Full sample plugin code available here: https://media.digitalauto.tech/data/files/668377ef-41a9-4b36-af80-2ef4e4fc6666TestIO.js
We have sample prototype at this link: https://digitalauto.netlify.app/model/1jNrd7yS32ZzFo3WXrJy/library/prototype/3qgZS366ARQaCkPEBtuk/view/run
Dashboard config:
[
{
"boxes": [1,2],
"plugin": "SocketIO",
"widget": "Client"
}
]