scratchfoundation / scratchx

Scratch Extension Site
https://github.com/llk/scratchx
190 stars 121 forks source link

I need to click first on my hat block (experimental extension) in the scripts window before it reacts to the event #151

Closed janvda closed 1 year ago

janvda commented 6 years ago

I am using the scratch2 offline version running on raspberry pi (version scratch-flash = ba2f624-dirty). I have created a scratch extension which I loaded using the "import experimental extension" menu.

The purpose of the extension is to make it possible to communicate to a server (node-red) using websockets.

So in the extension I have defined a hat block for receiving events from the server.

The problem is that the hat block is initially not working but when I click on the hat block in the Scripts window it suddenly starts working. So from then onward it is properly triggering the hat block each time the proper websocket event is received.

So something is happening when clicking on the hat block in the scripts window that makes hat block working as expected.

FYI the respective code of my extension:

(function (ext) {
    var socket = null;

    var connected = false;
    var incomingMessages = {};
   var lastEventValue = {}; 

    var myStatus = 1; // initially yellow
    var myMsg = 'not_ready';

    ext.connect = function (host,port,callback) {
        window.socket = new WebSocket("ws://127.0.0.1:1880/node_red_scratch");
        window.socket.onopen = function () {
            var msg = JSON.stringify({
                "command": "ready"
            });
            window.socket.send(msg);
            myStatus = 2;

            // change status light from yellow to green
            myMsg = 'ready';
            connected = true;

            // give the connection time establish
            window.setTimeout(function() {
            callback();
        }, 1000);

        };

        window.socket.onmessage = function (message) {
            var msg = JSON.parse(message.data);

                        //
                        var event=msg['event'];
                        incomingMessages[event]=true;
                      lastEventValue[event]=msg['value'];
            console.log(message.data)
        };

        window.socket.onclose = function (e) {
            console.log("Connection closed.");
            socket = null;
            connected = false;
            myStatus = 1;
            myMsg = 'not_ready'
        };
    };

   ext.when_I_receive = function(event) {
        if(incomingMessages[event]) {
            incomingMessages[event] = false;
            return true;
        } 
        return false;
    }
...
thisandagain commented 6 years ago

@khanning @cwillisf Any thoughts on this?