Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Submit feedback
Sign in / Register
Toggle navigation
M
MicScanSystemV1.0
Project
Project
Details
Activity
Releases
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
徐生海
MicScanSystemV1.0
Commits
bd7c532f
Commit
bd7c532f
authored
Jan 30, 2026
by
徐生海
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Initial commit
parent
854d2864
Changes
22
Show whitespace changes
Inline
Side-by-side
Showing
22 changed files
with
351 additions
and
8039 deletions
+351
-8039
AppBusinessController.py
AppBackEnd/AppBusinessController.py
+51
-47
ChamberDropBusiness.py
AppBackEnd/BackEndBusiness/ChamberDropBusiness.py
+2
-2
ChamberPickBusiness.py
AppBackEnd/BackEndBusiness/ChamberPickBusiness.py
+18
-3
SlideCellFocusingBusiness.py
AppBackEnd/BackEndBusiness/SlideCellFocusingBusiness.py
+2
-2
CameraImpl.py
AppCore/AppImplsbak/CameraImpl.py
+0
-1387
HitBotImpl.py
AppCore/AppImplsbak/HitBotImpl.py
+0
-1955
MicroscopeImpl.py
AppCore/AppImplsbak/MicroscopeImpl.py
+0
-1998
ModBusImpl.py
AppCore/AppImplsbak/ModBusImpl.py
+0
-1097
ScanCodeImpl.py
AppCore/AppImplsbak/ScanCodeImpl.py
+0
-598
WebSocketClient.py
AppCore/AppImplsbak/WebSocketClient.py
+0
-378
WebSocketServer.py
AppCore/AppImplsbak/WebSocketServer.py
+0
-261
__init__.py
AppCore/AppImplsbak/__init__.py
+0
-8
DetectionReader.py
AppCore/AppReaders/DetectionReader.py
+15
-67
HitBotReader.py
AppCore/AppReaders/HitBotReader.py
+26
-11
ManipulatorReader.py
AppCore/AppReaders/ManipulatorReader.py
+145
-86
ModBusPool.py
AppCore/AppReaders/ModBusPool.py
+1
-0
DetectionReaderInterface.py
AppInterfaces/AppImplInterfaces/DetectionReaderInterface.py
+33
-44
ModBusPoolInterface.py
AppInterfaces/AppImplInterfaces/ModBusPoolInterface.py
+6
-17
HitBotReaderInterface.py
AppInterfaces/AppReaderInterfaces/HitBotReaderInterface.py
+1
-1
ManipulatorReaderInterface.py
...erfaces/AppReaderInterfaces/ManipulatorReaderInterface.py
+1
-72
MicScanSystem.py
MicScanSystem.py
+5
-5
MicScanSystem.spec
MicScanSystem.spec
+45
-0
No files found.
AppBackEnd/AppBusinessController.py
View file @
bd7c532f
...
...
@@ -1043,12 +1043,12 @@ class AppBusinessController(AppBusinessInterface):
logWARNING
<<
message
def
waitForChamberAvailable
(
self
,
waittimes
:
int
=
30000
)
->
bool
:
isBuzzer
:
bool
=
self
.
isBuzzerAvailable
()
isChamberAvailable
:
bool
isChamberAvailable
:
bool
=
False
_waittimes
:
int
=
max
(
30000
,
waittimes
)
isWarning
:
bool
=
False
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
_waittimes
)
warning_string
:
str
=
f
'片仓没有安装到位 请检查安装好片仓'
try
:
if
self
.
system
.
isEnglishMode
():
warning_string
=
'The slide cassette is not properly installed. Please verify the installation'
while
True
:
...
...
@@ -1066,16 +1066,21 @@ class AppBusinessController(AppBusinessInterface):
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
self
.
system
.
WarningWaitTimes
())
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
isChamberAvailable
def
isChamberAvailable
(
self
)
->
bool
:
isChamberAvailable
:
bool
=
False
try
:
if
self
.
hasDetection
:
isChamberAvailable
=
self
.
detection
.
get_chamber_status
()
if
isChamberAvailable
!=
self
.
status
.
isChamberAvailable
():
self
.
status
.
setChamber
(
isChamberAvailable
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
isChamberAvailable
def
isBuzzerAvailable
(
self
)
->
bool
:
...
...
@@ -1806,14 +1811,14 @@ class AppBusinessController(AppBusinessInterface):
listentime
:
Qt
.
QDateTime
focusing_times
:
Qt
.
QDateTime
isWrong
:
int
=
RECODE_FAILURE
position_z
:
int
=
focusing_b_z
last_position_z
:
int
=
focusing_b_z
#
position_z: int = focusing_b_z
#
last_position_z: int = focusing_b_z
index
:
int
=
1
maxwaittimes
:
int
=
2000
#
maxwaittimes: int = 2000
max_focusing_times
:
int
=
60000
"""开始Z轴定速定焦"""
listentime
=
Qt
.
QDateTime
.
currentDateTime
()
begintimes
=
Qt
.
QDateTime
.
currentDateTime
()
#
listentime = Qt.QDateTime.currentDateTime()
#
begintimes = Qt.QDateTime.currentDateTime()
logSCANNING
<<
f
"{AppConvert.QDateTimeToString(Qt.QDateTime.currentDateTime())}开始玻片定焦"
"""开始定焦"""
self
.
microscope
.
set_z_speed
(
focusing_z_speed
)
...
...
@@ -1837,7 +1842,7 @@ class AppBusinessController(AppBusinessInterface):
item
.
Level
=
focusing_status
item
.
Index
=
index
index
+=
1
listentime
=
Qt
.
QDateTime
.
currentDateTime
()
#
listentime = Qt.QDateTime.currentDateTime()
if
isGrabbing
:
self
.
camera
.
GetFocusingData
(
item
,
classifier
)
else
:
...
...
@@ -1847,7 +1852,7 @@ class AppBusinessController(AppBusinessInterface):
if
RECODE_SUCCEED
==
isWrong
:
item
.
Position_Z
=
position_z
self
.
focusing_pool
.
SendEvent
(
item
)
print
(
f
"一帧定焦数据:{index} {listentime.msecsTo(Qt.QDateTime.currentDateTime())}ms"
)
#
print(f"一帧定焦数据:{index} {listentime.msecsTo(Qt.QDateTime.currentDateTime())}ms")
if
index
%
5
==
0
:
isWrong
,
Moving
,
Lower
,
Upper
,
Limit
,
Focus
=
self
.
microscope
.
ZDriverMoveStatus
()
if
RECODE_SUCCEED
==
isWrong
:
...
...
@@ -1897,13 +1902,13 @@ class AppBusinessController(AppBusinessInterface):
listentime
:
Qt
.
QDateTime
focusing_times
:
Qt
.
QDateTime
isWrong
:
int
=
RECODE_FAILURE
position_z
:
int
=
focusing_b_z
last_position_z
:
int
=
focusing_b_z
#
position_z: int = focusing_b_z
#
last_position_z: int = focusing_b_z
index
:
int
=
1
maxwaittimes
:
int
=
10000
max_focusing_times
:
int
=
60000
#
max_focusing_times: int = 60000
"""开始Z轴定速定焦"""
begintimes
=
Qt
.
QDateTime
.
currentDateTime
()
#
begintimes = Qt.QDateTime.currentDateTime()
logSCANNING
<<
f
"{AppConvert.QDateTimeToString(Qt.QDateTime.currentDateTime())}开始玻片定焦"
"""开始定焦"""
...
...
@@ -1912,7 +1917,7 @@ class AppBusinessController(AppBusinessInterface):
self
.
microscope
.
set_z_range
(
min
(
focusing_b_z
,
focusing_e_z
),
max
(
focusing_b_z
,
focusing_e_z
))
self
.
microscope
.
POS_CONST_Z
(
focusing_z_speed
)
focusing_times
=
Qt
.
QDateTime
.
currentDateTime
()
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
maxwaittimes
)
#
endtime: Qt.QDateTime = Qt.QDateTime.currentDateTime().addMSecs(maxwaittimes)
while
True
:
if
isFilter
:
if
self
.
status
.
focusing_status
==
ScanStatusLevel
.
FocusingFinish_Status
:
...
...
@@ -1925,18 +1930,19 @@ class AppBusinessController(AppBusinessInterface):
item
.
Level
=
focusing_status
item
.
Index
=
index
index
+=
1
listentime
=
Qt
.
QDateTime
.
currentDateTime
()
if
isGrabbing
:
self
.
camera
.
GetFocusingData
(
item
,
classifier
)
else
:
self
.
camera
.
GetRequestData
(
item
,
classifier
)
# listentime = Qt.QDateTime.currentDateTime()
# print(f"1一帧定焦数据:{index} {listentime.msecsTo(Qt.QDateTime.currentDateTime())}ms")
isWrong
,
position_z
=
self
.
motion
.
get_position_z
()
"""获取Z轴位置错误 重新移动到目标位置"""
if
RECODE_SUCCEED
==
isWrong
:
if
isGrabbing
:
self
.
camera
.
GetFocusingData
(
item
,
classifier
)
else
:
self
.
camera
.
GetRequestData
(
item
,
classifier
)
item
.
Position_Z
=
position_z
self
.
focusing_pool
.
SendEvent
(
item
)
print
(
f
"2一帧定焦数据:{index} {listentime.msecsTo(Qt.QDateTime.currentDateTime())}ms"
)
#
print(f"2一帧定焦数据:{index} {listentime.msecsTo(Qt.QDateTime.currentDateTime())}ms")
if
index
%
5
==
0
:
isWrong
,
Moving
,
Lower
,
Upper
,
Limit
,
Focus
=
self
.
microscope
.
ZDriverMoveStatus
()
if
RECODE_SUCCEED
==
isWrong
:
...
...
@@ -2345,20 +2351,18 @@ class AppBusinessController(AppBusinessInterface):
"""获取当前位置 如果当前机械臂位置大于安全位置 先回安全位置 再放片"""
self
.
hitbot
.
flush_scara_param
()
self
.
hitbot
.
moveToSafePosition
()
# SafeAction: HitBotSafeAction = HitBotSafeAction.getMinPrimaryItem()
# if not isinstance(SafeAction, HitBotModelInterface) or not isinstance(self.hitbot.yPosition, (int, float)):
# self.hitbot.moveToSafePosition()
# elif Float(self.hitbot.yPosition) < float(round(SafeAction.yPosition, 2)):
# self.hitbot.moveToSafePosition()
"""玻片取放片过程中不处理停止业务 只处理暂停业务"""
Action
=
Actions
[
0
]
if
chamber_number
==
4
or
chamber_number
==
9
:
self
.
hitbot
.
moveToSafePosition
(
True
)
Action
.
speed
=
self
.
system
.
HitBotSpeed4
elif
chamber_number
==
5
or
chamber_number
==
10
:
self
.
hitbot
.
moveToSafePosition
(
True
)
Action
.
speed
=
self
.
system
.
HitBotSpeed5
else
:
self
.
hitbot
.
moveToSafePosition
()
isWrong
=
self
.
waitForSucceedMoving
(
Action
)
if
RECODE_SUCCEED
!=
isWrong
:
Actions
=
HitBotChamberDropAction
.
getChamberDropActions
(
chamber_number
,
row_number
)
...
...
AppBackEnd/BackEndBusiness/ChamberDropBusiness.py
View file @
bd7c532f
...
...
@@ -154,8 +154,8 @@ class ChamberDropBusiness(Qt.QObject, AppBusinessController):
MinChamberNumber
,
MaxChamberNumber
=
self
.
system
.
getChamberRange
()
if
MinChamberNumber
<=
chamber_number
<=
MaxChamberNumber
and
MinRowNumber
<=
row_number
<=
MaxRowNumber
:
"""如果当前玻片不能取 直接退出"""
if
not
ChamberStatusModel
.
IsPickAvailable
(
chamber_number
,
row_number
):
return
RECODE_FAILURE
#
if not ChamberStatusModel.IsPickAvailable(chamber_number, row_number):
#
return RECODE_FAILURE
if
not
self
.
isValid
():
return
RECODE_FAILURE
if
not
self
.
isAvailable
:
...
...
AppBackEnd/BackEndBusiness/ChamberPickBusiness.py
View file @
bd7c532f
...
...
@@ -105,6 +105,11 @@ class ChamberPickBusiness(Qt.QObject, AppBusinessController):
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
if
isSafe
:
if
chamber_number
==
4
or
chamber_number
==
9
:
self
.
hitbot
.
moveToSafePosition
(
True
)
elif
chamber_number
==
5
or
chamber_number
==
10
:
self
.
hitbot
.
moveToSafePosition
(
True
)
else
:
self
.
hitbot
.
moveToSafePosition
()
"""处理片仓安装状态"""
while
not
self
.
waitForChamberAvailable
():
...
...
@@ -116,6 +121,11 @@ class ChamberPickBusiness(Qt.QObject, AppBusinessController):
AppTimeLoop
.
processEvents
(
self
.
system
.
WarningWaitTimes
())
if
self
.
status
.
waitForExitRunning
():
if
isSafe
:
if
chamber_number
==
4
or
chamber_number
==
9
:
self
.
hitbot
.
moveToSafePosition
(
True
)
elif
chamber_number
==
5
or
chamber_number
==
10
:
self
.
hitbot
.
moveToSafePosition
(
True
)
else
:
self
.
hitbot
.
moveToSafePosition
()
return
RECODE_SUCCEED
...
...
@@ -137,6 +147,11 @@ class ChamberPickBusiness(Qt.QObject, AppBusinessController):
isWrong
=
self
.
waitForPickWarning
(
chamber_number
,
row_number
)
if
isSafe
and
RECODE_SUCCEED
==
isWrong
:
if
chamber_number
==
4
or
chamber_number
==
9
:
self
.
hitbot
.
moveToSafePosition
(
True
)
elif
chamber_number
==
5
or
chamber_number
==
10
:
self
.
hitbot
.
moveToSafePosition
(
True
)
else
:
self
.
hitbot
.
moveToSafePosition
()
if
isExit
:
...
...
AppBackEnd/BackEndBusiness/SlideCellFocusingBusiness.py
View file @
bd7c532f
...
...
@@ -497,8 +497,8 @@ class SlideCellFocusingBusiness(Qt.QObject, AppBusinessController):
focusing_z_speed
=
Focusing
.
FocusingSpeed
objective_focusing_positions
=
model
.
Position_Z
#
objective_focusing_difference
=
abs
(
model
.
Position_Z
)
-
FocalDistance
focusing_b_z
=
max
(
min
(
int
(
objective_focusing_positions
-
abs
(
FocalDistance
)
-
abs
(
focusing_length
)
),
Focus_Upper_Limit
),
Focus_Lower_Limit
)
focusing_e_z
=
max
(
min
(
int
(
objective_focusing_positions
+
abs
(
FocalDistance
)
+
abs
(
focusing_length
)
),
Focus_Upper_Limit
),
Focus_Lower_Limit
)
focusing_b_z
=
max
(
min
(
int
(
objective_focusing_positions
-
abs
(
FocalDistance
)
),
Focus_Upper_Limit
),
Focus_Lower_Limit
)
focusing_e_z
=
max
(
min
(
int
(
objective_focusing_positions
+
abs
(
focusing_length
)
),
Focus_Upper_Limit
),
Focus_Lower_Limit
)
item
=
model
.
copy
()
item
.
Index
=
index
item
.
Focusing
=
Focusing
...
...
AppCore/AppImplsbak/CameraImpl.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: CameraImpl.py
@DateTime: 2025/4/9 23:06
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
from
pypylon
import
pylon
import
numpy
as
np
import
cv2
import
asyncio
from
abc
import
abstractmethod
from
AppCore.AppContextModels.CameraContext
import
CameraContext
from
AppCore.AppRequestModels.CameraRequest
import
CameraRequest
from
AppCore.AppDBModels.CameraModels.CameraInterface
import
CameraInterface
#
from
AppCore.AppDBModels.CameraModels.OtherCameraModel
import
OtherCameraModel
#
from
AppCore.AppDBModels.CameraModels.CameraModel
import
CameraModel
#
from
AppCore.AppDBModels.CameraModels.CameraColorModel
import
CameraColorModel
#
from
AppCore.AppDBModels.SlideModels.SlideModelInterface
import
SlideModelInterface
#
from
AppInterfaces.ImplInterface
import
(
ImplInterface
,
log_exceptions
,
AppUtils
,
AppConvert
,
AppTimeLoop
)
from
AppInterfaces.SingletonInterface
import
(
SingletonInterface
)
from
AppUtils.ImageUtils
import
ImageUtils
from
AppSettings.Settings
import
(
RECODE_FAILURE
,
RECODE_SUCCEED
,
SIGNAL_CONNECTION_TYPE
)
from
AppCore.Levels
import
*
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
from
AppLog.logHelper
import
logCAMERA
from
AppSettings.AppSetting
import
AppConfig
from
AppSettings.AppGlobalStatus
import
AppGlobalStatus
,
AppStatus
from
AppCore.ImplInterfaces
import
CameraImplInterface
CAMERA_DEFAULT_DELAY
:
int
=
50
MaxCameraRequestTimes
:
int
=
1000
class
CameraImpl
(
Qt
.
QObject
,
CameraImplInterface
,
SingletonInterface
):
Devices
:
list
[
pylon
.
DeviceInfo
]
#
Manager
:
pylon
.
InstantCamera
#
DeviceInfo
:
pylon
.
DeviceInfo
#
TlFactory
:
pylon
.
TlFactory
#
Parameter
:
CameraContext
#
Objective
:
int
#
Model
:
CameraInterface
#
Locker
:
Qt
.
QMutex
=
Qt
.
QMutex
()
@
classmethod
def
GetInstance
(
cls
,
*
args
,
**
kwargs
)
->
'CameraImpl'
:
return
super
(
CameraImpl
,
cls
)
.
GetInstance
(
*
args
,
**
kwargs
)
def
__init__
(
self
,
context
:
CameraContext
=
None
,
parent
:
Qt
.
QObject
=
None
):
super
(
CameraImpl
,
self
)
.
__init__
(
parent
=
parent
)
self
.
Parameter
=
context
self
.
Initialization
(
"CameraImpl"
,
self
,
parent
)
def
setParameter
(
self
,
context
:
CameraContext
):
isOpen
:
bool
=
self
.
IsOpen
()
self
.
deleManager
()
self
.
Parameter
=
context
self
.
initManager
(
self
.
Parameter
)
if
isOpen
:
self
.
Open
()
def
initValue
(
self
):
super
(
CameraImpl
,
self
)
.
initValue
()
if
not
self
.
hasTlFactory
:
self
.
initTlFactory
()
if
not
self
.
hasDevices
:
self
.
initDevices
()
if
not
self
.
hasParameter
:
self
.
initContext
()
self
.
initModel
()
self
.
initManager
(
self
.
Parameter
if
self
.
hasParameter
()
else
None
)
def
initModel
(
self
)
->
bool
:
if
not
self
.
hasObjective
:
self
.
Objective
=
ObjectiveLevel
.
ObjectiveNone
if
not
self
.
hasModel
or
self
.
Model
.
Level
!=
self
.
Objective
:
self
.
Model
=
AppStatus
.
getCameraModel
(
self
.
Objective
)
return
self
.
hasModel
and
self
.
Objective
==
self
.
Model
.
Level
def
initTlFactory
(
self
)
->
bool
:
if
not
self
.
hasTlFactory
:
self
.
TlFactory
=
pylon
.
TlFactory
.
GetInstance
()
return
self
.
hasTlFactory
def
initDevices
(
self
)
->
bool
:
self
.
initTlFactory
()
if
not
self
.
hasDevices
:
if
not
self
.
hasTlFactory
:
self
.
Devices
=
None
else
:
self
.
Devices
=
self
.
TlFactory
.
EnumerateDevices
()
if
self
.
hasDevices
:
from
AppLog.logHelper
import
logCAMERA
logCAMERA
<<
f
'{[device.GetModelName() for device in self.Devices]}'
return
self
.
hasDevices
def
initDeviceInfo
(
self
)
->
bool
:
self
.
initTlFactory
()
self
.
initDevices
()
self
.
initModel
()
if
not
self
.
hasDevices
or
not
self
.
hasModel
:
self
.
DeviceInfo
=
None
self
.
deleManager
()
else
:
for
device
in
self
.
Devices
:
if
device
.
GetVendorName
()
==
self
.
Model
.
VendorName
and
device
.
GetModelName
()
==
self
.
Model
.
ModelName
:
self
.
DeviceInfo
=
device
break
return
self
.
hasDeviceInfo
def
initConnect
(
self
):
super
(
CameraImpl
,
self
)
.
initConnect
()
def
deleConnect
(
self
):
super
(
CameraImpl
,
self
)
.
deleConnect
()
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasParameter
()
and
self
.
hasTlFactory
and
self
.
hasDeviceInfo
def
IsOpen
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
Manager
.
IsOpen
()
def
IsGrabbing
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
Manager
.
IsGrabbing
()
def
isEnabled
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
Manager
.
IsOpen
()
def
isDisable
(
self
)
->
bool
:
return
not
self
.
isEnabled
()
def
waitForStopGrabbing
(
self
,
waittimes
:
int
=
3000
)
->
bool
:
endtime
:
Qt
.
QDateTime
if
not
self
.
hasManager
():
return
False
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
waittimes
))
while
True
:
if
not
self
.
IsGrabbing
()
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
self
.
StopGrabbing
()
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
return
self
.
IsGrabbing
()
def
waitForClose
(
self
,
waittimes
:
int
=
3000
)
->
bool
:
endtime
:
Qt
.
QDateTime
if
not
self
.
hasManager
():
return
False
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
waittimes
))
while
True
:
if
not
self
.
IsOpen
()
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
if
not
self
.
Manager
.
IsOpen
():
break
try
:
self
.
Manager
.
Close
()
except
Exception
as
e
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
return
self
.
IsOpen
()
def
isCorrect
(
self
):
if
not
self
.
hasObjective
:
self
.
Objective
=
ObjectiveLevel
.
ObjectiveNone
if
not
self
.
hasDeviceInfo
:
self
.
deleManager
()
if
not
self
.
hasModel
:
self
.
deleManager
()
if
self
.
hasDeviceInfo
and
self
.
hasModel
:
return
self
.
Model
.
Level
==
self
.
Objective
and
self
.
DeviceInfo
.
GetModelName
()
==
self
.
Model
.
ModelName
and
self
.
DeviceInfo
.
GetVendorName
()
==
self
.
Model
.
VendorName
return
False
def
waitForFindDevice
(
self
,
waittimes
:
int
=
3000
)
->
bool
:
endtime
:
Qt
.
QDateTime
if
self
.
hasManager
()
and
self
.
isCorrect
():
return
True
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
waittimes
))
self
.
initContext
()
while
True
:
self
.
initManager
(
self
.
Parameter
)
if
self
.
hasManager
()
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
def
waitForDeviceOpen
(
self
,
waittimes
:
int
=
3000
)
->
bool
:
endtime
:
Qt
.
QDateTime
if
not
self
.
isCorrect
():
return
False
if
not
self
.
hasManager
():
return
False
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
waittimes
))
while
True
:
self
.
Manager
.
Open
()
if
self
.
IsOpen
()
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
return
self
.
IsOpen
()
def
initContext
(
self
):
if
not
self
.
hasParameter
():
self
.
Parameter
=
AppConfig
.
cameraConfig
def
Open
(
self
,
timeOut
:
int
=
1000
)
->
int
:
endtime
:
Qt
.
QDateTime
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
self
.
initContext
()
while
True
:
if
self
.
waitForFindDevice
(
timeOut
)
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
if
not
self
.
hasManager
():
return
RECODE_FAILURE
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
while
True
:
if
not
self
.
waitForStopGrabbing
(
timeOut
)
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
while
True
:
if
not
self
.
waitForClose
(
timeOut
)
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
self
.
Parameter
.
IsGrabbing
=
self
.
IsGrabbing
()
self
.
Parameter
.
IsOpen
=
self
.
IsOpen
()
try
:
self
.
initManager
(
self
.
Parameter
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
while
True
:
if
self
.
waitForDeviceOpen
(
timeOut
)
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
self
.
Parameter
.
IsOpen
=
self
.
IsOpen
()
self
.
Parameter
.
IsGrabbing
=
self
.
IsGrabbing
()
if
self
.
IsOpen
():
self
.
initCameraConfig
()
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
RECODE_SUCCEED
if
self
.
IsOpen
()
else
RECODE_FAILURE
def
CameraOpen
(
self
,
level
:
int
=
ObjectiveLevel
.
ObjectiveNone
,
timeOut
:
int
=
1000
)
->
int
:
endtime
:
Qt
.
QDateTime
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
self
.
initContext
()
self
.
Objective
=
level
while
True
:
if
self
.
waitForFindDevice
(
timeOut
):
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
if
not
self
.
hasManager
():
return
RECODE_FAILURE
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
while
True
:
if
not
self
.
waitForStopGrabbing
(
timeOut
):
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
self
.
Parameter
.
IsGrabbing
=
self
.
IsGrabbing
()
self
.
Parameter
.
IsOpen
=
self
.
IsOpen
()
try
:
if
not
self
.
isCorrect
():
self
.
initManager
()
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
abs
(
timeOut
))
while
True
:
if
self
.
waitForDeviceOpen
(
timeOut
):
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
CAMERA_DEFAULT_DELAY
)
self
.
Parameter
.
IsGrabbing
=
self
.
IsGrabbing
()
self
.
Parameter
.
IsOpen
=
self
.
IsOpen
()
if
self
.
IsOpen
():
self
.
Model
=
SystemConfig
.
getCameraModel
(
self
.
Objective
)
self
.
initCameraConfig
()
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
RECODE_SUCCEED
if
self
.
IsOpen
()
else
RECODE_FAILURE
def
setLevel
(
self
,
level
:
int
):
from
AppSettings.SystemSetting
import
SystemConfig
self
.
Objective
=
level
if
level
in
ObjectiveLevel
.
all
()
else
self
.
Objective
self
.
Model
=
SystemConfig
.
getCameraModel
(
level
)
self
.
initCameraConfig
()
def
setModel
(
self
,
level
:
int
):
from
AppSettings.SystemSetting
import
SystemConfig
self
.
Objective
=
level
if
level
in
ObjectiveLevel
.
all
()
else
self
.
Objective
self
.
Model
=
SystemConfig
.
getCameraModel
(
level
)
self
.
initCameraGama
()
def
setPixelParameter
(
self
,
level
:
int
):
from
AppSettings.SystemSetting
import
SystemConfig
self
.
Objective
=
level
if
level
in
ObjectiveLevel
.
all
()
else
self
.
Objective
self
.
Model
=
SystemConfig
.
getCameraModel
(
level
)
self
.
initCameraConfig
()
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
self
.
initContext
()
if
self
.
hasManager
():
self
.
waitForStopGrabbing
(
timeOut
)
self
.
waitForClose
(
timeOut
)
self
.
Parameter
.
IsGrabbing
=
self
.
IsGrabbing
()
self
.
Parameter
.
IsOpen
=
self
.
IsOpen
()
return
RECODE_FAILURE
if
self
.
Parameter
.
IsOpen
else
RECODE_SUCCEED
def
changedObjective
(
self
,
level
:
int
,
timeOut
:
int
=
1000
):
if
self
.
hasObjective
and
level
==
self
.
Objective
:
self
.
setLevel
(
level
)
return
RECODE_SUCCEED
else
:
self
.
Close
()
return
self
.
CameraOpen
(
level
,
timeOut
)
def
StartGrabbing
(
self
):
if
not
self
.
hasManager
():
return
if
not
self
.
IsOpen
():
return
self
.
initContext
()
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
if
self
.
Manager
.
IsGrabbing
():
return
self
.
Manager
.
StartGrabbing
(
pylon
.
GrabStrategy_LatestImages
)
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
def
Grabbing
(
self
,
):
if
not
self
.
hasManager
():
return
if
not
self
.
IsOpen
():
return
self
.
initContext
()
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
if
self
.
Manager
.
IsGrabbing
():
return
self
.
Manager
.
StartGrabbing
(
pylon
.
GrabStrategy_LatestImages
)
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
def
StopGrabbing
(
self
):
if
not
self
.
hasManager
():
return
if
self
.
Manager
.
IsGrabbing
():
self
.
Manager
.
StopGrabbing
()
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
def
isBayer
(
self
)
->
bool
:
return
SystemConfig
.
isBayer
()
def
isMoons
(
self
)
->
bool
:
return
SystemConfig
.
isMoons
()
def
isOther
(
self
)
->
bool
:
return
SystemConfig
.
isOther
()
def
GrabFrame
(
self
)
->
np
.
ndarray
:
result_image
:
np
.
ndarray
=
None
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
self
.
initContext
()
if
not
self
.
hasModel
:
return
result_image
if
self
.
Parameter
.
IsOpen
:
try
:
converter
=
pylon
.
ImageFormatConverter
()
#
converter
.
OutputBitAlignment
=
pylon
.
OutputBitAlignment_MsbAligned
#
converter
.
OutputPixelFormat
=
pylon
.
PixelType_RGB8packed
#
self
.
Manager
.
StartGrabbingMax
(
int
(
self
.
Model
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
self
.
Model
.
ExposureTime
))
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
result_image
=
converter
.
Convert
(
ImageFrame
)
.
GetArray
()
.
copy
()
except
Exception
as
e
:
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
result_image
def
GrabImage
(
self
)
->
np
.
ndarray
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
result_image
:
np
.
ndarray
=
None
self
.
initContext
()
if
not
self
.
hasModel
:
return
result_image
if
self
.
Parameter
.
IsOpen
and
self
.
Parameter
.
IsGrabbing
:
try
:
converter
=
pylon
.
ImageFormatConverter
()
#
converter
.
OutputBitAlignment
=
pylon
.
OutputBitAlignment_MsbAligned
#
converter
.
OutputPixelFormat
=
pylon
.
PixelType_RGB8packed
#
self
.
Manager
.
StartGrabbingMax
(
int
(
self
.
Model
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
self
.
Model
.
ExposureTime
))
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
result_image
=
converter
.
Convert
(
ImageFrame
)
.
GetArray
()
.
copy
()
except
Exception
as
e
:
logCAMERA
<<
AppUtils
.
toString
(
e
)
# logCAMERA << f"读取图像 {'成功' if result_image is not None else '失败'}"
return
result_image
def
GetImage
(
self
,
request
:
CameraRequest
)
->
CameraRequest
:
if
not
isinstance
(
request
,
CameraRequest
):
return
request
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
result_image
:
np
.
ndarray
=
None
request
.
StartTime
=
Qt
.
QDateTime
.
currentDateTime
()
self
.
initContext
()
if
not
self
.
hasModel
:
request
.
ImageSource
=
result_image
return
request
if
self
.
Parameter
.
IsOpen
and
self
.
Parameter
.
IsGrabbing
:
try
:
converter
=
pylon
.
ImageFormatConverter
()
#
converter
.
OutputBitAlignment
=
pylon
.
OutputBitAlignment_MsbAligned
#
converter
.
OutputPixelFormat
=
pylon
.
PixelType_RGB8packed
#
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
self
.
Model
.
ExposureTime
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
result_image
=
converter
.
Convert
(
ImageFrame
)
.
GetArray
()
.
copy
()
except
Exception
as
e
:
logCAMERA
<<
AppUtils
.
toString
(
e
)
request
.
FinishTime
=
Qt
.
QDateTime
.
currentDateTime
()
request
.
ImageSource
=
result_image
# logCAMERA << f"读取图像 {'成功' if result_image is not None else '失败'}"
return
request
def
GetQImage
(
self
)
->
Qt
.
QImage
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
result_image
:
np
.
ndarray
=
None
if
not
self
.
hasModel
:
return
Qt
.
QImage
()
if
self
.
Parameter
.
IsOpen
:
try
:
converter
=
pylon
.
ImageFormatConverter
()
#
converter
.
OutputBitAlignment
=
pylon
.
OutputBitAlignment_MsbAligned
#
converter
.
OutputPixelFormat
=
pylon
.
PixelType_RGB8packed
#
self
.
Manager
.
StartGrabbingMax
(
int
(
self
.
Model
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
self
.
Model
.
ExposureTime
))
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
result_image
=
converter
.
Convert
(
ImageFrame
)
.
GetArray
()
.
copy
()
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
# logCAMERA << f"读取图像 {'成功' if result_image is not None else '失败'}"
if
result_image
is
not
None
:
w
:
int
=
result_image
.
shape
[
1
]
h
:
int
=
result_image
.
shape
[
0
]
return
ImageUtils
.
cv2_to_QImage
(
result_image
,
w
,
h
)
return
Qt
.
QImage
()
async
def
GetMat
(
self
)
->
np
.
ndarray
:
result_image
=
self
.
GetNumpy
()
return
result_image
def
GetNumpy
(
self
,
isMono
:
bool
=
True
,
classifier
:
str
=
'Aberration'
)
->
np
.
ndarray
:
result_image
:
np
.
ndarray
=
None
if
not
self
.
hasModel
:
return
result_image
if
self
.
hasManager
()
and
self
.
Manager
.
IsOpen
():
try
:
ImageFrame
:
pylon
.
GrabResult
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
ExposureTime
:
int
isMono
=
self
.
Model
.
PixelFormat
==
'Mono8'
if
isMono
:
if
self
.
isAberration
(
classifier
):
ExposureTime
=
self
.
Model
.
AberrationExposureTime
elif
self
.
isKaryotyping
(
classifier
):
ExposureTime
=
self
.
Model
.
KaryotypingExposureTime
elif
self
.
isMicronucleus
(
classifier
):
ExposureTime
=
self
.
Model
.
MicronucleusExposureTime
else
:
ExposureTime
=
self
.
Model
.
ExposureTime
else
:
if
self
.
isAberration
(
classifier
):
ExposureTime
=
self
.
Model
.
AberrationExposureTime
elif
self
.
isKaryotyping
(
classifier
):
ExposureTime
=
self
.
Model
.
KaryotypingExposureTime
elif
self
.
isMicronucleus
(
classifier
):
ExposureTime
=
self
.
Model
.
MicronucleusExposureTime
# isMono = False
else
:
ExposureTime
=
self
.
Model
.
MicronucleusExposureTime
# isMono = False
try
:
if
int
(
self
.
Manager
.
ExposureTime
.
Value
)
!=
ExposureTime
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
except
Exception
as
e
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
# if not self.Manager.IsGrabbing():
# self.Manager.StartGrabbing(pylon.GrabStrategy_LatestImages)
if
self
.
IsGrabbing
():
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
# if not IsGrabbing:
# self.Manager.StopGrabbing()
else
:
self
.
Manager
.
StartGrabbingMax
(
int
(
self
.
Model
.
ImageCount
))
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
))
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
result_image
def
CameraReOpen
(
self
,
level
:
int
,
timeOut
:
int
=
1000
):
self
.
Close
(
timeOut
)
self
.
deleManager
()
self
.
CameraOpen
(
level
,
timeOut
)
def
StartFocusing
(
self
,
level
:
int
,
timeOut
:
int
=
1000
):
self
.
Objective
=
level
if
not
self
.
isCorrect
():
self
.
CameraReOpen
(
level
)
if
not
self
.
IsOpen
():
return
if
not
self
.
Manager
.
IsGrabbing
():
self
.
Manager
.
StartGrabbing
(
pylon
.
GrabStrategy_LatestImages
)
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
def
StopFocusing
(
self
):
if
not
self
.
IsOpen
():
return
if
self
.
IsGrabbing
():
self
.
Manager
.
StopGrabbing
()
self
.
Parameter
.
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
def
GetFocusingNumpy
(
self
,
isMono
:
bool
=
True
)
->
np
.
ndarray
:
result_image
:
np
.
ndarray
=
None
source_image
:
np
.
ndarray
=
None
if
not
self
.
hasModel
or
not
self
.
hasManager
():
return
result_image
try
:
ExposureTime
:
int
=
self
.
Model
.
ExposureTime
try
:
if
int
(
self
.
Manager
.
ExposureTime
.
Value
)
!=
ExposureTime
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
except
Exception
as
e
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
_isMono
:
bool
=
self
.
Model
.
isMono
()
if
self
.
Manager
.
IsGrabbing
():
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
_isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
else
:
self
.
Manager
.
StartGrabbingMax
(
int
(
self
.
Model
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
))
if
ImageFrame
is
not
None
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
_isMono
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
result_image
def
GetFocusingData
(
self
,
classifier
:
str
=
'Aberration'
)
->
np
.
ndarray
:
result_image
:
np
.
ndarray
=
None
source_image
:
np
.
ndarray
=
None
if
not
self
.
hasModel
or
not
self
.
hasManager
():
return
result_image
try
:
ExposureTime
:
int
isMono
:
bool
=
True
if
self
.
isAberration
(
classifier
):
ExposureTime
=
self
.
Model
.
AberrationExposureTime
elif
self
.
isMicronucleus
(
classifier
):
ExposureTime
=
self
.
Model
.
MicronucleusExposureTime
isMono
=
False
elif
self
.
isKaryotyping
(
classifier
):
ExposureTime
=
self
.
Model
.
KaryotypingExposureTime
else
:
ExposureTime
=
self
.
Model
.
ExposureTime
try
:
if
int
(
self
.
Manager
.
ExposureTime
.
Value
)
!=
ExposureTime
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
except
Exception
as
e
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
if
not
self
.
Manager
.
IsGrabbing
():
self
.
Manager
.
StartGrabbing
(
pylon
.
GrabStrategy_LatestImages
)
if
self
.
Manager
.
IsGrabbing
():
try
:
if
int
(
self
.
Manager
.
ExposureTime
.
Value
)
!=
ExposureTime
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
except
Exception
as
e
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
result_image
def
GetRequestData
(
self
,
request
:
CameraRequest
,
classifier
:
str
=
'Aberration'
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
camera
:
CameraRequest
if
isinstance
(
request
,
CameraRequest
):
if
not
request
.
has_StartTime
:
request
.
StartTime
=
Qt
.
QDateTime
.
currentDateTime
()
request
.
ImageSource
=
self
.
GetNumpyData
(
classifier
)
request
.
FinishTime
=
Qt
.
QDateTime
.
currentDateTime
()
isWrong
=
RECODE_SUCCEED
if
request
.
hasImageSource
else
RECODE_FAILURE
return
isWrong
def
GetNumpyData
(
self
,
classifier
:
str
=
'Aberration'
)
->
np
.
ndarray
:
result_image
:
np
.
ndarray
=
None
if
not
self
.
hasModel
:
return
result_image
if
self
.
Parameter
.
IsOpen
:
try
:
ImageFrame
:
pylon
.
GrabResult
ExposureTime
:
int
isMono
:
bool
=
True
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
if
self
.
isAberration
(
classifier
):
ExposureTime
=
self
.
Model
.
AberrationExposureTime
elif
self
.
isMicronucleus
(
classifier
):
ExposureTime
=
self
.
Model
.
MicronucleusExposureTime
isMono
=
False
elif
self
.
isKaryotyping
(
classifier
):
ExposureTime
=
self
.
Model
.
KaryotypingExposureTime
else
:
ExposureTime
=
self
.
Model
.
ExposureTime
try
:
if
int
(
self
.
Manager
.
ExposureTime
.
Value
)
!=
ExposureTime
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
except
Exception
as
e
:
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
if
not
self
.
Manager
.
IsGrabbing
():
self
.
Manager
.
StartGrabbing
(
pylon
.
GrabStrategy_LatestImages
)
if
self
.
IsGrabbing
():
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
result_image
def
ImageToColor
(
self
,
image
:
np
.
ndarray
,
pixel_fmt
:
str
,
isMono
:
bool
=
False
)
->
np
.
ndarray
:
img
:
np
.
ndarray
=
None
try
:
if
pixel_fmt
==
'Mono8'
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_GRAY2RGB
)
elif
pixel_fmt
==
'BayerGR8'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GR2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GR2RGB
)
elif
pixel_fmt
==
'BayerRG8'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_RG2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_RG2RGB
)
elif
pixel_fmt
==
'BayerGB8'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GB2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2RGB
)
elif
pixel_fmt
==
'BayerBG8'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2RGB
)
elif
pixel_fmt
==
'BayerGR12'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GR2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GR2RGB
)
elif
pixel_fmt
==
'BayerGR12p'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GR2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GR2RGB
)
elif
pixel_fmt
==
'BayerRG12'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_RG2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_RG2RGB
)
elif
pixel_fmt
==
'BayerRG12p'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_RG2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_RG2RGB
)
elif
pixel_fmt
==
'BayerGB12'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GB2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GB2RGB
)
elif
pixel_fmt
==
'BayerGB12p'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GB2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_GB2RGB
)
elif
pixel_fmt
==
'BayerBG12'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2RGB
)
elif
pixel_fmt
==
'BayerBG12p'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BAYER_BG2RGB
)
elif
pixel_fmt
==
'RGB8'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_RGB2GRAY
)
else
:
img
=
image
elif
pixel_fmt
==
'BGR8'
:
if
isMono
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BGR2GRAY
)
else
:
img
=
cv2
.
cvtColor
(
image
,
cv2
.
COLOR_BGR2RGB
)
if
img
is
not
None
and
len
(
img
.
shape
)
<=
2
:
img
=
np
.
stack
((
img
,
)
*
3
,
axis
=
-
1
)
pass
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
img
def
GetFrame
(
self
,
request
:
CameraRequest
)
->
CameraRequest
:
if
not
isinstance
(
request
,
CameraRequest
):
return
request
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
result_image
:
np
.
ndarray
=
None
request
.
StartTime
=
Qt
.
QDateTime
.
currentDateTime
()
if
not
self
.
hasModel
:
request
.
ImageSource
=
result_image
return
request
if
self
.
Parameter
.
IsOpen
:
try
:
self
.
Manager
.
StartGrabbingMax
(
int
(
self
.
Model
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
self
.
Model
.
ExposureTime
))
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
ObjectiveLevel
.
isMono
(
self
.
Model
.
Level
))
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
request
.
FinishTime
=
Qt
.
QDateTime
.
currentDateTime
()
request
.
ImageSource
=
result_image
# logCAMERA << f"读取图像 {'成功' if result_image is not None else '失败'}"
return
request
def
GetRequest
(
self
,
request
:
CameraRequest
,
isMono
:
bool
=
True
,
classifier
:
str
=
'Aberration'
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
camera
:
CameraRequest
if
isinstance
(
request
,
CameraRequest
):
if
not
request
.
has_StartTime
:
request
.
StartTime
=
Qt
.
QDateTime
.
currentDateTime
()
request
.
ImageSource
=
self
.
GetNumpy
(
isMono
,
classifier
)
request
.
FinishTime
=
Qt
.
QDateTime
.
currentDateTime
()
isWrong
=
RECODE_SUCCEED
if
request
.
hasImageSource
else
RECODE_FAILURE
return
isWrong
def
RequestMultiple
(
self
,
parameter
:
CameraInterface
,
ExposureTimes
:
list
[
int
])
->
list
[
np
.
ndarray
]:
images
:
list
[
np
.
ndarray
]
=
self
.
RequestMultipleNumpy
(
parameter
,
ExposureTimes
)
self
.
StopGrabbing
()
self
.
setRequestParameter
(
self
.
Manager
,
parameter
,
parameter
.
ExposureTime
)
return
images
def
RequestMultipleArray
(
self
,
parameter
:
CameraInterface
,
ExposureTimes
:
list
[
int
],
ImageArray
:
list
[
np
.
ndarray
],
isMono
:
bool
=
True
):
if
parameter
is
None
:
return
self
.
ChangedCameraParameter
(
self
.
Manager
,
parameter
)
self
.
RequestMultipleNumpyArray
(
parameter
,
ExposureTimes
,
ImageArray
,
isMono
)
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
parameter
.
ExposureTime
,
self
.
Model
)
return
def
RequestNumpy
(
self
,
parameter
:
CameraInterface
,
isMono
:
bool
=
True
)
->
np
.
ndarray
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
result_image
:
np
.
ndarray
=
None
if
not
isinstance
(
parameter
,
CameraInterface
):
return
result_image
ExposureTime
:
int
=
int
(
parameter
.
ExposureTime
)
if
not
isinstance
(
ExposureTime
,
(
float
,
int
)):
return
result_image
if
self
.
Parameter
.
IsOpen
:
try
:
result_image
=
None
IsGrabbing
=
self
.
Manager
.
IsGrabbing
()
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
if
self
.
Manager
.
IsGrabbing
():
if
not
self
.
Manager
.
IsGrabbing
():
self
.
Manager
.
StartGrabbing
(
pylon
.
GrabStrategy_LatestImages
)
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
else
:
self
.
Manager
.
StartGrabbingMax
(
int
(
parameter
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
))
if
ImageFrame
is
not
None
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
result_image
def
RequestMultipleImage
(
self
,
parameter
:
CameraInterface
,
ExposureTime
:
int
,
isMono
:
bool
=
True
)
->
np
.
ndarray
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
if
not
isinstance
(
parameter
,
CameraInterface
)
or
not
isinstance
(
ExposureTime
,
(
int
,
float
)):
return
None
result_image
:
np
.
ndarray
=
None
if
self
.
Parameter
.
IsOpen
:
try
:
result_image
=
None
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
if
self
.
Manager
.
IsGrabbing
():
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
else
:
self
.
Manager
.
StartGrabbingMax
(
int
(
parameter
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
))
if
ImageFrame
is
not
None
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
if
result_image
is
not
None
:
if
len
(
result_image
.
shape
)
==
2
:
result_image
=
np
.
stack
((
result_image
,)
*
3
,
axis
=-
1
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
result_image
def
RequestMultipleNumpy
(
self
,
parameter
:
CameraInterface
,
ExposureTimes
:
list
[
int
])
->
list
[
np
.
ndarray
]:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
if
not
isinstance
(
parameter
,
CameraInterface
)
or
not
isinstance
(
ExposureTimes
,
list
)
or
len
(
ExposureTimes
)
<=
0
:
return
None
isMono
:
bool
=
parameter
.
isMono
()
images
:
list
[
np
.
ndarray
]
=
[]
ImageFrame
:
pylon
.
GrabResult
Index
:
int
=
0
MaxLength
:
int
=
len
(
ExposureTimes
)
ImageFrame
:
pylon
.
GrabResult
result_image
:
np
.
ndarray
=
None
waittimes
:
int
ExposureTime
:
int
endtime
:
Qt
.
QDateTime
converter
:
pylon
.
ImageFormatConverter
if
self
.
Parameter
.
IsOpen
:
try
:
for
Index
,
ExposureTime
in
enumerate
(
ExposureTimes
):
result_image
=
None
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
if
self
.
Manager
.
IsGrabbing
():
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
else
:
self
.
Manager
.
StartGrabbingMax
(
int
(
parameter
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
))
if
ImageFrame
is
not
None
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
images
.
append
(
result_image
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
return
images
def
RequestMultipleNumpyArray
(
self
,
parameter
:
CameraInterface
,
ExposureTimes
:
list
[
int
],
ImageArray
:
list
[
np
.
ndarray
],
isMono
:
bool
=
True
)
->
list
[
np
.
ndarray
]:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
if
not
isinstance
(
parameter
,
CameraInterface
)
or
not
isinstance
(
ExposureTimes
,
list
)
or
len
(
ExposureTimes
)
<=
0
:
return
if
not
isinstance
(
ImageArray
,
list
):
return
if
not
self
.
Parameter
.
IsOpen
:
return
ImageFrame
:
pylon
.
GrabResult
#
Index
:
int
=
0
#
MaxLength
:
int
=
len
(
ExposureTimes
)
#
ImageFrame
:
pylon
.
GrabResult
#
result_image
:
np
.
ndarray
=
None
#
waittimes
:
int
#
ExposureTime
:
int
#
endtime
:
Qt
.
QDateTime
#
converter
:
pylon
.
ImageFormatConverter
#
if
self
.
Parameter
.
IsOpen
:
try
:
for
Index
,
ExposureTime
in
enumerate
(
ExposureTimes
):
result_image
=
None
self
.
ChangedCameraExposureTime
(
self
.
Manager
,
ExposureTime
,
self
.
Model
)
if
self
.
Manager
.
IsGrabbing
():
waittimes
=
int
(
ExposureTime
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
Manager
.
IsGrabbing
():
ImageFrame
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
),
pylon
.
TimeoutHandling_ThrowException
)
if
isinstance
(
ImageFrame
,
pylon
.
GrabResult
)
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
ImageArray
.
append
(
result_image
)
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
else
:
self
.
Manager
.
StartGrabbingMax
(
int
(
parameter
.
ImageCount
))
ImageFrame
:
pylon
.
GrabResult
=
self
.
Manager
.
RetrieveResult
(
int
(
ExposureTime
))
if
ImageFrame
is
not
None
and
ImageFrame
.
GrabSucceeded
():
source_image
=
ImageFrame
.
GetArray
()
result_image
=
self
.
ImageToColor
(
source_image
,
self
.
Model
.
PixelFormat
,
isMono
)
ImageArray
.
append
(
result_image
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
# self.StopGrabbing()
return
def
CameraRequest
(
self
,
model
:
CameraRequest
,
parameter
:
CameraInterface
):
isWrong
:
int
=
RECODE_FAILURE
camera
:
CameraRequest
if
isinstance
(
model
,
CameraRequest
):
camera
=
model
else
:
return
isWrong
camera
.
StartTime
=
Qt
.
QDateTime
.
currentDateTime
()
camera
.
ImageSource
=
self
.
RequestNumpy
(
parameter
)
isWrong
=
RECODE_SUCCEED
camera
.
FinishTime
=
Qt
.
QDateTime
.
currentDateTime
()
return
isWrong
def
GetStatus
(
self
)
->
CameraInterface
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
Status
:
CameraInterface
=
SystemConfig
.
getCameraModel
(
self
.
Objective
)
if
self
.
hasManager
():
self
.
getCameraStatus
(
self
.
Manager
,
Status
)
self
.
CameraGetStatus
.
emit
(
Status
)
logCAMERA
<<
f
"获取相机状态"
return
Status
def
setGain
(
self
,
value
):
try
:
self
.
Manager
.
Gain
.
Value
=
float
(
value
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
def
setGamma
(
self
,
value
):
try
:
self
.
Manager
.
Gamma
.
Value
=
float
(
value
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
def
setExposureTime
(
self
,
value
):
try
:
self
.
Manager
.
ExposureTime
.
Value
=
float
(
value
)
# 曝光时间
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
def
setImageROI
(
self
,
offsetX
,
offsetY
,
width
,
height
,
CenterX
:
bool
=
True
,
CenterY
:
bool
=
True
):
try
:
# 读取相机最大宽度和高度
MAX_W
:
int
=
int
(
self
.
Manager
.
WidthMax
.
Value
)
MAX_H
:
int
=
int
(
self
.
Manager
.
HeightMax
.
Value
)
ROI_W
:
int
=
offsetX
*
2
+
width
ROI_H
:
int
=
offsetY
*
2
+
height
_OffsetX
:
int
=
int
(
offsetX
)
if
ROI_W
<=
MAX_W
and
ROI_H
<=
MAX_H
else
self
.
Parameter
.
OffsetX
_OffsetY
:
int
=
int
(
offsetY
)
if
ROI_W
<=
MAX_W
and
ROI_H
<=
MAX_H
else
self
.
Parameter
.
OffsetY
_Dst_W
:
int
=
int
(
width
)
if
ROI_W
<=
MAX_W
and
ROI_H
<=
MAX_H
else
self
.
Parameter
.
Width
_Dst_H
:
int
=
int
(
height
)
if
ROI_W
<=
MAX_W
and
ROI_H
<=
MAX_H
else
self
.
Parameter
.
Height
self
.
Manager
.
OffsetX
.
Value
=
_OffsetX
self
.
Manager
.
OffsetY
.
Value
=
_OffsetY
self
.
Manager
.
Width
.
Value
=
_Dst_W
self
.
Manager
.
Height
.
Value
=
_Dst_H
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
def
setPixelFormat
(
self
,
value
:
int
):
try
:
self
.
Manager
.
Gamma
.
Value
=
int
(
value
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
def
initManager
(
self
,
context
:
CameraContext
=
None
,
**
args
):
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
self
.
initContext
()
try
:
if
not
self
.
initTlFactory
():
return
if
not
self
.
initDevices
():
return
if
self
.
isCorrect
():
return
if
not
self
.
initDeviceInfo
():
return
# print(f'{self.__class__.__name__} load {self.DeviceInfo.GetModelName()} {self.DeviceInfo.GetFullName()}')
self
.
Manager
=
pylon
.
InstantCamera
(
self
.
TlFactory
.
CreateDevice
(
self
.
DeviceInfo
.
GetFullName
()))
except
Exception
as
e
:
error
:
str
=
AppUtils
.
toString
(
e
)
logCAMERA
<<
error
self
.
Manager
=
None
# self.BaslerInfo = None
# self.TlFactory = None
def
deleManager
(
self
):
try
:
self
.
StopGrabbing
()
self
.
Close
()
if
self
.
hasManager
():
del
self
.
Manager
except
Exception
as
e
:
pass
self
.
Manager
=
None
self
.
TlFactory
=
None
self
.
DeviceInfo
=
None
pass
def
initCameraConfig
(
self
):
if
not
self
.
hasManager
()
or
not
self
.
hasDeviceInfo
or
not
self
.
hasModel
:
return
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
try
:
MAX_W
:
int
=
int
(
self
.
Manager
.
WidthMax
.
Value
)
MAX_H
:
int
=
int
(
self
.
Manager
.
HeightMax
.
Value
)
try
:
self
.
Manager
.
Height
.
Value
=
int
(
self
.
Model
.
Height
)
if
int
(
self
.
Model
.
Height
)
<=
MAX_H
else
int
(
MAX_H
)
# 宽度
self
.
Manager
.
Width
.
Value
=
int
(
self
.
Model
.
Width
)
if
int
(
self
.
Model
.
Width
)
<=
MAX_W
else
int
(
MAX_W
)
# 高度
self
.
Manager
.
CenterX
.
Value
=
bool
(
self
.
Model
.
CenterX
)
if
self
.
Model
.
hasCenterX
else
True
# X距中
self
.
Manager
.
CenterY
.
Value
=
bool
(
self
.
Model
.
CenterY
)
if
self
.
Model
.
hasCenterY
else
True
# X距中
self
.
Manager
.
ReverseX
.
Value
=
bool
(
self
.
Model
.
ReverseX
)
if
self
.
Model
.
hasReverseX
else
False
# X镜像
self
.
Manager
.
ReverseY
.
Value
=
bool
(
self
.
Model
.
ReverseY
)
if
self
.
Model
.
hasReverseY
else
False
# Y镜像
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasPixelFormat
:
try
:
self
.
Manager
.
PixelFormat
.
Value
=
str
(
self
.
Model
.
PixelFormat
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasExposureTime
:
try
:
self
.
Manager
.
ExposureTime
.
Value
=
float
(
self
.
Model
.
ExposureTime
)
# 曝光时间
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasGain
:
try
:
self
.
Manager
.
Gain
.
Value
=
float
(
self
.
Model
.
Gain
)
# 增益数值
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasGamma
:
try
:
self
.
Manager
.
Gamma
.
Value
=
float
(
self
.
Model
.
Gamma
)
# 伽马数值
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasBlackLevel
:
try
:
self
.
Manager
.
BlackLevel
.
Value
=
float
(
self
.
Model
.
BlackLevel
)
# 黑电平值
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasExposureMode
:
try
:
self
.
Manager
.
ExposureMode
.
IntValue
=
int
(
self
.
Model
.
ExposureMode
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasTriggerMode
:
try
:
self
.
Manager
.
TriggerMode
.
IntValue
=
int
(
self
.
Model
.
TriggerMode
)
# ('Off', 'On')
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasShutterMode
:
try
:
self
.
Manager
.
ShutterMode
.
IntValue
=
int
(
self
.
Model
.
ShutterMode
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasGainAuto
:
try
:
self
.
Manager
.
GainAuto
.
IntValue
=
int
(
self
.
Model
.
GainAuto
)
# 自动增益
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
DeviceInfo
.
GetModelName
()
==
SystemConfig
.
BayerCameraName
:
'''设置彩色相机'''
if
self
.
Model
.
hasLightSourcePreset
:
try
:
self
.
Manager
.
LightSourcePreset
.
Value
=
str
(
self
.
Model
.
LightSourcePreset
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
ColorParameter
:
CameraColorModel
=
CameraColorModel
.
getConfig
(
self
.
Model
.
Level
)
self
.
Manager
.
BalanceRatioSelector
.
IntValue
=
0
self
.
Manager
.
BalanceRatio
.
Value
=
ColorParameter
.
BalanceRatio0
self
.
Manager
.
BalanceRatioSelector
.
IntValue
=
1
self
.
Manager
.
BalanceRatio
.
Value
=
ColorParameter
.
BalanceRatio1
self
.
Manager
.
BalanceRatioSelector
.
IntValue
=
2
self
.
Manager
.
BalanceRatio
.
Value
=
ColorParameter
.
BalanceRatio2
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
0
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue0
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
1
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue1
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
2
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue2
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
3
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue0
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
4
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue1
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
5
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue2
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
6
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue20
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
7
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue21
)
self
.
Manager
.
ColorTransformationValueSelector
.
IntValue
=
int
(
8
)
self
.
Manager
.
ColorTransformationValue
.
IntValue
=
int
(
ColorParameter
.
ColorTransformationValue22
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
except
Exception
as
e
:
logCAMERA
<<
AppUtils
.
toString
(
e
)
else
:
logCAMERA
<<
"设置相机参数"
def
initCameraGama
(
self
):
if
not
self
.
IsOpen
():
return
try
:
if
self
.
Model
.
hasGain
:
try
:
self
.
Manager
.
Gain
.
Value
=
float
(
self
.
Model
.
Gain
)
# 增益数值
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasGamma
:
try
:
self
.
Manager
.
Gamma
.
Value
=
float
(
self
.
Model
.
Gamma
)
# 伽马数值
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
if
self
.
Model
.
hasBlackLevel
:
try
:
self
.
Manager
.
BlackLevel
.
Value
=
float
(
self
.
Model
.
BlackLevel
)
# 黑电平值
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
def
WhiteAutoOnce
(
self
):
if
self
.
hasManager
()
and
self
.
IsOpen
():
try
:
self
.
Manager
.
BalanceWhiteAuto
.
Value
=
'Once'
#('Off', 'Once', 'Continuous')
AppTimeLoop
.
delay
(
2000
)
self
.
Manager
.
BalanceWhiteAuto
.
Value
=
'Off'
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
@
staticmethod
def
getCameraStatus
(
camera
:
pylon
.
InstantCamera
,
Status
:
CameraInterface
):
if
not
isinstance
(
camera
,
pylon
.
InstantCamera
)
or
not
isinstance
(
Status
,
CameraInterface
):
return
# 读取相机状态
try
:
Status
.
ExposureMode
=
camera
.
ExposureMode
.
Value
Status
.
TriggerMode
=
camera
.
TriggerMode
.
Value
Status
.
ShutterMode
=
camera
.
ShutterMode
.
Value
Status
.
ExposureAuto
=
camera
.
ExposureAuto
.
Value
Status
.
GainAuto
=
camera
.
GainAuto
.
Value
Status
.
Width
=
camera
.
Width
.
Value
Status
.
Height
=
camera
.
Height
.
Value
Status
.
BalanceWhiteAuto
=
camera
.
BalanceWhiteAuto
.
Value
Status
.
ImageCount
=
camera
.
ImageCount
.
Value
Status
.
ExposureTime
=
camera
.
ExposureTime
.
Value
Status
.
R_BalanceRatio
=
camera
.
R_BalanceRatio
.
Value
Status
.
G_BalanceRatio
=
camera
.
G_BalanceRatio
.
Value
Status
.
B_BalanceRatio
=
camera
.
B_BalanceRatio
.
Value
Status
.
Gain
=
camera
.
Gain
.
Value
Status
.
Gamma
=
camera
.
Gamma
.
Value
Status
.
BlackLevel
=
camera
.
BlackLevel
.
Value
Status
.
Axis_Offset_X
=
camera
.
Axis_Offset_X
.
Value
Status
.
Axis_Offset_Y
=
camera
.
Axis_Offset_Y
.
Value
Status
.
Image_Offset_W
=
camera
.
Image_Offset_W
.
Value
Status
.
Image_Offset_H
=
camera
.
Image_Offset_H
.
Value
Status
.
PixelFormat
=
camera
.
PixelFormat
.
Value
Status
.
LightSourcePreset
=
camera
.
LightSourcePreset
.
Value
Status
.
CenterX
=
camera
.
CenterX
.
Value
Status
.
CenterY
=
camera
.
CenterY
.
Value
Status
.
ReverseX
=
camera
.
ReverseX
.
Value
Status
.
ReverseY
=
camera
.
ReverseY
.
Value
except
Exception
as
e
:
from
AppLog.logHelper
import
logCAMERA
from
AppUtils.AppUtils
import
AppUtils
logCAMERA
<<
AppUtils
.
toString
(
e
)
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'Manager'
)
and
self
.
Manager
is
not
None
def
hasParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'Parameter'
)
and
isinstance
(
self
.
Parameter
,
CameraContext
)
@
property
def
hasDeviceInfo
(
self
)
->
bool
:
return
hasattr
(
self
,
'DeviceInfo'
)
and
isinstance
(
self
.
DeviceInfo
,
pylon
.
DeviceInfo
)
@
property
def
hasTlFactory
(
self
)
->
bool
:
return
hasattr
(
self
,
'TlFactory'
)
and
isinstance
(
self
.
TlFactory
,
pylon
.
TlFactory
)
@
property
def
hasDevices
(
self
)
->
bool
:
return
hasattr
(
self
,
'Devices'
)
and
isinstance
(
self
.
Devices
,
(
list
,
tuple
))
@
property
def
hasObjective
(
self
)
->
bool
:
return
hasattr
(
self
,
'Objective'
)
and
isinstance
(
self
.
Objective
,
int
)
@
property
def
hasModel
(
self
)
->
bool
:
return
hasattr
(
self
,
'Model'
)
and
isinstance
(
self
.
Model
,
CameraInterface
)
# AppCamera: CameraImpl = CameraImpl.GetInstance()
\ No newline at end of file
AppCore/AppImplsbak/HitBotImpl.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: HitBotImpl.py
@DateTime: 2025/4/8 22:16
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
,
sip
import
ctypes
from
ctypes
import
*
from
abc
import
abstractmethod
from
AppInterfaces.ImplInterface
import
(
ImplInterface
,
AppTimeLoop
,
AppConvert
,
AppUtils
,
log_exceptions
)
from
AppSettings.Settings
import
(
RECODE_FAILURE
,
RECODE_SUCCEED
)
from
AppUtils.Float
import
Float
from
AppInterfaces.SingletonInterface
import
SingletonInterface
from
AppCore.Levels
import
*
from
AppCore.AppContextModels.HitBotContext
import
HitBotContext
from
AppCore.AppContextModels.HitBotData
import
HitBotData
from
AppSettings.AppSetting
import
AppSetting
,
AppConfig
from
AppInterfaces.globalSlot
import
globalSlot
,
AppSlot
from
AppCore.ImplInterfaces
import
HitBotImplInterface
from
AppCore.AppDBModels.DBModels
import
*
HITBOT_MOVE_MAX_WAIT_TIMES
:
int
=
30000
HITBOT_MOVE_MIN_WAIT_TIMES
:
int
=
3000
HITBOT_DEFAULT_DELAY
:
int
=
200
LIB_DEFAULT_LOAD_WAIT_TIMES
:
int
=
2000
LIB_DEFAULT_DELAY_TIMES
:
int
=
500
HITBOT_CHECK_DELAY
:
int
=
50
class
HitBotImpl
(
Qt
.
QObject
,
HitBotImplInterface
,
SingletonInterface
):
Manager
:
Qt
.
QLibrary
Parameter
:
HitBotContext
UpdateStatus
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
,
object
)
IOLocker
:
Qt
.
QReadWriteLock
=
Qt
.
QReadWriteLock
()
Locker
:
Qt
.
QMutex
=
Qt
.
QMutex
()
@
classmethod
def
GetInstance
(
cls
,
*
args
,
**
kwargs
)
->
'HitBotImpl'
:
return
super
(
HitBotImpl
,
cls
)
.
GetInstance
(
*
args
,
**
kwargs
)
def
__init__
(
self
,
context
:
HitBotContext
=
None
,
parent
:
Qt
.
QObject
=
None
):
super
(
HitBotImpl
,
self
)
.
__init__
(
parent
=
parent
)
self
.
initImpl
(
context
,
parent
)
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
and
self
.
hasParameter
def
isEnabled
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
Manager
.
isLoaded
()
def
isDisable
(
self
)
->
bool
:
return
not
self
.
isEnabled
()
def
setParameter
(
self
,
value
):
isOpen
:
bool
=
self
.
IsOpen
()
isEnabled
:
bool
=
self
.
isEnabled
()
if
isOpen
:
self
.
Close
()
if
isEnabled
:
self
.
UnLoadLibrary
()
self
.
initManager
(
value
)
if
isEnabled
:
self
.
LoadLibrary
()
if
isOpen
:
self
.
Open
()
def
initManager
(
self
,
context
:
object
,
**
args
):
from
AppSettings.AppSetting
import
AppSetting
,
AppConfig
if
not
self
.
hasParameter
or
self
.
Parameter
!=
context
:
self
.
Parameter
=
context
if
not
self
.
hasParameter
:
self
.
Parameter
=
AppConfig
.
hitBotConfig
if
not
self
.
hasManager
:
self
.
Manager
=
Qt
.
QLibrary
()
if
self
.
Manager
.
fileName
()
.
lower
()
!=
self
.
Parameter
.
absoluteFilePath
:
if
self
.
Manager
.
isLoaded
():
self
.
UnLoadLibrary
()
if
Qt
.
QLibrary
.
isLibrary
(
self
.
Parameter
.
absoluteFilePath
):
self
.
Manager
.
setFileName
(
self
.
Parameter
.
absoluteFilePath
)
def
deleManager
(
self
):
self
.
UnLoadLibrary
()
self
.
Manager
=
None
def
LoadLibrary
(
self
,
timeout
:
int
=
1000
)
->
int
:
waittimes
:
int
=
max
(
abs
(
timeout
),
LIB_DEFAULT_LOAD_WAIT_TIMES
)
if
not
self
.
isValid
():
if
not
self
.
hasParameter
:
self
.
Parameter
=
AppConfig
.
hitBotConfig
self
.
initManager
(
self
.
Parameter
if
self
.
hasParameter
else
None
)
if
not
self
.
isValid
()
or
not
self
.
hasManager
or
not
self
.
hasParameter
:
return
RECODE_FAILURE
if
self
.
isEnabled
():
if
self
.
Manager
.
fileName
()
.
lower
()
==
self
.
Parameter
.
absoluteFilePath
.
lower
():
self
.
Parameter
.
LibStatus
=
self
.
Manager
.
isLoaded
()
return
RECODE_SUCCEED
if
self
.
Parameter
.
LibStatus
else
RECODE_FAILURE
else
:
self
.
UnLoadLibrary
(
timeout
)
self
.
Parameter
.
LibStatus
=
False
self
.
Manager
.
setFileName
(
self
.
Parameter
.
absoluteFilePath
)
self
.
Manager
.
load
()
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
or
self
.
Parameter
.
LibStatus
:
break
self
.
Parameter
.
LibStatus
=
self
.
Manager
.
isLoaded
()
if
not
self
.
Parameter
.
LibStatus
:
self
.
Manager
.
setFileName
(
self
.
Parameter
.
absoluteFilePath
)
self
.
Manager
.
load
()
AppTimeLoop
.
processGlobalEvents
(
LIB_DEFAULT_DELAY_TIMES
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
LibStatus
else
RECODE_FAILURE
def
UnLoadLibrary
(
self
,
timeout
:
int
=
1000
)
->
int
:
waittimes
:
int
=
max
(
abs
(
timeout
),
LIB_DEFAULT_LOAD_WAIT_TIMES
)
if
not
self
.
isValid
():
if
not
self
.
hasParameter
:
self
.
Parameter
=
AppConfig
.
hitBotConfig
self
.
initManager
(
self
.
Parameter
if
self
.
hasParameter
else
None
)
if
not
self
.
isValid
()
or
not
self
.
hasManager
or
not
self
.
hasParameter
:
return
RECODE_SUCCEED
self
.
Parameter
.
LibStatus
=
self
.
Manager
.
isLoaded
()
if
not
self
.
Manager
.
isLoaded
():
self
.
Manager
.
deleteLater
()
self
.
Manager
=
None
AppTimeLoop
.
processGlobalEvents
(
LIB_DEFAULT_DELAY_TIMES
)
self
.
initManager
(
self
.
Parameter
if
self
.
hasParameter
else
None
)
return
RECODE_SUCCEED
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
or
not
self
.
Parameter
.
LibStatus
:
break
self
.
Parameter
.
LibStatus
=
self
.
Manager
.
isLoaded
()
if
self
.
Parameter
.
LibStatus
:
self
.
Manager
.
unload
()
AppTimeLoop
.
processGlobalEvents
(
LIB_DEFAULT_DELAY_TIMES
)
self
.
Manager
.
deleteLater
()
self
.
Manager
=
None
AppTimeLoop
.
processGlobalEvents
(
LIB_DEFAULT_DELAY_TIMES
)
self
.
initManager
(
self
.
Parameter
)
return
RECODE_SUCCEED
def
ReLoadLibrary
(
self
,
timeout
:
int
=
1000
)
->
int
:
self
.
UnLoadLibrary
(
timeout
)
return
self
.
LoadLibrary
(
timeout
)
@
log_exceptions
def
resolve
(
self
,
symbol
:
str
,
c_rec_type
,
*
c_args
):
if
self
.
isEnabled
()
and
not
AppConvert
.
isChinese
(
symbol
)
and
not
AppConvert
.
isEmpty
(
symbol
):
void_pointer
:
sip
.
voidptr
=
self
.
Manager
.
resolve
(
symbol
)
return
ctypes
.
CFUNCTYPE
(
c_rec_type
,
*
c_args
)(
void_pointer
.
__int__
())
return
None
@
staticmethod
def
copyHitBotData
(
src
:
HitBotData
,
dst
:
HitBotData
):
if
not
isinstance
(
src
,
HitBotData
)
or
not
isinstance
(
dst
,
HitBotData
):
return
for
_property
in
src
.
fields
:
setattr
(
dst
,
_property
,
getattr
(
src
,
_property
,
None
))
def
getHitBotData
(
self
)
->
HitBotData
:
self
.
flushProperty
()
return
HitBotData
.
instance
(
self
)
def
CurrentHitBotData
(
self
)
->
(
HitBotData
,
HitBotModel
):
data
:
HitBotData
=
HitBotData
.
instance
(
self
)
model
:
HitBotModel
=
HitBotModel
.
asHitBotData
(
self
)
return
data
,
model
def
asStatus
(
self
,
state
:
(
HitBotModelInterface
)):
self
.
flushProperty
()
if
isinstance
(
state
,
HitBotData
):
self
.
copyHitBotData
(
self
,
state
)
elif
isinstance
(
state
,
HitBotModel
,
HitBotModelInterface
):
state
.
asObject
(
self
)
pass
def
GetHitData
(
self
)
->
HitBotData
:
return
HitBotData
.
instance
(
self
)
def
GetHitPosition
(
self
)
->
(
HitBotData
,
HitBotModelInterface
):
data
:
HitBotData
=
HitBotData
.
instance
(
self
)
model
:
HitBotModel
=
HitBotModel
()
model
.
initProperty
()
model
.
movetype
=
HitBotMoveType
.
LMove_XYZR_G
model
.
xPosition
=
self
.
xPosition
model
.
yPosition
=
self
.
yPosition
model
.
zPosition
=
self
.
zPosition
model
.
rPosition
=
self
.
rPosition
model
.
efg_distance
=
self
.
efg_distance
return
data
,
model
def
GetHitModel
(
self
)
->
HitBotModelInterface
:
model
:
HitBotModel
=
HitBotModel
()
model
.
initProperty
()
model
.
movetype
=
HitBotMoveType
.
LMove_XYZR_G
model
.
xPosition
=
self
.
xPosition
model
.
yPosition
=
self
.
yPosition
model
.
zPosition
=
self
.
zPosition
model
.
rPosition
=
self
.
rPosition
model
.
efg_distance
=
self
.
efg_distance
return
model
pass
def
GetStatus
(
self
,
state
:
(
HitBotModelInterface
))
->
(
HitBotData
,
HitBotModel
):
self
.
flushProperty
()
data
:
HitBotData
model
:
HitBotModel
if
isinstance
(
state
,
HitBotData
):
self
.
copyHitBotData
(
self
,
state
)
data
=
state
model
=
HitBotModel
.
asHitBotData
(
self
)
elif
isinstance
(
state
,
HitBotModel
,
HitBotModelInterface
):
state
.
asObject
(
self
)
model
=
state
data
=
HitBotData
.
instance
(
self
)
else
:
data
=
HitBotData
.
instance
(
self
)
model
=
HitBotModel
.
asHitBotData
(
self
)
return
data
,
model
def
initImpl
(
self
,
context
:
HitBotContext
=
None
,
parent
:
Qt
.
QObject
=
None
):
self
.
initManager
(
context
)
self
.
Initialization
(
"HitBotImpl"
,
self
,
parent
)
def
initValue
(
self
):
super
(
HitBotImpl
,
self
)
.
initValue
()
self
.
initHitbotProperty
()
self
.
initEncodeProperty
()
self
.
initGripperProperty
()
self
.
ReLoadLibrary
()
def
initProperty
(
self
):
super
(
HitBotImpl
,
self
)
.
initProperty
()
self
.
initHitbotProperty
()
self
.
initEncodeProperty
()
self
.
initGripperProperty
()
def
deleProperty
(
self
):
super
(
HitBotImpl
,
self
)
.
deleProperty
()
self
.
initHitbotProperty
()
self
.
initEncodeProperty
()
self
.
initGripperProperty
()
def
deleValue
(
self
):
super
(
HitBotImpl
,
self
)
.
deleValue
()
self
.
Close
()
self
.
UnLoadLibrary
()
self
.
Manager
=
None
self
.
Parameter
=
None
self
.
initHitbotProperty
()
self
.
initEncodeProperty
()
self
.
initGripperProperty
()
def
Open
(
self
,
timeOut
:
int
=
10000
)
->
int
:
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
if
not
self
.
isValid
():
return
RECODE_FAILURE
if
not
self
.
isEnabled
():
self
.
ReLoadLibrary
(
timeOut
)
if
not
self
.
isEnabled
():
return
RECODE_FAILURE
waittimes
:
int
=
max
(
5000
,
timeOut
)
endtime
:
Qt
.
QDateTime
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
self
.
net_port_initial
()
Processes
:
list
[
dict
[
str
,
object
]]
=
AppUtils
.
getFilterProcesses
(
'server.exe'
)
serverPID
:
int
=
None
if
len
(
Processes
)
<=
0
else
Processes
[
0
]
.
get
(
'pid'
)
if
not
isinstance
(
serverPID
,
int
):
serverPID
=
AppUtils
.
start_process
(
"c:/Server/server.exe"
)
self
.
net_port_initial
()
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
self
.
flushProperty
()
if
self
.
is_connect
():
break
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
self
.
_get_scara_param
()
self
.
Parameter
.
IsOpen
=
self
.
IsOpen
()
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
if
self
.
isEnabled
():
if
self
.
IsInitialize
():
self
.
close_server
()
self
.
KillHitBotServer
()
# self.UnLoadLibrary(timeOut)
self
.
communicate_success
=
False
self
.
initial_finish
=
False
return
RECODE_SUCCEED
@
staticmethod
def
KillHitBotServer
():
Processes
:
list
[
dict
[
str
,
object
]]
=
AppUtils
.
getFilterProcesses
(
'server.exe'
)
for
item
in
Processes
:
AppUtils
.
terminate_process_by_pid
(
item
.
get
(
'pid'
,
None
))
def
IsOpen
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
communicate_success
def
IsStop
(
self
)
->
bool
:
return
self
.
IsOpen
()
and
self
.
is_stop
()
def
IsMoving
(
self
)
->
bool
:
return
self
.
IsOpen
()
and
not
self
.
is_stop
()
def
IsInitialize
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
isEnabled
()
and
self
.
initial_finish
def
initHitBot
(
self
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
()
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
if
not
self
.
is_stop
():
return
RECODE_FAILURE
"""
0 :机械臂不在线
1 :初始化成功
2 :参数错误
3 :当前位置不在限定范围
12 :传参错误
101 :传入参数不是整数
105 :某个关节失效
"""
isWrong
:
int
=
self
.
initial
(
self
.
HitbotType
,
self
.
MaxZPosition
)
self
.
updateProperty
()
if
not
self
.
initial_finish
:
return
isWrong
self
.
SetGripperState
(
GripperConfigModel
.
GripperON
())
return
self
.
unlock_position
()
def
AxisHome
(
self
)
->
int
:
isWrong
:
int
=
self
.
joint_home
(
AxisLevel
.
AxisX
)
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
:
int
=
self
.
joint_home
(
AxisLevel
.
AxisY
)
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
:
int
=
self
.
joint_home
(
AxisLevel
.
AxisZ
)
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
:
int
=
self
.
joint_home
(
AxisLevel
.
AxisR
)
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
:
int
=
self
.
initial
(
self
.
HitbotType
,
self
.
MaxZPosition
)
return
isWrong
def
MoveXYZ
(
self
,
axisType
:
int
,
movelength
:
float
,
movespeed
:
float
)
->
int
:
"""
:param axisType: 1 x 轴正方向,2 y 轴正方向,3 z 轴正方向
:param movelength: 移动距离(mm)
:param movespeed: 移动速度(mm/s)
:return:
0:正在执行其他指令,本次指令无效;
1:本次指令生效,机械臂开始运动;
2:设置速度小于等于零;
3:未初始化;
4:过程点无法到达;
5:方向参数错误;
6:伺服未开启;
7:该姿态无法完成直线运动;
11:手机端在控制;
101:传入参数 NOT A NUMBER;
102:发生碰撞,本次指令无效;
103:轴发生复位,需要重新初始化,本次指令无效;
"""
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
initial_finish
:
return
isWrong
try
:
isWrong
=
self
.
xyz_move
(
axisType
,
movelength
,
movespeed
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logHITBOT
logHITBOT
<<
AppUtils
.
toString
(
e
)
# self.flushProperty()
return
isWrong
pass
def
LineMoveXYZ
(
self
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
,
speed
:
float
)
->
int
:
"""
以 movel 的运动方式到达目标点 move_flag 等于 False 时,进行首次调用,返回 1 后,可以重复调用该函数设定新的目标点位
距离当前目标点有一定距离时,再次设定新的目标,机械臂将以一定的速度通过当前目标点,而后去往新的目标点。
:param x: 目标点 x 坐标(mm)
:param y: 目标点 y 坐标(mm)
:param z: 目标点 z 坐标(mm)
:param r: 目标点 r 坐标(deg)
:param speed: xyz 点的线速度(mm/s)或轴 4 的旋转角速度(deg/s)
:return:
• 0:正在执行其他指令,本次指令无效 1:本次指令生效,机械臂开始运动 2:设置速度小于等于零 3:未初始化 4:过程点无法到达
6:伺服未开启 7:存在中间过程点无法以机械臂当前姿态(手系)达到 11:手机端在控制 99:急停中 101:传入参数 NOT A NUMBER
102:发生碰撞,本次指令无效 103:轴发生复位,需要重新初始化,本次指令无效
"""
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
initial_finish
:
return
isWrong
try
:
isWrong
=
self
.
movel_xyz
(
x
,
y
,
z
,
r
,
speed
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logHITBOT
logHITBOT
<<
AppUtils
.
toString
(
e
)
return
isWrong
# 以 movej 的运动方式,并以指定手系达目标点
def
JopMoveXYZ
(
self
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
,
speed
:
float
,
roughly
:
float
)
->
int
:
"""
:param x:目标点 x 坐标(mm)
:param y:目标点 y 坐标(mm)
:param z:目标点 z 坐标(mm)
:param r:目标点 r 坐标(mm)
:param speed: xyz 点的线速度(mm/s)或轴 4 的旋转角速度
:param roughly: 0 先运动到前目标点,并且在当前目标点的速度等于 0,而后在去往新的目标点,
1 在有新目标点时,将在当前目标点附近以最大速度通过,
此参数取值范围 0 到 1,越大通过速度越快,但是通过点距离当前目标点越远
1 右手系,-1 左手系,angle2>0 右手系,否则为左手系
:return:
0:正在执行其他指令,本次指令无效
1:本次指令生效,机械臂开始运动
2:设置速度小于等于零
3:未初始化
4:目标点无法到达
6:伺服未开启
7:无法以设定手系到达目标点位
11:手机端在控制
99:急停中
101:传入参数 NOT A NUMBER
102:发生碰撞,本次指令无效
103:轴发生复位,需要重新初始化,本次指令无效
"""
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
initial_finish
:
return
isWrong
try
:
self
.
flushProperty
()
lr
:
int
=
1
if
int
(
self
.
angle2
)
>=
1
else
-
1
isWrong
=
self
.
new_movej_xyz_lr
(
x
,
y
,
z
,
r
,
speed
,
roughly
,
lr
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logHITBOT
logHITBOT
<<
AppUtils
.
toString
(
e
)
isWrong
=
HitBotMoveStatus
.
NOT_INITIALIZED
return
isWrong
def
JopMove_LR
(
self
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
,
speed
:
float
,
roughly
:
float
,
isLeft
:
bool
=
True
)
->
int
:
"""
:param isLeft:
:param x:目标点 x 坐标(mm)
:param y:目标点 y 坐标(mm)
:param z:目标点 z 坐标(mm)
:param r:目标点 r 坐标(mm)
:param speed: xyz 点的线速度(mm/s)或轴 4 的旋转角速度
:param roughly: 0 先运动到前目标点,并且在当前目标点的速度等于 0,而后在去往新的目标点,
1 在有新目标点时,将在当前目标点附近以最大速度通过,
此参数取值范围 0 到 1,越大通过速度越快,但是通过点距离当前目标点越远
1 右手系,-1 左手系,angle2>0 右手系,否则为左手系
:return:
0:正在执行其他指令,本次指令无效
1:本次指令生效,机械臂开始运动
2:设置速度小于等于零
3:未初始化
4:目标点无法到达
6:伺服未开启
7:无法以设定手系到达目标点位
11:手机端在控制
99:急停中
101:传入参数 NOT A NUMBER
102:发生碰撞,本次指令无效
103:轴发生复位,需要重新初始化,本次指令无效
lr:1 右手系,-1 左手系,angle2>0 右手系,否则为左手系
"""
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
initial_finish
:
return
isWrong
try
:
lr
:
int
=
-
1
if
isLeft
else
1
# self.change_attitude(speed)
isWrong
=
self
.
new_movej_xyz_lr
(
x
,
y
,
z
,
r
,
speed
,
roughly
,
lr
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logHITBOT
logHITBOT
<<
AppUtils
.
toString
(
e
)
isWrong
=
HitBotMoveStatus
.
NOT_INITIALIZED
return
isWrong
def
waitmovefinish
(
self
,
waittimes
:
int
=
5000
,
x
:
float
=
None
,
y
:
float
=
None
,
z
:
float
=
None
,
r
:
float
=
None
)
->
bool
:
"""
:param waittimes: 最大超时时间
:param x: 目标点 x 坐标(mm)
:param y: 目标点 y 坐标(mm)
:param z: 目标点 z 坐标(mm)
:param r: 目标点 r 坐标(deg)
:return: 是否停止
"""
if
not
self
.
initial_finish
:
return
True
is_finish
:
bool
is_complete
:
bool
=
isinstance
(
x
,
float
)
and
isinstance
(
y
,
float
)
or
isinstance
(
z
,
float
)
and
isinstance
(
r
,
float
)
isstop
:
bool
=
self
.
is_stop
()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
isstop
=
self
.
is_stop
()
if
isstop
:
break
self
.
_get_scara_param
()
if
not
self
.
move_flag
:
isstop
=
True
break
if
is_complete
:
is_target
:
bool
=
self
.
is_robot_goto_target
(
x
,
y
,
z
,
r
)
==
1
if
is_target
:
isstop
=
True
break
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
if
isstop
:
self
.
_get_scara_param
()
if
is_complete
:
is_target
:
bool
=
self
.
is_robot_goto_target
(
x
,
y
,
z
,
r
)
==
1
if
is_target
:
is_finish
=
True
return
is_finish
return
isstop
def
waitForMoveComplete
(
self
,
waittimes
:
int
,
delay
:
int
,
x
:
float
=
None
,
y
:
float
=
None
,
z
:
float
=
None
,
r
:
float
=
None
):
if
not
self
.
initial_finish
:
return
True
is_finish
:
bool
is_complete
:
bool
=
isinstance
(
x
,
float
)
and
isinstance
(
y
,
float
)
or
isinstance
(
z
,
float
)
and
isinstance
(
r
,
float
)
isstop
:
int
=
self
.
is_stop
()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
self
.
_get_scara_param
()
if
self
.
move_flag
:
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
continue
isstop
=
self
.
is_stop
()
if
isstop
:
break
if
is_complete
:
is_target
:
bool
=
self
.
is_robot_goto_target
(
x
,
y
,
z
,
r
)
==
1
if
is_target
:
isstop
=
True
break
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
if
isstop
:
if
is_complete
:
is_target
:
bool
=
self
.
is_robot_goto_target
(
x
,
y
,
z
,
r
)
==
1
if
is_target
:
is_finish
=
True
return
is_finish
self
.
_get_scara_param
()
return
isstop
def
waitForMoveStatus
(
self
,
waittimes
:
int
)
->
list
[
list
[
object
]]:
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
status
:
list
[
list
[
object
]]
=
[]
if
not
self
.
initial_finish
:
return
status
is_finish
:
bool
isstop
:
int
=
self
.
is_stop
()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
rate
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
IN_PORT
:
int
=
SystemConfig
.
CheckInPort
io
:
int
index
=
0
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
self
.
_get_scara_param
()
io
=
self
.
get_digital_in
(
IN_PORT
)
status
.
append
([
self
.
zPosition
,
io
])
# print(index, self.zPosition, io)
AppTimeLoop
.
processEvents
(
40
)
index
+=
1
if
self
.
move_flag
:
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
continue
isstop
=
self
.
is_stop
()
if
isstop
:
break
self
.
_get_scara_param
()
io
=
self
.
get_digital_in
(
7
)
status
.
append
([
self
.
zPosition
,
io
])
return
status
def
waitForMoveIOStatus
(
self
,
waittimes
:
int
)
->
list
[
object
]:
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
status
:
list
[
object
]
=
[]
if
not
self
.
initial_finish
:
return
status
is_finish
:
bool
isstop
:
int
=
self
.
is_stop
()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
rate
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
IN_PORT
:
int
=
SystemConfig
.
CheckInPort
io
:
int
index
=
0
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
self
.
_get_scara_param
()
if
not
self
.
move_flag
:
AppTimeLoop
.
delay
(
40
)
isstop
=
self
.
is_stop
()
if
isstop
:
break
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
AppTimeLoop
.
delay
(
40
)
self
.
_get_scara_param
()
return
status
def
waitForMovingStatus
(
self
,
waittimes
:
int
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
,
offset
:
float
)
->
int
:
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
status
:
int
=
0
if
not
self
.
initial_finish
:
return
status
is_finish
:
bool
# isstop: int = self.is_stop()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
IN_PORT
:
int
=
SystemConfig
.
CheckInPort
io
:
int
index
=
0
b_z
:
float
=
round
(
z
+
offset
,
2
)
e_z
:
float
=
round
(
z
-
offset
,
2
)
wait_delay
:
int
=
500
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
begin
:
Qt
.
QDateTime
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
status
+=
self
.
get_digital_in
(
IN_PORT
)
return
status
self
.
_get_scara_param
()
AppTimeLoop
.
processGlobalEvents
(
100
)
if
self
.
is_robot_goto_target
(
x
,
y
,
z
,
r
):
begin
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
wait_delay
)
break
if
not
self
.
move_flag
or
self
.
is_stop
():
status
+=
self
.
get_digital_in
(
IN_PORT
)
return
status
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
begin
:
break
status
+=
self
.
get_digital_in
(
IN_PORT
)
if
status
>=
1
:
break
AppTimeLoop
.
processGlobalEvents
(
100
)
return
status
def
waitForJointMovingStatus
(
self
,
waittimes
:
int
,
begin_z
:
float
,
end_z
:
float
)
->
int
:
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
status
:
int
=
0
if
not
self
.
initial_finish
:
return
status
is_finish
:
bool
# isstop: int = self.is_stop()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
rate
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
IN_PORT
:
int
=
SystemConfig
.
CheckInPort
io
:
int
index
=
0
msec
:
int
=
rate
.
msecsTo
(
Qt
.
QDateTime
.
currentDateTime
())
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
self
.
_get_scara_param
()
AppTimeLoop
.
processGlobalEvents
(
100
)
if
end_z
<=
Float
(
self
.
zPosition
)
<=
begin_z
:
status
+=
self
.
get_digital_in
(
IN_PORT
)
if
not
self
.
move_flag
or
self
.
is_stop
():
status
+=
self
.
get_digital_in
(
IN_PORT
)
break
# AppTimeLoop.processEvents(20)
status
+=
self
.
get_digital_in
(
IN_PORT
)
return
status
def
waitForMoving
(
self
,
x
:
float
=
None
,
y
:
float
=
None
,
z
:
float
=
None
,
r
:
float
=
None
,
waittimes
:
int
=
5000
)
->
bool
:
"""
:param waittimes: 最大超时时间
:param x: 目标点 x 坐标(mm)
:param y: 目标点 y 坐标(mm)
:param z: 目标点 z 坐标(mm)
:param r: 目标点 r 坐标(deg)
:return: 是否停止
"""
if
not
self
.
initial_finish
:
return
True
is_finish
:
bool
is_complete
:
bool
=
isinstance
(
x
,
float
)
and
isinstance
(
y
,
float
)
or
isinstance
(
z
,
float
)
and
isinstance
(
r
,
float
)
isstop
:
bool
=
self
.
is_stop
()
waittime
:
int
=
max
(
min
(
waittimes
,
HITBOT_MOVE_MAX_WAIT_TIMES
),
HITBOT_MOVE_MIN_WAIT_TIMES
)
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
isstop
=
self
.
is_stop
()
if
isstop
:
break
AppTimeLoop
.
processGlobalEvents
(
HITBOT_DEFAULT_DELAY
)
if
isstop
:
if
is_complete
:
is_finish
=
self
.
is_robot_goto_target
(
x
,
y
,
z
,
r
)
return
is_finish
return
isstop
def
StopHitBotMove
(
self
):
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
IsInitialize
():
return
isWrong
return
self
.
new_stop_move
()
def
GetEmStopState
(
self
):
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
IsInitialize
():
return
isWrong
return
self
.
get_hard_emergency_stop_state
()
def
SetEmStop
(
self
):
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
IsInitialize
():
return
isWrong
return
self
.
emergency_stop
()
def
ClearEmStop
(
self
):
isWrong
:
int
=
HitBotMoveStatus
.
NOT_INITIALIZED
if
not
self
.
IsInitialize
():
return
isWrong
return
self
.
clear_hard_emergency_stop
()
def
JointMove
(
self
,
axis
:
int
,
distance
:
float
,
speed
:
float
)
->
int
:
"""
:param axis : 关节号 1-4 正方向
:param distance : 旋转角度(deg)
:param speed :轴 3 为线速度(mm/s),其他为旋转速度(deg/s)
:return :
0:正在执行其他指令,本次指令无效;
1:本次指令生效,机械臂开始运动;
2:设置速度小于等于零;
3:未初始化;
5:轴号参数错误;
6:伺服未开启;
11:手机端在控制;
101:传入参数 NOT A NUMBER;
102:发生碰撞,本次指令无效;
103:轴发生复位,需要重新初始化,本次指令无效;
"""
if
not
self
.
IsInitialize
():
return
HitBotMoveStatus
.
NOT_INITIALIZED
return
self
.
single_joint_move
(
axis
,
distance
,
speed
)
def
isJointValid
(
self
,
axis
:
int
,
enable
:
bool
)
->
bool
:
"""
:param axis:关节号 1-4
:param enable: true 开启关节 false 屏蔽
:return: true:设置关节是否生效成功; false:关节号错误;
"""
if
not
self
.
IsInitialize
():
return
HitBotMoveStatus
.
NOT_INITIALIZED
return
self
.
check_joint
(
axis
,
enable
)
def
JointHome
(
self
,
axis
:
int
)
->
int
:
"""
:param axis: 轴号 1-4
:return: 0:未连接 1:调用成功 2:传入参数错误 3:机械臂正在初始化
"""
if
not
self
.
IsInitialize
():
return
HitBotMoveStatus
.
NOT_INITIALIZED
return
self
.
joint_home
(
axis
)
def
GetJointState
(
self
,
axis
:
int
)
->
int
:
if
not
self
.
IsInitialize
():
return
HitBotMoveStatus
.
NOT_INITIALIZED
return
self
.
get_joint_state
(
axis
)
def
GetGripperState
(
self
)
->
int
:
""":return: 1:成功 3:失败,未初始化;"""
if
not
self
.
IsInitialize
():
return
3
value
=
self
.
get_efg_state
()
return
value
def
GetGripperRotationAngle
(
self
)
->
float
:
""":return: 旋转角度"""
if
not
self
.
IsInitialize
():
return
self
.
_Manager
.
rPosition
self
.
updateProperty
()
return
self
.
rPosition
def
SetGripperRotationAngle
(
self
,
angle
:
float
,
speed
:
float
)
->
int
:
""":return: 旋转角度"""
if
not
self
.
IsInitialize
():
return
HitBotMoveStatus
.
NOT_INITIALIZED
isWrong
=
self
.
single_joint_move
(
AxisLevel
.
AxisR
,
angle
,
speed
)
self
.
waitForMoving
()
self
.
updateProperty
()
return
isWrong
def
SetGripperState
(
self
,
distance
:
float
)
->
int
:
"""
:param distance: Type==8:0 张开 1 闭合 Type==20:实际行程(mm)
:return: -1:控制参数发生变化 0 :type 参数错误 1:设置成功 3:未初始化;
"""
if
not
self
.
IsInitialize
():
return
RECODE_FAILURE
if
isinstance
(
distance
,
float
)
or
isinstance
(
distance
,
int
):
old
:
float
=
float
(
self
.
efg_travel_length
)
self
.
efg_distance
=
distance
rec
=
self
.
set_efg_state
(
self
.
efg_type
,
int
(
self
.
efg_distance
))
self
.
_get_efg_state
()
return
RECODE_SUCCEED
if
rec
==
1
else
RECODE_FAILURE
return
RECODE_SUCCEED
def
IsGrab
(
self
)
->
bool
:
"""夹爪是否夹取到东西"""
if
not
self
.
IsInitialize
():
return
False
GrabMinLength
:
float
GrabMaxLength
:
float
GripperON
:
float
GripperOFF
:
float
GrabOFF
:
float
=
GripperConfigModel
.
GrabOFF
()
isGrab
:
bool
=
False
efg_travel_length
:
float
GrabMinLength
,
GrabMaxLength
=
GripperConfigModel
.
isGrab
()
GripperON
,
GripperOFF
=
GripperConfigModel
.
Switch
()
"""夹爪是否关闭"""
self
.
SetGripperStatus
(
float
(
GrabOFF
))
AppTimeLoop
.
processEvents
(
50
)
self
.
_get_efg_state
()
efg_travel_length
=
self
.
efg_travel_length
isGrab
=
float
(
GrabMinLength
)
<=
Float
(
efg_travel_length
)
<=
float
(
GrabMaxLength
)
self
.
SetGripperStatus
(
float
(
GripperOFF
))
if
not
isGrab
:
print
(
f
'IsGrab: {isGrab} {GrabOFF} {GrabMinLength} {efg_travel_length} {GrabMaxLength}'
)
print
(
f
'IsGrab: {isGrab} GrabMinLength: {GrabMinLength} efg_travel_length: {efg_travel_length} GrabMaxLength:{GrabMaxLength}'
)
return
isGrab
def
IsGripperON
(
self
)
->
bool
:
if
not
self
.
IsInitialize
():
return
False
self
.
_get_efg_state
()
GripperON
:
float
GripperMiddle
:
float
GripperON
,
GripperMiddle
=
GripperConfigModel
.
isGripperON
()
return
float
(
GripperON
)
<=
Float
(
self
.
efg_travel_length
)
<
float
(
GripperMiddle
)
def
IsGripperOFF
(
self
)
->
bool
:
if
not
self
.
IsInitialize
():
return
False
self
.
_get_efg_state
()
GripperMinLength
:
float
GripperMaxLength
:
float
GripperMinLength
,
GripperMaxLength
=
GripperConfigModel
.
isGripperOFF
()
IsGripperOFF
:
bool
=
float
(
GripperMinLength
)
<=
Float
(
self
.
efg_travel_length
)
<=
float
(
GripperMaxLength
)
print
(
f
'IsGripperOFF: {IsGripperOFF} GripperMinLength: {GripperMinLength} <= {self.efg_travel_length} <= {GripperMaxLength}'
)
return
IsGripperOFF
def
IsBeginOFF
(
self
)
->
bool
:
if
not
self
.
IsInitialize
():
return
False
BeginOFF
:
float
GripperMinLength
:
float
BeginOFF
,
GripperMinLength
=
GripperConfigModel
.
isBeginOFF
()
self
.
_get_efg_state
()
return
float
(
BeginOFF
)
<=
Float
(
self
.
efg_travel_length
)
<
float
(
GripperMinLength
)
def
SetGripperON
(
self
)
->
int
:
GripperON
,
GripperOFF
=
GripperConfigModel
.
Switch
()
BeginOFF
=
GripperConfigModel
.
BeginOFF
()
isWrong
:
int
=
self
.
SetGripperState
(
float
(
GripperON
))
for
count
in
range
(
0
,
2
):
if
RECODE_SUCCEED
==
isWrong
and
self
.
IsGripperON
():
break
self
.
SetGripperState
(
float
(
BeginOFF
))
isWrong
=
self
.
SetGripperState
(
float
(
GripperON
))
return
isWrong
def
SetGripperOFF
(
self
)
->
int
:
GripperON
,
GripperOFF
=
GripperConfigModel
.
Switch
()
isWrong
:
int
=
self
.
SetGripperState
(
float
(
GripperOFF
))
BeginOFF
=
GripperConfigModel
.
BeginOFF
()
Step
:
float
=
1.0
for
count
in
range
(
1
,
3
):
if
RECODE_SUCCEED
==
isWrong
and
self
.
IsGripperOFF
():
break
isWrong
=
self
.
SetGripperState
(
float
(
GripperOFF
)
+
Step
*
count
)
# AppTimeLoop.processEvents(50)
return
isWrong
def
SetBeginOFF
(
self
)
->
int
:
isWrong
:
int
=
self
.
SetGripperStatus
(
float
(
GripperConfigModel
.
BeginOFF
()))
# AppTimeLoop.processEvents(50)
return
isWrong
def
SetBeginON
(
self
)
->
int
:
isWrong
:
int
=
self
.
SetGripperStatus
(
float
(
GripperConfigModel
.
BeginOFF
()))
# AppTimeLoop.processEvents(50)
return
isWrong
def
SetGrabON
(
self
):
isWrong
:
int
=
self
.
SetGripperStatus
(
float
(
GripperConfigModel
.
GrabON
()))
return
isWrong
def
SetGrabOFF
(
self
):
isWrong
:
int
=
self
.
SetGripperStatus
(
float
(
GripperConfigModel
.
GrabOFF
()))
return
isWrong
def
SetGripperStatus
(
self
,
distance
:
float
)
->
int
:
"""
:param distance: Type==8:0 张开 1 闭合 Type==20:实际行程(mm)
:return: -1:控制参数发生变化 0 :type 参数错误 1:设置成功 3:未初始化;
"""
if
not
self
.
IsInitialize
():
return
RECODE_FAILURE
if
isinstance
(
distance
,
(
float
,
int
)):
self
.
efg_distance
=
distance
self
.
efg_travel_length
=
distance
rec
=
self
.
set_efg_state
(
self
.
efg_type
,
float
(
self
.
efg_distance
))
return
RECODE_SUCCEED
if
rec
==
1
else
RECODE_FAILURE
return
RECODE_SUCCEED
def
isReach
(
self
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
)
->
bool
:
"""
:param x:x 坐标(mm)
:param y:y 坐标(mm)
:param z:z 坐标(mm)
:param r:r 坐标(deg)
:return: false:超出范围无法到达; true:可以到达;
"""
if
not
self
.
IsInitialize
():
return
False
return
self
.
judge_in_range_xyzr
(
x
,
y
,
z
,
r
)
pass
def
SetJointTorqueValue
(
self
,
axis
:
int
,
value
:
int
)
->
int
:
"""
:param axis: 轴编号
:param value: 转矩设定值,[1000,20000]
:return:0:未连接;1:设置成功;2:轴号错误;3:未初始化;
"""
if
not
self
.
IsInitialize
():
return
0
return
self
.
set_robot_joint_torque_value
(
axis
,
value
)
def
AxisXHome
(
self
)
->
int
:
""":return: 0:未连接 1:调用成功 2:传入参数错误 3:机械臂正在初始化"""
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
joint_home
(
AxisLevel
.
AxisX
)
def
AxisYHome
(
self
)
->
int
:
""":return: 0:未连接 1:调用成功 2:传入参数错误 3:机械臂正在初始化"""
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
joint_home
(
AxisLevel
.
AxisY
)
def
AxisZHome
(
self
)
->
int
:
""":return: 0:未连接 1:调用成功 2:传入参数错误 3:机械臂正在初始化"""
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
joint_home
(
AxisLevel
.
AxisZ
)
def
AxisRHome
(
self
)
->
int
:
""":return: 0:未连接 1:调用成功 2:传入参数错误 3:机械臂正在初始化"""
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
joint_home
(
AxisLevel
.
AxisR
)
def
isCollision
(
self
)
->
bool
:
"""查询机械臂是否发生碰撞 :return: False:未发生碰撞 True:发生碰撞"""
if
not
self
.
IsInitialize
():
return
False
return
self
.
is_collision
()
def
GetInputStatus
(
self
,
io_number
:
int
)
->
bool
:
if
not
self
.
IsInitialize
():
return
False
status
=
self
.
get_digital_in
(
io_number
)
return
status
def
GetCheckPortStatus
(
self
)
->
bool
:
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
return
self
.
GetInputStatus
(
SystemConfig
.
CheckInPort
)
def
ReadCheckPortStatus
(
self
,
count
:
int
,
split
:
int
=
100
)
->
list
[
int
]:
from
AppSettings.SystemSetting
import
SystemSetting
,
SystemConfig
Count
:
int
=
max
(
1
,
count
)
waittimes
:
int
=
max
(
10
,
split
)
result
:
list
[
int
]
=
[
0
]
*
max
(
1
,
count
)
for
index
in
range
(
Count
):
result
[
index
]
=
self
.
get_digital_in
(
SystemConfig
.
CheckInPort
)
AppTimeLoop
.
processEvents
(
waittimes
)
return
result
def
initHitbotProperty
(
self
):
self
.
CardNumber
=
180
self
.
xPosition
=
0.0
self
.
yPosition
=
0.0
self
.
zPosition
=
0.0
self
.
rPosition
=
0.0
self
.
angle1
=
0.0
self
.
angle2
=
0.0
self
.
communicate_success
=
False
self
.
initial_finish
=
False
self
.
move_flag
=
False
self
.
MaxZPosition
=
HitbotAxisZLength
.
Max180
self
.
HitbotType
=
HitbotLevel
.
Hitbot400
def
initEncodeProperty
(
self
):
self
.
encoder_x
=
0.0
self
.
encoder_y
=
0.0
self
.
encoder_z
=
0.0
self
.
encoder_r
=
0.0
self
.
encoder_angle1
=
0.0
self
.
encoder_angle2
=
0.0
pass
def
initGripperProperty
(
self
):
self
.
efg_distance
=
0.0
self
.
efg_type
=
GripperLevel
.
EFG_20
def
flushHitbotProperty
(
self
):
self
.
get_scara_param
()
def
flushEncodeProperty
(
self
):
self
.
get_encoder_coor
()
pass
def
flushGripperProperty
(
self
):
self
.
get_efg_state
()
def
flushProperty
(
self
):
self
.
_get_scara_param
()
self
.
_get_encoder_coor
()
self
.
_get_efg_state
()
print
(
f
"error: {self.get_error_code()}"
)
# print(self.__str__())
def
flush_scara_param
(
self
):
self
.
_get_scara_param
()
def
updateProperty
(
self
):
Locker
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
IOLocker
)
self
.
_get_scara_param
()
self
.
_get_encoder_coor
()
self
.
_get_efg_state
()
print
(
f
"error: {self.get_error_code()}"
)
# print(self.__str__())
def
isLeft
(
self
)
->
bool
:
if
not
self
.
initial_finish
:
return
True
self
.
_get_scara_param
()
return
Float
(
self
.
angle2
)
<=
float
(
0.0
)
def
_get_scara_param
(
self
):
"""
更新 x,y,z 等成员变量
:return:
"""
# self.initHitbotProperty()
c_xPosition
:
c_float
=
c_float
(
0
)
c_yPosition
:
c_float
=
c_float
(
0
)
c_zPosition
:
c_float
=
c_float
(
0
)
c_angle1
:
c_float
=
c_float
(
0
)
c_angle2
:
c_float
=
c_float
(
0
)
c_rPosition
:
c_float
=
c_float
(
0
)
c_communicate_success
:
c_bool
=
c_bool
(
0
)
c_initial_finish
:
c_bool
=
c_bool
(
0
)
c_move_flag
:
c_bool
=
c_bool
(
0
)
get_scara_param
=
self
.
resolve
(
'robot_get_scara_param'
,
c_void_p
)
if
not
get_scara_param
:
return
HitBot_DLL_Warning
get_scara_param
(
c_int
(
self
.
CardNumber
),
byref
(
c_xPosition
),
byref
(
c_yPosition
),
byref
(
c_zPosition
),
byref
(
c_angle1
),
byref
(
c_angle2
),
byref
(
c_rPosition
),
byref
(
c_communicate_success
),
byref
(
c_initial_finish
),
byref
(
c_move_flag
))
self
.
xPosition
=
round
(
c_xPosition
.
value
,
3
)
self
.
yPosition
=
round
(
c_yPosition
.
value
,
3
)
self
.
zPosition
=
round
(
c_zPosition
.
value
,
3
)
self
.
angle1
=
round
(
c_angle1
.
value
,
3
)
self
.
angle2
=
round
(
c_angle2
.
value
,
3
)
self
.
rPosition
=
round
(
c_rPosition
.
value
,
3
)
self
.
communicate_success
=
c_communicate_success
.
value
self
.
initial_finish
=
c_initial_finish
.
value
self
.
move_flag
=
c_move_flag
.
value
data
:
HitBotData
=
HitBotData
(
self
)
data
.
xPosition
=
self
.
xPosition
data
.
yPosition
=
self
.
yPosition
data
.
zPosition
=
self
.
zPosition
data
.
angle1
=
self
.
angle1
data
.
angle2
=
self
.
angle2
data
.
rPosition
=
self
.
rPosition
data
.
communicate_success
=
self
.
communicate_success
data
.
initial_finish
=
self
.
initial_finish
data
.
move_flag
=
self
.
move_flag
model
:
HitBotModel
=
HitBotModel
.
asHitBotData
(
data
)
self
.
UpdateStatus
.
emit
(
data
,
model
)
AppSlot
.
currentHitBotDataChanged
.
emit
(
data
,
model
)
# 更新编码器位置,调用后 encoder_x,encoder_y,encoder_z等变量会进行更新
def
_get_encoder_coor
(
self
):
"""
:return:
"""
self
.
initEncodeProperty
()
c_x
=
c_float
(
0
)
# 编码器 x 轴坐标
c_y
=
c_float
(
0
)
# 编码器 y 轴坐标
c_z
=
c_float
(
0
)
# 编码器 z 轴坐标
c_r
=
c_float
(
0
)
# 编码器 r 轴坐标
c_angle1
=
c_float
(
0
)
# 编码器 angle1 轴坐标
c_angle2
=
c_float
(
0
)
# 编码器 angle2 轴坐标
get_encoder_coor
=
self
.
resolve
(
'robot_get_encoder_param'
,
c_void_p
)
if
not
get_encoder_coor
:
return
HitBot_DLL_Warning
get_encoder_coor
(
c_int
(
self
.
CardNumber
),
byref
(
c_x
),
byref
(
c_y
),
byref
(
c_z
),
byref
(
c_angle1
),
byref
(
c_angle2
),
byref
(
c_r
))
self
.
encoder_x
=
round
(
c_x
.
value
,
2
)
self
.
encoder_y
=
round
(
c_y
.
value
,
2
)
self
.
encoder_z
=
round
(
c_z
.
value
,
2
)
self
.
encoder_r
=
round
(
c_r
.
value
,
2
)
self
.
encoder_angle1
=
round
(
c_angle1
.
value
,
2
)
self
.
encoder_angle2
=
round
(
c_angle2
.
value
,
2
)
# 获取电动夹爪状态
def
_get_efg_state
(
self
)
->
int
:
"""
:return: 1:成功 3:失败,未初始化;
"""
# self.initGripperProperty()
self
.
efg_travel_length
=
0.0
c_efg_type
:
c_int
=
c_int
(
0
)
c_efg_travel_length
:
c_float
=
c_float
(
0
)
func
=
self
.
resolve
(
'robot_get_efg_state'
,
c_int
)
if
not
func
:
return
3
rec
=
func
(
c_int
(
self
.
CardNumber
),
byref
(
c_efg_type
),
byref
(
c_efg_travel_length
))
self
.
efg_travel_length
=
round
(
c_efg_travel_length
.
value
,
2
)
return
rec
def
net_port_initial
(
self
)
->
int
:
"""
申请内存和初始化网络服务器 调用其他 api 之前,需要先调用该函数,否则将导致程序崩溃,同一个 python 程序控制多台手臂时,
每一个手臂对象都要调用该函数
:return: •1 成功 0 失败,一般是 40000 端口号被占用
"""
net_port_initial
=
self
.
resolve
(
'net_port_initial'
,
c_int
)
if
not
net_port_initial
:
return
0
return
net_port_initial
()
def
close_server
(
self
):
"""
关闭网络服务器(server.exe 程序)
:return: 调用后,手臂和 pc 的通讯将会断开
"""
robot_close_server
=
self
.
resolve
(
"robot_close_server"
,
c_void_p
)
if
robot_close_server
is
None
:
return
HitBot_DLL_Warning
return
robot_close_server
()
def
initial
(
self
,
generation
:
int
,
z_trail
:
float
):
"""
初始化机械臂的各项参数,机械臂进入工作状态
机械臂在运动时调用该函数,会造成机械臂抖动 返回 3 时,可以使用 joint_home 使关节强制回零
:param generation: 00mm 臂展系列传入 1,320mm 臂展系列及其他臂展手臂传入 5,
:param z_trail: 上下关节有效行程(mm)
:return:
0:机械臂不在线
1:初始化成功
2:generation 参数错误
3:机械臂当前位置不在限定范围,可以使用 joint_home使关节强制回零
12:z_travel 传参错误
101:传入参数 NOT A NUMBER
105:存在某一个关节失效
>= 10000,pid 自检异常
"""
robot_initial
=
self
.
resolve
(
"robot_initial"
,
c_int
,
*
[
c_int
,
c_int
,
c_float
])
if
robot_initial
is
None
:
return
HitBot_DLL_Warning
return
robot_initial
(
c_int
(
self
.
CardNumber
),
c_int
(
generation
),
c_float
(
z_trail
))
def
get_scara_param
(
self
):
"""
更新 x,y,z 等成员变量
:return:
"""
Locker
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
IOLocker
)
return
self
.
_get_scara_param
()
def
unlock_position
(
self
)
->
int
:
"""
解锁机械臂,使机械臂可以接受运动指令 一般初始化成功后立刻调用
:return: 0:机械臂不在线 1:成功
"""
unlock_position
=
self
.
resolve
(
'robot_unlock_position'
,
c_int
,
*
[
c_int
])
if
unlock_position
is
None
:
return
HitBot_DLL_Warning
return
unlock_position
(
c_int
(
self
.
CardNumber
))
def
is_connect
(
self
)
->
int
:
"""
查询机械臂是否在线
:return: False:机械臂不在线 True:机械臂在线
"""
is_connect
=
self
.
resolve
(
'robot_is_connect'
,
c_int
,
*
[
c_int
])
if
is_connect
is
None
:
return
HitBot_DLL_Warning
return
is_connect
(
c_int
(
self
.
CardNumber
))
def
get_joint_status
(
self
)
->
(
int
,
int
,
int
,
int
):
x
:
int
=
self
.
get_joint_state
(
1
)
y
:
int
=
self
.
get_joint_state
(
2
)
z
:
int
=
self
.
get_joint_state
(
3
)
r
:
int
=
self
.
get_joint_state
(
4
)
return
x
,
y
,
z
,
r
# 获取机械臂关节状态
def
get_joint_state
(
self
,
joint_num
:
int
)
->
int
:
"""
获取机械臂关节状态
:param joint_num: 轴号 1-4
:return:
0:轴发生复位,需要重新初始化 1:关节正常 2:传入参数超范围 3:未初始化 4:轴状态获取失败 5:发生碰撞; 6:处于拖动模式
7:关节缺轴/失效 8:编码器错误 9:电机堵转/过电流保护 10:过压保护 11:手臂收到 PC 发送的错误数据
12:手臂主控与驱动通讯异常 21: MOS ntc 开路 22:MOS ntc 短路 23:电机 ntc 开路 24:电机 ntc 短路
25:MOS ntc 温度过高 26:MOS ntc 温度过低 27:电机 ntc 温度过高 28:电机 ntc 温度过低
"""
robot_get_joint_state
=
self
.
resolve
(
'robot_get_joint_state'
,
c_int
,
*
[
c_int
,
c_int
])
if
robot_get_joint_state
is
None
:
return
HitBot_DLL_Warning
return
robot_get_joint_state
(
c_int
(
self
.
CardNumber
),
c_int
(
joint_num
))
pass
# 设定拖动示教功能是否开启
def
set_drag_teach
(
self
,
enable
:
bool
)
->
bool
:
"""
设定拖动示教功能是否开启
仅协作机型支持开启此功能 拖动示教功能开启后,轴 Z 3 不支持拖动,需要通过调用运 动函数控制轴 Z 3 部分新机型支持 z 轴拖动示教
:param enable: False:失败 True:成功
:return:
"""
set_drag_teach
=
self
.
resolve
(
'robot_set_drag_teach'
,
c_bool
,
*
[
c_int
,
c_bool
])
if
set_drag_teach
is
None
:
return
False
return
set_drag_teach
(
c_int
(
self
.
CardNumber
),
c_bool
(
enable
))
# 查询是否处于拖动示教状态
def
get_drag_teach
(
self
)
->
bool
:
"""
查询是否处于拖动示教状态
:return: • False:开启 True:关闭
"""
get_drag_teach
=
self
.
resolve
(
'robot_get_drag_teach'
,
c_bool
,
*
[
c_int
])
if
get_drag_teach
is
None
:
return
False
return
get_drag_teach
(
c_int
(
self
.
CardNumber
))
# 设定协作功能是否开启,开启后机械臂遇到障碍物会停止运动,并上报此状态
def
set_cooperation_fun_state
(
self
,
enable
:
bool
)
->
bool
:
"""
设定协作功能是否开启,开启后机械臂遇到障碍物会停止运动,并上报此状态
:param enable: True 开启,False 关闭
:return: False:成功 True:失败
"""
set_cooperation_fun_state
=
self
.
resolve
(
'robot_set_cooperation_fun_state'
,
c_bool
,
*
[
c_int
,
c_bool
])
if
set_cooperation_fun_state
is
None
:
return
False
return
set_cooperation_fun_state
(
c_int
(
self
.
CardNumber
),
c_bool
(
enable
))
# 查询机械臂是否开启协作功能
def
get_cooperation_fun_state
(
self
)
->
bool
:
"""
:return: False:开启 True:关闭
"""
get_cooperation_fun_state
=
self
.
resolve
(
'robot_get_cooperation_fun_state'
,
c_int
,
*
[
c_int
])
if
get_cooperation_fun_state
is
None
:
return
False
return
get_cooperation_fun_state
(
c_int
(
self
.
CardNumber
))
pass
# 查询机械臂是否发生碰撞
def
is_collision
(
self
)
->
bool
:
"""
# 查询机械臂是否发生碰撞 :return: False:未发生碰撞 True:发生碰撞
"""
is_collision
=
self
.
resolve
(
'robot_is_collision'
,
c_bool
,
*
[
c_int
])
if
is_collision
is
None
:
return
False
return
is_collision
(
c_int
(
self
.
CardNumber
))
# 使轴回到零位
def
joint_home
(
self
,
joint_num
:
int
)
->
int
:
"""
:param joint_num: 轴号
:return: 0:未连接 1:调用成功 2:传入参数错误 3:机械臂正在初始化
"""
joint_home
=
self
.
resolve
(
'robot_joint_home'
,
c_int
,
*
[
c_int
,
c_int
])
if
joint_home
is
None
:
return
HitBot_DLL_Warning
return
joint_home
(
c_int
(
self
.
CardNumber
),
c_int
(
joint_num
))
# 以 movel 的运动方式到达目标点
def
movel_xyz
(
self
,
goal_x
:
float
,
goal_y
:
float
,
goal_z
:
float
,
goal_r
:
float
,
speed
:
float
)
->
int
:
"""
以 movel 的运动方式到达目标点 move_flag 等于 False 时,进行首次调用,返回 1 后,可以重复调用该函数设定新的目标点位
距离当前目标点有一定距离时,再次设定新的目标,机械臂将以一定的速度通过当前目标点,而后去往新的目标点。
:param goal_x: 目标点 x 坐标(mm)
:param goal_y: 目标点 y 坐标(mm)
:param goal_z: 目标点 z 坐标(mm)
:param goal_r: 目标点 r 坐标(deg)
:param speed: xyz 点的线速度(mm/s)或轴 4 的旋转角速度(deg/s)
:return:
• 0:正在执行其他指令,本次指令无效 1:本次指令生效,机械臂开始运动 2:设置速度小于等于零 3:未初始化 4:过程点无法到达
6:伺服未开启 7:存在中间过程点无法以机械臂当前姿态(手系)达到 11:手机端在控制 99:急停中 101:传入参数 NOT A NUMBER
102:发生碰撞,本次指令无效 103:轴发生复位,需要重新初始化,本次指令无效
"""
movel_xyz
=
self
.
resolve
(
'robot_movel_xyz'
,
c_int
,
*
[
c_int
,
c_float
,
c_float
,
c_float
,
c_float
,
c_float
])
if
movel_xyz
is
None
:
return
HitBot_DLL_Warning
isWrong
:
int
=
movel_xyz
(
c_int
(
self
.
CardNumber
),
c_float
(
goal_x
),
c_float
(
goal_y
),
c_float
(
goal_z
),
c_float
(
goal_r
),
c_float
(
speed
))
error_string
:
str
=
HitBotMoveWarning
.
toString
(
isWrong
)
print
(
error_string
)
return
isWrong
# 切换手系
def
change_attitude
(
self
,
speed
:
float
)
->
int
:
"""
:param speed:线速度(mm/s)
:return: 0:机械臂正在执行其他指令,本次指令无效
1:本次指令生效,机械臂开始运动 2:设置速度小于等于零 3:未初始化 4:过程点无法到达 6:伺服未开启 11:手机端在控制
101:传入参数 NOT A NUMBER 102:发生碰撞,本次指令无效 103:轴发生复位,需要重新初始化,本次指令无效
"""
change_attitude
=
self
.
resolve
(
'robot_change_attitude'
,
c_int
,
*
[
c_int
,
c_float
])
if
change_attitude
is
None
:
return
HitBot_DLL_Warning
return
change_attitude
(
c_int
(
self
.
CardNumber
),
c_float
(
speed
))
pass
# 用于判断运动是否结束
def
wait_stop
(
self
)
->
bool
:
"""
wait_stop 属于开环控制,函数返回以后不代表手臂一定处
于静止状态,在关键点位需要搭配 is_robot_goto_target 使
用,此时 is_robot_goto_target 需要做超时处理,一般超时
时间 3s 即可
阻塞函数,运动数据下发完成后返回
:return: true:正常停止 false:存在某些异常使 wait_stop 超时,此时应停止手臂作业流程
"""
wait_stop
=
self
.
resolve
(
'robot_wait_stop'
,
c_bool
,
*
[
c_int
])
if
wait_stop
is
None
:
return
False
return
wait_stop
(
c_int
(
self
.
CardNumber
))
# 暂停机械臂的运动
def
pause_move
(
self
)
->
int
:
"""
:return: 默认返回 1
"""
pause_move
=
self
.
resolve
(
'robot_pause_move'
,
c_int
,
*
[
c_int
])
if
pause_move
is
None
:
return
HitBot_DLL_Warning
return
pause_move
(
c_int
(
self
.
CardNumber
))
# 恢复机械臂的运动
def
resume_move
(
self
)
->
int
:
"""
:return: 默认返回 1
"""
resume_move
=
self
.
resolve
(
'robot_resume_move'
,
c_int
,
*
[
c_int
])
if
resume_move
is
None
:
return
HitBot_DLL_Warning
return
resume_move
(
c_int
(
self
.
CardNumber
))
# 非阻塞,查询手臂是否停止运动
def
is_stop
(
self
)
->
int
:
"""
:return: 0:运动 1:停止
"""
robot_is_stop
=
self
.
resolve
(
'robot_is_stop'
,
c_bool
,
*
[
c_int
])
if
robot_is_stop
is
None
:
return
HitBot_DLL_Warning
return
robot_is_stop
(
c_int
(
self
.
CardNumber
))
# 设定 io 输出点状态
def
set_digital_out
(
self
,
io_number
:
int
,
io_value
:
int
)
->
int
:
"""
:param io_number: io 输出点编号
:param io_value: 设定值
:return: 0:io_number 参数错误 1:设置成功 3:未初始化
"""
set_digital_out
=
self
.
resolve
(
'robot_set_digital_io_out'
,
c_int
,
*
[
c_int
,
c_int
,
c_int
])
if
set_digital_out
is
None
:
return
HitBot_DLL_Warning
return
set_digital_out
(
c_int
(
self
.
CardNumber
),
c_int
(
io_number
),
c_int
(
io_value
))
# 获取 io 输出点状态
def
get_digital_out
(
self
,
io_number
)
->
int
:
"""
:param io_number:io 输出点编号
:return: -1:io_number 参数错误 0:io 口输出状态为断开 1:io 口输出状态为导通 3:未初始化
"""
get_digital_out
=
self
.
resolve
(
'robot_get_digital_io_out'
,
c_int
,
*
[
c_int
,
c_int
])
if
get_digital_out
is
None
:
return
HitBot_DLL_Warning
return
get_digital_out
(
c_int
(
self
.
CardNumber
),
c_int
(
io_number
))
pass
# 获取 io 输入点状态
def
get_digital_in
(
self
,
io_number
:
int
)
->
int
:
"""
:param io_number:io 输入点编号
:return: -1:io_number 参数错误 0:io 输入点没有被触发
"""
get_digital_in
=
self
.
resolve
(
'robot_get_digital_io_in'
,
c_int
,
*
[
c_int
,
c_int
])
if
get_digital_in
is
None
:
return
HitBot_DLL_Warning
return
get_digital_in
(
c_int
(
self
.
CardNumber
),
c_int
(
io_number
))
# 设定电动夹爪状态
def
set_efg_state
(
self
,
efg_type
:
int
,
efg_distance
:
(
int
,
float
))
->
int
:
"""
:param efg_type:8 EFG-8,20 EFG-20
:param efg_distance: Type==8:0 张开 1 闭合 Type==20:实际行程(mm)
:return: -1:控制参数发生变化 0 :type 参数错误 1:设置成功 3:未初始化;
"""
set_efg_state
=
self
.
resolve
(
'robot_set_efg_state'
,
c_int
,
*
[
c_int
,
c_int
,
c_float
])
if
set_efg_state
is
None
:
return
HitBot_DLL_Warning
self
.
efg_distance
=
efg_distance
result
:
int
=
set_efg_state
(
c_int
(
self
.
CardNumber
),
c_int
(
efg_type
),
c_float
(
efg_distance
))
self
.
_get_efg_state
()
self
.
_get_scara_param
()
return
result
# 获取电动夹爪状态
def
get_efg_state
(
self
)
->
int
:
"""
:return: 1:成功 3:失败,未初始化;
"""
Locker
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
IOLocker
)
rec
=
self
.
_get_efg_state
()
return
rec
# 以 movej 的运动方式,并以指定手系达目标点
def
new_movej_xyz_lr
(
self
,
goal_x
:
float
,
goal_y
:
float
,
goal_z
:
float
,
goal_r
:
float
,
speed
:
float
,
roughly
:
float
,
lr
:
int
)
->
int
:
"""
:param goal_x:目标点 x 坐标(mm)
:param goal_y:目标点 y 坐标(mm)
:param goal_z:目标点 z 坐标(mm)
:param goal_r:目标点 r 坐标(mm)
:param speed: xyz 点的线速度(mm/s)或轴 4 的旋转角速度
:param roughly: 0 先运动到前目标点,并且在当前目标点的速度等于 0,而后在去往新的目标点,
1 在有新目标点时,将在当前目标点附近以最大速度通过,
此参数取值范围 0 到 1,越大通过速度越快,但是通过点距离当前目标点越远
:param lr: 1 右手系,-1 左手系,angle2>0 右手系,否则为左手系
:return:
0:正在执行其他指令,本次指令无效
1:本次指令生效,机械臂开始运动
2:设置速度小于等于零
3:未初始化
4:目标点无法到达
6:伺服未开启
7:无法以设定手系到达目标点位
11:手机端在控制
99:急停中
101:传入参数 NOT A NUMBER
102:发生碰撞,本次指令无效
103:轴发生复位,需要重新初始化,本次指令无效
"""
new_movej_xyz_lr
=
self
.
resolve
(
'robot_new_movej_xyz_lr'
,
c_int
,
*
[
c_int
,
c_float
,
c_float
,
c_float
,
c_float
,
c_float
,
c_float
,
c_int
])
if
new_movej_xyz_lr
is
None
:
return
HitBot_DLL_Warning
return
new_movej_xyz_lr
(
c_int
(
self
.
CardNumber
),
c_float
(
goal_x
),
c_float
(
goal_y
),
c_float
(
goal_z
),
c_float
(
goal_r
),
c_float
(
speed
),
c_float
(
roughly
),
c_int
(
lr
))
# 立即结束当前正在执行的指令
def
new_stop_move
(
self
):
"""
立即结束当前正在执行的指令
:return:
"""
new_stop_move
=
self
.
resolve
(
'robot_new_stop_move'
,
c_int
,
*
[
c_int
])
if
new_stop_move
is
None
:
return
HitBot_DLL_Warning
return
new_stop_move
(
c_int
(
self
.
CardNumber
))
# 更新编码器位置,调用后 encoder_x,encoder_y,encoder_z等变量会进行更新
def
get_encoder_coor
(
self
):
"""
:return:
"""
Locker
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
IOLocker
)
rec
=
self
.
_get_encoder_coor
()
return
rec
# 获取急停状态
def
get_hard_emergency_stop_state
(
self
)
->
int
:
"""
:return:
-1:该机型不支持;
0:未处于急停状态;
1:处于急停状态;
3:未连接;
4:没有急停功能;
"""
get_hard_emergency_stop_state
=
self
.
resolve
(
'robot_get_hard_emergency_stop_state'
,
c_int
,
*
[
c_int
])
if
get_hard_emergency_stop_state
is
None
:
return
HitBot_DLL_Warning
return
get_hard_emergency_stop_state
(
c_int
(
self
.
CardNumber
))
pass
# 急停按钮复位后,发送清除急停状态,进入正常模式
def
clear_hard_emergency_stop
(
self
)
->
int
:
"""
:return:
-1:该机型不支持;
0:未处于急停状态;
1:解除成功;
1:解除超时
3:未连接;
4:没有急停功能;
5:正处于急停状态
"""
clear_hard_emergency_stop
=
self
.
resolve
(
'robot_clear_hard_emergency_stop'
,
c_int
,
*
[
c_int
])
if
clear_hard_emergency_stop
is
None
:
return
HitBot_DLL_Warning
return
clear_hard_emergency_stop
(
c_int
(
self
.
CardNumber
))
pass
# 查询机械臂是否到达目标点
def
is_robot_goto_target
(
self
,
target_x
:
float
,
target_y
:
float
,
target_z
:
float
,
target_r
:
float
)
->
int
:
"""
:param target_x: 目标点 x 坐标(mm)
:param target_y: 目标点 y 坐标(mm)
:param target_z: 目标点 z 坐标(mm)
:param target_r: 目标点 r 坐标(mm)
:return: 0:未到达;1:已到达;
"""
is_robot_goto_target
=
self
.
resolve
(
'robot_is_robot_goto_target'
,
c_int
,
*
[
c_int
,
c_float
,
c_float
,
c_float
,
c_float
])
if
is_robot_goto_target
is
None
:
return
HitBot_DLL_Warning
return
is_robot_goto_target
(
c_int
(
self
.
CardNumber
),
c_float
(
target_x
),
c_float
(
target_y
),
c_float
(
target_z
),
c_float
(
target_r
))
pass
# 485 夹爪手动初始化
def
com485_initial
(
self
,
baudRate
:
int
)
->
int
:
"""
:param baudRate: 波特率
:return:
1:夹爪初始化成功;
2:未初始化;
3:未连接;
4:波特率过小;
5:波特率过大;
6:接收超时;
7:设定反馈超时;
8:非 485 扩展模块;
-1:I/O 板发送超时;
"""
com485_initial
=
self
.
resolve
(
'robot_com485_initial'
,
c_int
,
*
[
c_int
,
c_int
])
if
com485_initial
is
None
:
return
HitBot_DLL_Warning
return
com485_initial
(
c_int
(
self
.
CardNumber
),
c_int
(
baudRate
))
pass
# 485 夹爪设置旋转速度
def
com485_set_rotation_speed
(
self
,
speed
:
float
)
->
int
:
"""
:param speed:旋转速度
:return:1:夹爪设置相对旋转角度成功;-1:I/0 板发送超时;-2:485 发送超时;2:准备发送状态位置超时;
3:下位机进入接收发送数据状态超时;6:接收超时;8:非 485 扩展模块;
"""
com485_set_rotation_speed
=
self
.
resolve
(
'robot_com485_set_rotation_speed'
,
c_int
,
*
[
c_int
,
c_float
])
if
com485_set_rotation_speed
is
None
:
return
HitBot_DLL_Warning
return
com485_set_rotation_speed
(
c_int
(
self
.
CardNumber
),
c_float
(
speed
))
# 485 夹爪设置夹持速度
def
com485_set_clamping_speed
(
self
,
speed
:
float
)
->
int
:
"""
:param speed: 夹持速度
:return:1:夹爪设置相对旋转角度成功;-1:I/0 板发送超时;-2:485 发送超时;2:准备发送状态位置超时;
3:下位机进入接收发送数据状态超时;6:接收超时;8:非 485 扩展模块;
"""
com485_set_clamping_speed
=
self
.
resolve
(
'robot_com485_set_clamping_speed'
,
c_int
,
*
[
c_int
,
c_float
])
if
com485_set_clamping_speed
is
None
:
return
HitBot_DLL_Warning
return
com485_set_clamping_speed
(
c_int
(
self
.
CardNumber
),
c_float
(
speed
))
pass
# 485 夹爪设置夹持距离
def
com485_set_clamping_distance
(
self
,
distance
:
float
):
"""
:param distance: 夹持距离
:return:1:夹爪设置相对旋转角度成功;-1:I/0 板发送超时;-2:485 发送超时;2:准备发送状态位置超时;
3:下位机进入接收发送数据状态超时;6:接收超时;8:非 485 扩展模块;
"""
com485_set_clamping_distance
=
self
.
resolve
(
'robot_com485_set_clamping_distance'
,
c_int
,
*
[
c_int
,
c_float
])
if
com485_set_clamping_distance
is
None
:
return
HitBot_DLL_Warning
return
com485_set_clamping_distance
(
c_int
(
self
.
CardNumber
),
c_float
(
distance
))
pass
# 485 夹爪获取夹持距离
def
com485_get_clamping_distance
(
self
)
->
float
:
"""
:return: 夹持距离
"""
com485_get_clamping_distance
=
self
.
resolve
(
'robot_com485_get_clamping_distance'
,
c_int
,
*
[
c_int
])
if
com485_get_clamping_distance
is
None
:
return
HitBot_DLL_Warning
return
com485_get_clamping_distance
(
c_int
(
self
.
CardNumber
))
pass
# 485 夹爪设置绝对旋转角度
def
com485_set_rotation_angle
(
self
,
angle
:
float
)
->
int
:
"""
:param angle: 绝对旋转角度
:return:1:夹爪设置相对旋转角度成功;-1:I/0 板发送超时;-2:485 发送超时;2:准备发送状态位置超时;
3:下位机进入接收发送数据状态超时;6:接收超时;8:非 485 扩展模块;
"""
com485_set_clamping_distance
=
self
.
resolve
(
'robot_com485_set_clamping_distance'
,
c_int
,
*
[
c_int
,
c_float
])
if
com485_set_clamping_distance
is
None
:
return
HitBot_DLL_Warning
return
com485_set_clamping_distance
(
c_int
(
self
.
CardNumber
),
c_float
(
angle
))
# 485 夹爪设置相对旋转角度
def
com485_set_relative_rotation_angle
(
self
,
angle
:
float
):
"""
:param angle: 相对旋转角度
:return:1:夹爪设置相对旋转角度成功;-1:I/0 板发送超时;-2:485 发送超时;2:准备发送状态位置超时;
3:下位机进入接收发送数据状态超时;6:接收超时;8:非 485 扩展模块;
"""
com485_set_relative_rotation_angle
=
self
.
resolve
(
'robot_com485_set_relative_rotation_angle'
,
c_int
,
*
[
c_int
,
c_float
])
if
com485_set_relative_rotation_angle
is
None
:
return
HitBot_DLL_Warning
return
com485_set_relative_rotation_angle
(
c_int
(
self
.
CardNumber
),
c_float
(
angle
))
# 485 夹爪获取旋转角度
def
com485_get_rotation_angle
(
self
)
->
float
:
"""
:return: 旋转角度
"""
com485_get_rotation_angle
=
self
.
resolve
(
'robot_com485_get_rotation_angle'
,
c_int
,
*
[
c_int
])
if
com485_get_rotation_angle
is
None
:
return
HitBot_DLL_Warning
return
com485_get_rotation_angle
(
c_int
(
self
.
CardNumber
))
# 485 夹爪获取夹持状态
def
com485_get_clamping_state
(
self
)
->
int
:
"""
0:到位;
1:运动中;
2:夹持;
3:掉落;
:return:
"""
com485_get_clamping_state
=
self
.
resolve
(
'robot_com485_get_clamping_state'
,
c_int
,
*
[
c_int
])
if
com485_get_clamping_state
is
None
:
return
HitBot_DLL_Warning
return
com485_get_clamping_state
(
c_int
(
self
.
CardNumber
))
# 485 夹爪获取旋转状态
def
com485_get_rotation_state
(
self
):
"""
:return: 0:到位;1:运动中;2:夹持;3:掉落;
"""
com485_get_rotation_state
=
self
.
resolve
(
'robot_com485_get_rotation_state'
,
c_int
,
*
[
c_int
])
if
com485_get_rotation_state
is
None
:
return
HitBot_DLL_Warning
return
com485_get_rotation_state
(
c_int
(
self
.
CardNumber
))
# RS485 夹爪发送数据控制夹爪
def
com485_send
(
self
,
data
:
bytes
,
len
:
int
)
->
int
:
"""
:param data: 485 夹爪数据
:param len: 485 夹爪数据长度
:return:
1:夹爪发送数据成功;
-1:I/0 板发送超时;
-2:485 发送超时;
2:准备发送状态位置超时;
3:下位机进入接收发送数据状态超时;
6:接收超时;
8:非 485 扩展模块;
"""
com485_send
=
self
.
resolve
(
'robot_com485_recv'
,
c_int
,
*
[
c_char_p
,
c_char
])
if
com485_send
is
None
:
return
HitBot_DLL_Warning
return
com485_send
(
c_int
(
self
.
CardNumber
),
c_char_p
(
data
),
c_char
(
len
))
# RS485 夹爪接收返回数据
def
com485_recv
(
self
,
data
:
bytes
)
->
int
:
"""
:param data: 485 夹爪返回数据
:return: 8:夹爪返回数据长度; -1:非 485 扩展模块; 0:485 接收失败;
"""
com485_recv
=
self
.
resolve
(
'robot_com485_recv'
,
c_int
,
*
[
c_char_p
])
if
com485_recv
is
None
:
return
HitBot_DLL_Warning
return
com485_recv
(
c_int
(
self
.
CardNumber
),
c_char_p
(
data
))
# 立刻停止机械臂运动,然后释放除上下以外关节的转矩
def
emergency_stop
(
self
):
emergency_stop
=
self
.
resolve
(
'robot_emergency_stop'
,
c_void_p
,
*
[
c_int
])
if
emergency_stop
is
None
:
return
HitBot_DLL_Warning
return
emergency_stop
(
c_int
(
self
.
CardNumber
))
# 判断点位是否可以到达
def
judge_in_range_xyzr
(
self
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
)
->
bool
:
"""
:param x:x 坐标(mm)
:param y:y 坐标(mm)
:param z:z 坐标(mm)
:param r:r 坐标(deg)
:return: false:超出范围无法到达; true:可以到达;
"""
judge_in_range_xyzr
=
self
.
resolve
(
'robot_judge_in_range_xyzr'
,
c_void_p
,
*
[
c_int
,
c_float
,
c_float
,
c_float
,
c_float
])
if
judge_in_range_xyzr
is
None
:
return
False
return
judge_in_range_xyzr
(
c_int
(
self
.
CardNumber
),
c_float
(
x
),
c_float
(
y
),
c_float
(
z
),
c_float
(
r
))
pass
# 检查关节是否有效
def
check_joint
(
self
,
joint_num
:
int
,
state
:
bool
)
->
bool
:
"""
:param joint_num:关节号 1-4
:param state: true 开启关节 false 屏蔽
:return: true:设置关节是否生效成功; false:关节号错误;
"""
check_joint
=
self
.
resolve
(
'robot_check_joint'
,
c_bool
,
*
[
c_int
,
c_int
,
c_bool
])
if
check_joint
is
None
:
return
False
return
check_joint
(
c_int
(
self
.
CardNumber
),
c_int
(
joint_num
),
c_bool
(
state
))
# 驱动机械臂某一个轴旋转指定角度
def
single_joint_move
(
self
,
axis
:
int
,
distance
:
float
,
speed
:
float
):
"""
:param axis : 关节号 1-4 正方向
:param distance : 旋转角度(deg)
:param speed :轴 3 为线速度(mm/s),其他为旋转速度(deg/s)
:return :
0:正在执行其他指令,本次指令无效;
1:本次指令生效,机械臂开始运动;
2:设置速度小于等于零;
3:未初始化;
5:轴号参数错误;
6:伺服未开启;
11:手机端在控制;
101:传入参数 NOT A NUMBER;
102:发生碰撞,本次指令无效;
103:轴发生复位,需要重新初始化,本次指令无效;
"""
single_joint_move
=
self
.
resolve
(
'robot_single_joint_move'
,
c_int
,
*
[
c_int
,
c_int
,
c_float
,
c_float
])
if
single_joint_move
is
None
:
return
HitBot_DLL_Warning
return
single_joint_move
(
c_int
(
self
.
CardNumber
),
c_int
(
axis
),
c_float
(
distance
),
c_float
(
speed
))
pass
# 驱动机械臂沿某一方向运动指定距离
def
xyz_move
(
self
,
direction
:
int
,
distance
:
float
,
speed
:
float
):
"""
:param direction: 1 x 轴正方向,2 y 轴正方向,3 z 轴正方向
:param distance: 移动距离(mm)
:param speed: 移动速度(mm/s)
:return:
0:正在执行其他指令,本次指令无效;
1:本次指令生效,机械臂开始运动;
2:设置速度小于等于零;
3:未初始化;
4:过程点无法到达;
5:方向参数错误;
6:伺服未开启;
7:该姿态无法完成直线运动;
11:手机端在控制;
101:传入参数 NOT A NUMBER;
102:发生碰撞,本次指令无效;
103:轴发生复位,需要重新初始化,本次指令无效;
"""
xyz_move
=
self
.
resolve
(
'robot_xyz_move'
,
c_int
,
*
[
c_int
,
c_int
,
c_float
,
c_float
])
if
xyz_move
is
None
:
return
HitBot_DLL_Warning
return
xyz_move
(
c_int
(
self
.
CardNumber
),
c_int
(
direction
),
c_float
(
distance
),
c_float
(
speed
))
pass
# 设置轨迹插补缓存区长度,减小或者增大停止或者暂停延时
def
set_Interpolation_position_buf_catch_count
(
self
,
count
:
int
):
"""
:param count:插补缓存区长度,默认 200,区间 [32,4096]
:return: 1:设置成功; 3:未初始化;
"""
set_Interpolation_position_buf_catch_count
=
self
.
resolve
(
'robot_set_Interpolation_position_buf_catch_count'
,
c_int
,
*
[
c_int
,
c_int
])
if
set_Interpolation_position_buf_catch_count
is
None
:
return
HitBot_DLL_Warning
return
set_Interpolation_position_buf_catch_count
(
c_int
(
self
.
CardNumber
),
c_int
(
count
))
pass
# 设置手臂执行缓存区长度,减小或者增大停止或者暂停延时
def
set_robot_buf_size
(
self
,
bufsize
:
int
)
->
int
:
"""
:param bufsize: 插补缓存区长度,默认 850,区间 [32,900]
:return:1:设置成功; 3:未初始化;
"""
set_robot_buf_size
=
self
.
resolve
(
'robot_set_robot_buf_size'
,
c_int
,
*
[
c_int
,
c_int
])
if
set_robot_buf_size
is
None
:
return
HitBot_DLL_Warning
return
set_robot_buf_size
(
c_int
(
self
.
CardNumber
),
c_int
(
bufsize
))
pass
# 设置各关节转矩设定值,限制电机输出转矩范围,来调节碰撞检测的灵敏度
def
set_robot_joint_torque_value
(
self
,
jointnum
:
int
,
value
:
int
):
"""
:param jointnum: 轴编号
:param value: 转矩设定值,[1000,20000]
:return:0:未连接;1:设置成功;2:轴号错误;3:未初始化;
"""
set_robot_joint_torque_value
=
self
.
resolve
(
'robot_set_robot_joint_torque_value'
,
c_int
,
*
[
c_int
,
c_int
,
c_int
])
if
set_robot_joint_torque_value
is
None
:
return
HitBot_DLL_Warning
return
set_robot_joint_torque_value
(
c_int
(
self
.
CardNumber
),
c_int
(
jointnum
),
c_int
(
value
))
pass
# 设置停止 I/O
def
set_stop_io
(
self
,
io_number
:
int
,
io_value
:
int
):
"""
:param io_number:I/O 号
:param io_value::I/0 信号值
:return: 0:设置停止 I/O 成功;
"""
robot_set_stop_io
=
self
.
resolve
(
'robot_set_stop_io'
,
c_int
,
*
[
c_int
,
c_int
,
c_int
])
if
robot_set_stop_io
is
None
:
return
HitBot_DLL_Warning
return
robot_set_stop_io
(
c_int
(
self
.
CardNumber
),
c_int
(
io_number
),
c_int
(
io_value
))
# 获取错误信息
def
get_error_code
(
self
):
robot_get_error_code
=
self
.
resolve
(
"robot_get_error_code"
,
c_int
,
*
[
c_int
])
if
robot_get_error_code
is
None
:
return
HitBot_DLL_Warning
return
robot_get_error_code
(
c_int
(
self
.
CardNumber
))
AppCore/AppImplsbak/MicroscopeImpl.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: MicroscopeImpl.py
@DateTime: 2025/4/8 20:21
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
from
abc
import
abstractmethod
from
AppCore.AppContextModels.MicroscopeContext
import
MicroscopeContext
from
AppCore.AppRequestModels.SerialRequest
import
SerialRequest
from
AppInterfaces.ImplInterface
import
(
ImplInterface
,
AppUtils
,
AppConvert
,
AppTimeLoop
,
log_exceptions
)
from
AppInterfaces.SingletonInterface
import
(
SingletonInterface
)
from
AppSettings.Settings
import
(
RECODE_FAILURE
,
RECODE_SUCCEED
)
from
AppCore.AppLevelModels.ObjectiveLevel
import
ObjectiveLevel
from
AppCore.DBModels
import
ObjectiveModel
,
FocusingConfigModel
from
AppCore.ImplInterfaces
import
MicroscopeInterface
MAX_SERIAL_DEFAULT_WAIT_TIMES
:
int
=
1500
MAX_SERIAL_READ_DELAY
:
int
=
5
MAX_SERIAL_SEND_BUFFER_LENGTH
:
int
=
255
class
MicroscopeImpl
(
Qt
.
QObject
,
MicroscopeInterface
,
SingletonInterface
):
Manager
:
Qt
.
QSerialPort
Parameter
:
MicroscopeContext
StartTime
:
Qt
.
QTime
isMoving
:
bool
Locker
:
Qt
.
QMutex
=
Qt
.
QMutex
()
_IsInitialize
:
bool
@
classmethod
def
GetInstance
(
cls
,
*
args
,
**
kwargs
)
->
'MicroscopeImpl'
:
return
super
(
MicroscopeImpl
,
cls
)
.
GetInstance
(
*
args
,
**
kwargs
)
@
property
def
parameter
(
self
)
->
MicroscopeContext
:
return
None
if
not
self
.
hasParameter
else
self
.
Parameter
def
initContext
(
self
):
from
AppSettings.AppSetting
import
AppSetting
,
AppConfig
self
.
Parameter
=
AppConfig
.
microscopeConfig
def
initManager
(
self
,
context
:
MicroscopeContext
=
None
,
**
args
):
self
.
initContext
()
if
not
self
.
hasManager
:
self
.
Manager
=
Qt
.
QSerialPort
()
def
__init__
(
self
,
parent
:
Qt
.
QObject
=
None
):
super
(
MicroscopeImpl
,
self
)
.
__init__
(
parent
=
parent
)
self
.
Initialization
(
"MicroscopeImpl"
,
self
,
parent
)
def
setParameter
(
self
,
context
:
MicroscopeContext
):
pass
def
initValue
(
self
):
super
(
MicroscopeImpl
,
self
)
.
initValue
()
self
.
initManager
()
self
.
StartTime
=
Qt
.
QTime
.
currentTime
()
def
deleValue
(
self
):
super
(
MicroscopeImpl
,
self
)
.
deleValue
()
self
.
Close
()
self
.
Manager
=
None
self
.
Parameter
=
None
def
deleManager
(
self
):
if
self
.
hasManager
:
self
.
Close
()
self
.
Manager
.
deleteLater
()
self
.
Manager
=
None
def
Open
(
self
,
timeOut
:
int
=
1000
)
->
int
:
self
.
initContext
()
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
if
not
self
.
isValid
():
return
RECODE_FAILURE
if
self
.
IsOpen
():
self
.
Manager
.
close
()
self
.
Parameter
.
IsOpen
=
False
waittime
:
int
=
max
(
timeOut
,
self
.
Parameter
.
ReadWaitTime
)
ETime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
if
self
.
_OpenSerial
(
self
.
Manager
,
self
.
Parameter
)
==
RECODE_SUCCEED
:
break
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
self
.
initContext
()
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
self
.
_CloseSerial
(
self
.
Manager
,
self
.
Parameter
)
return
RECODE_SUCCEED
def
ReOpen
(
self
,
timeOut
:
int
=
1000
)
->
int
:
self
.
Close
(
timeOut
)
return
self
.
Open
(
timeOut
)
def
isEqual
(
self
,
other
)
->
bool
:
if
isinstance
(
other
,
MicroscopeImpl
):
return
self
.
Manager
==
other
.
Manager
return
False
def
SendString
(
self
,
buffer
:
str
,
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
_SendSerialPort
(
self
.
Manager
,
Qt
.
QByteArray
(
buffer
.
encode
(
'utf-8'
)),
self
.
Parameter
.
ReadWaitTime
)
def
SendBinary
(
self
,
buffer
:
(
bytes
,
bytearray
,
Qt
.
QByteArray
),
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
_SendSerialPort
(
self
.
Manager
,
Qt
.
QByteArray
(
buffer
),
self
.
Parameter
.
ReadWaitTime
)
def
Send
(
self
,
buffer
,
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
if
isinstance
(
buffer
,
str
):
return
self
.
SendString
(
buffer
)
elif
isinstance
(
buffer
,
(
bytes
,
bytearray
,
Qt
.
QByteArray
)):
return
self
.
SendBinary
(
buffer
)
elif
isinstance
(
buffer
,
SerialRequest
):
return
self
.
_SendSerialPort
(
self
.
Manager
,
Qt
.
QByteArray
(
buffer
.
TransmitBinary
),
self
.
Parameter
.
ReadWaitTime
)
return
RECODE_FAILURE
def
ReadBinary
(
self
)
->
Qt
.
QByteArray
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
Qt
.
QByteArray
()
buffer
=
self
.
_ReadSerialPort
(
self
.
Manager
,
-
1
,
self
.
Parameter
.
ReadWaitTime
)
return
buffer
def
Read
(
self
,
request
:
SerialRequest
,
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
()
or
not
isinstance
(
request
,
SerialRequest
):
return
RECODE_FAILURE
return
self
.
_ReadSerial
(
self
.
Manager
,
self
.
Parameter
,
request
,
request
.
ReceivedWaits
)
def
ReadMic
(
self
,
request
:
SerialRequest
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
()
or
not
isinstance
(
request
,
SerialRequest
):
return
RECODE_FAILURE
return
self
.
_ReadMicSerial
(
self
.
Manager
,
self
.
Parameter
,
request
,
request
.
ReceivedWaits
)
def
WaitDone
(
self
,
request
:
SerialRequest
):
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
()
or
not
isinstance
(
request
,
SerialRequest
):
return
request
.
ResultNumber
=
RECODE_FAILURE
isWrong
:
int
=
self
.
Send
(
request
.
TransmitBinary
)
request
.
ResultNumber
=
isWrong
if
RECODE_SUCCEED
!=
isWrong
:
return
self
.
Read
(
request
)
def
Transmit
(
self
,
data
:
object
,
**
args
)
->
int
:
if
not
self
.
hasManager
:
self
.
initManager
(
AppConfig
.
microscopeConfig
)
if
not
self
.
hasManager
:
return
RECODE_FAILURE
if
self
.
IsOpen
():
return
self
.
Send
(
data
,
**
args
)
return
RECODE_FAILURE
def
Received
(
self
,
data
:
object
,
**
args
)
->
int
:
if
not
self
.
hasManager
:
self
.
initManager
(
AppConfig
.
microscopeConfig
)
if
not
self
.
hasManager
:
return
RECODE_FAILURE
if
self
.
IsOpen
():
return
self
.
Read
(
data
,
**
args
)
return
RECODE_FAILURE
def
initMicroscopeEvent
(
self
):
isWrong
:
int
=
self
.
GET_INIT_STATUS
()
if
RECODE_SUCCEED
==
isWrong
:
self
.
SET_Z_STEP_MODE
(
1
)
self
.
read_empty
()
self
.
SET_MASTER_EVENT
()
self
.
SET_TL_EVENT
()
self
.
SET_FIELD_TL_EVENT
()
self
.
SET_LED_EVENT
()
self
.
SET_OBJ_EVENT
()
self
.
SET_CONFIG_MODE
(
0
)
self
.
SET_Z_EVENT
()
self
.
set_SPOTLIGHT_EVENT
()
self
.
read_empty
()
def
initMicroscopeObjective
(
self
):
isWrong
:
int
=
self
.
GET_INIT_STATUS
()
if
RECODE_SUCCEED
==
isWrong
:
self
.
changed_spot_light
(
False
)
Wrong_Objective1
:
int
Wrong_Objective10
:
int
Wrong_Objective20
:
int
Wrong_Objective40
:
int
Wrong_Objective63
:
int
Wrong_Objective100
:
int
Wrong_ObjectiveNone
:
int
Objective1
:
int
Objective10
:
int
Objective20
:
int
Objective40
:
int
Objective63
:
int
Objective100
:
int
ObjectiveNone
:
int
_Objective1
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
Objective1
)
_Objective10
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
Objective10
)
_Objective20
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
Objective20
)
_Objective40
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
Objective40
)
_Objective63
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
Objective63
)
_Objective100
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
Objective100
)
_ObjectiveNone
:
int
=
ObjectiveLevel
.
toParameters
()
.
get
(
ObjectiveLevel
.
ObjectiveNone
)
Objective1
,
Wrong_Objective1
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
Objective1
)
Objective10
,
Wrong_Objective10
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
Objective10
)
Objective20
,
Wrong_Objective20
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
Objective20
)
Objective40
,
Wrong_Objective40
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
Objective40
)
Objective63
,
Wrong_Objective63
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
Objective63
)
Objective100
,
Wrong_Objective100
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
Objective100
)
ObjectiveNone
,
Wrong_ObjectiveNone
=
self
.
GET_OBJPAR
(
ObjectiveLevel
.
ObjectiveNone
)
if
RECODE_SUCCEED
!=
Wrong_Objective1
or
Objective1
!=
_Objective1
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
Objective1
)
if
RECODE_SUCCEED
!=
Wrong_Objective10
or
Objective10
!=
_Objective10
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
Objective10
)
if
RECODE_SUCCEED
!=
Wrong_Objective20
or
Objective20
!=
_Objective20
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
Objective20
)
if
RECODE_SUCCEED
!=
Wrong_Objective40
or
Objective40
!=
_Objective40
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
Objective40
)
if
RECODE_SUCCEED
!=
Wrong_Objective63
or
Objective63
!=
_Objective63
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
Objective63
)
if
RECODE_SUCCEED
!=
Wrong_Objective100
or
Objective100
!=
_Objective100
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
Objective100
)
if
RECODE_SUCCEED
!=
Wrong_ObjectiveNone
or
ObjectiveNone
!=
_ObjectiveNone
:
self
.
SET_OBJPAR
(
ObjectiveLevel
.
ObjectiveNone
)
Objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
ObjectiveLevel
.
ObjectiveNone
)
self
.
set_z_speed
(
Objective
.
Default_Speed
)
self
.
set_z_range
(
Objective
.
Lower_Limit
,
Objective
.
Upper_Limit
)
self
.
changedObjective
(
ObjectiveLevel
.
ObjectiveNone
)
def
initZDriver
(
self
):
isWrong
:
int
=
self
.
GET_INIT_STATUS
()
if
RECODE_SUCCEED
==
isWrong
:
Objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
ObjectiveLevel
.
ObjectiveNone
)
self
.
SET_Z_STEP_MODE
(
1
)
self
.
BREAK_Z
()
self
.
isMoving
=
False
self
.
set_z_speed
(
Objective
.
Default_Speed
)
self
.
SET_LOWER_LIMIT
(
Objective
.
Lower_Limit
)
self
.
SET_UPPER_LIMIT
(
Objective
.
Upper_Limit
)
self
.
isMoving
=
True
self
.
INIT_Z
()
self
.
waitmove_finish
(
Objective
.
Lower_Limit
)
self
.
BREAK_Z
()
self
.
isMoving
=
False
self
.
SET_Z_EVENT
()
def
initMicroscopeZDrive
(
self
):
isWrong
:
int
=
self
.
GET_INIT_STATUS
()
if
RECODE_SUCCEED
==
isWrong
:
Objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
ObjectiveLevel
.
ObjectiveNone
)
self
.
SET_Z_STEP_MODE
(
1
)
self
.
BREAK_Z
()
self
.
isMoving
=
False
self
.
set_z_speed
(
Objective
.
Default_Speed
)
self
.
SET_LOWER_LIMIT
(
Objective
.
Lower_Limit
)
self
.
SET_UPPER_LIMIT
(
Objective
.
Upper_Limit
)
self
.
waitmove
(
Objective
.
Lower_Limit
)
self
.
isMoving
=
True
self
.
INIT_Z
()
self
.
waitmove_finish
(
Objective
.
Lower_Limit
)
self
.
BREAK_Z
()
self
.
isMoving
=
False
position
:
int
_warning
:
int
_warning
,
position
=
self
.
get_position
()
if
_warning
==
RECODE_SUCCEED
and
position
>
Objective
.
Lower_Limit
:
self
.
waitmove
(
Objective
.
Lower_Limit
)
_warning
,
position
=
self
.
get_position
()
if
_warning
==
RECODE_SUCCEED
and
position
>
Objective
.
Lower_Limit
:
self
.
waitmove
(
Objective
.
Lower_Limit
)
self
.
SET_Z_EVENT
()
def
initMicroscopeLight
(
self
):
pass
isWrong
:
int
=
self
.
GET_INIT_STATUS
()
if
RECODE_SUCCEED
==
isWrong
:
self
.
SET_SHUTTER_LAMP
(
True
)
# self.INIT_APBL_TL()
# self.INIT_LFBL_TL()
self
.
SET_MIN_POS_ABS_LAMP
()
self
.
SET_MIN_POS_ABS_LFBL_TL
()
self
.
SET_MIN_POS_ABS_APBL_TL
()
# self.POS_MAX_TL_DIAPH1 ()
# self.POS_MAX_TL_DIAPH2 ()
def
initMicroscope
(
self
):
self
.
_IsInitialize
=
False
self
.
initMicroscopeEvent
()
self
.
initMicroscopeLight
()
self
.
initMicroscopeZDrive
()
self
.
initMicroscopeObjective
()
self
.
initMicroscopeEvent
()
self
.
_IsInitialize
=
True
def
move_to_z_lower_limit
(
self
)
->
int
:
self
.
set_z_move_mode
(
1
)
Objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
ObjectiveLevel
.
ObjectiveNone
)
self
.
set_z_speed
(
Objective
.
Default_Speed
)
self
.
set_z_range
(
Objective
.
Lower_Limit
,
Objective
.
Upper_Limit
)
return
self
.
waitmove
(
Objective
.
Lower_Limit
)
def
openTL
(
self
):
return
self
.
SET_SHUTTER_LAMP
(
True
)
def
closeTL
(
self
):
return
self
.
SET_SHUTTER_LAMP
(
False
)
def
IsTLOpen
(
self
)
->
bool
:
isWrong
:
int
enable
:
int
isWrong
,
enable
=
self
.
GET_SHUTTER_LAMP
()
return
isWrong
==
RECODE_SUCCEED
and
enable
==
1
def
home
(
self
)
->
int
:
self
.
initMicroscope
()
isWrong
:
int
=
self
.
GET_INIT_STATUS
()
self
.
_IsInitialize
=
RECODE_SUCCEED
==
isWrong
return
isWrong
def
waithome
(
self
)
->
int
:
return
self
.
home
()
def
move
(
self
,
position
:
(
float
,
int
))
->
int
:
isWrong
=
self
.
SET_POS_ABS_Z
(
int
(
round
(
float
(
position
),
0
)))
return
isWrong
def
stop_move
(
self
)
->
int
:
return
self
.
BREAK_Z
()
def
rel_move
(
self
,
value
:
int
)
->
int
:
return
self
.
SET_POS_REL_Z
(
value
)
def
waitmove
(
self
,
position
:
(
int
,
float
))
->
int
:
_position
:
int
_target
:
int
=
abs
(
int
(
round
(
float
(
position
),
0
)))
isWrong
:
int
# if self.hasMoving and self.isMoving:
# return RECODE_FAILURE
self
.
isMoving
=
True
isWrong
=
self
.
SET_POS_ABS_Z
(
_target
)
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
1000
)
while
True
:
if
RECODE_SUCCEED
==
isWrong
or
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
isWrong
=
self
.
SET_POS_ABS_Z
(
_target
)
isWrong
=
self
.
waitmove_complete
(
_target
)
self
.
isMoving
=
False
# AppTimeLoop.msleep(50)
return
isWrong
@
property
def
hasMoving
(
self
)
->
bool
:
return
hasattr
(
self
,
'isMoving'
)
and
isinstance
(
self
.
isMoving
,
(
bool
,
int
))
async
def
async_waitmove
(
self
,
position
:
(
int
,
float
))
->
int
:
_position
:
int
_target
:
int
=
int
(
round
(
float
(
position
),
0
))
isWrong
:
int
self
.
SET_POS_ABS_Z
(
_target
)
isWrong
=
self
.
waitmove_complete
(
_target
)
# AppTimeLoop.msleep(50)
return
isWrong
def
waitmove_complete
(
self
,
position
:
(
int
,
float
))
->
int
:
_position
:
int
_target
:
int
=
abs
(
int
(
round
(
float
(
position
),
0
)))
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
360000
)
begintime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
processtime
:
Qt
.
QDateTime
waittimes
:
int
=
0
waitdelay
:
int
=
5
count
:
int
=
0
maxCount
:
int
=
10
isWrong
,
_position
=
self
.
GET_POS_ABS_Z
()
last_position
:
int
=
_position
isWrong
:
int
=
RECODE_FAILURE
Moving
:
int
=
None
Lower
:
int
=
None
Upper
:
int
=
None
Limit
:
int
=
None
Focus
:
int
=
None
while
True
:
try
:
if
int
(
_position
)
==
int
(
_target
)
and
RECODE_SUCCEED
==
isWrong
:
break
except
Exception
as
e
:
pass
isWrong
,
Moving
,
Lower
,
Upper
,
Limit
,
Focus
=
self
.
ZDriverMoveStatus
()
if
RECODE_SUCCEED
==
isWrong
:
if
isinstance
(
Moving
,
int
)
and
not
Moving
:
break
if
isinstance
(
Lower
,
int
)
and
Lower
:
break
if
isinstance
(
Upper
,
int
)
and
Upper
:
break
if
isinstance
(
Limit
,
int
)
and
Limit
:
break
if
isinstance
(
Focus
,
int
)
and
Focus
:
break
isWrong
,
_position
=
self
.
GET_POS_ABS_Z
()
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
delay
(
waitdelay
)
self
.
BREAK_Z
()
self
.
isMoving
=
False
return
isWrong
def
waitmove_finish
(
self
,
position
:
(
int
,
float
))
->
int
:
_position
:
int
_target
:
int
=
int
(
round
(
float
(
position
),
0
))
isWrong
,
_position
=
self
.
GET_POS_ABS_Z
()
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
360000
)
processtime
:
Qt
.
QDateTime
=
endtime
.
addMSecs
(
500
)
waittimes
:
int
=
0
waitdelay
:
int
=
10
old_position
:
int
=
_position
while
_position
!=
_target
:
isWrong
,
Moving
,
Lower
,
Upper
,
Limit
,
Focus
=
self
.
ZDriverMoveStatus
()
if
RECODE_SUCCEED
==
isWrong
:
if
isinstance
(
Moving
,
int
)
and
Moving
==
0
:
break
if
isinstance
(
Lower
,
int
)
and
Lower
:
break
if
isinstance
(
Upper
,
int
)
and
Upper
:
break
if
isinstance
(
Limit
,
int
)
and
Limit
:
break
if
isinstance
(
Focus
,
int
)
and
Focus
:
break
isWrong
,
_position
=
self
.
GET_POS_ABS_Z
()
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
if
Qt
.
QDateTime
.
currentDateTime
()
>
processtime
:
if
old_position
==
_position
:
break
try
:
if
int
(
_position
)
==
int
(
_target
):
break
except
Exception
as
e
:
pass
waittimes
+=
waitdelay
AppTimeLoop
.
processEvents
(
waitdelay
)
# self.waitmove_finish(Objective.Lower_Limit)
self
.
BREAK_Z
()
self
.
isMoving
=
False
return
RECODE_SUCCEED
def
waitmove_lower_limit
(
self
):
isWrong
,
low_limit
=
self
.
GET_LOW_LIMIT_Z
()
self
.
SET_Z_STEP_MODE
(
1
)
self
.
waitmove
(
low_limit
if
isinstance
(
low_limit
,
(
float
,
int
))
else
0
)
return
RECODE_SUCCEED
def
waitmove_upper_limit
(
self
)
->
int
:
return
self
.
waitmove
(
self
.
MAX_Z_POSITION
)
def
getPosition
(
self
)
->
int
:
isWrong
:
int
position
:
int
isWrong
,
position
=
self
.
GET_POS_ABS_Z
()
return
position
def
setFastSpeedMode
(
self
):
return
self
.
SET_Z_STEP_MODE
(
1
)
def
setNormalSpeedMode
(
self
):
return
self
.
SET_Z_STEP_MODE
(
0
)
def
changedObjective
(
self
,
level
:
int
,
is_lower_limit
:
bool
=
True
)
->
int
:
# if is_lower_limit:
# isWrong = self.waitmove_lower_limit()
# else:
# isWrong = self.waitmove_safe(level)
# if isWrong != RECODE_SUCCEED:
# return isWrong
self
.
BREAK_Z
()
isWrong
=
self
.
SET_OBJ_POS_ABS_OBJ
(
level
)
if
RECODE_SUCCEED
!=
isWrong
:
isWrong
=
self
.
SET_OBJ_POS_ABS_OBJ
(
level
)
self
.
changedLightIntensity
(
level
)
self
.
BREAK_Z
()
return
isWrong
def
changedLightIntensity
(
self
,
level
:
int
)
->
int
:
isWrong
:
int
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
self
.
SET_SHUTTER_LAMP
(
True
)
self
.
SET_POS_ABS_LAMP
(
objective
.
LAMP
)
self
.
SET_POS_ABS_APBL_TL
(
objective
.
APBL
)
self
.
SET_POS_ABS_LFBL_TL
(
objective
.
LFBL
)
self
.
set_z_range
(
objective
.
Lower_Limit
,
objective
.
Upper_Limit
)
self
.
set_z_speed
(
objective
.
Default_Speed
)
self
.
set_z_move_mode
(
1
)
return
RECODE_SUCCEED
def
waitmove_safe
(
self
,
level
)
->
int
:
isWrong
:
int
position
:
int
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
isWrong
=
self
.
waitmove
(
objective
.
Safe_Limit
)
return
isWrong
def
get_objective_safe_limit
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Safe_Limit
def
get_objective_lower_limit
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Lower_Limit
def
get_objective_upper_limit
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Upper_Limit
def
get_objective_focus_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Focus_Speed
def
get_objective_first_focus_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
First_Focus_Speed
def
get_objective_second_focus_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Second_Focus_Speed
def
get_objective_three_focus_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Three_Focus_Speed
def
get_objective_default_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Default_Speed
def
get_objective_scan_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
objective
.
Scan_Speed
def
set_z_upper_limit
(
self
,
limit
=
-
1
)
->
int
:
return
self
.
SET_UPPER_LIMIT
(
int
(
limit
))
def
set_z_lower_limit
(
self
,
limit
=
-
1
)
->
int
:
return
self
.
SET_LOW_LIMIT_Z
(
int
(
limit
))
def
set_z_range
(
self
,
min_limit
:
int
=
-
1
,
max_limit
:
int
=
-
1
)
->
int
:
self
.
SET_LOW_LIMIT_Z
(
min_limit
)
self
.
SET_UPPER_LIMIT
(
max_limit
)
return
RECODE_SUCCEED
def
set_z_speed
(
self
,
speed
:
(
float
,
int
)):
return
self
.
SET_SPEED_Z
(
speed
)
def
set_z_move_mode
(
self
,
enable
:
(
int
,
bool
)):
return
self
.
SET_Z_STEP_MODE
(
1
if
isinstance
(
enable
,
(
int
,
bool
))
and
enable
else
0
)
def
set_objective_upper_limit
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
self
.
SET_UPPER_LIMIT
(
int
(
objective
.
Upper_Limit
))
def
set_objective_limit
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
self
.
SET_LOW_LIMIT_Z
(
int
(
objective
.
Lower_Limit
))
self
.
SET_UPPER_LIMIT
(
int
(
objective
.
Upper_Limit
))
self
.
SET_SPEED_Z
(
int
(
objective
.
Default_Speed
))
self
.
SET_Z_STEP_MODE
(
1
)
return
RECODE_SUCCEED
def
set_objective_lower_limit
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
self
.
SET_LOW_LIMIT_Z
(
int
(
objective
.
Lower_Limit
))
def
set_objective_focus_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
self
.
SET_SPEED_Z
(
objective
.
Focus_Speed
)
def
set_objective_default_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
self
.
SET_SPEED_Z
(
objective
.
Default_Speed
)
def
set_objective_scan_speed
(
self
,
level
)
->
int
:
objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
return
self
.
SET_SPEED_Z
(
objective
.
Scan_Speed
)
def
set_upper_limit
(
self
,
position
:
(
int
,
float
))
->
int
:
return
self
.
SET_UPPER_LIMIT
(
int
(
position
))
def
set_lower_limit
(
self
,
position
:
(
int
,
float
))
->
int
:
return
self
.
SET_LOW_LIMIT_Z
(
int
(
position
))
def
get_position
(
self
)
->
(
int
,
int
):
isWrong
:
int
position
:
int
isWrong
,
position
=
self
.
GET_POS_ABS_Z
()
return
isWrong
,
position
def
getObjective
(
self
)
->
int
:
isWrong
:
int
position
:
int
isWrong
,
position
=
self
.
GET_OBJ_POS_ABS_OBJ
()
return
position
def
currentObjective
(
self
)
->
(
int
,
int
):
isWrong
:
int
objective
:
int
isWrong
,
objective
=
self
.
GET_OBJ_POS_ABS_OBJ
()
return
isWrong
,
objective
def
SET_MASTER_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
70003
,
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
70003
return
isWrong
==
RECODE_SUCCEED
def
SET_OBJ_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
76003
,
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
76003
return
isWrong
==
RECODE_SUCCEED
def
SET_LAMP_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
77003
,
0
,
0
,
0
,
0
,
0
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
71003
return
isWrong
==
RECODE_SUCCEED
def
SET_Z_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
71003
,
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
71003
return
isWrong
==
RECODE_SUCCEED
def
SET_TL_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
84003
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
84003
return
isWrong
==
RECODE_SUCCEED
def
SET_FIELD_TL_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
83003
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
83003
return
isWrong
==
RECODE_SUCCEED
def
SET_LED_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
77003
,
0
,
0
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
77003
return
isWrong
==
RECODE_SUCCEED
def
set_SPOTLIGHT_EVENT
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
80003
,
0
,
0
,
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
return
result_list
[
0
]
==
80003
return
isWrong
==
RECODE_SUCCEED
def
CHECK_PROG
(
self
)
->
bool
:
"""返回固件状态 0 = 固件正在从引导扇区运行 1 = 固件正在从程序内存运行"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__CHECK_PROG
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
return
result_list
[
0
]
==
self
.
__CHECK_PROG
and
isinstance
(
result_list
[
1
],
int
)
and
int
(
result_list
[
1
])
==
1
return
isWrong
==
RECODE_SUCCEED
def
SET_TO_DEFAULT
(
self
):
"""个显微镜重置为出厂默认设置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_TO_DEFAULT
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
and
isinstance
(
result_list
[
0
],
int
):
isWrong
=
RECODE_SUCCEED
if
result_list
[
0
]
==
self
.
__SET_TO_DEFAULT
else
RECODE_FAILURE
return
isWrong
def
SET_CONFIG_MODE
(
self
,
enable
:
(
int
,
bool
)
=
0
):
"""设置配置模式 0: 配置模式关闭 1:配置模式开启"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_CONFIG_MODE
,
1
if
isinstance
(
enable
,
(
int
,
bool
))
and
enable
else
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
and
isinstance
(
result_list
[
0
],
int
):
isWrong
=
RECODE_SUCCEED
if
result_list
[
0
]
==
self
.
__SET_CONFIG_MODE
else
RECODE_FAILURE
return
isWrong
def
GET_CONFIG_MODE
(
self
):
"""设置配置模式 0: 配置模式关闭 1:配置模式开启"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_CONFIG_MODE
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
False
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
result_list
[
0
]
==
self
.
__GET_OBJ_POS_ABS_OBJ
and
isinstance
(
result_list
[
1
],
int
):
isWrong
=
result_list
[
1
]
return
isWrong
def
GET_INIT_STATUS
(
self
)
->
int
:
"""70080 获取初始化状态 0: 硬件初始化未完成 1:硬件初始化完成"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_INIT_STATUS
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_INIT_STATUS
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
if
result_list
[
1
]
==
1
else
RECODE_FAILURE
self
.
SET_Z_EVENT
()
return
isWrong
def
INIT_OBJPAR
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
level
=
ObjectiveLevel
.
ObjectiveNone
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_OBJPAR
,
level
,
1
,
ObjectiveLevel
.
toParameters
()
.
get
(
level
))
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_OBJPAR
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_OBJPAR
(
self
,
level
:
int
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
Objective
:
ObjectiveModel
=
ObjectiveModel
.
getObjectiveConfig
(
level
)
if
self
.
hasDone
():
parameters
:
list
=
[
(
Objective
.
Level
,
1
,
ObjectiveLevel
.
toParameters
()
.
get
(
level
)
),
(
Objective
.
Level
,
10
,
Objective
.
LFBL
),
# 设置放大倍率
(
Objective
.
Level
,
11
,
Objective
.
APBL
),
# 设置视场光阑值
(
Objective
.
Level
,
14
,
Objective
.
LAMP
),
# 设置孔径光阑值
]
for
parameter
in
parameters
:
self
.
execute
(
self
.
__SET_OBJPAR
,
*
parameter
)
return
RECODE_SUCCEED
def
GET_OBJPAR
(
self
,
level
:
int
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
level
in
ObjectiveLevel
.
all
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_OBJPAR
,
level
,
1
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
4
:
if
result_list
[
0
]
==
self
.
__GET_OBJPAR
and
isinstance
(
result_list
[
1
],
int
)
and
isinstance
(
result_list
[
3
],
int
):
if
result_list
[
1
]
==
level
:
return
RECODE_SUCCEED
,
result_list
[
3
]
self
.
SET_Z_EVENT
()
return
isWrong
,
0
def
SET_OBJ_POS_ABS_OBJ
(
self
,
level
:
int
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
level
in
ObjectiveLevel
.
toList
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_OBJ_POS_ABS_OBJ
,
level
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_OBJ_POS_ABS_OBJ
:
isWrong
=
RECODE_SUCCEED
else
:
AppTimeLoop
.
msleep
(
50
)
self
.
ReadMic
(
request
)
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_OBJ_POS_ABS_OBJ
:
isWrong
=
RECODE_SUCCEED
AppTimeLoop
.
msleep
(
1000
)
return
isWrong
def
GET_OBJ_POS_ABS_OBJ
(
self
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_OBJ_POS_ABS_OBJ
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
ObjectiveLevel
.
ObjectiveNone
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_OBJ_POS_ABS_OBJ
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
self
.
SET_Z_EVENT
()
return
isWrong
,
ObjectiveLevel
.
ObjectiveNone
def
SET_POS_ABS_LAMP
(
self
,
intensity
:
int
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
0
<=
intensity
<=
255
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_POS_ABS_LAMP
,
intensity
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_POS_ABS_LAMP
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_MAX_POS_ABS_LAMP
(
self
)
->
int
:
isWrong
:
int
=
self
.
SET_POS_ABS_LAMP
(
255
)
return
isWrong
def
SET_MIN_POS_ABS_LAMP
(
self
)
->
int
:
isWrong
:
int
=
self
.
SET_POS_ABS_LAMP
(
1
)
return
isWrong
def
GET_POS_ABS_LAMP
(
self
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_POS_ABS_LAMP
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_POS_ABS_LAMP
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
1
def
SET_SHUTTER_LAMP
(
self
,
enable
:
(
bool
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
enable
,
(
bool
,
int
)):
_enable
:
int
=
1
if
enable
==
True
or
enable
==
1
else
0
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_SHUTTER_LAMP
,
0
,
_enable
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_SHUTTER_LAMP
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_SHUTTER_LAMP
(
self
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_SHUTTER_LAMP
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
3
:
if
result_list
[
0
]
==
self
.
__GET_SHUTTER_LAMP
and
isinstance
(
result_list
[
2
],
int
):
return
RECODE_SUCCEED
,
result_list
[
2
]
return
isWrong
,
0
def
INIT_LFBL_TL
(
self
,
enable
:
(
bool
,
int
)
=
1
)
->
int
:
#__INIT_LFBL_TL
isWrong
:
int
=
RECODE_FAILURE
_enable
:
int
=
1
if
isinstance
(
enable
,
(
bool
,
int
))
and
enable
else
0
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__INIT_LFBL_TL
,
_enable
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__INIT_LFBL_TL
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
INIT_APBL_TL
(
self
,
enable
:
(
bool
,
int
)
=
1
)
->
int
:
#__INIT_APBL_TL
isWrong
:
int
=
RECODE_FAILURE
_enable
:
int
=
1
if
isinstance
(
enable
,
(
bool
,
int
))
and
enable
else
0
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__INIT_APBL_TL
,
_enable
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__INIT_APBL_TL
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_POS_ABS_LFBL_TL
(
self
,
value
:
int
)
->
int
:
"""视场光阑 定位到指定的绝对值"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
1
<=
value
<=
33
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_POS_ABS_LFBL_TL
,
value
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_POS_ABS_LFBL_TL
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_MAX_POS_ABS_LFBL_TL
(
self
)
->
int
:
"""视场光阑最大位置"""
isWrong
:
int
=
self
.
SET_POS_ABS_LFBL_TL
(
38
)
return
isWrong
def
SET_MIN_POS_ABS_LFBL_TL
(
self
)
->
int
:
"""视场光阑最大位置"""
isWrong
:
int
=
self
.
SET_POS_ABS_LFBL_TL
(
1
)
return
isWrong
def
POS_MAX_TL_DIAPH1
(
self
)
->
int
:
"""定位至视场光阑最大光圈位置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__POS_MAX_TL_DIAPH1
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__POS_MAX_TL_DIAPH1
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_SPOTLIGHT
(
self
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_SPOTLIGHT
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_SPOTLIGHT
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
0
def
SET_SPOTLIGHT
(
self
,
enable
:
(
bool
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
ENABLE
:
int
=
1
if
isinstance
(
enable
,
(
bool
,
int
))
and
enable
else
0
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_SPOTLIGHT
,
ENABLE
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_SPOTLIGHT
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
changed_spot_light
(
self
,
enable
:
(
bool
,
int
))
->
int
:
return
self
.
SET_SPOTLIGHT
(
enable
)
def
get_spot_light
(
self
)
->
(
int
,
int
):
return
self
.
GET_SPOTLIGHT
()
def
GET_POS_ABS_LFBL_TL
(
self
)
->
(
int
,
int
):
"""输出视场光阑的当前位置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_POS_ABS_LFBL_TL
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_POS_ABS_LFBL_TL
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
None
def
SET_POS_ABS_APBL_TL
(
self
,
value
:
int
)
->
int
:
"""孔径光阑 定位到指定的绝对值"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
1
<=
value
<=
38
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_POS_ABS_APBL_TL
,
value
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_POS_ABS_APBL_TL
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_POS_ABS_APBL_TL
(
self
)
->
object
:
"""输出孔径光阑的当前位置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_POS_ABS_APBL_TL
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_POS_ABS_APBL_TL
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
None
def
SET_MAX_POS_ABS_APBL_TL
(
self
)
->
int
:
"""孔径光阑最大位置"""
isWrong
:
int
=
self
.
SET_POS_ABS_APBL_TL
(
33
)
return
isWrong
def
SET_MIN_POS_ABS_APBL_TL
(
self
)
->
int
:
"""孔径光阑最大位置"""
isWrong
:
int
=
self
.
SET_POS_ABS_APBL_TL
(
1
)
return
isWrong
def
POS_MAX_TL_DIAPH2
(
self
)
->
int
:
"""定位至孔径光阑最大光圈位置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__POS_MAX_TL_DIAPH2
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__POS_MAX_TL_DIAPH2
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_MAN_ON_OFF
(
self
,
enable
:
(
bool
,
int
)
=
True
)
->
int
:
"""打开或关闭 Z-DRIVE 的手动操作"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
enable
,
(
bool
,
int
)):
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_MAN_ON_OFF
,
1
if
enable
else
0
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_MAN_ON_OFF
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_MAN_ON_OFF
(
self
)
->
(
int
,
int
):
"""返回 Z-DRIVE 的手动操作是否已打开或关闭"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_MAN_ON_OFF
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_MAN_ON_OFF
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
0
def
RESET_Z__UNIT
(
self
)
->
int
:
"""
此命令将 Z-DRIVE 的以下参数重置为默认值
加速度参数
速度参数
软件限制
焦点位置
自动传递事件
手动操作
"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__RESET_Z__UNIT
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__RESET_Z__UNIT
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
CHECK_Z__UNIT
(
self
)
->
int
:
"""读取固件状态 0 = 固件正在从引导扇区运行 1 = 固件正在从程序内存运行"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__CHECK_Z__UNIT
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__CHECK_Z__UNIT
and
isinstance
(
result_list
[
1
],
int
):
return
int
(
result_list
[
1
])
return
0
def
INIT_Z
(
self
)
->
int
:
"""初始化 Z-DRIVE Z-DRIVE 移动到下方硬件端开关并重置零点"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__INIT_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__INIT_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
INIT_RANGE_Z
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__INIT_RANGE_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__INIT_RANGE_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
BREAK_Z
(
self
)
->
int
:
"""此命令将中止 Z-DRIVE 的当前定位 未完全执行的命令将通过 FLOW_ERR 进行确认 之后BREAK_Z 将退出"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__BREAK_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__BREAK_Z
:
isWrong
=
RECODE_SUCCEED
self
.
isMoving
=
False
if
RECODE_SUCCEED
==
isWrong
:
self
.
isMoving
=
False
return
isWrong
def
ZDriverMoveStatus
(
self
)
->
(
int
,
int
,
int
,
int
,
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
Moving
:
int
=
None
Lower
:
int
=
None
Upper
:
int
=
None
Limit
:
int
=
None
Focus
:
int
=
None
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_Z_DRIVE_STATUS
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
,
int
,
int
,
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
6
:
if
result_list
[
0
]
==
self
.
__GET_Z_DRIVE_STATUS
:
isWrong
=
RECODE_SUCCEED
Moving
=
AppConvert
.
ObjectConvert
(
result_list
[
1
],
int
)
Lower
=
AppConvert
.
ObjectConvert
(
result_list
[
2
],
int
)
Upper
=
AppConvert
.
ObjectConvert
(
result_list
[
3
],
int
)
Limit
=
AppConvert
.
ObjectConvert
(
result_list
[
4
],
int
)
Focus
=
AppConvert
.
ObjectConvert
(
result_list
[
5
],
int
)
self
.
isMoving
=
isinstance
(
Moving
,
int
)
and
Moving
==
1
return
isWrong
,
Moving
,
Lower
,
Upper
,
Limit
,
Focus
def
SET_POS_ABS_Z
(
self
,
POS
:
(
int
,
float
))
->
int
:
"""将功能单元定位到以微步(计数)为单位的给定绝对值 Z 范围 0 – 最大位置值"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
self
.
MIN_Z_POSITION
<=
int
(
POS
)
<=
self
.
MAX_Z_POSITION
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_POS_ABS_Z
,
POS
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_POS_ABS_Z
:
isWrong
=
RECODE_SUCCEED
self
.
isMoving
=
RECODE_SUCCEED
==
isWrong
return
isWrong
def
GET_POS_ABS_Z
(
self
)
->
(
int
,
int
):
"""以微步(计数)为单位读取功能单元的当前位置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_POS_ABS_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_POS_ABS_Z
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
0
def
SET_POS_REL_Z
(
self
,
POS
:
(
int
,
float
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
POS
,
(
int
,
float
))
and
self
.
MIN_Z_POSITION
<=
abs
(
POS
)
<=
self
.
MAX_Z_POSITION
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_POS_REL_Z
,
POS
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_POS_REL_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
POS_CONST_Z
(
self
,
SPEED
:
int
)
->
int
:
"""以恒定速度移动到最大位置"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
SPEED
,
(
int
,
float
)):
request
:
SerialRequest
=
self
.
execute
(
self
.
__POS_CONST_Z
,
int
(
SPEED
))
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__POS_CONST_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_LOW_LIMIT_Z
(
self
,
value
:
int
)
->
int
:
"""将下限阈值设置为给定的 Z 轴位置 值“0”位于下部机械限位开关。如果参数值设置为-1,则阈值将重置为其默认值"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
value
,
(
int
,
float
)):
_pos
:
int
=
value
if
self
.
MIN_Z_POSITION
<=
value
<=
self
.
MAX_Z_POSITION
else
-
1
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_LOW_LIMIT_Z
,
_pos
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_LOW_LIMIT_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_FOCUS_Z
(
self
,
value
:
int
)
->
int
:
"""将焦点位置设置为指定的 Z 轴位置 如果参数值设置为 -1 ,则阈值将重置为其默认值。默认值: -1"""
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
value
,
(
int
,
float
)):
_pos
:
int
=
value
if
self
.
MIN_Z_POSITION
<=
value
<=
self
.
MAX_Z_POSITION
else
-
1
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_FOCUS_Z
,
_pos
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_FOCUS_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_LOW_LIMIT_Z
(
self
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_LOW_LIMIT_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_LOW_LIMIT_Z
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
0
def
GET_FOCUS_Z
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_FOCUS_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
-
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_FOCUS_Z
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
-
1
def
SET_RAMP_Z
(
self
,
value
:
int
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
value
,
(
int
,
float
))
and
self
.
MIN_Z_ACC
<=
value
<=
self
.
MAX_Z_ACC
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_RAMP_Z
,
value
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_RAMP_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_RAMP_Z
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_RAMP_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
-
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_RAMP_Z
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
-
1
def
SET_SPEED_Z
(
self
,
SPEED
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
SPEED
,
(
float
,
int
))
and
self
.
MIN_Z_SPEED
<=
int
(
SPEED
)
<=
self
.
MAX_Z_SPEED
:
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_SPEED_Z
,
int
(
SPEED
))
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_SPEED_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_SPEED_Z
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_SPEED_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_SPEED_Z
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
1
def
MOVE_TO_POS_FOCUS
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__MOVE_TO_POS_FOCUS
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__MOVE_TO_POS_FOCUS
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
MOVE_TO_LOW_LIMIT_Z
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__MOVE_TO_LOW_LIMIT_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__MOVE_TO_LOW_LIMIT_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_Z_STEP_MODE
(
self
,
enable
:
(
bool
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
_enable
:
int
=
1
if
isinstance
(
enable
,
(
bool
,
int
))
and
(
enable
==
True
or
enable
==
1
)
else
0
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_Z_STEP_MODE
,
_enable
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_Z_STEP_MODE
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_Z_STEP_MODE
(
self
)
->
(
int
,
int
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_Z_STEP_MODE
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
0
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_Z_STEP_MODE
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
0
def
SET_UPPER_LIMIT
(
self
,
POS
:
int
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
POS
,
int
):
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_UPPER_LIMIT
,
int
(
POS
))
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_UPPER_LIMIT
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
SET_LOWER_LIMIT
(
self
,
POS
:
int
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
()
and
isinstance
(
POS
,
int
):
request
:
SerialRequest
=
self
.
execute
(
self
.
__SET_LOW_LIMIT_Z
,
int
(
POS
))
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
1
:
if
result_list
[
0
]
==
self
.
__SET_LOW_LIMIT_Z
:
isWrong
=
RECODE_SUCCEED
return
isWrong
def
GET_LOWER_LIMIT
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_LOW_LIMIT_Z
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_LOW_LIMIT_Z
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
1
def
GET_UPPER_LIMIT
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
hasDone
():
request
:
SerialRequest
=
self
.
execute
(
self
.
__GET_UPPER_LIMIT
)
isWrong
=
request
.
ResultNumber
if
RECODE_SUCCEED
!=
isWrong
:
return
isWrong
,
1
isWrong
=
RECODE_FAILURE
result_list
:
list
=
self
.
parserReceived
(
request
,
[
int
,
int
])
if
isinstance
(
result_list
,
list
)
and
len
(
result_list
)
>=
2
:
if
result_list
[
0
]
==
self
.
__GET_UPPER_LIMIT
and
isinstance
(
result_list
[
1
],
int
):
return
RECODE_SUCCEED
,
result_list
[
1
]
return
isWrong
,
1
def
execute
(
self
,
Command
:
int
,
*
args
)
->
SerialRequest
:
# Locker: Qt.QWriteLocker = Qt.QWriteLocker(self._Locker)
command
:
str
args_str
:
str
=
''
if
isinstance
(
args
,
(
tuple
,
list
))
and
len
(
args
)
>
0
:
for
value
in
args
:
args_str
+=
f
' {value}'
command
=
f
'{Command}'
+
args_str
request
:
SerialRequest
=
SerialRequest
.
MicroscopeRequest
(
command
,
self
.
Manager
)
if
not
self
.
IsOpen
():
self
.
Open
(
1500
)
if
self
.
IsOpen
():
request
.
ResultNumber
=
RECODE_FAILURE
isWrong
:
int
=
self
.
Send
(
request
.
TransmitBinary
)
request
.
ResultNumber
=
isWrong
if
RECODE_SUCCEED
!=
isWrong
:
return
request
AppTimeLoop
.
delay
(
2
)
# time.sleep(10 / 100)
self
.
ReadMic
(
request
)
if
RECODE_SUCCEED
!=
request
.
ResultNumber
:
request
.
ReceivedBinary
=
b
''
self
.
ReadMic
(
request
)
return
request
def
read_empty
(
self
,
timeout
:
int
=
1000
)
->
SerialRequest
:
# Locker: Qt.QWriteLocker = Qt.QWriteLocker(self._Locker)
command
:
str
=
''
request
:
SerialRequest
=
SerialRequest
.
MicroscopeRequest
(
command
,
self
.
Manager
)
if
not
self
.
IsOpen
():
self
.
Open
(
1500
)
if
self
.
IsOpen
():
request
.
ReceivedWaits
=
timeout
request
.
ResultNumber
=
RECODE_FAILURE
AppTimeLoop
.
msleep
(
6
)
self
.
Read
(
request
)
return
request
def
parserReceived
(
self
,
request
:
SerialRequest
,
types
:
list
[
type
])
->
list
:
result
:
list
=
None
if
not
isinstance
(
request
,
SerialRequest
)
or
RECODE_SUCCEED
!=
request
.
ResultNumber
:
return
result
buffer
:
str
=
request
.
ReceivedBinary
.
decode
(
'utf-8'
)
results
:
list
[
str
]
=
buffer
.
split
(
'
\r
'
)
result_list
:
list
type_length
:
int
=
len
(
types
)
if
isinstance
(
types
,
(
tuple
,
list
))
else
0
result
=
[]
for
string_data
in
results
:
if
'$'
in
string_data
or
len
(
string_data
)
<=
0
:
result_list
=
[]
else
:
result_list
=
string_data
.
split
(
' '
)
for
index
,
data
in
enumerate
(
result_list
):
if
0
<=
index
<
type_length
:
try
:
result
.
append
(
AppConvert
.
ObjectConvert
(
data
,
types
[
index
]))
except
Exception
as
e
:
print
(
e
)
result
.
append
(
data
)
else
:
result
.
append
(
data
)
return
result
def
hasDone
(
self
)
->
bool
:
if
not
self
.
IsOpen
():
self
.
Open
()
return
self
.
IsOpen
()
__CHECK_PROG
:
int
=
70008
__SET_TO_DEFAULT
:
int
=
70018
__GET_CONFIG_MODE
:
int
=
70074
__SET_CONFIG_MODE
:
int
=
70075
__GET_INIT_STATUS
:
int
=
70080
__SET_OBJ_POS_ABS_OBJ
:
int
=
76022
__GET_OBJ_POS_ABS_OBJ
:
int
=
76023
__SET_OBJ_MODE
:
int
=
76025
__GET_OBJ_MODE
:
int
=
76026
__SET_OBJ_PATHO_MODE
:
int
=
76046
__GET_OBJ_PATHO_MODE
:
int
=
76047
__SET_OBJPAR
:
int
=
76032
__GET_OBJPAR
:
int
=
76033
__SET_POS_ABS_LAMP
:
int
=
77020
__GET_POS_ABS_LAMP
:
int
=
77021
__SET_SHUTTER_LAMP
:
int
=
77032
__GET_SHUTTER_LAMP
:
int
=
77033
__INIT_LFBL_TL
:
int
=
83020
__INIT_APBL_TL
:
int
=
84020
__SET_POS_ABS_LFBL_TL
:
int
=
83022
__GET_POS_ABS_LFBL_TL
:
int
=
83023
__POS_MAX_TL_DIAPH1
:
int
=
83029
__SET_POS_ABS_APBL_TL
:
int
=
84022
__GET_POS_ABS_APBL_TL
:
int
=
84023
__POS_MAX_TL_DIAPH2
:
int
=
84029
__GET_Z_DRIVE_STATUS
:
int
=
71004
__SET_MAN_ON_OFF
:
int
=
71005
__GET_MAN_ON_OFF
:
int
=
71006
__RESET_Z__UNIT
:
int
=
71007
__CHECK_Z__UNIT
:
int
=
71008
__INIT_Z
:
int
=
71020
__BREAK_Z
:
int
=
71021
__SET_POS_ABS_Z
:
int
=
71022
__GET_POS_ABS_Z
:
int
=
71023
__SET_POS_REL_Z
:
int
=
71024
__POS_CONST_Z
:
int
=
71025
__SET_LOW_LIMIT_Z
:
int
=
71026
__SET_FOCUS_Z
:
int
=
71027
__GET_LOW_LIMIT_Z
:
int
=
71028
__GET_FOCUS_Z
:
int
=
71029
__SET_RAMP_Z
:
int
=
71030
__GET_RAMP_Z
:
int
=
71031
__SET_SPEED_Z
:
int
=
71032
__GET_SPEED_Z
:
int
=
71033
__MOVE_TO_POS_FOCUS
:
int
=
71034
__MOVE_TO_LOW_LIMIT_Z
:
int
=
71035
__INIT_RANGE_Z
:
int
=
71044
__SET_Z_STEP_MODE
:
int
=
71050
__GET_Z_STEP_MODE
:
int
=
71051
__SET_UPPER_LIMIT
:
int
=
71055
__GET_UPPER_LIMIT
:
int
=
71056
__SET_SPOTLIGHT
:
int
=
81022
__GET_SPOTLIGHT
:
int
=
81023
MAX_Z_POSITION
:
int
=
6804441
MIN_Z_POSITION
:
int
=
0
MIN_Z_ACC
:
int
=
1
MAX_Z_ACC
:
int
=
3612
MIN_Z_SPEED
:
int
=
1
MAX_Z_SPEED
:
int
=
8820000
LOW_Z_STEP
:
int
=
1
HIG_Z_STEP
:
int
=
0
@
staticmethod
def
_OpenSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
MicroscopeContext
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
MicroscopeContext
):
return
isWrong
if
MicroscopeImpl
.
_isSerialOpened
(
serial
):
MicroscopeImpl
.
_CloseSerial
(
serial
,
Parameter
)
Parameter
.
IsOpen
=
False
try
:
serial
.
setPortName
(
Parameter
.
COM
)
serial
.
setBaudRate
(
Parameter
.
BaudRate
)
serial
.
setDataBits
(
Parameter
.
DataBit
)
serial
.
setParity
(
Parameter
.
ParityBit
)
serial
.
setStopBits
(
Parameter
.
StopBit
)
serial
.
setFlowControl
(
Parameter
.
FlowControl
)
Parameter
.
IsOpen
=
serial
.
open
(
Qt
.
QIODevice
.
ReadWrite
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logSERIAL
logSERIAL
<<
AppUtils
.
toString
(
e
)
Parameter
.
IsOpen
=
False
isWrong
=
RECODE_SUCCEED
if
Parameter
.
IsOpen
else
RECODE_FAILURE
return
isWrong
@
staticmethod
def
_CloseSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
MicroscopeContext
):
isWrong
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
MicroscopeContext
):
return
isWrong
try
:
Parameter
.
IsOpen
=
serial
.
isOpen
()
serial
.
close
()
Parameter
.
IsOpen
=
serial
.
isOpen
()
except
Exception
as
e
:
from
AppLog.logHelper
import
logSERIAL
logSERIAL
<<
AppUtils
.
toString
(
e
)
Parameter
.
IsOpen
=
False
isWrong
=
RECODE_SUCCEED
return
isWrong
@
staticmethod
def
_ReadSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
MicroscopeContext
,
request
:
SerialRequest
,
timeout
:
int
=
-
1
):
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
MicroscopeContext
):
return
isWrong
if
not
isinstance
(
request
,
SerialRequest
):
return
isWrong
request
.
ResultNumber
=
isWrong
if
request
.
ReceivedTails
is
None
or
len
(
request
.
ReceivedTails
)
<=
0
:
request
.
ReceivedBinary
=
MicroscopeImpl
.
_ReadSerialPort
(
serial
,
-
1
,
timeout
)
return
RECODE_SUCCEED
TimerLoop
:
AppTimeLoop
=
AppTimeLoop
()
waittime
:
int
=
max
(
timeout
,
Parameter
.
ReadWaitTime
)
def
read_serial_port
(
Serial
:
Qt
.
QSerialPort
,
Request
:
SerialRequest
,
Loop
:
AppTimeLoop
):
from
AppLog.logHelper
import
logSERIAL
tails
:
Qt
.
QByteArray
=
Qt
.
QByteArray
(
Request
.
ReceivedTails
)
maxlength
:
int
readlength
:
int
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
bufferlength
:
int
atEnd
:
bool
=
False
while
True
:
if
Loop
.
remainingTime
()
<=
0
or
atEnd
:
break
maxlength
=
Serial
.
bytesAvailable
()
if
maxlength
<=
0
:
Serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# AppTimeLoop.msleep(MAX_SERIAL_READ_DELAY)
else
:
while
maxlength
>
0
:
bufferlength
=
len
(
buffer
)
buffer
.
append
(
Serial
.
read
(
1
))
readlength
=
len
(
buffer
)
-
bufferlength
if
readlength
>
0
:
maxlength
-=
readlength
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
if
atEnd
:
break
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
else
:
Serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# AppTimeLoop.msleep(MAX_SERIAL_READ_DELAY)
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
if
atEnd
:
break
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
# logSERIAL << f"Read: {buffer}"
Request
.
ReceivedBinary
=
buffer
.
data
()
Request
.
ResultNumber
=
RECODE_SUCCEED
if
atEnd
else
RECODE_FAILURE
Loop
.
exit
()
return
TimerLoop
.
execute
(
waittime
,
read_serial_port
,
**
{
"Serial"
:
serial
,
"Request"
:
request
,
"Loop"
:
TimerLoop
})
return
RECODE_SUCCEED
@
staticmethod
def
_ReadMicSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
MicroscopeContext
,
request
:
SerialRequest
,
timeout
:
int
=
-
1
):
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
MicroscopeContext
):
return
isWrong
if
not
isinstance
(
request
,
SerialRequest
):
return
isWrong
request
.
ResultNumber
=
isWrong
if
request
.
ReceivedTails
is
None
or
len
(
request
.
ReceivedTails
)
<=
0
:
request
.
ReceivedBinary
=
MicroscopeImpl
.
_ReadSerialPort
(
serial
,
-
1
,
timeout
)
return
RECODE_SUCCEED
TimerLoop
:
AppTimeLoop
=
AppTimeLoop
()
waittime
:
int
=
max
(
timeout
,
Parameter
.
ReadWaitTime
)
def
read_serial_port
(
Serial
:
Qt
.
QSerialPort
,
Request
:
SerialRequest
,
Loop
:
AppTimeLoop
):
from
AppLog.logHelper
import
logSERIAL
tails
:
Qt
.
QByteArray
=
Qt
.
QByteArray
(
Request
.
ReceivedTails
)
maxlength
:
int
readlength
:
int
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
bufferlength
:
int
atEnd
:
bool
=
False
send_buffer
:
bytes
=
Request
.
TransmitBinary
[
0
:
5
]
while
True
:
if
Loop
.
remainingTime
()
<=
0
or
atEnd
:
break
maxlength
=
Serial
.
bytesAvailable
()
if
maxlength
<=
0
:
Serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# AppTimeLoop.msleep(MAX_SERIAL_READ_DELAY)
else
:
bufferlength
=
len
(
buffer
)
buffer
.
append
(
Serial
.
readAll
())
readlength
=
len
(
buffer
)
-
bufferlength
if
readlength
>
0
:
maxlength
-=
readlength
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
if
atEnd
:
break
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
isSucceed
:
bool
=
buffer
.
indexOf
(
send_buffer
)
>=
0
if
atEnd
:
if
isSucceed
:
buffer
=
buffer
.
mid
(
buffer
.
indexOf
(
send_buffer
))
break
else
:
buffer
=
buffer
.
mid
(
buffer
.
indexOf
(
tails
)
+
len
(
tails
))
continue
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
# logSERIAL << f"Read: {buffer}"
Request
.
ReceivedBinary
=
buffer
.
data
()
Request
.
ResultNumber
=
RECODE_SUCCEED
if
atEnd
else
RECODE_FAILURE
Loop
.
exit
()
return
TimerLoop
.
execute
(
waittime
,
read_serial_port
,
**
{
"Serial"
:
serial
,
"Request"
:
request
,
"Loop"
:
TimerLoop
})
return
RECODE_SUCCEED
@
staticmethod
def
_ReadSerialPort
(
serial
:
Qt
.
QSerialPort
,
length
:
int
,
waittimes
:
int
=
1000
)
->
Qt
.
QByteArray
:
from
AppLog.logHelper
import
logSERIAL
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
maxlength
:
int
remaining
:
int
readlength
:
int
bufferlength
:
int
waittime
:
int
=
max
(
waittimes
,
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
ETime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
maxlength
=
serial
.
bytesAvailable
()
if
Qt
.
QDateTime
.
currentDateTime
()
>=
ETime
:
break
if
0
<
length
<=
maxlength
:
break
if
length
<=
0
:
buffer
.
append
(
serial
.
readAll
())
else
:
ETime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
remaining
=
min
(
length
,
maxlength
)
while
remaining
>
0
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
bufferlength
=
len
(
buffer
)
buffer
.
append
(
serial
.
read
(
remaining
))
readlength
=
len
(
buffer
)
-
bufferlength
if
readlength
>
0
:
remaining
-=
readlength
else
:
serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# logSERIAL << f"Send: {buffer}"
return
buffer
@
staticmethod
def
_SendSerial
(
serial
:
Qt
.
QSerialPort
,
buffer
:
Qt
.
QByteArray
,
timeout
:
int
=
1000
):
return
MicroscopeImpl
.
_ReadSerialPort
(
serial
=
serial
,
buffer
=
buffer
,
waittimes
=
timeout
)
@
staticmethod
def
_SendSerialPort
(
serial
:
Qt
.
QSerialPort
,
buffer
:
Qt
.
QByteArray
,
waittimes
:
int
)
->
int
:
from
AppLog.logHelper
import
logSERIAL
isWrong
:
int
maxlength
:
int
remaining
:
int
sendlength
:
int
sendindex
:
int
waittime
:
int
=
max
(
waittimes
,
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
ETime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
if
serial
.
isWritable
()
or
serial
.
bytesToWrite
()
<=
0
:
break
serial
.
flush
()
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
remaining
=
len
(
buffer
)
sendindex
=
0
ETime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
remaining
>=
MAX_SERIAL_SEND_BUFFER_LENGTH
:
sendlength
=
serial
.
write
(
buffer
.
mid
(
sendindex
,
MAX_SERIAL_SEND_BUFFER_LENGTH
))
if
sendlength
<=
0
:
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
else
:
sendindex
+=
MAX_SERIAL_SEND_BUFFER_LENGTH
remaining
-=
MAX_SERIAL_SEND_BUFFER_LENGTH
while
remaining
>
0
:
sendlength
=
serial
.
write
(
buffer
.
mid
(
sendindex
,
remaining
))
if
sendlength
<=
0
:
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
else
:
sendindex
+=
remaining
remaining
-=
remaining
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
if
serial
.
isWritable
()
or
serial
.
bytesToWrite
()
<=
0
:
break
serial
.
flush
()
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
# logSERIAL << f"Send: {buffer}"
isWrong
=
RECODE_SUCCEED
if
remaining
<=
0
else
RECODE_FAILURE
return
isWrong
@
staticmethod
def
_isSerialOpened
(
serial
:
Qt
.
QSerialPort
)
->
bool
:
return
isinstance
(
serial
,
Qt
.
QSerialPort
)
and
serial
.
isOpen
()
@
staticmethod
def
_isSerialReadable
(
serial
:
Qt
.
QSerialPort
)
->
bool
:
return
isinstance
(
serial
,
Qt
.
QSerialPort
)
and
serial
.
isReadable
()
@
staticmethod
def
_isSerialWritable
(
serial
:
Qt
.
QSerialPort
)
->
bool
:
return
isinstance
(
serial
,
Qt
.
QSerialPort
)
and
serial
.
isWritable
()
AppCore/AppImplsbak/ModBusImpl.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: ModBusImpl.py
@DateTime: 2025/4/8 20:20
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
from
abc
import
abstractmethod
from
pymodbus.client.tcp
import
ModbusTcpClient
from
pymodbus.payload
import
BinaryPayloadBuilder
,
BinaryPayloadDecoder
from
pymodbus.constants
import
Endian
import
struct
from
AppCore.AppContextModels.ModBusContext
import
ModBusContext
from
AppCore.AppContextModels.ModBusRegister
import
ModBusRegister
from
AppCore.AppRequestModels.ModBusRequest
import
ModBusRequest
from
AppInterfaces.ImplInterface
import
(
ImplInterface
,
AppTimeLoop
,
AppConvert
,
AppUtils
,
log_exceptions
)
from
AppCore.ImplInterfaces
import
ModBusInterface
from
AppSettings.Settings
import
(
RECODE_FAILURE
,
RECODE_SUCCEED
)
MODBUS_UNIT
:
int
=
1
class
ModBusImpl
(
Qt
.
QObject
,
ModBusInterface
):
Manager
:
ModbusTcpClient
Parameter
:
ModBusContext
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasParameter
()
@
property
def
isAvailable
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
IsOpen
()
def
__init__
(
self
,
context
:
ModBusContext
=
None
,
parent
:
Qt
.
QObject
=
None
):
super
(
ModBusImpl
,
self
)
.
__init__
(
parent
=
parent
)
self
.
Parameter
=
context
self
.
Initialization
(
"ModBusImpl"
,
self
,
parent
)
@
classmethod
def
instance
(
cls
,
context
:
ModBusContext
=
None
,
parent
:
Qt
.
QObject
=
None
)
->
'ModBusImpl'
:
result
=
cls
.
__new__
(
cls
)
result
.
__init__
(
context
=
context
,
parent
=
parent
)
# result.Open()
return
result
def
setParameter
(
self
,
context
:
ModBusContext
):
if
self
.
Parameter
.
isEqual
(
context
):
return
isOpen
:
bool
=
self
.
IsOpen
()
self
.
deleManager
()
self
.
Parameter
=
context
self
.
initManager
(
self
.
Parameter
)
if
isOpen
:
self
.
Open
()
def
IsOpen
(
self
)
->
bool
:
try
:
return
self
.
isValid
()
and
self
.
Manager
.
is_socket_open
()
except
Exception
as
e
:
return
False
def
isEnabled
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
Manager
.
is_socket_open
()
def
isDisable
(
self
)
->
bool
:
return
not
self
.
isEnabled
()
def
Open
(
self
,
timeOut
:
int
=
1000
)
->
int
:
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
if
not
self
.
isValid
():
return
RECODE_FAILURE
if
self
.
isEnabled
():
self
.
Close
(
timeOut
)
self
.
Parameter
.
IsOpen
=
False
try
:
self
.
Manager
.
connect
()
self
.
Parameter
.
IsOpen
=
self
.
Manager
.
connected
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
if
not
self
.
isValid
():
return
RECODE_SUCCEED
try
:
self
.
Manager
.
close
()
del
self
.
Manager
self
.
Manager
=
None
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
self
.
Parameter
.
IsOpen
=
False
return
RECODE_SUCCEED
if
not
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
initManager
(
self
,
context
:
ModBusContext
=
None
,
**
args
):
if
not
self
.
hasParameter
()
or
self
.
Parameter
!=
context
:
self
.
Parameter
=
context
if
not
self
.
hasParameter
():
from
AppSettings.AppSetting
import
AppSetting
,
AppConfig
self
.
Parameter
=
AppConfig
.
manipulatorConfig
.
modBusConfig
if
not
self
.
hasParameter
():
self
.
Parameter
=
ModBusContext
()
if
not
self
.
hasManager
():
try
:
self
.
Manager
=
ModbusTcpClient
(
self
.
Parameter
.
Addr
,
port
=
self
.
Parameter
.
Port
,
timeout
=
self
.
Parameter
.
TimeOut
,
reconnect_delay_max
=
self
.
Parameter
.
ReconnectedTimes
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
self
.
Manager
=
None
def
deleManager
(
self
):
if
self
.
hasManager
():
try
:
self
.
Manager
.
close
()
del
self
.
Manager
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
self
.
Manager
=
None
self
.
Parameter
.
IsOpen
=
False
@
log_exceptions
def
ReadRegister
(
self
,
address
:
int
):
if
self
.
isValid
():
count
:
int
=
1
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
return
response
.
registers
return
None
@
log_exceptions
def
ReadRegisters
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
int
])
->
int
:
count
:
int
=
max
(
1
,
Count
)
if
self
.
isEnabled
()
or
isinstance
(
values
,
list
):
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
buffer
=
response
.
registers
values
.
clear
()
values
.
extend
(
buffer
)
return
RECODE_SUCCEED
if
len
(
values
)
==
count
else
RECODE_FAILURE
return
RECODE_FAILURE
@
log_exceptions
def
ReadCoil
(
self
,
address
:
int
)
->
int
:
if
self
.
isValid
():
count
:
int
=
1
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
return
response
.
bits
[
0
]
return
None
@
log_exceptions
def
ReadCoils
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
bool
])
->
int
:
count
:
int
=
max
(
1
,
Count
)
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
print
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
values
.
clear
()
values
.
extend
(
response
.
bits
)
return
RECODE_SUCCEED
if
len
(
values
)
==
count
else
RECODE_FAILURE
return
RECODE_FAILURE
@
log_exceptions
def
SendCoil
(
self
,
address
:
int
,
value
:
bool
)
->
int
:
if
self
.
isValid
():
try
:
response
=
self
.
Manager
.
write_coil
(
address
=
address
,
value
=
value
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_coil
(
address
=
address
,
value
=
value
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendCoils
(
self
,
address
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
try
:
response
=
self
.
Manager
.
write_coils
(
address
=
address
,
values
=
values
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_coils
(
address
=
address
,
values
=
values
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendRegister
(
self
,
address
:
int
,
value
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
value
,
list
):
try
:
response
=
self
.
Manager
.
write_register
(
address
=
address
,
value
=
value
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_register
(
address
=
address
,
value
=
value
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
ReadFloats
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
float
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
Step
:
int
=
2
Length
:
int
=
max
(
1
,
Count
)
ByteLength
=
Step
*
Length
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_SUCCEED
else
:
return
RECODE_SUCCEED
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
byte_array
=
struct
.
pack
(
'<{}'
.
format
(
'H'
*
ByteLength
),
*
response
.
registers
)
result
:
list
[
float
]
=
struct
.
unpack
(
"<{}"
.
format
(
'f'
*
Length
),
bytes
(
byte_array
))
values
.
clear
()
values
.
extend
(
result
)
return
RECODE_SUCCEED
else
:
return
RECODE_FAILURE
@
log_exceptions
def
ReadFloat
(
self
,
address
:
int
)
->
float
:
if
self
.
isValid
():
DataLength
=
2
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
DataLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
DataLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
byte_array
=
struct
.
pack
(
'<HH'
,
*
response
.
registers
)
result
:
float
=
struct
.
unpack
(
"<f"
,
bytes
(
byte_array
))[
0
]
return
round
(
result
,
2
)
return
None
@
log_exceptions
def
SendFloats
(
self
,
address
:
int
,
values
:
list
[
float
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
FloatLength
=
len
(
values
)
DataLength
=
FloatLength
*
2
byte_array
:
list
[
bytes
]
=
[
struct
.
pack
(
'<f'
,
float
(
value
))
for
value
in
values
]
value_list
:
list
[
int
]
=
[]
for
_bytes
in
byte_array
:
value_list
.
extend
(
struct
.
unpack
(
'<HH'
,
_bytes
))
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
value_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
value_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_SUCCEED
else
:
return
RECODE_SUCCEED
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendFloat
(
self
,
address
:
int
,
value
:
float
)
->
int
:
if
self
.
isValid
()
and
isinstance
(
value
,
(
float
,
int
)):
value_list
:
list
[
int
]
=
[]
value_list
.
extend
(
struct
.
unpack
(
'<HH'
,
struct
.
pack
(
'<f'
,
float
(
value
))))
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
value_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
value_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
ReadInt32
(
self
,
address
:
int
):
if
self
.
isValid
():
Length
:
int
=
1
ByteLength
:
int
=
Length
*
2
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
byte_data
=
struct
.
pack
(
'>{}H'
.
format
(
ByteLength
),
*
response
.
registers
)
int32_values
=
struct
.
unpack
(
'>{}i'
.
format
(
Length
),
byte_data
)
return
int32_values
[
0
]
return
None
pass
@
log_exceptions
def
ReadInt32s
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
Step
:
int
=
2
Length
:
int
=
max
(
1
,
Count
)
ByteLength
=
Step
*
Length
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
byte_data
=
struct
.
pack
(
'>{}H'
.
format
(
ByteLength
),
*
response
.
registers
)
int32_values
=
struct
.
unpack
(
'>{}i'
.
format
(
Length
),
byte_data
)
values
.
clear
()
values
.
extend
(
int32_values
)
return
RECODE_SUCCEED
else
:
return
RECODE_FAILURE
@
log_exceptions
def
SendInt32
(
self
,
address
:
int
,
value
:
int
)
->
int
:
if
self
.
isValid
():
DataLength
=
2
byte_data
=
struct
.
pack
(
'>i'
,
int
(
value
))
register_list
=
struct
.
unpack
(
'>{}H'
.
format
(
DataLength
),
byte_data
)
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendInt32s
(
self
,
address
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
FloatLength
=
len
(
values
)
DataLength
=
FloatLength
*
2
byte_data
=
struct
.
pack
(
'>{}i'
.
format
(
FloatLength
),
*
values
)
register_list
=
struct
.
unpack
(
'>{}H'
.
format
(
DataLength
),
byte_data
)
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
ReadUInt32
(
self
,
address
:
int
):
if
self
.
isValid
():
Length
:
int
=
1
ByteLength
:
int
=
Length
*
2
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
byte_data
=
struct
.
pack
(
'>{}H'
.
format
(
ByteLength
),
*
response
.
registers
)
int32_values
=
struct
.
unpack
(
'>{}I'
.
format
(
Length
),
byte_data
)
return
int32_values
[
0
]
return
None
pass
@
log_exceptions
def
ReadUInt32s
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
Step
:
int
=
2
Length
:
int
=
max
(
1
,
Count
)
ByteLength
=
Step
*
Length
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
byte_data
=
struct
.
pack
(
'>{}H'
.
format
(
ByteLength
),
*
response
.
registers
)
int32_values
=
struct
.
unpack
(
'>{}I'
.
format
(
Length
),
byte_data
)
values
.
clear
()
values
.
extend
(
int32_values
)
return
RECODE_SUCCEED
else
:
return
RECODE_FAILURE
@
log_exceptions
def
SendUInt32
(
self
,
address
:
int
,
value
:
int
)
->
int
:
if
self
.
isValid
():
DataLength
=
2
byte_data
=
struct
.
pack
(
'>I'
,
int
(
value
))
register_list
=
struct
.
unpack
(
'>{}H'
.
format
(
DataLength
),
byte_data
)
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendUInt32s
(
self
,
address
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
FloatLength
=
len
(
values
)
DataLength
=
FloatLength
*
2
byte_data
=
struct
.
pack
(
'>{}I'
.
format
(
FloatLength
),
*
values
)
register_list
=
struct
.
unpack
(
'>{}H'
.
format
(
DataLength
),
byte_data
)
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
ReadInt16
(
self
,
address
:
int
):
if
self
.
isValid
():
Length
:
int
=
1
ByteLength
:
int
=
Length
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
byte_data
=
struct
.
pack
(
'>{}H'
.
format
(
ByteLength
),
*
response
.
registers
)
int32_values
=
struct
.
unpack
(
'>{}h'
.
format
(
Length
),
byte_data
)
return
int32_values
[
0
]
return
None
pass
@
log_exceptions
def
ReadInt16s
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
Step
:
int
=
1
Length
:
int
=
max
(
1
,
Count
)
ByteLength
=
Step
*
Length
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
ByteLength
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
byte_data
=
struct
.
pack
(
'>{}H'
.
format
(
ByteLength
),
*
response
.
registers
)
int32_values
=
struct
.
unpack
(
'>{}h'
.
format
(
Length
),
byte_data
)
values
.
clear
()
values
.
extend
(
int32_values
)
return
RECODE_SUCCEED
else
:
return
RECODE_FAILURE
@
log_exceptions
def
SendInt16
(
self
,
address
:
int
,
value
:
int
)
->
int
:
if
self
.
isValid
():
register_list
=
[
int
(
value
)]
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendInt16s
(
self
,
address
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
FloatLength
=
len
(
values
)
DataLength
=
FloatLength
byte_data
=
struct
.
pack
(
'>{}h'
.
format
(
FloatLength
),
*
values
)
register_list
=
struct
.
unpack
(
'>{}H'
.
format
(
DataLength
),
byte_data
)
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
register_list
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
ReadUInt16
(
self
,
address
:
int
):
if
self
.
isValid
():
Length
:
int
=
1
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
Length
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
Length
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
not
response
.
isError
()
and
len
(
response
.
registers
)
>=
Length
:
return
response
.
registers
[
0
]
return
None
pass
@
log_exceptions
def
ReadUInt16s
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
Step
:
int
=
2
Length
:
int
=
max
(
1
,
Count
)
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
Length
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_holding_registers
(
address
=
address
,
count
=
Length
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
values
.
clear
()
values
.
extend
(
response
.
registers
)
return
RECODE_SUCCEED
else
:
return
RECODE_FAILURE
@
log_exceptions
def
SendUInt16
(
self
,
address
:
int
,
value
:
int
)
->
int
:
if
self
.
isValid
():
try
:
response
=
self
.
Manager
.
write_register
(
address
=
address
,
value
=
int
(
value
),
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_register
(
address
=
address
,
value
=
int
(
value
),
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendUInt16s
(
self
,
address
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
values
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_registers
(
address
=
address
,
values
=
values
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
ReadState
(
self
,
address
:
int
)
->
int
:
if
self
.
isValid
():
count
:
int
=
1
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
None
else
:
return
None
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
None
return
response
.
bits
[
0
]
return
None
@
log_exceptions
def
ReadStatus
(
self
,
address
:
int
,
Count
:
int
,
values
:
list
[
bool
])
->
int
:
count
:
int
=
max
(
1
,
Count
)
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
read_coils
(
address
=
address
,
count
=
count
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
print
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
values
.
clear
()
values
.
extend
(
response
.
bits
)
return
RECODE_SUCCEED
if
len
(
values
)
==
count
else
RECODE_FAILURE
return
RECODE_FAILURE
@
log_exceptions
def
SendState
(
self
,
address
:
int
,
value
:
bool
)
->
int
:
if
self
.
isValid
():
try
:
response
=
self
.
Manager
.
write_coil
(
address
=
address
,
value
=
value
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_coil
(
address
=
address
,
value
=
value
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
@
log_exceptions
def
SendStatus
(
self
,
address
:
int
,
values
:
list
[
int
])
->
int
:
if
self
.
isValid
()
and
isinstance
(
values
,
list
):
_values
=
[
True
if
isinstance
(
state
,
(
bool
,
int
))
and
state
else
False
for
state
in
values
]
try
:
response
=
self
.
Manager
.
write_coils
(
address
=
address
,
values
=
_values
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
try
:
if
e
.
errno
==
10054
:
self
.
deleManager
()
self
.
ReOpen
()
except
Exception
as
ex
:
pass
if
self
.
IsOpen
():
try
:
response
=
self
.
Manager
.
write_coils
(
address
=
address
,
values
=
_values
,
slave
=
MODBUS_UNIT
)
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
return
RECODE_FAILURE
else
:
return
RECODE_FAILURE
if
response
.
isError
():
AppUtils
.
print_current_function_info
(
f
"ModBus error: {response}"
)
return
RECODE_FAILURE
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'Manager'
)
and
self
.
Manager
is
not
None
def
hasParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'Parameter'
)
and
self
.
Parameter
is
not
None
AppCore/AppImplsbak/ScanCodeImpl.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: ScanCodeImpl.py
@DateTime: 2025/4/9 23:07
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
from
abc
import
abstractmethod
from
AppCore.AppContextModels.SerialContext
import
SerialContext
from
AppCore.AppRequestModels.SerialRequest
import
SerialRequest
from
AppInterfaces.ImplInterface
import
(
ImplInterface
,
AppConvert
,
AppUtils
,
AppTimeLoop
,
log_exceptions
)
from
AppInterfaces.SingletonInterface
import
(
SingletonInterface
)
from
AppCore.ImplInterfaces
import
ScanCodeInterface
from
AppSettings.Settings
import
(
RECODE_FAILURE
,
RECODE_SUCCEED
,
SIGNAL_CONNECTION_TYPE
)
MAX_SERIAL_DEFAULT_WAIT_TIMES
:
int
=
5000
MAX_SERIAL_READ_DELAY
:
int
=
5
MAX_SERIAL_SEND_BUFFER_LENGTH
:
int
=
255
SERIAL_CODE_SCAN_DELAY
:
int
=
50
SERIAL_READ_CODE_SCAN_DELAY
:
int
=
200
class
ScanCodeImpl
(
Qt
.
QObject
,
ScanCodeInterface
,
SingletonInterface
):
_isScanning
:
bool
=
False
_ScanLocker
:
Qt
.
QReadWriteLock
=
Qt
.
QReadWriteLock
()
TransmitString
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
,
str
)
TransmitBinary
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
,
object
)
TransmitSignal
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
,
object
)
ReceivedSignal
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
,
object
)
Parameter
:
SerialContext
Manager
:
Qt
.
QSerialPort
Locker
:
Qt
.
QMutex
=
Qt
.
QMutex
()
@
classmethod
def
GetInstance
(
cls
,
*
args
,
**
kwargs
)
->
'ScanCodeImpl'
:
return
super
(
ScanCodeImpl
,
cls
)
.
GetInstance
(
*
args
,
**
kwargs
)
def
__init__
(
self
,
context
:
SerialContext
=
None
,
parent
:
Qt
.
QObject
=
None
):
super
(
ScanCodeImpl
,
self
)
.
__init__
(
parent
=
parent
)
self
.
Parameter
=
context
self
.
Initialization
(
"ScanCodeImpl"
,
self
,
parent
)
self
.
initContext
()
self
.
ReOpen
()
def
initContext
(
self
):
from
AppSettings.AppSetting
import
AppConfig
if
self
.
Parameter
!=
AppConfig
.
CodeScanningConfig
:
self
.
Parameter
=
AppConfig
.
CodeScanningConfig
def
initConnect
(
self
):
if
not
self
.
hasManager
():
self
.
initManager
(
self
.
Parameter
if
self
.
hasParameter
()
else
None
)
def
initManager
(
self
,
context
:
object
=
None
,
**
args
):
if
not
self
.
hasParameter
():
self
.
Parameter
=
context
if
not
self
.
hasParameter
():
self
.
Parameter
=
SerialContext
()
if
not
self
.
hasManager
():
self
.
Manager
=
Qt
.
QSerialPort
()
def
deleManager
(
self
):
if
self
.
hasManager
():
self
.
Close
()
self
.
Manager
.
deleteLater
()
self
.
Manager
=
None
def
deleConnect
(
self
):
super
(
ScanCodeImpl
,
self
)
.
deleConnect
()
def
IsScanning
(
self
)
->
bool
:
Locker
:
Qt
.
QReadLocker
=
Qt
.
QReadLocker
(
self
.
_ScanLocker
)
return
self
.
_isScanning
def
setHostMode
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
Result
:
str
=
None
isWrong
:
int
=
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
CONSOLE_MODE
))
if
RECODE_SUCCEED
==
isWrong
:
Result
=
self
.
ReadString
()
print
(
f
"主机模式:{Result} "
)
isWrong
=
RECODE_SUCCEED
if
isinstance
(
Result
,
str
)
and
len
(
Result
)
>
0
else
RECODE_FAILURE
return
isWrong
def
getVERSION
(
self
)
->
int
:
from
AppSettings.SystemSetting
import
SystemConfig
Result
:
str
=
None
isWrong
:
int
=
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
GET_VERSION
))
if
RECODE_SUCCEED
==
isWrong
:
Result
=
self
.
ReadString
()
print
(
f
"扫码器版本:{Result}"
)
isWrong
=
RECODE_SUCCEED
if
isinstance
(
Result
,
str
)
and
len
(
Result
)
>
0
and
self
.
VERSION
in
Result
else
RECODE_FAILURE
return
isWrong
def
waitForScanning
(
self
,
timeout
:
int
=
1500
)
->
bool
:
waittimes
:
int
=
max
(
timeout
,
self
.
Parameter
.
SpaceTime
)
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
self
.
IsScanning
():
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
AppTimeLoop
.
processGlobalEvents
(
SERIAL_READ_CODE_SCAN_DELAY
)
return
self
.
IsScanning
()
def
ScanningCode
(
self
,
timeout
:
int
=
1500
)
->
str
:
result
:
str
=
None
from
AppCore.AppDBModels.ConfigModels.SystemConfigModel
import
SystemConfigModel
if
self
.
waitForScanning
(
timeout
):
return
result
Locker
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
_ScanLocker
)
self
.
_isScanning
=
True
endtime
:
Qt
.
QDateTime
if
RECODE_SUCCEED
!=
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
START_DECODE
)):
self
.
_isScanning
=
False
return
result
request
:
SerialRequest
waittimes
:
int
request
,
waittimes
=
SystemConfigModel
.
ScanCodeRequest
()
request
.
ReceivedBinary
=
b
''
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
if
RECODE_SUCCEED
==
self
.
Read
(
request
):
break
AppTimeLoop
.
processGlobalEvents
(
SERIAL_READ_CODE_SCAN_DELAY
)
result
=
request
.
ReceivedBinary
.
replace
(
request
.
ReceivedTails
,
b
''
)
.
decode
(
'utf-8'
)
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
STOP_DECODE
))
self
.
_isScanning
=
False
return
result
def
StartScanningCode
(
self
)
->
int
:
self
.
_isScanning
=
True
isWrong
:
int
=
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
START_DECODE
))
return
isWrong
def
StopScanningCode
(
self
,
**
args
)
->
int
:
isWrong
:
int
=
RECODE_SUCCEED
# isWrong = self.SendBinary(bytes.fromhex(self.STOP_DECODE))
self
.
_isScanning
=
False
return
isWrong
def
ReadScanningCode
(
self
,
timeout
:
int
=
1500
)
->
str
:
result
:
str
=
None
waittimes
:
int
endtime
:
Qt
.
QDateTime
request
:
SerialRequest
from
AppCore.AppDBModels.ConfigModels.SystemConfigModel
import
SystemConfigModel
request
,
waittimes
=
SystemConfigModel
.
ScanCodeRequest
()
request
.
ReceivedBinary
=
b
''
request
.
ReceivedWaits
=
timeout
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
if
RECODE_SUCCEED
==
self
.
Read
(
request
):
break
AppTimeLoop
.
processGlobalEvents
(
SERIAL_READ_CODE_SCAN_DELAY
)
result
=
request
.
ReceivedBinary
.
replace
(
request
.
ReceivedTails
,
b
''
)
.
decode
(
'utf-8'
)
return
result
def
ReadRequest
(
self
,
request
,
timeout
:
int
=
1500
)
->
str
:
result
:
str
=
None
waittimes
:
int
=
max
(
timeout
,
self
.
Parameter
.
ReadWaitTime
)
endtime
:
Qt
.
QDateTime
request
:
SerialRequest
request
.
ReceivedWaits
=
timeout
endtime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
:
break
if
RECODE_SUCCEED
==
self
.
Read
(
request
):
break
AppTimeLoop
.
processGlobalEvents
(
SERIAL_READ_CODE_SCAN_DELAY
)
result
=
request
.
ReceivedBinary
.
replace
(
request
.
ReceivedTails
,
b
''
)
.
decode
(
'utf-8'
)
return
result
def
StopScanning
(
self
):
while
self
.
IsScanning
():
self
.
waitForScanning
()
if
not
self
.
IsScanning
():
return
Locker
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
_ScanLocker
)
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
STOP_DECODE
))
self
.
_isScanning
=
False
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasParameter
()
def
IsOpen
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
Manager
.
isOpen
()
def
isEnabled
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
Manager
.
isOpen
()
def
isDisable
(
self
)
->
bool
:
return
not
self
.
isEnabled
()
def
Open
(
self
,
timeOut
:
int
=
1000
)
->
int
:
self
.
initContext
()
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
if
not
self
.
isValid
():
return
RECODE_FAILURE
if
self
.
IsOpen
():
self
.
Manager
.
close
()
self
.
Parameter
.
IsOpen
=
False
waittime
:
int
=
max
(
timeOut
,
self
.
Parameter
.
ReadWaitTime
)
ETime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
if
self
.
_OpenSerial
(
self
.
Manager
,
self
.
Parameter
)
==
RECODE_SUCCEED
:
break
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
if
self
.
IsOpen
()
and
self
.
_isScanning
:
self
.
SendBinary
(
bytes
.
fromhex
(
self
.
STOP_DECODE
))
self
.
_CloseSerial
(
self
.
Manager
,
self
.
Parameter
)
return
RECODE_SUCCEED
def
ReOpen
(
self
,
timeOut
:
int
=
1000
)
->
int
:
self
.
Close
(
timeOut
)
return
self
.
Open
(
timeOut
)
def
isEqual
(
self
,
other
)
->
bool
:
if
isinstance
(
other
,
ScanCodeImpl
):
return
self
.
Manager
==
other
.
Manager
return
False
def
SendString
(
self
,
buffer
:
str
,
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
_SendSerialPort
(
self
.
Manager
,
Qt
.
QByteArray
(
buffer
.
encode
(
'utf-8'
)),
self
.
Parameter
.
ReadWaitTime
)
def
SendBinary
(
self
,
buffer
:
(
bytes
,
bytearray
,
Qt
.
QByteArray
),
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
return
self
.
_SendSerialPort
(
self
.
Manager
,
Qt
.
QByteArray
(
buffer
),
self
.
Parameter
.
ReadWaitTime
)
def
ReadString
(
self
,
**
args
)
->
str
:
result
:
str
=
None
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
result
request
:
SerialRequest
=
SerialRequest
()
request
.
ReceivedTails
=
b
'06'
request
.
ReceivedWaits
=
300
if
RECODE_SUCCEED
==
self
.
_ReadSerial
(
self
.
Manager
,
self
.
Parameter
,
request
,
request
.
ReceivedWaits
):
try
:
buffer
=
request
.
ReceivedBinary
.
replace
(
request
.
ReceivedTails
,
b
''
)
buffer
=
buffer
.
replace
(
b
'
\r\n
'
,
b
''
)
result
=
buffer
.
decode
(
'utf-8'
)
except
Exception
as
e
:
result
=
None
return
result
def
Send
(
self
,
buffer
,
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
RECODE_FAILURE
if
isinstance
(
buffer
,
str
):
return
self
.
SendString
(
buffer
)
elif
isinstance
(
buffer
,
(
bytes
,
bytearray
,
Qt
.
QByteArray
)):
return
self
.
SendBinary
(
buffer
)
elif
isinstance
(
buffer
,
SerialRequest
):
return
self
.
_SendSerialPort
(
self
.
Manager
,
Qt
.
QByteArray
(
buffer
.
TransmitBinary
),
self
.
Parameter
.
ReadWaitTime
)
return
RECODE_FAILURE
def
ReadBinary
(
self
)
->
Qt
.
QByteArray
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
():
return
Qt
.
QByteArray
()
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
if
Qt
.
QTime
.
currentTime
()
>
self
.
StartTime
:
self
.
StartTime
=
Qt
.
QTime
.
currentTime
()
.
addMSecs
(
self
.
Parameter
.
SpaceTime
)
buffer
=
self
.
_ReadSerialPort
(
self
.
Manager
,
-
1
,
self
.
Parameter
.
ReadWaitTime
)
return
buffer
def
Read
(
self
,
request
:
SerialRequest
,
**
args
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
()
or
not
isinstance
(
request
,
SerialRequest
):
return
RECODE_FAILURE
return
self
.
_ReadSerial
(
self
.
Manager
,
self
.
Parameter
,
request
,
request
.
ReceivedWaits
)
def
ReadMic
(
self
,
request
:
SerialRequest
)
->
int
:
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
()
or
not
isinstance
(
request
,
SerialRequest
):
return
RECODE_FAILURE
return
self
.
_ReadMicSerial
(
self
.
Manager
,
self
.
Parameter
,
request
,
request
.
ReceivedWaits
)
def
WaitDone
(
self
,
request
:
SerialRequest
):
if
not
self
.
IsOpen
():
self
.
Open
(
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
if
not
self
.
IsOpen
()
or
not
isinstance
(
request
,
SerialRequest
):
return
request
.
ResultNumber
=
RECODE_FAILURE
isWrong
:
int
=
self
.
Send
(
request
.
TransmitBinary
)
request
.
ResultNumber
=
isWrong
if
RECODE_SUCCEED
!=
isWrong
:
return
self
.
Read
(
request
)
@
staticmethod
def
_OpenSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
SerialContext
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
SerialContext
):
return
isWrong
if
ScanCodeImpl
.
_isSerialOpened
(
serial
):
ScanCodeImpl
.
_CloseSerial
(
serial
,
Parameter
)
Parameter
.
IsOpen
=
False
try
:
serial
.
setPortName
(
Parameter
.
COM
)
serial
.
setBaudRate
(
Parameter
.
BaudRate
)
serial
.
setDataBits
(
Parameter
.
DataBit
)
serial
.
setParity
(
Parameter
.
ParityBit
)
serial
.
setStopBits
(
Parameter
.
StopBit
)
serial
.
setFlowControl
(
Parameter
.
FlowControl
)
Parameter
.
IsOpen
=
serial
.
open
(
Qt
.
QIODevice
.
ReadWrite
)
except
Exception
as
e
:
from
AppLog.logHelper
import
logSERIAL
logSERIAL
<<
AppUtils
.
toString
(
e
)
Parameter
.
IsOpen
=
False
isWrong
=
RECODE_SUCCEED
if
Parameter
.
IsOpen
else
RECODE_FAILURE
return
isWrong
@
staticmethod
def
_CloseSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
SerialContext
):
isWrong
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
SerialContext
):
return
isWrong
try
:
Parameter
.
IsOpen
=
serial
.
isOpen
()
serial
.
close
()
Parameter
.
IsOpen
=
serial
.
isOpen
()
except
Exception
as
e
:
from
AppLog.logHelper
import
logSERIAL
logSERIAL
<<
AppUtils
.
toString
(
e
)
Parameter
.
IsOpen
=
False
isWrong
=
RECODE_SUCCEED
return
isWrong
@
staticmethod
def
_ReadSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
SerialContext
,
request
:
SerialRequest
,
timeout
:
int
=
-
1
):
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
SerialContext
):
return
isWrong
if
not
isinstance
(
request
,
SerialRequest
):
return
isWrong
request
.
ResultNumber
=
isWrong
if
request
.
ReceivedTails
is
None
or
len
(
request
.
ReceivedTails
)
<=
0
:
request
.
ReceivedBinary
=
ScanCodeImpl
.
_ReadSerialPort
(
serial
,
-
1
,
timeout
)
return
RECODE_SUCCEED
TimerLoop
:
AppTimeLoop
=
AppTimeLoop
()
waittime
:
int
=
max
(
timeout
,
Parameter
.
ReadWaitTime
)
def
read_serial_port
(
Serial
:
Qt
.
QSerialPort
,
Request
:
SerialRequest
,
Loop
:
AppTimeLoop
):
from
AppLog.logHelper
import
logSERIAL
tails
:
Qt
.
QByteArray
=
Qt
.
QByteArray
(
Request
.
ReceivedTails
)
maxlength
:
int
readlength
:
int
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
bufferlength
:
int
atEnd
:
bool
=
False
while
True
:
if
Loop
.
remainingTime
()
<=
0
or
atEnd
:
break
maxlength
=
Serial
.
bytesAvailable
()
if
maxlength
<=
0
:
Serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
else
:
while
maxlength
>
0
:
bufferlength
=
len
(
buffer
)
buffer
.
append
(
Serial
.
read
(
1
))
readlength
=
len
(
buffer
)
-
bufferlength
if
readlength
>
0
:
maxlength
-=
readlength
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
if
atEnd
:
break
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
else
:
Serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# AppTimeLoop.msleep(MAX_SERIAL_READ_DELAY)
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
if
atEnd
:
break
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
# logSERIAL << f"Read: {buffer}"
Request
.
ReceivedBinary
=
buffer
.
data
()
Request
.
ResultNumber
=
RECODE_SUCCEED
if
atEnd
else
RECODE_FAILURE
Loop
.
exit
()
return
TimerLoop
.
execute
(
waittime
,
read_serial_port
,
**
{
"Serial"
:
serial
,
"Request"
:
request
,
"Loop"
:
TimerLoop
})
return
RECODE_SUCCEED
@
staticmethod
def
_ReadMicSerial
(
serial
:
Qt
.
QSerialPort
,
Parameter
:
SerialContext
,
request
:
SerialRequest
,
timeout
:
int
=
-
1
):
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
serial
,
Qt
.
QSerialPort
)
or
not
isinstance
(
Parameter
,
SerialContext
):
return
isWrong
if
not
isinstance
(
request
,
SerialRequest
):
return
isWrong
request
.
ResultNumber
=
isWrong
if
request
.
ReceivedTails
is
None
or
len
(
request
.
ReceivedTails
)
<=
0
:
request
.
ReceivedBinary
=
ScanCodeImpl
.
_ReadSerialPort
(
serial
,
-
1
,
timeout
)
return
RECODE_SUCCEED
TimerLoop
:
AppTimeLoop
=
AppTimeLoop
()
waittime
:
int
=
max
(
timeout
,
Parameter
.
ReadWaitTime
)
def
read_serial_port
(
Serial
:
Qt
.
QSerialPort
,
Request
:
SerialRequest
,
Loop
:
AppTimeLoop
):
from
AppLog.logHelper
import
logSERIAL
tails
:
Qt
.
QByteArray
=
Qt
.
QByteArray
(
Request
.
ReceivedTails
)
maxlength
:
int
readlength
:
int
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
bufferlength
:
int
atEnd
:
bool
=
False
send_buffer
:
bytes
=
Request
.
TransmitBinary
[
0
:
5
]
while
True
:
if
Loop
.
remainingTime
()
<=
0
or
atEnd
:
break
maxlength
=
Serial
.
bytesAvailable
()
if
maxlength
<=
0
:
Serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# AppTimeLoop.msleep(MAX_SERIAL_READ_DELAY)
else
:
bufferlength
=
len
(
buffer
)
buffer
.
append
(
Serial
.
readAll
())
readlength
=
len
(
buffer
)
-
bufferlength
if
readlength
>
0
:
maxlength
-=
readlength
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
if
atEnd
:
break
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
try
:
atEnd
=
buffer
.
indexOf
(
tails
)
>=
0
isSucceed
:
bool
=
buffer
.
indexOf
(
send_buffer
)
>=
0
if
atEnd
:
if
isSucceed
:
buffer
=
buffer
.
mid
(
buffer
.
indexOf
(
send_buffer
))
break
else
:
buffer
=
buffer
.
mid
(
buffer
.
indexOf
(
tails
)
+
len
(
tails
))
continue
except
Exception
as
e
:
logSERIAL
<<
AppUtils
.
toString
(
e
)
# logSERIAL << f"Read: {buffer}"
Request
.
ReceivedBinary
=
buffer
.
data
()
Request
.
ResultNumber
=
RECODE_SUCCEED
if
atEnd
else
RECODE_FAILURE
Loop
.
exit
()
return
TimerLoop
.
execute
(
waittime
,
read_serial_port
,
**
{
"Serial"
:
serial
,
"Request"
:
request
,
"Loop"
:
TimerLoop
})
return
RECODE_SUCCEED
@
staticmethod
def
_ReadSerialPort
(
serial
:
Qt
.
QSerialPort
,
length
:
int
,
waittimes
:
int
=
1000
)
->
Qt
.
QByteArray
:
from
AppLog.logHelper
import
logSERIAL
buffer
:
Qt
.
QByteArray
=
Qt
.
QByteArray
()
maxlength
:
int
remaining
:
int
readlength
:
int
bufferlength
:
int
waittime
:
int
=
max
(
waittimes
,
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
ETime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
maxlength
=
serial
.
bytesAvailable
()
if
Qt
.
QDateTime
.
currentDateTime
()
>=
ETime
:
break
if
0
<
length
<=
maxlength
:
break
if
length
<=
0
:
buffer
.
append
(
serial
.
readAll
())
else
:
ETime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
remaining
=
min
(
length
,
maxlength
)
while
remaining
>
0
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
bufferlength
=
len
(
buffer
)
buffer
.
append
(
serial
.
read
(
remaining
))
readlength
=
len
(
buffer
)
-
bufferlength
if
readlength
>
0
:
remaining
-=
readlength
else
:
serial
.
waitForReadyRead
(
MAX_SERIAL_READ_DELAY
)
# logSERIAL << f"Send: {buffer}"
return
buffer
@
staticmethod
def
_SendSerial
(
serial
:
Qt
.
QSerialPort
,
buffer
:
Qt
.
QByteArray
,
timeout
:
int
=
1000
):
return
ScanCodeImpl
.
_ReadSerialPort
(
serial
=
serial
,
buffer
=
buffer
,
waittimes
=
timeout
)
@
staticmethod
def
_SendSerialPort
(
serial
:
Qt
.
QSerialPort
,
buffer
:
Qt
.
QByteArray
,
waittimes
:
int
)
->
int
:
from
AppLog.logHelper
import
logSERIAL
isWrong
:
int
maxlength
:
int
remaining
:
int
sendlength
:
int
sendindex
:
int
waittime
:
int
=
max
(
waittimes
,
MAX_SERIAL_DEFAULT_WAIT_TIMES
)
ETime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
if
serial
.
isWritable
()
or
serial
.
bytesToWrite
()
<=
0
:
break
serial
.
flush
()
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
remaining
=
len
(
buffer
)
sendindex
=
0
ETime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittime
)
while
remaining
>=
MAX_SERIAL_SEND_BUFFER_LENGTH
:
sendlength
=
serial
.
write
(
buffer
.
mid
(
sendindex
,
MAX_SERIAL_SEND_BUFFER_LENGTH
))
if
sendlength
<=
0
:
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
else
:
sendindex
+=
MAX_SERIAL_SEND_BUFFER_LENGTH
remaining
-=
MAX_SERIAL_SEND_BUFFER_LENGTH
while
remaining
>
0
:
sendlength
=
serial
.
write
(
buffer
.
mid
(
sendindex
,
remaining
))
if
sendlength
<=
0
:
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
else
:
sendindex
+=
remaining
remaining
-=
remaining
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
ETime
:
break
if
serial
.
isWritable
()
or
serial
.
bytesToWrite
()
<=
0
:
break
serial
.
flush
()
AppTimeLoop
.
processGlobalEvents
(
MAX_SERIAL_READ_DELAY
)
# logSERIAL << f"Send: {buffer}"
isWrong
=
RECODE_SUCCEED
if
remaining
<=
0
else
RECODE_FAILURE
return
isWrong
@
staticmethod
def
_isSerialOpened
(
serial
:
Qt
.
QSerialPort
)
->
bool
:
return
isinstance
(
serial
,
Qt
.
QSerialPort
)
and
serial
.
isOpen
()
@
staticmethod
def
_isSerialReadable
(
serial
:
Qt
.
QSerialPort
)
->
bool
:
return
isinstance
(
serial
,
Qt
.
QSerialPort
)
and
serial
.
isReadable
()
@
staticmethod
def
_isSerialWritable
(
serial
:
Qt
.
QSerialPort
)
->
bool
:
return
isinstance
(
serial
,
Qt
.
QSerialPort
)
and
serial
.
isWritable
()
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'Manager'
)
and
isinstance
(
self
.
Manager
,
Qt
.
QSerialPort
)
def
hasParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'Parameter'
)
and
isinstance
(
self
.
Parameter
,
SerialContext
)
AppCore/AppImplsbak/WebSocketClient.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: WebSocketClient.py
@DateTime: 2025/6/28 20:53
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
from
AppSettings.Settings
import
RECODE_FAILURE
,
RECODE_SUCCEED
,
CODE_FAILURE
,
CODE_SUCCESS
,
CODE_WARNING
from
AppInterfaces.ImplInterface
import
ImplInterface
,
AppUtils
,
AppConvert
,
AppTimeLoop
,
log_exceptions
from
AppCore.Contexts
import
WebSocketContext
from
AppCore.Requests
import
Request
,
Response
from
AppCore.Levels
import
WebAPILevel
from
AppCore.ImplInterfaces
import
WebClientInterface
SOCKET_DEFAULT_DELAY
:
int
=
50
SOCKET_MAX_CONNECT_DELAY
:
int
=
2000
class
WebSocketClient
(
Qt
.
QObject
,
WebClientInterface
):
IOLocker
:
Qt
.
QReadWriteLock
Manager
:
Qt
.
QWebSocket
Parameter
:
WebSocketContext
ConnectedSignal
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
Request
)
DisconnectedSignal
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
Request
)
ReceivedFrame
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
Request
)
TransmitFrame
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
)
def
__init__
(
self
,
parent
:
Qt
.
QObject
=
None
):
super
(
WebSocketClient
,
self
)
.
__init__
(
parent
=
parent
)
self
.
Initialization
(
'WebSocketClient'
,
self
,
parent
)
self
.
initManager
(
context
=
None
)
@
classmethod
def
instance
(
cls
,
context
:
WebSocketContext
=
None
,
socket
:
Qt
.
QWebSocket
=
None
,
parent
:
Qt
.
QObject
=
None
)
->
'WebSocketClient'
:
result
:
WebSocketClient
=
cls
.
__new__
(
cls
)
result
.
__init__
(
parent
=
parent
)
result
.
initManager
(
context
,
socket
=
socket
)
return
result
def
initConnect
(
self
):
super
(
WebSocketClient
,
self
)
.
initConnect
()
TYPE
:
Qt
.
Qt
.
ConnectionType
=
Qt
.
Qt
.
ConnectionType
(
Qt
.
Qt
.
AutoConnection
|
Qt
.
Qt
.
UniqueConnection
)
self
.
TransmitFrame
.
connect
(
slot
=
self
.
slot_SocketTransmitFrame
,
type
=
TYPE
)
def
deleConnect
(
self
):
super
(
WebSocketClient
,
self
)
.
deleConnect
()
def
deleValue
(
self
):
super
(
WebSocketClient
,
self
)
.
deleValue
()
self
.
Close
()
self
.
Manager
=
None
self
.
Parameter
=
None
def
initValue
(
self
):
super
(
WebSocketClient
,
self
)
.
initValue
()
if
not
self
.
hasLocker
:
self
.
IOLocker
=
Qt
.
QReadWriteLock
()
self
.
Manager
=
None
self
.
Parameter
=
None
@
property
def
hasLocker
(
self
)
->
bool
:
return
hasattr
(
self
,
'IOLocker'
)
and
isinstance
(
self
.
IOLocker
,
Qt
.
QReadWriteLock
)
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'Manager'
)
and
self
.
Manager
is
not
None
def
hasParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'Parameter'
)
and
self
.
Parameter
is
not
None
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasParameter
()
def
IsOpen
(
self
)
->
bool
:
return
False
if
not
self
.
hasParameter
()
else
self
.
Parameter
.
IsOpen
def
isEnabled
(
self
)
->
bool
:
return
False
if
not
self
.
hasParameter
()
else
self
.
Parameter
.
IsOpen
def
isDisable
(
self
)
->
bool
:
return
True
if
not
self
.
hasParameter
()
else
not
self
.
Parameter
.
IsOpen
def
Open
(
self
,
timeOut
:
int
=
1000
)
->
int
:
waittimes
:
int
=
max
(
abs
(
timeOut
),
SOCKET_MAX_CONNECT_DELAY
)
if
not
self
.
isValid
():
self
.
initManager
(
self
.
Parameter
)
if
not
self
.
isValid
():
return
RECODE_FAILURE
if
self
.
IsOpen
()
and
self
.
EqualSocket
(
self
.
Manager
,
self
.
Parameter
):
return
RECODE_SUCCEED
self
.
Parameter
.
IsOpen
=
False
self
.
Manager
.
abort
()
self
.
Manager
.
open
(
Qt
.
QUrl
(
self
.
Parameter
.
API
))
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
or
self
.
Parameter
.
IsOpen
:
break
AppTimeLoop
.
processGlobalEvents
(
SOCKET_DEFAULT_DELAY
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
# SOCKET_DEFAULT_DELAY
# SOCKET_MAX_CONNECT_DELAY
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
waittimes
:
int
=
max
(
abs
(
timeOut
),
SOCKET_MAX_CONNECT_DELAY
)
if
not
self
.
isValid
():
return
RECODE_SUCCEED
if
not
self
.
IsOpen
():
return
RECODE_SUCCEED
self
.
Manager
.
abort
()
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
or
not
self
.
Parameter
.
IsOpen
:
break
AppTimeLoop
.
processGlobalEvents
(
SOCKET_DEFAULT_DELAY
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
initManager
(
self
,
context
:
object
,
**
args
):
from
AppSettings.AppSetting
import
AppSetting
,
AppConfig
if
not
self
.
hasParameter
():
self
.
Parameter
=
AppConfig
.
webConfig
if
isinstance
(
context
,
WebSocketContext
):
if
self
.
Parameter
.
API
.
lower
()
!=
context
.
API
.
lower
():
self
.
Parameter
.
API
=
context
.
API
self
.
Parameter
.
Mode
=
context
.
Mode
self
.
Parameter
.
Descriptor
=
context
.
Descriptor
self
.
Parameter
.
IsOpen
=
False
socket
:
Qt
.
QWebSocket
=
args
.
get
(
'socket'
,
None
)
if
isinstance
(
socket
,
Qt
.
QWebSocket
):
if
self
.
hasManager
():
if
id
(
self
.
Manager
)
!=
id
(
socket
):
self
.
Manager
.
close
()
self
.
deleSocketConnect
(
self
.
Manager
)
self
.
Manager
=
socket
self
.
initSocketConnect
(
self
.
Manager
)
else
:
self
.
Manager
=
socket
self
.
initSocketConnect
(
self
.
Manager
)
else
:
if
not
self
.
hasManager
():
self
.
Manager
=
Qt
.
QWebSocket
()
self
.
initSocketConnect
(
self
.
Manager
)
def
initContext
(
self
):
if
not
self
.
hasParameter
():
self
.
Parameter
=
WebSocketContext
()
def
initIOLocker
(
self
):
if
not
self
.
hasLocker
:
self
.
IOLocker
=
Qt
.
QReadWriteLock
()
def
deleManager
(
self
):
self
.
initContext
()
if
self
.
hasManager
():
self
.
Manager
.
abort
()
if
self
.
hasParameter
():
self
.
Parameter
.
IsOpen
=
False
self
.
Parameter
.
Descriptor
=
0
self
.
Manager
=
None
def
initSocketConnect
(
self
,
socket
:
Qt
.
QWebSocket
):
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
):
return
TYPE
:
Qt
.
Qt
.
ConnectionType
=
Qt
.
Qt
.
ConnectionType
(
Qt
.
Qt
.
AutoConnection
|
Qt
.
Qt
.
UniqueConnection
)
socket
.
textFrameReceived
.
connect
(
slot
=
self
.
slot_SocketReadStringFrame
,
type
=
TYPE
)
socket
.
binaryFrameReceived
.
connect
(
slot
=
self
.
slot_SocketReadBinaryFrame
,
type
=
TYPE
)
socket
.
error
.
connect
(
slot
=
self
.
slot_SocketCurrentError
,
type
=
TYPE
)
socket
.
stateChanged
.
connect
(
slot
=
self
.
slot_SocketStateChanged
,
type
=
TYPE
)
socket
.
connected
.
connect
(
slot
=
self
.
slot_SocketConnected
,
type
=
TYPE
)
socket
.
disconnected
.
connect
(
slot
=
self
.
slot_SocketDisconnected
,
type
=
TYPE
)
pass
def
deleSocketConnect
(
self
,
socket
:
Qt
.
QWebSocket
):
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
):
return
self
.
Parameter
.
IsOpen
=
False
socket
.
textFrameReceived
.
disconnect
()
socket
.
binaryFrameReceived
.
disconnect
()
socket
.
error
.
disconnect
()
socket
.
stateChanged
.
disconnect
()
socket
.
connected
.
disconnect
()
socket
.
disconnected
.
disconnect
()
def
slot_SocketReadStringFrame
(
self
,
buffer
:
str
):
self
.
initIOLocker
()
Locker
:
Qt
.
QReadLocker
=
Qt
.
QReadLocker
(
self
.
IOLocker
)
from
AppLog.logHelper
import
logWEBSERVER
,
logWARNING
request
:
Request
=
Request
()
try
:
request
.
asJson
(
buffer
)
request
.
Buffer
=
buffer
except
Exception
as
e
:
logWARNING
<<
AppUtils
.
toString
(
e
)
return
request
.
level
=
WebAPILevel
.
toValue
(
request
.
callback
)
request
.
Handler
=
self
request
.
Buffer
=
buffer
logWEBSERVER
<<
f
"Address:{self.Manager.peerAddress().toString()} Port: {self.Manager.peerPort()} data: {buffer}"
self
.
ReceivedFrame
.
emit
(
request
)
pass
def
slot_SocketReadBinaryFrame
(
self
,
buffer
:
bytes
):
self
.
initIOLocker
()
Locker
:
Qt
.
QReadLocker
=
Qt
.
QReadLocker
(
self
.
IOLocker
)
from
AppLog.logHelper
import
logWEBSERVER
,
logWARNING
request
:
Request
=
Request
()
try
:
string
=
buffer
.
decode
(
'utf-8'
)
request
.
asJson
(
string
)
request
.
Buffer
=
string
except
Exception
as
e
:
logWARNING
<<
AppUtils
.
toString
(
e
)
return
request
.
level
=
WebAPILevel
.
toValue
(
request
.
callback
)
request
.
Handler
=
self
logWEBSERVER
<<
f
"Address:{self.Manager.peerAddress().toString()} Port: {self.Manager.peerPort()} data: {string}"
self
.
ReceivedFrame
.
emit
(
request
)
pass
def
slot_SocketCurrentError
(
self
,
error
):
socket
:
Qt
.
QWebSocket
=
self
.
sender
()
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
):
return
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
current_function_info
(
f
"ADDR: {socket.peerAddress().toString()} Port: {socket.peerPort()} SocketError: {error} errorString: {socket.errorString()}"
)
self
.
Parameter
.
IsOpen
=
socket
.
state
()
==
Qt
.
QAbstractSocket
.
SocketState
.
ConnectedState
pass
def
slot_SocketStateChanged
(
self
,
state
:
int
):
socket
:
Qt
.
QWebSocket
=
self
.
sender
()
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
):
return
self
.
Parameter
.
IsOpen
=
socket
.
state
()
==
Qt
.
QAbstractSocket
.
SocketState
.
ConnectedState
pass
def
slot_SocketConnected
(
self
):
self
.
Parameter
.
IsOpen
=
True
self
.
Parameter
.
Address
=
self
.
Manager
.
localAddress
()
.
toString
()
self
.
Parameter
.
Port
=
self
.
Manager
.
localPort
()
self
.
ConnectedSignal
.
emit
(
Request
.
instance
(
buffer
=
None
,
Handler
=
self
))
pass
def
slot_SocketDisconnected
(
self
):
self
.
Parameter
.
IsOpen
=
False
self
.
ConnectedSignal
.
emit
(
Request
.
instance
(
buffer
=
None
,
Handler
=
self
))
def
slot_SocketTransmitFrame
(
self
,
buffer
):
if
isinstance
(
buffer
,
str
):
self
.
TransmitString
(
buffer
)
elif
isinstance
(
buffer
,
bytes
)
or
isinstance
(
buffer
,
bytearray
)
or
isinstance
(
buffer
,
Qt
.
QByteArray
):
self
.
TransmitBinary
(
buffer
)
else
:
self
.
TransmitBinary
(
buffer
)
pass
def
TransmitString
(
self
,
buffer
,
**
args
)
->
int
:
sendBuffer
:
str
if
isinstance
(
buffer
,
str
):
sendBuffer
=
buffer
elif
isinstance
(
buffer
,
bytes
)
or
isinstance
(
buffer
,
bytearray
):
sendBuffer
=
buffer
.
decode
(
'utf-8'
)
elif
isinstance
(
buffer
,
Qt
.
QByteArray
):
sendBuffer
=
buffer
.
data
()
.
decode
(
'utf-8'
)
elif
isinstance
(
buffer
,
Response
):
sendBuffer
=
buffer
.
toJson
()
elif
isinstance
(
buffer
,
Request
):
sendBuffer
=
buffer
.
toJson
()
else
:
sendBuffer
=
f
"{buffer}"
self
.
SocketSendString
(
self
.
Manager
,
sendBuffer
)
def
TransmitBinary
(
self
,
buffer
,
**
args
)
->
int
:
sendBuffer
:
bytes
if
isinstance
(
buffer
,
str
):
sendBuffer
=
buffer
.
encode
(
'utf-8'
)
elif
isinstance
(
buffer
,
bytes
)
or
isinstance
(
buffer
,
bytearray
):
sendBuffer
=
buffer
elif
isinstance
(
buffer
,
Qt
.
QByteArray
):
sendBuffer
=
buffer
.
data
()
elif
isinstance
(
buffer
,
Response
):
sendBuffer
=
buffer
.
toJson
()
.
encode
(
'utf-8'
)
elif
isinstance
(
buffer
,
Request
):
sendBuffer
=
buffer
.
toJson
()
.
encode
(
'utf-8'
)
else
:
sendBuffer
=
f
"{buffer}"
.
encode
(
'utf-8'
)
self
.
SocketSendBinary
(
self
.
Manager
,
sendBuffer
)
@
staticmethod
def
SocketSendString
(
socket
:
Qt
.
QWebSocket
,
buffer
:
str
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
)
or
AppConvert
.
isEmpty
(
buffer
):
return
isWrong
try
:
OtherLength
:
int
=
socket
.
bytesToWrite
()
MaxLength
:
int
=
len
(
buffer
)
SendLength
:
int
while
OtherLength
>
0
:
AppTimeLoop
.
processGlobalEvents
(
SOCKET_DEFAULT_DELAY
)
OtherLength
=
socket
.
bytesToWrite
()
SendLength
=
socket
.
sendTextMessage
(
buffer
)
OtherLength
=
socket
.
bytesToWrite
()
while
OtherLength
>
0
:
AppTimeLoop
.
processGlobalEvents
(
SOCKET_DEFAULT_DELAY
)
OtherLength
=
socket
.
bytesToWrite
()
isWrong
=
SendLength
==
MaxLength
or
OtherLength
<=
0
except
Exception
as
e
:
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
toString
(
e
)
return
isWrong
@
staticmethod
def
SocketSendBinary
(
socket
:
Qt
.
QWebSocket
,
buffer
:
bytes
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
)
or
not
isinstance
(
buffer
,
bytes
)
or
len
(
buffer
)
<=
0
:
return
isWrong
try
:
# OtherLength: int = socket.bytesToWrite()
MaxLength
:
int
=
len
(
buffer
)
# SendLength: int
# while OtherLength > 0:
# AppTimeLoop.processGlobalEvents(SOCKET_DEFAULT_DELAY)
# OtherLength = socket.bytesToWrite()
SendLength
=
socket
.
sendBinaryMessage
(
buffer
)
# OtherLength = socket.bytesToWrite()
# while OtherLength > 0:
# AppTimeLoop.processGlobalEvents(SOCKET_DEFAULT_DELAY)
# OtherLength = socket.bytesToWrite()
isWrong
=
SendLength
==
MaxLength
except
Exception
as
e
:
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
toString
(
e
)
return
isWrong
@
staticmethod
def
SocketClose
(
socket
:
Qt
.
QWebSocket
,
Parameter
:
WebSocketContext
)
->
int
:
isWrong
:
int
=
RECODE_SUCCEED
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
)
or
not
isinstance
(
Parameter
,
WebSocketContext
):
return
isWrong
try
:
socket
.
close
()
Parameter
.
IsOpen
=
False
except
Exception
as
e
:
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
toString
(
e
)
return
isWrong
@
staticmethod
def
SocketOpen
(
socket
:
Qt
.
QWebSocket
,
Parameter
:
WebSocketContext
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
)
or
not
isinstance
(
Parameter
,
WebSocketContext
):
return
isWrong
WebSocketClient
.
SocketClose
(
socket
,
Parameter
)
Parameter
.
IsOpen
=
False
try
:
socket
.
open
(
Qt
.
QUrl
(
Parameter
.
API
))
isWrong
=
RECODE_SUCCEED
except
Exception
as
e
:
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
toString
(
e
)
isWrong
=
RECODE_FAILURE
return
isWrong
@
staticmethod
def
EqualSocket
(
Manager
:
Qt
.
QWebSocket
,
Parameter
:
WebSocketContext
)
->
bool
:
if
not
isinstance
(
Manager
,
Qt
.
QWebSocket
)
or
not
isinstance
(
Parameter
,
WebSocketContext
):
return
False
return
Manager
.
requestUrl
()
.
toString
()
.
lower
()
==
Qt
.
QUrl
(
Parameter
.
API
)
.
toString
()
.
lower
()
\ No newline at end of file
AppCore/AppImplsbak/WebSocketServer.py
deleted
100644 → 0
View file @
854d2864
#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName: WebSocketServer.py
@DateTime: 2025/6/28 20:53
@SoftWare: PyCharm
@Author :xsh
"""
from
PyQt5
import
Qt
from
AppSettings.Settings
import
(
RECODE_FAILURE
,
RECODE_SUCCEED
,
CODE_SUCCESS
,
PROCESS_EVENT_DELAY
)
from
AppInterfaces.ImplInterface
import
AppUtils
,
AppTimeLoop
from
AppInterfaces.ImplInterface
import
ServerImplInterface
from
AppCore.Contexts
import
WebSocketContext
from
AppCore.Requests
import
Request
,
Response
from
AppCore.AppLevelModels.WebAPILevel
import
WebAPILevel
from
AppCore.AppImpls.WebSocketClient
import
WebSocketClient
,
SOCKET_MAX_CONNECT_DELAY
from
AppCore.ImplInterfaces
import
WebServerInterface
,
WebClientInterface
DEFAULT_WEBSERVER_NAME
:
str
=
"MicroscopeScanWebServer"
DEFAULT_WEBSERVER_SECURE_MODE
=
Qt
.
QWebSocketServer
.
SslMode
.
NonSecureMode
class
WebSocketServer
(
Qt
.
QObject
,
WebServerInterface
):
Manager
:
Qt
.
QWebSocketServer
Parameter
:
WebSocketContext
TransmitFrame
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
)
ReceivedFrame
:
Qt
.
pyqtSignal
=
Qt
.
pyqtSignal
(
object
)
def
__init__
(
self
,
context
=
None
,
parent
:
Qt
.
QObject
=
None
):
super
(
WebSocketServer
,
self
)
.
__init__
(
parent
=
parent
)
self
.
Parameter
=
context
self
.
Initialization
(
"WebSocketServer"
,
self
,
parent
)
@
classmethod
def
instance
(
cls
,
context
=
None
,
parent
:
Qt
.
QObject
=
None
)
->
'WebSocketServer'
:
result
:
WebSocketServer
=
cls
.
__new__
(
cls
)
result
.
__init__
(
context
,
parent
)
return
result
def
Start
(
self
)
->
bool
:
return
self
.
Open
()
==
RECODE_SUCCEED
def
Stop
(
self
):
self
.
Close
()
def
initValue
(
self
):
super
(
WebSocketServer
,
self
)
.
initValue
()
self
.
initManager
(
context
=
self
.
Parameter
if
self
.
hasParameter
else
None
)
def
deleValue
(
self
):
super
(
WebSocketServer
,
self
)
.
deleValue
()
if
self
.
hasManager
:
self
.
deleServerConnect
(
self
.
Manager
)
self
.
Close
()
self
.
Manager
=
None
self
.
Parameter
=
None
self
.
Handles
=
[]
def
deleProperty
(
self
):
super
(
WebSocketServer
,
self
)
.
deleProperty
()
self
.
deleHandles
()
def
initConnect
(
self
):
super
(
WebSocketServer
,
self
)
.
initConnect
()
TYPE
:
Qt
.
Qt
.
ConnectionType
=
Qt
.
Qt
.
ConnectionType
(
Qt
.
Qt
.
AutoConnection
|
Qt
.
Qt
.
UniqueConnection
)
self
.
TransmitFrame
.
connect
(
slot
=
self
.
slot_SocketTransmitFrame
,
type
=
TYPE
)
def
deleConnect
(
self
):
super
(
WebSocketServer
,
self
)
.
deleConnect
()
try
:
self
.
TransmitFrame
.
disconnect
(
self
.
slot_SocketTransmitFrame
)
except
Exception
as
e
:
pass
def
IsOpen
(
self
)
->
bool
:
return
self
.
hasManager
and
self
.
Manager
.
isListening
()
def
isEnabled
(
self
)
->
bool
:
return
self
.
hasManager
and
self
.
Manager
.
isListening
()
def
isDisable
(
self
)
->
bool
:
return
not
self
.
isEnabled
()
def
Open
(
self
,
timeOut
:
int
=
1000
)
->
int
:
waittimes
:
int
=
max
(
abs
(
timeOut
),
SOCKET_MAX_CONNECT_DELAY
)
if
not
self
.
hasManager
:
self
.
initManager
(
self
.
Parameter
if
self
.
hasManager
else
None
)
if
not
self
.
hasManager
:
return
RECODE_FAILURE
if
self
.
IsOpen
():
return
RECODE_SUCCEED
url
:
Qt
.
QUrl
=
Qt
.
QUrl
(
self
.
Parameter
.
API
)
print
(
url
,
url
.
port
(),
url
.
host
())
self
.
Parameter
.
IsOpen
=
self
.
Manager
.
listen
(
Qt
.
QHostAddress
(
url
.
host
()),
url
.
port
(
9903
))
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
or
self
.
Parameter
.
IsOpen
:
break
AppTimeLoop
.
processEvents
(
PROCESS_EVENT_DELAY
)
self
.
Parameter
.
IsOpen
=
self
.
Manager
.
listen
(
Qt
.
QHostAddress
(
self
.
Parameter
.
Addr
),
self
.
Parameter
.
Port
)
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
Close
(
self
,
timeOut
:
int
=
1000
)
->
int
:
waittimes
:
int
=
max
(
abs
(
timeOut
),
SOCKET_MAX_CONNECT_DELAY
)
if
not
self
.
isValid
:
return
RECODE_SUCCEED
if
not
self
.
IsOpen
():
return
RECODE_SUCCEED
self
.
Manager
.
close
()
endtime
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
.
addMSecs
(
waittimes
)
while
True
:
self
.
Parameter
.
IsOpen
=
self
.
Manager
.
isListening
()
if
Qt
.
QDateTime
.
currentDateTime
()
>
endtime
or
not
self
.
Parameter
.
IsOpen
:
break
AppTimeLoop
.
processEvents
(
PROCESS_EVENT_DELAY
)
self
.
Manager
.
close
()
return
RECODE_SUCCEED
if
self
.
Parameter
.
IsOpen
else
RECODE_FAILURE
def
initManager
(
self
,
context
:
object
,
**
args
):
if
isinstance
(
context
,
WebSocketContext
):
if
not
self
.
hasParameter
or
self
.
Parameter
!=
context
:
self
.
Parameter
=
context
if
not
self
.
hasParameter
:
self
.
Parameter
=
WebSocketContext
()
self
.
initHandles
()
if
not
self
.
hasManager
:
self
.
Manager
=
Qt
.
QWebSocketServer
(
DEFAULT_WEBSERVER_NAME
,
DEFAULT_WEBSERVER_SECURE_MODE
)
self
.
initServerConnect
(
self
.
Manager
)
def
deleManager
(
self
):
self
.
Close
()
self
.
deleHandles
()
self
.
Manager
=
None
def
initServerConnect
(
self
,
socket
:
Qt
.
QWebSocketServer
):
if
not
isinstance
(
socket
,
Qt
.
QWebSocketServer
):
return
TYPE
:
Qt
.
Qt
.
ConnectionType
=
Qt
.
Qt
.
ConnectionType
(
Qt
.
Qt
.
AutoConnection
|
Qt
.
Qt
.
UniqueConnection
)
socket
.
acceptError
.
connect
(
slot
=
self
.
slot_acceptError
,
type
=
TYPE
)
socket
.
serverError
.
connect
(
slot
=
self
.
slot_serverError
,
type
=
TYPE
)
socket
.
newConnection
.
connect
(
slot
=
self
.
slot_newConnection
,
type
=
TYPE
)
def
deleServerConnect
(
self
,
socket
:
Qt
.
QWebSocketServer
):
if
not
isinstance
(
socket
,
Qt
.
QWebSocketServer
):
return
socket
.
acceptError
.
disconnect
()
socket
.
serverError
.
disconnect
()
socket
.
newConnection
.
disconnect
()
def
initSocketConnect
(
self
,
socket
:
WebSocketClient
):
if
not
isinstance
(
socket
,
WebSocketClient
):
return
TYPE
:
Qt
.
Qt
.
ConnectionType
=
Qt
.
Qt
.
ConnectionType
(
Qt
.
Qt
.
AutoConnection
|
Qt
.
Qt
.
UniqueConnection
)
socket
.
ReceivedFrame
.
connect
(
slot
=
self
.
slot_SocketReceivedFrame
,
type
=
TYPE
)
socket
.
ConnectedSignal
.
connect
(
slot
=
self
.
slot_SocketConnected
,
type
=
TYPE
)
socket
.
DisconnectedSignal
.
connect
(
slot
=
self
.
slot_SocketDisconnected
,
type
=
TYPE
)
def
deleSocketConnect
(
self
,
socket
:
WebSocketClient
):
if
not
isinstance
(
socket
,
WebSocketClient
):
return
socket
.
ReceivedFrame
.
disconnect
()
socket
.
ConnectedSignal
.
disconnect
()
socket
.
DisconnectedSignal
.
disconnect
()
def
slot_acceptError
(
self
,
socketError
):
server
:
Qt
.
QWebSocketServer
=
self
.
sender
()
if
not
isinstance
(
server
,
Qt
.
QWebSocketServer
):
return
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
current_function_info
(
f
"ADDR: {server.serverAddress().toString()} Port: {server.serverPort()} Error: {socketError}"
)
pass
def
slot_serverError
(
self
,
closeCode
):
server
:
Qt
.
QWebSocketServer
=
self
.
sender
()
if
not
isinstance
(
server
,
Qt
.
QWebSocketServer
):
return
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
current_function_info
(
f
"ADDR: {server.serverAddress().toString()} Port: {server.serverPort()} closeCode: {closeCode}"
)
pass
def
slot_newConnection
(
self
):
Server
:
Qt
.
QWebSocketServer
=
self
.
sender
()
if
not
isinstance
(
Server
,
Qt
.
QWebSocketServer
):
return
socket
:
Qt
.
QWebSocket
=
Server
.
nextPendingConnection
()
if
not
isinstance
(
socket
,
Qt
.
QWebSocket
):
return
from
AppLog.logHelper
import
logWEBSERVER
logWEBSERVER
<<
AppUtils
.
current_function_info
(
f
"Server: {Server.serverUrl()} ADDR: {socket.peerAddress().toString()} Port: {socket.peerPort()}"
)
handler
:
WebSocketClient
=
WebSocketClient
.
instance
(
context
=
None
,
socket
=
socket
)
index
:
int
=
self
.
indexOf
(
handler
)
if
index
>=
0
:
return
self
.
initSocketConnect
(
handler
)
self
.
Handles
.
append
(
handler
)
response
:
Response
=
Request
.
instance
(
buffer
=
None
,
code
=
CODE_SUCCESS
,
message
=
"连接成功"
,
callback
=
WebAPILevel
.
toString
(
WebAPILevel
.
NoneWebAPI
))
print
(
response
.
toJson
())
handler
.
TransmitFrame
.
emit
(
response
.
toJson
())
pass
def
slot_SocketReceivedFrame
(
self
,
buffer
):
self
.
ReceivedFrame
.
emit
(
buffer
)
pass
def
slot_SocketConnected
(
self
,
request
:
Request
):
if
isinstance
(
request
,
Request
):
return
Lock
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
IOLocker
)
index
:
int
number
:
int
=
len
(
self
.
Handles
)
if
isinstance
(
request
.
Handler
,
WebSocketClient
):
index
=
self
.
indexOf
(
request
.
Handler
)
elif
isinstance
(
request
.
Handler
,
Qt
.
QWebSocket
):
index
=
self
.
indexOf
(
request
.
Handler
)
else
:
index
=
number
if
index
<
0
:
self
.
Handles
.
append
(
request
.
Handler
)
pass
def
slot_SocketDisconnected
(
self
,
request
:
Request
):
if
isinstance
(
request
,
Request
):
return
Lock
:
Qt
.
QWriteLocker
=
Qt
.
QWriteLocker
(
self
.
IOLocker
)
index
:
int
if
isinstance
(
request
.
Handler
,
WebSocketClient
):
index
=
self
.
indexOf
(
request
.
Handler
)
elif
isinstance
(
request
.
Handler
,
Qt
.
QWebSocket
):
index
=
self
.
indexOf
(
request
.
Handler
)
else
:
index
=
-
1
if
index
>=
0
:
self
.
Handles
.
pop
(
index
)
def
slot_SocketTransmitFrame
(
self
,
buffer
):
self
.
TransmitString
(
buffer
)
pass
def
slot_WebServerTransmit
(
self
,
name
:
str
,
buffer
):
if
name
==
self
.
__class__
.
__name__
:
self
.
TransmitString
(
buffer
)
pass
def
TransmitString
(
self
,
buffer
,
**
args
)
->
int
:
if
len
(
self
.
Handles
)
<=
0
:
return
RECODE_SUCCEED
socket
:
WebSocketClient
for
index
,
socket
in
enumerate
(
self
.
Handles
):
if
socket
is
not
None
:
socket
.
TransmitFrame
.
emit
(
buffer
)
return
RECODE_SUCCEED
def
__getitem__
(
self
,
key
:
int
)
->
WebSocketClient
:
return
super
(
WebSocketServer
,
self
)
.
__getitem__
(
key
)
def
__setitem__
(
self
,
key
:
int
,
value
:
WebSocketClient
):
super
(
WebSocketServer
,
self
)
.
__setitem__
(
key
,
value
)
AppCore/AppImplsbak/__init__.py
deleted
100644 → 0
View file @
854d2864
#!D:/IDE/anaconda3/envs python
# -*- coding: UTF-8 -*-
"""
@Author: Administrator
@FileName:__init__.py.py
\n
@DateTime: 2025/6/18 17:32
\n
@Author :xsh
"""
AppCore/AppReaders/DetectionReader.py
View file @
bd7c532f
...
...
@@ -36,94 +36,42 @@ class DetectionReader(Qt.QObject, DetectionReaderInterface):
self
.
_IsInitialize
=
isinstance
(
pool
,
ModBusPoolInterface
)
and
isinstance
(
context
,
DetectionContext
)
self
.
Initialization
(
"DetectionReader"
,
self
,
parent
)
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'_Manager'
)
and
isinstance
(
self
.
_Manager
,
ModBusPoolInterface
)
def
hasParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'_Parameter'
)
and
isinstance
(
self
.
_Parameter
,
DetectionContext
)
def
initManager
(
self
):
self
.
initContext
()
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
from
AppCore.AppReaders.ModBusPool
import
ModBusPool
self
.
_
Manager
=
ModBusPool
.
GetInstance
()
@
property
def
manager
(
self
)
->
ModBusPoolInterface
:
return
None
if
not
self
.
hasManager
()
else
self
.
_Manager
self
.
Manager
=
ModBusPool
.
GetInstance
()
def
deleManager
(
self
)
:
self
.
Manager
=
None
@
property
def
Parameter
(
self
)
->
DetectionContext
:
return
None
if
not
self
.
hasParameter
()
else
self
.
_Parameter
@
Parameter
.
setter
def
Parameter
(
self
,
value
:
DetectionContext
):
self
.
initContext
()
def
initContext
(
self
):
from
AppSettings.AppSetting
import
AppConfig
self
.
_Parameter
=
AppConfig
.
manipulatorConfig
.
detectionConfig
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasParameter
()
self
.
Parameter
=
DetectionContext
()
try
:
self
.
Parameter
.
deserialize
(
AppConfig
.
manipulatorConfig
.
detectionConfig
.
serialize
())
except
Exception
as
e
:
AppUtils
.
print_Exception
(
e
)
def
IsOpen
(
self
)
->
bool
:
return
self
.
isValid
()
and
self
.
_Manager
.
IsOpen
()
@
property
def
isAvailable
(
self
)
->
bool
:
handle
:
ModBusInterface
=
self
.
handler
()
return
self
.
hasManager
()
and
handle
is
not
None
and
handle
.
isAvailable
def
Open
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
self
.
initContext
()
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
return
RECODE_FAILURE
if
self
.
_
Manager
.
IsOpen
():
if
self
.
Manager
.
IsOpen
():
return
RECODE_SUCCEED
return
self
.
Manager
.
Open
(
timeOut
)
return
self
.
_Manager
.
Open
(
timeOut
)
def
handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
():
return
None
if
not
self
.
_Manager
.
IsOpen
():
self
.
_Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
():
return
None
return
self
.
_Manager
.
detectorhandler
def
slow_handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
():
return
None
if
not
self
.
_Manager
.
IsOpen
():
self
.
_Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
():
return
None
return
self
.
_Manager
.
slow_handler
def
readhandler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
():
return
None
if
not
self
.
_Manager
.
IsOpen
():
self
.
_Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
():
return
None
return
self
.
_Manager
.
readhandler
def
scan_handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
():
return
None
if
not
self
.
_Manager
.
IsOpen
():
self
.
_Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
():
return
None
return
self
.
_Manager
.
scan_handler
def
Close
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
self
.
initContext
()
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
return
RECODE_FAILURE
self
.
_
Manager
.
Close
(
timeOut
)
self
.
Manager
.
Close
(
timeOut
)
...
...
AppCore/AppReaders/HitBotReader.py
View file @
bd7c532f
...
...
@@ -1037,7 +1037,7 @@ class HitBotReader(Qt.QObject, HitBotReaderInterface):
self
.
manager
.
GetGripperState
()
return
self
.
manager
.
efg_distance
def
moveToSafePosition
(
self
):
def
moveToSafePosition
(
self
,
isSlow
:
bool
=
False
):
if
not
self
.
IsInitialize
():
return
False
from
AppSettings.AppGlobalStatus
import
AppStatus
...
...
@@ -1100,8 +1100,14 @@ class HitBotReader(Qt.QObject, HitBotReaderInterface):
self
.
move
(
yAction
)
if
not
self
.
_Manager
.
isLeft
():
model
=
moveAction
.
copy
()
if
isSlow
:
model
.
speed
=
50
else
:
model
.
speed
=
100
self
.
JMove_LR
(
model
,
True
)
if
isSlow
:
moveAction
.
speed
=
50
else
:
moveAction
.
speed
=
100
self
.
_Manager
.
flush_scara_param
()
self
.
move
(
moveAction
)
...
...
@@ -1126,6 +1132,9 @@ class HitBotReader(Qt.QObject, HitBotReaderInterface):
is_r_move
=
True
if
Float
(
moveAction
.
xPosition
)
!=
float
(
self
.
_Manager
.
xPosition
):
moveAction
.
xPosition
=
Default
.
xPosition
if
isSlow
:
moveAction
.
speed
=
50
else
:
moveAction
.
speed
=
200
is_move
=
True
if
Float
(
moveAction
.
zPosition
)
!=
float
(
self
.
_Manager
.
zPosition
):
...
...
@@ -1133,9 +1142,15 @@ class HitBotReader(Qt.QObject, HitBotReaderInterface):
is_move
=
True
if
not
self
.
_Manager
.
isLeft
():
model
=
moveAction
.
copy
()
if
isSlow
:
model
.
speed
=
50
else
:
model
.
speed
=
100
self
.
JMove_LR
(
model
,
True
)
if
is_move
:
if
isSlow
:
moveAction
.
speed
=
50
else
:
if
is_r_move
:
moveAction
.
speed
=
200
else
:
...
...
@@ -1147,8 +1162,8 @@ class HitBotReader(Qt.QObject, HitBotReaderInterface):
return
True
def
ToSafePosition
(
self
)
->
int
:
return
RECODE_SUCCEED
if
self
.
moveToSafePosition
()
else
RECODE_FAILURE
def
ToSafePosition
(
self
,
isSlow
:
bool
=
False
)
->
int
:
return
RECODE_SUCCEED
if
self
.
moveToSafePosition
(
isSlow
)
else
RECODE_FAILURE
def
isReach
(
self
,
x
:
float
,
y
:
float
,
z
:
float
,
r
:
float
)
->
bool
:
"""
...
...
AppCore/AppReaders/ManipulatorReader.py
View file @
bd7c532f
...
...
@@ -16,7 +16,7 @@ from AppCore.Contexts import ModBusContext, ModBusRegister, AxisCo
from
AppInterfaces.ImplInterfaces
import
ModBusPoolInterface
,
ModBusInterface
,
AxisReaderInterface
#
from
AppInterfaces.ReaderInterfaces
import
ManipulatorReaderInterface
#
from
AppUtils.HardWareUnit
import
HardWareUnit
from
AppCore.DBModels
import
*
class
ManipulatorReader
(
Qt
.
QObject
,
ManipulatorReaderInterface
,
SingletonInterface
):
_IsInitialize
:
bool
Locker
:
Qt
.
QMutex
=
Qt
.
QMutex
()
...
...
@@ -32,9 +32,9 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
IsInitialize
(
self
)
->
bool
:
if
not
self
.
_hasIsInitialize
:
self
.
_IsInitialize
=
False
if
not
self
.
hasAxisX
()
or
not
self
.
axis_x
.
IsInitialize
:
if
not
self
.
hasAxisX
or
not
self
.
axis_x
.
IsInitialize
:
return
False
if
not
self
.
hasAxisY
()
or
not
self
.
axis_y
.
IsInitialize
:
if
not
self
.
hasAxisY
or
not
self
.
axis_y
.
IsInitialize
:
return
False
return
True
...
...
@@ -46,11 +46,11 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
@
property
def
Parameter
(
self
)
->
ModBusContext
:
return
None
if
not
self
.
hasManager
()
else
self
.
_Manager
.
Parameter
return
None
if
not
self
.
hasManager
else
self
.
_Manager
.
Parameter
def
initValue
(
self
):
super
(
ManipulatorReader
,
self
)
.
initValue
()
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
self
.
initManager
()
self
.
initAxisX
()
self
.
initAxisY
()
...
...
@@ -68,15 +68,19 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
initManager
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
from
AppCore.AppReaders.ModBusPool
import
ModBusPool
self
.
_Manager
=
ModBusPool
(
context
=
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
modBusConfig
)
if
not
self
.
_Manager
.
IsOpen
:
self
.
_Manager
.
Open
()
def
deleManager
(
self
):
self
.
_Manager
=
None
def
initAxisX
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasAxisX
()
:
if
not
self
.
hasAxisX
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_AxisX
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
axisXConfig
,
self
.
_Manager
)
self
.
_AxisX
.
IsScanning
=
False
...
...
@@ -84,14 +88,14 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
initAxisY
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasAxisY
()
:
if
not
self
.
hasAxisY
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_AxisY
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
axisYConfig
,
self
.
_Manager
)
self
.
_AxisY
.
IsScanning
=
False
self
.
_AxisY
.
setLevel
(
AxisLevel
.
AxisY
)
def
initScanX
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasScanX
()
:
if
not
self
.
hasScanX
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_ScanX
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
scanXConfig
,
self
.
_Manager
)
self
.
_ScanX
.
IsScanning
=
True
...
...
@@ -99,14 +103,14 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
initScanY
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasScanY
()
:
if
not
self
.
hasScanY
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_ScanY
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
scanYConfig
,
self
.
_Manager
)
self
.
_ScanY
.
IsScanning
=
True
self
.
_ScanY
.
setLevel
(
AxisLevel
.
ScanY
)
def
initSlowX
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasSlowX
()
:
if
not
self
.
hasSlowX
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_SlowX
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
SlowScanXConfig
,
self
.
_Manager
)
self
.
_SlowX
.
IsScanning
=
True
...
...
@@ -115,7 +119,7 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
initSlowY
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasSlowY
()
:
if
not
self
.
hasSlowY
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_SlowY
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
SlowScanYConfig
,
self
.
_Manager
)
self
.
_SlowY
.
IsScanning
=
True
...
...
@@ -123,7 +127,7 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
initDropOilX
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasDropOilX
()
:
if
not
self
.
hasDropOilX
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_DropOilX
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
DropOilXConfig
,
self
.
_Manager
)
self
.
_DropOilX
.
IsScanning
=
False
...
...
@@ -131,59 +135,16 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
initDropOilY
(
self
):
from
AppSettings.AppSetting
import
AppSetting
if
not
self
.
hasDropOilY
()
:
if
not
self
.
hasDropOilY
:
from
AppCore.AppReaders.AxisReader
import
AxisReader
self
.
_DropOilY
=
AxisReader
(
AppSetting
.
GetInstance
()
.
ManipulatorConfig
.
DropOilYConfig
,
self
.
_Manager
)
self
.
_DropOilY
.
IsScanning
=
False
self
.
_DropOilY
.
setLevel
(
AxisLevel
.
DropOilY
)
@
property
def
isAvailable
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasAxisX
()
and
self
.
hasAxisY
()
and
self
.
hasScanX
()
and
self
.
hasScanY
()
and
self
.
hasSlowX
()
and
self
.
hasSlowY
()
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'_Manager'
)
and
isinstance
(
self
.
_Manager
,
ModBusPoolInterface
)
def
hasDeviceX
(
self
)
->
bool
:
return
hasattr
(
self
,
'_DeviceX'
)
and
isinstance
(
self
.
_DeviceX
,
AxisContext
)
def
hasDeviceY
(
self
)
->
bool
:
return
hasattr
(
self
,
'_DeviceY'
)
and
isinstance
(
self
.
_DeviceY
,
AxisContext
)
def
hasAxisX
(
self
)
->
bool
:
return
hasattr
(
self
,
'_AxisX'
)
and
isinstance
(
self
.
_AxisX
,
AxisReaderInterface
)
def
hasAxisY
(
self
)
->
bool
:
return
hasattr
(
self
,
'_AxisY'
)
and
isinstance
(
self
.
_AxisY
,
AxisReaderInterface
)
def
hasScanXParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'_ScanXParameter'
)
and
isinstance
(
self
.
_ScanXParameter
,
AxisContext
)
def
hasScanYParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'_ScanYParameter'
)
and
isinstance
(
self
.
_ScanYParameter
,
AxisContext
)
def
hasScanX
(
self
)
->
bool
:
return
hasattr
(
self
,
'_ScanX'
)
and
isinstance
(
self
.
_ScanX
,
AxisReaderInterface
)
def
hasScanY
(
self
)
->
bool
:
return
hasattr
(
self
,
'_ScanY'
)
and
isinstance
(
self
.
_ScanY
,
AxisReaderInterface
)
def
hasSlowX
(
self
)
->
bool
:
return
hasattr
(
self
,
'_SlowX'
)
and
isinstance
(
self
.
_SlowX
,
AxisReaderInterface
)
def
hasSlowY
(
self
)
->
bool
:
return
hasattr
(
self
,
'_SlowY'
)
and
isinstance
(
self
.
_SlowY
,
AxisReaderInterface
)
def
hasDropOilX
(
self
)
->
bool
:
return
hasattr
(
self
,
'_DropOilX'
)
and
isinstance
(
self
.
_DropOilX
,
AxisReaderInterface
)
def
hasDropOilY
(
self
)
->
bool
:
return
hasattr
(
self
,
'_DropOilY'
)
and
isinstance
(
self
.
_DropOilY
,
AxisReaderInterface
)
def
handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
return
None
if
not
self
.
_Manager
.
IsOpen
:
self
.
_Manager
.
Open
()
...
...
@@ -194,12 +155,12 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
home_xy
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
:
int
=
HardWareUnit
.
axis_home_xy
(
self
.
axis_x
,
self
.
axis_y
)
return
isWrong
def
hasHome
(
self
)
->
(
int
,
int
):
if
self
.
isValid
()
:
if
self
.
isValid
:
return
self
.
_AxisX
.
hasAxisHome
(),
self
.
_AxisY
.
hasAxisHome
()
return
RECODE_FAILURE
,
RECODE_FAILURE
...
...
@@ -228,7 +189,7 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
start_waitmove_scanning
(
self
,
x
:
(
float
,
int
),
y
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_move_parameter_xy
(
self
.
axis_x
,
self
.
axis_y
,
round
(
float
(
x
),
4
),
round
(
float
(
y
),
4
))
return
isWrong
pass
...
...
@@ -237,7 +198,7 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
waitmove_scanning
(
self
,
xPosition
:
(
float
,
int
),
yPosition
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
begin
:
Qt
.
QDateTime
=
Qt
.
QDateTime
.
currentDateTime
()
if
self
.
isValid
()
and
isinstance
(
xPosition
,
(
float
,
int
))
and
isinstance
(
yPosition
,
(
float
,
int
)):
if
self
.
isValid
and
isinstance
(
xPosition
,
(
float
,
int
))
and
isinstance
(
yPosition
,
(
float
,
int
)):
isWrong
=
HardWareUnit
.
axis_waitmove_xy
(
self
.
axis_x
,
self
.
axis_y
,
round
(
float
(
xPosition
),
4
),
round
(
float
(
yPosition
),
4
))
return
isWrong
...
...
@@ -245,60 +206,60 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
move_x
(
self
,
p
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_move
(
self
.
axis_x
,
round
(
float
(
p
),
4
))
return
isWrong
def
waitmove_x
(
self
,
p
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_waitmove
(
self
.
axis_x
,
round
(
float
(
p
),
4
))
return
isWrong
def
move_y
(
self
,
p
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_move
(
self
.
axis_y
,
round
(
float
(
p
),
4
))
return
isWrong
def
waitmove_y
(
self
,
p
:
(
float
,
int
))
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_waitmove
(
self
.
axis_y
,
round
(
float
(
p
),
4
))
return
isWrong
def
home_x
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_home
(
self
.
axis_x
)
return
isWrong
def
waithome_x
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_waithome
(
self
.
axis_x
)
return
isWrong
def
home_y
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_home
(
self
.
axis_y
)
return
isWrong
def
waithome_y
(
self
):
isWrong
:
int
=
RECODE_FAILURE
if
self
.
isValid
()
:
if
self
.
isValid
:
isWrong
=
HardWareUnit
.
axis_waithome
(
self
.
axis_y
)
return
isWrong
def
position_x
(
self
)
->
float
:
if
self
.
isValid
()
:
if
self
.
isValid
:
return
self
.
_AxisX
.
position
()
return
0.0
def
position_y
(
self
)
->
float
:
if
self
.
isValid
()
:
if
self
.
isValid
:
return
self
.
_AxisY
.
position
()
return
0.0
...
...
@@ -306,15 +267,119 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
isWrong
:
int
x
:
float
=
None
y
:
float
=
None
if
self
.
isValid
()
:
if
self
.
isValid
:
xWrong
,
x
=
self
.
_AxisX
.
getPosition
()
yWrong
,
y
=
self
.
_AxisY
.
getPosition
()
return
x
,
y
def
start_scanning_xy
(
self
,
x
,
y
)
->
int
:
return
HardWareUnit
.
axis_waitmove_xy
(
self
.
axis_x
,
self
.
axis_y
,
round
(
float
(
x
),
4
),
round
(
float
(
y
),
4
))
def
reload_velocity
(
self
):
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasAxisX
and
self
.
hasAxisY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
AxisX
)
self
.
axis_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
AxisY
)
self
.
axis_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
reload_orl_speed
(
self
):
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasDropOilX
and
self
.
hasDropOilY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
DropOilX
)
self
.
oil_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
DropOilY
)
self
.
oil_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
reset_scanning
(
self
,
x
:
(
int
,
float
),
y
:
(
int
,
float
))
->
int
:
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasScanX
and
self
.
hasScanY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
ScanX
)
self
.
scan_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
ScanY
)
self
.
scan_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
reset_oiling
(
self
,
x
:
(
int
,
float
),
y
:
(
int
,
float
))
->
int
:
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasDropOilX
and
self
.
hasDropOilY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
DropOilX
)
self
.
oil_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
DropOilY
)
self
.
oil_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
reset_moving
(
self
,
x
:
(
int
,
float
),
y
:
(
int
,
float
))
->
int
:
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasAxisX
and
self
.
hasAxisY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
AxisX
)
self
.
axis_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
AxisY
)
self
.
axis_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
reset_slow_scanning
(
self
,
x
:
(
int
,
float
),
y
:
(
int
,
float
))
->
int
:
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasSlowX
and
self
.
hasSlowY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
SlowScanX
)
self
.
axis_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
SlowScanY
)
self
.
axis_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
start_dropoiling
(
self
):
pass
def
waitmove_scan_xy
(
self
,
x
:
(
float
,
int
),
y
:
(
float
,
int
))
->
int
:
return
HardWareUnit
.
axis_waitmove_xy
(
self
.
scan_x
,
self
.
scan_y
,
round
(
float
(
x
),
4
),
round
(
float
(
y
),
4
))
def
waitmove_slow_scanning_xy
(
self
,
x
:
(
float
,
int
),
y
:
(
float
,
int
))
->
(
int
,
str
):
return
HardWareUnit
.
axis_waitmove_xy
(
self
.
slow_x
,
self
.
slow_y
,
round
(
float
(
x
),
4
),
round
(
float
(
y
),
4
))
def
waitmove_scanning_xy
(
self
,
action
:
'SlideModelInterface'
,
isSafe
:
bool
=
False
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
if
isinstance
(
action
,
SlideModelInterface
):
return
HardWareUnit
.
axis_waitmove_xy
(
self
.
scan_x
,
self
.
scan_y
,
action
.
Position_X
,
action
.
Position_Y
)
return
isWrong
def
setScanMoveEnable
(
self
,
enable
:
bool
):
return
HardWareUnit
.
axis_move_enable_xy
(
self
.
scan_x
,
self
.
scan_y
,
enable
)
def
setMoveEnable
(
self
,
enable
:
bool
):
return
HardWareUnit
.
axis_move_enable_xy
(
self
.
axis_x
,
self
.
axis_y
,
enable
)
def
setSlowEnable
(
self
,
enable
:
bool
):
return
HardWareUnit
.
axis_move_enable_xy
(
self
.
slow_x
,
self
.
slow_y
,
enable
)
def
anointing_xy
(
self
,
x
:
(
float
,
int
),
y
:
(
float
,
int
)):
return
HardWareUnit
.
axis_waitmove_xy
(
self
.
oil_x
,
self
.
oil_y
,
round
(
float
(
x
),
4
),
round
(
float
(
y
),
4
))
def
reload_axis_speed
(
self
):
from
AppCore.AppDBModels.ConfigModels.AxisVelocityModel
import
AxisVelocityModel
if
self
.
hasAxisX
()
and
self
.
hasAxisY
()
:
if
self
.
hasAxisX
and
self
.
hasAxisY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
AxisX
)
self
.
axis_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
AxisY
)
...
...
@@ -329,14 +394,14 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
Deceleration
:
float
if
isSlow
:
if
self
.
hasSlowX
()
and
self
.
hasSlowY
()
:
if
self
.
hasSlowX
and
self
.
hasSlowY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
SlowScanX
)
self
.
slow_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
SlowScanY
)
self
.
slow_y
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
return
RECODE_SUCCEED
else
:
if
self
.
hasScanX
()
and
self
.
hasScanY
()
:
if
self
.
hasScanX
and
self
.
hasScanY
:
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
ScanX
)
self
.
scan_x
.
changedMoveParameter
(
Velocity
,
Acceleration
,
Deceleration
)
Velocity
,
Acceleration
,
Deceleration
=
AxisVelocityModel
.
getConfig
(
AxisLevel
.
ScanY
)
...
...
@@ -344,18 +409,12 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
return
RECODE_SUCCEED
return
RECODE_FAILURE
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
hasAxisX
()
and
self
.
hasAxisY
()
def
IsOpen
(
self
)
->
bool
:
return
self
.
hasManager
()
and
self
.
_Manager
.
IsOpen
def
Open
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
self
.
initManager
()
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
return
RECODE_FAILURE
if
self
.
_Manager
.
IsOpen
:
return
RECODE_SUCCEED
...
...
@@ -363,9 +422,9 @@ class ManipulatorReader(Qt.QObject, ManipulatorReaderInterface, SingletonInterfa
def
Close
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
self
.
initManager
()
if
not
self
.
hasManager
()
:
if
not
self
.
hasManager
:
return
RECODE_FAILURE
if
not
self
.
_Manager
.
IsOpen
:
return
RECODE_SUCCEED
...
...
AppCore/AppReaders/ModBusPool.py
View file @
bd7c532f
...
...
@@ -88,6 +88,7 @@ class ModBusPool(Qt.QObject, ModBusPoolInterface, SingletonInterface):
super
(
ModBusPool
,
self
)
.
deleValue
()
self
.
deleManagers
()
def
IsOpen
(
self
)
->
bool
:
handler
:
ModBusInterface
=
self
.
handle
return
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
IsOpen
()
...
...
AppInterfaces/AppImplInterfaces/DetectionReaderInterface.py
View file @
bd7c532f
...
...
@@ -17,8 +17,8 @@ from AppInterfaces.AppImplInterfaces.ModBusPoolInterface import ModBusPoolInt
from
AppInterfaces.AppReaderInterfaces.AppReaderInterface
import
AppReaderInterface
#
class
DetectionReaderInterface
(
AppReaderInterface
):
_
Manager
:
ModBusPoolInterface
_
Parameter
:
DetectionContext
Manager
:
ModBusPoolInterface
Parameter
:
DetectionContext
...
...
@@ -28,14 +28,14 @@ class DetectionReaderInterface(AppReaderInterface):
handler
:
ModBusInterface
=
self
.
handler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_status
:
bool
=
True
if
isinstance
(
enable
,
(
bool
,
int
))
and
enable
else
False
isWrong
=
self
.
SendBool
(
handler
,
self
.
_
Parameter
.
OilPumpRegister
,
_status
)
isWrong
=
self
.
SendBool
(
handler
,
self
.
Parameter
.
OilPumpRegister
,
_status
)
return
isWrong
def
get_oil_switch_status
(
self
)
->
int
:
isWrong
:
int
=
RECODE_FAILURE
handler
:
ModBusInterface
=
self
.
handler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
isWrong
=
self
.
ReadBool
(
handler
,
self
.
_
Parameter
.
OilPumpRegister
)
isWrong
=
self
.
ReadBool
(
handler
,
self
.
Parameter
.
OilPumpRegister
)
return
isWrong
def
set_oil_speed
(
self
,
speed
:
int
)
->
int
:
...
...
@@ -44,7 +44,7 @@ class DetectionReaderInterface(AppReaderInterface):
handler
:
ModBusInterface
=
self
.
handler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_speed
:
int
=
round
(
speed
,
0
)
if
isinstance
(
speed
,
float
)
else
speed
isWrong
=
self
.
SendUInt16
(
self
.
handler
(),
self
.
_
Parameter
.
OilSpeedRegister
,
_speed
)
isWrong
=
self
.
SendUInt16
(
handler
,
self
.
Parameter
.
OilSpeedRegister
,
_speed
)
return
isWrong
def
get_oil_speed
(
self
)
->
(
int
,
int
):
...
...
@@ -53,7 +53,7 @@ class DetectionReaderInterface(AppReaderInterface):
_speed
:
int
=
0
handler
:
ModBusInterface
=
self
.
readhandler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
speed
:
int
=
self
.
ReadUInt16
(
self
.
handler
(),
self
.
_
Parameter
.
OilSpeedRegister
,
_speed
)
speed
:
int
=
self
.
ReadUInt16
(
handler
,
self
.
Parameter
.
OilSpeedRegister
,
_speed
)
if
isinstance
(
speed
,
int
):
_speed
=
speed
isWrong
=
RECODE_SUCCEED
...
...
@@ -65,7 +65,7 @@ class DetectionReaderInterface(AppReaderInterface):
status
:
bool
=
False
handler
:
ModBusInterface
=
self
.
readhandler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_status
:
bool
=
self
.
ReadBool
(
self
.
handler
(),
self
.
_
Parameter
.
OilStatusRegister
)
_status
:
bool
=
self
.
ReadBool
(
handler
,
self
.
Parameter
.
OilStatusRegister
)
status
=
_status
if
isinstance
(
_status
,
bool
)
else
False
return
status
...
...
@@ -73,7 +73,7 @@ class DetectionReaderInterface(AppReaderInterface):
status
:
bool
=
False
handler
:
ModBusInterface
=
self
.
readhandler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_status
:
bool
=
self
.
ReadBool
(
self
.
handler
(),
self
.
_
Parameter
.
DoorStatusRegister
)
_status
:
bool
=
self
.
ReadBool
(
handler
,
self
.
Parameter
.
DoorStatusRegister
)
status
=
_status
if
isinstance
(
_status
,
bool
)
else
False
return
status
...
...
@@ -81,7 +81,7 @@ class DetectionReaderInterface(AppReaderInterface):
status
:
bool
=
False
handler
:
ModBusInterface
=
self
.
readhandler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_status
:
bool
=
self
.
ReadBool
(
self
.
handler
(),
self
.
_
Parameter
.
DoorStatusRegister
)
_status
:
bool
=
self
.
ReadBool
(
handler
,
self
.
Parameter
.
DoorStatusRegister
)
status
=
_status
if
isinstance
(
_status
,
bool
)
else
False
return
status
...
...
@@ -90,7 +90,7 @@ class DetectionReaderInterface(AppReaderInterface):
status
:
bool
=
False
handler
:
ModBusInterface
=
self
.
readhandler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_status
:
bool
=
self
.
ReadBool
(
self
.
handler
(),
self
.
_
Parameter
.
ChamberStatusRegister
)
_status
:
bool
=
self
.
ReadBool
(
handler
,
self
.
Parameter
.
ChamberStatusRegister
)
status
=
_status
if
isinstance
(
_status
,
bool
)
else
False
return
status
...
...
@@ -108,7 +108,7 @@ class DetectionReaderInterface(AppReaderInterface):
handler
:
ModBusInterface
=
self
.
handler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
_status
:
bool
=
True
if
isinstance
(
enable
,
(
bool
,
int
))
and
enable
else
False
isWrong
=
self
.
SendBool
(
self
.
handler
(),
self
.
_
Parameter
.
BuzzerRegister
,
_status
)
isWrong
=
self
.
SendBool
(
handler
,
self
.
Parameter
.
BuzzerRegister
,
_status
)
return
isWrong
def
get_buzzer_switch
(
self
)
->
int
:
...
...
@@ -116,60 +116,54 @@ class DetectionReaderInterface(AppReaderInterface):
isWrong
:
int
=
RECODE_FAILURE
handler
:
ModBusInterface
=
self
.
readhandler
()
if
isinstance
(
handler
,
ModBusInterface
)
and
handler
.
isAvailable
:
isWrong
=
self
.
ReadBool
(
self
.
handler
(),
self
.
_
Parameter
.
BuzzerRegister
)
isWrong
=
self
.
ReadBool
(
handler
,
self
.
Parameter
.
BuzzerRegister
)
return
isWrong
def
handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
:
return
None
if
not
self
.
_Manager
.
IsOpen
:
self
.
_
Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
:
if
not
self
.
Manager
.
IsOpen
()
:
self
.
Manager
.
Open
()
if
not
self
.
Manager
.
IsOpen
()
:
return
None
return
self
.
_
Manager
.
handle
return
self
.
Manager
.
handle
def
slow_handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
:
return
None
if
not
self
.
_Manager
.
IsOpen
:
self
.
_
Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
:
if
not
self
.
Manager
.
IsOpen
()
:
self
.
Manager
.
Open
()
if
not
self
.
Manager
.
IsOpen
()
:
return
None
return
self
.
_
Manager
.
slow_handler
return
self
.
Manager
.
slow_handler
def
readhandler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
:
return
None
if
not
self
.
_Manager
.
IsOpen
:
self
.
_
Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
:
if
not
self
.
Manager
.
IsOpen
()
:
self
.
Manager
.
Open
()
if
not
self
.
Manager
.
IsOpen
()
:
return
None
return
self
.
_
Manager
.
readhandler
return
self
.
Manager
.
readhandler
def
scan_handler
(
self
)
->
ModBusInterface
:
if
not
self
.
hasManager
:
return
None
if
not
self
.
_Manager
.
IsOpen
:
self
.
_
Manager
.
Open
()
if
not
self
.
_Manager
.
IsOpen
:
if
not
self
.
Manager
.
IsOpen
()
:
self
.
Manager
.
Open
()
if
not
self
.
Manager
.
IsOpen
()
:
return
None
return
self
.
_
Manager
.
scan_handler
return
self
.
Manager
.
scan_handler
@
property
def
parameter
(
self
)
->
DetectionContext
:
return
None
if
not
self
.
hasParameter
else
self
.
_Parameter
@
parameter
.
setter
def
parameter
(
self
,
value
:
DetectionContext
):
self
.
_Parameter
=
value
if
not
self
.
hasParameter
:
self
.
_Parameter
=
None
return
None
if
not
self
.
hasParameter
else
self
.
Parameter
@
property
def
hasParameter
(
self
)
->
bool
:
return
hasattr
(
self
,
'
_Parameter'
)
and
isinstance
(
self
.
_
Parameter
,
DetectionContext
)
return
hasattr
(
self
,
'
Parameter'
)
and
isinstance
(
self
.
Parameter
,
DetectionContext
)
@
property
def
isAvailable
(
self
)
->
bool
:
...
...
@@ -181,21 +175,16 @@ class DetectionReaderInterface(AppReaderInterface):
@
property
def
IsOpen
(
self
)
->
bool
:
return
self
.
hasManager
and
self
.
manager
.
IsOpen
return
self
.
hasManager
and
self
.
Manager
.
IsOpen
()
@
property
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'
_Manager'
)
and
isinstance
(
self
.
_
Manager
,
ModBusPoolInterface
)
return
hasattr
(
self
,
'
Manager'
)
and
isinstance
(
self
.
Manager
,
ModBusPoolInterface
)
@
property
def
manager
(
self
)
->
ModBusPoolInterface
:
return
None
if
not
self
.
hasManager
else
self
.
_
Manager
return
None
if
not
self
.
hasManager
else
self
.
Manager
@
manager
.
setter
def
manager
(
self
,
value
):
self
.
_Manager
=
value
if
not
self
.
hasManager
:
self
.
_Manager
=
None
@
abstractmethod
def
setLevel
(
self
,
level
:
int
):
...
...
AppInterfaces/AppImplInterfaces/ModBusPoolInterface.py
View file @
bd7c532f
...
...
@@ -31,34 +31,25 @@ class ModBusPoolInterface(PoolInterface):
@
property
@
abstractmethod
def
isAvailable
(
self
)
->
bool
:
pass
return
self
.
IsOpen
()
@
property
@
abstractmethod
def
isValid
(
self
)
->
bool
:
pas
s
return
self
.
hasParameter
and
self
.
hasManager
s
@
property
@
abstractmethod
def
IsOpen
(
self
)
->
bool
:
pass
@
property
@
abstractmethod
def
hasManager
(
self
)
->
bool
:
pas
s
return
self
.
hasManager
s
@
property
@
abstractmethod
def
manager
(
self
):
pas
s
return
None
if
not
self
.
hasManagers
else
self
.
Manager
s
@
manager
.
setter
@
abstractmethod
def
manager
(
self
,
value
):
pass
@
abstractmethod
def
Open
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
...
...
@@ -68,13 +59,11 @@ class ModBusPoolInterface(PoolInterface):
def
Close
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
pass
@
abstractmethod
def
initManager
(
self
):
pass
self
.
initManagers
(
None
)
@
abstractmethod
def
deleManager
(
self
):
pass
self
.
deleManagers
()
def
Transmit
(
self
,
data
:
object
,
**
args
)
->
int
:
return
RECODE_FAILURE
...
...
AppInterfaces/AppReaderInterfaces/HitBotReaderInterface.py
View file @
bd7c532f
...
...
@@ -227,7 +227,7 @@ class HitBotReaderInterface(AppReaderInterface):
pass
@
abstractmethod
def
moveToSafePosition
(
self
):
def
moveToSafePosition
(
self
,
isSlow
:
bool
=
False
):
pass
@
abstractmethod
...
...
AppInterfaces/AppReaderInterfaces/ManipulatorReaderInterface.py
View file @
bd7c532f
...
...
@@ -110,77 +110,11 @@ class ManipulatorReaderInterface(AppReaderInterface):
def
oil_y
(
self
)
->
AxisReaderInterface
:
return
None
if
not
self
.
hasDropOilY
else
self
.
_DropOilY
""""""
@
axis_x
.
setter
def
axis_x
(
self
,
value
):
self
.
_AxisX
=
value
if
not
self
.
hasAxisX
:
self
.
_AxisX
=
None
@
axis_y
.
setter
def
axis_y
(
self
,
value
):
self
.
_AxisY
=
value
if
not
self
.
hasAxisY
:
self
.
_AxisY
=
None
@
scan_x
.
setter
def
scan_x
(
self
,
value
):
self
.
_ScanX
=
value
if
not
self
.
hasScanX
:
self
.
_ScanX
=
None
@
scan_y
.
setter
def
scan_y
(
self
,
value
):
self
.
_ScanY
=
value
if
not
self
.
hasScanY
:
self
.
_ScanY
=
None
@
slow_x
.
setter
def
slow_x
(
self
,
value
):
self
.
_SlowX
=
value
if
not
self
.
hasSlowX
:
self
.
_SlowX
=
None
@
slow_y
.
setter
def
slow_y
(
self
,
value
):
self
.
_SlowY
=
value
if
not
self
.
hasSlowY
:
self
.
_SlowY
=
None
@
scan_axis_x
.
setter
def
scan_axis_x
(
self
,
value
):
self
.
_ScanX
=
value
if
not
self
.
hasScanX
:
self
.
_ScanX
=
None
@
scan_axis_y
.
setter
def
scan_axis_y
(
self
,
value
):
self
.
_ScanY
=
value
if
not
self
.
hasScanY
:
self
.
_ScanY
=
None
@
oil_x
.
setter
def
oil_x
(
self
,
value
):
self
.
_DropOilX
=
value
if
not
self
.
hasDropOilX
:
self
.
_DropOilX
=
None
@
oil_y
.
setter
def
oil_y
(
self
,
value
):
self
.
_DropOilY
=
value
if
not
self
.
hasDropOilY
:
self
.
_DropOilY
=
None
@
property
def
parameter
(
self
)
->
ModBusContext
:
return
None
if
not
self
.
manager
else
self
.
manager
.
parameter
@
parameter
.
setter
def
parameter
(
self
,
value
):
if
self
.
hasManager
:
self
.
manager
.
parameter
=
value
@
property
def
hasManager
(
self
)
->
bool
:
return
hasattr
(
self
,
'_Manager'
)
and
isinstance
(
self
.
_Manager
,
ModBusPoolInterface
)
...
...
@@ -226,7 +160,7 @@ class ManipulatorReaderInterface(AppReaderInterface):
def
isValid
(
self
)
->
bool
:
return
self
.
hasManager
and
self
.
manager
.
isValid
@
property
def
IsOpen
(
self
)
->
bool
:
return
self
.
hasManager
and
self
.
manager
.
IsOpen
...
...
@@ -235,11 +169,6 @@ class ManipulatorReaderInterface(AppReaderInterface):
def
manager
(
self
):
return
None
if
not
self
.
hasManager
else
self
.
_Manager
@
manager
.
setter
def
manager
(
self
,
value
):
self
.
_Manager
=
value
if
not
self
.
hasManager
:
self
.
_Manager
=
None
@
abstractmethod
def
Open
(
self
,
timeOut
:
int
=
1000
,
**
args
)
->
int
:
...
...
MicScanSystem.py
View file @
bd7c532f
...
...
@@ -31,17 +31,17 @@ if __name__ == "__main__":
if
AppUtils
.
IsServerAvailable
(
AppConfig
.
WebConfig
.
API
):
from
AppInterfaces.bases
import
*
from
AppUtils.DataBaseDeploy
import
DataBaseDeploy
from
AppSettings.App
StatusSetting
import
AppStatus
from
AppSettings.App
GlobalStatus
import
AppStatus
from
AppSettings.SystemSetting
import
SystemConfig
from
AppSettings.HitBotSetting
import
HitBotSetting
,
HitBotConfig
from
AppBackEnd.AppEventBusBusiness
import
*
from
AppCore.AppDBModels.DBModels
import
*
DataBaseDeploy
.
init
()
AppStatus
.
Update
FromDBModel
()
HitBotConfig
.
UpdateFromDBModel
()
SystemConfig
.
UpdateFromDBModel
()
TrayModel
.
UpdateM
odel
()
AppStatus
.
Update
MaxLocation
()
SystemConfig
.
UpdateMaxLocation
()
HitBotConfig
.
UpdateMaxLocation
()
TrayModel
.
UpdateM
axLocation
()
from
AppCore.AppManagers.HardWareManager
import
HardWareManager
from
AppCore.Readers
import
ModBusPool
from
AppBackEnd.AppScanningFlow
import
AppScanningFlow
...
...
MicScanSystem.spec
0 → 100644
View file @
bd7c532f
# -*- mode: python ; coding: utf-8 -*-
a
=
Analysis
(
[
'MicScanSystem.py'
],
pathex
=
[],
binaries
=
[],
datas
=
[],
hiddenimports
=
[],
hookspath
=
[],
hooksconfig
=
{},
runtime_hooks
=
[],
excludes
=
[],
noarchive
=
False
,
optimize
=
0
,
)
pyz
=
PYZ
(
a
.
pure
)
exe
=
EXE
(
pyz
,
a
.
scripts
,
[],
exclude_binaries
=
True
,
name
=
'MicScanSystem'
,
debug
=
False
,
bootloader_ignore_signals
=
False
,
strip
=
False
,
upx
=
True
,
console
=
True
,
disable_windowed_traceback
=
False
,
argv_emulation
=
False
,
target_arch
=
None
,
codesign_identity
=
None
,
entitlements_file
=
None
,
icon
=
[
'MicScanSystem.ico'
],
)
coll
=
COLLECT
(
exe
,
a
.
binaries
,
a
.
datas
,
strip
=
False
,
upx
=
True
,
upx_exclude
=
[],
name
=
'MicScanSystem'
,
)
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment