def on_data(frame_id, img, bboxes, img_path): """ When objects are detected, this function will be called. Args: frame_id: the frame number img: a numpy array which stored the frame bboxes: A list contains several `libs.darknet.yolo_device.ExtendedBoundingBox` object. The list contains all detected objects in a single frame. img_path: The path of the stored frame. If `output_dir` is None, this parameter will be None too. """ global tmp for det in bboxes: now = datetime.datetime.now() # You can push these variables to IoTtalk sever class_name = det.get_class_name() confidence = det.get_confidence() center_x, center_y = det.get_center() if int(now.strftime("%Y%m%d%H%M%S"))>int((tmp+datetime.timedelta(seconds=10)).strftime("%Y%m%d%H%M%S")): # You can add different condition at here msg = "\nPeople detected, see: https://"+img_path.split('www')[1]+"\nToday's snapshots: https://"+(img_path.split('www')[1]).rsplit("/", 2)[0]+"/" tmp = now LineNotify.line_notify(msg) DAN.push('yPerson-I', str(det.get_obj_id()), center_x, center_y, img_path.split('www')[1]) print(confidence, center_x, center_y) print(img_path) time.sleep(1)
def job_of_time_action_info(_action_list): global time_probe global last_time global now_time last_time = 0 while (time_probe < len(action_list)): # get current action list target = action_list[time_probe] # get current time now_time = target[0] # iottalk delay #now_time -= 2 # get current action target_action = target[1] target_time = now_time - last_time time.sleep(target_time) print("timer: ", end='') print(now_time) print("action: ", end='') print(target_action) #if (DAN.state == 'SET_DF_STATUS'): DAN.push('musicMonitorI', target_action) # update last_time last_time = now_time # move probe to next action time_probe += 1 time.sleep(300) # dummy delay XDD
def resume(): print('Sending information', end='', flush=True) i = 5 while(i): i -= 1 time.sleep(1) DAN.push('ReversiTalkAIOutput', -1, {'event': 'emitBoardUpdate', 'data': 'AI is fetching data.'}) print('.', end='', flush=True) print('Information sent.')
def handle_message(event): Msg = event.message.text if Msg == 'Hello, world': return print('GotMsg:{}'.format(Msg)) DAN.push('TextSenderIDF', Msg) #line_bot_api.reply_message(event.reply_token,TextSendMessage(text=value1[0])) # Reply API example userId = event.source.user_id if not userId in user_id_set: user_id_set.add(userId) saveUserId(userId)
def auto_push_switch(): global data while True: if data['Manual_mode'] == 0: if check_time() and check_control(): Switch_control(1, 'control') else: Switch_control(0, 'control') DAN.push('Switch1', data['switch']) time.sleep(5)
def print_sound(indata=0, outdata=50, frames=1000, time=10, status=50): global gotInput, volume_norm volume_norm = np.linalg.norm(indata) * 10 print(int(volume_norm)) if (int(volume_norm) > 10): max_volume = int(volume_norm) # #print("max volume = ",max_volume,"\n") DAN.push('wea_date', max_volume, max_volume) gotInput = True
def Push_Activate(): try: IDF_data = 1 DAN.push('SState_I4', IDF_data) 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) #start few second time.sleep(120) IDF_data = 0 DAN.push('SState_I4', IDF_data)
def turn_off_job(toggle_id): #print(datetime.now()) DAN.push('5Toggle-I{}'.format(toggle_id), 0) print('5Toggle-I{} push 0'.format(toggle_id)) job_dict['toggle{}'.format(toggle_id)]['trigger_status'] = 0 get_turn_off_data = { 'id': toggle_id, 'turn_off_time': job_dict['toggle{}'.format(toggle_id)]['turn_off_time'].strftime( '%H:%M'), 'toggle_value': job_dict['toggle{}'.format(toggle_id)]['toggle_value'], 'trigger_status': job_dict['toggle{}'.format(toggle_id)]['trigger_status'] } print(get_turn_off_data)
def handle_message(event): Msg = event.message.text if Msg == 'Hello, world': return print('GotMsg:{}'.format(Msg)) DAN.push('MSG-I', Msg) #Line_Temp=DAN.pull('MSG-O') #Line_Temp=str(Line_Temp) #Line_Temp=Line_Temp.replace("[","") #Line_Temp=Line_Temp.replace("]","") #Line_Temp=Line_Temp.replace("'","") line_bot_api.reply_message( event.reply_token, TextSendMessage(text='hello')) # Reply API example userId = event.source.user_id if not userId in user_id_set: user_id_set.add(userId) saveUserId(userId)
def job_of_music_feature(music_file): """ fetch message from music file and get music features """ midi_file = MidiFile(music_file) note_color = ColorMapping() for msg in midi_file: # print(dir(msg)) # exit() time.sleep(msg.time) if not msg.is_meta: # print(msg) str_msg = str(msg) mid = MidiMessage(str_msg) if mid.channel() == 0: # print(str_msg) # print('note:', mid.note()) # print('velocity: ', mid.velocity()) if mid.velocity() > 0: color = note_color.get_note_color(mid.note()) print('color:', color) # print(color[0]) # exit() DAN.push('Note', color[0], color[1], color[2])
def send_frame_to_iottalk(buf, boxes): #print(type(buf)) #array = buf.tolist() #print(len(buf)) frame_string = str(buf) person_information = json.dumps(boxes) #print(person_information) #print(data) #print(len(data)) try: # @0: string # @1: json DAN.push('IDF_Frame', frame_string, person_information) print('push') 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.')
def job_of_send_info(): global sequence, action_list, send_signal, change, now, last, freq_list while (sequence < len(action_list)): #Pull data from a device feature called "Dummy_Control" #value1=DAN.pull('Dummy_Control') #if value1 != None: # send_signal = 1 #print (value1[0]) #Push data to a device feature called "Dummy_Sensor" # job_of_play_music() #change = action_list[sequence] #change = int(change[0]) change = int(freq_list[now]) / 100 change = int(change) # change = change+1 # change = change % 8 push_data = [0, 0, 0, 0, 0, 0, 0] if (change == 0): push_data = [0, 0, 0, 0, 0, 0, 1] elif (change == 1): push_data = [0, 0, 0, 0, 0, 1, 1] elif (change == 2): push_data = [0, 0, 0, 0, 1, 1, 1] elif (change == 3): push_data = [0, 0, 0, 1, 1, 1, 1] elif (change == 4): push_data = [0, 0, 1, 1, 1, 1, 1] elif (change == 5): push_data = [0, 1, 1, 1, 1, 1, 1] elif (change >= 6): push_data = [1, 1, 1, 1, 1, 1, 1] else: push_data = [0, 0, 0, 0, 0, 0, 0] # sequence += 1 print(change, freq_list[now]) #color_list = [] if (beat_strength[sequence] > 6): print(beat_strength[sequence]) if (sequence == len(action_list)): DAN.push('music_ctl_i', 0, 0, 0, 0, 0, 0, 0) else: DAN.push('music_ctl_i', push_data[0], push_data[1], push_data[2], push_data[3], push_data[4], push_data[5], push_data[6]) last = now now = now + 1 sequence += 1 time.sleep(float(action_list[now]) - float(action_list[last])) # end DAN.push('music_ctl_i', 0, 0, 0, 0, 0, 0, 0)
def parse(what): global cmd, r, g, b, Luminance, lum what += ["-1", "-1", "-1", "-1"] # append for missing argument (cmd, haha, *_) = what # Luminance value cmd = cmd.upper() if cmd[0] == "Q" or cmd[0] == "E": return if cmd[0] == "S": showData() return if cmd[0] == "L": Luminance = myInt(haha) if Luminance < 0: Luminance = 198 # no data DAN.push('Dummy_Sensor', Luminance, Luminance) elif cmd[0] == "C": # Color r, g, b, brightness (cmd2, r, g, b, lum, *_) = what r = myInt(r) g = myInt(g) b = myInt(b) # ignore exception if (r < 0): r = 102 # no data if g < 0: g = 153 if b < 0: b = 153 DAN.push('Color-I', r, g, b) lum = myInt(lum) # Lum NOT specified if got -1 if lum >= 0: Luminance = lum DAN.push('Dummy_Sensor', Luminance, Luminance) else: print("Illegal command. Only C / L two commands allowed.") print("Please Re-Enter your ", end="")
or (int(mode) == 2 and globals.sunlight != "0.0")): value2 = 100 print("Time to wake up!!!!!!!!!!\n") else: value2 = 0 print("TIME ", hour, ": ", minute, "\n") #print(hour,sethour,minute,setminute) #value3 = hum gotInput = False # so that you can input again #if(allDead): break DAN.push('wea_date', value2, value2) #DAN.push ('AtPressure', value2, value2) time.sleep(1) DAN.push('wea_hum', hum, hum) time.sleep(1) DAN.push('wea_rain', rain, rain) time.sleep(1) DAN.push('wea_temp', temp, temp)
DAN.profile['dm_name'] = 'Dummy_Device' DAN.profile['df_list'] = ['Dummy_Sensor', 'Dummy_Control'] DAN.profile['d_name'] = None # None for autoNaming DAN.device_registration_with_retry(ServerURL, Reg_addr) tag = 0 cnt = 0 now_time = 0 delta = 0 avg_delay = 0 sum_delay = 0 while True: try: #Pull data from a device feature called "Dummy_Control" DAN.push('Dummy_Sensor', time.time()) value1 = DAN.pull('Dummy_Control') if cnt >= 100: avg_delay = sum_delay / 100 print(avg_delay) if value1 != None and cnt < 100: #if value1[0] == now_time delta = time.time() - value1[0] sum_delay = sum_delay + delta print(sum_delay) cnt = cnt + 1 #Push data to a device feature called "Dummy_Sensor" #value2=random.uniform(1, 10) #time.sleep(0.1)
DAN.profile['dm_name'] = 'Dummy_Device' DAN.profile['df_list'] = [ 'Dummy_Sensor', 'Dummy_Control', ] #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 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)
if tmp is None: print 'f_name is none' continue else: client.delete(f_name) v = type_(tmp) if v is not None: os.system( r'echo "default-on" > /sys/class/leds/ds:green:wlan/trigger' ) print 'DAN.push({f}, {v!r})'.format( f=f_name, v=v, ) DAN.push(f_name, v) os.system( r'echo "none" > /sys/class/leds/ds:green:wlan/trigger') if reConnecting: '''LED_flash(1)''' reConnecting = 0 #except KeyboardInterrupt: # DAN.deregister() # LED_flash(0) # break except Exception, e: print(e) '''LED_flash(0) '''
threadx.start() while True: try: if (allDead): break #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" #value2=random.uniform(1, 10) ## original Dummy_Device example if gotInput: # we have data in theInput if (allDead): break gotInput = False # so that you can input again DAN.push('Dummy_Sensor', theInput, theInput) # 試這: DAN.push('Dummy_Sensor', theInput) #DAN.push('Color-I', theInput[0], theInput[1], theInput[2]) 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) try: time.sleep(0.2) except KeyboardInterrupt: break time.sleep(0.25)
for row in data_rows: if len(row.find_all('td')) == 16: loc = row.find_all('td')[1].find('a').text if (loc in Cord) and (loc == target): print(Cord[loc]['eng'] + " temp:" + row.find_all('td')[3].text + " wind:" + (row.find_all('td')[7].text )[0:len(row.find_all('td')[7].text) - 1] + " humidity:" + row.find_all('td')[12].text + " rainfall:" + row.find_all('td')[14].text) DAN.push( 'weather-i', Cord[loc]['eng'] + " temp:" + row.find_all('td')[3].text + " wind:" + (row.find_all('td')[7].text )[0:len(row.find_all('td')[7].text) - 1] + " humidity:" + row.find_all('td')[12].text + " rainfall:" + row.find_all('td')[14].text) #Push data to a device feature called "Dummy_Sensor" # test = input("instruction: ") # DAN.push ('weather-I',test) 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.')
gotInput = True # 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: # Push data to a device feature called "Dummy_Sensor" if gotInput: gotInput = False # so that you can input again if (allDead): break DAN.push('Dummy_Sensor', theInput[0], theInput[1], theInput[2]) 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) try: time.sleep(0.5) except KeyboardInterrupt: break time.sleep(0.5) try:
print() print(select_df) #print(list) #print("counter = ",counter) #Push data to a device feature called "Dummy_Sensor" #value2=random.uniform(1, 10) ## original Dummy_Device example if gotInput: # we have data in theInput try: value2 = float(theInput) except: value2 = 0 if (allDead): break gotInput = False # so that you can input again DAN.push('Dummy_Sensor', value2, value2) # 試這: DAN.push('Dummy_Sensor', theInput) 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) try: time.sleep(0.2) except KeyboardInterrupt: break time.sleep(0.25) try:
#value2=random.uniform(1, 10) sss = theInput.split(' ') if (len(sss) == 1): flag = 1 value2 = float(theInput) elif (len(sss) >= 2): if (len(sss) == 2): sss.append(color[2]) for i in range(3): color[i] = float(sss[i]) flag = 2 gotInput = False # so that you can input again if (allDead): break if (flag == 1): DAN.push('Dummy_Sensor', value2, value2) elif (flag == 2): DAN.push('Color-I', color[0], color[1], color[2]) 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) try: time.sleep(0.2) except KeyboardInterrupt: break
# print(value1[0]) if cnt > 100: print("result delay:") print(sum_delay / 100) if value1 != None and cnt <= 100: cnt = cnt + 1 # print(value1) print("now delay: ") delay = time.time() - value1[0] sum_delay = sum_delay + delay print(delay) #Push data to a device feature called "Dummy_Sensor" # value2 = random.uniform(1, 10) now_time = time.time() #print(now_time) #DAN.push('Dummy_Sensor', value2, value2) DAN.push('Dummy_Sensor', now_time) #print(now_time) #DAN.push('Sandy_I', 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) #time.sleep(0.2)
time.sleep(15) while True: try: website = crawl_site('https://od.moi.gov.tw/MOI/v1/pbs') site_json = json.loads(website.text) new_accidents = get_element(site_json) print(accident_list) # print(new_accidents) for single_new_accident in new_accidents: print(single_new_accident) DAN.push('accident_info', single_new_accident[0], single_new_accident[1], single_new_accident[2], single_new_accident[3], single_new_accident[4]) time.sleep(1) new_accidents = [] print(new_accidents) 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)
import time, DAN, requests, random ServerURL = 'http://140.113.199.189:9999' #with no secure connection #ServerURL = 'https://DomainName' #with SSL connection Reg_addr = str(random.randint(1, 1024)) #if None, Reg_addr = MAC address DAN.profile['dm_name']='TextSender' DAN.profile['df_list']=['TextSenderIDF'] DAN.profile['d_name']= None # None for autoNaming DAN.device_registration_with_retry(ServerURL, Reg_addr) while True: try: DAN.push ('TextSenderIDF', input('(sendtext)>>>')) 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)
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: parse(ans) #value2=float( theInput ) except: value2 = 0 gotInput = False # so that you can input again if (allDead): break if cmd[0] == "L": #luminance DAN.push('Dummy_Sensor', Luminance, Luminance) print("cmd=", cmd, "; Luminance=", Luminance) elif cmd[0] == "C": #color DAN.push('Color-I', r, g, b) DAN.push('Dummy_Sensor', Luminance, Luminance) print("cmd=", cmd, ",R=", r, ",G=", g, ",B=", b, ",LUM=", Luminance) elif cmd[0] == "S": showData() continue elif cmd[0] == "Q" or cmd[0] == "E": break else: print( "Illegal command. Only C / L / S / Q / E commands allowed." )
) os.system(r'echo "none" > /sys/class/leds/arduino:blue:wlan/trigger') for f_name, type_ in idf_list: tmp = client.get(f_name) if tmp is None: continue else: client.delete(f_name) v = type_(tmp) if v is not None: os.system(r'echo "default-on" > /sys/class/leds/arduino:blue:wlan/trigger') print 'DAN.push({f}, {v!r})'.format( f=f_name, v=v,) DAN.push(f_name, v) os.system(r'echo "none" > /sys/class/leds/arduino:blue:wlan/trigger') if reConnecting: LED_flash(1) reConnecting = 0 #except KeyboardInterrupt: # DAN.deregister() # LED_flash(0) # break except Exception, e: print(e) LED_flash(0)
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 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(ServerIP, Reg_addr) else: print('Connection failed due to unknow reasons.') reConnecting = True
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)
#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) 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) try: time.sleep(0.2) except KeyboardInterrupt: break time.sleep(0.5) try:
#ServerURL = 'http://IP:9999' #with non-secure connection ServerURL = 'https://6.iottalk.tw' #with SSL connection Reg_addr = 'aaaarrrroooonnnn'#if None, Reg_addr = MAC address DAN.profile['dm_name']='temperature-0858610' DAN.profile['df_list']=['rain','temperature','wet','wind_direction','wind_power','RainMeter-O','Temperature-O','Humidity-O','WindDirection-O','WindSpeed-O','MSG-O'] DAN.profile['d_name']= 'Aaron' 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 last = 0 while True: try: DAN.push('rain',rain) DAN.push('temperature',temperature) #Push data to an input device feature "Dummy_Sensor" DAN.push('wet',wet) DAN.push('wind_direction',wind1) DAN.push('wind_power',wind2) #================================== 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)