Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[15.0][IMP] web_widget_remote_measure: add tcp direct connection #2808

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions web_widget_remote_measure/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from . import controllers
from . import models
1 change: 1 addition & 0 deletions web_widget_remote_measure/controllers/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import main
44 changes: 44 additions & 0 deletions web_widget_remote_measure/controllers/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# Copyright 2023 Tecnativa - David Vidal
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import socket

from odoo.http import Controller, request, route


class RemoteDeviceTcpConnection(Controller):
"""Connect directly to a remote device"""

def _get_weight(self, data, host, port, time_out=1):
"""Direct tcp connection to the remote device"""
response = None
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as device:
device.settimeout(time_out)
device.connect((host, port))
try:
if data:
if isinstance(data, str):
data = data.encode("utf-8")
device.sendall(data)
# Get in one shot. The info won't be longer than a few bytes
response = device.recv(64)
except Exception as e:
raise (e)
finally:
device.close()
return response

@route(
"/remote_measure_device/<int:device>", type="json", auth="user", sitemap=False
)
def request_weight(self, device=None, command=None, **kw):
"""Meant be called from the remote scale widget js code"""
device = request.env["remote.measure.device"].browse(device)
command = command or b""
kw.get("timeout", 1)
response = b""
host, port = device.host.split(":")
try:
response = self._get_weight(command, host, int(port))
except socket.timeout:
response = b"timeout"
return response
8 changes: 8 additions & 0 deletions web_widget_remote_measure/models/remote_measure_device.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,16 @@ class RemoteMeasureDevice(models.Model):
selection=[
("websockets", "Web Sockets"),
("webservices", "Web Services"),
("tcp", "Direct connection"),
],
required=True,
)
host = fields.Char(required=True)
instant_read = fields.Boolean(help="Read right on as the widget gets rendered")
non_stop_read = fields.Boolean(
help="Don't stop reading until the widget is disposed"
)
read_interval = fields.Integer(
help="(0 for no sleep between reads) Miliseconds to wait between device reads"
)
test_measure = fields.Float(default=0.0)
115 changes: 108 additions & 7 deletions web_widget_remote_measure/static/src/js/remote_measure_widget.esm.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,82 @@ export const RemoteMeasureMixin = {
_connect_to_webservices() {
return;
},
/**
* Send read params to the remote device
* @returns {Object}
*/
_read_from_device_tcp_params() {
return {command: false};
},
/**
* Process call
* @returns {Number}
*/
async _read_from_device_tcp() {
const data = await this._rpc({
route: `/remote_measure_device/${this.remote_device_data.id}` || [],
params: this._read_from_device_tcp_params(),
});
if (!data) {
return null;
}
const processed_data = this[`_proccess_msg_${this.protocol}`](data);
if (isNaN(processed_data.value)) {
processed_data.value = 0;
}
return processed_data;
},
/**
* Connect to the local controller, which makes the direct connection to the
* scale.
*/
async _connect_to_tcp() {
var icon = "fa-thermometer-empty";
var stream_success_counter = 20;
this._unstableMeasure();
// Used to set the read interval if any
const timer = (ms) => new Promise((res) => setTimeout(res, ms));
// Don't keep going forever unless non stop reading
for (
let attemps_left = this.remote_device_data.non_stop_read ? Infinity : 1000;
attemps_left > 0;
attemps_left--
) {
// Allow to break the loop manually
if (this.stop) {
break;
}
const processed_data = await this._read_from_device_tcp();
if (!processed_data) {
continue;
}
if (processed_data.stable) {
this._stableMeasure();
} else {
this._unstableMeasure();
stream_success_counter = 20;
}
if (processed_data.stable && stream_success_counter <= 0) {
this._stableMeasure();
this._awaitingMeasure();
this._recordMeasure();
break;
} else if (this.remote_device_data.non_stop_read) {
stream_success_counter = 20;
this._recordMeasure();
}
if (stream_success_counter) {
--stream_success_counter;
}
icon = this._nextStateIcon(icon);
this.amount = processed_data.value;
this._setMeasure();
// Set sleep interval
if (this.remote_device_data.read_interval) {
await timer(this.remote_device_data.read_interval);
}
}
},
/**
* Convert the measured units to the units expecte by the record if different
* @param {Number} amount
Expand Down Expand Up @@ -162,16 +238,32 @@ export const RemoteMeasureMixin = {
this.start_add = false;
},
/**
* Start requesting measures from the remote device
* @param {MouseEvent} ev
* Request measure to remote device
*/
_onMeasure(ev) {
ev.preventDefault();
measure() {
this.stop = false;
this.$start_measure.addClass("d-none");
this.$stop_measure.removeClass("d-none");
this.$icon = this.$stop_measure.find("i");
this[`_connect_to_${this.connection_mode}`]();
},
/**
* Stop requesting measures from device
*/
measure_stop() {
this._closeSocket();
this.stop = true;
this._awaitingMeasure();
this._recordMeasure();
},
/**
* Start requesting measures from the remote device
* @param {MouseEvent} ev
*/
_onMeasure(ev) {
ev.preventDefault();
this.measure();
},
_onMeasureAdd(ev) {
ev.preventDefault();
this.start_add = true;
Expand All @@ -187,9 +279,7 @@ export const RemoteMeasureMixin = {
*/
_onValidateMeasure(ev) {
ev.preventDefault();
this._closeSocket();
this._awaitingMeasure();
this._recordMeasure();
this.measure_stop();
},
/**
* Remote measure handle to start measuring
Expand Down Expand Up @@ -339,6 +429,17 @@ export const RemoteMeasure = FieldFloat.extend(RemoteMeasureMixin, {
this.$el.prepend(this.$start_measure, this.$stop_measure);
return def;
},
/**
* Read right on if configured
* @override
*/
start() {
this._super(...arguments).then(() => {
if (this.remote_device_data.instant_read) {
this.measure();
}
});
},
/**
* Ensure that the socket is allways closed
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@
<field name="connection_mode" />
</group>
</group>
<group>
<group string="Read behavior">
<field name="instant_read" />
<field name="non_stop_read" />
<field name="read_interval" />
</group>
</group>
</sheet>
</form>
</field>
Expand Down
14 changes: 14 additions & 0 deletions web_widget_remote_measure/views/res_users_views.xml
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,18 @@
</page>
</field>
</record>
<record id="res_users_form_view" model="ir.ui.view">
<field name="model">res.users</field>
<field name="inherit_id" ref="base.view_users_form_simple_modif" />
<field name="arch" type="xml">
<group name="preferences" position="inside">
<group name="devices" string="Devices">
<field
name="remote_measure_device_id"
string="Preferred remote device"
/>
</group>
</group>
</field>
</record>
</odoo>
Loading