def setup(hass, config):
    """Set up the Goalfeed component."""
    conf = config[DOMAIN]
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD)

    def goal_handler(data):
        """Handle goal events."""
        goal = json.loads(json.loads(data))

        hass.bus.fire("goal", event_data=goal)

    def connect_handler(data):
        """Handle connection."""
        post_data = {
            "username": username,
            "password": password,
            "connection_info": data,
        }
        resp = requests.post(GOALFEED_AUTH_ENDPOINT, post_data,
                             timeout=30).json()

        channel = pusher.subscribe("private-goals", resp["auth"])
        channel.bind("goal", goal_handler)

    pusher = pysher.Pusher(GOALFEED_APP_ID,
                           secure=False,
                           port=8080,
                           custom_host=GOALFEED_HOST)

    pusher.connection.bind("pusher:connection_established", connect_handler)
    pusher.connect()

    return True
Beispiel #2
0
 def __init__(self, api_key):
     self.__api_key = api_key
     self.__job_channel_auth = None
     self.__job_channel_name = 'presence-jobs.{}'
     self.__job_channel = None
     self.__connected = False
     self.__wshost = 'socket.elytica.com'
     self.__pusher = pysher.Pusher(custom_host=self.__wshost, key='elytica_service',\
       secret=self.__api_key, auto_sub=True, ping_interval=30)
     self.__headers = {"Authorization": "Bearer " + api_key}
     self.__scheme = "https://"
     self.__basename = "service.elytica.com/api"
     self.__api_user = "******"
     self.__channel_auth = "service.elytica.com/broadcasting/auth"
     self.__api_projects = "/projects"
     self.__api_applications = "/applications"
     self.__api_projects_createjob = "/projects/{project}/createjob"
     self.__api_projects_getjobs = "/projects/{project}/getjobs"
     self.__api_projects_files = "/projects/{project}/files"
     self.__api_update = "/update/{job}"
     self.__api_projects_upload = "/projects/{project}/upload"
     self.__api_projects_assignfile = "/projects/{project}/assignfile/{job}"
     self.__api_projects_outputfiles = "/projects/{project}/outputfiles/{job}"
     self.__api_projects_download = "/projects/{project}/download/{file}"
     self.__projects = []
     self.__jobs = []
     self.__applications = []
     self.__inputfiles = []
     self.__outputfiles = []
     self.__selected_project = None
     self.__selected_application = None
     self.__selected_job = None
Beispiel #3
0
 def initPusher(self):
     self.pusher = Pusher(app_id=os.getenv('PUSHER_APP_ID', None), key=os.getenv('PUSHER_APP_KEY', None), secret=os.getenv('PUSHER_APP_SECRET', None), cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     # инициализирую новый Pysher клиент передавая APP_KEY
     self.clientPusher = pysher.Pusher(os.getenv('PUSHER_APP_KEY', None), os.getenv('PUSHER_APP_CLUSTER', None))
     # Связываюсь с соеденением событием и передаю connectHandler в качестве обратного вызова
     self.clientPusher.connection.bind('pusher:connection_established', self.connectHandler)
     self.clientPusher.connect()
class Trades:
    pusher = pysher.Pusher("de504dc5763aeef9ff52", daemon=False)

    def __init__(self):
        self.pusher.connection.bind('pusher:connection_established',
                                    self.listen)
        self.pusher.connect()

    def listen(self, data):
        channel = self.pusher.subscribe('live_trades_ltcusd')
        channel.bind('trade', self.get)

    def get(self, *args):
        jsonify = args[0].split("'")[0]
        data = json.loads(jsonify)
        self.push_to_DB(data)

    def push_to_DB(self, data):
        unixtimestamp = int(data["timestamp"])
        price = data['price_str']
        amount = data['amount']
        sel_order = data['type']
        buy_id = data['buy_order_id']
        sell_id = data['sell_order_id']

        cur.execute(
            "INSERT INTO TRADES (UNIXTIMESTAMP,PRICE,AMOUNT,SELL_ORDER,BUY_ID,SELL_ID) \
              VALUES (%s, %s, %s, %s, %s, %s)",
            (unixtimestamp, price, amount, sel_order, buy_id, sell_id))

        conn.commit()
 def __init__(self, *args, **kwargs):
     self.key = "de504dc5763aeef9ff52"
     self.channels = {}
     self.messages = {
         "live_trades": ["trade"],
         "order_book": ["data"],
         "diff_order_book": ["data"],
         "live_orders": ["order_created", "order_changed", "order_deleted"]
     }
     for channel in self.messages.keys():
         self.channels[channel] = []
         for pair in ["btceur", "eurusd"]:
             self.channels[channel + "_" + pair] = []
     self.orderbook = {
         "btc": {
             "eur": None,
             "usd": None
         },
         "eur": {
             "usd": None
         }
     }
     self.lastprice = self.orderbook
     self.openorders = self.orderbook
     for base in self.openorders.keys():
         for quote in self.openorders[base].keys():
             self.openorders[base][quote] = {"price": {}, "id": {}}
     self.pusher = pysher.Pusher(self.key)
     self.pusher.connect()
 def __init__(self):
     if os.path.exists("./data.json"):
         with open('data.json', 'r') as openfile:
             json_object = json.load(openfile)
             pusherID = json_object["pusherAppID"]
             pusherKey = json_object["pusherKey"]
             pusherSecret = json_object["pusherSecret"]
             pusherCluster = json_object["pusherCluster"]
     #start a logging handler so we can see the raw communication data
     root = logging.getLogger()
     root.setLevel(logging.INFO)
     ch = logging.StreamHandler(sys.stdout)
     root.addHandler(ch)
     #end logging
     self.pusher_server = pysher.Pusher(key=pusherKey,
                                        cluster=pusherCluster)
     self.pusher_server.connection.bind('pusher:connection_established',
                                        self.__connect_handler)
     self.pusher_server.connect()
     try:
         self.pusher_client = pusher.Pusher(app_id=pusherID,
                                            key=pusherKey,
                                            secret=pusherSecret,
                                            cluster=pusherCluster)
     except ValueError as err:
         print(
             "Pusher Connection Failed. Check Your Credentials!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
         )
     while True:
         # Do other things in the meantime here...
         time.sleep(1)
Beispiel #7
0
 def __init__(self, pair_name):
     self.pair_name = pair_name
     self.pusher = pysher.Pusher(self.WEX_PUSHER_KEY,
                                 custom_host='ws-{}.pusher.com'.format(
                                     self.WEX_PUSHER_CLUSTER),
                                 log_level=logging.WARNING)
     self._logger = logging.getLogger(__name__)
Beispiel #8
0
def main():

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.WARNING)
    # output = logging.StreamHandler(sys.stdout)
    output = logging.FileHandler('galileu.log')
    formatter = logging.Formatter('%(message)s\n-')
    output.setFormatter(formatter)
    logger.addHandler(output)

    def func(last_data):
        with open('lattest.csv', 'a', newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            data_dict = json.loads(last_data)
            spamwriter.writerow([data_dict['timestamp'],data_dict['price'],data_dict['amount']])
    
    def connect_handler(data):
        channel = pusher.subscribe('live_trades')
        channel.bind('trade', func)

    while True:
        appkey = 'de504dc5763aeef9ff52'
        logger.warning('\nConnecting at {}.'.format(datetime.datetime.utcfromtimestamp(time.time())))
        pusher = pysher.Pusher(appkey)
        pusher.connection.bind('pusher:connection_established', connect_handler)
        pusher.connect()
        while True:
            time.time()
Beispiel #9
0
    def __init__(self, appKey, cluster, secret, callback, logging=False):
        if logging:
            root = logging.getLogger()
            root.setLevel(logging.INFO)
            ch = logging.StreamHandler(sys.stdout)
            root.addHandler(ch)

        self.pusher = pysher.Pusher(appKey, cluster=cluster, secret=secret)
        self.callback = callback
Beispiel #10
0
    def __init__(
            self,
            api_token: str,
            email=None,
            password=None,
            existing_session=None,
            analysis_path=None,
            twofactor_prompt: Callable = None,
            subscribe: bool = False,
            config: ConfigParser = ConfigParser(),
    ):
        """ Construct a connection with the specified API key """

        # Save configuration info
        self.config = config

        # Save the API key
        self.api_token: str = api_token

        # Save authentication information, if we were given any
        self.email: str = email
        self.password: str = password

        # API result cache
        self._cache: Dict[str, Any] = {}
        self.cache_timeout: float = 60

        # Callback to get two factor prompt
        self.twofactor_prompt = twofactor_prompt

        # Ongoing session for standard authentication
        self.session = requests.Session()
        self.session.cookies.update({"hackthebox_session": existing_session})

        # List of tracked machines
        self._machines: Dict[int, Machine] = {}

        # Path where machine analysis is kept
        self.analysis_path = analysis_path

        # Subscribe the asynchronous messages via Pusher (WebSockets)
        if subscribe:
            # If you don't subscribe, you don't need pysher
            import pysher

            self.subcribed: bool = True
            self.subscriber_lock: threading.Lock = threading.RLock()
            self.subscribers: Dict[str, Callable] = {}
            self.pusher = pysher.Pusher("97608bf7532e6f0fe898", cluster="eu")

            def _on_connect(data):
                channel = self.pusher.subscribe("notifications-channel")
                channel.bind("display-notification", self._on_notification)

            self.pusher.connection.bind("pusher:connection_established",
                                        _on_connect)
            self.pusher.connect()
Beispiel #11
0
 def initiate_pusher(self):
     self.pusher = Pusher(app_id=os.getenv('PUSHER_APP_ID', None),
                          key=os.getenv('PUSHER_APP_KEY', None),
                          secret=os.getenv('PUSHER_APP_SECRET', None),
                          cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     self.client_pusher = pysher.Pusher(key=os.getenv('PUSHER_APP_KEY', None),
                                        cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     self.client_pusher.connection.bind('pusher:connection_established', self.connection_manager)
     self.client_pusher.connect()
Beispiel #12
0
 def initPusher(self):
     self.pusher = Pusher(app_id="PUSHER_APP_ID",
                          key="PUSHER_KEY",
                          secret="PUSHER_SECRET",
                          cluster="PUSHER_CLUSTER")
     self.clientPusher = pysher.Pusher("PUSHER_KEY", "PUSHER_CLUSTER")
     self.clientPusher.connection.bind('pusher:connection_established',
                                       self.connectHandler)
     self.clientPusher.connect()
Beispiel #13
0
 def start_engine(self):
     self.pusher = Pusher(app_id=self.PUSHER_APP_ID,
                          key=self.PUSHER_APP_KEY,
                          secret=self.PUSHER_APP_SECRET,
                          cluster=self.PUSHER_APP_CLUSTER)
     self.clientPusher = pysher.Pusher(self.PUSHER_APP_KEY,
                                       self.PUSHER_APP_CLUSTER)
     self.clientPusher.connection.bind('pusher:connection_established',
                                       self.connectHandler)
     self.clientPusher.connect()
 def initPusher(self):
     self.pusher = Pusher(app_id=os.getenv("PUSHER_APP_ID"),
                          key=os.getenv("PUSHER_APP_KEY"),
                          secret=os.getenv("PUSHER_APP_SECRET"),
                          cluster=os.getenv("PUSHER_APP_CLUSTER"))
     self.clientPusher = pysher.Pusher(os.getenv("PUSHER_APP_KEY"),
                                       os.getenv("PUSHER_APP_CLUSTER"))
     self.clientPusher.connection.bind("pusher:connection_established",
                                       self.connectHandler)
     self.clientPusher.connect()
Beispiel #15
0
def pusher_client():
    return pysher.Pusher(pInfo["key"],
                         cluster=pInfo["cluster"],
                         secure=False,
                         secret=pInfo["secret"],
                         user_data={"user_id": device_token},
                         daemon=True,
                         port=pInfo["port"],
                         reconnect_interval=10,
                         custom_host=pInfo["host"],
                         auto_sub=False)
Beispiel #16
0
def main():

    logger = logging.getLogger(__name__)
    logger.setLevel(logging.WARNING)
    # output = logging.StreamHandler(sys.stdout)
    output = logging.FileHandler('galileu.log')
    formatter = logging.Formatter('%(message)s\n-')
    output.setFormatter(formatter)
    logger.addHandler(output)
    ts_first_error = 0
    ts_last_error = 0

    def func(last_data):
        with open('lattest.csv', 'a', newline='') as csvfile:
            spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            data_dict = json.loads(last_data)
            spamwriter.writerow([data_dict['timestamp'],data_dict['price'],data_dict['amount']])

    def connect_handler(data):
        channel = pusher.subscribe('live_trades')
        channel.bind('trade', func)

    while True:
        try:
            appkey = 'de504dc5763aeef9ff52'
            logger.warning('\nConnecting at {}.'.format(datetime.datetime.utcfromtimestamp(time.time())))
            pusher = pysher.Pusher(appkey)
            pusher.connection.bind('pusher:connection_established', connect_handler)
            pusher.connect()
            if ts_first_error != 0:
                ts_connection = time.time()
                time_off = ts_connection - ts_first_error
                logger.warning('The connection was lost for about {} seconds.'.format(time_off))    

            while True:
                time.sleep(1)

        except:
            ts_error = time.time()
            logger.exception('Something wrong happened at {}, {}.'.format(ts_error,datetime.datetime.utcfromtimestamp(ts_error)))
            # There are two ways the code can go through this statement. 
            # First way. Time since last error occurred is too small. If that's the case, pusher may be down and
            # we need to chill a bit before trying to reconnect. 
            if (ts_error - ts_last_error)<1:
                time.sleep(1)
            # Second way. Time since last error occurred is not that small. If that's the case, pusher may not be
            # the reason for the error. Rather, the problem may be due to some error elsewhere, so we will not
            # overload the server by trying to reconnect straight away.
            else:
                ts_first_error = ts_error
                with open('lattest.csv', 'a', newline='') as csvfile:
                    spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
                    spamwriter.writerow(['BREAK at {}, {}.'.format(ts_first_error,datetime.datetime.utcfromtimestamp(time.time()))])
            ts_last_error = ts_error
 def __init__(self, currency, code):
     super().__init__(currency)
     self.code = code
     self.update_rate = 0.0001
     self.isWebsocket = True
     self.pusher = pysher.Pusher("de504dc5763aeef9ff52",
                                 log_level=logging.ERROR)
     self.pusher.connection.bind('pusher:connection_established',
                                 self.connect_handler)
     self.pusher.connect()
     self.depth_data = {'asks': [], 'bids': []}
     self.depth_update_time = time.time()
Beispiel #18
0
 def initPusher(self):
     print(os.getenv('PUSHER_APP_ID', None))
     self.pusher = Pusher(app_id=os.getenv('PUSHER_APP_ID', None),
                          key=os.getenv('PUSHER_APP_KEY', None),
                          secret=os.getenv('PUSHER_APP_SECRET', None),
                          cluster=os.getenv('PUSHER_APP_CLUSTER', None))
     self.clientPusher = pysher.Pusher(
         os.getenv('PUSHER_APP_KEY', None),
         os.getenv('PUSHER_APP_CLUSTER', None))
     self.clientPusher.connection.bind('pusher:connection_established',
                                       self.connectHandler)
     self.clientPusher.connect()
Beispiel #19
0
    def start(self):
        """
        Extension of Pusher.connect() method, which registers all callbacks with
        the relevant channels, before initializing a connection.
        :return:
        """
        super(BitstampWSS, self).start()

        self.pusher = pysher.Pusher(self.addr, **self.__pusher_options)
        self.pusher.connection.bind('pusher:connection_established',
                                    self._register_bindings)
        self.pusher.connect()
Beispiel #20
0
    def initPusher(self):
        self.pusher = Pusher(app_id=settings['PUSHER_APP_ID'],
                             key=settings['PUSHER_APP_KEY'],
                             secret=settings['PUSHER_APP_SECRET'],
                             cluster=settings['PUSHER_APP_CLUSTER'])
        self.clientPusher = pysher.Pusher(settings['PUSHER_APP_KEY'],
                                          settings['PUSHER_APP_CLUSTER'])
        self.clientPusher.connection.bind('pusher:connection_established',
                                          self.connectHandler)
        self.clientPusher.connect()

        # Connection established change screens
        self.change_screen("chat_screen")
Beispiel #21
0
 def __init__(self, apiID=None, apiKey=None, apiSecret=None):
     self.proxydict = None
     self.client_id = apiID
     self.api_key = apiKey
     self.api_secret = apiSecret
     self.logger = logging.getLogger('root')
     self.pusher = pysher.Pusher("de504dc5763aeef9ff52")
     self.pusher.connection.bind('pusher:connection_established',
                                 self.connect_handler)
     self.pusher.connect()
     self.depth_data = None
     self.update_time = time.time()
     #wait for data
     self._wait_for_data()
Beispiel #22
0
    def __init__(self):
        '''Initialize HackTheBux pusher.com API instance.'''

        warnings.filterwarnings('ignore', category=UserWarning, module='bs4')
        self.pusher = pysher.Pusher(PUSHER_APP_ID, PUSHER_APP_CLUSTER)
        self.pusher.connection.bind('pusher:connection_established', self.connect_handler)
        self.pusher.connect()
        self.channels = {
            'notifications-channel': None,
            'shoutbox-channel'     : None,
            'infobox-channel'      : None,
            'VPN-us-free-1'        : None,
            'VPN-eu-free-1'        : None,
            'owns-channel'         : None,
        }
        self.events = []
def main():

	# Read room id
	roomId = -1

	try:
		f = open('./room_id.conf', 'r')
	except FileNotFoundError as e:
		roomId = 8126
	else:	
		roomId = int(f.readLine().strip())
		f.close()
	
	#Establish pusher connection
	pusher = pysher.Pusher(appkey)

	def connectionHandler(data):
		channel = pusher.subscribe(channelName)
		channel.bind(eventName, eventHandler)

	pusher.connection.bind('pusher:connection_established', connectionHandler)
	pusher.connect()

	# Listen for incoming messages from the board
	while True:


		# This should probably just be removed. It's trash
		if(not testMode):
			#Receives the data from the User
			data = raw_input("Enter the led command to be sent: ")
			data_list = list(data)
			for i in data_list:
				try:
					#Sends to the Slaves 
					writeNumber(ord(i))
					time.sleep(.1)
				except Exception as e:
					print(e)
		
			try:
				writeNumber(0x0A)
			except Exception as e:
					print(e)
class Orders(Trades):
    pusher = pysher.Pusher("de504dc5763aeef9ff52", daemon=False)

    def listen(self, data):
        channel = self.pusher.subscribe('live_orders_ltcusd')
        channel.bind('order_created', self.get)

    def push_to_DB(self, data):
        unixtimestamp = int(data["datetime"])
        price = data["price"]
        amount = data["amount"]
        sel_order = data["order_type"]
        order_id = data['id']

        cur.execute(
            "INSERT INTO ORDERS (ORDER_ID,UNIXTIMESTAMP,PRICE,AMOUNT,SELL_ORDER) \
              VALUES (%s, %s, %s, %s, %s)",
            (order_id, unixtimestamp, price, amount, sel_order))

        conn.commit()
Beispiel #25
0
    def __init__(self, streamer, config):
        self._config = config

        self._deviceName = self._config.getstr("DEFAULT", "devicename")
        self._zooId = self._config.getstr("DEFAULT", "zooid")
        self._deviceId = self._config.getstr("DEFAULT", "deviceid")
        self._pusherKey = self._config.getstr("PUSHER", "key")
        self._pusherSecret = self._config.getstr("PUSHER", "secret")
        self._pusherHost = self._config.getstr("PUSHER", "host")

        self._logfile = open("./true360/logs/pusher-log.txt", "w")
        self._log_handler(self._logfile)
        self._pusher = pysher.Pusher(key=self._pusherKey,
                                     secret=self._pusherSecret,
                                     custom_host=self._pusherHost,
                                     name="connection-thread")
        self._channel = None
        self._connection = None
        self._connected = False

        self._registration_channel = "private-%s" % self._deviceId
        self._device_channel = None

        self._streamer = streamer
Beispiel #26
0
index = 0.00000001


def channel_callback(data):
    global index
    print("Channel Callback: %s" % data)
    print("time %.2fs" % (index / 100.0))
    index = 0


def connect_handler(data):
    print('connceted!')
    channel = pusher.subscribe("live_orders_bchusd")
    print(channel)

    channel.bind('order_created', channel_callback)


if __name__ == '__main__':

    appkey = "de504dc5763aeef9ff52"

    pusher = pysher.Pusher(appkey)

    pusher.connection.bind('pusher:connection_established', connect_handler)
    pusher.connect()

    while True:
        index += 1
        sleep(0.01)
Beispiel #27
0
Datei: leds.py Projekt: PhanNN/pi
import RPi.GPIO as GPIO
import time
import sys
from random import randint
import time
import pysher
import logging

root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
root.addHandler(ch)
# from pubnub import Pubnub

pusher = pysher.Pusher('4068d8398911c1ddbbea', True, None, None, logging.INFO,
                       True, None, 10, 'ws-ap1.pusher.com')


def my_func(*args, **kwargs):
    print("processing Args:", args)
    print("processing Kwargs:", kwargs)


def _callback(m, channel):
    print(m)

    dc = m['brightness'] * 10

    if m['item'] == 'light-living':
        living.ChangeDutyCycle(dc)
Beispiel #28
0
import yaml
from functools import partial
from CWMetrics import CWMetrics

# Parse config
with open(sys.argv[1], 'r') as config_file:
    config = yaml.load(config_file)

metrics = CWMetrics(config['exchange']['name'])

kafka_producer = KafkaProducer(
    bootstrap_servers=config['kafka']['address'],
    value_serializer=lambda v: json.dumps(v).encode('utf-8'))

# Init pusher
pusher = pysher.Pusher(key="de504dc5763aeef9ff52")


def orderbookHandler(symbols, dataraw):
    data = json.loads(dataraw)
    symbolBase = symbols.upper()[0:3]
    symbolQuote = symbols.upper()[3:]
    payload = {}
    payload['exchange'] = "bitstamp"
    payload['symbol'] = symbolBase + "/" + symbolQuote
    payload['data'] = {}
    payload['data']['asks'] = list(
        map(lambda entry: [float(entry[0]), float(entry[1])], data['asks']))
    payload['data']['bids'] = list(
        map(lambda entry: [float(entry[0]), float(entry[1])], data['bids']))
    payload['timestamp'] = int(float(data['microtimestamp']) / 1e3)
Beispiel #29
0
# HOPIN_PUSHER_KEY to the pusher key
# The latter two can be extracted with a web inspector logged into hopin.

# Upon first run, the script will perform a google authentication process,
# with the tokens stored in a local file.

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

# Add a logging handler so we can see the raw communication data
import logging
root = logging.getLogger()
root.setLevel(logging.INFO)
ch = logging.StreamHandler(sys.stdout)
root.addHandler(ch)

pusher = pysher.Pusher(os.environ['HOPIN_PUSHER_KEY'], cluster='eu')
service = None
DOCUMENT_ID = os.environ['HOPIN_MONITOR_GOOGLE_DOC']
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']


def message_handler(message_data):
    global service
    message = json.loads(message_data)
    if message['body'].strip().startswith('Q:'):
        question = message['body'].strip()[2:].strip()
        print(f"Found question: {message['user']['name']} > {question}")

        values = [[
            datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
Beispiel #30
0
 def __init__(self, pair, **kwargs):
     self.pusher = pysher.Pusher(os.getenv("BITSTAMP_KEY"))
     self.exchange = "Bitstamp"
     self.pair = pair
     self.cnx = mysql.connector.connect(**kwargs)
     self.cursor = self.cnx.cursor()