<commit_before>import socket

from SimpleCV import Camera, Image
import cv2
import numpy
import sys
import os
import time
import imgproc
import json
from valueconfig import ValueConfig
from object import Obj
from threading import Thread
import threading
import subprocess

cam_id = 0

x_offset = -1
y_offset = -1


# Really hacky way to detect if the camera is connected. Always returns true on Windows and OSX.
# TODO maybe this doesn't have to return true always on OSX, but I doubt we'll ever have an OSX machine running this.
def camera_connected():
    if sys.platform == 'linux' or sys.platform == 'linux2':
        # TODO, look for any /dev/video since the camera doesn't have to be video0
        return os.path.exists('/dev/video%s' % cam_id)  # The system sees a camera
    else:
        return True


# Does image processing
class ImgProcThread(Thread):
    def __init__(self, camera, obj, config):
        super(ImgProcThread, self).__init__()
        self.camera = camera
        self.obj = obj
        self.config = config

    def run(self):
        global found
        global not_found_count
        global s
        global lastConnectRetry
        not_found_count = 0
        max_not_found = 3

        s = None
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(2)  # Timeout @ 2 secs
            s.connect(('169.254.65.94', 8622))
        except socket.error:
            s = None


        lastConnectRetry = 0
        while True:
            input_img = self.camera.getImage()
            found = False

            def on_blob(b):
                global found
                global not_found_count
                global s
                global lastConnectRetry

                rect_width = b.minRectWidth()
                rect_height = b.minRectHeight()

                rect_ctr_x = b.minRectX()

                mrX = rect_ctr_x-rect_width/2
                mrY = b.minRectY()-rect_height/2
                # px * (px/cm) = cm
                x_offset = int(round((rect_ctr_x - input_img.width/2) * (obj.width / rect_width)))
                found = True
                not_found_count = 0

                print("Sending a real value!")
                if s is not None:
                    try:
                        to_send = "x=-1;y=%d;" % x_offset  # x is not yet implemented
                        s.send(str(len(to_send)).ljust(16))
                        s.send(to_send)
                        s.close()
                    except socket.error:
                        s = None  # So we will try to reconnect later
                elif int(round(time.time() * 1000)) - lastConnectRetry > 30000:  # If we haven't retried for 30 seconds
                    print("Trying to reconnect to the rio.")
                    lastConnectRetry = int(round(time.time() * 1000))
                    try:
                        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        s.settimeout(2)  # Timeout @ 2 secs
                        s.connect(('169.254.65.94', 8622))
                    except socket.error:
                        s = None

            if not found:
                not_found_count += 1
            if not_found_count >= max_not_found:
                # It's been missing for a bit now, let's send some arbitrary negative numbers!
                to_send = "x=-10;y=-10"
                print("SENDING -10!")
                if s is not None:
                    try:
                        s.send(str(len(to_send)).ljust(16))
                        s.send(to_send)
                        s.close()
                    except socket.error:
                        pass

            processed_img = imgproc.process_image(self.obj, input_img, self.config, on_blob)
            time.sleep(0.5)


class ServerThread(Thread):
    def __init__(self, camera):
        super(ServerThread, self).__init__()
        self.camera = camera

    def run(self):
        port = 8621
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind(('localhost', port))
        server_socket.listen(1)  # max 1 connection - we only have one camera, so we can't send images to two people at once
        print('Listening on port %s' % port)
        connection = None
        while True:
            connection, address = server_socket.accept()
            try:  # Don't let any bad things that happen with one connection cause the whole server to crash
                data = connection.recv(1024)
                print('Got some data:')
                print(data)<commit_msg>Globals for IPs and ports<commit_after>import socket

from SimpleCV import Camera, Image
import cv2
import numpy
import sys
import os
import time
import imgproc
import json
from valueconfig import ValueConfig
from object import Obj
from threading import Thread
import threading
import subprocess

ROBORIO_IP = '10.8.61.2'
ROBORIO_LISTEN_PORT = 8622

CONFIG_LISTEN_HOST = ''
CONFIG_LISTEN_PORT = 8621

cam_id = 0

x_offset = -1
y_offset = -1


# Really hacky way to detect if the camera is connected. Always returns true on Windows and OSX.
# TODO maybe this doesn't have to return true always on OSX, but I doubt we'll ever have an OSX machine running this.
def camera_connected():
    if sys.platform == 'linux' or sys.platform == 'linux2':
        # TODO, look for any /dev/video since the camera doesn't have to be video0
        return os.path.exists('/dev/video%s' % cam_id)  # The system sees a camera
    else:
        return True


# Does image processing
class ImgProcThread(Thread):
    def __init__(self, camera, obj, config):
        super(ImgProcThread, self).__init__()
        self.camera = camera
        self.obj = obj
        self.config = config

    def run(self):
        global found
        global not_found_count
        global s
        global lastConnectRetry
        not_found_count = 0
        max_not_found = 3

        s = None
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(2)  # Timeout @ 2 secs
            s.connect((ROBORIO_IP, ROBORIO_LISTEN_PORT))
        except socket.error:
            s = None


        lastConnectRetry = 0
        while True:
            input_img = self.camera.getImage()
            found = False

            def on_blob(b):
                global found
                global not_found_count
                global s
                global lastConnectRetry

                rect_width = b.minRectWidth()
                rect_height = b.minRectHeight()

                rect_ctr_x = b.minRectX()

                mrX = rect_ctr_x-rect_width/2
                mrY = b.minRectY()-rect_height/2
                # px * (px/cm) = cm
                x_offset = int(round((rect_ctr_x - input_img.width/2) * (obj.width / rect_width)))
                found = True
                not_found_count = 0

                print("Sending a real value!")
                if s is not None:
                    try:
                        to_send = "x=-1;y=%d;" % x_offset  # x is not yet implemented
                        s.send(str(len(to_send)).ljust(16))
                        s.send(to_send)
                        s.close()
                    except socket.error:
                        s = None  # So we will try to reconnect later
                elif int(round(time.time() * 1000)) - lastConnectRetry > 30000:  # If we haven't retried for 30 seconds
                    print("Trying to reconnect to the rio.")
                    lastConnectRetry = int(round(time.time() * 1000))
                    try:
                        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                        s.settimeout(2)  # Timeout @ 2 secs
                        s.connect((ROBORIO_IP, ROBORIO_LISTEN_PORT))
                    except socket.error:
                        s = None

            if not found:
                not_found_count += 1
            if not_found_count >= max_not_found:
                # It's been missing for a bit now, let's send some arbitrary negative numbers!
                to_send = "x=-10;y=-10"
                print("SENDING -10!")
                if s is not None:
                    try:
                        s.send(str(len(to_send)).ljust(16))
                        s.send(to_send)
                        s.close()
                    except socket.error:
                        pass

            processed_img = imgproc.process_image(self.obj, input_img, self.config, on_blob)
            time.sleep(0.5)


class ServerThread(Thread):
    def __init__(self, camera):
        super(ServerThread, self).__init__()
        self.camera = camera

    def run(self):
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.bind((CONFIG_LISTEN_HOST, CONFIG_LISTEN_PORT))
        server_socket.listen(1)  # max 1 connection - we only have one camera, so we can't send images to two people at once
        print('Listening on port %s' % CONFIG_LISTEN_PORT)
        connection = None
        while True:
            connection, address = server_socket.accept()
            try:  # Don't let any bad things that happen with one connection cause the whole server to crash
                data = connection.recv(1024)
                print('Got some data:')
                print(data)
{'fraction_non_alphanumeric': 0.07962628729164455, 'fraction_numerical': 0.01592525745832891, 'mean_word_length': 1.5900467418201816, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 3, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6217952', 'n_tokens_mistral': 2766, 'n_tokens_neox': 2541, 'n_words': 776}