Files
Odoo-Modules/fusion_iot/iot/iot_handlers/drivers/SixDriver.py
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

181 lines
8.8 KiB
Python

# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ctypes
from time import sleep
from logging import getLogger
from odoo.addons.iot_drivers.tools.system import IS_WINDOWS
from odoo.addons.iot_drivers.iot_handlers.lib.ctypes_terminal_driver import CtypesTerminalDriver, import_ctypes_library, CTYPES_BUFFER_SIZE, create_ctypes_string_buffer
_logger = getLogger(__name__)
CANCELLED_BY_POS = 2 # Error code returned when you press "cancel" in PoS
# Load library
LIB_NAME = 'libsix_odoo_w.dll' if IS_WINDOWS else 'libsix_odoo_l.so'
TIMAPI = import_ctypes_library('tim', LIB_NAME)
# int six_cancel_transaction(t_terminal_manager *terminal_manager)
TIMAPI.six_cancel_transaction.argtypes = [ctypes.c_void_p]
# int six_perform_transaction
TIMAPI.six_perform_transaction.argtypes = [
ctypes.c_void_p, # t_terminal_manager *terminal_manager
ctypes.c_char_p, # char *pos_id
ctypes.c_int, # int user_id
ctypes.c_int, # int transaction_type
ctypes.c_int, # int amount
ctypes.c_char_p, # char *currency_str
ctypes.c_char_p, # char *transaction_id,
ctypes.c_char_p, # char *merchant_receipt
ctypes.c_char_p, # char *customer_receipt
ctypes.c_char_p, # char *card_number
ctypes.c_char_p, # char *card_brand
ctypes.POINTER(ctypes.c_int), # int *error_code
ctypes.c_char_p, # char *error
]
TIMAPI.six_terminal_balance.argtypes = [
ctypes.c_void_p, # t_terminal_manager *terminal_manager
ctypes.c_char_p, # char *balance_receipt_buffer
ctypes.POINTER(ctypes.c_int), # int *n_receipts
]
class SixDriver(CtypesTerminalDriver):
connection_type = 'tim'
def __init__(self, identifier, device):
super(SixDriver, self).__init__(identifier, device)
self.device_name = 'Six terminal %s' % self.device_identifier
self.device_manufacturer = 'Six'
def processTransaction(self, transaction):
if transaction['amount'] <= 0:
return self.send_status(
error='The terminal cannot process negative or null transaction amounts.',
request_data=transaction
)
elif transaction['transactionType'] not in ['Refund', 'Payment']:
return self.send_status(
error='Invalid transaction type.',
request_data=transaction
)
# Notify PoS about the transaction start
self.send_status(stage='WaitingForCard', request_data=transaction)
# Transaction buffers
transaction_id = create_ctypes_string_buffer()
merchant_receipt = create_ctypes_string_buffer()
customer_receipt = create_ctypes_string_buffer()
card_number = create_ctypes_string_buffer()
card_brand = create_ctypes_string_buffer()
error_code = ctypes.c_int(0)
error = create_ctypes_string_buffer()
# Transaction
try:
_logger.info('Start transaction #%s', transaction)
result = TIMAPI.six_perform_transaction(
self.dev, # t_terminal_manager *terminal_manager
str(transaction['posId']).encode(), # char *pos_id
ctypes.c_int(transaction['userId']), # int user_id
ctypes.c_int(1) if transaction['transactionType'] == 'Payment' else ctypes.c_int(2), # int transaction_type
ctypes.c_int(transaction['amount']), # int amount
transaction['currency'].encode(), # char *currency_str
transaction_id, # char *transaction_id
merchant_receipt, # char *merchant_receipt
customer_receipt, # char *customer_receipt
card_number, # char *card_number
card_brand, # char *card_brand
ctypes.byref(error_code), # int *error_code
error, # char *error
)
# Transaction successful
if result == 1:
_logger.info('Successfully finished transaction #%s', transaction)
self.send_status(
response='Approved',
ticket=customer_receipt.value.decode(),
ticket_merchant=merchant_receipt.value.decode(),
card=card_brand.value.decode(),
card_no=card_number.value.decode(),
transaction_id=transaction_id.value.decode(),
request_data=transaction,
)
# Transaction failed
elif result == 0:
# If cancelled by Odoo Pos
if error_code.value == CANCELLED_BY_POS:
sleep(3) # Wait a couple of seconds between cancel requests as per documentation
_logger.info("Transaction #%s cancelled by PoS user", transaction)
self.send_status(stage='Cancel', request_data=transaction)
_logger.info("Transaction %s cancelled by Odoo PoS", transaction)
# If an error was encountered
else:
error_message = f"{error_code.value}: {error.value.decode()}"
_logger.info("Transaction #%s failed with error: %s", transaction, error_message)
self.send_status(error=error_message, request_data=transaction)
# Terminal disconnected
elif result == -1:
_logger.warning("Terminal disconnected during transaction #%s", transaction)
self.send_status(disconnected=True)
except OSError:
_logger.exception("Failed to perform Six transaction. Check for potential segmentation faults")
sleep(3) # needed to space out transaction requests
self.send_status(
error="An error has occured. Check the transaction result manually with the payment provider",
request_data=transaction,
)
def cancelTransaction(self, transaction):
self.send_status(stage='waitingCancel', request_data=transaction)
if not self.terminal_busy:
# In case of restart after sending a payment request, the terminal is not busy
# but the pos is still waiting for the transaction confirmation: we need to be
# able to unblock it pressing cancel
return self.send_status(stage="Cancel", request_data=transaction)
try:
_logger.info("cancel transaction request for %s", transaction)
if not TIMAPI.six_cancel_transaction(ctypes.cast(self.dev, ctypes.c_void_p)):
_logger.info("Transaction #%s could not be cancelled", transaction)
self.send_status(stage='Cancel', error='Transaction could not be cancelled', request_data=transaction)
except OSError:
_logger.exception("Failed to cancel Six transaction. Check for potential segmentation faults.")
sleep(3) # needed to space out cancellation requests
self.send_status(
error="An error has occured when cancelling Six transaction. Check the transaction result manually with the payment provider",
request_data=transaction,
)
def six_terminal_balance(self, data):
balance_receipt_buffer = create_ctypes_string_buffer()
n_receipts = ctypes.c_int(0)
try:
_logger.info("Requesting terminal balance")
result = TIMAPI.six_terminal_balance(self.dev, balance_receipt_buffer, ctypes.byref(n_receipts))
if result:
_logger.info("Terminal balance request success")
# If this ever occurs the C code will need to be adapted to handle multiple receipts
n_receipts_val = n_receipts.value
receipt_val = balance_receipt_buffer.value.decode()
if n_receipts_val > 1:
_logger.warning("%s receipts returned from terminal balance request, only the first will be used", n_receipts_val)
elif n_receipts_val == -1:
receipt_val += "\nTruncated receipt"
_logger.warning("The balance receipt was truncated, consider increasing the buffer size")
self.send_status(request_data=data, ticket=receipt_val)
else:
_logger.info("Failed to get terminal balance")
self.send_status(error="Failed to get terminal balance", request_data=data)
except OSError:
_logger.exception("Failed to get terminal balance. Check for potential segmentation faults.")
self.send_status(
error="An error has occured when requesting the terminal balance. Check the terminal manually",
request_data=data,
)