Web Socket Help

I'm sorry, but really, you should learn more about basics of javascript. Before jumping into a thing like this. Start here, make yourself a favor, study and learn
https://www.w3schools.com/js/default.asp

You have received much help about lot of things already. I can only add:

  • You need to debug more
  • You need to keep the syntax correct (you are missing the ; sign at the end of several lines)
  • You have to declare your variables (very important)
  • You should insert the console.log() statement in more places to verify that the incoming & received data is as expected

Look at the line you have
message1 = (message.payload)
Do you think this will work? Well, maybe. Is it fulfilling the requirement for the javascript syntax? No

1 Like

Krambriw,
I've spent hours on that website......people learn in different ways, I've always learnt more by doing, having something i need to achieve, than following a load of meaningless examples........but that's just me.

Appreciate the feedback, I'd picked up the none assignment of variable and already changes that line.

Cheers
Ant

Websockets are a very odd protocol, certainly not the easiest place to start. But that's why Node-RED has at least 3 options when it comes to them.

They drive me mad sometimes even with the help of the Socket.IO library.

Well, myself I found many valuable examples on that site while learning. You did not think that you are consuming a lot of other users time when you just throw in code that you easily could have checked and fixed yourself? Using some great available tools like this one: The W3C Markup Validation Service

Anyway, I will finally provide you with a simple sample. It is partly from a log tool I created for use in NR. You can send messages to it via websocket and it will update various elements in the html. You can experiment with it and check how I'm updating the content. I have in addition added two buttons. By clicking on them you will see how they get updated using messages incoming via the websocket connection. Hope this helps

Is your project for fun? If it's commercial, you should consider hire a consultant

[{"id":"104a92c8.9851cd","type":"http in","z":"993670cc.78716","name":"","url":"/log","method":"get","swaggerDoc":"","x":160,"y":110,"wires":[["5553015b.7415b"]]},{"id":"5553015b.7415b","type":"template","z":"993670cc.78716","name":"log","field":"payload","fieldType":"msg","format":"html","syntax":"plain","template":"<!DOCTYPE html>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/> \n<title>Simple websocket test page</title>\n\n<style>\n    .on { \n        border:4px inset;\n        color:#369;\n        background:#f9d543; \n    }\n        \n    .off {\n        border:4px outset;\n        color:#369;\n        background:#f9d543; \n    }\n</style>\n\n<script>\nvar cntr = 0;\nvar old_cntr = 0;\nvar old_hours = '';\nvar old_minutes = '';\nvar old_seconds = '';\nvar oldLine = '';\nvar global_n = '';\nvar myVar = 0;\nvar worker = new Worker('worker.js');\npingOK = true;\ninitial = window.setInterval(refresh, 1500);\nkeepAlive = window.setInterval(kAlive, 15000);\nwSocket = null;\ninProgress = false;\nprot = \"\";\nip = \"\";\nurl = \"\";\nchk = 0;\n\n\n\tfunction doWork(prm) {\n\t\tworker.postMessage(prm);\n\t}\n\n\tfunction checkEven(val) {\n\t\treturn (val%2 === 0);\n\t}\n\n\tworker.onmessage = function (evt) {\n\t\tmyVar = evt.data[1];\n      if (evt.data[0] === 999) {\n\t\t\tdocument.getElementById(\"output\").style.color =\"red\";\n\t\t\twSocket.close();\n\t\t}\n\t\telse {\n\t\t\tif (checkEven(evt.data[0])) {\n\t\t\t\tdocument.getElementById(\"output\").style.color =\"black\";\n\t\t\t}\n\t\t\telse {\n\t\t\t\tdocument.getElementById(\"output\").style.color =\"blue\";\n\t\t\t}\n\t\t}\n\t};\n\n\tfunction init() {\n\t\t// event handlers for WebSocket:\n\t\tinProgress = true;\n        wSocket = null;\n        prot = \"\";\n        ip = location.host;\n\n        if (location.protocol == \"https:\") {\n            prot = \"wss://\";\n        }\n        else {\n            prot = \"ws://\";\n        }\n\t\turl = prot + ip + \"/ws/location\";\n\t\twSocket = new WebSocket(url);\n\t\twriteToScreen('init.begin:readyState :'+url);\n\t\twriteToScreen('init.begin:readyState :'+wSocket.readyState);\n\t\twriteToScreen('init.begin:inProgress :'+inProgress);\n\t\twSocket.onopen = function() {\n\t\t\tdocument.getElementById(\"output\").style.backgroundColor =\"black\"; //Black\n\t\t\twriteToScreen('onOpen:readyState :'+wSocket.readyState);\n\t\t\tdoPing();\n\t\t};\n\t\twSocket.onmessage = wsMessage;\n\t\twSocket.onclose = function() {\n\t\t\tdocument.getElementById(\"output\").style.backgroundColor =\"#C0C0C0\"; //Grey\n\t\t\twriteToScreen('onClose:readyState :'+wSocket.readyState);\n\t\t};\n\t\tinProgress = false;\n\t\twriteToScreen('init.finished:inProgress :'+inProgress);\n\t}\n \t\t\t\t\t\n    function kAlive() {\n        if (wSocket.readyState == 1 && !inProgress) {\n            //writeToScreen('kAlive:inProgress :'+pingOK);\n            if (!pingOK) {\n                writeToScreen('pong timeout: '+pingOK);\n                wSocket.close();\n            }\n            else {\n                doPing();\n            }\n        }\n    }\n\n    function doPing() {\n        pingOK = false;\n        doSend({'method':'Ping','id':keepAlive});\n    }\n\n\tfunction refresh() {\n\t\tif (wSocket.readyState == 3){\n\t\t\tif (!inProgress) {\n                pingOK = true;\n                //writeToScreen('refresh:inProgress :'+inProgress+wSocket.readyState);\n                chk += 1;\n                writeToScreen('counter :'+chk);\n                if ( chk > 0) {\n                    chk = 0;\n                    init();\n                }\n\t\t\t\t\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction writeToScreen(message) { \n        var pre = document.createElement(\"p\"); \n        pre.style.wordWrap = \"break-word\"; \n        pre.innerHTML = message; \n        output.appendChild(pre); \n\t} \n\n\tfunction doSend(strng) {\n\t\tif (wSocket.readyState == 1) {\n\t\t\twSocket.send(JSON.stringify(strng));\n\t\t}\n\t}\n    \n    function TriggerWebSocketEvent(eventname, el){\n        if(el.className == \"on\") {\n            el.className=\"off\";\n            doSend(eventname+' turnoff');\n            } \n        else {\n            el.className=\"on\";\n            doSend(eventname+' turnon');\n            } \n        return false;\n    }\n\n    function wsMessage(evt) { \n        inProgress = true;\n\n        if (event.data.match('lights facade entrance turnon')) {\n            document.getElementById(\"p21\").style.backgroundColor=\"#FBF14D\";\n            document.getElementById(\"p21\").style.color =\"black\";\n            document.getElementById(\"p21\").className = \"on\";\n            document.getElementById(\"p21\").style.fontSize =\"25\";\n        }\n        if (event.data.match('lights facade entrance turnoff')) {\n            document.getElementById(\"p21\").style.backgroundColor=\"black\";\n            document.getElementById(\"p21\").style.color =\"white\";\n            document.getElementById(\"p21\").className = \"off\";\n            document.getElementById(\"p21\").style.fontSize =\"25\";\n        }\n\n        if (event.data.match('lights facade balcony turnon')) {\n            //alert(event.data);\n            document.getElementById(\"p19\").style.backgroundColor=\"#FBF14D\";\n            document.getElementById(\"p19\").style.color =\"black\";\n            document.getElementById(\"p19\").className = \"on\";\n            document.getElementById(\"p19\").style.fontSize =\"25\";\n        }\n        if (event.data.match('lights facade balcony turnoff')) {\n            //alert(event.data);\n            document.getElementById(\"p19\").style.backgroundColor=\"black\";\n            document.getElementById(\"p19\").style.color =\"white\";\n            document.getElementById(\"p19\").className = \"off\";\n            document.getElementById(\"p19\").style.fontSize =\"25\";\n        }\n\n        if (event.data.search(\"Pong\")!=-1) {\n            pingOK = true;\n        }\n        pingOK = true;\n        var d = new Date();\n        var hours = d.getHours();\n        var minutes = d.getMinutes();\n        var seconds = d.getSeconds();\n        var year = d.getFullYear();\n        var month = d.getMonth();\n        if (month < 10) {\n            month = '0'+ month;\n        }\n        var day = d.getDate();\n        if (day < 10) {\n            day = '0'+ day;\n        }\n        global_n = year+'-'+month+'-'+day;\n        document.getElementById(\"theBody\").style.backgroundColor =\"green\"; //Green\n        if (seconds < 10) {\n            seconds = \"0\" + seconds;\n        }\n        if (minutes < 10) {\n            minutes = \"0\" + minutes;\n        }\n\t\tif (oldLine !== '') {\n\t\t\tif ( cntr > 0 ) {\n\t\t\t\told_cntr = cntr - 1;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif ( cntr === 0 ) {\n\t\t\t\t\told_cntr = 10;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttxtID = old_cntr.toString();\n\t\t\tdocument.getElementById(txtID).style.color =\"white\";\n\t\t\tdocument.getElementById(txtID).innerHTML = oldLine;\n\t\t}\n\t\ttxtID = cntr.toString();\n\t\tdocument.getElementById(txtID).style.color =\"yellow\";\n\t\tdocument.getElementById(txtID).innerHTML = 'RESPONSE: '+global_n+' '+hours+':'+minutes+':'+seconds+' '+evt.data;\n\t\told_hours = hours;\n\t\told_minutes = minutes;\n\t\told_seconds = seconds;\n\t\tif (old_hours !== '') {\n\t\t\toldLine =  'RESPONSE: '+global_n+' '+old_hours+':'+old_minutes+':'+old_seconds+' '+evt.data;\n\t\t}\n\t\tcntr += 1;\n\t\tif ( cntr > 10) {\n\t\t\t  cntr = 0;\n\t\t}\n\t\tdoWork(myVar);\n        inProgress = false;\n    }\n</script> \n<body id=\"theBody\" onLoad=\"init()\" bgcolor=black text=white link=white vlink=white alink=white/>\n<div id=\"output\"></div> \n<br />\n<text id=\"0\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"1\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"2\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"3\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"4\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"5\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"6\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"7\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"8\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"9\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<text id=\"10\"><font face=\"arial\" color=\"white\" font size=\"1\">&nbsp;Log entry</font></text><br />\n<br />\n<center>\n    <table border=\"2\" width=\"100%\" height=\"10%\">\n  <tr><!-- Row 1 -->\n        <td><div style=\"text-align:center\"><button id=\"p21\" class=\"off\" onMouseDown=\"TriggerWebSocketEvent('lights facade entrance', this)\" style=\"background-color:black; height:60px; width:280px\">&nbsp;Main Entrance&nbsp;</button></div></td>\n        <td><div style=\"text-align:center\"><button id=\"p19\" class=\"off\" onMouseDown=\"TriggerWebSocketEvent('lights facade balcony', this)\" style=\"background-color:black; height:60px; width:280px\">&nbsp;Balcony&nbsp;</button></div></td>\n  </tr>\n</table>\n</center>\n</body>\n","x":370,"y":110,"wires":[["5fc19b31.437be4"]]},{"id":"5fc19b31.437be4","type":"http response","z":"993670cc.78716","name":"","x":530,"y":110,"wires":[]},{"id":"98bfa1fa.2ce5b","type":"comment","z":"993670cc.78716","name":"Websocket Log Viewer","info":"","x":200,"y":70,"wires":[]},{"id":"cabb8bc1.09e9c8","type":"websocket out","z":"993670cc.78716","name":"","server":"fd2d0ed6.0b368","client":"","x":730,"y":190,"wires":[]},{"id":"b3408b4c.0e35d8","type":"inject","z":"993670cc.78716","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"10","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"hello","payloadType":"str","x":380,"y":250,"wires":[["cabb8bc1.09e9c8"]]},{"id":"f73e78f4.0c1388","type":"websocket in","z":"993670cc.78716","name":"","server":"fd2d0ed6.0b368","client":"","x":180,"y":190,"wires":[["3555b8c1.fa2a48"]]},{"id":"3555b8c1.fa2a48","type":"function","z":"993670cc.78716","name":"","func":"\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":370,"y":190,"wires":[["cabb8bc1.09e9c8"]]},{"id":"f6e13fc.7c739c","type":"inject","z":"993670cc.78716","name":"Whatever you want to send","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"Whatever you want to send","payloadType":"str","x":440,"y":310,"wires":[["cabb8bc1.09e9c8"]]},{"id":"fd2d0ed6.0b368","type":"websocket-listener","path":"/ws/location","wholemsg":"false"}]

Thanks for the help.

The project is just for fun.......trying something different. It's probably a bit of learning for work; but as you said I would hire a pro to do that. Went through some of the W3School and sorted the syntax / errors. Its weird the string that is output from node red; I use the message.topic the debugging tool says undefined. Its as though the code doesn't recognise it is a JSON message?? This is really where I'm stuck now.

I'll have a look at the code you sent.

Cheers,
Ant

Thanks I have success.

The problem was I needed to use JSON.parse to format the message through the websocket; then boom all started to work.

Thanks for the help.
Ant

2 Likes

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.