Exemplo n.º 1
0
def Print(arg):
    while True:
        try:

            NUM = DAN.pull('HKA_MSG_NUM')
            print(NUM)
            NUM = str(NUM)
            NUM = NUM.replace("[", "")
            NUM = NUM.replace("]", "")
            NUM = NUM.replace("'", "")

            String = DAN.pull('HKA_MSG_STRING')
            print(String)
            String = str(String)
            String = String.replace("[", "")
            String = String.replace("]", "")
            String = String.replace("'", "")

            for userId in user_id_set:
                if NUM != 'None' and String != 'None':
                    line_bot_api.push_message(
                        userId, TextSendMessage(text=NUM + ' 時間: ' +
                                                String))  # Push API example
            time.sleep(0.5)
        except Exception as e:
            print(e)
            if str(e).find('mac_addr not found:') != -1:
                print('Reg_addr is not found. Try to re-register...')
                DAN.device_registration_with_retry(ServerURL, Reg_addr)
            else:
                print('Connection failed due to unknow reasons.')
                time.sleep(1)
Exemplo n.º 2
0
def server():
    while True:
        rawInput = DAN.pull('FP_LB3_msg_pull')
        if rawInput != None and bool(rawInput[0]):
            content = json.loads(str(rawInput[0]))
            if content['type'] == 'state_update':
                print("推播通知")
                for orderId in content['content']['orderID']:
                    query = (Users.select(Users, Orders).join(
                        Orders, on=(Users.userID == Orders.userID)).where(
                            Orders.orderID == orderId))
                    lineId = query[0].lineID
                    orderUid = query[0].orders_sent_by_user[0].orderUID
                    print(orderUid)
                    if content['content']['status'] == 1:
                        line_bot_api.push_message(
                            lineId,
                            TextSendMessage(
                                text='訂單編號{} 已開始出貨,欲知詳情請輸入「我的訂單狀態」。'.format(
                                    orderUid)))
                    elif content['content']['status'] == -1:
                        line_bot_api.push_message(
                            lineId,
                            TextSendMessage(text='訂單編號{} 已經送達,敬請前往取貨,謝謝您。'.
                                            format(orderUid)))
                    else:
                        print('push message status error')
            else:
                print('status not state_update')
Exemplo n.º 3
0
def south():
    while True:
        Msg = DAN.pull('wash_south')
        if Msg is not None:
            if Msg[0] != "":
                reply = "南棟:\n"
                w1num = len(crawl.sort_data_with_geo('S1W',
                                                     crawl.get_status()))
                reply += "1F洗衣機 %d 台" % (w1num)
                if w1num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('S1W'))

                d1num = len(crawl.sort_data_with_geo('S1D',
                                                     crawl.get_status()))
                reply += "\n1F烘衣機 %d 台" % (d1num)
                #if d1num == 0:
                #reply += " 最快%d分鐘後可使用"%(crawl.get_earilest_avaliable('S1D'))

                w10num = len(
                    crawl.sort_data_with_geo('S10W', crawl.get_status()))
                reply += "\n10F洗衣機 %d 台" % (w10num)
                if w10num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('S10W'))

                d10num = len(
                    crawl.sort_data_with_geo('S10D', crawl.get_status()))
                reply += "\n10F烘衣機 %d 台" % (d10num)
                if d10num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('S10D'))

                line_bot_api.push_message(Msg[0], TextSendMessage(text=reply))
                print(reply)
Exemplo n.º 4
0
def receive_frame_from_iottalk():

    #print('start receive frame from iottalk')
    try:
        data = DAN.pull('ODF_Frame')
        if data != None:
            frame_string = data[0]
            person_information = data[1]
            #print(person_information)

            tmp_array = literal_eval(frame_string)
            tmp_boxes = json.loads(person_information)
            #tmp_nparray = np.array(tmp_array)
            #tmp_buf = tmp_nparray.astype('uint8')
            #frame = cv2.imdecode(tmp_buf, 1)
            #cv2.imshow('Receive',frame)
            #cv2.waitKey(1)

            return (tmp_array, tmp_boxes)

    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
        else:
            print('Connection failed due to unknow reasons.')
            #time.sleep(1)

    #time.sleep(0.2)
    return None
Exemplo n.º 5
0
def trace():
	global device_location_bind
	while True:
		rawInput = DAN.pull('FP_LB3_trace_pull')
		if rawInput != None:
			content = json.loads(str(rawInput[0]))
			device_location_bind.update({content['driverId']: [content['lat'], content['long']]})
			print(content['driverId'], 'move to', content['lat'], content['long'])
Exemplo n.º 6
0
def whilepull():
    global Label_List
    while live_flag:
        for i in range(len(odf_List)):
            value = DAN.pull(odf_List[i])
            #print('Pull: {0} = {1}'.format(odf_List[i], value))
            if value != None:
                print('Pull: {0} = {1}'.format(odf_List[i], value[0]))
                Label_List[i].config(text=str(value[0]))
        time.sleep(1)
Exemplo n.º 7
0
def job():
    while 1:
        value1 = DAN.pull('msgO')
        if value1 != None:
            try:
                for userId in user_id_set:
                    line_bot_api.push_message(
                        userId,
                        TextSendMessage(text=value1[0]))  # Push API example
            except Exception as e:
                print(e)
Exemplo n.º 8
0
def Auto_pull():
    global odf_list, odf_data, data
    while True:
        time.sleep(5)
        if DAN.state == 'RESUME':
            for odf in odf_list:
                d = DAN.pull(odf)
                if d != None:
                    #print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S %p')-data[odf+'_time'])
                    data[odf + '_time'] = datetime.datetime.now().strftime(
                        '%H:%M:%S %p')
                    odf_data[odf] = round(d[0], 2)
Exemplo n.º 9
0
def pushlinemsg(user_id_set):
    while True:
        msg = DAN.pull('MSG-O')
        msg = str(msg)
        #print('msg:',msg)
        if msg:
            print('PushMsg:{}'.format(msg))
            for usrId in user_id_set:
                if msg != 'None':
                    line_bot_api.push_message(userId,
                                              TextSendMessage(text=msg))
                    time.sleep(5)
Exemplo n.º 10
0
def my_status():
    while True:
        Msg = DAN.pull('wash_my_status')
        if Msg is not None:
            if Msg[0] != "":
                if Msg[0] in user_list:
                    rest = crawl.get_duration(user_list[Msg[0]])
                    if rest > 0:
                        reply = "還剩%d分鐘就完成了" % rest
                    else:
                        reply = "無人使用本機器"
                    line_bot_api.push_message(Msg[0],
                                              TextSendMessage(text=reply))
                    print("我的使用狀態 " + reply)
                else:
                    line_bot_api.push_message(
                        Msg[0], TextSendMessage(text='你沒有正在使用的機器'))
                    print("你沒有正在使用的機器")
Exemplo n.º 11
0
def Iottalk_message():
    while True:
        try:
            value1 = DAN.pull('position')
            if value1 != None:
                nearby = GameInfo.updatePos(value1[0], float(value1[1]),
                                            float(value1[2]))
                if nearby:
                    line_bot_api.push_message(
                        nearby, TextSendMessage(
                            text='Treasure is nearby!!'))  # Push API example

        except Exception as e:
            print(e)
            if str(e).find('mac_addr not found:') != -1:
                print('Reg_addr is not found. Try to re-register...')
                DAN.device_registration_with_retry(ServerURL, Reg_addr)
            else:
                print('Connection failed due to unknow reasons.')
                time.sleep(1)
        time.sleep(0.2)
Exemplo n.º 12
0
def register():
    while True:
        Msg = DAN.pull('wash_register')
        if Msg is not None:
            if Msg[0] != "":
                if len(Msg[0][0]) == 0:
                    line_bot_api.push_message(
                        Msg[0][1], TextSendMessage(text='請輸入你正在使用的機器編號'))
                else:
                    data = crawl.sort_data_with_geo(Msg[0][0],
                                                    crawl.get_data(crawl.url))
                    if len(data) == 1:
                        if (crawl.get_duration(Msg[0][0]) == 0):
                            line_bot_api.push_message(
                                Msg[0][1],
                                TextSendMessage(text='請開始使用後再輸入機器編號'))
                        else:
                            user_list[Msg[0][1]] = Msg[0][0]
                            line_bot_api.push_message(
                                Msg[0][1],
                                TextSendMessage(text='你正在使用的機器為%s,使用完畢會提醒你' %
                                                Msg[0][0]))

                            timer = threading.Timer(
                                10, finish_timer,
                                args=(Msg[0][1],
                                      ))  #crawl.get_duration(Msg[0][0])*60
                            timer.daemon = True
                            timer.start()

                            timer = threading.Timer(
                                5, rest_timer,
                                args=(Msg[0][1],
                                      ))  #crawl.get_duration(Msg[0][0])*60-180
                            timer.daemon = True
                            timer.start()
                    else:
                        line_bot_api.push_message(
                            Msg[0][1], TextSendMessage(text='請輸入正確的機器編號'))
                print("我目前正在使用 " + str(Msg[0]))
Exemplo n.º 13
0
def Print(arg):
    while True:
        try:
            Line_Temp = DAN.pull('MSG-O')
            print(Line_Temp)
            Line_Temp = str(Line_Temp)
            Line_Temp = Line_Temp.replace("[", "")
            Line_Temp = Line_Temp.replace("]", "")
            Line_Temp = Line_Temp.replace("'", "")
            for userId in user_id_set:
                if Line_Temp != 'None':
                    line_bot_api.push_message(
                        userId,
                        TextSendMessage(text=Line_Temp))  # Push API example
            time.sleep(10)
        except Exception as e:
            print(e)
            if str(e).find('mac_addr not found:') != -1:
                print('Reg_addr is not found. Try to re-register...')
                DAN.device_registration_with_retry(ServerURL, Reg_addr)
            else:
                print('Connection failed due to unknow reasons.')
                time.sleep(1)
Exemplo n.º 14
0
def north():
    while True:
        Msg = DAN.pull('wash_north')
        if Msg is not None:
            if Msg[0] != "":
                reply = "北棟:\n"
                w1num = len(crawl.sort_data_with_geo('N1W',
                                                     crawl.get_status()))
                reply += "1F洗衣機 %d 台" % (w1num)
                if w1num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('N1W'))

                d1num = len(crawl.sort_data_with_geo('N1D',
                                                     crawl.get_status()))
                reply += "\n1F烘衣機 %d 台" % (d1num)
                if d1num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('N1D'))

                w9num = len(crawl.sort_data_with_geo('N9W',
                                                     crawl.get_status()))
                reply += "\n9F洗衣機 %d 台" % (w9num)
                if w9num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('N9W'))

                d9num = len(crawl.sort_data_with_geo('N9D',
                                                     crawl.get_status()))
                reply += "\n9F烘衣機 %d 台" % (d9num)
                if d1num == 0:
                    reply += " 最快%d分鐘後可使用" % (
                        crawl.get_earilest_avaliable('N9D'))

                line_bot_api.push_message(Msg[0], TextSendMessage(text=reply))
                print(reply)
Exemplo n.º 15
0
DAN.device_registration_with_retry(ServerURL, Reg_addr)
#DAN.deregister()  #if you want to deregister this device, uncomment this line
#exit()            #if you want to deregister this device, uncomment this line

while True:
    try:
        IDF_data = random.uniform(1, 10)
        DAN.push(
            'Dummy_Sensor',
            IDF_data)  #Push data to an input device feature "Dummy_Sensor"

        #==================================

        ODF_data = DAN.pull(
            'Dummy_Control'
        )  #Pull data from an output device feature "Dummy_Control"
        if ODF_data != None:
            print(ODF_data[0])

    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
        else:
            print('Connection failed due to unknow reasons.')
            time.sleep(1)

    time.sleep(0.2)
Exemplo n.º 16
0
incomming = {}
for f_name in [t[0] for t in odf_list]:
    incomming[f_name] = 0

reConnecting = 0
while True:
    try:
        cache = {}
        check_list = [t[0] for t in odf_list]
        for f_name, index, pin_name in odf_list:
            if f_name not in cache.keys():
                os.system(
                    r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger'
                )
                PIN = DAN.pull(f_name)
                cache[f_name] = PIN
            else:
                PIN = cache[f_name]

            if PIN != None:

                check_list.remove(f_name)

                if PIN[index] != None:
                    client.put(pin_name, str(int(PIN[index])))
                else:
                    continue

                if f_name not in check_list:
                    incomming[f_name] = (incomming[f_name] + 1) % 10000
Exemplo n.º 17
0
def timestamp_handler(timestamp):
    year = '2018'
    month = timestamp.split()[0].split('/')[0]
    day = timestamp.split()[0].split('/')[1]
    hour = timestamp.split()[1].split(':')[0]
    minute = timestamp.split()[1].split(':')[1]
    second = '00'
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second


####################################################################

while True:
    try:
        #Pull data from a device feature called "Dummy_Control"
        value1 = DAN.pull('weather-o')
        if value1 != None:
            target = value1[0]
            for url in urls:
                res = requests.get(url)
                res.encoding = 'utf-8'
                #確認是否回傳成功
                if res.status_code == requests.codes.ok:
                    #成功的話開始解析網頁
                    soup = BeautifulSoup(res.text, 'html.parser')
                    data_rows = soup.find_all('tr')
                    # print(data_rows[1].find_all('td'))
                    # 一筆資料
                    # [<td style="display: none;">46694</td>,                  *ID 0
                    # <td id="MapID46694"><a href="46694.htm">基隆</a></td>,   *測站名稱  1
                    # <td>11/20 11:20</td>,                                    *觀測時間  2
Exemplo n.º 18
0
from datetime import datetime as dt

ServerURL = 'https://2.iottalk.tw' #Change to your IoTtalk IP or None for autoSearching
Reg_addr=None # if None, Reg_addr = MAC address

DAN.profile['dm_name']='Dummy_Device'
DAN.profile['df_list']=['Dummy_Sensor', 'Dummy_Control',]
DAN.profile['d_name']= 'changhsinjung' 

DAN.device_registration_with_retry(ServerURL, Reg_addr)
alias = DAN.get_alias('Dummy_Sensor')
#print(alias)

while 1:
    try:
        tmp = alias 
        alias = DAN.get_alias('Dummy_Sensor')
        #TimeStr2 = dt.now().strftime('%H:%M:%S')
        if alias != [] :
            if alias!=tmp:
                print(alias)
            DAN.push("Dummy_Sensor",allstring)
            x = DAN.pull("Dummy_Control")
            print(x)

    except Exception as e:
        print(e)

    time.sleep(60)

        'job': None
    },
    'toggle3': {
        'trigger_time': None,
        'job': None
    },
    'toggle4': {
        'trigger_time': None,
        'job': None
    },
}

while True:
    try:
        for toggle_id in range(1, 5):
            data = DAN.pull('Threshold-O{}'.format(toggle_id))

            if data is not None:
                data = data[0]
                trigger_time = None

                if data in (0, 1):
                    DAN.push('Trigger-I{}'.format(toggle_id), data)
                    print('Trigger-I{} push {}'.format(toggle_id, data))
                    print(
                        job_dict['toggle{}'.format(toggle_id)]['trigger_time'])
                    if job_dict['toggle{}'.format(toggle_id)]['trigger_time'] is not None and \
                        datetime.now() < job_dict['toggle{}'.format(toggle_id)]['trigger_time']:
                        job3 = job_dict['toggle{}'.format(toggle_id)]['job']
                        job3.remove()
                        job_dict['toggle{}'.format(
Exemplo n.º 20
0
]
#DAN.profile['d_name']= 'Assign a Device Name'

DAN.device_registration_with_retry(ServerURL, Reg_addr)
#DAN.deregister()  #if you want to deregister this device, uncomment this line
#exit()            #if you want to deregister this device, uncomment this line
curr = 0
last = 1
while True:
    try:
        #IDF_data = random.uniform(1, 10)
        #DAN.push ('T0858812-I', IDF_data) #Push data to an input device feature "Dummy_Sensor"

        #==================================
        ODF_data = DAN.pull(
            'T0858812-O'
        )  #Pull data from an output device feature "Dummy_Control"
        if ODF_data != None:
            if ODF_data[0] > 0:
                curr = 1
            else:
                curr = 0
            if last != curr:
                print(curr)
            last = curr

    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
width = screen_size.width
screen_y = height / 2
screen_x = width / 2
gear = 1.0
current_flap = 0
sign_x = 0
sign_y = 0
sign_z = 0
xxx = 0
y = 0
z = 0
add_speed = 0
minus_speed = 0
while True:
    try:
        x = DAN.pull('Gear')
        if x is not None:
            if gear != x[0]:
                pyautogui.press('g')
            gear = x[0]
        print('a')
        x = DAN.pull('Calibrate')
        if x is not None:
            calibrate = x[0]
        print('b')
        x = DAN.pull('Terminate')
        if x is not None:
            terminate = x[0]
        print('c')
        x = DAN.pull('Add_speed')
        if x is not None:
Exemplo n.º 22
0

for i in range(Cell_num):
    DAN.profile['df_list'].append(getCellIDF_name(i + 1))
    DAN.profile['df_list'].append(getCellODF_name(i + 1))
#DAN.profile['d_name']= 'Assign a Device Name'

DAN.device_registration_with_retry(ServerURL, Reg_addr)
#DAN.deregister()  #if you want to deregister this device, uncomment this line
#exit()            #if you want to deregister this device, uncomment this line

#print(DAN.profile['df_list'])

while 1:
    try:
        for i in range(Cell_num):
            data = DAN.pull(getCellODF_name(i + 1))
            if data != None:
                DAN.push(getCellIDF_name(i + 1), data[0])

    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
        else:
            print('Connection failed due to unknow reasons.')
            time.sleep(1)

    time.sleep(0.2)
Exemplo n.º 23
0
            sys.exit()  # break  # raise   #  ?
        gotInput = True


# creat a thread to do Input data from keyboard, by [email protected]
threadx = threading.Thread(target=doRead)
threadx.daemon = True
threadx.start()

wind_lim = 21
visibility_lim = 15
prevMsg = 'fak'

while True:
    try:
        data = DAN.pull('Dummy_Control')
        if data != None:
            data = data[0]
            msg = ''
            if data[0] == 1:  # weather
                windir, speed, visi = data[1]
                if speed > wind_lim:
                    msg += 'WindSpeed too fast; '
                if visi < visibility_lim:
                    msg += 'Visibility too low; '
            elif data[0] == 2:  # accel
                ax, ay, az = data[1]
                if az < 3:
                    msg += 'Elite flying skill; '
            if msg != '' and msg != prevMsg:
                print(msg)
Exemplo n.º 24
0
import time, DAN, requests, random

ServerURL = 'http://140.113.199.200' #with no secure connection
#ServerURL = 'https://DomainName' #with SSL connection
Reg_addr = None #if None, Reg_addr = MAC address

DAN.profile['dm_name']='getWeather'
DAN.profile['df_list']=['Dummy_Sensor', 'MAP']
DAN.profile['d_name']= None # None for autoNaming
DAN.device_registration_with_retry(ServerURL, Reg_addr)

while True:
    try:
    #Pull data from a device feature called "Dummy_Control"
        value1=DAN.pull('MAP')
        if value1 != None:
            print (value1[0])

    #Push data to a device feature called "Dummy_Sensor"
        value2=random.uniform(1, 10)
        DAN.push ('Dummy_Sensor', value2,  value2)


    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
        else:
            print('Connection failed due to unknow reasons.')
            time.sleep(1)    
Exemplo n.º 25
0
odfs = config.odfs
idfs = config.idfs

DAN.profile['dm_name'] = config.basic["dm_name"]
DAN.profile['df_list'] = [name for (name, _) in (odfs + idfs)]
DAN.profile['d_name'] = config.basic["d_name"]  # None for autoNaming
DAN.device_registration_with_retry(ServerIP, Reg_addr)
LED_flash(1)

reConnecting = False

while True:
    try:
        #Pull data
        for (name, t) in odfs:
            val = DAN.pull(name)
            wrt.transmission_led(True)
            if val != None:
                client.put(name, str(val[0]))
        wrt.transmission_led(False)

        #Push data
        for (name, t) in idfs:
            data = client.get(name)
            DAN.push(name, t(data))
            wrt.transmission_led(True)
        wrt.transmission_led(False)

        if reConnecting:
            LED_flash(1)
            reConnecting = False
Exemplo n.º 26
0
@author: hankyang
"""
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
import threading
import time
import DAN

ServerURL = 'https://6.iottalk.tw'  #with SSL connection
Reg_addr = 'hank23020111154641'  #if None, Reg_addr = MAC address

DAN.profile['dm_name'] = 'L0858605'
DAN.profile['df_list'] = ['Line_Out']

DAN.device_registration_with_retry(ServerURL, Reg_addr)
while True:
    try:
        msg = DAN.pull('Line_Out')
        print(msg)
    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
        else:
            print('Connection failed due to unknow reasons.')
            time.sleep(1)
    time.sleep(5)
Exemplo n.º 27
0
LED_flash(1)

incomming = {}
for f_name in [t[0] for t in odf_list]:
    incomming[f_name] = 0

reConnecting = 0
while True:
    try:
        cache = {}
	check_list=[t[0] for t in odf_list]
	for f_name, index, pin_name in odf_list:

            if f_name not in cache.keys():
                os.system(r'echo "default-on" > /sys/class/leds/arduino:blue:wlan/trigger')
  	        PIN = DAN.pull(f_name)
		cache[f_name] = PIN
            else:
	        PIN = cache[f_name]
	
            if PIN != None:
   
                check_list.remove(f_name)

                if PIN[index] != None:
                    client.put(pin_name, str(int(PIN[index])))
                else: 
                    continue
                
                if f_name not in check_list:
                    incomming[f_name] = (incomming[f_name] + 1) % 10000
Exemplo n.º 28
0
def initial():
    initial_high()
    time.sleep(0.5)
    initial_low()
    time.sleep(0.5)
    SingleServoCtrl(6, 0, 50)
    time.sleep(1)


initial()
print('Initial done')

while True:
    try:
        Servo_O1_data = DAN.pull('Thumb-O')
        Servo_O2_data = DAN.pull('Index-O')
        Servo_O3_data = DAN.pull('Middle-O')
        Servo_O4_data = DAN.pull('Ring-O')
        Servo_O5_data = DAN.pull('Pinky-O')
        Servo_O6_data = DAN.pull('Wrist-O')
        if Servo_O1_data != None:
            servo1_data = Servo_O1_data[1]
            SingleServoCtrlWithAngle(1, servo1_data)
            #print('Servo1 data:'+ str(servo1_data))
        if Servo_O2_data != None:
            servo2_data = Servo_O2_data[1]
            SingleServoCtrlWithAngle(2, servo2_data)
            #print('Servo2 data:'+ str(servo2_data))
        if Servo_O3_data != None:
            servo3_data = Servo_O3_data[1]
Exemplo n.º 29
0
ServerIP = '140.113.199.199' # https://test.iottalk.tw
Reg_addr = '0316092' #None # if None, Reg_addr = MAC address

DAN.profile['dm_name']='0316092'
DAN.profile['df_list']=['0316092']
DAN.profile['d_name']= None # None for autoNaming
DAN.device_registration_with_retry(ServerIP, Reg_addr)

flag = 0 # 1: UP (neg) 2: DOWN (pos)
changeFlag = 0

# Start Device
while True:
    try:
    #Pull data from a device feature called "Dummy_Control"
        value1 = DAN.pull('0316092') # array

        if value1 != None:
            if(value1[0] == 1): #UP
                if flag != 1:
                    changeFlag = 1
                flag = 1
            else:
                if flag != 2:
                    changeFlag = 1
                flag = 2

            if changeFlag == 1:
                if flag == 1:
                    print('face up')
                else:
Exemplo n.º 30
0
           sys.stdout = sys.__stdout__
           print(" Thread say Bye bye ---------------", flush=True)
           sys.exit( )   ## break  # raise   #  ?
        gotInput=True
        if theInput !='quit' and theInput != "exit":
           print("Will send " + theInput, end="   , ")

#creat a thread to do Input data from keyboard, by [email protected]
threadx = threading.Thread(target=doRead)
threadx.daemon = True
threadx.start()

while True:
    try:
    #Pull data from a device feature called "Dummy_Control"
        value1=DAN.pull('Dummy_Control')
        if value1 != None:
            print (value1[0])
    #Push data to a device feature called "Dummy_Sensor" 
        if gotInput:
           if theInput =='quit' or theInput=="exit":
              break  #  sys.exit( );
           #value2=random.uniform(1, 10)
           try:
              value2=float( theInput )
           except:
              value2=0
           gotInput=False   # so that you can input again 
           if(allDead): break
           DAN.push ('Dummy_Sensor', value2,  value2)
Exemplo n.º 31
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 11 22:08:53 2019

@author: huangjunkai
"""
import time, random, requests
import DAN

ServerURL = 'https://6.iottalk.tw'  #with SSL connection
Reg_addr = 'qwwfoijefoiqhfeoiqvho'  #if None, Reg_addr = MAC address

DAN.profile['dm_name'] = 'L0858605'
DAN.profile['df_list'] = ['Line_Out', 'Dummy_Sensor']
DAN.device_registration_with_retry(ServerURL, Reg_addr)
while True:
    try:
        ANS = DAN.pull('Line_Out')
        print(ANS)
    except Exception as e:
        print(e)
        if str(e).find('mac_addr not found:') != -1:
            print('Reg_addr is not found. Try to re-register...')
            DAN.device_registration_with_retry(ServerURL, Reg_addr)
        else:
            print('Connection failed due to unknow reasons.')
            time.sleep(1)
    time.sleep(5)