Пример #1
0
 def save_account(self, username, password):
     consolelog.log(LOG_TITLE, "Saving email account")
     self.save_to_file({
         self.gmail_username: username,
         self.gmail_password: password
     })
     return True
Пример #2
0
 def on_message(self, ws, message):
     self.set_status("ok")
     consolelog.log(LOG_TITLE, "msg - > %s" % message)
     message = json.loads(message)
     if (message['type'] == "tickle"):
         self.fetch_pushes(self.last_timestamp)
     self.getToken()  #For check change token
Пример #3
0
 def run(self):
     self.status = SmsStatus.SENDING
     self.status_callback(self.status)
     consolelog.log(LOG_TITLE, "thread started")
     self.config()
     try:
         #command_string = 'sudo gammu sendsms TEXT ' + self.sms_number + ' -textutf8 "' + self.sms_message + '" '
         #print commands.getoutput(command_string)
         self.status = SmsStatus.ERROR
         sm = gammu.StateMachine()
         sm.ReadConfig()
         sm.Init()
         message = {
             'Text': self.sms_message,
             'SMSC': {
                 'Location': 1
             },
             'Number': self.sms_number,
         }
         # Actually send the message
         result = sm.SendSMS(message)
         consolelog.log(LOG_TITLE, "Send sms Success")
         self.status = SmsStatus.SUCCESS
     except gammu.ERR_DEVICENOTEXIST:
         consolelog.log(LOG_TITLE, "Error device doesn't exist")
         self.status = SmsStatus.ERR_DEVICENOTEXIST
     except gammu.ERR_NOSIM:
         consolelog.log(LOG_TITLE, "Error can not access SIM card")
         self.status = SmsStatus.ERR_NOSIM
     except ValueError:
         consolelog.log(LOG_TITLE, "Error")
         self.status = SmsStatus.ERROR
     self.status_callback(self.status)
Пример #4
0
 def run(self):
     self.set_flag(True)
     start = time.time()
     consolelog.log(LOG_TITLE, "Saying " + self.phrase)
     os.system("echo \"" + self.phrase + "\" | festival --tts")
     end = time.time() - start
     consolelog.log(LOG_TITLE, "time used %f s" % end)
     self.set_flag(False)
Пример #5
0
 def __init__(self, gogod_config=None):
     consolelog.log(LOG_TITLE, "init")
     self.conf = config.Config() if gogod_config is None else gogod_config
     self.running_list = {}
     self.reserved_name = [
         '__init__.py', 'checker.py', 'gogod_interface.py', 'example.py',
         'example_with_variable.py'
     ]
     self.autorun()
Пример #6
0
 def __init__(self, gogod_config=None):
     self.last_handle_time = 0
     self.conf = config.Config() if gogod_config is None else gogod_config
     self.api_key = self.conf.get_iftt_key()
     self.event_name = None
     self.dict_data = None
     self.limit_check = rate_limit_checker.RateLimitChecker(
         _rate_limit_ifttt)
     consolelog.log(LOG_TITLE, "Created Class")
Пример #7
0
    def run(self):
        """ Method that runs forever """
        consolelog.log(LOG_TITLE, "background started")
        while True:
            # Do something
            # print('Status : ' + self.status)
            if (self.status == "none"):
                self.new_ws_connection()
            elif (self.status == "close"):
                self.new_ws_connection()

            time.sleep(self.interval)
Пример #8
0
    def run(self):
        # self.token = "m3b2ydsSGqkq9meRZAgbKoE0PmSXQqAB"

        self.getToken()

        if self.is_valid_token(self.token):
            self.fetch_pushes()

        global flag_run
        if ((flag_run == False) and (self.token is not None)):
            consolelog.log(LOG_TITLE, "starting")
            self.connect()
Пример #9
0
    def __init__(self, gogod_config=None, sendKeyValue=None):
        global _latest_sender_id
        self.last_handle_time   = 0
        self.conf               = config.Config() if gogod_config is None else gogod_config
        self.sendKeyValue       = sendKeyValue
        self.token              = self.conf.get_telegram_bot_token()
        _latest_sender_id       = self.get_sender()
        consolelog.log(LOG_TITLE, "Created Class")

        self.connect()

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True                            # Daemonize thread
        thread.start()                                  # Start the execution
Пример #10
0
    def config(self):
        if not os.path.exists(GAMMU_CONFIG_FILE):
            consolelog.log(LOG_TITLE, "No gammu config File")
            gammu_config_content = '''[gammu]

port = /dev/ttyUSB0
model =
connection = at19200
synchronizetime = yes
logfile =
logformat = nothing
use_locking =
gammuloc =
            '''

            file = open(GAMMU_CONFIG_FILE, "w+")
            file.write(gammu_config_content)
            file.close()
            consolelog.log(LOG_TITLE, "Written config to file")

        if 'DefaultVendor' not in open(USB_CONFIG_FILE).read():
            consolelog.log(LOG_TITLE, "No Device config")
            modeswitch_content = '''DefaultVendor= 0x12d1
DefaultProduct = 0x1446
TargetVendor = 0x12d1
TargetProductList ="1001,1406,140b,140c,141b,14ac"
CheckSuccess = 20
MessageContent ="55534243123456780000000000000011060000000000000000000000000000"'''

            file = open(USB_CONFIG_FILE, 'a')
            file.write(modeswitch_content)
            file.close()
            consolelog.log(LOG_TITLE, "Written device config")

        os.system("sudo usb_modeswitch -c /etc/usb_modeswitch.conf")
Пример #11
0
    def init_mqtt_client(self):
        MQTT_USER = self.uid
        MQTT_CLIENT_ID = self.uid

        if (self.mqtt_client is not None and self.mqtt_client.is_connected):
            if self.mqtt_client.username != MQTT_USER:
                consolelog.log(LOG_TITLE, "MQTT disconnect the exists")
                self.mqtt_client.disconnect()
            else:
                consolelog.log(LOG_TITLE, "MQTT keep the exists")
                return

        self.mqtt_client = mqtt.Client(MQTT_CLIENT_ID)
        self.mqtt_client.username_pw_set(MQTT_USER, MQTT_PASSWORD)
        self.mqtt_client.on_connect = mqtt_on_connect
        self.mqtt_client.on_disconnect = mqtt_on_disconnect
        self.mqtt_client.is_connected = False
        self.mqtt_client.is_connecting = True
        self.mqtt_client.username = MQTT_USER

        global LAST_CONNECT
        LAST_CONNECT = time.time()

        # mqtt_client.on_message = on_message
        consolelog.log(LOG_TITLE, "MQTT connecting")

        try:
            self.mqtt_client.connect(MQTT_ADDRESS, port=1883, keepalive=10)
        except Exception as e:
            print(e)
            consolelog.log(LOG_TITLE, "MQTT connect error")
        time.sleep(0.1)
Пример #12
0
    def list_files(self):

        library_list = []

        for f in os.listdir(os.path.abspath(ADDONS_PATH)):
            module_name, ext = os.path.splitext(
                f)  # Handles no-extension files, etc.
            if ext == '.py':  # Important, ignore .pyc/other files.
                consolelog.log(LOG_TITLE, 'found %s' % (module_name))
                # module = __import__(module_name)
                library_list.append("%s%s" % (module_name, ext))
        return list(
            set(library_list) -
            (set(self.reserved_name) -
             set(['example.py', 'example_with_variable.py'])))
Пример #13
0
    def __init__(self, gogod_config=None):
        threading.Thread.__init__(self)
        self.state_normal = False  # False = queue, True = normal

        self.conf = config.Config() if gogod_config is None else gogod_config
        self._last_handle = {}

        self.data_to_update = {}

        self.uid = self.conf.get('datalog_uid')
        self.mqtt_client = None
        self.is_connected = False
        self.is_connecting = True

        consolelog.log(LOG_TITLE, "Created Thread ")
        self.start()
Пример #14
0
    def get_queue_file(self):
        return_data = None
        if os.path.exists(QUEUE_FILE):
            with open(QUEUE_FILE, 'r') as f:
                data = f.readline()
                if data == '':
                    return return_data

                io_string = StringIO(data)
                try:
                    return json.load(io_string)
                except:
                    # if invalid
                    self.pop_queue_file()
                    consolelog.log(LOG_TITLE, "Queue file error")

        return return_data
Пример #15
0
    def publish(self, data):

        if self.uid is None or self.uid == '':
            return

        if self.mqtt_client is None:
            self.init_mqtt_client()
        elif not self.mqtt_client.is_connected and not self.mqtt_client.is_connecting:
            self.init_mqtt_client()

        if self.mqtt_client.is_connected:
            consolelog.log(LOG_TITLE, data)
            self.mqtt_client.publish(
                "log/%s/%s" % (data["user"], data["field"]),
                "%s %s=%s" % (data["user"], data["field"], data["value"]))
            global LAST_CONNECT
            LAST_CONNECT = time.time()
Пример #16
0
    def pub_publish(self, data):

        # uid = self.uid
        if self.uid is None or self.uid == '':
            # uid = data["channel"]
            self.uid = data["channel"] + self.random_string()

        if self.mqtt_client is None:
            self.init_mqtt_client()
        elif not self.mqtt_client.is_connected and not self.mqtt_client.is_connecting:
            self.init_mqtt_client()

        if self.mqtt_client.is_connected:
            consolelog.log(LOG_TITLE, data)
            self.mqtt_client.publish(
                "plog/%s/%s" % (data["channel"], data["field"]),
                "%s %s=%s" % (data["channel"], data["field"], data["value"]))
            global LAST_CONNECT
            LAST_CONNECT = time.time()
Пример #17
0
    def save_to_file(self, params):

        if self.status_callback is not None and (self.gmail_username in params
                                                 or self.gmail_password
                                                 in params):
            self.status_callback(10 + self.EmailStatus.CONNECTING)

        data = {}
        if os.path.exists(CONFIG_FILE):
            jsonFile = open(CONFIG_FILE, "r")
            data = json.load(jsonFile)
            jsonFile.close()

            for key, value in params.iteritems():

                if not self.is_valid_config_name(key):
                    continue

                if key == self.gmail_password:
                    value = None if value == "None" else value
                    data[key] = self.enc.EncodeAES(value)
                else:
                    data[key] = value

                self.current[key] = value

            jsonFile = open(CONFIG_FILE, "w+")
            jsonFile.write(json.dumps(data))
            jsonFile.close()

        # Backup old account
        # if (os.path.exists(self.ENCRYPT_FILE)):
        #     os.rename(self.ENCRYPT_FILE, self.ENCRYPT_FILE+".bak")
        # file = open(self.ENCRYPT_FILE, "w")
        # file.write(param.username + "\n")
        # file.write(self.encrypt(self.ENCRYPT_PASSWORD, param.password) + "\n")
        # file.close()

        consolelog.log(LOG_TITLE, "Saved")

        if self.status_callback is not None:
            self.status_callback(10 + self.EmailStatus.SUCCESS)
Пример #18
0
    def __init__(self, gogod_config=None):
        threading.Thread.__init__(self)
        self.data_to_update = {}
        self.data_from_queue = {}
        self.last_handle = 0
        self.count = 0
        self.state_normal = False  # False = queue, True = normal
        self.queue_not_upload = Queue.Queue()
        self.flag_connect = False

        self.conf = config.Config() if gogod_config is None else gogod_config

        self.api_key = self.conf.getClouddataKey()
        self._last_handle = {'field1': 0}
        self.valid_names = [
            'field1', 'field2', 'field3', 'field4', 'field5', 'field6',
            'field7', 'field8', 'created_at'
        ]
        consolelog.log(LOG_TITLE, "Created Thread")
        self.start()
Пример #19
0
 def fetch_pushes(self, timestamp=1429750800):
     request = urllib2.Request(
         "https://api.pushbullet.com/v2/pushes?modified_after=%s" %
         timestamp)
     request.add_header("Authorization", "Bearer %s" % self.token)
     try:
         result = urllib2.urlopen(request)
         json_data = result.read()
         self.last_timestamp = time.time()
         data = json.loads(json_data)
         #print data
         if 'pushes' in data:
             for entry in data['pushes']:
                 if (not entry['dismissed']):
                     if (len(entry['title'].split(' ')) == 1):
                         self.callback_setKeyValueEvent(
                             entry['title'], entry['body'])
                     # print data
     except:
         consolelog.log(LOG_TITLE, "Fetch Error")
Пример #20
0
    def run(self):
        global _latest_sender_id, _bot, _last_worked_token

        self.bot = telepot.Bot(self.token)
        if self.token in _connected_token:
            consolelog.log(LOG_TITLE, "already connected")
            return

        try:
            self.bot.getMe()
            self.is_connected = True
            _connected_token.append(self.token)
            _bot = self.bot
            _last_worked_token = self.token
            consolelog.log(LOG_TITLE, "Connected")
        except:
            self.bot = None
            self.is_connected = False
            consolelog.log(LOG_TITLE, "Invalid token")
            return

        self.bot.message_loop({'chat': self.on_telegram_message})

        self.send_telegram_message('Hello, I woke up.')

        while(True):
            if self.stopped():
                return
            time.sleep(1)
Пример #21
0
    def upload_file(self, params):

        result = {'result': False}
        confirm = params['confirm'] == 'true'
        filename = self.corect_filename(params['file']['filename'])

        full_file_path = os.path.join(ADDONS_PATH, filename)
        consolelog.log(LOG_TITLE, 'file named %s' % filename)

        #Check is a reserved name
        if filename in self.reserved_name:
            result['message'] = 'file_reserved'
            consolelog.log(LOG_TITLE, 'file reserved')
            return result

        # Check file exists?
        result['message'] = (os.path.exists(full_file_path))
        if result['message'] and not confirm:
            result['message'] = 'file_exists'
            consolelog.log(LOG_TITLE, 'file exists')
            return result

        # Write html content to a file.
        htmlFile = open(full_file_path, "w+")
        htmlFile.write(params['file']['body'])
        htmlFile.close()
        result['result'] = True

        return result
Пример #22
0
    def checkdo(self):
        threading.Timer(1.0, self.checkdo).start()
        self.count += 1
        self.state_normal = False

        # Checking the exist queue first
        if self.count <= 1:

            if self.data_from_queue == {}:
                queue_data = self.get_queue_file()
                queue_data = self.check_valid_name(queue_data)
                if queue_data is not None and queue_data != {}:
                    self.data_from_queue = queue_data
                else:
                    self.pop_queue_file()
            else:
                self.state_normal = True

            if self.data_from_queue != {}:
                consolelog.log(LOG_TITLE, "Queueing")
                # if send data success then clear variable
                if self.updateData(self.data_from_queue):
                    self.data_from_queue = {}
                    self.pop_queue_file()

        if (self.count > 1 or self.state_normal) and self.data_to_update != {}:
            #elif self.data_to_update != {} :
            self.count = 0
            if not self.updateData(self.data_to_update):
                self.onFail()
                self.addToQueue(self.data_to_update)

            self.clearData()

        elif self.data_to_update == {}:
            self.count = 0

        if self.count >= 4:
            self.count = 0
Пример #23
0
    def on_telegram_message(self, msg):
        global _latest_sender_id

        content_type, chat_type, chat_id = telepot.glance(msg)
        message = msg['text']

        if self.latest_sender_id != chat_id:
            self.latest_sender_id = chat_id
            _latest_sender_id = chat_id
            self.save_sender(chat_id)

        if self.bot is None:
            return

        for str in ['ping', 'echo']:

            if message.startswith(str):
                message = re.sub(str,'',message,1)
                self.bot.sendMessage(chat_id, message.strip())
                break

        consolelog.log(LOG_TITLE, "message : %s" % message)
        if self.sendKeyValue is not None:
            self.sendKeyValue("telegram", message)
Пример #24
0
    def start_addons(self, filename):

        result = {'result': False, 'error': ''}
        consolelog.log(LOG_TITLE, 'Starting %s' % filename)
        # check is already run
        if filename in self.running_list:
            result['error'] = 'Already Run'
            consolelog.log(LOG_TITLE, '%s already run' % filename)
            return result

        # Verify the file syntax
        file_verify = self.verify(filename)
        if not file_verify['result']:
            consolelog.log(LOG_TITLE, 'verify %s fail' % filename)
            return file_verify

        full_filepath = os.path.join(ADDONS_PATH, filename)
        cmd = 'python %s' % full_filepath
        result_testrun = self.testrun(cmd)

        # Verify the file
        if not result_testrun['result']:
            return result_testrun

        pro = subprocess.Popen(cmd.split(),
                               stdout=subprocess.PIPE,
                               shell=False,
                               preexec_fn=os.setsid)
        # out, err = pro.communicate()
        # result['message'] = out
        # result['error'] = err
        # result['result'] = (err == '')
        result['result'] = True

        if result['result']:
            self.running_list[filename] = pro
        # else:
        #     os.killpg(os.getpgid(pro.pid), signal.SIGTERM)  # Send the signal to all the process groups

        consolelog.log(LOG_TITLE,
                       'Started %s %s' % (filename, result['result']))
        return result
Пример #25
0
    def getToken(self):
        token = self.conf.getPushbulletToken()
        # print token
        if ((self.token is not None) and (self.token != token)):
            consolelog.log(LOG_TITLE, "Token changed by user")
            self.set_status("close")
            self.ws.close()
            self.stop()

        if ((self.token != token) and self.is_valid_token(token)):
            self.token = token
            consolelog.log(LOG_TITLE, "Changed token")

        elif ((self.token != token) and self.token is not None
              and not self.is_valid_token(token)):
            consolelog.log(LOG_TITLE, "Invalid token file")
Пример #26
0
    def makeWebRequest(self, event_name=None, dict_data=None):

        self.getAPIKey()
        if event_name is None or self.api_key is None:
            return False
        #self.flag_connect = True
        consolelog.log(LOG_TITLE, event_name)
        consolelog.log(LOG_TITLE, dict_data)

        url = "https://maker.ifttt.com/trigger/%s/with/key/%s" % (event_name,
                                                                  self.api_key)
        try:
            r = requests.post(url, data=dict_data)
            return_data = r.text
            self.last_handle_time = time.time()
            consolelog.log(LOG_TITLE, return_data)
            #self.flag_connect = False
            return True

        except:
            consolelog.log(LOG_TITLE, "Connected Error")
            #self.flag_connect = False
            return False
        return False
Пример #27
0
    def stop_addons(self, filename):

        result = {'result': True}

        if filename in self.running_list:
            consolelog.log(LOG_TITLE, 'Terminating %s' % filename)
            pro = self.running_list[filename]
            os.killpg(
                os.getpgid(pro.pid),
                signal.SIGTERM)  # Send the signal to all the process groups
            del self.running_list[filename]
            result['result'] = True
            consolelog.log(LOG_TITLE, 'Terminated %s' % filename)
        else:
            consolelog.log(LOG_TITLE, ' %s is not run' % filename)

        return result
Пример #28
0
    def send_telegram_photo(self, filename):
        global _latest_sender_id, _bot, _last_worked_token

        if _latest_sender_id is None or _bot is None:
            return

        filepath = self.conf.auto_filepath_image(filename)
        if not os.path.exists(filepath):
            return
        consolelog.log(LOG_TITLE, 'sending image')
        url     = 'https://api.telegram.org/bot%s/sendPhoto' % _last_worked_token
        files   = {'photo': open(filepath, 'rb')}
        data    = {'chat_id': _latest_sender_id,'caption':filename}
        try:
            r       = requests.post(url, data=data, files=files)
            consolelog.log(LOG_TITLE, 'sent result %s' % r.json()['ok'])
        except:
            consolelog.log(LOG_TITLE, 'sent image fail')
Пример #29
0
    def updateData(self, dictData):
        #if self.flag_connect:
        #    return False

        #self.flag_connect = True
        dictData = self.check_valid_name(dictData)
        consolelog.log(LOG_TITLE, "%s" % dictData)
        self.getAPIKey()

        if not self.conf.validateClouddataKey(self.api_key):
            return False

        if dictData is None or dictData == {}:
            return True

        data = copy.deepcopy(dictData)
        data['key'] = self.api_key

        params = urllib.urlencode(dictData)
        request = urllib2.Request(
            "https://data.learninginventions.org/update?key=%s&%s" %
            (self.api_key, params))
        try:
            # r = requests.post("https://data.learninginventions.org/update", data=data, ,verify=False)
            # return_data = r.text
            result = urllib2.urlopen(request)
            return_data = result.read()
            self.last_timestamp = time.time()

            consolelog.log(LOG_TITLE, "Seq. =%s" % return_data)

            #self.flag_connect = False
            #return int(return_data) > -1
            return True

        except:
            consolelog.log(LOG_TITLE, "Connected Error")
            #self.flag_connect = False
            return False
        return False
Пример #30
0
def send(status_callback, sms_number, sms_message):
    consolelog.log(LOG_TITLE, "starting sms thread")
    sms_thread = SmsHandle(status_callback, sms_number, sms_message)
    sms_thread.start()