class Smartex: OP_OK = 0 OP_ERR = -1 MSE_THRESHOLD = 12 pijuice = PiJuice(1, 0x14) def __init__( self, configsFile='/home/smartex/image-analyser/new_gen/configs.json'): if not os.path.exists(configsFile): print("Config file does not exist.") exit() print "Starting..." self.configsFile = configsFile self.operationConfigs = json.loads(open(configsFile).read()) print "Configurations loaded from " + configsFile logging.basicConfig(filename='/home/smartex/image-analyser/new_gen/smartex_main.log', level=logging.INFO, \ format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.getLogger().addHandler(logging.StreamHandler()) if (self.operationConfigs['CAMERA_TYPE'] == "ids"): print "IDS" from ids_camera import Camera else: print "Ardu cam" from ardu_camera import Camera self.camera = Camera(self.operationConfigs) self.webServer = WebServer(self.operationConfigs) self.aws = AWS(self.operationConfigs) self.authEverything() self.fabricWorker = FabricWorker(20, self.aws.bucket, self.webServer.client, self.operationConfigs) if self.authenticated: self.webSockets = WebSockets(self.operationConfigs, self.webServer.session_id) self.webSockets.startWSockService() self.deffectDetection() self.webSockets.join() self.fabricWorker.join() else: logging.warning("You need to authenticate first!") def updateJsonFile(self): jsonFile = open(self.configsFile, "w+") jsonFile.write(json.dumps(self.operationConfigs)) jsonFile.close() def setLEDParams(self, pi, i, j): i = (i % 26) j = (j % 26) valFront = min((i * 10), 255) valBack = min((j * 10), 255) self.operationConfigs['frontledint'] = valFront WebSockets.changeLEDInt(pi, self.operationConfigs['frontledgpio'], self.operationConfigs['frontledint']) self.operationConfigs['backledint'] = valBack WebSockets.changeLEDInt(pi, self.operationConfigs['backledgpio'], self.operationConfigs['backledint']) 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 def authEverything(self): while self.webServer.authWS() != self.OP_OK: logging.warning("Reconnecting WebServer!") self.lastID = self.webServer.getLastID() if self.operationConfigs['storage'] == "ONLINE": while self.aws.connectAWSS3() != self.OP_OK: logging.warning("Reconnecting AWS!") self.authenticated = True def calcFabricMSE(self, image_path): mse = 100.0 if self.img_ant != "": try: begin = datetime.datetime.now() im1 = cv2.imread(image_path) gray1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY) im2 = cv2.imread(self.img_ant) gray2 = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY) m = self.mse(gray1, gray2) mse = m elapsed = datetime.datetime.now() - begin logging.info("MSE of " + str(m) + " - elapsed time (s): {}\n".format( elapsed.total_seconds())) except Exception as ex: logging.exception("Error calculating mse for " + image_path + " and " + self.img_ant) return mse def mse(self, imageA, imageB): err = np.sum((imageA.astype("float") - imageB.astype("float"))**2) err /= float(imageA.shape[0] * imageA.shape[1]) # return the MSE, the lower the error, the more "similar" the two images are return err def brightness(self, im_file): im = Image.open(im_file).convert('L') stat = ImageStat.Stat(im) return stat.rms[0] def breakIteration(self, begin): try: os.remove(self.img_ant) except: pass #self.img_ant = self.camera.imagePath elapsed = datetime.datetime.now() - begin sleep_time = max( self.operationConfigs['interval'] - elapsed.total_seconds(), 0) logging.info("Breaking iteration| Elapsed time (s): {}".format( elapsed.total_seconds())) logging.info("Will sleep for (s): {}".format(sleep_time)) sleep(sleep_time) pass def blinkLED(self): pass self.pijuice.status.SetLedBlink('D2', 2, [255, 0, 0], 50, [255, 0, 0], 50) sleep(.1) self.pijuice.status.SetLedState('D2', [0, 0, 0])
from pijuice import PiJuice from balena import Balena # Start the SDK if auth token is set if os.environ['AUTH_TOKEN']: balena = Balena() balena.auth.login_with_token(os.environ['AUTH_TOKEN']) print(balena.auth.is_logged_in()) # Wait for device I2C device to start while not os.path.exists('/dev/i2c-1'): print("Waiting to identify PiJuice") time.sleep(0.1) # Initiate PiJuice pijuice = PiJuice(1, 0x14) # Get all parameters and return as a dictionary def get_battery_paremeters(pijuice): juice = {} charge = pijuice.status.GetChargeLevel() juice['charge'] = charge['data'] if charge[ 'error'] == 'NO_ERROR' else charge['error'] # Temperature [C] temperature = pijuice.status.GetBatteryTemperature() juice['temperature'] = temperature['data'] if temperature[ 'error'] == 'NO_ERROR' else temperature['error']
#!/usr/bin/env python3 import os from pijuice import PiJuice pj = PiJuice(bus=1, address=0x14) pj.status.SetLedBlink(led='D2', count=3, rgb1=[0, 0, 200], period1=1000, rgb2=[200, 0, 0], period2=1000) # Remove power to PiJuice MCU IO pins pj.power.SetSystemPowerSwitch(0) # Remove 5V power to RPi after 60 seconds # Wait for the timer to finish before restarting the board pj.power.SetPowerOff(delay=60) # Shut down the RPi os.system('sudo shutdown now')
# This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. import smbus import Adafruit_DHT # this library works for DHT11 DHT22 and AM2302 sensors import time import spidev from pijuice import PiJuice # Import pijuice module from flask import Flask, render_template pijuice = PiJuice(1, 0x14) # Instantiate PiJuice interface object # Open SPI bus spi = spidev.SpiDev() spi.open(0, 0) spi.max_speed_hz = 1000000 dh22_sensor = Adafruit_DHT.DHT22 pin = 4 #DHT22 data pin on the raspberry pi # Define sensor channels light_channel = 0 temp_channel = 1
PM10 = int.from_bytes(pm_dat[6:9], byteorder='little') / 100.0 PM4 = int.from_bytes(pm_dat[9:12], byteorder='little') / 100.0 T = int.from_bytes(thp_dat[6:8], byteorder='little') / 100.0 H = int.from_bytes(thp_dat[0:1], byteorder='little') P = int.from_bytes(thp_dat[2:6], byteorder='little') / 100.0 #info = int.from_bytes(bat_dat[1:2], byteorder='little') #bat = int.from_bytes(bat_dat[0:1], byteorder='little') timeofreading = strftime("%Y-%m-%d %H:%M:%S", localtime()) f = open('atmotube_reading.txt', 'w') to_write = str(timeofreading) + "," + str(TVOC) + "," + str(T) + "," + str( H) + "," + str(P) + "," + str(PM1) + "," + str(PM25) + "," + str( PM10) + "," + str(PM4) f.write(to_write) f.close() time_now = datetime.now().time() night_start = datetime.strptime('2020-06-03 23:00:00', '%Y-%m-%d %H:%M:%S').time() night_end = datetime.strptime('2020-06-04 05:00:00', '%Y-%m-%d %H:%M:%S').time() if time_now > night_start or time_now < night_end: time.sleep(100) pj = PiJuice(1, 0x14) pj.power.SetPowerOff(30) os.system("sudo shutdown now")
def main(): global pijuice global btConfig global configData global status global chargeLevel global logger global sysEvEn global minChgEn global minBatVolEn global lowChgEn global lowBatVolEn global noPowEn pid = str(os.getpid()) with open(PID_FILE, 'w') as pid_f: pid_f.write(pid) if not os.path.exists(configPath): with open(configPath, 'w+') as conf_f: conf_f.write(json.dumps(configData)) try: pijuice = PiJuice(1, 0x14) except: sys.exit(0) reload_settings() # Handle SIGHUP signal to reload settings signal.signal(signal.SIGHUP, reload_settings) if len(sys.argv) > 1 and str(sys.argv[1]) == 'stop': isHalting = False if os.path.exists(HALT_FILE): # Created in _SystemHalt() called in main pijuice_sys process isHalting = True os.remove(HALT_FILE) try: if (('watchdog' in configData['system_task']) and ('enabled' in configData['system_task']['watchdog']) and configData['system_task']['watchdog']['enabled'] ): # Disabling watchdog ret = pijuice.power.SetWatchdog(0) if ret['error'] != 'NO_ERROR': time.sleep(0.05) ret = pijuice.power.SetWatchdog(0) except: pass sysJobTargets = str(subprocess.check_output(["systemctl", "list-jobs"])) reboot = True if re.search('reboot.target.*start', sysJobTargets) is not None else False # reboot.target exists swStop = True if re.search('(?:halt|shutdown).target.*start', sysJobTargets) is not None else False # shutdown | halt exists causePowerOff = True if (swStop and not reboot) else False ret = pijuice.status.GetStatus() if ( ret['error'] == 'NO_ERROR' and not isHalting # Flag set in _SystemHalt() and causePowerOff # proper time to power down (!rebooting) and configData.get('system_task',{}).get('ext_halt_power_off', {}).get('enabled',False) ): # Set duration for when pijuice will cut power (Recommended 30+ sec, for halt to complete) try: powerOffDelay = int(configData['system_task']['ext_halt_power_off'].get('period',30)) pijuice.power.SetPowerOff(powerOffDelay) print("PiJuice powering off in %s seconds" % configData['system_task']['ext_halt_power_off'].get('period',30)) except ValueError: pass sys.exit(0) if (('watchdog' in configData['system_task']) and ('enabled' in configData['system_task']['watchdog']) and configData['system_task']['watchdog']['enabled'] and ('period' in configData['system_task']['watchdog']) ): try: p = int(configData['system_task']['watchdog']['period']) ret = pijuice.power.SetWatchdog(p) except: p = None timeCnt = 5 while dopoll: if configData.get('system_task', {}).get('enabled'): ret = pijuice.status.GetStatus() if ret['error'] == 'NO_ERROR': status = ret['data'] if status['isButton']: _EvalButtonEvents() timeCnt -= 1 if timeCnt == 0: timeCnt = 5 if ('isFault' in status) and status['isFault']: _EvalFaultFlags() if minChgEn: _EvalCharge() if minBatVolEn: _EvalBatVoltage() if noPowEn: _EvalPowerInputs(status) time.sleep(1)
'-d', '--delay', type=int, metavar='[{}-{}]'.format(delay_min, delay_max), help=("Delay in seconds. Note that this delay must allow proper " "shutdown of the system. Given that system shutdown is initiated " "immediately it is recommended that this is 30 seconds at " "minimum.")) argparser.add_argument('-c', '--cancel', action='store_true', help="Cancel a scheduled power-off") args = argparser.parse_args() i2c_bus = 1 # found with `i2cdetect -l` i2c_bus_address = 0x14 # found with `pijuice_cli` > General pijuice = PiJuice(i2c_bus, i2c_bus_address) if args.cancel: pijuice.power.SetPowerOff(255) elif args.delay: if delay_min <= args.delay <= delay_max: pijuice.power.SetPowerOff(args.delay) else: argparser.error( "Given delay {} is outside allowed interval (min: {}, max: {})". format(args.delay, delay_min, delay_max)) else: argparser.error("Expected either -d/--delay or -c/--cancel argument")
def main(): global pijuice global btConfig global configData global status global chargeLevel global logger global sysEvEn global minChgEn global minBatVolEn global lowChgEn global lowBatVolEn global noPowEn pid = str(os.getpid()) with open(PID_FILE, 'w') as pid_f: pid_f.write(pid) if not os.path.exists(configPath): with open(configPath, 'w+') as conf_f: conf_f.write(json.dumps(configData)) try: pijuice = PiJuice(1, 0x14) except: sys.exit(0) reload_settings() # Handle SIGHUP signal to reload settings signal.signal(signal.SIGHUP, reload_settings) if len(sys.argv) > 1 and str(sys.argv[1]) == 'stop': try: if (('watchdog' in configData['system_task']) and ('enabled' in configData['system_task']['watchdog']) and configData['system_task']['watchdog']['enabled']): # Disabling watchdog ret = pijuice.power.SetWatchdog(0) if ret['error'] != 'NO_ERROR': time.sleep(0.05) ret = pijuice.power.SetWatchdog(0) except: pass sys.exit(0) if (('watchdog' in configData['system_task']) and ('enabled' in configData['system_task']['watchdog']) and configData['system_task']['watchdog']['enabled'] and ('period' in configData['system_task']['watchdog'])): try: p = int(configData['system_task']['watchdog']['period']) ret = pijuice.power.SetWatchdog(p) except: p = None timeCnt = 5 while dopoll: if configData.get('system_task', {}).get('enabled'): ret = pijuice.status.GetStatus() if ret['error'] == 'NO_ERROR': status = ret['data'] if status['isButton']: _EvalButtonEvents() timeCnt -= 1 if timeCnt == 0: timeCnt = 5 if ('isFault' in status) and status['isFault']: _EvalFaultFlags() if minChgEn: _EvalCharge() if minBatVolEn: _EvalBatVoltage() if noPowEn: _EvalPowerInputs(status) time.sleep(1)
class Smartex: # MONGO_PORT = 27017 OP_OK = 0 OP_ERR = -1 # CAMERA_RETRYS = 10 pijuice = PiJuice(1, 0x14) def __init__(self, configsFile='image-analyser/configs.json'): self.operationConfigs = json.loads(open(configsFile).read()) while self.initCamera( ) != self.OP_OK and self.operationConfigs['CAMERA_RETRYS'] > 0: logging.warning('Error in initCamera()') self.pijuice.status.SetLedBlink('D2', 2, [255, 0, 0], 50, [255, 0, 0], 50) sleep(1) self.pijuice.status.SetLedState('D2', [0, 0, 0]) self.operationConfigs['CAMERA_RETRYS'] -= 1 self.DEVICE_ID = id logging.basicConfig(filename='smartex_main.log', level=logging.DEBUG,\ format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') def initCamera(self): try: self.hcam = ueye.HIDS(0) self.pccmem = ueye.c_mem_p() self.memID = ueye.c_int() self.hWnd = ctypes.c_voidp() ueye.is_InitCamera(self.hcam, self.hWnd) ueye.is_SetDisplayMode(self.hcam, 0) self.sensorinfo = ueye.SENSORINFO() ueye.is_GetSensorInfo(self.hcam, self.sensorinfo) return self.OP_OK except: return self.OP_ERR def connectMongoDB(self): try: con = MongoClient(self.operationConfigs['MONGO_HOST'], self.operationConfigs['MONGO_PORT']) self.db = con[self.operationConfigs['DBNAME']] self.pijuice.status.SetLedBlink('D2', 2, [0, 0, 255], 50, [0, 0, 255], 50) sleep(.01) self.pijuice.status.SetLedState('D2', [0, 0, 0]) except: logging.warning('Error in connectMongoDB!\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 def saveImage(self): try: time1 = datetime.datetime.now() ueye.is_AllocImageMem(self.hcam, self.sensorinfo.nMaxWidth, self.sensorinfo.nMaxHeight, 24, self.pccmem, self.memID) ueye.is_SetImageMem(self.hcam, self.pccmem, self.memID) ueye.is_SetDisplayPos(self.hcam, 100, 100) self.nret = ueye.is_FreezeVideo(self.hcam, ueye.IS_WAIT) self.imageTimeStamp = datetime.datetime.now().strftime( '%Y_%m_%d_%H_%M_%S') self.imageName = 'imagem_%s.jpg' % self.imageTimeStamp self.imagePath = self.operationConfigs[ 'savingDirectory'] + self.imageName self.FileParams = ueye.IMAGE_FILE_PARAMS() self.FileParams.pwchFileName = self.imagePath self.FileParams.nFileType = ueye.IS_IMG_BMP self.FileParams.ppcImageMem = None self.FileParams.pnImageID = None self.nret = ueye.is_ImageFile(self.hcam, ueye.IS_IMAGE_FILE_CMD_SAVE, self.FileParams, ueye.sizeof(self.FileParams)) ueye.is_FreeImageMem(self.hcam, self.pccmem, self.memID) sleep(.01) ueye.is_ExitCamera(self.hcam) time2 = datetime.datetime.now() elapsed_time = time2 - time1 logging.info('Saved: {}! Elasped time (ms): {}'.format( self.imageName, elapsed_time.microseconds / 1000)) self.pijuice.status.SetLedBlink('D2', 2, [0, 255, 0], 50, [0, 255, 0], 50) sleep(.1) self.pijuice.status.SetLedState('D2', [0, 0, 0]) except: logging.warning('NOT SAVED: {}!\n'.format(self.imageName)) 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 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
def main(argv): # Set default save location #save_location = "/media/usb0/" save_location = "/var/lib/nature-juice/" # Command line defaults verbose = False logo = False forceTrigger = False # Create a pijuice and a camera objects pijuice = PiJuice(1, 0x14) camera = PiCamera() # Time for watchdog detectTime = datetime.now() maxTimeIdle = 10 # minutes # Set save location try: opts, args = getopt.getopt(argv, "ho:lvf") for opt, arg in opts: if opt == "-h": printHelp() sys.exit() elif opt == "-l": logo = True elif opt == "-o": # Basic error checking save_location = arg.strip() save_location = save_location if save_location.startswith( "/") else "/" + save_location save_location = save_location if save_location.endswith( "/") else save_location + "/" elif opt == "-v": verbose = True elif opt == "-f": forceTrigger = True except getopt.GetoptError: printHelp() sys.exit(2) logging.info("Starting a new session. Charge level: " + str(pijuice.status.GetChargeLevel()["data"]) + "%") try: while datetime.now().minute - detectTime.minute <= maxTimeIdle: pijuiceIo2 = pijuice.status.GetIoDigitalInput(2) if (pijuiceIo2['error'] == 'NO_ERROR' and pijuiceIo2['data'] == 1) or forceTrigger: if forceTrigger: forceTrigger = not forceTrigger # Toggle forceTrigger flag until next reboot detectTime = datetime.now() # Get current time get_date = detectTime.strftime( "%Y-%m-%d") # Get and format the date get_time = detectTime.strftime( "%H-%M-%S.%f") # Get and format the time # Recording that a PIR trigger was detected and logging the battery level at this time message = "PIR trigger detected" logging.info(message) printVerbose(verbose, message) # Assigning a variable so we can create a photo JPG file that contains the date and time as its name photo_name = save_location + get_date + '_' + get_time + '.jpg' # Log that we have just taking a photo message = "About to take a photo and save to " + photo_name logging.info(message) printVerbose(verbose, message) if (logo): # Prepare the base picture stream = io.BytesIO() # Prepare the font fontsize = 16 padding = 4 # Check under /usr/share/fonts/truetype/freefont/ for the available fonts font = ImageFont.truetype("FreeSerif.ttf", fontsize) camera.capture(stream, format='jpeg') stream.seek(0) base = Image.open(stream) draw = ImageDraw.Draw(base) font = ImageFont.truetype("FreeSerif.ttf", fontsize) # Prepare date and time ina different format for the picture overlayText = get_date + " " + detectTime.strftime( "%H:%M:%S") printVerbose( verbose, "Date and time used for the overlay " + overlayText) baseWidth, baseHeight = base.size printVerbose( verbose, "Width and height of the picture saved " + str(baseWidth) + "X" + str(baseHeight)) draw.text((padding, baseHeight - fontsize - padding), overlayText, (255, 255, 255), font=font) # Load the logo watermarks watermark = Image.open("nature-juice_logo_90.png", 'r') # Add watermark xy_offset = (1, 1) base.paste(watermark, xy_offset, mask=watermark) # Save the picture with the logo message = "Added the overlay logo and text" logging.info(message) printVerbose(verbose, message) base.save(photo_name) watermark.close() else: # Not using PIL saves the picture with all details untouched # Check the properties of both pictures with/without logo to see the differences camera.capture(photo_name, use_video_port=False, format='jpeg', thumbnail=None) message = "Picture saved successfully" logging.info(message) printVerbose(verbose, message) sleep(1) message = "Shutting down due to inactivity to conserve battery. Charge level: " + str( pijuice.status.GetChargeLevel()["data"]) + "%" logging.info(message) printVerbose(verbose, message) subprocess.Popen(['sudo', 'shutdown', '-h', 'now']) except KeyboardInterrupt: print("KeyboardInterrupt detected. Exiting program") sys.exit() except: print("Error detected. Exiting program") sys.exit(2)
UNK = c.UNK ERROR = c.ERROR NOERROR = c.NOERROR AC_POWER = 0 BATTERY_POWER = 1 # Pre-defined LED Colors LED_RED = [0xFF, 0x00, 0x00] LED_GRN = [0x00, 0xFF, 0x00] LED_BLU = [0x00, 0x00, 0xFF] LED_WHT = [0xFF, 0xFF, 0xFF] LED_OFF = [0x00, 0x00, 0x00] # module globals pj = PiJuice(c.PJ_BUS, c.PJ_ADDR) def init(): # assume we're starting on AC Power getFirmwareVersion() if (getPowerState() == BATTERY_POWER): log.log(log.CRITICAL, "Power Status indicates running on Battery") return ERROR log.log(log.ALWAYS, "pijuice init complete") # blink led twice to show we're running pj.status.SetLedState('D2', LED_OFF) time.sleep(0.1)
class Smartex: OP_OK = 0 OP_ERR = -1 # CAMERA_RETRYS = 10 pijuice = PiJuice(1, 0x14) def __init__(self, configsFile='configs.json'): print "Starting..." self.configsFile = configsFile self.operationConfigs = json.loads(open(configsFile).read()) print "Configurations loaded from " + configsFile while self.initCamera( ) != self.OP_OK and self.operationConfigs['CAMERA_RETRYS'] > 0: logging.warning('Error in initCamera()') self.pijuice.status.SetLedBlink('D2', 2, [255, 0, 0], 50, [255, 0, 0], 50) sleep(1) self.pijuice.status.SetLedState('D2', [0, 0, 0]) self.operationConfigs['CAMERA_RETRYS'] -= 1 self.DEVICE_ID = id print "Setting up logging configs..." # logging.getLogger('socketIO-client-nexus').setLevel(logging.DEBUG) logging.basicConfig(filename='smartex_main.log', level=logging.INFO, \ format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') logging.getLogger().addHandler(logging.StreamHandler()) print "Smartex module initiated with success!" def updateJsonFile(self): jsonFile = open(self.configsFile, "w+") jsonFile.write(json.dumps(self.operationConfigs)) jsonFile.close() def initCamera(self): try: self.hcam = ueye.HIDS(0) self.pccmem = ueye.c_mem_p() self.memID = ueye.c_int() self.hWnd = ctypes.c_voidp() ueye.is_InitCamera(self.hcam, self.hWnd) ueye.is_SetDisplayMode(self.hcam, 0) self.sensorinfo = ueye.SENSORINFO() ueye.is_GetSensorInfo(self.hcam, self.sensorinfo) print self.sensorinfo return self.OP_OK except: print "\n\nERR\n\n" return self.OP_ERR def connectAWSS3(self): logging.info("Connecting AWS3...") try: con = boto.connect_s3(self.operationConfigs['AWS_ACCESS_KEY'], self.operationConfigs['AWS_SECRET_KEY'], host=self.operationConfigs['REGION_HOST']) self.bucket = con.get_bucket(self.operationConfigs['AWS_BUCKET']) return True except: logging.warning('Error in connectAWSS3!\n') self.blinkLED() return False def authWS(self): try: time1 = datetime.datetime.now() logging.info("Authenticating in WS!") self.client = requests.session() # Retrieve the CSRF token first self.client.get('http://192.168.0.102:3000/login') # sets cookie if 'csrftoken' in self.client.cookies: self.csrftoken = self.client.cookies['csrftoken'] elif '_csrf' in self.client.cookies: self.csrftoken = self.client.cookies['_csrf'] elif 'sessionId' in self.client.cookies: self.csrftoken = self.client.cookies['sessionId'] else: self.csrftoken = self.client.cookies['csrf'] login_data = dict(username='******', password='******', csrfmiddlewaretoken=self.csrftoken, next='/') r = self.client.post( self.operationConfigs['AUTH_ENDPOINT'], data=login_data, headers=dict(Referer='http://192.168.0.102:3000/login')) time2 = datetime.datetime.now() elapsed_time = time2 - time1 logging.info("\nAuthentication status code: {}".format( r.status_code)) # logging.info("Authentication response headers: {}".format(r.headers)) # logging.info("Authentication response cookies: {}\n".format(r.cookies)) logging.info("Authenticated in WS!! Elapsed time (s): {}\n".format( elapsed_time.total_seconds())) self.blinkLED() return True except: logging.warning('Error authenticating with WS\n') self.blinkLED() return False pass pass def getLastID(self): r = self.client.get( 'http://192.168.0.102:3000/api/fabric/lastID') # sets cookie data = r.json() print(data['data']['id']) self.lastID = data['data']['id'] pass def saveImage(self): # try: time1 = datetime.datetime.now() ueye.is_AllocImageMem(self.hcam, self.sensorinfo.nMaxWidth, self.sensorinfo.nMaxHeight, 24, self.pccmem, self.memID) ueye.is_SetImageMem(self.hcam, self.pccmem, self.memID) ueye.is_SetDisplayPos(self.hcam, 100, 100) self.nret = ueye.is_FreezeVideo(self.hcam, ueye.IS_WAIT) self.rawImageTimeStamp = datetime.datetime.now() self.imageTimeStamp = datetime.datetime.now().strftime( '%Y_%m_%d_%H_%M_%S') self.imageName = 'imagem_%s.jpg' % self.imageTimeStamp self.imagePath = self.operationConfigs[ 'savingDirectory'] + self.imageName # self.imagePath = self.operationConfigs['savingDirectory'] + "tmp.jpg" self.FileParams = ueye.IMAGE_FILE_PARAMS() self.FileParams.pwchFileName = self.imagePath self.FileParams.nFileType = ueye.IS_IMG_BMP self.FileParams.ppcImageMem = None self.FileParams.pnImageID = None self.nret = ueye.is_ImageFile(self.hcam, ueye.IS_IMAGE_FILE_CMD_SAVE, self.FileParams, ueye.sizeof(self.FileParams)) ueye.is_FreeImageMem(self.hcam, self.pccmem, self.memID) sleep(.01) ueye.is_ExitCamera(self.hcam) # self.image = np.ones((self.sensorinfo.nMaxHeight.value, self.sensorinfo.nMaxWidth.value), dtype=np.uint8) # ueye.is_CopyImageMem(self.hcam, self.pccmem, self.memID, self.image.ctypes.data) self.image = np.uint8(ndimage.imread(self.imagePath, flatten=True)) time2 = datetime.datetime.now() elapsed_time = time2 - time1 logging.info('Saved: {}! Elasped time (s): {}'.format( self.imageName, elapsed_time.total_seconds())) # except: # logging.warning('NOT SAVED: {}!\n'.format(self.imageName)) # self.blinkLED() # pass def uploadImages(self): # try: if self.operationConfigs['storage'] == "ONLINE": logging.info("#upload full res: " + self.imagePath) fuuid = str(uuid.uuid4()) k = Key(self.bucket) k.key = 'F_' + fuuid + '.png' k.set_contents_from_filename(self.imagePath, cb=percent_cb, num_cb=10) self.imgUrl = 'https://' + self.operationConfigs[ 'REGION_HOST'] + '/' + self.operationConfigs[ 'AWS_BUCKET'] + '/' + k.key k.set_acl('public-read') logging.info("#generate 128*128 thumbnail") im = Image.open(self.imagePath) im.thumbnail((128, 128), Image.ANTIALIAS) head, tail = os.path.split(self.imagePath) thumb_path = head + "/T_" + tail im.save(thumb_path, "PNG") logging.info("#upload thumbnail") k = Key(self.bucket) k.key = "T_" + fuuid + '.png' k.set_contents_from_filename(thumb_path, cb=percent_cb, num_cb=10) self.thumbUrl = 'https://' + self.operationConfigs[ 'REGION_HOST'] + '/' + self.operationConfigs[ 'AWS_BUCKET'] + '/' + k.key k.set_acl('public-read') else: time1 = datetime.datetime.now() fuuid = str(uuid.uuid4()) name = 'F_' + fuuid + '.png' pil_img = Image.fromarray(self.image) buff = BytesIO() pil_img.save(buff, format="JPEG") # b64Img = base64.b64encode(buff.getvalue()).decode("utf-8") with open(self.imagePath, "rb") as imageFile: b64Img = base64.b64encode(imageFile.read()) logging.info("Sending image to local storage!") img = {name: "data:image/png;base64, " + b64Img} r = requests.post("http://" + self.operationConfigs['STORAGE_ENDPOINT'] + "/" + name, json=img) self.imgUrl = 'http://192.168.0.102:3000/fabrics/' + name im = Image.open(self.imagePath) im.thumbnail((128, 128), Image.ANTIALIAS) logging.info("#upload thumbnail") name = "T_" + fuuid + '.png' buff = BytesIO() im.save(buff, format="JPEG") b64Img = base64.b64encode(buff.getvalue()).decode("utf-8") img = {name: "data:image/png;base64, " + b64Img} r = requests.post("http://" + self.operationConfigs['STORAGE_ENDPOINT'] + "/" + name, json=img) self.thumbUrl = 'http://192.168.0.102:3000/fabrics/' + name time2 = datetime.datetime.now() elapsed_time = time2 - time1 logging.info( "Sent images to local storage!! Elapsed time (s): {}\n".format( elapsed_time.total_seconds())) # except: # logging.warn("Error sendig image to local storage!\n") 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 def blinkLED(self): pass self.pijuice.status.SetLedBlink('D2', 2, [255, 0, 0], 50, [255, 0, 0], 50) sleep(.1) self.pijuice.status.SetLedState('D2', [0, 0, 0]) def connectWSock(self): try: socketIO = SocketIO(self.operationConfigs['SOCK_ENDPOINT'], 3000, cookies={'sessionId': s.csrftoken}, wait_for_connection=False) socketIO.on('connect', on_connect) socketIO.on('/devices/updated', self.on_updated) socketIO.on('disconnect', on_disconnect) socketIO.on('reconnect', on_reconnect) socketIO.wait() except ConnectionError: logging.warning('Error connecting WebSockets\n') def on_updated(self, *args): try: configs = args[0]['data'] print configs print '\n' if configs['code'] == self.operationConfigs['DEVICE_ID']: if configs.get('stop', -1) >= 0: self.operationConfigs['stopMachineMode'] = ( configs['stop'] == 1) if configs.get('detection', -1) >= 0: self.operationConfigs['deffectDetectionMode'] = ( configs['detection'] == 1) if configs.get('gpio', -1) >= 0: self.operationConfigs['outputPort'] = configs['gpio'] if configs.get('interval', -1) >= 0: self.operationConfigs['interval'] = configs['interval'] if configs.get('storage', -1) >= 0: self.operationConfigs['storage'] = configs['storage'] self.updateJsonFile() print self.operationConfigs except ValueError: logging.warning("Error parsing configs: " + ValueError)
def batteryFunc(): global logger logger.info('Battery: service requested') pijuice = PiJuice(1, 0x14) charge = pijuice.status.GetChargeLevel() return str(charge['data'])
def main(): global pijuice global btConfig global configData global status global sysEvEn global chargeLevel global logger global minChgEn global minBatVolEn global lowChgEn global lowBatVolEn global noPowEn pid = str(os.getpid()) with open(PID_FILE, 'w') as pid_f: pid_f.write(pid) if not os.path.exists(configPath): with open(configPath, 'w+') as conf_f: conf_f.write(json.dumps(configData)) try: pijuice = PiJuice(1, 0x14) except: sys.exit(0) reload_settings() try: for b in pijuice.config.buttons: conf = pijuice.config.GetButtonConfiguration(b) if conf['error'] == 'NO_ERROR': btConfig[b] = conf['data'] except: # powButton = None pass # Handle SIGHUP signal to reload settings signal.signal(signal.SIGHUP, reload_settings) #logger = logging.getLogger('pijuice') #hdlr = logging.FileHandler('/home/pi/pijuice.log') #formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') #hdlr.setFormatter(formatter) #logger.addHandler(hdlr) #logger.setLevel(logging.INFO) if len(sys.argv) > 1 and str(sys.argv[1]) == 'stop': try: if (('watchdog' in configData['system_task']) and ('enabled' in configData['system_task']['watchdog']) and configData['system_task']['watchdog']['enabled'] ): # Disabling watchdog ret = pijuice.power.SetWatchdog(0) if ret['error'] != 'NO_ERROR': time.sleep(0.05) ret = pijuice.power.SetWatchdog(0) #logger.info('watchdog disabled') except: pass sys.exit(0) if (('watchdog' in configData['system_task']) and ('enabled' in configData['system_task']['watchdog']) and configData['system_task']['watchdog']['enabled'] and ('period' in configData['system_task']['watchdog']) ): try: p = int(configData['system_task']['watchdog']['period']) ret = pijuice.power.SetWatchdog(p) #logger.info('watchdog enabled') except: p = None #logger.info('cannot enable watchdg') sysEvEn = 'system_events' in configData minChgEn = configData.get('system_task', {}).get('min_charge', {}).get('enabled', False) minBatVolEn = configData.get('system_task', {}).get('min_bat_voltage', {}).get('enabled', False) lowChgEn = sysEvEn and configData.get('system_events', {}).get('low_charge', {}).get('enabled', False) lowBatVolEn = sysEvEn and configData.get('system_events', {}).get('low_battery_voltage', {}).get('enabled', False) noPowEn = sysEvEn and configData.get('system_events', {}).get('no_power', {}).get('enabled', False) timeCnt = 5 while dopoll: if configData.get('system_task', {}).get('enabled'): ret = pijuice.status.GetStatus() if ret['error'] == 'NO_ERROR': status = ret['data'] if status['isButton']: _EvalButtonEvents() timeCnt -= 1 if timeCnt == 0: timeCnt = 5 if ('isFault' in status) and status['isFault']: _EvalFaultFlags() if minChgEn: _EvalCharge() if minBatVolEn: _EvalBatVoltage() if noPowEn: _EvalPowerInputs(status) time.sleep(1)
class Smartex: MONGO_PORT = 27017 OP_OK = 0 OP_ERR = -1 CAMERA_RETRYS = 10 pijuice = PiJuice(1, 0x14) def __init__(self, DBNAME, MONGO_HOST, id='7AKy0GDOEb'): self.DBNAME = DBNAME self.MONGO_HOST = MONGO_HOST while self.initCamera() != self.OP_OK and self.CAMERA_RETRYS > 0: logging.warning('Error in initCamera()') sleep(1) self.CAMERA_RETRYS -= 1 self.DEVICE_ID = id logging.basicConfig(filename='smartex_main.log', level=logging.DEBUG,\ format='%(asctime)s - %(levelname)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S') def initCamera(self): try: self.hcam = ueye.HIDS(0) self.pccmem = ueye.c_mem_p() self.memID = ueye.c_int() self.hWnd = ctypes.c_voidp() ueye.is_InitCamera(self.hcam, self.hWnd) ueye.is_SetDisplayMode(self.hcam, 0) self.sensorinfo = ueye.SENSORINFO() ueye.is_GetSensorInfo(self.hcam, self.sensorinfo) return self.OP_OK except: return self.OP_ERR def connectMongoDB(self): try: con = MongoClient(self.MONGO_HOST, self.MONGO_PORT) self.db = con[self.DBNAME] except: logging.warning('Error in connectMongoDB!\n') pass def operationConfigs(self): self.deffectDetectionMode = str( raw_input('Deffect detection mode: (on/off)')) or 'on' if self.deffectDetectionMode == 'on': logging.info('Detection mode: ON') self.stopMachineMode = str( raw_input('Stop machine mode: (on/off)')) or 'on' if self.stopMachineMode == 'on': logging.info('Stop mode: ON') self.outputPort = int( raw_input('RPi low voltage GPIO port: (27)')) or 27 elif self.stopMachineMode == 'off': logging.info('Stop mode: OFF') else: logging.info('Input not recognized, not gonna stop.') elif self.deffectDetectionMode == 'off': logging.info('Detection mode: OFF') else: logging.warning('Input not recognized, not gonna detect.') def setSavingDirectory(self, directory='/home/smartex/teste_tojo/'): self.savingDirectory = directory if not os.path.exists(self.savingDirectory): os.makedirs(self.savingDirectory) def saveImage(self): try: time1 = datetime.datetime.now() ueye.is_AllocImageMem(self.hcam, self.sensorinfo.nMaxWidth, self.sensorinfo.nMaxHeight, 24, self.pccmem, self.memID) ueye.is_SetImageMem(self.hcam, self.pccmem, self.memID) ueye.is_SetDisplayPos(self.hcam, 100, 100) self.nret = ueye.is_FreezeVideo(self.hcam, ueye.IS_WAIT) self.imageTimeStamp = datetime.datetime.now().strftime( '%Y_%m_%d_%H_%M_%S') self.imageName = 'imagem_%s.jpg' % self.imageTimeStamp self.imagePath = self.savingDirectory + self.imageName self.FileParams = ueye.IMAGE_FILE_PARAMS() self.FileParams.pwchFileName = self.imagePath self.FileParams.nFileType = ueye.IS_IMG_BMP self.FileParams.ppcImageMem = None self.FileParams.pnImageID = None self.nret = ueye.is_ImageFile(self.hcam, ueye.IS_IMAGE_FILE_CMD_SAVE, self.FileParams, ueye.sizeof(self.FileParams)) ueye.is_FreeImageMem(self.hcam, self.pccmem, self.memID) sleep(.1) ueye.is_ExitCamera(self.hcam) time2 = datetime.datetime.now() elapsed_time = time2 - time1 logging.info('Saved: {}! Elasped time (ms): {}'.format( self.imageName, elapsed_time.microseconds / 1000)) except: logging.warning('NOT SAVED: {}!\n'.format(self.imageName)) pass 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.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' logging.info("Defeito agulha!") if lycraDeffectDetected[0]: self.fabric['defect'] = lycraDeffectDetected[1] logging.info("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: 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)) except: logging.warning('Fabric DB instance not saved in MongoDB\n') pass sleep(1) i += 1