Exemple #1
0
def html(request, page_id):
    conn = sqlite3.connect(setting.get("DB"))
    page = conn.execute("select html from pages where id = %s;" % page_id).fetchone()
    if page:
        return page[0]
    else:
        return "<h1>no current id!</h1>"
Exemple #2
0
def data(msg, PASSWD):
    import setting
    import ujson
    from mqtt import MQTTClient
    global answer
    answer = 'OK'
    IOTHUB = setting.get('iothub')
    DEVICE = setting.get('iotdevicename')
    KEY = setting.get('iotdevicesecret')
    USER = IOTHUB + '/' + DEVICE + '/api-version=2016-11-14'
    print('--------------MQTT----------')
    print('DEVICE: ', DEVICE)
    print('IOTHUB: ', IOTHUB)
    print('USER: '******'PASSWD: ', PASSWD)
    c = MQTTClient(
        DEVICE, IOTHUB, 8883, USER, PASSWD, 0, True
    )  # client_id, server, port=0, user=None, password=None, keepalive=0, ssl=False, ssl_params={})
    c.set_callback(sub_cb)
    try:
        c.connect()
        print('--------------PUBLISH----------')
        print('DEVICE: ', 'devices/' + DEVICE + '/messages/events/')
        print('MSG: ', msg)
        c.publish('devices/' + DEVICE + '/messages/events/', msg, False,
                  1)  # topic, msg, retain=False, qos=0
        c.subscribe('$iothub/twin/res/#', 1)  # topic, qos=0
        c.publish('$iothub/twin/GET/?$rid=2', '', False, 1)
        c.wait_msg()
        dictr = {}
        dictr["RSSI"] = setting.get('RSSI')
        dictr["health"] = setting.get('health')
        dictr["hwid"] = setting.get('hwid')
        dictr["VBat"] = setting.get('VBat')
        dictr["FWversion"] = setting.get('FWversion')
        dictr["FWnumber"] = setting.get('FWnumber')
        try:
            dict = ujson.loads(answer)
            print('RX TWIN MSG: ', dict)
            dict_rep = dict["reported"]
            keyp = dict_rep["keypresses"] + 1
            dictr["keypresses"] = keyp
        except:
            dictr["keypresses"] = 1
        print('TX TWIN MSG: ', dictr)
        reported = ujson.dumps(dictr)
        c.publish('$iothub/twin/PATCH/properties/reported/?$rid=1', reported,
                  False, 1)
        c.disconnect()
    except ():
        answer = 'ERROR'
    return answer
Exemple #3
0
def update():
    import ujson
    import setting
    import network
    try:
        FWnumber_me = setting.get('FWnumber')
        FWnumber_new = setting.get('FWnumberNew')
        print('FW me: ', FWnumber_me)
        print('FW new: ', FWnumber_new)
        if FWnumber_me != FWnumber_new:
            import wget
            import wifi
            import os
            FWurl = setting.get('FWurl')
            print('Download new FW: ', FWurl)
            if wifi.wait_sta(15):
                print('Start Update: ', FWurl)
                encoded = wget.get(FWurl).decode()
                path_spl = FWurl.split('/')
                protokoll = path_spl.pop(0)
                path_spl.pop(0)
                server = path_spl.pop(0)
                file = path_spl.pop()
                path = '/'.join(path_spl)
                dict = ujson.loads(encoded)
                file_list = dict['INSTALL']
                for file in file_list:
                    print('Update File : ' + protokoll + '//' + server + '/' +
                          path + '/' + file + ' >>> ' + file + '.tmp')
                    a = wget.get_file(
                        protokoll + '//' + server + '/' + path + '/' + file,
                        file + '.tmp')
                    fileSize = os.stat(file + '.tmp')
                    if fileSize[6] > 0:
                        os.rename(file + '.tmp', file)
                        print('Renamed file ' + file + '.tmp', file)
                    else:
                        print('Error updating file : ', file)
                        return
                setting.set('FWnumber', FWnumber_new)
                setting.set('FWversion', '{:04.2f}'.format(FWnumber_new / 100))
    except:
        print('ERROR in RepUpdate.update')
Exemple #4
0
 def get(self, flash=''):
     requests_per_minute = setting.get('worker.requests-per-minute', int,
                                       REQUESTS_PER_MINUTE)
     local_object_duration = setting.get('worker.local-object-duration',
                                         int, LOCAL_OBJECT_DURATION)
     broadcast_active_duration = setting.get(
         'worker.broadcast-active-duration', int, BROADCAST_ACTIVE_DURATION)
     broadcast_incremental_backup = setting.get(
         'worker.broadcast-incremental-backup', bool,
         BROADCAST_INCREMENTAL_BACKUP)
     image_local_cache = setting.get('worker.image-local-cache', bool,
                                     IMAGE_LOCAL_CACHE)
     self.render('settings/general.html',
                 requests_per_minute=requests_per_minute,
                 local_object_duration=int(local_object_duration /
                                           (60 * 60 * 24)),
                 broadcast_active_duration=int(broadcast_active_duration /
                                               (60 * 60 * 24)),
                 broadcast_incremental_backup=broadcast_incremental_backup,
                 image_local_cache=image_local_cache,
                 flash=flash)
Exemple #5
0
def search(request, query):
    conn = sqlite3.connect(setting.get("DB"))
    conn.row_factory = json_factory
    cur = conn.cursor()
    offset = (int(request.GET.get("page", "1")) - 1) * 10
    result = cur.execute(
        """
		select url,title from pages where title like '%s' limit 10 offset %d;
		"""
        % (("%" + query + "%"), offset)
    ).fetchall()
    return Response(json.dumps(result), content_type="application/json")
Exemple #6
0
    def _create_workers(self):
        self._workers.clear()
        requests_per_minute = setting.get('worker.requests-per-minute', int,
                                          REQUESTS_PER_MINUTE)
        local_object_duration = setting.get('worker.local-object-duration',
                                            int, LOCAL_OBJECT_DURATION)
        broadcast_incremental_backup = setting.get(
            'worker.broadcast-incremental-backup', bool,
            BROADCAST_INCREMENTAL_BACKUP)
        broadcast_active_duration = setting.get(
            'worker.broadcast-active-duration', int, BROADCAST_ACTIVE_DURATION)
        image_local_cache = setting.get('worker.image-local-cache', bool,
                                        IMAGE_LOCAL_CACHE)

        self._worker_input = Queue()
        worker_args = {
            'debug': settings.get('debug'),
            'queue_in': self._worker_input,
            'queue_out': self._worker_output,
            'requests_per_minute': requests_per_minute,
            'local_object_duration': local_object_duration,
            'broadcast_incremental_backup': broadcast_incremental_backup,
            'image_local_cache': image_local_cache,
            'broadcast_active_duration': broadcast_active_duration,
            'db_path': db.DATEBASE_PATH,
        }
        worker = Worker(**worker_args)
        self._workers[worker.name] = worker
        proxies = setting.get('worker.proxies', 'json')
        if not proxies:
            return
        for proxy in proxies:
            worker_args['proxy'] = proxy
            worker = Worker(**worker_args)
            self._workers[worker.name] = worker
Exemple #7
0
def new(VBat):
    import setting
    import ubinascii
    import network
    try:
        keypresses = setting.get('keypresses') + 1
        hwid = ubinascii.hexlify(network.WLAN().config('mac'),
                                 ':').decode().upper()
        setting.set('keypresses', keypresses)
        setting.set('hwid', hwid)
        setting.set('VBat', VBat)
        setting.set('RSSI', network.WLAN().status('rssi'))
    except:
        print('ERROR in RepUpdate.new')
def now(ExTime=600):
    from ntptime import settime
    import setting
    import utime
    import time

    timeserver = setting.get('timeserver')
    try:
        print(utime.time())
        timeset = False
        nn = 0
        while timeset == False:
            try:
                if timeserver == '':
                    settime()
                    timeset = True
                else:
                    settime(timeserver)
                    timeset = True
            except:
                timeset = False
                print('Try NTP')
                nn += 1
                if nn == 15:
                    timeset = True
                time.sleep(1)
        print(utime.time())
        IOTHUB = setting.get('iothub')
        DEVICE = setting.get('iotdevicename')
        KEY = setting.get('iotdevicesecret')
        USER = IOTHUB + '/' + DEVICE  #+ '/api-version=2016-11-14'
        EXPIRES = utime.time() + 946684800 + ExTime  # +30 Jahre + 10 Min
        PASSWD = GenerateAzureSasToken(IOTHUB + '/devices/' + DEVICE, KEY,
                                       EXPIRES)
    except:
        PASSWD = ''
    return PASSWD
Exemple #9
0
	def __init__(self):
		self.conn = sqlite3.connect(setting.get("DB"))
		self.readed = 0
		try:
			self.conn.execute("""
				create table pages (
					id INTEGER PRIMARY KEY,
					title text,
					html text,
					content_hash integer,
					url text,
					depth real,
					created_date text);
			""")
			self.conn.execute("""
				create index pages_title on pages(title desc);
				create index pages_url on pages(url desc);
			""")
		except:
			pass
Exemple #10
0
def do_sta():
    import network
    import time
    import setting
    try:
        ssid = setting.get('ssid')
        password = setting.get('password')
        usedhcp = setting.get('usedhcp')
        ip = setting.get('ip')
        netmask = setting.get('netmask')
        gateway = setting.get('gateway')
        dnsserver = setting.get('dnsserver')
        sta_if = network.WLAN(network.STA_IF)
        sta_if.active(True)
        if usedhcp == 'no':
            sta_if.ifconfig((ip, netmask, gateway, dnsserver))
        sta_if.connect(ssid, password)
        setting.set('opsmode', 'client')
    except:
        print('ERROR STA WIFI')
Exemple #11
0
 def get(self, flash=''):
     proxies = setting.get('worker.proxies', 'json', [])
     self.render('settings/network.html',
                 proxies='\n'.join(proxies),
                 flash=flash)
def handleInterrupt(timer):    
    global interruptCounter
    global save_flag
    interruptCounter = interruptCounter + 1
    if interruptCounter == 1:        
        timeserver = setting.get('timeserver')
        if timeserver == '':
            setting.set('timeserver', 'pool.ntp.org') 
        webrepl.stop()
        RepUpdate.new(VBat)
                    
    if interruptCounter <= 5:
        print('<= 5 sec')
        if adc.read() < 200:
            timer.deinit()
            wifi.do_nothing()
            wifi.do_sta()
            print('Push Message')
            led_blink(10, 200, 0)
            if wifi.wait_sta(15):
                try:
                    import GenSasToken
                    import AzurePublish
                    import ubinascii
                    import network
                    mac = ubinascii.hexlify(network.WLAN().config('mac'),':').decode().upper()
                    UserJson = setting.get('userjson')
                    UserJson = UserJson.strip('\n')
                    UserJson = UserJson.strip('\r')
                    UserJson = UserJson.strip('\n')
                    UserJson = UserJson.strip(' ')
                    UserJson = UserJson.lstrip('{')
                    UserJson = UserJson.rstrip('}')
                    UserJson = UserJson.strip(' ')
                    msg = '{"UniqueID": "' + mac + '"'
                    if UserJson != '':
                        msg += ',' + UserJson
                    msg += '}'
                    gc.collect()
                    token = GenSasToken.now()
                    gc.collect()
                    encoded = AzurePublish.data(msg, token)
                except:
                    encoded = 'ERROR'
            else:
                encoded = 'ERROR'
            if encoded != 'ERROR':
                try:
                    dict = ujson.loads(encoded)
                    dict = dict["desired"]
                    setting.set('FWnumberNew', dict["FWnumber"])
                    setting.set('FWurl', dict["FWurl"])
                except:
                    print('ERROR TWIN MSG')
                led_blink(1, 1023, 0)
            else:
                print('ERROR Azure TX')
                led_blink(1, 0, 1023)
            time.sleep(2)    
            led_blink(1, 0, 0)
            RepUpdate.update()
            shutdown(save_flag)
    if interruptCounter == 5:
        print('5 sec')
        led_blink(1, 200, 200)
    if interruptCounter == 10:
        print('10 sec')
        if adc.read() < 200:
            print('WEB AP ...')
            timer.deinit()
            wifi.do_nothing()
            wifi.do_ap()
            led_blink(1, 0, 200)
            time.sleep(2)
            try:
                import webserver
                webserver.start()
            except:
                print('WEB Server Crash') 
            led_blink(1, 0, 0)
            shutdown()
        else:
            led_blink(3, 200, 200)
    if interruptCounter == 15:
        print('15 sec')
        if adc.read() < 200:
            print('WEB STA ...')
            timer.deinit()
            wifi.do_nothing()
            wifi.do_sta()
            led_blink(3, 0, 200)
            if wifi.wait_sta(15):
                try:
                    import webserver
                    webserver.start()
                except:
                    print('WEB Server Crash') 
            led_blink(1, 0, 0)
            shutdown()
        else:
            led_blink(10, 0, 511)
            print('Repair Time 120 sec')
            wifi.do_nothing()
            wifi.do_ap()
            wifi.do_sta()
            wifi.wait_sta(15)
            webrepl.start()
    if interruptCounter == 120:
        timer.deinit()
        print('120 sec')
        shutdown(False)