def test_subscribe_pub_unsubscribe(self): ch = helper.gen_channel("test-subscribe-sub-pub-unsub") pubnub = PubNub(pnconf_sub_copy()) subscribe_listener = SubscribeListener() publish_operation = NonSubscribeListener() message = "hey" try: pubnub.add_listener(subscribe_listener) pubnub.subscribe().channels(ch).execute() subscribe_listener.wait_for_connect() pubnub.publish().channel(ch).message(message).pn_async( publish_operation.callback) if publish_operation. await () is False: self.fail("Publish operation timeout") publish_result = publish_operation.result assert isinstance(publish_result, PNPublishResult) assert publish_result.timetoken > 0 result = subscribe_listener.wait_for_message_on(ch) assert isinstance(result, PNMessageResult) assert result.channel == ch assert result.subscription is None assert result.timetoken > 0 assert result.message == message pubnub.unsubscribe().channels(ch).execute() subscribe_listener.wait_for_disconnect()
def test_subscribe_pub_unsubscribe(self): ch = helper.gen_channel("test-subscribe-sub-pub-unsub") pubnub = PubNub(pnconf_sub_copy()) subscribe_listener = SubscribeListener() publish_operation = NonSubscribeListener() message = "hey" try: pubnub.add_listener(subscribe_listener) pubnub.subscribe().channels(ch).execute() subscribe_listener.wait_for_connect() pubnub.publish().channel(ch).message(message).async(publish_operation.callback) if publish_operation.await() is False: self.fail("Publish operation timeout") publish_result = publish_operation.result assert isinstance(publish_result, PNPublishResult) assert publish_result.timetoken > 0 result = subscribe_listener.wait_for_message_on(ch) assert isinstance(result, PNMessageResult) assert result.channel == ch assert result.subscription is None assert result.timetoken > 0 assert result.message == message pubnub.unsubscribe().channels(ch).execute() subscribe_listener.wait_for_disconnect()
def writeDB(data, server, port): client = MongoClient(server, port) db = client.home1 # writing new data in db db.home1.insert_one(data) data.pop('_id', None) my_listener = SubscribeListener() pb.add_listener(my_listener) pb.subscribe().channels(channel).execute() my_listener.wait_for_connect() print 'connected' print data print type(data) while True: try: envelope = pb.publish().channel(channel).message(data).sync() print("publish timetoken: %d" % envelope.result.timetoken) except PubNubException as e: print 'exception...' pass # pb.publish().channel(channel).message(data) print 'published' result = my_listener.wait_for_message_on(channel) print 'result message' print result.message print 'waiting' t_sleep = random.randint(0, 6) print 'T_SLEEP', t_sleep time.sleep(t_sleep)
def get(self, request): pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-c7c2aa20-b56f-11e8-b6ef-c2e67adadb66" pnconfig.publish_key = "pub-c-fdd957cd-be31-427f-9e91-9c2bed852ba9" pnconfig.ssl = True pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels("test_channel").execute() my_listener.wait_for_connect() print('connected') pubnub.publish().channel('test_channel').message({ 'order': 16, 'owner': 1 }).sync() info = my_listener.wait_for_message_on('test_channel') print(info.message) print(pubnub.time()) print(pubnub.timestamp()) pubnub.unsubscribe().channels('test_channel').execute() my_listener.wait_for_disconnect() print('unsubscribe') envelope = pubnub.history().channel('test_channel').count(100).sync() print(envelope) return Response(dict(info.message))
def long_function(self, timeout,no): self.working = True timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout,)) timeout_work.setDaemon(True) timeout_work.start() import logging import pubnub from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener import time import os pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b' pnconfig.publish_key = '' pubnub = PubNub(pnconfig) n=0 my_listener = SubscribeListener() pubnub.subscribe().channels('Channel-82ldwdilv').execute() fp=os.path.join(os.environ['ProgramData'],"new.csv") with open(fp,'w+') as f: f.write("\t\t\t\t HEALTH REPORT\t\t\t\t") f.write('\n\n\n\n\n') import sys reload(sys) sys.setdefaultencoding('utf8') while True: print "Listening..."# endless/long work pubnub.add_listener(my_listener) result = my_listener.wait_for_message_on('Channel-82ldwdilv') data=result.message pubnub.remove_listener(my_listener) k=[] uno= zlib.decompress(base64.b64decode(data)) #print uno a=len(key) f='' for i in range (0,a): f+=uno[i] print f if (f==key): print "hai" with open(fp,'a+') as f: print "writing fin file" f.write(uno[a:]) f.write(",\n\n") if not self.working: # if state is working == true still working break self.set_state(True)
def ListenMessage(threadName, delay): my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels('awesomeChannel').execute() my_listener.wait_for_connect() print('connected') result = my_listener.wait_for_message_on('awesomeChannel') keep_goin = True print("starting to listen") while keep_goin: print(result.message) result = my_listener.wait_for_message_on('awesomeChannel') if result.message == "bye": keep_goin = False
def long_function(self, timeout, no): self.working = True timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout, )) timeout_work.setDaemon(True) timeout_work.start() import logging import pubnub from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener import time import os pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-b1b31f80-179a-11e8-95aa-1eb18890f15d' pnconfig.publish_key = '' pubnub = PubNub(pnconfig) n = 0 my_listener = SubscribeListener() pubnub.subscribe().channels('Channel-706fxzjkv').execute() fp = os.path.join(os.environ['ProgramData'], "new.csv") sample = '' for i in list_head: if i == None: sample = sample + "None" + "," else: sample = sample + i + "," with open(fp, 'w') as f: f.write(sample) f.write('\n') while True: print "Listening..." # endless/long work pubnub.add_listener(my_listener) result = my_listener.wait_for_message_on('Channel-706fxzjkv') pubnub.remove_listener(my_listener) result = result.message print result[0] sample = "" if (result[0] == KEY): with open(fp, 'a+') as f: for i in range(1, len(result)): if result[i] == None: sample = sample + "None" + "," else: sample = sample + result[i] + "," f.write(sample) f.write('\n') if not self.working: # if state is working == true still working break self.set_state(True)
def start_pub_nub_server(pn_instance, pn_instance_channel): print("Initializing Pub Nub Server") try: my_listener = SubscribeListener() pn_instance.add_listener(my_listener) pn_instance.subscribe().channels(pn_instance_channel).execute() my_listener.wait_for_connect() while True: result = my_listener.wait_for_message_on(pn_instance_channel) if result.message[1] == 'Server': # if it is for me print("Just received a message: ", end='') print(result.message) petitioner = result.message[0] if petitioner in lockers_owners_dic: if result.message[2] == 'locker_status': locker_status = lockers_lock_status_is_open[ lockers_owners_dic[petitioner]] response = ['Server', petitioner] if locker_status: response.append("open") else: response.append("closed") response.append(pn_instance.uuid) print("Responding: ", end='') print(response) pn_instance.publish().channel( pn_instance_channel).message(response).sync() elif result.message[2] == 'open': # Call function to open the locker print("Opening " + petitioner + "'s locker") thread_to_open_locker = Thread( target=set_locker_lock_state, args=( lockers_owners_dic[petitioner], True, pn_instance, pn_instance_channel, )) thread_to_open_locker.start() elif result.message[2] == 'close': # Call function to close the locker print("Closing " + petitioner + "'s locker") thread_to_open_locker = Thread( target=set_locker_lock_state, args=( lockers_owners_dic[petitioner], False, pn_instance, pn_instance_channel, )) thread_to_open_locker.start() finally: pn_instance.unsubscribe().channels(pn_instance_channel).execute() print("PubNub instance unsubscribed") return
def long_function(self, timeout, no): self.working = True timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout, )) timeout_work.setDaemon(True) timeout_work.start() import logging import pubnub from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener import time import os pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-ff76b412-17b2-11e8-bb84-266dd58d78d1' pnconfig.publish_key = '' pubnub = PubNub(pnconfig) n = 0 my_listener = SubscribeListener() pubnub.subscribe().channels('Channel-n3jbvzcv1').execute() fp = os.path.join(os.environ['ProgramData'], "new.csv") with open(fp, 'w') as f: for i in range(0, len(list_head)): ht = list_head[i] + ',' f.write(ht) f.write('\n') while True: print "Listening..." # endless/long work pubnub.add_listener(my_listener) result = my_listener.wait_for_message_on('Channel-n3jbvzcv1') n = result.message pubnub.remove_listener(my_listener) k = ast.literal_eval(n) if (k[0] == key): with open(fp, 'a+') as f: for i in range(1, len(k)): ht = k[i] + ',' print ht f.write(ht) f.write('\n') if not self.working: # if state is working == true still working break self.set_state(True)
def start_pub_nub_server(channel_name): pn_config = PNConfiguration() pn_config.subscribe_key = "INSERT API KEY" pn_config.publish_key = "INSERT API KEY" pn_config.uuid = '3242a702-6d6f-42d4-a548-356af0b95681' # instantiate a PubNub instance pub_nub = PubNub(pn_config) try: my_listener = SubscribeListener() pub_nub.add_listener(my_listener) pub_nub.subscribe().channels(channel_name).execute() my_listener.wait_for_connect() while True: result = my_listener.wait_for_message_on(channel_name) if result.message[1] == 'Server': # if it is for me print("Just received a message: ", end='') print(result.message) petitioner = result.message[0] if petitioner in lockers_owners_dic: if result.message[2] == 'locker_status': locker_status = lockers_lock_status_is_open[ lockers_owners_dic[petitioner]] response = ['Server', petitioner] if locker_status: response.append("open") else: response.append("closed") response.append(str(pn_config.uuid)) print("Responding: ", end='') print(response) pub_nub.publish().channel( pub_num_lockers_channel).message(response).sync() elif result.message[2] == 'open': # Call function to open the locker print("Opening " + petitioner + "'s locker") lockers_lock_status_is_open[ lockers_owners_dic[petitioner]] = True print(lockers_lock_status_is_open) elif result.message[2] == 'close': # Call function to close the locker print("Closing " + petitioner + "'s locker") lockers_lock_status_is_open[ lockers_owners_dic[petitioner]] = False print(lockers_lock_status_is_open) finally: pub_nub.unsubscribe().channels(channel_name).execute() pub_nub.stop() print("Unsubscribe") return
def get_data_from_pubnub(): my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels(my_channel).execute() my_listener.wait_for_connect() result = my_listener.wait_for_message_on('awesomeChannel') print(result.message) pubnub.unsubscribe().channels('awesomeChannel').execute() my_listener.wait_for_disconnect() print('unsubscribed')
def subscribe_pub(channel, msg): my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels(channel).execute() my_listener.wait_for_connect() print('connected') pubnub.publish().channel(channel).message(msg).sync() result = my_listener.wait_for_message_on(channel) print(result.message) # Unsubscribe pubnub.unsubscribe().channels(channel).execute() my_listener.wait_for_disconnect() print('unsubscribed')
def pubnub_call(self, channel): pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f" pnconfig.ssl = False pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels(channel).execute() my_listener.wait_for_connect() while True: bf_result = my_listener.wait_for_message_on(channel) bf_data = bf_result.message print bf_data # pubnub.unsubscribe().channels(channel).execute() # my_listener.wait_for_disconnect() return bf_data
def listen(self, functionmapper): ''' Implements a multicast pub/sub. It is the responsibility of the subscriber determine if it needs to perform any actions based on the message key functionmapper is a dict that maps payload keys to methods to call Methods will receive the payload as the first argument. e.g.: ``` functionmapper = { 'test': { 'module': 'config', 'method': 'foo' } } ``` ''' my_listener = SubscribeListener() self.pubnub.add_listener(my_listener) self.pubnub.subscribe().channels(self.channel).execute() # self.pubnub.add_channel_to_channel_group()\ # .channel_group("test")\ # .channels(channels)\ # .sync() my_listener.wait_for_connect() print('connected') while True: result = my_listener.wait_for_message_on(self.channel) print(result.message) event_key = result.message.get('key') task_definition = functionmapper.get(event_key, None) print ('key: {}'.format(event_key)) print ('task defn: {}'.format(task_definition)) if task_definition is not None: mod = importlib.import_module(task_definition.get('module')) method = task_definition.get('method') getattr(mod, method)(result.message)
class BitflyerPubnub(object): """docstring for BitflyerPubnub""" def __init__(self, channel): pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-52a9ab50-291b-11e5-baaa-0619f8945a4f" self.pubnub = PubNub(pnconfig) self.listener = SubscribeListener() self.channel = channel def __enter__(self): self.pubnub.add_listener(self.listener) self.pubnub.subscribe().channels([self.channel]).execute() self.listener.wait_for_connect() return self def listen(self, key): return self.listener.wait_for_message_on(self.channel).message[key] def __exit__(self, type, value, traceback): self.pubnub.unsubscribe().channels([self.channel]).execute() self.listener.wait_for_disconnect()
#!./venv/bin/python from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener import json channel_name = 'pubnub-twitter' pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-78806dd4-42a6-11e4-aed8-02ee2ddab7fe' pnconfig.ssl = False pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels(channel_name).execute() my_listener.wait_for_connect() print('connected') counter = 1 while(counter <= 1): result = json.dumps(my_listener.wait_for_message_on(channel_name).message) print(result) counter += 1 pubnub.unsubscribe() print('unsubscribed')
class BitflyerHelper: api_key = "" api_secret = "" pubnub_subscribe_key = "" error_count = 0 pubnub = None def __init__(self, api_key, api_secret, pubnub_subscribe_key=""): self.session = requests.session() self.api_key = api_key self.api_secret = api_secret self.pubnub_subscribe_key = pubnub_subscribe_key self.listener = SubscribeListener() self.session.mount('https://', HTTPAdapter(max_retries=5)) self.session.mount('http://', HTTPAdapter(max_retries=5)) # リアルタイム(pubnub)で情報を取得するためのセットアップ def setup_pubnub(self): pnconfig = PNConfiguration() pnconfig.subscribe_key = self.pubnub_subscribe_key pnconfig.ssl = False self.pubnub = PubNub(pnconfig) self.pubnub.add_listener(self.listener) # 板情報をリアルタイムで取得するためのセットアップ def subscribe_board_pubnub(self): self.pubnub.subscribe().channels( 'lightning_board_snapshot_FX_BTC_JPY').execute() self.listener.wait_for_connect() # 板情報の差分をリアルタイムで取得するためのセットアップ def subscribe_board_diff_pubnub(self): self.pubnub.subscribe().channels( 'lightning_board_FX_BTC_JPY').execute() self.listener.wait_for_connect() # 約定履歴をリアルタイムで取得するためのセットアップ def subscribe_executions_pubnub(self): self.pubnub.subscribe().channels( 'lightning_executions_FX_BTC_JPY').execute() self.listener.wait_for_connect() # 板情報をリアルタイムで取得 def get_board_pubnub(self): return self.listener.wait_for_message_on( "lightning_board_snapshot_FX_BTC_JPY").message # 板情報の差分をリアルタイムで取得 def get_board_diff_pubnub(self): return self.listener.wait_for_message_on( "lightning_board_FX_BTC_JPY").message # 約定履歴をリアルタイムで取得 def get_executions_pubnub(self): return self.listener.wait_for_message_on( 'lightning_executions_FX_BTC_JPY').message # 4本値の取得, period: n本足を秒数で表記, after: 指定したunixtime以降のデータを取得 """ 返り値 [UNIX timestamp, 始値, 高値, 安値, 終値, 出来高] """ def get_ohlc(self, period: int, after: int, before: int): endpoint = "https://api.cryptowat.ch/markets/bitflyer/btcfxjpy/ohlc?" \ "periods={0}&after={1}&before={2}".format(str(period), str(after), str(before)) response = self.get_request(endpoint) return response # マーケットの一覧を取得 def get_markets(self): response = self.get_request("/v1/getmarkets").json() return response # 板情報を取得 def get_board(self, product_code: ProductCode): params = {"product_code": product_code.value} response = self.get_request("/v1/getboard", params=params).json() return response # Tickerを取得 def get_ticker(self, product_code: ProductCode): params = {"product_code": product_code.value} response = self.get_request("/v1/getticker", params=params).json() return response # 約定履歴 def get_executions(self, product_code: ProductCode): params = {"product_code": product_code.value} response = self.get_request("/v1/getexecutions", params=params).json() return response # 板の状態 def get_board_state(self, product_code: ProductCode): params = {"product_code": product_code.value} response = self.get_request("/v1/getboardstate", params=params).json() return response # 取引所の状態 def get_health(self, product_code: ProductCode): params = {"product_code": product_code.value} response = self.get_request("/v1/gethealth", params=params).json() return response # チャットの取得 def get_chats(self, from_date: str = None): params = {} response = self.get_request("/v1/getchats", params=params).json() return response # APIキーの権限を取得 def get_permissions(self): method = "GET" endpoint = "/v1/me/getpermissions" body = "" headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.get_request(endpoint=endpoint, params=body, headers=headers).json() return response # 資産残高を取得 def get_balance(self): method = "GET" endpoint = "/v1/me/getbalance" body = "" headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.get_request(endpoint=endpoint, params=body, headers=headers).json() return response # 証拠金の状態を取得 def get_collateral(self): method = "GET" endpoint = "/v1/me/getcollateral" body = "" headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.get_request(endpoint=endpoint, params=body, headers=headers).json() return response # 通貨別の証拠金の数量を取得 def get_collateralaccounts(self): method = "GET" endpoint = "/v1/me/getcollateralaccounts" body = "" headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.get_request(endpoint=endpoint, params=body, headers=headers).json() return response # 新規注文を出す def send_child_order(self, child_order: ChildOrder): method = "POST" endpoint = "/v1/me/sendchildorder" body = child_order.to_body() print(body) body = json.dumps(body) headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.post_request(endpoint=endpoint, params=body, headers=headers).json() print(response) return response # 注文をキャンセルする def cancel_child_order(self, product_code: ProductCode, child_order_acceptance_id: str): method = "POST" endpoint = "/v1/me/cancelchildorder" body = { "product_code": product_code.value, "child_order_acceptance_id": child_order_acceptance_id } body = json.dumps(body) headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.post_request(endpoint=endpoint, params=body, headers=headers) return response # 新規の親注文を出す(特殊注文) def send_parent_order(self, parent_order): method = "POST" endpoint = "/v1/me/sendparentorder" body = parent_order.to_body() body = json.dumps(body) headers = self.create_private_header(method=method, endpoint=endpoint, body=body) response = self.post_request(endpoint=endpoint, params=body, headers=headers).json() print(response) return response # 注文の一覧を取得 def get_child_orders(self, product_code: ProductCode): method = "GET" endpoint = "/v1/me/getchildorders?product_code={}".format( product_code.value) headers = self.create_private_header(method=method, endpoint=endpoint, body="") response = self.get_request(endpoint=endpoint, headers=headers).json() return response # 建玉の一覧を取得 def get_positions(self, product_code: ProductCode): method = "GET" endpoint = "/v1/me/getpositions?product_code={}".format( product_code.value) headers = self.create_private_header(method=method, endpoint=endpoint, body="") response = self.get_request(endpoint=endpoint, headers=headers) if response.status_code == 200: return response.json() else: return None # Private API用のヘッダーを作成 def create_private_header(self, method, endpoint, body): if self.api_key and self.api_secret: access_timestamp = str(time.time()) api_secret = str.encode(self.api_secret) text = str.encode(access_timestamp + method + endpoint + body) access_sign = hmac.new(api_secret, text, hashlib.sha256).hexdigest() auth_header = { "ACCESS-KEY": self.api_key, "ACCESS-TIMESTAMP": access_timestamp, "ACCESS-SIGN": access_sign, "Content-Type": "application/json" } return auth_header else: sys.exit() # GETメソッド用 def get_request(self, endpoint, params=None, headers=None): if endpoint[0] == "/": url = BASE_URL.format(endpoint) else: url = endpoint while True: try: response = self.session.get(url, params=params, timeout=5, headers=headers) if not (response.status_code == 200 or response.status_code == 404): continue self.error_count = 0 return response except Exception as e: if self.error_count < error_limit: self.error_count += 1 continue else: sys.exit(e) # POSTメソッド用 def post_request(self, endpoint, params=None, headers=None): url = BASE_URL.format(endpoint) while True: try: response = self.session.post(url, data=params, timeout=5, headers=headers) if response.status_code != 200: continue self.error_count = 0 return response except Exception as e: if self.error_count < error_limit: self.error_count += 1 continue else: sys.exit(e)
def signal_handler(signal, frame): print('You pressed Ctrl+C!') pubnub.unsubscribe().channels('lapChannel').execute() my_listener.wait_for_disconnect() print('unsubscribed') sys.exit(0) pnconfig = PNConfiguration() pnconfig.publish_key = pubnub_keys.PUB_KEY pnconfig.subscribe_key = pubnub_keys.SUB_KEY pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels('lapChannel').execute() my_listener.wait_for_connect() print('connected') while (True): result = my_listener.wait_for_message_on('lapChannel') print(result.message) os.system("say '%s'" % result.message) #engine.say(result.message) #engine.runAndWait() time.sleep(0.05)
from pubnub.callbacks import SubscribeCallback from pubnub.enums import PNStatusCategory from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener pnconfig = PNConfiguration() pnconfig.subscribe_key = "sub-c-bab9dc6c-912f-11e9-9769-e24cdeae5ee1" pnconfig.publish_key = "pub-c-14a2c33b-ff74-4bb7-8139-ff46eed621cc" pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels('awesomeChannel').execute() my_listener.wait_for_connect() print('connected') result = my_listener.wait_for_message_on('awesomeChannel') while result != "": print(result.message) result = my_listener.wait_for_message_on('awesomeChannel') if result.message == "bye": break print("bye") print("Disconnected")
pubnub.unsubscribe().channels(my_channel).execute() my_listener.wait_for_disconnect() print('unsubscribed') if __name__ == "__main__": try: message = pubnub.subscribe().channels(my_channel).execute() my_listener.wait_for_connect() except Exception as e: print("ERROR: {}".format(e.message)) print("##### {} #####".format(my_channel)) while True: try: result = my_listener.wait_for_message_on(my_channel) data = result.message # print("{}".format(data).encode('utf-8')) dt = data["date_time"].encode("utf-8") t = float(data["temperature"].encode("utf-8")) p = round(float(data["pressure"].encode("utf-8")), 5) print("sensor sent-time {}: Temperature {} F, Pressure {} bar". format(dt, t, p)) except (IOError, TypeError) as e: # and since we got a type error # disconnect_channel() print(str(e)) except KeyboardInterrupt as e: # since we're exiting the program print(str(e)) disconnect_channel()
my_listener = SubscribeListener( ) # create listner_object to read the msg from the Broker/Server pubnub.add_listener( my_listener) # add listner_object to pubnub_object to subscribe it pubnub.subscribe().channels( channel).execute() # subscribe the channel (Runs in background) my_listener.wait_for_connect( ) # wait for the listner_obj to connect to the Broker.Channel print('connected') # print confirmation msg pubnub.publish().channel(channel).message( data).sync() # publish the data to the mentioned channel while True: # Infinite loop result = my_listener.wait_for_message_on( channel) # Read the new msg on the channel print(result.message) # print the new msg for command in result.message.values(): # Check for PM command. if command == pmx_str: pm_instance = pt_pms5003('/dev/ttyAMA0') pma, pmb, pmc = pm_instance.pt_pms5003_read() data['message'] = "PM 1.0=" + str(pma) + " PM 2.5=" + str( pmb) + " PM 10.0=" + str(pmc) pubnub.publish().channel(channel).message(data).sync() # Check for Temperature command. elif command == temp_str: data['message'] = "Temperature(Celcuis) = " + ds18b20_read() pubnub.publish().channel(channel).message(data).sync()
my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels('SECURE.BN9NDS0PFC').execute() my_listener.wait_for_connect() print("Test #18") msg = json.loads( json.dumps({ "enquiry": False, "module_name": "philapi", "requested_function": "light_switch", "parameters": [True, 1] })) accumulated_time = 0 for x in range(0, 1): start = time.time() pubnub.publish().channel('SECURE.BN9NDS0PFC').message(msg).sync() test1 = my_listener.wait_for_message_on('SECURE.BN9NDS0PFC') print("My request: " + str(msg)) # print("Request serialised: " + str(test1.message)) test2 = my_listener.wait_for_message_on('SECURE.BN9NDS0PFC') # print(x + 1) print("Gateway response: " + str(test2.message)) end = time.time() loop_average = end - start accumulated_time += loop_average # print("accumulated: " + str(accumulated_time))
LED_PIN = 4 #GPIO.setup(LED_PIN,GPIO.OUT) pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-f271816a-f3c4-11e6-88c3-0619f8945a4f' pnconfig.publish_key = 'pub-c-b4be713a-be4f-4872-b5c8-6232f76df1d4' pnconfig.ssl = False pb = PubNub(pnconfig) # pb = PubNub(publish_key='pub-c-b4be713a-be4f-4872-b5c8-6232f76df1d4', subscribe_key='sub-c-f271816a-f3c4-11e6-88c3-0619f8945a4f') channel = 'RMBX' print 'SUBSCRIBING...' my_listener = SubscribeListener() pb.add_listener(my_listener) pb.subscribe().channels('RMBX').execute() my_listener.wait_for_connect() result = my_listener.wait_for_message_on('RMBX') print(result.message) print 'PASSED...' # pb.subscribe(channels=channel, callback=_callback, error=_error)
#!./venv/bin/python from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener channel_name = 'hacker-news' pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-c00db4fc-a1e7-11e6-8bfd-0619f8945a4f' pnconfig.ssl = False pubnub = PubNub(pnconfig) my_listener = SubscribeListener() pubnub.add_listener(my_listener) pubnub.subscribe().channels(channel_name).execute() my_listener.wait_for_connect() print('connected') counter = 1 while(counter < 100): print(my_listener.wait_for_message_on(channel_name).message) counter += 1 pubnub.unsubscribe() print('unsubscribed')
new_dictColor = {0: '\033[32m', 1: '\033[33m', 2:'\033[31m'} pred = classifier.predict_classes(input_fn=lambda: input_predict(roadsTrainTest)) for i in pred: print(new_dict[i]) def getUserInput(text): data = [int(x) for x in text.split(",")] feature_cols1 = {k:tf.constant(data[i],shape = [1,1]) for i, k in enumerate(FEATURE_KEYS)} return feature_cols1 def sendMsg(txt): try: pubnub.publish().channel('Channel-5a7bgoadr').message({'trafficlight': txt }).sync() except: print('ERR::::X:S::X:S:SX:XS:X:') pubnub.subscribe().channels('Channel-5a7bgoadr').execute() print(':Waiting for device Data:') while(True): # Getting message from traffic light PUB_SUB channel result = my_listener.wait_for_message_on('Channel-5a7bgoadr') # print(result.message) if 'isActiveChannel' in result.message.keys() and result.message['isActiveChannel'] : pred1 = classifier.predict_classes(input_fn=lambda: getUserInput(result.message['cars'])) print('Day,Time,RoadNo,Cars') for j in pred1: print(new_dictColor[j] + new_dict[j]+ '\033[0m') sendMsg(new_dict[j])
p = subprocess.Popen(inputcommand, stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() return output def speakthistext(txt): # write out to wav file b = 'espeak -w temp.wav "%s" 2>>/dev/null' % txt # speak aloud c = 'espeak -ven+m1 -k1 -s150 --punct="<characters>" "%s" 2>>/dev/null' % txt #speak aloud execute_unix(b) execute_unix(c) print("Listening for name") result = str(my_listener.wait_for_message_on('awesomeChannel').message) names = ["connor-o'hara", "timothy hurley", "brian oten", "robbie ratcliff"] for i in names: if i in result: speakthistext("Hello, " + result + " how are you doing?") print("speaking") else: print("Not a recognized name") break # elif result == "Motion Detected":
def long_function(self, timeout, no): self.working = True timeout_work = threading.Thread(name="thread_name", target=self.work_time, args=(timeout, )) timeout_work.setDaemon(True) timeout_work.start() import logging import pubnub from pubnub.exceptions import PubNubException from pubnub.pnconfiguration import PNConfiguration from pubnub.pubnub import PubNub, SubscribeListener import time import os pnconfig = PNConfiguration() pnconfig.subscribe_key = 'sub-c-5dec13b4-1c6f-11e8-9e0d-86843e43dc8b' pnconfig.publish_key = '' pubnub = PubNub(pnconfig) n = 0 my_listener = SubscribeListener() pubnub.subscribe().channels('Channel-82ldwdilv').execute() fp = os.path.join(os.environ['ProgramData'], "new.csv") header = [] header.append('COMPUTER NAME') header.append('IP ADDRESS') for i in range(0, len(fnl_nf) - 3): header.append('APPLICATION ' + str(i + 1)) with open(fp, 'w+') as f: f.write( "\t\t\t\tFIND THE SPECIFIC APPLICATION REPORT FOR ALL DEVICES\t\t\t\t\n" ) for i in range(0, len(header)): f.write(str(header[i]) + ',') f.write('\n') import sys reload(sys) sys.setdefaultencoding('utf8') while True: print "Listening..." # endless/long work pubnub.add_listener(my_listener) result = my_listener.wait_for_message_on('Channel-82ldwdilv') n = result.message pubnub.remove_listener(my_listener) if (n[0] == key): with open(fp, 'a') as f: for i in range(1, len(n)): f.write(n[i] + ',') f.write('\n') if not self.working: # if state is working == true still working break self.set_state(True)