Files
gsinghpal 6e964c230f feat(iot): repackaged Odoo iot modules + Fusion Plating sensor wrapper
Phase A of the IoT initiative — gets the server-side infrastructure
in place before the Raspberry Pi hardware arrives, so the iot admin
UI + /fp/iot/ingest endpoint are ready to accept the first real
temperature reading as soon as the Pi is wired up.

New top-level folder: fusion_iot/

1. **iot_base/** — Odoo S.A. iot_base module, copied from
   RePackaged-Odoo verbatim. LGPL-3 upstream, no changes needed.

2. **iot/** — Odoo S.A. iot module, repackaged:
   - `models/update.py` neutralised (removed the publisher_warranty
     IoT-Box-counting report that phones home to odoo.com for
     enterprise licence enforcement)
   - `iot_handlers/lib/load_worldline_library.sh` deleted (proprietary
     Worldline payment lib fetch from download.odoo.com, not needed)
   - `wizard/add_iot_box.py._connect_iot_box_with_pairing_code` —
     upstream called odoo.com's iot-proxy to resolve pairing codes;
     replaced with a no-op. Pi-side iot_drivers proxy registers
     directly with this Odoo server instead.
   - Manifest rebranded with an explicit changelog preamble.

3. **fusion_plating_iot/** — new plating-specific wrapper:
   - `fp.tank.sensor` — maps an iot.device (or a direct-HTTP-ingest
     sensor) to a fusion.plating.tank + fusion.plating.bath.parameter.
     Supports DS18B20, PT100/1000, pH, conductivity, level. Per-sensor
     alert_min/max overrides.
   - `fp.tank.reading` — append-only time-series. On create, evaluates
     against sensor's alert range. On in-spec → out-of-spec TRANSITION,
     auto-raises a fusion.plating.quality.hold (once per excursion,
     no spam during sustained out-of-spec).
   - `POST /fp/iot/ingest` — shared-secret HTTP endpoint for sensors
     bypassing the Pi proxy. Token via X-FP-IOT-Token header OR body.
     Accepts single-reading or batch payloads.
   - Menu under Plating → Operations → Sensors & Readings.
   - Tank form inherits get a Sensors tab inline.

Deployed to entech. Verified end-to-end:
- Install: iot_base + iot + fusion_plating_iot all 'installed'
- Smoke test: in-spec → out-of-spec → hold raised (HOLD-0010);
  continued excursion → NO duplicate hold; back-in-spec → NEW
  excursion → NEW hold (HOLD-0011) ✓
- HTTP endpoint: correct token → 200 accepted; wrong token → 401;
  unknown device_serial → 404; batch payload → 200 accepted=N ✓

Phase B (when Raspberry Pi hardware arrives): DS18B20 iot_handler
driver for the Pi-side iot_drivers proxy + systemd service on
vanilla Raspberry Pi OS + first live reading from physical probe.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 10:46:45 -04:00

129 lines
5.3 KiB
Python

from datetime import timedelta
import logging
import secrets
from urllib.parse import urlsplit
from odoo import api, fields, models
from odoo.http import request
_logger = logging.getLogger(__name__)
class IotBox(models.Model):
_name = 'iot.box'
_description = 'IoT Box'
name = fields.Char('Name', required=True)
identifier = fields.Char(string='Identifier', readonly=True)
device_ids = fields.One2many('iot.device', 'iot_id', string="Devices")
device_count = fields.Integer(compute='_compute_device_count')
ip = fields.Char('Domain Address', readonly=True)
drivers_auto_update = fields.Boolean('Automatic drivers update', help='Automatically update drivers when the IoT Box boots', default=True)
version = fields.Char('Image Version', readonly=True)
version_commit_url = fields.Html(readonly=True, compute='_compute_commit_url')
company_id = fields.Many2one('res.company', 'Company')
ssl_certificate_end_date = fields.Datetime('SSL Certificate End Date', readonly=True)
must_install_fdm_module = fields.Boolean(
"A fiscal data module is connected to this IoT Box", readonly=True, compute="_compute_must_install_fdm_module"
)
def _default_token(self):
"""Generate a token used in the iot box "token" field or by the wizards used to connect a new IoT Box.
Also clears the token from the configuration parameters if used to assign the "token" field to
make the token unique per IoT Box.
:return: The token generated by the wizard.
"""
icp_sudo = self.env['ir.config_parameter'].sudo()
iot_token_param = icp_sudo.search([('key', '=', 'iot.iot_token')], limit=1)
iot_token_value = iot_token_param.value if iot_token_param else None
if (
not iot_token_param
or not iot_token_value
or iot_token_param.write_date + timedelta(minutes=15) < fields.Datetime.now()
):
_logger.info("No valid token found in the configuration parameters, generating a new one.")
iot_token_value = secrets.token_hex(16)
icp_sudo.set_param('iot.iot_token', iot_token_value)
return iot_token_value
token = fields.Char(default=lambda self: self._default_token(), readonly=True)
def _compute_device_count(self):
for box in self:
box.device_count = len(box.device_ids)
@api.ondelete(at_uninstall=True)
def _unlink_iot_box(self):
self.env['iot.channel'].send_message({
"iot_identifiers": self.mapped('identifier')
}, 'server_clear')
def open_homepage(self):
self.ensure_one()
scheme = urlsplit(request.httprequest.referrer).scheme
return {
'type': 'ir.actions.act_url',
'url': f'{scheme}://{self.ip}' if scheme == 'https' else f'{scheme}://{self.ip}:8069',
'target': 'new',
}
@api.model
def connect_iot_box(self, local_iot_boxes):
"""
This method is called when pressing the "Connect" button in the IoT app.
Used to connect a new IoT Box to a database.
:return: action to open the wizard view depending on the result of the iot-proxy request sent by the wizard
"""
wizard = self.env['add.iot.box'].create({})
self.env['iot.discovered.box'].create([
{
"pairing_code": box["pairing_code"],
"serial_number": box.get("serial_number"),
"add_iot_box_wizard_id": wizard.id,
}
for box in local_iot_boxes
])
return wizard.add_iot_box_wizard_action()
@api.depends('device_ids')
def _compute_must_install_fdm_module(self):
is_module_installed = (
self.env['ir.module.module'].sudo().search([('name', '=', 'pos_blackbox_be')], limit=1).state == 'installed'
)
for box in self:
box.must_install_fdm_module = (
self.env.company.country_id.code == "BE"
and not is_module_installed
and any(device.type == 'fiscal_data_module' for device in box.device_ids)
)
def install_fdm_module(self):
"""Install the pos_blackbox_be module if it is not installed and a fiscal data module is connected to the IoT Box."""
if not self.must_install_fdm_module:
return
module = self.env['ir.module.module'].sudo().search([('name', '=', 'pos_blackbox_be')], limit=1)
if module and module.state != 'installed':
module.button_immediate_install()
_logger.info("pos_blackbox_be module installed successfully.")
return {
'type': 'ir.actions.client',
'tag': 'reload',
}
_logger.warning("pos_blackbox_be module is already installed or not found.")
return None
@api.depends('version')
def _compute_commit_url(self):
base_url = "https://www.github.com/odoo/odoo/commit/"
for box in self:
if box.version and "#" in box.version:
image_version, commit_hash = box.version.split("#", 1)
box.version_commit_url = (
f'<span>{image_version}#<a href="{base_url}{commit_hash}" target="_blank">{commit_hash}</a></span>'
)
else:
box.version_commit_url = f'<span>{box.version}</span>' if box.version else False