Spaces:
Running
Running
final version project
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .env +9 -0
- .gitattributes +28 -0
- .gitignore +4 -0
- Dockerfile +112 -0
- MecheyePackage/ResultWriter.py +493 -0
- MecheyePackage/Scripts/__init__.py +3 -0
- MecheyePackage/Scripts/big_circle1.py +280 -0
- MecheyePackage/Scripts/edges.py +38 -0
- MecheyePackage/Scripts/lengths.py +207 -0
- MecheyePackage/Scripts/slope.py +114 -0
- MecheyePackage/__init__.py +1 -0
- MecheyePackage/config.json +141 -0
- MecheyePackage/mecheye_trigger.py +182 -0
- MecheyePackage/mock_data/horizontal.npy +3 -0
- MecheyePackage/mock_data/horizontal2.npy +3 -0
- MecheyePackage/mock_data/small.npy +3 -0
- MecheyePackage/mock_data/test.py +25 -0
- MecheyePackage/mock_data/vertical.npy +3 -0
- MecheyePackage/point_index.txt +1 -0
- MecheyePackage/points.py +174 -0
- MecheyePackage/profiler_utils.py +199 -0
- MecheyePackage/robot_control.py +62 -0
- MecheyePackage/scan.py +1086 -0
- MecheyePackage/ws_robot_state.py +244 -0
- README.md +4 -4
- __init__.py +92 -0
- config.py +28 -0
- entrypoint.sh +12 -0
- etc/.pwd.lock +0 -0
- etc/adduser.conf +88 -0
- etc/alternatives/README +2 -0
- etc/alternatives/awk +1 -0
- etc/alternatives/editor +1 -0
- etc/alternatives/nawk +1 -0
- etc/alternatives/nc +1 -0
- etc/alternatives/netcat +1 -0
- etc/alternatives/pager +1 -0
- etc/alternatives/pico +1 -0
- etc/alternatives/rmt +1 -0
- etc/alternatives/w +1 -0
- etc/apt/apt.conf.d/01-vendor-ubuntu +1 -0
- etc/apt/apt.conf.d/01autoremove +59 -0
- etc/apt/apt.conf.d/70debconf +3 -0
- etc/apt/apt.conf.d/docker-autoremove-suggests +1 -0
- etc/apt/apt.conf.d/docker-clean +3 -0
- etc/apt/apt.conf.d/docker-gzip-indexes +1 -0
- etc/apt/apt.conf.d/docker-no-languages +1 -0
- etc/apt/sources.list +49 -0
- etc/apt/trusted.gpg.d/ubuntu-keyring-2012-archive.gpg +0 -0
- etc/apt/trusted.gpg.d/ubuntu-keyring-2012-cdimage.gpg +0 -0
.env
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
HOST=0.0.0.0
|
| 2 |
+
PORT=7860
|
| 3 |
+
DEBUG=false
|
| 4 |
+
LOG_FILE=scan_process.log
|
| 5 |
+
SCAN_OUTPUTS=scan_output.json
|
| 6 |
+
IP_ADDRESS=0.0.0.0
|
| 7 |
+
APPWRITE_API_KEY=standard_dba651c5ded8910fe42ceee983b19a94610196b426560d82f45e3ca7160e3b9cbeaa9cf108d6e0b6e85873f8f0c8a8ddfe72f99e233652e5b9e03e15220b05e9dae0fa826fb9f6db31dcc7f6fb8298cb3d369640bc090dcc86b76eb270d9e3212f11e2ffeb53273f1628ae0f376befea4fd2f62e304504a143079c1879ae5b44
|
| 8 |
+
REACT_APP_DEVICE_IP=0.0.0.0
|
| 9 |
+
REACT_APP_PORT=7860
|
.gitattributes
CHANGED
|
@@ -33,3 +33,31 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
lib/libcrypto.so.1.1 filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
lib/libssl.so.1.1 filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
usr/local/bin/FRController filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
usr/local/etc/apache/apr-util/lib/libaprutil-1.a filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
usr/local/etc/apache/apr-util/lib/libaprutil-1.so.0.6.3 filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
usr/local/etc/apache/apr/lib/libapr-1.a filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
usr/local/etc/apache/apr/lib/libapr-1.so.0.7.2 filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
usr/local/etc/apache/httpd/bin/ab filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
usr/local/etc/apache/httpd/bin/httpd filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
usr/local/etc/apache/httpd/manual/images/*.png filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
usr/local/etc/apache/httpd/modules/*.so filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
usr/local/etc/apache/pcre/bin/* filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
usr/local/etc/apache/pcre/lib/* filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
usr/local/etc/apache_webrecovery/httpd/bin/httpd filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
usr/local/etc/apache_webrecovery/httpd/logs/* filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
usr/local/etc/apache_webrecovery/httpd/modules/*.so filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
usr/local/etc/slave_station/** filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
usr/local/etc/web/file_factory/ptp/* filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
usr/local/etc/web/upgrade_server filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
usr/local/etc/webrecovery/*.so filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
usr/local/lib/*.so* filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
usr/local/lib/*.a filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
usr/local/etc/apache/httpd/modules/mod_fr_handler.so-0 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
usr/local/etc/apache_webrecovery/httpd/manual/images/bal-man-b.png filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
usr/local/etc/apache_webrecovery/httpd/manual/images/bal-man-w.png filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
usr/local/etc/apache_webrecovery/httpd/manual/images/bal-man.png filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
usr/local/etc/apache_webrecovery/httpd/manual/images/rewrite_process_uri.png filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
usr/local/etc/apache_webrecovery/httpd/modules/mod_fr_handler.so.bak filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/MecheyePackage/Scan_Outputs/
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
/MecheyePackage/mock_data/*.ply
|
Dockerfile
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ==============================================================================
|
| 2 |
+
# Production Dockerfile for Robotics Control & Data Processing API
|
| 3 |
+
# ==============================================================================
|
| 4 |
+
|
| 5 |
+
FROM ubuntu:22.04
|
| 6 |
+
|
| 7 |
+
# ==============================================================================
|
| 8 |
+
# Environment Configuration
|
| 9 |
+
# ==============================================================================
|
| 10 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 11 |
+
SHELL=/bin/bash \
|
| 12 |
+
PYTHONUNBUFFERED=1 \
|
| 13 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 14 |
+
PIP_NO_CACHE_DIR=1 \
|
| 15 |
+
PIP_DISABLE_PIP_VERSION_CHECK=1 \
|
| 16 |
+
LD_PRELOAD=/lib/x86_64-linux-gnu/liblz4.so.1 \
|
| 17 |
+
PYTHONPATH=/usr/local/lib/python3.10/site-packages
|
| 18 |
+
|
| 19 |
+
# ==============================================================================
|
| 20 |
+
# Run as root
|
| 21 |
+
# ==============================================================================
|
| 22 |
+
USER root
|
| 23 |
+
|
| 24 |
+
# ==============================================================================
|
| 25 |
+
# System Dependencies Installation
|
| 26 |
+
# ==============================================================================
|
| 27 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 28 |
+
python3-dev \
|
| 29 |
+
python3.10 \
|
| 30 |
+
python3.10-venv \
|
| 31 |
+
python3-pip \
|
| 32 |
+
libexpat1 \
|
| 33 |
+
libpcre3 \
|
| 34 |
+
libssl3 \
|
| 35 |
+
liblua5.3-0 \
|
| 36 |
+
libopencv-dev libglfw3-dev libgtk-3-dev \
|
| 37 |
+
gcc g++ cmake make pkg-config \
|
| 38 |
+
libflann-dev libssl-dev libusb-1.0-0 libusb-1.0-0-dev \
|
| 39 |
+
wget curl net-tools ca-certificates unzip rsync linuxptp \
|
| 40 |
+
&& apt-get clean \
|
| 41 |
+
&& rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
|
| 42 |
+
|
| 43 |
+
# ==============================================================================
|
| 44 |
+
# Python Dependencies Installation
|
| 45 |
+
# ==============================================================================
|
| 46 |
+
RUN python3 -m pip install --upgrade pip wheel setuptools
|
| 47 |
+
RUN python3 -m pip install --no-cache-dir \
|
| 48 |
+
Cython numpy opencv-python opencv-contrib-python \
|
| 49 |
+
MechEyeAPI websocket-client apscheduler eventlet appwrite
|
| 50 |
+
|
| 51 |
+
# ==============================================================================
|
| 52 |
+
# Application Setup
|
| 53 |
+
# ==============================================================================
|
| 54 |
+
WORKDIR /app
|
| 55 |
+
|
| 56 |
+
COPY requirements.txt .
|
| 57 |
+
RUN python3 -m pip install --no-cache-dir -r requirements.txt
|
| 58 |
+
COPY . .
|
| 59 |
+
|
| 60 |
+
# ==============================================================================
|
| 61 |
+
# Mech-Eye .deb ve Robot .so dosyalarını runtime'da indir
|
| 62 |
+
# ==============================================================================
|
| 63 |
+
RUN mkdir -p /app/MecheyePackage/mecheyeinstall && \
|
| 64 |
+
curl -L -o /app/MecheyePackage/mecheyeinstall/Mech-Eye_API_2.5.0_amd64.zip \
|
| 65 |
+
"https://cdn-obj.azureedge.net/community/community_downloads/Mech-Eye%20SDK%202.5.0/Mech-Eye_API_2.5.0_amd64.zip?se=4763-03-21T07%3A44%3A16Z&sp=r&sv=2023-11-03&sr=b&sig=KFqefXy%2BD%2B35t4BDQjm8zgbdGVA6/nwAUTqwL4djB5g%3D" && \
|
| 66 |
+
unzip /app/MecheyePackage/mecheyeinstall/Mech-Eye_API_2.5.0_amd64.zip -d /app/MecheyePackage/mecheyeinstall/ && \
|
| 67 |
+
dpkg -i /app/MecheyePackage/mecheyeinstall/*.deb || (apt-get install -f -y) && \
|
| 68 |
+
rm -f /app/MecheyePackage/mecheyeinstall/Mech-Eye_API_2.5.0_amd64.zip
|
| 69 |
+
|
| 70 |
+
RUN mkdir -p /usr/local/lib/python3.10/site-packages/fair_api && \
|
| 71 |
+
curl -L -o /usr/local/lib/python3.10/site-packages/fair_api/Robot.cpython-310-x86_64-linux-gnu.so \
|
| 72 |
+
"https://github.com/FAIR-INNOVATION/fairino-python-sdk/raw/a1451207e918c228b8933bf5d89bc58a05618103/Linux/fairino/Robot.cpython-310-x86_64-linux-gnu.so"
|
| 73 |
+
|
| 74 |
+
RUN rm -f /usr/local/lib/python3.10/site-packages/mecheye/profiler_utils.py
|
| 75 |
+
COPY ./MecheyePackage/profiler_utils.py /usr/local/lib/python3.10/site-packages/mecheye/
|
| 76 |
+
|
| 77 |
+
# ==============================================================================
|
| 78 |
+
# Config ve Apache dosyaları
|
| 79 |
+
# ==============================================================================
|
| 80 |
+
COPY usr/local/ /tmp/usr-local/
|
| 81 |
+
COPY etc /tmp/etc/
|
| 82 |
+
RUN rsync -a --ignore-existing /tmp/usr-local/ /usr/local/ \
|
| 83 |
+
&& rsync -a --ignore-existing /tmp/etc/ /etc/ \
|
| 84 |
+
&& rm -rf /tmp/usr-local /tmp/etc /tmp/www
|
| 85 |
+
|
| 86 |
+
# ==============================================================================
|
| 87 |
+
# Kütüphane dosyaları ve izinler
|
| 88 |
+
# ==============================================================================
|
| 89 |
+
COPY lib/libssl.so.1.1 /usr/lib/x86_64-linux-gnu/
|
| 90 |
+
COPY lib/libcrypto.so.1.1 /usr/lib/x86_64-linux-gnu/
|
| 91 |
+
RUN ldconfig
|
| 92 |
+
|
| 93 |
+
# Sadece yazılabilir dizinlere tam izin ver
|
| 94 |
+
RUN mkdir -p /var/www/empty /tmp \
|
| 95 |
+
&& chmod -R 777 /app /usr/local /tmp /var/www/empty
|
| 96 |
+
|
| 97 |
+
# ==============================================================================
|
| 98 |
+
# PTP araçları ve diğer statik dosyalar
|
| 99 |
+
# ==============================================================================
|
| 100 |
+
COPY static /app/static
|
| 101 |
+
|
| 102 |
+
# ==============================================================================
|
| 103 |
+
# Expose port
|
| 104 |
+
# ==============================================================================
|
| 105 |
+
ENV IP_ADDRESS=0.0.0.0
|
| 106 |
+
ENV PORT=7860
|
| 107 |
+
EXPOSE 7860
|
| 108 |
+
|
| 109 |
+
# ==============================================================================
|
| 110 |
+
# Startup
|
| 111 |
+
# ==============================================================================
|
| 112 |
+
ENTRYPOINT ["/app/entrypoint.sh"]
|
MecheyePackage/ResultWriter.py
ADDED
|
@@ -0,0 +1,493 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from appwrite.client import Client
|
| 2 |
+
from appwrite.services.databases import Databases
|
| 3 |
+
from appwrite.query import Query
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
import json
|
| 6 |
+
import sqlite3
|
| 7 |
+
import logging
|
| 8 |
+
import os
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
from typing import Dict, Any, Set, Tuple, Optional, List
|
| 11 |
+
|
| 12 |
+
class AppwriteDataWriter:
|
| 13 |
+
def __init__(self, log_level: str = "INFO"):
|
| 14 |
+
load_dotenv()
|
| 15 |
+
|
| 16 |
+
# Configure logger with proper formatting and handlers
|
| 17 |
+
self._setup_logging(log_level)
|
| 18 |
+
|
| 19 |
+
# Initialize Appwrite client
|
| 20 |
+
self._init_appwrite_client()
|
| 21 |
+
|
| 22 |
+
# Database configuration
|
| 23 |
+
self.database_id = "Jaguar"
|
| 24 |
+
self.collection_id = "mission_results"
|
| 25 |
+
|
| 26 |
+
self.logger.info("AppwriteDataWriter initialized successfully")
|
| 27 |
+
|
| 28 |
+
# Ensure database attributes exist
|
| 29 |
+
self._ensure_attributes()
|
| 30 |
+
|
| 31 |
+
def _setup_logging(self, log_level: str) -> None:
|
| 32 |
+
"""Setup comprehensive logging configuration"""
|
| 33 |
+
self.logger = logging.getLogger(f"{__name__}.{self.__class__.__name__}")
|
| 34 |
+
|
| 35 |
+
# Prevent duplicate handlers if logger already configured
|
| 36 |
+
if self.logger.handlers:
|
| 37 |
+
return
|
| 38 |
+
|
| 39 |
+
self.logger.setLevel(getattr(logging, log_level.upper(), logging.INFO))
|
| 40 |
+
|
| 41 |
+
# Create console handler with formatting
|
| 42 |
+
console_handler = logging.StreamHandler()
|
| 43 |
+
console_handler.setLevel(logging.DEBUG)
|
| 44 |
+
|
| 45 |
+
# Create file handler for persistent logging
|
| 46 |
+
file_handler = logging.FileHandler('appwrite_operations.log')
|
| 47 |
+
file_handler.setLevel(logging.INFO)
|
| 48 |
+
|
| 49 |
+
# Create detailed formatter
|
| 50 |
+
detailed_formatter = logging.Formatter(
|
| 51 |
+
'%(asctime)s - %(name)s - %(levelname)s - %(funcName)s:%(lineno)d - %(message)s',
|
| 52 |
+
datefmt='%Y-%m-%d %H:%M:%S'
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
# Create simple formatter for console
|
| 56 |
+
simple_formatter = logging.Formatter(
|
| 57 |
+
'%(levelname)s - %(funcName)s - %(message)s'
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
console_handler.setFormatter(simple_formatter)
|
| 61 |
+
file_handler.setFormatter(detailed_formatter)
|
| 62 |
+
|
| 63 |
+
self.logger.addHandler(console_handler)
|
| 64 |
+
self.logger.addHandler(file_handler)
|
| 65 |
+
|
| 66 |
+
def _init_appwrite_client(self) -> None:
|
| 67 |
+
"""Initialize Appwrite client with error handling"""
|
| 68 |
+
try:
|
| 69 |
+
self.client = Client()
|
| 70 |
+
self.client.set_endpoint("http://192.168.1.22:8880/v1")
|
| 71 |
+
self.client.set_project("68643fcb0001cf502505")
|
| 72 |
+
|
| 73 |
+
api_key = os.getenv("APPWRITE_API_KEY")
|
| 74 |
+
if not api_key:
|
| 75 |
+
raise ValueError("APPWRITE_API_KEY environment variable not set")
|
| 76 |
+
|
| 77 |
+
self.client.set_key(api_key)
|
| 78 |
+
self.db = Databases(self.client)
|
| 79 |
+
|
| 80 |
+
self.logger.info("Appwrite client initialized successfully")
|
| 81 |
+
|
| 82 |
+
except Exception as e:
|
| 83 |
+
self.logger.error(f"Failed to initialize Appwrite client: {e}")
|
| 84 |
+
raise
|
| 85 |
+
|
| 86 |
+
def _ensure_attributes(self) -> None:
|
| 87 |
+
"""Ensure all required database attributes exist"""
|
| 88 |
+
attributes = [
|
| 89 |
+
("date", "string", 20),
|
| 90 |
+
("index", "integer", None),
|
| 91 |
+
("group_number", "integer", None),
|
| 92 |
+
("feature", "string", 255),
|
| 93 |
+
("value", "double", None),
|
| 94 |
+
("result_id", "string", 100),
|
| 95 |
+
("mission_id", "string", 100) # Missing required attribute
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
self.logger.info("Ensuring database attributes exist")
|
| 99 |
+
created_count = 0
|
| 100 |
+
existing_count = 0
|
| 101 |
+
|
| 102 |
+
for key, attr_type, size in attributes:
|
| 103 |
+
try:
|
| 104 |
+
if attr_type == "string":
|
| 105 |
+
self.db.create_string_attribute(
|
| 106 |
+
self.database_id,
|
| 107 |
+
self.collection_id,
|
| 108 |
+
key=key,
|
| 109 |
+
size=size,
|
| 110 |
+
required=True if key in ["result_id", "mission_id"] else False
|
| 111 |
+
)
|
| 112 |
+
elif attr_type == "integer":
|
| 113 |
+
self.db.create_integer_attribute(
|
| 114 |
+
self.database_id,
|
| 115 |
+
self.collection_id,
|
| 116 |
+
key=key,
|
| 117 |
+
required=False
|
| 118 |
+
)
|
| 119 |
+
elif attr_type == "double":
|
| 120 |
+
self.db.create_float_attribute(
|
| 121 |
+
self.database_id,
|
| 122 |
+
self.collection_id,
|
| 123 |
+
key=key,
|
| 124 |
+
required=False
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
self.logger.debug(f"Created attribute: {key} ({attr_type})")
|
| 128 |
+
created_count += 1
|
| 129 |
+
|
| 130 |
+
except Exception as e:
|
| 131 |
+
if "already exists" in str(e).lower():
|
| 132 |
+
self.logger.debug(f"Attribute already exists: {key}")
|
| 133 |
+
existing_count += 1
|
| 134 |
+
else:
|
| 135 |
+
self.logger.error(f"Failed to create attribute '{key}': {e}")
|
| 136 |
+
|
| 137 |
+
self.logger.info(f"Attributes status - Created: {created_count}, Existing: {existing_count}")
|
| 138 |
+
|
| 139 |
+
def is_appwrite_available(self) -> bool:
|
| 140 |
+
"""Check if Appwrite service is available"""
|
| 141 |
+
try:
|
| 142 |
+
self.logger.debug("Checking Appwrite availability")
|
| 143 |
+
|
| 144 |
+
response = self.db.list_documents(
|
| 145 |
+
database_id=self.database_id,
|
| 146 |
+
collection_id=self.collection_id,
|
| 147 |
+
queries=[Query.limit(1)]
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
self.logger.debug("Appwrite service is available")
|
| 151 |
+
return True
|
| 152 |
+
|
| 153 |
+
except Exception as e:
|
| 154 |
+
self.logger.warning(f"Appwrite service unavailable: {e}")
|
| 155 |
+
return False
|
| 156 |
+
|
| 157 |
+
def write_to_sqlite(self, result: Dict[str, Any], index: int, group_number: int, mission_id: str = None) -> None:
|
| 158 |
+
"""Write data to local SQLite buffer with optimized logging"""
|
| 159 |
+
self.logger.debug(f"Buffering {len(result)} features - index: {index}, Group: {group_number}")
|
| 160 |
+
|
| 161 |
+
try:
|
| 162 |
+
conn = sqlite3.connect("local_buffer.db")
|
| 163 |
+
cursor = conn.cursor()
|
| 164 |
+
|
| 165 |
+
# Check if result_id and mission_id columns exist, add if not
|
| 166 |
+
cursor.execute("PRAGMA table_info(buffered_results)")
|
| 167 |
+
columns = [column[1] for column in cursor.fetchall()]
|
| 168 |
+
|
| 169 |
+
# Create table with all required columns
|
| 170 |
+
if 'buffered_results' not in [row[0] for row in cursor.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()]:
|
| 171 |
+
cursor.execute("""
|
| 172 |
+
CREATE TABLE buffered_results (
|
| 173 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 174 |
+
date TEXT,
|
| 175 |
+
index INTEGER,
|
| 176 |
+
group_number INTEGER,
|
| 177 |
+
feature TEXT,
|
| 178 |
+
value REAL,
|
| 179 |
+
result_id TEXT,
|
| 180 |
+
mission_id TEXT
|
| 181 |
+
)
|
| 182 |
+
""")
|
| 183 |
+
else:
|
| 184 |
+
# Add missing columns if they don't exist
|
| 185 |
+
if 'result_id' not in columns:
|
| 186 |
+
cursor.execute("ALTER TABLE buffered_results ADD COLUMN result_id TEXT")
|
| 187 |
+
self.logger.info("Added result_id column to buffered_results table")
|
| 188 |
+
if 'mission_id' not in columns:
|
| 189 |
+
cursor.execute("ALTER TABLE buffered_results ADD COLUMN mission_id TEXT")
|
| 190 |
+
self.logger.info("Added mission_id column to buffered_results table")
|
| 191 |
+
|
| 192 |
+
records_written = 0
|
| 193 |
+
failed_conversions = 0
|
| 194 |
+
result_id = f"iter_{index}_group_{group_number}_{datetime.now().strftime('%H%M%S')}"
|
| 195 |
+
mission_id = mission_id or f"mission_{group_number}"
|
| 196 |
+
|
| 197 |
+
for feature, raw_value in result.items():
|
| 198 |
+
try:
|
| 199 |
+
value = float(raw_value) if raw_value is not None else None
|
| 200 |
+
except (ValueError, TypeError):
|
| 201 |
+
if failed_conversions == 0: # Log only first conversion error to reduce noise
|
| 202 |
+
self.logger.warning(f"Value conversion issues detected in batch (index {index})")
|
| 203 |
+
value = None
|
| 204 |
+
failed_conversions += 1
|
| 205 |
+
|
| 206 |
+
cursor.execute("""
|
| 207 |
+
INSERT INTO buffered_results (date, index, group_number, feature, value, result_id, mission_id)
|
| 208 |
+
VALUES (DATE('now'), ?, ?, ?, ?, ?, ?)
|
| 209 |
+
""", (index, group_number, feature, value, result_id, mission_id))
|
| 210 |
+
|
| 211 |
+
records_written += 1
|
| 212 |
+
|
| 213 |
+
conn.commit()
|
| 214 |
+
conn.close()
|
| 215 |
+
|
| 216 |
+
if failed_conversions > 0:
|
| 217 |
+
self.logger.info(f"Buffered {records_written} records with {failed_conversions} conversion issues")
|
| 218 |
+
else:
|
| 219 |
+
self.logger.debug(f"Successfully buffered {records_written} records")
|
| 220 |
+
|
| 221 |
+
except Exception as e:
|
| 222 |
+
self.logger.error(f"Failed to write to SQLite buffer: {e}")
|
| 223 |
+
raise
|
| 224 |
+
|
| 225 |
+
def get_current_group_info(self) -> Tuple[int, Set[int]]:
|
| 226 |
+
"""Get current group information with detailed logging"""
|
| 227 |
+
try:
|
| 228 |
+
self.logger.debug("Retrieving current group information")
|
| 229 |
+
|
| 230 |
+
# Get the highest group number
|
| 231 |
+
max_group_result = self.db.list_documents(
|
| 232 |
+
database_id=self.database_id,
|
| 233 |
+
collection_id=self.collection_id,
|
| 234 |
+
queries=[
|
| 235 |
+
Query.order_desc("group_number"),
|
| 236 |
+
Query.limit(1)
|
| 237 |
+
]
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
current_group = 0
|
| 241 |
+
if max_group_result['documents']:
|
| 242 |
+
current_group = max_group_result['documents'][0]['group_number']
|
| 243 |
+
self.logger.debug(f"Found current group: {current_group}")
|
| 244 |
+
else:
|
| 245 |
+
self.logger.info("No existing groups found, starting with group 0")
|
| 246 |
+
|
| 247 |
+
# Get all indexs for the current group
|
| 248 |
+
group_results = self.db.list_documents(
|
| 249 |
+
database_id=self.database_id,
|
| 250 |
+
collection_id=self.collection_id,
|
| 251 |
+
queries=[
|
| 252 |
+
Query.equal("group_number", current_group),
|
| 253 |
+
Query.limit(1000)
|
| 254 |
+
]
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
group_indices = set()
|
| 258 |
+
for doc in group_results['documents']:
|
| 259 |
+
group_indices.add(doc['index'])
|
| 260 |
+
|
| 261 |
+
self.logger.info(f"Group {current_group} has {len(group_indices)} indexs: {sorted(group_indices)}")
|
| 262 |
+
return current_group, group_indices
|
| 263 |
+
|
| 264 |
+
except Exception as e:
|
| 265 |
+
self.logger.error(f"Failed to retrieve group information: {e}")
|
| 266 |
+
return 0, set()
|
| 267 |
+
|
| 268 |
+
def flush_sqlite_to_appwrite(self) -> None:
|
| 269 |
+
"""Flush buffered SQLite data to Appwrite with optimized error handling"""
|
| 270 |
+
try:
|
| 271 |
+
self.logger.debug("Checking for buffered data to flush")
|
| 272 |
+
|
| 273 |
+
conn = sqlite3.connect("local_buffer.db")
|
| 274 |
+
cursor = conn.cursor()
|
| 275 |
+
cursor.execute("SELECT * FROM buffered_results")
|
| 276 |
+
buffered_data = cursor.fetchall()
|
| 277 |
+
|
| 278 |
+
if not buffered_data:
|
| 279 |
+
self.logger.debug("No buffered data to flush")
|
| 280 |
+
conn.close()
|
| 281 |
+
return
|
| 282 |
+
|
| 283 |
+
self.logger.info(f"Flushing {len(buffered_data)} buffered records to Appwrite")
|
| 284 |
+
|
| 285 |
+
successful_writes = 0
|
| 286 |
+
failed_writes = 0
|
| 287 |
+
error_messages = set() # Use set to avoid duplicate error messages
|
| 288 |
+
|
| 289 |
+
for i, row in enumerate(buffered_data, 1):
|
| 290 |
+
# Handle different row formats for backward compatibility
|
| 291 |
+
if len(row) == 6: # Old format: id, date, index, group_number, feature, value
|
| 292 |
+
_, date, index, group_number, feature, value = row
|
| 293 |
+
result_id = f"iter_{index}_group_{group_number}_{i}"
|
| 294 |
+
mission_id = f"mission_{group_number}"
|
| 295 |
+
elif len(row) == 7: # Format with result_id: id, date, index, group_number, feature, value, result_id
|
| 296 |
+
_, date, index, group_number, feature, value, result_id = row
|
| 297 |
+
mission_id = f"mission_{group_number}"
|
| 298 |
+
else: # New format with both: id, date, index, group_number, feature, value, result_id, mission_id
|
| 299 |
+
_, date, index, group_number, feature, value, result_id, mission_id = row
|
| 300 |
+
|
| 301 |
+
document_data = {
|
| 302 |
+
"date": date,
|
| 303 |
+
"index": index,
|
| 304 |
+
"group_number": group_number,
|
| 305 |
+
"feature": feature,
|
| 306 |
+
"value": value,
|
| 307 |
+
"result_id": result_id,
|
| 308 |
+
"mission_id": mission_id
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
try:
|
| 312 |
+
self.db.create_document(
|
| 313 |
+
database_id=self.database_id,
|
| 314 |
+
collection_id=self.collection_id,
|
| 315 |
+
document_id="unique()",
|
| 316 |
+
data=document_data
|
| 317 |
+
)
|
| 318 |
+
successful_writes += 1
|
| 319 |
+
|
| 320 |
+
except Exception as e:
|
| 321 |
+
error_messages.add(str(e))
|
| 322 |
+
failed_writes += 1
|
| 323 |
+
# Log only every 10th error to reduce log spam
|
| 324 |
+
if failed_writes <= 3 or failed_writes % 10 == 0:
|
| 325 |
+
self.logger.error(f"Flush error (#{failed_writes}): {e}")
|
| 326 |
+
|
| 327 |
+
# Delete successfully written records
|
| 328 |
+
if successful_writes > 0:
|
| 329 |
+
success_ids = [row[0] for row in buffered_data[:successful_writes]]
|
| 330 |
+
placeholders = ",".join(["?" for _ in success_ids])
|
| 331 |
+
cursor.execute(f"DELETE FROM buffered_results WHERE id IN ({placeholders})", success_ids)
|
| 332 |
+
conn.commit()
|
| 333 |
+
|
| 334 |
+
conn.close()
|
| 335 |
+
|
| 336 |
+
if failed_writes > 0:
|
| 337 |
+
self.logger.warning(f"Flush completed with issues - Success: {successful_writes}, Failed: {failed_writes}")
|
| 338 |
+
if len(error_messages) <= 3: # Log unique error messages if few
|
| 339 |
+
for error_msg in error_messages:
|
| 340 |
+
self.logger.error(f"Unique error: {error_msg}")
|
| 341 |
+
else:
|
| 342 |
+
self.logger.info(f"Successfully flushed {successful_writes} records")
|
| 343 |
+
|
| 344 |
+
except Exception as e:
|
| 345 |
+
self.logger.error(f"Critical error during flush operation: {e}")
|
| 346 |
+
|
| 347 |
+
def write_to_db(self, result: Dict[str, Any], index: int, group_number: int, mission_id: str = None) -> None:
|
| 348 |
+
"""Write data to database with intelligent error handling and reduced logging noise"""
|
| 349 |
+
self.logger.info(f"Database write - index: {index}, Group: {group_number}, Features: {len(result)}")
|
| 350 |
+
|
| 351 |
+
try:
|
| 352 |
+
# First, try to flush any existing buffered data
|
| 353 |
+
self.flush_sqlite_to_appwrite()
|
| 354 |
+
|
| 355 |
+
successful_writes = 0
|
| 356 |
+
failed_writes = 0
|
| 357 |
+
result_id = f"iter_{index}_group_{group_number}_{datetime.now().strftime('%H%M%S')}"
|
| 358 |
+
mission_id = mission_id or f"mission_{group_number}"
|
| 359 |
+
error_messages = set() # Track unique errors
|
| 360 |
+
|
| 361 |
+
for feature_name, raw_value in result.items():
|
| 362 |
+
try:
|
| 363 |
+
value_float = float(raw_value) if raw_value is not None else None
|
| 364 |
+
except (ValueError, TypeError):
|
| 365 |
+
if failed_writes == 0: # Log conversion issues once per batch
|
| 366 |
+
self.logger.warning(f"Data type conversion issues in index {index}")
|
| 367 |
+
value_float = None
|
| 368 |
+
|
| 369 |
+
document_data = {
|
| 370 |
+
"date": datetime.now().strftime("%Y-%m-%d"),
|
| 371 |
+
"index": index,
|
| 372 |
+
"group_number": group_number,
|
| 373 |
+
"feature": feature_name,
|
| 374 |
+
"value": value_float,
|
| 375 |
+
"result_id": result_id,
|
| 376 |
+
"mission_id": mission_id
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
try:
|
| 380 |
+
response = self.db.create_document(
|
| 381 |
+
database_id=self.database_id,
|
| 382 |
+
collection_id=self.collection_id,
|
| 383 |
+
document_id="unique()",
|
| 384 |
+
data=document_data
|
| 385 |
+
)
|
| 386 |
+
successful_writes += 1
|
| 387 |
+
|
| 388 |
+
except Exception as e:
|
| 389 |
+
error_messages.add(str(e))
|
| 390 |
+
failed_writes += 1
|
| 391 |
+
# Log only first few errors to avoid spam
|
| 392 |
+
if failed_writes <= 2:
|
| 393 |
+
self.logger.warning(f"Appwrite write failed for '{feature_name}', buffering: {e}")
|
| 394 |
+
|
| 395 |
+
# Batch buffer failed writes
|
| 396 |
+
if failed_writes > 0:
|
| 397 |
+
failed_features = {k: v for i, (k, v) in enumerate(result.items()) if i >= successful_writes}
|
| 398 |
+
self.write_to_sqlite(failed_features, index, group_number, mission_id)
|
| 399 |
+
|
| 400 |
+
if failed_writes > 2: # Summarize if many failures
|
| 401 |
+
self.logger.warning(f"Multiple write failures ({failed_writes} total), all buffered locally")
|
| 402 |
+
|
| 403 |
+
# Summary logging
|
| 404 |
+
if successful_writes > 0 and failed_writes == 0:
|
| 405 |
+
self.logger.info(f"✓ All {successful_writes} features written successfully")
|
| 406 |
+
elif successful_writes > 0:
|
| 407 |
+
self.logger.info(f"Partial success - Written: {successful_writes}, Buffered: {failed_writes}")
|
| 408 |
+
else:
|
| 409 |
+
self.logger.warning(f"All {failed_writes} features buffered due to Appwrite issues")
|
| 410 |
+
|
| 411 |
+
except Exception as e:
|
| 412 |
+
self.logger.error(f"Critical error during database write, buffering all data: {e}")
|
| 413 |
+
self.write_to_sqlite(result, index, group_number, mission_id)
|
| 414 |
+
|
| 415 |
+
def create_document(self, data: Dict[str, Any], document_id: Optional[str] = None) -> Optional[Dict[str, Any]]:
|
| 416 |
+
"""Create a single document with enhanced logging"""
|
| 417 |
+
self.logger.debug(f"Creating document with ID: {document_id or 'auto-generated'}")
|
| 418 |
+
|
| 419 |
+
try:
|
| 420 |
+
result = self.db.create_document(
|
| 421 |
+
database_id=self.database_id,
|
| 422 |
+
collection_id=self.collection_id,
|
| 423 |
+
document_id=document_id or "unique()",
|
| 424 |
+
data=data
|
| 425 |
+
)
|
| 426 |
+
self.logger.info(f"Document created successfully: {result['$id']}")
|
| 427 |
+
return result
|
| 428 |
+
|
| 429 |
+
except Exception as e:
|
| 430 |
+
self.logger.error(f"Document creation failed: {e}")
|
| 431 |
+
return None
|
| 432 |
+
|
| 433 |
+
def update_document(self, document_id: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 434 |
+
"""Update a document with enhanced logging"""
|
| 435 |
+
self.logger.debug(f"Updating document: {document_id}")
|
| 436 |
+
|
| 437 |
+
try:
|
| 438 |
+
result = self.db.update_document(
|
| 439 |
+
database_id=self.database_id,
|
| 440 |
+
collection_id=self.collection_id,
|
| 441 |
+
document_id=document_id,
|
| 442 |
+
data=data
|
| 443 |
+
)
|
| 444 |
+
self.logger.info(f"Document updated successfully: {document_id}")
|
| 445 |
+
return result
|
| 446 |
+
|
| 447 |
+
except Exception as e:
|
| 448 |
+
self.logger.error(f"Document update failed for {document_id}: {e}")
|
| 449 |
+
return None
|
| 450 |
+
|
| 451 |
+
def create_multiple_documents(self, data_list: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
| 452 |
+
"""Create multiple documents with progress logging"""
|
| 453 |
+
self.logger.info(f"Creating {len(data_list)} documents")
|
| 454 |
+
|
| 455 |
+
results = []
|
| 456 |
+
successful = 0
|
| 457 |
+
failed = 0
|
| 458 |
+
|
| 459 |
+
for i, data in enumerate(data_list, 1):
|
| 460 |
+
result = self.create_document(data)
|
| 461 |
+
if result:
|
| 462 |
+
results.append(result)
|
| 463 |
+
successful += 1
|
| 464 |
+
else:
|
| 465 |
+
failed += 1
|
| 466 |
+
|
| 467 |
+
# Log progress for large batches
|
| 468 |
+
if i % 20 == 0 or i == len(data_list):
|
| 469 |
+
self.logger.debug(f"Batch progress: {i}/{len(data_list)} processed")
|
| 470 |
+
|
| 471 |
+
self.logger.info(f"Batch creation completed - Success: {successful}, Failed: {failed}")
|
| 472 |
+
return results
|
| 473 |
+
|
| 474 |
+
def upsert_document(self, document_id: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 475 |
+
"""Upsert (update or create) a document with detailed logging"""
|
| 476 |
+
self.logger.debug(f"Attempting upsert for document: {document_id}")
|
| 477 |
+
|
| 478 |
+
# Try update first
|
| 479 |
+
result = self.update_document(document_id, data)
|
| 480 |
+
if result:
|
| 481 |
+
self.logger.debug(f"Document updated via upsert: {document_id}")
|
| 482 |
+
return result
|
| 483 |
+
|
| 484 |
+
# If update fails, try create
|
| 485 |
+
self.logger.debug(f"Update failed, attempting create for: {document_id}")
|
| 486 |
+
try:
|
| 487 |
+
result = self.create_document(data, document_id)
|
| 488 |
+
if result:
|
| 489 |
+
self.logger.info(f"Document created via upsert: {document_id}")
|
| 490 |
+
return result
|
| 491 |
+
except Exception as e:
|
| 492 |
+
self.logger.error(f"Upsert operation completely failed for {document_id}: {e}")
|
| 493 |
+
return None
|
MecheyePackage/Scripts/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .slope import *
|
| 2 |
+
from .big_circle1 import *
|
| 3 |
+
from .lengths import *
|
MecheyePackage/Scripts/big_circle1.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
import open3d as o3d
|
| 4 |
+
import matplotlib.pyplot as plt
|
| 5 |
+
from scipy.optimize import leastsq
|
| 6 |
+
from scipy.stats import circstd
|
| 7 |
+
from Scripts import edges
|
| 8 |
+
import datetime
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class CircleFitter:
|
| 13 |
+
def __init__(self, point):
|
| 14 |
+
"""
|
| 15 |
+
CircleFitter sınıfı, verilen nokta bulutu (pcd) üzerinde çember fitting işlemleri yapar.
|
| 16 |
+
"""
|
| 17 |
+
self.pcd = point
|
| 18 |
+
self.commonp = None
|
| 19 |
+
self.datum = self.get_datum()
|
| 20 |
+
|
| 21 |
+
def get_B(self, strip_width=20):
|
| 22 |
+
points = self.pcd
|
| 23 |
+
medianx = np.median(points[:, 0])
|
| 24 |
+
mediany = np.median(points[:, 1]) # Y eksenindeki orta nokta
|
| 25 |
+
strip_points = points[(np.abs(points[:, 1] - mediany) < strip_width / 2) &
|
| 26 |
+
(np.abs(points[:, 0] - medianx) < strip_width / 2)]
|
| 27 |
+
if len(strip_points) == 0:
|
| 28 |
+
raise ValueError("Şerit içinde nokta bulunamadı.")
|
| 29 |
+
return np.min(strip_points[:, 2])
|
| 30 |
+
|
| 31 |
+
def get_datum(self):
|
| 32 |
+
strip_width = 1
|
| 33 |
+
x_center = np.median(self.pcd[:, 0])
|
| 34 |
+
strip_points = self.pcd[np.abs(self.pcd[:, 0] - x_center) < strip_width / 2]
|
| 35 |
+
self.datum = np.min(strip_points[:, 1])
|
| 36 |
+
return self.datum
|
| 37 |
+
|
| 38 |
+
def calculate_error_metrics(self, x_points, y_points, xc, yc, r, circle_name="Circle"):
|
| 39 |
+
"""
|
| 40 |
+
Çember fitting için hata metriklerini hesaplar ve txt dosyasına yazar.
|
| 41 |
+
|
| 42 |
+
Args:
|
| 43 |
+
x_points, y_points: Çember fitting yapılan noktalar
|
| 44 |
+
xc, yc, r: Hesaplanan çember merkezi ve yarıçapı
|
| 45 |
+
circle_name: Çember ismi (Circle 1, Circle 2 vb.)
|
| 46 |
+
"""
|
| 47 |
+
n_points = len(x_points)
|
| 48 |
+
|
| 49 |
+
# Her nokta için çember merkezine olan mesafe
|
| 50 |
+
distances_to_center = np.sqrt((x_points - xc)**2 + (y_points - yc)**2)
|
| 51 |
+
|
| 52 |
+
# Geometrik hata: Her noktanın çember üzerinden sapması
|
| 53 |
+
geometric_errors = np.abs(distances_to_center - r)
|
| 54 |
+
|
| 55 |
+
# Hata metrikleri
|
| 56 |
+
mean_error = np.mean(geometric_errors)
|
| 57 |
+
rms_error = np.sqrt(np.mean(geometric_errors**2))
|
| 58 |
+
std_deviation = np.std(geometric_errors)
|
| 59 |
+
max_error = np.max(geometric_errors)
|
| 60 |
+
min_error = np.min(geometric_errors)
|
| 61 |
+
|
| 62 |
+
# Açısal analiz
|
| 63 |
+
angles_rad = np.arctan2(y_points - yc, x_points - xc)
|
| 64 |
+
angles_deg = np.degrees(angles_rad)
|
| 65 |
+
angles_deg[angles_deg < 0] += 360 # 0-360 normalize et
|
| 66 |
+
|
| 67 |
+
# Açısal dağılım metrikleri
|
| 68 |
+
angle_range = np.max(angles_deg) - np.min(angles_deg)
|
| 69 |
+
angle_mean = np.mean(angles_deg)
|
| 70 |
+
|
| 71 |
+
# ✅ Circular (dairesel) standart sapma – doğru yöntem
|
| 72 |
+
angle_std = np.degrees(circstd(angles_rad, high=2*np.pi, low=0))
|
| 73 |
+
|
| 74 |
+
# Açısal sektörlerde dağılım (her 45° bir sektör)
|
| 75 |
+
sectors = np.floor(angles_deg / 45).astype(int)
|
| 76 |
+
sector_counts = np.bincount(sectors, minlength=8)
|
| 77 |
+
|
| 78 |
+
# TXT dosyasına yaz
|
| 79 |
+
timestamp = datetime.datetime.now().strftime("%d_%H%M")
|
| 80 |
+
filename = f"{circle_name}{timestamp}.txt"
|
| 81 |
+
mode = 'a' if os.path.exists(filename) else 'w'
|
| 82 |
+
|
| 83 |
+
with open(filename, mode, encoding='utf-8') as f:
|
| 84 |
+
f.write(f"\n{'='*60}\n")
|
| 85 |
+
f.write(f"ÇEMBER FİTTİNG ANALİZİ - {circle_name}\n")
|
| 86 |
+
f.write(f"Analiz Zamanı: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
|
| 87 |
+
f.write(f"{'='*60}\n\n")
|
| 88 |
+
|
| 89 |
+
f.write(f"GENEL BİLGİLER:\n")
|
| 90 |
+
f.write(f"Nokta Sayısı: {n_points}\n")
|
| 91 |
+
f.write(f"Çember Merkezi: ({xc:.4f}, {yc:.4f})\n")
|
| 92 |
+
f.write(f"Yarıçap: {r:.4f}\n\n")
|
| 93 |
+
|
| 94 |
+
f.write(f"GEOMETRİK HATA METRİKLERİ:\n")
|
| 95 |
+
f.write(f"Ortalama Hata: {mean_error:.6f}\n")
|
| 96 |
+
f.write(f"RMS Hata: {rms_error:.6f}\n")
|
| 97 |
+
f.write(f"Standart Sapma: {std_deviation:.6f}\n")
|
| 98 |
+
f.write(f"Maksimum Hata: {max_error:.6f}\n")
|
| 99 |
+
f.write(f"Minimum Hata: {min_error:.6f}\n\n")
|
| 100 |
+
|
| 101 |
+
f.write(f"AÇISAL DAĞILIM ANALİZİ:\n")
|
| 102 |
+
f.write(f"Açı Aralığı: {angle_range:.2f}°\n")
|
| 103 |
+
f.write(f"Açısal Ortalama: {angle_mean:.2f}°\n")
|
| 104 |
+
f.write(f"Açısal Standart Sapma (circular): {angle_std:.2f}°\n\n")
|
| 105 |
+
|
| 106 |
+
f.write(f"SEKTÖR DAĞILIMI (45° sektörler):\n")
|
| 107 |
+
for i, count in enumerate(sector_counts):
|
| 108 |
+
start_angle = i * 45
|
| 109 |
+
end_angle = (i + 1) * 45
|
| 110 |
+
f.write(f"Sektör {i+1} ({start_angle}°-{end_angle}°): {count} nokta\n")
|
| 111 |
+
|
| 112 |
+
f.write(f"\n{'='*60}\n")
|
| 113 |
+
|
| 114 |
+
print(f"Hata metrikleri {filename} dosyasına kaydedildi.")
|
| 115 |
+
|
| 116 |
+
def get_distance(self, second_crc=True, z_distance_to_datum=102.1, reel_datum=None):
|
| 117 |
+
"""
|
| 118 |
+
Çember merkezinin doğru noktaya öklid mesafesini hesaplar ve görselleştirir.
|
| 119 |
+
Orijinal pcd üzerindeki noktalar ve hesaplanan merkezleri çizer.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
second_crc (bool): İkinci çemberin merkezini kullanıp kullanmayacağınızı belirtir.
|
| 123 |
+
z_distance_to_datum (float): Datum'a göre z mesafesi.
|
| 124 |
+
reel_datum (float, optional): Gerçek datum değeri. Varsayılan olarak self.datum kullanılır.
|
| 125 |
+
|
| 126 |
+
Returns:
|
| 127 |
+
distance (float): Çember merkezinin uzaklığı.
|
| 128 |
+
ok (bool): Mesafenin 3 mm'den küçük olup olmadığını kontrol eder.
|
| 129 |
+
"""
|
| 130 |
+
datum = self.datum
|
| 131 |
+
|
| 132 |
+
# Çember merkezlerini seç
|
| 133 |
+
if second_crc:
|
| 134 |
+
median = np.median(self.pcd[:, 0])
|
| 135 |
+
xc_outer, zc_outer = self.xc_outer_2, self.zc_outer_2
|
| 136 |
+
else:
|
| 137 |
+
median = np.median(self.pcd[:, 0])
|
| 138 |
+
xc_outer, zc_outer = self.xc_outer, self.zc_outer
|
| 139 |
+
|
| 140 |
+
# Median ve z_center hesaplamaları
|
| 141 |
+
z_center = datum + z_distance_to_datum
|
| 142 |
+
|
| 143 |
+
# Öklid mesafesi
|
| 144 |
+
distance = np.hypot(xc_outer - median, zc_outer - z_center)
|
| 145 |
+
|
| 146 |
+
# Mesafenin doğruluk kontrolü
|
| 147 |
+
ok = distance < 3
|
| 148 |
+
|
| 149 |
+
# Görselleştirme
|
| 150 |
+
plt.figure(figsize=(8, 8))
|
| 151 |
+
plt.scatter(self.pcd[:, 0], self.pcd[:, 1], s=1, color='blue', label='Orijinal Noktalar')
|
| 152 |
+
plt.scatter(median, z_center, color='orange', label='z_center (Referans Nokta)')
|
| 153 |
+
plt.scatter(xc_outer, zc_outer, color='red', label='Çember Merkezi')
|
| 154 |
+
plt.title("Çember Merkezi ve Referans Nokta")
|
| 155 |
+
plt.xlabel("X")
|
| 156 |
+
plt.ylabel("Z")
|
| 157 |
+
plt.axis('equal')
|
| 158 |
+
plt.legend()
|
| 159 |
+
|
| 160 |
+
return distance, ok
|
| 161 |
+
|
| 162 |
+
def fit_circle(self, x, y):
|
| 163 |
+
"""
|
| 164 |
+
Verilen X ve Y noktalarına çember fitting yapar.
|
| 165 |
+
"""
|
| 166 |
+
def calc_radius(xc, yc, x, y):
|
| 167 |
+
return np.sqrt((x - xc)**2 + (y - yc)**2)
|
| 168 |
+
|
| 169 |
+
def cost_function(params, x, y):
|
| 170 |
+
xc, yc, r = params
|
| 171 |
+
return calc_radius(xc, yc, x, y) - r
|
| 172 |
+
|
| 173 |
+
def initial_guess(x, y):
|
| 174 |
+
xc = np.mean(x)
|
| 175 |
+
yc = np.mean(y)
|
| 176 |
+
r = np.mean(np.sqrt((x - xc)**2 + (y - yc)**2))
|
| 177 |
+
return [xc, yc, r]
|
| 178 |
+
|
| 179 |
+
guess = initial_guess(x, y)
|
| 180 |
+
result, _ = leastsq(cost_function, guess, args=(x, y))
|
| 181 |
+
return result # xc, yc, r
|
| 182 |
+
|
| 183 |
+
def fit_circles_and_plot(
|
| 184 |
+
self,
|
| 185 |
+
name,
|
| 186 |
+
find_second_circle=True,
|
| 187 |
+
val_x=0.18,
|
| 188 |
+
val_z=0.796,
|
| 189 |
+
delta_z=14,
|
| 190 |
+
clc_metrics=False
|
| 191 |
+
):
|
| 192 |
+
"""
|
| 193 |
+
Nokta bulutunun X-Z düzleminde çember fitting işlemlerini gerçekleştirir ve görselleştirir.
|
| 194 |
+
|
| 195 |
+
Args:
|
| 196 |
+
find_second_circle (bool): İkinci çemberi bulup bulmama seçeneği.
|
| 197 |
+
val_x (float): Dinamik filtreleme için X eksenindeki oran.
|
| 198 |
+
val_z (float): Dinamik filtreleme için Z eksenindeki oran.
|
| 199 |
+
delta_z (float): Filtreleme bölgesinin Z eksenindeki genişliği.
|
| 200 |
+
"""
|
| 201 |
+
try:
|
| 202 |
+
self.find_second_circle = find_second_circle
|
| 203 |
+
|
| 204 |
+
# X-Z düzlemine projekte edilen noktalar
|
| 205 |
+
projected_points_2d = self.pcd[:, [0, 1]]
|
| 206 |
+
|
| 207 |
+
# Kenar koordinatlarını al
|
| 208 |
+
edge_coords = edges.process_and_visualize(projected_points_2d)
|
| 209 |
+
|
| 210 |
+
# Kenarları ölçekle
|
| 211 |
+
scale = edges.get_scale()
|
| 212 |
+
x2d, z2d = edge_coords[:, 1] / scale, edge_coords[:, 0] / scale
|
| 213 |
+
|
| 214 |
+
# Dinamik filtreleme parametreleri
|
| 215 |
+
min_x, max_x = np.min(projected_points_2d[:, 0]), np.max(projected_points_2d[:, 0])
|
| 216 |
+
min_z, max_z = np.min(projected_points_2d[:, 1]), np.max(projected_points_2d[:, 1])
|
| 217 |
+
x_min = min_x + val_x * (max_x - min_x)
|
| 218 |
+
x_max = x_min + 26
|
| 219 |
+
z_min = min_z + val_z * (max_z - min_z)
|
| 220 |
+
z_max = z_min + delta_z
|
| 221 |
+
|
| 222 |
+
# İlk çember fitting
|
| 223 |
+
mask_1 = (x2d > x_min) & (x2d < x_max) & (z2d > z_min) & (z2d < z_max)
|
| 224 |
+
x_2d_1, z_2d_1 = x2d[mask_1], z2d[mask_1]
|
| 225 |
+
xc_outer, zc_outer, r_outer = self.fit_circle(x_2d_1, z_2d_1)
|
| 226 |
+
self.xc_outer, self.zc_outer = xc_outer, zc_outer
|
| 227 |
+
|
| 228 |
+
# İlk çember için hata metriklerini hesapla
|
| 229 |
+
if clc_metrics:
|
| 230 |
+
self.calculate_error_metrics(x_2d_1, z_2d_1, xc_outer, zc_outer, r_outer, name)
|
| 231 |
+
|
| 232 |
+
# Çemberlerin çizimi
|
| 233 |
+
theta = np.linspace(0, 2 * np.pi, 100)
|
| 234 |
+
x_outer_circle = xc_outer + r_outer * np.cos(theta)
|
| 235 |
+
z_outer_circle = zc_outer + r_outer * np.sin(theta)
|
| 236 |
+
|
| 237 |
+
# Görselleştirme
|
| 238 |
+
fig, ax = plt.subplots(figsize=(8, 8))
|
| 239 |
+
ax.scatter(x2d, z2d, s=1, color='blue', label='Noktalar')
|
| 240 |
+
ax.plot(x_outer_circle, z_outer_circle, color='red', label=f'Çember 1 (R = {r_outer:.2f})')
|
| 241 |
+
|
| 242 |
+
# Filtreleme alanını dikdörtgen olarak ekle
|
| 243 |
+
ax.add_patch(
|
| 244 |
+
plt.Rectangle(
|
| 245 |
+
(x_min, z_min),
|
| 246 |
+
x_max - x_min,
|
| 247 |
+
z_max - z_min,
|
| 248 |
+
edgecolor='red', facecolor='none', linewidth=2, label='Filtreleme Bölgesi'
|
| 249 |
+
)
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if find_second_circle:
|
| 253 |
+
# İkinci çember fitting
|
| 254 |
+
zc_min_2 = zc_outer
|
| 255 |
+
zc_max_2 = zc_outer + 5
|
| 256 |
+
mask_2 = (x2d > x_min) & (x2d < x_max) & (z2d > zc_min_2) & (z2d < zc_max_2)
|
| 257 |
+
x_2d_2, z_2d_2 = x2d[mask_2], z2d[mask_2]
|
| 258 |
+
xc_outer_2, zc_outer_2, r_outer_2 = self.fit_circle(x_2d_2, z_2d_2)
|
| 259 |
+
self.xc_outer_2, self.zc_outer_2 = xc_outer_2, zc_outer_2
|
| 260 |
+
|
| 261 |
+
# İkinci çember çizimi
|
| 262 |
+
x_outer_circle_2 = xc_outer_2 + r_outer_2 * np.cos(theta)
|
| 263 |
+
z_outer_circle_2 = zc_outer_2 + r_outer_2 * np.sin(theta)
|
| 264 |
+
ax.plot(x_outer_circle_2, z_outer_circle_2, color='green', label=f'Çember 2 (R = {r_outer_2:.2f})')
|
| 265 |
+
|
| 266 |
+
ax.set_title("X-Z Düzleminde Nokta Bulutu, Çember Fitting ve Filtreleme Alanı")
|
| 267 |
+
ax.set_xlabel("X")
|
| 268 |
+
ax.set_ylabel("Z")
|
| 269 |
+
ax.axis('equal')
|
| 270 |
+
ax.legend()
|
| 271 |
+
|
| 272 |
+
# Return kısmı
|
| 273 |
+
if find_second_circle:
|
| 274 |
+
return (xc_outer, zc_outer, r_outer*2), (xc_outer_2, zc_outer_2, r_outer_2*2), fig, ax
|
| 275 |
+
else:
|
| 276 |
+
return (xc_outer, zc_outer, r_outer*2), fig, ax
|
| 277 |
+
|
| 278 |
+
except Exception as e:
|
| 279 |
+
print(f"Hata big_circle1.py: {e}")
|
| 280 |
+
return None
|
MecheyePackage/Scripts/edges.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import cv2
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from scipy.spatial import cKDTree
|
| 5 |
+
|
| 6 |
+
def get_scale():
|
| 7 |
+
return 13
|
| 8 |
+
|
| 9 |
+
def upscale_points(points, scale, image_size=(300, 300)):
|
| 10 |
+
upscale_size = (image_size[0] * scale, image_size[1] * scale)
|
| 11 |
+
image = np.zeros(upscale_size, dtype=np.uint8)
|
| 12 |
+
for x, y in points:
|
| 13 |
+
x, y = int(x * scale), int(y * scale)
|
| 14 |
+
if 0 <= x < upscale_size[1] and 0 <= y < upscale_size[0]:
|
| 15 |
+
cv2.circle(image, (x, y), radius=0, color=255, thickness=3)
|
| 16 |
+
return image
|
| 17 |
+
|
| 18 |
+
def detect_edges(image):
|
| 19 |
+
blurred = cv2.GaussianBlur(image, (1,1), 0.5)
|
| 20 |
+
edges = cv2.Canny(image, 150, 200)
|
| 21 |
+
return edges
|
| 22 |
+
|
| 23 |
+
def radius_outlier_removal(points, radius=5, min_neighbors=3):
|
| 24 |
+
tree = cKDTree(points)
|
| 25 |
+
counts = tree.query_ball_point(points, r=radius)
|
| 26 |
+
mask = np.array([len(c) >= min_neighbors for c in counts])
|
| 27 |
+
return points[mask]
|
| 28 |
+
|
| 29 |
+
def process_and_visualize(points):
|
| 30 |
+
scale = get_scale()
|
| 31 |
+
high_res_image = upscale_points(points, scale=scale)
|
| 32 |
+
edges = detect_edges(high_res_image)
|
| 33 |
+
|
| 34 |
+
edge_coords = np.column_stack(np.where(edges > 0))
|
| 35 |
+
# Radius-based outlier temizliği
|
| 36 |
+
edge_coords = radius_outlier_removal(edge_coords, radius=5, min_neighbors=3)
|
| 37 |
+
|
| 38 |
+
return edge_coords
|
MecheyePackage/Scripts/lengths.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import open3d as o3d
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from Scripts import edges
|
| 5 |
+
import logging
|
| 6 |
+
from numpy import isfinite
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
def get_40(points):
|
| 11 |
+
x_min = np.min(points[:, 0]) # X eksenindeki minimum değer
|
| 12 |
+
x_max = np.max(points[:, 0]) # X eksenindeki maksimum değer
|
| 13 |
+
x_width = x_max - x_min # Genişlik (fark)
|
| 14 |
+
return x_width
|
| 15 |
+
|
| 16 |
+
def save_filtered_point_cloud(points_array, file_path):
|
| 17 |
+
if points_array.size > 0:
|
| 18 |
+
pcd = o3d.geometry.PointCloud()
|
| 19 |
+
pcd.points = o3d.utility.Vector3dVector(points_array)
|
| 20 |
+
o3d.io.write_point_cloud(file_path, pcd)
|
| 21 |
+
else:
|
| 22 |
+
print(f"'{file_path}' boş bir veri içeriyor, kaydedilmedi.")
|
| 23 |
+
|
| 24 |
+
def arm_horn_lengths(points, b_vertical=None):
|
| 25 |
+
if b_vertical is None:
|
| 26 |
+
raise ValueError("b_vertical değeri None olamaz.")
|
| 27 |
+
|
| 28 |
+
# X merkezine göre bölme
|
| 29 |
+
x_center = (np.max(points[:, 0]) + np.min(points[:, 0])) / 2
|
| 30 |
+
delta_x = 1
|
| 31 |
+
|
| 32 |
+
# Filtrelenmiş noktalar
|
| 33 |
+
filtered_points = points[
|
| 34 |
+
(points[:, 0] > x_center) & (points[:, 0] < x_center+ delta_x)
|
| 35 |
+
]
|
| 36 |
+
|
| 37 |
+
# Boş veri kontrolü
|
| 38 |
+
if filtered_points.size == 0:
|
| 39 |
+
logger.error("Uyarı: Filtrelenmiş nokta bulutu boş!")
|
| 40 |
+
return 0.0
|
| 41 |
+
|
| 42 |
+
# Görselleştirme
|
| 43 |
+
plt.figure(figsize=(12, 8))
|
| 44 |
+
|
| 45 |
+
# Orijinal nokta bulutu (gri, küçük)
|
| 46 |
+
plt.scatter(points[:, 0], points[:, 1], c='lightgray', s=1, alpha=0.5, label='Orijinal')
|
| 47 |
+
|
| 48 |
+
# Filtrelenmiş nokta bulutları (daha büyük ve renkli)
|
| 49 |
+
if filtered_points.size > 0:
|
| 50 |
+
plt.scatter(filtered_points[:, 0], filtered_points[:, 1], c='red', s=3, alpha=0.8, label='Filtre 1')
|
| 51 |
+
|
| 52 |
+
plt.xlabel('X')
|
| 53 |
+
plt.ylabel('Y')
|
| 54 |
+
plt.title('Nokta Bulutu Filtreleme Sonuçları (XY Görünümü)')
|
| 55 |
+
plt.legend()
|
| 56 |
+
plt.grid(True, alpha=0.3)
|
| 57 |
+
plt.axis('equal') # Eşit ölçeklendirme
|
| 58 |
+
|
| 59 |
+
# PNG olarak kaydet
|
| 60 |
+
# plt.savefig('filtered_point_clouds_xy.png', dpi=300, bbox_inches='tight')
|
| 61 |
+
# plt.show()
|
| 62 |
+
|
| 63 |
+
l_248 = b_vertical - np.min(filtered_points[:, 1])
|
| 64 |
+
return l_248
|
| 65 |
+
|
| 66 |
+
def horn_diff(points, y_offset_low=60, y_offset_high=100, z_threshold=8, margin_fraction=0.05):
|
| 67 |
+
"""
|
| 68 |
+
Nokta bulutunun X-Y düzlemindeki sol ve sağ bölgesini analiz eder,
|
| 69 |
+
kenar noktalarını belirler ve kenar çizgisine yakın noktaların ortalamasıyla
|
| 70 |
+
yeni left ve right değerlerini hesaplayıp farklarını görselleştirir.
|
| 71 |
+
|
| 72 |
+
Parameters:
|
| 73 |
+
- points: numpy.ndarray, 3D noktaları içeren dizi (Nx3).
|
| 74 |
+
- y_offset_low: float, Y ekseninde alt limit için offset.
|
| 75 |
+
- y_offset_high: float, Y ekseninde üst limit için offset.
|
| 76 |
+
- z_threshold: float, Z eksenindeki üst noktalardan seçme eşiği.
|
| 77 |
+
- margin_fraction: float, kenar nokta seçiminde, grubun x aralığının kullanılacak oranı.
|
| 78 |
+
|
| 79 |
+
Returns:
|
| 80 |
+
- x_difference: float, yeni left ve right arasındaki fark.
|
| 81 |
+
- difference: float, medyan ile hesaplanan merkez arasındaki fark.
|
| 82 |
+
"""
|
| 83 |
+
import numpy as np
|
| 84 |
+
import matplotlib.pyplot as plt
|
| 85 |
+
|
| 86 |
+
# Medyan x değeri
|
| 87 |
+
median = np.median(points[:, 0])
|
| 88 |
+
y_min = np.min(points[:, 1]) + y_offset_low
|
| 89 |
+
y_max_val = np.min(points[:, 1]) + y_offset_high
|
| 90 |
+
|
| 91 |
+
# Sol ve sağ bölgeleri filtrele
|
| 92 |
+
left = points[(points[:, 0] < median) & (points[:, 1] > y_min) & (points[:, 1] < y_max_val)]
|
| 93 |
+
right = points[(points[:, 0] > median) & (points[:, 1] > y_min) & (points[:, 1] < y_max_val)]
|
| 94 |
+
|
| 95 |
+
# Z ekseni filtresi: Yeterli veri varsa
|
| 96 |
+
left = left[left[:, 2] > (np.max(left[:, 2]) - z_threshold)] if left.size > 0 else np.empty((0, 3))
|
| 97 |
+
right = right[right[:, 2] > (np.max(right[:, 2]) - z_threshold)] if right.size > 0 else np.empty((0, 3))
|
| 98 |
+
|
| 99 |
+
# Kenar işlemleri: edges modülündeki fonksiyonu çağır (varsayım: edges modülü mevcut)
|
| 100 |
+
if left.size > 0:
|
| 101 |
+
processed_left = edges.process_and_visualize(left[:, [0, 1]])
|
| 102 |
+
if isinstance(processed_left, tuple):
|
| 103 |
+
processed_left = processed_left[0]
|
| 104 |
+
processed_left = np.array(processed_left)
|
| 105 |
+
else:
|
| 106 |
+
processed_left = np.empty((0, 2))
|
| 107 |
+
|
| 108 |
+
if right.size > 0:
|
| 109 |
+
processed_right = edges.process_and_visualize(right[:, [0, 1]])
|
| 110 |
+
if isinstance(processed_right, tuple):
|
| 111 |
+
processed_right = processed_right[0]
|
| 112 |
+
processed_right = np.array(processed_right)
|
| 113 |
+
else:
|
| 114 |
+
processed_right = np.empty((0, 2))
|
| 115 |
+
|
| 116 |
+
# Ölçek bilgisini al
|
| 117 |
+
scale = edges.get_scale()
|
| 118 |
+
|
| 119 |
+
# İşlenmiş verileri iki boyutlu diziye dönüştür.
|
| 120 |
+
# Not: sütun sırası; ilk sütun x değeri, ikinci sütun y değeri.
|
| 121 |
+
if processed_left.size > 0:
|
| 122 |
+
left_arr = np.column_stack((processed_left[:, 1] / scale, processed_left[:, 0] / scale))
|
| 123 |
+
else:
|
| 124 |
+
left_arr = np.empty((0, 2))
|
| 125 |
+
if processed_right.size > 0:
|
| 126 |
+
right_arr = np.column_stack((processed_right[:, 1] / scale, processed_right[:, 0] / scale))
|
| 127 |
+
else:
|
| 128 |
+
right_arr = np.empty((0, 2))
|
| 129 |
+
|
| 130 |
+
# left_arr'deki en yüksek x değerine yakın (kenar) noktaların ortalaması
|
| 131 |
+
if left_arr.size > 0:
|
| 132 |
+
max_left_val = np.max(left_arr[:, 0])
|
| 133 |
+
left_range = max_left_val - np.min(left_arr[:, 0])
|
| 134 |
+
left_margin = left_range * margin_fraction
|
| 135 |
+
left_edge_points = left_arr[left_arr[:, 0] >= max_left_val - left_margin]
|
| 136 |
+
new_left = np.mean(left_edge_points[:, 0])
|
| 137 |
+
else:
|
| 138 |
+
new_left = None
|
| 139 |
+
|
| 140 |
+
# right_arr'deki en düşük x değerine yakın (kenar) noktaların ortalaması
|
| 141 |
+
if right_arr.size > 0:
|
| 142 |
+
min_right_val = np.min(right_arr[:, 0])
|
| 143 |
+
right_range = np.max(right_arr[:, 0]) - min_right_val
|
| 144 |
+
right_margin = right_range * margin_fraction
|
| 145 |
+
right_edge_points = right_arr[right_arr[:, 0] <= min_right_val + right_margin]
|
| 146 |
+
new_right = np.mean(right_edge_points[:, 0])
|
| 147 |
+
else:
|
| 148 |
+
new_right = None
|
| 149 |
+
|
| 150 |
+
# Hesaplamalar ve görselleştirme
|
| 151 |
+
if new_left is not None and new_right is not None:
|
| 152 |
+
center = (new_left + new_right) / 2
|
| 153 |
+
difference = np.abs(median - center)
|
| 154 |
+
# print("feature14", difference)
|
| 155 |
+
x_difference = new_right - new_left
|
| 156 |
+
|
| 157 |
+
plt.figure(figsize=(8, 8))
|
| 158 |
+
plt.scatter(points[:, 0], points[:, 1], s=1, color='blue', alpha=0.5, label='Object')
|
| 159 |
+
plt.scatter(left_arr[:, 0], left_arr[:, 1], s=10, color='green', label='Left')
|
| 160 |
+
plt.scatter(right_arr[:, 0], right_arr[:, 1], s=10, color='red', label='Right')
|
| 161 |
+
# Yeni kenar ortalamalarını gösteren çizgiler
|
| 162 |
+
plt.axvline(new_left, color='green', linestyle='--', label='New Left')
|
| 163 |
+
plt.axvline(new_right, color='red', linestyle='--', label='New Right')
|
| 164 |
+
plt.title("X-Y Düzleminde Boynuz Farkları")
|
| 165 |
+
plt.xlabel("X")
|
| 166 |
+
plt.ylabel("Y")
|
| 167 |
+
plt.axis('equal')
|
| 168 |
+
plt.legend()
|
| 169 |
+
plt.grid(True)
|
| 170 |
+
plt.show()
|
| 171 |
+
|
| 172 |
+
return x_difference, difference
|
| 173 |
+
else:
|
| 174 |
+
# print("Sol veya sağ bölge için yeterli nokta yok.")
|
| 175 |
+
return 0, 0
|
| 176 |
+
|
| 177 |
+
def filter_and_visualize_projection_with_ply(points):
|
| 178 |
+
# X ekseninde ortadaki bölgeyi seç
|
| 179 |
+
median = np.median(points[:, 0])
|
| 180 |
+
|
| 181 |
+
# Y ekseninde max Y değeri ve max Y - 40 arası, Z ekseninde max Z - 15 arası filtreleme
|
| 182 |
+
y_max = np.max(points[:, 1])
|
| 183 |
+
z_max = np.max(points[:, 2])
|
| 184 |
+
|
| 185 |
+
# Filtreleme işlemi
|
| 186 |
+
projected_points_2d = points[
|
| 187 |
+
(points[:, 0] < median + 1) &
|
| 188 |
+
(points[:, 0] > median - 1) &
|
| 189 |
+
(points[:, 1] < y_max) &
|
| 190 |
+
(points[:, 1] > y_max - 50) &
|
| 191 |
+
(points[:, 2] > z_max - 13)
|
| 192 |
+
]
|
| 193 |
+
|
| 194 |
+
l_81_5 = np.min(projected_points_2d[:, 1])-np.min(points[:, 1])
|
| 195 |
+
l_7_1 = np.max(projected_points_2d[:, 1])-np.min(projected_points_2d[:, 1])
|
| 196 |
+
# Görselleştirme
|
| 197 |
+
plt.figure(figsize=(8, 8))
|
| 198 |
+
plt.scatter(points[:, 2], points[:, 1], color='red', s=1, label="All Points (Y-Z Proj.)")
|
| 199 |
+
plt.scatter(projected_points_2d[:, 2], projected_points_2d[:, 1], color='blue', s=1, label="Filtered Region (Y-Z Proj.)")
|
| 200 |
+
plt.title("Y-Z Düzleminde Filtrelenmiş Bölge ve Tüm Noktalar")
|
| 201 |
+
plt.xlabel("Y")
|
| 202 |
+
plt.ylabel("Z")
|
| 203 |
+
plt.axis('equal')
|
| 204 |
+
plt.legend()
|
| 205 |
+
plt.grid(True)
|
| 206 |
+
|
| 207 |
+
return l_81_5, l_7_1
|
MecheyePackage/Scripts/slope.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import open3d as o3d
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
from scipy.optimize import leastsq
|
| 5 |
+
from Scripts import edges
|
| 6 |
+
# Çember fitting için yardımcı fonksiyonlar
|
| 7 |
+
def calc_radius(xc, yc, x, y):
|
| 8 |
+
return np.sqrt((x - xc)**2 + (y - yc)**2)
|
| 9 |
+
|
| 10 |
+
def cost_function(params, x, y):
|
| 11 |
+
xc, yc, r = params
|
| 12 |
+
return calc_radius(xc, yc, x, y) - r
|
| 13 |
+
|
| 14 |
+
def initial_guess(x, y):
|
| 15 |
+
xc = np.mean(x)
|
| 16 |
+
yc = np.mean(y)
|
| 17 |
+
r = np.mean(np.sqrt((x - xc)**2 + (y - yc)**2))
|
| 18 |
+
return [xc, yc, r]
|
| 19 |
+
|
| 20 |
+
def slope(pcd, b_vertical=None, y_divisor=0.22, delta_y=0.5, crc_l=58.67):
|
| 21 |
+
"""
|
| 22 |
+
Nokta bulutu üzerinde kaydırma, filtreleme ve çember fitting işlemleri yapar.
|
| 23 |
+
|
| 24 |
+
Parameters:
|
| 25 |
+
- points: numpy.ndarray, giriş nokta bulutu (Nx3 boyutunda).
|
| 26 |
+
- y_divisor: float, Y ekseninde filtreleme için bölme faktörü.
|
| 27 |
+
- delta_y: float, X ekseni için filtreleme genişliği.
|
| 28 |
+
- crc_l: float, Y ekseninde filtreleme uzunluğu.
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
- yc, zc: float, fitted circle'ın merkezi koordinatları.
|
| 32 |
+
- r_outer: float, fitted circle'ın yarıçapı.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
points = np.asarray(pcd).copy()
|
| 36 |
+
l79_73 = 0
|
| 37 |
+
|
| 38 |
+
# Y eksenini ters çevir
|
| 39 |
+
points[:, 1] = -points[:, 1]
|
| 40 |
+
|
| 41 |
+
# Minimum değerleri çıkararak noktaları kaydır
|
| 42 |
+
min_vals = np.min(points, axis=0)
|
| 43 |
+
points -= min_vals
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Min ve max değerleri hesapla
|
| 47 |
+
x_min, x_max = np.min(points[:, 0]), np.max(points[:, 0])
|
| 48 |
+
y_min, y_max = np.min(points[:, 1]), np.max(points[:, 1])
|
| 49 |
+
z_min, z_max = np.min(points[:, 2]), np.max(points[:, 2])
|
| 50 |
+
|
| 51 |
+
# Y ve Z ekseni filtreleme sınırlarını belirle
|
| 52 |
+
y_min_filter = y_min + (y_divisor * (y_max - y_min)) - 2
|
| 53 |
+
y_max_filter = y_min_filter + crc_l
|
| 54 |
+
x_center = (x_min + x_max) / 2
|
| 55 |
+
|
| 56 |
+
z_min_filter = z_min + 0.05 * (z_max - z_min)
|
| 57 |
+
z_max_filter = z_min_filter + 100
|
| 58 |
+
|
| 59 |
+
# Filtreleme işlemi
|
| 60 |
+
filtered_points = points[
|
| 61 |
+
(points[:, 0] > x_center - delta_y) &
|
| 62 |
+
(points[:, 0] < x_center + delta_y) &
|
| 63 |
+
(points[:, 1] > y_min_filter) &
|
| 64 |
+
(points[:, 1] < y_max_filter)
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
# Kenar işleme (2D)
|
| 68 |
+
projected_points_2d = edges.process_and_visualize(filtered_points[:, [1, 2]])
|
| 69 |
+
# projected_points_2d = filtered_points[:, [1, 2]]
|
| 70 |
+
# Çember fitting için 2D koordinatlar
|
| 71 |
+
scale= edges.get_scale()
|
| 72 |
+
y_2d, z_2d = projected_points_2d[:, 1] / scale, projected_points_2d[:, 0] / scale
|
| 73 |
+
|
| 74 |
+
# Başlangıç tahmini ve fitting işlemi
|
| 75 |
+
guess = initial_guess(y_2d, z_2d)
|
| 76 |
+
result, _ = leastsq(cost_function, guess, args=(y_2d, z_2d))
|
| 77 |
+
yc, zc, r_outer = result
|
| 78 |
+
|
| 79 |
+
# print(f"Seçilen çemberin merkezi: ({yc:.2f}, {zc:.2f}), Yarıçap: {r_outer:.2f}")
|
| 80 |
+
|
| 81 |
+
if b_vertical:
|
| 82 |
+
b_vertical= - b_vertical
|
| 83 |
+
b_vertical= b_vertical - min_vals[1]
|
| 84 |
+
l79_73 = yc - b_vertical
|
| 85 |
+
# print("l_79_73",l79_73)
|
| 86 |
+
|
| 87 |
+
# Çember noktalarını oluştur
|
| 88 |
+
theta = np.linspace(0, 2 * np.pi, 100)
|
| 89 |
+
circle_y = yc + r_outer * np.cos(theta)
|
| 90 |
+
circle_z = zc + r_outer * np.sin(theta)
|
| 91 |
+
# Görselleştirme
|
| 92 |
+
plt.figure(figsize=(8, 8))
|
| 93 |
+
plt.scatter(points[:,1], points[:,2], color='green', label='Noktalar')
|
| 94 |
+
plt.scatter(y_2d, z_2d, color='blue', label='Noktalar')
|
| 95 |
+
plt.plot(circle_y, circle_z, color='red', label=f'Fitted Circle (r={r_outer:.2f})')
|
| 96 |
+
plt.title("Y-Z Düzleminde Nokta Bulutu ve Çember Fitting")
|
| 97 |
+
plt.xlabel("Y")
|
| 98 |
+
plt.ylabel("Z")
|
| 99 |
+
plt.axis('equal')
|
| 100 |
+
plt.legend()
|
| 101 |
+
plt.grid(True)
|
| 102 |
+
|
| 103 |
+
# Open3D ile 3D görselleştirme
|
| 104 |
+
# filtered_pcd = o3d.geometry.PointCloud()
|
| 105 |
+
# filtered_pcd.points = o3d.utility.Vector3dVector(filtered_points)
|
| 106 |
+
# filtered_pcd.paint_uniform_color([0, 0, 1]) # Mavi renk
|
| 107 |
+
# filtered_pcd2 = o3d.geometry.PointCloud()
|
| 108 |
+
# filtered_pcd2.points = o3d.utility.Vector3dVector(points)
|
| 109 |
+
# filtered_pcd2.paint_uniform_color([1, 0, 0]) # Kırmızı renk
|
| 110 |
+
|
| 111 |
+
# o3d.io.write_point_cloud("filtered_points.ply", filtered_pcd)
|
| 112 |
+
# o3d.io.write_point_cloud("filtered2.ply", filtered_pcd2)
|
| 113 |
+
|
| 114 |
+
return yc, zc, r_outer, l79_73
|
MecheyePackage/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# This file can be empty
|
MecheyePackage/config.json
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"db_config": {
|
| 3 |
+
"database": "cobot",
|
| 4 |
+
"host": "192.168.1.180",
|
| 5 |
+
"password": "0",
|
| 6 |
+
"user": "0"
|
| 7 |
+
},
|
| 8 |
+
"drop_object": true,
|
| 9 |
+
"file_path": "point_index.txt",
|
| 10 |
+
"ignored_points": [
|
| 11 |
+
14,
|
| 12 |
+
15,
|
| 13 |
+
17,
|
| 14 |
+
25,
|
| 15 |
+
26,
|
| 16 |
+
22,
|
| 17 |
+
35,
|
| 18 |
+
36,
|
| 19 |
+
19,
|
| 20 |
+
39,
|
| 21 |
+
41,
|
| 22 |
+
44,
|
| 23 |
+
45,
|
| 24 |
+
46
|
| 25 |
+
],
|
| 26 |
+
"max_rescan": 0,
|
| 27 |
+
"pick": true,
|
| 28 |
+
"put_back": true,
|
| 29 |
+
"range_": 64,
|
| 30 |
+
"robot_positions": {
|
| 31 |
+
"h_2": [
|
| 32 |
+
-375,
|
| 33 |
+
100,
|
| 34 |
+
545,
|
| 35 |
+
-90,
|
| 36 |
+
-90,
|
| 37 |
+
180
|
| 38 |
+
],
|
| 39 |
+
"notOK": [
|
| 40 |
+
-621,
|
| 41 |
+
325,
|
| 42 |
+
511,
|
| 43 |
+
117,
|
| 44 |
+
-83,
|
| 45 |
+
-148
|
| 46 |
+
],
|
| 47 |
+
"p_91": [
|
| 48 |
+
-335,
|
| 49 |
+
100,
|
| 50 |
+
350,
|
| 51 |
+
-90,
|
| 52 |
+
-0.0005,
|
| 53 |
+
90
|
| 54 |
+
],
|
| 55 |
+
"scrc": [
|
| 56 |
+
-450,
|
| 57 |
+
-130,
|
| 58 |
+
470,
|
| 59 |
+
82.8,
|
| 60 |
+
89.93,
|
| 61 |
+
-7.3
|
| 62 |
+
]
|
| 63 |
+
},
|
| 64 |
+
"same_object": false,
|
| 65 |
+
"same_place_index": -1,
|
| 66 |
+
"save_figures": false,
|
| 67 |
+
"save_point_clouds": false,
|
| 68 |
+
"save_to_db": false,
|
| 69 |
+
"tolerances": {
|
| 70 |
+
"Feature1 (102.1)": [
|
| 71 |
+
102.1,
|
| 72 |
+
2
|
| 73 |
+
],
|
| 74 |
+
"Feature10 (R2-35)": [
|
| 75 |
+
35,
|
| 76 |
+
1.5
|
| 77 |
+
],
|
| 78 |
+
"Feature11 (3mm)": [
|
| 79 |
+
0,
|
| 80 |
+
3
|
| 81 |
+
],
|
| 82 |
+
"Feature12 (88.6)": [
|
| 83 |
+
88.6,
|
| 84 |
+
1.5
|
| 85 |
+
],
|
| 86 |
+
"Feature13 (10.6)": [
|
| 87 |
+
10.6,
|
| 88 |
+
1
|
| 89 |
+
],
|
| 90 |
+
"Feature14 (81.5)": [
|
| 91 |
+
81.5,
|
| 92 |
+
1.5
|
| 93 |
+
],
|
| 94 |
+
"Feature15 (L23.4)": [
|
| 95 |
+
23.4,
|
| 96 |
+
1
|
| 97 |
+
],
|
| 98 |
+
"Feature16 (L17.2)": [
|
| 99 |
+
17.2,
|
| 100 |
+
1
|
| 101 |
+
],
|
| 102 |
+
"Feature17 (2C)": [
|
| 103 |
+
0,
|
| 104 |
+
2
|
| 105 |
+
],
|
| 106 |
+
"Feature2 (25mm/2)": [
|
| 107 |
+
25,
|
| 108 |
+
1
|
| 109 |
+
],
|
| 110 |
+
"Feature3 (23.1)": [
|
| 111 |
+
23.1,
|
| 112 |
+
1
|
| 113 |
+
],
|
| 114 |
+
"Feature4 (25mm/2)": [
|
| 115 |
+
25,
|
| 116 |
+
1
|
| 117 |
+
],
|
| 118 |
+
"Feature5 (L40)": [
|
| 119 |
+
40,
|
| 120 |
+
1
|
| 121 |
+
],
|
| 122 |
+
"Feature6 (L248)": [
|
| 123 |
+
248,
|
| 124 |
+
2
|
| 125 |
+
],
|
| 126 |
+
"Feature7 (L42)": [
|
| 127 |
+
42,
|
| 128 |
+
1.5
|
| 129 |
+
],
|
| 130 |
+
"Feature8 (L79.73)": [
|
| 131 |
+
79.73,
|
| 132 |
+
1.5
|
| 133 |
+
],
|
| 134 |
+
"Feature9 (R1-50)": [
|
| 135 |
+
50,
|
| 136 |
+
1.5
|
| 137 |
+
]
|
| 138 |
+
},
|
| 139 |
+
"use_agg": true,
|
| 140 |
+
"vel_mul": 0.7055
|
| 141 |
+
}
|
MecheyePackage/mecheye_trigger.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
from mecheye.shared import *
|
| 3 |
+
from mecheye.profiler import *
|
| 4 |
+
from mecheye.profiler_utils import *
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
from time import sleep
|
| 8 |
+
from multiprocessing import Lock
|
| 9 |
+
import threading
|
| 10 |
+
import sys
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from fair_api import Robot
|
| 13 |
+
import logging
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
robot = Robot.RPC('127.0.0.1')
|
| 18 |
+
mutex = Lock()
|
| 19 |
+
|
| 20 |
+
class CustomAcquisitionCallback(AcquisitionCallbackBase):
|
| 21 |
+
def __init__(self, width):
|
| 22 |
+
AcquisitionCallbackBase.__init__(self)
|
| 23 |
+
self.profile_batch = ProfileBatch(width)
|
| 24 |
+
|
| 25 |
+
def run(self, batch):
|
| 26 |
+
mutex.acquire()
|
| 27 |
+
self.profile_batch.append(batch)
|
| 28 |
+
mutex.release()
|
| 29 |
+
|
| 30 |
+
class TriggerWithExternalDeviceAndFixedRate(object):
|
| 31 |
+
def __init__(self, vel_mul=1):
|
| 32 |
+
self.profiler = Profiler()
|
| 33 |
+
self.vel_mul = vel_mul
|
| 34 |
+
self.robot = robot
|
| 35 |
+
self.current_di0_value = (0, 0)
|
| 36 |
+
|
| 37 |
+
def set_timed_exposure(self, exposure_time: int):
|
| 38 |
+
show_error(self.user_set.set_enum_value(ExposureMode.name, ExposureMode.Value_Timed))
|
| 39 |
+
show_error(self.user_set.set_int_value(ExposureTime.name, exposure_time))
|
| 40 |
+
|
| 41 |
+
def set_hdr_exposure(self, exposure_time: int, proportion1: float, proportion2: float, first_threshold: float, second_threshold: float):
|
| 42 |
+
show_error(self.user_set.set_enum_value(ExposureMode.name, ExposureMode.Value_HDR))
|
| 43 |
+
show_error(self.user_set.set_int_value(ExposureTime.name, exposure_time))
|
| 44 |
+
show_error(self.user_set.set_float_value(HdrExposureTimeProportion1.name, proportion1))
|
| 45 |
+
show_error(self.user_set.set_float_value(HdrExposureTimeProportion2.name, proportion2))
|
| 46 |
+
show_error(self.user_set.set_float_value(HdrFirstThreshold.name, first_threshold))
|
| 47 |
+
show_error(self.user_set.set_float_value(HdrSecondThreshold.name, second_threshold))
|
| 48 |
+
|
| 49 |
+
def set_parameters(self, scan_line_count):
|
| 50 |
+
self.user_set = self.profiler.current_user_set()
|
| 51 |
+
|
| 52 |
+
show_error(self.user_set.set_enum_value(DataAcquisitionTriggerSource.name, DataAcquisitionTriggerSource.Value_Software))
|
| 53 |
+
show_error(self.user_set.set_enum_value(LineScanTriggerSource.name, LineScanTriggerSource.Value_FixedRate))
|
| 54 |
+
show_error(self.user_set.set_float_value(SoftwareTriggerRate.name, 907))
|
| 55 |
+
show_error(self.user_set.set_int_value(ScanLineCount.name, scan_line_count))
|
| 56 |
+
show_error(self.user_set.set_int_value(CallbackRetrievalTimeout.name, 60000))
|
| 57 |
+
|
| 58 |
+
show_error(self.user_set.set_int_value(LaserPower.name, 100))
|
| 59 |
+
show_error(self.user_set.set_int_value(MinLaserLineWidth.name, 2))
|
| 60 |
+
show_error(self.user_set.set_int_value(MaxLaserLineWidth.name, 30))
|
| 61 |
+
show_error(self.user_set.set_enum_value(AnalogGain.name, AnalogGain.Value_Gain_2))
|
| 62 |
+
show_error(self.user_set.set_int_value(DigitalGain.name, 0))
|
| 63 |
+
show_error(self.user_set.set_int_value(MinGrayscaleValue.name, 50))
|
| 64 |
+
show_error(self.user_set.set_enum_value(SpotSelection.name, SpotSelection.Value_Strongest))
|
| 65 |
+
show_error(self.user_set.set_int_value(MinSpotIntensity.name, 51))
|
| 66 |
+
show_error(self.user_set.set_int_value(MaxSpotIntensity.name, 205))
|
| 67 |
+
show_error(self.user_set.set_enum_value(Filter.name, Filter.Value_Mean))
|
| 68 |
+
show_error(self.user_set.set_enum_value(MeanFilterWindowSize.name, MeanFilterWindowSize.Value_WindowSize_2))
|
| 69 |
+
show_error(self.user_set.set_bool_value(EnableBlindSpotFiltering.name, False))
|
| 70 |
+
show_error(self.user_set.set_bool_value(EnableXAxisAlignment.name, False))
|
| 71 |
+
show_error(self.user_set.set_enum_value(ExposureMode.name, ExposureMode.Value_Timed))
|
| 72 |
+
show_error(self.user_set.set_int_value(ExposureTime.name, 1000))
|
| 73 |
+
|
| 74 |
+
error, self.data_width = self.user_set.get_int_value(DataPointsPerProfile.name)
|
| 75 |
+
show_error(error)
|
| 76 |
+
error, self.capture_line_count = self.user_set.get_int_value(ScanLineCount.name)
|
| 77 |
+
show_error(error)
|
| 78 |
+
error, data_acquisition_trigger_source = self.user_set.get_enum_value(DataAcquisitionTriggerSource.name)
|
| 79 |
+
show_error(error)
|
| 80 |
+
self.is_software_trigger = data_acquisition_trigger_source == DataAcquisitionTriggerSource.Value_Software
|
| 81 |
+
|
| 82 |
+
def acquire_profile_data_using_callback(self, lua_name) -> bool:
|
| 83 |
+
# self.profile_batch.clear()
|
| 84 |
+
# show_error(self.user_set.set_int_value(CallbackRetrievalTimeout.name, 60000))
|
| 85 |
+
# self.callback = CustomAcquisitionCallback(self.data_width).__disown__()
|
| 86 |
+
|
| 87 |
+
# status = self.profiler.register_acquisition_callback(self.callback)
|
| 88 |
+
# if not status.is_ok():
|
| 89 |
+
# show_error(status)
|
| 90 |
+
# return False
|
| 91 |
+
|
| 92 |
+
extra_commands = [{"cmd": 303, "data": {"mode": "1"}}]
|
| 93 |
+
pre_move = None
|
| 94 |
+
post_move = None
|
| 95 |
+
|
| 96 |
+
scrc2 = [-450, 130, 470, 82.80, 89.93, -7.30]
|
| 97 |
+
p90 = [-335, -400, 450, -90, -0.7, 90]
|
| 98 |
+
p91 = [-337, 250, 450, -90, -0.7, 90]
|
| 99 |
+
h1 = [-382, -120, 580, -90, -91, 180]
|
| 100 |
+
h2 = [-382, 200, 580, -90, -91, 180]
|
| 101 |
+
h1_alt = [-432, -120, 510, -90, -91, 180]
|
| 102 |
+
h2_alt = [-432, 200, 510, -90, -91, 180]
|
| 103 |
+
|
| 104 |
+
if lua_name == "small.lua":
|
| 105 |
+
pre_move = ("MoveCart", scrc2)
|
| 106 |
+
post_move = ("MoveCart", h2)
|
| 107 |
+
elif lua_name == "horizontal.lua":
|
| 108 |
+
pre_move = ("MoveCart", h1)
|
| 109 |
+
post_move = ("MoveCart", h1_alt)
|
| 110 |
+
elif lua_name == "horizontal2.lua":
|
| 111 |
+
pre_move = ("MoveCart", h2_alt)
|
| 112 |
+
post_move = ("MoveCart", p91)
|
| 113 |
+
elif lua_name == "vertical.lua":
|
| 114 |
+
pre_move = ("MoveCart", p90)
|
| 115 |
+
|
| 116 |
+
self._move_robot(*pre_move)
|
| 117 |
+
|
| 118 |
+
# status = self.profiler.start_acquisition()
|
| 119 |
+
# if not status.is_ok():
|
| 120 |
+
# show_error(status)
|
| 121 |
+
# return False
|
| 122 |
+
|
| 123 |
+
# if self.is_software_trigger:
|
| 124 |
+
# status = self.profiler.trigger_software()
|
| 125 |
+
# if not status.is_ok():
|
| 126 |
+
# show_error(status)
|
| 127 |
+
# return False
|
| 128 |
+
|
| 129 |
+
# self._wait_for_profile_data()
|
| 130 |
+
|
| 131 |
+
# status = self.profiler.stop_acquisition()
|
| 132 |
+
# if not status.is_ok():
|
| 133 |
+
# show_error(status)
|
| 134 |
+
|
| 135 |
+
if post_move:
|
| 136 |
+
self._move_robot(*post_move)
|
| 137 |
+
time.sleep(1)
|
| 138 |
+
|
| 139 |
+
# self.profile_batch.append(self.callback.profile_batch)
|
| 140 |
+
return True
|
| 141 |
+
|
| 142 |
+
def _move_robot(self, move_type: str, coordinates: list, vel_cart=54, vel_l=54):
|
| 143 |
+
if move_type == "MoveCart":
|
| 144 |
+
self.robot.MoveCart(coordinates, 0, 0, vel=self.vel_mul * vel_cart)
|
| 145 |
+
elif move_type == "MoveCart":
|
| 146 |
+
self.robot.MoveCart(coordinates, 0, 0, vel=self.vel_mul * vel_l)
|
| 147 |
+
elif move_type == "MoveJ":
|
| 148 |
+
self.robot.MoveJ(coordinates, 0, 0, vel=self.vel_mul * 100)
|
| 149 |
+
else:
|
| 150 |
+
raise ValueError(f"Unsupported move type: {move_type}")
|
| 151 |
+
|
| 152 |
+
def save_depth_and_intensity(self, depth_file_name, intensity_file_name):
|
| 153 |
+
cv2.imwrite(depth_file_name, self.profile_batch.get_depth_map().data())
|
| 154 |
+
cv2.imwrite(intensity_file_name, self.profile_batch.get_intensity_image().data())
|
| 155 |
+
|
| 156 |
+
def main(self, lua_name, scan_line_count=4000):
|
| 157 |
+
|
| 158 |
+
mock_data = True
|
| 159 |
+
|
| 160 |
+
if not mock_data:
|
| 161 |
+
if not find_and_connect(self.profiler):
|
| 162 |
+
return -1
|
| 163 |
+
|
| 164 |
+
self.set_parameters(scan_line_count)
|
| 165 |
+
|
| 166 |
+
self.profile_batch = ProfileBatch(self.data_width)
|
| 167 |
+
|
| 168 |
+
if not self.acquire_profile_data_using_callback(lua_name):
|
| 169 |
+
return -1
|
| 170 |
+
|
| 171 |
+
if self.profile_batch.check_flag(ProfileBatch.BatchFlag_Incomplete):
|
| 172 |
+
print("Part of the batch's data is lost, the number of valid profiles is:",
|
| 173 |
+
self.profile_batch.valid_height())
|
| 174 |
+
|
| 175 |
+
points = save_point_cloud(profile_batch=self.profile_batch, user_set=self.user_set, save_csv=False, save_ply=False, save_np=True)
|
| 176 |
+
|
| 177 |
+
self.profiler.disconnect()
|
| 178 |
+
else:
|
| 179 |
+
if not self.acquire_profile_data_using_callback(lua_name):
|
| 180 |
+
return -1
|
| 181 |
+
points = np.load(f"MecheyePackage/mock_data/{lua_name.split('.')[0]}.npy")
|
| 182 |
+
return points
|
MecheyePackage/mock_data/horizontal.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b2c17ab2548e9ddf318be10dd834af37ae8b0dc783ede4f36d9d8cfda7631e7
|
| 3 |
+
size 670856
|
MecheyePackage/mock_data/horizontal2.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2316f0ef2ea1a144abcc70f898d04cea78dd9e9628f0fe21f1474e4e3ac0cbd6
|
| 3 |
+
size 644720
|
MecheyePackage/mock_data/small.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:974501c714f81b1785b19fb529f55fdc99c45a88b7a3a78814d015ff345f9767
|
| 3 |
+
size 4030616
|
MecheyePackage/mock_data/test.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import open3d as o3d
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
# Read point clouds
|
| 5 |
+
pcd_vertical = o3d.io.read_point_cloud("/home/eypan/Projects/Jaguar_Project/MecheyePackage/mock_data/vertical.ply")
|
| 6 |
+
pcd_horizontal = o3d.io.read_point_cloud("/home/eypan/Projects/Jaguar_Project/MecheyePackage/mock_data/horizontal.ply")
|
| 7 |
+
pcd_horizontal2 = o3d.io.read_point_cloud("/home/eypan/Projects/Jaguar_Project/MecheyePackage/mock_data/horizontal2.ply")
|
| 8 |
+
pcd_small = o3d.io.read_point_cloud("/home/eypan/Projects/Jaguar_Project/MecheyePackage/mock_data/small.ply")
|
| 9 |
+
|
| 10 |
+
# Optionally voxel downsample
|
| 11 |
+
pcd_horizontal = pcd_horizontal.voxel_down_sample(voxel_size=0.3)
|
| 12 |
+
pcd_horizontal2 = pcd_horizontal2.voxel_down_sample(voxel_size=0.3)
|
| 13 |
+
pcd_vertical = pcd_vertical.voxel_down_sample(voxel_size=0.2)
|
| 14 |
+
|
| 15 |
+
# Save numpy arrays
|
| 16 |
+
np.save('MecheyePackage/mock_data/vertical.npy', np.asarray(pcd_vertical.points))
|
| 17 |
+
np.save('MecheyePackage/mock_data/horizontal.npy', np.asarray(pcd_horizontal.points))
|
| 18 |
+
np.save('MecheyePackage/mock_data/horizontal2.npy', np.asarray(pcd_horizontal2.points))
|
| 19 |
+
np.save('MecheyePackage/mock_data/small.npy', np.asarray(pcd_small.points))
|
| 20 |
+
|
| 21 |
+
# Save PLY files
|
| 22 |
+
o3d.io.write_point_cloud("MecheyePackage/mock_data/vertical_downsample.ply", pcd_vertical)
|
| 23 |
+
o3d.io.write_point_cloud("MecheyePackage/mock_data/horizontal_downsample.ply", pcd_horizontal)
|
| 24 |
+
o3d.io.write_point_cloud("MecheyePackage/mock_data/horizontal2_downsample.ply", pcd_horizontal2)
|
| 25 |
+
o3d.io.write_point_cloud("MecheyePackage/mock_data/small_downsample.ply", pcd_small)
|
MecheyePackage/mock_data/vertical.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ca262eb677f0bfc6473e471308b2fe412cc273922b23a3100af36255eb6ff624
|
| 3 |
+
size 7458008
|
MecheyePackage/point_index.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
1
|
MecheyePackage/points.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
left_of_robot_points = [
|
| 2 |
+
# Block 1
|
| 3 |
+
{"p_up": [-538, -391.1, 224.0, 180.0, 0.0, 90],
|
| 4 |
+
"p": [-538.0, -391.1, 138.0, 180.0, 0.0, 90]},
|
| 5 |
+
{"p_up": [-480.0 + 2.2, -382.1, 224.0, 180.0, 0.0, -90],
|
| 6 |
+
"p": [-480.0 + 2.2, -382.1, 138.0, 180.0, 0.0, -90]},
|
| 7 |
+
# Block 2
|
| 8 |
+
{"p_up": [-415.0 - 1, -395.775 + 4, 224.0, 180.0, 0.0, 90],
|
| 9 |
+
"p": [-415.0 - 1, -395.775 + 4, 138.0, 180.0, 0.0, 90]},
|
| 10 |
+
{"p_up": [-360.0 - 1, -389 + 4, 224.0, 180.0, 0.0, -90],
|
| 11 |
+
"p": [-360.0 - 1, -389 + 4, 138.0, 180.0, 0.0, -90]},
|
| 12 |
+
# Block 3
|
| 13 |
+
{"p_up": [-295.0, -395.775, 224.0, 180.0, 0.0, 90],
|
| 14 |
+
"p": [-295.0, -395.775, 138.0, 180.0, 0.0, 90]},
|
| 15 |
+
{"p_up": [-242.023, -389.162, 224.0, 180.0, 0.0, -90],
|
| 16 |
+
"p": [-242.023, -389.162, 138.0, 180.0, 0.0, -90]},
|
| 17 |
+
# Block 4
|
| 18 |
+
{"p_up": [-178.397, -399.168, 224.0, 180.0, 0.0, 90],
|
| 19 |
+
"p": [-178.397, -399.168, 138.0, 180.0, 0.0, 90]},
|
| 20 |
+
{"p_up": [-120.0, -391.157, 224.0, 180.0, 0.0, -90],
|
| 21 |
+
"p": [-120.0, -391.157, 138.0, 180.0, 0.0, -90]},
|
| 22 |
+
# Block 5
|
| 23 |
+
{"p_up": [ -60.026, -401.787, 224.0, 180.0, 0.0, 90],
|
| 24 |
+
"p": [-60.026, -401.787, 138.0, 180.0, 0.0, 90]},
|
| 25 |
+
{"p_up": [ -2.0, -393.001, 224.0, 180.0, 0.0, -90],
|
| 26 |
+
"p": [ -2.0, -393.001, 138.0, 180.0, 0.0, -90]},
|
| 27 |
+
# Block 6
|
| 28 |
+
{"p_up": [ 60.979, -403.79, 224.0, 180.0, 0.0, 90],
|
| 29 |
+
"p": [ 60.979, -403.79, 138.0, 180.0, 0.0, 90]},
|
| 30 |
+
{"p_up": [117, -395.775, 224.0, 180.0, 0.0, -90],
|
| 31 |
+
"p": [117, -395.775, 138.0, 180.0, 0.0, -90]},
|
| 32 |
+
# Block 7
|
| 33 |
+
{"p_up": [182, -406.019, 224.0, 180.0, 0.0, 90],
|
| 34 |
+
"p": [182, -406.019, 138.0, 180.0, 0.0, 90]},
|
| 35 |
+
{"p_up": [238.98, -398.296, 224.0, 180.0, 0.0, -90],
|
| 36 |
+
"p": [238.98, -398.296, 138.0, 180.0, 0.0, -90]},
|
| 37 |
+
# Block 8
|
| 38 |
+
{"p_up": [302, -410.126, 224.0, 180.0, 0.0, 90],
|
| 39 |
+
"p": [302, -410.126, 138.0, 180.0, 0.0, 90]},
|
| 40 |
+
{"p_up": [358.981, -400, 224.0, 180.0, 0.0, -90],
|
| 41 |
+
"p": [358.981, -400, 138.0, 180.0, 0.0, -90]},
|
| 42 |
+
# Block 9
|
| 43 |
+
{"p_up": [422, -412.034, 224.0, 180.0, 0.0, 90],
|
| 44 |
+
"p": [422, -412.034, 138.0, 180.0, 0.0, 90]},
|
| 45 |
+
{"p_up": [479, -402.048, 224.0, 180.0, 0.0, -90],
|
| 46 |
+
"p": [479, -402.048, 138.0, 180.0, 0.0, -90]},
|
| 47 |
+
# Block 10
|
| 48 |
+
{"p_up": [540.981, -412 , 224.0, 180.0, 0.0, 90],
|
| 49 |
+
"p": [540.981, -412, 138.0, 180.0, 0.0, 90]},
|
| 50 |
+
{"p_up": [599.984, -404, 224.0, 180.0, 0.0, -90],
|
| 51 |
+
"p": [599.984, -404, 138.0, 180.0, 0.0, -90]}
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
left_small = [
|
| 55 |
+
# Block 1
|
| 56 |
+
{"p_up": [-355.0 - 6, -735.775, 224.0, 180.0, 0.0, 90],
|
| 57 |
+
"p": [-355.0 - 6, -735.775, 138.0, 180.0, 0.0, 90]},
|
| 58 |
+
{"p_up": [-300.5 - 6, -735.775, 224.0, 180.0, 0.0, -90],
|
| 59 |
+
"p": [-300.5 - 6, -735.775, 138.0, 180.0, 0.0, -90]},
|
| 60 |
+
# Block 2
|
| 61 |
+
{"p_up": [-246, -740, 224.0, 180.0, 0.0, 90],
|
| 62 |
+
"p": [-246, -740, 138.0, 180.0, 0.0, 90]},
|
| 63 |
+
{"p_up": [-187, -736.809, 224.0, 180.0, 0.0, -90],
|
| 64 |
+
"p": [-187, -735.775, 138.0, 180.0, 0.0, -90]},
|
| 65 |
+
# Block 3
|
| 66 |
+
{"p_up": [-127, -744.775, 224.0, 180.0, 0.0, 90],
|
| 67 |
+
"p": [-127, -744, 138.0, 180.0, 0.0, 90]},
|
| 68 |
+
{"p_up": [ -66, -738.62, 224.0, 180.0, 0.0, -90],
|
| 69 |
+
"p": [ -66, -738.62, 138.0, 180.0, 0.0, -90]},
|
| 70 |
+
# Block 4
|
| 71 |
+
{"p_up": [-5, -746.833, 224.0, 180.0, 0.0, 90],
|
| 72 |
+
"p": [ -5, -746.833, 138.0, 180.0, 0.0, 90]},
|
| 73 |
+
{"p_up": [ 53, -740.831, 224.0, 180.0, 0.0, -90],
|
| 74 |
+
"p": [ 53, -740.831, 138.0, 180.0, 0.0, -90]},
|
| 75 |
+
# Block 5
|
| 76 |
+
{"p_up": [114.094, -747.833, 224.0, 180.0, 0.0, 90],
|
| 77 |
+
"p": [114.094, -747.833, 138.0, 180.0, 0.0, 90]},
|
| 78 |
+
{"p_up": [173, -744.829, 224.0, 180.0, 0.0, -90],
|
| 79 |
+
"p": [173, -744.829, 138.0, 180.0, 0.0, -90]},
|
| 80 |
+
# Block 6
|
| 81 |
+
{"p_up": [233.011, -750, 224.0, 180.0, 0.0, 90],
|
| 82 |
+
"p": [233.011, -750, 138.0, 180.0, 0.0, 90]},
|
| 83 |
+
{"p_up": [291.003, -748.828, 224.0, 180.0, 0.0, -90],
|
| 84 |
+
"p": [291.003, -748.828, 138.0, 180.0, 0.0, -90]}
|
| 85 |
+
]
|
| 86 |
+
|
| 87 |
+
right_of_robot_points = [
|
| 88 |
+
{"p_up": [-542.13, 399.0, 224.0, 180, 0, 90],
|
| 89 |
+
"p": [-533.13, 399.0, 138, 180, 0, 90]},
|
| 90 |
+
{"p_up": [-466.269, 399.949, 224.0, 180, 0, -90],
|
| 91 |
+
"p": [-466.269, 399.0, 138, 180, 0, -90]},
|
| 92 |
+
{"p_up": [-403.838, 399.0, 224.0, 180, 0, 90],
|
| 93 |
+
"p": [-403.838, 399.0, 138, 180, 0, 90]},
|
| 94 |
+
{"p_up": [-344.47, 406.83, 224.0, 180, 0, -90],
|
| 95 |
+
"p": [-344.471, 406.83, 138, 180, 0, -90]},
|
| 96 |
+
{"p_up": [-283.27, 395.494, 224.0, 180, 0, 90],
|
| 97 |
+
"p": [-283.27, 395.494, 138, 180, 0, 90]},
|
| 98 |
+
{"p_up": [-225.166, 407.34, 224.0, 180, 0, -90],
|
| 99 |
+
"p": [-225.166, 407.34, 138, 180, 0, -90]},
|
| 100 |
+
{"p_up": [-161.926, 393.811, 224.0, 180, 0, 90],
|
| 101 |
+
"p": [-161.926, 393.811, 138, 180, 0, 90]},
|
| 102 |
+
{"p_up": [-105.989, 404.829, 224.0, 180, 0, -90],
|
| 103 |
+
"p": [-105.989, 404.829, 138, 180, 0, -90]},
|
| 104 |
+
{"p_up": [ -42.995, 391.82, 224.0, 180, 0, 90],
|
| 105 |
+
"p": [ -42.995, 391.82, 138, 180, 0, 90]},
|
| 106 |
+
{"p_up": [16.005, 403.012, 224.0, 180, 0, -90],
|
| 107 |
+
"p": [ 16.005, 403.012, 138, 180, 0, -90]},
|
| 108 |
+
{"p_up": [ 78.007, 390.986, 224.0, 180, 0, 90],
|
| 109 |
+
"p": [ 78.007, 390.986, 138, 180, 0, 90]},
|
| 110 |
+
{"p_up": [ 136.009, 401, 224.0, 180, 0, -90],
|
| 111 |
+
"p": [ 136.009, 401.0, 138, 180, 0, -90]},
|
| 112 |
+
{"p_up": [ 199.005, 389.826, 224.0, 180, 0, 90],
|
| 113 |
+
"p": [ 199.005, 389.826, 138, 180, 0, 90]},
|
| 114 |
+
{"p_up": [ 256.012, 397, 224.0, 180, 0, -90],
|
| 115 |
+
"p": [ 256.012, 397, 138, 180, 0, -90]},
|
| 116 |
+
{"p_up": [ 317.003, 384.987, 224.0, 180, 0, 90],
|
| 117 |
+
"p": [ 317.003, 384.987, 138, 180, 0, 90]},
|
| 118 |
+
{"p_up": [ 375.006, 392.998, 224.0, 180, 0, -90],
|
| 119 |
+
"p": [ 375.006, 392.998, 138, 180, 0, -90]},
|
| 120 |
+
{"p_up": [ 437.12, 382.974, 224.0, 180, 0, 90],
|
| 121 |
+
"p": [ 437.12, 382.974, 138, 180, 0, 90]},
|
| 122 |
+
{"p_up": [ 496.009, 392.991, 224.0, 180, 0, -90],
|
| 123 |
+
"p": [ 496.009, 392.991, 138, 180, 0, -90]},
|
| 124 |
+
{"p_up": [ 557.007, 380.997, 224.0, 180, 0, 90],
|
| 125 |
+
"p": [ 557.007, 380.997, 138, 180, 0, 90]},
|
| 126 |
+
{"p_up": [ 615.006, 390.26, 224.0, 180, 0, -90],
|
| 127 |
+
"p": [ 615.006, 390.26, 138, 180, 0, -90]}
|
| 128 |
+
]
|
| 129 |
+
|
| 130 |
+
right_small = [
|
| 131 |
+
{"p_up": [-340, 746.032, 224.0, 180, 0, 90],
|
| 132 |
+
"p": [-340, 746.032, 138, 180, 0, 90]},
|
| 133 |
+
{"p_up": [-277, 751.98, 224, 180, 0, -90],
|
| 134 |
+
"p": [-277, 751.98, 138, 180, 0, -90]},
|
| 135 |
+
{"p_up": [-220, 744.168, 224, 180, 0, 90],
|
| 136 |
+
"p": [-220 ,744.168, 138, 180, 0, 90]},
|
| 137 |
+
{"p_up": [-159.372, 750.327, 224, 180, 0, -90],
|
| 138 |
+
"p": [-159.372, 750.327, 138, 180, 0, -90]},
|
| 139 |
+
{"p_up": [-97.395, 742.409, 224, 180, 0, 90],
|
| 140 |
+
"p": [-97.395, 742.409, 138, 180, 0, 90]},
|
| 141 |
+
{"p_up": [ -41.372, 748.472, 224, 180, 0, -90],
|
| 142 |
+
"p": [ -41.372, 748.472, 138, 180, 0, -90]},
|
| 143 |
+
{"p_up": [ 24.616, 740.0, 224, 180, 0, 90],
|
| 144 |
+
"p": [ 24.616, 740.0, 138, 180, 0, 90]},
|
| 145 |
+
{"p_up": [ 78.609, 745.213, 224, 180, 0, -90],
|
| 146 |
+
"p": [ 78.609, 745.213, 138, 180, 0, -90]},
|
| 147 |
+
{"p_up": [ 143.61, 737.0, 224, 180, 0, 90],
|
| 148 |
+
"p": [ 143.61, 737.0, 138, 180, 0, 90]},
|
| 149 |
+
{"p_up": [ 199.626, 743.0, 224, 180, 0, -90],
|
| 150 |
+
"p": [ 199.626, 740.0, 138, 180, 0, -90]},
|
| 151 |
+
{"p_up": [ 264.007, 737.808, 224, 180, 0, 90],
|
| 152 |
+
"p": [ 264.007, 737.808, 138, 180, 0, 90]},
|
| 153 |
+
{"p_up": [ 322.615, 740.0, 224, 180, 0, -90],
|
| 154 |
+
"p": [ 322.615, 740.0, 138, 180, 0, -90]}
|
| 155 |
+
]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
left_transit_point = [300.0, -390.775, 399.1, 180.0, 0.0, 90]
|
| 159 |
+
right_transit_point = [300.0, 398.775, 399.1, 180.0, 0.0, 90]
|
| 160 |
+
p90 = [-345, -345, 450, -90, 0, 90]
|
| 161 |
+
p91 = [-345, 205, 450, -90, 0, 90]
|
| 162 |
+
|
| 163 |
+
place = [-711.97, 160.132, 237.98, -90, 0.0, 88.702]
|
| 164 |
+
preplace = [-712.015, 160.132, 277.945, -90, 0.0, 88.702]
|
| 165 |
+
prepreplace = [-630.833, 160.132, 276.948, -90.996, 0.0, 89]
|
| 166 |
+
safeback = [-690.181, 160.132, 236.533, -90.996, 0.0, 89]
|
| 167 |
+
|
| 168 |
+
trash = [-445.049, 5, 380, 15, 86, -164]
|
| 169 |
+
|
| 170 |
+
metal_detector = [-604.861, -567.033, 199.97, -179.994, 0, 0]
|
| 171 |
+
post_metal_detector = [-611.882,-567,-12, -179.994, 0, 0]
|
| 172 |
+
|
| 173 |
+
# metal_detector = [-624.861, -650.033, 199.97, -179.994, 0, -178]
|
| 174 |
+
# post_metal_detector = [-631.882,-650,-6, -179.994, 0, -178]
|
MecheyePackage/profiler_utils.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from mecheye.profiler import *
|
| 2 |
+
from mecheye.shared import *
|
| 3 |
+
import numpy as np
|
| 4 |
+
import time
|
| 5 |
+
pitch = 1e-3
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def print_profiler_info(profiler_info: ProfilerInfo):
|
| 9 |
+
print("Device Firmware Version:", profiler_info.firmware_version)
|
| 10 |
+
print("Device IP Address:", profiler_info.ip_address)
|
| 11 |
+
return 1
|
| 12 |
+
|
| 13 |
+
def connect_by_ip(profiler: Profiler, ip_address: str, timeout_ms=5000) -> bool:
|
| 14 |
+
max_retries = 2
|
| 15 |
+
for attempt in range(max_retries):
|
| 16 |
+
error_status = profiler.connect(ip_address, timeout_ms)
|
| 17 |
+
if error_status.is_ok():
|
| 18 |
+
print(f"Connected to profiler at {ip_address}")
|
| 19 |
+
return True
|
| 20 |
+
print(f"Attempt {attempt+1} failed: {error_status.description()}") # Log error details
|
| 21 |
+
time.sleep(3)
|
| 22 |
+
print(f"Connection failed after {max_retries} attempts.")
|
| 23 |
+
return False
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def find_and_connect(profiler: Profiler) -> bool:
|
| 27 |
+
profiler_infos = Profiler.discover_profilers()
|
| 28 |
+
|
| 29 |
+
if len(profiler_infos) == 0:
|
| 30 |
+
print("No Mech-Eye 3D Laser Profilers found.")
|
| 31 |
+
return False
|
| 32 |
+
|
| 33 |
+
# for i in range(len(profiler_infos)):
|
| 34 |
+
# print_profiler_info(profiler_infos[i])
|
| 35 |
+
|
| 36 |
+
input_index = 0
|
| 37 |
+
|
| 38 |
+
error_status = profiler.connect(profiler_infos[input_index])
|
| 39 |
+
if not error_status.is_ok():
|
| 40 |
+
# show_error(error_status)
|
| 41 |
+
return False
|
| 42 |
+
return True
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def find_and_connect_multi_profiler() -> list:
|
| 46 |
+
profiler_infos = Profiler.discover_profilers()
|
| 47 |
+
|
| 48 |
+
if len(profiler_infos) == 0:
|
| 49 |
+
print("No Mech-Eye 3D Laser Profilers found.")
|
| 50 |
+
return []
|
| 51 |
+
|
| 52 |
+
for i in range(len(profiler_infos)):
|
| 53 |
+
print("Mech-Eye device index :", i)
|
| 54 |
+
print_profiler_info(profiler_infos[i])
|
| 55 |
+
|
| 56 |
+
indices = set()
|
| 57 |
+
|
| 58 |
+
while True:
|
| 59 |
+
print("Please enter the device index you want to connect: ")
|
| 60 |
+
print("Enter the character 'c' to terminate adding devices")
|
| 61 |
+
|
| 62 |
+
input_index = input()
|
| 63 |
+
if input_index == 'c':
|
| 64 |
+
break
|
| 65 |
+
if input_index.isdigit() and 0 <= int(input_index) < len(profiler_infos):
|
| 66 |
+
indices.add(int(input_index))
|
| 67 |
+
else:
|
| 68 |
+
print("Input invalid! Please enter the device index you want to connect: ")
|
| 69 |
+
|
| 70 |
+
profilers = []
|
| 71 |
+
for index in indices:
|
| 72 |
+
profiler = Profiler()
|
| 73 |
+
status = profiler.connect(profiler_infos[index])
|
| 74 |
+
if status.is_ok():
|
| 75 |
+
profilers.append(profiler)
|
| 76 |
+
else:
|
| 77 |
+
show_error(status)
|
| 78 |
+
|
| 79 |
+
return profilers
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def print_profiler_status(profiler_status: ProfilerStatus):
|
| 83 |
+
print(".....Profiler temperatures.....")
|
| 84 |
+
print("Controller CPU: ",
|
| 85 |
+
f"{profiler_status.temperature.controller_cpu_temperature:.2f}", "°C", sep="")
|
| 86 |
+
print("Sensor CPU: ",
|
| 87 |
+
f"{profiler_status.temperature.sensor_cpu_temperature:.2f}", "°C", sep="")
|
| 88 |
+
print("...............................")
|
| 89 |
+
print()
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def save_data_to_ply(file_name: str, profile_batch: ProfileBatch, x_unit: float, y_unit: float, use_encoder_values: bool, encoder_vals: np.array, is_organized: bool = True):
|
| 93 |
+
data_width = profile_batch.width()
|
| 94 |
+
with open(file_name, 'w') as file:
|
| 95 |
+
depth = profile_batch.get_depth_map().data()
|
| 96 |
+
vertex_count = depth.size if is_organized else depth[~np.isnan(
|
| 97 |
+
depth)].size
|
| 98 |
+
y, x = np.indices(depth.shape, dtype=np.uint16)
|
| 99 |
+
|
| 100 |
+
file.write(f"""ply
|
| 101 |
+
format ascii 1.0
|
| 102 |
+
comment File generated
|
| 103 |
+
comment x y z data unit in mm
|
| 104 |
+
element vertex {vertex_count}
|
| 105 |
+
property float x
|
| 106 |
+
property float y
|
| 107 |
+
property float z
|
| 108 |
+
end_header
|
| 109 |
+
"""
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
def depth_to_point(x, y, depth):
|
| 113 |
+
if not np.isnan(depth):
|
| 114 |
+
file.write("{} {} {}\n".format(
|
| 115 |
+
x * x_unit * pitch, y * y_unit * pitch, depth))
|
| 116 |
+
elif is_organized:
|
| 117 |
+
file.write("nan nan nan\n")
|
| 118 |
+
|
| 119 |
+
np.vectorize(depth_to_point)(x, np.repeat(encoder_vals, data_width).reshape(depth.shape) if use_encoder_values else y, depth)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def save_data_to_csv(file_name: str, profile_batch: ProfileBatch, x_unit: float, y_unit: float, use_encoder_values: bool, encoder_vals: np.array, is_organized: bool = True):
|
| 123 |
+
data_width = profile_batch.width()
|
| 124 |
+
with open(file_name, 'w') as file:
|
| 125 |
+
file.write("X,Y,Z\n")
|
| 126 |
+
depth = profile_batch.get_depth_map().data()
|
| 127 |
+
y, x = np.indices(depth.shape, np.uint16)
|
| 128 |
+
|
| 129 |
+
def depth_to_point(x, y, depth):
|
| 130 |
+
if not np.isnan(depth):
|
| 131 |
+
file.write("{},{},{}\n".format(x * x_unit *
|
| 132 |
+
pitch, y * y_unit * pitch, depth))
|
| 133 |
+
elif is_organized:
|
| 134 |
+
file.write("nan,nan,nan\n")
|
| 135 |
+
|
| 136 |
+
np.vectorize(depth_to_point)(x, np.repeat(encoder_vals, data_width).reshape(
|
| 137 |
+
depth.shape) if use_encoder_values else y, depth)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def get_trigger_interval_distance() -> float:
|
| 141 |
+
while True:
|
| 142 |
+
trigger_interval_distance = input(
|
| 143 |
+
"Please enter encoder trigger interval distance (unit: um, min: 1, max: 65535): ")
|
| 144 |
+
if trigger_interval_distance.isdigit() and 1 <= float(trigger_interval_distance) <= 65535:
|
| 145 |
+
return float(trigger_interval_distance)
|
| 146 |
+
print("Input invalid!")
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def save_data_to_np(profile_batch: ProfileBatch, x_unit: float, y_unit: float, use_encoder_values: bool, encoder_vals: np.array, is_organized: bool = True):
|
| 150 |
+
depth = profile_batch.get_depth_map().data()
|
| 151 |
+
y, x = np.indices(depth.shape, dtype=np.uint16)
|
| 152 |
+
|
| 153 |
+
# Geçerli depth değerlerini al
|
| 154 |
+
valid_mask = ~np.isnan(depth)
|
| 155 |
+
|
| 156 |
+
# Geçerli verileri filtrele
|
| 157 |
+
valid_x = x[valid_mask]
|
| 158 |
+
valid_y = y[valid_mask]
|
| 159 |
+
valid_depth = depth[valid_mask]
|
| 160 |
+
|
| 161 |
+
valid_points_array = np.stack([valid_x * x_unit * pitch, valid_y * y_unit * pitch, valid_depth], axis=-1, dtype=np.float32)
|
| 162 |
+
|
| 163 |
+
return valid_points_array
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def save_point_cloud(profile_batch: ProfileBatch, user_set: UserSet, save_ply: bool = True, save_csv: bool = False, is_organized: bool = True, save_np=False):
|
| 167 |
+
if profile_batch.is_empty():
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
error, x_unit = user_set.get_float_value(XAxisResolution.name)
|
| 171 |
+
if not error.is_ok():
|
| 172 |
+
show_error(error)
|
| 173 |
+
return
|
| 174 |
+
|
| 175 |
+
error, y_unit = user_set.get_float_value(YResolution.name)
|
| 176 |
+
if not error.is_ok():
|
| 177 |
+
show_error(error)
|
| 178 |
+
return
|
| 179 |
+
|
| 180 |
+
error, line_scan_trigger_source = user_set.get_enum_value(LineScanTriggerSource.name)
|
| 181 |
+
if not error.is_ok():
|
| 182 |
+
show_error(error)
|
| 183 |
+
return
|
| 184 |
+
use_encoder_values = line_scan_trigger_source == LineScanTriggerSource.Value_Encoder
|
| 185 |
+
|
| 186 |
+
error, trigger_interval = user_set.get_int_value(EncoderTriggerInterval.name)
|
| 187 |
+
if not error.is_ok():
|
| 188 |
+
show_error(error)
|
| 189 |
+
return
|
| 190 |
+
|
| 191 |
+
encoder_vals = profile_batch.get_encoder_array().data().squeeze().astype(np.int64)
|
| 192 |
+
encoder_vals = (encoder_vals - encoder_vals[0]) / trigger_interval
|
| 193 |
+
|
| 194 |
+
if save_csv:
|
| 195 |
+
save_data_to_csv("PointCloud.csv", profile_batch, x_unit, y_unit, use_encoder_values, encoder_vals, is_organized)
|
| 196 |
+
if save_ply:
|
| 197 |
+
save_data_to_ply("PointCloud.ply", profile_batch, x_unit, y_unit, use_encoder_values, encoder_vals, is_organized)
|
| 198 |
+
if save_np:
|
| 199 |
+
return save_data_to_np(profile_batch, x_unit, y_unit, use_encoder_values, encoder_vals, is_organized)
|
MecheyePackage/robot_control.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import requests
|
| 3 |
+
import logging
|
| 4 |
+
# Global değişkenler
|
| 5 |
+
session = None
|
| 6 |
+
login_cookies = None
|
| 7 |
+
login_headers = None
|
| 8 |
+
|
| 9 |
+
# Giriş işlemi
|
| 10 |
+
def login():
|
| 11 |
+
global session, login_cookies, login_headers
|
| 12 |
+
login_url = "http://127.0.0.1/action/login"
|
| 13 |
+
login_data = {"password": "123","username": "admin"}
|
| 14 |
+
session = requests.Session()
|
| 15 |
+
try:
|
| 16 |
+
login_response = session.post(login_url, data=login_data)
|
| 17 |
+
|
| 18 |
+
if login_response.status_code == 200:
|
| 19 |
+
login_cookies = session.cookies.get_dict()
|
| 20 |
+
login_headers = login_response.headers
|
| 21 |
+
return login_cookies, login_headers
|
| 22 |
+
else:
|
| 23 |
+
logging.error(f"Giriş başarısız: {login_response.status_code}")
|
| 24 |
+
logging.error("Hata mesajı: %s", login_response.text)
|
| 25 |
+
sys.exit()
|
| 26 |
+
except requests.RequestException as e:
|
| 27 |
+
logging.exception("Giriş sırasında bir hata oluştu.")
|
| 28 |
+
sys.exit()
|
| 29 |
+
|
| 30 |
+
# Komut gönderme fonksiyonu
|
| 31 |
+
def send_command(cmd_data):
|
| 32 |
+
global session, login_cookies, login_headers
|
| 33 |
+
|
| 34 |
+
# Giriş kontrolü
|
| 35 |
+
if not login_cookies or not login_headers:
|
| 36 |
+
login()
|
| 37 |
+
|
| 38 |
+
set_url = "http://127.0.0.1/action/set"
|
| 39 |
+
cookie_value = login_cookies.get("-goahead-session-", "")
|
| 40 |
+
headers = {
|
| 41 |
+
"accept": login_headers.get("accept", "application/json, text/plain, */*"),
|
| 42 |
+
"accept-encoding": login_headers.get("accept-encoding", "gzip, deflate"),
|
| 43 |
+
"accept-language": login_headers.get("accept-language", "en-US,en;q=0.9"),
|
| 44 |
+
"connection": "keep-alive",
|
| 45 |
+
"content-type": "application/json;charset=UTF-8",
|
| 46 |
+
"cookie": f"-goahead-session-={cookie_value}",
|
| 47 |
+
"origin": "http://127.0.0.1",
|
| 48 |
+
"referer": "http://127.0.0.1/index.html",
|
| 49 |
+
"user-agent": login_headers.get("user-agent", "Mozilla/5.0 (X11; Linux x86_64)")
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
response = session.post(set_url, headers=headers, json=cmd_data)
|
| 54 |
+
if response.status_code == 200:
|
| 55 |
+
return response.text
|
| 56 |
+
else:
|
| 57 |
+
logging.error(f"İstek başarısız: {response.status_code}")
|
| 58 |
+
logging.error("Hata mesajı: %s", response.text)
|
| 59 |
+
return None
|
| 60 |
+
except requests.RequestException as e:
|
| 61 |
+
logging.exception("Komut gönderme sırasında bir hata oluştu.")
|
| 62 |
+
return None
|
MecheyePackage/scan.py
ADDED
|
@@ -0,0 +1,1086 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
try:
|
| 2 |
+
import inspect
|
| 3 |
+
import os
|
| 4 |
+
import sys
|
| 5 |
+
import threading
|
| 6 |
+
import time
|
| 7 |
+
import numpy as np
|
| 8 |
+
import requests
|
| 9 |
+
import open3d as o3d
|
| 10 |
+
import matplotlib
|
| 11 |
+
from Scripts import *
|
| 12 |
+
from mecheye_trigger import TriggerWithExternalDeviceAndFixedRate
|
| 13 |
+
from points import *
|
| 14 |
+
import json
|
| 15 |
+
import mysql.connector
|
| 16 |
+
import logging
|
| 17 |
+
import socketio
|
| 18 |
+
# from ResultWriter import AppwriteDataWriter
|
| 19 |
+
from matplotlib.figure import Figure
|
| 20 |
+
from scipy.spatial import cKDTree
|
| 21 |
+
except ImportError as e:
|
| 22 |
+
print(f"Import error: {e}")
|
| 23 |
+
sys.exit(1)
|
| 24 |
+
|
| 25 |
+
# DEVICE_IP = os.environ.get('IP_ADDRESS')
|
| 26 |
+
# PORT = os.environ.get('PORT')
|
| 27 |
+
# if not DEVICE_IP or not PORT:
|
| 28 |
+
# raise EnvironmentError('Environment variables REACT_APP_DEVICE_IP and REACT_APP_PORT must be set')
|
| 29 |
+
|
| 30 |
+
API_BASE_URL = ""
|
| 31 |
+
|
| 32 |
+
logger = logging.getLogger(__name__)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
base_dir = os.path.dirname(os.path.abspath(__file__))
|
| 36 |
+
config_path = os.path.join(base_dir, 'config.json')
|
| 37 |
+
|
| 38 |
+
with open(config_path, "r") as f:
|
| 39 |
+
config = json.load(f)
|
| 40 |
+
|
| 41 |
+
class RobotWrapper:
|
| 42 |
+
def __init__(self, robot):
|
| 43 |
+
self.robot = robot
|
| 44 |
+
self.move_methods = ['MoveCart', 'MoveCart', 'MoveJ']
|
| 45 |
+
|
| 46 |
+
def __getattr__(self, name):
|
| 47 |
+
attr = getattr(self.robot, name)
|
| 48 |
+
|
| 49 |
+
if name in self.move_methods and callable(attr):
|
| 50 |
+
def wrapped_method(*args, **kwargs):
|
| 51 |
+
try:
|
| 52 |
+
response = attr(*args, **kwargs)
|
| 53 |
+
print(f"ROBOT RESPONSE for {name}: {response}")
|
| 54 |
+
|
| 55 |
+
if response != 0: # Hata durumu
|
| 56 |
+
# Detaylı hata bilgisi
|
| 57 |
+
frame = inspect.currentframe().f_back
|
| 58 |
+
filename = frame.f_code.co_filename
|
| 59 |
+
line_number = frame.f_lineno
|
| 60 |
+
function_name = frame.f_code.co_name
|
| 61 |
+
|
| 62 |
+
error_msg = f"ROBOT ERROR: {name} failed with response {response}"
|
| 63 |
+
location_msg = f"Error at line {line_number} in '{function_name}' ({os.path.basename(filename)})"
|
| 64 |
+
|
| 65 |
+
print(error_msg)
|
| 66 |
+
print(location_msg)
|
| 67 |
+
|
| 68 |
+
# Hata logunu kaydet
|
| 69 |
+
try:
|
| 70 |
+
with open('robot_error_log.txt', 'a') as f:
|
| 71 |
+
f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] {error_msg}\n")
|
| 72 |
+
f.write(f"{location_msg}\n")
|
| 73 |
+
f.write(f"Args: {args}, Kwargs: {kwargs}\n")
|
| 74 |
+
f.write("-" * 50 + "\n")
|
| 75 |
+
except:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
print("CRITICAL ROBOT ERROR - SHUTTING DOWN")
|
| 79 |
+
sys.exit(1)
|
| 80 |
+
|
| 81 |
+
return response
|
| 82 |
+
except Exception as e:
|
| 83 |
+
print(f"EXCEPTION in robot {name}: {e}")
|
| 84 |
+
raise
|
| 85 |
+
|
| 86 |
+
return wrapped_method
|
| 87 |
+
|
| 88 |
+
return attr
|
| 89 |
+
|
| 90 |
+
mech_eye = TriggerWithExternalDeviceAndFixedRate(vel_mul=config["vel_mul"])
|
| 91 |
+
robot = mech_eye.robot
|
| 92 |
+
robot = RobotWrapper(robot) # Wrap the robot with error handling
|
| 93 |
+
|
| 94 |
+
def handle_errors(func):
|
| 95 |
+
def wrapper(*args, **kwargs):
|
| 96 |
+
try:
|
| 97 |
+
return func(*args, **kwargs)
|
| 98 |
+
except Exception as e:
|
| 99 |
+
# Daha detaylı hata bilgisi
|
| 100 |
+
import traceback
|
| 101 |
+
error_details = traceback.format_exc()
|
| 102 |
+
print(f"CRITICAL ERROR in {func.__name__}: {e}")
|
| 103 |
+
print(f"ERROR TRACEBACK:\n{error_details}")
|
| 104 |
+
|
| 105 |
+
# Hata logunu dosyaya kaydet
|
| 106 |
+
try:
|
| 107 |
+
with open('error_log.txt', 'a') as f:
|
| 108 |
+
f.write(f"[{time.strftime('%Y-%m-%d %H:%M:%S')}] ERROR in {func.__name__}: {e}\n")
|
| 109 |
+
f.write(f"TRACEBACK:\n{error_details}\n")
|
| 110 |
+
f.write("-" * 50 + "\n")
|
| 111 |
+
except:
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
# Robot güvenlik pozisyonuna al
|
| 115 |
+
try:
|
| 116 |
+
if read_current_point_index() >= 32:
|
| 117 |
+
res = robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * 50)
|
| 118 |
+
else:
|
| 119 |
+
res = robot.MoveCart(p90, 0, 0, vel=config["vel_mul"] * 50)
|
| 120 |
+
print(f"Robot moved to safe position with response: {res}")
|
| 121 |
+
robot.WaitMs(500)
|
| 122 |
+
robot.ResetAllError()
|
| 123 |
+
print("Robot moved to safe position due to error.")
|
| 124 |
+
except Exception as robot_error:
|
| 125 |
+
print(f"Failed to move robot to safe position: {robot_error}")
|
| 126 |
+
|
| 127 |
+
# Hata durumunda graceful exit
|
| 128 |
+
print("EXITING DUE TO CRITICAL ERROR")
|
| 129 |
+
sys.exit(1)
|
| 130 |
+
|
| 131 |
+
return wrapper
|
| 132 |
+
|
| 133 |
+
def read_current_point_index() -> int:
|
| 134 |
+
file_path = os.path.join(base_dir, "point_index.txt")
|
| 135 |
+
if os.path.exists(file_path):
|
| 136 |
+
with open(file_path, 'r') as file:
|
| 137 |
+
return int(file.read().strip())
|
| 138 |
+
return 0
|
| 139 |
+
|
| 140 |
+
def write_current_point_index(index: int):
|
| 141 |
+
file_path = os.path.join(base_dir, "point_index.txt")
|
| 142 |
+
with open(file_path, 'w') as file:
|
| 143 |
+
file.write(str(index))
|
| 144 |
+
|
| 145 |
+
def is_mysql_available() -> bool:
|
| 146 |
+
try:
|
| 147 |
+
# conn = mysql.connector.connect(
|
| 148 |
+
# host="192.168.1.180",
|
| 149 |
+
# user="cobot_dbuser",
|
| 150 |
+
# password="um6vv$7*sJ@5Q*",
|
| 151 |
+
# database="cobot",
|
| 152 |
+
# connection_timeout=2 # hızlıca timeout versin
|
| 153 |
+
# )
|
| 154 |
+
# conn.close()
|
| 155 |
+
return True
|
| 156 |
+
except mysql.connector.Error:
|
| 157 |
+
print("MySQL veritabanına bağlanılamıyor.")
|
| 158 |
+
return False
|
| 159 |
+
|
| 160 |
+
# Add save_figures configuration if not present
|
| 161 |
+
if "save_figures" not in config:
|
| 162 |
+
config["save_figures"] = True
|
| 163 |
+
with open(config_path, "w") as f:
|
| 164 |
+
json.dump(config, f, indent=4)
|
| 165 |
+
|
| 166 |
+
def save_figure(obj, filename: str, dpi: int = 300):
|
| 167 |
+
"""Helper function to save matplotlib Figure veya plt objesini"""
|
| 168 |
+
if not config["save_figures"]:
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
fig_path = os.path.join(os.path.dirname(__file__), "Scan_Outputs", "figures", filename)
|
| 172 |
+
os.makedirs(os.path.dirname(fig_path), exist_ok=True)
|
| 173 |
+
|
| 174 |
+
if isinstance(obj, Figure):
|
| 175 |
+
obj.savefig(fig_path, dpi=dpi, bbox_inches='tight')
|
| 176 |
+
else:
|
| 177 |
+
# plt objesi varsayımı
|
| 178 |
+
obj.savefig(fig_path, dpi=dpi, bbox_inches='tight')
|
| 179 |
+
|
| 180 |
+
print(f"Plot saved to {fig_path}")
|
| 181 |
+
|
| 182 |
+
def safe_round(value, decimals=3):
|
| 183 |
+
try:
|
| 184 |
+
return round(float(value), decimals)
|
| 185 |
+
except (TypeError, ValueError):
|
| 186 |
+
return value
|
| 187 |
+
|
| 188 |
+
def sor_filter(points: np.ndarray, k: int = 20, n_sigma: float = 1.0):
|
| 189 |
+
points = points.astype(np.float32)
|
| 190 |
+
tree = cKDTree(points)
|
| 191 |
+
|
| 192 |
+
# n_jobs=-1 ile tüm çekirdekler
|
| 193 |
+
distances, _ = tree.query(points, k=k+1)
|
| 194 |
+
|
| 195 |
+
# Ortalama mesafe
|
| 196 |
+
mean_dist = np.mean(distances[:, 1:], axis=1)
|
| 197 |
+
|
| 198 |
+
# Threshold
|
| 199 |
+
threshold = np.mean(mean_dist) + n_sigma * np.std(mean_dist)
|
| 200 |
+
|
| 201 |
+
# Mask ve filtre
|
| 202 |
+
mask = mean_dist <= threshold
|
| 203 |
+
return points[mask]
|
| 204 |
+
|
| 205 |
+
# Backend configuration: Agg mode is non-interactive; TkAgg is interactive.
|
| 206 |
+
if config["use_agg"]:
|
| 207 |
+
matplotlib.use('Agg')
|
| 208 |
+
import matplotlib.pyplot as plt
|
| 209 |
+
plt.show = lambda: None
|
| 210 |
+
else:
|
| 211 |
+
matplotlib.use('TkAgg')
|
| 212 |
+
import matplotlib.pyplot as plt
|
| 213 |
+
|
| 214 |
+
class JaguarScanner:
|
| 215 |
+
"""
|
| 216 |
+
JaguarScanner class; a professional application that manages self.robot control, scanning, and measurement operations.
|
| 217 |
+
|
| 218 |
+
Features:
|
| 219 |
+
- Collects, processes, and saves measurement data to an Excel file.
|
| 220 |
+
- Manages the robot's pick and put-back operations.
|
| 221 |
+
- Increases performance with threaded computation.
|
| 222 |
+
"""
|
| 223 |
+
def __init__(self, vel_mul: float=1, use_agg: bool = config["use_agg"], put_back: bool = False):
|
| 224 |
+
"""
|
| 225 |
+
Initializes a JaguarScanner instance.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
vel_mul (float): Velocity multiplier.
|
| 229 |
+
use_agg (bool, optional): Use Agg mode. Default is True.
|
| 230 |
+
put_back (bool, optional): Whether the part will be put back. If False, it is directed to the trash point.
|
| 231 |
+
"""
|
| 232 |
+
self.mech_eye = TriggerWithExternalDeviceAndFixedRate(vel_mul)
|
| 233 |
+
self.robot = self.mech_eye.robot
|
| 234 |
+
self.pcd = o3d.geometry.PointCloud()
|
| 235 |
+
self.small_pcd = o3d.geometry.PointCloud()
|
| 236 |
+
self.vert_pcd = o3d.geometry.PointCloud()
|
| 237 |
+
self.hor_pcd = o3d.geometry.PointCloud()
|
| 238 |
+
self.small_fig = None
|
| 239 |
+
self.hor_fig = None
|
| 240 |
+
self.results = []
|
| 241 |
+
self.old_point = None
|
| 242 |
+
self.excel_threads = []
|
| 243 |
+
self.points = left_of_robot_points + left_small + right_of_robot_points + right_small
|
| 244 |
+
self.pick_point = 1
|
| 245 |
+
self.robot_tcp = [0, 0, 0, 0, 0, 0]
|
| 246 |
+
self.sio = socketio.Client()
|
| 247 |
+
self.current_di0_value = 0
|
| 248 |
+
self.current_di1_value = 0
|
| 249 |
+
self.di0_thread = threading.Thread(target=self.read_di0_updates, daemon=True)
|
| 250 |
+
self.di0_thread.start()
|
| 251 |
+
self.rescan = 0
|
| 252 |
+
# self.db_writer = AppwriteDataWriter()
|
| 253 |
+
|
| 254 |
+
def read_di0_updates(self):
|
| 255 |
+
sio = self.sio
|
| 256 |
+
@sio.event
|
| 257 |
+
def connect():
|
| 258 |
+
print("Connected to Socket.IO server!")
|
| 259 |
+
|
| 260 |
+
@sio.event
|
| 261 |
+
def robot_status(data):
|
| 262 |
+
json_data = {"data": data, "error": None}
|
| 263 |
+
try:
|
| 264 |
+
self.robot_tcp = list(data.get("TCP", {"x": 0, "y": 0, "z": 0, "rx": 0, "ry": 0, "rz": 0}).values())
|
| 265 |
+
self.current_di0_value = data.get("DI0", 0)
|
| 266 |
+
self.current_di1_value = data.get("DI1",0)
|
| 267 |
+
# print("di1",self.current_di1_value)
|
| 268 |
+
except Exception as e:
|
| 269 |
+
json_data["error"] = str(e)
|
| 270 |
+
print(f"Error processing robot_status: {e}")
|
| 271 |
+
|
| 272 |
+
# try:
|
| 273 |
+
# with open('robot_data.json', 'w') as f:
|
| 274 |
+
# json.dump(json_data, f, indent=4)
|
| 275 |
+
# print(f"Data written to robot_data.json: {json_data}")
|
| 276 |
+
# except Exception as e:
|
| 277 |
+
# print(f"Error writing to JSON file: {e}")
|
| 278 |
+
|
| 279 |
+
try:
|
| 280 |
+
sio.connect('http://0.0.0.0:7860')
|
| 281 |
+
sio.wait()
|
| 282 |
+
except Exception as e:
|
| 283 |
+
json_data = {"data": None, "error": f"Connection error: {str(e)}"}
|
| 284 |
+
try:
|
| 285 |
+
with open('robot_data.json', 'w') as f:
|
| 286 |
+
json.dump(json_data, f, indent=4)
|
| 287 |
+
print(f"Connection error written to robot_data.json: {e}")
|
| 288 |
+
except Exception as e:
|
| 289 |
+
print(f"Error writing connection error to JSON file: {e}")
|
| 290 |
+
print(f"Connection error: {e}")
|
| 291 |
+
|
| 292 |
+
@staticmethod
|
| 293 |
+
def rotate_point_cloud(points: np.ndarray, angle_degrees: float, axis: str) -> np.ndarray:
|
| 294 |
+
angle_radians = np.radians(angle_degrees)
|
| 295 |
+
if axis == "z":
|
| 296 |
+
rotation_matrix = np.array([
|
| 297 |
+
[np.cos(angle_radians), -np.sin(angle_radians), 0],
|
| 298 |
+
[np.sin(angle_radians), np.cos(angle_radians), 0],
|
| 299 |
+
[0, 0, 1]
|
| 300 |
+
])
|
| 301 |
+
elif axis == "x":
|
| 302 |
+
rotation_matrix = np.array([
|
| 303 |
+
[1, 0, 0],
|
| 304 |
+
[0, np.cos(angle_radians), -np.sin(angle_radians)],
|
| 305 |
+
[0, np.sin(angle_radians), np.cos(angle_radians)]
|
| 306 |
+
])
|
| 307 |
+
elif axis == "y":
|
| 308 |
+
rotation_matrix = np.array([
|
| 309 |
+
[np.cos(angle_radians), 0, np.sin(angle_radians)],
|
| 310 |
+
[0, 1, 0],
|
| 311 |
+
[-np.sin(angle_radians), 0, np.cos(angle_radians)]
|
| 312 |
+
])
|
| 313 |
+
else:
|
| 314 |
+
raise ValueError("Desteklenmeyen eksen. 'x', 'y' veya 'z' girin.")
|
| 315 |
+
return points @ rotation_matrix.T
|
| 316 |
+
|
| 317 |
+
@staticmethod
|
| 318 |
+
def to_origin(points: np.ndarray) -> np.ndarray:
|
| 319 |
+
min_x, min_y = np.min(points[:, 0]), np.min(points[:, 1])
|
| 320 |
+
points[:, 0] -= min_x
|
| 321 |
+
points[:, 1] -= min_y
|
| 322 |
+
return points
|
| 323 |
+
|
| 324 |
+
@staticmethod
|
| 325 |
+
def remove_gripper_points(points: np.ndarray) -> np.ndarray:
|
| 326 |
+
min_x = np.min(points[:, 0])
|
| 327 |
+
y_candidates = points[:, 1][points[:, 0] < min_x + 23]
|
| 328 |
+
y_min, y_max = np.min(y_candidates), np.max(y_candidates)
|
| 329 |
+
return points[(points[:, 1] < y_min-5) | (points[:, 1] > y_max+5)]
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def get_next_valid_index(self, current_index: int, total_points: int) -> int:
|
| 333 |
+
with open(config_path, 'r') as file:
|
| 334 |
+
config = json.load(file)
|
| 335 |
+
ignored = config.get('ignored_points', [])
|
| 336 |
+
next_index = (current_index + 1) % total_points
|
| 337 |
+
while ignored and next_index in ignored:
|
| 338 |
+
next_index = (next_index + 1) % total_points
|
| 339 |
+
return next_index
|
| 340 |
+
|
| 341 |
+
# def write_to_sqlite(self, result, iteration, group_number):
|
| 342 |
+
# self.db_writer.write_to_sqlite(result, iteration, group_number)
|
| 343 |
+
|
| 344 |
+
# def is_database_available(self) -> bool:
|
| 345 |
+
# return self.db_writer.is_appwrite_available()
|
| 346 |
+
|
| 347 |
+
# def get_current_group_info(self):
|
| 348 |
+
# return self.db_writer.get_current_group_info()
|
| 349 |
+
|
| 350 |
+
# def write_to_db(self, result: dict, iteration: int, group_number: int):
|
| 351 |
+
# self.db_writer.write_to_db(result, iteration, group_number)
|
| 352 |
+
|
| 353 |
+
def check_part_quality(self, results: dict) -> int:
|
| 354 |
+
for feature, target_tolerance in config["tolerances"].items():
|
| 355 |
+
target, tolerance = target_tolerance
|
| 356 |
+
value = results.get(feature, None)
|
| 357 |
+
|
| 358 |
+
if value is None:
|
| 359 |
+
print(f"Parça kalite kontrolünden geçemedi: {feature} değeri hesaplanamadı")
|
| 360 |
+
return False
|
| 361 |
+
|
| 362 |
+
lower_bound = target - tolerance
|
| 363 |
+
upper_bound = target + tolerance
|
| 364 |
+
|
| 365 |
+
if not (lower_bound <= value <= upper_bound):
|
| 366 |
+
deviation = abs(value - target)
|
| 367 |
+
print(f"Parça kalite kontrolünden geçemedi: {feature} = {value}, hedef = {target}±{tolerance}")
|
| 368 |
+
|
| 369 |
+
# Gürültüden kaynaklı olabilir mi kontrolü (örneğin toleransın 2 katından fazla sapma varsa)
|
| 370 |
+
if deviation > tolerance * 2:
|
| 371 |
+
|
| 372 |
+
print(f"⚠ Uyarı: {feature} ölçümünde olasılıkla gürültü kaynaklı anormal bir değer algılandı.")
|
| 373 |
+
return deviation
|
| 374 |
+
|
| 375 |
+
return False
|
| 376 |
+
|
| 377 |
+
print("Parça kalite kontrolünden başarıyla geçti.")
|
| 378 |
+
return True
|
| 379 |
+
|
| 380 |
+
def pick_object(self, point: dict, soft_point, failed_pick: bool = False):
|
| 381 |
+
"""
|
| 382 |
+
Performs the pick operation.
|
| 383 |
+
|
| 384 |
+
Args:
|
| 385 |
+
point (dict): Target point.
|
| 386 |
+
soft_point: Soft point position.
|
| 387 |
+
use_left_transit_point (bool): Whether to use back transit.
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
transit_vel = 80
|
| 391 |
+
|
| 392 |
+
# Special case: Extra transit movements at certain points
|
| 393 |
+
if point == right_of_robot_points[0]:
|
| 394 |
+
transit_vel = 50
|
| 395 |
+
self.robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 396 |
+
elif point == left_of_robot_points[0]:
|
| 397 |
+
transit_vel = 50
|
| 398 |
+
self.robot.MoveCart(p90, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 399 |
+
|
| 400 |
+
if not failed_pick:
|
| 401 |
+
if self.cycle == 0:
|
| 402 |
+
self.robot.Mode(1) # Set robot to manual mode so it moves slower on the first movement
|
| 403 |
+
|
| 404 |
+
self.robot.MoveCart(soft_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 405 |
+
|
| 406 |
+
self.robot.Mode(0) # Set robot to automatic mode
|
| 407 |
+
|
| 408 |
+
# Transit movements
|
| 409 |
+
if point in (right_of_robot_points + right_small) and point["p_up"][0] > 300:
|
| 410 |
+
transit_vel = 50
|
| 411 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 412 |
+
elif point in (left_of_robot_points+left_small) and (point["p_up"][0] > 300 and point in left_of_robot_points):
|
| 413 |
+
transit_vel = 50
|
| 414 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 415 |
+
|
| 416 |
+
# Pick movements
|
| 417 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 418 |
+
self.robot.MoveCart(point["p"], 0, 0, vel=config["vel_mul"] * 50)
|
| 419 |
+
self.robot.WaitMs(1000)
|
| 420 |
+
self.robot.SetDO(7, 1) # Signal to grip the part
|
| 421 |
+
print("PICK OBJECT", self.current_di0_value)
|
| 422 |
+
|
| 423 |
+
# Check if the pick operation was successful according to the DI0 value
|
| 424 |
+
if not self.current_di0_value:
|
| 425 |
+
print("Part successfully gripped.")
|
| 426 |
+
self.robot.Mode(0)
|
| 427 |
+
elif self.current_di0_value == 1:
|
| 428 |
+
start_time = time.time()
|
| 429 |
+
while self.current_di0_value == 1 and (time.time() - start_time) < 5:
|
| 430 |
+
if (time.time() - start_time)%2 == 0:
|
| 431 |
+
print("Part gripping error, waiting...")
|
| 432 |
+
time.sleep(0.1)
|
| 433 |
+
if self.current_di0_value == 1:
|
| 434 |
+
# In case of part gripping error
|
| 435 |
+
self.robot.SetDO(7, 0)
|
| 436 |
+
print("Part gripping error.")
|
| 437 |
+
self.robot.Mode(1)
|
| 438 |
+
# Update index for new pick attempt
|
| 439 |
+
current_index = read_current_point_index()
|
| 440 |
+
current_index = self.get_next_valid_index(current_index, len(self.points))
|
| 441 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 442 |
+
write_current_point_index(current_index)
|
| 443 |
+
|
| 444 |
+
# Prepare for new pick operation
|
| 445 |
+
point = self.points[current_index]
|
| 446 |
+
if current_index < len(left_of_robot_points + left_small):
|
| 447 |
+
soft_point = p90
|
| 448 |
+
else:
|
| 449 |
+
soft_point = p91
|
| 450 |
+
|
| 451 |
+
if config["same_place_index"]!= -1:
|
| 452 |
+
point = self.points[config["same_place_index"]]
|
| 453 |
+
else:
|
| 454 |
+
point = self.points[current_index]
|
| 455 |
+
|
| 456 |
+
self.pick_point = point
|
| 457 |
+
self.pick_soft_point = soft_point
|
| 458 |
+
self.pick_left_transit_point = left_transit_point
|
| 459 |
+
self.pick_object(point, soft_point,failed_pick=True) # Recursive call for new pick attempt
|
| 460 |
+
return
|
| 461 |
+
else:
|
| 462 |
+
print("Part successfully gripped.")
|
| 463 |
+
self.robot.Mode(0)
|
| 464 |
+
|
| 465 |
+
self.robot.WaitMs(1500)
|
| 466 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 467 |
+
# Return transit movements
|
| 468 |
+
if point in (right_of_robot_points + right_small) and point["p_up"][0] > 300:
|
| 469 |
+
transit_vel = 50
|
| 470 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 471 |
+
elif point in (left_of_robot_points+left_small) and (point["p_up"][0] > 300 and point in left_of_robot_points):
|
| 472 |
+
transit_vel = 50
|
| 473 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 474 |
+
|
| 475 |
+
if read_current_point_index()==33 and config["same_place_index"] == -1:
|
| 476 |
+
self.robot.MoveCart([-350.269, 407.949, 224.0, 180, 0, -90], 0, 0, vel=config["vel_mul"] * transit_vel) # index 33 olduğunda p91 noktasına gidemediği için biraz geri gelip öyle gidiyoruz p91 e
|
| 477 |
+
|
| 478 |
+
# Final movement: go to soft point
|
| 479 |
+
self.robot.MoveCart(soft_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 480 |
+
|
| 481 |
+
@handle_errors
|
| 482 |
+
def smol_calc(self, small_data: np.ndarray,sor_filter_enabled: bool = True):
|
| 483 |
+
# Rotate, filter, and move the point cloud to the origin reference
|
| 484 |
+
small = small_data
|
| 485 |
+
if config["save_point_clouds"]:
|
| 486 |
+
out_path = os.path.join(os.path.dirname(__file__), "Scan_Outputs", "small.ply")
|
| 487 |
+
o3d.io.write_point_cloud(out_path, self.small_pcd)
|
| 488 |
+
print(f"Small point cloud saved to {out_path}")
|
| 489 |
+
circle_fitter = CircleFitter(small)
|
| 490 |
+
|
| 491 |
+
(_, z_center_small, radius_small), self.small_fig, ax = circle_fitter.fit_circles_and_plot(
|
| 492 |
+
find_second_circle=False, val_x=0.20, val_z=0.2, delta_z=23, clc_metrics=False, name="SMALL"
|
| 493 |
+
)
|
| 494 |
+
# Save the plot before getting other measurements
|
| 495 |
+
save_figure(self.small_fig, "small_circles.png")
|
| 496 |
+
|
| 497 |
+
s_datum = circle_fitter.get_datum()
|
| 498 |
+
self.dist_3mm_s, _ = circle_fitter.get_distance(second_crc=False, z_distance_to_datum=23.1)
|
| 499 |
+
self.feature_3 = z_center_small - s_datum
|
| 500 |
+
self.radius_small = radius_small
|
| 501 |
+
self.z_center_small = z_center_small
|
| 502 |
+
|
| 503 |
+
if config["use_agg"]:
|
| 504 |
+
plt.close()
|
| 505 |
+
elif not config["use_agg"]:
|
| 506 |
+
plt.show()
|
| 507 |
+
|
| 508 |
+
print("smol_calc completed successfully.")
|
| 509 |
+
|
| 510 |
+
@handle_errors
|
| 511 |
+
def hor_calc(self, horizontal_data: np.ndarray, horizontal2_data: np.ndarray,sor_filter_enabled: bool = True):
|
| 512 |
+
# First, we make corrections on horizontal2_data
|
| 513 |
+
if sor_filter_enabled:
|
| 514 |
+
horizontal_data = sor_filter(horizontal_data, k=20, n_sigma=1.0)
|
| 515 |
+
horizontal2_data = sor_filter(horizontal2_data, k=20, n_sigma=1.0)
|
| 516 |
+
|
| 517 |
+
if config["save_point_clouds"]:
|
| 518 |
+
out_path2 = os.path.join(os.path.dirname(__file__), "Scan_Outputs", "horizontal2.ply")
|
| 519 |
+
self.pcd.points = o3d.utility.Vector3dVector(horizontal2_data)
|
| 520 |
+
o3d.io.write_point_cloud(out_path2, self.pcd)
|
| 521 |
+
print(f"Horizontal2 point cloud saved to {out_path2}")
|
| 522 |
+
|
| 523 |
+
out_path_pre = os.path.join(os.path.dirname(__file__), "Scan_Outputs", "horizontal_pre.ply")
|
| 524 |
+
self.pcd.points = o3d.utility.Vector3dVector(horizontal_data)
|
| 525 |
+
o3d.io.write_point_cloud(out_path_pre, self.pcd)
|
| 526 |
+
print(f"Horizontal pre point cloud saved to {out_path_pre}")
|
| 527 |
+
|
| 528 |
+
# Datum calculation
|
| 529 |
+
diff = np.abs(np.max(horizontal_data[:, 0]) - np.min(horizontal2_data[:, 0]))
|
| 530 |
+
datum_horizontal = np.max(horizontal_data[:, 0]) - diff
|
| 531 |
+
|
| 532 |
+
# Create line points and merge with point cloud
|
| 533 |
+
y_values = np.linspace(np.min(horizontal_data[:, 1]), np.max(horizontal_data[:, 1]), num=100)
|
| 534 |
+
line_points = np.array([[datum_horizontal, y, np.min(horizontal_data[:, 2])] for y in y_values])
|
| 535 |
+
augmented_pc = np.vstack((horizontal_data, line_points))
|
| 536 |
+
horizontal = self.rotate_point_cloud(augmented_pc, 90, "z")
|
| 537 |
+
horizontal = self.to_origin(horizontal)
|
| 538 |
+
self.horizontal = horizontal
|
| 539 |
+
self.l_40 = get_40(horizontal)
|
| 540 |
+
self.hor_pcd.points = o3d.utility.Vector3dVector(horizontal)
|
| 541 |
+
if config["save_point_clouds"]:
|
| 542 |
+
out_path_post = os.path.join(os.path.dirname(__file__), "Scan_Outputs", "horizontal_post.ply")
|
| 543 |
+
o3d.io.write_point_cloud(out_path_post, self.hor_pcd)
|
| 544 |
+
print(f"Horizontal post point cloud saved to {out_path_post}")
|
| 545 |
+
|
| 546 |
+
self.circle_fitter = CircleFitter(horizontal)
|
| 547 |
+
_,circle2, self.hor_fig, ax = self.circle_fitter.fit_circles_and_plot(clc_metrics=False, name="HORIZONTAL")
|
| 548 |
+
save_figure(self.hor_fig, "horizontal_circles.png")
|
| 549 |
+
|
| 550 |
+
self.dist_3mm_h = self.circle_fitter.get_distance()[0]
|
| 551 |
+
self.height = np.max(self.horizontal[:, 1]) - self.circle_fitter.get_datum()
|
| 552 |
+
self.feature_1 = circle2[1]
|
| 553 |
+
self.feature_2 = circle2[2]
|
| 554 |
+
|
| 555 |
+
if config["use_agg"]:
|
| 556 |
+
plt.close()
|
| 557 |
+
elif not config["use_agg"]:
|
| 558 |
+
plt.show()
|
| 559 |
+
|
| 560 |
+
print("hor_calc completed successfully.")
|
| 561 |
+
|
| 562 |
+
@handle_errors
|
| 563 |
+
def process_vertical_measurement(self, vertical_data: np.ndarray,sor_filter_enabled: bool = True):
|
| 564 |
+
# Process vertical data
|
| 565 |
+
# vertical = self.remove_gripper_points(vertical_data)
|
| 566 |
+
vertical = vertical_data
|
| 567 |
+
# if sor_filter_enabled:
|
| 568 |
+
# vertical = sor_filter(vertical, k=20, n_sigma=1.0)
|
| 569 |
+
# vertical = self.rotate_point_cloud(vertical, 180, "z")
|
| 570 |
+
# self.vert_pcd.points = o3d.utility.Vector3dVector(vertical)
|
| 571 |
+
if config["save_point_clouds"]:
|
| 572 |
+
out_path_vertical = os.path.join(os.path.dirname(__file__), "Scan_Outputs", "vertical.ply")
|
| 573 |
+
o3d.io.write_point_cloud(out_path_vertical, self.vert_pcd)
|
| 574 |
+
print(f"Vertical point cloud saved to {out_path_vertical}")
|
| 575 |
+
|
| 576 |
+
vertical_copy = self.to_origin(vertical.copy())
|
| 577 |
+
|
| 578 |
+
l_17_2, ok_17_2 = horn_diff(vertical_copy)
|
| 579 |
+
save_figure(plt, "vertical_horn_17_2.png")
|
| 580 |
+
if not config["use_agg"]:
|
| 581 |
+
plt.show()
|
| 582 |
+
plt.close()
|
| 583 |
+
|
| 584 |
+
l_23_4, ok_23_4 = horn_diff(vertical_copy, 240, 280)
|
| 585 |
+
save_figure(plt, "vertical_horn_23_4.png")
|
| 586 |
+
if not config["use_agg"]:
|
| 587 |
+
plt.show()
|
| 588 |
+
plt.close()
|
| 589 |
+
|
| 590 |
+
# Result calculations
|
| 591 |
+
B = self.circle_fitter.get_B()
|
| 592 |
+
b_trans_val = np.max(vertical[:, 1]) - np.max(self.horizontal[:, 2])
|
| 593 |
+
b_vertical = B + b_trans_val
|
| 594 |
+
_, _, r1, l_79_73 = slope(vertical, b_vertical)
|
| 595 |
+
save_figure(plt, "vertical_slope_1.png")
|
| 596 |
+
if not config["use_agg"]:
|
| 597 |
+
plt.show()
|
| 598 |
+
plt.close()
|
| 599 |
+
|
| 600 |
+
_, _, r2, _ = slope(vertical, y_divisor=0.11, crc_l=28)
|
| 601 |
+
save_figure(plt, "vertical_slope_2.png")
|
| 602 |
+
if not config["use_agg"]:
|
| 603 |
+
plt.show()
|
| 604 |
+
plt.close()
|
| 605 |
+
|
| 606 |
+
# median_value = np.median(vertical[:, 0])
|
| 607 |
+
# filtered_values = vertical[vertical[:, 0] == median_value]
|
| 608 |
+
l_42 = np.max(vertical[:, 1]) - b_vertical
|
| 609 |
+
l_248 = arm_horn_lengths(vertical, b_vertical)
|
| 610 |
+
mean_3mm = np.mean([self.dist_3mm_h, self.dist_3mm_s])
|
| 611 |
+
|
| 612 |
+
l_81_5,l_7_1 = filter_and_visualize_projection_with_ply(self.horizontal)
|
| 613 |
+
l_88_6 = l_81_5 + l_7_1
|
| 614 |
+
save_figure(plt, "vertical_projection.png")
|
| 615 |
+
if not config["use_agg"]:
|
| 616 |
+
plt.show()
|
| 617 |
+
plt.close()
|
| 618 |
+
|
| 619 |
+
vertical_results = {
|
| 620 |
+
"l_17_2": l_17_2,
|
| 621 |
+
"feature_2":self.feature_2,
|
| 622 |
+
"l_23_4": l_23_4,
|
| 623 |
+
"l_42": l_42,
|
| 624 |
+
"l_79_73": l_79_73,
|
| 625 |
+
"l_248": l_248,
|
| 626 |
+
"r1": (r1 - self.feature_2/2),
|
| 627 |
+
"r2": (r2 + self.feature_2/2),
|
| 628 |
+
"feature_1": self.feature_1,
|
| 629 |
+
"mean_3mm": mean_3mm,
|
| 630 |
+
"l_88_6": l_88_6,
|
| 631 |
+
"10_6":self.feature_3 - self.radius_small/2,
|
| 632 |
+
"l_40":self.l_40,
|
| 633 |
+
"23.1":self.feature_3,
|
| 634 |
+
"feature_4":self.radius_small,
|
| 635 |
+
"l_81_5": l_81_5,
|
| 636 |
+
"ok_17_2": ok_17_2
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
current_results = self.combine_results(vertical_results)
|
| 640 |
+
print("Vertical measurements processed successfully.")
|
| 641 |
+
return current_results
|
| 642 |
+
|
| 643 |
+
def after_scan(self,quality_check: int):
|
| 644 |
+
|
| 645 |
+
# Part drop operations
|
| 646 |
+
if config["pick"]:
|
| 647 |
+
print("Part drop operation started.")
|
| 648 |
+
if config["drop_object"]:
|
| 649 |
+
#Check whether the part quality is acceptable according to that drop it to metal detector or trash if put_back is False
|
| 650 |
+
if quality_check == 1:
|
| 651 |
+
drop_point = metal_detector
|
| 652 |
+
print("Part passed quality control, dropping to metal detector.")
|
| 653 |
+
else:
|
| 654 |
+
drop_point = trash
|
| 655 |
+
print("Part failed quality control, dropping to trash instead of metal detector.")
|
| 656 |
+
|
| 657 |
+
if config["put_back"] and drop_point == trash:
|
| 658 |
+
point = self.pick_point
|
| 659 |
+
soft_point = self.pick_soft_point
|
| 660 |
+
transit_vel = 60
|
| 661 |
+
|
| 662 |
+
self.robot.MoveCart(soft_point, 0, 0, vel=config["vel_mul"] * 100)
|
| 663 |
+
if point in right_of_robot_points and point["p_up"][0] > 300:
|
| 664 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 665 |
+
elif (point["p_up"][0] > 300) and (point in (left_of_robot_points+left_small)):
|
| 666 |
+
transit_vel = 50
|
| 667 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 668 |
+
|
| 669 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 670 |
+
self.robot.MoveCart(point["p"], 0, 0, vel=config["vel_mul"] * 50)
|
| 671 |
+
self.robot.WaitMs(500)
|
| 672 |
+
self.robot.SetDO(7, 0)
|
| 673 |
+
self.robot.WaitMs(1000)
|
| 674 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 675 |
+
|
| 676 |
+
if point in right_of_robot_points and point["p_up"][0] > 300:
|
| 677 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 678 |
+
elif (point["p_up"][0] > 300) and (point in (left_of_robot_points+left_small)):
|
| 679 |
+
transit_vel = 50
|
| 680 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 681 |
+
|
| 682 |
+
else: # If put_back is false or drop point is not trash, take the part to the band station and drop it at the metal_detector point
|
| 683 |
+
print("Going to band station.")
|
| 684 |
+
self.robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * 70)
|
| 685 |
+
# Piston and vacuum control steps for dropping to metal detector
|
| 686 |
+
self.robot.Mode(1)
|
| 687 |
+
self.robot.SetDO(1, 1) # mainflow on
|
| 688 |
+
self.robot.SetDO(0, 0) # Piston off
|
| 689 |
+
self.robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * 70)
|
| 690 |
+
|
| 691 |
+
index = read_current_point_index()
|
| 692 |
+
if index%2==1 and index<32:
|
| 693 |
+
value = 149
|
| 694 |
+
elif index<32 :
|
| 695 |
+
value = 148
|
| 696 |
+
if index%2==1 and index>=32:
|
| 697 |
+
value = 146
|
| 698 |
+
elif index>=32:
|
| 699 |
+
value = 148
|
| 700 |
+
|
| 701 |
+
preplace[1] = value
|
| 702 |
+
prepreplace[1] = value
|
| 703 |
+
place[1] = value
|
| 704 |
+
safeback[1] = value
|
| 705 |
+
if not self.current_di1_value:
|
| 706 |
+
self.robot.SetDO(3, 0) # Vacuum off
|
| 707 |
+
self.robot.SetDO(5, 0) # Rail open
|
| 708 |
+
self.robot.SetDO(2, 1) # Rail closed
|
| 709 |
+
self.robot.MoveCart(prepreplace, 0, 0, vel=config["vel_mul"] * 70)
|
| 710 |
+
self.robot.SetDO(0, 1) # Piston on
|
| 711 |
+
self.robot.MoveCart(preplace, 0, 0, vel=config["vel_mul"] * 35)
|
| 712 |
+
self.robot.SetDO(3, 1) # Vacuum on
|
| 713 |
+
self.robot.MoveCart(place, 0, 0, vel=config["vel_mul"] * 10)
|
| 714 |
+
self.robot.WaitMs(2000)
|
| 715 |
+
self.robot.SetDO(0, 0) # Piston off
|
| 716 |
+
self.robot.WaitMs(2000)
|
| 717 |
+
self.robot.SetDO(2, 0)
|
| 718 |
+
self.robot.SetDO(5, 1) #Rail
|
| 719 |
+
self.robot.WaitMs(2000)
|
| 720 |
+
else:
|
| 721 |
+
self.robot.MoveCart(prepreplace, 0, 0, vel=config["vel_mul"] * 70)
|
| 722 |
+
self.robot.MoveCart(preplace, 0, 0, vel=config["vel_mul"] * 35)
|
| 723 |
+
self.robot.MoveCart(place, 0, 0, vel=config["vel_mul"] * 10)
|
| 724 |
+
|
| 725 |
+
# self.robot.WaitMs(2000)
|
| 726 |
+
# self.robot.SetDO(7, 0) # Drop the part
|
| 727 |
+
# self.robot.WaitMs(1000)
|
| 728 |
+
# self.robot.MoveCart(safeback, 0, 0, vel=config["vel_mul"] * 35)
|
| 729 |
+
# self.robot.WaitMs(1000)
|
| 730 |
+
self.robot.SetDO(0, 1) # Piston on
|
| 731 |
+
self.robot.WaitMs(1000)
|
| 732 |
+
self.robot.SetDO(3, 0) # Vacuum off (piston vacuum)
|
| 733 |
+
self.robot.WaitMs(1000)
|
| 734 |
+
self.robot.SetDO(0, 0) # Piston off
|
| 735 |
+
self.robot.WaitMs(1000)
|
| 736 |
+
self.robot.SetDO(5, 0) # Rail open
|
| 737 |
+
self.robot.SetDO(2, 1) # Rail closed
|
| 738 |
+
self.robot.MoveCart(place, 0, 0, vel=config["vel_mul"] * 35)
|
| 739 |
+
self.robot.WaitMs(1000)
|
| 740 |
+
self.robot.SetDO(7, 1)
|
| 741 |
+
self.robot.WaitMs(1000)
|
| 742 |
+
self.robot.SetDO(0, 1) # Piston on
|
| 743 |
+
self.robot.MoveCart(preplace, 0, 0, vel=config["vel_mul"] * 35)
|
| 744 |
+
self.robot.SetDO(3, 1) # Vacuum on
|
| 745 |
+
self.robot.MoveCart(prepreplace, 0, 0, vel=config["vel_mul"] * 10)
|
| 746 |
+
self.robot.SetDO(0, 0) # Piston off
|
| 747 |
+
self.robot.WaitMs(2500)
|
| 748 |
+
self.robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * 80)
|
| 749 |
+
self.robot.SetDO(2, 0)
|
| 750 |
+
self.robot.SetDO(5, 1) #Rail
|
| 751 |
+
self.robot.Mode(0)
|
| 752 |
+
self.robot.WaitMs(500)
|
| 753 |
+
self.robot.MoveCart(p90, 0, 0, vel=config["vel_mul"] * 80)
|
| 754 |
+
self.robot.SetDO(13,1)
|
| 755 |
+
self.robot.MoveCart(metal_detector, 0, 0, vel=config["vel_mul"] * 80)
|
| 756 |
+
self.robot.MoveCart(post_metal_detector, 0, 0, vel=config["vel_mul"] * 70)
|
| 757 |
+
self.robot.WaitMs(500)
|
| 758 |
+
self.robot.SetDO(7, 0)
|
| 759 |
+
self.robot.WaitMs(500)
|
| 760 |
+
self.robot.MoveCart(metal_detector, 0, 0, vel=config["vel_mul"] * 80)
|
| 761 |
+
self.robot.SetDO(12,1)
|
| 762 |
+
self.robot.SetDO(13,0)
|
| 763 |
+
self.robot.MoveCart(p90, 0, 0, vel=config["vel_mul"] * 100)
|
| 764 |
+
|
| 765 |
+
print("Object dropped at appropriate drop point.")
|
| 766 |
+
elif config["put_back"] :
|
| 767 |
+
point = self.pick_point
|
| 768 |
+
soft_point = self.pick_soft_point
|
| 769 |
+
transit_vel = 60
|
| 770 |
+
|
| 771 |
+
self.robot.MoveCart(soft_point, 0, 0, vel=config["vel_mul"] * 60)
|
| 772 |
+
if point in right_of_robot_points and point["p_up"][0] > 300:
|
| 773 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 774 |
+
elif (point["p_up"][0] > 300) and (point in (left_of_robot_points+left_small)):
|
| 775 |
+
transit_vel = 50
|
| 776 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 777 |
+
|
| 778 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 779 |
+
self.robot.MoveCart(point["p"], 0, 0, vel=config["vel_mul"] * 50)
|
| 780 |
+
self.robot.WaitMs(500)
|
| 781 |
+
self.robot.SetDO(7, 0)
|
| 782 |
+
self.robot.WaitMs(1500)
|
| 783 |
+
self.robot.MoveCart(point["p_up"], 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 784 |
+
|
| 785 |
+
if point in right_of_robot_points and point["p_up"][0] > 300:
|
| 786 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 787 |
+
elif (point["p_up"][0] > 300) and (point in (left_of_robot_points+left_small)):
|
| 788 |
+
transit_vel = 50
|
| 789 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * transit_vel)
|
| 790 |
+
else:
|
| 791 |
+
print("Part drop setting disabled.")
|
| 792 |
+
|
| 793 |
+
def combine_results(self, vertical_results: dict) -> dict:
|
| 794 |
+
# Helper function to safely get values
|
| 795 |
+
def safe_get(dict_obj, key, default=None):
|
| 796 |
+
value = dict_obj.get(key, default)
|
| 797 |
+
# If a value is a dictionary, convert to string representation
|
| 798 |
+
if isinstance(value, dict):
|
| 799 |
+
# print(f"Warning: Dictionary value detected for {key}: {value}")
|
| 800 |
+
return str(value)
|
| 801 |
+
return value
|
| 802 |
+
|
| 803 |
+
results = {
|
| 804 |
+
"Feature1 (102.1)": safe_round(safe_get(vertical_results, "feature_1"), 3),
|
| 805 |
+
"Feature2 (25mm/2)": safe_round(safe_get(vertical_results,"feature_2"), 3),
|
| 806 |
+
"Feature3 (23.1)": safe_round(safe_get(vertical_results,"23.1"), 3),
|
| 807 |
+
"Feature4 (25mm/2)": safe_round(safe_get(vertical_results,"feature_4"), 3),
|
| 808 |
+
"Feature5 (L40)": safe_round(safe_get(vertical_results,"l_40"), 3),
|
| 809 |
+
"Feature6 (L248)": safe_round(safe_get(vertical_results, "l_248"), 3),
|
| 810 |
+
"Feature7 (L42)": safe_round(safe_get(vertical_results, "l_42"), 3),
|
| 811 |
+
"Feature8 (L79.73)": safe_round(safe_get(vertical_results, "l_79_73"), 3),
|
| 812 |
+
"Feature9 (R1-50)": safe_round(safe_get(vertical_results, "r1"), 3),
|
| 813 |
+
"Feature10 (R2-35)": safe_round(safe_get(vertical_results, "r2"), 3),
|
| 814 |
+
"Feature11 (3mm)": safe_round(safe_get(vertical_results, "mean_3mm"), 3),
|
| 815 |
+
"Feature12 (88.6)": safe_round(safe_get(vertical_results, "l_88_6"), 3),
|
| 816 |
+
"Feature13 (10.6)": safe_round(safe_get(vertical_results, "10_6"), 3),
|
| 817 |
+
"Feature14 (81.5)": safe_round(safe_get(vertical_results, "l_81_5"), 3),
|
| 818 |
+
"Feature15 (L23.4)": safe_round(safe_get(vertical_results, "l_23_4"), 3),
|
| 819 |
+
"Feature16 (L17.2)": safe_round(safe_get(vertical_results, "l_17_2"), 3),
|
| 820 |
+
"Feature17 (2C)": safe_round(safe_get(vertical_results, "ok_17_2"), 3)
|
| 821 |
+
}
|
| 822 |
+
|
| 823 |
+
# Ensure all values are serializable
|
| 824 |
+
for key, value in results.items():
|
| 825 |
+
try:
|
| 826 |
+
# For testing, json.dumps
|
| 827 |
+
json.dumps(value)
|
| 828 |
+
except (TypeError, OverflowError):
|
| 829 |
+
print(f"Non-serializable value found: {key} = {value}")
|
| 830 |
+
results[key] = str(value)
|
| 831 |
+
|
| 832 |
+
return results
|
| 833 |
+
|
| 834 |
+
def run_scan_cycle(self):
|
| 835 |
+
print("Başladı run scan")
|
| 836 |
+
ROBOT_POSITIONS = config["robot_positions"]
|
| 837 |
+
self.robot.SetDO(3, 1) # Vacuum on
|
| 838 |
+
self.robot.SetDO(0,0) #
|
| 839 |
+
self.robot.SetDO(1, 1) #
|
| 840 |
+
self.robot.SetDO(13,0) #Stop metal detector band
|
| 841 |
+
|
| 842 |
+
# Initialize group info
|
| 843 |
+
self.current_group, self.group_indices = 0, set() #self.get_current_group_info()
|
| 844 |
+
|
| 845 |
+
if self.robot_tcp[0] >= 300:
|
| 846 |
+
if self.robot_tcp[1] >= 0:
|
| 847 |
+
print("Robot is on the right side", self.robot_tcp[0])
|
| 848 |
+
self.robot.MoveCart(right_transit_point, 0, 0, vel=config["vel_mul"] * 60)
|
| 849 |
+
self.robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * 60)
|
| 850 |
+
else:
|
| 851 |
+
print("Robot is on the left side", self.robot_tcp[0])
|
| 852 |
+
self.robot.MoveCart(left_transit_point, 0, 0, vel=config["vel_mul"] * 60)
|
| 853 |
+
self.robot.MoveCart(p90, 0, 0, vel=config["vel_mul"] * 60)
|
| 854 |
+
else:
|
| 855 |
+
if self.robot_tcp[1] >= 0:
|
| 856 |
+
print("Robot is on the right side", self.robot_tcp[0])
|
| 857 |
+
self.robot.MoveCart(p91, 0, 0, vel=config["vel_mul"] * 60)
|
| 858 |
+
else:
|
| 859 |
+
print("Robot is on the left side", self.robot_tcp[0])
|
| 860 |
+
self.robot.MoveCart(p90, 0, 0, vel=config["vel_mul"] * 60)
|
| 861 |
+
|
| 862 |
+
self.cycle = 0
|
| 863 |
+
while self.cycle < config["range_"]:
|
| 864 |
+
start_time = time.time()
|
| 865 |
+
|
| 866 |
+
# Reset rescan counter at the beginning of each cycle
|
| 867 |
+
self.rescan = 0
|
| 868 |
+
|
| 869 |
+
current_index = read_current_point_index()
|
| 870 |
+
if current_index in config["ignored_points"]:
|
| 871 |
+
current_index = self.get_next_valid_index(current_index, len(self.points))
|
| 872 |
+
write_current_point_index(current_index)
|
| 873 |
+
|
| 874 |
+
if self.cycle != 0:
|
| 875 |
+
self.old_point = self.points[current_index]
|
| 876 |
+
current_index = self.get_next_valid_index(current_index, len(self.points))
|
| 877 |
+
write_current_point_index(current_index)
|
| 878 |
+
|
| 879 |
+
# Scan attempt loop - separate from cycle loop
|
| 880 |
+
scan_successful = False
|
| 881 |
+
selected_results = {}
|
| 882 |
+
attempt_results = []
|
| 883 |
+
|
| 884 |
+
while not scan_successful and self.rescan <= config["max_rescan"]:
|
| 885 |
+
try:
|
| 886 |
+
print(f"Scan attempt {self.rescan + 1}/{config['max_rescan'] + 1}")
|
| 887 |
+
|
| 888 |
+
# Only pick object on first attempt of each cycle
|
| 889 |
+
if config["pick"] and self.rescan == 0:
|
| 890 |
+
if current_index < len(left_of_robot_points + left_small):
|
| 891 |
+
soft_point = p90
|
| 892 |
+
else:
|
| 893 |
+
soft_point = p91
|
| 894 |
+
|
| 895 |
+
if config["same_place_index"] != -1:
|
| 896 |
+
point = self.points[config["same_place_index"]]
|
| 897 |
+
else:
|
| 898 |
+
point = self.points[current_index]
|
| 899 |
+
|
| 900 |
+
self.pick_point = point
|
| 901 |
+
self.pick_soft_point = soft_point
|
| 902 |
+
self.pick_left_transit_point = left_transit_point
|
| 903 |
+
print("Picking object...")
|
| 904 |
+
self.pick_object(point, soft_point)
|
| 905 |
+
print("Object picked.")
|
| 906 |
+
# Move to scan position
|
| 907 |
+
self.robot.MoveCart(ROBOT_POSITIONS['scrc'], 0, 0, vel=config["vel_mul"] * 100)
|
| 908 |
+
|
| 909 |
+
# Perform scans
|
| 910 |
+
small_data = self.mech_eye.main(lua_name="small.lua", scan_line_count=1500)
|
| 911 |
+
print(small_data.shape)
|
| 912 |
+
if config["use_agg"]:
|
| 913 |
+
thread_small = threading.Thread(target=self.smol_calc, args=(small_data,))
|
| 914 |
+
thread_small.start()
|
| 915 |
+
else:
|
| 916 |
+
self.smol_calc(small_data)
|
| 917 |
+
plt.show()
|
| 918 |
+
|
| 919 |
+
horizontal_data = self.mech_eye.main(lua_name="horizontal.lua", scan_line_count=1500)
|
| 920 |
+
horizontal2_data = self.mech_eye.main(lua_name="horizontal2.lua", scan_line_count=1500)
|
| 921 |
+
if config["use_agg"]:
|
| 922 |
+
thread_horizontal = threading.Thread(target=self.hor_calc, args=(horizontal_data, horizontal2_data))
|
| 923 |
+
thread_horizontal.start()
|
| 924 |
+
else:
|
| 925 |
+
self.hor_calc(horizontal_data, horizontal2_data)
|
| 926 |
+
plt.show()
|
| 927 |
+
|
| 928 |
+
vertical_data = self.mech_eye.main(lua_name="vertical.lua", scan_line_count=4000)
|
| 929 |
+
plt.show()
|
| 930 |
+
|
| 931 |
+
if config["use_agg"]:
|
| 932 |
+
thread_small.join()
|
| 933 |
+
thread_horizontal.join()
|
| 934 |
+
|
| 935 |
+
current_results = self.process_vertical_measurement(vertical_data)
|
| 936 |
+
attempt_results.append(current_results.copy())
|
| 937 |
+
|
| 938 |
+
quality_check_result = self.check_part_quality(current_results)
|
| 939 |
+
is_valid_measurement = quality_check_result in [True, False]
|
| 940 |
+
if not is_valid_measurement:
|
| 941 |
+
print("Initial quality check is deviated (noise). Retaking measurements...",quality_check_result)
|
| 942 |
+
thread_small = threading.Thread(target=self.smol_calc, args=(small_data,))
|
| 943 |
+
thread_small.start()
|
| 944 |
+
thread_horizontal = threading.Thread(target=self.hor_calc, args=(horizontal_data, horizontal2_data))
|
| 945 |
+
thread_horizontal.start()
|
| 946 |
+
current_results = self.process_vertical_measurement(vertical_data)
|
| 947 |
+
attempt_results.append(current_results.copy())
|
| 948 |
+
|
| 949 |
+
quality_check_result = self.check_part_quality(current_results)
|
| 950 |
+
is_valid_measurement = quality_check_result in [True, False]
|
| 951 |
+
|
| 952 |
+
quality_check = True if quality_check_result == True else False
|
| 953 |
+
|
| 954 |
+
# Determine if scan should be repeated
|
| 955 |
+
if not is_valid_measurement:
|
| 956 |
+
print(f"Invalid measurement detected (noise). Attempt {self.rescan + 1}")
|
| 957 |
+
if self.rescan < config["max_rescan"]:
|
| 958 |
+
self.rescan += 1
|
| 959 |
+
continue # Continue scan attempt loop
|
| 960 |
+
else:
|
| 961 |
+
print("Max rescan attempts reached. Using last measurement...")
|
| 962 |
+
scan_successful = True
|
| 963 |
+
|
| 964 |
+
elif not quality_check:
|
| 965 |
+
print(f"Quality check failed. Attempt {self.rescan + 1}")
|
| 966 |
+
if self.rescan < config["max_rescan"]:
|
| 967 |
+
self.rescan += 1
|
| 968 |
+
continue # Continue scan attempt loop
|
| 969 |
+
else:
|
| 970 |
+
print("Max rescan attempts reached. Continuing...")
|
| 971 |
+
scan_successful = True
|
| 972 |
+
else:
|
| 973 |
+
# Scan successful
|
| 974 |
+
print("Scan successful!")
|
| 975 |
+
scan_successful = True
|
| 976 |
+
|
| 977 |
+
except Exception as e:
|
| 978 |
+
print(f"Error during scan attempt {self.rescan + 1}: {e}")
|
| 979 |
+
current_results = {"Error": str(e)}
|
| 980 |
+
attempt_results.append(current_results.copy())
|
| 981 |
+
|
| 982 |
+
if self.rescan < config["max_rescan"]:
|
| 983 |
+
self.rescan += 1
|
| 984 |
+
print(f"Retrying due to error... Attempt {self.rescan + 1}")
|
| 985 |
+
continue
|
| 986 |
+
else:
|
| 987 |
+
print("Max rescan attempts reached after error. Continuing...")
|
| 988 |
+
scan_successful = True
|
| 989 |
+
|
| 990 |
+
# Select best result from attempts
|
| 991 |
+
valid_results = []
|
| 992 |
+
for result in attempt_results:
|
| 993 |
+
if "Error" not in result:
|
| 994 |
+
test_quality = self.check_part_quality(result)
|
| 995 |
+
if test_quality in [True, False]:
|
| 996 |
+
valid_results.append(result)
|
| 997 |
+
|
| 998 |
+
if valid_results:
|
| 999 |
+
selected_results = valid_results[-1]
|
| 1000 |
+
final_quality_check = self.check_part_quality(selected_results) == True
|
| 1001 |
+
print("Using last valid measurement from attempts.")
|
| 1002 |
+
else:
|
| 1003 |
+
selected_results = attempt_results[-1] if attempt_results else {"Error": "No measurements obtained"}
|
| 1004 |
+
final_quality_check = False
|
| 1005 |
+
print("No valid measurements found. Using last measurement.")
|
| 1006 |
+
|
| 1007 |
+
# Finalize results
|
| 1008 |
+
self.cycle += 1
|
| 1009 |
+
selected_results["Index"] = read_current_point_index()
|
| 1010 |
+
selected_results["OK"] = "1" if final_quality_check else "0"
|
| 1011 |
+
|
| 1012 |
+
if selected_results["OK"] == "0" : # If part is not OK, save point clouds for review
|
| 1013 |
+
out_dir = os.path.join(os.path.dirname(__file__), "Scan_Outputs")
|
| 1014 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 1015 |
+
|
| 1016 |
+
pcd_dict = {
|
| 1017 |
+
"horizontal.ply": self.hor_pcd,
|
| 1018 |
+
"small.ply": self.small_pcd,
|
| 1019 |
+
"vertical.ply": self.vert_pcd
|
| 1020 |
+
}
|
| 1021 |
+
|
| 1022 |
+
for filename, pcd in pcd_dict.items():
|
| 1023 |
+
index_filename = f"{os.path.splitext(filename)[0]}_{selected_results['Index']}.ply"
|
| 1024 |
+
out_path = os.path.join(out_dir, index_filename)
|
| 1025 |
+
o3d.io.write_point_cloud(out_path, pcd)
|
| 1026 |
+
print(f"Point cloud saved to {out_path}")
|
| 1027 |
+
|
| 1028 |
+
# Save figures if save_figures is False
|
| 1029 |
+
if not config["save_figures"]:
|
| 1030 |
+
save_figure(self.hor_fig, f"horizontal_circles_{selected_results['Index']}.png")
|
| 1031 |
+
save_figure(self.small_fig, f"small_circles_{selected_results['Index']}.png")
|
| 1032 |
+
|
| 1033 |
+
|
| 1034 |
+
# Group management
|
| 1035 |
+
current_index = read_current_point_index()
|
| 1036 |
+
if current_index not in self.group_indices:
|
| 1037 |
+
self.group_indices.add(current_index)
|
| 1038 |
+
if len(self.group_indices) >= 64:
|
| 1039 |
+
self.current_group += 1
|
| 1040 |
+
self.group_indices = {current_index}
|
| 1041 |
+
|
| 1042 |
+
# Save to database
|
| 1043 |
+
if config["save_to_db"]:
|
| 1044 |
+
try:
|
| 1045 |
+
print("Writing results to database...")
|
| 1046 |
+
# self.write_to_db(selected_results, iteration=read_current_point_index(), group_number=self.current_group)
|
| 1047 |
+
print("Results written to database successfully.")
|
| 1048 |
+
except Exception as e:
|
| 1049 |
+
print(f"Database write error: {e}")
|
| 1050 |
+
|
| 1051 |
+
selected_results["Processing Time (s)"] = time.time() - start_time
|
| 1052 |
+
|
| 1053 |
+
# Cleanup and save results
|
| 1054 |
+
attempt_results.clear()
|
| 1055 |
+
|
| 1056 |
+
if config["use_agg"]:
|
| 1057 |
+
plt.close("all")
|
| 1058 |
+
|
| 1059 |
+
if "Error" in selected_results or "Index" in selected_results:
|
| 1060 |
+
try:
|
| 1061 |
+
with open('jsons/scan_output.json', 'a') as f:
|
| 1062 |
+
f.write(json.dumps(selected_results) + '\n')
|
| 1063 |
+
except Exception as e:
|
| 1064 |
+
print(f"Error writing to output file: {e}")
|
| 1065 |
+
|
| 1066 |
+
# After scan operations
|
| 1067 |
+
try:
|
| 1068 |
+
self.after_scan(final_quality_check)
|
| 1069 |
+
except Exception as e:
|
| 1070 |
+
print(f"Error in after_scan: {e}")
|
| 1071 |
+
|
| 1072 |
+
if __name__ == "__main__":
|
| 1073 |
+
try:
|
| 1074 |
+
print("Starting Jaguar Scanner...")
|
| 1075 |
+
scanner = JaguarScanner(vel_mul=config["vel_mul"])
|
| 1076 |
+
scanner.run_scan_cycle()
|
| 1077 |
+
print("Scan cycle completed successfully")
|
| 1078 |
+
except KeyboardInterrupt:
|
| 1079 |
+
print("Scan interrupted by user")
|
| 1080 |
+
sys.exit(0)
|
| 1081 |
+
except Exception as e:
|
| 1082 |
+
import traceback
|
| 1083 |
+
error_details = traceback.format_exc()
|
| 1084 |
+
print(f"MAIN PROCESS ERROR: {e}")
|
| 1085 |
+
print(f"FULL TRACEBACK:\n{error_details}")
|
| 1086 |
+
sys.exit(1)
|
MecheyePackage/ws_robot_state.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import threading
|
| 3 |
+
import websocket
|
| 4 |
+
import time
|
| 5 |
+
from MecheyePackage.robot_control import login
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
class WebSocketManager:
|
| 11 |
+
def __init__(self, url="ws://127.0.0.1:9999/"):
|
| 12 |
+
self.connection_status = 0 # 0: kapalı, 1: açık
|
| 13 |
+
self.socket_error = False
|
| 14 |
+
self.logout_flag = False
|
| 15 |
+
|
| 16 |
+
self.ws_instance = None
|
| 17 |
+
self.url = url
|
| 18 |
+
self.cookies = None
|
| 19 |
+
|
| 20 |
+
self.reconnect_timer = None
|
| 21 |
+
self.reconnect_interval = None
|
| 22 |
+
self.retry_count = 0
|
| 23 |
+
self.max_retries = 5
|
| 24 |
+
self.base_retry_delay = 0.5
|
| 25 |
+
|
| 26 |
+
self.lock = threading.Lock()
|
| 27 |
+
|
| 28 |
+
self.di_values = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,] # DI0-DI15
|
| 29 |
+
self.tcp = [3, 3, 3, 3, 3, 3] # x,y,z,rx,ry,rz
|
| 30 |
+
|
| 31 |
+
self.mode = 1
|
| 32 |
+
|
| 33 |
+
def clear_timers(self):
|
| 34 |
+
if self.reconnect_timer:
|
| 35 |
+
self.reconnect_timer.cancel()
|
| 36 |
+
self.reconnect_timer = None
|
| 37 |
+
if self.reconnect_interval:
|
| 38 |
+
self.reconnect_interval.cancel()
|
| 39 |
+
self.reconnect_interval = None
|
| 40 |
+
|
| 41 |
+
def on_message(self, ws, message):
|
| 42 |
+
try:
|
| 43 |
+
data = json.loads(message)
|
| 44 |
+
|
| 45 |
+
if message == 'websocket close':
|
| 46 |
+
logger.warning("Sunucu logout mesajı gönderdi")
|
| 47 |
+
self.logout_flag = True
|
| 48 |
+
self.connection_status = 0
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
if not isinstance(data, dict):
|
| 52 |
+
logger.warning("Geçersiz mesaj formatı, logout yapılıyor")
|
| 53 |
+
self.logout_flag = True
|
| 54 |
+
self.connection_status = 0
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
with self.lock:
|
| 58 |
+
if "cl_di" in data:
|
| 59 |
+
self.di_values[0] = data["cl_di"][0]
|
| 60 |
+
self.di_values[1] = data["cl_di"][1]
|
| 61 |
+
self.di_values[2] = data["cl_di"][2]
|
| 62 |
+
self.di_values[3] = data["cl_di"][3]
|
| 63 |
+
self.di_values[4] = data["cl_di"][4]
|
| 64 |
+
self.di_values[5] = data["cl_di"][5]
|
| 65 |
+
self.di_values[6] = data["cl_di"][6]
|
| 66 |
+
self.di_values[7] = data["cl_di"][7]
|
| 67 |
+
self.di_values[8] = data["cl_di"][8]
|
| 68 |
+
self.di_values[9] = data["cl_di"][9]
|
| 69 |
+
self.di_values[10] = data["cl_di"][10]
|
| 70 |
+
self.di_values[11] = data["cl_di"][11]
|
| 71 |
+
self.di_values[12] = data["cl_di"][12]
|
| 72 |
+
self.di_values[13] = data["cl_di"][13]
|
| 73 |
+
self.di_values[14] = 1-int(data["cl_di"][14])
|
| 74 |
+
self.di_values[15] = 1-int(data["cl_di"][15])
|
| 75 |
+
|
| 76 |
+
if "tcp" in data:
|
| 77 |
+
self.tcp = data["tcp"]
|
| 78 |
+
|
| 79 |
+
if "mode" in data:
|
| 80 |
+
self.mode = data["mode"]
|
| 81 |
+
|
| 82 |
+
self.connection_status = 1
|
| 83 |
+
self.logout_flag = False
|
| 84 |
+
self.retry_count = 0
|
| 85 |
+
|
| 86 |
+
except json.JSONDecodeError as e:
|
| 87 |
+
logger.error(f"JSON parse hatası: {e}")
|
| 88 |
+
except Exception as e:
|
| 89 |
+
logger.error(f"Mesaj işleme hatası: {e}")
|
| 90 |
+
|
| 91 |
+
def on_error(self, ws, error):
|
| 92 |
+
|
| 93 |
+
with self.lock:
|
| 94 |
+
self.socket_error = True
|
| 95 |
+
self.connection_status = 0
|
| 96 |
+
logger.error(f"WebSocket hatası: {error}")
|
| 97 |
+
|
| 98 |
+
def on_close(self, ws, close_status_code, close_msg):
|
| 99 |
+
|
| 100 |
+
with self.lock:
|
| 101 |
+
self.connection_status = 0
|
| 102 |
+
logger.warning(f"Bağlantı kapandı - Status: {close_status_code}, Mesaj: {close_msg}")
|
| 103 |
+
self.clear_timers()
|
| 104 |
+
if not self.logout_flag:
|
| 105 |
+
self._schedule_reconnect()
|
| 106 |
+
|
| 107 |
+
def on_open(self, ws):
|
| 108 |
+
with self.lock:
|
| 109 |
+
self.socket_error = False
|
| 110 |
+
self.connection_status = 1
|
| 111 |
+
self.retry_count = 0
|
| 112 |
+
logger.info("WebSocket bağlantısı açıldı")
|
| 113 |
+
self.clear_timers()
|
| 114 |
+
|
| 115 |
+
def _schedule_reconnect(self):
|
| 116 |
+
if self.retry_count >= self.max_retries:
|
| 117 |
+
logger.error(f"Maksimum deneme sayısına ulaşıldı ({self.max_retries})")
|
| 118 |
+
return
|
| 119 |
+
|
| 120 |
+
delay = self.base_retry_delay * (2 ** self.retry_count)
|
| 121 |
+
delay = min(delay, 30)
|
| 122 |
+
logger.info(f"Yeniden bağlanma {delay} saniye sonra denenecek (deneme: {self.retry_count + 1})")
|
| 123 |
+
|
| 124 |
+
self.reconnect_timer = threading.Timer(delay, self._attempt_reconnect)
|
| 125 |
+
self.reconnect_timer.start()
|
| 126 |
+
|
| 127 |
+
def _attempt_reconnect(self):
|
| 128 |
+
|
| 129 |
+
if self.logout_flag:
|
| 130 |
+
logger.info("Manuel kapanma, yeniden bağlanma iptal edildi")
|
| 131 |
+
return
|
| 132 |
+
|
| 133 |
+
with self.lock:
|
| 134 |
+
self.retry_count += 1
|
| 135 |
+
|
| 136 |
+
logger.info(f"Yeniden bağlanma denemesi: {self.retry_count}")
|
| 137 |
+
|
| 138 |
+
try:
|
| 139 |
+
self._close_connection()
|
| 140 |
+
time.sleep(0.1)
|
| 141 |
+
|
| 142 |
+
logger.info("Yeni login yapılıyor...")
|
| 143 |
+
self.cookies, _ = login()
|
| 144 |
+
self._create_connection()
|
| 145 |
+
|
| 146 |
+
except Exception as e:
|
| 147 |
+
logger.error(f"Yeniden bağlanma hatası: {e}")
|
| 148 |
+
if not self.logout_flag:
|
| 149 |
+
self._schedule_reconnect()
|
| 150 |
+
|
| 151 |
+
def _close_connection(self):
|
| 152 |
+
if self.ws_instance:
|
| 153 |
+
try:
|
| 154 |
+
self.ws_instance.close()
|
| 155 |
+
logger.info("Önceki WebSocket bağlantısı kapatıldı")
|
| 156 |
+
except Exception as e:
|
| 157 |
+
logger.warning(f"Bağlantı kapatılırken hata: {e}")
|
| 158 |
+
finally:
|
| 159 |
+
self.ws_instance = None
|
| 160 |
+
|
| 161 |
+
def _create_connection(self):
|
| 162 |
+
if not self.cookies:
|
| 163 |
+
raise Exception("Cookie alınamadı")
|
| 164 |
+
|
| 165 |
+
cookie_header = "; ".join(f"{k}={v}" for k, v in self.cookies.items())
|
| 166 |
+
|
| 167 |
+
self.ws_instance = websocket.WebSocketApp(
|
| 168 |
+
self.url,
|
| 169 |
+
header={"Cookie": cookie_header},
|
| 170 |
+
on_message=self.on_message,
|
| 171 |
+
on_error=self.on_error,
|
| 172 |
+
on_close=self.on_close,
|
| 173 |
+
on_open=self.on_open
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
thread = threading.Thread(
|
| 177 |
+
target=self.ws_instance.run_forever,
|
| 178 |
+
kwargs={"ping_interval": None, "ping_timeout": None}
|
| 179 |
+
)
|
| 180 |
+
thread.daemon = True
|
| 181 |
+
thread.start()
|
| 182 |
+
|
| 183 |
+
def connect(self):
|
| 184 |
+
|
| 185 |
+
with self.lock:
|
| 186 |
+
if self.connection_status == 1:
|
| 187 |
+
logger.info("Zaten bağlı durumda")
|
| 188 |
+
return True
|
| 189 |
+
|
| 190 |
+
self.logout_flag = False
|
| 191 |
+
self.socket_error = False
|
| 192 |
+
self.retry_count = 0
|
| 193 |
+
|
| 194 |
+
try:
|
| 195 |
+
logger.info("Login yapılıyor...")
|
| 196 |
+
self.cookies, _ = login()
|
| 197 |
+
self._create_connection()
|
| 198 |
+
return True
|
| 199 |
+
|
| 200 |
+
except Exception as e:
|
| 201 |
+
logger.error(f"Bağlantı hatası ws_robot_state: {e}")
|
| 202 |
+
return False
|
| 203 |
+
|
| 204 |
+
def disconnect(self):
|
| 205 |
+
with self.lock:
|
| 206 |
+
self.logout_flag = True
|
| 207 |
+
self.connection_status = 0
|
| 208 |
+
|
| 209 |
+
self.clear_timers()
|
| 210 |
+
self._close_connection()
|
| 211 |
+
logger.info("WebSocket bağlantısı manuel olarak kesildi")
|
| 212 |
+
|
| 213 |
+
def is_connected(self):
|
| 214 |
+
with self.lock:
|
| 215 |
+
return self.connection_status == 1
|
| 216 |
+
|
| 217 |
+
def get_robot_state(self):
|
| 218 |
+
with self.lock:
|
| 219 |
+
return {
|
| 220 |
+
"di_values": self.di_values,
|
| 221 |
+
"tcp": self.tcp,
|
| 222 |
+
"mode": self.mode,
|
| 223 |
+
"connection_status": self.connection_status,
|
| 224 |
+
"socket_error": self.socket_error
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
# Global instance
|
| 228 |
+
ws_manager = WebSocketManager()
|
| 229 |
+
|
| 230 |
+
# Backward compatibility fonksiyonları
|
| 231 |
+
def initialize_websocket():
|
| 232 |
+
return ws_manager.connect()
|
| 233 |
+
|
| 234 |
+
def start_websocket():
|
| 235 |
+
return ws_manager.connect()
|
| 236 |
+
|
| 237 |
+
def get_di_values():
|
| 238 |
+
return ws_manager.di_values
|
| 239 |
+
|
| 240 |
+
def get_tcp():
|
| 241 |
+
return ws_manager.tcp
|
| 242 |
+
|
| 243 |
+
def get_mode():
|
| 244 |
+
return ws_manager.mode
|
README.md
CHANGED
|
@@ -1,11 +1,11 @@
|
|
| 1 |
---
|
| 2 |
title: Jaguar Project
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
-
short_description: 3D
|
| 9 |
---
|
| 10 |
|
| 11 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
title: Jaguar Project
|
| 3 |
+
emoji: 💻
|
| 4 |
+
colorFrom: pink
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: docker
|
| 7 |
pinned: false
|
| 8 |
+
short_description: 3D Pointcloud based measurement system
|
| 9 |
---
|
| 10 |
|
| 11 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
__init__.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# __init__.py
|
| 2 |
+
from flask import Flask
|
| 3 |
+
from flask import send_from_directory
|
| 4 |
+
import os
|
| 5 |
+
from flask_cors import CORS
|
| 6 |
+
from flask_socketio import SocketIO
|
| 7 |
+
from config import Config
|
| 8 |
+
import sentry_sdk
|
| 9 |
+
from sentry_sdk.integrations.flask import FlaskIntegration
|
| 10 |
+
|
| 11 |
+
# Blueprint'leri import et
|
| 12 |
+
from routes.scan_routes import scan_bp
|
| 13 |
+
from routes.health_routes import health_bp
|
| 14 |
+
from routes.robot_routes import robot_bp
|
| 15 |
+
|
| 16 |
+
# Robot servisini import et
|
| 17 |
+
from services.robot_service import start_robot_service, set_status_callback
|
| 18 |
+
|
| 19 |
+
import atexit
|
| 20 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 21 |
+
import eventlet
|
| 22 |
+
eventlet.monkey_patch()
|
| 23 |
+
|
| 24 |
+
MAX_LOG_LINES = 1000 # Maksimum tutulacak satır sayısı
|
| 25 |
+
|
| 26 |
+
def trim_log_file():
|
| 27 |
+
try:
|
| 28 |
+
with open(Config.LOG_FILE, 'r') as f:
|
| 29 |
+
lines = f.readlines()
|
| 30 |
+
if len(lines) > MAX_LOG_LINES:
|
| 31 |
+
with open(Config.LOG_FILE, 'w') as f:
|
| 32 |
+
f.writelines(lines[-MAX_LOG_LINES:])
|
| 33 |
+
print(f"[LOG] Log dosyası budandı ({len(lines)} satır → {MAX_LOG_LINES})")
|
| 34 |
+
except Exception as e:
|
| 35 |
+
print(f"[ERROR] Log budama hatası: {e}")
|
| 36 |
+
|
| 37 |
+
# Scheduler başlat
|
| 38 |
+
scheduler = BackgroundScheduler()
|
| 39 |
+
scheduler.add_job(func=trim_log_file, trigger="interval", minutes=5)
|
| 40 |
+
scheduler.start()
|
| 41 |
+
|
| 42 |
+
# Uygulama kapanırken scheduler’ı durdur
|
| 43 |
+
atexit.register(lambda: scheduler.shutdown())
|
| 44 |
+
|
| 45 |
+
# SocketIO objesi global
|
| 46 |
+
socketio = SocketIO(cors_allowed_origins="*", async_mode='eventlet')
|
| 47 |
+
|
| 48 |
+
def create_app():
|
| 49 |
+
# Initialize Sentry SDK before creating Flask app
|
| 50 |
+
# sentry_sdk.init(
|
| 51 |
+
# dsn="http://05fa900e3706431f9e40608fc7b5f3dc@glitchtip.mndiz.corp/4",
|
| 52 |
+
# # Add data like request headers and IP for users
|
| 53 |
+
# send_default_pii=True,
|
| 54 |
+
# # Enable Flask integration
|
| 55 |
+
# integrations=[FlaskIntegration()],
|
| 56 |
+
# # Set traces_sample_rate to 1.0 to capture 100% of transactions for performance monitoring
|
| 57 |
+
# # We recommend adjusting this value in production
|
| 58 |
+
# traces_sample_rate=2.0,
|
| 59 |
+
# )
|
| 60 |
+
|
| 61 |
+
app = Flask(__name__,static_folder="static/react/static",template_folder="static/react")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
CORS(app)
|
| 65 |
+
|
| 66 |
+
# Blueprint'leri kaydet
|
| 67 |
+
app.register_blueprint(scan_bp)
|
| 68 |
+
app.register_blueprint(robot_bp)
|
| 69 |
+
app.register_blueprint(health_bp)
|
| 70 |
+
|
| 71 |
+
@app.route("/", defaults={"path": ""})
|
| 72 |
+
@app.route("/<path:path>")
|
| 73 |
+
def serve(path):
|
| 74 |
+
if path != "" and os.path.exists(os.path.join(app.static_folder, path)):
|
| 75 |
+
return send_from_directory(app.static_folder, path)
|
| 76 |
+
else:
|
| 77 |
+
return send_from_directory(app.template_folder, "index.html")
|
| 78 |
+
# SocketIO'yu init et
|
| 79 |
+
socketio.init_app(app)
|
| 80 |
+
|
| 81 |
+
# Robot servisi için callback fonksiyonunu ayarla
|
| 82 |
+
def emit_robot_data(event_name, data):
|
| 83 |
+
"""Robot verilerini SocketIO ile yayınla"""
|
| 84 |
+
socketio.emit(event_name, data)
|
| 85 |
+
|
| 86 |
+
# Callback'i robot servisine kaydet
|
| 87 |
+
set_status_callback(emit_robot_data)
|
| 88 |
+
|
| 89 |
+
# Robot servisini başlat (bağımsız thread'lerde)
|
| 90 |
+
start_robot_service()
|
| 91 |
+
|
| 92 |
+
return app, socketio
|
config.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# config.py
|
| 2 |
+
import os
|
| 3 |
+
from dotenv import load_dotenv
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
load_dotenv() # .env dosyasını yükler
|
| 7 |
+
|
| 8 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 9 |
+
|
| 10 |
+
class Config:
|
| 11 |
+
HOST = os.getenv("HOST", "0.0.0.0")
|
| 12 |
+
PORT = int(os.getenv("PORT", 7860))
|
| 13 |
+
DEBUG = os.getenv("DEBUG", "false").lower() == "false"
|
| 14 |
+
LOG_FILE = str(BASE_DIR / "scan_process.log")
|
| 15 |
+
SCAN_OUTPUTS = str(BASE_DIR / "jsons/scan_output.json")
|
| 16 |
+
MAX_RETRIES = int(os.getenv("MAX_RETRIES", 10))
|
| 17 |
+
ROBOT_TIMEOUT = float(os.getenv("ROBOT_TIMEOUT", 2.0))
|
| 18 |
+
SOCKET_PING_INTERVAL = int(os.getenv("SOCKET_PING_INTERVAL", 1))
|
| 19 |
+
SOCKET_PING_TIMEOUT = int(os.getenv("SOCKET_PING_TIMEOUT", 5))
|
| 20 |
+
# Database configuration
|
| 21 |
+
DB_HOST = os.getenv("DB_HOST", "1.1.1.1")
|
| 22 |
+
DB_USER = os.getenv("DB_USER", "cobot_dbuser")
|
| 23 |
+
DB_PASSWORD = os.getenv("DB_PASSWORD", "0")
|
| 24 |
+
DB_NAME = os.getenv("DB_NAME", "cobot")
|
| 25 |
+
# Mecheye scan script
|
| 26 |
+
SCAN_SCRIPT_PATH = str(BASE_DIR / "MecheyePackage" / "scan.py")
|
| 27 |
+
CONFIG_PATH = str(BASE_DIR / "MecheyePackage" / "config.json")
|
| 28 |
+
|
entrypoint.sh
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -e
|
| 3 |
+
|
| 4 |
+
echo "Starting FRController..."
|
| 5 |
+
/etc/init.d/frinit.sh start &
|
| 6 |
+
|
| 7 |
+
echo "Waiting for FRController on 127.0.0.1:7860..."
|
| 8 |
+
/app/wait-for-it.sh 127.0.0.1:7860 -t 60 -- echo "FRController is up"
|
| 9 |
+
|
| 10 |
+
echo "FRController is running"
|
| 11 |
+
exec python3 -u /app/run.py
|
| 12 |
+
echo "FRController has stopped"
|
etc/.pwd.lock
ADDED
|
File without changes
|
etc/adduser.conf
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /etc/adduser.conf: `adduser' configuration.
|
| 2 |
+
# See adduser(8) and adduser.conf(5) for full documentation.
|
| 3 |
+
|
| 4 |
+
# The DSHELL variable specifies the default login shell on your
|
| 5 |
+
# system.
|
| 6 |
+
DSHELL=/bin/bash
|
| 7 |
+
|
| 8 |
+
# The DHOME variable specifies the directory containing users' home
|
| 9 |
+
# directories.
|
| 10 |
+
DHOME=/home
|
| 11 |
+
|
| 12 |
+
# If GROUPHOMES is "yes", then the home directories will be created as
|
| 13 |
+
# /home/groupname/user.
|
| 14 |
+
GROUPHOMES=no
|
| 15 |
+
|
| 16 |
+
# If LETTERHOMES is "yes", then the created home directories will have
|
| 17 |
+
# an extra directory - the first letter of the user name. For example:
|
| 18 |
+
# /home/u/user.
|
| 19 |
+
LETTERHOMES=no
|
| 20 |
+
|
| 21 |
+
# The SKEL variable specifies the directory containing "skeletal" user
|
| 22 |
+
# files; in other words, files such as a sample .profile that will be
|
| 23 |
+
# copied to the new user's home directory when it is created.
|
| 24 |
+
SKEL=/etc/skel
|
| 25 |
+
|
| 26 |
+
# FIRST_SYSTEM_[GU]ID to LAST_SYSTEM_[GU]ID inclusive is the range for UIDs
|
| 27 |
+
# for dynamically allocated administrative and system accounts/groups.
|
| 28 |
+
# Please note that system software, such as the users allocated by the base-passwd
|
| 29 |
+
# package, may assume that UIDs less than 100 are unallocated.
|
| 30 |
+
FIRST_SYSTEM_UID=100
|
| 31 |
+
LAST_SYSTEM_UID=999
|
| 32 |
+
|
| 33 |
+
FIRST_SYSTEM_GID=100
|
| 34 |
+
LAST_SYSTEM_GID=999
|
| 35 |
+
|
| 36 |
+
# FIRST_[GU]ID to LAST_[GU]ID inclusive is the range of UIDs of dynamically
|
| 37 |
+
# allocated user accounts/groups.
|
| 38 |
+
FIRST_UID=1000
|
| 39 |
+
LAST_UID=59999
|
| 40 |
+
|
| 41 |
+
FIRST_GID=1000
|
| 42 |
+
LAST_GID=59999
|
| 43 |
+
|
| 44 |
+
# The USERGROUPS variable can be either "yes" or "no". If "yes" each
|
| 45 |
+
# created user will be given their own group to use as a default. If
|
| 46 |
+
# "no", each created user will be placed in the group whose gid is
|
| 47 |
+
# USERS_GID (see below).
|
| 48 |
+
USERGROUPS=yes
|
| 49 |
+
|
| 50 |
+
# If USERGROUPS is "no", then USERS_GID should be the GID of the group
|
| 51 |
+
# `users' (or the equivalent group) on your system.
|
| 52 |
+
USERS_GID=100
|
| 53 |
+
|
| 54 |
+
# If DIR_MODE is set, directories will be created with the specified
|
| 55 |
+
# mode. Otherwise the default mode 0755 will be used.
|
| 56 |
+
DIR_MODE=0755
|
| 57 |
+
|
| 58 |
+
# If SETGID_HOME is "yes" home directories for users with their own
|
| 59 |
+
# group the setgid bit will be set. This was the default for
|
| 60 |
+
# versions << 3.13 of adduser. Because it has some bad side effects we
|
| 61 |
+
# no longer do this per default. If you want it nevertheless you can
|
| 62 |
+
# still set it here.
|
| 63 |
+
SETGID_HOME=no
|
| 64 |
+
|
| 65 |
+
# If QUOTAUSER is set, a default quota will be set from that user with
|
| 66 |
+
# `edquota -p QUOTAUSER newuser'
|
| 67 |
+
QUOTAUSER=""
|
| 68 |
+
|
| 69 |
+
# If SKEL_IGNORE_REGEX is set, adduser will ignore files matching this
|
| 70 |
+
# regular expression when creating a new home directory
|
| 71 |
+
SKEL_IGNORE_REGEX="dpkg-(old|new|dist|save)"
|
| 72 |
+
|
| 73 |
+
# Set this if you want the --add_extra_groups option to adduser to add
|
| 74 |
+
# new users to other groups.
|
| 75 |
+
# This is the list of groups that new non-system users will be added to
|
| 76 |
+
# Default:
|
| 77 |
+
#EXTRA_GROUPS="dialout cdrom floppy audio video plugdev users"
|
| 78 |
+
|
| 79 |
+
# If ADD_EXTRA_GROUPS is set to something non-zero, the EXTRA_GROUPS
|
| 80 |
+
# option above will be default behavior for adding new, non-system users
|
| 81 |
+
#ADD_EXTRA_GROUPS=1
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# check user and group names also against this regular expression.
|
| 85 |
+
#NAME_REGEX="^[a-z][-a-z0-9_]*\$"
|
| 86 |
+
|
| 87 |
+
# use extrausers by default
|
| 88 |
+
#USE_EXTRAUSERS=1
|
etc/alternatives/README
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please read the update-alternatives(1) man page for information on this
|
| 2 |
+
directory and its contents.
|
etc/alternatives/awk
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/usr/bin/mawk
|
etc/alternatives/editor
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/bin/nano
|
etc/alternatives/nawk
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/usr/bin/mawk
|
etc/alternatives/nc
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/bin/nc.openbsd
|
etc/alternatives/netcat
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/bin/nc.openbsd
|
etc/alternatives/pager
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/bin/more
|
etc/alternatives/pico
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/bin/nano
|
etc/alternatives/rmt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/usr/sbin/rmt-tar
|
etc/alternatives/w
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
/usr/bin/w.procps
|
etc/apt/apt.conf.d/01-vendor-ubuntu
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Acquire::Changelogs::AlwaysOnline "true";
|
etc/apt/apt.conf.d/01autoremove
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
APT
|
| 2 |
+
{
|
| 3 |
+
NeverAutoRemove
|
| 4 |
+
{
|
| 5 |
+
"^firmware-linux.*";
|
| 6 |
+
"^linux-firmware$";
|
| 7 |
+
"^linux-image-[a-z0-9]*$";
|
| 8 |
+
"^linux-image-[a-z0-9]*-[a-z0-9]*$";
|
| 9 |
+
};
|
| 10 |
+
|
| 11 |
+
VersionedKernelPackages
|
| 12 |
+
{
|
| 13 |
+
# linux kernels
|
| 14 |
+
"linux-image";
|
| 15 |
+
"linux-headers";
|
| 16 |
+
"linux-image-extra";
|
| 17 |
+
"linux-modules";
|
| 18 |
+
"linux-modules-extra";
|
| 19 |
+
"linux-signed-image";
|
| 20 |
+
"linux-image-unsigned";
|
| 21 |
+
# kfreebsd kernels
|
| 22 |
+
"kfreebsd-image";
|
| 23 |
+
"kfreebsd-headers";
|
| 24 |
+
# hurd kernels
|
| 25 |
+
"gnumach-image";
|
| 26 |
+
# (out-of-tree) modules
|
| 27 |
+
".*-modules";
|
| 28 |
+
".*-kernel";
|
| 29 |
+
"linux-backports-modules-.*";
|
| 30 |
+
"linux-modules-.*";
|
| 31 |
+
# tools
|
| 32 |
+
"linux-tools";
|
| 33 |
+
"linux-cloud-tools";
|
| 34 |
+
# build info
|
| 35 |
+
"linux-buildinfo";
|
| 36 |
+
# source code
|
| 37 |
+
"linux-source";
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
Never-MarkAuto-Sections
|
| 41 |
+
{
|
| 42 |
+
"metapackages";
|
| 43 |
+
"contrib/metapackages";
|
| 44 |
+
"non-free/metapackages";
|
| 45 |
+
"restricted/metapackages";
|
| 46 |
+
"universe/metapackages";
|
| 47 |
+
"multiverse/metapackages";
|
| 48 |
+
};
|
| 49 |
+
|
| 50 |
+
Move-Autobit-Sections
|
| 51 |
+
{
|
| 52 |
+
"oldlibs";
|
| 53 |
+
"contrib/oldlibs";
|
| 54 |
+
"non-free/oldlibs";
|
| 55 |
+
"restricted/oldlibs";
|
| 56 |
+
"universe/oldlibs";
|
| 57 |
+
"multiverse/oldlibs";
|
| 58 |
+
};
|
| 59 |
+
};
|
etc/apt/apt.conf.d/70debconf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Pre-configure all packages with debconf before they are installed.
|
| 2 |
+
// If you don't like it, comment it out.
|
| 3 |
+
DPkg::Pre-Install-Pkgs {"/usr/sbin/dpkg-preconfigure --apt || true";};
|
etc/apt/apt.conf.d/docker-autoremove-suggests
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Apt::AutoRemove::SuggestsImportant "false";
|
etc/apt/apt.conf.d/docker-clean
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
DPkg::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };
|
| 2 |
+
APT::Update::Post-Invoke { "rm -f /var/cache/apt/archives/*.deb /var/cache/apt/archives/partial/*.deb /var/cache/apt/*.bin || true"; };
|
| 3 |
+
Dir::Cache::pkgcache ""; Dir::Cache::srcpkgcache "";
|
etc/apt/apt.conf.d/docker-gzip-indexes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Acquire::GzipIndexes "true"; Acquire::CompressionTypes::Order:: "gz";
|
etc/apt/apt.conf.d/docker-no-languages
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Acquire::Languages "none";
|
etc/apt/sources.list
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# See http://help.ubuntu.com/community/UpgradeNotes for how to upgrade to
|
| 2 |
+
# newer versions of the distribution.
|
| 3 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic main restricted
|
| 4 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic main restricted
|
| 5 |
+
|
| 6 |
+
## Major bug fix updates produced after the final release of the
|
| 7 |
+
## distribution.
|
| 8 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic-updates main restricted
|
| 9 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic-updates main restricted
|
| 10 |
+
|
| 11 |
+
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
|
| 12 |
+
## team. Also, please note that software in universe WILL NOT receive any
|
| 13 |
+
## review or updates from the Ubuntu security team.
|
| 14 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic universe
|
| 15 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic universe
|
| 16 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic-updates universe
|
| 17 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic-updates universe
|
| 18 |
+
|
| 19 |
+
## N.B. software from this repository is ENTIRELY UNSUPPORTED by the Ubuntu
|
| 20 |
+
## team, and may not be under a free licence. Please satisfy yourself as to
|
| 21 |
+
## your rights to use the software. Also, please note that software in
|
| 22 |
+
## multiverse WILL NOT receive any review or updates from the Ubuntu
|
| 23 |
+
## security team.
|
| 24 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic multiverse
|
| 25 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic multiverse
|
| 26 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic-updates multiverse
|
| 27 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic-updates multiverse
|
| 28 |
+
|
| 29 |
+
## N.B. software from this repository may not have been tested as
|
| 30 |
+
## extensively as that contained in the main release, although it includes
|
| 31 |
+
## newer versions of some applications which may provide useful features.
|
| 32 |
+
## Also, please note that software in backports WILL NOT receive any review
|
| 33 |
+
## or updates from the Ubuntu security team.
|
| 34 |
+
deb http://archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse
|
| 35 |
+
# deb-src http://archive.ubuntu.com/ubuntu/ bionic-backports main restricted universe multiverse
|
| 36 |
+
|
| 37 |
+
## Uncomment the following two lines to add software from Canonical's
|
| 38 |
+
## 'partner' repository.
|
| 39 |
+
## This software is not part of Ubuntu, but is offered by Canonical and the
|
| 40 |
+
## respective vendors as a service to Ubuntu users.
|
| 41 |
+
# deb http://archive.canonical.com/ubuntu bionic partner
|
| 42 |
+
# deb-src http://archive.canonical.com/ubuntu bionic partner
|
| 43 |
+
|
| 44 |
+
deb http://security.ubuntu.com/ubuntu/ bionic-security main restricted
|
| 45 |
+
# deb-src http://security.ubuntu.com/ubuntu/ bionic-security main restricted
|
| 46 |
+
deb http://security.ubuntu.com/ubuntu/ bionic-security universe
|
| 47 |
+
# deb-src http://security.ubuntu.com/ubuntu/ bionic-security universe
|
| 48 |
+
deb http://security.ubuntu.com/ubuntu/ bionic-security multiverse
|
| 49 |
+
# deb-src http://security.ubuntu.com/ubuntu/ bionic-security multiverse
|
etc/apt/trusted.gpg.d/ubuntu-keyring-2012-archive.gpg
ADDED
|
Binary file (2.8 kB). View file
|
|
|
etc/apt/trusted.gpg.d/ubuntu-keyring-2012-cdimage.gpg
ADDED
|
Binary file (2.79 kB). View file
|
|
|