def __init__(self, config_file='/config/switch.txt'):
     config_loader = ConfigurationLoader(config_file)
     configs = config_loader.load_configuration('mqtt_broker', 'mqtt_topic',
                                                'mqtt_id', 'switch_pin',
                                                'switch_update_period')
     self.config_file = config_file
     self.switch_update_period = int(configs['switch_update_period'])
     self.mqtt_client = MQTTClient(configs['mqtt_id'],
                                   configs['mqtt_broker'])
     self.mqtt_client.DEBUG = True
     self.mqtt_topic = configs['mqtt_topic']
     self.switch_pin_num = int(configs['switch_pin'])
     self.switch_pin = Pin(self.switch_pin_num, Pin.IN)
     self.id = configs['mqtt_id']
     self.mqtt_broker = configs['mqtt_broker']
     self.logger = MyLogger(False)
     self.logger.log('DEBUG', self.id,
                     'Connecting to {}...'.format(self.mqtt_broker))
     try:
         self.mqtt_client.connect()
         self.logger.log('INFO', self.id,
                         'Reconnected to {}'.format(self.mqtt_broker))
     except:
         self.logger.log(
             'ERROR', self.id,
             'Connection failure to {}'.format(self.mqtt_broker))
     self.last_switch_position = self.switch_pin.value()
     self.mqtt_messages_sent = 0
     self.debounce_time = 0.5
     self.timer = None
     self.init_timer()
    def __init__(self):
        self.config_file = os.path.dirname(os.path.abspath(__file__)) + '/config.json'
        config_data = self.load_configuration()

        self.command_runner = SystemCommandRunner()
        self.configuration = ConfigurationLoader(json_config_data=config_data)
        self.git_handler = GitHandler(project_path=self.configuration.get_project_path_value())
Beispiel #3
0
 def __init__(self, config_file):
     self.config_loader = ConfigurationLoader(config_file)
     configs = self.config_loader.load_configuration(
         'check_delay', 'broker', 'topic', 'mqtt_id',
         'installed_version_file', 'mqtt_logger_conf')
     self.check_delay = int(configs['check_delay'])
     self.logger = MyLogger(True, configs['mqtt_logger_conf'])
     self.mqtt_client = MQTTClient(configs['mqtt_id'], configs['broker'])
     self.mqtt_client.DEBUG = True
     self.mqtt_client.set_callback(self.read_update)
     self.mqtt_topic = configs['topic']
Beispiel #4
0
	def __init__(self, config_file, networks_file):
		self.config_loader = ConfigurationLoader(config_file)
		self.wlan = network.WLAN(network.STA_IF)
		self.wlan.active(False)
		sleep(0.5)
		self.wlan.active(True)
		sleep(0.5)
		self.wlan.disconnect()
		configs = self.config_loader.load_configuration('check_delay', 'mqtt_conf_file')
		self.check_delay = int(configs['check_delay'])
		mqtt_conf_file = configs['mqtt_conf_file']
		self.logger = MyLogger(mqtt=False, mqtt_conf=mqtt_conf_file)
		self.networks_file = networks_file
Beispiel #5
0
    def __init__(self, mqtt=False, mqtt_conf="/conf/mqtt_conf.txt"):
        self.mqtt = mqtt
        config_loader = ConfigurationLoader(mqtt_conf)
        broker = config_loader.load_configuration('mqtt_broker')['mqtt_broker']
        if mqtt:
            self.publisher = MQTTClient('logger', broker)
            self.publisher.DEBUG = True
            self.publisher.MSG_QUEUE_MAX = 0

        self.rtc = RTC()
        self.colors = {
            "DEBUG": "\033[0m",
            "RESET": "\033[0m",
            "WARNING": "\033[35m",
            "ERROR": "\033[33m",
            "CRITICAL": "\033[31m",
            "INFO": "\033[32m"
        }
Beispiel #6
0
class Updater:
    def __init__(self, config_file):
        self.config_loader = ConfigurationLoader(config_file)
        configs = self.config_loader.load_configuration(
            'check_delay', 'broker', 'topic', 'mqtt_id',
            'installed_version_file', 'mqtt_logger_conf')
        self.check_delay = int(configs['check_delay'])
        self.logger = MyLogger(True, configs['mqtt_logger_conf'])
        self.mqtt_client = MQTTClient(configs['mqtt_id'], configs['broker'])
        self.mqtt_client.DEBUG = True
        self.mqtt_client.set_callback(self.read_update)
        self.mqtt_topic = configs['topic']

    def read_update(self, topic, msg, retained, duplicate):
        print(json.loads(msg))
        self.reset_retained()

    def reset_retained(self):
        try:
            self.mqtt_client.publish(self.mqtt_topic, '', retain=True)
        except:
            None

    def fetch_update(self):
        mqtt_client = self.mqtt_client
        if not self._connected_to_mqtt():
            self.logger.log('WARNING', 'Updater', 'Reconnecting to the broker')
            try:
                mqtt_client.connect()
                self.mqtt_client.subscribe(self.mqtt_topic)
                self.logger.log('DEBUG', 'Updater',
                                'Reconnected to the broker')
            except:
                self.logger.log('ERROR', 'Updater',
                                'Broker reconnection error!')

        try:
            mqtt_client.check_msg()
        except:
            None

    def _connected_to_mqtt(self):
        try:
            self.mqtt_client.ping()
            return True
        except:
            return False
Beispiel #7
0
            self.mover.go_to_default_position()
            return
        target = self._get_target(msg)
        self.mover.move_to_and_grab(target)
        self.mover.drop_in_dropzone()
        self._request_new_target()

    def _get_target(self, msg):
        targets = []
        for msg_target in msg.targets:
            coordinate = Coordinate(msg_target.x, msg_target.y, msg_target.z)
            targets.append(Target(coordinate))
        target = self.find_closest.find(targets)
        rospy.loginfo("Closest target is at [{0}, {1}, {2}]".format(
            target.x, target.y, target.z))  # debugging
        return target


if __name__ == "__main__":
    rospy.init_node("game_node")
    joint_mover = JointMover("/arm_controller/follow_joint_trajectory",
                             GripperControl())
    config = ConfigurationLoader("config.json")
    dropzone = config.dropzone()
    default_position = config.default_position()
    arm_mover = ArmMover(joint_mover, dropzone, default_position)
    node = GameNode(arm_mover, FindClosest(arm_mover), config.game_publish(),
                    config.game_subscribe())
    rospy.loginfo("Game node is running")
    node.start()
Beispiel #8
0
class WifiManager:
    def __init__(self, config_file, networks_file):
        self.config_loader = ConfigurationLoader(config_file)
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(False)
        sleep(0.5)
        self.wlan.active(True)
        sleep(0.5)
        self.wlan.disconnect()
        configs = self.config_loader.load_configuration(
            'check_delay', 'mqtt_conf_file')
        self.check_delay = int(configs['check_delay'])
        mqtt_conf_file = configs['mqtt_conf_file']
        self.logger = MyLogger(mqtt=True, mqtt_conf=mqtt_conf_file)
        self.networks_file = networks_file

    def scan(self):
        try:
            with open(self.networks_file, 'rb') as file:
                saved_networks = json.load(file)

            networks_ssids = list(saved_networks.keys())

        except Exception:
            try:
                self.logger.log('ERROR', 'WifiManager',
                                'Error loading networks file.')
            except OSError:
                None
            raise OSError("Error loading networks file.")

        try:
            scan_results = [str(result[0]) for result in self.wlan.scan()]
        except OSError:
            self.logger.log("ERROR", "WifiManager", "No networks!")
            scan_results = list()

        available_networks = [
            network for network in scan_results and networks_ssids
        ]

        try:
            self.logger.log(
                'INFO', 'WifiManager',
                'Available networks: {}'.format(available_networks))
        except OSError:
            None

        return available_networks, saved_networks

    def connect(self, available_networks, networks):
        for network_ssid in available_networks:
            self.logger.log("DEBUG", 'WifiManager',
                            'Trying connection to {}'.format(network_ssid))
            self.wlan.connect(network_ssid, networks[network_ssid])
            while self.wlan.status() is network.STAT_CONNECTING:
                sleep(0.250)
            if self.wlan.status() == network.STAT_GOT_IP:
                return network_ssid

        return None

    def check_connection(self):
        if not self.wlan.status() is network.STAT_GOT_IP:
            available_networks, saved_networks = self.scan()
            ssid = self.connect(available_networks, saved_networks)
            try:
                if ssid:
                    self.logger.log(
                        'INFO', 'WifiManager',
                        'Connected to: {}; IP:{}'.format(
                            ssid,
                            self.wlan.ifconfig()[0]))
                else:
                    self.logger.log('ERROR', 'WifiManager', 'Not connected')
            except OSError as oe:
                print(str(oe))
        return self._find_mode(gameMode, bricks)

    def _isInArea(self, coordinateToCheck, b):
        return coordinateToCheck > b[0] and coordinateToCheck < b[1]

    def _cordinateInArea(self, coord_set, boundrySet):
        xInRange = self._isInArea(coord_set[0], boundrySet.get(
            app_constants.robotWorkZoneGetX))
        yInRange = self._isInArea(coord_set[1], boundrySet.get(
            app_constants.robotWorkZoneGetY))
        return xInRange and yInRange

    def _find_mode(self, mode, bricks):
        rospy.loginfo("I am in mode %s" % mode)
        bik = []
        if mode == 1:
            bik = filter(lambda x: x[0] == app_constants.red, bricks)
        elif mode == 2:
            bik = filter(lambda x: x[0] == app_constants.red or x[0] == app_constants.yellow, bricks)
        else:
            bik = bricks
        print bik
        return bik


if __name__ == '__main__':
    config = ConfigurationLoader("config.json")
    brain = MasterBrainNode(config.game_subscribe(), config.game_publish())
    rospy.loginfo("Brain node is running")
    rospy.spin()
class Preprocessor:
    config_file = 'config.json'
    configuration = {}

    command_runner = None
    git_handler = None

    def __init__(self):
        self.config_file = os.path.dirname(os.path.abspath(__file__)) + '/config.json'
        config_data = self.load_configuration()

        self.command_runner = SystemCommandRunner()
        self.configuration = ConfigurationLoader(json_config_data=config_data)
        self.git_handler = GitHandler(project_path=self.configuration.get_project_path_value())

    def execute(self):
        errors = self.validate()

        if errors.__len__() > 0:
            self.show_errors(errors)
        else:
            self.do_commit()

    def validate(self):
        files_to_check = self.get_files_to_check_list()

        if files_to_check.__len__() <= 0:
            return []

        errors = {}
        filename = ''
        appendable = True

        files_to_check = " ".join(files_to_check)

        phpcs_run_command = self.configuration.get_codesniffer_path_value() + ' --standard=PSR2' + files_to_check
        phpcs_response = self.command_runner.execute(command=phpcs_run_command)

        break_point_list = self.get_break_points()

        for line in phpcs_response:
            if 'FILE:' in line:
                filename = line.split(':')[1].strip()

            if any(break_point in line for break_point in break_point_list):
                data = line.split('|')

                if data.__len__() == 3:

                    if not errors.get(filename):
                        errors[filename] = []

                    errors[filename].append({
                        'line': data[0].strip(),
                        'message': data[2].strip()
                    })
                appendable = True
            elif line.split('|').__len__() > 1 and line.split('|')[0].isspace() and appendable:
                errors[filename][-1]['message'] += ' ' + line.split('|')[2].strip()
            else:
                appendable = False

        return errors

    def load_configuration(self):
        with open(self.config_file) as config_data_file:
            config_data = json.load(config_data_file)

        return config_data

    def get_files_to_check_list(self):
        files_to_check = []
        add_to_check_list = False

        files_to_commit = self.git_handler.status()

        for line in files_to_commit:

            if 'Changes to be committed' in line:
                add_to_check_list = True
            elif 'Untracked files' in line or 'Changes not staged for commit' in line:
                add_to_check_list = False
            elif '.php~' in line:
                add_to_check_list = False

            if add_to_check_list is True and ('new file' in line or 'modified' in line):
                filename = self.configuration.get_project_path_value() + '/' + line.split(':')[1].strip()

                if self.configuration.get_ignore_view_files_value():
                    if any(view_files_extension in filename
                           for view_files_extension in
                           self.configuration.get_view_files_extensions_list()):
                        continue

                if self.configuration.get_ignore_js_files_value():
                    if any(js_files_extension in filename
                           for js_files_extension in
                           self.configuration.get_js_files_extensions_list()):
                        continue

                files_to_check.append(filename)

        return files_to_check

    @staticmethod
    def show_errors(self, errors):
        for file in errors:
            print('')
            print(file)
            error_list = errors.get(file)
            for error in error_list:
                print('- ' + error.get('message') + '(line: ' + error.get('line') + ')')

    def get_break_points(self):
        severity_level = self.configuration.get_severity_level_value()

        break_points = [Severity.ERROR]

        if severity_level == Severity.WARNING:
            break_points.append(Severity.WARNING)

        return break_points

    def do_commit(self):
        commit_message = sys.argv[1]
        commit_response = self.git_handler.commit(message=commit_message)

        for line in commit_response:
            print(line)