示例#1
0
 def get_image(self, image_id):
     """Download an image from the FarmBot Web App API."""
     if USE_FARMWARE_TOOLS:
         image_json = app.get('images', image_id)
     else:
         response = self.api_get('images/' + str(image_id))
         image_json = response.json() if response.status_code == 200 else {}
     try:
         image_url = image_json['attachment_url']
     except KeyError:
         image_filename = None
     else:
         try:
             testfilename = self.dir + 'test_write.try_to_write'
             testfile = open(testfilename, "w")
             testfile.close()
             os.remove(testfilename)
         except IOError:
             directory = '/tmp/'
         else:
             directory = self.dir
         image_filename = directory + str(image_id) + '.jpg'
         self._download_image_from_url(image_filename, image_url)
         self.coordinates = list([
             int(image_json['meta']['x']),
             int(image_json['meta']['y']),
             int(image_json['meta']['z'])
         ])
     return image_filename
示例#2
0
    def get_peripheral_cached(self, peripheral_name):
        cache_id = "peripherals"
        lifetime = 60 * 60

        if cache.is_cached(cache_id):
            log(
                "hit; using cached result: {}".format(cache.get(cache_id)),
                title="get_peripheral_cached",
            )
            res = cache.get(cache_id)
        else:
            res = app.get("peripherals")
            log("miss; loading from API: {}".format(res),
                title="get_peripheral_cached")

            # if not the expected response, replace with stub for debugging locally
            if type(res) is list and len(res) > 0:
                cache.save(cache_id, res, lifetime)
            else:  # for debugging
                res = [{"pin": 999, "label": "water"}]

        # find peripheral in results
        try:
            out = next(item for item in res
                       if item["label"].lower() == peripheral_name.lower())
        except:
            raise Exception(
                "Cannot find peripheral_name {} in results {}".format(
                    peripheral_name, res))

        return out
示例#3
0
文件: Farmbot.py 项目: avonwyss/MLH
def __create_identifiable(endpoint: str, typ: Type[TIdentifiable]) -> Dict[Union[str, int], TIdentifiable]:
    factory = get_factory(typ)
    result: Dict[Union[str, int], TIdentifiable] = dict()
    for data in app.get(endpoint):
        instance: TIdentifiable = factory(data)
        result[instance.id] = instance
        result[instance.name] = instance
    return result
示例#4
0
def run_tests(app_login):
    'Run app tests.'
    TIMESTAMP = str(int(time.time()))
    print(app.log('hi', get_info=app_login))
    print(app.request('GET', 'tools', get_info=app_login))
    print(app.request('GET', 'tools', return_dict=True, get_info=app_login))
    print(app.get('sensors', get_info=app_login))
    print(app.search_logs({'type': 'warn'}, get_info=app_login))
    print(app.get('sensors', return_dict=True, get_info=app_login))
    print(app.get('invalid_endpoint', get_info=app_login))
    print(app.post('tools', payload='invalid payload', get_info=app_login))
    TOOL = app.post('tools', payload={'name': 'test_tool_' + TIMESTAMP},
                    get_info=app_login)
    print(TOOL)
    TOOL_ID = TOOL['id']
    print(app.put('tools', TOOL_ID,
                  payload={'name': 'test_tool_edit_' + TIMESTAMP},
                  get_info=app_login))
    print(app.delete('tools', TOOL_ID, get_info=app_login))
    print(app.search_points({'pointer_type': 'Plant'}, get_info=app_login))
    print(app.get_points(get_info=app_login))
    print(app.get_plants(get_info=app_login))
    print(app.get_toolslots(get_info=app_login))
    print(app.get_property('device', 'name', get_info=app_login))
    print(app.download_plants(get_info=app_login))
    PLANT = app.add_plant(x=100, y=100, get_info=app_login)
    print(PLANT)
    PLANT_ID = PLANT['id']
    print(app.delete('points', PLANT_ID, get_info=app_login))
    PLANT2 = app.add_plant(x=10, y=20, z=30, radius=10, openfarm_slug='mint',
                           name='test', get_info=app_login)
    print(PLANT2)
    print(app.delete('points', PLANT2['id'], get_info=app_login))
    app.post('sequences', {'name': 'test', 'body': []}, get_info=app_login)
    app.post('sequences', {'name': u'test \u2713', 'body': []},
             get_info=app_login)
    print(app.find_sequence_by_name(name=u'test \u2713', get_info=app_login))
    print(app.find_sequence_by_name(name='test', get_info=app_login))
    print()
示例#5
0
    def read_sensor(self):
        read = device.read_pin(59, "Soil sensor", 1)
        #device.log(message=str(read), message_type="info")
        values = app.get("sensor_readings")

        tabValues = []

        for input in values:
            tabValues.append(input.get("value"))
            #device.log(message=str(input.get("value")), message_type="info")

        lastVal = 1 - tabValues[len(tabValues) - 1] / 1023

        return lastVal
示例#6
0
    def save_plant(save_point):
        """ Execute the PUT points/{id} API call.

        Arguments:
            point {dict} -- Celeryscript Point JSON object to update

        Raises:
            e -- exception
        """
        try:
            if len(save_point) < 2:
                log("Nothing to save: {}".format(save_point),
                    title="save_plant")
                return

            if Logger.LOGGER_LEVEL < 3:
                if "meta" in save_point:
                    # to avoid replacing older point meta data, we load it and merge it
                    log(
                        "Loading plant data from API for ID: {}".format(
                            save_point["id"]),
                        title="save_plant",
                    )
                    plant_data_from_api = app.get("points/{}".format(
                        save_point["id"]))

                    if "meta" in plant_data_from_api:
                        # see https://stackoverflow.com/a/26853961
                        save_point["meta"] = {
                            **plant_data_from_api["meta"],
                            **save_point["meta"],
                        }

                log("Saving Point: {}".format(save_point), title="save_plant")

                endpoint = "points/{}".format(save_point["id"])
                app.put(endpoint, payload=save_point)
            else:
                log(
                    "FAKE Saving Point (debug level = 3): {}".format(
                        save_point),
                    title="save_plant",
                )

        except Exception as e:
            log("Exception thrown: {}".format(e), "error", title="save_plant")
            raise e
示例#7
0
    def load_sequences_ids(self):
        self.sequences = app.get("sequences")

        self.config["sequence_init_dic"] = {}
        self.config["sequence_beforemove_dic"] = {}
        self.config["sequence_aftermove_dic"] = {}
        self.config["sequence_end_dic"] = {}

        for s in self.sequences:
            for e in self.config["sequence_init"]:
                if str(s["name"]).lower() == e.lower():
                    self.config["sequence_init_dic"][s["name"]] = int(s["id"])
            for e in self.config["sequence_beforemove"]:
                if str(s["name"]).lower() == e.lower():
                    self.config["sequence_beforemove_dic"][s["name"]] = int(
                        s["id"])
            for e in self.config["sequence_aftermove"]:
                if str(s["name"]).lower() == e.lower():
                    self.config["sequence_aftermove_dic"][s["name"]] = int(
                        s["id"])
            for e in self.config["sequence_end"]:
                if str(s["name"]).lower() == e.lower():
                    self.config["sequence_end_dic"][s["name"]] = int(s["id"])

        log(
            "init: {}".format(self.config["sequence_init_dic"]),
            title="load_sequences_id",
        )
        log(
            "before: {}".format(self.config["sequence_beforemove_dic"]),
            title="load_sequences_id",
        )
        log(
            "after: {}".format(self.config["sequence_aftermove_dic"]),
            title="load_sequences_id",
        )
        log("end: {}".format(self.config["sequence_end_dic"]),
            title="load_sequences_id")
示例#8
0
文件: Farmbot.py 项目: avonwyss/MLH
 def __init__(self, config_type: Type[TConfig], manifest_name: Optional[str]):
     self.debug = False
     self.local = False
     self.app_name = manifest_name or type(self).__name__
     device.log(f"Initializing farmware {type(self).__name__} with manifest name {self.app_name}", "debug")
     rx = re.compile(f"^{re.escape(self.app_name.replace('-', '_'))}_([a-z_]+)$", re.IGNORECASE)
     config = {}
     for env in os.environ.items():
         match = rx.match(env[0])
         if match:
             name = match.group(1).lower()
             if name == 'action':
                 if env[1].lower() != 'real':
                     self.debug = True
                     device.log('TEST MODE, NO sequences or movement will be run, plants will NOT be updated', 'warn')
             else:
                 config[name] = env[1]
     device.log(f"Farmware raw config: {json.dumps(config)}", 'debug')
     try:
         self.config = deserialize(config_type, config)
     except Exception as e:
         raise ValueError('Error getting farmware config: ' + str(e))
     import utils
     utils.tz = int(app.get('device')['tz_offset_hrs'])
示例#9
0
#!/usr/bin/env python
'''Hello Farmware

A simple Farmware example that tells FarmBot to log a new message.
'''

from farmware_tools import device
from farmware_tools import app
'''def keepValues(input):
    device.log(input)
    return input.get("value")'''

device.log(message='Hello world 21', message_type='success')

#res = device.read_pin(59, "Soil sensor", 1)
#device.log(message=str(res), message_type="info")

res2 = app.get("sensor_readings")
#device.log(message=str(res2), message_type="info")

tabValues = []

for input in res2:
    tabValues.append(input.get("value"))
    #device.log(message=str(input.get("value")), message_type="info")

device.log(message=str(tabValues), message_type="info")

device.log(message='Fin hello farmware', message_type='success')