Help to send AJAX with NippleJS

2

I'm using nippleJS: link

I'm not 100% sure if it's possible to send the joystick information but I'd say yes. I want to send an AJAX form with the position of the joystick and I want it to be in real time to control some engines. I can not send the information. I'm using this:

<script type="text/javascript">
$(document).ready(function() {

    $('#static').onclick(function(evento){
        /* Cancelamos el envío del formulario */
        evento.stopPropagation();
        evento.preventDefault();

        var dataString = $('#static').serialize()

        $.ajax({
            type: "POST",
            url: "/cgi-bin/motorcontrol.py",
            data: dataString,
            dataType: "json",
            success: function(data) {

            }
        });
    });
});
</script>


<div id="static"></div>
<script src="./dist/nipplejs.min.js"></script>   
<script>
   var static = nipplejs.create({
       zone: document.getElementById('static'),
       mode: 'static',
       position: {left: '75%', top: '50%'},
       color: 'black'
   });
</script>

I'm using .onclick to only work when I'm pressing the joystick. The script to which it is addressed is this:

#! /usr/bin/python

import cgi, cgitb
import socket
cgitb.enable()

form = cgi.FieldStorage()
searchterm = form.getvalue('static')

socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sent = socket.sendto(str(searchterm) + "3", ('127.0.0.1', 31113))

And this:

#! /usr/bin/python

import serial, socket

ser = serial.Serial('/dev/ttyACM0',9600)

socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

socket.bind(('127.0.0.1', 31113))
print "Esperando conexion"

while True:
  # Recibimos hasta 200 caracteres en un paquete UDP
  datos, remoto = socket.recvfrom(200)
  print("Datos recibidos de " + str(remoto) + " - " + str(datos))
  ser.write(str(datos))
  # Devolvemos los datos recibidos a modo de "ACK" (opcional)
  sent = socket.sendto(datos, remoto)

I use them to see the data that arrives but nothing comes of anything.

    
asked by Orizzon 06.10.2017 в 22:43
source

1 answer

1

In the official documentation is documented the interface of events that it offers, being the event move to which it seems that you need to subscribe your code to send updates of the movement and the event end to send a return to the neutral point:

<script>
    /*  false: no se está enviando nada al servidor
        true: se están enviando datos al servidor
        datos: hay datos pendientes de ser enviados al servidor
    */
    var pendiente = false;
    var joystick = nipplejs.create({
        zone: document.getElementById('static'),
        mode: 'static',
        position: {
            left: '75%',
            top: '50%',
        },
        color: 'black',
    });
    function controlador(evento, datos) {
        /* Comprobamos si podemos hacer el envío o encolarlo */
        if (pendiente === false) {
            /* Marcamos que tenemos un envío pendiente de ser completado */
            pendiente = true;
            $.ajax({
                type: "post",
                url: "URL_A_TU_SCRIPT",
                data: {
                    grados: datos.angle.degree,
                    distancia: datos.distance,
                },
                dataType: "json", /* OJO: Esto es lo que se espera recibir en lo siguiente */
                success: function (datos) {
                    console.log(datos);
                },
                complete: function () {
                    console.log("Fin trabajo");
                    /* Si hay un dato en cola de envío lo enviamos */
                    if (pendiente === true) {
                        /* Marcamos el trabajo como finalizado */
                        pendiente = false;
                    } else {
                        var datos = pendiente;
                        pendiente = false;
                        controlador(evento, datos);
                    }
                },
            });
        } else {
            console.log("Trabajo encolado");
            /* Ponemos en cola de envío el dato actual */
            pendiente = datos;
        }
    }
    /* Configuramos el controlador del evento "move" del joystick */
    joystick.on('move', controlador);
    /* Cuando finalizamos el uso del joystick inyectamos una posición neutra */
    joystick.on('end', function (evento, datos) {
        /* Simulamos un evento en posición neutra */
        controlador(evento, {
            angle: { degree: 0.0 },
            distance: 0,
        });
    });
</script>

I have implemented a dispatch queue manager to avoid saturating the server with XHR requests if there are very fast events that can not be addressed by the web server. Until the response to the previous request is not received, the next one is not sent, and if there was a pending request to be sent it is replaced by the last one received.

Your python script must be modified to correctly receive XHR values:

#! /usr/bin/python

import cgi, cgitb
import socket
cgitb.enable()

form = cgi.FieldStorage()
grados = form.getvalue('grados')
distancia = form.getvalue('distancia')

socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Esto debes modificarlo para enviar lo necesario al arduino/servidor UDP
#sent = socket.sendto(str(searchterm) + "3", ('127.0.0.1', 31113))
sent = socket.sendto("G:" + grados + ";D:" + distancia, ('127.0.0.1', 31113))
    
answered by 23.10.2017 / 09:56
source