Esempio n. 1
0
 def get_answer(self, socket):
     answer_len = socket.myreceive(2)
     # answer_len = int.from_bytes(answer_len, self.endian)
     answer_len = struct.unpack('!H', answer_len)[0]
     Log.log(5, 'answer len is {}'.format(answer_len))
     answer = socket.myreceive(answer_len - 2)
     return answer
Esempio n. 2
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.log = Log()

    async def on_message_activity(self, turn_context: TurnContext):
        info = get_data()
        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        json_str = json.loads((str(result.entities[0])).replace("'", "\""))
        weather = weather_info.get_weather_info(json_str.get('entity'))
        self.log.write_log(sessionID='session1',
                           log_message="Bot Says: " + str(weather))
        await turn_context.send_activity(f"{weather}")
Esempio n. 3
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.luis_util = LuisUtil()
        self.log = Log()

    async def on_message_activity(self, turn_context: TurnContext):
        #weather_info=WeatherInformation()
        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        out = self.luis_util.luis_result_as_dict(result)
        print(out)
        weather = out['topScoringIntent']['intent']
        weather = d[weather]
        #json_str = json.loads((str("hello")).replace("'", "\""))
        #weather=weather_info.get_weather_info(json_str.get('entity'))
        #weather = "i dont have anaswer"
        self.log.write_log(sessionID='session1',
                           log_message="Bot Says: " + str(weather))
        await turn_context.send_activity(f"{weather}")
Esempio n. 4
0
def messages():
    if "application/jason" in request.headers["content-type"]:
        log = Log()
        request_body = request.jason

        # Activity is basically what user says and what we are sending as a response
        # they are termed as bot activity.
        # So the message exchange between the bot and the user is Activity
        user_says = Activity().deserialize(request_body)

        # Whatever user has said
        log.write_log(sessionID="session1",
                      log_message="user says: " + str(user_says))
        authorization_header = (request.headers["Authorization"]
                                if "Authorization" in request.headers else "")

        # Here the 2 new words async and await mean to make the code asyncronous
        # so that parts of our code doesn't wait for this piece of code to get executed!
        async def call_user_fun(turncontext):
            await luis_bot_dialog.turn_on(turncontext)

        task = loop.create_task(
            bot_adapter.process_activity(user_says, authorization_header,
                                         call_user_fun))
        loop.run_until_complete(task)
        return ""
    else:
        return Response(status=406)  # status for Not Acceptable
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.kb_host = self.configuration['KB_HOST']
        self.kb_endpoint = self.configuration['KB_ENDPOINT']
        self.kb_route = ''

        self.log = Log()
Esempio n. 6
0
 def mysend(self, msg):
     totalsent = 0
     while totalsent < len(msg):
         sent = self.sock.send(msg[totalsent:])
         if sent == 0:
             raise RuntimeError("socket connection broken")
         totalsent = totalsent + sent
     Log.log(5, 'sent msg: {}'.format(msg))
     return totalsent
Esempio n. 7
0
 def __init__(self):
     self.config_reader = ConfigReader()
     self.configuration = self.config_reader.read_config()
     self.luis_app_id=self.configuration['LUIS_APP_ID']
     self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
     self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
     self.luis_app = LuisApplication(self.luis_app_id,self.luis_endpoint_key,self.luis_endpoint)
     self.luis_options = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
     self.luis_recognizer = LuisRecognizer(application=self.luis_app,prediction_options=self.luis_options,include_api_results=True)
     self.log=Log()
Esempio n. 8
0
 def __init__(self, port, server_ip, client, timeout=3):
     self.__port = port
     Log.log(1, 'pi server thread, port is {}'.format(port))
     self.__server_ip = server_ip
     self.__client = client
     self.__timeout = timeout
     self.__socket = MySocket()
     self.__socket.bind(port)
     Log.log(0, 'binded on port {}'.format(port))
     self.__socket.listen(2)
     self.__stopped = threading.Event()
     self.__server_thread = threading.Thread(target=self.main, name='pi_server_t')
Esempio n. 9
0
    def __init__(self, conversation_state: ConversationState,
                 user_state: UserState):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.qna_knowledge_base_id = self.configuration["QNA_KNOWLEDGEBASE_ID"]
        self.qna_endpoint_key = self.configuration["QNA_ENDPOINT_KEY"]
        self.qna_host = self.configuration["QNA_ENDPOINT_HOST"]
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(knowledge_base_id=self.qna_knowledge_base_id,
                             endpoint_key=self.qna_endpoint_key,
                             host=self.qna_host))
        self.log = Log()
        self.IntentIdentified = False
        self.intent = 'none'
        self.stat = 'init'
        self.city = ""
        self.score = ""

        if conversation_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. conversation_state is required but None was given"
            )
        if user_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. user_state is required but None was given"
            )

        self.conversation_state = conversation_state
        self.user_state = user_state

        self.conversation_data_accessor = self.conversation_state.create_property(
            "ConversationData")
        self.user_profile_accessor = self.user_state.create_property(
            "UserProfile")
Esempio n. 10
0
    def main(self):
        while not self.__registered.isSet() and not self.__stopped.isSet():
            self.register_on_server()
            if self.__registered.isSet():
                break
            self.__stopped.wait(self.__timeout)

        self.__stopped.wait(self.__timeout)
        while not self.__stopped.is_set():
            for device in self.__devices:
                if type(device) is Thermometer:
                    temp = device.getTemp()
                    Log.log(4, 'temp is {}'.format(temp))
                    self.send_float_val(device.getKey(), temp)

            Log.log(1, 'waiting for stop')
            self.__stopped.wait(self.__timeout)
Esempio n. 11
0
def messages():
    if "application/json" in request.headers["content-type"]:
        log = Log()
        request_body = request.json
        user_says = Activity().deserialize(request_body)
        log.write_log(sessionID='session1',log_message="user says: "+str(user_says))
        authorization_header = (request.headers["Authorization"] if "Authorization" in request.headers else "")

        async def call_user_fun(turncontext):
            await luis_bot_dialog.on_turn(turncontext)

        task = loop.create_task(
            bot_adapter.process_activity(user_says, authorization_header, call_user_fun)
        )
        loop.run_until_complete(task)
        return ""
    else:
        return Response(status=406)  # status for Not Acceptable
Esempio n. 12
0
 def __createDevicesList(self, devs_file_path):
     with open(devs_file_path, 'r') as devices_file:
         lines = devices_file.readlines()
         dev_key = 0
         current_line = 0
         for line in lines:
             current_line += 1
             try:
                 self.__devices.append(initialize.addDevice(line, dev_key))
                 dev_key += 1
             except KeyError as error:
                 Log.log(
                     1, 'unresolved device code {} at line {}'.format(
                         error, current_line))
             except ValueError as error:
                 Log.log(
                     1, '{} at line {}: {}'.format(devs_file_path,
                                                   current_line, error))
class KnowledgeBase():
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.kb_host = self.configuration['KB_HOST']
        self.kb_endpoint = self.configuration['KB_ENDPOINT']
        self.kb_route = ''

        self.log = Log()

    def get_answer_from_kb(self, kb_details, question_from_user):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.kb_route = self.configuration[kb_details]

        question_to_kb = {}
        question_to_kb.update({'question': question_from_user})


        headers = {
            'Authorization': 'EndpointKey ' + self.kb_endpoint,
            'Content-Type': 'application/json'
        }

        try:
            self.log.write_log(sessionID='session1', log_message="question " + str(question_to_kb))
            self.conn = http.client.HTTPSConnection(self.kb_host, port=443)
            self.conn.request("POST", self.kb_route, str(question_to_kb), headers)
            self.response = self.conn.getresponse()
            self.answer = self.response.read()

            #this code is written to fetch the actual answer provided by the knowlegemaker

            answer_in_str = str(json.loads(self.answer))
            answer_in_dict = ast.literal_eval(answer_in_str)
            answer_return = answer_in_dict['answers'][0]['answer']

            self.log.write_log(sessionID='session1', log_message="question " + str(answer_return))
            return answer_return

        except:
            print("Unexpected error:", sys.exc_info()[0])
            print("Unexpected error:", sys.exc_info()[1])
Esempio n. 14
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id, self.luis_endpoint_key, self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True, include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(application=self.luis_app, prediction_options=self.luis_options,
                                              include_api_results=True)
        self.log = Log()

    async def on_message_activity(self, turn_context: TurnContext):
        knowledgebase = KnowledgeBase()

        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        top_intent = self.top_intent(luis_result)

        user_query = turn_context.activity.text

        kb_answer = knowledgebase.get_answer_from_kb(top_intent, user_query)
        self.log.write_log(sessionID='session1', log_message="Answer from KB is : " + str(kb_answer))
        await turn_context.send_activity(f"{kb_answer}")

    @staticmethod
    def top_intent(results: RecognizerResult, default_intent: str = "None", min_score: float = 0.0) -> str:
        if results is None:
            raise TypeError("LuisRecognizer.top_intent(): results cannot be None.")

        top_intent: str = None
        top_score: float = -1.0
        if results.intents:
            for intent_name, intent_score in results.intents.items():
                score = intent_score.score
                if score > top_score and score >= min_score:
                    top_intent = intent_name
                    top_score = score

        return top_intent or default_intent
Esempio n. 15
0
class LuisConnect(ActivityHandler):
    def __init__(self):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id=self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,self.luis_endpoint_key,self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(application=self.luis_app,prediction_options=self.luis_options,include_api_results=True)
        self.log=Log()
 

    async def on_message_activity(self,turn_context:TurnContext):
        weather_info=WeatherInformation()
        luis_result = await self.luis_recognizer.recognize(turn_context)
        result = luis_result.properties["luisResult"]
        #json_str = json.loads((str(result.entities[0])).replace("'", "\""))
        #weather=weather_info.get_weather_info(json_str.get('entity'))
        #self.log.write_log(sessionID='session1',log_message="Bot Says: "+str(weather))
        #await turn_context.send_activity(f"{weather}")

        check = json.loads((str(result.intents[0])).replace("'", "\""))
        if check.get('intent') == 'Welcome':
            await turn_context.send_activity(f"Hello, I can help you know the weather of any city")

            #print("Welcome")
        elif check.get('intent') == 'weather': 
            json_str = json.loads((str(result.entities[0])).replace("'", "\""))
            weather=weather_info.get_weather_info(json_str.get('entity'))
            self.log.write_log(sessionID='session1',log_message="Bot Says: "+str(weather))
            await turn_context.send_activity(f"{weather}")
        else:
            json_str = json.loads((str(result.entities[0])).replace("'", "\""))
            weather=weather_info.get_weather_data(json_str.get('entity'))
            self.log.write_log(sessionID='session1',log_message="Bot Says: "+str(weather))
            await turn_context.send_activity(f"{weather}")
Esempio n. 16
0
class LuisConnect(ActivityHandler):
    def __init__(self, conversation_state: ConversationState,
                 user_state: UserState):
        self.config_reader = ConfigReader()
        self.configuration = self.config_reader.read_config()
        self.luis_app_id = self.configuration['LUIS_APP_ID']
        self.luis_endpoint_key = self.configuration['LUIS_ENDPOINT_KEY']
        self.luis_endpoint = self.configuration['LUIS_ENDPOINT']
        self.luis_app = LuisApplication(self.luis_app_id,
                                        self.luis_endpoint_key,
                                        self.luis_endpoint)
        self.luis_options = LuisPredictionOptions(include_all_intents=True,
                                                  include_instance_data=True)
        self.luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_options,
            include_api_results=True)
        self.qna_knowledge_base_id = self.configuration["QNA_KNOWLEDGEBASE_ID"]
        self.qna_endpoint_key = self.configuration["QNA_ENDPOINT_KEY"]
        self.qna_host = self.configuration["QNA_ENDPOINT_HOST"]
        self.qna_maker = QnAMaker(
            QnAMakerEndpoint(knowledge_base_id=self.qna_knowledge_base_id,
                             endpoint_key=self.qna_endpoint_key,
                             host=self.qna_host))
        self.log = Log()
        self.IntentIdentified = False
        self.intent = 'none'
        self.stat = 'init'
        self.city = ""
        self.score = ""

        if conversation_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. conversation_state is required but None was given"
            )
        if user_state is None:
            raise TypeError(
                "[StateManagementBot]: Missing parameter. user_state is required but None was given"
            )

        self.conversation_state = conversation_state
        self.user_state = user_state

        self.conversation_data_accessor = self.conversation_state.create_property(
            "ConversationData")
        self.user_profile_accessor = self.user_state.create_property(
            "UserProfile")
        # session['IntentIdentified']=False
        # session['state']="init"
        # session['intent']='none'

    async def on_turn(self, turn_context: TurnContext):
        await super().on_turn(turn_context)

        await self.conversation_state.save_changes(turn_context)
        await self.user_state.save_changes(turn_context)

    def welcome(self):
        return "Hi How can I help you?"

    async def __send_intro_card(self, turn_context: TurnContext):
        card = HeroCard(
            title="Welcome to Bot Framework!",
            text="Welcome to Welcome Users bot sample! This Introduction card "
            "is a great way to introduce your Bot to the user and suggest "
            "some things to get them started. We use this opportunity to "
            "recommend a few next steps for learning more creating and deploying bots.",
            images=[CardImage(url="https://aka.ms/bf-welcome-card-image")],
            buttons=[
                CardAction(
                    type=ActionTypes.open_url,
                    title="Get an overview",
                    text="Get an overview",
                    display_text="Get an overview",
                    value=
                    "https://docs.microsoft.com/en-us/azure/bot-service/?view=azure-bot-service-4.0",
                ),
                CardAction(
                    type=ActionTypes.open_url,
                    title="Ask a question",
                    text="Ask a question",
                    display_text="Ask a question",
                    value=
                    "https://stackoverflow.com/questions/tagged/botframework",
                ),
                CardAction(
                    type=ActionTypes.open_url,
                    title="Learn how to deploy",
                    text="Learn how to deploy",
                    display_text="Learn how to deploy",
                    value=
                    "https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-howto-deploy-azure?view=azure-bot-service-4.0",
                ),
            ],
        )

        return await turn_context.send_activity(
            MessageFactory.attachment(CardFactory.hero_card(card)))

    def _process_input(self, text: str):
        color_text = "is the best color, I agree."

        if text == "red":
            return f"Red {color_text}"

        if text == "yellow":
            return f"Yellow {color_text}"

        if text == "blue":
            return f"Blue {color_text}"

        return "Please select a color from the suggested action choices"

    async def _send_suggested_actions(self, turn_context: TurnContext):
        """
            Creates and sends an activity with suggested actions to the user. When the user
            clicks one of the buttons the text value from the "CardAction" will be displayed
            in the channel just as if the user entered the text. There are multiple
            "ActionTypes" that may be used for different situations.
            """

        reply = MessageFactory.text("Confirm the option")

        reply.suggested_actions = SuggestedActions(actions=[
            CardAction(title="YES", type=ActionTypes.im_back, value="YES"),
            CardAction(title="NO", type=ActionTypes.im_back, value="NO"),
        ])

        return await turn_context.send_activity(reply)

    async def on_message_activity(self, turn_context: TurnContext):
        # weather_info=WeatherInformation()
        # print("new session :",session)
        # Get the state properties from the turn context.
        user_profile = await self.user_profile_accessor.get(
            turn_context, UserProfile)
        conversation_data = await self.conversation_data_accessor.get(
            turn_context, ConversationData)
        conversation_data.channel_id = turn_context.activity.channel_id
        print(conversation_data.channel_id)
        if user_profile.name is None:
            # First time around this is undefined, so we will prompt user for name.
            if conversation_data.prompted_for_user_name:
                # Set the name to what the user provided.
                user_profile.name = turn_context.activity.text

                # Acknowledge that we got their name.
                await turn_context.send_activity(
                    f"Thanks { user_profile.name }. To see conversation data, type anything in the {conversation_data.channel_id}"
                )

                # Reset the flag to allow the bot to go though the cycle again.
                conversation_data.prompted_for_user_name = False
            else:
                # Prompt the user for their name.
                await turn_context.send_activity("What is your name?")

                # Set the flag to true, so we don't prompt in the next turn.
                conversation_data.prompted_for_user_name = True
        else:
            print("1", self.IntentIdentified)
            print("turn_context", turn_context.activity.text)
            if self.IntentIdentified == False:
                luis_result = await self.luis_recognizer.recognize(turn_context
                                                                   )
                result = luis_result.properties["luisResult"]
                print(str(result.intents[0]))
                intentDetails = json.loads(
                    (str(result.intents[0])).replace("'", "\""))
                intent = intentDetails.get('intent')
                score = intentDetails.get('score')
                print(intent)
                print(score)
                self.IntentIdentified = True
                self.intent = intent
                self.score = score
            if self.intent == "Welcome" and self.score > 0.5:
                #bot_reply = "Hi How can I help you?"
                #bot_reply = self.welcome()
                await self.__send_intro_card(turn_context)
                bot_reply = f"{ user_profile.name }. To where should i book a flight for you?."
                self.IntentIdentified = False
            elif self.intent == "BookFlight" and self.score > 0.5:
                if self.stat == 'init':
                    print(str(result.entities[0]))
                    json_str = json.loads(
                        (str(result.entities[0])).replace("'", "\""))
                    #weather=weather_info.get_weather_info(json_str.get('entity'))
                    self.city = json_str.get('entity')
                    bot_reply = "should I book a flight to " + self.city + "."
                    await turn_context.send_activity(f"{bot_reply}")
                    print("1")
                    #await self._send_suggested_actions(turn_context)
                    print("2")
                    text = turn_context.activity.text.lower()
                    print("text", text)
                    #response_text = self._process_input(text)
                    #await turn_context.send_activity(MessageFactory.text(response_text))
                    self.stat = 'bookFlight'
                    bot_reply = ""
                    return await self._send_suggested_actions(turn_context)
                elif self.stat == 'bookFlight':
                    if turn_context.activity.text == "YES":
                        bot_reply = "Booked a flight to " + self.city + "."
                        self.stat = 'init'
                    else:
                        bot_reply = "cancelled booking procedure."
                        self.stat = 'init'
                self.log.write_log(sessionID='session1',
                                   log_message="Bot Says: " + str(bot_reply))
                self.IntentIdentified = False
            elif self.score < 0.5:
                # The actual call to the QnA Maker service.
                bot_reply = ""
                self.IntentIdentified = False
                response = await self.qna_maker.get_answers(turn_context)
                if response and len(response) > 0:
                    await turn_context.send_activity(
                        MessageFactory.text(response[0].answer))
                else:
                    await turn_context.send_activity(
                        "No QnA Maker answers were found.")
            await turn_context.send_activity(f"{bot_reply}")

    async def on_members_added_activity(self, members_added: ChannelAccount,
                                        turn_context: TurnContext):
        for member_added in members_added:
            if member_added.id != turn_context.activity.recipient.id:
                await turn_context.send_activity("Hello How can I help you!")
Esempio n. 17
0
    def main(self):
        Log.log(0, 'pi server is working')
        while not self.__stopped.isSet():
            Log.log(3, 'waiting for connection')
            self.__socket.set_timeout(1)
            try:
                connection, address = self.__socket.accept()
            except Exception as e:
                Log.log(0, 'exception when accepting connection {}'.format(e))
                continue

            Log.log(1, 'something connected')
            client_socket = MySocket(connection)
            msg = client_socket.get_msg()
            # Log.log(1, 'msg from server: {}'.format(msg))
            msg_type = MsgType.to_msg_type(struct.pack('B', msg[2]))
            if msg_type == MsgType.setState:
                dev_id = struct.unpack('!H', msg[3:5])[0]
                state = struct.unpack('!H', msg[5:7])[0]
                Log.log(2, 'received set state dev={}, state={}'.format(dev_id, state))
                device = self.__client.getDevice(dev_id)
                device.setState(state)
            else:
                Log.log(1, 'received bad msg type={} (expected setState)'.format(struct.pack('B', msg[0])))
Esempio n. 18
0
 def send_float_val(self, dev_key, val):
     socket = MySocket()
     socket.connect(self.__server_ip, self.__port)
     Log.log(1, 'connected to server')
     msg = ValMsg.generate_float_val_msg(val, self.__id, dev_key)
     try:
         socket.mysend(msg)
         answer = self.get_answer(socket)
         Log.log(
             2, 'reveived msg {}, msg type is {}'.format(answer, answer[0]))
         msg_type = MsgType.to_msg_type(struct.pack('B', answer[0]))
         if msg_type == MsgType.ack:
             Log.log(4, 'successfully sent value')
         elif msg_type == MsgType.nack:
             Log.log(4, 'Failed to send val')
         else:
             Log.log(
                 3, 'received msg_type {} when expecting ack/nack'.format(
                     msg_type))
             raise RuntimeError('unresolved msg_type received')
     except RuntimeError as e:
         Log.log(
             0, 'Failed to send value {}: {} ... closing connection'.format(
                 val, e))
         socket.close()
Esempio n. 19
0
def sigint_handler(signum, frame):
    Log.log(0, 'ending by SIGINT')
    client.stop()
    pi_server.stop()
    Log.log(0, 'ending')
    Log.close()


signal.signal(signal.SIGINT, sigint_handler)

port = 12345
server_ip = '192.168.1.19'
rpi_key = 12
# TODO: rpi_key port and ip from file or other better way
devices_path = 'devices.conf'
log_filepath = 'logs/file.log'
Log.init(log_filepath, 5)
Log.log(0, 'server parameters: port = {}, ip = {}'.format(port, server_ip))
# TODO: path from file or something

client = Client(devices_path, server_ip, port)
pi_server = RpiServer(port + 1, server_ip, client)

Log.log(0, 'configured {} devices'.format(len(client.getDevices())))
for dev in client.getDevices():
    # Log.log(1, dev.__dict__)
    Log.log(1, dev.str())

client.start_work()
pi_server.start()
Esempio n. 20
0
#coding:utf-8
import unittest, time
from config.config import config
from time import sleep
from logger.logger import Log

log = Log()
driver = config.driver


class accountManagement(unittest.TestCase):
    def setUp(self):
        sleep(2)

    def tearDown(self):
        sleep(2)
        log.info(u"--------测试结束--------")

    def test001_accountManagement(self):
        u"""账号管理"""
        log.info(u"--------测试用例开始--------")
        driver.find_element_by_link_text(u"权限管理").click()
        sleep(1)
        driver.find_element_by_link_text(u"账号管理").click()
        sleep(1)
        driver.find_element_by_class_name("textInput").send_keys("txj_testjg1")
        sleep(1)
        log.info(u"输入内容:txj_testjg1")
        driver.find_element_by_class_name("button").click()
        sleep(2)
        log.info(u"点击按钮:class = button")
Esempio n. 21
0
 def stop(self):
     self.__stopped.set()
     self.__main_thread.join()
     Log.log(0, 'client main thread joined')
Esempio n. 22
0
 def stop(self):
     self.__stopped.set()
     self.__server_thread.join()
     Log.log(1, 'server pi thread joined')
Esempio n. 23
0
 def get_msg(self):
     msg_len = self.myreceive(2)
     unpacked_len = struct.unpack('!H', msg_len)[0]
     Log.log(3, 'received msg len is {}'.format(unpacked_len))
     msg = self.myreceive(unpacked_len - 2)
     return msg_len + msg
Esempio n. 24
0
def messages():
    if request.method == 'GET':
        token_sent = request.args.get("hub.verify_token")
        print("1")
        if token_sent == 'LUIS':
            return request.args.get("hub.challenge")
            print("2")
        return 'Invalid verification token'
    elif request.method == 'POST':
        data = request.get_json()
        print(data)
        #if data['channelId'] != 'emulator':
        if 'object' in data.keys():
            if data['object'] == "page":
                entries = data['entry']

                for entry in entries:
                    messaging = entry['messaging']

                    for messaging_event in messaging:

                        sender = messaging_event['sender']['id']
                        recipient = messaging_event['recipient']['id']

                        if messaging_event.get('message'):
                            if messaging_event['message'].get('text'):
                                query = messaging_event['message']['text']
                                reply = predict.getIntent(query)
                                bot.send_text_message(sender, reply)

            return "ok", 200
            # async def messages(req: Request) -> Response:
            # if "application/json" in req.headers["Content-Type"]:
            # body = await req.json()
            # else:
            # return Response(status=415)

            # activity = Activity().deserialize(body)
            # auth_header = req.headers["Authorization"] if "Authorization" in req.headers else ""

            # response = await ADAPTER.process_activity(activity, auth_header, luis_bot_dialog.on_turn)
            # if response:
            # return json_response(data=response.body, status=response.status)
            # return Response(status=201)
        else:
            if "application/json" in request.headers["content-type"]:
                log = Log()
                request_body = request.json
                print("request_body", request_body)
                user_says = Activity().deserialize(request_body)
                print("user_says", user_says)
                log.write_log(sessionID='session1',
                              log_message="user says: " + str(user_says))
                authorization_header = (request.headers["Authorization"]
                                        if "Authorization" in request.headers
                                        else "")

                async def call_user_fun(turncontext):

                    await luis_bot_dialog.on_turn(turncontext)

                task = loop.create_task(
                    bot_adapter.process_activity(user_says,
                                                 authorization_header,
                                                 call_user_fun))
                loop.run_until_complete(task)
                return ""
            else:
                return Response(status=406)  # status for Not Acceptable
Esempio n. 25
0
def sigint_handler(signum, frame):
    Log.log(0, 'ending by SIGINT')
    client.stop()
    pi_server.stop()
    Log.log(0, 'ending')
    Log.close()
Esempio n. 26
0
 def register_on_server(self):
     socket = MySocket()
     socket.connect(self.__server_ip, self.__port)
     Log.log(1, "connected to server")
     msg = (3).to_bytes(2, self.endian)
     msg += MsgType.reg.value
     try:
         socket.mysend(msg)
         answer = self.get_answer(socket)
         Log.log(
             2, "received msg {}, msg_type is {}".format(answer, answer[0]))
         # msg_type = MsgType.to_msg_type(answer[0].to_bytes(1, self.endian))
         msg_type = MsgType.to_msg_type(struct.pack('B', answer[0]))
         if msg_type == MsgType.ack:
             self.__id = struct.unpack('!H', answer[1:3])[0]
             Log.log(3, 'received id is {}'.format(self.__id))
         elif msg_type == MsgType.nack:
             raise RuntimeError('nack received, reg refused by server')
         else:
             # Log.log(3, 'received msg_type {} when expecting ack'.format(msg_type))
             raise RuntimeError(
                 'unresolved msg_type received {}, expecting ack/nack'.
                 format(msg_type))
         for device in self.__devices:
             msg, length = device.generateMsg()
             msg = struct.pack(
                 '!H', length + 5) + MsgType.dev.value + struct.pack(
                     '!H', self.__id) + msg
             socket.mysend(msg)
             answer = self.get_answer(socket)
             # msg_type = MsgType.to_msg_type(answer[0].to_bytes(1, self.endian))
             msg_type = MsgType.to_msg_type(struct.pack('B', answer[0]))
             if msg_type == MsgType.ack:
                 dev_id = struct.unpack('!H', answer[1:3])[0]
                 Log.log(3, 'device {} successful sent'.format(dev_id))
             elif msg_type == MsgType.nack:
                 dev_id = struct.unpack('!H', answer[1:3])[0]
                 Log.log(3, 'failed to send device {}'.format(dev_id))
             else:
                 Log.log(
                     3, 'received msg_type {} when expecting ack'.format(
                         msg_type))
                 raise RuntimeError('unresolved msg_type received')
         msg = struct.pack('!H', 5) + MsgType.end.value + struct.pack(
             '!H', self.__id)
         socket.mysend(msg)
         Log.log(2, 'successfully registered on server')
         socket.close()
         self.__registered.set()
     except RuntimeError as e:
         Log.log(0,
                 'registering failed: {} ... closing connection'.format(e))
         socket.close()
Esempio n. 27
0
# try:
from .endpoint import Endpoint
from .device_types import DevTypeCode
from .device_types import DevTypeId
from socket import htons
import struct
from logger.logger import Log
GpioEnabled = True
try:
    import RPi.GPIO as gpio
except ModuleNotFoundError as e:
    Log.log(0, 'Failed to import RPi.GPIO: {}'.format(e))
    GpioEnabled = False

# except SystemError:
#     from endpoint import Endpoint
#     from device_types import DevTypeCode
#     from device_types import DevTypeId


class Light(Endpoint):
    def __init__(self, key, name, pin, zero_triggered=False):
        super().__init__(key, name)
        self.__pin = pin
        self.__zero_triggered = zero_triggered
        if GpioEnabled:
            gpio.setmode(gpio.BCM)
            gpio.setup(pin, gpio.OUT)

    def turnOn(self):
        #TODO