예제 #1
0
 def load_sequences_id(self):
     self.sequences = self.api.api_get('sequences')
     self.input_sequence_init_dic = {}
     self.input_sequence_beforemove_dic = {}
     self.input_sequence_aftermove_dic = {}
     self.input_sequence_end_dic = {}
     for s in self.sequences:
         for e in self.input_sequence_init:
             if str(s['name']).lower() == e.lower() : self.input_sequence_init_dic[s['name']] = int(s['id'])
         for e in self.input_sequence_beforemove:
             if str(s['name']).lower() == e.lower() : self.input_sequence_beforemove_dic[s['name']] = int(s['id'])
         for e in self.input_sequence_aftermove:
             if str(s['name']).lower() == e.lower() : self.input_sequence_aftermove_dic[s['name']] = int(s['id'])
         for e in self.input_sequence_end:   
             if str(s['name']).lower() == e.lower() : self.input_sequence_end_dic[s['name']] = int(s['id'])    
     if self.input_debug >= 1:
         log('init: {}'.format(self.input_sequence_init_dic), message_type='debug', title=str(self.farmwarename) + ' : load_sequences_id')
         log('before: {}'.format(self.input_sequence_beforemove_dic) , message_type='debug', title=str(self.farmwarename) + ' : load_sequences_id')
         log('after: {}'.format(self.input_sequence_aftermove_dic) , message_type='debug', title=str(self.farmwarename) + ' : load_sequences_id')
         log('end: {}'.format(self.input_sequence_end_dic), message_type='debug', title=str(self.farmwarename) + ' : load_sequences_id')
예제 #2
0
 def capture(self):
     """Take a photo."""
     if CAMERA == 'RPI':
         # With Raspberry Pi Camera:
         try:
             retcode = call([
                 "raspistill", "-w", "640", "-h", "480", "-o",
                 self.save(filename_only=True)
             ])
         except OSError:
             log("Raspberry Pi Camera not detected.",
                 message_type='error',
                 title='take-photo')
             sys.exit(0)
         else:
             if retcode == 0:
                 print("Image saved: {}".format(
                     self.save(filename_only=True)))
                 return self.save(filename_only=True)
             else:
                 log("Problem getting image.",
                     message_type='error',
                     title='take-photo')
                 sys.exit(0)
     else:  # With USB camera:
         self.camera_port = 0
         # image_width = 1600
         # image_height = 1200
         discard_frames = 20
         self.camera_check()  # check for camera
         camera = cv2.VideoCapture(self.camera_port)
         sleep(0.1)
         # try:
         #     camera.set(cv2.CAP_PROP_FRAME_WIDTH, image_width)
         #     camera.set(cv2.CAP_PROP_FRAME_HEIGHT, image_height)
         # except AttributeError:
         #     camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, image_width)
         #     camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, image_height)
         for _ in range(discard_frames):
             camera.grab()
         self.ret, self.image = camera.read()
         camera.release()
         if not self.ret:
             log("Problem getting image.",
                 message_type='error',
                 title='take-photo')
             sys.exit(0)
         self.image_captured = True
         return self.save()
예제 #3
0
    def api_setup(self):
        # API requests setup
        try:
            api_token = os.environ['API_TOKEN']
        except KeyError:
            api_token = 'Not Set'
            log('API_TOKEN not set',
                message_type='error',
                title='Class API:api_setup')

        try:
            encoded_payload = api_token.split('.')[1]
            encoded_payload += '=' * (4 - len(encoded_payload) % 4)
            json_payload = base64.b64decode(encoded_payload).decode('utf-8')
            server = json.loads(json_payload)['iss']
        except:
            server = '//my.farmbot.io'

        self.api_url = 'http{}:{}/api/'.format(
            's' if 'localhost' not in server and not re.compile(
                '^//((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
            ).match(server) else '', server)
        self.headers = {
            'Authorization': 'Bearer {}'.format(api_token),
            'content-type': "application/json"
        }

        if self.farmware.input_debug >= 1:
            log(self.api_url,
                message_type='debug',
                title='Class API:api_setup')
        if self.farmware.input_debug >= 1:
            log(self.headers,
                message_type='debug',
                title='Class API:api_setup')
        if self.farmware.input_debug >= 1:
            log(json_payload,
                message_type='debug',
                title='Class API:api_setup')
예제 #4
0
    def get_input_env(self):
        prefix = self.farmwarename.lower().replace('-', '_')

        self.input_title = os.environ.get(prefix + "_title", '-')
        self.input_tool = os.environ.get(prefix + "_tool", 'BACKUP_USERENV')
        self.input_debug = int(os.environ.get(prefix + "_debug", 1))

        if self.input_debug >= 1:
            log('title: {}'.format(self.input_title),
                message_type='debug',
                title=self.farmwarename)
            log('tool: {}'.format(self.input_tool),
                message_type='debug',
                title=self.farmwarename)
            log('debug: {}'.format(self.input_debug),
                message_type='debug',
                title=self.farmwarename)
예제 #5
0
def mergearrays(matrix1, matrix2):
    res_matrix = matrix1
    row2 = matrix2[0, :, :]
    for i in range(matrix1.shape[0]):
        row1 = matrix1[i, :, :]
        res = sum(abs(row2[0] - row1[0]) +
                  abs(row2[1] - row1[1])) / row1.shape[0]
        log(str(res))
        if res < 8:
            subindex = i
            break
    counter = matrix1.shape[0] - subindex
    log(str(counter))
    res_matrix = np.concatenate((res_matrix[:, :, :], matrix2[counter:, :, :]),
                                axis=0)
    log(str(res_matrix.shape))
    return res_matrix
예제 #6
0
 def restore_bot_state(self):
     self.botstate = get_bot_state()
     if self.input_debug >= 1:
         log('botstate Before: {}'.format(self.botstate),
             message_type='debug',
             title=self.farmwarename)
     self.toolslot = self.get_toolslot(points=self.api.api_get('points'),
                                       tools=self.api.api_get('tools'),
                                       tool_name=self.input_tool)
     if self.input_debug >= 1:
         log('toolslot: {}'.format(self.toolslot),
             message_type='debug',
             title=self.farmwarename)
     for e in self.toolslot['meta']:
         if self.input_debug >= 1:
             log('set_user_env: {} => {}'.format(e,
                                                 self.toolslot['meta'][e]),
                 message_type='debug',
                 title=self.farmwarename)
         if self.input_debug < 2:
             self.check_celerypy(set_user_env(e, self.toolslot['meta'][e]))
예제 #7
0
 def backup_bot_state(self):
     self.botstate = get_bot_state()
     if self.input_debug >= 1:
         log('botstate: {}'.format(self.botstate),
             message_type='debug',
             title=self.farmwarename)
     self.toolslot = self.get_toolslot(points=self.api.api_get('points'),
                                       tools=self.api.api_get('tools'),
                                       tool_name=self.input_tool)
     if self.input_debug >= 1:
         log('toolslot Before: {}'.format(self.toolslot),
             message_type='debug',
             title=self.farmwarename)
     self.toolslot['meta'] = self.botstate["user_env"]
     if self.input_debug < 2:
         endpoint = 'points/{}'.format(self.toolslot['id'])
         self.api.api_put(endpoint=endpoint, data=self.toolslot)
     self.toolslot = self.get_toolslot(points=self.api.api_get('points'),
                                       tools=self.api.api_get('tools'),
                                       tool_name=self.input_tool)
     if self.input_debug >= 1:
         log('toolslot After: {}'.format(self.toolslot),
             message_type='debug',
             title=self.farmwarename)
예제 #8
0
    def api_setup(self):
        # API requests setup
        try:
            api_token = os.environ['API_TOKEN']
        except KeyError:
            api_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJib3QiLCJzdWIiOjE0NiwiaWF0IjoxNTE3NTY4NjI5LCJqdGkiOiI4MTRjODkzZi1lMGQzLTRhMGMtOGZkNi03ODc0ZWE4NmE1YjkiLCJpc3MiOiIvLzEwLjEuMS45MDozMDAwIiwiZXhwIjoxNTIxMDI0NjI5LCJtcXR0IjoiMTAuMS4xLjkwIiwiYm90IjoiZGV2aWNlXzIxMSIsInZob3N0IjoiLyIsIm1xdHRfd3MiOiJ3czovLzEwLjEuMS45MDozMDAyL3dzIiwib3NfdXBkYXRlX3NlcnZlciI6Imh0dHBzOi8vYXBpLmdpdGh1Yi5jb20vcmVwb3MvRmFybUJvdC9mYXJtYm90X29zL3JlbGVhc2VzLzkyMDA5NDMiLCJpbnRlcmltX2VtYWlsIjoicmRlZ29zc2VAaW5pdGhpbmsuZnIiLCJmd191cGRhdGVfc2VydmVyIjoiREVQUkVDQVRFRCIsImJldGFfb3NfdXBkYXRlX3NlcnZlciI6Ik5PVF9TRVQifQ.K8Fv-Y2XuOEa_1ZoiwO3MZYk5X4FT8tvG6UKj2GTzwq2KpGU28DySaUa7z2AnfxI_L50Yuc2GviHVKkrhFAzum4mRKXpzIBkpHnLUSc_VvPdsYIXrU_cDn5nTDrZoO_okje0hepp6SBPtCyuimf6iijpergVCNUj8w-SNuft62ZnE_0f1JI8glTjCOSuPIVAoZmlYb2sd8_m9OSivqHbagunql2uAsgfY5-88Xsh7cn5fy04S_f04-AEi3iyEqchGjlfxWu7rPuPg7jSGbv0hYzBR36H2C2YOfbPrRQlleD5kom7JXYDlrdJPV3d48NlB3SJQGxtYYM9XmafAtf2YQ'

        try:
            encoded_payload = api_token.split('.')[1]
            encoded_payload += '=' * (4 - len(encoded_payload) % 4)
            json_payload = base64.b64decode(encoded_payload).decode('utf-8')
            server = json.loads(json_payload)['iss']
        except:
            server = '//my.farmbot.io'

        self.api_url = 'http{}:{}/api/'.format(
            's' if 'localhost' not in server and not re.compile(
                '^//((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)'
            ).match(server) else '', server)
        self.headers = {
            'Authorization': 'Bearer {}'.format(api_token),
            'content-type': "application/json"
        }

        if self.farmware.input_debug >= 1:
            log(self.api_url,
                message_type='debug',
                title='Class API:api_setup')
        if self.farmware.input_debug >= 1:
            log(self.headers,
                message_type='debug',
                title='Class API:api_setup')
        if self.farmware.input_debug >= 1:
            log(json_payload,
                message_type='debug',
                title='Class API:api_setup')
예제 #9
0
    def get_input_env(self):
        prefix = self.farmwarename.lower().replace('-', '_')

        self.input_title = os.environ.get(prefix + "_title", '-')
        self.input_pointname = os.environ.get(prefix + "_pointname", '*')
        self.input_openfarm_slug = os.environ.get(prefix + "_openfarm_slug",
                                                  '*')
        self.input_age_min_day = int(
            os.environ.get(prefix + "_age_min_day", -1))
        self.input_age_max_day = int(
            os.environ.get(prefix + "_age_max_day", 36500))
        self.input_plant_stage = os.environ.get(prefix + "_plant_stage", '*')
        self.input_filter_meta_key = os.environ.get(
            prefix + "_filter_meta_key", 'None')
        self.input_filter_meta_value = os.environ.get(
            prefix + "_filter_meta_value", 'None')
        self.input_sequence_init = os.environ.get(prefix + "_sequence_init",
                                                  'None')
        self.input_sequence_beforemove = os.environ.get(
            prefix + "_sequence_beforemove", 'None')
        self.input_sequence_aftermove = os.environ.get(
            prefix + "_sequence_aftermove", 'None')
        self.input_sequence_end = os.environ.get(prefix + "_sequence_end",
                                                 'None')
        self.input_save_meta_key = os.environ.get(prefix + "_save_meta_key",
                                                  'None')
        self.input_save_meta_value = os.environ.get(
            prefix + "_save_meta_value", 'None')
        self.input_default_z = int(os.environ.get(prefix + "_default_z", 0))
        self.input_default_speed = int(
            os.environ.get(prefix + "_default_speed", 800))
        self.input_debug = int(os.environ.get(prefix + "_debug", 1))

        if self.input_debug >= 1:
            log('title: {}'.format(self.input_title),
                message_type='debug',
                title=self.farmwarename)
            log('pointname: {}'.format(self.input_pointname),
                message_type='debug',
                title=self.farmwarename)
            log('openfarm_slug: {}'.format(self.input_openfarm_slug),
                message_type='debug',
                title=self.farmwarename)
            log('age_min_day: {}'.format(self.input_age_min_day),
                message_type='debug',
                title=self.farmwarename)
            log('age_max_day: {}'.format(self.input_age_max_day),
                message_type='debug',
                title=self.farmwarename)
            log('filter_meta_key: {}'.format(self.input_filter_meta_key),
                message_type='debug',
                title=self.farmwarename)
            log('filter_meta_value: {}'.format(self.input_filter_meta_value),
                message_type='debug',
                title=self.farmwarename)
            log('sequence_init: {}'.format(self.input_sequence_init),
                message_type='debug',
                title=self.farmwarename)
            log('sequence_beforemove: {}'.format(
                self.input_sequence_beforemove),
                message_type='debug',
                title=self.farmwarename)
            log('sequence_aftermove: {}'.format(self.input_sequence_aftermove),
                message_type='debug',
                title=self.farmwarename)
            log('sequence_end: {}'.format(self.input_sequence_end),
                message_type='debug',
                title=self.farmwarename)
            log('save_meta_key: {}'.format(self.input_save_meta_key),
                message_type='debug',
                title=self.farmwarename)
            log('save_meta_value: {}'.format(self.input_save_meta_value),
                message_type='debug',
                title=self.farmwarename)
            log('default_z: {}'.format(self.input_default_z),
                message_type='debug',
                title=self.farmwarename)
            log('default_speed: {}'.format(self.input_default_speed),
                message_type='debug',
                title=self.farmwarename)
            log('debug: {}'.format(self.input_debug),
                message_type='debug',
                title=self.farmwarename)
예제 #10
0
 def log_input(self):
     log('title: {}'.format(self.input_title),
         message_type='info',
         title=self.farmwarename)
     log('filter_min_x: {}'.format(self.input_filter_min_x),
         message_type='info',
         title=self.farmwarename)
     log('filter_max_x: {}'.format(self.input_filter_max_x),
         message_type='info',
         title=self.farmwarename)
     log('filter_min_y: {}'.format(self.input_filter_min_y),
         message_type='info',
         title=self.farmwarename)
     log('filter_max_y: {}'.format(self.input_filter_max_y),
         message_type='info',
         title=self.farmwarename)
     log('sequence_init: {}'.format(self.input_sequence_init),
         message_type='info',
         title=self.farmwarename)
     log('sequence_beforemove: {}'.format(self.input_sequence_beforemove),
         message_type='info',
         title=self.farmwarename)
     log('sequence_aftermove: {}'.format(self.input_sequence_aftermove),
         message_type='info',
         title=self.farmwarename)
     log('sequence_end: {}'.format(self.input_sequence_end),
         message_type='info',
         title=self.farmwarename)
     log('offset_x: {}'.format(self.input_offset_x),
         message_type='info',
         title=self.farmwarename)
     log('offset_y: {}'.format(self.input_offset_y),
         message_type='info',
         title=self.farmwarename)
     log('default_z: {}'.format(self.input_default_z),
         message_type='info',
         title=self.farmwarename)
     log('default_speed: {}'.format(self.input_default_speed),
         message_type='info',
         title=self.farmwarename)
     log('debug: {}'.format(self.input_debug),
         message_type='info',
         title=self.farmwarename)
예제 #11
0
import os

from FARMWARE import MyFarmware
from CeleryPy import log
from CeleryPy import read_status

from ENV import redis_load
from ENV import load

if __name__ == "__main__":

    FARMWARE_NAME = "Test-Farmware"

    log('Start...', message_type='info', title=FARMWARE_NAME)

    #log(read_status(), message_type='info', title=FARMWARE_NAME)

    #log(os.environ.get('FARMWARE_URL','not set'), message_type='info', title=FARMWARE_NAME)

    log(redis_load(key='location.position', name='x'),
        message_type='info',
        title=FARMWARE_NAME)
    log(load(name='location'), message_type='info', title=FARMWARE_NAME)
    log(os.environ, message_type='info', title=FARMWARE_NAME)
    """
    try:
        farmware = MyFarmware(FARMWARE_NAME)
    except Exception as e:
        log(e ,message_type='error', title=FARMWARE_NAME + " : init" )
        raise Exception(e)
    else:
예제 #12
0
 def count_downloaded_plants(self):
     plant_count = len(self.plants['known'])
     log("{} weeds were detected.".format(plant_count),
         message_type='info',
         title='WeedStomp')
예제 #13
0
                              headers=self.headers)
            print(r, r.json())
            self.response = r

        if self.search_sequence_counter < 3:
            with Sequence("FW_WeedStomp", "green", upload) as s:
                s.write_pin(number=10, value=1, mode=0)
                s.wait(milliseconds=200)
                s.write_pin(number=10, value=0, mode=0)
        if self.response.status_code == 422:
            log("Cant create sequence because this name already exists. Check for upper- and lowercases.",
                message_type='info',
                title='WeedStomp')
        if self.response.status_code == 200:
            log("Created a sequence named FW_WeedStomp.",
                message_type='info',
                title='WeedStomp')
            CeleryPy.sync()
            a.load_sequences_from_app()
        else:
            print("There was an Error creating the sequence.")

if __name__ == "__main__":
    a = WeedStomp()

    log("Starting", message_type='info', title='WeedStomp')

    a.load_weeds_from_web_app()
    a.count_downloaded_plants()
    a.load_sequences_from_app()
예제 #14
0
import os
from FARMWARE import MyFarmware
from CeleryPy import log
import sys

if __name__ == "__main__":

    #FARMWARE_NAME = "Loop-Plants-With-Filters"
    FARMWARE_NAME = ((__file__.split(os.sep))[len(__file__.split(os.sep)) -
                                              3]).replace('-master', '')

    log('Start...', message_type='info', title=FARMWARE_NAME)

    try:
        reload(sys)
        sys.setdefaultencoding('utf8')  #force utf8 for celerypy return code
    except:
        pass

    try:
        farmware = MyFarmware(FARMWARE_NAME)
    except Exception as e:
        log(e, message_type='error', title=FARMWARE_NAME + " : init")
        raise Exception(e)
    else:
        try:
            farmware.run()
        except Exception as e:
            log(e, message_type='error', title=FARMWARE_NAME + " : run")
            raise Exception(e)
예제 #15
0
 def save_data_csv(value):
     """To save data into a csv file"""
     with open(self.dir + 'db_plant_radius_test.csv', mode='a') as dbprt:
         db_writer = csv.writer(dbprt, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
         db_writer.writerow([strftime("%Y-%m-%d_%H:%M:%S", gmtime()), value])
     log('Data is supposed to have been saved into db_plant_radius_test.csv')
예제 #16
0
 def count_downloaded_plants(self):
     plant_count = len(self.plants['known'])
     log( "{} plants were detected." .format(plant_count)
         ,message_type= 'info',title= 'Water-everything')
예제 #17
0
 def sort_points(self):
     self.points = sorted(self.points , key=lambda elem: (int(elem['x']), int(elem['y'])))
     if self.input_debug >= 1: log(self.points, message_type='debug', title=str(self.farmwarename) + ' : sort_points')
예제 #18
0
 def execute_sequence_end(self):
     if self.input_sequence_end_id != -1 : 
         if self.input_debug >= 1: log('Execute Sequence: ' + self.input_sequence_end + ' id:' + str(self.input_sequence_end_id), message_type='debug', title=str(self.farmwarename) + ' : execute_sequence_end')
         if self.input_debug < 2: self.check_celerypy(execute_sequence(sequence_id=self.input_sequence_end_id))
     else:
         if self.input_debug >= 1: log('Sequence Not Found' , message_type='debug', title=str(self.farmwarename) + ' : execute_sequence_end')
예제 #19
0
import os
from farmware_process import MyFarmware
from CeleryPy import log
import sys

if __name__ == "__main__":
    FARMWARE_NAME = "prueba_1_moverFB"
    log('los patitos dicen cuacua', message_type='info', title=FARMWARE_NAME)
    reload(sys)
    sys.setdefaultencoding('utf8')
    try:
        farmware = MyFarmware(FARMWARE_NAME)
    except Exception as e:
        log(e, message_type='error', title=FARMWARE_NAME + " : init")
        raise Exception(e)
    else:
        try:
            farmware.run()
        except Exception as e:
            log(e, message_type='error', title=FARMWARE_NAME + " : run")
raise Exception(e)
예제 #20
0
                        "iters": 1
                    }],
                    HSV_min=[49, 95, 50],
                    HSV_max=[110, 255, 255])
PD.detect_plants()  # detect coordinates and sizes of weeds and plants
if len(PD.plant_db.coordinate_locations) >= 1:
    holes = []
    for coordinate_location in PD.plant_db.coordinate_locations:
        if 19 > coordinate_location[2] > 7 and coordinate_location[
                0] < 950 and coordinate_location[1] > 200:
            holes.append([coordinate_location[0], coordinate_location[1]])
    rows, cols = array_shape(holes)
    matrix10 = np.zeros((rows, cols, 2))
    matrix10 = fill_array(matrix10, holes)
    matrix10 = matrix10[:, 0:6, :]
    log(str(matrix10.shape))
######################_______________________________________________________##################################################
CeleryPy.move_absolute((845, 600, 0), (0, 0, 0), 150)
CeleryPy.wait(5000)
file = Capture().capture()
img2 = cv2.imread(file, 1)
image_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
circles = cv2.HoughCircles(image_gray,
                           cv2.HOUGH_GRADIENT,
                           1,
                           12,
                           param1=65,
                           param2=30,
                           minRadius=15,
                           maxRadius=34)
circles = np.uint16(np.around(circles))
예제 #21
0
 def mov_robot_photo(self):
     log('Execute move: ', message_type='debug', title=str(self.farmwarename))
     move_absolute(
         location=[self.x_photo_pos, self.y_photo_pos, self.z_photo_pos],
         offset=[0, 0, 0],
         speed=800)
예제 #22
0
 def mov_robot_origin(self):
     log('Execute move: ', message_type='debug', title=str(self.farmwarename))
     move_absolute(
         location=[0, 0, 0],
         offset=[0, 0, 0],
         speed=800)
예제 #23
0
#!/usr/bin/env python
import os
from CeleryPy import log
import sys

if __name__ == "__main__":
    """FARMWARE_NAME = ((__file__.split(os.sep))[len(__file__.split(os.sep)) - 3]).replace('-master', '')"""
    """log('Start... hello world!', message_type='info', title=FARMWARE_NAME)"""
    log('Helllooo fukiiinnn worlllddd')
    """sys.setdefaultencoding('utf8')"""
예제 #24
0
                            "kernel": 'ellipse',
                            "type": 'erode',
                            "iters": 1
                        }],
                        HSV_min=[49, 95, 50],
                        HSV_max=[110, 255, 255])
    PD.detect_plants()  # detect coordinates and sizes of weeds and plants
    if len(PD.plant_db.coordinate_locations) >= 1:
        holes = []
        for coordinate_location in PD.plant_db.coordinate_locations:
            if coordinate_location[2] > 10.5 and coordinate_location[1] > 200:
                holes.append([coordinate_location[0], coordinate_location[1]])
        rows, cols = array_shape(holes)
        matrix00 = np.zeros((rows, cols, 2))
        matrix00 = fill_array(matrix00, holes)
        log(str(matrix00.shape))
#######___________________________________________________-####################################
    CeleryPy.move_absolute((500, 600, 0), (0, 0, 0), 150)
    CeleryPy.wait(5000)
    file = Capture().capture()
    img2 = cv2.imread(file, 1)
    image = invert(img2)
    image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    res = cv2.matchTemplate(image_gray, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.7)
    for pt in zip(*loc[::-1]):
        cv2.circle(img2, (int(pt[0] + w / 2), int(pt[1] + h / 2)), 15,
                   (0, 255, 0), cv2.FILLED)
    new_image = img2
    cv2.imwrite('/tmp/images/1549138022.jpg', new_image)
    mask = create_mask(new_image, np.array([HL, SL, VL]),
예제 #25
0
    def get_input_env(self):
        prefix = self.farmwarename.lower().replace('-','_')
        
        self.input_title = os.environ.get(prefix+"_title", '-')
        self.input_id = os.environ.get(prefix+"_id", '*')
        self.input_pointname = os.environ.get(prefix+"_pointname", '*')
        self.input_openfarm_slug = os.environ.get(prefix+"_openfarm_slug", '*')
        self.input_age_min_day = int(os.environ.get(prefix+"_age_min_day", -1))
        self.input_age_max_day = int(os.environ.get(prefix+"_age_max_day", 36500))
        self.input_filter_meta_key = os.environ.get(prefix+"_filter_meta_key", 'None')
        self.input_filter_meta_value = os.environ.get(prefix+"_filter_meta_value", 'None')
        self.input_filter_min_x = os.environ.get(prefix+"_filter_min_x", 'None')
        self.input_filter_max_x = os.environ.get(prefix+"_filter_max_x", 'None')
        self.input_filter_min_y = os.environ.get(prefix+"_filter_min_y", 'None')
        self.input_filter_max_y = os.environ.get(prefix+"_filter_max_y", 'None')
        self.input_save_name = os.environ.get(prefix+"_save_name", 'None')
        self.input_remove_all_metadata = os.environ.get(prefix+"_remove_all_metadata", 'No')
        self.input_save_meta_key = os.environ.get(prefix+"_save_meta_key", 'None')
        self.input_save_meta_value = os.environ.get(prefix+"_save_meta_value", 'None')
        self.input_save_date = os.environ.get(prefix+"_save_date", 'None')
        self.input_debug = int(os.environ.get(prefix+"_debug", 1))

        if self.input_debug >= 1:
            log('title: {}'.format(self.input_title), message_type='debug', title=self.farmwarename)
            log('id: {}'.format(self.input_id), message_type='debug', title=self.farmwarename)
            log('pointname: {}'.format(self.input_pointname), message_type='debug', title=self.farmwarename)
            log('openfarm_slug: {}'.format(self.input_openfarm_slug), message_type='debug', title=self.farmwarename)
            log('age_min_day: {}'.format(self.input_age_min_day), message_type='debug', title=self.farmwarename)
            log('age_max_day: {}'.format(self.input_age_max_day), message_type='debug', title=self.farmwarename)
            log('filter_meta_key: {}'.format(self.input_filter_meta_key), message_type='debug', title=self.farmwarename)
            log('filter_meta_value: {}'.format(self.input_filter_meta_value), message_type='debug', title=self.farmwarename)
            log('filter_min_x: {}'.format(self.input_filter_min_x), message_type='debug', title=self.farmwarename)
            log('filter_max_x: {}'.format(self.input_filter_max_x), message_type='debug', title=self.farmwarename)
            log('filter_min_y: {}'.format(self.input_filter_min_y), message_type='debug', title=self.farmwarename)
            log('filter_max_y: {}'.format(self.input_filter_max_y), message_type='debug', title=self.farmwarename)
            log('save_name: {}'.format(self.input_save_name), message_type='debug', title=self.farmwarename)
            log('remove_all_metadata: {}'.format(self.input_remove_all_metadata), message_type='debug', title=self.farmwarename)
            log('save_meta_key: {}'.format(self.input_save_meta_key), message_type='debug', title=self.farmwarename)
            log('save_meta_value: {}'.format(self.input_save_meta_value), message_type='debug', title=self.farmwarename)
            log('save_date: {}'.format(self.input_save_date), message_type='debug', title=self.farmwarename)
            log('debug: {}'.format(self.input_debug), message_type='debug', title=self.farmwarename)
예제 #26
0
for cl in PD.plant_db.coordinate_locations:
    if cl[2] > 12.0:
        radios.append(cl[2])
        radios_counter = radios_counter + 1
suma_radios = sum(radios)
try:
    if suma_radios / radios_counter >= 15.0:
        #O=len(PD.plant_db.coordinate_locations)
        dir_path = os.path.dirname(os.path.realpath(__file__))
        matrix = np.load(dir_path + '/' + 'array1.npy')
        matrix2 = np.load(dir_path + '/' + 'array2.npy')
        matrix3 = np.load(dir_path + '/' + 'array3.npy')
        matrix4 = np.load(dir_path + '/' + 'array4.npy')
        for coordinate_location in PD.plant_db.coordinate_locations:
            log("Plant detected at X = {:5.0f} mm, Y = {:5.0f} mm with R = {:.1f} mm"
                .format(coordinate_location[0], coordinate_location[1],
                        coordinate_location[2]))
        send_message(message='TUDO BEM',
                     message_type='success',
                     channel='toast')
        CeleryPy.move_absolute(weeder, (0, 0, 0), 150)
        CeleryPy.move_absolute(weeder, (100, 0, 0), 150)
        CeleryPy.move_absolute(weeder, (100, 0, 100), 150)
        CeleryPy.move_absolute(weeder, (100, 0, 200), 150)
        CeleryPy.write_pin(number=4, value=1, mode=0)
        CeleryPy.wait(100)
        CeleryPy.write_pin(number=4, value=0, mode=0)
        CeleryPy.wait(200)
        CeleryPy.write_pin(number=4, value=1, mode=0)

        for i, coordinate_location in enumerate(
예제 #27
0
import os
import sys

from CeleryPy import log
from DB import DB

if __name__ == "__main__":

    log("Lets do this.", message_type='info', title='Water-everything')

    plantdb = DB()

    plantdb.load_plants_from_web_app()  #Get plant points from Webapp
    plantdb.count_downloaded_plants()  #Print Plantcount in log
    plantdb.load_sequences_from_app(
    )  #Get sequences and determine the sequence id
    plantdb.loop_plant_points(
    )  #Move to plant points and water them with the Water on/off sequence
예제 #28
0
 def apply_filters(self,
                   points,
                   point_name='',
                   openfarm_slug='',
                   age_min_day=0,
                   age_max_day=36500,
                   meta_key='',
                   meta_value='',
                   min_x='none',
                   max_x='none',
                   min_y='none',
                   max_y='none',
                   pointer_type='Plant',
                   plant_stage='none'):
     if self.input_debug >= 1:
         log(points,
             message_type='debug',
             title=str(self.farmwarename) + ' : load_points')
     filtered_points = []
     now = datetime.datetime.utcnow()
     for p in points:
         if p['pointer_type'].lower() == pointer_type.lower():
             b_meta = False
             if str(p['planted_at']).lower() == 'none' or str(
                     p['planted_at']).lower() == None:
                 ref_date = p['created_at']
             else:
                 ref_date = p['planted_at']
             age_day = (now - datetime.datetime.strptime(
                 ref_date, '%Y-%m-%dT%H:%M:%S.%fZ')).days
             if str(meta_key).lower() != 'none':
                 try:
                     if self.input_filter_meta_op.lower(
                     ) == "none" or self.input_filter_meta_op.lower(
                     ) == "==":
                         b_meta = ((p['meta'][meta_key]
                                    ).lower() == meta_value.lower())
                     elif self.input_filter_meta_op == ">=":
                         b_meta = ((p['meta'][meta_key]) >= meta_value)
                     elif self.input_filter_meta_op == "<=":
                         b_meta = ((p['meta'][meta_key]) <= meta_value)
                     elif self.input_filter_meta_op == "<":
                         b_meta = ((p['meta'][meta_key]) < meta_value)
                     elif self.input_filter_meta_op == ">":
                         b_meta = ((p['meta'][meta_key]) > meta_value)
                     elif self.input_filter_meta_op == "!=":
                         b_meta = ((p['meta'][meta_key]).lower() !=
                                   meta_value.lower())
                     elif self.input_filter_meta_op.lower() == "regex":
                         b_meta = bool(
                             re.compile(meta_value).match(
                                 p['meta'][meta_key]))
                     elif self.input_filter_meta_op.lower() == "daysmax":
                         b_meta = bool(
                             (datetime.datetime.utcnow() -
                              datetime.datetime.strptime(
                                  p['meta'][meta_key],
                                  '%Y-%m-%d %H:%M:%S.%f')).total_seconds() /
                             86400 <= int(meta_value))
                     elif self.input_filter_meta_op.lower() == "minutesmax":
                         b_meta = bool(
                             (datetime.datetime.utcnow() -
                              datetime.datetime.strptime(
                                  p['meta'][meta_key],
                                  '%Y-%m-%d %H:%M:%S.%f')).total_seconds() /
                             60 <= int(meta_value))
                     elif self.input_filter_meta_op.lower() == "daysmin":
                         b_meta = bool(
                             (datetime.datetime.utcnow() -
                              datetime.datetime.strptime(
                                  p['meta'][meta_key],
                                  '%Y-%m-%d %H:%M:%S.%f')).total_seconds() /
                             86400 >= int(meta_value))
                     elif self.input_filter_meta_op.lower() == "minutesmin":
                         b_meta = bool(
                             (datetime.datetime.utcnow() -
                              datetime.datetime.strptime(
                                  p['meta'][meta_key],
                                  '%Y-%m-%d %H:%M:%S.%f')).total_seconds() /
                             60 >= int(meta_value))
                     else:
                         b_meta = False
                 except Exception as e:
                     if self.input_debug >= 1:
                         log(e,
                             message_type='error',
                             title=str(self.farmwarename) +
                             ' : exception filter_meta')
                     b_meta = False
             else:
                 b_meta = True
             if str(min_x).lower() == 'none' or str(
                     max_x).lower() == 'none':
                 b_coordinate_x = True
             else:
                 if int(min_x) <= int(p['x']) <= int(max_x):
                     b_coordinate_x = True
                 else:
                     b_coordinate_x = False
             if str(min_y).lower() == 'none' or str(
                     max_y).lower() == 'none':
                 b_coordinate_y = True
             else:
                 if int(min_y) <= int(p['y']) <= int(max_y):
                     b_coordinate_y = True
                 else:
                     b_coordinate_y = False
             if plant_stage.lower() == 'none':
                 b_plantstage = True
             else:
                 try:
                     if plant_stage.lower() == p['plant_stage'].lower():
                         b_plantstage = True
                     else:
                         b_plantstage = False
                 except Exception as e:
                     b_plantstage = True
             if (p['name'].lower() == point_name.lower(
             ) or point_name == '*') and (p['openfarm_slug'].lower(
             ) == openfarm_slug.lower() or openfarm_slug == '*') and (
                     age_min_day <= age_day <= age_max_day
             ) and b_meta == True and b_coordinate_x and b_coordinate_y and b_plantstage:
                 filtered_points.append(p.copy())
     return filtered_points
예제 #29
0
import os
from FARMWARE import MyFarmware
from CeleryPy import log
import sys

if __name__ == "__main__":
    FARMWARE_NAME = "Motion_test"
    log('Come on, man, just move yourself on', message_type='info', title=FARMWARE_NAME)
    reload(sys)
    sys.setdefaultencoding('utf8')
    try:
        farmware = MyFarmware(FARMWARE_NAME)
    except Exception as e:
        log(e, message_type='error', title=FARMWARE_NAME + " : init")
        raise Exception(e)
    else:
        try:
            farmware.run()
        except Exception as e:
            log(e ,message_type='error', title=FARMWARE_NAME + " : run" )
            raise Exception(e)
예제 #30
0
 def save(image):
     """Save the plot image."""
     filename = '/test_data_plot_{}.png'.format(int(time()))
     log('Image to be saved in: ' + self.dir + filename)
     cv2.imwrite(self.dir + filename, image)