跳至内容
Odoo 菜单
  • 登录
  • 免费试用
  • 应用程序
    财务
    • 会计
    • 发票
    • 费用
    • 电子表格 (BI)
    • 文档
    • 电子签名
    销售
    • 客户关系管理
    • 销售
    • POS 销售点管理-零售
    • POS 销售点管理 - 餐厅
    • 订阅
    • 租赁
    网站
    • 网站设计
    • 电子商务
    • 博客
    • 论坛
    • 在线客服
    • 在线学习
    供应链
    • 库存
    • 制造
    • 产品生命周期
    • 采购
    • 维护保养
    • 品控
    人力资源
    • 员工
    • 招聘
    • 休假
    • 评价
    • 内部推荐
    • 车队
    营销
    • 社媒营销
    • 电邮营销
    • 短信营销
    • 近期活动
    • 营销自动化
    • 网上调查
    服务
    • 项目管理
    • 工时单
    • 现场服务
    • 服务台
    • 排期
    • 预约
    生产力
    • 讨论
    • 批核
    • IoT物联网
    • VoIP
    • 知识库
    • WhatsApp
    第三方应用软件 Odoo 定制 Odoo云端平台
  • 行业
    零售
    • 书店
    • 服装店
    • 家具店
    • 食品杂货店
    • 五金店
    • 玩具店
    餐饮与酒店服务
    • 酒吧及酒馆
    • 餐厅
    • 快餐
    • 民宿
    • 饮品分销商
    • 酒店
    房地产
    • 房地产代理
    • 建筑师事务所
    • 建造业
    • 地产管理
    • 园艺
    • 业主协会
    咨询
    • 会计师事务所
    • Odoo合作伙伴
    • 市场推广公司
    • 律师事务所
    • 人才招聘
    • 审核 & 认证
    制造
    • 纺织
    • 金属
    • 家具
    • 食品
    • 啤酒厂
    • 企业礼品
    保健与健身
    • 体育俱乐部
    • 眼镜店
    • 健身中心
    • 健康从业者
    • 药房
    • 发型屋
    商贸服务
    • 维修人员
    • IT 硬件及支持
    • 太阳能系统
    • 鞋匠
    • 清洁服务
    • 暖通空调服务
    其他
    • 非营利组织
    • 环境机构
    • 广告牌租赁
    • 摄影服务
    • 自行车租赁
    • 软件经销商
    浏览所有行业
  • 社区
    学习
    • 教学视频
    • 文档
    • 认证
    • 培训
    • 博客
    • 播客
    赋能教育
    • 教育计划
    • Scale Up! 商业游戏
    • 参观Odoo
    获取软件
    • 下载
    • 版本对比
    • 发布
    合作
    • Github
    • 论坛
    • 近期活动
    • 翻译
    • 成为合作伙伴
    • 合作伙伴服务
    • 注册您的会计事务所
    获取服务
    • 寻找合作伙伴
    • 查找会计服务
    • 预约顾问咨询
    • 安装及推行服务
    • 客户参考
    • 支持
    • 升级
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    获取演示
  • 定价
  • 技术支持

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • 客户关系管理
  • e-Commerce
  • 会计
  • 库存
  • PoS
  • 项目
  • MRP
All apps
只限注册用戶才可与社群互动。
所有帖文 人 徽章
标签 (查看所有)
odoo accounting v14 pos v15
关于此论坛区
只限注册用戶才可与社群互动。
所有帖文 人 徽章
标签 (查看所有)
odoo accounting v14 pos v15
关于此论坛区
帮助

runtime error cannot set daemon status of active thread

订阅

此帖文有活动时,接收通知

此问题已终结
threadingpyhtonodooV8
11298 查看
形象
Ranga Dharmapriya


I'm trying to connect pos box with network printer. But when I run my code, I got this error.

raise RuntimeError("cannot set daemon status of active thread")

Anyone know how to fix this error?

python code

 import commands
import logging
import simplejson
import os
import os.path
import io
import base64
import openerp
import time
import random
import math
import md5
import openerp.addons.hw_proxy.controllers.main as hw_proxy
import pickle
import re
import subprocess
import traceback

try:
    from .. escpos import *
    from .. escpos.exceptions import *
    from .. escpos.printer import Usb
    from .. escpos.printer import Network
except ImportError:
    escpos = printer = None

from threading import Thread, Lock
from Queue import Queue, Empty

try:
    import usb.core
    import socket
except ImportError:
    usb = None
    socket = None

from PIL import Image

from openerp import http
from openerp.http import request
from openerp.tools.translate import _

_logger = logging.getLogger(__name__)


class EscposDriver(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.queue = Queue()
        self.lock  = Lock()
        self.status = {'status': 'connecting', 'messages':[]}

    def connected_network_devices(self):
        connected = '192.168.1.200'
        return connected

    def lockedstart(self):
        with self.lock:
            if not self.isAlive():
                self.daemon = True
                self.start()

    def get_escpos_printer(self):

        printers = self.connected_network_devices()
        if len(printers) > 0:
            print printers
            self.set_status('connected', 'Connected to'+printers)
            return Network(printers)
        else:
             self.set_status('disconnected', 'Printer Not Found')
             return None

    def get_status(self):
        self.push_task('status')
        return self.status

    def open_cashbox(self,printer):
        printer.cashdraw(2)
        printer.cashdraw(5)

    def set_status(self, status, message = None):
        _logger.info(status+' : '+ (message or 'no message'))
        if status == self.status['status']:
            if message != None and (len(self.status['messages']) == 0 or message != self.status['messages'][-1]):
                self.status['messages'].append(message)
        else:
            self.status['status'] = status
            if message:
                self.status['messages'] = [message]
            else:
                self.status['messages'] = []

        if status == 'error' and message:
            _logger.error('ESC/POS Error: '+message)
        elif status == 'disconnected' and message:
            _logger.warning('ESC/POS Device Disconnected: '+message)

    def run(self):

        if not escpos:
            _logger.error('ESC/POS cannot initialize, please verify system dependencies.')
            return
        while True:
            try:
                error = True
                timestamp, task, data = self.queue.get(True)

                printer = self.get_escpos_printer()

                if printer == None:
                    if task != 'status':
                        self.queue.put((timestamp,task,data))
                    error = False
                    time.sleep(5)
                    continue
                elif task == 'receipt':
                    if timestamp >= time.time() - 1 * 60 * 60:
                        self.print_receipt_body(printer,data)
                        printer.cut()
                elif task == 'xml_receipt':
                    if timestamp >= time.time() - 1 * 60 * 60:
                        printer.receipt(data)
                elif task == 'cashbox':
                    if timestamp >= time.time() - 12:
                        self.open_cashbox(printer)
                elif task == 'printstatus':
                    self.print_status(printer)
                elif task == 'status':
                    pass
                error = False

            except NoDeviceError as e:
                print "No device found %s" %str(e)
            except HandleDeviceError as e:
                print "Impossible to handle the device due to previous error %s" % str(e)
            except TicketNotPrinted as e:
                print "The ticket does not seems to have been fully printed %s" % str(e)
            except NoStatusError as e:
                print "Impossible to get the status of the printer %s" % str(e)
            except Exception as e:
                self.set_status('error', str(e))
                errmsg = str(e) + '\n' + '-'*60+'\n' + traceback.format_exc() + '-'*60 + '\n'
                _logger.error(errmsg);
            finally:
                if error:
                    self.queue.put((timestamp, task, data))
                if printer:
                    printer.close()

    def push_task(self,task, data = None):
        self.lockedstart()
        self.queue.put((time.time(),task,data))

    def print_status(self,eprint):
        localips = ['0.0.0.0','127.0.0.1','127.0.1.1','192.168.20.122']
        ips =  [ c.split(':')[1].split(' ')[0] for c in commands.getoutput("/sbin/ifconfig").split('\n') if 'inet addr' in c ]
        ips =  [ ip for ip in ips if ip not in localips ]
        eprint.text('\n\n')
        eprint.set(align='center',type='b',height=2,width=2)
        eprint.text('PosBox Status\n')
        eprint.text('\n')
        eprint.set(align='center')

        if len(ips) == 0:
            eprint.text('ERROR: Could not connect to LAN\n\nPlease check that the PosBox is correc-\ntly connected with a network cable,\n that the LAN is setup with DHCP, and\nthat network addresses are available')
        elif len(ips) == 1:
            eprint.text('IP Address:\n'+ips[0]+'\n')
        else:
            eprint.text('IP Addresses:\n')
            for ip in ips:
                eprint.text(ip+'\n')

        if len(ips) >= 1:
            eprint.text('\nHomepage:\nhttp://'+ips[0]+':8069\n')

        eprint.text('\n\n')
        eprint.cut()

    def print_receipt_body(self,eprint,receipt):

        def check(string):
            return string != True and bool(string) and string.strip()

        def price(amount):
            return ("{0:."+str(receipt['precision']['price'])+"f}").format(amount)

        def money(amount):
            return ("{0:."+str(receipt['precision']['money'])+"f}").format(amount)

        def quantity(amount):
            if math.floor(amount) != amount:
                return ("{0:."+str(receipt['precision']['quantity'])+"f}").format(amount)
            else:
                return str(amount)

        def printline(left, right='', width=40, ratio=0.5, indent=0):
            lwidth = int(width * ratio)
            rwidth = width - lwidth
            lwidth = lwidth - indent

            left = left[:lwidth]
            if len(left) != lwidth:
                left = left + ' ' * (lwidth - len(left))

            right = right[-rwidth:]
            if len(right) != rwidth:
                right = ' ' * (rwidth - len(right)) + right

            return ' ' * indent + left + right + '\n'

        def print_taxes():
            taxes = receipt['tax_details']
            for tax in taxes:
                eprint.text(printline(tax['tax']['name'],price(tax['amount']), width=40,ratio=0.6))

        # Receipt Header
        if receipt['company']['logo']:
            eprint.set(align='center')
            eprint.print_base64_image(receipt['company']['logo'])
            eprint.text('\n')
        else:
            eprint.set(align='center',type='b',height=2,width=2)
            eprint.text(receipt['company']['name'] + '\n')

        eprint.set(align='center',type='b')
        if check(receipt['company']['contact_address']):
            eprint.text(receipt['company']['contact_address'] + '\n')
        if check(receipt['company']['phone']):
            eprint.text('Tel:' + receipt['company']['phone'] + '\n')
        if check(receipt['company']['vat']):
            eprint.text('VAT:' + receipt['company']['vat'] + '\n')
        if check(receipt['company']['email']):
            eprint.text(receipt['company']['email'] + '\n')
        if check(receipt['company']['website']):
            eprint.text(receipt['company']['website'] + '\n')
        if check(receipt['header']):
            eprint.text(receipt['header']+'\n')
        if check(receipt['cashier']):
            eprint.text('-'*32+'\n')
            eprint.text('Served by '+receipt['cashier']+'\n')

        # Orderlines
        eprint.text('\n\n')
        eprint.set(align='center')
        for line in receipt['orderlines']:
            pricestr = price(line['price_display'])
            if line['discount'] == 0 and line['unit_name'] == 'Unit(s)' and line['quantity'] == 1:
                eprint.text(printline(line['product_name'],pricestr,ratio=0.6))
            else:
                eprint.text(printline(line['product_name'],ratio=0.6))
                if line['discount'] != 0:
                    eprint.text(printline('Discount: '+str(line['discount'])+'%', ratio=0.6, indent=2))
                if line['unit_name'] == 'Unit(s)':
                    eprint.text( printline( quantity(line['quantity']) + ' x ' + price(line['price']), pricestr, ratio=0.6, indent=2))
                else:
                    eprint.text( printline( quantity(line['quantity']) + line['unit_name'] + ' x ' + price(line['price']), pricestr, ratio=0.6, indent=2))

        # Subtotal if the taxes are not included
        taxincluded = True
        if money(receipt['subtotal']) != money(receipt['total_with_tax']):
            eprint.text(printline('','-------'));
            eprint.text(printline(_('Subtotal'),money(receipt['subtotal']),width=40, ratio=0.6))
            print_taxes()
            #eprint.text(printline(_('Taxes'),money(receipt['total_tax']),width=40, ratio=0.6))
            taxincluded = False


        # Total
        eprint.text(printline('','-------'));
        eprint.set(align='center',height=2)
        eprint.text(printline(_('         TOTAL'),money(receipt['total_with_tax']),width=40, ratio=0.6))
        eprint.text('\n\n');

        # Paymentlines
        eprint.set(align='center')
        for line in receipt['paymentlines']:
            eprint.text(printline(line['journal'], money(line['amount']), ratio=0.6))

        eprint.text('\n');
        eprint.set(align='center',height=2)
        eprint.text(printline(_('        CHANGE'),money(receipt['change']),width=40, ratio=0.6))
        eprint.set(align='center')
        eprint.text('\n');

        # Extra Payment info
        if receipt['total_discount'] != 0:
            eprint.text(printline(_('Discounts'),money(receipt['total_discount']),width=40, ratio=0.6))
        if taxincluded:
            print_taxes()
            #eprint.text(printline(_('Taxes'),money(receipt['total_tax']),width=40, ratio=0.6))

        # Footer
        if check(receipt['footer']):
            eprint.text('\n'+receipt['footer']+'\n\n')
        eprint.text(receipt['name']+'\n')
        eprint.text(      str(receipt['date']['date']).zfill(2)
                    +'/'+ str(receipt['date']['month']+1).zfill(2)
                    +'/'+ str(receipt['date']['year']).zfill(4)
                    +' '+ str(receipt['date']['hour']).zfill(2)
                    +':'+ str(receipt['date']['minute']).zfill(2) )

driver = EscposDriver()

driver.push_task('printstatus')

hw_proxy.drivers['escpos'] = driver

class EscposProxy(hw_proxy.Proxy):

    @http.route('/hw_proxy/open_cashbox', type='json', auth='none', cors='*')
    def open_cashbox(self):
        _logger.info('ESC/POS: OPEN CASHBOX')
        driver.push_task('cashbox')

    @http.route('/hw_proxy/print_receipt', type='json', auth='none', cors='*')
    def print_receipt(self, receipt):
        _logger.info('ESC/POS: PRINT RECEIPT')
        driver.push_task('receipt',receipt)

    @http.route('/hw_proxy/print_xml_receipt', type='json', auth='none', cors='*')
    def print_xml_receipt(self, receipt):
        _logger.info('ESC/POS: PRINT XML RECEIPT')
        driver.push_task('xml_receipt',receipt)

    @http.route('/hw_proxy/escpos/add_supported_device', type='http', auth='none', cors='*')
    def add_supported_device(self, device_string):
        _logger.info('ESC/POS: ADDED NEW DEVICE:'+device_string)
        driver.add_supported_device(device_string)
        return "The device:\n"+device_string+"\n has been added to the list of supported devices.<br/><a href='/hw_proxy/status'>Ok</a>"

    @http.route('/hw_proxy/escpos/reset_supported_devices', type='http', auth='none', cors='*')
    def reset_supported_devices(self):
        try:
            os.remove('escpos_devices.pickle')
        except Exception as e:
            pass
        return 'The list of supported devices has been reset to factory defaults.<br/><a href="/hw_proxy/status">Ok</a>'

1
形象
丢弃

do you find a solution ??

喜欢讨论吗?不要只阅读,加入进来!

立即创建账户,享受专属功能,与我们的精彩社区互动!

注册
相关帖文 回复 查看 活动
models.py code to open a text file and append string , the text file is inside the odoo module (V8)
pyhton odooV8
形象
0
8月 18
4255
How to invisible field in tree view by check box?
openerp7 pyhton odooV8
形象
形象
1
4月 16
6683
CONFIGURACION DE CORREO PROPIO POR PRUMERA VEZ
odooV8
形象
0
3月 25
2001
How to remove model if not in the py files anymore
odooV8
形象
0
1月 25
4267
Start odoo server automatically in Ubuntu 14.04 on reboot 已解决
odooV8
形象
形象
1
8月 23
15900
社区
  • 教学视频
  • 文档
  • 论坛
开源
  • 下载
  • Github
  • Runbot
  • 翻译
服务
  • Odoo.sh 托管
  • 支持
  • 升级
  • 自定义开发服务
  • 教育
  • 查找会计服务
  • 寻找合作伙伴
  • 成为合作伙伴
关于我们
  • 我们的公司
  • 品牌资产
  • 联系我们
  • 招聘
  • 近期活动
  • 播客
  • 博客
  • 客户
  • 法律 • 隐私
  • 安全
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo致力于为企业管理提供高效智能的开源解决方案,是全球业内高速成长的软件服务商之一,逾七百五十万用户选择Odoo进行数字化升级。通过一系列全业务链覆盖、高度集成、简单易用的商业应用,助力企业实现信息化改革、降本增效并释放公司增长潜力。

Odoo独特的价值在于是一款非常容易使用又完全集成的应用。

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now