Ejemplo n.º 1
0
    def deffectDetection(self):

        i = 1
        while True:

            print('Taking image # ' + str(i))

            image = self.takeImage()
            self.saveImage(image)
            self.saveImageLastImage(image)

            with open(self.imagePath, "rb") as imageFile:
                self.b64Img = base64.b64encode(imageFile.read())

            self.fabric = {
                '_id': i,
                'defect': 'None',
                'date': self.imageTimeStamp,
                'imageUrl': 'imgs/' + self.imageName,
                'imageBIN': self.b64Img,
                'deviceID': self.DEVICE_ID,
            }

            if self.deffectDetectionMode == 'on':
                lycraDeffectDetected = funcao_deteccao_lycra_tracadelas(
                    self.imagePath)
                agulhaDeffectDetected = funcao_detecao_agulhas(self.imagePath)

                if agulhaDeffectDetected:
                    self.fabric['defect'] = 'Agulha'
                    print("Defeito agulha!")

                if lycraDeffectDetected[0]:
                    self.fabric['defect'] = lycraDeffectDetected[1]
                    print("Defeito lycra!")

                if self.stopMachineMode == 'on' and (lycraDeffectDetected[0]
                                                     or agulhaDeffectDetected):

                    GPIO.setmode(GPIO.BCM)
                    GPIO.setup(self.outputPort, GPIO.OUT, initial=GPIO.LOW)
                    GPIO.output(self.outputPort, GPIO.LOW)
                    sleep(1)
                    GPIO.setup(self.outputPort,
                               GPIO.IN,
                               pull_up_down=GPIO.PUD_DOWN)

            #por try except

            try:
                self.db['fabrics'].save(self.fabric)
                print("Sent to DB!!")
            except:
                print(
                    'Fabric DB instance not saved in MongoDB at {}!\n'.format(
                        self.imageTimeStamp))
                pass

            sleep(1)
            i += 1
Ejemplo n.º 2
0
    def deffectDetection(self):
        i = 1
        j = 1
        pi = pigpio.pi()
        pi1 = pigpio.pi()
        WebSockets.changeLEDInt(pi, self.operationConfigs['frontledgpio'],
                                self.operationConfigs['frontledint'])
        WebSockets.changeLEDInt(pi1, self.operationConfigs['backledgpio'],
                                self.operationConfigs['backledint'])
        self.USBpowerOutput = 'OFF'
        self.img_ant = ""
        self.date_ant = datetime.datetime.now()
        start_stop = 0
        reason = "Unknown"
        self.duration = 0
        self.stoped = False
        while True:
            begin = datetime.datetime.now()
            logging.info('Beginning iteration # ' + str(i))
            self.UPSpowerInput = self.pijuice.status.GetStatus(
            )['data']['powerInput']

            if self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'ON':
                if not self.stoped:
                    self.stoped = True
                    reason = "Abertura de portas"
                    start_stop = self.date_ant
                logging.warning(
                    'UPS not being charged - shutting down camera.\n')
                powerOffUSBs()
                self.USBpowerOutput = 'OFF'
                sleep(3)
                continue

            elif self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'OFF':
                logging.warning('UPS not being charged - trying again.\n')
                sleep(3)
                continue

            elif self.UPSpowerInput == 'PRESENT' and self.USBpowerOutput == 'OFF':
                logging.info(
                    'UPS just started being charged - booting camera.\n')
                powerOnUSBs()
                self.USBpowerOutput = 'ON'
                if self.stoped:
                    end_stop = datetime.datetime.now()
                    elapsed = end_stop - start_stop
                    logging.info("Paragem de (s): {}\n".format(
                        elapsed.total_seconds()))
                    self.duration = elapsed.total_seconds()
                    self.stoped = False

                    fabric = {
                        '_id': self.lastID + i,
                        'defect': defect,
                        'brightness': 0,
                        'mse': 0,
                        'stoped': 1,
                        'reason': reason,
                        'duration': self.duration,
                        'date': start_stop,
                        'imageUrl': "",
                        'thumbUrl': "",
                        'deviceID': self.operationConfigs['DEVICE_ID'],
                        'LEDBack': self.operationConfigs['backledint'],
                        'LEDFront': self.operationConfigs['frontledint']
                    }
                    start_stop = 0
                    reason = "Unknown"
                    obj = {'path': "", 'fabric': fabric}
                    self.fabricWorker.add_work(obj)
                    i += 1
                sleep(3)

            now = datetime.datetime.now()
            elapsed = now - begin

            logging.debug("USB ports are up - elapsed time (s): {}".format(
                elapsed.total_seconds()))

            now_ant = now
            now = datetime.datetime.now()
            elapsed = now - now_ant

            logging.debug("Camera is ready - elapsed time (s): {}".format(
                elapsed.total_seconds()))

            try:
                logging.info('Taking image!')
                if self.operationConfigs['flash']:
                    WebSockets.changeLEDInt(
                        pi, self.operationConfigs['frontledgpio'],
                        self.operationConfigs['frontledint'])
                    WebSockets.changeLEDInt(
                        pi1, self.operationConfigs['backledgpio'],
                        self.operationConfigs['backledint'])
                #self.setLEDParams(pi, i - 1, j - 1)
                try:
                    self.img_ant = self.camera.imagePath
                    self.date_ant = self.camera.rawImageTimeStamp
                except:
                    pass
                self.camera.saveImage()

                if self.operationConfigs['flash']:
                    WebSockets.changeLEDInt(
                        pi, self.operationConfigs['frontledgpio'], 0)
                    WebSockets.changeLEDInt(
                        pi1, self.operationConfigs['backledgpio'], 0)

                if self.pijuice.status.GetStatus(
                )['data']['powerInput'] == 'NOT_PRESENT':
                    logging.info("Aborting iteration! No power!")
                    continue

                #self.setLEDParams(pi, 1, 1)
                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.debug(
                    "Image taken and saved - elapsed time (s): {}".format(
                        elapsed.total_seconds()))
            except Exception as ex:
                logging.exception(
                    "Error taking/saving image! Continuing to next iteration.."
                )
                sleep(2)
                continue

            defect = 'None'
            bright = 0
            stop = 0

            try:
                bright = self.brightness(self.camera.imagePath)
                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.debug("Brightness of " + str(bright) +
                              " - elapsed time (s): {}\n".format(
                                  elapsed.total_seconds()))
            except Exception as ex:
                logging.exception("Error calculating brightness for " +
                                  self.camera.imagePath)

            if bright < 16:
                logging.info("Skipping image with low light " +
                             self.camera.imagePath)
                self.breakIteration(begin)
                continue

            mse = self.calcFabricMSE(self.camera.imagePath)

            if mse < Smartex.MSE_THRESHOLD:
                if self.stoped:
                    logging.info("Skipping image. Machine is stoped")
                    self.breakIteration(begin)
                    continue
                else:
                    self.stoped = True
                    start_stop = self.camera.rawImageTimeStamp
                    self.breakIteration(begin)
                    continue

            elif start_stop != 0:
                end_stop = self.camera.rawImageTimeStamp
                elapsed = end_stop - start_stop
                logging.info("Paragem de (s): {}\n".format(
                    elapsed.total_seconds()))
                self.duration = elapsed.total_seconds()

                stop = 1
                self.stoped = False

                fabric = {
                    '_id': self.lastID + i,
                    'defect': defect,
                    'brightness': bright,
                    'mse': mse,
                    'stoped': stop,
                    'reason': reason,
                    'duration':
                    self.duration + self.operationConfigs['interval'],
                    'date': start_stop,
                    'imageUrl': "",
                    'thumbUrl': "",
                    'deviceID': self.operationConfigs['DEVICE_ID'],
                    'LEDBack': self.operationConfigs['backledint'],
                    'LEDFront': self.operationConfigs['frontledint']
                }
                start_stop = 0
                reason = "Unknown"
                obj = {'path': "", 'fabric': fabric}
                self.fabricWorker.add_work(obj)
                stop = 0
                i += 1

            if self.operationConfigs['deffectDetectionMode']:
                logging.info("Analyzing images for defect..")
                lycraDeffectDetected = funcao_deteccao_lycra_tracadelas(
                    self.camera.image)
                agulhaDeffectDetected = funcao_detecao_agulhas(
                    self.camera.image)

                if agulhaDeffectDetected:
                    defect = 'Agulha'
                    logging.info("Defeito agulha detectado!")
                elif lycraDeffectDetected[0]:
                    defect = lycraDeffectDetected[1]
                    logging.info("Defeito lycra detectado!")

                if self.operationConfigs['stopMachineMode'] and (
                        lycraDeffectDetected[0]
                        or agulhaDeffectDetected) and bright >= 30:
                    logging.info("Stoping the machine!")
                    GPIO.setmode(GPIO.BCM)
                    GPIO.setup(self.operationConfigs['outputPort'],
                               GPIO.OUT,
                               initial=GPIO.LOW)
                    GPIO.output(self.operationConfigs['outputPort'], GPIO.LOW)
                    sleep(1)
                    GPIO.setup(self.operationConfigs['outputPort'],
                               GPIO.IN,
                               pull_up_down=GPIO.PUD_DOWN)

                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.debug(
                    "Detection modules finished -elapsed time (s): {}\n".
                    format(elapsed.total_seconds()))

            fabric = {
                '_id': self.lastID + i,
                'defect': defect,
                'brightness': bright,
                'mse': mse,
                'stoped': stop,
                'reason': "---",
                'duration': self.duration,
                'date': self.camera.rawImageTimeStamp,
                'imageUrl': "",
                'thumbUrl': "",
                'deviceID': self.operationConfigs['DEVICE_ID'],
                'LEDBack': self.operationConfigs['backledint'],
                'LEDFront': self.operationConfigs['frontledint']
            }

            obj = {'path': self.camera.imagePath, 'fabric': fabric}
            self.fabricWorker.add_work(obj)
            self.duration = 0

            elapsed = datetime.datetime.now() - begin
            sleep_time = max(
                self.operationConfigs['interval'] - elapsed.total_seconds(), 0)

            logging.info('Iteration # ' + str(i) + " finished!")
            logging.info("Total elapsed time (s): {}".format(
                elapsed.total_seconds()))
            logging.info("Will sleep for (s): {}".format(sleep_time))

            sleep(sleep_time)
            i += 1
            if i % 26 == 0:
                j += 1
Ejemplo n.º 3
0
def cam_deffect_detection():
    detectionOn = str(raw_input('Deffect detection mode: (on/off)')) or 'on'
    if detectionOn == 'on':
        print('Detection mode: ON')
    elif detectionOn == 'off':
        print('Detection mode: OFF')
    else:
        print('Input not recognized, not gonna detect.')
    stopMachineOn = str(raw_input('Stop machine mode: (on/off)')) or 'on'
    if stopMachineOn == 'on':
        print('Stop mode: ON')
        output_port = int(raw_input('RPi low voltage GPIO port: (27)')) or 27
    elif stopMachineOn == 'off':
        print('Stop mode: OFF')
    else:
        print('Input not recognized, not gonna stop.')

    #cam = ids.Camera()
    #cam.color_mode = ids.ids_core.COLOR_RGB8    # Get images in RGB format

    #cam.auto_exposure = True
    #cam.continuous_capture = True               # Start image capture

    #for shutters in range(115, 150 ,5):
    #for shutters in range(50,60,5):
    #shutters /= 10.
    #cam.exposure = shutters                            # Set initial exposure to 5ms
    directory = 'teste_domingo_migusta/'
    if not os.path.exists(directory):
        os.makedirs(directory)
    #directory2 = 'imagens/%s' %  now.strftime('%Y_%m_%d_%H_%M_%S')
    #if not os.path.exists(directory2):
    #    os.makedirs(directory2)
    #print(shutters)
    N = int(raw_input('Number of photos: ')) or 15
    for i in range(N):
        now = datetime.datetime.now()
        imgName = 'image%s.jpg' % now.strftime('%Y_%m_%d_%H_%M_%S')
        path1 = directory + imgName
        camera.capture(path1)
        print('Saved: ' + path1)
        #img, meta = cam.next()                      # Get image as a Numpy array
        #pil_img = Image.fromarray(img)
        #nome_imagem = 'imagem_%s.jpg' % datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
        #path2 = directory + nome_imagem
        #pil_img.save(path1, quality = 100)
        #pil_img.save('teste_domingo_migusta/last_image.jpg', quality = 100)
        #print('Saved: ' + path2)

        fabric = {
            '_id': (i + 15),
            'defect': 'None',
            'date': datetime.datetime.now(),
            'imageUrl': 'imgs/' + imgName,
            'deviceID': 'GJjybzAy5V'
        }

        if detectionOn == 'on':
            deffect_lycra = funcao_deteccao_lycra_tracadelas(path1)
            deffect_agulha = funcao_detecao_agulhas(path1)

            if stopMachineOn == 'on' and (deffect_lycra[0] or deffect_agulha):

                if deffect_agulha:
                    fabric['defect'] = 'agulha'
                if deffect_lycra[0]:
                    fabric['defect'] = deffect_lycra[1]

                GPIO.setmode(GPIO.BCM)
                GPIO.setup(output_port, GPIO.OUT, initial=GPIO.LOW)
                GPIO.output(output_port, GPIO.HIGH)
                sleep(1)
                GPIO.setup(output_port, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                #break

        db['fabrics'].insert_one(fabric)
        sleep(.8)
Ejemplo n.º 4
0
    def deffectDetection(self):

        i = 1
        while True:

            self.UPSpowerInput = self.pijuice.status.GetStatus(
            )['data']['powerInput']

            if i == 1:
                self.USBpowerOutput = 'ON'

            if self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'ON':
                logging.warning(
                    'UPS not being charged - shutting down camera.\n')
                powerOffUSBs()
                self.USBpowerOutput = 'OFF'
                sleep(1)
                continue

            elif self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'OFF':
                logging.warning('UPS not being charged - trying again.\n')
                sleep(1)
                continue

            elif self.UPSpowerInput == 'PRESENT' and self.USBpowerOutput == 'OFF':
                logging.info(
                    'UPS just started being charged - booting camera.\n')
                powerOnUSBs()
                self.USBpowerOutput = 'ON'
                sleep(5)

            if i != 1:
                self.initCamera()

            logging.info('Taking image # ' + str(i))
            self.saveImage()

            with open(self.imagePath, "rb") as imageFile:
                self.b64Img = base64.b64encode(imageFile.read())

            self.fabric = {
                '_id': i,
                'defect': 'None',
                'date': self.imageTimeStamp,
                'imageUrl': 'imgs/' + self.imageName,
                'imageBIN': self.b64Img,
                'deviceID': self.operationConfigs['DEVICE_ID'],
            }

            if self.operationConfigs['deffectDetectionMode']:
                lycraDeffectDetected = funcao_deteccao_lycra_tracadelas(
                    self.imagePath)
                agulhaDeffectDetected = funcao_detecao_agulhas(self.imagePath)

                if agulhaDeffectDetected:
                    self.fabric['defect'] = 'Agulha'
                    logging.info("Defeito agulha!")

                if lycraDeffectDetected[0]:
                    self.fabric['defect'] = lycraDeffectDetected[1]
                    logging.info("Defeito lycra!")

                if self.operationConfigs['stopMachineMode'] and (
                        lycraDeffectDetected[0] or agulhaDeffectDetected):

                    GPIO.setmode(GPIO.BCM)
                    GPIO.setup(self.operationConfigs['outputPort'],
                               GPIO.OUT,
                               initial=GPIO.LOW)
                    GPIO.output(self.operationConfigs['outputPort'], GPIO.LOW)
                    sleep(1)
                    GPIO.setup(self.operationConfigs['outputPort'],
                               GPIO.IN,
                               pull_up_down=GPIO.PUD_DOWN)

            #por try except

            try:
                time1 = datetime.datetime.now()
                self.db['fabrics'].save(self.fabric)
                time2 = datetime.datetime.now()
                elapsed_time = time2 - time1
                logging.info("Sent to DB!! Elapsed time (ms): {}\n".format(
                    elapsed_time.microseconds / 1000))
                self.pijuice.status.SetLedBlink('D2', 2, [0, 0, 255], 50,
                                                [0, 0, 255], 50)
                sleep(.1)
                self.pijuice.status.SetLedState('D2', [0, 0, 0])
            except:
                logging.warning('Fabric DB instance not saved in MongoDB\n')
                self.pijuice.status.SetLedBlink('D2', 2, [255, 0, 0], 50,
                                                [255, 0, 0], 50)
                sleep(.1)
                self.pijuice.status.SetLedState('D2', [0, 0, 0])
                pass

            sleep(1)
            i += 1
Ejemplo n.º 5
0
    def deffectDetection(self):
        i = 1
        while True:
            begin = datetime.datetime.now()
            logging.info('Iteration # ' + str(i))
            self.UPSpowerInput = self.pijuice.status.GetStatus(
            )['data']['powerInput']

            if i == 1:
                self.USBpowerOutput = 'OFF'

            if self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'ON':
                logging.warning(
                    'UPS not being charged - shutting down camera.\n')
                powerOffUSBs()
                self.USBpowerOutput = 'OFF'
                sleep(1)
                continue

            elif self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'OFF':
                logging.warning('UPS not being charged - trying again.\n')
                sleep(1)
                continue

            elif self.UPSpowerInput == 'PRESENT' and self.USBpowerOutput == 'OFF':
                logging.info(
                    'UPS just started being charged - booting camera.\n')
                powerOnUSBs()
                self.USBpowerOutput = 'ON'
                sleep(2)

            if i != 1:
                self.initCamera()

            logging.info('Taking image!')
            try:
                self.saveImage()
            except:
                continue

            defect = 'None'

            time1 = datetime.datetime.now()
            if self.operationConfigs['deffectDetectionMode']:
                logging.info("Starting detection modules!")
                lycraDeffectDetected = funcao_deteccao_lycra_tracadelas(
                    self.image)
                agulhaDeffectDetected = funcao_detecao_agulhas(self.image)

                if agulhaDeffectDetected:
                    defect = 'Agulha'
                    logging.info("Defeito agulha!")

                if lycraDeffectDetected[0]:
                    defect = lycraDeffectDetected[1]
                    logging.info("Defeito lycra!")

                if self.operationConfigs['stopMachineMode'] and (
                        lycraDeffectDetected[0] or agulhaDeffectDetected):
                    GPIO.setmode(GPIO.BCM)
                    GPIO.setup(self.operationConfigs['outputPort'],
                               GPIO.OUT,
                               initial=GPIO.LOW)
                    GPIO.output(self.operationConfigs['outputPort'], GPIO.LOW)
                    sleep(1)
                    GPIO.setup(self.operationConfigs['outputPort'],
                               GPIO.IN,
                               pull_up_down=GPIO.PUD_DOWN)

                time2 = datetime.datetime.now()
                elapsed_time = time2 - time1
                logging.info(
                    "Detection modules finished! Elapsed time (s): {}\n".
                    format(elapsed_time.total_seconds()))

            logging.info("Uploading image!")
            try:
                self.uploadImages()
            except:
                continue
            self.fabric = {
                '_id': self.lastID + i,
                'defect': defect,
                'date': self.rawImageTimeStamp,
                'imageUrl': self.imgUrl,
                'thumbUrl': self.thumbUrl,
                'deviceID': self.operationConfigs['DEVICE_ID'],
            }
            # por try except
            try:
                time1 = datetime.datetime.now()
                logging.info("Sending to WS!")
                r = self.client.post(self.operationConfigs['FABRIC_ENDPOINT'],
                                     data=self.fabric)
                time2 = datetime.datetime.now()
                elapsed_time = time2 - time1
                logging.info("Fabric post status code: {}".format(
                    r.status_code))
                logging.info("Sent to WS!! Elapsed time (s): {}\n".format(
                    elapsed_time.total_seconds()))
                # self.blinkLED()
            except:
                logging.warning('Error communicating with WS\n')
                self.blinkLED()
                pass

            elapsed = datetime.datetime.now() - begin
            sleep_time = max(
                self.operationConfigs['interval'] - elapsed.total_seconds(), 0)
            logging.info("\nTotal elapsed time (s): {}".format(
                elapsed.total_seconds()))
            logging.info("Will sleep for (s): {}".format(sleep_time))
            print(self.operationConfigs['interval'], elapsed.total_seconds())
            sleep(sleep_time)
            i += 1
Ejemplo n.º 6
0
def cam_deffect_detection():
    detectionOn = str(raw_input('Deffect detection mode: (on/off)')) or 'on'
    if detectionOn == 'on':
        print('Detection mode: ON')
    elif detectionOn == 'off':
        print('Detection mode: OFF')
    else:
        print('Input not recognized, not gonna detect.')
    stopMachineOn = str(raw_input('Stop machine mode: (on/off)')) or 'on'
    if stopMachineOn == 'on':
        print('Stop mode: ON')
        output_port = int(raw_input('RPi low voltage GPIO port: (27)')) or 27
    elif stopMachineOn == 'off':
        print('Stop mode: OFF')
    else:
        print('Input not recognized, not gonna stop.')    
    now = datetime.datetime.now()

    cam = ids.Camera()
    cam.color_mode = ids.ids_core.COLOR_RGB8    # Get images in RGB format

    cam.auto_exposure = True
    cam.continuous_capture = True               # Start image capture

    #for shutters in range(115, 150 ,5):
    #for shutters in range(50,60,5):
    #shutters /= 10.
    #cam.exposure = shutters                            # Set initial exposure to 5ms
    directory = 'teste_domingo_migusta/'
    if not os.path.exists(directory):
        os.makedirs(directory)
    #directory2 = 'imagens/%s' %  now.strftime('%Y_%m_%d_%H_%M_%S') 
    #if not os.path.exists(directory2):
    #    os.makedirs(directory2)
    #print(shutters)
    N = int(raw_input('Number of photos: ')) or 15
    for i in range(N):
        #path1 = directory2 +'/image%s.jpg' % now.strftime('%Y_%m_%d_%H_%M_%S')
        #camera.capture(path1)
        #print('Saved: ' + path1) 
        img, meta = cam.next()                      # Get image as a Numpy array
        #pil_img = Image.fromarray(img)
	nome_imagem = 'imagem_%s.jpg' % datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S') 
        path2 = directory + nome_imagem
        #pil_img.save(path2, quality = 100)
	
	misc.imsave(path2,img)
        
	#pil_img.save('teste_domingo_migusta/last_image.jpg', quality = 100)
        
	misc.imsave('teste_domingo_migusta/last_image.jpg',img)	

	print('Saved: ' + path2)

        fabric = {
            '_id': i,
            'defect': 'None',
            'date': datetime.datetime.now(),
            'imageUrl': "imgs/"+nome_imagem,
            'deviceID' : 'GJjybzAy5V'
        }

        if detectionOn == 'on':
            deffect_lycra = funcao_deteccao_lycra_tracadelas(path2)
            deffect_agulha = funcao_detecao_agulhas(path2)

            if stopMachineOn == 'on' and (deffect_lycra[0] or deffect_agulha):

                if deffect_agulha:
                    fabric['defect'] = 'agulha'
                if deffect_lycra[0]:
                    fabric['defect'] = deffect_lycra[1]

                contents = urllib2.urlopen("http://192.168.0.105:8080/api/stop").read()

        db['fabrics'].insert_one(fabric)
        sleep(.8)
Ejemplo n.º 7
0
    def deffectDetection(self):
        i = 1
        while True:
            begin = datetime.datetime.now()
            logging.info('Beginning iteration # ' + str(i))
            self.UPSpowerInput = self.pijuice.status.GetStatus()['data']['powerInput']

            if i == 1:
                self.USBpowerOutput = 'OFF'

            if self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'ON':
                logging.warning('UPS not being charged - shutting down camera.\n')
                powerOffUSBs()
                self.USBpowerOutput = 'OFF'
                sleep(1)
                continue

            elif self.UPSpowerInput == 'NOT_PRESENT' and self.USBpowerOutput == 'OFF':
                logging.warning('UPS not being charged - trying again.\n')
                sleep(1)
                continue

            elif self.UPSpowerInput == 'PRESENT' and self.USBpowerOutput == 'OFF':
                logging.info('UPS just started being charged - booting camera.\n')
                powerOnUSBs()
                self.USBpowerOutput = 'ON'
                sleep(2)

            now = datetime.datetime.now()
            elapsed = now - begin

            logging.info("\nUSB ports are up - elapsed time (s): {}".format(elapsed.total_seconds()))

            if i != 1:
                self.initCamera()

            now_ant = now
            now = datetime.datetime.now()
            elapsed = now - now_ant

            logging.info("\nCamera is ready - elapsed time (s): {}".format(elapsed.total_seconds()))

            try:
                logging.info('Taking image!')
                self.saveImage()
                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.info("\nImage taken and saved - elapsed time (s): {}".format(elapsed.total_seconds()))
            except:
                logging.warn("Error taking/saving image! Continuing to next iteration..")
                continue

            defect = 'None'

            if self.operationConfigs['deffectDetectionMode']:
                logging.info("Analyzing images for defect..")
                lycraDeffectDetected = funcao_deteccao_lycra_tracadelas(self.image)
                agulhaDeffectDetected = funcao_detecao_agulhas(self.image)

                if agulhaDeffectDetected:
                    defect = 'Agulha'
                    logging.info("Defeito agulha detectado!")

                if lycraDeffectDetected[0]:
                    defect = lycraDeffectDetected[1]
                    logging.info("Defeito lycra detectado!")

                if self.operationConfigs['stopMachineMode'] and (lycraDeffectDetected[0] or agulhaDeffectDetected):
                    logging.info("Stoping the machine!")
                    GPIO.setmode(GPIO.BCM)
                    GPIO.setup(self.operationConfigs['outputPort'], GPIO.OUT, initial=GPIO.LOW)
                    GPIO.output(self.operationConfigs['outputPort'], GPIO.LOW)
                    sleep(1)
                    GPIO.setup(self.operationConfigs['outputPort'], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.info("\nDetection modules finished -elapsed time (s): {}\n".format(elapsed.total_seconds()))

            try:
                logging.info("Uploading image!")
                self.uploadImages()
                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.info("\nImage uploaded - elapsed time (s): {}\n".format(elapsed.total_seconds()))
            except:
                logging.warn("Error uploading image! Continuing to next iteration..")
                continue

            self.fabric = {
                '_id': self.lastID + i,
                'defect': defect,
                'date': self.rawImageTimeStamp,
                'imageUrl': self.imgUrl,
                'thumbUrl': self.thumbUrl,
                'deviceID': self.operationConfigs['DEVICE_ID'],
            }

            try:
                logging.info("Uploading fabric object!")
                self.uploadFabric()
                now_ant = now
                now = datetime.datetime.now()
                elapsed = now - now_ant
                logging.info("\nFabric object uploaded - elapsed time (s): {}\n".format(elapsed.total_seconds()))
            except:
                logging.warn("Error uploading fabric object! Continuing to next iteration..")
                continue


            elapsed = datetime.datetime.now() - begin
            sleep_time = max(self.operationConfigs['interval'] - elapsed.total_seconds(), 0)
            logging.info('Iteration # ' + str(i) + " finished!")
            logging.info("\nTotal elapsed time (s): {}".format(elapsed.total_seconds()))
            logging.info("Will sleep for (s): {}".format(sleep_time))
            #print(self.operationConfigs['interval'], elapsed.total_seconds())
            sleep(sleep_time)
            i += 1