Merge branch 'develop' of https://e.coding.net/jikimo-hn/jikimo_sfs/jikimo_sf into feature/修改机床参数bug

This commit is contained in:
qihao.gong@jikimo.com
2024-02-23 18:15:45 +08:00
12 changed files with 185 additions and 112 deletions

View File

@@ -157,7 +157,8 @@ class Manufacturing_Connect(http.Controller):
if workorder.state != 'ready':
res = {'Succeed': False, 'ErrorCode': 202, 'Error': '工单未就绪'}
return json.JSONEncoder().encode(res)
work_equipment_id = request.env['maintenance.equipment'].sudo().search([('name', '=', equipment_id)], limit=1)
work_equipment_id = request.env['maintenance.equipment'].sudo().search([('name', '=', equipment_id)],
limit=1)
if not work_equipment_id:
res = {'Succeed': False, 'ErrorCode': 202, 'Error': '没有找到该加工设备'}
return json.JSONEncoder().encode(res)
@@ -212,8 +213,20 @@ class Manufacturing_Connect(http.Controller):
ret = json.loads(datas)
production_id = ret['BillId']
routing_type = ret['CraftId']
request.env['mrp.workorder'].sudo().search(
workorder = request.env['mrp.workorder'].sudo().search(
[('production_id', '=', production_id), ('routing_type', '=', routing_type)], limit=1)
if workorder:
if 'ReportPaht' in ret:
download_state = request.env['mrp.workorder'].with_user(
request.env.ref("base.user_admin")).download_reportfile_tmp(workorder,
ret['ReportPaht'])
if download_state is not False:
request.env['mrp.workorder'].with_user(
request.env.ref("base.user_admin")).get_detection_file(workorder, ret['ReportPaht'])
else:
res = {'Succeed': False, 'ErrorCode': 204, 'Error': '检测报告文件从FTP拉取失败'}
else:
res = {'Succeed': False, 'ErrorCode': 203, 'Error': '未传ReportPaht字段'}
except Exception as e:
res = {'Succeed': False, 'ErrorCode': 202, 'Error': e}
logging.info('PartQualityInspect error:%s' % e)
@@ -377,8 +390,10 @@ class Manufacturing_Connect(http.Controller):
[('feeder_station_destination', '=', ret['DeviceId'])])
if workpiece_delivery:
for wd in workpiece_delivery:
if wd.production_id.production_line_state == '待上产线':
logging.info('wd.production_id:%s' % workpiece_delivery.production_id.id)
logging.info('wd.workorder_id:%s' % wd.workorder_id.name)
if wd.workorder_id.state == 'done' and wd.production_id.production_line_state == '待上产线':
logging.info('wd.production_id:%s' % wd.production_id.name)
logging.info('wd.production_line_state:%s' % wd.production_id.production_line_state)
wd.production_id.write({'production_line_state': '已上产线'})
else:
res = {'Succeed': False, 'ErrorCode': 203, 'Error': '该DeviceId没有对应的工件配送数据'}
@@ -409,8 +424,10 @@ class Manufacturing_Connect(http.Controller):
[('feeder_station_destination', '=', ret['DeviceId'])])
if workpiece_delivery:
for wd in workpiece_delivery:
if wd.production_id.production_line_state == '已上产线':
logging.info('wd.production_id:%s' % workpiece_delivery.production_id.id)
logging.info('wd.workorder_id:%s' % wd.workorder_id.name)
if wd.workorder_id.state == 'done' and wd.production_id.production_line_state == '已上产线':
logging.info('wd.production_id:%s' % wd.production_id.name)
logging.info('wd.production_line_state:%s' % wd.production_id.production_line_state)
wd.production_id.write({'production_line_state': '已下产线'})
else:
res = {'Succeed': False, 'ErrorCode': 203, 'Error': '该DeviceId没有对应的工件配送数据'}

View File

@@ -139,14 +139,7 @@ class ResMrpWorkOrder(models.Model):
string='生产线', store=True)
production_line_state = fields.Selection(related='production_id.production_line_state',
string='上/下产线', store=True)
detection_report_path = fields.Char('检测报告链接地址')
# @api.onchange('rfid_code')
# def compute_rfid(self):
# workorder = self.env['mrp.workorder'].search([('production_id', '=', self.production_id.id)])
# if workorder:
# for item in workorder:
# item.write({'rfid_code': self.rfid_code})
detection_report = fields.Binary('检测报告', readonly=True)
def get_plan_workorder(self, production_line):
tomorrow = (date.today() + timedelta(days=+1)).strftime("%Y-%m-%d")
@@ -634,6 +627,36 @@ class ResMrpWorkOrder(models.Model):
self.production_id.button_mark_done1()
# self.production_id.state = 'done'
# 将FTP的检测报告文件下载到临时目录
def download_reportfile_tmp(self, workorder, reportpath):
production_no = workorder.production_id.name.replace('/', '_')
remotepath = os.path.join('/', production_no, 'detection')
serverdir = os.path.join('/tmp', production_no, 'detection')
ftp_resconfig = self.env['res.config.settings'].get_values()
ftp = FtpController(str(ftp_resconfig['ftp_host']), int(ftp_resconfig['ftp_port']),
ftp_resconfig['ftp_user'],
ftp_resconfig['ftp_password'])
download_state = ftp.download_reportfile_tree(remotepath, serverdir, reportpath)
logging.info('download_state:%s' % download_state)
return download_state
# 根据中控系统提供的检测文件地址去ftp里对应的制造订单里获取
def get_detection_file(self, workorder, reportPath):
logging.info('workorder:%s' % workorder.name)
logging.info('制造订单:%s' % workorder.production_id.name)
logging.info('reportPath:%s' % reportPath)
serverdir = os.path.join('/tmp', reportPath).replace('//', '/')
logging.info('serverdir:%s' % serverdir)
for root, dirs, files in os.walk(serverdir):
for f in files:
logging.info('f:%s' % f)
if os.path.splitext(f)[1] == ".pdf":
full_path = os.path.join(serverdir, root, f)
logging.info('检测文件路径:%s' % full_path)
if full_path is not False:
workorder.detection_report = base64.b64encode(
open(full_path, 'rb').read())
class CNCprocessing(models.Model):
_name = 'sf.cnc.processing'
@@ -713,6 +736,8 @@ class CNCprocessing(models.Model):
logging.info('cnc_file_path:%s' % cnc_file_path)
self.write_file(cnc_file_path, cnc_processing)
# 创建附件(nc文件)
def attachment_create(self, name, data):
attachment = self.env['ir.attachment'].create({

View File

@@ -415,7 +415,7 @@
<field name="production_id" invisible="1"/>
<field name="workpiece_code"/>
<field name="feeder_station_start" force_save="1"/>
<field name="feeder_station_destination"/>
<field name="feeder_station_destination" force_save="1"/>
<field name="production_line_id"/>
<field name="task_delivery_time" readonly="1"/>
<field name="task_completion_time" readonly="1"/>
@@ -430,9 +430,9 @@
<field name="results" invisible="1"/>
<page string="后置三元检测" attrs='{"invisible": [("routing_type","!=","CNC加工")]}'>
<group>
<field name="detection_report_path" attrs='{"invisible":[("results","!=",False)]}'/>
<field name="test_results" widget="selection" attrs='{"invisible":[("results","!=",False)]}'/>
<field name="results" readonly="1" attrs='{"invisible":[("results","!=","合格")]}'/>
<field name="detection_report" attrs='{"invisible":[("results","!=",False)]}' widget="pdf_viewer"/>
</group>
<div class="col-12 col-lg-6 o_setting_box">
<button type="object" class="oe_highlight" name="recreateManufacturingOrWorkerOrder"

View File

@@ -29,6 +29,7 @@ class FtpController():
logging.info("进入FTP目录 ")
self.ftp.cwd(target_dir) # 切换工作路径
logging.info('FTP目录:%s' % target_dir)
self.ftp.mkd('detection')
remotenames = self.ftp.nlst()
logging.info('FTP目录文件:%s' % remotenames)
for file in remotenames:
@@ -39,6 +40,32 @@ class FtpController():
except Exception:
return 0
# 下载目录下的检测文件
def download_reportfile_tree(self, target_dir, serverdir, reportpath):
try:
logging.info("进入FTP目录 ")
logging.info('FTP目录1:%s' % target_dir)
logging.info('serverdir:%s' % serverdir)
logging.info('reportpath:%s' % reportpath)
target_dir1 = target_dir.split('/')
logging.info('target_dir1:%s' % target_dir1[1])
target_dir = os.path.join('/', target_dir1[1])
logging.info('target_dir:%s' % target_dir)
self.ftp.cwd(target_dir) # 切换工作路径
logging.info('FTP目录111111:%s' % target_dir[2])
self.ftp.cwd(target_dir[2]) # 切换工作路径
logging.info('FTP目录:%s' % target_dir)
remotenames = self.ftp.nlst()
logging.info('FTP目录检测报告文件:%s' % remotenames)
for file in remotenames:
server = os.path.join(serverdir, file)
logging.info('server' % server)
if file.find(reportpath) != -1:
self.download_file(server, file)
return 1
except:
return False
# 下载指定目录下的指定文件
def download_file(self, serverfile, remotefile):
file_handler = open(serverfile, 'wb')

View File

@@ -1,34 +1,36 @@
import json
import requests
import logging
from odoo import fields, models, api
from odoo.exceptions import ValidationError
from datetime import datetime
from odoo.addons.sf_base.commons.common import Common
class QualityCheck(models.Model):
_inherit = "quality.check"
_description = '零件特采'
# ==========零件特采接口==========
def _register_tool_groups(self):
create_url = '/AutoDeviceApi/PartSpecProc'
sf_sync_config = self.env['res.config.settings'].get_values()
token = sf_sync_config['token']
sf_secret_key = sf_sync_config['sf_secret_key']
headers = Common.get_headers(self, token, sf_secret_key)
strurl = sf_sync_config['sf_url'] + create_url
val = {
'RfidCode': None,
}
kw = json.dumps(val, ensure_ascii=False)
r = requests.post(strurl, json={}, data={'kw': kw, 'token': token}, headers=headers)
def _register_quality_check(self):
# create_url = '/AutoDeviceApi/PartSpecProc'
# sf_sync_config = self.env['res.config.settings'].get_values()
# token = sf_sync_config['token']
# sf_secret_key = sf_sync_config['sf_secret_key']
# headers = Common.get_headers(self, token, sf_secret_key)
headers = {'Authorization': 'Ba F2CF5DCC-1A00-4234-9E95-65603F70CC8A'}
crea_url = "https://x24467i973.zicp.fun/AutoDeviceApi/PartSpecProc"
val = ['0037835872']
r = requests.post(crea_url, json=val, headers=headers)
ret = r.json()
if r == 200:
logging.info('_register_quality_check:%s' % ret)
if ret['Succeed']:
return "零件特采发送成功"
else:
raise ValidationError("零件特采发送失败")
# @api.onchange('quality_state')
# def _onchange_quality_state(self):
# if self.quality_state in ['pass', 'fail']:
# self._register_tool_groups()
def do_fail(self):
self.write({
'quality_state': 'fail',
'user_id': self.env.user.id,
'control_date': datetime.now()})
self._register_quality_check()

View File

@@ -8,54 +8,6 @@ from odoo.http import request
class Manufacturing_Connect(http.Controller):
# @http.route('/AutoDeviceApi/GetToolInfo', type='json', auth='none', methods=['GET', 'POST'], csrf=False,
# cors="*")
# def get_equipment_tool_Info(self, **kw):
# """
# 机床刀库实时信息
# :param kw:
# :return:
# """
# logging.info('get_equipment_tool_Info:%s' % kw)
# try:
# datas = request.httprequest.data
# ret = json.loads(datas)
# ret = json.loads(ret.get('result'))
# logging.info('DeviceId:%s' % ret)
# equipment = request.env['maintenance.equipment'].sudo().search([('name', '=', ret['DeviceId'])])
#
# res = {'Succeed': True, 'Datas': []}
# if equipment:
# for item in equipment:
# data = []
# for equipment_tool_id in item.product_template_ids:
# functional_tool_id = self.env['sf.functional.cutting.tool.entity'].sudo().search(
# [('code', '=', equipment_tool_id.tool_code)])
#
# alarm_time = None
# if functional_tool_id.functional_tool_status == '报警':
# alarm_time = self.env['sf.functional.tool.warning'].sudo().search(
# [('code', '=', equipment_tool_id.tool_code)]).alarm_time
# equipment_tool = {
# 'RfidCode': None,
# 'ToolId': equipment_tool_id.code,
# 'ToolName': equipment_tool_id.functional_tool_name_id.name,
# 'MaxLife': equipment_tool_id.life_value_max,
# 'UseLife': equipment_tool_id.used_value,
# 'AddDatetime': equipment_tool_id.tool_install_time,
# 'State': functional_tool_id.functional_tool_status,
# 'WarnDate': alarm_time if alarm_time else False
# }
# data.append(equipment_tool)
# res['Datas'].append({
# 'DeviceId': item.name,
# 'Data': data
# })
# except Exception as e:
# res = {'Succeed': False, 'ErrorCode': 202, 'Error': e}
# logging.info('get_equipment_tool_Info error:%s' % e)
# return json.JSONEncoder().encode(res)
@http.route('/AutoDeviceApi/ToolGroup', type='json', auth='none', methods=['GET', 'POST'], csrf=False,
cors="*")
def get_functional_tool_groups_Info(self, **kw):

View File

@@ -692,6 +692,15 @@ class CAMWorkOrderProgramKnifePlan(models.Model):
names = categories._search([], order=order, access_rights_uid=SUPERUSER_ID)
return categories.browse(names)
@api.onchange('plan_execute_status')
def _onchange_plan_execute_status(self):
for record in self:
if record.plan_execute_status == '已完成':
self.env['sf.cnc.processing'].register_cnc_processing(record)
def knife_plan_cnc_processing(self):
self.env['sf.cnc.processing'].register_cnc_processing(self)
def apply_for_tooling(self):
"""
申请装刀
@@ -757,13 +766,12 @@ class CAMWorkOrderProgramKnifePlan(models.Model):
if functional_tools:
for functional_tool in functional_tools:
if functional_tool.on_tool_stock_num == 0:
# self.env['sf.cnc.processing'].register_cnc_processing(cnc_processing)
if functional_tool.tool_stock_num == 0 and functional_tool.side_shelf_num == 0:
status = True
else:
status = True
if status:
self.env['sf.cam.work.order.program.knife.plan'].sudo().create({
knife_plan = self.env['sf.cam.work.order.program.knife.plan'].sudo().create({
'name': cnc_processing.workorder_id.production_id.name,
'cam_procedure_code': cnc_processing.program_name,
'filename': cnc_processing.cnc_id.name,
@@ -778,6 +786,8 @@ class CAMWorkOrderProgramKnifePlan(models.Model):
'shank_model': cnc_processing.cutting_tool_handle_type,
'estimated_processing_time': cnc_processing.estimated_processing_time,
})
# 创建装刀请求
knife_plan.apply_for_tooling()
class FunctionalToolAssembly(models.Model):

View File

@@ -1,5 +1,6 @@
import json
import requests
import logging
from odoo import models, api, fields
from odoo.exceptions import ValidationError
from odoo.addons.sf_base.commons.common import Common
@@ -21,6 +22,10 @@ class SfMaintenanceEquipmentTool(models.Model):
used_value = fields.Integer('已使用值(min)', related='functional_tool_name_id.used_value')
tool_install_time = fields.Datetime('机内装刀时间')
# def write_tool(self, datas):
# if datas:
# print(datas)
@api.model_create_multi
def create(self, vals_list):
tools = super().create(vals_list)
@@ -38,23 +43,52 @@ class SfMaintenanceEquipment(models.Model):
# ==========机床当前刀库实时信息接口==========
def register_equipment_tool(self):
sf_sync_config = self.env['res.config.settings'].get_values()
token = sf_sync_config['token']
sf_secret_key = sf_sync_config['sf_secret_key']
headers = Common.get_headers(self, token, sf_secret_key)
strurl = "https://x24467i973.zicp.fun/AutoDeviceApi/GetToolInfos"
val = {
"DeviceId": self.name
}
kw = json.dumps(val, ensure_ascii=False)
r = requests.get(strurl, json={}, data={'kw': kw, 'token': token}, headers=headers)
# sf_sync_config = self.env['res.config.settings'].get_values()
# token = sf_sync_config['token']
# sf_secret_key = sf_sync_config['sf_secret_key']
# headers = Common.get_headers(self, token, sf_secret_key)
headers = {'Authorization': 'Ba F2CF5DCC-1A00-4234-9E95-65603F70CC8A'}
crea_url = "https://x24467i973.zicp.fun/AutoDeviceApi/GetToolInfos"
params = {"DeviceId": self.name}
r = requests.get(crea_url, params=params, headers=headers)
ret = r.json()
print(ret)
if r == 200:
logging.info('register_equipment_tool:%s' % ret)
datas = ret['Datas']
self.write_maintenance_equipment_tool(datas)
if ret['Succeed']:
return "机床当前刀库实时信息指令发送成功"
else:
raise ValidationError("机床当前刀库实时信息指令发送失败")
def write_maintenance_equipment_tool(self, datas):
if datas:
for data in datas:
maintenance_equipment_id = self.search([('name', '=', data['DeviceId'])])
if maintenance_equipment_id:
equipment_tool_id = self.env['maintenance.equipment.tool'].sudo().search(
[('equipment_id', '=', maintenance_equipment_id.id), ('code', '=', data['ToolId'])])
functional_tool_id = self.env['sf.functional.cutting.tool.entity'].sudo().search(
[('rfid', '=', data['RfidCode'])])
time = None
if data['AddDatetime']:
datatime = str(data['AddDatetime'])
time = fields.Datetime.from_string(datatime[0:10] + ' ' + datatime[11:19])
if equipment_tool_id and functional_tool_id:
tool_install_time = {'Nomal': '正常', 'Warning': '报警'}
equipment_tool_id.write({
'functional_tool_name_id': functional_tool_id.id,
'tool_install_time': time
})
functional_tool_id.write({
'max_lifetime_value': data['MaxLife'],
'used_value': data['UseLife'],
'functional_tool_status': tool_install_time.get(data['State'])
})
else:
raise ValidationError('获取的【%s】设备不存在!!!' % data['DeviceId'])
else:
raise ValidationError('没有获取到刀具库信息!!!')
class StockLot(models.Model):
_inherit = 'stock.lot'

View File

@@ -1,5 +1,6 @@
import json
import requests
import logging
from odoo import fields, models, api
from odoo.exceptions import ValidationError
from odoo.addons.sf_base.commons.common import Common
@@ -10,21 +11,22 @@ class CNCprocessing(models.Model):
_description = 'CNC加工用刀检测'
# ==========MES装刀指令接口==========
def register_cnc_processing(self, cnc_processing):
sf_sync_config = self.env['res.config.settings'].get_values()
token = sf_sync_config['token']
sf_secret_key = sf_sync_config['sf_secret_key']
headers = Common.get_headers(self, token, sf_secret_key)
def register_cnc_processing(self, knife_plan):
# sf_sync_config = self.env['res.config.settings'].get_values()
# token = sf_sync_config['token']
# sf_secret_key = sf_sync_config['sf_secret_key']
# headers = Common.get_headers(self, token, sf_secret_key)
headers = {'Authorization': 'Ba F2CF5DCC-1A00-4234-9E95-65603F70CC8A'}
strurl = "https://x24467i973.zicp.fun/AutoDeviceApi/ToolLoadInstruct"
val = {
'DeviceId': cnc_processing.workorder_id.machine_tool_name,
'RfidCode': None,
'ToolId': cnc_processing.cutting_tool_no
'DeviceId': knife_plan.machine_table_name,
'RfidCode': knife_plan.sf_functional_tool_assembly_id.rfid,
'ToolId': int(knife_plan.cutter_spacing_code_id.code[1:])
}
kw = json.dumps(val, ensure_ascii=False)
r = requests.post(strurl, json={}, data={'kw': kw, 'token': token}, headers=headers)
r = requests.post(strurl, json=val, headers=headers)
ret = r.json()
if r == 200:
logging.info('register_cnc_processing:%s' % ret)
if ret['Succeed']:
return "MES装刀指令发送成功"
else:
raise ValidationError("MES装刀指令发送失败")

View File

@@ -12,7 +12,7 @@
<button string="获取机床刀库信息" name="register_equipment_tool" type="object" class="btn-primary"/>
<field name='product_template_ids'>
<tree editable='bottom'>
<field name="code"/>
<field name="code" readonly="false"/>
<field name="tool_code"/>
<field name="functional_tool_type"/>
<field name="functional_tool_name_id"/>

View File

@@ -812,6 +812,8 @@
attrs="{'invisible': [('plan_execute_status', '!=', '0')]}" confirm="是否确认申请装刀"/>
<button string="撤回" name="revocation" type="object" class="btn-primary"
attrs="{'invisible': [('plan_execute_status', '!=', '1')]}" confirm="是否确认撤回装刀"/>
<button string="发起中控装刀" name="knife_plan_cnc_processing" type="object" class="btn-primary"
attrs="{'invisible': [('plan_execute_status', '!=', '2')]}"/>
<field name="plan_execute_status" widget="statusbar" statusbar_visible="0,1,2"/>
</header>
@@ -827,7 +829,7 @@
<field name="filename"/>
<field name="production_line_id"/>
<field name="machine_table_name_id" string="机台号"/>
<field name="cam_cutter_spacing_code"/>
<field name="cutter_spacing_code_id"/>
<field name="tool_position_interface_type"/>
<field name="sf_functional_tool_assembly_id" string="组装单"/>
</group>
@@ -1040,7 +1042,7 @@
<group>
<group>
<field name="barcode_id" invisible="True"/>
<field name="rfid" string="功能刀具rfid"/>
<field name="rfid" string="功能刀具rfid" readonly="false"/>
<field name="code"/>
<field name="after_assembly_functional_tool_name"
string="功能刀具名称"/>

View File

@@ -401,7 +401,9 @@ class ShelfLocation(models.Model):
# objs_all = self.env['maintenance.equipment'].search([('id', '=', self.id)])
# machine_tool_list = []
r = requests.get(crea_url, headers=headers)
params = {'DeviceId': 'Cabinet-AL'}
r = requests.get(crea_url, params=params, headers=headers)
ret = r.json()
print(ret)