def test_bytes_expected_but_got_string(): try: crc8().update(str()) except TypeError as e: assert e.args[0] == "Unicode-objects must be encoded before hashing" else: assert False, "Strings can not be passed to crc8 before encoding."
def test_bytes_expected_but_got_string(): try: crc8().update(u"\u1234") except UnicodeEncodeError as error: assert error.args[0] == ENCODE_FAILURE_MESSAGE else: assert False, "Can not encode \"\\u1234\"."
def test_bytes_expected_but_got_string(): try: crc8().update(str()) except TypeError as e: assert e.args[ 0] == "Unicode-objects must be encoded before hashing" else: assert False, "Strings can not be passed to crc8 before encoding."
def test_bytes_expected(): if PY2: message = "must be string or buffer" else: message = "object supporting the buffer API required" try: crc8().update(None) except TypeError as e: assert e.args[0] == message else: assert False, "None can not be passed to crc8 before encoding."
def map_addr(s, d): """ Map the current source and dest address to the ones in the topo """ s_out, d_out = crc8(0, s, 0x31) % 11 + 1, crc8(0, d, 0x1d) % 11 + 1 count = 0 while s_out == d_out and count < 5: s_out, d_out = crc8(0, s, 0x31) % 11 + 1, crc8(0, d, 0x1d) % 11 + 1 count += 1 s_out, d_out = 's' + str(s_out), 's' + str(d_out) return s_out, d_out
def map_addr_tree(s, d, tors): """ Map the current source and dest address to the ones in the topo """ n = len(tors) s_out, d_out = crc8(0, s, 0x31)%n + 1, crc8(0, d, 0x1d)%n + 1 count = 0 while s_out == d_out and count < 5: s_out, d_out = crc8(0, s, 0x31)%n + 1, crc8(0, d, 0x1d)%n + 1 count += 1 s_out, d_out = tors[s_out], tors[d_out] return s_out, d_out
def map_addr_tree_3(s, d, tors, block=4): """ Map the current source and dest address to the ones in the topo """ block_id = crc8(0, s, 0x31) % block s_d = crc8(0, s, 0x31) % 2 n1 = 128 if block_id == 0: n2 = 128 * 3 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[s_out], tors[128 + d_out] elif block_id == 3: n2 = 128 * 3 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[d_out] elif block_id == 1: out_block = random.randint(0, 2) if out_block == 0: n2 = 128 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[d_out] elif out_block == 1: n2 = 128 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[128 * (block_id + 1) + d_out] else: n2 = 128 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[128 * (block_id + 2) + d_out] elif block_id == 2: out_block = random.randint(0, 2) if out_block == 0: n2 = 128 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[d_out] elif out_block == 1: n2 = 128 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[128 * (1 + 1) + d_out] else: n2 = 128 s_out, d_out = random.randint(0, n1 - 1), random.randint(0, n2 - 1) s_out, d_out = tors[128 * block_id + s_out], tors[128 * (block_id + 1) + d_out] return s_out, d_out
def map_addr_tree(s, d, tors): """ Map the current source and dest address to the ones in the topo """ n = len(tors) s_out = crc8(0, s, 0x31) % n tor_ds = tors[:s_out] + tors[s_out + 1:] nd = n - 1 d_out = crc8(0, d, 0x1d) % nd s_out, d_out = tors[s_out], tor_ds[d_out] return s_out, d_out
def make_sos_packet(am_group, module_src, module_dst, dst_addr, src_addr, msg_type, payload, sbp, access_code, pad_for_usrp=True): """ Build a SOS packet @param am_group: @param module_src: @param module_dst: @param dst_addr: @param src_addr: @param msg_type: @param payload: @param sbp: @param access_code: @param pad_for_usrp: """ if len(payload) > MAX_PKT_SIZE: raise ValueError, "len(payload) must be in [0, %d]" %(MAX_PKT_SIZE) header = ''.join((chr(am_group), chr(module_src), chr(module_dst), chr(dst_addr&0xFF), chr((dst_addr >> 8) & 0xFF), chr(src_addr&0xFF), chr((src_addr >> 8) & 0xFF), chr(msg_type&0xFF), chr((len(payload) & 0xFF)))) crcClass = crc8.crc8() crc = struct.pack('H', crcClass.crc(header[1:]+payload)) #crc = chr(0xfe) # create the packet with the syncronization header of 100x '10' in front. pkt = ''.join((20*struct.pack('B', 0xaa), access_code, header, payload, crc, 20*struct.pack('B', 0xaa))) return pkt
def test_get_nonexistent_line(self, cache, get_line, line_number): get_line.return_value = None empty_last_line = bytes([line_number & 255]) + \ b"\x00" * 25 + b'\x01' # last line flag empty_last_line += crc8.crc8(empty_last_line).digest() line = cache.get_line_configuration_message(line_number) assert line == empty_last_line
def _sending_thread(self): """Manages the sending of packets to the robot. Sends messages in order from the tx queue, waiting if any messages have responses pending. """ inc = 0 while self._ble_thread.is_alive(): # block sending new commands until no responses pending if self._responses_pending(): continue if not self._tx_q.empty(): packet, expectResponse = self._tx_q.get() packet = bytearray(packet) packet[2] = inc if expectResponse: self.pending_lock.acquire() # need a timeout because responses are not guaranteed. resp_expire = time.time() + self._calculate_timeout(packet) self.pending_resp.append((packet[0:3], resp_expire)) self.pending_lock.release() self._send_raw_ble(packet + crc8.crc8(packet).digest()) inc += 1 if inc > 255: inc = 0
async def _command_set_nfc_ir_mcu_config(self, sub_command_data): input_report = InputReport() input_report.set_input_report_id(0x21) input_report.set_misc() input_report.set_ack(0xA0) input_report.reply_to_subcommand_id(SubCommand.SET_NFC_IR_MCU_CONFIG.value) self._mcu.update_status() data = list(bytes(self._mcu)[0:34]) crc = crc8() crc.update(bytes(data[:-1])) checksum = crc.digest() data[-1] = ord(checksum) for i in range(len(data)): input_report.data[16+i] = data[i] # Set MCU mode cmd if sub_command_data[1] == 0: if sub_command_data[2] == 0: self._mcu.set_state(McuState.STAND_BY) elif sub_command_data[2] == 4: self._mcu.set_state(McuState.NFC) else: logger.info(f"unknown mcu state {sub_command_data[2]}") else: logger.info(f"unknown mcu config command {sub_command_data}") await self.write(input_report)
def next_hop(cur_hop, pre_hop, s, d, hash_str, table, seeds, polys, flow_paths ): print('cur_hop, pre_hop', cur_hop, pre_hop) if cur_hop == d: hash_str0 = hash_str hash_str = hash_str0[0:14] marker = hash_str0[14:] if marker != 'None': append_path(hash_str, pre_hop, cur_hop, flow_paths) return n = len(hash_str) # Header = 4+4+2+2+1 bytes hash_str0 = hash_str hash_str = hash_str0[0:13] marker = hash_str0[13:] if marker == cur_hop: append_path(hash_str, pre_hop, cur_hop, flow_paths) nhop = table[cur_hop][d][0] n = len(table[cur_hop][d]) if n > 1: ni = crc8(seeds[cur_hop], hash_str, polys[cur_hop])%n nhop = table[cur_hop][d][ni] next_hop(nhop, cur_hop, s, d, hash_str0, table, seeds, polys, flow_paths)
def __init__( self, all_cb=None, new_data_cb=None, ack_packet_finished_cb=None, error_cb=None, client_unreachable=None ): self._com = "" self._serial = serial.Serial self._idx = 0 self._buffer = [] self._crc = crc8() ## @brief comport reading thread self._thread = Thread(target=self._loop, name="comport") # self._thread.setDaemon(True) self._comportContinue = threading.Event() self._comportContinue.set() self._newdata_cb = new_data_cb self._ack_packet_finished_cb = ack_packet_finished_cb self._client_unreachable = client_unreachable self._error_cb = error_cb self._master_cb = all_cb self._lock = Lock() ## @brief wireless transmition packet queue processing thread self._send_thread = Thread(target=self._sending_loop2, name="ack payload sender") # self._send_thread.setDaemon(True) self._sendContinue = threading.Event() self._sendContinue.set() self._send_queue = Queue.Queue() self._packet_inside = False self._buffer = [] self._log = logging.getLogger("root.serialHardware") self._tx_finished_lock = Lock() self._loop_idx = 0 self._loop_reciver_timeout_lock = Lock()
def MCU_crc(data): if not isinstance(data, bytes): data = bytes(data) my_hash = crc8.crc8() my_hash.update(data) # At this point I'm not even mad this works... return my_hash.digest()[0]
def run(self): while self.keep_running: print "cc1k_sos_pkt: waiting for packet" msg = self.rcvd_pktq.delete_head() ok = 1 payload = msg.to_string() #print "received packet " am_group = ord(payload[0]) module_src = ord(payload[1]) module_dst = ord(payload[2]) dst_addr = ord(payload[4])*256 + ord(payload[3]) src_addr = ord(payload[6])*256 + ord(payload[5]) msg_type = ord(payload[7]) msg_len = ord(payload[8]) msg_payload = payload[9:9+msg_len] crc = ord(payload[-2]) + ord(payload[-1])*256 crcClass = crc8.crc8() crcCheck = crcClass.crc(payload[1:9+msg_len]) #print " bare msg: " + str(map(hex, map(ord, payload))) #print " am group: " + str(am_group) #print " src_addr: "+str(src_addr)+" dst_addr: "+str(dst_addr) #print " src_module: " + str(module_src) + " dst_module: " + str(module_dst) #print " msg type: " + str(msg_type) + " msg len: " +str(msg_len) #print " msg: " + str(map(hex, map(ord, msg_payload))) #print " crc: " + str(crc) #print " crc_check: " + str(crcCheck) #print ok = (crc == crcCheck) if self.callback: self.callback(ok, am_group, src_addr, dst_addr, module_src, module_dst, msg_type, msg_payload, crc)
def command_set_nfc_ir_mcu_config(mcu, report, output_report): report[1] = 0x21 report[3] = 0x8E report[14] = 0xA0 report[15] = 0x21 mcu.update_status() data = list(bytes(mcu)[0:34]) crc = crc8() crc.update(bytes(data[:-1])) checksum = crc.digest() data[-1] = ord(checksum) for i in range(len(data)): report[16 + i] = data[i] sub_command_data = output_report[12:] if sub_command_data[1] == 0: if sub_command_data[2] == 0: write_to_buffer(message_buffer, "Changed MCU state to stand by", "comment") mcu.set_state(McuState.STAND_BY) elif sub_command_data[2] == 4: write_to_buffer(message_buffer, "Changed MCU state to NFC", "comment") mcu.set_state(McuState.NFC) else: print(f"unknown mcu state {sub_command_data[2]}") else: print(f"unknown mcu config command {sub_command_data}") return bytes(report)
def _recv(self, timeout=1): ready, _, _ = select.select([self.sock], [], [], timeout) if not ready: return None, None, None, None data, addr = self.sock.recvfrom(1024) if len(data) < 4: logger.error("Received a packet that's too short: %s", repr(data)) return None, None, None, None type_ = struct.unpack(self.P_HEADER, data[:4])[0] if type_ not in self.PACKET_TYPES_REV: logger.error("Received an invalid packet type: %s: %s", repr(data[:4]), repr(data)) return None, None, None, None crc = crc8.crc8() crc.update(data) crc = crc.digest()[0] type_ = self.PACKET_TYPES_REV[type_] fmt, fields = getattr(self, 'P_' + type_) out = dict( zip(fields, struct.unpack(fmt, data[4:struct.calcsize(fmt) + 4]))) out['data'] = data[struct.calcsize(self.P_HEADER) + struct.calcsize(fmt):] or None for k, v in self.PARSERS.get(type_, {}).items(): if k in out: out[k] = v(out[k]) return addr, type_, out, crc
def check_crc(p): crc = crc8.crc8() crc.update(p.packetType) crc.update(p.length / 256) crc.update(p.length % 256) for i in range(0, p.length): crc.update(p.payload[i]) return int(crc) == p.crc8
def compute_checksum(self, len_bytes, bytes): hash = crc8.crc8() hash._sum = 0x02 hash.update(len_bytes) hash.update(bytes) checksum = hash.digest()[0] checksum = checksum ^ 0x02 return checksum
def __init__(self, port=None, host=None, family=socket.AF_INET, sock_type=socket.SOCK_STREAM): self.host = host if host else app.config['LSERVER_HOST'] self.port = port if port else app.config['LSERVER_PORT'] self.tea = None # tea.Tea() if app.config['NEEDENCRYPTION'] else None self.crc8 = crc8.crc8() self.sock = socket.socket(family=family, type=sock_type) self.connected = False self.broken = False
def writereg_once(self, reg, v): if self.bus: hash = crc8.crc8() hash.update(chr(reg)) hash.update(chr(v)) crc = hash.digest() self.bus.write_i2c_block_data(self.addr, reg, [v, ord(crc)]) readBack = self.bus.read_byte(self.addr) crc = self.bus.read_byte(self.addr) else: hash = crc8.crc8() hash.update(chr(reg)) hash.update(chr(v)) crc = hash.digest() (count, i2cdata) = self.pi.bb_i2c_zip(self.sdaPin, (4, self.addr, # set addr to self.addr 2, 7, 3, reg, v, crc, # start, write three bytes (reg, v, crc) 2, 6, 1, # (re)start, read one byte 2, 6, 1, # (re)start, read one byte 3, # stop 0)) # end if count<0: raise I2CError("i2c error") if count!=2: raise I2CError("i2c wrong byte count") readBack = i2cdata[0] crc = i2cdata[1] # note that readBack will actually return the next register. But, # that's alright, we don't care -- we just want to check to make # sure we didn't get an error back. if (readBack == 0xFF) and (crc == 0xFF): raise ReceiveCRCError("receive crc error") if (readBack == 0xFF) and (crc == 0xFE): raise ReceiveSizeError("receive size error") if (readBack == 0xFF) and (crc == 0xFD): raise ReceiveUninitializedError("receive uninitialized error") hash = crc8.crc8() hash.update(chr(readBack)) if crc != ord(hash.digest()): raise CRCError("crc error, readBack=%2X, crc=%2X, localCrc=%X" % (readBack, crc, ord(hash.digest())))
def GetResponse(self, remain): partial_packet = remain pkt_len = 0 FI_HDR = "\x00" + self.getRepHeader(self._target) STATE = 0 pkt_frame_len = "" pkt_frame_data = "" loop_times = 0 time_start = float(time.time() * 1000) while True: time_check = float(time.time() * 1000) if (len(partial_packet) >= 2 and STATE == 0): if FI_HDR == partial_packet[:2]: STATE = 1 partial_packet = partial_packet[2:] else: print_err_dump(partial_packet, "Wrong Rsp header, return") return False if (len(partial_packet) >= 3 and STATE == 1): if ((ord(partial_packet[0]) ^ ord(partial_packet[1])) != ord(partial_packet[2])): print_err_dump(partial_packet, "LCS not equal Lm ^ Ll, return") return False pkt_len = ord(partial_packet[0]) + ord(partial_packet[1])*256 pkt_frame_len = partial_packet[:3] partial_packet = partial_packet[3:] STATE = 2 if (len(partial_packet) >= pkt_len and STATE == 2): pkt_frame_data = partial_packet[:pkt_len] STATE = 3 if (len(partial_packet) == (pkt_len + 1) and STATE == 3): crc = crc8() val = crc.crc(pkt_frame_len + pkt_frame_data) if chr(val) != partial_packet[len(pkt_frame_data)]: print_err_dump(partial_packet, "Wrong CRC8 checksum") return False self._response = pkt_frame_data return True waiting = self._port.inWaiting() read_bytes = self._port.read(1 if waiting == 0 else waiting) if read_bytes == '' and (time_check - time_start) > self.RESPONSE_TIMEOUT: if (len(self._full_packet) == 0): print_err("ACK received but not response after %d" % (self.RESPONSE_TIMEOUT)) else: print_err_dump(self._full_packet, "Receive timeout after %d, receive: " % (self.RESPONSE_TIMEOUT)) return False for b in read_bytes: self._full_packet += b partial_packet += b
def spine_sw_up_0(pre_hop, cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): append_path(hash_str, cur_hop, paths) byte_cnt[cur_hop] += size link_byte_cnt[pre_hop + ' ' + cur_hop] += size port_num = 2 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop]) % port_num next_hop = port_list[cur_hop].split()[port] spine_sw_up_1(cur_hop, next_hop, ev, hash_str, size, byte_cnt, link_byte_cnt, paths)
def _encode_payload(self): data = self._encode_struct('>BBBLLQ', self._version, self._compatibility_version, int(self._material_unit), self._material_total, self._material_remaining, self._total_usage_duration) data = data[:19] + crc8(data[:19]).digest() return data[0:20]
def spine_sw(cur_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths): byte_cnt[cur_hop] += size port_num = 4 port = crc8(seeds[cur_hop], (hash_str), polys[cur_hop]) % port_num next_hop = port_list[cur_hop].split()[port] aggr_sw(cur_hop, next_hop, ev, hash_str, size, seeds, polys, port_list, byte_cnt, link_byte_cnt, paths)
def crc8(self, byte_frame): """ Calculate CRC8 with non standard init value :param byte_frame: list of bytes with entire frame :return: crc8 """ hash_crc8 = crc8.crc8(initial_start=0xFF) # non standard init value hash_crc8.update( byte_frame ) # CRC8 with beginning frame, without CRC and ending tags return hash_crc8.digest()
def _calcCrc(self, package, data): """Calculates the CRC8 for the given package and returns it.""" msg = bytearray() msg.extend(struct.pack("B", self.START_BYTE)) msg.extend(struct.pack("B", self.messageType)) msg.extend(struct.pack("H", self.commandType)) self._packData(msg, data) crc = crc8() return crc.crc(msg)
def test_copy(): crc = crc8() crc.update(b'asd') crc2 = crc.copy() assert crc2 != crc assert crc2.digest() == crc.digest() crc2.update(b"asd") assert crc2.digest() != crc.digest() crc.update(b"asd") assert crc2.digest() == crc.digest() assert crc2.copy() != crc
def get_checksum(self): """Updates byte fields and returns CRC-8 hash""" self.header_bytes = struct.pack("<iiii", self.frame_len, self.cmd, self.num_items, self.item_size) self.data_bytes = struct.pack( f"<{self.num_items}{'B' if self.item_size == 1 else 'i'}", *self.data) hasher = crc8.crc8() hasher.update(self.header_bytes + self.data_bytes) return hasher.digest()
def readreg_once(self, reg): if self.bus: hash = crc8.crc8() hash.update(chr(reg)) crc = hash.digest() self.bus.write_i2c_block_data(self.addr, reg, [ord(crc)]) data = self.bus.read_byte(self.addr) crc = self.bus.read_byte(self.addr) else: hash = crc8.crc8() hash.update(chr(reg)) crc = hash.digest() (count, i2cdata) = self.pi.bb_i2c_zip(self.sdaPin, (4, self.addr, # set addr to self.addr 2, 7, 2, reg, crc, # start, write two byte (reg, crc) 2, 6, 1, # (re)start, read one byte 2, 6, 1, # (re)start, read one byte 3, # stop 0)) # end if count<0: raise I2CError("i2c error") if count!=2: raise I2CError("i2c wrong byte count") data = i2cdata[0] crc = i2cdata[1] if (data == 0xFF) and (crc == 0xFF): raise ReceiveCRCError("receive crc error") if (data == 0xFF) and (crc == 0xFE): raise ReceiveSizeError("receive size error") if (data == 0xFF) and (crc == 0xFD): raise ReceiveUninitializedError("receive uninitialized error") hash = crc8.crc8() hash.update(chr(data)) if crc != ord(hash.digest()): raise CRCError("crc error, data=%2X, crc=%2X, localCrc=%X" % (data, crc, ord(hash.digest()))) return data
def SSCFrameEncoder(RFID: bytes, CartID: bytes, op: bytes = bytes([0]), opData: bytes = bytes([0, 0, 0, 0])): hash = crc8.crc8() assert (len(RFID) == 4) assert (len(CartID) == 3) assert (len(op) == 1) assert (len(opData) == 3) base = RFID + CartID + op + opData hash.update(base) return base + hash.digest()
def test_crc8_calculate(self): # Given data = [b'\x04', b'\x03', b'\xFB', b'\xAD', b'\xFF', b'\xBD'] expected_crc8 = b'\xBF' # When hash = crc8.crc8() for byte in data: hash.update(byte) # Then assert hash.digest() == expected_crc8
def test_get_normal_line(self, cache, machine, machine_bytes, last_line, get_line, line_number): if last_line: get_line.return_value = None assert cache.get(line_number + 1) is None get_line.return_value = [] is_last = cache.is_last(line_number) assert is_last == last_line machine.needle_positions_to_bytes.return_value = machine_bytes expected_line_bytes = bytes([line_number & 255]) + \ machine_bytes + bytes([last_line]) expected_line_bytes += crc8.crc8(expected_line_bytes).digest() line_bytes = cache.get_line_configuration_message(line_number) assert line_bytes == expected_line_bytes
def get_line_configuration_message(self, line_number): """Return the cnfLine content without id for the line. :param int line_number: the number of the line :rtype: bytes :return: a cnfLine message without id as defined in :ref:`cnfLine` """ if line_number not in self._line_configuration_message_cache: line_bytes = self.get_bytes(line_number) if line_bytes is not None: line_bytes = bytes([line_number & 255]) + line_bytes line_bytes += bytes([self.is_last(line_number)]) line_bytes += crc8(line_bytes).digest() self._line_configuration_message_cache[line_number] = line_bytes del line_bytes line = self._line_configuration_message_cache[line_number] if line is None: # no need to cache a lot of empty lines line = (bytes([line_number & 255]) + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01') line += crc8(line).digest() return line
def callback(self): id = int(self.NodeId.get()) name = self.devName.get() #|0|msglen|nodeid|name n bytes|CRC| msgLen = len(name) if( msgLen == 0): return msgLen += 3 data = chr(msgLen) data += chr(id)+name crc = crc8.crc8(data) data += chr(crc) print data print "MsgLen: %d and CRC:%x"%(msgLen,crc) self.port.send(chr(0))#begin of msg self.port.send(data)
def calculate(self, src_data = None): if src_data == None: return self.dst_data src_data = bytearray(src_data) src_data.append(crc8.crc8(src_data)) dst_data = [] dst_data.append(self._flag) dst_data.append(self._base + len(src_data)*2 ) last_nibble = 0 for i in range(len(src_data)): now_nibble = int(src_data[i]) >> 4 dst_data.append( self._base + ( (((i * 2) ^ last_nibble) << 4) | now_nibble)) last_nibble = now_nibble now_nibble = int(src_data[i]) & 0x0f dst_data.append( self._base + ( (((i * 2 + 1) ^ last_nibble) << 4) | now_nibble)) last_nibble = now_nibble return dst_data
def test_performance(msg): '''news = wowmessage_pb2.news() news.needResponse = True #bool(random.randint(0,1)) news.message = msg news.len = len(msg) news_str = news.SerializeToString()''' #use json dic = {"needResponse":True, "message": msg, "len": len(msg)} news_str = json.dumps(dic) c=crc8.crc8() crc_str = c.crc8_data(news_str) with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s: s.connect((HOST, PORT)) s.sendall(crc_str) print('send data:%s to lserver' % (msg,)) if dic['needResponse']: s.settimeout(2) buf=s.recv(1024) print "client recv data: %s" %(c.reverse_crc8_data(buf))
def send_data(self,sensor,val,address,port): try: value = int(val) except ValueError: value = 50 try: proxy_port = int(port) except ValueError: proxy_port = 77777 try: i = int(sensor) except ValueError: i = 0 crc = crc8() types = (0x81,0x82,0x83,0x84,0x85,0x86) type = 0x81 if ((i>0)and(i<7)): type = types[i-1] c = crc.crc(chr(type) + chr((value & 0xff)) + chr(((value >> 8) & 0xff))) #print hex(c) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((address,proxy_port)) s.send(chr(type) + chr((value & 0xff)) + chr(((value >> 8) & 0xff)) + chr(c)) return """<html><body>OK!</body></html>"""
def test_update123(): crc = crc8() crc.update(b"123") assert crc.digest() == CRC8_123 assert crc.hexdigest() == CRC8_123_HEX
def test_update(): crc = crc8() crc.update(b"abc") assert crc.digest() == CRC8_ABC
def test_string_accepted(): crc = crc8() crc.update("abc") assert crc.digest() == CRC8_ABC
def main(argv): # Interpret parameters sensorConfig = "" hexFile = "../../build/artifacts/smartsensor_fw/opt/smartsensor_fw.hex" helpText = (argv[0] if len(argv)>0 else "generate.py") + \ " [-d] [-i <hex-file>] <sensor-type>" helpMore = "Supported sensor types:\n\t" + ", ".join(ss_type.allTypes()) try: opts, args = getopt.getopt(argv[1:],"hdi:") except getopt.GetoptError: print helpText sys.exit(2) for opt, arg in opts: if opt == '-h': print helpText print helpMore sys.exit() elif opt == "-i": hexFile = arg elif opt == "-d": if len(args)>0: try: ss_type.descriptor(args[0]) sys.exit(0) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) else: sys.exit("Enter a sensor type\n"+helpMore) if len(args)==0: print helpText print helpMore sys.exit(2) else: sensorConfig = args[0] try: descriptor = ss_type.descriptor(sensorConfig) except KeyError: sys.exit(args[0]+" is not a valid sensor type.\n"+helpMore) # Decide the new sensor's ID try: firstType = descriptor["channels"][0]["type"] except IndexError: firstType = 0xFF # TODO(nikita): Proper ID generation idNew = array('B', [0, 0, 0, 0, 0, firstType, random.randint(0,255), random.randint(0,255), firstType]) # Create the new sensor's descriptor channelsStr = b"" for channel in descriptor["channels"]: # Pack each channel packer = struct.Struct( "<B%upB%us"%(len(channel["description"])+1,len(channel["additional"]))) channelsStr += packer.pack( packer.size, channel["description"], channel["type"], channel["additional"].tostring()) packer = struct.Struct( "<H%upBBB%usB"%(len(descriptor["description"])+1,len(channelsStr))) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, 0xC8) crc = crc8(0, array('B', descriptorStr)) descriptorStr = packer.pack( packer.size, descriptor["description"], descriptor["chunksNumer"], descriptor["chunksDenom"], len(descriptor["channels"]), channelsStr, crc) descriptorNew = array('B', descriptorStr) # Write the ID and descriptor to the hex file descriptorPlaceholder = \ b"Do not change this string. It is a placeholder that is replaced in the " + \ b"compiled hex file when the deploy script is run." idPlaceholder = "SENSORID" ih = IntelHex(hexFile) ihDict = ih.todict() ihArr = array('B', [ihDict[key] for key in sorted(ihDict)]) ihString = ihArr.tostring() try: descriptorIndex = ihArr.tostring().index(descriptorPlaceholder) except ValueError: sys.exit('Error: Descriptor placeholder not found in hex file.') try: idIndex = ihArr.tostring().index(idPlaceholder) except ValueError: sys.exit('Error: ID placeholder not found in hex file.') descriptorDict = {descriptorIndex+i: descriptorNew[i] for i in range(len(descriptorNew))} idDict = {idIndex+i: idNew[i] for i in range(len(idNew))} ihDict = dict(ihDict.items()+descriptorDict.items()+idDict.items()) newIh = IntelHex() newIh.fromdict(ihDict) newIh.tofile(sys.stdout, format='hex') # Print new hex file to stdout
def test_initialize_with_bytes(): assert crc8(b'123').digest() == CRC8_123
def test_initial_hexdigest(): assert crc8().hexdigest() == CRC8_INITIAL_HEX
def test_initial_digest(): assert crc8().digest() == CRC8_INITIAL
def test_update_split(): crc = crc8() crc.update(b"a") crc.update(b"bc") assert crc.digest() == CRC8_ABC assert crc.hexdigest() == CRC8_ABC_HEX
def test_block_size(): assert crc8().block_size == 1
def test_digest_size(): assert crc8().digest_size == 1