def save_certificates(config_dict: dict) -> None: """ Save AWS certificates to files. :param config_dict: dict with credentials. :return: None """ global cfg logging.debug("save_certificates()") try: mkdir(CERTIFICATES_DIR) except: pass if 'cert_pem' in config_dict.keys(): certificate_string = config_dict['cert_pem'] cfg.cert_pem = config_dict['cert_pem'] with open(CERTIFICATE_PATH, "w", encoding="utf8") as infile: infile.write(certificate_string) if 'priv_key' in config_dict.keys(): private_key_string = config_dict['priv_key'] cfg.private_key = config_dict['priv_key'] logging.info(private_key_string) with open(KEY_PATH, "w", encoding="utf8") as infile: infile.write(private_key_string) if 'cert_ca' in config_dict.keys(): ca_certificate_string = config_dict['cert_ca'] cfg.cert_ca = config_dict['cert_ca'] with open(CA_CERTIFICATE_PATH, "w", encoding="utf8") as infile: infile.write(ca_certificate_string)
def authorization_request() -> str: """ Register your ESP in cloud. It takes password and login from aws_config.json :return: JSON Web Token """ global cfg logging.debug("Authorization request function") headers = DEFAULT_JSON_HEADER url = cfg.api_url + API_AUTHORIZATION_URL body = {} body['is_removed'] = True body['created_at'] = 0 body['username'] = cfg.api_login body['password'] = cfg.api_password logging.debug('LOGIN: {}, password: {}'.format(cfg.api_login, cfg.api_password)) body = ujson.dumps(body) try: response = urequests.post(url, data=body, headers=headers) except IndexError as e: logging.info("No internet connection: {}".format(e)) return "" except Exception as e: logging.info("Failed to authorize in API {}".format(e)) return "" if response.status_code != '200' and response.status_code != 200: logging.error(response.text) return "" response_dict = response.json() jwt_token = response_dict.get("data") return jwt_token
def axis(self, directionUp, thenWait=0): if directionUp: if self.type == Motor.MOVE: self.signal.on(Pin.DEFAULT_FWD_AXIS_UP) self.signal.off(Pin.DEFAULT_FWD_AXIS_DWN) elif self.type == Motor.TURN: self.signal.on(Pin.DEFAULT_SIDES_AXIS_UP) self.signal.off(Pin.DEFAULT_SIDES_AXIS_DWN) else: RuntimeError("invalid motor definition: %s" % self.type) else: if self.type == Motor.MOVE: self.signal.on(Pin.DEFAULT_FWD_AXIS_DWN) self.signal.off(Pin.DEFAULT_FWD_AXIS_UP) elif self.type == Motor.TURN: self.signal.on(Pin.DEFAULT_SIDES_AXIS_DWN) self.signal.off(Pin.DEFAULT_SIDES_AXIS_UP) else: RuntimeError("invalid motor definition: %s" % self.type) if thenWait: if self.verbose: logger.debug('[Motor(%s)] waiting %s seconds', self.type, thenWait) time.sleep(thenWait)
def save() -> None: """ Save config to file. :return: None. """ logging.debug("ESPConfig.save()") global cfg config_dict = cfg.as_dictionary with open(CONFIG_FILE_PATH, "w", encoding="utf8") as infile: dump(config_dict, infile) logging.info("New config saved!")
def subscribe_server(self, key): context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://" + config.HOST + ":" + config.PORT_SUB) socket.setsockopt(zmq.SUBSCRIBE, key) while True: try: data = socket.recv() logging.debug(json.loads(data), "[SUBSCRIBE]") self.data_sub.append(json.loads(data)) except: traceback.print_exc()
def update_config_dict(new_config: dict) -> None: """ Updates configuration. :param new_config: New configuration. :return: None """ logging.debug("update_config_dict()") file_path = 'config.json' with open(file_path, "r", encoding="utf8") as infile: old_config = load(infile) modified_entries = 0 for key in old_config.keys(): try: if old_config[key] != new_config[key]: logging.debug('Changing config entry: {} \n from: {}, to: {}'.format(key, old_config[key], new_config[key])) old_config[key] = new_config[key] modified_entries += 1 except: pass if modified_entries > 0: with open(file_path, "w", encoding="utf8") as infile: dump(old_config, infile) logging.debug('Modified {} entrires. Config updated succesfully!'.format(modified_entries)) else: logging.debug('No changes to config file were made!')
def load_from_file(self) -> None: """ Load configuration of ESP from file. :return: None """ logging.debug("ESPConfig.load_from_file()") config_file_exists = True if not utils.check_if_file_exists(CONFIG_FILE_PATH): with open(CONFIG_FILE_PATH, "w", encoding="utf8") as file: config_file_exists = False empty_config = {} self.device_uid = get_mac_address_as_string() dump(empty_config, file) with open(CONFIG_FILE_PATH, "r", encoding="utf8") as infile: config_dict = load(infile) self.ssid = config_dict.get('ssid', DEFAULT_SSID) self.password = config_dict.get('password', DEFAULT_PASSWORD) self.aws_endpoint = config_dict.get('aws_endpoint', DEFAULT_AWS_ENDPOINT) self.aws_client_id = config_dict.get('client_id', DEFAULT_AWS_CLIENT_ID) self.aws_topic = config_dict.get('topic', DEFAULT_AWS_TOPIC) self.use_aws = config_dict.get('use_aws', DEFAULT_USE_AWS) self.data_publishing_period_in_ms = config_dict.get('data_publishing_period_ms', DEFAULT_DATA_PUBLISHING_PERIOD_MS) self.use_dht = config_dict.get('use_dht', DEFAULT_USE_DHT) self.dht_measurement_pin = config_dict.get('dht_measurement_pin', DEFAULT_DHT_MEASUREMENT_PIN) self.dht_power_pin = config_dict.get('dht_power_pin', DEFAULT_DHT_POWER_PIN) self.dht_type = config_dict.get('dht_type', DEFAULT_DHT_TYPE) self.wifi_timeout = config_dict.get('wifi_connection_timeout', DEFAULT_WIFI_TIMEOUT) self.mqtt_port = config_dict.get('mqtt_port', DEFAULT_MQTT_PORT) self.mqtt_port_ssl = config_dict.get('mqtt_port_ssl', DEFAULT_MQTT_PORT_SSL) self.mqtt_timeout = config_dict.get('mqtt_timeout', DEFAULT_MQTT_TIMEOUT) self.ap_config_done = config_dict.get('AP_config_done', DEFAULT_AP_CONFIG_DONE) self.configuration_after_first_power_on_done = \ config_dict.get('configuration_after_first_power_on_done', DEFAULT_CONFIGURATION_AFTER_FIRST_POWER_ON_DONE) self.QOS = config_dict.get('QOS', DEFAULT_QOS) self.tested_connection_cloud = config_dict.get('tested_connection_cloud', DEFAULT_TESTED_CONNECTION_CLOUD) self.printed_time = config_dict.get('printed_time', DEFAULT_PRINTED_TIME) self.got_sensor_data = config_dict.get('got_sensor_data', DEFAULT_GOT_SENSOR_DATA) self.published_to_cloud = config_dict.get('published_to_cloud', DEFAULT_PUBLISHED_TO_CLOUD) self.private_key = config_dict.get('private_key', DEFAULT_PRIV_KEY) self.cert_pem = config_dict.get('cert_pem', DEFAULT_CERT_PEM) self.cert_ca = config_dict.get('cert_ca', DEFAULT_CERT_CA) if not self.device_uid: self.device_uid = config_dict.get('device_uid', DEFAULT_DEVICE_UID) if not config_file_exists: self.save()
def read_certificates(parse: bool = False) -> (bool, str, str): """ Read certificates from files. :return: Error code (True - OK, False - at least one certificate does not exist), text of certificates. """ logging.debug("read_certificates()") result, aws_certificate = utils.read_from_file(CERTIFICATE_PATH) result2, aws_key = utils.read_from_file(KEY_PATH) if parse: aws_certificate.replace('\n', '') aws_key.replace('\n', '') return (result and result2), aws_certificate, aws_key else: return (result and result2), aws_certificate, aws_key
def stop(self): if self.verbose: logger.debug('[Motor(%s)] stopping...', self.type) if self.type == Motor.MOVE: self.signal.off(Pin.DEFAULT_FWD_AXIS_UP) self.signal.off(Pin.DEFAULT_FWD_AXIS_DWN) elif self.type == Motor.TURN: self.signal.off(Pin.DEFAULT_SIDES_AXIS_UP) self.signal.off(Pin.DEFAULT_SIDES_AXIS_DWN) else: RuntimeError("invalid motor definition: %s" % self.type) if self.verbose: logger.debug('[Motor(%s)] stopped', self.type)
def push_server(self): context = zmq.Context() socket = context.socket(zmq.PUSH) for port in config.PORT_PUSH: socket.connect("tcp://" + config.HOST + ":" + port) while True: try: for data in self.data_push: print logging.debug(data, "[PUSH]") socket.send(data) self.data_push.remove(data) except: traceback.print_exc()
def subscribe_server(self, key): context = zmq.Context() socket = context.socket(zmq.SUB) socket.connect("tcp://" + config.HOST + ":" + config.PORT_SUB) socket.setsockopt(zmq.SUBSCRIBE, str(key)) while True: try: data = socket.recv() data = " ".join(data.split(" ")[1:]) print logging.debug(data, "[SUBSCRIBE]") self.data_sub.append(json.loads(data)) # to decrease CPU usage time.sleep(0.001) except: traceback.print_exc()
def update_state(self, room_id, state, deck_state, poker_state, turn): if room_id != self.room_id: return self.state = state self.deck_state = deck_state self.poker_state = poker_state self.turn = get(turn, 'Ok') logging.debug(repr(self.state)) logging.debug(repr(self.deck_state)) logging.debug(repr(self.poker_state)) logging.debug(repr(self.turn)) self.display(False)
def incoming(): message = messages_from_json([request.args['message']])[0] if not any(isinstance(message, allowed_type) for allowed_type in ALLOWED_MESSAGE_TYPES): logging.debug('Ignoring non allowed message of type {}'.format(message.type)) return '', 200 if message.mention and message.mention != Config.BOT_USERNAME: logging.debug('Dropping message mentioning another bot. Message is mentioning {}'.format(message.mention)) return '', 200 user = BotUser.get_by_id(message.from_user) if message.mention: # handle the case where we're mentioned inline if message.body == '': translated = "What do you want translated?" elif user.current_state_data()['language'] is None: translated = gizoogleshit.gizoogleit(message.body) elif user.current_state_data()['language'] == "thug": translated = gizoogleshit.gizoogleit(message.body) else: translated = getTranslation.translateshit(user.current_state_data()['language'], message.body) outgoing_messages = [TextMessage(to=message.from_user, body=translated, chat_id=message.chat_id)] else: outgoing_messages = state_machine.handle_message(message.from_user, message) logging.debug('Processing message: {}'.format(message)) if len(outgoing_messages) > 0: kik.send_messages(outgoing_messages) return '', 200
def start(self): logger.debug('[Diagnostics] diagnostics starting...') with Signal.default().prepared(): logger.debug('[Diagnostics] #### Performing sequencial run ####') self.moveFwdThenBack(stop=True) self.turnRightThenLeft() logger.debug('[Diagnostics] #### Performing parallel run ####') self.moveFwdThenBack(stop=False) self.turnRightThenLeft() self.turnMotor.stop() logger.debug('[Diagnostics] diagnostics complete!')
def __init__(self): """ ESPConfig constructor. """ logging.debug("ESPConfig.__init__()") self.ssid = DEFAULT_SSID self.password = DEFAULT_PASSWORD self.aws_endpoint = DEFAULT_AWS_ENDPOINT self.aws_client_id = DEFAULT_AWS_CLIENT_ID self.aws_topic = DEFAULT_AWS_TOPIC self.data_publishing_period_in_ms = DEFAULT_DATA_PUBLISHING_PERIOD_MS self.use_dht = DEFAULT_USE_DHT self.use_aws = DEFAULT_USE_AWS self.dht_measurement_pin = DEFAULT_DHT_MEASUREMENT_PIN self.dht_power_pin = DEFAULT_DHT_POWER_PIN self.dht_type = DEFAULT_DHT_TYPE self.wifi_timeout = DEFAULT_WIFI_TIMEOUT self.mqtt_port = DEFAULT_MQTT_PORT self.mqtt_port_ssl = DEFAULT_MQTT_PORT_SSL self.mqtt_timeout = DEFAULT_MQTT_TIMEOUT self.ap_config_done = DEFAULT_AP_CONFIG_DONE self.ntp_synchronized = DEFAULT_NTP_SYNCHRONIZED self.configuration_after_first_power_on_done = DEFAULT_CONFIGURATION_AFTER_FIRST_POWER_ON_DONE self.QOS = DEFAULT_QOS self.api_url = DEFAULT_API_URL self.api_login = DEFAULT_API_LOGIN self.api_password = DEFAULT_API_PASSWORD self.device_uid = "" self.tested_connection_cloud = DEFAULT_TESTED_CONNECTION_CLOUD self.printed_time = DEFAULT_PRINTED_TIME self.got_sensor_data = DEFAULT_GOT_SENSOR_DATA self.published_to_cloud = DEFAULT_PUBLISHED_TO_CLOUD self.private_key = DEFAULT_PRIV_KEY self.cert_pem = DEFAULT_CERT_PEM self.cert_ca = DEFAULT_CERT_CA
def as_dictionary(self) -> dict: """ Returns configuration as dict. :return: Configuration. """ logging.debug("ESPConfig.as_dictionary()") config_dict = {} config_dict['ssid'] = self.ssid config_dict['password'] = self.password config_dict['aws_endpoint'] = self.aws_endpoint config_dict['client_id'] = self.aws_client_id config_dict['topic'] = self.aws_topic config_dict['use_aws'] = self.use_aws config_dict['data_publishing_period_ms'] = self.data_publishing_period_in_ms config_dict['use_dht'] = self.use_dht config_dict['dht_measurement_pin'] = self.dht_measurement_pin config_dict['dht_power_pin'] = self.dht_power_pin config_dict['dht_type'] = self.dht_type config_dict['wifi_connection_timeout'] = self.wifi_timeout config_dict['mqtt_port'] = self.mqtt_port config_dict['mqtt_port_ssl'] = self.mqtt_port_ssl config_dict['mqtt_timeout'] = self.mqtt_timeout config_dict['AP_config_done'] = self.ap_config_done config_dict['configuration_after_first_power_on_done'] = self.configuration_after_first_power_on_done config_dict['device_uid'] = self.device_uid config_dict['QOS'] = self.QOS config_dict['tested_connection_cloud'] = self.tested_connection_cloud config_dict['printed_time'] = self.printed_time config_dict['got_sensor_data'] = self.got_sensor_data config_dict['published_to_cloud'] = self.published_to_cloud config_dict['private_key'] = self.private_key config_dict['cert_pem'] = self.cert_pem config_dict['cert_ca'] = self.cert_ca return config_dict
def start(self, **kwargs): self.tornadoApp.listen(self.port) logger.debug('[start] listening on %s', self.port) tornado.ioloop.IOLoop.current().start()
def turnRight(self, *args, **kwargs): if self.verbose: logger.debug('[Motor(%s)] turn right', self.type) self.axis(True, *args, **kwargs)
def turnLeft(self, *args, **kwargs): if self.verbose: logger.debug('[Motor(%s)] turn left', self.type) self.axis(False, *args, **kwargs)
def moveBack(self, *args, **kwargs): if self.verbose: logger.debug('[Motor(%s)] move backwards', self.type) self.axis(False, *args, **kwargs)
def moveForward(self, *args, **kwargs): if self.verbose: logger.debug('[Motor(%s)] move forward', self.type) self.axis(True, *args, **kwargs)