예제 #1
0
 def run(self):
     sleep(0.2)
     while True:
         if self.ser.in_waiting:
             try:
                 text = self.ser.readline()
                 local_dt = datetime.utcnow().replace(
                     tzinfo=pytz.utc).astimezone(
                         pytz.timezone('Asia/Taipei'))
                 currentTime = pytz.timezone('Asia/Taipei').normalize(
                     local_dt).strftime('%H:%M:%S\'%f')[:-3]
                 self.timeQueue.put(currentTime)
                 self.dataQueue.put(text)
             except SerialException as e:
                 print("Serial exception: " + str(e))
                 pass
예제 #2
0
 def output_csv(self):
     file_path = getcwd() #取路徑的資料
     with open(file_path + "/" + today() + "weaned weight" +'.csv','a+',encoding="utf-8",newline='') as csv_file:
         write = csv.writer(csv_file)
         header = ["sow id", "piglet id", "weight","fence weight","number born alive"]
         write.writerow(header)
         print("===OUTPUT CSV DEBUG PART===")
         for j in range(len(self.system.fence_list)-1):
             print("fence_weight: "+str(self.system.fence_list[j].weight)) # 印在終端機的
             if self.system.fence_list[j].weight is not None:       
                 for i in range(len(self.system.fence_list[j].piglet_list)-1):        
                     print("pig_weight: "+str(self.system.fence_list[j].piglet_list[i].weight)) 
                     temp = self.system.fence_list[j].pig_id[i] # [母豬,小豬]
                     temp.append(str(self.system.fence_list[j].piglet_list[i].weight)) # [母豬,小豬,小豬重量]
                     print(list_to_str(temp)) # 印在終端機的
                     write.writerow(temp)
             temp1 = ["", "", "", self.system.fence_list[j].weight, len(self.system.fence_list[j].piglet_list)-1]
             write.writerow(temp1)
         print("===OUTPUT CSV DEBUG PART===")
예제 #3
0
 def analyze_data5(self):
     print(f'analyze method 5 利用滑動窗口,判斷數據穩定後,算平均')
     analyze_data5(self.system.threshold, self.system.sampleSize, self.weight_values, self.time_values, getcwd(), self.data_filename)
예제 #4
0
 def analyze_data4(self):
     print(f'analyze method 4 取{self.system.sampleSize}筆data, 前 n比不計, 刪除離群值, 算平均')
     analyze_data4(self.system.threshold, self.system.sampleSize, self.weight_values, getcwd(), self.data_filename)
예제 #5
0
 def analyze_data1(self):
     print(f'analyze method 1 取{self.system.sampleSize}筆data, 直接算平均')
     analyze_data1(self.system.threshold, self.system.sampleSize, self.weight_values, getcwd(), self.data_filename)
예제 #6
0
 def get_record_file(self):
     self.data_filename, self.weight_values, self.time_values = get_record_file()
     print("取得歷史資料: " + self.data_filename)
     btn_list = [self.btn_analyze_data1, self.btn_analyze_data2, self.btn_analyze_data3, self.btn_analyze_data4, self.btn_analyze_data5, self.btn_analyze_data_all]
     for btn in btn_list:
         btn.configure(state=NORMAL)
예제 #7
0
 def write_data(self, info):
     if self.ser.is_open == True:
         print("serial writing data:" + str(info))
         self.ser.write(info.encode("utf-8"))
     else:
         print("serial write error")
예제 #8
0
    def read_data(self):  #讀取資料
        value = True
        while self.system.dataQueue.qsize():
            try:  # get data from queue
                data = self.system.dataQueue.get()
                currentTime = self.system.timeQueue.get()
                # print("original data: "+ str(data))
                data = data.decode().strip("ST,GS,").strip("US,GS,").strip("ST,NT,").strip("ST,TR,").strip("OL,GS")
                data = data.strip().strip("kg").strip().strip("+").replace(" ", "")
                if value:
                    try:  # transfer to float
                        data = float(data)
                        value = False
                        error = 0
                    except:
                        error = 1
                        print("read_data except_error")
                    if not error:
                        self.weight_var.set(data)
                        # local_dt = datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Taipei'))
                        # currentTime = pytz.timezone('Asia/Taipei').normalize(local_dt).strftime('%H:%M:%S\'%f')[:-3]
                        print("serial: " + currentTime + " " + str(data))
                        self.system.datafile.write(currentTime + " " + str(data) + "\n")
                        
                        ##########  Algorithms Part  ##########
                        if (data - self.totalWeight) >= self.system.threshold:  #  record weight
                            self.system.fence_list[-1].piglet_list[-1].weight_list.append(data)
                            self.system.fence_list[-1].piglet_list[-1].time_list.append(currentTime)
                            self.pig_weight_show.configure(bg="gray77",fg="gray77")
                            self.litter_weighing_show.configure(bg="gray77",fg="gray77")
                        elif (self.totalWeight - data) >= self.system.threshold:  #  pick up pig
                            if data < self.system.threshold and data >=0:
                                self.litter_weight.set(str(round(self.system.fence_list[-1].weight,2))+"kg")
                                self.litter_weighing_show.configure(bg="white",fg="black")
                                self.en_sow.configure(font=("Calibri",26),width=10, fg="red")
                                self.input_sow_id.set("請輸入耳號")
                                self.totalWeight = 0.0
                                self.clear_table()
                                self.system.datafile.close()
                                self.system.datafile = open(today()+'_'+time()+'.log',"w")
                                f = Fence()
                                self.system.fence_list.append(f)
                                self.zeroing()
                        # claculate the average
                        statement = False  #自動/手動決定重量有不同的判斷式
                        if (len(self.system.fence_list[-1].piglet_list[-1].weight_list)) >= self.system.sampleSize:
                            if self.system.autoMode:
                                statement = True
                        if str(self.focus_get()) == ".!frame.!frame.!button2":
                            if not self.system.autoMode:
                                statement = True
                                local_dt = datetime.utcnow().replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Taipei'))
                                tmp = pytz.timezone('Asia/Taipei').normalize(local_dt).strftime('%H:%M:%S\'%f')[:-3] +  " press_decide_weight_button\n"
                                self.system.datafile.write(tmp) #記錄按按鈕的時間
                        if statement:
                            # check if stationary or not
                            index = self.system.fence_list[-1].piglet_list[-1].index
                            temp_list = self.system.fence_list[-1].piglet_list[-1].weight_list[index:index+self.system.sampleSize]
                            time_list = self.system.fence_list[-1].piglet_list[-1].time_list[index:index+self.system.sampleSize]
                            self.system.fence_list[-1].piglet_list[-1].index += 1
                            # pass the temp_list and time_list into kpss_test function to check if it is stationary or not
                            ser_data = pd.Series(temp_list, index=time_list)
                            self.system.fence_list[-1].piglet_list[-1].kptest.append(1 if kpss_test(ser_data) else 0)  # record the kpss return value
                            if len(self.system.fence_list[-1].piglet_list[-1].kptest) < 5:
                                continue  # less than five times
                            if self.system.fence_list[-1].piglet_list[-1].kptest[-5:] != [1]*5:
                                continue  # the latest five value is not stationary
                            # is stationary! -> calculate the average
                            temp_list = self.system.fence_list[-1].piglet_list[-1].weight_list[index-4:index+self.system.sampleSize]
                            temp_list = [round(i-self.totalWeight, 2) for i in temp_list]  # minus the former totalWeight to get actual weight
                            last_ave = round(np.mean(temp_list), 2)  # get the average
                            self.system.fence_list[-1].piglet_list[-1].weight = last_ave  # record the pig weight actual value
                            self.totalWeight += last_ave  # renew totalWeight
                            self.system.fence_list[-1].weight = self.totalWeight  # record the fence weight


                            # 儲存豬耳號
                            temp_ID=[self.input_sow_id.get() ,self.input_piglet_id.get()]
                            self.system.fence_list[-1].pig_id.append(temp_ID)  # record ID
                            self.tree.insert("","end",values=[self.input_piglet_id.get(), str(last_ave)])  # add pigID and weight in the table
                            self.update_minmax(last_ave)  # update the min and max value
                            # claculate pig number
                            if self.system.fence_list[-1].piglet_list is not []:
                                self.piglet_save_num.set("已存豬數:"+str(len(self.system.fence_list[-1].piglet_list)))
                                self.system.fence_list[-1].piglet_num = len(self.system.fence_list[-1].piglet_list)
                            # show information on GUI
                            self.piglet_weight.set(str(round(self.system.fence_list[-1].piglet_list[-1].weight,2))+"kg")
                            self.pig_weight_show.configure(bg="white",fg="black")
                            self.en_piglet.configure(font=("Calibri",26),width=10, fg="red")
                            self.input_piglet_id.set("請輸入耳號")
                            # create a new pig, be ready to weight the next pig
                            p = Pig()
                            self.system.fence_list[-1].piglet_list.append(p)   
            except queue.Empty:
                pass
        self.weight_value_show = self.label_weighing_nowshow.after(100, self.read_data)
예제 #9
0
 def stop_weighting(self):
     self.label_weighing_nowshow.after_cancel(self.weight_value_show)
     self.system.serialthread.ser.reset_input_buffer()
     self._async_raise(self.system.serialthread.ident, SystemExit)
     self.system.serialthread.join()  
     print("Stopped!")
     self.system.datafile.close()
     self.system.serialthread.ser.close()
     print("===STOP WEIGHTING DEBUG PART===")
     print(len(self.system.fence_list))
     for i in range(self.system.fence_list[0].piglet_num):
         print("length: " +str(len(self.system.fence_list[0].piglet_list[i].weight_list)))
         print(self.system.fence_list[0].piglet_list[i].weight)
     print("===STOP WEIGHTING DEBUG PART===")
     self.output_csv()