1 
2 #include "stdafx.h"
3 #include "1WireCommon.h"
4 
5 // str is the family hex code "ff"
ToFamily(const std::string & str)6 _e1WireFamilyType ToFamily(const std::string& str)
7 {
8 	if (str.length() > 2)
9 		return _e1WireFamilyTypeUnknown;
10 
11 	unsigned int xID;
12 	std::stringstream ss;
13 	ss << std::hex << str;
14 	if (!(ss >> xID))
15 		return _e1WireFamilyTypeUnknown;
16 
17 	return (_e1WireFamilyType)xID;
18 }
19 
DeviceIdToByteArray(const std::string & deviceId,unsigned char * byteArray)20 void DeviceIdToByteArray(const std::string& deviceId,/*out*/unsigned char* byteArray)
21 {
22 	std::string str = deviceId;
23 	if (str.length() < (2 * DEVICE_ID_SIZE))
24 	{
25 		size_t fillupSize = (2 * DEVICE_ID_SIZE) - str.length();
26 		str.insert(0, fillupSize, '0');
27 	}
28 
29 	for (unsigned int idx = 0; idx < DEVICE_ID_SIZE; idx++)
30 	{
31 		std::stringstream ss;
32 		uint32_t i;
33 		ss << std::hex << str.substr(2 * idx, 2);
34 		if (!(ss >> i))
35 			byteArray[DEVICE_ID_SIZE - idx - 1] = 0;
36 		byteArray[DEVICE_ID_SIZE - idx - 1] = (uint8_t)i;
37 	}
38 }
39 
ByteArrayToDeviceId(const unsigned char * byteArray)40 std::string ByteArrayToDeviceId(const unsigned char* byteArray)
41 {
42 	std::stringstream sID;
43 	for (size_t idx = DEVICE_ID_SIZE; idx > 0; idx--)
44 		sID << std::hex << std::uppercase << std::setw(2) << std::setfill('0') << (unsigned int)byteArray[idx - 1];
45 	return sID.str();
46 }
47 
w1_crc16_update(unsigned short crc,unsigned char a)48 unsigned short w1_crc16_update(unsigned short crc, unsigned char a)
49 {
50 	crc ^= a;
51 	for (int i = 0; i < 8; ++i)
52 	{
53 		if (crc & 1)
54 			crc = (crc >> 1) ^ 0xA001;
55 		else
56 			crc = (crc >> 1);
57 	}
58 
59 	return crc;
60 }
61 
Crc16(const unsigned char * byteArray,size_t arraySize)62 unsigned char Crc16(const unsigned char* byteArray, size_t arraySize)
63 {
64 	unsigned short crc16 = 0;
65 	for (size_t i = 0; i < arraySize; i++)
66 		crc16 = w1_crc16_update(crc16, byteArray[i]);
67 	return (~crc16) & 0xFF;
68 }
69