TPM Command CreatePrimary UEFI App - tpm

I'm trying to implement a UEFI App for the CreatePrimary TPM Command.
i understand i need to pack the command parameters in a canonical way and swap the byte order to Big Endiann.
Still i get the an error response code for some reason.
what am i missing here?
CreatePrimaryCmd()
{
EFI_STATUS Status = EFI_SUCCESS;
EFI_TREE_PROTOCOL *TreeProtocol;
TPM2_CreatePrimary_COMMAND CreatePrimary_cmd;
TPM2_CreatePrimary_RESPONSE CreatePrimary_ret;
UINT32 i;
UINT32 CmdSize;
UINT8 *Buffer;
UINT8 *AuthSizeOffset;
UINT16 *SizeOffset;
TPM2B_AUTH NewAuth;
Status = gBS->LocateProtocol( &gEfiTreeProtocolGuid,
NULL,
(VOID **) &TreeProtocol);
if (EFI_ERROR (Status)) {
DebugPrint(EFI_D_ERROR,"Failed to locate EFI_TREE_PROTOCOL [%r]\n", Status);
return Status;
}
NewAuth.size = 0;
Tpm2HierarchyChangeAuth (TPM_RH_OWNER, NULL, &NewAuth);
ZeroMem(&CreatePrimary_cmd, sizeof(CreatePrimary_cmd));
CreatePrimary_cmd.Header.tag = (TPMI_ST_COMMAND_TAG)SwapBytes16(TPM_ST_SESSIONS);
CreatePrimary_cmd.Header.commandCode = TPM_H2NL(TPM_CC_CreatePrimary);
Buffer = (UINT8 *)&CreatePrimary_cmd.Header.commandCode;
Buffer += sizeof(UINT32);
//PrimaryHandle
*(UINT32 *)Buffer = TPM_H2NL(TPM_RH_OWNER);
Buffer += sizeof(UINT32);
//
// Add in Auth session
//
AuthSizeOffset = Buffer;
*(UINT32 *)Buffer = 0;
Buffer += sizeof(UINT32);
// authHandle
*(UINT32 *)Buffer = TPM_H2NL(TPM_RS_PW);
Buffer += sizeof(UINT32);
// nonce = nullNonce
*(UINT16 *)Buffer = 0;
Buffer += sizeof(UINT16);
// sessionAttributes = 0
*(UINT8 *)Buffer = 0;
Buffer += sizeof(UINT8);
// auth = nullAuth
*(UINT16 *)Buffer = 0;
Buffer += sizeof(UINT16);
// authorizationSize
*(UINT32 *)AuthSizeOffset = TPM_H2NL((UINT32)(Buffer - AuthSizeOffset - sizeof(UINT32)));
//InSensitive.size
*(UINT16 *)Buffer = TPM_H2NS(2);
Buffer += sizeof(UINT16);
//sensitive.userAuth.size
*(UINT16 *)Buffer = TPM_H2NS(0);
Buffer += sizeof(UINT16);
//sensitive.data.keySize
*(UINT16 *)Buffer = TPM_H2NS(0);
Buffer += sizeof(UINT16);
//InPublic.size will be set later
SizeOffset = (UINT16 *)Buffer;
Buffer += sizeof(UINT16);
//InPublic.publicArea.type
*(UINT16 *)Buffer = TPM_H2NS(TPM2_ALG_RSA);
Buffer += sizeof(UINT16);
//publicArea.nameAlg
*(UINT16 *)Buffer = TPM_H2NS(TPM2_ALG_SHA1);
Buffer += sizeof(UINT16);
/*
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.stClear= CLEAR;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.fixedTPM = CLEAR;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.fixedParent = CLEAR;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.sensitiveDataOrigin = SET;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.userWithAuth = SET;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.adminWithPolicy = CLEAR;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.noDA = SET;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.restricted = SET;
CreatePrimary_cmd.InPublic.publicArea.objectAttributes.decrypt = SET;
*/
//publicArea.objectAttributes
*(UINT32 *)Buffer = TPM_H2NL(0x30460);
Buffer += sizeof(UINT32);
//publicArea.authPolicy.size
*(UINT16 *)Buffer = 0;
Buffer += sizeof(UINT16);
//InPublic.publicArea.parameters.rsaDetail.symmetric.algorithm
*(UINT16 *)Buffer = TPM_H2NS(TPM2_ALG_AES);
Buffer += sizeof(UINT16);
//InPublic.publicArea.parameters.rsaDetail.symmetric.keyBits
*(UINT16 *)Buffer = TPM_H2NS(48);
Buffer += sizeof(UINT16);
//publicArea.parameters.rsaDetail.symmetric.mode
*(UINT16 *)Buffer = TPM_H2NS(TPM2_ALG_CFB);
Buffer += sizeof(UINT16);
//InPublic.publicArea.parameters.rsaDetail.scheme.scheme
*(UINT16 *)Buffer = TPM_H2NS(TPM2_ALG_NULL);
Buffer += sizeof(UINT16);
//InPublic.publicArea.parameters.rsaDetail.keyBits
*(UINT16 *)Buffer = TPM_H2NS(48);
Buffer += sizeof(UINT16);
//InPublic.publicArea.parameters.rsaDetail.exponent
*(UINT32 *)Buffer = TPM_H2NL(0);
Buffer += sizeof(UINT32);
//InPublic.publicArea.unique.rsa.keySize
*(UINT16 *)Buffer = 0;
Buffer += sizeof(UINT16);
//InPublic.size
*SizeOffset = TPM_H2NS(((UINT16)((UINT16*)Buffer - SizeOffset - sizeof(UINT16))));
//OutsideInfo.size
*(UINT16 *)Buffer = TPM_H2NS(1);
Buffer += sizeof(UINT16);
//OutsideInfo.buffer
*(UINT8 *)Buffer = 0;
Buffer += sizeof(UINT8);
//CreationPCR.count
*(UINT32 *)Buffer = 0;
Buffer += sizeof(UINT32);
//CreatePrimary_cmd.CreationPCR.pcrSelections.hash
CmdSize = (UINT32)(Buffer - (UINT8*)&CreatePrimary_cmd);
DebugPrint(EFI_D_ERROR,"CmdSize [0x%x]\n",CmdSize);
CreatePrimary_cmd.Header.paramSize = TPM_H2NL(CmdSize);
printbuffer((UINT8*)&CreatePrimary_cmd,CmdSize);
Status = TreeProtocol->SubmitCommand( TreeProtocol,
CmdSize,
(UINT8*)&CreatePrimary_cmd,
sizeof (CreatePrimary_ret),
(UINT8*)&CreatePrimary_ret);
if (EFI_ERROR (Status)) {
DebugPrint(EFI_D_ERROR,"Failed to SubmitCommand [%d]\n", Status);
return Status;
}
DebugPrint(EFI_D_ERROR,"\nCreatePrimary_ret.Header.paramSize [0x%08x]\n", SwapBytes32(CreatePrimary_ret.Header.paramSize));
DebugPrint(EFI_D_ERROR,"CreatePrimary_ret.Header.responseCode [0x%08x]\n", SwapBytes32(CreatePrimary_ret.Header.responseCode));
DebugPrint(EFI_D_ERROR,"CreatePrimary_ret.Header.tag [0x%04x]\n", SwapBytes16(CreatePrimary_ret.Header.tag));
DebugPrint(EFI_D_ERROR,"CreatePrimary_ret.ObjectHandle [0x%08x]\n", SwapBytes32(CreatePrimary_ret.ObjectHandle));
DebugPrint(EFI_D_ERROR,"CreatePrimary_cmd.InPublic.publicArea.unique.rsa.size) [0x%08x]\n", SwapBytes16(CreatePrimary_cmd.InPublic.publicArea.unique.rsa.keySize));
DebugPrint(EFI_D_ERROR,"RSA Key\n");
for( i = 0 ; i < 256 ; ++i)
{
DebugPrint(EFI_D_ERROR,"%02x", CreatePrimary_cmd.InPublic.publicArea.unique.rsa.key[i]);
}
DebugPrint(EFI_D_ERROR,"\n");
return Status;
}
The Response printouts:
80 02 00 00 00 44 00 00 01 31 40 00 00 01 00 00
00 09 40 00 00 09 00 00 00 00 00 00 02 00 00 00
00 00 0C 00 01 00 04 00 03 04 60 00 00 00 06 00
30 00 43 00 10 00 30 00 00 00 00 00 00 00 01 00
00 00 00 00
CreatePrimary_ret.Header.paramSize [0x0000000A]
CreatePrimary_ret.Header.responseCode [0x000001D5]
CreatePrimary_ret.Header.tag [0x8001]
CreatePrimary_ret.ObjectHandle [0x00000000]
CreatePrimary_cmd.InPublic.publicArea.unique.rsa.size) [0x00000000]

Related

NRF24L01 issue with Raspberry Pi and Raspberry Pi Pico

I've tried to communicate my tiny Raspberry Pi Zero 2W and Raspberry Pi Pico with NRF24L01. After my researchs and tryings I decided to the projects on the internet usualy not working. After sifting through alternatives and libraries, I decided to use lib_nrf24 library at Raspberry Pi and nrf24l01.py library at Raspberry Pi Pico. When I look carefully, I saw the libraries very similar with variable names. There is some configuration parameters both of them. I tried to set the parameters in the same way in both files. And I created a sender code on Raspberry Pi Pico and create basic receiver code at Raspberry Pi Zero 2W. But it didn't work. How can I solve this issue?
Raspberry Pi Pico Code:
from machine import Pin, SPI
import struct
import time
from nrf24l01 import NRF24L01
csn = Pin(15, mode=Pin.OUT, value=1)
ce = Pin(14, mode=Pin.OUT, value=0)
pipes = (b"\xf1\xf1\xf0\xf0\xfe0", b"\xe0\xe0\xf1\xf1\xe0")
def setup():
nrf = NRF24L01(SPI(0), csn, ce, payload_size=6)
nrf.open_tx_pipe(pipes[0])
nrf.open_rx_pipe(1, pipes[1])
nrf.start_listening()
return nrf
def dataSend(nrf):
while True:
testValue = 5
print("Mesafe: ", distance, "cm")
try:
nrf.send(struct.pack("i", distance))
time.sleep(0.1)
except OSError:
print('message lost')
def auto_ack(nrf):
nrf.reg_write(0x01, 0b11111000) # enable auto-ack on all pipes
nrf = setup()
auto_ack(nrf)
dataSend(nrf)
Raspberry Pi Zero 2W Code:
import RPi.GPIO as GPIO
import time
import spidev
from lib_nrf24 import NRF24
GPIO.setmode(GPIO.BCM)
pipes = [[0xE0, 0xE0, 0xF1, 0xF1, 0xE0], [0xF1, 0xF1, 0xF0, 0xF0, 0xE0]]
radio = NRF24(GPIO,spidev.SpiDev())
radio.begin(0, 25)
radio.setPayloadSize(32)
radio.setChannel(0x05)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)
radio.openReadingPipe(1, pipes[0])
radio.printDetails()
while len(sendMessage) < 32:
sendMessage.append(0)
while True:
start = time.time()
radio.startListening()
while not radio.available(0):
time.sleep(1/100)
if time.time() - start > 2:
print("Timed out.")
break
radio.stopListening()
time.sleep(3)
Except thoose codes, when thoose codes not working I've changed some parameters in library files both of them.
**Parameters of nrf24l01.py library at Raspberry Pi Pico:
**
# nRF24L01+ registers
CONFIG = const(0x00)
EN_RXADDR = const(0x02)
SETUP_AW = const(0x03)
SETUP_RETR = const(0x04)
RF_CH = const(0x05)
RF_SETUP = const(0x06)
STATUS = const(0x07)
RX_ADDR_P0 = const(0x0A)
TX_ADDR = const(0x10)
RX_PW_P0 = const(0x11)
FIFO_STATUS = const(0x17)
DYNPD = const(0x1C)
# CONFIG register
EN_CRC = const(0x08) # enable CRC
CRCO = const(0x04) # CRC encoding scheme; 0=1 byte, 1=2 bytes
PWR_UP = const(0x02) # 1=power up, 0=power down
PRIM_RX = const(0x01) # RX/TX control; 0=PTX, 1=PRX
# RF_SETUP register
POWER_0 = const(0x00) # -18 dBm
POWER_1 = const(0x02) # -12 dBm
POWER_2 = const(0x04) # -6 dBm
POWER_3 = const(0x06) # 0 dBm
SPEED_1M = const(0x00)
SPEED_2M = const(0x08)
SPEED_250K = const(0x20)
# STATUS register
RX_DR = const(0x40) # RX data ready; write 1 to clear
TX_DS = const(0x20) # TX data sent; write 1 to clear
MAX_RT = const(0x10) # max retransmits reached; write 1 to clear
# FIFO_STATUS register
RX_EMPTY = const(0x01) # 1 if RX FIFO is empty
# constants for instructions
R_RX_PL_WID = const(0x60) # read RX payload widthx"
R_RX_PAYLOAD = const(0x61) # read RX payload
W_TX_PAYLOAD = const(0xA0) # write TX payload
FLUSH_TX = const(0xE1) # flush TX FIFO
FLUSH_RX = const(0xE2) # flush RX FIFO
NOP = const(0xFF) # use to read STATUS register
**Parameters of lib_nrf24.py library at Raspberry Pi Zero2W:
**
MAX_CHANNEL = 127
MAX_PAYLOAD_SIZE = 32
# PA Levels
PA_MIN = 0
PA_LOW = 1
PA_HIGH = 2
PA_MAX = 3
PA_ERROR = 4
# Bit rates
BR_1MBPS = 0
BR_2MBPS = 1
BR_250KBPS = 2
# CRC
CRC_DISABLED = 0
CRC_8 = 1
CRC_16 = 2
CRC_ENABLED = 3
# Registers
CONFIG = 0x00
EN_AA = 0x01
EN_RXADDR = 0x02
SETUP_AW = 0x03
SETUP_RETR = 0x04
RF_CH = 0x05
RF_SETUP = 0x06
STATUS = 0x07
OBSERVE_TX = 0x08
CD = 0x09
RX_ADDR_P0 = 0x0A
RX_ADDR_P1 = 0x0B
RX_ADDR_P2 = 0x0C
RX_ADDR_P3 = 0x0D
RX_ADDR_P4 = 0x0E
RX_ADDR_P5 = 0x0F
TX_ADDR = 0x10
RX_PW_P0 = 0x11
RX_PW_P1 = 0x12
RX_PW_P2 = 0x13
RX_PW_P3 = 0x14
RX_PW_P4 = 0x15
RX_PW_P5 = 0x16
FIFO_STATUS = 0x17
DYNPD = 0x1C
FEATURE = 0x1D
# Bit Mnemonics */
MASK_RX_DR = 6
MASK_TX_DS = 5
MASK_MAX_RT = 4
EN_CRC = 3
CRCO = 2
PWR_UP = 1
PRIM_RX = 0
ENAA_P5 = 5
ENAA_P4 = 4
ENAA_P3 = 3
ENAA_P2 = 2
ENAA_P1 = 1
ENAA_P0 = 0
ERX_P5 = 5
ERX_P4 = 4
ERX_P3 = 3
ERX_P2 = 2
ERX_P1 = 1
ERX_P0 = 0
AW = 0
ARD = 4
ARC = 0
PLL_LOCK = 4
RF_DR = 3
RF_PWR = 6
RX_DR = 6
TX_DS = 5
MAX_RT = 4
RX_P_NO = 1
TX_FULL = 0
PLOS_CNT = 4
ARC_CNT = 0
TX_REUSE = 6
FIFO_FULL = 5
TX_EMPTY = 4
RX_FULL = 1
RX_EMPTY = 0
DPL_P5 = 5
DPL_P4 = 4
DPL_P3 = 3
DPL_P2 = 2
DPL_P1 = 1
DPL_P0 = 0
EN_DPL = 2
EN_ACK_PAY = 1
EN_DYN_ACK = 0
# Instruction Mnemonics
R_REGISTER = 0x00
W_REGISTER = 0x20
REGISTER_MASK = 0x1F
ACTIVATE = 0x50
R_RX_PL_WID = 0x60
R_RX_PAYLOAD = 0x61
W_TX_PAYLOAD = 0xA0
W_ACK_PAYLOAD = 0xA8
FLUSH_TX = 0xE1
FLUSH_RX = 0xE2
REUSE_TX_PL = 0xE3
NOP = 0xFF
I changed the library parameters to be the same but still could not communicate between the two devices. I used different values with these parameters to understand where the problem is, for example, I changed the receiver and sender pipe values by crossing each other, but it still didn't work. I think the codes work well but my library RF configuration parameters are false.

azure tts use go sdk generate in stream to wav less 46 byte

i use this samplehttps://github.com/Microsoft/cognitive-services-speech-sdk-go/blob/1af83b0cf8fb/samples/synthesizer/to_audio_data_stream.go
and i wirte byte to file and i find file cant open
stream.SaveToWavFileAsync("fun.wav")
//use this func can save a file which can open
output
Synthesis started.
Synthesizing, audio chunk size 65582.
Synthesizing, audio chunk size 294510.
Synthesizing, audio chunk size 56446.
Synthesizing, audio chunk size 65582.
Synthesizing, audio chunk size 1710.
Synthesized, audio length 483646.
Read [483600] bytes from audio data stream.
the stream less 46 bytes
pcm need add wav head.
func PcmToWav(dst []byte, numChannel int, sampleRate int) (resDst []byte) {
byteDst := dst
longSampleRate := sampleRate
byteRate := 16 * sampleRate * numChannel / 8
totalAudioLen := len(byteDst)
totalDataLen := totalAudioLen + 36
var header = make([]byte, 44)
// RIFF/WAVE header
header[0] = 'R'
header[1] = 'I'
header[2] = 'F'
header[3] = 'F'
header[4] = byte(totalDataLen & 0xff)
header[5] = byte((totalDataLen >> 8) & 0xff)
header[6] = byte((totalDataLen >> 16) & 0xff)
header[7] = byte((totalDataLen >> 24) & 0xff)
//WAVE
header[8] = 'W'
header[9] = 'A'
header[10] = 'V'
header[11] = 'E'
// 'fmt ' chunk
header[12] = 'f'
header[13] = 'm'
header[14] = 't'
header[15] = ' '
// 4 bytes: size of 'fmt ' chunk
header[16] = 16
header[17] = 0
header[18] = 0
header[19] = 0
// format = 1
header[20] = 1
header[21] = 0
header[22] = byte(numChannel)
header[23] = 0
header[24] = byte(longSampleRate & 0xff)
header[25] = byte((longSampleRate >> 8) & 0xff)
header[26] = byte((longSampleRate >> 16) & 0xff)
header[27] = byte((longSampleRate >> 24) & 0xff)
header[28] = byte(byteRate & 0xff)
header[29] = byte((byteRate >> 8) & 0xff)
header[30] = byte((byteRate >> 16) & 0xff)
header[31] = byte((byteRate >> 24) & 0xff)
// block align
header[32] = byte(2 * 16 / 8)
header[33] = 0
// bits per sample
header[34] = 16
header[35] = 0
//data
header[36] = 'd'
header[37] = 'a'
header[38] = 't'
header[39] = 'a'
header[40] = byte(totalAudioLen & 0xff)
header[41] = byte((totalAudioLen >> 8) & 0xff)
header[42] = byte((totalAudioLen >> 16) & 0xff)
header[43] = byte((totalAudioLen >> 24) & 0xff)
resDst = append(header, dst...)
return
}

How to calculate tcp packet checksum correctly?

I am trying to implement a checksum calculation algorithm using this link
Here is an example of a byte slice and checksums for it.
And also my implementation code, tell me what I'm doing wrong.
//https://gist.github.com/david-hoze/0c7021434796997a4ca42d7731a7073a
func chksum(iph *ipv4.Header,payload []byte)uint16{
// https://github.com/mikioh/-stdyng/blob/master/afpacket.go
var htons = func(i uint16) uint16 {return (i<<8)&0xff00 | i>>8}
tcpLen := iph.TotalLen - iph.Len
src := iph.Src
dst := iph.Dst
var csum uint32
for i := 0; i < 16; i += 2 {
csum += uint32(src[i]) << 8
csum += uint32(src[i+1])
csum += uint32(dst[i]) << 8
csum += uint32(dst[i+1])
}
csum += uint32(htons(6)) // TCP PROTO
csum += uint32(htons(uint16(tcpLen)))
// old chksum
payload[16] = 0
payload[17] = 0
var i int
for tcpLen > 1 {
csum += uint32(payload[i]) << 8
csum += uint32(payload[i+1])
tcpLen -= 2
i++
}
if tcpLen % 2 == 1 {
csum += uint32(payload[tcpLen - 1]) << 8
}
for csum > 0xffff{
csum = (csum >> 16) + (csum & 0xffff)
}
return ^uint16(csum)
}
// output
[69 0 0 60 179 32 64 0 64 6 108 0 192 168 77 61 192 168 77 13 203 50
0 22 69 21 146 157 0 0 0 0 160 194 250 240 65 21 0 0 2 4 5 180 4 2 8
10 38 105 38 58 0 0 0 0 1 3 3 7]
src chkSumOriginaltcp = 0x4115 calc chkSumFaketcp = 0x72e8
Please tell me where I could be mistaken, it is very important to me
func chksum(data []byte, srcip, dstip []byte) uint16 {
data[16],data[17] = 0,0 //zero on original check sum
psheader := []byte{
srcip[0], srcip[1], srcip[2], srcip[3],
dstip[0], dstip[1], dstip[2], dstip[3],
0,
6, // TCP
0, byte(len(data)), // length (16 bits)
}
csum := make([]byte, 0, len(psheader)+len(data))
csum = append(csum, psheader...)
csum = append(csum, data...)
lenSumThis := len(csum)
var word uint16
var sum uint32
for i := 0; i+1 < lenSumThis; i += 2 {
word = uint16(csum[i])<<8 | uint16(csum[i+1])
sum += uint32(word)
}
if lenSumThis%2 != 0 {
sum += uint32(csum[len(csum)-1])
}
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
return uint16(^sum)
}

Concox GT800 / Wetrack800 GPS device data decoding

I'm using twisted python tcp server
I encoded the byte string with
byte.hex()
data_1 = 78 78 11 01 0 XXXXXXXXXXXXXXX 80 00 21 21 00 00 38 54 0d0a
data_2 = 78 78 11 01 0 XXXXXXXXXXXXXXX 80 00 21 21 00 32 2a c5 0d0a
7878 -> Start bit
11 -> Packet length
01 -> Protocol Number
XX..XX -> IMEI
0d0a -> End bit
I find problem in decoding this part 8000212100322ac5 according to their documentation its a login packet and I should send some response to it.
For C# GPS Socket communication (CONCOX)
I'm in need of algorithm or a decoding method in python
For GT-800 this i think this will help you
class TcpGpsReceiver(protocol.Protocol):
""" Event driven callback handler
"""
def __init__(self):
"""Constructor
"""
self.imei_no = ''
def gt_800(self, decoded_data):
""" Decode the GT-800 Device Data
"""
if decoded_data[4:6].decode() == '11': # Check if login
print('Login')
self.imei_no = decoded_data[9:24]
data = codecs.decode('7878050100059FF80D0A', encoding='hex', errors='strict')
self.transport.write(data)
if decoded_data[4:6].decode().upper() == '0A':
print('Heat beat received')
serial_number = hex(int(decoded_data[18:22], 16))[2:]
data = codecs.decode('78780513{}670E0D0A'.format(get_serial_number(serial_number)),
encoding='hex', errors='strict')
print(decoded_data[18:22], ' -> serial number')
self.transport.write(data)
if decoded_data[4:6].decode() == '22':
print('Decoding')
s_no = hex(int(decoded_data[66:70], 16))[2:]
date_time = decoded_data[8:20]
latitude = int(decoded_data[23:30], 16) / 1800000
longitude = int(decoded_data[31:38], 16) / 1800000
timestamp = datetime(year=int(date_time[0:2], 16),
month=int(date_time[2:4], 16),
day=int(date_time[4:6], 16),
hour=int(date_time[6:8], 16),
minute=int(date_time[8:10], 16),
second=int(date_time[10:12], 16)).strftime('%Y-%m-%d %H:%M:%S')
location = dict(device_id=self.imei_no.decode(), imei=self.imei_no.decode(), timestamp=timestamp,
location=[latitude, longitude],
speed=0, course=0, state=0, altitude=0)
print(location)
# Code to access location data
self.imei_no = ''
self.transport.loseConnection()
if decoded_data[6:8].decode().upper() == '8A':
print('Date time requested')
s_no = hex(int(decoded_data[8:12], 16))[2:]
now = datetime.now()
month_hex = '0' + hex(now.month)[2:]
print(decoded_data[12:16], hex(int(decoded_data[12:16], 16))[2:])
date_string = '{}{}{}{}{}{}{}{}'.format(hex(int(str(now.year)[2:]))[2:], month_hex, return_date_hex(now.day),
return_date_hex(now.hour), return_date_hex(now.minute),
return_date_hex(now.second),
get_serial_number(s_no), get_serial_number(hex(int(decoded_data[12:16],
16))[2:]))
print(date_string)
data = codecs.decode('78780B8A{}0D0A'.format(date_string), encoding='hex', errors='strict')
self.transport.write(data)
def dataReceived(self, data):
""" Called when data is received across a transport
"""
decoded_data = codecs.encode(data, encoding='hex', errors='strict')
print(datetime.now())
self.gt_800(decoded_data)
def get_serial_number(s_no):
"""Decoding serial No
"""
if len(s_no) == 1:
return '000' + s_no
if len(s_no) == 2:
return '00' + s_no
if len(s_no) == 3:
return '0' + s_no
if len(s_no) > 4:
return '0000'
return s_no
def retrun_date_hex(data):
print(data)
if len(str(hex(data)[2:])) == 2:
return hex(data)[2:]
else:
return '0' + hex(data)[2:]
class TcpGpsReceiverFactory(protocol.Factory):
""" Persistent configuration information, inherits from protocol.Factory
"""
def buildProtocol(self, addr):
""" Creates a protocol for each new connection
"""
return TcpGpsReceiver()
if _name_ == '_main_':
# Called when the module ran directly
reactor.listenTCP(10206, TcpGpsReceiverFactory())
reactor.run()

How can I find the alphabetic position of the letters in a word and then add the numbers up?

I wrote some of the code which gives me the total of the word with the position of the English alphabet but I am looking for something that prints the line like this:
book: 2 + 15 + 15 + 11 = 43
def convert(string):
sum = 0
for c in string:
code_point = ord(c)
location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
sum += location + 1
return sum
print(convert('book'))
def convert(string):
parts = []
sum = 0
for c in string:
code_point = ord(c)
location = code_point - 65 if code_point >= 65 and code_point <= 90 else code_point - 97
sum += location + 1
parts.append(str(location + 1))
return "{0}: {1} = {2}".format(string, " + ".join(parts), sum)
print(convert('book'))
Heres the output:
book: 2 + 15 + 15 + 11 = 43
More info on string.format and string.join.

Resources