def __init__(self, muxType, signal0, signal1 , carrierFrequency = GlobalSettings.carrierFrequency ,muxCarrierFrequency = GlobalSettings.multiplexCarrierFrequency, messageFrequency = GlobalSettings.messageFrequency, carrierAmplitude = GlobalSettings.multiplexCarrierAmplitude, sampleTime = GlobalSettings.sampleTime): self.fmux = muxCarrierFrequency self.fc = carrierFrequency self.fm = messageFrequency self.ac = carrierAmplitude self.ts = sampleTime self.type = muxType self.time = np.arange(0,1/self.fm,self.ts) self.roll = int((1.0/self.fc)/4.0*(1.0/self.ts)) self.quaterPoint = int(len(self.time)/4.0) #used to ensure correct normaliZaTION self.halfPoint = int(len(self.time)/2.0) #below we handle transmitters self.fakeTransmission = Transmission(1) self.cleanPilot, self.cosWave = self.GeneratePilot(False) self.s0, self.h0 = self.SignalDetector(signal0) self.fmux = 3* muxCarrierFrequency if(self.type == MultiplexerType.TDM): self.cleanPilot, self.cosWave = self.GeneratePilot(False,2) self.s1, self.h1 = self.SignalDetector(signal1)
def run(self): try: self.message_loop(self.handle) log.debug('Listening ...') while 1: tc = Transmission() arr = Transmission.garbage_collection(tc) if len(arr) > 0: # 노티할애가 있으면 pms = Plexmediaserver() if not pms.refresh(2): log.debug("refresh 실패로 완료된 시드유지함") return str = "\n".join(arr) for room in self.public_room: self.sendMessage(room, "%s\n 준비되었습니다." % str) time.sleep(10) except Exception as e: log.exception("Main loop error")
def __init__(self): Transmission.__init__(self, GearBoxFord(), Pedal(Pedal.TYPE_CLUTCH))
def handle(self, msg): flavor = 'normal' # normal message if flavor == 'normal': content_type, chat_type, chat_id = telepot.glance(msg) log.info('Normal Message:%s %s %s', content_type, chat_type, chat_id) log.debug(json.dumps(msg, ensure_ascii=False)) command = msg['text'] from_id = msg['from']['id'] chat_id = msg['chat']['id'] log.debug(command) if not command.startswith('/'): # 명령커맨드일 경우 return keyword = command[1:].split(' ') if not from_id in self.admin_id: log.debug(" 권한 없는 사용자(%d)가 봇을 호출" % from_id) self.sendMessage(chat_id, "저는 주인님의 명령만 듣습니다. 본인의 봇을 소환하세요. https://blog.zeroidle.com 에서 도움을 얻을 수 있습니다.") return if keyword[0] == "셧다운": log.debug("셧다운 권한확인") if from_id in self.admin_id: # 앞에서 권한체크하므로 이제 필요없음, 삭제예정 self.sendMessage(chat_id, "모든 서버를 셧다운 합니다.") else: log.debug(" 권한 없는 사용자(%d)가 셧다운 시도" % from_id) self.sendMessage(chat_id, "권한이 없습니다.") elif keyword[0] == "하이": self.sendMessage(chat_id, "반갑구만 반가워요") elif keyword[0] == "정보": self.sendMessage(chat_id,"chat_id:%s\nfrom_id:%s"%(chat_id, from_id)) elif keyword[0] == "검색": # 토렌트 검색해야지 if chat_id in self.public_room: # 채팅방이 공방이면 self.sendMessage(chat_id, "공개방입니다.\n 봇을 따로 소환해 검색하세요") return result = self.get_search_list(' '.join(keyword[1:])) self.set_menu(chat_id, from_id, result) elif keyword[0] == '받기': # 토렌트 검색해야지 idx = int(keyword[1].split('.')[0]) - 1 menu = self.menu[chat_id][idx] log.debug("다운로드주소 : %s" % menu['link']) #dn_link = self.get_magnet_url_from_torrenthaja(menu['link']) dn_link = self.get_magnet_url_from_torrenthaja(menu['link']) tc = Transmission() dn_path = tc.get_dnpath(menu['title']) log.debug("title: %s " % menu['title']) log.debug("link: %s " % dn_link) log.debug("다운로드경로는 %s" % dn_path) to = tc.add_torrent(dn_link, download_dir=dn_path) if (to): log.debug("downloading : %s %s" % (to.id, to.name)) self.sendMessage(chat_id, '%s 다운로딩' % menu['title']) else: self.sendMessage(chat_id, '다운로드 실패') elif keyword[0] == '확인': # 토렌트 진행상황 확인 tc = Transmission() torrents = tc.get_torrents() if len(torrents) == 0: self.sendMessage(chat_id, "다운로드중인 파일은 없습니다.") return str = '' for torrent in torrents: str = str + "%s - %s peers %.2f %%\n" % ( torrent.name[:20], torrent.peersConnected, torrent.percentDone * 100) self.sendMessage(chat_id, str) elif keyword[0] == "갱신": pms = Plexmediaserver() arr = [1, 2] for num in arr: pms.refresh(num) else: str = {"/검색 [검색어] - 검색어를 토렌트사이트에서 검색합니다.", "/확인 - 토렌트 다운로드 진행상황을 확인합니다.", "/갱신 - Plex Media Server 라이브러리를 갱신합니다."} str = "\n".join(str) self.sendMessage(chat_id, str) # inline query - need `/setinline` elif flavor == 'inline_query': query_id, from_id, query_string = telepot.glance(msg, flavor=flavor) print('Inline Query:', query_id, from_id, query_string) def compute_answer(): # Compose your own answers articles = [{'type': 'article', 'id': 'abc', 'title': query_string, 'message_text': query_string}] return articles self._answerer.answer(msg, compute_answer) # chosen inline result - need `/setinlinefeedback` elif flavor == 'chosen_inline_result': result_id, from_id, query_string = telepot.glance(msg, flavor=flavor) print('Chosen Inline Result:', result_id, from_id, query_string)
class Demultiplexer(): def __init__(self, muxType, signal0, signal1 , carrierFrequency = GlobalSettings.carrierFrequency ,muxCarrierFrequency = GlobalSettings.multiplexCarrierFrequency, messageFrequency = GlobalSettings.messageFrequency, carrierAmplitude = GlobalSettings.multiplexCarrierAmplitude, sampleTime = GlobalSettings.sampleTime): self.fmux = muxCarrierFrequency self.fc = carrierFrequency self.fm = messageFrequency self.ac = carrierAmplitude self.ts = sampleTime self.type = muxType self.time = np.arange(0,1/self.fm,self.ts) self.roll = int((1.0/self.fc)/4.0*(1.0/self.ts)) self.quaterPoint = int(len(self.time)/4.0) #used to ensure correct normaliZaTION self.halfPoint = int(len(self.time)/2.0) #below we handle transmitters self.fakeTransmission = Transmission(1) self.cleanPilot, self.cosWave = self.GeneratePilot(False) self.s0, self.h0 = self.SignalDetector(signal0) self.fmux = 3* muxCarrierFrequency if(self.type == MultiplexerType.TDM): self.cleanPilot, self.cosWave = self.GeneratePilot(False,2) self.s1, self.h1 = self.SignalDetector(signal1) def BandPassFilter(self, lowerLimit, upperLimit, signal,order = 2): nyq = 0.5 * (1/self.ts) low = lowerLimit/nyq high = upperLimit/nyq b, a = butter(order, [low, high], btype='band', analog=False) #b = num a = denom y = filtfilt(b,a,signal, method = 'gust') return y def DemodulateDSB_SC(self, signal, frequency, shift, angle): freq = 2 * np.pi * (self.fmux + shift) * self.time demodCarrier = np.array(np.cos(freq -angle)) preDemod = np.multiply(signal,demodCarrier) lpfSignal = self.LowPassFilter(frequency, preDemod) #LPF ampFixSignal = np.array([((x*2)) for x in lpfSignal]) return ampFixSignal def DemodulateDSB_FC(self, signal, frequency ,pilot = True): signal[signal < 0] = 0 #Rectify lpfSignal = self.LowPassFilter(frequency, signal) #LPF dc = np.mean(lpfSignal[self.quaterPoint:len(self.time)-self.quaterPoint]) noDCSignal = np.array([x-dc for x in lpfSignal]) tmpSignal = noDCSignal[self.quaterPoint:len(self.time)-self.quaterPoint] tmpSignal[tmpSignal < 0] negValuesSignal = -1*tmpSignal maxPos = float(np.amax(noDCSignal)) maxNeg = float(np.amax(negValuesSignal)) factor = maxPos/maxNeg for (i, item) in enumerate(noDCSignal): if(item < 0): noDCSignal[i] = noDCSignal[i]*factor # #offset remains of e-17 to e-18 demodulatedSignalMax = np.amax(noDCSignal[self.quaterPoint:len(self.time)-self.quaterPoint]) correctedSignal = np.array([x*(1/demodulatedSignalMax) for x in noDCSignal]) return correctedSignal, noDCSignal def LowPassFilter(self, frequency, signal,order = 4): nyq = 0.5 * (1/self.ts) Wc = frequency/nyq b, a = butter(order, Wc, btype='low') #b = num a = denom y = filtfilt(b, a, signal,method = 'gust') trimVal = int(4.0*self.roll) trimTop = y[0:y.size-trimVal] trimBot = trimTop[trimVal:trimTop.size] return trimBot def GeneratePilot(self, DSB_FC= True, factor = 1): outputSignal = np.array(np.cos(2 * np.pi * factor * self.fc * self.time)) carrier = np.array(np.cos(2 * np.pi * (self.fmux) * self.time)) modulatedSignal = np.multiply(outputSignal,carrier) y = self.DemodulateDSB_SC(modulatedSignal, 3*self.fc, 0,0) return y, outputSignal def ChannelEstimator(self, pilot, signal): maxPilot = float(np.amax(pilot[self.quaterPoint:len(self.time)-self.quaterPoint])) maxSignal = float(np.amax(signal[self.quaterPoint:len(self.time)-self.quaterPoint])) magnitude = np.divide(maxSignal,maxPilot) #6,02% error here to magH factor = np.divide(maxPilot,maxSignal) ampFixSignal = np.array([x*factor for x in signal]) period = float(1.0/self.fc) #in this case for my pilot length = period/(self.ts) halfPeriod = int(float(length/2.0)) shift = np.argmax(ampFixSignal[self.halfPoint - 0* halfPeriod:self.halfPoint +2* halfPeriod]) angle = 2*np.pi* shift*(1/length) return magnitude, angle def SignalDetector(self, signal): if(self.type == MultiplexerType.FDM): pilotSignal = self.BandPassFilter(self.fmux - 4*self.fc,self.fmux + 4*self.fc,signal) magnitude = self.EstimatePilotMaxWithFFT(pilotSignal) pilot1= self.DemodulateDSB_SC(pilotSignal, 3*self.fc,0,0) goodMag, badAngle = self.ChannelEstimator(self.cleanPilot ,pilot1) pilot2= self.DemodulateDSB_SC(pilotSignal, 3*self.fc,0,badAngle) badMag, goodAngle = self.ChannelEstimator(self.cleanPilot ,pilot2) channel = (magnitude * np.cos(goodAngle)) + (1j * magnitude* np.sin(goodAngle)) correct = [False] * 4 channels = [0] * 4 channels[0] = (magnitude * np.cos(goodAngle)) + (1j * magnitude* np.sin(goodAngle)) self.fakeTransmission.OverideWave(self.cosWave) self.fakeTransmission.MultiplySymbol(channels[0]) correct[0] = self.QuadrantSelect(pilot2[4750:5250],self.fakeTransmission.wave[4750:5250]) channels[1] = complex(-1*channels[0].real,-1*channels[0].imag) self.fakeTransmission.OverideWave(self.cosWave) self.fakeTransmission.MultiplySymbol(channels[1]) correct[1] = self.QuadrantSelect(pilot2[4750:5250],self.fakeTransmission.wave[4750:5250]) channels[2] = complex(-1*channels[0].real,channels[0].imag) self.fakeTransmission.OverideWave(self.cosWave) self.fakeTransmission.MultiplySymbol(channels[2]) correct[2] = self.QuadrantSelect(pilot2[4750:5250],self.fakeTransmission.wave[4750:5250]) channels[3] = complex(channels[0].real,-1*channels[0].imag) self.fakeTransmission.OverideWave(self.cosWave) self.fakeTransmission.MultiplySymbol(channels[3]) correct[3] = self.QuadrantSelect(pilot2[4750:5250],self.fakeTransmission.wave[4750:5250]) n = 0 for truth in correct: if(truth==True): channel = channels[n] break n+=1 self.fakeTransmission.OverideWave(self.cosWave) self.fakeTransmission.MultiplySymbol(channel) maxP = np.argmax(pilot1[:1000]) maxT = np.argmax(self.fakeTransmission.wave[:1000]) if(abs(maxP-maxT) < 250 or abs(maxP-maxT) > 500): channel = complex(-1*channel.real,-1*channel.imag) self.fakeTransmission.OverideWave(self.cosWave) self.fakeTransmission.MultiplySymbol(channel) dataSignal = self.BandPassFilter(self.fmux + 4*self.fc,self.fmux + 12 * self.fc,signal) data = self.DemodulateDSB_SC(dataSignal, 3 * self.fc,8*self.fc,goodAngle) return data, channel if(self.type == MultiplexerType.TDM): pilotSignal = signal[len(self.time):int(2*len(self.time))] dataSignal = signal[0:len(self.time)] magnitude, angle = self.ChannelEstimator(self.cleanPilot ,pilotSignal) channel = (magnitude * np.cos(angle)) + (1j * magnitude* np.sin(angle)) return dataSignal, channel def FFT(self, signal): n = len(signal) # length of the signal k = np.arange(n) T = n/(1/self.ts) frq = k/T # two sides frequency range frq = frq[range(n/40)] # one side frequency range Y = np.fft.fft(signal)/n # fft computing and normalization Y = Y[range(n/40)] fig, ax = plot.subplots(2, 1) ax[1].plot(frq,abs(Y),'r') # plotting the spectrum ax[1].set_xlabel('Freq (Hz)') ax[1].set_ylabel('|Y(freq)|') def PrintFilter(self,b,a, nyq): plot.figure() plot.clf() w, h = freqs(b, a, worN=2000) plot.plot((nyq/np.pi)*w, abs(h)) #plt.xscale('linear') plot.title('Butterworth filter frequency response') plot.xlabel('Frequency [Hz]') plot.ylabel('Amplitude') plot.margins(0, 0.1) plot.grid(which='both', axis='both') def EstimatePilotMaxWithFFT(self, modulatedPilot, pilotMagnitude = 1): fftPilot = np.fft.fft(modulatedPilot)/len(modulatedPilot) # fft computing and normalization return (max(abs(fftPilot))*4)/pilotMagnitude def QuadrantSelect(self, pilot, tansmission): maxP = np.amax(pilot) maxT = np.amax(tansmission) sumP = np.sum(pilot) sumT = np.sum(tansmission) diffP = sumP-maxP diffT = sumT-maxT difference = abs(diffP-diffT) if(difference < 50): return True else: return False
parser.add_option('-l', '--limit' , metavar='LIMIT', dest='limit', type="int", help='Limit the number of torrents diplayed. 0 means no limit. [default is 0]', default=0) parser.add_option('-c', '--colorfile' , metavar='FILE', dest='colorfile', help='File containing color codes for different states of torrents, overriding the template (\"Stopped\", \"Downloading\", \"Up & Down\", \"Idle\", \"Seeding\"). If not given, the colors in the template are used.') parser.add_option('-U', '--username' , metavar='USERNAME', dest='username', help='Username for authorization') parser.add_option('-P', '--password' , metavar='PASSWORD', dest='password', help='Password for authorizaion') parser.add_option('-S', '--sort', metavar='FIELD', type='string', dest='sortfield', help='Sort the list of torrents by the value of the specified field. [default: none]') parser.add_option('-R', '--reverse', dest='reverse', default=False, action='store_true', help='If this option is used, the list of torrents is reversed (even if no sorting criterion is given).') #~ parser.add_option('short', 'long' , metavar='', dest='', help='') (opts, args) = parser.parse_args() if not opts.s_template_file and not opts.t_template_file: print "No templates specified at all. Please give a torrent and/or summary template." parser.print_help() sys.exit(1) transmission = Transmission(options=opts) torrents, summary = transmission.get_simple_torrent_data(active_only=opts.activeonly) color_code = ColorCode(color_filename=opts.colorfile) # Summary if opts.s_template_file: s_template = Template(opts.s_template_file) s_template.set_data(summary) s_info = s_template.get_string() print s_info # Torrents if opts.t_template_file:
def CreateTransmission(self, symbol): transmission = Transmission(symbol) return transmission