import struct import time from .BxCmd import baseBxCmd from .BxCmdCode import CMD_SYSTEM_CLOCK_CORRECT from .BxUtils import BIN2Uint64 class CmdSystemClockCorrect(baseBxCmd): def __init__(self, t): super().__init__(CMD_SYSTEM_CLOCK_CORRECT.group, CMD_SYSTEM_CLOCK_CORRECT.code) self.sysTime = t # 转换为BCD码 year = BIN2Uint64(Uint2BCD(t.tm_year, False), '<') month = BIN2Uint64(Uint2BCD(t.tm_mon, False), '<') day = BIN2Uint64(Uint2BCD(t.tm_mday, False), '<') hour = BIN2Uint64(Uint2BCD(t.tm_hour, False), '<') minute = BIN2Uint64(Uint2BCD(t.tm_min, False), '<') second = BIN2Uint64(Uint2BCD(t.tm_sec, False), '<') week = BIN2Uint64(Uint2BCD(t.tm_wday + 1, False), '<') # tm_wday是0-6,对应周一到周日,这里转换为1-7 if week == 0: week = 7 self.year = int(year) self.month = int(month) self.day = int(day) self.hour = int(hour) self.minute = int(minute) self.second = int(second) self.week = int(week) def Build(self): result = bytearray() # 写入命令组 result.append(self.Group()) # 写入命令 result.append(self.Cmd()) # 写入响应标志 result.append(self.ReqResp()) # 写入保留值 result.append(0x00) result.append(0x00) # 写入年份(BCD码) y = bytearray([ self.year & 0xff, (self.year >> 8) & 0xff, (self.year >> 16) & 0xff, (self.year >> 24) & 0xff, ]) if y[0] == 0x00 and y[1] == 0x00: result.append(y[2]) result.append(y[3]) else: result.append(y[0]) result.append(y[1]) # 写入月份(BCD码) m = bytearray([ self.month & 0xff, (self.month >> 8) & 0xff, (self.month >> 16) & 0xff, (self.month >> 24) & 0xff, ]) result.append(m[0]) # 写入日期(BCD码) d = bytearray([ self.day & 0xff, (self.day >> 8) & 0xff, (self.day >> 16) & 0xff, (self.day >> 24) & 0xff, ]) result.append(d[0]) # 写入小时(BCD码) h = bytearray([ self.hour & 0xff, (self.hour >> 8) & 0xff, (self.hour >> 16) & 0xff, (self.hour >> 24) & 0xff, ]) result.append(h[0]) # 写入分钟(BCD码) min_ = bytearray([ self.minute & 0xff, (self.minute >> 8) & 0xff, (self.minute >> 16) & 0xff, (self.minute >> 24) & 0xff, ]) result.append(min_[0]) # 写入秒(BCD码) s = bytearray([ self.second & 0xff, (self.second >> 8) & 0xff, (self.second >> 16) & 0xff, (self.second >> 24) & 0xff, ]) result.append(s[0]) # 写入星期(BCD码) week_ = bytearray([ self.week & 0xff, (self.week >> 8) & 0xff, (self.week >> 16) & 0xff, (self.week >> 24) & 0xff, ]) result.append(week_[0]) return bytes(result) # uint转BCD def Uint2BCD(n, isBigEndian): b = bytearray() while True: h = (n // 10) % 10 l = n % 10 b.append((h << 4) | l) n = n // 100 if n == 0: break if not isBigEndian: return b # 反转字节顺序 l = len(b) r = bytearray(l) for i, v in enumerate(b): r[l-1-i] = v return r def NewBxCmdSystemClockCorrect(t): return CmdSystemClockCorrect(t)