Browse Source

[IMP] socket manager

Gogs 7 years ago
parent
commit
ce921dbadd
6 changed files with 230 additions and 77 deletions
  1. 2 1
      __openerp__.py
  2. 1 4
      controllers/main.py
  3. 0 0
      static/src/css/main.css
  4. 204 69
      static/src/js/main.js
  5. 10 0
      static/src/xml/main.xml
  6. 13 3
      views/print_engine_sockets.xml

+ 2 - 1
__openerp__.py

@@ -9,5 +9,6 @@
         'templates.xml',
         'views/print_engine_sockets.xml',
         'views/print_engine_printers.xml'
-    ]
+    ],
+    'qweb': ['static/src/xml/*.xml'],
 }

+ 1 - 4
controllers/main.py

@@ -45,10 +45,7 @@ class PrintEngineController(http.Controller):
 
         assert len(printer_ids) == 0
 
-        data = json.loads(kw.get('data'))
-        values = [{'name': printer} for printer in data['printers']]
-        
-        # printer_obj.create(values)
+        print(kw)
 
     '''
     '''

+ 0 - 0
static/src/css/main.css


+ 204 - 69
static/src/js/main.js

@@ -1,101 +1,236 @@
 
 (function () {
-    if (!window.openerp) {
-        return;
-    }
-
-    if (!openerp.print_engine) {
-        openerp.print_engine = {};
-    }
+    var instance = openerp
+    openerp.print_engine = {}
     
-    if (!openerp.print_engine.sockets) {
-        openerp.print_engine.sockets = [];
-    }
+    /**
+     * 
+     */
+    instance.print_engine.SocketManager = instance.web.Class.extend({
+        init: function () {
+            this.socket = null;
+            this.state = 'offline';
+            this.attemps = 0;
+
+            this.start();
+        },
+        start: function () {
+            var self = this;
+            this.getSockets().then(function () {
+                self.connect();
+            });
+        },
+        getSockets: function () {
+            var defer = $.Deferred();
+            var self = this;
+
+            $.get('/print_engine/sockets').done(function (data) {
+                self.sockets = data.sockets;
+                defer.resolve(data.sockets);
+            }).fail(function (error){
+                defer.reject(error);
+            });
+
+            return defer;
+        },
+        urlize: function (info) {
+            return info.protocol + '://' + info.host + ':' + info.port + info.path;
+        },
+        connect: function () {
+            if (this.sockets.length === 0) {
+                return
+            }
+
+            var self = this;
+            var url = this.urlize(this.sockets[0]);
+
+            if (this.socket) {
+                this.socket = null;
+            }
+            
+            try {
+                this.socket = new WebSocket(url);
+
+                this.socket.onopen = function (e) {
+                    self.handleOpen(e);
+                };
+                this.socket.onclose = function (e) {
+                    self.handleClose(e);
+                };
+                this.socket.onerror = function (e) {
+                    self.handleError(e);
+                };
+                this.socket.onmessage = function (e) {
+                    self.handleMessage(e);
+                };
+            } catch(e) {
+                // Ignore exception
+            }
+        },
+        reconnect: function () {
+            this.state = 'reconnecting';
+            var self = this;
+
+            if (this.attemps === 3) {
+                this.state = 'offline';
+                return;
+            }
+
+            setTimeout(function () {
+                self.connect();
+
+                self.attemps = self.attemps + 1;
+            }, 3000);
+        },
+        handleOpen: function (e) {
+            this.state = 'online';
+        },
+        handleClose: function (e) {
+            this.reconnect();
+        },
+        handleMessage: function (e) {
+            var obj = JSON.parse(e.data);
+
+            if (obj.printers) {
+                this.sendToServer('/print_engine/update', e.data).then(function (ok) {
+                    console.log(ok);
+                });
+            }
+        },
+        handleError: function (e) {
+            // Ignore error
+        },
+        sendToSocket: function (data) {
+            if (this.state !== 'online') {
+                return;
+            }
+
+            if (!data) {
+                return;
+            }
+
+            this.socket.send(JSON.stringify(data));
+        },
+        sendToServer: function (url, data) {
+            var defer = $.Deferred();
+
+            var json = {
+                jsonrpc: '2.0',
+                method: 'call',
+                data: data
+            }
+
+            $.post(url, json).done(function (response) {
+                defer.resolve(response);
+            }).fail(function (error) {
+                defer.reject(error);
+            });
+
+            return defer;
+        },
+        discoveryPrinters: function () {
+            var commands = {
+                action: 'list'
+            }
 
-    $.get('/print_engine/sockets', function (data) {
-        for (var i = 0; i < data.sockets.length; i++) {
-            connect(data.sockets[i]);
+            this.sendToSocket(commands);
+        },
+        print(printer, data) {
+            if (this.state !== 'online') {
+                return;
+            }
+
+            if (!printer) {
+                return;
+            }
+
+            if (!data) {
+                return;
+            }
+
+            var commands = {
+                action: 'print',
+                printer: printer,
+                data: data
+            }
+
+            this.sendToSocket(commands)
         }
     });
 
     /**
      * 
-     * @param {*} options 
      */
-    var buildUrl = function(options) {
-        return options.protocol + '://' + options.host + ':' + options.port + options.path 
-    }
+    instance.print_engine.PrinterTopWidget = instance.web.Widget.extend({
+        template: 'printEngine.PrinterTopWidget',
+        init: function (parent) {
+            this._super(parent)
+        },
+        start: function () {
+            console.log('started');
+        }
+    })
 
     /**
-     * Connect to websocket
      * 
-     * @param {*} socket 
+     * 
      */
-    var connect = function (socket) {
-        var url = buildUrl(socket);
-        socket = new WebSocket(url);
-
-        /**
-         * 
-         * @param {*} e 
-         */
-        socket.onopen = function (e) {
-            openerp.print_engine.sockets.push({
-                instance: this,
-                status: 'online'
-            });
-        }
-
-        /**
-         * 
-         * @param {*} e 
-         */
-        socket.onclose = function (e) {
-            console.log()
+    instance.print_engine.ping = function () {
+        if (!instance.print_engine.socket_manager) {
+            return;
         }
 
-        /**
-         * 
-         * @param {*} e 
-         */
-        socket.onerror = function (e) {
-            console.log(e);
+        openerp.web.notification.do_warn('Atención', 'pong')
+    }
+    
+    /**
+     * 
+     */
+    instance.print_engine.discovery_printers = function (element, action) {
+        if (!instance.print_engine.socket_manager) {
+            return;
         }
 
-        /**
-         * 
-         * @param {*} e 
-         */
-        socket.onmessage = function (e) {
-            console.log(e);
-        }
+        instance.print_engine.socket_manager.discoveryPrinters();
     }
-
+    
     /**
-     * Send action to printer
      * 
-     * @param {*} data 
      */
-    var sendToSocket = function (data) {
-        data = JSON.stringify(data);
+    instance.print_engine.test_printer = function (element, action) {
+        if (!instance.print_engine.socket_manager) {
+            return;
+        }
 
-        console.log(data);
+        instance.print_engine.socket_manager.test();
     }
 
     /**
-     * Update printers on server
      * 
-     * @param {*} data 
      */
-    var updatePrinters = function (printers) {
-        var data = {
-            jsonrpc: '2.0',
-            method: 'call',
-            data: printers
+    instance.print_engine.print = function (element, action) {
+        if (!instance.print_engine.socket_manager) {
+            return;
         }
 
-        $.post('/print_engine/update', data, function (response) {
-            console.log(response);
+        instance.print_engine.socket_manager.print();
+    }
+
+    instance.print_engine.socket_manager = new instance.print_engine.SocketManager()
+
+    instance.web.client_actions.add('print_engine.ping', 'instance.print_engine.ping')
+    instance.web.client_actions.add('print_engine.discovery_printers', 'instance.print_engine.discovery_printers')
+    instance.web.client_actions.add('print_engine.test_printer', 'instance.print_engine.test_printer')
+
+
+    if(openerp.web && openerp.web.UserMenu) {
+        openerp.web.UserMenu.include({
+            do_update: function(){
+                var printer = new openerp.print_engine.PrinterTopWidget(this);
+                printer.appendTo($('.oe_systray'));
+
+                return this._super.apply(this, arguments);
+            }
         });
     }
-}).call(this)
+})()

+ 10 - 0
static/src/xml/main.xml

@@ -0,0 +1,10 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<templates xml:space="preserve">
+    <t t-name="printEngine.PrinterTopWidget">
+        <li t-att-title='_t("Printer Status")'>
+            <a href="#">
+                <i class="fa fa-print" aria-hidden="true" />
+            </a>
+        </li>
+    </t>
+</templates>

+ 13 - 3
views/print_engine_sockets.xml

@@ -24,8 +24,8 @@
             <field name="arch" type="xml">
                 <form string="Socket">
                     <header>
-                        <button name="socket_probe" string="Probar conexión" />
-                        <button name="socket_discovery" string="Detectar impresoras" />
+                        <button type="action" name="print_engine.ping_action" string="Probar conexión" />
+                        <button type="action" name="print_engine.discovery_printers_action" string="Detectar impresoras" />
                     </header>
                     <sheet>
                         <h1>
@@ -47,7 +47,7 @@
             </field>
         </record>
 
-        <!-- Socket Action -->
+        <!-- Socket Actions -->
         <record id="print_engine.action_sockets" model="ir.actions.act_window">
             <field name="name">Sockets</field>
             <field name="type">ir.actions.act_window</field>
@@ -64,6 +64,16 @@
             </field>
         </record>
 
+        <record id="print_engine.ping_action" model="ir.actions.client">
+            <field name="name">Ping socket action</field>
+            <field name="tag">print_engine.ping</field>
+        </record>
+
+        <record id="print_engine.discovery_printers_action" model="ir.actions.client">
+            <field name="name">Discovery printers action</field>
+            <field name="tag">print_engine.discovery_printers</field>
+        </record>
+
         <menuitem id="print_engine.sockets" name="Impresión" parent="base.menu_config" action="print_engine.action_sockets" sequence="150" />
     </data>
 </openerp>