async def protocol_handler(bot): await asyncio.sleep(3) # wait for bot start while True: try: data, source = sock_proto.recvfrom(1024) packet = Protocol.decode(data) if packet.code == Protocol.CODE_IFALIVE: status_info = _handle_status( True, datetime.datetime.now().timestamp()) if status_info: await bot.send_message(LOG_ID, '[INFO] Device is running now') if packet.code == Protocol.CODE_STARTTIME: startup_time = datetime.datetime.fromisoformat(packet.payload) time = startup_time.__format__('%H:%M:%S') date = startup_time.__format__('%d %h %Y') up_time = str(datetime.datetime.now() - startup_time) for i, s in enumerate(up_time[::-1]): if s == '.': up_time = up_time[:-i - 1] break await bot.send_message( packet.cid, f'System uptime: {up_time}\nStartup time: {time} - {date}' ) except socket.timeout: await asyncio.sleep(0.01) except Exception as err: log.error(f'[protocol_handler] {err}') await bot.send_message(LOG_ID, f'[ERROR:protocol_handler] {err}')
class Speed(ChassisDev): TYPE = 0x02 # 12 bytes data package format in struct pack_pmt = "3f" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Speed", pub_topic = "/speed_wheel", pub_msg_class = Float32MultiArray, pub_rate = 20) self.speeds = Float32MultiArray() self.speeds.data = [0,0,0] ChassisDev.pub_data_update(self, self.speeds) ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): wheel0, wheel1, wheel2 = \ self.protocol.decode(bin_data_pack) self.speeds.data = [wheel0, wheel1, wheel2] ChassisDev.pub_data_update(self, self.speeds)
class Odom(ChassisDev): TYPE = 0x01 # 12 bytes data package format in struct pack_pmt = "3i" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Chassis", pub_topic = "/encoder_cnts", pub_msg_class = Float32MultiArray, pub_rate = 20) self.counters = Float32MultiArray() ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): counter0, counter1, counter2 = \ self.protocol.decode(bin_data_pack) self.counters.data = [counter0, counter1, counter2] ChassisDev.pub_data_update(self, self.counters)
class Battery(ChassisDev): TYPE = 0x03 # 12 bytes data package format in struct pack_pmt = "2f2H" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "smart_battery", pub_topic = "smart_battery", pub_msg_class = SmartBatteryStatus) self.battery_status = SmartBatteryStatus() ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): try: voltage, rate, _,_ = \ self.protocol.decode(bin_data_pack) except e: print e return self.battery_status.voltage = voltage self.battery_status.rate = rate self.battery_status.charge_state = 0 if voltage > 2000: self.battery_status.percentage = 100 - (2520 - voltage)/4 else: self.battery_status.percentage = 100 - (1260 - voltage)/1.6 ChassisDev.pub_data_update(self, self.battery_status)
class Speed(ChassisDev): TYPE = 0x02 # 12 bytes data package format in struct pack_pmt = "3f" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Speed", pub_topic="/speed_wheel", pub_msg_class=Float32MultiArray, pub_rate=20) self.speeds = Float32MultiArray() self.speeds.data = [0, 0, 0] ChassisDev.pub_data_update(self, self.speeds) ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): wheel0, wheel1, wheel2 = \ self.protocol.decode(bin_data_pack) self.speeds.data = [wheel0, wheel1, wheel2] ChassisDev.pub_data_update(self, self.speeds)
class Odom(ChassisDev): TYPE = 0x01 # 12 bytes data package format in struct pack_pmt = "3i" def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "Chassis", pub_topic="/encoder_cnts", pub_msg_class=Float32MultiArray, pub_rate=20) self.counters = Float32MultiArray() ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): counter0, counter1, counter2 = \ self.protocol.decode(bin_data_pack) self.counters.data = [counter0, counter1, counter2] ChassisDev.pub_data_update(self, self.counters)
def listen(self): active = True while active: try: r = self.client.conn.recv(3) if r != b'': headerType, size = HeaderParser.decode(r) data = Protocol.decode(self.client.conn.recv(size)) if headerType == Header.SES: self.client.session = data['session'] self.ses_signal.emit() elif headerType == Header.LIS: self.lis_signal.emit(data['users']) elif headerType == Header.ERR: self.err_signal.emit(data['msg']) elif headerType == Header.ACK: self.ack_signal.emit(data['msg']) elif headerType == Header.HIS: self.his_signal.emit(data['history']) elif headerType == Header.LOG: self.client.salt = bytes.fromhex(data['password'])[:32] MainWindow.client.login(None, None) except socket.error as ex: print(ex) active = False
class MPU(ChassisDev): TYPE = 0x04 # 12 bytes data package format in struct pack_pmt = "3f" TYPE_ACC = 0x00 TYPE_GYRO = 0x01 def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "chassis", pub_topic="imu/data_raw", pub_rate=10, pub_msg_class=Imu) self.imu = Imu() ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): if struct.unpack("20B", bin_data_pack)[2] == self.TYPE_GYRO: try: x, y, z = \ self.protocol.decode(bin_data_pack) self.imu.angular_velocity.x = x self.imu.angular_velocity.y = y self.imu.angular_velocity.z = z self.imu.header.frame_id = 'base_footprint' self.imu.header.stamp = rospy.Time.now() ChassisDev.pub_data_update(self, self.imu) except Exception as e: print e return else: try: x, y, z = \ self.protocol.decode(bin_data_pack) self.imu.linear_acceleration.x = x self.imu.linear_acceleration.y = y self.imu.linear_acceleration.z = z except e: print e return
def handle(self): r = self.socket.recv(3) if r != b'': headerType, size = HeaderParser.decode(r) data = Protocol.decode(self.socket.recv(size)) h, p = None, None if headerType == Header.LOG: r = requests.get(URL.local + 'users', params={'username': data['login']}) j = r.json() if r.status_code == 200 and j != {}: u2 = bytes.fromhex(j['password']) u1 = self.passwordHash(data['password'], u2[:32]) if u1[32:] == u2[32:]: h, p = Protocol.encode(Header.SES, session=self.uuid) self.transfer(h, p) Logger.log('User logged in (' + str(data['login']) + ')') return UserLogged(self, j['id'], j['username']) h, p = Protocol.encode(Header.ERR, msg='Invalid login data') Logger.log('User login invalid data ' + str(self.address)) elif headerType == Header.REG: r = requests.post(URL.local + 'users', json={ 'username': data['login'], 'password': self.passwordHash( data['password']).hex() }) if r.status_code == 201: h, p = Protocol.encode(Header.ACK, msg='Created Account') Logger.log('User registered ') elif r.status_code == 409: h, p = Protocol.encode(Header.ERR, msg='Account already exists') msg = r.json()['Message'] Logger.log('User thats already exists creation try (' + str(data['login']) + ')') else: h, p = Protocol.encode(Header.ERR, msg='Invalid register data') Logger.log('User register invalid data ') elif headerType == Header.DIS: raise socket.error(data['msg']) if h != None and p != None: self.transfer(h, p) return None
def receive(self): try: data, addr = self.rs.recvfrom(1500) data = Protocol.decode(data) logger.debug('Receive Packet: ' + data.hex()) header, payload = Protocol.split(data) header, payload = Protocol.interpret_header( header), Protocol.interpret_payload(payload) logger.debug('Received Header: ' + str(header)) logger.debug('Received Payload: ' + str(payload)) self.header['token_id'] = header['token_id'] return header, payload except: raise ConnectionProblem()
class MPU(ChassisDev): TYPE = 0x04 # 12 bytes data package format in struct pack_pmt = "3f" TYPE_ACC = 0x00 TYPE_GYRO = 0x01 def __init__(self): self.protocol = Protocol(self.TYPE, self.pack_pmt) ChassisDev.__init__(self, "chassis", pub_topic="imu/data_raw", pub_rate=10, pub_msg_class=Imu) self.imu = Imu() ChassisDev.start_pub(self) def data_handler(self, bin_data_pack): if struct.unpack("20B", bin_data_pack)[2] == self.TYPE_GYRO: try: x, y, z = self.protocol.decode(bin_data_pack) self.imu.angular_velocity.x = x self.imu.angular_velocity.y = y self.imu.angular_velocity.z = z self.imu.header.frame_id = "base_footprint" self.imu.header.stamp = rospy.Time.now() ChassisDev.pub_data_update(self, self.imu) except Exception as e: print e return else: try: x, y, z = self.protocol.decode(bin_data_pack) self.imu.linear_acceleration.x = x self.imu.linear_acceleration.y = y self.imu.linear_acceleration.z = z except e: print e return
def main(): with open("tp_analyse.txt") as f: first = True ret = [] for l in f: try: adr = int(l[:4], 16) except ValueError: continue if adr == 0: if not first: ret.append(data) first = False data = bytearray() if adr % 16 == 0: #print(adr, bytearray.fromhex(l[6:53].split(" "))) data += bytearray.fromhex(l[6:53]) ret.append(data) for s in ret: data = Protocol.decode(s) # print(data.hex(" ")) print(Protocol.analyze(data)[1])
def handle(self): r = self.socket.recv(3) if r != b'': headerType, size = HeaderParser.decode(r) data = Protocol.decode(self.socket.recv(size)) h, p = None, None if headerType == Header.DIS: raise socket.error('Disconnect') elif headerType == Header.ALI: r = requests.get(URL.local + 'quizzes-categories') if r.status_code == 200: j = r.json() l = [] for x in j: l.append(x['category_name']) h, p = Protocol.encode(Header.LIS, quizes=l) Logger.log('Category request') else: h, p = Protocol.encode(Header.ERR, msg='Cant get categories') Logger.log('Category request failed') elif headerType == Header.STR: if data['category'] == []: r = requests.get(URL.local + 'quizzes-categories') r2 = requests.get(URL.local + 'stats', params={'userid': self.dbID}) if r.status_code == 200 and r2.status_code == 200: cat = r.json() stat = r2.json() ret = [] for x in stat: for y in cat: if x['quizid'] == y['id']: print('abc') ret.append({ 'category': y['category_name'], 'score': x['score'] }) break if ret != []: h, p = Protocol.encode(Header.STA, stats=ret) else: h, p = Protocol.encode(Header.ERR, msg='empty') Logger.log('Stats request ' + str(self.dbID)) else: Logger.log('Stats request failed' + str(self.dbID)) else: r = requests.get(URL.local + 'top-stats', params={'category': data['category']}) if r.status_code == 200: stat = r.json() if stat != []: h, p = Protocol.encode(Header.STA, stats=stat) else: h, p = Protocol.encode(Header.ERR, msg='empty') Logger.log('Stats request ' + str(self.dbID)) else: Logger.log('Stats request failed' + str(self.dbID)) elif headerType == Header.QUI: r = requests.get(URL.local + 'quizzes', params={'category_name': data['category']}) if r.status_code == 200 and self.quiz == None: j = r.json() qq = [] for x in j: q = x['Question']['question'] cor = None a = x['Answers'] for y in a: if y['id'] == x['Question']['correct_answer']: cor = y['answer'] b = [] for i in range(4): b.append(str(a[i]['answer'])) qq.append(Question(q, b, str(cor))) self.quiz = Quiz(qq, j[0]['Question']['quizid']) question = self.quiz.next() h, p = Protocol.encode(Header.QUE, question=question.question, answers=question.answers, correct=question.correct) Logger.log('Quiz begin' + str(self.dbID)) else: h, p = Protocol.encode(Header.ERR, msg='Cant begin quiz') Logger.log('Quiz request fail ' + str(self.dbID)) elif headerType == Header.NXT: if self.quiz != None: question = self.quiz.next() h, p = Protocol.encode(Header.QUE, question=question.question, answers=question.answers, correct=question.correct) Logger.log('next question ' + str(self.dbID)) else: h, p = Protocol.encode(Header.ERR, msg='Invalid request') Logger.log('next question fail ' + str(self.dbID)) elif headerType == Header.END: if self.quiz != None: r = requests.patch(URL.local + 'stats', json={ 'userid': self.dbID, 'quizid': self.quiz.quizid, 'score': data['score'] }) self.quiz = None h, p = Protocol.encode(Header.ACK, msg='Quiz completed') Logger.log('Quiz end ' + str(self.dbID)) else: h, p = Protocol.encode(Header.ERR, msg='Invalid end request') Logger.log('Quiz end request fail ' + str(self.dbID)) if h != None and p != None: self.transfer(h, p) return None
def handle(self): r = self.socket.recv(3) if r != b'': headerType, size = HeaderParser.decode(r) data = Protocol.decode(self.socket.recv(size)) h, p = None, None if headerType == Header.LOG: r = requests.get(URL.local + 'users', params={'username': data['login']}) j = r.json() if r.status_code == 200 and j != {} and data['password'] != 'X': u2 = bytes.fromhex(j['password']) u1 = bytes.fromhex(data['password']) if u1[32:] == u2[32:]: h, p = Protocol.encode(Header.SES, session=self.uuid) self.transfer(h, p) Logger.log('User logged in (' + str(data['login']) + ')') return UserLogged(self, j['id'], j['username']) elif r.status_code == 200 and j != {} and data[ 'password'] == 'X': h, p = Protocol.encode(Header.LOG, login=data['login'], password=j['password']) self.transfer(h, p) return None h, p = Protocol.encode(Header.ERR, msg='Invalid login data') Logger.log('User login invalid data ' + str(self.address)) elif headerType == Header.REG: r = requests.post(URL.local + 'users', json={ 'username': data['login'], 'email': data['email'], 'password': data['password'] }) if r.status_code == 201: h, p = Protocol.encode(Header.ACK, msg='Created Account') Logger.log('User registered ') elif r.status_code == 409: h, p = Protocol.encode(Header.ERR, msg='Account already exists') msg = r.json()['Message'] Logger.log('User thats already exists creation try (' + str(data['login']) + ')') else: h, p = Protocol.encode(Header.ERR, msg='Invalid register data') Logger.log('User register invalid data ') elif headerType == Header.FRP: ru = requests.get(URL.local + 'users', params={'username': data['login']}) j = ru.json() if ru.status_code == 200: if j != {}: mail = j['email'] r = requests.post('https://molly.ovh:5050/token/' + data['login'], verify=False) j2 = r.json() token = j2['token'] threading.Thread(target=sendRecoveryMail, args=( mail, token, )).start() Logger.log('FRP send') h, p = Protocol.encode(Header.ACK, msg='Send recovery mail') Logger.log('FRP used') else: h, p = Protocol.encode(Header.ERR, msg='Error occured') Logger.log('FRP error') elif headerType == Header.DIS: raise socket.error(data['msg']) if h != None and p != None: self.transfer(h, p) return None
def handle(self): r = self.socket.recv(3) if r != b'': headerType, size = HeaderParser.decode(r) data = Protocol.decode(self.socket.recv(size)) h, p = None, None if headerType == Header.DIS: raise socket.error('Disconnect') elif headerType == Header.MSG: historyID = self.checkHistory(self.username, data['reciever']) if historyID != None: r = requests.post(URL.local + 'history-manager', json={ 'history_id': historyID, 'username': self.username, 'content': data['msg'] }) elif headerType == Header.DEL: r = requests.delete(URL.local + 'users', params={'username': self.username}) if r.status_code == 200: h, p = Protocol.encode(Header.ACK, msg='Deletion succesfull') else: h, p = Protocol.encode(Header.ERR, msg='Deletion failed') elif headerType == Header.CHP: r = requests.patch(URL.local + 'users', json=({ 'password': data['password'] }), params={'username': self.username}) if r.status_code == 200: h, p = Protocol.encode(Header.ACK, msg='Change password succesfull') else: h, p = Protocol.encode(Header.ERR, msg='Change password failed') elif headerType == Header.CHM: r = requests.patch(URL.local + 'users', json=({ 'email': data['email'] }), params={'username': self.username}) if r.status_code == 200: h, p = Protocol.encode(Header.ACK, msg='Change mail succesfull') else: h, p = Protocol.encode(Header.ERR, msg='Change mail failed') elif headerType == Header.UPD: self.reciever = data['reciever'] if self.reciever != None: self.checkHistory(self.username, self.reciever) if h != None and p != None: self.transfer(h, p) return None
headerType, size = HeaderParser.decode(conn.recv(3)) data = Protocol.decode(conn.recv(size)) if headerType == Header.ACK: print(data['msg']) elif headerType == Header.ERR: print(data['msg']) ''' session = None _login = '******' login(_login, '123') headerType, size = HeaderParser.decode(conn.recv(3)) data = Protocol.decode(conn.recv(size)) if headerType == Header.SES: session = data['session'] print(session) #statsRequest() beginQuiz('Sport') headerType, size = HeaderParser.decode(conn.recv(3)) data = Protocol.decode(conn.recv(size)) print(data) for x in range(9): nextQueston() headerType, size = HeaderParser.decode(conn.recv(3))